content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def quick_sort(nums):
"""
快速排序:
从数组中找出一个基准,把数组与基准比较分成大小两组,递归排序
时间复杂度:
O(n^2)
@param nums: 无序数组
@return: 升序数组
>>> import random
>>> nums = random.sample(range(-50, 50), 50)
>>> quick_sort(nums) == sorted(nums)
True
>>> quick_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
>>> quick_sort([])
[]
"""
if len(nums) < 2:
return nums
# cur = nums.pop()
cur = nums[0]
low_list = []
high_list = []
for num in nums[1:]:
(high_list if num > cur else low_list).append(num)
# if num > cur:
# high_list.append(num)
# else:
# low_list.append(num)
return quick_sort(low_list) + [cur] + quick_sort(high_list) | 447470d5bcd372958df82514dc20750a8fef56d4 | 211,717 |
def get_program_frames(command_dicts):
"""
Parces command_dicts to produce a list of frames that represent the
programs timestep
:param command_dicts: list formatted by mimic_program containing dicts of
program info at each program timestep
:return frames: list
"""
frames = []
for command in command_dicts:
frames.append(command['Frame'])
return frames | 8203b043752fad3ba379f21fa5114e2dcc98e830 | 484,543 |
def code() -> str:
"""
Example G-code module, a drawing of the number "5".
Please simulate first, before milling.
"""
return """
G90
G17
G00 X0 Y0
G00 X0 Y12.5
G02 I7.5 J0 X7.5 Y20
G00 X17.5 Y20
G02 I0 J-7.5 X25.001 Y12.5
G00 X25.001 Y0
G00 X45 Y0
G00 X45 Y20
""" | 5c84c5fdca6a3fce959a11f47716fde4db199edb | 85,781 |
def widget_type(field):
"""Determine a field's widget type on the fly.
:rtype: str
Example:
.. code::
{% if field|widget_type == "Textarea" %}
...
{% endif %}
"""
try:
return field.field.widget.__class__.__name__
except AttributeError:
return field.widget.__class__.__name__ | f53cdef299b2f945c98d30607abaeeab4307e912 | 65,461 |
def _boundaries_to_sizes(a, boundaries, axis):
"""Converting boundaries of splits to sizes of splits.
Args:
a: the array to be split.
boundaries: the boundaries, as in np.split.
axis: the axis along which to split.
Returns:
A list of sizes of the splits, as in tf.split.
"""
if axis >= len(a.shape):
raise ValueError('axis %s is out of bound for shape %s' % (axis, a.shape))
total_size = a.shape[axis]
sizes = []
sizes_sum = 0
prev = 0
for i, b in enumerate(boundaries):
size = b - prev
if size < 0:
raise ValueError('The %s-th boundary %s is smaller than the previous '
'boundary %s' % (i, b, prev))
size = min(size, max(0, total_size - sizes_sum))
sizes.append(size)
sizes_sum += size
prev = b
sizes.append(max(0, total_size - sizes_sum))
return sizes | 7aedf75a6431be5d613eea74f65677858cd5be70 | 289,006 |
def format_nmmpmat(denmat):
"""
Format a given 7x7 complex numpy array into the format for the n_mmp_mat file
Results in list of 14 strings. Every 2 lines correspond to one row in array
Real and imaginary parts are formatted with 20.13f in alternating order
:param denmat: numpy array (7x7) and complex for formatting
:raises ValueError: If denmat has wrong shape or datatype
:returns: list of str formatted in lines for the n_mmp_mat file
"""
if denmat.shape != (7, 7):
raise ValueError(f'Matrix has wrong shape for formatting: {denmat.shape}')
if denmat.dtype != complex:
raise ValueError(f'Matrix has wrong dtype for formatting: {denmat.dtype}')
#Now we generate the text in the format expected in the n_mmp_mat file
nmmp_lines = []
for row in denmat:
nmmp_lines.append(''.join([f'{x.real:20.13f}{x.imag:20.13f}' for x in row[:3]]) + f'{row[3].real:20.13f}')
nmmp_lines.append(f'{row[3].imag:20.13f}' + ''.join([f'{x.real:20.13f}{x.imag:20.13f}' for x in row[4:]]))
return nmmp_lines | a39dfac693e4acd7632deebef416d27cf18df71e | 691,392 |
import torch
def normalized_columns_initializer(weights, std=1.0):
"""
Weights are normalized over their column. Also, allows control over std which is useful for
initialising action logit output so that all actions have similar likelihood
"""
out = torch.randn(weights.size())
out *= std / torch.sqrt(out.pow(2).sum(1, keepdim=True))
return out | 14a648d2060aab510794b957c1d672f1c91b88ae | 261,593 |
import torch
def safe_cholesky(A, epsilon=1.0e-8):
"""
Equivalent of torch.linalg.cholesky that progressively adds
diagonal jitter to avoid cholesky errors.
"""
if A.shape == (1, 1):
return A.sqrt()
try:
return torch.linalg.cholesky(A)
except RuntimeError as e:
Aprime = A.clone()
jitter_prev = 0.0
for i in range(5):
jitter_new = epsilon * (10 ** i)
Aprime.diagonal(dim1=-2, dim2=-1).add_(jitter_new - jitter_prev)
jitter_prev = jitter_new
try:
return torch.linalg.cholesky(Aprime)
except RuntimeError:
continue
raise e | baf05fdb9da0f576b8973345cad5e96dae3c2b24 | 244,933 |
def convert_string_to_bool(value):
"""
Converts the string values "True" or "False" to their boolean
representation.
:param value: The string.
:type value: str.
:returns: True, False
"""
if(value != None) and ((value == True) or (value == "True") or (value == "true")):
return True
else:
return False | e9bd0b7139b26d7efb54124cd20c87de8e571174 | 251,891 |
def build_v07_spec(config_spec, project, email, zone, setup_project):
"""Create a v0.7 or later KFDef spec."""
gcp_plugin = None
for p in config_spec["spec"]["plugins"]:
if p["kind"] != "KfGcpPlugin":
continue
gcp_plugin = p
if not gcp_plugin:
raise ValueError("No gcpplugin found in spec")
gcp_plugin["spec"]["project"] = project
gcp_plugin["spec"]["email"] = email
gcp_plugin["spec"]["zone"] = zone
gcp_plugin["spec"]["skipInitProject"] = not setup_project
return config_spec | 1aa43bc9c167559548ede1eb94a24a86e5b33baa | 268,493 |
def string_edit_distance(s1, s2):
"""
Calculate the Levenshtein edit-distance between two strings.
The edit distance is the number of characters that need to be
substituted, inserted, or deleted, to transform s1 into s2. For
example, transforming "rain" to "shine" requires three steps,
consisting of two substitutions and one insertion:
"rain" -> "sain" -> "shin" -> "shine". These operations could have
been done in other orders, but at least three steps are needed.
:param s1, s2: The strings to be analysed
:type s1: str
:type s2: str
:rtype int
"""
def _edit_dist_init(len1, len2):
lev = []
for i in range(len1):
lev.append([0] * len2) # initialize 2-D array to zero
for i in range(len1):
lev[i][0] = i # column 0: 0,1,2,3,4,...
for j in range(len2):
lev[0][j] = j # row 0: 0,1,2,3,4,...
return lev
def _edit_dist_step(lev, i, j, c1, c2):
a = lev[i - 1][j] + 1 # skipping s1[i]
b = lev[i - 1][j - 1] + (c1 != c2) # matching s1[i] with s2[j]
c = lev[i][j - 1] + 1 # skipping s2[j]
lev[i][j] = min(a, b, c) # pick the cheapest
# set up a 2-D array
len1 = len(s1)
len2 = len(s2)
lev = _edit_dist_init(len1 + 1, len2 + 1)
# iterate over the array
for i in range(len1):
for j in range(len2):
_edit_dist_step(lev, i + 1, j + 1, s1[i], s2[j])
return lev[len1][len2] | 59c32d67558b76201457827c0251c10cc097f6be | 133,382 |
def list(conn):
""" Given an connection, return a list of providers. """
try:
return conn.get(url='/auth-providers')['providers']
except SystemError as e:
raise e | afc14be81cddc1492e7c095ffb94f3d55ff34acb | 274,649 |
def format_int(n: int) -> bytes:
"""Format an integer using a variable-length binary encoding."""
if n < 128:
a = [n]
else:
a = []
while n > 0:
a.insert(0, n & 0x7f)
n >>= 7
for i in range(len(a) - 1):
# If the highest bit is set, more 7-bit digits follow
a[i] |= 0x80
return bytes(a) | f9599fc66ab16a6285c5f0fc7f7a9ab5dc0080f3 | 491,443 |
def read_xml_schema(xml_schema):
""" returns xml_schema (XSD) file as a string """
with open(xml_schema, 'r') as schema_file:
schema = schema_file.read()
return schema | 86ef8651a0efb3c86aeed80964bc96a2d0485f82 | 350,034 |
import pytz
from datetime import datetime
def convert_unix_ts(timestamp, timezone = "Europe/Berlin"):
"""Utility function to help converting flespi utc unix time output to human readable.
Parameters:
-----------
timestamp: int
Unix time generated py flespi platform.
timezone: str
Time zone of the user. Defaoults to: Europe/Berlin
Returns:
--------
date: str
Human readable time with a following format: %Y-%m-%d %H:%M:%S
"""
timezone = pytz.timezone(timezone)
date = datetime.fromtimestamp(timestamp, timezone)
return date.strftime('%Y-%m-%d %H:%M:%S') | 0f869f311e41b26cc897c2c63611b9a09e4ddcb2 | 660,519 |
def tokenize(tokenizer, data, max_length = 128):
"""
Iterate over the data and tokenize it. Sequences longer than max_length are trimmed.
:param tokenizer: tokenizer to use for tokenization
:param data: list of sentences
:return: a list of the entire tokenized data
"""
tokenized_data = []
for sent in data:
tokens = tokenizer.encode(sent, add_special_tokens=True)
# keeping a maximum length of bert tokens: 512
tokenized_data.append(tokens[:max_length])
return tokenized_data | 30b3786c1299bc42cd2698eae83ce1c6bdc3cfbe | 15,834 |
def is_in_polygon(point, polygon):
"""
:param point: (lat, lng)
:param polygon: [point1, point2, point3, point4](points are ordered)
:return: True if point is in the polygon else False
"""
point_num = len(polygon)
if point_num < 3:
return False
result = False
for i in range(0, point_num):
point_one = polygon[i]
point_two = polygon[i - 1]
if (point_one[0] < point[0] <= point_two[0]) or (
point_two[0] < point[0] <= point_one[0]):
if (point_one[1] + (point[0] - point_one[0]) / (
point_two[0] - point_one[0]) * (
point_two[1] - point_one[1]) <
point[1]):
result = not result
return result | d708becdd74ea11c495132dd8f474ccb47227b4c | 151,479 |
def string_rotate(line: str, num_of_symbol: int) -> str:
"""
Function make left rotate for string
:param line: Line to rotate
:param num_of_symbol: Number of symbol to rotate
:return: Rotating line
"""
return line[num_of_symbol:] + line[:num_of_symbol] | f7cd8aa6979f8991714e4b82c95246f380e2e7af | 325,224 |
def get_nyquist_frequency(timedata):
"""returns the Nyquist frequency from time data"""
return (abs(0.5 * len(timedata) / timedata[-1] - timedata[0])) | 9b6a4a657b8586caf550455a284c506ec747e0af | 597,114 |
def order_synapses_by_section_number(cur,stype='chemical'):
"""
Returns synapses ordered by section number. Row format
[pre,post,sections,mid obj,continNum,IMG_Number,IMG_SectionNumber,X,Y]
Parameters
----------
cur : MySQLdb cursor
stype : str
synapse type : 'chemical' or 'electrical'
"""
sql = ("select pre,post,sections,mid,continNum,"
"object.IMG_Number,image.IMG_SectionNumber, "
"object.OBJ_X,object.OBJ_Y "
"from synapsecombined "
"join object on synapsecombined.mid = object.OBJ_Name "
"join image on image.IMG_Number = object.IMG_Number "
"where synapsecombined.type = '%s' "
"order by image.IMG_SectionNumber"
%stype)
cur.execute(sql)
return cur.fetchall() | 9323206be61a0e013a869d7d2fd1bf68a99a7109 | 373,953 |
def split_sample(labels):
"""
Split the 'Sample' column of a DataFrame into a list.
Parameters
----------
labels: DataFrame
The Dataframe should contain a 'Sample' column for splitting.
Returns
-------
DataFrame
Updated DataFrame has 'Sample' column with a list of strings.
"""
sample_names = labels["Sample"].str.split(" ", n=1, expand=False)
labels['Sample'] = sample_names
return labels | 483f1b78e07a2156aa3e48ae6c1f5ce41f5e60fe | 706,320 |
import json
def build_gh_issue_body(submission):
""" Build the body of a GitHub issue for the submission of a simulator
Args:
submission (:obj:`SimulatorSubmission`): simulator
Returns:
:obj:`str`: body for a GitHub issue for the submission of a simulator
"""
return "\n".join([
"---",
"id: {}".format(submission.id),
"version: {}".format(submission.version),
"specificationsUrl: {}".format(submission.specifications_url),
"specificationsPatch: {}".format(json.dumps(submission.specifications_patch)),
"validateImage: {}".format(submission.validate_image),
"commitSimulator: {}".format(submission.commit_simulator),
"",
"---",
]) | 430ec1007f0cd8b5b4a7c26f526ddb09d2ae8eb8 | 192,048 |
def get_attributes(message):
"""
Return a dictionary of the message attributes.
"""
return {key: value['string_value']
for key, value in message[0].message_attributes.iteritems()} | df6668560a74a7b49b936e89cb0c11f20de630b0 | 149,309 |
def _trim_bounds(arr):
""" Returns the bounds which would be used in numpy.trim_zeros """
first = 0
for i in arr:
if i != 0.0:
break
else:
first = first + 1
last = len(arr)
for i in arr[::-1]:
if i != 0.0:
break
else:
last = last - 1
return first, last | 27c3dfab5fd111303b6df9d02bca9c9a7ff8720f | 181,979 |
def cstr2str(cs, encoding='utf8'):
"""Convert a null-terminated C-string bytes to a Python string"""
return cs.split(b'\0', 1)[0].decode(encoding) | fe9d94b8ec7474c369c0b50a11f94f76f6f161d4 | 443,313 |
def splitValues(txt, sep=",", lq='"<', rq='">'):
"""
Helper function returns list of delimited values in a string,
where delimiters in quotes are protected.
sep is string of separator
lq is string of opening quotes for strings within which separators are not recognized
rq is string of corresponding closing quotes
"""
result = []
cursor = 0
begseg = cursor
while cursor < len(txt):
if txt[cursor] in lq:
# Skip quoted or bracketed string
eq = rq[lq.index(txt[cursor])] # End quote/bracket character
cursor += 1
while cursor < len(txt) and txt[cursor] != eq:
if txt[cursor] == '\\': cursor += 1 # skip '\' quoted-pair
cursor += 1
if cursor < len(txt):
cursor += 1 # Skip closing quote/bracket
elif txt[cursor] in sep:
result.append(txt[begseg:cursor])
cursor += 1
begseg = cursor
else:
cursor += 1
# append final segment
result.append(txt[begseg:cursor])
return result | 78e383d1a80910e9849767e992bf54c4cf72630a | 63,448 |
def is_array_of(thing):
""" Is thing an Array? """
return hasattr(thing.type_(), "is_array_of") | d0f7e59e0113d2cd13b4585e1d7a5a0a9c2b3a6d | 180,121 |
def aggregate_ravens(data, sub_num):
"""
Aggregate data from the Raven's Matrices task.
Calculates various summary statistics for the Raven's Matrices task for a
given subject.
Parameters
----------
data : dataframe
Pandas dataframe containing a single subjects trial data for the task.
sub_num : str
Subject number to which the data file belongs.
Returns
-------
stats : list
List containing the calculated data for the subject.
"""
ravens_rt = data["RT"].mean()
ravens_count = data["correct"].sum()
ravens_num_items = data.shape[0]
ravens_prop = ravens_count / ravens_num_items
return [sub_num, ravens_rt, ravens_count, ravens_prop, ravens_num_items] | 35a4f2d1b080d8ddec77e9d42c84eae0463d20d0 | 616,718 |
import json
def _add_to_entrypoint(cmd):
"""Return command to add `cmd` to the container's entrypoint."""
base_cmd = "sed -i '$i{}' $ND_ENTRYPOINT"
escaped_bash_cmd = json.dumps(cmd)[1:-1]
return base_cmd.format(escaped_bash_cmd) | bfff78dec9c904bdf98f3dd600e4f40105e2601f | 343,491 |
def is_end(connectivity):
"""
Returns True if connectivity corresponds to an endpoint (is one).
:param connectivity: Scalar or matrix
:return: Boolean or matrix of boolean
"""
return connectivity == 1 | db0999e86376d4415638bda9bf344038a40a0b2b | 294,275 |
import io
def util_load_txt(path: str):
"""
Utility to load text data from a local folder.
"""
with io.open(path, mode='r', encoding='utf-8') as file:
return file.read() | bfd40809fcd207a036b8675bb9e97e8c4677217a | 336,132 |
def _app_id(app_id):
"""
Make sure the app_id is in the correct format.
"""
if app_id[0] != "/":
app_id = "/{}".format(app_id)
return app_id | 5aa54cc06584380d8a99cd5abea06d79324b72c3 | 532,620 |
def modevaltohex(mode_val):
""" convert mode_val value that can be either xeh string or int to a hex string """
if isinstance(mode_val, int):
return (hex(mode_val)[2:]).upper()
if isinstance(mode_val, str):
return mode_val
return None | 1b8341f3b096dcbba9a14ad225cca7732296650b | 532,095 |
def curvature_mean(curvatures_per_phase):
""" Given the curvatures along pp for each phase, calculate mean curvature
"""
# Mean curvature per phase (1 value per phase)
mean_curvature_per_phase = []
for curvatures in curvatures_per_phase:
mean_curvature_per_phase.append(float(curvatures.mean()))
# stats
mean_curvature_phase_min = min(mean_curvature_per_phase)
mean_curvature_phase_max = max(mean_curvature_per_phase)
mean_curvature_phase_change = mean_curvature_phase_max - mean_curvature_phase_min
return (mean_curvature_per_phase, mean_curvature_phase_min, mean_curvature_phase_max,
mean_curvature_phase_change ) | d6c6c48555ee76fe5f26c72d860ac0c0594456c5 | 410,855 |
def pprEvent(e):
"""Pretty print an event"""
return e.event | 8c91f124b3f4bffa2ea20d1f0bc2385cd99c2e52 | 491,329 |
import json
def read_dict(filepath, encoding='utf-8'):
"""
Read a dictonary from a JSON file.
:param str filepath: Path to file
:param str encoding: File encoding to use
:returns: The dictionary
:rtype: dict
"""
with open(filepath, mode='r', encoding=encoding) as f:
return json.loads(f.read()) | d57320a42ad2f37420479868eec45c79a9241284 | 198,951 |
def scale_simulation_fit(simulated_value, actual_value, number_individuals, total_individuals):
"""
Calculates goodness of fit for the provided values, and scales based on the total number of individuals that exist.
The calculation is 1 - (abs(x - y)/max(x, y)) * n/n_tot for x, y simulated and actual values, n, n_tot for metric
and total
number of individuals.
:param simulated_value: the simulated value of the metric
:param actual_value: the actual value of the metric
:param number_individuals: the number of individuals this metric relates to
:param total_individuals: the total number of individuals across all sites for this metric
:return: the scaled fit value
"""
return (
(1 - (abs(simulated_value - actual_value)) / max(simulated_value, actual_value))
* number_individuals
/ total_individuals
) | 04f6364012c044387ab4007941321a655450e232 | 57,684 |
def infer(runner, input_tensors):
""" Run loaded subgraphs.
Args:
runner: an instance of Runner.
input_tensors: Input tensors. Format: {name: value}.
Returns:
Output tensors. Format: {name: value}.
"""
return runner.infer(input_tensors) | a8f497052be34ffc9191ae072f2d9355214c4fbe | 593,387 |
def isabs(s):
"""Test whether a path is absolute"""
return s.startswith('/') | 41d69b168a47829f8fd4b213624fca7f8682b022 | 671,252 |
def _IsLongMacro(command):
"""Checks whether a command is a long macro."""
if len(command) == 3 and command[0] == "LONG" and command[1] == "MACRO":
return True
return False | 2962e1b892214c28d5a44110d9c787ac7429be12 | 178,489 |
def node_to_internal_type(node):
"""
Use the internal_type property of a node (bblfsh.Node) as its final path representation
:param node: base_node
:return: node's internal_type or the string itself (in case its UP/DOWN token or a leaf)
"""
if type(node) == str:
return node
return node.internal_type | b692b21889bb48c6f014c4c1749e76b9e27c6e41 | 339,571 |
def keyval_list_to_dict(l):
"""
Converts a list of key=value strings to a dictionary.
:param l: the list
:return: the dictionary
"""
stripped = lambda s: s.strip('"').strip("'")
d = {}
for e in l:
keyval = e.split("=", 2)
if len(keyval) == 2:
d[stripped(keyval[0])] = stripped(keyval[1])
return d | 1bb778f9c67ca2606b9acbf75625102fef8f664a | 264,863 |
def get_enabled_connection_subnets(connection):
"""Retrieve configured as enabled subnets for given connection.
Args:
connection (dict): A connection object that has agent_connection_services injected.
Returns:
set: A set of enabled agent service subnet ids
"""
return {
subnet["agent_service_subnet_id"]
for subnet in connection.get("agent_connection_services", {}).get(
"agent_connection_subnets", []
)
if subnet["agent_connection_subnet_is_enabled"]
} | 000170dc640d8f429b1ff807308e117bec2c12c9 | 448,711 |
def project(atts, row, renaming={}):
"""Create a new dictionary with a subset of the attributes.
Arguments:
- atts is a sequence of attributes in row that should be copied to the
new result row.
- row is the original dictionary to copy data from.
- renaming is a mapping of names such that for each k in atts,
the following holds:
- If k in renaming then result[k] = row[renaming[k]].
- If k not in renaming then result[k] = row[k].
- renaming defaults to {}
"""
res = {}
for c in atts:
if c in renaming:
res[c] = row[renaming[c]]
else:
res[c] = row[c]
return res | ccc07b789ff510b3bdddfccc95d6e29721c15786 | 350,661 |
def sizeof_fmt(num):
"""
Return a human readable string describing the size of something.
:param num: the number in machine-readble form
:type num: int
:param base: base of each unit (e.g. 1024 for KiB -> MiB)
:type base: int
:param suffix: suffix to add. By default, the string returned by sizeof_fmt() does not contain a suffix other than 'K', 'M', ...
:type suffix: str
"""
for unit in ['B', 'KiB', 'MiB', 'GiB']:
if num < 1024:
return "%3.1f%s" % (num, unit)
num /= 1024.0
return "%3.1f%s" % (num, 'Ti') | 1812ffc70897fcfac420479419fd75aca61ccc2e | 280,196 |
def is_valid_cord(x, y, w, h):
"""
Tell whether the 2D coordinate (x, y) is valid or not.
If valid, it should be on an h x w image
"""
return x >=0 and x < w and y >= 0 and y < h | 9dff108ffd3f6baf16eb729c9acb672ed1f93e9b | 600,101 |
def median(data):
"""Calculate the median of a list."""
data.sort()
num_values = len(data)
half = num_values // 2
if num_values % 2:
return data[half]
return 0.5 * (data[half-1] + data[half]) | 740255e4873459dbbbab3de6bba908eecc2b1837 | 535,877 |
def compare_languge(language, lang_list):
"""
Check if language is found
"""
found = False
for l in lang_list:
if language == l.lower():
found = True
break
return found | bd9f95167e719e490fb770ba62668a313ece8f0e | 358,581 |
def to_instance_format(hub: str, group: str, project: str) -> str:
"""Convert input to hub/group/project format."""
return f"{hub}/{group}/{project}" | 40c979c1791b6fb8078738eeac1a1907377962b6 | 117,981 |
def titles(posts):
"""Get a set of post titles from a list of posts."""
return set(p["title"] for p in posts) | 389b5f85028c57773a68d95fd357ddea7b3ea4ca | 564,044 |
def distance(dna_strand1, dna_strand2):
"""Calculate hamming distance between two DNA strands."""
if len(dna_strand1) != len(dna_strand2):
raise ValueError
counter = 0
for i in range(len(dna_strand1)):
if dna_strand1[i] != dna_strand2[i]:
counter += 1
return counter | e4546d0d0e06c67347d013880ded3431db2c3c60 | 214,911 |
from typing import List
def check_urls_in_file(filename: str, urls: List[str]) -> List[List[str]]:
"""Get any occurrence of the specified URLs in the specified file
:param filename: The file to scan
:param urls: The URLs to find in the file
:return: List of URLs found and in which file, e.g. [['https://test.com', '/source/hello.md']]
"""
found = []
with open(filename) as f:
contents = f.read()
for url in urls:
if contents.find(url) != -1:
found.append([url, filename])
return found | 452ba80bd2c1c0fef41b80388610c37d86547ab0 | 522,152 |
def make_rnn_for_scan(rnn, params):
"""Scan requires f(h, x) -> h, h, in this application.
Args:
rnn : f with sig (params, h, x) -> h
params: params in f() sig.
Returns:
f adapted for scan
"""
def rnn_for_scan(h, x):
h = rnn(params, h, x)
return h, h
return rnn_for_scan | 98b29d4814ab8404ac80b1dfcc09d96e10b92feb | 189,921 |
import uuid
def gen_token(max_length=5):
"""
Generate a random token.
"""
return uuid.uuid4().hex[:max_length] | 97eb9e90c62495939a95587daf1812cbde713cd9 | 598,154 |
import re
def filter_vowel_cons_ratio(word, ratio=0.5):
"""Return True if the ratio of vowels to consonants is > `ratio`.
This can be used as an ad-hoc pronunciation filter.
:param word (str): The word
:param ratio (float, optional): The ratio
:rtype: int
"""
vowels = re.compile(r'[aeiouy]')
consonants = re.compile(r'[^aeyiuo]')
vmatch = re.findall(vowels, word.lower())
cmatch = re.findall(consonants, word.lower())
_ratio = float(len(vmatch)) / float(len(cmatch))
return _ratio > ratio | 0bb87d6b6d40f83c9826eb0988888a9c1105db3b | 19,728 |
import torch
from warnings import warn
def device_available(device: str) -> bool:
"""
Check if the given device is available to use.
If it is not available, a warning is given.
:param device: device on that the training should run
:type device: str
:return: True, if the device is available, False otherwise
:rtype: bool
"""
if "cuda" in device and not torch.cuda.is_available():
warn("CUDA device cannot be found.")
return False
return True | 98d2a45a89730fab6003004bc8f0160268f4321e | 355,301 |
from typing import Set
def select_define(defines: Set[str], family_header: str) -> str:
"""Selects valid define from set of potential defines.
Looks for the defines in the family header to pick the correct one.
Args:
defines: set of defines provided by `parse_product_str`
family_header: `{family}.h` read into a string
Returns:
A single valid define
Raises:
ValueError if exactly one define is not found.
"""
valid_defines = list(
filter(
lambda x: f'defined({x})' in family_header or f'defined ({x})' in
family_header, defines))
if len(valid_defines) != 1:
raise ValueError("Unable to select a valid define")
return valid_defines[0] | fafd14907ad98f84c2f019441a181afc54855c24 | 70,388 |
def to_bytestring (s):
"""Convert the given unicode string to a bytestring, using the standard encoding,
unless it's already a bytestring"""
if s:
if isinstance(s, str):
return s
else:
return s.encode('utf-8') | 26be74aac5ef8d18ce512e535b2acfe633577548 | 572,313 |
def linearly_increasing_force(t_start, t_end, f_max):
"""
Returns a linearly increasing force:
f_max at t_end
-------------
/
/ |
/ |
/ |
---- |__ t_end
|__ t_start
Parameters
----------
t_start: float
time where linear force starts to raise
t_end: float
time where force reaches maximum
f_max: float
maximum value of force
Returns
-------
f: callable
function f(t)
"""
def f(t):
if t <= t_start:
return 0.0
elif t_start < t <= t_end:
return f_max * (t-t_start) / (t_end-t_start)
else:
return f_max
return f | ee4c541662cee2f72280b1d039993a172c0fa7f8 | 119,554 |
def clamp(number: int, max_value: int, min_value: int) -> int:
""" Clamp value into a range """
return max(min(number, max_value), min_value) | addfdea377cdf40501ef3aeabbb421316b0083d8 | 109,950 |
import hashlib
def md5_hash(data_bytes):
"""
Hash the specified byte array with the MD5 algorithm
:param data_bytes: The byte array to hash
:return: The hash of the byte array
"""
return hashlib.md5(data_bytes).hexdigest() | f03c84c8ffcfbd79266f9e17d25b36b3db2b1985 | 475,895 |
def unpack3(var, struct_var, buff):
"""
Create an unpack call on the ``struct.Struct`` object with the name
``struct_var``.
:param var: variable the stores the result of unpack call, ``str``
:param str struct_var: name of the struct variable used to unpack ``buff``
:param buff: buffer that the unpack reads from, ``StringIO``
"""
return '%s = %s.unpack(%s)' % (var, struct_var, buff) | 64af84415b6ea6a97bab0797ad5e44923d457fcb | 636,181 |
def parse_benchmark_name(name: str):
"""
Parses a template benchmark name with a size
>>> parse_benchmark_name('BM_Insert_Random<int64_t, int64_t, std::unordered_map>/1000')
('BM_Insert_Random', ['int64_t', 'int64_t', 'std::unordered_map'], 1000)
"""
base_name = name[0 : name.find('<')]
t_params = [ x.strip() for x in name[name.find('<') + 1 : name.find('>')].split(',')]
size = int(name[name.find('/') + 1:])
return base_name, t_params, size | 1628d67272a33078dd9b2c5b105f530552bd1776 | 118,768 |
def cat_matrices2D(mat1, mat2, axis=0):
"""Concatenates two matrices along a specific axis"""
ans = []
if axis == 0 and len(mat1[0]) == len(mat2[0]):
return mat1 + mat2
elif axis == 1 and len(mat1) == len(mat2):
for i in range(len(mat1)):
ans.append(mat1[i] + mat2[i])
return ans
return None | 88b5ebe9079e8fbf2e9b6da3ed2c8db2227e7719 | 160,606 |
import itertools
def flatten(iterable):
"""Concatenate several iterables."""
return itertools.chain.from_iterable(iterable) | 868ef9e0bd02d7c0c67d096c74c8eb69d87b2bfa | 642,461 |
def parse_mime_type(mime_type):
"""Carves up a mime-type and returns a tuple of the (type, subtype, params) where
'params' is a dictionary of all the parameters for the media range. For example, the
media range 'application/xhtml;q=0.5' would get parsed into:
('application', 'xhtml', {'q', '0.5'})
"""
parts = mime_type.split(";")
params = dict([tuple([s.strip() for s in param.split("=")]) for param in parts[1:]])
full_type = parts[0].strip()
# Java URLConnection class sends an Accept header that includes a single "*"
# Turn it into a legal wildcard.
if full_type == "*":
full_type = "*/*"
(type, subtype) = full_type.split("/")
return (type.strip(), subtype.strip(), params) | 746153d8f6b14b403a2f36bbce18417305d95ee0 | 538,123 |
def median(x):
"""Finds the median value of data set x"""
x_sorted = sorted(x)
mid = len(x) // 2
if len(x) % 2 == 1:
return x_sorted[mid]
else:
l = mid - 1
h = mid
return (x_sorted[l] + x_sorted[h]) / 2 | 87395bcbc1bc4800318a61cf7c4d3dbdc925486a | 62,531 |
def from_gm_timestamp(timestamp):
"""Convert timestamp in microseconds to timestamp in seconds."""
return int(timestamp) // 1000000 | 7ce61f6435f832efc1224ea39fb66aca1d829c24 | 186,023 |
def _fmt_unique_name(appname, app_uniqueid):
"""Format app data into a unique app name.
"""
return '{app}-{id:>013s}'.format(
app=appname.replace('#', '-'),
id=app_uniqueid,
) | ebbc78dd656065acf94d212a5f6e2badbd466b39 | 177,811 |
def gpfInfo(fileName):
"""
Get information on a gpc/gpf file.
:Arguments:
- fileName: name of the file to read
:Returns:
- contours: number of contours
- holes: number of holes (if contained)
- points: total number of points
- withHoles: file contains hole-flags
"""
f = open(fileName, 'r')
contours = int(f.readline())
holes = 0
points = 0
withHoles = True
for c in range(contours):
pp = int(f.readline())
x = 0
if c == 0:
# check for hole-flags
try:
holes += int(f.readline())
except:
withHoles = False
x = 1
else:
if withHoles:
holes += int(f.readline())
[ f.readline() for p in range(pp-x) ]
points += pp
f.close()
return contours, holes, points, withHoles | 8d88eda19ed783337eff2ad7497b773ca08c4566 | 500,472 |
def is_core_type(type_):
"""Returns "true" if the type is considered a core type"""
return type_.lower() in {
'int', 'long', 'int128', 'int256', 'double',
'vector', 'string', 'bool', 'true', 'bytes', 'date'
} | 3ef8c43869c0eb717cca04defd69a569a38f4afa | 217,102 |
import requests
import logging
def get_data_from_url(url, timeout=10):
"""Get data from URL"""
try:
response = requests.get(url, timeout=timeout)
return response.text
except requests.exceptions.RequestException as ex:
logging.error(ex) | 0da66c91dc8208696a890027c92d5d9381db98a6 | 353,985 |
import collections
import torch
def imdict_to_img(img_dict, n_per_row=8, n_rows=1):
"""Returns an image where each row corresponds to a key in the dictionary.
Values are expected to be of format BxCxHxW.
"""
od = collections.OrderedDict(sorted(img_dict.items()))
imgs = torch.stack(list(od.values()), dim=0) # AxBxCxHxW
# make the rows
imgs = torch.stack([imgs[:, i*n_per_row:(i+1)*n_per_row] for i in range(n_rows)], dim=0) # n_rows x A x n_per_row x CxHxW
imgs = imgs.flatten(0,2)
return imgs | 44f852da172089994d7c0b6a070d4df3686efbfa | 230,997 |
from typing import Iterable
def write_vocab(vocab: Iterable[str], fname: str) -> str:
"""
Write the vocabulary to the fname, one entry per line
Mostly for compatibility with transformer BertTokenizer
"""
with open(fname, "w") as sink:
for v in vocab:
sink.write(v + "\n")
return fname | 768a62193b4e0dc2f646d07a9898041128a254d8 | 514,293 |
def get_range_to_list(range_str):
"""
Takes a range string (e.g. 123-125) and return the list
"""
start = int(range_str.split('-')[0])
end = int(range_str.split('-')[1])
if start > end:
print("Your range string is wrong, the start is larger than the end!", range_str)
return range(start, end+1) | a88d9780ac2eba1d85ae70c1861f6a3c74991e5c | 399 |
import base64
import bz2
def encode(payload):
"""Encode a string for tranmission over the network using base64 encoding of the bz2 compressed string.
We bz2 compress because we can and also to counteract the inefficiency of the base64 encoding.
Args:
payload(str): string we want to transmit over the wire
Returns:
str: base64 encoded, bz2 compressed string
"""
return base64.urlsafe_b64encode(bz2.compress(payload.encode('utf-8'))).decode('utf-8') | 098f65b18bb127e3414ec37267e010f5d927c059 | 528,338 |
def strip_tsv(path):
"""
Strip unnecesaty lines from the given result TSV file.
"""
def keep(line):
"""
Returns false if the given line should be stripped.
"""
if line.startswith("Files already downloaded"): return False
elif line.startswith("Train: epoch = ") : return False
else : return True
# Create stripped text.
text = "\n".join([line.rstrip() for line in path.open("rt") if keep(line)])
# Overwrite to the file.
path.write_text(text)
print(path, "done") | 35c79df28a12342fc99071d1c2876e090f5e147b | 530,727 |
def fill(lst, mold, subs):
"""For every <mold> element in <lst>, substitute for the according
<subs> value (indexically). """
nlst = list(lst).copy()
j = 0
for i, elem in enumerate(lst):
if elem == mold:
nlst[i] = subs[j]
j += 1
return nlst | 359b278899da936c15c6a8fe63e34649204ff7f7 | 591,678 |
def alphabetize(value):
"""Lowercases, then alphabetizes, a list of strings"""
if isinstance(value, list) and all(isinstance(s, str) for s in value):
return sorted([s.lower() for s in value])
else:
raise TypeError("Argument must be a list of strings") | 636bec3db5966020549b0a5e73132c3bab6d7a37 | 255,136 |
def get_source(cell):
"""Gets the source code of a cell in a way that works for both nbformat and JSON
Args:
cell (``nbformat.NotebookNode``): notebook cell
Returns:
``list`` of ``str``: each line of the cell source
"""
source = cell['source']
if isinstance(source, str):
return cell['source'].split("\n")
elif isinstance(source, list):
return [l.strip() for l in source]
assert False, f'unknown source type: {type(source)}' | ed404a944c1c606967c2dc8c73d615c6a6256778 | 389,319 |
def exception_models_to_message(exceptions: list) -> str:
"""Formats a list of exception models into a single string """
message = ""
for exception in exceptions:
if message: message += "\n\n"
message += f"Code: {exception.code}" \
f"\nMessage: {exception.message}" \
f"\nSeverity: {exception.severity}" \
f"\nData: {exception.data}"
return message | 56f40ab1fe0d1a03abeaa08d1f9898c7abdb0552 | 15,205 |
def _compat_compare_digest(a, b):
"""Implementation of hmac.compare_digest for python < 2.7.7.
This function uses an approach designed to prevent timing analysis by
avoiding content-based short circuiting behaviour, making it appropriate
for cryptography.
"""
if len(a) != len(b):
return False
# Computes the bitwise difference of all characters in the two strings
# before returning whether or not they are equal.
difference = 0
for (a_char, b_char) in zip(a, b):
difference |= ord(a_char) ^ ord(b_char)
return difference == 0 | 4eac07f6cf3c02f79ee7361edbf503ecab4d4526 | 548,411 |
def ones_list(n):
"""Return a list of n ones."""
l = [1 for x in range(n)]
return l | 75ae14cdacaf5ee96850df9854079854d8b7b5d0 | 330,330 |
import copy
import random
def strategy_func_random(zmws):
"""
>>> random.seed(12345); strategy_func_random([])
[]
>>> random.seed(12345); strategy_func_random([('synthetic/1', 9)])
[('synthetic/1', 9)]
>>> random.seed(12345); strategy_func_random([('synthetic/1', 9), ('synthetic/2', 21), ('synthetic/3', 9), ('synthetic/4', 15), ('synthetic/5', 20)])
[('synthetic/5', 20), ('synthetic/3', 9), ('synthetic/2', 21), ('synthetic/1', 9), ('synthetic/4', 15)]
"""
ret = copy.deepcopy(zmws)
random.shuffle(ret)
return ret | 8fe4bca9239d9da68db5c3bd8f40f1b42175d0cc | 592,111 |
def select_from(items, indexes):
"""
:param items: a list of items.
:param indexes: an iterable of indexes within `items`.
:returns: a list of the items corresponding to the indexes.
"""
return [items[i] for i in indexes] | 91edeb1cfdeaa2e57abbf0bb3f599c6855953b37 | 56,571 |
def get_submodule_by_path(module, path):
"""
Return a sub-module by its name.
The path may refer to any nested node using '/' as the path delimiter.
"""
# Separate out the next module's name
parts = path.split('/', 1)
name = parts[0]
sub_path = parts[1] if len(parts) == 2 else None
if hasattr(module, name):
submodule = getattr(module, name)
if sub_path is None:
return submodule
return get_submodule_by_path(module=submodule, path=sub_path)
raise KeyError(f'No module named "{name}" found.') | 9e115fe2c1992474a771a53bf65bc43aaf93b72a | 504,167 |
def S_crop_values(_data_list, _max, _min):
"""
Returns a filtered data where values are discarded according to max, min limits.
"""
f_data = []
ds = len(_data_list)
i = 0
while i < ds:
if _data_list[i] >= _max:
f_data.append(_max)
elif _data_list[i] <= _min:
f_data.append(_min)
else:
f_data.append(_data_list[i])
i += 1
return f_data | 2e5eac918d16c9a25009d368308782fdb300eea0 | 607,376 |
def video_sort(videos, key, keyType=str, reverse=False):
"""
Given a list of video records that are dotty dictionaries return back a
sorted version that is sorted based on the provided key. The keys will be
converted using the given key type during the sort for comparison purposes.
This is a very simple wrapper on a standard function, but the plan is to
also implement filtering at some point in the future as well.
"""
return sorted(videos, key=lambda k: keyType(k[key]), reverse=reverse) | 6cee2fa9c332b7a3601ce63aa959424167a9065a | 78,708 |
def to_tuple(collection):
"""
Return a tuple of basic Python values by recursively converting a mapping
and all its sub-mappings.
For example::
>>> to_tuple({7: [1,2,3], 9: {1: [2,6,8]}})
((7, (1, 2, 3)), (9, ((1, (2, 6, 8)),)))
"""
if isinstance(collection, dict):
collection = tuple(collection.items())
assert isinstance(collection, (tuple, list))
results = []
for item in collection:
if isinstance(item, (list, tuple, dict)):
results.append(to_tuple(item))
else:
results.append(item)
return tuple(results) | 45aae0c4b3e7c5f2c0e3c0b19a7eb897b4875c35 | 275,407 |
def schema(schema_id):
"""
Decorator to assign a schema name to an endpoint handler.
"""
def decorator(handler):
handler.__schema_id__ = schema_id
return handler
return decorator | f12acaef56405be83755fd01a50a821b7e7c227e | 236,058 |
def expected_win(theirs, mine):
"""Compute the expected win rate of my strategy given theirs"""
assert abs(theirs.r + theirs.p + theirs.s - 1) < 0.001
assert abs(mine.r + mine.p + mine.s - 1) < 0.001
wins = theirs.r * mine.p + theirs.p * mine.s + theirs.s * mine.r
losses = theirs.r * mine.s + theirs.p * mine.r + theirs.s * mine.p
return wins - losses | 92de2010287e0c027cb18c3dd01d95353e4653c4 | 2,144 |
def axis_converter(total_axis: int, axis: int):
"""
Calculate axis using `total_axis`.
For axis less than 0, and greater than 0.
Parameters
----------
total_axis : int
Total axis num.
axis : int
Current axis num.
Returns
-------
int
Calculated current axis.
"""
if axis < 0:
return total_axis + axis
else:
return axis | 16af5dd91111a91a5cd3e0eb2c9709493d341384 | 377,646 |
def calc_sos(x,y):
"""
Calculate the sum-of-squared error for two lists of numbers, x and y.
returns sos = ∑(x-y)²
"""
xy = list(zip(*[x,y]))
sos = sum([(x-y)**2 for x,y in xy])
return sos | d882f8980416f04158df2286a020268ebe9a8d7f | 287,365 |
def gauss_fill(std):
"""Gaussian fill helper to reduce verbosity."""
return ('GaussianFill', {'std': std}) | afa06a76157cf287e669fbe3be4757dc3d823c17 | 612,309 |
def popular_articles_query(limit=None):
"""Return an SQL string to query for popular articles.
Args:
limit (int): The maximum number of results to query for. If
ommited, query for all matching results.
Returns:
str: An SQL string. When used in a query, the result will contain
two columns:
- str: The article's name.
- str: The number of page visits (e.g. "1337 views").
"""
return """
SELECT title, format('%s views', count(*)) AS views
FROM log
JOIN articles ON log.path = ('/article/' || articles.slug)
GROUP BY articles.title
ORDER BY count(*) DESC
LIMIT {number};
""".format(number=limit or 'ALL') | baa5ed8e7ee50ab5e3d58c8a4b9b7571298353f8 | 304,981 |
def somatorio(n):
"""
Função recursiva que recebe um valor inteiro n >= 0, e devolve o somatório de 0 até n.
Exemplos:
------------
somatorio(0) deve devolver 0;
somatorio(2) deve devolver 3, pois 0+1+2 = 3;
somatorio(5) deve devolver 15, pois 0+1+2+3+4+5 = 15;
Retorno:
-----------
int: soma dos números inteiros de 0 até n.
"""
if n == 0:
return 0
else:
return n + somatorio(n-1) | 4a3852afa1f04d77fbd6b1581802ed47a9ff1950 | 76,438 |
def XYZ_to_xy(XYZ):
"""Convert XYZ to xy
Args:
XYZ ([float, float, float]: X, Y, Z input values
Returns:
.[float, float]
"""
X, Y, Z = XYZ
divider = (X + Y + Z)
x = X / divider
y = Y / divider
return [x, y] | cc41bd7dda4339c813619171d2a885c420a276a5 | 19,770 |
def flatten(nested):
"""
flattens a nested list
>>> flatten([['wer', 234, 'brdt5'], ['dfg'], [[21, 34,5], ['fhg', 4]]])
['wer', 234, 'brdt5', 'dfg', 21, 34, 5, 'fhg', 4]
"""
result = []
try:
# dont iterate over string-like objects:
try:
nested + ''
except(TypeError):
pass
else:
raise TypeError
for sublist in nested:
for element in flatten(sublist):
result.append(element)
except(TypeError):
result.append(nested)
return result | 3634057e2dbae0ef98fd215cd810ff314667dc80 | 670,552 |
def manageSource(cursor, ref_citation, ref_link):
"""
Testing whether one source and its associated link exist in the database, if not insert it in the database
Parameters
-----------
cursor: psycopg2 cursor
cursor for the current operations in the database
ref_citation: str
complete text describing the reference
ref_link
URL link to the reference ressources
Returns
------------
return the cd_ref to the reference
"""
# Does the source exist
if ref_link == ' ':
ref_link = None
SQL = "SELECT count(*) FROM refer WHERE citation = %s"
cursor.execute(SQL, [ref_citation])
nb, = cursor.fetchone()
cit_exists = bool(nb)
if cit_exists:
SQL = "SELECT cd_ref FROM refer WHERE citation = %s"
cursor.execute(SQL, [ref_citation])
cdRef, = cursor.fetchone()
else:
# insertion of the source if it does not exist
SQL = "INSERT INTO refer(citation,link) VALUES(%s,%s) RETURNING cd_ref"
cursor.execute(SQL,[ref_citation, ref_link])
cdRef, = cursor.fetchone()
# it should return the id of the source in the database
return cdRef | 6ace5ec1bf30b73ec1fff0f43a3e17ee3c5bfec7 | 420,697 |
import click
def prepare_instance_authentication(ctx, session, public_key):
"""
Sends an ephemeral public key to the target instance used to authenticate the SSH session.
"""
click.echo("sending public key to target instance...")
client = session.client("ec2-instance-connect")
return client.send_ssh_public_key(
InstanceId=ctx.obj["ssh_instance_id"],
InstanceOSUser=ctx.obj["ssh_instance_user"],
SSHPublicKey=public_key,
AvailabilityZone=ctx.obj["ssh_instance_az"],
) | 53c2a51f6715bed4729598c61170f80d415f3f72 | 584,401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.