content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_all(model, scenario):
"""
:param model: a database model with fields scenario and name which are unique together
:return: a dictionary of the fields of the given model corresponding to the current simulation,
with their name fields as key.
"""
records = model.objects.filter(scenario=sce... | ac53802ce77dabe070f18c6c4aaac8fdf213d950 | 678,257 |
def collapse_sents(doc):
""" Collapse a doc to a list of sentences """
return [sent for part in doc for sent in part] | f640d485e01d470f46a009bc3f5d35f78a1027ba | 221,653 |
import re
def get_cmip_file_info(filename):
"""
From a CMIP6 filename, return the variable name as well as the start and end year
"""
if filename[-3:] != '.nc':
return False, False, False
attrs = filename.split('_')
var = attrs[0]
pattern = r'\d{6}-\d{6}'
match = re.match(pa... | 5296b7edf98adae455805b2138260d7e1afdc842 | 291,370 |
import click
def call_client_method(method, *args):
"""
Given a API client method and its arguments try to call or exit program
:param method: API client method
:param args: Arguments for method
:return: object from method call
"""
try:
return method(*args)
except Exception as ... | f5b1afddbb1c1ca7d5b3ce1ac8615d9674a7147a | 123,554 |
def lyap_r_len(**kwargs):
"""
Helper function that calculates the minimum number of data points required
to use lyap_r.
Note that none of the required parameters may be set to None.
Kwargs:
kwargs(dict):
arguments used for lyap_r (required: emb_dim, lag, trajectory_len and
min_tsep)
Retur... | 0190ce1328c239561465e03109ca624eac3432d7 | 561,047 |
def _get_cls(prefix: str | None, index: int) -> str:
"""Constructs a class identifier with the given prefix and index."""
return "ptg" + ("-" + prefix if prefix is not None else "") + str(index) | 2f9f390a8999d795d891ee93f33eacc9fe281abc | 253,562 |
import itertools
def flatten(lol):
"""
See http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python
e.g. [['image00', 'image01'], ['image10'], []] -> ['image00', 'image01', 'image10']
"""
chain = list(itertools.chain(*lol))
return chain | b6233b7d268bb13c74c7e8a6bcae835282f9be46 | 157,659 |
def getAverage(items):
"""
Gets the average amount in a list.
Args:
items (list): must contain floats or integers.
Returns:
(integer, float): average of all the items in list.
"""
return sum(items) / len(items) | 77e633decb9789b8a5e82a831b5539740dea85dc | 299,950 |
def toBytes(s):
"""
Method aimed to convert a string in type bytes
@ In, s, string, string to be converted
@ Out, response, bytes, the casted value
"""
if type(s) == type(""):
return s.encode()
elif type(s).__name__ in ['unicode','str','bytes']:
return bytes(s)
else:
return s | fb5253027efc0f98fc8da803a4982b49fd9af533 | 104,266 |
import time
import json
def retrieve_from_stash(request, key, timeout, default_value, min_count=None, retain=False):
"""Retrieve the set of reports for a given report ID.
This will extract either the set of reports, credentials, or request count
from the stash (depending on the key passed in) and return it enc... | 3aa3067a0e397e60c2c405c6e02362544d7442f3 | 257,058 |
def floatN(x):
"""
Convert the input to a floating point number if possible, but return NaN if it's not
:param x: Value to convert
:return: floating-point value of input, or NaN if conversion fails
"""
try:
return float(x)
except ValueError:
return float('NaN') | 58013fc6e79ca3294981cb79e4dfc844ed00df9e | 93,685 |
def format_price(amount):
"""
Format a price in USD
Args:
amount (decimal.Decimal): A decimal value
Returns:
str: A currency string
"""
return f"${amount:0,.2f}" | 56a27bffe7bbc273951f7058bce7e0329d78c6e2 | 211,639 |
def format_pattern(bit, pattern):
"""Return a string that is formatted with the given bit using either % or .format on the given pattern."""
try:
if "%" in pattern:
return pattern % bit
except:
pass
try:
return pattern.format(bit)
except:
return pattern | ad1aba8ca129d8639a84d1be9904f06feb9b7164 | 466,302 |
def extract_phone_number(num, replacement):
"""Takes in the phone number as string and replace_with arg as replacement, returns processed phone num or None"""
phone_num = "".join(i for i in num if i.isdigit())
if len(phone_num) != 10:
phone_num = replacement if replacement == "--blank--" else num
... | cf49aa0f2cea5974feb487385d76349430e3b5f7 | 18,644 |
def hamming_similarity(s1, s2):
"""
Hamming string similarity, based on Hamming distance
https://en.wikipedia.org/wiki/Hamming_distance
:param s1:
:param s2:
:return:
"""
if len(s1) != len(s2):
return .0
return sum([ch1 == ch2 for ch1, ch2 in zip(s1, s2)]) / len(s1) | 8a07dc99ae17e29fe9972c001b3586c23a89958f | 448,359 |
def to_title(str):
"""returns a string formatted as a title"""
return str.replace("_", " ").capitalize() | 13336936174445f61d5209ce1fabd19d7ae66fa2 | 25,753 |
def get_value_from_tuple_list(list_of_tuples, search_key, value_index):
"""
Find "value" from list of tuples by using the other value in tuple as a
search key and other as a returned value
:param list_of_tuples: tuples to be searched
:param search_key: search key used to find right tuple
:param ... | bc98e43430bca180bc95886aafc3580d87eab5f5 | 436,654 |
def getVar(var, d, exp = 0):
"""Gets the value of a variable
Example:
>>> d = init()
>>> setVar('TEST', 'testcontents', d)
>>> print getVar('TEST', d)
testcontents
"""
return d.getVar(var,exp) | b9cfb18566fabcbe133b20308539edfecbe15451 | 430,987 |
import unicodedata
def unicode_normalize(text):
"""Return the given text normalized to Unicode NFKC."""
normalized_text = unicodedata.normalize('NFKC', text)
return normalized_text | 1b6defacd09665412a1b31dd48f5291c4984d044 | 7,083 |
def delete_from(to_delete, string, pos):
"""
Deletes instance of 'str' in 'data' at this 'pos'
:param to_delete: string to be deleted from 'string'
:param string: string from which 'to_delete' will be deleted
:param pos: position of 'string' to delete
"""
data_array = list(string)
for i ... | 99d859ea646b776dfbdda486aadbda4cba9adfb9 | 545,968 |
def get_ether_vendor(mac, lookup_path):
"""
Takes a MAC address and looks up and returns the vendor for it.
"""
mac = ''.join(mac.split(':'))[:6].upper()
try:
with open(lookup_path, 'r') as f:
for line in f:
if line.startswith(mac):
return line... | b7f9b161fd1b00ef0a28fc37f210799eec8c1113 | 564,629 |
def coverage_rule(M, i, j, w):
"""
Total staffing coverage constraint
:param M: Model
:param i: period
:param j: day
:param w: week
:return: Constraint rule
"""
return M.cov[i, j, w] + M.under1[i, j, w] + M.under2[i, j, w] >= M.dmd_staff[i, j, w] | 28db465b702fbb7eb78102582a9f4edcbf4344c4 | 371,317 |
def getrouteccil(docdf):
"""
This splits the data frame column to produce new columns holding route and ccil information
Parameters
docdf: A dataframe holding the paragraphs of the document
Returns
docdf: A dataframe with new columns in appropriate order
"""
docdf[['route','... | afbf534919596c56826e693103269e1dd2d21f00 | 214,427 |
def sls_cmd(command, spec):
"""Returns a shell command string for a given Serverless Framework `command` in the given `spec` context.
Configures environment variables (envs)."""
envs = (
f"STAGE={spec['stage']} "
f"REGION={spec['region']} "
f"MEMORY_SIZE={spec['memory_size']} "
)... | 11d55f92e7dd34676666dfbfb8068490a33fb282 | 566,533 |
def select_nodes(batch_data, roots):
"""
Run 'select' in MCTS on a batch of root nodes.
"""
nodes = []
for i, root in enumerate(roots):
data = batch_data[i]
game = data[0]
state = data[1]
player_1 = data[2]
player_2 = data[3]
root = roots[i]
p... | bf6684814314b78200e115fdbb245c0a861fd74a | 80,876 |
import json
def parse_json(file_location):
"""
Load a json file into a dictionary.
:param file_location: The file to load
:return: A dictionary of the loaded data
"""
file = open(file_location, 'r')
json_data = json.loads(file.read())
file.close()
return json_data | 67323381d18e823b4aa4bf85ace1bc868878b463 | 398,112 |
def decode_float(value):
"""Decode a float after checking to make sure it is not already a float, 0, or empty."""
if type(value) is float:
return value
elif value == 0:
return 0.0
elif not value:
return None
return float(value) | 6bf499633b9a8ad7f669b899c15452f88efa88bc | 580,638 |
def _none_to_neg_1(x):
""" Swaps None to -1 for torch tensor compatibility. """
if x is None:
return -1
else:
return x | 3498c3d5457933f4ccdfbcd366fe4f45ee276a1d | 114,348 |
def sum_neg_off_diags_naive(m):
"""Returns sum of negative off-diags in m.
Naive, slow implementation -- don't use. Primarily here to check correctness
of faster implementation.
"""
sum = 0
for row_i, row in enumerate(m):
for col_i, item in enumerate(row):
if (row_i != col_i... | 027854945c295f4df067b7d440fdbf9b63f9ac81 | 260,390 |
import requests
def get_team(team_id, gw):
""" Get the players in a team
Args:
team_id (int): Team id to get the data from
gw (int): GW in which the team is taken
Returns:
(tuple): List of integers, Remaining budget
"""
res = requests.get(
'https://fantasy.premier... | 295c46628c14ad64715ee4a06537598878a8ef2e | 21,495 |
def CreateMnemonicsPython(mnemonicsIds):
""" Create the opcodes dictionary for Python. """
s = "Mnemonics = {\n"
for i in mnemonicsIds:
s += "0x%x: \"%s\", " % (mnemonicsIds[i], i)
if len(s) - s.rfind("\n") >= 76:
s = s[:-1] + "\n"
# Fix ending of the block.
s = s[:-2] # Remote last comma/space we always ad... | 4aab5f65413e8f2841d52a73b3e3a28396c867ec | 76,071 |
def strclass(cls):
"""Generate a class name string, including module path.
Remove module '__main__' from the ID, as it is not useful in most cases.
"""
if cls.__module__ == "__main__":
return cls.__name__
return f"{cls.__module__}.{cls.__name__}" | d2ca0f6e4dcdb737c67935172fa977a529fc9f80 | 613,166 |
def rename_bridge(df, batch_num):
""" Append batch number to bridge sample label """
cols = df.columns.tolist()
cols[-1] = 'Bridge%d' % batch_num
df.columns = cols
return df | 4acf0eb470f2a71429a26069618058d6a773b2b6 | 524,834 |
import random
import string
def make_key(length=64):
"""Generate a sequence of random characters."""
return "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length)
) | 4c9760ea00b3d4b38c2c0d918cf75f1059159df8 | 406,573 |
import json
def json_retreiver(json_filename):
"""Call this from a variable with a filename string to populate
with json content"""
filename = json_filename
with open(filename) as f:
return json.load(f) | e0fd2118b56d4638afa230fd866190fc0ebad2b6 | 457,626 |
def whitespace_tokenize(text):
"""Splits an input into tokens by whitespace."""
return text.strip().split() | 266f6bb537f82e599c85c96f70675a571bf5dafd | 36,688 |
def make_tag(token_function: str, span_type: str, delimiter: str = "-") -> str:
"""Create a tag from a token function and a span type.
Args:
token_function: The token function for the tag, it is the first part of the tag.
span_type: The type of the span this tag is part of it. It is the second ... | 4be5eafe6925e6b7ff53c76c003f0706b0e56edc | 160,394 |
def lamb_blasius(re):
"""
Calculate friction coefficient according to Blasius.
Parameters
----------
re : float
Reynolds number.
Returns
-------
lamb : float
Darcy friction factor.
"""
return 0.3164 * re ** (-0.25) | 45ae98b55d7e84a55a6f054350172c95dd224876 | 489,034 |
def _trim_quality(seq, qual, to_trim, min_length):
"""Trim bases of the given quality from 3' read ends.
"""
removed = 0
while qual.endswith(to_trim):
removed += 1
qual = qual[:-1]
if len(qual) >= min_length:
return seq[:len(seq) - removed], qual
else:
return None... | 8aa42a0cf4df8cbfd73e3bb464430ef8bf57b0e0 | 578,382 |
def get_multiples_desc(number, count):
"""
return the first count multiples of number in desc order in a list.
e.g call with input (3,2) returns [6,3]
call with input(5,3) returns [15,10, 5]
Hint: one line of code, use a builtin function we have already seen in the lists lesson.
"""
return ... | a95a4b74a8298b28e9c5bd3b90c3100dc4df5c74 | 279,973 |
def get_kp_labels(bands_node, kpoints_node=None):
"""
Get Kpoint labels with their x-positions in matplotlib compatible format.
A KpointsData node can optionally be given to fall back to if no labels
are found on the BandsData node. The caller is responsible for ensuring
the nodes match. This shou... | decd7c5f0a027fa975b7bdab692548f3c0c7d05a | 674,676 |
def get_third_party_permissions(manifest_tree):
"""Analyze manifest to see what permissions to request."""
root = manifest_tree.getroot()
values = []
third_party = set()
for neighbor in root.iter('uses-permission'):
values.append(list(neighbor.attrib.values()))
for val in values:
... | 93c78b021369eea6bbdbc2d2b59aee08268bb142 | 548,193 |
def trim_bg(img, color=None):
"""Trim background rows/cols from an image-like object."""
if color is None:
color = img[0, 0]
img = img[:, (img != color).any(0).any(-1)]
img = img[(img != color).any(1).any(-1)]
return img | 23a1105415953f90b36cb1b5266035eeeefab32c | 348,668 |
def mbxor(msg: bytearray, key: bytearray) -> bytearray:
"""Encrypt a message using the repeating key xor.
Arguments:
msg {bytearray} -- Message to be encrypted
key {bytearray} -- Key to be used
Returns:
bytearray -- Ciphertext of msg ^ key, length of longer msg
"""
cipher =... | cc7b02a69df0114589bea5af787b8ef6a3b6a95b | 536,319 |
def compile_hierarchy_req_str_list(geo_list: dict, str_list: list) -> list:
"""Recursively go through geo config to get list ids and combine with their str.
An example of hierarchial required geo ids would be:
county subdivision:
{
'<state id>': {
'<county id>': {... | 2de7df35c975f5842d4c88124e52da2698764a4b | 599,457 |
import torch
def get_entropy_loss(memory, args, i_agent):
"""Compute entropy loss for exploration
Args:
memory (ReplayMemory): Class that includes trajectories
args (argparse): Python argparse that contains arguments
i_agent (int): Index of agent to compute entropy loss
Returns:
... | 0d031100d17b64402340f1c0626a04fc083be8a0 | 32,591 |
def as_json_bool(value):
"""
Casts a value as a json-compatible boolean string
:param value: the value we want to force to a json-compatible boolean string
:type value: bool
:return: json-compatible boolean string
:rtype: str
"""
return str(bool(value)).lower() | eb7b9ffa142706947db8435f088d0e2ee390eaf0 | 133,983 |
def BFT(tree):
""" Breadth-first treavsal on general RST tree
:type tree: SpanNode instance
:param tree: an general RST tree
"""
queue = [tree]
bft_nodelist = []
while queue:
node = queue.pop(0)
bft_nodelist.append(node)
queue += node.nodelist
return bft_nodelist | 2e034943b0d9f55a1fcc2391e2a4fd4fe2b5dfcd | 395,986 |
def calc_min_flow(m0, m1):
"""
This function calculates the minimum flow of a distribution by comparison of two vectors.
this is useful when looking up at multiple buildings in a for loop.
:param m0: last minimum mass flow rate
:param m1: current minimum mass flow rate
:type m0: float
:type ... | e202e5d2ff0a1d451c4492fad8d1145cf017a85e | 144,822 |
def STR_CASE_CMP(x, y):
"""
Performs case-insensitive comparison of two strings. Returns
1 if first string is “greater than” the second string.
0 if the two strings are equal.
-1 if the first string is “less than” the second string.
https://docs.mongodb.com/manual/reference/operator... | 8fe54c3b62cb3b286b4b59583911a8a637f0fa69 | 126,735 |
def input_to_int(value):
"""
Checks that user input is an integer.
Parameters
----------
n : user input to check
Returns
-------
integer : n cast to an integer
Raises
------
ValueError : if n is not an integer
"""
if str(value).isdigit():
return int(value)
... | 702f6102a0abe37b139afcf298308ed1fc51ecf4 | 55,676 |
import copy
def get_subdatasets_transforms(transform_params):
"""Get transformation parameters for each subdataset: training, validation and testing.
Args:
transform_params (dict):
Returns:
dict, dict, dict: Training, Validation and Testing transformations.
"""
transform_params =... | 8b5ec9f9ebefde3447807e860bd482e6957f3ead | 489,191 |
def btdot(large, small):
"""Batch dot tensor product.
If the dimension of small is `N+1`, perform a batch N-dimensional dot product.
The dot operation produces the sum of the multiplied components. For example,
if small is 2D, perform a vector-vector multiplication. The first dimension
... | 6940a2f2bc3aa37dd54ad3e09f4cf753e9bde6f0 | 320,088 |
def check_parent(obj, Nparent):
"""Recursively check that the object have the correct number of parent
For instance: check_parent(stator, 3) will check that
output.simu.machine.stator exist
Parameters
----------
obj :
A pyleecan object
Nparent : int
Number of parent we expec... | 3167f952f9561bf0ec6977cdb14e6672d614009d | 213,722 |
import pathlib
def store_path_constructor(filename, dir_path):
""" Construct a filepath object for fxcm file store in the designated
clean store
:param filename: regex "^[A-Z]{6}_20\\d{1,2}_\\d{1,2}" ex: "AUDCAD_2015_1"
:param dir_path: base path
:return: full path
"""
store = pathlib.Pat... | a7897de23da3bbd29329f3d90046cea7b9664779 | 556,986 |
from typing import Optional
from typing import Union
import math
def calculate_gain(nonlinearity: str, param: Optional[Union[int, float]] = None):
"""
Return the recommended gain value for the given nonlinearity function.
The values are as follows:
================= =================================... | 8c80343f1435b7e3e84b83557cff8aa35443b326 | 655,804 |
import re
def strip_version(arxiv_id):
"""
Remove the version suffix from an arXiv id.
:param arxiv_id: The (canonical) arXiv ID to strip.
:returns: The arXiv ID without the suffix version
>>> strip_version('1506.06690v1')
'1506.06690'
>>> strip_version('1506.06690')
'1506.06690'
... | dd5cb79abbd842e6e968e4690af75d1797c830dd | 299,315 |
def get_cursor_ratio(image_size: tuple, screen_size: tuple):
"""
Used to calculate the ratio of the x and y axis of the image to the screen size.
:param image_size: (x, y,) of image size.
:param screen_size: (x, y,) of screen size.
:return: (x, y,) as the ratio of the image size to the screen size.
... | 7e0f0e66ba572657cc058aa7e83feeac2212f818 | 105,731 |
def get_number_of_epochs(opt, loader_train):
"""define the number of training epochs based on the lenght of the dataset and the number of steps"""
epochs = opt['epochs']
iter_per_epoch = -(-len(loader_train.dataset) // opt['bs'])
if epochs < 0:
epochs = 1 + opt['nsteps'] // iter_per_epoch
re... | a73904933e151ad03bb7ef3f9a23f0627d0ca086 | 95,777 |
from typing import Dict
def config_to_runner_env(config: Dict[str, str]) -> Dict[str, str]:
"""
Converts runner config to standard env vars (prefixed with 'RUNNER_')
Args:
config: Runner config dictionary
Returns:
Formatted env map for runner
"""
return {f"RUNNER_{key.upper()... | 93faf5bf6f9a113dd10b6341674138d153e0bbd2 | 130,160 |
def make_histogram(s: list) -> dict:
"""Takes a string or a list, finds its elements frequency and returns a dictionary with
element-frequency as key-value pairs.
"""
d = dict()
for char in s:
d[char] = 1 + d.get(char, 0)
return d | 355206fe757571fc9973df9b3984a642c829abdd | 561,457 |
import torch
def initialize_decoder_module(in_channels: int, out_channels: int) -> torch.nn.Module:
"""Initialize a decoder module including a ConvT, batchnorm and ReLU
"""
m = torch.nn.Sequential(
torch.nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, kernel_size=4, stride=2... | ca2b1dc9c6f52b162aeccfae0b72d434b821aea8 | 509,208 |
def ham(s1, s2):
"""Return the Hamming distance between equal-length sequences"""
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
mm=0
sup=0
for el1, el2 in zip(s1, s2):
if el1=='-' and el2=='-':
continue
sup +=1
if el1... | 42ee5c8cbbcbf1d9e59e6bac2941bed969ad08bf | 486,086 |
def vcf_get_index(vcf):
"""Return index as "CHR.POS"."""
return [
".".join([chrom, str(pos)]) for chrom, pos in zip(
vcf["variants/CHROM"],
vcf["variants/POS"]
)
] | 1dda63652283b6506fc666ca2d563d2267fa6e25 | 258,112 |
def _calc_pred_mse(tau, level):
"""Calculate a scaled predicted MSE based on
the predicted noise variance and the level of wavelet decomposition.
Args:
tau (list): predicted noise variance in each subband in the "wavelet" format.
Returns:
pred_mse (float): scaled predicted MSE.
N... | 44a008601f8aea96ea701d7b9b4585559c9e0690 | 126,576 |
def check_chemistry_def(chemistry):
""" Validate a chemistry definition dict. Return (ok, error_msg) """
required_keys = [
'description',
'barcode_read_type', 'barcode_read_offset', 'barcode_read_length',
'rna_read_type', 'rna_read_offset', 'rna_read_length',
'rna_read2_type', 'r... | 7eb3713325678aeaf139d7b21e60998ccdf784b5 | 139,575 |
def _FindPeakOnActual(latency_value):
"""Find a peak on actual stream using timestamp of reference peak and delay.
Args:
latency_value: (tuple (float, float)) containing a timestamp and a delay
value. Unit is seconds.
Returns:
(float) timestamp of the peak on the actual stream. Unit is seconds.
... | 97421af61a247854cb22c46571218584c387554f | 472,581 |
from pathlib import Path
import stat
def is_special_file(path: Path) -> bool:
"""Check to see if a special file.
It checks if the file is a character special device, block special device,
FIFO, or socket.
"""
mode = path.stat().st_mode
# Character special device.
if stat.S_ISCHR(mode):
... | 5cf516dfa8cf15d502216b83d36bf5a1f226ef88 | 270,706 |
def read_file(name):
"""Given the path of a file, return a list of numbers to be processed.
"""
d = []
file = open(name,'r')
data = file.readlines()
for line in data:
items = line.split()
d.append(int(items[0]))
return d | fc0f94ee01df683a8c5e449089508c00ca0b0f3a | 455,433 |
def list_services(config_dict):
"""
List available services
Args:
config_dict (dict): configuration dictionary
Returns:
list: list of available services
"""
return list(config_dict.keys()) | a3226589405292f0bcef99aabaec71722aaeb1db | 697,838 |
import json
def write_to_json_file(file_path, file_contents):
"""
Writes the given file_contents to the file_path in JSON format if current
user's permissions grants to do so.
:param file_path: Absolute path for the file
:param file_contents: Contents of the output file
:return: Output path
... | f34898b8ec01e6035a7b255914d91db0e14bca88 | 155,338 |
def move(x, y, direction, multiplier):
""" Moves point (x,y) in direction, returns a pair """
if direction == "UP":
return (x,y-multiplier)
elif direction == "DOWN":
return (x,y+multiplier)
elif direction == "LEFT":
return (x-multiplier, y)
elif direction == "RIGHT":
return (x+multiplier, y)
return (x,y) | 5dc4d27e3a7eb3643adacc1f3ebaf9fe85a94d07 | 303,992 |
def contains_duplicate(nums: list[int]) -> bool:
"""Returns True if any value appears at least twice in the array, otherwise False
Complexity:
n = len(nums)
Time: O(n)
Space: O(n)
Args:
nums: array of possibly non-distinct values
Examples:
>>> contains_duplicat... | 397c5f03cd7025eec1fda6041e1a344e7e61f4bc | 691,000 |
import torch
def get_torch_device(try_to_use_cuda):
"""
Return torch device. If using cuda (GPU), will also set cudnn.benchmark to True
to optimize CNNs.
Args:
try_to_use_cuda (bool): if True and cuda is available, will use GPU
Returns:
device (torch.Device): device to use for mo... | 8bdc407df3fc0a8184f99c1cdaabaccb34792547 | 148,581 |
def clean_plan_name(plan_name):
"""Standardize plan name."""
return str.lower(plan_name.replace(' ', '_')) | 863468932c12145ebb1ed819fbf0d2ede9c2f4e8 | 107,878 |
def merge (d, o):
"""Recursively merges keys from o into d and returns d."""
for k in o.keys():
if type(o[k]) is dict and k in d:
merge(d[k], o[k])
else:
d[k] = o[k]
return d | 1c1477e87c9596f10fc283969b985109b9d4cac6 | 333,999 |
def insertion_sort(integers):
"""Iterate over the list of integers. With each iteration,
place the new element into its sorted position by shifting
over elements to the left of the pointer until the correct
location is found for the new element.
Sorts the list in place. O(n^2) running time, O(1) spa... | ee7aa8920406f7c74870e346e486f29486894df1 | 15,670 |
def extract_preterminals(tree):
"""Extract the preterminals from the given tree."""
return [node for node in tree.subtrees() if node.height() == 2] | 41386b2165fa5394c5a5cdc7c09c928681ba0b11 | 317,667 |
def _is_notify_empty(notify_db):
"""
notify_db is considered to be empty if notify_db is None and neither
of on_complete, on_success and on_failure have values.
"""
if not notify_db:
return True
return not (notify_db.on_complete or notify_db.on_success or notify_db.on_failure) | 23c7e29240597991b7d7ee6ccf55a9e39fb9dbae | 527,878 |
import random
def d6() -> int:
"""Roll a D6"""
return random.randint(1, 6) | 8a56a6bc614a5397d28fb5abafd97df0383276f4 | 50,569 |
def is_integer(s_in):
"""Check if string represents an integer."""
s_in = str(s_in)
if s_in[0] in ('-', '+'):
return s_in[1:].isdigit()
return s_in.isdigit() | 70ad2b0500625163d834aca0e81bdd23c791750c | 163,382 |
import shlex
def shlex_join(split_command):
"""Return a shell-escaped string from *split_command*.
This is from Python 3.8:
https://github.com/python/cpython/blob/3.8/Lib/shlex.py
XXX: Obsolete with 3.8.
"""
return ' '.join(shlex.quote(arg) for arg in split_command) | 6556d64fcc5fcc5f013459c8a8285167fb288d84 | 166,772 |
def make_prefix_tree(flat_dict):
"""Convert a dictionary with keys of dotted strings into nested dicts with common prefixes.
Ex: { 'abc.xyz': 1, 'abc.def': 2, 'www': 3} is converted to:
{ 'abc': {'xyz': 1, 'def': 2}, 'www': 3 }
"""
tree = {}
for key, value in flat_dict.items():
subt... | 723f9ee1ad6c50b88f3456d51c2d91b90d4f4dca | 524,646 |
def downcase_string(s):
"""Convert initial char to lowercase"""
return s[:1].lower() + s[1:] if s else '' | 05ee7c118b3d635f978ddf73f107336cea26375c | 355,921 |
import socket
import struct
def ipIntToString(ip_int):
"""Convert integer formatted IP to IP string"""
return socket.inet_ntoa(struct.pack('!L',ip_int)) | 4883a075476f136640a691fce839f2c758ec84bd | 252,572 |
def listToNum(list):
"""Converts a bit-list [0, 1, 0, 1] to an int."""
return int(''.join(str(x) for x in list), 2) | 9ab86c56b09f6ffe4d158350d066c38a4f014c5a | 94,686 |
def add_tabix_subparser(subparser):
"""
Get commandline arguments
Args:
subparser (?): Subparser object.
Returns:
args (Namespace): the parsed arguments.
"""
parser = subparser.add_parser("tabix", help="Tabix subparser")
parser.add_argument("-vcf", "--variant-call-file", dest... | 001d09086df2f9c0308496eeda6476f85345278e | 609,356 |
def duthost(testbed_devices):
"""
Shortcut fixture for getting DUT host
"""
return testbed_devices["dut"] | 51e92bfe15cb2046616df34144eae0836adbff73 | 554,710 |
def compose(fun_f, fun_g):
"""
Composition of two functions.
:param fun_f: callable
:param fun_g: callable
:return: callable
"""
return lambda x: fun_f(fun_g(x)) | 8a40332d610fd4ae8bbe89b2843c95d7493822ff | 53,388 |
def get_attribute(target, name):
""" Gets an attribute from a Dataset or Group.
Gets the value of an Attribute if it is present (get ``None`` if
not).
Parameters
----------
target : Dataset or Group
Dataset or Group to get the attribute of.
name : str
Name of the attribute ... | 7c80d02c4f079055ec534cdf15f17cb0f7d5cde5 | 127,946 |
def part1(data):
"""
Each digit of a seven-segment display is rendered by turning on or off any of seven segments named a through g
There are ten unique signal patterns:
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c ... | 11be73780676b97fa20b8fd9137a6a4b3f1d845b | 579,230 |
def ashex(line):
"""
convert a byte-array to a space separated list of 2-digit hex values.
"""
return " ".join("%02x" % _ for _ in line) | d51dafe221c81697569f0d714fe814f8690d77aa | 387,361 |
def _get_input(prompt: str, default_value: str) -> str:
"""Wrapper around input() which shows the current (default value)."""
if default_value:
prompt = '{} ({}): '.format(prompt, default_value)
else:
prompt = '{}: '.format(prompt)
return input(prompt).strip().lower() or default_value | 5c6bbabb219b35a17f26a03feaa29f27e0b6590a | 171,912 |
def str_to_bin_array(number, array_length=None):
"""Creates a binary array for the given number. If a length is specified, then the returned array will have the same
add leading zeros to match `array_length`.
Args:
number: the number to be represented as a binary array.
array_length: optional) ... | f2a6763c59da9efa2c08943278622b3b50d703e2 | 114,918 |
def get_ratio(data_frame, field):
"""Calculates the ratio of the values of a given field of a DataFrame.
Args:
data_frame (DataFrame): a Pandas DataFrame to analyze
field (string): the field to calculate the values of
Returns:
Series: Pandas Series representing the count of distinc... | bd0f99369feda29f886f6195c32366a1775c46bc | 153,029 |
import time
def ValueOfDate() -> int:
"""
Return current unix time in milisecond (Rounded to nearest number)
"""
return round(time.time() * 1000) | cc0b51a1eb997ae12e19f40751fde28caad12877 | 664,050 |
def split_file(infile, prefix, max_size=50*1024*1024, file_buffer=1024):
"""
file: the input file
prefix: prefix of the output files that will be created
max_size: maximum size of each created file in bytes
buffer: buffer size in bytes
Returns the number of parts created.
"""
with open(... | 27d329610d1545995d600ec53dd9ae48301e6d75 | 571,607 |
def pow(x, y):
"""
Return x raised to the power y.
"""
return x**y | fac9a0235e03d15ddaa32d6e2aaf1561b0bb8df2 | 198,917 |
def bytes2str(info):
""" Converts bytes to string. """
if isinstance(info, bytes):
info = info.decode("utf-8")
return info | 562f297f1169d66f4c53da5e9027c750f60bfb6d | 226,212 |
def binary_search(arr, key):
"""
binary seach using iterative method
"""
first = 0
last = len(arr)-1
found = False
while first <= last and not found:
mid = (first + last) // 2
if arr[mid] == key:
found = True
else:
if arr[mid] > key :
last = mid -1
else:
first = mid + 1
return found | 2957a9f9900b69f31c24954ad040f4f70f79cdf7 | 564,756 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.