content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def calculate_pct_poi_msgs(series):
"""calculates the percentage of a potential POI's
total messages that are to or from a POI
Args:
series (pandas.core.series.Series): data series associated with a single POI
Returns:
[pandas.core.series.Series]: data series with the added POI message calculate
"""
total_msgs = series["from_messages"] + series["to_messages"]
series["pct_poi_messages"] = 0
if total_msgs > 0:
series["pct_poi_messages"] = (
(series["from_poi_to_this_person"] + series["from_this_person_to_poi"])
/ float(total_msgs)
) * 100
return series["pct_poi_messages"]
|
857e23204e6eab5db36f23d583613dd19bc7ffd4
| 703,543 |
import struct
def _read_int(f, b):
"""
Read an integer of a specified number of bytes from the filestream f
"""
if b == 1:
return struct.unpack('<B', f.read(b))[0]
elif b == 2:
return struct.unpack('<H', f.read(b))[0]
elif b == 4:
return struct.unpack('<I', f.read(b))[0]
elif b == 8:
return struct.unpack('<Q', f.read(b))[0]
|
36bcc2ccd4edd61fd9c6a438c3a069e699b7b17a
| 703,544 |
def compare_equality(col_1, col_2):
"""
This function compare the equality of two columns
and output an accuracy percentage
"""
return float(col_1.eq(col_2.values).mean())
|
adf6e6bb26988c7ee0211669881b2cd8331838da
| 703,546 |
def saveForwardState(old_s_tree, new_s_tree, s):
"""Saving the s_current as well as all its successors in the old_s_tree into the new_s_tree.
Parameters
----------
old_s_tree : dict
The old tree.
new_s_tree : dict
The new tree.
s_current : :py:class:`ast_toolbox.mcts.AdaptiveStressTesting.ASTState`
The current state.
Returns
----------
new_s_tree : dict
The new tree.
"""
if not (s in old_s_tree):
return new_s_tree
new_s_tree[s] = old_s_tree[s]
for sa in old_s_tree[s].a.values():
for s1 in sa.s.keys():
saveForwardState(old_s_tree, new_s_tree, s1)
return new_s_tree
|
1cf8aeac314c2f224a76d9c91c3bf1a8d54fd9df
| 703,547 |
import json
import os
import logging
def load_and_save_params(default_params, exp_dir, ignore_existing=False):
"""Update default_params with params.json from exp_dir and overwrite params.json with updated version."""
default_params = json.loads(json.dumps(default_params))
param_path = os.path.join(exp_dir, 'params.json')
logging.info("Searching for '%s'" % param_path)
if os.path.exists(param_path) and not ignore_existing:
logging.info("Loading existing params.")
with open(param_path, 'r') as fd:
params = json.load(fd)
default_params.update(params)
if not os.path.exists(exp_dir):
os.makedirs(exp_dir)
with open(param_path, 'w') as fd:
json.dump(default_params, fd, indent=4)
return default_params
|
4a0e9c1e24ec914abe1540ad9dd7d655b96c0e39
| 703,549 |
def generate_input_with_unknown_words(file_path):
"""Reads the file with the given file_path.
Replaces every first occurance of a (word, tag) pair with ("<UNK>", tag).
Creates dictionary of all words encountered in following format:
{(word, tag) : count}"""
seen_tuples = []
label_matches = dict()
file_lines = []
with open(file_path) as f:
for line in f:
file_lines = file_lines + [line.lower().split()]
word_tuples = zip(file_lines[0::3], file_lines[1::3], file_lines[2::3])
for (words, part_of_speech, word_type) in word_tuples:
type_tuple = zip(words, word_type)
for word_and_tag in type_tuple:
if word_and_tag in seen_tuples:
label_matches.update({word_and_tag : (label_matches.get(word_and_tag, 0) + 1)})
else:
tag = word_and_tag[1]
unknown_entry = ("<UNK>", tag)
label_matches.update({unknown_entry : (label_matches.get(unknown_entry, 0) + 1)})
seen_tuples.append(word_and_tag)
return label_matches
|
21479c1953dc1779a28bc49a38de55c383513fbf
| 703,550 |
def terminal_values(rets):
"""
Computes the terminal values from a set of returns supplied as a T x N DataFrame
Return a Series of length N indexed by the columns of rets
"""
return (rets+1).prod()
|
bea1f2a668deac3e915f7531ab68aea207e57d91
| 703,551 |
def getColumnNames(hdu):
"""Get names of columns in HDU."""
return [d.name for d in hdu.get_coldefs()]
|
9ac8fefe6fcf0e7aed10699f19b849c14b022d47
| 703,553 |
import torch
def embedding_to_probability(embedding: torch.Tensor, centroids: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
"""
Vectorizing this is slower than the loop!!!
# / (e_ix - C_kx)^2 (e_iy - C_ky)^2 (e_iz - C_kz)^2 \
# prob_k(e_i) = exp |-1 * ---------------- - ----------------- - ------------------ |
# \ 2*sigma_kx ^2 2*sigma_ky ^2 2 * sigma_kz ^2 /
:param embedding: [B, K=3, X, Y, Z] torch.Tensor where K is the likely centroid component: {X, Y, Z}
:param centroids: [B, I, K_true=3] torch.Tensor where I is the number of instances in the image and K_true is centroid
{x, y, z}
:param sigma: torch.Tensor of shape = (1) or (embedding.shape)
:return: [B, I, X, Y, Z] of probabilities for instance I
"""
num = 512
sigma = sigma + 1e-10 # when sigma goes to zero, things tend to break
centroids = centroids / num # Half the size of the image so vectors can be +- 1
# Calculates the euclidean distance between the centroid and the embedding
# embedding [B, 3, X, Y, Z] -> euclidean_norm[B, 1, X, Y, Z]
# euclidean_norm = sqrt(Δx^2 + Δy^2 + Δz^2) where Δx = (x_embed - x_centroid_i)
prob = torch.zeros((embedding.shape[0],
centroids.shape[1],
embedding.shape[2],
embedding.shape[3],
embedding.shape[4]), device=embedding.device)
sigma = sigma.pow(2).mul(2)
for i in range(centroids.shape[1]):
# Calculate euclidean distance between centroid and embedding for each pixel
euclidean_norm = (embedding - centroids[:, i, :].view(centroids.shape[0], 3, 1, 1, 1)).pow(2)
# Turn distance to probability and put it in preallocated matrix
if sigma.shape[0] == 3:
prob[:, i, :, :, :] = torch.exp(
(euclidean_norm / sigma.view(centroids.shape[0], 3, 1, 1, 1)).mul(-1).sum(dim=1)).squeeze(1)
else:
prob[:, i, :, :, :] = torch.exp((euclidean_norm / sigma).mul(-1).sum(dim=1)).squeeze(1)
return prob
|
133b7b81bb00db2110b6ec9709ab89924dee2dc4
| 703,554 |
def get_url(server_name, listen_port):
"""
Generating URL to get the information
from namenode/namenode
:param server_name:
:param listen_port:
:return:
"""
if listen_port < 0:
print ("Invalid Port")
exit()
if not server_name:
print("Pass valid Hostname")
exit()
URL = "http://"+server_name+":"+str(listen_port)+"/jmx"
return URL
|
097e347a75eb581ae97734552fa6f9e7d3b11ce6
| 703,555 |
def euler97():
"""Solution for problem 97."""
mod = 10 ** 10
return (1 + 28433 * pow(2, 7830457, mod)) % mod
|
ab04cf67431a434f147f3615bee5a211b58ccbde
| 703,556 |
def latex_code(size):
"""
Get LaTeX code for size
"""
return "\\" + size + " "
|
03478f8f62bb2b70ab5ca6ece66d4cdca3595dd6
| 703,557 |
def has_cycle_visit(visiting, parents, adjacency_list, s):
"""
Check if there is a cycle in a graph starting
at the node s
"""
visiting[s] = True
for u in adjacency_list[s]:
if u in visiting:
return True
if u in parents:
continue
parents[u] = s
if has_cycle_visit(visiting, parents, adjacency_list, u):
return True
del visiting[s]
return False
|
5f87f6f39d88cbae93e7e461590002ca6a94aa20
| 703,558 |
def remove_trailing_whitespace(line):
"""Removes trailing whitespace, but preserves the newline if present.
"""
if line.endswith("\n"):
return "{}\n".format(remove_trailing_whitespace(line[:-1]))
return line.rstrip()
|
2c5f7b3a35152b89cda6645911569c9d2815f47e
| 703,559 |
def process_settings(pelicanobj):
"""Sets user specified Katex settings"""
katex_settings = {}
katex_settings['auto_insert'] = True
katex_settings['process_summary'] = True
return katex_settings
|
9799d9ea6bf17fabd1640c4e69ca3b1da5406829
| 703,560 |
import networkx
def make_cross(length=20, width=2) -> networkx.Graph:
"""Builds graph which looks like a cross.
Result graph has (2*length-width)*width vertices.
For example, this is a cross of width 3:
...
+++
+++
...+++++++++++...
...+++++++++++...
...+++++++++++...
+++
+++
...
:param length: Length of a cross.
:param width: Width of a cross.
"""
assert width < length * 2
nodes = set()
for i in range(length // 2, length // 2 + width):
for j in range(0, length):
nodes.add((i, j))
nodes.add((j, i))
nodes = list(nodes)
node_index = {nodes[i]: i for i in range(len(nodes))}
graph = networkx.Graph()
graph.add_nodes_from(range(len(nodes)))
for x, y in nodes:
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
if (x + dx, y + dy) in node_index:
graph.add_edge(node_index[(x, y)],
node_index[(x + dx, y + dy)])
return graph
|
f0be683fd8971ea8b3cc0b40977a939c117e9906
| 703,561 |
def print_table(input_dict, title='', header=('Key', 'Value'), style=('', '-')):
"""Print the dict in a table form"""
assert input_dict.__class__ is dict, "Only accept class='dict'"
if input_dict is None:
return None
max_string = 110
key_list = list(input_dict.keys())
val_list = list(map(str, input_dict.values()))
key_list.append(header[0])
val_list.append(header[1])
# find the longest key value
width_left = min(len(max(key_list, key=len)), max_string)
width_right = min(len(max(val_list, key=len)), max_string)
width_full = width_left + width_right + 2 + 2 + 1
# structure
table_struct = f"{{:>{width_left}}} | {{:>{width_right}}}"
# top border
print(style[0] * width_full)
# title
print(f"{{:^{width_full}}}".format(f"~{title}~"))
print(style[1] * width_full)
# contents
print(table_struct.format(header[0], header[1]))
print(style[1] * width_full)
for key, val in input_dict.items():
# format empty value
if val == '':
val = '-'
# trim long string
if len(str(val)) > max_string:
print(table_struct.format(key, str(val)[0:max_string]))
else:
print(table_struct.format(key, str(val)))
# bot boader
print(style[0] * width_full)
print("\n")
|
47844b6526723fbf63bc347ed1487442fc497904
| 703,562 |
def must_be_known(in_limit, out_limit):
"""
Logical combinatino of limits enforcing a known state
The logic determines that we know that the device is fully inserted or
removed, alerting the MPS if the device is stuck in an unknown state or
broken
Parameters
----------
in_limit : ``bool``
Whether the in limit is active
out_limit: ``bool``
Whether the out limit is active
Returns
-------
is_known
Whether the logical combination of the limit switch ensure that the
device position is known
"""
return in_limit != out_limit
|
241b66b359643d069aa4066965879bb6ac76f2ae
| 703,564 |
def scale(x):
"""Scales values to [-1, 1].
**Parameters**
:x: array-like, shape = arbitrary; unscaled data
**Returns**
:x_scaled: array-like, shape = x.shape; scaled data
"""
minimum = x.min()
return 2.0 * (x - minimum) / (x.max() - minimum) - 1.0
|
e5c40a4a840a1fa178a2902378a51bfefc83b368
| 703,565 |
def group_data_by_columns(datasets, columns):
"""
:param datasets: [CxNxSxF]
:param columns: F
:return: CxNxFxS
"""
new_dataset = []
for i in range(len(datasets)):
datalist = []
for row in range(len(datasets[i][0][0])):
row_data = []
for column_idx in range(len(columns)):
col_data = []
for series in range(len(datasets[i][0][0][row])):
col_data.append(datasets[i][0][0][row][series][column_idx])
row_data.append(col_data)
datalist.append(row_data)
new_dataset.append((datalist, datasets[i][0][1]))
return new_dataset
|
8a73c959501f422c26fe358c05ddc6a574123009
| 703,566 |
def GetStaticPipelineOptions(options_list):
"""
Takes the dictionary loaded from the yaml configuration file and returns it
in a form consistent with the others in GenerateAllPipelineOptions: a list of
(pipeline_option_name, pipeline_option_value) tuples.
The options in the options_list are a dict:
Key is the name of the pipeline option to pass to beam
Value is the value of the pipeline option to pass to beam
"""
options = []
for option in options_list:
if len(list(option.keys())) != 1:
raise Exception('Each item in static_pipeline_options should only have'
' 1 key/value')
option_kv = list(option.items())[0]
options.append((option_kv[0], option_kv[1]))
return options
|
d49effbdeb687ec62a2e2296330f66521023944c
| 703,567 |
def _field_object_metadata(field_object):
"""Return mapping of field metadata key to value.
Args:
field_object (arcpy.Field): ArcPy field object.
Returns:
dict.
"""
meta = {"object": field_object}
key_attribute_name = {
"alias_name": "aliasName",
"base_name": "baseName",
"default_value": "defaultValue",
"is_editable": "editable",
"is_nullable": "isNullable",
"is_required": "required",
}
key_attribute_same = ["name", "type", "length", "precision", "scale"]
for key in key_attribute_same:
key_attribute_name[key] = key
for key, attribute_name in key_attribute_name.items():
meta[key] = getattr(field_object, attribute_name)
return meta
|
1e653737f1dee41c7ce786735368e55f4908b116
| 703,569 |
def mean_of_cluster(list_of_points):
"""Calculates the center of the list of points
"""
number_of_points = float(len(list_of_points))
vector_total = [float(0), float(0)]
for point in list_of_points:
for index, component in enumerate(point):
vector_total[index] += component
return vector_total[0] / number_of_points, vector_total[1] / number_of_points
|
b94b5ea40fb08253bcade35282692bbb58b85e98
| 703,570 |
def range_overlap(a_min, a_max, b_min, b_max):
"""
Neither range is completely greater than the other
"""
return (a_min <= b_max) and (b_min <= a_max)
|
c05d8b0799f62300760ad69704a5091c3830ad26
| 703,571 |
import json
def read_json(json_file_path: str) -> dict:
"""Takes a JSON file and returns a dictionary"""
with open(json_file_path, "r") as fp:
data = json.load(fp)
return data
|
07cb6c606de83b2b51ddcbf64f7eb45d6907f973
| 703,572 |
import os
def _get_user_guide_directory():
"""Returns absolute path to docs/ directory"""
docsdir = os.path.join("docs", "user_guide")
return os.path.abspath(docsdir)
|
147294fe005f7d6756aeb4c3579bddf795668087
| 703,573 |
import uuid
def unique_variable_name():
"""Creates a unique variable name. Useful when attempting to introduce
a new token to see if it can fix specific cases of SyntaxError."""
name = uuid.uuid4()
return "_%s" % name.hex
|
d4b54a8ab76fa8bddd6fe62a735f1dd886e9e62a
| 703,574 |
def cleaner_unicode(string):
"""
Objective :
This method is used to clean the special characters from the report string and
place ascii characters in place of them
"""
if string is not None:
return string.encode('ascii', errors='backslashreplace')
else:
return string
|
f4e2c4b9fa7f4a644e409a5d429531a34bc1c6c2
| 703,575 |
import subprocess
import sys
def subprocess_call(args, cwd, capture_output=False, **kwargs):
"""Calls a subprocess, possibly capturing output."""
try:
if capture_output:
return subprocess.check_output(args, cwd=cwd, **kwargs)
else:
return subprocess.check_call(args, cwd=cwd, **kwargs)
except subprocess.CalledProcessError:
print("ERROR executing subprocess (from {}):\n {}".format(
cwd, " ".join(args)),
file=sys.stderr)
sys.exit(1)
|
956837dae6e7b74f1e51cd87e4c920bfe08eb2d0
| 703,576 |
def enthalpy_Shomate(T, hCP):
"""
enthalpy_Shomate(T, hCP)
NIST vapor, liquid, and solid phases
heat capacity correlation
H - H_ref (kJ/mol) = A*t + 1/2*B*t^2 + 1/3*C*t^3 +
1/4*D*t^4 - E*1/t + F - H
t (K) = T/1000.0
H_ref is enthalpy in kJ/mol at 298.15 K
Parameters
T, temperature in Kelvin
hCP, A=hCP[0], B=hCP[1], C=hCP[2], D=hCP[3], E=hCP[4], F=hCP[5], H=hCP[7]
A, B, C, D, E, F, and H are regression coefficients
Returns
enthalpy in kJ/mol at T relative to enthalpy at 298.15 K
"""
t = T/1000.0
return hCP[0]*t + hCP[1]/2*t**2 + hCP[2]/3*t**3 + hCP[3]/4*t**4 - hCP[4]/t + hCP[5] - hCP[7]
|
05e3f3a35a87f767a44e2e1f4e35e768e12662f7
| 703,577 |
def get_acres(grid, coordinates):
"""Get acres from coordinates on grid."""
acres = []
for row, column in coordinates:
if 0 <= row < len(grid) and 0 <= column < len(grid[0]):
acres.append(grid[row][column])
return acres
|
e4ba6aabe07d8859481aefaba4d4559f1ec25e96
| 703,578 |
def highest_mag(slide):
"""Returns the highest magnification for the slide
"""
return int(slide.properties['aperio.AppMag'])
|
d42361c979a5addf0ebf4c7081a284c9bc0477ec
| 703,579 |
import re
def enumerate_destination_file_name(destination_file_name):
"""
Append a * to the end of the provided destination file name.
Only used when query output is too big and Google returns an error
requesting multiple file names.
"""
if re.search(r'\.', destination_file_name):
destination_file_name = re.sub(
r'\.', f'_*.', destination_file_name, 1)
else:
destination_file_name = f'{destination_file_name}_*'
return destination_file_name
|
6b398597db26a175e305446ac39c363a5077ba96
| 703,581 |
def demistoVersion():
"""Retrieves server version and build number
Returns:
dict: Objects contains server version and build number
"""
return {
'version': '5.5.0',
'buildNumber': '12345'
}
|
39ef34f88f44ecfad9d30a80bcdb74ad1833c3ae
| 703,582 |
import os
def create_work_name(name):
""" Remove ".nzb" and ".par(2)" """
strip_ext = ['.nzb', '.par', '.par2']
name = name.strip()
if name.find('://') < 0:
name_base, ext = os.path.splitext(name)
# In case it was one of these, there might be more
while ext.lower() in strip_ext:
name = name_base
name_base, ext = os.path.splitext(name)
return name.strip()
else:
return name.strip()
|
5e5405505a7c342ebb372ea53ad8330919b0979a
| 703,583 |
def bias_act(x, b=None, dim=1, gain=None, clamp=None):
"""Slow reference implementation of `bias_act()`
"""
# spec = activation_funcs[act]
# alpha = float(alpha if alpha is not None else 0)
gain = float(gain if gain is not None else 1)
clamp = float(clamp if clamp is not None else -1)
# Add bias.
if b is not None:
x = x + b.reshape([-1 if i == dim else 1 for i in range(x.ndim)])
# Evaluate activation function.
# alpha = float(alpha)
# x = spec.func(x, alpha=alpha)
# Scale by gain.
gain = float(gain)
if gain != 1:
x = x * gain
# Clamp.
if clamp >= 0:
x = x.clip(-clamp, clamp) # pylint: disable=invalid-unary-operand-type
return x
|
3e98d5941d29c78ecd5c46c9ec960f14cedc36e9
| 703,584 |
def combine_envs(*envs):
"""Combine zero or more dictionaries containing environment variables.
Environment variables later from dictionaries later in the list take
priority over those earlier in the list. For variables ending with
``PATH``, we prepend (and add a colon) rather than overwriting.
If you pass in ``None`` in place of a dictionary, it will be ignored.
"""
result = {}
for env in envs:
if env:
for key, value in env.iteritems():
if key.endswith('PATH') and result.get(key):
result[key] = '%s:%s' % (value, result[key])
else:
result[key] = value
return result
|
feb6e00b9c0b1262220339feac6c5ac2ae6b6b17
| 703,585 |
import torch
def generate_square_subsequent_mask(sz):
"""
Generate attention mask using triu (triangle) attention
"""
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = (
mask.float()
.masked_fill(mask == 0, float("-inf"))
.masked_fill(mask == 1, float(0.0))
)
return mask
|
5631e89a275eee13c4b01a7b856421f6b45c2588
| 703,586 |
def len_column(table):
"""
Add length column containing the length of the original entry in the seq column.
Insert a number column with numbered entries for each row.
"""
for pos, i in enumerate(table):
i.insert(0, pos)
i.append(len(i[1]))
return table
|
5a9215bc2feade70873de6adccd2b4c4b6acfed9
| 703,587 |
def read_maze(file_name):
"""
Reads a maze stored in a text file and returns a 2d list containing the maze representation.
"""
try:
with open(file_name) as fh:
maze = [[char for char in line.strip("\n")] for line in fh]
num_cols_top_row = len(maze[0])
for row in maze:
if len(row) != num_cols_top_row:
print("The maze is not rectangular.")
raise SystemExit
return maze
except OSError:
print("There is a problem with the file you have selected.")
raise SystemExit
|
373e121a9dc827307fc6b56350f8b19247115651
| 703,588 |
def sns_certificate(*args):
""" Mock requests to retrieve the SNS signing certificate """
with open('tests/files/certificate.pem') as cert_file:
cert = cert_file.read()
return cert
|
6d1198c7ea3c29be28dbecf6affe5c31ab51267a
| 703,589 |
def translate_delta(mat, dx, dy):
"""
Return matrix with elements translated by dx and dy, filling the would-be
empty spaces with 0. I feel this method may not be the most efficient.
"""
rows, cols = len(mat), len(mat[0])
# Filter out simple deltas
if (dx == 0 and dy == 0):
return mat
elif (abs(dx) >= rows or abs(dy) >= cols):
return [[0 for col in mat[0]] for row in mat]
dmat = []
# Create new matrix translated by dx and dy
for r in range(rows):
drow = []
for c in range(cols):
if (r + dy in range(rows) and c - dx in range(cols)):
drow.append(mat[r + dy][c - dx])
else:
drow.append(0)
dmat.append(drow)
return dmat
|
38492c874bc7bbd59787f4b2d94c2ea0150e69f8
| 703,590 |
def u2(vector):
"""
This function calculates the utility for agent 2.
:param vector: The reward vector.
:return: The utility for agent 2.
"""
utility = vector[0] * vector[1]
return utility
|
93b9210db00ee9a3ddca4cd9b447a7348f63a659
| 703,591 |
def counting_sort_integers(values, max_val=None, min_val=None, inplace=False):
"""
Sorts an array of integers using counting_sort.
Let n = len(values), k = max_val+1
"""
if len(values) == 0:
return values if inplace else []
#Runs in O(n) time if max_val is None or min_val is None
if max_val is None:
#If both are None, find max and min simultaneously.
if min_val is None:
max_val = min_val = values[0]
for value in values[1:]:
if value > max_val:
max_val = value
elif value < min_val:
min_val = value
else:
max_val = max(values)
elif min_val is None:
min_val = min(values)
#Assume values are integers in the range 0,1,2,...,max_val
#Runs in O(k) time
counts = [0 for _ in range(min_val,max_val+1)]
#Runs in O(n) time
for value in values:
counts[value-min_val] += 1
#Overwrite values if inplace==True, otherwise create a new array for output.
#Requires O(n) time if inplace is False.
output = values if inplace else [0 for _ in range(len(values))]
#Simultaneously iterate through output and counts arrays.
#value will be the index of counts array - this is the value
#we will be storing in the output array.
value = min_val
#Iterate through output array, storing one value at a time.
#The for loop has n iterations.
#The inner while loop will have a total of k iterations.
#So the runtime for this loop is O(n+k)
for i in range(len(output)):
#Find the next value with a nonzero count.
while counts[value-min_val] == 0:
value += 1
#Store the value in the output array and decrease its count.
output[i] = value
counts[value-min_val] -= 1
#Total runtime, in iterations, is 2k+2n if max_key is passed and inplace==True.
#Another n is added if max_key is None or inplace is False, for a maximum
#runtime of 2k+4n.
return output
|
d53b00b8753d8adc1782e5941b4b6dcce7c80ca3
| 703,592 |
def xfun(p,B,pv0,f):
"""
Steady state solution for x without CRISPR
"""
return f/(B*p-p/pv0)
|
874d7d5a1d0d485aafa6f7298e1d214ca86ea90e
| 703,593 |
def pattern_matching(pattern, genome):
"""Find all occurrences of a pattern in a string.
Args:
pattern (str): pattern string to search in the genome string.
genome (str): search space for pattern.
Returns:
List, list of int, i.e. all starting positions in genome where pattern appears as a substring.
Examples:
Find all the starting positions for a pattern string in the genome string.
1.
>>> pattern = 'ATAT'
>>> genome = 'GATATATGCATATACTT'
>>> positions = pattern_matching(pattern, genome)
>>> positions
[1, 3, 9]
2.
>>> pattern = 'CTTGATCAT'
>>> genome = 'CTTGATCATCTTGATCATCTTGATCAT'
>>> positions = pattern_matching(pattern, genome)
>>> positions
[0, 9, 18]
"""
positions = [] # output variable
for i in range(len(genome)-len(pattern)+1):
if genome[i:i+len(pattern)] == pattern:
positions.append(i)
return positions
|
86ae704586fbac937e044f41a8831f2669c4e7dc
| 703,594 |
import glob
def findLblWithoutImg(pathI, pathII):
"""
:param pathI: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/images/*.jpg"
:param pathII: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/labels/*.txt"
:return: num of image which not has label
"""
num = 0
pathI = glob.glob(pathI)
pathII = glob.glob(pathII)
imgNames = [i.split("\\")[-1].split(".")[0] for i in pathI]
lblNames = [i.split("\\")[-1].split(".")[0] for i in pathII]
for lbl in lblNames:
if lbl not in imgNames:
print(lbl)
num += 1
return num
|
30edbff244acb0014b54cf3c85d86a47d779d226
| 703,595 |
import math
def lcf_float(val1, val2, tolerance):
"""Finds lowest common floating point factor between two floating point numbers"""
i = 1.0
while True:
test = float(val1) / i
check = float(val2) / test
floor_check = math.floor(check)
compare = floor_check * test
if val2 - compare < (tolerance / 2.0):
return test
i += 1.0
|
b4bef1a63984440f43a1b0aa9bf9805cb4bfd466
| 703,596 |
def check_num_row(data):
"""
@param df: dataframe
@return: return 1 if checking condition is true
"""
return data.shape[0] > 10
|
0761c4d31bc3a14132d6c1547d03149bd10013c5
| 703,597 |
def _convert_text_to_logs_format(text: str) -> str:
"""Convert text into format that is suitable for logs.
Arguments:
text: text that should be formatted.
Returns:
Shape for logging in loguru.
"""
max_log_text_length = 50
start_text_index = 15
end_text_index = 5
return (
"...".join((text[:start_text_index], text[-end_text_index:]))
if len(text) > max_log_text_length
else text
)
|
4f7ff95a5cd74bdccd41559f58292cc9b1003ba2
| 703,598 |
import random
def generate_random_slug(length=40, prefix=None):
"""
This function is used, for example, to create Coupon code mechanically
when a customer pays for the subscriptions of an organization which
does not yet exist in the database.
"""
if prefix:
length = length - len(prefix)
# make sure the slug starts with a letter in case it is used as a resource
# name (variable or database).
suffix = random.choice("abcdef")
suffix += "".join(
[random.choice("abcdef0123456789") for val in range(length - 1)]
) # Generated coupon codes
# are stored as ``Transaction.event_id`` with
# a 'cpn_' prefix. The total event_id must be less
# than 50 chars.
if prefix:
return str(prefix) + suffix
return suffix
|
add5e68d0ed6d3831993410afc5ec7900eb212c4
| 703,599 |
def digits_to_num(L, reverse=False):
"""Returns a number from a list of digits, given by the lowest power of 10 to the highest, or
the other way around if `reverse` is True"""
digits = reversed(L) if reverse else L
n = 0
for i, d in enumerate(digits):
n += d * (10 ** i)
return n
|
1648073d46411fd430afea4f40f7fa9f4567793c
| 703,600 |
import sys
import os
def executable(name):
"""Return the full path to an executable"""
suffix = ""
folder = "bin"
if sys.platform == "win32":
suffix = ".exe"
folder = os.path.join(folder, "Release")
return os.path.join("..", folder, name + suffix)
|
8fbc4aa30e5ad3aeb126f7c5adbbdd62e68091c2
| 703,601 |
def clean_zeros(a, b, M):
""" Remove all components with zeros weights in a and b
"""
M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd)
a2 = a[a > 0]
b2 = b[b > 0]
return a2, b2, M2
|
3e2def6e88a7ac5a67b9849a9dcd2f5f5156fb00
| 703,602 |
import re
def get_cheque_code(cheque: str):
"""Get code"""
if (
re.search(r'BTC_CHANGE_BOT\?start=', cheque)
or not re.search(r'BTC_CHANGE_BOT\?start=', cheque)
and re.search(r'Chatex_bot\?start=', cheque)
):
return re.findall(r'c_\S+', cheque)[0]
elif re.search(r'Getwallet_bot\?start=', cheque):
return re.findall(r'g_\S+', cheque)[0]
return cheque
|
97d0b3cadfb6010b48ed6fb148083060c50720ff
| 703,603 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
return [len(p) for p in lines]
|
83747e57bddf24484633e38ce27c51c7c8fce971
| 703,605 |
import urllib3
import certifi
def load_content(site, host, links):
"""Tests a site."""
# Security: Verified HTTPS with SSL/TLS
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED', # Force certificate check.
ca_certs=certifi.where(), # Path to the Certifi bundle.
)
start_page_search = """https://startpage.com/do/search
?cmd=process_search&language=english&enginecount=1&pl=&abp=
1&cdm=&tss=1&ff=&theme=&prf=464341bcfbcf47b736ff43307aef287a
&suggestOn=1&flag_ac=0&lui=english&cat=web&query="""
start_page_search = start_page_search.replace('\n', '')
start_page_search = start_page_search.replace(' ', '')
if host:
start_page_search = start_page_search + "host%3A"+host+"+"
start_page_search = start_page_search+"link%3A"+site
if not links:
start_page_search = start_page_search.replace("link%3A", "")
response = http.request('GET', start_page_search)
return response
|
5a599579133297c2e6ab3231b466f1b6184d22cc
| 703,606 |
def get_types_dict():
"""
:return: type name read in as string to type method mapping
"""
return {"str": str, "float": float, "int": int}
|
7a386fa63cba73e35672b15c31bc8b2c59361f24
| 703,607 |
def create_class_hierarchy_dict(cls):
"""Returns the dictionary with all members of the class ``cls`` and its superclasses."""
dict_extension_order = cls.__mro__[-2::-1] # Reversed __mro__ without the 'object' class
attrs_dict = {}
for base_class in dict_extension_order:
attrs_dict.update(vars(base_class))
return attrs_dict
|
0378fb3243a48964fcec42fddb38c0664a338ee4
| 703,608 |
from datetime import datetime
def month_to_date(month):
"""
Convert month to date format.
Keyword arguments:
month -- the month to convert to date format
"""
month = datetime.strptime(month, '%Y-%m')
date = month.strftime('%Y-%m-%d') # eg 2018-02-01
date = datetime.strptime(date, '%Y-%m-%d') # return datetime object
return date
|
e417eefa63430e422a53bd194fbb1e0d5e453c7b
| 703,609 |
def encode(string):
"""Encode some critical characters to html entities."""
return string.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>') \
.replace(' ', ' ') \
.replace('\n', '<br>') if string else ''
|
faea4b2f2e032b5e05e2c99bc56a1cf35e60b85d
| 703,610 |
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
return rem(x-a, a)
|
22b421c090970810f9aa4d55ff5a700e1301c0b8
| 703,611 |
import platform
import subprocess
import re
import os
def get_env_prefix():
"""
Automatically identify os_type information which use for
install path of bash_completion.d
"""
TARGET_BIN_PATH = '/usr/local/bin/'
os_type = platform.system()
cygwin = r'CYGWIN|cygwin'
if os_type == "Linux":
TARGET_COMPLETION_PATH = "/etc/bash_completion.d/"
# Darwin is indicate Mac OS
elif os_type == "Darwin":
proc = subprocess.Popen(
'brew --prefix', shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
brew_prefix = "{0}/etc/bash_completion.d/".format(
stdout.rstrip().decode("utf-8"))
TARGET_COMPLETION_PATH = brew_prefix
# Return true if CYGWIN or cygwin there in os type string
elif re.search(cygwin, os_type):
TARGET_COMPLETION_PATH = '/etc/bash_completion.d/'
TARGET_BIN_PATH = '/usr/bin/'
if not os.path.exists(TARGET_COMPLETION_PATH):
os.makedirs(TARGET_COMPLETION_PATH)
else:
raise ValueError(
'Unknown OS type found. This Operating System is not supported.')
return TARGET_COMPLETION_PATH, TARGET_BIN_PATH
|
fd290446484ae0f0392aaf4c34dc2feef0aa3553
| 703,612 |
import subprocess
def check_output(args):
"""
Delegates to subprocess.check_output() if it is available, otherwise
provides a reasonable facsimile.
"""
if 'check_output' in dir(subprocess):
out = subprocess.check_output(args)
else:
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
out, err = proc.communicate()
ret = proc.poll()
if ret:
raise subprocess.CalledProcessError(ret, args[0], output=out)
if type(out) is bytes:
"""
git isn't guaranteed to always return UTF-8, but for our purposes
this should be fine as tags and hashes should be ASCII only.
"""
out = out.decode('utf-8')
return out
|
bbe456c8b3d2e8f1acd0f32478828ce44af7842f
| 703,613 |
def demo7(response):
"""在每次请求后运行"""
# eg:修改响应头
print(response)
print('=========== after func run =============')
# response.headers['Content-Type'] = 'application/json;charset=utf-8;'
return response
|
86991057bb48f1da33b3417387009d98744d2d94
| 703,614 |
def identity(value):
"""
Node returning the input value.
"""
return value
|
e1af1346b11bc36a4426ad3c557dc01045657de8
| 703,616 |
import re
def parse_members_for_workspace(toml_path):
"""Parse members from Cargo.toml of the worksapce"""
with open(toml_path, mode='rb') as f:
data = f.read()
manifest = data.decode('utf8')
regex = re.compile(r"^members\s*=\s*\[(.*?)\]", re.S | re.M)
members_block = regex.findall(manifest)[0]
out = []
members = members_block.split('\n')
regex2 = re.compile(r'\s*"(.*?)".*')
for mem in members:
if (len(mem.strip()) == 0) or re.match(r".*#\signore", mem):
continue
out.append(regex2.findall(mem)[0])
return out
|
63926ac1eaadc360e2407f2fff5f41b7667e52b4
| 703,618 |
import torch
def steering(taus, n_fft):
""" This function computes a steering vector by using the time differences
of arrival for each channel (in samples) and the number of bins (n_fft).
The result has the following format: (batch, time_step, n_fft/2 + 1, 2, n_mics).
Arguments:
----------
taus : tensor
The time differences of arrival for each channel. The tensor must have
the following format: (batch, time_steps, n_mics).
n_fft : int
The number of bins resulting of the STFT. It is assumed that the
argument "onesided" was set to True for the STFT.
Example:
--------f
>>> import torch
>>> from speechbrain.dataio.dataio import read_audio
>>> from speechbrain.processing.features import STFT
>>> from speechbrain.processing.multi_mic import Covariance
>>> from speechbrain.processing.multi_mic import GccPhat, tdoas2taus, steering
>>>
>>> xs_speech = read_audio(
... 'samples/audio_samples/multi_mic/speech_-0.82918_0.55279_-0.082918.flac'
... )
>>> xs_noise = read_audio('samples/audio_samples/multi_mic/noise_diffuse.flac')
>>> xs = xs_speech + 0.05 * xs_noise
>>> xs = xs.unsqueeze(0) # [batch, time, channels]
>>> fs = 16000
>>> stft = STFT(sample_rate=fs)
>>> cov = Covariance()
>>> gccphat = GccPhat()
>>>
>>> Xs = stft(xs)
>>> n_fft = Xs.shape[2]
>>> XXs = cov(Xs)
>>> tdoas = gccphat(XXs)
>>> taus = tdoas2taus(tdoas)
>>> As = steering(taus, n_fft)
"""
# Collecting useful numbers
pi = 3.141592653589793
frame_size = int((n_fft - 1) * 2)
# Computing the different parts of the steering vector
omegas = 2 * pi * torch.arange(0, n_fft, device=taus.device) / frame_size
omegas = omegas.repeat(taus.shape + (1,))
taus = taus.unsqueeze(len(taus.shape)).repeat(
(1,) * len(taus.shape) + (n_fft,)
)
# Assembling the steering vector
a_re = torch.cos(-omegas * taus)
a_im = torch.sin(-omegas * taus)
a = torch.stack((a_re, a_im), len(a_re.shape))
a = a.transpose(len(a.shape) - 3, len(a.shape) - 1).transpose(
len(a.shape) - 3, len(a.shape) - 2
)
return a
|
c33264516e6903d22533c9f23585739438aa5d75
| 703,619 |
def decodeXMLName(name):
"""
Decodes an XML (namespace, localname) pair from an ASCII string as encoded
by encodeXMLName().
"""
if name[0] is not "{": return (None, name.decode("utf-8"))
index = name.find("}")
if (index is -1 or not len(name) > index):
raise ValueError("Invalid encoded name: %r" % (name,))
return (name[1:index].decode("utf-8"), name[index+1:].decode("utf-8"))
|
28a81aed2477b444ac061b21ca838912ee2bf24b
| 703,620 |
import argparse
def parse_args() -> argparse.Namespace:
"""Parse user command line arguments."""
parser = argparse.ArgumentParser(
prog="ssacc",
description="Map SSA County Codes to ZIP Codes.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-r",
type=int,
required=False,
default=0,
help="Regenerate the ZIP to FIPS county code CSV, if -r 1.",
)
return parser.parse_args()
|
0ea9ec39d22c2908e9b72452b5553ca62ab02aa7
| 703,622 |
from typing import Dict
from typing import Any
from typing import List
import copy
def move_to_location(
object_instance: Dict[str, Any],
location: Dict[str, Any],
object_bounds: List[Dict[str, float]],
previous_object: Dict[str, Any]
) -> Dict[str, Any]:
"""Move the given object to a new location and return the object."""
new_location = copy.deepcopy(location)
if previous_object and 'offset' in previous_object:
new_location['position']['x'] += previous_object['offset']['x']
new_location['position']['z'] += previous_object['offset']['z']
if 'offset' in object_instance:
new_location['position']['x'] -= object_instance['offset']['x']
new_location['position']['z'] -= object_instance['offset']['z']
object_instance['shows'][0]['position'] = new_location['position']
object_instance['shows'][0]['rotation'] = new_location['rotation']
object_instance['shows'][0]['boundingBox'] = object_bounds
return object_instance
|
079f7367d04d732a93aa2ac18a1255a061e00243
| 703,623 |
import optparse
def parse_args():
"""
Parse command line options into variables
"""
parser = optparse.OptionParser(usage="Usage: %prog [options]")
parser.add_option("--film-urls",
type="string",
dest="urls",
help=("Film URLs to pick from, separated by commas")
)
parser.add_option("--film-urls-file-path",
type="string",
dest="filepath",
help=("File that contains film URLs to pick from")
)
parser.add_option("--optimize-for",
type="choice",
dest="optimize_for",
choices=["day", "evening"],
default="evening",
help=("Option for optimizing for day or evening times")
)
(options, args) = parser.parse_args()
return options
|
e618915c8c6a6211e208b3bca662ad951c46a507
| 703,626 |
def plural(items_or_count,
singular: str,
count_format='',
these: bool = False,
number: bool = True,
are: bool = False) -> str:
"""Returns the singular or plural form of a word based on a count."""
try:
count = len(items_or_count)
except TypeError:
count = items_or_count
prefix = ('this ' if count == 1 else 'these ') if these else ''
num = f'{count:{count_format}} ' if number else ''
suffix = (' is' if count == 1 else ' are') if are else ''
if singular.endswith('y'):
result = f'{singular[:-1]}{"y" if count == 1 else "ies"}'
elif singular.endswith('s'):
result = f'{singular}{"" if count == 1 else "es"}'
else:
result = f'{singular}{"" if count == 1 else "s"}'
return f'{prefix}{num}{result}{suffix}'
|
01f397579b60538f25710566507973bdc6422874
| 703,627 |
import sqlite3
def db_setup(db_name):
"""Database setup."""
cxn = sqlite3.connect(db_name, timeout=30.0)
cxn.execute('PRAGMA page_size = {}'.format(2 ** 16))
cxn.execute("PRAGMA journal_mode = WAL")
return cxn
|
55092a98aed1e0a42ebf004a116913cfbecfb5f9
| 703,628 |
def role_object_factory(role_name='role.test_role'):
"""Cook up a fake role."""
role = {
'nameI18n': role_name[:32],
'active': 1
}
return role
|
e79e7b22a83d9da721b074d32878eabeca4054cd
| 703,629 |
import itertools
def create_possible_expected_messages(message_template, expected_types):
"""
Some error messages contain dictionaries with error types. Dictionaries
in Python are unordered so it makes testing unpredictable. This
function takes in a message template and a list of types and returns
a list that contains error messages for every permutation of the types.
Args:
message_template (str): A string with a single format argument ({}).
expected_types (list): A list of types. Ex: [str, int]
Returns:
list: A list of the given error message formatted with all permutations
of the given type list.
"""
# Create an iterable of all the permutations of the types.
# Can roughly be thought of as a list of tuples
type_premutations = itertools.permutations(expected_types)
# For each permutation, map each type in the permutation to a string
# and remove '<' and '>' since this is how our exceptions format them.
formatted_string_types = [
map(lambda s: str(s).replace('<', '').replace('>', ''), t)
for t in type_premutations
]
# Finally, create an error message with each permutation.
return [
message_template.format(', '.join(f)) for f in formatted_string_types
]
|
674dec990e0786d3e313a9b8deec72e37588d8eb
| 703,630 |
def load_saved_recipes(filename):
"""
Internal method for reading contens of given file.
"""
contents = []
try:
# Read file line by line, recipe by recipe
with open(filename, 'r') as recipes_file:
contents = recipes_file.readlines()
return contents
except Exception:
print('Problem reading recipes from file.')
|
60cf9ace8cd3cbcc40aae6fa5c1d2def50bf95b9
| 703,631 |
def GetNetworkConfig(has_external_ip, network):
"""Helper method to create a network config."""
network_interfaces = {
'network': network
}
if has_external_ip:
network_interfaces['accessConfigs'] = [{
'name': 'external-nat',
'type': 'ONE_TO_ONE_NAT'
}]
return network_interfaces
|
c0ee213c5c289fb2f6eb4b34fc18028233a1d162
| 703,633 |
from operator import inv
def zeros(a):
"""
Return the number of cleared bits in the sequence.
>>> assert zeros([0, 0]) == 2
>>> assert zeros([0, 1]) == 1
>>> assert zeros([1, 0]) == 1
>>> assert zeros([1, 1]) == 0
>>> assert zeros([1, 1, 1, 0, 1]) == 1
>>> assert zeros([0, 1, 0, 0, 0]) == 4
"""
return sum(inv(a))
|
76f041390dfe43bcc583e39fc7a3e3d761f87c25
| 703,634 |
def escape_special_char(string):
"""
Is called on all paths to remove all special characters but it's not good.
Should be moved in core
Should be called only in get_wrapper_path and unescape_special_char in get_entry
and in script += 'menu_click... in menu_click as it's already done
should replace -> by _>
"""
for r in (("\\", "\\\\"), ("\t", "\\t"), ("\n", "\\n"), ("\r", "\\r"), ("\v", "\\v"), ("\f", "\\f"), ('"', '\\"')):
string = string.replace(*r)
return string
|
cb3d4bd0d7370ec9c3d76543db8e3aafaf1bd8e8
| 703,635 |
from pathlib import Path
def fp_search_rglob(spt_root="../",
st_rglob='*.py',
ls_srt_subfolders=None,
verbose=False,
):
"""Searches for files with search string in a list of folders
Parameters
----------
spt_root : string
root folder to search in
st_rglob : string
search for files with this rglob string
ls_srt_subfolders : :obj:`list` of :obj:`str`
a list of subfolders of the spt_root to search in
verbose: bool
print details
Returns
-------
:obj:`list` of :obj:`str`
A list of file names
Examples
--------
>>> ls_spn = fp_search_rglob(spt_root="../",
>>> ls_srt_subfolders=['rmd', 'pdf'],
>>> st_rglob = '*d*.py')
[WindowsPath('../rmd/bookdownparse.py'), WindowsPath('../rmd/mattexmd.py'), WindowsPath('../rmd/rmdparse.py'), WindowsPath('../pdf/pdfgen.py')]
"""
# Directories to search in
if ls_srt_subfolders is None:
# ls_srt_subfolders = ['calconevar/', 'derivative/', 'derivative_application/',
# 'matrix_basics/',
# 'opti_firm_constrained/', 'opti_hh_constrained_brsv/',
# 'opti_hh_constrained_brsv_inequality/']
# ls_srt_subfolders = ['matrix_basics/']
ls_spt = [spt_root]
else:
ls_spt = [spt_root + srt_subf for srt_subf in ls_srt_subfolders]
if verbose:
print(ls_spt)
# get file names
ls_spn_found_tex = [spn_file for spt_srh in ls_spt
for spn_file in Path(spt_srh).rglob(st_rglob)]
if verbose:
print(ls_spn_found_tex)
return ls_spn_found_tex
|
e8fe03f9549ae77147ec96263411db9273d2c4cb
| 703,636 |
def get_minimum(feature):
"""Get minimum of either a single Feature or Feature group."""
if hasattr(feature, "location"):
return feature.location.min()
return min(f.location.min() for f in feature)
|
aec98f5bc065c6a97d32bc9106d67579f76f7751
| 703,637 |
def isUniqueSFW(str):
"""
Given a string, checks if the string has unique charachters
Note that this solution is inefficient as it takes O(n^2)
"""
l = len(str)
for i in range(l):
for j in range(l):
if i != j and not ord(str[i]) ^ ord(str[j]):
return False
return True
|
369eddfc360a2661e063183a30c9d511a5deb3de
| 703,638 |
def get_3x3_homothety(x,y,z):
"""return a homothety 3x3 matrix"""
a= [x,0,0]
b= [0,y,0]
c= [0,0,z]
return [a,b,c]
|
5c6c2d8931334cc13297e787a079499753c1976c
| 703,639 |
def scrape_to_list_value(scraped_rows, i, list_name):
"""insert row of rows of scraped data
input i for skipping rows
return value in dollars"""
to_scrape = scraped_rows[i::7]
list_name = []
for i in range(len(to_scrape)):
num = float(to_scrape[i][0].replace(',', '.'))
num_dollar = round((num * 1.14), 2)
list_name.append(num_dollar)
return list_name
|
62117d0d78a4fd691baa4163a19962c2fb1443d3
| 703,640 |
def get_nodes_from_vpc_id(vpc_id):
""" calculate node-ids from vpc_id. If not a vpc_id, then single node
returned
"""
try: vpc_id = int(vpc_id)
except ValueError as e: return ["%s" % vpc_id ]
if vpc_id > 0xffff:
n1 = (0xffff0000 & vpc_id) >> 16
n2 = (0x0000ffff & vpc_id)
return ["%s" % n1, "%s" % n2]
return ["%s" % vpc_id]
|
5c3a6506a721f9d518579df39a91ec38118d5e75
| 703,641 |
def ex_verb_voice(sent, ex_set, be_outside_ex=True):
"""
Finds verb voice feature.
1. One of the tokens in the set must be partisip - VBG
2. One of the tokens in the set must be lemma 'be'
3. VBN's head has lemma 'be'
If none of the tokens is verb, returns string 'None'
@param sent List of tokens in sentence.
@param ex_set set of nums in expression
@return string Active, Passive or None
"""
criteria_1 = False
criteria_2 = False
criteria_3 = False
verb_exists = False
_slice = []
for num in ex_set:
_slice.append(num-1)
if sent[num-1]['pos'] == 'VBN':
criteria_1 = True
if sent[int(sent[num-1]['head'])-1]['lemma'] == 'be':
criteria_3 = True
if sent[num-1]['lemma'] == 'be':
criteria_2 = True
if sent[num-1]['pos'][0] == 'V':
verb_exists = True
if criteria_1 and criteria_2 and criteria_3:
return 'Passive'
elif criteria_1 and criteria_3 and be_outside_ex:
_slice.sort()
return 'Passive'
elif verb_exists:
return 'Active'
else:
return 'None'
|
8891a792528af0c44865e4bbc63f269a85df4da9
| 703,642 |
def get_player_actions(game, player):
"""
Returns player's actions for a game.
:param game: game.models.Game
:param player: string
:rtype: set
"""
qs = game.action_set.filter(player=player)
return set(list(qs.values_list('box', flat=True)))
|
9b961afbee7c3a0e8f44e78c269f37a9b6613488
| 703,643 |
def create_lkas_ui(packer, main_on, enabled, steer_alert):
"""Creates a CAN message for the Ford Steer Ui."""
if not main_on:
lines = 0xf
elif enabled:
lines = 0x3
else:
lines = 0x6
values = {
"Set_Me_X80": 0x80,
"Set_Me_X45": 0x45,
"Set_Me_X30": 0x30,
"Lines_Hud": lines,
"Hands_Warning_W_Chime": steer_alert,
}
return packer.make_can_msg("Lane_Keep_Assist_Ui", 0, values)
|
16c226698160b14194daf63baf61bb3952e1cd59
| 703,644 |
import torch
def get_pytorch_device() -> torch.device:
"""Checks if a CUDA enabled GPU is available, and returns the
approriate device, either CPU or GPU.
Returns
-------
device : torch.device
"""
device = torch.device("cpu")
if torch.cuda.is_available():
device = torch.device("cuda:0")
return device
|
0109f3146c96bec08bbe6fa62e5a8bc5638e461c
| 703,645 |
import time
import random
def creat_order_num(user_id):
"""
生成订单号
:param user_id: 用户id
:return: 订单号
"""
time_stamp = int(round(time.time() * 1000))
randomnum = '%04d' % random.randint(0, 100000)
order_num = str(time_stamp) + str(randomnum) + str(user_id)
return order_num
|
339764f7dc943c46d959a9bfdc6c48dc9ecd6bef
| 703,646 |
def get_rst_title_char(level):
"""Return character used for the given title level in rst files.
:param level: Level of the title.
:type: int
:returns: Character used for the given title level in rst files.
:rtype: str
"""
chars = (u'=', u'-', u'`', u"'", u'.', u'~', u'*', u'+', u'^')
if level < len(chars):
return chars[level]
return chars[-1]
|
b646b9e0010d87ece7f5c8c53c8abf89ca557a21
| 703,647 |
import os
def toPath(prefix, metric):
"""Translate the metric key name in metric to its OS path location
rooted under prefix."""
m = metric.replace(".", "/") + ".wsp"
return os.path.join(prefix, m)
|
161ea82432c9e6a5e23ab9305133156ba35755f3
| 703,648 |
def get_sample_ids(fams):
""" create a ditionary mapping family ID to sample, to subID
Returns:
e.g {'10000': {'p': 'p1', 's': 's1'}, ...}
"""
sample_ids = {}
for i, row in fams.iterrows():
ids = set()
for col in ['CSHL', 'UW', 'YALE']:
col = 'SequencedAt' + col
if type(row[col]) == float:
continue
ids |= set(row[col].split(','))
# we want to refer to the individuals by 'p' or 's' for proband or
# sibling, since that is how they are represented in the de novo table
sample_ids[str(row.familyId)] = dict( (x[0], x) for x in ids )
return sample_ids
|
443e63b486a1bdb8a64595beda30f75468af7560
| 703,649 |
def calcbw(K, N, srate):
"""Calculate the bandwidth given K."""
return float(K + 1) * srate / N
|
13e99bcb729352feb66a34aac66e12b1c5e158ef
| 703,651 |
def format_sqlexec(result_rows, maxlen):
"""
Format rows of a SQL query as a discord message, adhering to a maximum
length.
If the message needs to be truncated, a (truncated) note will be added.
"""
codeblock = "\n".join(str(row) for row in result_rows)
message = f"```\n{codeblock}```"
if len(message) < maxlen:
return message
else:
note = "(truncated)"
return f"```\n{codeblock[:maxlen - len(note)]}```{note}"
|
3b98590c72245241ba488e07fdfdd20acae441cf
| 703,652 |
import re
def regex_sub_groups_global(pattern, repl, string):
"""
Globally replace all groups inside pattern with `repl`.
If `pattern` doesn't have groups the whole match is replaced.
"""
for search in reversed(list(re.finditer(pattern, string))):
for i in range(len(search.groups()), 0 if search.groups() else -1, -1):
start, end = search.span(i)
string = string[:start] + repl + string[end:]
return string
|
67e909778d9565d498fc3e7b3c9522378e971846
| 703,653 |
def _parse( filepath : str ) -> list:
"""
[summary]
Arguments:
filepath {str} -- [description]
Returns:
list -- [description]
"""
with open( filepath, 'r' ) as f:
raw_data = f.read( ) # not readlines( ), as this needs to be one long string
data = list( map( int, raw_data.split( ) ) )
return data
|
6814c4f45aee453f6387761ee7c4f3e64c669b1c
| 703,654 |
def stations_level_over_threshold(stations, tol):
"""Returns a list of the tuples, each containing the name of a station at which the relative
water level is above tol and the relative water level at that station"""
output = []
for station in stations:
relative_level = station.relative_water_level()
# the following raises an exception if relative_level is None
try:
if relative_level > tol:
output.append((station, relative_level))
except:
pass
# sort list by second value in descending order
output.sort(key=lambda x: x[1], reverse=True)
return output
|
87be1329ea8b7e58796ebfe33a6f9e9503777227
| 703,655 |
def deregister_device(device):
"""
Task that deregisters a device.
:param device: device to be deregistered.
:return: response from SNS
"""
return device.deregister()
|
44bec0e3ac356f150a0c4a6a0632939a20caafb0
| 703,656 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.