content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def dpv(vec1, vec2)->float:
"""Dot product of two vectors"""
product = 0.
for idx, val in enumerate(vec1):
product += val * vec2[idx]
return product
|
985ae996878daa24793fb6f96c170a3e637cf610
| 200,066 |
def is_proxy(obj):
""" Return True if `obj` is an array proxy
"""
try:
return obj.is_proxy
except AttributeError:
return False
|
871c163b30ccc1b31b435c9baac5c0d6063d271e
| 40,308 |
def is_palindrome(n, base=10):
"""
Is the given number n a palindrome in the given base?
"""
if base == 10:
n_str = str(n)
elif base == 2:
n_str = "{0:b}".format(n)
else:
raise RuntimeError("Only 2 and 10 bases supported")
for i in range(len(n_str) // 2):
if n_str[i] != n_str[-1 - i]:
return False
return True
|
7e90c2122888d853850a84229ca3ca65074a8993
| 629,659 |
def extract_best_aligns(aligns_df):
"""Extracts alignments with highest score from the provided alignments
dataframe.
"""
mask = aligns_df.groupby('seq_index').agg({'score': 'idxmax'}) # get /!\ FIRST /!\ index of max align score for each sequence
aligns_df_best = aligns_df.loc[mask['score']].reset_index(drop=True)
return aligns_df_best
|
a7b512631a96c87380a20bea90dd2228ea020396
| 616,769 |
def bitstring_readable(data, batch_size, model_output=None, whole_batch=False):
"""Produce a human readable representation of the sequences in data.
Args:
data: data to be visualised
batch_size: size of batch
model_output: optional model output tensor to visualize alongside data.
whole_batch: whether to visualise the whole batch. Only the first sample
will be visualized if False
Returns:
A string used to visualise the data batch
"""
def _readable(datum):
return '+' + ' '.join(['-' if x == 0 else '%d' % x for x in datum]) + '+'
obs_batch = data.observations
targ_batch = data.target
iterate_over = range(batch_size) if whole_batch else range(1)
batch_strings = []
for batch_index in iterate_over:
obs = obs_batch[batch_index, :, :]
targ = targ_batch[batch_index, :, :]
readable_obs = 'Observations:\n' + '\n'.join([_readable(obs_vector) for obs_vector in obs])
readable_targ = 'Targets:\n' + '\n'.join([_readable(targ_vector) for targ_vector in targ])
strings = [readable_obs, readable_targ]
if model_output is not None:
output = model_output[batch_index, :, :]
strings.append('Model Output:\n' + '\n'.join([_readable(output_vec) for output_vec in output]))
batch_strings.append('\n\n'.join(strings))
return '\n' + '\n\n\n\n'.join(batch_strings)
|
342b6720dd30b1f8d8b984a5d49b09913050fd40
| 688,148 |
def large_dollar_volume_stocks(df, price_column, volume_column, top_percent):
"""
Get the stocks with the largest dollar volume stocks.
Parameters
----------
df : DataFrame
Stock prices with dates and ticker symbols
price_column : str
The column with the price data in `df`
volume_column : str
The column with the volume in `df`
top_percent : float
The top x percent to consider largest in the stock universe
Returns
-------
large_dollar_volume_stocks_symbols : List of str
List of of large dollar volume stock symbols
"""
dollar_traded = df.groupby('ticker').apply(lambda row: sum(row[volume_column] * row[price_column]))
return dollar_traded.sort_values().tail(int(len(dollar_traded) * top_percent)).index.values.tolist()
|
ef2e168dd1738a9c8e759cafd5f6180ffb65bf1c
| 276,938 |
import math
def prob_no_match(n):
"""analytical result using integers - python can handle arb large numbers"""
return math.factorial(n)*math.comb(365,n)/(365**n)
|
fe292657654c4413fd3d9751e6a10be7c38f2c19
| 662,011 |
from typing import Mapping
def _recursive_update(d, u):
"""Recursively update a nested dict with another."""
# https://stackoverflow.com/a/3233356/1595060
for k, v in u.items():
if isinstance(v, Mapping):
d[k] = _recursive_update(d.get(k, {}), v)
else:
d[k] = v
return d
|
0562fa333b2667db02675382c95ce09bcbd23758
| 538,505 |
def test_data_dir(name):
"""
Decorator allowing to customize test data directory for a test.
The specified name will be used only as the last component of the path
following the directory corresponding to the test class (by default
test name itself is used for this purpose).
Example::
@test_data_dir('common_test_data')
def test_scenario():
...
"""
def decorator(f):
f._test_data_dir = name
return f
return decorator
|
bbc437c8b247edae24a5f5c81caa674bcb827fc9
| 173,561 |
def group_by_key(dict_list, key):
"""
>>> data = [
... {'a': 1, 'b': 2},
... {'a': 1, 'b': 3}
... ]
>>> group_by_key(data, 'a')
{1: [{'a': 1, 'b': 2}, {'a': 1, 'b': 3}]}
"""
grouped = {}
for d in dict_list:
group_key = d.get(key)
grouped.setdefault(group_key, [])
grouped[group_key].append(d)
return grouped
|
b1635a225fc2afb45460cca88b8a7d66934dc0c7
| 160,702 |
def buffer_to_offset(buffer):
"""
Convert a byte buffer into an integer offset according to ArcGIS packing
scheme:
(buffer[0] & 0xff) +
(buffer[1] & 0xff) * 2 ** 8 +
(buffer[2] & 0xff) * 2 ** 16 +
(buffer[3] & 0xff) * 2 ** 24 ...
Parameters
----------
buffer: list[bytes]
byte buffer
Returns
-------
int: offset
"""
return sum(((v & 0xFF) * 2 ** (i * 8) for i, v in enumerate(buffer)))
|
537d1aaaaba577f59cb7641982b7f7bf93e0af29
| 427,490 |
def line(display=False):
"""To make easy separations while printing in console"""
if display == True:
return print("____________________________________________________________\n")
|
aa038f45baa15fc2326a0dac44df5f0ca9944abb
| 400,671 |
def group_edge_pairs(edges):
"""
Group pairs of forward and reverse edges between nodes as tuples in a
list together with single directed edges if any
:param edges: list of edges
:type edges: :py:list
:return: paired edges
:rtype: :py:list
"""
pairs = []
done = []
for e in edges:
if e in done:
continue
reverse_e = e[::-1]
if reverse_e in edges:
pairs.append((e, reverse_e))
done.append(reverse_e)
else:
pairs.append(e)
done.append(e)
return pairs
|
5f1313138dbe575081a7cf9a75aea0682e835e98
| 304,641 |
def calculate_xy_coords(image_size, screen_size):
"""Calculates x and y coordinates used to display image centered on screen.
Args:
image_size as tuple (int width in pixels, int height in pixels).
screen_size as tuple (int width in pixels, int height in pixels).
Returns:
tuple (int x coordinate, int y coordinate).
"""
image_width, image_height = image_size
screen_width, screen_height = screen_size
x = (screen_width - image_width) / 2
y = (screen_height - image_height) / 2
return (x, y)
|
08980f1ee015d9f8bae44d4371c9a7a7ba2fd09e
| 561,515 |
def args_env(args):
"""
Create a dictionary of enumerated arguments.
"""
return {str(i): str(v) for i, v in enumerate(args)}
|
730dfa5fd2af90dac7c529a2f1529f36ea435e2a
| 204,952 |
def can_merge(a, b):
"""
Test if two cubes may be merged into a single cube (their bounding box)
:param a: cube a, tuple of tuple ((min coords), (max coords))
:param b: cube b, tuple of tuple ((min coords), (max coords))
:return: bool, if cubes can be merged
"""
c = 0 # Count the number of continued dimensions
for i, j, k, l in zip(a[0], a[1], b[0], b[1]):
x = i == k and j == l # If this dimension matches exactly
y = i == l or j == k # If one cube continues the other
z = y and (c == 0) # If we are the first dimension to be continued
if not x and not z:
return False
if y: # Increment the continued dimension count
c += 1
return True
|
88a7e5a1d3145548f12396e66aae12cba0ee938f
| 503,639 |
from typing import List
def get_function_contents_by_name(lines: List[str], name: str):
"""
Extracts a function from `lines` of segmented source code with the name `name`.
Args:
lines (`List[str]`):
Source code of a script seperated by line.
name (`str`):
The name of the function to extract. Should be either `training_function` or `main`
"""
if name != "training_function" and name != "main":
raise ValueError(f"Incorrect function name passed: {name}, choose either 'main' or 'training_function'")
good_lines, found_start = [], False
for line in lines:
if not found_start and f"def {name}" in line:
found_start = True
good_lines.append(line)
continue
if found_start:
if name == "training_function" and "def main" in line:
return good_lines
if name == "main" and "if __name__" in line:
return good_lines
good_lines.append(line)
|
60239b0063e83a71641d85194f72a9cc61221177
| 705,031 |
from functools import reduce
from operator import add
def determine_breadth(iterable):
"""
Determines the breadth of the addable contents of the iterable
"""
return reduce(add, iterable)
|
117a5b242ebe1df069e16e598dd489c7abd9b26c
| 499,595 |
def get_announcement(message, reminder_offset):
"""
Generates the announcement message
:param str message: Message about the event
:param number reminder_offset: Minutes in which event is about to happen
"""
pos = message.find(":")
if pos == -1:
activity = message.strip()
message = f"{activity} in {reminder_offset} minutes."
else:
activity = message[pos + 1 :].strip()
person = message[0:pos].strip()
message = f"Hello {person}, you have {activity} in {reminder_offset} minutes."
return message
|
18d9921c815bcb0783ccf7d3fc010989c68aeaa2
| 471,531 |
def get_concordance(text,
keyword,
idx,
window):
"""
For a given keyword (and its position in an article), return
the concordance of words (before and after) using a window.
:param text: text
:type text: string
:param keyword: keyword
:type keyword: str or unicode
:param idx: keyword index (position) in list of article's words
:type idx: int
:window: number of words to the right and left
:type: int
:return: concordance
:rtype: list(str or unicode)
"""
text_list= text.split()
text_size = len(text_list)
if idx >= window:
start_idx = idx - window
else:
start_idx = 0
if idx + window >= text_size:
end_idx = text_size
else:
end_idx = idx + window + 1
concordance_words = []
for word in text_list[start_idx:end_idx]:
concordance_words.append(word)
return concordance_words
|
508a989a8d59c4877fe40291bd24be406374962a
| 667,478 |
import json
def retrieve(corpus_path, labels_path="", edges_path=""):
"""
Retrieve corpus and labels of a custom dataset
given their path
Parameters
----------
corpus_path : path of the corpus
labels_path : path of the labels document
Returns
-------
result : dictionary with corpus and
optionally labels of the corpus
"""
result = {}
corpus = []
labels = []
with open(corpus_path) as file_input:
for line in file_input:
corpus.append(str(line))
result["corpus"] = corpus
if len(labels_path) > 1:
with open(labels_path) as file_input:
for label in file_input:
labels.append(json.loads(label))
result["doc_labels"] = labels
if len(edges_path) > 1:
doc_ids = {}
tmp_edges = []
with open(edges_path) as file_input:
for line in file_input:
neighbours = str(line)
neighbours = neighbours[2:len(neighbours)-3]
doc_ids[neighbours.split()[0]] = True
tmp_edges.append(neighbours)
edges_list = []
for edges in tmp_edges:
tmp_element = ""
for edge in edges.split():
if edge in doc_ids:
tmp_element = tmp_element + edge + " "
edges_list.append(tmp_element[0:len(tmp_element)-1])
result["edges"] = edges_list
return result
|
f27acec7d3f80359bf3ea63f7fcf7d8eca0bf152
| 596,430 |
def removesuffix(s: str, suffix:str) -> str:
"""Removes the suffix from s."""
if s.endswith(suffix):
return s[:-len(suffix)]
return s
|
538ca2ef7021b01f09a7c9db56069639a9389d95
| 52,390 |
def remove_prepended_comment(orig_df):
"""
remove the '#' prepend to the first column name
Note: if there is no comment, this won't do anything (idempotency).
"""
input_df = orig_df.copy()
first_col = input_df.columns[0]
return input_df.rename(columns={first_col: first_col.replace('#', "")})
|
c4f11b50644070e0f26464a97feef11b4c1e6dbb
| 119,685 |
def get_ordinal_string(n):
"""
Return the ordinal representation of a positive integer (e.g. 1 -> "1st")
Code by CTT @ http://stackoverflow.com/a/739301
"""
if 10 <= n % 100 < 20:
return str(n) + 'th'
else:
return str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th")
|
c451b2fdbe6b050c63d64c0ae8cef061793df332
| 489,847 |
def _is_file_external(f):
"""Returns True if the given file is an external file."""
return f.owner.workspace_root != ""
|
ea3b3854d85da2c6275f1f66cdb06f5cc8d88bef
| 201,523 |
def nombre_joueurs_annee(annee,liste):
"""
Fonction qui en paramètre prend une année (int)
et la liste des joueurs sous forme de liste de dictionnaires
et qui retourne le nombre de joueurs ayant joués l'année donnée
"""
compteur = 0
for enreg in liste :
if int(enreg['Année']) == annee:
compteur += 1
return compteur
|
75ae36a2cac32bd6b02a4a3ade1cfab82af8f575
| 48,220 |
def AuthorToJSON(author):
"""
Converts an Author object into a JSON-compatible dictionary.
Returns None on failure.
"""
if not author:
return None
try:
json_dict = {
"type":"author",
"id":author.url,
"host":author.host,
"displayName":author.username,
"url":author.url,
"github":author.github
}
return json_dict
except:
return None
|
2cf4c6f764aaf6f38bfcc99d8a19f907dce3dae1
| 293,750 |
import requests
def basic_auth_request(method, url, token=None, payload=None, params=None):
"""
make a request using basic authorization
:param method: [GET, POST, PUT, DELETE ...]
:param url:
:param token: basic authentication token
:param payload: post body
:param params: Dictionary or bytes to be sent in the query string
:return:
"""
request_kwargs = {}
if token is not None:
request_kwargs["headers"] = {"Authorization": "Basic {0}".format(token)}
if payload is not None:
request_kwargs["json"] = payload
if params is not None:
request_kwargs["params"] = params
return requests.request(method, url, **request_kwargs)
|
610e951151c224a5bdf7b4fe74e759e5f713bce0
| 194,561 |
def probability_in_subspace(wavefunc: dict, subspace: list) -> float:
"""
Calculates the probability that the wavefunction 'wavefunc' lies in 'subspace'
Note: This only works for subspaces aligned with the comp. basis.
:param wavefunc: dict, contains complex amplitudes of the wavefunction
in computational basis states
:param subspace: list, list containing the computational basis vectors which
span the subspace
:return: float
"""
assert isinstance(wavefunc, dict), 'Please provide your state as a dict.'
assert isinstance(subspace, list), 'Please provide subspace as a list of str.'
# Deal with empty subspace:
if not subspace:
return 0
assert isinstance(subspace[0], str), 'Please provide subspace as a list of str.'
assert len(wavefunc) >= len(subspace)
subspace_prob = 0.
# add up probabilities for all basisvectors in the subspace
for basisvector in subspace:
basisvector_prob = abs(wavefunc[basisvector]) ** 2
subspace_prob += basisvector_prob
return subspace_prob
|
1762c6ce3f3569557fcacecbdb806ebb3655afc8
| 232,612 |
def is_sublist(l1, l2, pos=False):
"""
Check if l1 is a sublist of l2 (it contains all elements from l1 in the same order).
if pos is True, return position where sublist starts, not a boolean value
"""
if l1 == []:
return 0 if pos else True
elif l1 == l2:
return 0 if pos else True
elif len(l1) > len(l2):
return -1 if pos else False
for i in range(len(l2)):
if l2[i] == l1[0]:
n = 1
while (n < len(l1)) and (i + n < len(l2)) and (l2[i + n] == l1[n]):
n += 1
if n == len(l1):
return i if pos else True
return -1 if pos else False
|
8be3d2253d6381e61ee58369bdf0c939e11d017d
| 614,920 |
import typing
def asBool(key: str, value: typing.Union[str, bool, int]) -> bool:
"""
Coerce a key to boolean
Parameters
----------
key : str
Name of this setting. Used in error reporting
value : string or bool or int
Trivial for booleans. If integer, return the corresponding
value **only** for values of ``1`` and ``0``. If a string,
values of ``{"1", "yes", "y", "true"}`` denote True, values
of ``{"0", "no", "n", "false"}`` denote False. Strings are
case-insensitive
Raises
------
TypeError
If the conversion fails
"""
if isinstance(value, bool):
return value
elif isinstance(value, int):
if value == 0:
return False
if value == 1:
return True
raise ValueError(
f"Could not coerce {key}={value} to boolean. Integers "
"must be zero or one"
)
elif isinstance(value, str):
if value.lower() in {"1", "yes", "y", "true"}:
return True
if value.lower() in {"0", "no", "n", "false"}:
return False
raise ValueError(
f"Could not coerce {key}={value} to boolean. Strings must be "
"0 1 y n yes no true false"
)
raise TypeError(f"Could not coerce {key}={value} to boolean")
|
8df4a0479145e3128398e1b61206c81070bd5969
| 131,501 |
def _NormalizePath(path):
"""Returns the normalized path of the given one.
Normalization include:
* Convert '\\' to '/'
* Convert '\\\\' to '/'
* Resolve '../' and './'
Example:
'..\\a/../b/./c/test.cc' --> 'b/c/test.cc'
"""
path = path.replace('\\', '/')
path = path.replace('//', '/')
filtered_parts = []
for part in path.split('/'):
if part == '..':
if filtered_parts:
filtered_parts.pop()
elif part == '.':
continue
else:
filtered_parts.append(part)
return '/'.join(filtered_parts)
|
ed6cd73f1c59eeef4d55121a99bb29c2e569a6da
| 82,049 |
def _softmax_output_grad(ans, x, y):
"""Gradient function for softmax output."""
def grad(_0): #pylint: disable= missing-docstring
N = x.shape[0]
return (ans - y) / N
return grad
|
324d12cae270d5274a5d23c560f953a3d37baaa0
| 535,994 |
def gst_value_from_inclusive(amount, gst_rate):
"""Calculate GST component from a GST inclusive total.
GST amount calculated as amount - (1 + gst_rate)).
Args:
amount (float): GST inclusive amount
gst_rate (float): GST rate to apply.
Returns:
gst_component (float): Calculated GST component.
"""
return amount - (amount / (1 + gst_rate))
|
5d7ba72bfe97598da3b360cf2e263aef59214af2
| 612,899 |
import pytz
def compare_dates(date_a, date_b):
"""
Compares two dates with offset-aware format.
Args:
date_a: The first date to compare
date_b: The second date to compare
Returns:
- if the date_b is greater than date_a = =1
- if the date_a is greater than date_b = 1
- otherwise = 0
"""
try:
date_a_offset_aware = pytz.UTC.localize(date_a)
except ValueError:
date_a_offset_aware = date_a
try:
date_b_offset_aware = pytz.UTC.localize(date_b)
except ValueError:
date_b_offset_aware = date_b
if date_a_offset_aware > date_b_offset_aware:
return 1
elif date_b_offset_aware > date_a_offset_aware:
return -1
else:
return 0
|
9cede76385991eb06eb43c5ec664574be521ab65
| 189,390 |
def read_msr_line(line, tstat_switch, msr_id_switch):
"""
Function to read msr components from a single line in adj file
:param line: Msr line in adj file
:param tstat_switch: True/False switch for presence of tstats
:param msr_id_switch: True/False switch for presence of msr_ids
:return: Dictionary of components
"""
msr_type = line[:1]
stn1 = line[2:22].strip()
stn2 = line[22:42].strip()
if stn2 == '':
stn2 = None
stn3 = line[42:62].strip()
if stn3 == '':
stn3 = None
if msr_type == 'D':
if msr_id_switch:
items = line.split()
cluster_id = items[-1].strip()
msr_id = items[-2]
else:
msr_id = None
cluster_id = None
msr_components = {
'msr_type': msr_type,
'stn1': stn1,
'stn2': stn2,
'stn3': stn3,
'msr_id': msr_id,
'cluster_id': cluster_id
}
return msr_components
else:
if line[62:65].strip() == '*':
ignore = True
else:
ignore = False
cardinal = line[65:67].strip()
msr = line[67:86].strip()
adj = line[86:105].strip()
cor = line[105:117].strip()
msr_sd = line[117:130].strip()
adj_sd = line[130:143].strip()
cor_sd = line[143:156].strip()
nstat = line[156:167].strip()
if tstat_switch:
tstat = line[167:178].strip()
pelzer = line[178:190].strip()
pre_adj_cor = line[190:204].strip()
outlier = line[204:216]
if msr_id_switch:
msr_id = line[216:226].strip()
cluster_id = line[226:236].strip()
else:
msr_id = None
cluster_id = None
else:
tstat = None
pelzer = line[167:178].strip()
pre_adj_cor = line[180:193].strip()
outlier = line[204:205]
if msr_id_switch:
msr_id = line[205:216].strip()
cluster_id = line[216:226].strip()
else:
msr_id = None
cluster_id = None
msr_components = {
'msr_type': msr_type,
'stn1': stn1,
'stn2': stn2,
'stn3': stn3,
'ignore': ignore,
'cardinal': cardinal,
'msr': msr,
'adj': adj,
'cor': cor,
'msr_sd': msr_sd,
'adj_sd': adj_sd,
'cor_sd': cor_sd,
'nstat': nstat,
'tstat': tstat,
'pelzer': pelzer,
'pre_adj_cor': pre_adj_cor,
'outlier': outlier,
'msr_id': msr_id,
'cluster_id': cluster_id
}
return msr_components
|
40e5f1b76fa525c6b6b47f878bd54839a4bf05b0
| 449,180 |
def PrintSourceMatrix(S,params):
"""Auxiliary function to print the source matrix (S)"""
dim = params["dim"] # Spatial dimensions
print("The source term matrix is:\n")
for i in range (0,dim+2):
for j in range (0,dim+2):
print("S[",i,",",j,"]=",S[i,j],"\n")
return 0
|
be00de08d18f00ee421962290d91999cff9fb545
| 122,157 |
def get_special_tokens(vocab_size):
"""Gets the ids of the four special tokens.
The four special tokens are:
pad: padding token
oov: out of vocabulary
bos: begin of sentence
eos: end of sentence
Args:
vocab_size: The vocabulary size.
Returns:
The four-tuple (pad, oov, bos, eos).
"""
pad = 0
oov = vocab_size + 1
bos = vocab_size + 2
eos = vocab_size + 3
return pad, oov, bos, eos
|
5e1b058f91c55e2da58d1bec1538739e0d593352
| 147,238 |
def calculate_tcp_checksum(message):
""" Calculate the TCP checksum
@param message: payload + TCP headers + pseudoheader
@return: 16-bit TCP checksum value
"""
cs = 0
for i in range(0, len(message), 2):
w = (ord(message[i])<<8 + ord(message[i+1]))
cs = cs + w
cs = (cs>>16) + (cs & 0xffff)
cs = ~cs & 0xffff
return cs
|
29012bad836e671e38cd6e7bb781ebae3fe09a54
| 453,006 |
import time
def ControlRate(t_last_call, max_rate):
"""
Limits rate at which this function is called by sleeping.
Returns the time of invocation.
"""
p = 1.0 / max_rate
t_current = time.time()
dt = t_current - t_last_call
if dt < p:
time.sleep(p - dt)
return t_current
|
67d79eb4cdba4825ba1936ad86917a548002890f
| 338,697 |
import itertools
def GetLatencyEvents(process, timeline_range):
"""Get LatencyInfo trace events from the process's trace buffer that are
within the timeline_range.
Input events dump their LatencyInfo into trace buffer as async trace event
of name starting with "InputLatency". Non-input events with name starting
with "Latency". The trace event has a member 'data' containing its latency
history.
"""
latency_events = []
if not process:
return latency_events
for event in itertools.chain(
process.IterAllAsyncSlicesStartsWithName('InputLatency'),
process.IterAllAsyncSlicesStartsWithName('Latency')):
if event.start >= timeline_range.min and event.end <= timeline_range.max:
for ss in event.sub_slices:
if 'data' in ss.args:
latency_events.append(ss)
return latency_events
|
17e932bdd04c1efc069b84606fb104e340f7f9a2
| 577,021 |
def splitlines(text):
"""Split text into lines."""
return text.splitlines()
|
bc599e88ce14feeddb51dc6c4a48a459c01160e3
| 282,782 |
from typing import List
def format_row(columns: List[str], widths: List[int]) -> str:
"""Format one row of the table. This may go into multiple lines if
any of the columns were wrapped."""
row = ""
had_values = True
lineno = 0
while had_values:
had_values = False
line = ""
for (i, c) in enumerate(columns):
collines = c.split("\n")
if len(collines) > lineno:
had_values = True
line += "| " + collines[lineno] + " "
else:
line += "|" + " " * (2 + widths[i])
if had_values:
row += line + "|\n"
lineno += 1
return row[0:-1]
|
c01bd30b6a73f8ea83f936d139c003db952fe58b
| 496,560 |
import ast
def _combine_side_inputs(side_input_shapes='',
side_input_types='',
side_input_names=''):
"""Zips the side inputs together.
Args:
side_input_shapes: forward-slash-separated list of comma-separated lists
describing input shapes.
side_input_types: comma-separated list of the types of the inputs.
side_input_names: comma-separated list of the names of the inputs.
Returns:
a zipped list of side input tuples.
"""
side_input_shapes = [
ast.literal_eval('[' + x + ']') for x in side_input_shapes.split('/')
]
side_input_types = eval('[' + side_input_types + ']') # pylint: disable=eval-used
side_input_names = side_input_names.split(',')
return zip(side_input_shapes, side_input_types, side_input_names)
|
e67e634ad0a2d48ecaa621bb663d50e91964a426
| 393,755 |
def dict_sample_list(a_dict, n_sample = 4):
"""Sample dictionary data using even spacing - returns a list for printing"""
data_len = len(a_dict)
header = ['Printing {} entries evenly sampled from {} combinations:\n'.format(n_sample, data_len)]
return header + ['** {} ** \n{}'.format(k,repr(a_dict[k])) for k in list(a_dict.keys())[1:-1:data_len // n_sample]]
|
a76bf2bc18bb9356bf38ccef566a38e87757fa28
| 128,877 |
def _bbox(pts):
"""Find the AABB bounding box for a set of points"""
x, y = pts[0]
ax, ay, bx, by = x, y, x, y
for i in range(1, len(pts)):
x, y = pts[i]
ax = x if x < ax else ax
ay = y if y < ay else ay
bx = x if x > bx else bx
by = y if y > by else by
return ax, ay, bx, by
|
95802ea790153020fcd6c20193536e1b19ca6102
| 657,737 |
def get_x(path, width):
"""Gets the x value from the image filename"""
return (float(int(path.split("_")[1])) - width/2) / (width/2)
|
c387ce4415b75677f2c7b4a1bc27b12cba469d22
| 630,738 |
def hasCycle(head):
"""
Use two pointers(one slow, one fast) to traverse the list.
Two pointers are bound to meet if there is a cycle;
otherwise, fast pointer will reach the end eventually.
"""
slow = head
fast = head
while fast and fast.next: # note the condition
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
|
ab518c35d44bf86d75e6a1cc1f631b8acadc9795
| 594,578 |
import string
import random
def generate_identifier(size = 16, chars = string.ascii_uppercase + string.digits):
"""
Generates a random identifier (may be used as password) with
the provided constrains of length and character ranges.
This function may be used in the generation of random based
keys for both passwords and api keys.
@type size: int
@param size: The size (in number of characters) to be used in
the generation of the random identifier.
@type chars: List
@param chars: The list containing the characters to be used
in the generation of the random identifier.
@rtype: String
@return: The randomly generated identifier obeying to the
provided constrains.
"""
return "".join(random.choice(chars) for _index in range(size))
|
fc749c1ac2294c365c17a54ff3d096d466fb48d6
| 619,492 |
import re
def tokenize(text):
"""Tokenize the text (i.e., insert spaces around all tokens)"""
toks = re.sub(r'([?.!;,:-]+)(?![0-9])', r' \1 ', text) # enforce space around all punct
# most common contractions
toks = re.sub(r'([\'’´])(s|m|d|ll|re|ve)\s', r' \1\2 ', toks) # I'm, I've etc.
toks = re.sub(r'(n[\'’´]t\s)', r' \1 ', toks) # do n't
# other contractions, as implemented in Treex
toks = re.sub(r' ([Cc])annot\s', r' \1an not ', toks)
toks = re.sub(r' ([Dd])\'ye\s', r' \1\' ye ', toks)
toks = re.sub(r' ([Gg])imme\s', r' \1im me ', toks)
toks = re.sub(r' ([Gg])onna\s', r' \1on na ', toks)
toks = re.sub(r' ([Gg])otta\s', r' \1ot ta ', toks)
toks = re.sub(r' ([Ll])emme\s', r' \1em me ', toks)
toks = re.sub(r' ([Mm])ore\'n\s', r' \1ore \'n ', toks)
toks = re.sub(r' \'([Tt])is\s', r' \'\1 is ', toks)
toks = re.sub(r' \'([Tt])was\s', r' \'\1 was ', toks)
toks = re.sub(r' ([Ww])anna\s', r' \1an na ', toks)
# clean extra space
toks = re.sub(r'\s+', ' ', toks)
return toks
|
14269361eaaf55346bf08469896db408665d703a
| 492,582 |
def truncate(s, amount) -> str:
"""Return a string that is no longer than the amount specified."""
if len(s) > amount:
return s[:amount - 3] + "..."
return s
|
0cac2bf590a7d57197d80847ae551f8f8a9e7906
| 302,692 |
def parse_strling_info_for_locus(strling_genotype_df, locus_chrom, locus_start, locus_end, margin=700):
"""Extract info related to a specific locus from the STRling genotype table.
See https://strling.readthedocs.io/en/latest/outputs.html for more details.
Args:
strling_genotype_df (pd.DataFrame): parsed STRling genotype table
locus_chrom (str): locus chromosome
locus_start (int): locus start coord
locus_end (int): locus end coord
margin (int): when looking for matching STRling results, include calls this many base pairs away from the locus.
This should be approximately the fragment-length or slightly larger (700 is a reasonable value for
Illumina short read data).
"""
locus_chrom = locus_chrom.replace("chr", "")
strling_results_for_locus = strling_genotype_df[
(strling_genotype_df.chrom.str.replace("chr", "") == locus_chrom)
& (strling_genotype_df.start_1based < locus_end + margin)
& (strling_genotype_df.end_1based > locus_start - margin)
]
"""
Example row:
{'allele1_est': 0.0,
'allele2_est': 22.09,
'anchored_reads': 8,
'chrom': 'chr4',
'depth': 32.0,
'expected_spanning_pairs': 57.83,
'left': 39348477,
'left_clips': 5,
'repeatunit': 'AAGGG',
'right': 39348477,
'right_clips': 0,
'spanning_pairs': 0,
'spanning_pairs_pctl': 0.0,
'spanning_reads': 0,
'sum_str_counts': 265,
'unplaced_pairs': 0}
"""
return [row.to_dict() for _, row in strling_results_for_locus.iterrows()]
|
09313a37946679ffba97cc044601a59bfdcab120
| 385,096 |
import random
def random_choice(sequence):
"""Return a random element from the non-empty sequence."""
return random.SystemRandom().choice(sequence)
|
942e9e2a7967a02863c76c84b2a2b6228fad35b0
| 614,016 |
def __slice_scov__(cov, dep, given):
"""
Slices a covariance matrix keeping only the covariances between the variables
indicated by the array of indices of the independent variables.
:param cov: Covariance matrix.
:param dep: Index of dependent variable.
:param given: Array of indices of independent variables.
:return: A |given| x |given| matrix of covariance.
"""
row_selector = [x for x in range(cov.shape[0]) if x in given and x != dep]
col_selector = [x for x in range(cov.shape[1]) if x in given and x != dep]
v = cov[row_selector, :]
v = v[:, col_selector]
return v
|
a5742c8dc4db245521477b0bf8c6ad8f3b463a2b
| 696,286 |
def drawBorder(grid: list) -> list:
"""Draw a border around the maze"""
for i, x in enumerate(grid): # Left and Right border
x[0] = x[len(grid)-1] = (20,20,20)
grid[i] = x
grid[0] = grid[len(grid)-1] = [(20,20,20) for x in range(len(grid))] # Top and Bottom border
return grid
|
6aef946dc201c0c16df4daedc6a93512844cfcc5
| 547,638 |
def iterkeys(obj, **kwargs):
"""Iterate over dict keys in Python 2 & 3."""
return (obj.iterkeys(**kwargs)
if hasattr(obj, 'iterkeys')
else iter(obj.keys(**kwargs)))
|
03787c0e8bb493c721871990c4068144782370e2
| 697,552 |
def join_string_lists(**kwargs) -> dict:
"""Convert named lists of strings to one dict with comma-separated strings.
:param kwargs: Lists of strings
:return: Converted dict.
Example:
>>> join_string_lists(foo=["a", "b", "c"], bar=["a", "b"], foobar=None)
{"foo": "a,b,c", "bar": "a,b"}
"""
return {k: ",".join(v) for k, v in kwargs.items() if v}
|
c5c93c0335ccedf37edf0d202a1fed4f5b7d0243
| 588,936 |
def num2char(numpair, key):
"""Takes in a numpair like '34', and returns the character in row 3 (actually 4th row)
and column 4 (actually 5th column) of the key"""
row_num = int(numpair[0])
column_num = int(numpair[1])
return(key[row_num][column_num])
|
a86cf1ef327d2f1fbedf8b661e812c4d486fb3ac
| 33,521 |
def closest_number(val, num_list):
"""
Return closest element to val in num_list.
Parameters
----------
val: integer, float,
value to find closest element from num_list.
num_list: list,
list from which to find the closest element.
Returns
-------
A element of num_list.
"""
return min(num_list, key=lambda x: abs(x-val))
|
cf58cafbed0c2a0b773c287157581620bb915b68
| 389,003 |
def nid(x):
"""Return the address of an array data, used to check whether two arrays
refer to the same data in memory."""
return x.__array_interface__['data'][0]
|
5a3e3760b492e418f96ceacdd31eb9a35c124ef4
| 287,902 |
def build_file_list(path):
"""
Build a list a list of files (and directories) by iterating recursively
over the given path
:param path: The path to iterate over
:type path: pathlib.Path
:return: A tuple of directories and files
:rtype: tuple(list, list)
"""
dirs = []
files = []
for x in path.iterdir():
try:
if x.is_symlink():
continue
elif x.is_dir():
dirs.append(x)
new_dirs, new_files = build_file_list(x)
dirs.extend(new_dirs)
files.extend(new_files)
elif x.is_file():
files.append(x)
except PermissionError:
continue
return dirs, files
|
1558bf9fda13ded5a478d477116ad031e8aea434
| 308,447 |
def get_timeout(run_type):
"""Get timeout for a each run type - daily, hourly etc
:param run_type: Run type
:type run_type: str
:return: Number of seconds the tool allowed to wait until other instances
finish
:rtype: int
"""
timeouts = {
'hourly': 3600 / 2,
'daily': 24 * 3600 / 2,
'weekly': 7 * 24 * 3600 / 2,
'monthly': 30 * 24 * 3600 / 2,
'yearly': 365 * 24 * 3600 / 2
}
return timeouts[run_type]
|
40c07cb61bb3fa4c43538c0bf265990fe763a929
| 634,294 |
def default_key(rarity: float) -> float:
"""The default function that converts rarity to drop rate (1/x)
Parameters
----------
rarity : float
the rarity of the item
Returns
-------
float
the drop rate of the item
"""
return 1 / rarity
|
806e624efe27bd80aef4ef1077842bcbb984634f
| 340,903 |
import pkg_resources
import yaml
def get_metadata(package_name):
"""
Return runner related metadata for the provided runner package name.
:rtype: ``list`` of ``dict``
"""
file_path = pkg_resources.resource_filename(package_name, 'runner.yaml')
with open(file_path, 'r') as fp:
content = fp.read()
metadata = yaml.safe_load(content)
return metadata
|
0ae30c8cfe35eec3dd96f551a99963cc403c211f
| 299,034 |
import json
def jsonifyer(someDict):
"""Provides standardization of pretty json
Args:
someDict (dict): Any JSON compatible dictionary
Returns:
JSON string
"""
return json.dumps(someDict, sort_keys=True, indent=4, separators=(',', ': '))
|
c274e742875dc333f1da3e8b0b3cd5f0aff7a6e9
| 146,495 |
def not_equal(x, y):
"""Element-wise `(x != y)`."""
return x != y
|
4905b947a768f773088de670e810ad626c147726
| 363,733 |
def _build_technical_detail(
target: str, header: str, method: str, uri: str, param: str, attack: str, evidence: str) -> str:
"""Build the technical detail markdown content."""
return f"""{header}
* Target: {target}
```http
{method} {uri}
{param}
{attack}
{evidence}
```
"""
|
2d20ad7f67f0c1e93d6933b905ca9096deb4b168
| 512,462 |
def getallis(l,match):
"""
get all indices of match pattern in list
"""
return [i for i, x in enumerate(l) if x == match]
|
6d4496a9356d2ef839066fc5a5c40896af86b809
| 351,672 |
def move_bounding_rect(rect, delta_x, delta_y):
""" Move bounding rect x,y by some delta_x, delta_y . """
x, y, w, h = rect
return (x+delta_x, y+delta_y, w, h)
|
1610d738c35d9d5ffd580a901fcef8a143c85106
| 370,016 |
def hits_to_dict(hits_df):
"""
Given a hits_df, return a dict of sample id -> list of hits
"""
sample_to_clones = {}
for sample, sub_hits_df in hits_df.groupby("sample_id"):
sample_to_clones[sample] = sub_hits_df[
["clone1", "clone2"]
].stack().unique()
return sample_to_clones
|
427cee30e7f477dab7d84363177046c6b9800329
| 279,910 |
def count(lbls, wntarget):
"""
Count the number of line transitions with wavenumber smaller than wntarget.
Parameters
----------
lbls: List of lbl objects
wntarget: Float
The target wavenumber.
Returns
-------
nwave: Integer
The number of transitions with wavenumber smaller than wntarget.
"""
nwave = 0
for lbl in lbls:
nwave += lbl.bs(wntarget, 0, lbl.nlines-1)
return nwave
|
3d44e19bb8f79593a4f0525cb0ab11c0984b8f88
| 545,570 |
import random
def init_centroids(data:list, k):
"""
Can be intialiazed in several ways. One of them is picking K random samples from the data
:param data:
:return:
"""
return random.sample(data, k)
|
31ca7a01b4a79c6d0d73a2899fa55f45610d3d7d
| 442,082 |
def doc_to_text(doc, sent_delim='\n'):
"""
Convert document object to original text represention.
Assumes parser offsets map to original document offsets
:param doc:
:param sent_delim:
:return:
"""
text = []
for sent in doc.sentences:
offsets = map(int, sent.stable_id.split(":")[-2:])
char_start, char_end = offsets
text.append({"text": sent.text, "char_start": char_start, "char_end": char_end})
s = ""
for i in range(len(text) - 1):
gap = text[i + 1]['char_start'] - text[i]['char_end']
s += text[i]['text'] + (sent_delim * gap)
return s
|
afdee8854392fa1133db38673118fdbac87314eb
| 578,937 |
def middle_truncate(value, size):
"""
Truncates a string to the given size placing the ellipsis in the middle.
"""
size = int(size)
if len(value) > size:
if size > 3:
start = (size - 3) / 2
end = (size - 3) - start
return value[:start] + u'\u2026' + value[-end:]
else:
return value[:size] + u'\u2026'
else:
return value
|
afe7183f4673750b3cce70472b7a3713119ecc7d
| 482,322 |
def get_doc_str(fun):
"""Get the doc string for a function and return a default if none is found."""
if fun.__doc__:
return '\n'.join([line.strip() for line in fun.__doc__.split('\n')])
else:
return 'No documentation provided for %s()' % fun.__name__
|
ab7653a8975fc632c6682e74b9bf67e21b7ffdd1
| 80,182 |
def is_feature_extractor_model(model_config):
"""
If the model is a feature extractor model:
- evaluation model is on
- trunk is frozen
- number of features specified for features extraction > 0
"""
return (
model_config.FEATURE_EVAL_SETTINGS.EVAL_MODE_ON
and (
model_config.FEATURE_EVAL_SETTINGS.FREEZE_TRUNK_ONLY
or model_config.FEATURE_EVAL_SETTINGS.FREEZE_TRUNK_AND_HEAD
)
and len(model_config.FEATURE_EVAL_SETTINGS.LINEAR_EVAL_FEAT_POOL_OPS_MAP) > 0
)
|
53c9b398efb09099bbe8257f875720a2ec41a495
| 43,515 |
import ntpath
import posixpath
def to_posix(path):
"""
Return a path using the posix path separator given a path that may contain
posix or windows separators, converting "\\" to "/". NB: this path will
still be valid in the windows explorer (except for a UNC or share name). It
will be a valid path everywhere in Python. It will not be valid for windows
command line operations.
"""
return path.replace(ntpath.sep, posixpath.sep)
|
6e11d24beda6316168462220a771ce90369e8eb0
| 680,090 |
def append_form_control(value):
"""A filter for adding bootstrap classes to form fields."""
return value.replace(
'<input', '<input class="form-control"'
).replace(
'<textarea', '<textarea class="form-control"'
).replace(
'<select', '<select class="form-control"'
)
|
57de329073f6389b8ee6c28ae3f2af7e8d298ffd
| 206,608 |
def prefixed(strlist, prefix):
"""
Filter a list to values starting with the prefix string
:param strlist: a list of strings
:param prefix: str
:return: a subset of the original list to values only beginning with the prefix string
"""
return [g for g in strlist if str(g).startswith(prefix)]
|
b5603ed8cd6efb5bc7fc99dbc90471c17bccc4b4
| 177,944 |
def zone_origin(zone_object):
""" Return coordinates of a zone
Args:
zone_object (EpBunch): zone element in zone list
Returns: Coordinates [X, Y, Z] of the zone in a list
"""
return [zone_object.X_Origin, zone_object.Y_Origin, zone_object.Z_Origin]
|
a539761f757feb65dd653456bec2f357b2a57945
| 457,466 |
def to_string(obj, last_comma=False):
"""Convert to string in one line.
Args:
obj(list, tuple or dict): a list, tuple or dict to convert.
last_comma(bool): add a comma at last.
Returns:
(str) string.
Example:
>>> to_string([1, 2, 3, 4], last_comma=True)
>>> # 1, 2, 3, 4,
>>> to_string({'a': 2,'b': 4})
>>> # a=2, b=4
"""
s = ''
if type(obj) == list or type(obj) == tuple:
for i, data in enumerate(obj):
s += str(data)
if last_comma or i != len(obj)-1:
s += ', '
elif type(obj) == dict:
for i, data in enumerate(obj.items()):
k, v = data
s += '%s=%s' % (str(k), str(v))
if last_comma or i != len(obj)-1:
s += ', '
else:
s = str(obj)
return s
|
1f22e31a84ec33749e43fd4fadabe268c4c322b6
| 433,021 |
def find_inner(obj, find_key):
"""
Recursively search through the data structure to find objects
keyed by find_key.
"""
results = []
if not hasattr(obj, "__iter__"):
# not a sequence type - return nothing
# this excludes strings
return results
if isinstance(obj, dict):
# a dict - check each key
for key, prop in obj.items():
if key == find_key:
results.extend(prop)
elif isinstance(prop, dict):
results.extend(find_inner(prop, find_key))
elif isinstance(obj, list):
# a list / tuple - check each item
for i in obj:
results.extend(find_inner(i, find_key))
return results
|
e0448d873f6f5e1c33a22db882dc352bb97e4fa0
| 470,249 |
def split_lindblad_paramtype(typ):
"""
Splits a Lindblad-gate parameteriation type into
a base-type (e.g. "H+S") and an evolution-type
string.
Parameters
----------
typ : str
The parameterization type, e.g. "H+S terms".
Returns
-------
base_type : str
The "base-parameterization" part of `typ`.
evotype : str
The evolution type corresponding to `typ`.
"""
bTyp = typ.split()[0] # "base" type
evostr = " ".join(typ.split()[1:])
if evostr == "": evotype = "densitymx"
elif evostr == "terms": evotype = "svterm"
elif evostr == "clifford terms": evotype = "cterm"
else: raise ValueError("Unrecognized evotype in `typ`=%s" % typ)
return bTyp, evotype
|
91a5cad144de0c4f3fb4e6572c03472899f0d3e8
| 138,013 |
def clean_side_panel(sidepanel):
"""
Cleans the SidePanel data and stores it in a dict.
Parameter:
sidepanel: html-sidepanel extracted using bs4
Returns:
data: dict of extracted data
"""
data = dict()
for x in sidepanel:
x = x.text.strip().replace('\n', '')
index = x.find(':')
if index == -1:
continue
y, x = x[:index], x[index+1:].strip()
data[y] = x
return data
|
c9fab309b64b788283e0848a0777fd3ef80014ad
| 25,228 |
import itertools
def normalize_padding(padding, rank):
"""
normalized format of padding should have length equal to rank+2
And the order should follow the order of dimension
ex. Conv2d (rank=2) it's normalized format length:2+2 ==>(left, right,top bottom)
Args:
padding (None, int, tuple):
rank (int):
Returns:
the normalized format of padding
Examples:
>>> normalize_padding(((1,0),(1,0)),2)
(1, 0, 1, 0)
>>> normalize_padding((1,0),2)
(0, 0, 1, 1)
"""
if padding is None:
padding = (0,) * (2 * rank)
elif isinstance(padding, int):
padding = (padding,) * (2 * rank)
elif isinstance(padding, (list, tuple)) and len(padding) == 1:
padding = padding * (2 * rank)
elif isinstance(padding, (list, tuple)) and len(padding) == rank and isinstance(padding[0], int):
# rank=2 (1,1)=>(1,1,1,1) (1,0)=>(0,0,1,1)
reversed_padding = list(padding)
reversed_padding.reverse()
return_padding = []
for i in range(rank):
return_padding.append(reversed_padding[i])
return_padding.append(reversed_padding[i])
padding = tuple(return_padding)
elif isinstance(padding, (list, tuple)) and len(padding) == rank and isinstance(padding[0], (list, tuple)):
# rank=2 ((1,0),(1,0)=>(1,0,1,0)
padding = tuple(list(itertools.chain(*list(padding))))
elif isinstance(padding, (list, tuple)) and len(padding) == 2 * rank and isinstance(padding[0], int):
padding = padding
return padding
|
6e67d1a7ff408c013fe7fc122a0b0320025e2373
| 37,154 |
def null_input_op_fn(x):
"""This function does no transformation on the inputs, used as default."""
return x
|
913f921a571703bef6b9768b69fc53474045d021
| 339,351 |
import math
def float_iszero(distance: float, threshold: float = 1e-05) -> bool:
"""
Computes if a distance is close to zero modulo an epsilon.
:param distance: distance to evaluate
:param threshold: the epsilon value
:return: true or false if the condition is met
"""
return math.isclose(distance, 0.0, rel_tol=threshold, abs_tol=threshold)
|
0b58c9a80242d1d2c88df454525f68d38abcd0b5
| 293,893 |
def get_main_domain_name(url_str) -> str:
"""get url domain texts
Args:
url_str (str): url string
Returns:
str: domain name of url
"""
domain_name = url_str.split("/")[2]
main_domain_name = domain_name.split(".")[-2]
return main_domain_name
|
ddc3fc8aa2b0b61eafd84ac9754c271f011ac8d2
| 627,602 |
def get_flights_sorted_price(flights, reverse=False):
"""Return a list of flights sorted by price.
Args:
flights (list): list of flights, each flight is represented
by a dictionary.
reverse (bool, optional): defines the sorting order,
by default to False - ascending, if True sort in descending order.
Returns:
list: a list of flights sorted by price.
"""
return sorted(
flights,
key=lambda flight: float(flight['Price']['TicketPrice']),
reverse=reverse,
)
|
2d21ff6ccee3e07b5ce4aaf7627c94be2570aeb7
| 667,375 |
def remove_non_ascii(text: str) -> str:
""" Removes non ascii characters
:param text: Text to be cleaned
:return: Clean text
"""
return ''.join(char for char in text if ord(char) < 128)
|
94a003856809eb740b5c85af094095acb2e07dad
| 29,211 |
def get_allowed_tokens_from_config(config, module='main'):
"""Return a list of allowed auth tokens from the application config"""
env_variable_name = ""
if module == "main":
env_variable_name = 'DM_ANTIVIRUS_API_AUTH_TOKENS'
elif module == 'callbacks':
# though SNS uses the "Basic" auth scheme, we can treat the payload section of the header as a single opaque
# token set in DM_ANTIVIRUS_API_CALLBACK_AUTH_TOKENS like any normal "Bearer" tokens.
env_variable_name = 'DM_ANTIVIRUS_API_CALLBACK_AUTH_TOKENS'
return [token for token in config.get(env_variable_name, '').split(':') if token]
|
ade52605bf0c390091fc201a01c010ec8d1a0a46
| 608,274 |
import torch
def load_checkpoint(checkpoint_file, model, model_opt):
"""
Loads a checkpoint including model state and running loss for continued training
"""
if checkpoint_file is not None:
checkpoint = torch.load(checkpoint_file)
state_dict = checkpoint["state_dict"]
start_iter = checkpoint['iter']
running_loss = checkpoint['running_loss']
opt_state_dict = checkpoint['optimizer']
model_opt.load_state_dict(opt_state_dict)
for state in model_opt.state.values():
for key, value in state.items():
if isinstance(value, torch.Tensor):
state[key] = value.cuda()
model.load_state_dict(state_dict)
else:
start_iter = 1
running_loss = 0
return start_iter, running_loss
|
ea9239646bb74cf5b9ff9a2ffa39e2ab96d9a2ed
| 66,087 |
def new_session(graph, expire_on_commit=False):
"""
Create a new session.
"""
return graph.sessionmaker(expire_on_commit=expire_on_commit)
|
14376529c4d7737450a4ed420c93b7d6bb9a3275
| 485,849 |
def unique_column_name(df, name):
"""
Generate a column name that is not already present in the dataframe.
"""
i = 1
newname = name
while newname in list(df):
i += 1
newname = '%s_%d' % (name, i)
return newname
|
61adf22cf7da2b502a49a6a8ff00506277104a31
| 308,064 |
import typing
def is_unpackable(obj: typing.Any):
"""
Checks if the given object is unpackable or not (if you can use **obj or not)
"""
return all(hasattr(obj, attr) for attr in ('keys', '__getitem__'))
|
27a3cd1c6bdff581411796c4f4b1d3caa9f04ad0
| 269,543 |
def replace_user_in_file_path(file_name, user):
"""Replace user name in give file path
Args:
file_name (str): Path to file
user (str): New user to replace with
Returns:
str: New file path
"""
file_items = [x.strip()
for x in file_name.strip().split('/') if len(x.strip())]
file_items[1] = user
return "/" + '/'.join(file_items).strip()
|
db4426f99cd6930d7edc8277e5c5ecf1870853e4
| 124,816 |
def dictget(d, l):
"""
Lookup item in nested dict using a list of keys, or None if non-existent
d: nested dict
l: list of keys, or None
"""
try:
dl0 = d[l[0]]
except (KeyError, TypeError):
return None
if len(l) == 1:
return dl0
return dictget(dl0, l[1:])
|
8adc8d795700e622f4c8c384ed65b38abd44f0d1
| 257,789 |
def y_intersection(line_slope, intercept, x_value):
"""
Finds the y value of the line (y = mx + b) at point x and returns the point
This basically solves y = mx + b
:param line_slope: slope of the line (m)
:param intercept: the intercept of the line (b)
:param x_value: the value to be used (substituted with x)
:return: the y value
"""
return x_value, line_slope * x_value + intercept
|
0b96f1fcce597a48ae88f286b543fed5c0e7917e
| 327,386 |
def jaccard_distance(label1, label2):
"""Jaccard distance metric"""
union_len = len(label1 | label2)
intersection_len = len(label1 & label2)
return (union_len - intersection_len) / float(union_len)
|
c1d025eff5eae5ab3d1558e35f43e137c5e5d65d
| 374,667 |
def create_id(fname: str, lname: str) -> str:
"""Create a player ID from a first name and last name.
String format: <first 5 characters of last name><first 2 characters of first name><01>
The last two integer digits allow for the prevention of ID conflicts.
To increment by an integer n, use add_n(player_id, n)
NOTE: spaces, periods, and apostrophes are omitted
"""
fname = fname.lower()
# remove spaces, periods, and apostrophes
lname = lname.lower().replace(" ", "").replace(".", "").replace("'", "")
if len(lname) > 5:
lname = lname[0:5]
if len(fname) > 2:
fname = fname[0:2]
return "{}{}01".format(lname, fname)
|
b67279adca01076723d81a34c69af3186c044fc6
| 511,864 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.