content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
import re
def split_if_then(source_file: str) -> dict:
"""Split a script file into component pieces"""
logging.debug("Splitting '{}' into IF/THEN blocks".format(source_file))
with open(source_file) as f:
source_text = f.read()
logging.debug("Read {} bytes".format(len(source_text... | 585f5ecfec144116840fa0a0be228cc279482fda | 10,300 |
import re
def id_label_to_project(id_label):
"""
Given a project's id_label, return the project.
"""
match = re.match(r"direct-sharing-(?P<id>\d+)", id_label)
if match:
project = DataRequestProject.objects.get(id=int(match.group("id")))
return project | bd5f322b986776b95a3b3b9203e67c2caaa81c8a | 10,301 |
def payoff_blotto_sign(x, y):
"""
Returns:
(0, 0, 1) -- x wins, y loss;
(0, 1, 0) -- draw;
(1, 0, 0)-- x loss, y wins.
"""
wins, losses = 0, 0
for x_i, y_i in zip(x, y):
if x_i > y_i:
wins += 1
elif x_i < y_i:
losses += 1
if wins > losses:
... | 5a34ce81fdff8f90ee715d9c82fc55abf7eb2904 | 10,302 |
def import_trips(url_path, dl_dir, db_path, taxi_type, nrows=None, usecols=None,
overwrite=False, verbose=0):
"""Downloads, cleans, and imports nyc tlc taxi record files for the
specified taxi type into a sqlite database.
Parameters
----------
url_path : str or None
Path to... | 8e017873a1b17f493ee5b2df4457690a2fbc7b63 | 10,303 |
def householder(h_v: Vector) -> Matrix:
"""Get Householder transformation Matrix"""
return Matrix.identity(h_v.size()).subtract(2 * h_v * h_v.transpose() / (h_v * h_v)) | 686e8088eff5bf1b14e1438f0668a865a59a13d4 | 10,304 |
def _suppression_loop_body(boxes, iou_threshold, output_size, idx):
"""Process boxes in the range [idx*_NMS_TILE_SIZE, (idx+1)*_NMS_TILE_SIZE).
Args:
boxes: a tensor with a shape of [batch_size, anchors, 4].
iou_threshold: a float representing the threshold for deciding whether boxes
overlap too much... | 4adcb176d8d7269bded2b684d830a90a371d0df5 | 10,305 |
from typing import Iterable
import hashlib
import json
def calculate_invalidation_digest(requirements: Iterable[str]) -> str:
"""Returns an invalidation digest for the given requirements."""
m = hashlib.sha256()
inputs = {
# `FrozenOrderedSet` deduplicates while keeping ordering, which speeds up t... | 1fb2f014ad0b0ea98031d022ed02942e1b6ac1d0 | 10,306 |
def to_base_str(n, base):
"""Converts a number n into base `base`."""
convert_string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < base:
return convert_string[n]
else:
return to_base_str(n // base, base) + convert_string[n % base] | bc137d41c9543ef1a201f4bb14234fa277067a77 | 10,307 |
def number_of_photons(i,n=6):
"""Check if number of photons in a sample is higher than n (default value is 6)"""
bitstring = tuple(i)
if sum(bitstring) > n:
return True
else:
return False | 6c7cfea354aa4948d2c94469708f250e6d5b659d | 10,308 |
from typing import List
from typing import Optional
from typing import Dict
def _build_conflicts_from_states(
trackers: List[TrackerWithCachedStates],
domain: Domain,
max_history: Optional[int],
conflicting_state_action_mapping: Dict[int, Optional[List[Text]]],
tokenizer: Optional[Tokenizer] = Non... | 651a200dfd94518b4eb9da76d915794a761c9777 | 10,309 |
def inception_d(input_layer, nfilt):
# Corresponds to a modified version of figure 10 in the paper
"""
Parameters
----------
input_layer :
nfilt :
Returns
-------
"""
l1 = bn_conv(input_layer, num_filters=nfilt[0][0], filter_size=1)
l1 = bn_conv(l1, num_filters=nfilt[0][1]... | cb1a192ef210239c0eafe944126eb965dbcf6357 | 10,310 |
def generate_response(response, output):
"""
:param response:
:return dictionary
"""
status, command = None, None
if isinstance(response, dict):
status = response.get('ok', None)
response.get('command', None)
elif isinstance(response, object):
status = getattr(respo... | ea8764dd3e8f0205a0ec1dd278164140a414dadc | 10,311 |
def check_add_predecessor(data_predecessor_str_set, xml_data_list, xml_chain_list, output_xml):
"""
Check if each string in data_predecessor_str_set is corresponding to an actual Data object,
create new [Data, predecessor] objects lists for object's type : Data.
Send lists to add_predecessor() to write ... | d6bef7af0e32202825705ac36c3b4f09b3aa62ce | 10,312 |
def try_wrapper(func, *args, ret_=None, msg_="", verbose_=True, **kwargs):
"""Wrap ``func(*args, **kwargs)`` with ``try-`` and ``except`` blocks.
Args:
func (functions) : functions.
args (tuple) : ``*args`` for ``func``.
kwargs (kwargs) : ``*kwargs`` for ``func``.
ret_ (any... | 6098c966deffd5ac5ae4bba84219088b2052d878 | 10,313 |
def hnet_bsd(args, x, train_phase):
"""High frequency convolutions are unstable, so get rid of them"""
# Sure layers weight & bias
order = 1
nf = int(args.n_filters)
nf2 = int((args.filter_gain)*nf)
nf3 = int((args.filter_gain**2)*nf)
nf4 = int((args.filter_gain**3)*nf)
bs = args.batch_s... | 0c44775d5d342b73975cd7ffd00971d4f98fb4aa | 10,314 |
import numpy
def hdrValFilesToTrainingData(input_filebase: str, target_varname: str):
"""Extracts useful info from input_filebase.hdr and input_filebase.val
Args:
input_filebase -- points to two files
target_varname -- this will be the y, and the rest will be the X
Returns:
Xy: 2d arra... | de1427340dfed2dc36cdd05f43841399f54ac6a0 | 10,315 |
def create_column(number_rows: int, column_type: ColumnType) -> pd.Series:
"""Creates a column with either duplicated values or not, and either of string or int type.
:param number_rows: the number of rows in the data-frame.
:param column_type: the type of the column.
:returns: the data-frame.
"""
... | 0280f914960b222d589ae13b648339f1ff7ae562 | 10,316 |
import os
def abspath(url):
"""
Get a full path to a file or file URL
See os.abspath
"""
if url.startswith('file://'):
url = url[len('file://'):]
return os.path.abspath(url) | 5c739b7894b4b6d3aabbce9813ce27c72eea6f5d | 10,317 |
import ctypes
def PumpEvents(timeout=-1, hevt=None, cb=None):
"""This following code waits for 'timeout' seconds in the way
required for COM, internally doing the correct things depending
on the COM appartment of the current thread. It is possible to
terminate the message loop by pressing CTRL+C, whi... | 4b24bfc7e68b0953c98b507e6ba5176e4b060011 | 10,318 |
def check_mix_up(method):
"""Wrapper method to check the parameters of mix up."""
@wraps(method)
def new_method(self, *args, **kwargs):
[batch_size, alpha, is_single], _ = parse_user_args(method, *args, **kwargs)
check_value(batch_size, (1, FLOAT_MAX_INTEGER))
check_positive(alpha,... | 528c30d73df3a26d8badc6df17508c6c2e6f69ae | 10,319 |
def generate_motif_distances(cluster_regions, region_sizes, motifs, motif_location, species):
"""
Generates all motif distances for a lsit of motifs
returns list[motif_distances]
motif_location - str location that motifs are stored
species - str species (for finding stored motifs)
... | 4694db72aaf550cac210387e50187fe910e21bf3 | 10,320 |
def sig_to_vrs(sig):
""" Split a signature into r, s, v components """
r = sig[:32]
s = sig[32:64]
v = int(encode_hex(sig[64:66]), 16)
# Ethereum magic number
if v in (0, 1):
v += 27
return [r, s, v] | 48884e4718de7bdda0527470d4e608e8f6b563b8 | 10,321 |
def index_to_string_table_from_tensor(mapping, default_value="UNK", name=None):
"""Returns a lookup table that maps a `Tensor` of indices into strings.
This operation constructs a lookup table to map int64 indices into string
values. The mapping is initialized from a string `mapping` 1-D `Tensor` where
each el... | 22ba72e1fe6ab28c5eb16a32152de4094d8d2e73 | 10,322 |
def test_profile_reader_no_aws_config(monkeypatch, tmp_path, capsys):
"""Test profile reader without aws config file."""
fake_get_path_called = 0
def fake_get_path():
nonlocal fake_get_path_called
fake_get_path_called += 1
return tmp_path
monkeypatch.setattr(awsswitch, "get_pat... | 549e2f08cfac1f3f579906a80f3853cba8d2501e | 10,323 |
def get_exclusion_type(exclusion):
"""
Utility function to get an exclusion's type object by finding the exclusion type that has the given
exclusion's code.
:param exclusion: The exclusion to find the type for.
:return: The exclusion type if found, None otherwise.
"""
for exclusion_type in E... | 778efc4cbd6481ae25f76985f30aa593e1e786fa | 10,324 |
def generatePlans(update):
"""
For an update object provided this function references the updateModuleList which lets all exc
modules determine if they need to add functions to change the state of the system when new
chutes are added to the OS.
Returns: True in error, as in we should stop with thi... | d764b2b18cebb81c450ef54aaa1a8b6893ec16c8 | 10,325 |
from typing import Dict
def get_str_by_path(payload: Dict, path: str) -> str:
"""Return the string value from the dict for the path using dpath library."""
if payload is None:
return None
try:
raw = dpath_util.get(payload, path)
return str(raw) if raw is not None else raw
exce... | bf8077838c2dd2278cd9209b6c560271faaa78cb | 10,326 |
import requests
import json
def get_token_from_code(request):
"""
Get authorization code the provider sent back to you
Find out what URL to hit to get tokens that allow you to ask for
things on behalf of a user.
Prepare and send a request to get tokens.
Parse the tokens using the OAuth 2 cl... | 00edc369150ddb18023799768c4843333079944e | 10,327 |
def DeWeStartCAN(nBoardNo, nChannelNo):
"""Dewe start CAN"""
if f_dewe_start_can is not None:
return f_dewe_start_can(c_int(nBoardNo), c_int(nChannelNo))
else:
return -1 | f810bb73152899fbfbb89caccec469a647c90223 | 10,328 |
def mw_wo_sw(mol, ndigits=2):
"""Molecular weight without salt and water
:param ndigits: number of digits
"""
cp = clone(mol) # Avoid modification of original object
remover.remove_water(cp)
remover.remove_salt(cp)
return round(sum(a.mw() for _, a in cp.atoms_iter()), ndigits) | 32b83d5e74eec3fdc4d18012dc29ed5e3d85edf3 | 10,329 |
def get_contact_list_info(contact_list):
"""
Get contact list info out of contact list
In rgsummary, this looks like:
<ContactLists>
<ContactList>
<ContactType>Administrative Contact</ContactType>
<Contacts>
<Contact>
... | 18d82190ad971b2a2cabb60706fc1486a91a32a5 | 10,330 |
import requests
def enableLegacyLDAP(host, args, session):
"""
Called by the ldap function. Configures LDAP on Lagecy systems.
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the ldap subcommand
@param session: the ... | 7ae9763930c6a0de29f8eac032b3e58d5cd64791 | 10,331 |
from typing import List
from typing import Dict
from typing import OrderedDict
def retrieve_panelist_appearance_counts(panelist_id: int,
database_connection: mysql.connector.connect
) -> List[Dict]:
"""Retrieve yearly apperance count f... | 27a5ccb192cf55714fed8316d647f53bce0ffbb2 | 10,332 |
from datetime import datetime
def chart(
symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"),
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2009, 12, 31), # data stops at 2013/1/1
normalize=True,
):
"""Display a graph of the price history for the list of ticker symbols provide... | 2b4272daa353e21c7f1927e1d8ad68b6c184d97b | 10,333 |
def create_table(peak_id, chrom, pstart, pend, p_center, min_dist_hit, attrib_keys, min_pos, genom_loc, ovl_pf, ovl_fp, i):
"""Saves info of the hit in a tabular form to be written in the output table. """
if attrib_keys != ["None"]:
# extract min_dist_content
[dist, [feat, fstart, fend, strand,... | 476f0e272fe604c5254b68e93fa059f2ae942b2d | 10,334 |
def _get_tests(tier):
"""Return a generator of test functions."""
return TEST_TIERS[tier] | 364b263f2dc64b375092de6f2de9e771dbc020c2 | 10,335 |
def get_first_of_iterable(iterable):
"""
Return the first element of the given sequence.
Most useful on generator types.
:param iterable iterable: input iterable
:returns: tuple(iterable, first_element). If a generator is passed,
a new generator will be returned preserving the original val... | a16ae6795eb656a98ad6c620ae4f177d9cfc2387 | 10,336 |
import sqlite3
def getTiers(connection=None):
"""
"""
# Open the master database if it is not supplied.
flag = False
if connection is None:
connection = sqlite3.connect(MASTER)
flag = True
# Create a cursor from the connection.
cursor = connection.cursor()
# Execute ... | 1689f9aec4f84f5427e04352e1ce546e548eb505 | 10,337 |
from typing import Any
from typing import get_type_hints
from typing import get_origin
from typing import Union
from typing import get_args
def get_repr_type(type_: Any) -> Any:
"""Parse a type and return an representative type.
Example:
All of the following expressions will be ``True``::
... | fe74d79c1fcc74ff86d0c41db3f8f9da37dbf69a | 10,338 |
from datetime import datetime
import calendar
def get_month_range_from_dict(source):
"""
:param source: dictionary with keys 'start' and 'end
:return: a tuple of datatime objects in the form (start, end)
"""
now = timezone.now()
start = source.get('start')
end = source.get('end', datetime... | af68ad0ebcd63444c627fe5b408e1b59dc54e985 | 10,339 |
def softmax_ad_set_dim_func(head, data, axis):
"""Look up the softmax_ad_set_dim_map, and return hash_value, hash_key."""
key = []
key.append(tuple(data.shape))
key.append(data.dtype)
key.append(axis)
hash_key = str(tuple(key))
if hash_key in softmax_ad_set_dim_map.keys():
return ct... | c2077a70c47bb45dcbc79325e7620d4c63324560 | 10,340 |
import csv
def parse_latency_stats(fp):
"""
Parse latency statistics.
:param fp: the file path that stores the statistics
:returns an average latency in milliseconds to connect a pair of initiator and responder clients
"""
latency = []
with open(fp) as csvfile:
csvreader = csv.Dict... | c50c730b5c5bea704bd682d003baa0addfd7ee89 | 10,341 |
import time
import os
def get_tweets(input, out_dir, ext):
"""
This function takes the list of individuals with the periods list and runs twint for each period. It stores the result in a csv file called c.Output and returns the dictionary of uncollected names and periods.
"""
counter = 0
uncollect... | 3f8e7793eb95610d8bf549a40b63727782eed178 | 10,342 |
def micro_jaccard(y_true, y_pred):
"""
Calculate the micro Jaccard-score, i.e. TP / (TP + FP + FN).
:param y_true: `numpy.array` of shape `(n_samples,)` or `(n_samples, n_classes)`. True labels or class assignments.
:param y_pred: `numpy.array` of shape `(n_samples,)` or `(n_samples, n_classes)`. Predi... | b2be25baa6b161dabd676bcb4e58b2682485725f | 10,343 |
def round_to_nreads(number_set, n_reads, digit_after_decimal=0):
"""
This function take a list of number and return a list of percentage, which represents the portion of each number in sum of all numbers
Moreover, those percentages are adding up to 100%!!!
Notice: the algorithm we are using here is 'Lar... | c7a50b5caffb072b3fb6de9478b4acf83f701780 | 10,344 |
def _get_raster_extent(src):
"""
extract projected extent from a raster dataset
(min_x, max_x, min_y, max_y)
Parameters
----------
src : gdal raster
Returns
-------
(min_x, max_x, min_y, max_y)
"""
ulx, xres, xskew, uly, yskew, yres = src.GetGeoTransform()
lrx = ulx + (... | 49ed0b3c583cbfa5b9ecbc96d94aec42aeba3a32 | 10,345 |
def joined_table_table_join_args(joined_table: SQLParser.JoinedTableContext) -> dict:
"""
Resolve a joinedTable ParseTree node into relevant keyword arguments for TableJoin.
These will be pushed down and applied to the child TableRef.
"""
assert isinstance(joined_table, SQLParser.JoinedTableContext)... | 7419e63d28a4a34a49fe50e917faa478b246cb09 | 10,346 |
def find_by_name(name):
"""
Find and return a format by name.
:param name: A string describing the name of the format.
"""
for format in FORMATS:
if name == format.name:
return format
raise UnknownFormat('No format found with name "%s"' % name) | 3626316b961d913217036ddc58eaa71dbdaea1a7 | 10,347 |
import sys
import re
def test_endpoints(host, port, use_ssl, endpoints):
"""
Test each endpoint with its associated method and compile lists of endpoints that
can and cannot be accessed without prior authentication
"""
conn = get_conn(host, port, use_ssl)
if not conn:
sys.exit("Failed ... | fcc33766039e522046a492cd0dcbc8df50970481 | 10,348 |
def create_neighborhood_polygons(gdf):
""" an attempt to muild neighborhoods polygons from asset points"""
gdf = gdf.reset_index()
neis = gdf['Neighborhood'].unique()
gdf['neighborhood_shape'] = gdf.geometry
# Must be a geodataframe:
for nei in neis:
gdf1 = gdf[gdf['Neighborhood'] == nei... | 7ca77acfd73a4b13f9088e3839121076d1a70730 | 10,349 |
def custom_gradient(f=None):
"""Decorator to define a function with a custom gradient.
This decorator allows fine grained control over the gradients of a sequence
for operations. This may be useful for multiple reasons, including providing
a more efficient or numerically stable gradient for a sequence of oper... | 6c6432ab9a10c219d811651db2cbbf2321e43b95 | 10,350 |
def Field(name,
ctype,
field_loader=FieldLoaderMethod.OPTIONAL,
comment=None,
gen_setters_and_getters=True):
"""Make a field to put in a node class.
Args:
name: field name
ctype: c++ type for this field
Should be a ScalarType like an int, string or enum ty... | 9f3f84be56213640ca9d7368d35bdca8eb9958b2 | 10,351 |
from typing import Tuple
from typing import List
def sql(dataframe: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame, List[str], str]:
"""Infer best fit data types using dataframe values. May be an object converted to a better type,
or numeric values downcasted to a smallter data type.
Parameters
--... | d64a2d44cb3a89896aa3b7c19ec1a11bb8fcc2ff | 10,352 |
def calculateDeviation(img, lineLeft,lineRight, ):
"""This function calculates
the deviation of the vehicle from the center of the
image
"""
frameCenter = np.mean([lineLeft.bestx,lineRight.bestx] , dtype=np.int32)
imgCenter = img.shape[1]//2
dev = frameCenter - imgCenter
xm_p... | 79d16240a2d606cb25360532ac77e4fbe834e23d | 10,353 |
import requests
def post_new_tracker_story(message, project_id, user):
"""Posts message contents as a story to the bound project."""
if ";" in message:
name, description = message.split(";", maxsplit=1)
else:
name, description = (message, "")
story_name = "{name} (from {user})".format(... | b26391ad07159df3087cf22c136e5959a7fb6f4b | 10,354 |
def nz2epsmu(N, Z):#{{{
""" Accepts index of refraction and impedance, returns effective permittivity and permeability"""
return N/Z, N*Z | 3173df57ab5ad573baab87cd4fd6f353fcf69e2c | 10,355 |
import scipy
def logdet_symm(m, check_symm=False):
"""
Return log(det(m)) asserting positive definiteness of m.
Parameters
----------
m : array-like
2d array that is positive-definite (and symmetric)
Returns
-------
logdet : float
The log-determinant of m.
"""
... | 4e4358cb9094d671ba393d653adf685a916c4fa3 | 10,356 |
def merge(left, right):
""" Merge helper
Complexity: O(n)
"""
arr = []
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
# Sort each one and place into the result
if left[left_cursor] <= right[right_cursor]:
arr.append(l... | c6730a0fe5bfcaf713c6c3fa8f2e777db50e4445 | 10,357 |
def validate_form_data(FORM_Class):
"""
Validates the passed form/json data to a request and passes the
form to the called function.
If form data is not valid, return a 406 response.
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
form = FOR... | d0287479d3c5da32c5fbd48a8f2047b64bce5e2b | 10,358 |
def set_axis_tick_format(
ax, xtickformat=None, ytickformat=None, xrotation=0, yrotation=0
):
"""Sets the formats for the ticks of a single axis
:param ax: axis object
:param xtickformat: optional string for the format of the x ticks
:param ytickformat: optional string for the format of the y ticks... | 06b7f6cc5ba78fa093cf517a5df414fa1bb6f504 | 10,359 |
def two_body(y, t):
"""
Solves the two body problem
:param y: state vector
y = [rx,ry,rz,vx,vy,vz]
:param t: time
:return: dy
"""
rx, ry, rz = y[0], y[1], y[2]
vx, vy, vz = y[3], y[4], y[5]
r = np.array([rx, ry, rz])
v = np.array([vx, vy, vz])
r_mag = np.linalg.norm... | 5a04f279caa3a540f76d3af488344414f4b3547e | 10,360 |
import argparse
import os
def args_parse_params(params):
""" create simple arg parser with default values (input, output)
:param dict dict_params:
:return obj: object argparse<...>
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-i',
'--path_in',
type=str,... | 42f9a3504c5f3005e5e7117fec80730abddb1e6c | 10,361 |
def DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0):
"""
z_prime,a_hat,e_phi = DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0)
Decision directed carrier phase tracking
z = complex baseband PSK signal at one sample per symbol
M = The PSK modulation order, i.e., 2, 8, or 8.
BnTs = t... | 77bcd1dd49a7bb9dfd40b8b45c9a9eb129ed674d | 10,362 |
from typing import Dict
from typing import Any
def rubrik_gps_vm_snapshot_create(client: PolarisClient, args: Dict[str, Any]) -> CommandResults:
"""
Trigger an on-demand vm snapshot.
:type client: ``PolarisClient``
:param client: Rubrik Polaris client to use
:type args: ``dict``
:param args:... | b065c29e58043b2785f48cf788fb1414262b0eee | 10,363 |
import os
def getFullCorpus(emotion, speakerID = None):
"""
Return the 6 speakers files in a massive vstack
:param emotion:
:param speakerID:
:return:
"""
if emotion not in emotions or (speakerID is not None and speakerID not in speakers):
raise Exception("No Such speaker: {} or e... | b9894e28e75263fe0a84bc947437f093fc9827d8 | 10,364 |
def CT_freezing_first_derivatives(SA, p, saturation_fraction):
"""
Calculates the first derivatives of the Conservative Temperature at
which seawater freezes, with respect to Absolute Salinity SA and
pressure P (in Pa).
Parameters
----------
SA : array-like
Absolute Salinity, g/kg
... | af3aa120e2e2620f16d984b29d42d583ed9fd347 | 10,365 |
import logging
def run(gParameters):
"""
Runs the model using the specified set of parameters
Args:
gParameters: a python dictionary containing the parameters (e.g. epoch)
to run the model with.
"""
#
if 'dense' in gParameters:
dval = gParameters['dense']
if type... | 53a904dc5aeb7942623d2db6957505d43612f174 | 10,366 |
def get_territory_center(territory: inkex.Group) -> inkex.Vector2d:
"""
Get the name of the territory from its child title element. If no title, returns
Warzone.UNNAMED_TERRITORY_NAME
:param territory:
:return:
territory name
"""
center_rectangle: inkex.Rectangle = territory.find(f"./{Sv... | 90f9e8ae7eebc5f3acf3d6e4100dec36ef5839d9 | 10,367 |
def batch_norm_relu(inputs, is_training, data_format):
"""Performs a batch normalization followed by a ReLU."""
# We set fused=True for a significant performance boost. See
# https://www.tensorflow.org/performance/performance_guide#common_fused_ops
inputs = tf.layers.batch_normalization(
inputs=inputs, ax... | 3d9d08000cd4dc5b90b64c6fdce7fca0039c5a03 | 10,368 |
def create_success_status(found_issue):
"""Create a success status for when an issue number was found in the title."""
issue_number = found_issue.group("issue")
url = f"https://bugs.python.org/issue{issue_number}"
return util.create_status(STATUS_CONTEXT, util.StatusState.SUCCESS,
... | 0aab1eeb7f3b5a27b06a7f47dac5d105dbeef5fd | 10,369 |
def score_to_rating_string(score):
"""
Convert score to rating
"""
if score < 1:
rating = "Terrible"
elif score < 2:
rating = "Bad"
elif score < 3:
rating = "OK"
elif score < 4:
rating = "Good"
else:
rating = "Excellent"
return rating | 0c6a5aba0cb220a470f2d40c73b873d11b1a0f98 | 10,370 |
def deconv1d_df(t, observed_counts, one_sided_prf, background_count_rate, column_name='deconv', same_time=True,
deconv_func=emcee_deconvolve, **kwargs):
"""
deconvolve and then return results in a pandas.DataFrame
"""
#print("working on chunk with length {}".format(len(observed_counts)))
... | bc773398762ac7e82876d935b6ca0b0351960865 | 10,371 |
def create_parser() -> ArgumentParser:
"""Create a parser instance able to parse args of script.
return:
Returns the parser instance
"""
parser = ArgumentParser()
version = get_distribution('hexlet-code').version
parser.add_argument('first_file', help='path to JSON or YAML file')
pa... | 93f06dd056ab9121be1ad1312b67024312a4108f | 10,372 |
import os
def parse_alignment_file(file_path):
"""Parse the buildAlignment.tsv output file from CreateHdpTrainingData
:param file_path: path to alignment file
:return: panda DataFrame with column names "kmer", "strand", "level_mean", "prob"
"""
assert os.path.exists(file_path), "File path does no... | 77ad066b5a85ff608eecc4e8ac8ab83c07cafd8a | 10,373 |
def remap_key(ctx, origin_key, destination_key, *, mode=None, level=None):
"""Remap *origin_key* to *destination_key*.
Returns an instance of :class:`RemappedKey`.
For valid keys refer to `List of Keys
<https://www.autohotkey.com/docs/KeyList.htm>`_.
The optional keyword-only *mode* and *level* a... | f4a8f7cddea2f82a13d06b5f3f3c4031e862e32b | 10,374 |
def get_anime_list(wf):
"""Get an Animelist instance.
:param Workflow3 wf: the Workflow3 object
:returns: Animelist object
:rtype: Animelist
"""
try:
animelist = Animelist(
wf.settings['UID'], wf.get_password('bangumi-auth-token')
)
except Exception as e:
... | a16a063afd2ac6a3fba4877665185a30971e8387 | 10,375 |
def use_linear_strategy():
"""
Uses a linear function to generate target velocities.
"""
max_velocity = kmph2mps(rospy.get_param("~velocity", 40))
stop_line_buffer = 2.0
def linear_strategy(distances_to_waypoints, current_velocity):
# Target velocity function should be a line
# ... | 7f0be5e0e11c7d29bb68ce7007e911f0fd14d6e2 | 10,376 |
def recomputation_checkpoint(module: nn.Module):
"""Annotates the output of a module to be checkpointed instead of
recomputed"""
def recompute_outputs(module, inputs, outputs):
return tuple(poptorch.recomputationCheckpoint(y) for y in outputs)
return module.register_forward_hook(recompute_outp... | a39f106f05e84b36ab21a948044adb14fb44b6cd | 10,377 |
import requests
import json
def get_random_quote() -> str:
"""Retrieve a random quote from the Forismatic API.
Returns:
str: The retrieved quote
"""
quote = ""
while quote == "":
response = requests.get(
"http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&forma... | bd189878c76a4da1544a6d3762c2a67f69ad1846 | 10,378 |
def has_datapoint(fake_services, metric_name=None, dimensions=None, value=None, metric_type=None, count=1):
"""
Returns True if there is a datapoint seen in the fake_services backend that
has the given attributes. If a property is not specified it will not be
considered. Dimensions, if provided, will ... | 59797809cb73644236cdc8d35cf9698491fff83a | 10,379 |
def optimizeMemoryUsage(foregroundTasks, backgroundTasks, K):
"""
:type foregroundTasks: List[int]
:type backgroundTasks: List[int]
:type K: int
:rtype: List[List[int]]
"""
res = []
curr_max = 0
if len(foregroundTasks) == 0:
for j in range(len(backgroundTasks)):
... | be7de70bf39ea1872ad1d5bbb9c5209ae3978c8c | 10,380 |
import itertools
def cv_indices(num_folds,num_samples):
"""
Given number of samples and num_folds automatically create a subjectwise cross validator
Assumption: per subject we have 340 samples of data
>>> cv_set = cv_indices(2,680)
>>> cv_set
>>> (([0:340],[340:680]),([340:680,0:340]))
Alg... | ce0d983458a089919f5581ebc0a650f73cf4c423 | 10,381 |
import pkg_resources
import json
import jsonschema
def load_schema(schema_name: str) -> dict:
"""Load a JSON schema.
This function searches within apollon's own schema repository.
If a schema is found it is additionally validated agains Draft 7.
Args:
schema_name: Name of schema. Must be fi... | b8ebed15394fef7ec1bb9ab735e4f8cb2201df0b | 10,382 |
def question_12(data):
"""
Question 12 linear transform the data, plot it, and show the newly created cov matrix.
:param data: data
:return: data after linear transformation
"""
s_mat = np.array([[0.1, 0, 0], [0, 0.5, 0], [0, 0, 2]])
new_data = np.matmul(s_mat, data)
plot_3d(new_data, "Q... | e0904f6a36d2833b48e064ff62d3071d07ab448b | 10,383 |
def update_storage(user_choice):
"""It updates the Coffee Machine resources after a beverage is ordered."""
resources["water"] = resources["water"] - MENU[user_choice]["ingredients"]["water"]
resources["milk"] -= MENU[user_choice]["ingredients"]["milk"]
resources["coffee"] -= MENU[user_choice]["ingredie... | 48c642fad80a124fd802a2ae1e1fc440ffa20203 | 10,384 |
def second_test_function(dataset_and_processing_pks):
"""
Pass a result of JSON processing to a function that saves result on a model.
:param dataset_and_processing_pks: tuple of two (Dataset PK, Processing PK)
:return: tuple of two (Dataset PK; JSON (Python's list of dicts))
"""
# unpack tuple... | b21960b1349c825b00997281dfbef4ef924846d0 | 10,385 |
def matplotlib_axes_from_gridspec_array(arr, figsize=None):
"""Returned axes layed out as indicated in the array
Example:
--------
>>> # Returns 3 axes layed out as indicated by the array
>>> fig, axes = matplotlib_axes_from_gridspec_array([
>>> [1, 1, 3],
>>> [2, 2, 3],
>>> ... | e1048ea32a6c3c8ea87a82c5c32f7e009c1b5c19 | 10,386 |
def _fetch_gene_annotation(gene, gtf):
"""
Fetch gene annotation (feature boundaries) and the corresponding sequences.
Parameters:
-----------
gene
gene name that should be found in the "gene_name" column of the GTF DataFrame.
type: str
gtf
GTF annotation D... | d08307fd3e079e6de3bca702a0d9f41005a6d5f7 | 10,387 |
from django.core.servers.basehttp import AdminMediaHandler
def deploy_static():
"""
Deploy static (application) versioned media
"""
if not env.STATIC_URL or 'http://' in env.STATIC_URL: return
remote_dir = '/'.join([deployment_root(),'env',env.project_fullname,'static'])
m_prefix = len(en... | 7c1c8d7ce725e285e08f5fa401f6e431a35fc77c | 10,388 |
import array
def randomPolicy(Ts):
""" Each action is equally likely. """
numA = len(Ts)
dim = len(Ts[0])
return ones((dim, numA)) / float(numA), mean(array(Ts), axis=0) | 6c99ecfe141cb909bceb737e9d8525c9c773ea74 | 10,389 |
def calc_TiTiO2(P, T):
"""
Titanium-Titanium Oxide (Ti-TiO2)
================================
Define TiTiO2 buffer value at 1 bar
Parameters
----------
P: float
Pressure in GPa
T: float or numpy array
Temperature in degrees K
Returns
-------
float or numpy array
log_fO2
References
----------
Bar... | c4f920db3ff6020eba896039228e7adbcdcd4234 | 10,390 |
def nlevenshtein_scoredistance(first_data, memento_data):
"""Calculates the Normalized Levenshtein Distance given the content in
`first_data` and `memento_data`.
"""
score = compute_scores_on_distance_measure(
first_data, memento_data, distance.nlevenshtein)
return score | e85776c5ae95533c500a47d550ea848e6feceed7 | 10,391 |
def parameter_from_numpy(model, name, array):
""" Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.gluon.parameter
a parameter object... | babf1a32e55d92bbe1ad2588167bd813836637e7 | 10,392 |
def execute_workflow_command():
"""Command that executes a workflow."""
return (
Command().command(_execute_workflow).require_migration().require_clean().with_database(write=True).with_commit()
) | f20b5be4d37f14179f0097986f2f75b1de699b79 | 10,393 |
import tqdm
def fast_parse(python_class, parse_function, data_to_parse, number_of_workers=4, **kwargs):
"""
Util function to split any data set to the number of workers,
Then return results using any give parsing function
Note that when using dicts the Index of the Key will be passed to t... | ffbd377a53362cb532c84860f3b26ff2ed1234c6 | 10,394 |
import copy
def create_plate(dim=DIMENSION, initial_position=-1):
"""
Returns a newly created plate which is a matrix of dictionnaries (a matrix of cells) and places the first crystal cell in it at the inital_pos
The keys in a dictionnary represent the properties of the cell
:Keys of the dictionn... | 1f1b806035dc6dc24796840f7cb31c61cf7ec5a7 | 10,395 |
import unicodedata
def CanonicalizeName(raw_name: Text):
"""Strips away all non-alphanumeric characters and converts to lowercase."""
unicode_norm = unicodedata.normalize('NFKC', raw_name).lower()
# We only match Ll (lowercase letters) since alphanumeric filtering is done
# after converting to lowercase. Nl a... | bd8d2d47dae4220e51dab8d44a0c6b603986ecff | 10,396 |
from datetime import datetime
import json
def data_v1( request ):
""" Handles all /v1/ urls. """
( service_response, rq_now, rq_url ) = ( {}, datetime.datetime.now(), common.make_request_url(request) ) # initialization
dump_param_handler = views_helper.DumpParamHandler( rq_now, rq_url )
if request.GE... | 18e98f015cb92f0d0e2ac6bbe9627d4c6ab33fb0 | 10,397 |
import subprocess
import sys
def ssh(server, cmd, checked=True):
""" Runs command on a remote machine over ssh."""
if checked:
return subprocess.check_call('ssh %s "%s"' % (server, cmd),
shell=True, stdout=sys.stdout)
else:
return subprocess.call('ssh ... | b8d1d492b7528dc7e601cf994b2c7a32b31af0d3 | 10,398 |
def permutations(n, r=None):
"""Returns the number of ways of arranging r elements of a set of size n in
a given order - the number of permuatations.
:param int n: The size of the set containing the elements.
:param int r: The number of elements to arange. If not given, it will be\
assumed to be eq... | 7eab1c02ab0864f2abd9d224145938ab580ebd74 | 10,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.