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=scenario)
return {record.name: record for record in records}
|
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(pattern, attrs[-1])
if not match:
# this variable doesnt have time
return var, False, False
start = int(attrs[-1][:4])
end = int(attrs[-1][7:11])
return var, start, end
|
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 e:
click.echo(str(e), err=True)
exit(1)
|
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)
Returns:
minimum number of data points required to call lyap_r with the given
parameters
"""
# minimum length required to find single orbit vector
min_len = (kwargs['emb_dim'] - 1) * kwargs['lag'] + 1
# we need trajectory_len orbit vectors to follow a complete trajectory
min_len += kwargs['trajectory_len'] - 1
# we need min_tsep * 2 + 1 orbit vectors to find neighbors for each
min_len += kwargs['min_tsep'] * 2 + 1
return min_len
|
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 encoded as JSON.
When retrieving reports, this will not return any reports until min_count
reports have been received.
If timeout seconds elapse before the requested data can be found in the stash,
or before at least min_count reports are received, default_value will be
returned instead."""
t0 = time.time()
while time.time() - t0 < timeout:
time.sleep(0.5)
with request.server.stash.lock:
value = request.server.stash.take(key=key)
if value is not None:
have_sufficient_reports = (min_count is None or len(value) >= min_count)
if retain or not have_sufficient_reports:
request.server.stash.put(key=key, value=value)
if have_sufficient_reports:
return json.dumps(value)
return default_value
|
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
return phone_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 value_index: Index telling which side of tuple is
returned and which is used as a key
:return: Value from either side of tuple
"""
for i, v in enumerate(list_of_tuples):
if v[value_index ^ 1] == search_key:
return v[value_index]
|
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 in range(len(to_delete)):
data_array.pop(pos)
return "".join(data_array)
|
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.split()[1].strip()
except Exception as e: # pragma: no cover
return 'NO DATA'
|
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','narrative']] = docdf['narrative'].str.split(' – ',1,expand=True)
docdf[['ccil','narrative']] = docdf['narrative'].str.split(' / ',1,expand=True)
docdf = docdf[['route','ccil','narrative']]
print(docdf['ccil'])
#replace blank ccils to be implemented
return docdf
|
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']} "
)
return f"{envs}serverless {command} --verbose"
|
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]
player = player_1 if game.player(state) else player_2
nodes.append(player.select(root))
return nodes
|
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) and (item < 0):
sum += item
return sum
|
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.premierleague.com/api/entry/' +
f'{team_id}/event/{gw}/picks/').json()
# Scrape GW before FH to get the team from GW prior
if res['active_chip'] == 'freehit':
res = requests.get(
'https://fantasy.premierleague.com/api/entry/' +
f'{team_id}/event/{gw-1}/picks/').json()
# Adjust the player id with fplreview indices
return [i['element'] for i in res['picks']], res['entry_history']['bank']
|
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 add for the last line.
if s[-1] != "\n":
s += "\n"
# Return mnemonics dictionary only.
return s + "}"
|
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 part
of the tag.
delimiter: A separator character (or sequence of characters) that separate the
`token_function` and the `span_type`.
Returns:
The created tag.
"""
return f"{token_function}{delimiter}{span_type}"
|
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, 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 list(reversed(range(number,(number*count)+1,number)))
|
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 should be the case if you take the kpoints from
the input and the bands from the
output of a calculation node.
:param BandsData bands_node:
The BandsData node will be searched labels first
:param KpointsData kpoints_node:
The optional KpointsData node will be searched only if no labels are
present on the BandsData node. No consistency checks are performed.
:return: (kpx, kpl), the x-coordinates and text labels
:rtype: tuple(list[int], list[unicode])
:raises AttributeError: if neither of the given nodes have a labels
attribute
"""
kplabs = None
kpx = []
kpl = []
try:
kplabs = bands_node.labels
except AttributeError as err:
if kpoints_node:
kplabs = kpoints_node.labels
else:
raise err
if kplabs:
kpx = [i[0] for i in kplabs]
kpl = [i[1] for i in kplabs]
for i, kpoints in enumerate(kpl):
if kpoints == 'G':
kpl[i] = r'$\Gamma$'
return kpx, kpl
|
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:
for perm in val:
if 'com' in perm:
third_party.add(perm)
return third_party
|
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 = bytearray(len(msg))
for i in range(len(msg)):
cipher[i] = msg[i] ^ key[i % len(key)]
return 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>': {
'<county subdivision id>': '<county subdivision name>'
}
}
}
Args:
geo_list: Dict of geo ids required for a particular summary level.
str_list: List API query prefix string for each level of dict.
Returns:
List of required geo strings to be added to API call.
"""
ret_list = []
for k, v in geo_list.items():
if isinstance(v, dict):
new_list = str_list.copy()
new_list[1] = f'{str_list[0]}{k}{str_list[1]}'
ret_list.extend(compile_hierarchy_req_str_list(v, new_list[1:]))
else:
ret_list.append(f'{str_list[0]}{k}')
return ret_list
|
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:
entropy_loss (torch.Tensor): Entropy loss for encouraging exploration
"""
_, _, entropies, _, _ = memory.sample()
entropy = torch.stack(entropies[i_agent], dim=1)
assert entropy.shape == (args.traj_batch_size, args.ep_horizon), \
"Shape must be: (batch, ep_horizon)"
entropy_loss = -args.entropy_weight * torch.mean(torch.sum(entropy, dim=1))
return entropy_loss
|
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 m1: float
:return: mmin: new minimum mass flow rate
:rtype: float
"""
if m0 == 0:
m0 = 1E6
if m1 > 0:
mmin = min(m0, m1)
else:
mmin = m0
return mmin
|
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/aggregation/strcasecmp/
for more details
:param x: The first string or expression of string
:param y: The second string or expression of string
:return: Aggregation operator
"""
return {'$strcasecmp': [x, y]}
|
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)
else:
raise ValueError('Expecting integer. Got: "{0}" ({1})'
.format(value, type(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 = copy.deepcopy(transform_params)
train, valid, test = {}, {}, {}
subdataset_default = ["training", "validation", "testing"]
# Loop across transformations
for transform_name in transform_params:
subdataset_list = ["training", "validation", "testing"]
# Only consider subdatasets listed in dataset_type
if "dataset_type" in transform_params[transform_name]:
subdataset_list = transform_params[transform_name]["dataset_type"]
# Add current transformation to the relevant subdataset transformation dictionaries
for subds_name, subds_dict in zip(subdataset_default, [train, valid, test]):
if subds_name in subdataset_list:
subds_dict[transform_name] = transform_params[transform_name]
if "dataset_type" in subds_dict[transform_name]:
del subds_dict[transform_name]["dataset_type"]
return train, valid, test
|
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
of both tensors is a batch dimension and it must match or be broadcastable.
If large has extra dimensions, they are considered batch dimensions too.
Args:
large (tensor): its last `N` dimensions are multiplied by small. The remaining
dimensions are batch dimensions.
small (tensor): a tensor whose first dimension is the batch, and the
remaining ones are to be multiplied. Its dimension must be equal or
saller than those of large.
Returns:
tensor: the result of the product.
"""
dim_diff = large.dim() - small.dim()
batch_dim = small.size(0)
extra_dims = [1] * dim_diff
remaining_dims = small.size()[1:]
sview = small.view(batch_dim, *extra_dims, *remaining_dims)
return (large * sview).sum(tuple(range(dim_diff + 1, large.dim())))
|
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 expect the object to have
Returns
-------
has_parent : bool
True if the object has N parent
"""
if Nparent == 0:
return True
elif obj.parent is None:
return False
else:
return check_parent(obj.parent, Nparent - 1)
|
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.Path(dir_path)
symbol = filename[:6]
year = filename[7:11]
full_filename = filename + '.csv.gz'
return store / symbol / year / full_filename
|
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:
================= ====================================================
nonlinearity gain
================= ====================================================
Linear / Identity :math:`1`
Conv{1,2,3}D :math:`1`
Sigmoid :math:`1`
Tanh :math:`\\frac{5}{3}`
ReLU :math:`\sqrt{2}`
Leaky Relu :math:`\sqrt{\\frac{2}{1 + \\text{negative\_slope}^2}}`
SELU :math:`\\frac{3}{4}`
================= ====================================================
Parameters
----------
nonlinearity : str
Name of the non-linear function
param : Union[int, float], optional
Optional parameter for the non-linear function
"""
linear_fns = ['linear', 'conv1d', 'conv2d', 'conv3d']
if nonlinearity in linear_fns or nonlinearity == 'sigmoid':
return 1
elif nonlinearity == 'tanh':
return 5.0 / 3
elif nonlinearity == 'relu':
return math.sqrt(2.0)
elif nonlinearity == 'leaky_relu':
if param is None:
negative_slope = 0.01
elif not isinstance(param, bool) and isinstance(param, int) or isinstance(param, float):
# True/False are instances of int, hence check above
negative_slope = param
else:
raise ValueError("negative_slope {} not a valid number".format(param))
return math.sqrt(2.0 / (1 + negative_slope ** 2))
elif nonlinearity == 'selu':
return 3.0 / 4 # Value found empirically (https://github.com/pytorch/pytorch/pull/50664)
else:
raise ValueError("Unsupported nonlinearity {}".format(nonlinearity))
|
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'
"""
return re.sub(r"v\d+\Z", '', arxiv_id)
|
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.
"""
x_ratio = screen_size[0] / image_size[0]
y_ratio = screen_size[1] / image_size[1]
return x_ratio, y_ratio
|
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
return epochs, iter_per_epoch
|
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()}": config[key] for key in config}
|
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, padding=1, bias=False),
torch.nn.BatchNorm2d(num_features=out_channels, momentum=1, track_running_stats=False),
torch.nn.LeakyReLU(negative_slope=1e-2)
)
return m
|
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 != el2:
mm +=1
return mm*1.0/sup
|
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.
Note:
The predicted MSE is used to determine whether to stop D-VDAMP early.
"""
pred_mse = 0
pred_mse += tau[0] * (4 ** (-level))
for b in range(level):
weight = 4 ** (b - level)
for s in range(3):
pred_mse += tau[b + 1][s] * weight
return pred_mse
|
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', 'rna_read2_offset', 'rna_read2_length',
'umi_read_type', 'umi_read_offset', 'umi_read_length',
'si_read_type', 'si_read_offset', 'si_read_length',
'read_type_to_bcl_processor_filename',
'read_type_to_bcl2fastq_filename',
'strandedness',
]
if 'name' not in chemistry:
return (False, "Chemistry definition is missing a 'name' key")
missing_keys = set(required_keys) - set(chemistry.keys())
if len(missing_keys) > 0:
return (False, "Keys missing from chemistry definition %s: %s" % (chemistry['name'], ','.join(sorted(list(missing_keys)))))
return True, None
|
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.
"""
return latency_value[0] - latency_value[1]
|
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):
return True
# Block special device
if stat.S_ISBLK(mode):
return True
# FIFO.
if stat.S_ISFIFO(mode):
return True
# Socket.
if stat.S_ISSOCK(mode):
return True
return False
|
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
:rtype: str
:raises: This method raises OSError if it cannot write to file_path.
"""
with open(file_path, mode='w', encoding='utf-8') as handler:
json.dump(file_contents, handler)
return file_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_duplicate([1,2,3,1])
True
>>> contains_duplicate([1,2,3,4])
False
>>> contains_duplicate([1,1,1,3,3,4,3,2,4,2])
True
"""
"""ALGORITHM"""
## INITIALIZE VARS ##
# DS's/res
nums_set = set()
for num in nums:
if num not in nums_set:
nums_set.add(num)
else:
return True
else:
return False
|
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 models
"""
if try_to_use_cuda and torch.cuda.is_available():
torch.backends.cudnn.benchmark = True
device = torch.device("cuda:0")
else:
device = torch.device("cpu")
return device
|
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) space.
"""
integers_clone = list(integers)
for i in range(1, len(integers_clone)):
j = i
while integers_clone[j] < integers_clone[j - 1] and j > 0:
integers_clone[j], integers_clone[j-1] = integers_clone[j-1], integers_clone[j]
j -= 1
return integers_clone
|
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():
subtree = tree
parts = key.split('.')
for part in parts[:-1]:
if part not in subtree:
subtree[part] = {}
subtree = subtree[part]
subtree[parts[-1]] = value
return tree
|
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="vcf",
help="Tabix indexed VCF.")
parser.add_argument("-in", "--primer-input-file", dest="p_info",
help="The output of the primer pipeline.")
parser.add_argument("-o", "--output", dest="output",
help="The name of the output file")
return parser
|
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 to get.
Returns
-------
value
The value of the attribute if it is present, or ``None`` if it
isn't.
"""
if name not in target.attrs:
return None
else:
return target.attrs[name]
|
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 . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg gggg ....
5: 6: 7: 8: 9:
aaaa aaaa aaaa aaaa aaaa
b . b . . c b c b c
b . b . . c b c b c
dddd dddd .... dddd dddd
. f e f . f e f . f
. f e f . f e f . f
gggg gggg .... gggg gggg
Each entry consists of ten unique signal patterns, a | delimiter, and finally the four digit output value
Within an entry, the same wire/segment connections are used (but you don't know what the connections actually are)
In the output values, how many times do digits 1, 4, 7, or 8 appear?
"""
count_1478 = 0
for item in data:
for output_value in item[1]:
if len(output_value) in [2, 3, 4, 7]:
count_1478 += 1
return count_1478
|
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) the length of the binary array to be created. (Default value = None)
Returns:
the binary array representation of `number`.
"""
bin_str = "{0:b}".format(number)
bin_str = bin_str.zfill(array_length) if array_length else bin_str
return list(map(int, bin_str))
|
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 distinct values as
ratio
"""
return data_frame[field].value_counts(normalize=True) * 100
# ------------------------------------------------------------ get_ratio()
|
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(infile, 'r+b') as src:
suffix = 0
while True:
with open(prefix + '.%s' % suffix, 'w+b') as tgt:
written = 0
while written < max_size:
data = src.read(file_buffer)
if data:
tgt.write(data)
written += file_buffer
else:
return suffix
suffix += 1
|
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.