content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def round_up(value):
"""
Rounds up a value to the nearest integer.
Arguments:
value (float): The value to round up.
Returns:
int: The rounded up value.
"""
try:
return int(math.ceil(float(value)))
except ValueError:
return value | a402bf14a1465e421b0fe1e93fe6a9c7f7aee2af | 583,294 |
def str2int(string):
""" Safely convert string to int or return None. """
return int(string) if string else None | 643eae6fc0ca5fe8383993bc839bee8c7905828a | 583,296 |
def get_locale_strings(path, prefix, middle, add_cr):
"""
Returns a string created by converting an installer locale properties file
into the format required by NSIS locale files.
Parameters:
path - the path to the installer locale properties file to preprocess
prefix - a string to prefix eac... | 0741b5879e24aa531ff83309d070efce0b9e9369 | 583,299 |
def null_group_membership(username, group):
"""Default group membership test.
Gives HOST permission to all users and MOD permission to those
with dpauth.moderator Django permission.
Custom implementations can delegate to this one if group is blank.
Parameters:
username -- the Username instance... | fd0651597887a47b03ec0bff37ac643b13662038 | 583,300 |
def perpetuity(A, r):
"""
A = annual payment
r = discount rate
returns present value
"""
return(A/r) | 9d771b23edf2a9f0eef9e33b3bf5a04e06dbd8b8 | 583,302 |
import codecs
def readTokens(path):
"""
Function to store tokens.txt in a list buffer.
Arguments
---------
path: location of tokens.txt
Return
---------
list of tokens
"""
# Create an empty buffer to hold all the sentences
tokensBuf = []
# Open the file
with codecs.open(path, 'r') as data:
for line... | fbb10c9aac4d5db44f9a27cc4d1657f9997ff3cf | 583,303 |
import hashlib
def md5(s):
"""returns the md5 hash of string s as a hex string"""
return hashlib.md5(s.encode("utf-8")).hexdigest() | c0d74c0e56b13874c14297cd784f3fbb4a57c813 | 583,307 |
def MergeIniDD(fusionDD, serverDD):
""" Merge Fusion's current state of its ini Definition Dictionary with
the server's DD. Fusion's DD takes precedence.
Parameters:
fusionDD - Fusion's current ini definition dictionary
serverDD - server's ini definition dictionary
Return Value:... | e1e2ecc3b718fa42ff2fa9df1202aea3287c0b6d | 583,308 |
import torch
def make_A(As, ns, device=torch.device("cpu"), dtype=torch.float32):
"""Create the 3D tensor A as needed by gel_solve, given a list of feature
matrices.
Arguments:
As: list of feature matrices, one per group (size mxn_j).
ns: LongTensor of group sizes.
device: torch d... | 238fc4252bd93f64e08f519611582281660e372b | 583,309 |
def filter_relation(relation, relation_type, relation_subtype, entity_ids):
"""
Function to filter a relation for given: type, subtype and entitiy ids.
Args:
relation (dict): dictionary representing a relation.
relation_type (str): relation type.
relation_subtype (str): relation sub... | 889f7fde1c1b09d6bccede7517818e1cde40e17f | 583,312 |
def package_version(filename, varname):
"""Return package version string by reading `filename` and retrieving its
module-global variable `varnam`."""
_locals = {}
with open(filename) as fp:
exec(fp.read(), None, _locals)
return _locals[varname] | 8b64f69a41b790bd8f376d53a954c2e0e6514645 | 583,315 |
def create_opponents(fixtures: dict, sort=False) -> dict:
"""Return the fixtures list for each PL team.
Args:
fixtures (dict, optional): fixtures
sort (boolean, optional): Sort opponents on gameweek. Defaults to False.
Returns:
dict: {team_id: [{team_id: int, difficulty: int, venue: ... | 838bfb311da90c85d9ee85ba8217b9b7ef440ac9 | 583,316 |
from typing import Any
def to_string(input_to_convert: Any) -> str:
"""
Converts to string, assumes utf-8 encoding for bytes
Input can be bytes, str, numpy array
:param input_to_convert: Dataset value to convert
:return: str
"""
if isinstance(input_to_convert, bytes):
return input_... | 16a6440167f2a3315830ee8bf83d0e5a0eef55a7 | 583,319 |
def _get_channels(forward, noise_cov=None, evoked=None):
"""Get channels from a forward object and exclude bad ones."""
fwd_sol_ch_names = forward['sol']['row_names']
info = forward["info"]
all_ch_names = set(fwd_sol_ch_names)
all_bads = set(info['bads'])
if noise_cov is not None:
all_ch... | a2dc1c2d4259ce8e66902a3b98489351165c2b1c | 583,336 |
def easy_unpack(tuple):
"""
returns a tuple with 3 elements - first, third and second to the last
"""
tuple2=(tuple[0], tuple[2], tuple[-2])
return tuple2 | fc0b4e4abd71e7b67756850e5f66bf6d6614d195 | 583,339 |
def _unify_strand(strand1, strand2):
"""If strands are equal, return the strand, otherwise return None"""
if strand1 != strand2:
strand = '.'
else:
strand = strand1
return strand | c59366ebfa4f4ee4311b6b68b468b4843c8300bf | 583,345 |
def scale_box2d(box, scale):
"""Scale box."""
h, w = box[1]
return (box[0], (h * scale, w * scale), box[2]) | 33a7115db3a98903b2928bdc25b9cc99c17c8168 | 583,348 |
def filter_migration_targets(targets, app_labels=None, exclude=None):
"""Filter migration execution targets based on the given criteria.
Args:
targets (list of tuple):
The migration targets to be executed.
app_labels (set of unicode, optional):
The app labels to limit t... | ea7c261f9b2bb173e18f64de27b38da0d52cb74e | 583,350 |
import re
def re_match(user_form, re_input):
"""Outputs a .group(1) string from a regular expression match."""
re_match = re.compile(re_input)
re_match = re_match.search(user_form)
if re_match:
return re_match.group(1).strip() | 95ec3be5433b5497b31057bcbdd8c2d55ff99dc5 | 583,352 |
def add_prefix_un(word):
"""Take the given word and add the 'un' prefix.
:param word: str - containing the root word.
:return: str - of root word prepended with 'un'.
"""
return 'un' + word | 5ce5b6899d1ebd83572ba2daaf1467ed3b239055 | 583,353 |
import torch
def select_device(gpu):
"""
选择CPU或GPU
Args:
gpu (bool): 选择GPU如果True,否则CPU
Returns:
device (torch.device): 'cpu' or 'cuda:0'
"""
if gpu:
assert torch.cuda.is_available(), ('Error: Requested GPU, '
'but GPU is not a... | 72f5263640856fd91ceb2c31750a288694482cf5 | 583,354 |
def dict_create(text):
""" Build dictionary with list of words from text """
dict = {'': ['']}
for i in range(0, len(text)):
if i < len(text) - 2:
if text[i] + " " + text[i+1] not in dict:
dict[text[i] + " " + text[i+1]] = [text[i+2]]
else:
di... | 7b652e59d376cc2db5877906df81c5efb7d060fd | 583,355 |
def rebinmask(mask, binx, biny, enlarge=False):
"""Re-bin (shrink or enlarge) a mask matrix.
Inputs
------
mask: np.ndarray
mask matrix.
binx: integer
binning along the 0th axis
biny: integer
binning along the 1st axis
enlarge: bool, optional
direction of bin... | 17c943e46d3ae26640fe2bf09cd0353b7dfb0952 | 583,356 |
import asyncio
def chunked_http_client(num_chunks):
"""
Returns a function that can fetch from a URL, ensuring that only
"num_chunks" of simultaneous connects are made.
"""
semaphore = asyncio.Semaphore(num_chunks) # <1>
async def http_get(url, client_session): # <2>
nonlocal semaph... | cb644f632bac83acdb812dfba8190d6dc456c92d | 583,359 |
def convert(im_height, im_width, box):
"""
Converts the box from normalized coordinates to absolute pixel values.
Arguments:
im_height: int
The image height, in pixels
im_width: int
The image width, in pixels
box: (int, int, int, int)
(left, right, top, bot) box co... | 62ae220212f2e850d90a6a75b4d71317d332bc5c | 583,360 |
def transform_pts_Rt(pts, R, t):
"""
Applies a rigid transformation to 3D points.
:param pts: nx3 ndarray with 3D points.
:param R: 3x3 rotation matrix.
:param t: 3x1 translation vector.
:return: nx3 ndarray with transformed 3D points.
"""
assert (pts.shape[1] == 3)
pts_t = R.dot(pt... | da76c5c110d8325fe14912ede34064223f3789e9 | 583,362 |
def par_insertion(pairs, chars, rules, steps):
"""
Apply steps of par insertion to the polymer template.
:param pairs: template pairs
:param chars: counter of characters
:param steps: number of required steps
:return: pairs, chars
"""
for _ in range(steps):
for (a, b), value in p... | 9058ce6aa1626d22bd9eaca0e613fdfcdd51d264 | 583,363 |
import re
def _syllable_count_sv(word):
"""count the number of syllables in a Swedish word"""
word = word.lower()
vowels = 'aoueiyåöä'
found_vowels = [b for b in word if b in vowels]
if found_vowels:
# journalist is the exceptional word where ou is counted as one syllable.
if not r... | f7935a85d301014cb0136f579ba7dcf1305b4375 | 583,368 |
def _getElementsFrom(smsTopList, dataset):
"""
Get elements that belong to any of the TxNames in dataset
(appear in any of constraints in the result).
Loop over all elements in smsTopList and returns a copy of the elements belonging
to any of the constraints (i.e. have efficiency != 0). The cop... | cbda3827bac0f1ace032cb39522085797fee7b2d | 583,369 |
def make_vars(spec):
"""Returns configurable variables for make"""
return f"AZURE_REGION={spec['region']} RESOURCE_GROUP_NAME={spec['resource_group']} STORAGE_ACCOUNT_NAME={spec['storage_acc_name']} FUNCTION_APP_NAME={spec['app_name']} APPINSIGHTS_NAME={spec['app_insights_name']}" | e7ac16ab906e215b53bdda14ae93a1746d162ace | 583,370 |
import base64
def b64decode(s: str) -> bytes:
"""
Returns an iterable collection of bytes representing a base-64 encoding of a given string.
"""
return base64.decodebytes(s.encode('utf-8')) | 300fa7265196c788dbc0824248f63062b184728d | 583,372 |
def sqrt(a: float) -> float:
"""Return the square root of a.
Args:
a (float): the number that you want to take the square root of
Raises:
ValueError: raises if `a` is below `0`
Returns:
float: the square root of `a`
"""
if a < 0:
raise ValueError("math domain ... | 2a9dc7f8db74296a3f74b21de27824ab5272b45c | 583,375 |
def wuyts_line_Av(Acont):
"""
Wuyts prescription for extra extinction towards nebular emission
"""
return Acont + 0.9*Acont - 0.15*Acont**2 | 220c5d1ae4bfdb370eb235aff75d8fcc958b068a | 583,376 |
def GetOSMallocTagSummary(malloc_tag):
""" Summarize the given OSMalloc tag.
params:
malloc_tag : value - value representing a _OSMallocTag_ * in kernel
returns:
out_str - string summary of the OSMalloc tag.
"""
if not malloc_tag:
return "Invalid malloc tag value:... | 7d2c076bcf9b3e056613cc71af4949615c759f1f | 583,377 |
def get_value_and_unit(value_string):
"""
Takes a string and splits it up, returning the number part and the unit part
:param (str) value_string: examples: "100Mi", "8", "500n" (does not need to include unit)
:return: ((int) numerical value, (str) unit, which is empty string for no unit)
"""
i ... | 74456b78a8382e3f092a2ab7b3960d4b5e32a8d7 | 583,378 |
def sort_heap_updates(heap_updates, num_heap_updates):
"""Take an array of unsorted heap updates and sort by row number."""
row_numbers = heap_updates[:num_heap_updates, 0]
# use mergesort since it is stable (and supported by numba)
heap_updates[:num_heap_updates] = heap_updates[:num_heap_updates][
... | da70daa17663a41260d3a9fcc9900b58fa372a54 | 583,379 |
def get_item_hash(terms, i):
"""
Computes the hash of the `terms`, based on its index `i`.
:param terms: the terms
:type terms: List[Term]
:param i: the index of the term
:type i: int
:return: the hash
:rtype: int
"""
if terms[i] is None:
return 0
if terms[i].is_cons... | b62ea9f22a4ae11e34a7b569f0f0dbb5d540a99f | 583,381 |
def str_from_file(path):
"""
Return file contents as string.
"""
with open(path) as f:
s = f.read().strip()
return s | b3b12fb53edcf806c420f290cef0f5217341d5bb | 583,383 |
def is_list(value):
"""
Returns True if the given value is a list-like instance
>>> is_list([1, 2, 3])
True
>>> is_list(u'2')
False
"""
return isinstance(value, (list, tuple, set)) | 566890395d57b4b9e14312f983d932322eb6f93b | 583,384 |
def get_label(trait):
"""Format the trait's label."""
part = trait["part"] if trait.get("part") else ""
subpart = trait["subpart"] if trait.get("subpart") else ""
trait = trait["trait"] if trait["trait"] not in ("part", "subpart") else ""
return " ".join([p for p in [part, subpart, trait] if p]) | 84728941631fa8bdaaa3e02cd9903c4f9e3b50d8 | 583,387 |
def round_scalar(scalar):
"""Rounds a scalar to the nearest integer
Args:
scalar (float): scalar to round
Returns:
int: input rounded to the nearest int
"""
return int(round(scalar)) | 1641c78eb80ed6d3344742ed1b291ea08996d299 | 583,389 |
import base64
def encode_images(images):
"""
Encodes the processed image(s).
Args:
images: A list of input images (nparrays)
Returns: A list of encoded image(s) as ByteStrings
"""
ret = []
for image in images:
ret.append((base64.b64encode(image)).decode('utf-8'))
retu... | e539018809545cc2240eca3e5b63ab5fd9e98229 | 583,392 |
import inspect
def _accepts_args(fn, *args, **kwargs):
"""Returns True if `fn` can accept `*args` and `**kwargs`."""
try:
inspect.signature(fn).bind_partial(*args, **kwargs)
return True
except TypeError:
return False | 0b912c5398999347b1aaf36931988689c36d2dce | 583,397 |
def _hdf5_yt_array_lite(fh, field):
"""
Read an hdf5 dataset. If that dataset has a "units" attribute,
return that as well, but do not cast as a unyt_array.
"""
units = ""
if "units" in fh[field].attrs:
units = fh[field].attrs["units"]
if units == "dimensionless": units = ""
ret... | c03f5f8e5f0c62cb5d0ef18b9aee0ed629a47000 | 583,399 |
def line_text(*fields, **kargs):
"""
Transform a list of values into a tsv line
:param fields: list of values as parameters
:param kargs: optional arguments: null_value: value to interpret as None
:return: tsv line text
"""
null_value = kargs.get("null_value", "")
return "\t".join([str(x) if x is not None else ... | 0b3abf4f408b5f75807d0ee514f88d2c2e1f98bd | 583,406 |
def _list_str(string, separator=','):
"""Convert comma separated string to list."""
return string.strip('{:s} \n\t'.format(separator)) | dd272909c58ededde01ad6ebb01101d58788c42f | 583,407 |
def validipaddr(address):
"""
Returns True if `address` is a valid IPv4 address.
>>> validipaddr('192.168.1.1')
True
>>> validipaddr('192.168. 1.1')
False
>>> validipaddr('192.168.1.800')
False
>>> validipaddr('192.168.1')
False
"""
try:
... | a04450a660d2147c0955bb034d045596b2ba22f1 | 583,408 |
def _try_import(module_name, insistance):
"""Maybe import a module and maybe raise an error if the import fails.
"""
if insistance in [False, 'no', 'false', 'False']:
return None
module = None
try:
module = __import__(module_name)
except ImportError as e:
if insistance in... | d43a1640724d8cc9306e3aeeda9ddddc95fdce64 | 583,411 |
def add_cell(self, node_indices, cell_type):
"""Add a new cell defined by node indices and cell type.
Parameters
----------
self : MeshMat
an Mesh object
node_indices : ndarray
a ndarray of points indices
cell_type : str
Define the type of cell.
Returns
-------
... | 0fcb1de3a5b2a3572d44ab4120515db71d78d8ac | 583,412 |
import math
def logadd10(x,y):
""" Addition in logspace (base 10): if x=log(a) and y=log(b), returns log(a+b) """
return x + math.log10(1 + pow(10,y-x)) | a8c17cc5a197858db61a062c08aa77b8df7505eb | 583,413 |
def add_match_to_dict(dictionary, match, prefix=""):
"""Add all group-value pairs from match to dict with given key prefix."""
dictionary[prefix + "0"] = match.group(0)
for idx, val in enumerate(match.groups()):
dictionary[prefix + str(idx + 1)] = val
for key, val in match.groupdict().items():
... | ccd10576db8903cdf1175fa45594b6b897c1baea | 583,415 |
def is_matching_submodule(prev_submodule, new_submodule):
"""Match two npm submodules based on package name or location."""
if 'package_name' in prev_submodule and 'package_name' in new_submodule:
return prev_submodule['package_name'] == new_submodule['package_name']
assert 'package_location' in p... | e9d1cbcafff2d929a66848538ca25971bc5146bc | 583,416 |
def to_hex(num):
"""
Convert a number to hex format
"""
if num < 0:
return "-0x%x" % (-num)
else:
return "0x%x" % num | cd5ac5427660a2ece3c87a4efd0b8219f2fe760c | 583,428 |
def size_in_gb(size):
"""Return the size in GB without the unit."""
result = size.replace(' ', '')
if result[-2:] == 'GB':
return result[:-2]
elif result[-2:] == 'TB':
# some size are provided in x.y GB
# we need to compute the size in TB by
# considering the input as a ... | 015875ebfe5da532b064756390ca96e9654a06c0 | 583,429 |
def process_cameo(event):
"""
Provides the "root" CAMEO event, a Goldstein value for the full CAMEO code,
and a quad class value.
Parameters
----------
event: Tuple.
(DATE, SOURCE, TARGET, EVENT) format.
Returns
-------
root_code: String.
First two dig... | 9eaf7ad60c3e81afdf1dbf0f566ba677e11669cd | 583,437 |
import re
def process_dynamic_value(line):
""" Cheks if the current line has an assignment
in the form of variable = ${some.value}
Arguments:
line {string} -- the line to be checked for the dynamic assignment
Returns:
dynamic_value -- matched text from line.
... | bf6f0413ae6f2385b76a893806cf4421806433cc | 583,438 |
from typing import Iterable
from typing import List
def script_param_indexing(array_lengths: Iterable[int],
repeat: int) -> List[str]:
"""Creates the script lines that set parameter indices for a run.
Args:
array_lengths: The number of parameter settings used for each parameter,
... | 56af825f4594def58b32c5a7205803395d937d48 | 583,440 |
def get_rid_dict(contrib_element):
""" For an individual contributor, get the list of their associated rids.
More about rids: https://jats.nlm.nih.gov/archiving/tag-library/1.1/attribute/rid.html
Used in get_contrib_info().
:param contrib_element: An article XML element with the tag <contrib>
:retur... | 6e106aeb0acb1bc93569df3b5e2496882e8b8ba7 | 583,442 |
import random
def flip_coin() -> str:
"""Flip a coin and output heads or tails randomly."""
result = 'heads' if random.randint(0, 1) == 0 else 'tails'
print(result)
return result | fc5c0b865760df7e00a7734e9285c4a16ead5095 | 583,443 |
def cli_env(tracking_server_uri):
"""Provides an environment for the MLflow CLI pointed at the local tracking server."""
cli_env = {
"LC_ALL": "en_US.UTF-8",
"LANG": "en_US.UTF-8",
"MLFLOW_TRACKING_URI": tracking_server_uri,
}
return cli_env | dad51e20804842df418b5aea7eb6c2e4524add9d | 583,450 |
import torch
def census_transform(img: torch.Tensor, kernel_size: int) -> torch.Tensor:
"""Census transform
calculates the census transform of an image of shape [N x C x H x W] with
batch size N, number of channels C, height H and width W. If C > 1, the census
transform is applied independently... | 989d01e0ce3328d83c4ec46d15825926554c5bdb | 583,451 |
import re
def get_node_type_yaml(name, mapper):
"""Map SHCD device name to device type.
Args:
name: A string from SHCD representing the device name
mapper: An array of tuples (SHCD name, hostname, device type)
Returns:
node_type: A string with the device type
rename: The ... | 4d1a108dd6c45e2c35a5b1a09681dc69c116d6bc | 583,453 |
from typing import Dict
from typing import Any
def deep_copy(t: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Returns copy of dict `t`, following nested dict structures.
:param t: Input dictionary
:returns: Copied dictionary
"""
r = {}
for k, v in t.items():
if isinstance(v, dict):
... | 74040fee7bed445af1555874f674e8149aa9b835 | 583,455 |
def select( display ):
"""Make the given display the "current" display (global scene)"""
global scene
scene = display
return display | a0d6d7663da5df12db48f2c0791b5ff2ee326fac | 583,457 |
import aiohttp
import json
async def get_jailbreaks():
"""Gets all jailbreaks on stkc's API
Returns
-------
list
"Jailbreaks"
"""
response = {}
async with aiohttp.ClientSession() as client:
async with client.get('https://assets.stkc.win/jailbreaks.json') as resp:
... | 826829e7e3c88ddafc2e2ab43993e3f20bf76ef1 | 583,458 |
def validity_of_currencytype(ctype, ftype):
"""This function checks if the user input of Cryptocurrency type
or Fiat Money type are truly the latter.
Returns 1 if found an error in the input, else returns 0."""
available_cryptocurrencies = ['ADA', 'BTC', 'BSV', 'ETH',
'ETC', 'B... | 17b491678e6069f1ba819e8267b3e9f81ae21810 | 583,465 |
from typing import Dict
from typing import Any
from typing import Optional
from typing import Sized
def add_if_exists(obj: Dict[str, Any], key_name: str, key_value: Optional[Any]) -> Dict[str, Any]:
"""
Add the value to the given dictionary if it is not None.
:param obj: Dictionary to add to.
:param ... | 433f21768bc9dcc7cd4b306bc60d8f5e81bd8fda | 583,468 |
def parse_weights(weights):
"""Parse loss weights from configuration setting.
Args:
weights: weights in configuration
Return:
a list where each element is the weight as float
"""
weights = weights.split(",")
weights = [float(w) for w in weights]
return weights | 2bd33435794baef46e85a196c7ed3ac711dd9c0e | 583,471 |
def get_network(ip, netmask):
"""Get network address from ip and netmask"""
ip_octets = ip.split('.')
nm_octets = netmask.split('.')
return '.'.join(
[str(int(ip_octets[x]) & int(nm_octets[x])) for x in range(0,4)]
) | 84036180e41262ef817ab8e0219acff43cfc3f6b | 583,475 |
def route(path, **kwargs):
"""Define a http route that should trigger the function
The parameters to this decorator will be passed to the ``route`` function of Bottle
:param path: path to match
:param kwargs: additional keyword arguments to be passed to Bottle
"""
def route_decorator(f):
... | 2ca6db973f6f0fb8c9cf064ec6045edc4aaa474e | 583,477 |
import importlib
def import_class(import_path: str) -> object:
""" Import class from import_path
:type str:
:param import_path: path to module similar to path.to.module.ClassName
:returns: imported class
"""
splitted = import_path.split('.')
class_name = splitted[-1:][0]
module_pat... | c4b2dc1443029271adc5f04135cb1e277aa52ea6 | 583,479 |
def get_header_desc(reader, header_id):
"""Get description field of an header field ID
Args:
reader (cyvcf2.VCF)
header_id (str)
Returns:
str: Information from a vcf header description
"""
for rec in reader.header_iter():
d = rec.info()
if d.get('ID'... | 42eec0905bf497d7fd4be4485b1e5b682289a3dd | 583,484 |
def special_load_rules(branch):
"""
Detect if the branch requires special conversion rules.
"""
try:
return "__data_type__" in branch
except TypeError:
return False | 3c5737fca3538df947f9d85c616ee5750b4edc0f | 583,485 |
def shared_features_attr_or_input_features(self, x_embed_features: int) -> int:
"""Use class attribute for the embedding features, back off to matching.
Note:
This function is basically a method that is set as a class attribute to
avoid issues of JAX returning tracer values for this function.
This ass... | c437e81a24c5bd3ed7698faa5fcd14b23be3451b | 583,487 |
def _get_cols_length(table, cols_num):
"""Return the max length of every columns.
"""
cols_length = [0] * cols_num
for row in table:
for (i, col) in enumerate(row):
col_len = len(col)
if col_len > cols_length[i]:
cols_length[i] = col_len
return cols_le... | 02c852944d3d5efc50bec79adfe32f4519803c7a | 583,492 |
def makeHeaderLine(M):
"""
Input:
M: scalar, number of dimensions in a hFunction
header line has format "seed,est0,est1,..,estM,hasMet,tau,nStep,nXstep,timeTaken"
"""
estsPart = ["est%d" %x for x in range(M)]
estsStr = ','.join(estsPart)
line = "seed," + estsStr + ",hasMet,tau,nSte... | 7900a2f7fce4ce444a08139aef7a6b3fce175d8e | 583,493 |
def pad_sentences(data_batch, pad=0, raw=False):
"""
Given a sentence, returns the sentence padded with the 'PAD' string. If
`pad` is smaller than the size of the sentence, the sentence is trimmed
to `pad` elements. If `pad` is 0, the function just returns the original
`data`. If raw is False, then ... | c1f038fb07fd92a72ce75cdfcf3c9493b499376d | 583,494 |
def get_elmo(model, sentence_list, indices_list):
"""
Get elmo embeddings
:param model: elmo model
:param sentence_list: List of sentences for which embeddings will be created
:param indices_list: List of list of indices. For every sentence: A list of indices for which words embeddings will be creat... | 7c7eaf757d0e64d92e433296c43d6ac85585593d | 583,505 |
def inherit_docstring_from(cls):
"""
This decorator modifies the decorated function's docstring by
replacing occurrences of '%(super)s' with the docstring of the
method of the same name from the class `cls`.
If the decorated method has no docstring, it is simply given the
docstring of `cls`s me... | b5d0563ef07abfb8687c018e2088e653c2ec2dc5 | 583,506 |
def render_block_list(title, blocks):
"""Renders a table of blocks with just the block name (and link)"""
body = f"""<p>{title} ({len(blocks)})</p>
<table>
<tr><th>Block</th></tr>
"""
for block in blocks:
body += f"<tr><td><a href='/b/{block['num']}'>{block['name']}</a></td></tr>"
bo... | ea94e1f5678d5754dda40dc11f4b04b39aac2eff | 583,510 |
def build_dict(word_count, min_count):
"""Construct dictionaries about words' id and frequency.
Args:
word_count: list, with element like (word, count)
min_count: int, minimum number of word occurrences
Returns:
2 dictionary that map word to id, id to word, respectively.
"""
... | 4af4bdeffe481c5df1db04d39685a22890d429a4 | 583,511 |
import json
import requests
def make_request(method, url, params=None, auth=None):
"""
:param method: HTTP method
:param url: URL
:param params: dict of query parameters
:param auth: 2-tuple of (user, password)
:returns: HTTP response
"""
headers = {'content-type': 'application/json'}
... | 10bac579158faf4bb6e360f95eb8510c1ca6e277 | 583,512 |
def cross_product(v1, v2):
"""Returns the cross product between two vectors
Arguments:
v1 {Vector3} - First vector
v2 {Vector3} - Second vector
Returns:
Vector3 - Cross product between the vectors
"""
return v1.cross(v2) | bfc8567d1376cdefedd574ab2d1a2183b73e7bbe | 583,513 |
def _text_point_at_line_end(size, p1, p2):
"""
Calculate position of the text relative to a line defined by points
p1 and p2.
Parameters:
- size: text size, a (width, height) tuple
- p1: beginning of line segment
- p2: end of line segment
"""
name_dx = 0.0
name_dy =... | bfbb0f550e0aac184028dfe492be7a89981d7cda | 583,516 |
def distance(a, b):
"""
Calculate distance between coordinates a and b.
Params
------
a : tuple
b : tuple
Returns
-------
out : float
Squared distance between coordinates a and b.
"""
return (a[0] - b[0])**2 + (a[1] - b[1])**2 | 990965804a94cd142feb7593d1c065acf6097184 | 583,517 |
import re
def _strToVal_Regexp(v, regexp, flag=0, excludeStart=[]):
"""Test (and convert) a generic string type, with a check against a regular expression.
@param v: the literal string to be converted
@param regexp: the regular expression to check against
@param flag: flags to be used in the regular e... | ad99f0892e8709e400ab8793274be4dfd110e7b3 | 583,522 |
import torch
def test_mask() -> torch.Tensor:
"""Single 4x4 test mask with index labels.
:return: 4x4 single-channel index tensor
:rtype: torch.Tensor
"""
return torch.tensor([[0, 1, 3, 3], [2, 4, 2, 1], [1, 2, 2, 0], [2, 255, 255, 255]], dtype=torch.int) | 9e4e7ecb2b00a34cd9dd85b528f2fda19828cb0a | 583,523 |
def read_file(path):
"""Read path and return the data as a giant string."""
with open(path, 'r') as rf:
return rf.read() | 35116a6dbfc2c5f2cdcec6a9515df5f76d6623ac | 583,524 |
import ipaddress
def is_valid_ip(v):
"""Check if is a valid IP address
:param str v: A string value
:return: IP address version if valid, else 0
:rtype: int
"""
try:
ip = ipaddress.ip_address(v)
except ValueError:
version = 0
else:
version = ip.version
re... | 8db7ac88cebfe0afeee859cc22b66105ffb66a8d | 583,529 |
import re
def run(text, meta):
"""Remove refs from the text.
Returns text with a regex substitution and unchanged META."""
pat = re.compile(meta.get("ref_regex", "[[(]*ref:[0-9a-f]+[])]*"))
text = pat.sub("", text)
return text, meta | 5ff0034a9269594b994819f7c9df2719f9d009f1 | 583,530 |
def _unavailable(err):
"""A wrapper that raises a RuntimeError if a function is not supported."""
def wrapper(*fargs, **kw):
raise RuntimeError(err)
return wrapper | b3dac84043bf3fcc965d21efe1717033202d65e6 | 583,531 |
def FPKM_to_TPM(df):
"""FPKM expression values to TPMs.
The sum of all TPMs in each sample are the same.
Refer to : https://www.rna-seqblog.com/rpkm-fpkm-and-tpm-clearly-explained/
Parameters
----------
df: pandas.DataFrame
Each row is a gene, and each column is a sample.
R... | 94066354d7ddc8347b0a6bdb12a8828865c8e482 | 583,532 |
def time_dhms_to_frac(dhmses):
"""Converts time in format d:h:m:s to time in parameters format =
fraction of the day.
"""
fractions = list()
for dhms in dhmses:
day, hour, minute, second = dhms
fraction = day + hour / 24.0 + minute / (24.0 * 60.0) + \
second / (24.0 * 60... | 1d99d5f614ecd0c10851ca591763af19c53a7de9 | 583,533 |
import re
def _parse_bitbucket_url(url):
"""
Handle URLs of the form:
- git://bitbucket.org/conducto/super.git
- git@bitbucket.org:conducto/super.git
- https://bitbucket.org/conducto/super.git
- git@bitbucket.org-user/conducto/super.git
Look for "bitbucket.org/{owner}/{repo}.git" or "b... | f81126c461017d97371c2e823d9fe829d6654a01 | 583,534 |
from pathlib import Path
def in_template(path: Path) -> Path:
"""Prepend the template directory to the path."""
return "{{cookiecutter.project_slug}}" / path | 23aa80c4c784273cafa9f1062e3a5151b6db32f9 | 583,536 |
def unique_list(list_redundant):
"""Select only unique elements in a list
"""
list_unique_elements = []
for element in list_redundant:
if element in list_unique_elements:
continue
else:
list_unique_elements.append(element)
return list_unique_elements | a3366a180e973d3e97b7e8f15dadc5e3327c65eb | 583,540 |
def message(file_checker, which=0):
"""Return a string of the message lines associated with the message of a file checker."""
assert(len(file_checker.messages) > which)
return "\n".join(file_checker.messages[which].message) | 8575f96d756e19b2a4cceb205d28e59cf0ac0d34 | 583,543 |
from pathlib import Path
def dir_path(path):
"""Wrapper around Path that ensures this directory is created."""
if not isinstance(path, Path):
path = Path(path)
path.mkdir(exist_ok=True, parents=True)
return path | 9227f9ac99d6c4278ea16c094c08205deeed7337 | 583,544 |
def get_book_info(book_id, metadata):
"""
Returns some basic information about a book given the book id and the metadata dataframe.
"""
book_info = metadata[metadata['best_book_id'] == book_id][[
'authors', 'original_publication_year', 'title', 'language_code', 'average_rating', 'image_url']]
... | 692e8d13d53823158b99d7c46562e6416c0ab7a5 | 583,551 |
def winding_number(
*,
x_center: float,
y_center: float,
xs_boundary: tuple[float, ...],
ys_boundary: tuple[float, ...],
) -> int:
"""
Computes the winding number.
The boundary, composed of paired x and y cooredinates as `xs_boundary` and
`ys_boundary` is assume to be closed. Thus, ... | 20a0cf83c0c2412331901910111a35dffb33863d | 583,554 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.