content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def setup(*setup_functions):
"""Decorator that reigsters setup functions with a test.
The functions passed in as setup functions take an optional 'context'
parameter of type checkers.Context.
Note that the decorator takes in Test instances, so this decorator should be
used *above* the @checkers.test decorat... | 26f7d8e30911638248bf68e0a4a96f463d25b603 | 615,831 |
def get_lines(path, remove_comments=True):
"""Returns the lines in a C/C++ header file that are not empty.
Also strips the whitespace from each line and can optionally remove
the comments.
Parameters
----------
path : :class:`str`
The path to a C/C++ header file.
remove_comme... | dbdc3d30ada5896b0b0234476d9446997ae9081d | 615,839 |
def is_route(tag):
""" Checks if an HTML tag is a bus route.
:param tag A BeautifulSoup tag
:return True if the tag has a "data-routes" attribute, False otherwise"""
return tag.has_attr("data-routes") | a568a7cd610095e233eed7f04caf04983572e4d7 | 615,840 |
def _time_to_micros(time):
"""Convert a time into microseconds since midnight.
Parameters
----------
time : datetime.time
The time to convert.
Returns
-------
us : int
The number of microseconds since midnight.
Notes
-----
This does not account for leap seconds or... | ee72b7d5cb35c03453cf7d645808d3675e7fc1dc | 615,843 |
def get_team_avg_height(team):
"""calculate a new avg_height based on current team's player's heights.
If no players on team, return 0
"""
num_players = len(team['players'])
if num_players == 0:
# No players return 0
return 0
# calculate average height of existing players
tot... | 712385425f232c4a7b62ab820983b20033fd97e7 | 615,845 |
import re
def uncoded(src):
"""Strips out any `# encoding: ???` lines found at the head of the source listing"""
lines = src.split("\n")
for i in range(min(len(lines), 2)):
lines[i] = re.sub(r'#.*coding[=:]\s*([-\w.]+)', '#', lines[i])
return "\n".join(lines) | db8326165e9cec4be39c1b9a175ec9ea8f557f6e | 615,847 |
from typing import Optional
def validate_discharge_efficiency(discharge_efficiency: Optional[float]) -> Optional[float]:
"""
Validates the discharge efficiency of an object.
Discharge efficiency is always optional.
:param discharge_efficiency: The discharge efficiency of the object.
:return: The ... | 689e951673954f2112112d2d6e1c358f9ef7678b | 615,852 |
def getCreditMultiplier(floorIndex):
"""
Returns the skill credit multiplier appropriate for a particular
floor in a building battle. The floorIndex is 0 for the first
floor, up through 4 for the top floor of a five-story building.
"""
# Currently, this is 1 for the first floor (floor 0), 1.5 f... | f2804647ccf9d6f2b0d453742ffd53c6c8843270 | 615,853 |
import json
def get_json(data, pretty=False, **kwargs):
"""
A convenience wrapper around ``json.dumps`` that respects the ordering of
keys in classes like ``OrderedDict``, ``SortedDict``, and
``DefinedOrderDict``.
:param data: the object to encode in JSON
:param pretty:
whether or not... | 222bbd705a23b0ad37ac4500a400592aa42eacef | 615,855 |
def calc_force(df, close, volume, col_name="force"):
"""Calculate force indicator (Elder).
:param df: Data frame to do and add calculations to
:param close: Pandas dataframe column name close price
:param volume: Pandas dataframe column name volume
:param col_name: Pandas dataframe column name for ... | 125dd9028eca8b3429682118c5887fa475c6d7e3 | 615,857 |
def combine_prediction_metadata_batches(metadata_list):
"""Combines a list of dicts with the same keys and lists as values into a single dict with concatenated lists
for each corresponding key
Args:
metadata_list (list): list of dicts with matching keys and lists for values
Returns:
... | 28fd647b19e5affa3f04c7909a4ba7ff17993da1 | 615,866 |
import base64
def str_to_base64(data, encoding='utf-8'):
"""Codifica uma string (por padrão, UTF-8) em Base64.
:param str data: String a ser codificada em Base64.
:param str encoding: Opcional. O *encoding* da string `data`. Se não for
especificado, o padrão é `'utf-8'`.
:returns: Uma string... | a8012e75edec99a1c3379dd0c07b2165073b2a06 | 615,867 |
def factor_out_twos(n):
"""
Returns the tuple (d,s) such that n = d*(2**s) for the smallest value of d
"""
d = n
s = 0
while d % 2 == 0:
s += 1
d //= 2
return d,s | 76ed2fa981673098afd66239eca960607e96d7e9 | 615,873 |
import torch
def generate_final_context_matrix(context_matrix_dict, ending_key_to_exclude="_nokg"):
"""Takes the average of the context matrices where their key does not end
in ending_key_to_exclude.
Args:
context_matrix_dict: Dict of batch x M x K x H matrices of embeddings for each candidate
... | ac1aaaf083ffda973ad8591e60bca0357db8d708 | 615,874 |
def _columns(cursor, table):
"""Return the columns of a table as a list."""
cursor.execute('''
SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = %s
''', (table, ))
return [column['column_name'] for column in cursor.fetchall()] | 03544abe0980dfa00b366b38687f4795707b9385 | 615,876 |
import json
def pre_proc(batch, **kwargs):
"""
Pre-processing of batch.
Assumes format (n_samples, n_channels, height, width).
"""
#opening stats file
with open(kwargs["stats_fp"]) as f:
stats = json.load(f)
#converting keys from str to int
stats = {int(k): v for k, v in stats... | d80df08dbcdbab7224a34e3cde5db3c13b1212ed | 615,885 |
def _strip_match(matchobj):
"""Strip whitespace from a RE-match-object
Parameters
----------
matchobj : re.Match
Match-object of regular-expression.
Returns
-------
str
Stripped string
"""
return matchobj.group(0).strip() | 77565857853069194696ab9e50f51d1f48090376 | 615,886 |
import math
def equal(a, b, abstol=1e-16, reltol=0, mathlib=math):
"""Check if two values are equal.
By default, we test with (absolute) tolerances. This can be changed as desired.
For exact equality, set abstol=reltol=0.
mathlib allows to specify the module from which isclose should be used: numpy,... | 8d28f8d24b72d3d1ff1117e6dbfba26819bb3355 | 615,891 |
import json
def get_json(res):
"""Return json response as a dictionary or list."""
return json.loads(res.data.decode('utf-8')) | a09e9f81b4de097f21c5873bf7b9cc602258c9e1 | 615,892 |
def _slice_ndfilter(data, filter_func, slices, args, size, footprint, kwargs):
"""
Helper function passing image slices to `scipy.ndimage` filters that is
pickleable for threading with `multiprocessing`
Parameters
----------
data, filter_func, args, size, footprint :
See `multiproc... | 0ae440067b974f34ef14eb2ab7a01d13013f184d | 615,893 |
def isIntraChrom(read1, read2):
"""
Return true is the reads pair is intrachromosomal
read1 : [AlignedRead]
read2 : [AlignedRead]
"""
if read1.tid == read2.tid:
return True
else:
return False | b1b0a6fd87015f8dbb5803b8bd08c634df0598bd | 615,897 |
def parse_tract_fips(tract_fips):
"""
turn a full tract fips code into a tuple of state, county, tract
"""
return tract_fips[:2], tract_fips[2:5], tract_fips[5:] | c7add9ccc304c3f0993022a0ef5b3a3be72d0fce | 615,904 |
def _get_indices(item, seq):
"""Return the indices where `item` occurs in `seq`
Returns
-------
Generator[int]"""
return (n for n, x in enumerate(seq) if x == item) | 9f9cc56ca66250581b18d60ade91ed8d54bc342f | 615,905 |
import json
def read_json_file(path):
"""Returns JSON parsed data from file."""
with open(path, "r") as file:
return json.load(file) | eb036c43a5f16d5bf2d803089b84e95c3d932d74 | 615,907 |
def reaction_int2str( reaction_int, silent=True ):
#;{{{
"""
Translate reaction number to reaction string.
The idea of this functions is to ensure that in all function within
this file the same reaction is meant when referring to reaction 3
(or any other number).
The integer provided to this f... | 0313eab8f67968317f7503f20c1da5800185fb31 | 615,908 |
def z_to_params(z, P, n_m, n_t):
"""Convert single vectors of unknowns z into separate vectors of unknowns."""
lambda_ = z[0:n_m]
beta = z[n_m : 2 * n_m]
betat = z[2 * n_m : 2 * n_m + n_t]
T = z[2 * n_m + n_t :]
return lambda_, beta, betat, T | 38ab1165cdb48d608d12158dce8939c5253b468e | 615,909 |
def _ParamExists(param_obj, param_name):
"""Tests whether param_name is contained in param_obj."""
if not param_obj:
return
for k, _ in param_obj.IterParams():
if k == param_name:
return True
return False | 69cb7ac1acc566fb89aa438752a10019350064f8 | 615,910 |
def cleanup_frame(frame):
"""Make the columns have better names, and ordered in a better order."""
frame = frame.rename(columns={"Non- Hispanic white": "White"})
frame = frame.reindex(columns=["Asian", "White", "Hispanic", "Black"])
return frame | fb79f5d5161fe71e0ddc038caf095ecc0db69341 | 615,911 |
def get_service_dependency_tree(yml_dict, run_exclude_images):
"""Method to generate a dict of services and services it depends on
:param yml_dict: dict generated from docker-compose yml
:type yml_dict: dict
:param run_exclude_images: List of name of dependency services which
... | ad91ab527aa7ae447ba2f8d7713b71ca92d816a9 | 615,912 |
def get_job_tasks(rank, ranks, tasks_tot):
"""
Return a tuple of job task indices for a particular rank.
This function distribute the job tasks in tasks_tot
over all the ranks.
Note
----
This is a primerly a MPI help function.
Parameters
----------
rank : int
Current M... | d61a77d737bc198ac13487999699d4434fd5b290 | 615,920 |
def _graph_string(graph):
"""Helper to serialize a graph to string."""
if graph:
return graph.as_graph_def(add_shapes=True).SerializeToString()
else:
return b'' | 2df37d75c2df72a3285365562259b1f420d2d5a2 | 615,921 |
def filtered_packageversion(version, revision):
""" Emit "version-revision" if version and revision are not null
else "version" if version is not null
else ""
"""
return "" if (not version or version == "") else version if (not revision or revision == "") else version + "-" + revision | 8bd5d7fa932baefc8c2bd21a7d5d1dcbcde5e995 | 615,923 |
def checkSameLoop(ra, rb):
"""
check if two anchors are exact same
"""
if ra[1] == rb[1] and ra[2] == rb[2] and ra[4] == rb[4] and ra[5] == rb[5]:
return True
return False | 0a3f760394506bd7556a635a3996d3ddfcd06748 | 615,924 |
def uniqueness(container):
"""
Checks if the container is unique.
In case of uniqueness it returns True
"""
return len(container) == len(list(set(container))) | 562531910b07c598ba51af4fc3a4ebe93132083c | 615,926 |
def create_query_parameters(filter_expressions: list, sorting_expressions: list) -> dict:
"""
Create query parameters
Parameters
----------
filter_expressions: List[dict]
Filtering parameters [{'name': draft, 'op': gt, 'val':30}]
sorting_expressions: List[dict]
Sorting parameter... | 9ef6a3ff9eee1c3eb0fd79240f6309888413e0d4 | 615,927 |
def _write_triggers_from_sequence_free_spell(array, trigger_file):
"""
Write triggers from free spell.
Helper Function to write trigger data to provided trigger_file.
It writes in the following order:
(I) presented letter, (II) timestamp
"""
for i in array:
# extract the lett... | 8503b24cd33d48bbac8bfd61d583e093bce66d75 | 615,928 |
def string_split(input_string):
"""Split a string based on the presence of commas
Each line of the file is read in as a single string, so it is necessary
to separate this string into two categories: time and voltage. Given that
the file is comma separated, this function is used to split each string
... | 1600a3b8021c1f41fd213bbb0204b1860029def4 | 615,929 |
def expand_id_map(id_map, all_ids):
""" Ensures all ids within all_ids are included as keys in the mapping """
unmapped_ids = list(set(all_ids).difference(id_map.keys()))
for i in unmapped_ids:
id_map[i] = i
return id_map | 10e80cc2d3a84de745bc03f09f56c197b5bab13a | 615,931 |
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges | f43e79a4d604d8ce322fdd1fc7c22bdf57725e60 | 615,933 |
def indexOf(a, b):
"""Return the first index of b in a."""
for i, j in enumerate(a):
if j == b:
return i
else:
raise ValueError('sequence.index(x): x not in sequence') | 0d5b3dba712f699a2fdc48c54b53e74ca0482b0c | 615,941 |
from typing import Optional
import inspect
import types
def get_class_that_defined_method(method: object) -> Optional[object]:
"""Retrieves the class that defines a method.
Taken from https://stackoverflow.com/a/25959545/4293396
:param method: The method
:return: The class that defines the method
... | a240741f672c52c0d304c188a8b463d4183a2585 | 615,942 |
def aes_to_scale(var):
"""
Look up the scale that should be used for a given aesthetic
"""
if var in {'x', 'xmin', 'xmax', 'xend', 'xintercept'}:
var = 'x'
elif var in {'y', 'ymin', 'ymax', 'yend', 'yintercept'}:
var = 'y'
return var | 0d55067354c3e8afb37aaab35f02905324fdcf62 | 615,944 |
import queue
def get_all_from_queue(q):
"""
Returns at least one element from the queue, tries to return as many as possible.
:param q: The queue to get elements from
:return: A list of elements fetched from the queue
"""
data = [q.get()]
while True:
try:
data.append(q.... | b1f85eabe47bc515b78e751117c0e7c20505ccf2 | 615,948 |
from datetime import datetime
def find_now(start):
"""
Calculate the amount of time passed from the start
of the algorithm
"""
return str(datetime.now() - start) | bbd606fc55b7b8dc64739bdeba1d700bc3acc689 | 615,950 |
import re
def _get_badchars(data: str) -> str:
"""Returns the badchars contained in a string."""
regex = r"[^a-zA-Z0-9\s]"
match = re.findall(regex, data)
match = sorted(set(match)) # unique and sort
return "".join(match) | feeee709365a44bd1d7710dc808afb8020230fa3 | 615,951 |
from datetime import datetime
def to_datetime(timestamp):
"""
Convert MediaWiki timestamp to a datetime object.
Assumes the format to be in "MW" ISO with "Z" instead of +00:00 for timezone.
:type timestamp: str
:rtype datetime
"""
return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ') | 0fb99bf718ae2d26ae0d46c9ce2d26dea6435990 | 615,963 |
def get_datastore_id(client, name):
"""return the id of a datastore
arguments:
client -- an authenticated trove client
name -- the name of the datastore to find
returns:
the id of the datastore or None if not found
"""
try:
store = client.datastores.find(name=name)
retu... | d7a9e8e9d4ed1c12d40128516aedfbdbbf44bd74 | 615,968 |
def _populate_set_with_patches(new_set, unused_patches, bundle, logger):
"""
Adds entries to set new_set from the bundle's patch_order if they are unique.
Entries that are not unique are logged as warnings.
Returns True if warnings were logged; False otherwise
"""
warnings = False
try:
... | ed855544aca9427a1090bc0cb32a08ed8889d10d | 615,972 |
def wav_packing_string(num_frames, num_channels, bit_depth):
"""
Get the string for packing or unpacking a given number of frames using the struct module.
Args:
num_frames: int - The number of frames to cover in the packing string
num_channels: int - The number of channels in the audio, e.... | b356747e248e489e9c6bf9fb8963ba4013082ab2 | 615,973 |
def charcount(string, char):
"""counts occurrences of c at the start of s."""
i = 0
while i < len(string) and string[i] == char:
i += 1
return i | 556c0df4805ff467fa313e65cc66c466eb4fe3fd | 615,974 |
def sequence2dict(seq):
"""Helper function for cx_Oracle.
For each element in the sequence, creates a dictionary item equal
to the element and keyed by the position of the item in the list.
>>> sequence2dict(("Matt", 1))
{'1': 'Matt', '2': 1}
Source:
http://www.gingerandjohn.com/archives/2... | ddce391848ac48dd24531914cfa5e2c4ab2a7234 | 615,976 |
import pkg_resources
def get_highest_installed(project_name):
"""Return highest version of installed package.
@param project_name: PyPI project name
@type project_name: string
@return: string of highest installed version
"""
environment = pkg_resources.Environment()
return environment[p... | 961dbb7e8f3d6d59de7b544a20f8a0c92dd80acb | 615,978 |
def allelic_balance(gt):
"""Return allelic balance from genotype value."""
if not gt.get("dp"):
return 0.0
else:
return gt.get("ad") / gt.get("dp") | dcf42a3337581fedb28663fef62cfa46312902f1 | 615,981 |
def get_coordinates(axis_value, ranges):
"""Get coordinates pairs from axis_value and other_values."""
start, end = ranges
return [(axis_value, other_value) for other_value in range(start, end + 1)] | 0fe2912e0b35aaf53181fd722a309b3746dddbf2 | 615,982 |
def generate_mock_method(method):
"""Generate MOCK_METHOD google macro."""
return (
f"MOCK_METHOD({method.ret_type}, {method.name}, "
f"({method.parameters}), ({method.qualifiers}));"
) | a934f8cc039c4257731216dca0141ddb4b4c9823 | 615,985 |
def _calc_overlap(geom1, geom2):
"""Return area overlap"""
return geom1.intersection(geom2).area | 13183e0f20dd441425b55793d667a0f7ff73ac59 | 615,995 |
def url_from_icon_id(id: str) -> str:
"""Get a downloadable URL from a string ID
Args:
id (str): Flaticon ID
Returns:
str: URL pointing to the .png file for this icon
"""
return f"https://image.flaticon.com/icons/png/512/{id[:-3]}/{id}.png" | 5548ed7de881301b6967e3eab8f8c4bc9309080a | 615,998 |
from typing import Any
from typing import Tuple
def _normalize_slice_key(key: Any) -> Tuple:
""" Normalizes slice key into always being a top-level tuple.
Args:
key: Slicing key that is passed within __getitem__.
Returns:
Expanded slice as a tuple.
"""
if not isinstance(key, tupl... | 27862909fd2c12d72b7770ca6076fd63951887cf | 616,005 |
import random
def chunk_list(examples, chunk_size=2, pad_to_divisible=True):
"""
Args:
examples: iterable, examples grouped by image/video
chunk_size: int, number of examples in each chunk.
pad_to_divisible: bool, pad the examples to be divisible by chunk_size.
>>> test_examples = ... | a66ba4a2018b72b500466da37cd7dbb7bcb43238 | 616,006 |
def snakecase_key(key):
"""
Convert the key to snake_case by replacing ':' with '_'
and remove any leading '_'
This is so the keys are valid as Python kwargs and can be used to filter
the page models on on keys in the wp_post_meta which is a JSONField().
"""
return (
str(key) # some... | 80f0a09954648010adad9e1da405d0610dfc43eb | 616,007 |
from pathlib import Path
def testfile_checker(pytester, checker):
"""Return callable that compares pre existing file to testfile.
This fixture is designed to run in a test case that injects the
pytester fixture. pytester sets the current working directory
to a temporary directory while it is active. ... | 75f235b63547249770c04afa52c3b1b38bbc4001 | 616,012 |
import inspect
def clsname(obj):
"""Get objects class name.
Args:
obj (:obj:`object`):
The object or class to get the name of.
Returns:
(:obj:`str`)
"""
if inspect.isclass(obj) or obj.__module__ in ["builtins", "__builtin__"]:
return obj.__name__
return o... | f2787e0f94f95bcafb4668130eb8ab23d84fd7b6 | 616,015 |
def getAxis(node):
"""Parse rotation axis of a joint."""
axis = [0.0, 0.0, 0.0]
axisElement = node.getElementsByTagName('axis')[0].getAttribute('xyz').split()
axis[0] = float(axisElement[0])
axis[1] = float(axisElement[1])
axis[2] = float(axisElement[2])
return axis | ce9b268fcbd564845a1b05a342c96ed94998bd09 | 616,018 |
def preprocess_channel_types(channel_types):
"""
Preprocesses the given channel type values.
Parameters
----------
channel_types : `None`, `iterable` of `int`
Channel types to limit a slash command parameter to.
Returns
-------
processed_channel_types : `None` or `tuple... | 0afc2915f05053d2fd780aa4abc53ad460fdad6b | 616,020 |
def cipher(text, shift, encrypt=True):
"""
Function to encipher or decipher the string by using different shift number.
Parameters
----------
text : string
A string that you wish to encipher or decipher.
shift : integer
An integer that you wish to shift.
encrypt : boolea... | be24472672cb8ac4f9e582ea367f639f9709fb93 | 616,022 |
def get_sorted_key_index(class_key, class_dict):
"""
Given class_dict, returns an index that would result from ordering the keys
in class_dict according to their values and accessing one of the keys (class_key).
That index can be used to access multiclass prediction scores
"""
assert(isinstance... | 8e053c36e9647ed1446ccbd15987c75425d73bb1 | 616,023 |
def build_dummy_module_call(group_name, fifo_name, module_in, PE_ids):
"""Build the call of the dummy module
Parameters
----------
group_name: str
fifo_name: str
module_in: int
PE_ids: list
"""
dir_str = "out" if module_in == 0 else "in"
lines = []
lines.append("\n")
li... | 97effabf9031295e4362f57d49c0cca86769b2e8 | 616,027 |
def fact(n):
"""Calculate the value of n factorial."""
# n! = n*(n-1)*...*2*1
product = 1
for i in range(1, n+1):
product *= i
return product | d69912c04086d5b3e93e5f6e81836157cc378fcc | 616,030 |
def has_variable(obj, variable):
"""Tries to check if an object has a variable."""
if hasattr(obj, "has_variable"):
return obj.has_variable(variable)
return False | ebcd16faeacf029a622f0c31c19d1169fa1729e1 | 616,034 |
def _check_lunch_hours(time, lunch_start, lunch_end):
"""Checks if the time is during lunch"""
return (time < lunch_start) or (time >= lunch_end) | 97f80818af3577623de0e66011a3ab3f8170f878 | 616,035 |
import re
def parse_deal_code(deal_code):
"""
Converts an sku and it's quantity into separate parts.
eg.
A -> 1, A
3A -> 3, A
Args:
deal_code (string) - contains sku item and an optional quantity
(defaults to 1)
Returns:
int - quantity of item
... | 9cb6ce1adacbe9c7cfcc1882bfcdd10c88fd5951 | 616,037 |
def _links(x):
"""Helper function to link states with one another."""
return [(x[i],x[i+1]) for i,_ in enumerate(x[:-1])] | 6a10117b704cf723cb4f63677535f3145fd166e2 | 616,038 |
def get_total_figure_number(axis_matrix):
"""
Gets the number of figures from an axis_matrix generated by pyplot. Used by the hash to place configs in the
correct part of the axis_matrix
Parameters:
axis_matrix (1D or 2D numpy array) = Array returned by pyplot once multiple figu... | dcab29bd85735bee19756a084c182fb0a60e9549 | 616,040 |
def sanitize(str, strip=[" "], remove=["\r", "\n"]):
"""Return a whitespace-stripped, newline-stripped string.
Args:
str (str): The string to be sanitized.
strip (str[], optional) Additional things to be stripped.
remove (str[], optional) Additional things to be removed.
Returns:
(str) ... | d84d0f021cbaa283ee0cfe4128c362188e4dbef2 | 616,041 |
def get_timeout(filesize):
"""
Get a proper time-out limit based on the file size.
:param filesize: file size (int).
:return:
"""
timeout_max = 3 * 3600 # 3 hours
timeout_min = 300 # self.timeout
timeout = timeout_min + int(filesize / 0.5e6) # approx < 0.5 Mb/sec
return min(ti... | c6047968c6837f80da2936853f79688fadc56975 | 616,045 |
def get_effective_batch_size(opts):
"""Returns effective batch size
:param dict opts: A dictionary containing benchmark parameters. Must contain
`batch_size`, `device` and optionally `num_gpus`.
:return: Effective batch size.
:rtype: int
"""
num_devices = 1 if opts['device... | 7e91081840bbd9b335984b34194eac77b9307640 | 616,047 |
import torch
def MaskedDenseMM(X, Y, rows, cols):
"""Helper routine for Backward computation for spmm
Z = X[rows,:] x Y[cols,:]
Args:
X: dense matrix
Y: dense matrix
rows: row indices of X
cols: row indices of Y
Returns:
Z as defined above
"""
#Z = X * ... | ea0b05d9631cfa91a8368398dd9c4336061c54b5 | 616,050 |
def _strip_whitespace(text_content: str) -> str:
"""Return text_content with leading and trailing whitespace removed
"""
output_content: str = str(text_content)
if text_content is not None and len(text_content) > 0:
output_content = text_content.strip()
return output_content | 6dda9623013f9ec7289e1098f49d8f991fbe2079 | 616,055 |
import torch
from datetime import datetime
from typing import Counter
def train_seed_generator(graph, args):
"""Generate Seed (Edges) based on some techniques
[1] chronologically split, use fresh data (e.g. latest one year)
[2] filter by edge type, here use the edge features dim=0, may use edge type exp... | dc1ce1b000022a798c2bbbf6bf470fc716aec883 | 616,059 |
def get_first(iterable, default=None):
"""Get the first not None item from an iterable or default."""
if iterable:
for item in iterable:
if item:
return item
return default | 5e96a323a9484c0b308a1491f64a5fdc05fed936 | 616,060 |
import base64
def base64_encode(bot, trigger):
"""Encodes a message into base64."""
if not trigger.group(2):
return bot.reply('I need something to encode.')
encodedBytes = base64.b64encode(trigger.group(2).encode('utf-8'))
encodedStr = str(encodedBytes, 'utf-8')
bot.say(encodedStr) | d9d515ee07b5cb48a28cf0196f483f5e69201fc6 | 616,061 |
def second_moment(data):
"""`second_moment` feature function
:param data: data to evaluate feature function on
:return: squared data
"""
return data**2 | 5f789d13decfe895b75eba48284603e687bd2eab | 616,063 |
def as_iterable(iterable_or_scalar):
"""Utility for converting an object to an iterable.
Parameters
----------
iterable_or_scalar : anything
Returns
-------
l : iterable
If `obj` was None, return the empty tuple.
If `obj` was not iterable returns a 1-tuple containing `obj`.
Ot... | a0b19a89715e6c06c3f5dc9d66480c9c1f44ea42 | 616,064 |
def decodeXMLName(name):
"""
Decodes an XML (namespace, name) pair from an ASCII string as
encoded by encodeXMLName().
"""
def invalid():
raise ValueError("Invalid encoded name: %r" % (name,))
if not name:
invalid()
if name[0] is "{":
index = name.find("}")
... | 39f0f8977b2c897b80b4c022d4a474a16fa1832a | 616,067 |
def build_input_map(protomap, inputs):
"""Builds a map to feed tensors in `protomap` using `inputs`.
Args:
protomap: A proto map<string,TensorInfo>.
inputs: A map with same keys as `protomap` of Tensors and SparseTensors.
Returns:
A map from nodes refered by TensorInfo protos to corresponding input
... | 0180db7b5c3ecd78b16fc07a0ad7a57d25e9101f | 616,068 |
def _named_tempfile_func(error_class):
"""Create a mock function for NamedTemporaryFile that always raises.
Parameters
----------
error_class : exception class
The error that should be raised when asking for a NamedTemporaryFile.
Returns
-------
named_temp_file : callable
A... | d27cd798f1462b25b5efea44f1cf8b5f59718938 | 616,071 |
def split_sample_name(s):
"""Split sample name into numerical and non-numerical parts
Utility function which splits the supplied sample name
into numerical (i.e. integer) and non-numerical (i.e. all
other types of character) parts, and returns the parts as
a list.
For example:
>>> split_s... | 9cd5e325de37d49a69cef0b9965cc019e027e5e7 | 616,076 |
def get_page(request):
"""Returns the page parameter from the request.GET dictionary if it exists else default to page = 1"""
if 'page' in request.GET.keys():
page = request.GET['page']
else:
page = 1
return page | aac00fa28d16c0b66803b0ce347d1ae019686b73 | 616,078 |
def aggregation(item1, item2):
"""
For an (airport, counters) item, perform summary aggregations.
"""
count1, total1, squares1, min1, max1 = item1
count2, total2, squares2, min2, max2 = item2
minimum = min((min1, min2))
maximum = max((max1, max2))
count = count1 + count2
total =... | 257086d11e07450983d18cea3c81212484a769eb | 616,083 |
def get_round_id(rounds_list, tourn_id, tourn_day):
"""
Helper function to get the round_id
based on the specified tourn_id and tourn_day
"""
for item in rounds_list:
if item.get_tourn_id() == tourn_id:
if item.get_day() == tourn_day:
return item.get_round_id()
... | 040ea3f0d30501645e5c5816e69a6fc0af049570 | 616,089 |
import torch
def load_pth_embeddings(params, source):
"""
Reload pretrained embeddings from a PyTorch binary file.
"""
# reload PyTorch binary file
lang = params.src_lang if source else params.tgt_lang
data = torch.load(params.src_emb if source else params.tgt_emb)
dico = data['dico']
... | 70ad535cef2efe9b2de78fa31381bcedb4bc4dae | 616,090 |
def hyphen_to_underscore_string(string):
"""
Convert hyphens to underscores in the given string
"""
return string.replace('-', '_') | 56de69760f5c7cb8cfe0fe95660ac86fc166ff53 | 616,092 |
def extract_spectrum(fit_table, binNumber):
"""
Get the ``NBurst`` fitted spectrum for a given bin number.
Parameters
----------
fit_table :
the fit_table containg the fitted spectra
binNumber : int
the binNumber
Returns
-------
tuple of :class:`~numpy:numpy.ndarray`
... | 7892d8265ec0eb1135498b11d6cb604c481fbf6b | 616,098 |
def read_as_list(filename):
"""Read the file at filename and store its contents into a list."""
with open(filename) as f:
result = [line.rstrip() for line in f.readlines()]
f.close()
return result | 429fa2ff77bf645e99a0ff0d64b717868f0fc6cb | 616,099 |
def harmonize_entities(default_ents, requested_ents):
"""Harmonizes two dictionaries representing default_ents and requested requested_ents.
Given two dictionaries of entity: boolean key: value pairs, returns a
dictionary where the values of entities specified in `requested_ents` override those specified
... | bfc69d64146dae47afbb82ca48ce844028b0556b | 616,102 |
def bookmarklet_html() -> str:
"""Return HTML for serving the bookmarklet.
Returns:
HTML with instructions and links
"""
return """
<!DOCTYPE html>
<html>
<head>
<title>Salesforce Session ID Bookmarklet</title>
<script>
function copyId() {{
var idField = document.getEl... | e99a09e18a9c1f6807d8b22e247dfee10696db8e | 616,109 |
def trim_short_sentences(text: list):
"""
Trims short sentences from a list of sentences.
"""
text = [t for t in text if len(t) > 120]
return text | a0eb9841c8ffb5634b6295a2576f6d9c981cc834 | 616,113 |
def safeformat(str, **kwargs):
"""Function safeformat
A quick python (3.2+) way to avoid errors with missing keywords in strings.
Taken from https://stackoverflow.com/questions/17215400/python-format-string-unused-named-arguments
:param str: The list of strings with brackets
:param **kwargs: Argumen... | 6d0e01b13b653585e18af2aa234a468fcb184e12 | 616,117 |
import random
def random_id(length): # This function has two doctests inside it to give an example on how to make doctests
"""
Creates a random configuration key for the session - for safety of session variables.
>>> len(random_id(50)) == 50
True
>>> random_id('hello')
Traceback (most recent... | c0fd91738e1b233c72dacaebf089e1cac3848f68 | 616,125 |
import torch
def weighted_nll_loss(inpt: torch.Tensor, target: torch.Tensor, weight: torch.Tensor):
"""What `torch.nll_loss` with `reduction='weighted_average'` should be"""
return (
torch.nn.functional.nll_loss(inpt, target, weight=weight, reduction="sum")
/ weight.take(target).sum()
) | 2d67040100caa8ebb7e44f1ec20ef98fe8cb9e5a | 616,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.