content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def atom(draw):
"""
atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
"""
#'(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
return '' | 091f62e3669c8a557c8233b96bb73b43250bb681 | 665,222 |
import os
def ext(path): # type: (str) -> str
""" /dir1/dir2/file.ext.txt -> .txt
/dir1/dir2/ ->
"""
return os.path.splitext(path)[1] | 16e028a008dab4e11c2c5a4c236a6917abd07e86 | 665,223 |
def obj_type(key):
"""If it is a 'dir' it will end with a slash
otherwise it is a 'file'
"""
if key[-1:] == '/':
return 'directory'
else:
return 'file' | ec26ad76cde52142cff8c7b96dfa75ce5ad49e7e | 665,224 |
def hg(server, cmd_string):
"""Runs a Mercurial command through the given command server.
"""
server.run_command(cmd_string)
text, exit_code = server.receive_data()
return text, exit_code | 3a49a707a7d0ddf7d4e4f726d5a883f9dfaab44e | 665,225 |
def enthalpyVaporization(T, eVP):
"""
enthalpyVaporization(T, eVP)
enthalpyVaporization (kJ/mol) = A*(1-T/critT)^n
Parameters
T, temperature in Kelvin
eVP, A=eVP[0], critT=eVP[1], n=eVP[2]
A and n are regression coefficients, critT: critical temperature
Returns
ent... | cca3e061d884d95833d5adf833de29940b822d55 | 665,226 |
def metricresample(metric, samples):
"""
Resample a metric vector using random resamples computed using
indexresample.
Parameters:
- - - - -
metric: array of scalar values describing mesh
samples: indices to sample from
"""
resamples = metric[samples]
return resamples | b5a894dc56a2841ab4eda4396ab2719306633892 | 665,227 |
def get_reader_pairs(reader):
"""Return the set of alphabetically-sorted word (str) tuples
in `reader`
"""
return {tuple(sorted([w1, w2])): score for w1, w2, score in reader()} | 8e38bcbe58d5377d8fc171857390c1e836ecc9b3 | 665,229 |
from typing import Callable
def _node_not_implemented(node_name: str) -> Callable[..., None]:
"""
Return a function that raises a NotImplementedError with a passed node name.
"""
def f(self, *args, **kwargs):
raise NotImplementedError(f"'{node_name}' nodes are not implemented")
return f | 69d8d1df08e4896962cef981fd758271e09c4d32 | 665,230 |
def sorted_options(options):
"""Sort a sequence of options into canonical order.
Return a list with the same elements as *options* sorted using the option
:attr:`number<UrOption.number>` as the key. The sort is stable:
options with the same number remain in their original order. This
operation is... | 9b7cd3b2a5e88b160dd30f1bd4253269b93d4a26 | 665,231 |
def gcd_r(a: int, b: int) -> int:
"""recursive greatest common divisor
:param a:
:param b:
.. doctest:: python
>>> from pupy.maths import gcd_it
>>> from pupy.maths import gcd_r
>>> gcd_it(1, 4) == gcd_r(1, 4)
True
>>> gcd_it(2, 6) == gcd_r(2, 6)
True
... | 37b5debad789954e628b373bcf427a0c13a42d62 | 665,233 |
import os
import glob
import yaml
def read_yaml_snippets(args):
"""Reads and parses yaml snippets under `release-notes.d` directory
Args:
args (Namespace): Parsed command line attributes
Returns:
dictionary: A dictionary consists of a new release notes item generated from
... | 10e26ce0d69df0bfd2316eba239e46b4348f525f | 665,234 |
def GenerateLibraryDescription(lib_name):
"""Generates a library description consisting of its full name and version.
Args:
lib_name: The name of the library for which a description is to be
generated.
Returns:
A string description of the given library.
"""
tmp_lib = __import__('adspygoo... | 6a3046f7c45b90f3b6e45d1a32fb5da8c365dad3 | 665,235 |
from typing import Counter
def term_freq(tokens) -> dict:
"""
Takes in a list of tokens (str) and return a dictionary of term frequency of each token
(doc = a list of tokens)
"""
#counting occurrences of each unique token
term_count = Counter(tokens)
#total number of tokens
n_tokens = ... | 175763a993e4097a82b70635cca95eb5a1eaee64 | 665,236 |
def inverseTransform(tran):
"""
An SVG transform matrix looks like
[ a c e ]
[ b d f ]
[ 0 0 1 ]
And it's inverse is
[ d -c cf - de ]
[ -b a be - af ] * ( ad - bc ) ** -1
[ 0 0 1 ]
And, no reasonable 2d coordi... | 79a5edc7a0387838d5cab42b52e6ec303c20a98b | 665,237 |
def element(a):
""" Return the element """
return a.GetSymbol() | d2e335aff22978da0ae4627c8cae25f6b80cd602 | 665,238 |
def dataRange(data):
""" This is used to find the range of a set of data. The range is the difference between the lowest and highest valued digits in a given set of data."""
data = data
data.sort()
return data[len(data)-1] - data[0] | 73c6e7ec5948b1732d355af2af1a813abf3a360c | 665,239 |
def get_class_plural_name(cls):
"""Convert class name to it's plural form"""
base = cls.__name__.lower()
for ending in ('s', 'z', 'x', 'ch', 'sh'):
if base.endswith(ending):
return base + 'es'
if base.endswith('y'):
return base[:-1] + 'ies'
else:
return base + 's' | f7df342b440da1ec6f4d3c2b9d8bc0df35bca075 | 665,240 |
def drop_col(df, col):
"""
If a pandas.DataFrame has a particular column, drop it.
args
----
df : pandas.DataFrame
col : str
returns
-------
pandas.DataFrame, same DataFrame without column
"""
if col in df.columns:
df = df.drop(col, axi... | 7ea9fd416ba04a1d6dfa160c68407347819d31e2 | 665,241 |
def read_day(sheet,start,num_of_groups,day=1):
"""
:param sheet: передается страница
:param start: передается левый верхний угол ячейки дня
:param day: если первый день в неделе - передается двойка
:return: вощзращается список структур из данных ячеек
"""
def check_merge(sheet,row,column):
... | 49fab53537fb1e0cc94a01393c0c2a57963babc1 | 665,242 |
def print_deps_stdout_arg(request):
"""Argument for printing deps to stdout"""
return request.param | 63d735cd08b71bf12bef624c187ca9e128621ae6 | 665,243 |
def read_map_file(file_name):
"""
reads a map file generated by TI's ARM compiler. the function expects a file of a form similar to:
.
.
.
GLOBAL SYMBOLS: SORTED BY Symbol Address
address name
------- ----
00000000 __TI_static_base__
00000000 g_pfnVectors
00000200 __S... | 553fb838402220424a94335d3ad566c2a93a224f | 665,244 |
import argparse
def add_data_args(parser: argparse.ArgumentParser):
"""Train/valid/test data arguments."""
group = parser.add_argument_group('data', 'data configurations')
group.add_argument('--model-parallel-size', type=int, default=1,
help='size of the model parallel.')
group... | 568bdad8f785cde43c05ad3f9d0435d1b69bf0e8 | 665,246 |
from typing import Union
from typing import List
def process_dorms(dorms: Union[str, None] = None,
size: Union[int, None] = None,
default_dorm: str = 'Unknown',
dorm_separator: Union[str, None] = None) -> List[List[str]]:
"""Process the dorms.
Args:
... | 848c7bee5a5701465ac791c3196f5253ecfd50f8 | 665,247 |
def N_bar(tree):
"""
Returns the $\bar{N}$ statistic: the average number of nodes above a
terminal node.
"""
leaf_count = 0
nbar = 0
for leaf_node in tree.leaf_node_iter():
leaf_count += 1
for parent in leaf_node.ancestor_iter(inclusive=False):
nbar += 1
retur... | d80bcc320ab50fec946562389f0a4bccb5077677 | 665,248 |
def osm_area_sql(grid, osm, cat):
"""
Returns a sql fragment that sums the total area by category of a grid
cell coverd by OSM polygon features
Args:
grid (string): a PostGIS table name containing the grid
osm (string): a PostGIS table name containing the OSM polygon features
ca... | 5d3898dd8434cc3481dde3d43f6e957100550e94 | 665,249 |
import os
def rmkdir(path):
"""Method creates directory
Args:
path (str): directory path
Returns:
bool: result
Raises:
exeception: Exception
"""
result = False
if path != '' and not os.path.exists(path):
try:
os.makedirs(path)
retur... | 72a1605b927d2f40d1c4f56e102410f664d306d6 | 665,250 |
import re
def multiple_capture(pattern, string):
""" capture from first match for a multi-capture pattern
"""
match = re.search(pattern, string, flags=re.MULTILINE)
return match.groups() if match else None | 880af7ef230f4bd5b42bb221976433bb1f572d79 | 665,251 |
from typing import Any
def get_record_code(record: dict[str, Any]) -> str:
"""Returns the concatenated codes for a taric record."""
return f"{record['record_code']}{record['subrecord_code']}" | 11e438fbee7a831494ce47fcd59dce8c3840adcb | 665,252 |
import requests
from bs4 import BeautifulSoup
def get_soup(request, element, class_value):
"""
Uses the BeautifulSoup library to retrieve the HTML text for a given webpage request.
:param request: The webpage request for which the HTML text is to be retrieved.
:param element: The element of the webpag... | c93d82b978394119af240fcafdc6c9e5050751e5 | 665,253 |
def clear_lines(black_white_image):
"""清除单像素点干扰线
原理:上下两个点或左右两个点为异色,则该点属于干扰线的点
:param black_white_image: 黑白二值图
:return: image
"""
for x in range(1, black_white_image.size[0] - 1):
for y in range(1, black_white_image.size[1] - 1):
pix = black_white_image.getpixel((x, y))
... | 536b459fbf85ba53929172d30171eede05ada6f4 | 665,254 |
def _write_url_file(images, separator=" "):
""" ImageNet generally uses a specific format to store the URLs of images.
This converts a set of images into this format.
Args:
images: The set of images to write. It should contain tuples with image
WNIDs and URLs.
separator: Default string used to separat... | 4e67aebdc59d2e72a95e6435f4550c0aaf95dca5 | 665,255 |
import os
def at_root(*args):
""" Return path relative to formasaurus source code """
return os.path.join(os.path.dirname(__file__), *args) | d83f069b039d42b4bfc36582e602111bd70641d2 | 665,256 |
import pathlib
from typing import Union
def _should_granule_be_processed(
filename: str, save_dir: pathlib.Path, order_number: Union[str, int]
) -> bool:
"""
Return True iff the given granule should be processed (i.e. has not yet been saved)
Args:
filename (str): Name of the granule `.h5` fil... | f8693f2dd1052c09ea9718f14040e76e2a9bf051 | 665,257 |
import os
import gzip
import json
def load_playback_file(filename):
"""Load a gzip json playback file."""
cur_fp = os.path.realpath(__file__)
cur_dir = os.path.dirname(cur_fp)
fp = os.path.join(cur_dir, "mocks", filename)
with gzip.open(fp, "rb") as fh:
content = fh.read().decode("utf-8")
... | d532ef47a355e68c5a219bf04f19f03dc0c22eef | 665,258 |
def logamp_structure(logamp_a, logamp_b, axis=-1):
"""Structure function for log-amplitude fluctuations.
See Daigle, equation 17.
"""
return ((logamp_a-logamp_b)**2.0).mean(axis=axis) | 062be67d9b971883b5e48ca3e6090a8140d25a14 | 665,259 |
def catch(func, handle=lambda e: e, *args, **kwargs):
"""Helper function to enable the list comprehension in xmltolist.
Whenenver a data field doesn't have an entry, put an empty string.
cf. http://stackoverflow.com/a/8915613
"""
try:
return func(*args, **kwargs)
except KeyError:
... | a5b93ee2ead4622686018404e9f2c55ad8931cb4 | 665,260 |
def _merge_keys(dicts):
"""Return the union of the keys in the list of dicts."""
keys = []
for d in dicts:
keys.extend(d.keys())
return frozenset(keys) | 221289bf8697d63edb32f1405e324d2d05376931 | 665,261 |
def is_list_of_dict(value):
""" Check if value is a non-empty list of dictionaries """
return isinstance(value, list) and len(value) > 0 and all(isinstance(elem, dict) for elem in value) | a99d91a9ecbc92e203a001b94a413c757fa25ffb | 665,263 |
def nav_active(context, item):
"""
Returns 'active' is item is the active nav bar item, and '' otherwise.
"""
default = ''
try:
url_name = context['request'].resolver_match.url_name
except:
return default
if url_name == item:
return 'active'
return default | 1c2db3e1a829cf74106d7771078c0e6fa5a1e951 | 665,264 |
from typing import IO
from typing import Any
from pathlib import Path
def containing_directory(file_object: IO[Any]) -> Path:
"""Return the directory containing the given file."""
return Path(file_object.name).parent.absolute() | 9bcc5669e7377bbb919ec9f979ae83f4e6905a4c | 665,265 |
def _mm_multiply(A, B):
"""calculate the product of two matrices A, B"""
mA, nA = len(A), len(A[0]) #number of rows, cols in A
mB, nB = len(B), len(B[0]) #number of rows, cols in B
C = []
if nA != mB:
print('Matrix multiplication was not performed: invalid dimensions')
return None
... | 419a6488a1ec6d06b47d0a63e728a28036b11a47 | 665,266 |
import re
def GetVersion(path):
"""Get the version of this python tool."""
version_str = 'XWalk packaging tool version '
file_handle = open(path, 'r')
src_content = file_handle.read()
version_nums = re.findall(r'\d+', src_content)
version_str += ('.').join(version_nums)
file_handle.close()
return vers... | 7a8283021aedcd3d0788ef5c857a133d1be3726f | 665,267 |
import argparse
def parse_cmdline():
"""Child worker command line parsing"""
parser = argparse.ArgumentParser(description='Remote runner parser')
parser.add_argument('--address', action="store")
parser.add_argument('--index', action="store")
parser.add_argument('--testplan', action="store")
pa... | 78e83d9a73839c12468702fa85eddc086e0b5c49 | 665,268 |
def index():
"""RETURN: landing page message."""
return "PuPPy API is live!" | f19eddeab8ac2eb2cfcc94a9ee9b6a9c61f921d1 | 665,270 |
def getLeaves(ob, pre=""):
""" getLeaves tree, returns dictionary mapping
paths from root to leafs to value of leafs
"""
return ob._getLeaves(pre) | 73d1a2e260ebaad3eba1a3b5cce1db3e76b267dd | 665,271 |
import torch
def sample_symmetric(dim, mean=0, std=10, **kwargs):
"""generate a random symmetric matrix with a particular eigenvalue
distribution"""
# sample random orthogonal matrix (uniformly)
Q, R = torch.linalg.qr(torch.randn(dim, dim, **kwargs))
Q.mul_(R.diagonal().sign().view(1, -1))
# ... | 980b0a858a18d8f4aab927d19c9563189b34b492 | 665,273 |
import os
import pickle
def get_aaindex(index_list):
"""Get the aaindex from data/aaindex.data.
:param index_list: the index we want to get.
:return: a list of AAIndex obj.
"""
new_aaindex = []
full_path = os.path.realpath(__file__)
file_path = "%s/data/aaindex.data" % os.path.dirname(ful... | cfda082d329279b44f1eddf75fb08cc1f9322def | 665,274 |
from pandas import DataFrame
def make_df_statistics(cv_results):
"""Return results from `calculate_statistics` into a DataFrame"""
metrics = [
'accuracy_score', 'precision_score', 'recall_score', 'specificity_score',
'f1_score', 'f2_score', 'geometric_mean_score', 'matthews_corrcoef',
... | 34407f2bc480ebf5159c281deabe164207e19f56 | 665,275 |
import re
def find_ip(url):
""" Find IP address in string (code from dusty 1.0) """
ip_pattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s') # pylint: disable=W1401
ip_value = re.findall(ip_pattern, url)
return ip_value | 00dc6dbff6cee52bca91fac33d6e35a4c3025dfe | 665,276 |
from typing import List
def l2s(inputs: List) -> List[str]:
"""
Transforms a list into list of strings.
:param inputs:
objects
:return: list of str(object)
"""
return [str(inp) for inp in inputs] | 26a250ca0ae499281621a619e96c22414fa65d54 | 665,277 |
import argparse
def default_argument_parser():
"""
Create a parser with some common arguments used by detectron2 users.
Returns:
argparse.ArgumentParser:
"""
parser = argparse.ArgumentParser(description="ObjectDetection2 Training")
parser.add_argument("--test_dir", default="/2_data/wj... | 820dd4095b7bb47a1ad74618871357b351e05003 | 665,278 |
def find_components(graph):
""" breadth first search graph traversal algorithm """
connected_components = []
vertices = list(graph)
while vertices:
start_node = vertices.pop()
queue = [start_node]
visited = [start_node]
while queue:
node = queue.pop(0)
... | 0066d493a0573028a0c0978e847cb146d263a8e1 | 665,279 |
def doc_modifier(doc):
"""
"""
return doc.replace(
'delay_shift (bool, optional): flag to simulate spike propagation '
'delay from one layer to next. Defaults to True.',
'delay_shift (bool, optional): flag to simulate spike propagation '
'delay from one layer to next. Default... | bc74bd15f237760cf7bf99a96ceec14cb4b6b9ba | 665,280 |
def readIdentificationFile(infile, sep="\t"):
"""
read lines from a peptide identification file and store the column split version
of those lines (without header) in a list.
(return: list of peptide identifications as list of identification )
infile: file containing identification lines (like output of
I... | 867f87b5e3daf46911e1c1b0d0b54fbc9e9c958e | 665,281 |
from typing import Dict
def parse_node_id(node_id: str) -> Dict:
"""
解析节点ID
:param node_id: 节点ID "host|instance|host|123"
:return: {
"object_type": "HOST",
"node_type": "INSTANCE",
"type": "host",
"id": 123,
}
"""
object_type, node_type, _type, _id = node_id... | bb2d34f715a363dbbb8ef188491898095e9c966e | 665,282 |
def intsqrt(x):
"""
Return the largest integer whose square is less than or equal to x.
"""
if x == 0:
return 0
# invariant: l^2 <= x and x < r^2
l = 1
r = x
while r-l > 1:
m = l + (r-l)//2
s = m*m
if s <= x:
l = m
else:
r =... | bd9927beba0ffaa79af6df39fd6f71e8e3fa13d5 | 665,284 |
def _convert12(model):
"""
Converts a model from JMI type 1 to JMI type 2.
"""
# Convert array to object
results = {}
for element in model:
results[element['id']] = element
# Update contains field if needed
if 'contains' not in element.keys():
element['contai... | 4031d9f0b3257c41b628d261824d24bd9d8f19c1 | 665,286 |
import sys
import time
import logging
def timed(func):
""" Decorator used to benchmark function runtime"""
def wrapped(*arg, **kwarg):
target_base_name = sys.argv[0]
# target_base_name = os.path.basename(__file__).split(".")[0].capitalize()
target_function_name = func.__name__
... | 6fcf512c9fc6ab0efe6216ea42db55e226d50851 | 665,287 |
def _rchild(i):
"""
Returns the right child node of the given node.
"""
return 2 * i + 2 | 63f64c3438501e3f1cb11a53ef43d4b80884f4c8 | 665,288 |
def make_list(string):
"""Make a list of floats out of a string after removing unwanted chars."""
l1 = string.strip('[] \n')
l2 = l1.split(',')
return [float(c.strip()) for c in l2] | acdf9342b8147a6db2ff316eaecf8c83f261b9b4 | 665,289 |
import os
def executable(path):
"""Test for executable file."""
return os.access(path, os.X_OK) | f78bf14f4d5d25d59d79f8e64ddf075f51c997d8 | 665,290 |
def reverse_and_complement(sequence):
"""Get the reversed and complemented form of `sequence`.
Returns a string that is the reversed and complemented sequence
of `sequence`.
If `sequence` is empty, an empty string is returned.
"""
#Convert all rna_sequence to upper case:
sequence=sequence.... | e6ef3412639cbdfad0f7e892fad6bf7adda7add2 | 665,291 |
def _bcIsForVectorValues(bc, mesh):
"""Guess if boundary condition is supposed to be for vector valued problems
"""
verbose=False
def testForV3(t):
if verbose:
print("test for v3", t)
try:
if callable(t):
test = t(mesh.boundary(0))
els... | 4871b83cc2cb4878c9a52de809561b5b64a9cfb5 | 665,292 |
def watermelon(weight):
"""
Check condition.
"""
if weight % 2 == 0 and weight > 2:
return "YES"
return "NO" | ff454192c0bf42d2673cc11dd66fa2bf9106a475 | 665,293 |
def ansible_playbook_options():
"""
Lists the options available for ansible-playbook
"""
ansible_options = [
"--ask-become-pass", "--ask-pass", "--ask-su-pass", "--ask-sudo-pass",
"--ask-vault-pass", "--become", "--become-method", "--become-user",
"--check", "--connection", "--d... | ca5c3698a9d0dcac3106d0daa4f5a7b57cecac5f | 665,294 |
def vcross(self, labxr="", labyr="", labzr="", labx1="", laby1="",
labz1="", labx2="", laby2="", labz2="", **kwargs):
"""Forms element table items from the cross product of two vectors.
APDL Command: VCROSS
Parameters
----------
labxr, labyr, labzr
Label assigned to X, Y, and Z-... | ed40fd87eebfae617c1a3406b07d0ec7261c83e5 | 665,295 |
import hashlib
def sign(params, api_key):
"""
signature api
:param params: [(`class`:`str`, `class`:`object`)]
:return: `class`:`str`
"""
params = [(key, value) for key, value in params if value]
params = sorted(params, key=lambda param: param[0])
temp = u'&'.join([u'{0}={1}'.format(ke... | 2d96c6ef6c91719c8e7721be124a813b8306fe28 | 665,296 |
def get_last_lines_from_file(file_localtion, x=50):
""" returns an array of the last x lines of a file """
with open(file_localtion, "r") as the_file:
lines = the_file.readlines()
last_lines = lines[-x:]
return last_lines | 40c4ef64d9aac05299f9543d160ff6f57dfc609c | 665,297 |
import time
import logging
def time_it(func):
"""
Measures time
"""
def wrap(*args, **kwargs):
time1 = time.time()
ret = func(*args, **kwargs)
time2 = time.time()
final_time = time2 - time1
mins, secs = divmod(final_time, 60)
logging.info(f"{func.__name... | 0453481ff3435e2c8340b1dfaad873f3393a389a | 665,298 |
import os
def save(mail, name=None, target_path=None, overwrite=False) -> bool:
"""Save a mail."""
if name is None:
name = str(mail['subject'] + '.eml') if mail.get('subject') else 'Untitled'
if target_path is None:
target_path = os.getcwd()
file_path = os.path.join(target_path, name... | 60e624a509eaf0dc05d5a064143d5e573d5ffbd9 | 665,299 |
def memoized_triple_step(step):
"""Find number of step combinations for maximum of three steps at a time
:param step Number of steps left
:return Number of step combinations
"""
if step < 0:
return 0
elif step == 0:
return 1
return memoized_triple_step(step - 3) + \
... | bf1ef8fba952a73ce9160fc123d5cb4b263866a3 | 665,300 |
def subs_op_args(expr, args):
"""
Substitute Operator argument values into an expression. `args` is
expected to be as produced by `Operator.arguments` -- it can only
contain string keys, with values that are not themselves expressions
which will be substituted into.
"""
return expr.subs({i.n... | 59d996ad62f15cf47decc9639567a1a724b54b01 | 665,301 |
def standardized_api_list(component):
"""
Convert result dict to list just to have standardized API
"""
keyword = 'componentResults'
if (not isinstance(component, dict) or
keyword not in component or
not component[keyword]):
return component
# Remove reference, ... | 2520b948982ce8e96107fcbfa2e531eeb753970b | 665,303 |
def get_action(mod_line):
"""Function to return the type of action requested by the user for a
given module, using the pavilion configuration syntax. The string can
be in one of three formats:
1) '[mod-name]' - The module 'mod-name' is to be loaded.
2) '[old-mod-name]->[mod-name]' - The... | 170471eee01d3b974a9bf50785dfaa0d4bd44083 | 665,304 |
import os
def checking_scraping_allowance(robot_file, url_sub_category):
"""
Check if it is allowed to scrap the subcategory of a url
Arguments : url to robot.txt file
url subcategory
Return : Boolean True/False
"""
robot_res = os.popen(f'curl {robot_file}').read()
auth_r... | 8c61c5f2a1e374ed1b1a4719f7548a491b9a36e3 | 665,305 |
def calculate_rent(
product_price: float,
minimum_rent_period: int,
rent_period: int,
discount_rate: float = 0,
) -> float: # noqa E125
"""Calculate product rent over period
NOTE:
"Rent is calculated by mult... | 8a18cc98804ee3cea1406291f715b518f48d30bf | 665,306 |
import yaml
from typing import Any
def string_as_block(dumper: yaml.Dumper, data: str) -> Any:
"""string_as_block uses YAML's block style for strings with newlines."""
if "\n" in data:
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
return dumper.represent_scalar("tag:yaml... | 041a91de4cc12f82e7b8070e6eb7a8cadda1cb99 | 665,308 |
def qualified_name_tuple(cls):
""" Get the module name and the thing-name for a class.
e.g. ('instakit.processors.halftone', 'FloydSteinberg')
"""
mod_name = getattr(cls, '__module__')
cls_name = getattr(cls, '__qualname__',
getattr(cls, '__name__'))
return mod_name, cls_name | 2726dbe46db342193aca4f33c4164be57abe97fd | 665,309 |
def recursive_node_count(sll):
"""Solution to exercise R-7.3.
Describe a recursive algorithm that counts the number of nodes in a singly
linked list.
"""
def recurse(node, count):
if node is None: # Base case, found tail of linked list
return count
return recurse(node.... | ac26733203639c1be575dc8a739504dad9a7f041 | 665,310 |
def with_lock(lock, fn):
"""
Call fn with lock acquired. Guarantee that lock is released upon
the return of fn.
Returns the value returned by fn, or raises the exception raised
by fn.
(Lock can actually be anything responding to acquire() and
release().)
"""
lock.acquire()
try... | d8ed4c4a933483ac0aa5291c815b8afa64ca3957 | 665,311 |
def dailyLow (lowTemps, date):
"""Finds the low temperature for date in question.
.. warning:
Assumes date has been validated using dateValidation and that data
exists for date in question using dataAvailable.
:param list lowTemps: Low temperatures for given month
:param date: Date (Mo... | 78db75edc2af96b8bb80b344ed6f04f83506e1f9 | 665,312 |
def byte_to_gb(byte):
"""Convert bytes to GB"""
return byte / (1024.0 * 1024 * 1024) | 7bfd1dd1bcd2808e7189af185baa93d36774c6e2 | 665,313 |
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
r1 = [0] * 4
r2 = []
pos1, pos2 = 0, 0
score = 0
for num in line:
if num != 0:
r1[pos1] = num
pos1 += 1
while len(r1) > 1:
if r1[pos2] == r1[pos2 + 1]:
... | 329cc83b0446358999ec31c8a326ed27c502c2eb | 665,314 |
import argparse
def _parse_args():
"""Parses command line arguments"""
parser = argparse.ArgumentParser(description='Template file')
parser.add_argument(
'required',
help='an example required argument')
return parser.parse_args() | d0c8dce7cd99dba4b811c22cba337ef82d0895c2 | 665,315 |
def accesskey(request):
"""Get the accesskey from command line.
Arguments:
request: Gives access to the requesting test context.
Returns:
A accesskey from command line.
"""
return request.config.getoption("--accesskey") | aebf5c58fdfc9b279d6d1662fe25eee46abafa18 | 665,316 |
import time
import os
def pick_seed():
"""Returns a seed for a random number generator selected using
a mixture of the current time and the current process ID."""
return int(time.time()) ^ (os.getpid() << 16) & 0xffffffff; | fc553e955d9a895b113c74441d63d58ff407ddd2 | 665,317 |
import os
def count_filedirs(dirname):
"""Counts the number of directories and files in a given directory. Counts recursively.
dirname must be readable.
Returns:
nb of directories
nb of files
This is somewhat the equivalent of: find ./smali -type d -print
or -type f
"""
asser... | f67f9aaf0480e3568560075901c9c1bdd8401986 | 665,318 |
def b2b_ipv4_devices(b2b_raw_config, tx_port, rx_port):
"""Returns a list of ipv4 tx device and rx device objects
Each device object is ipv4, ethernet and vlan
"""
tx_device, rx_device = b2b_raw_config.devices.device().device()
tx_device.name, rx_device.name = "Tx Devices Ipv4", "Rx Devices Ipv4"
... | 48d4629c519a7881bd3226ff472a8e3cde870aa9 | 665,319 |
def normalize_vartype(vartype):
"""Return the canonical form for a variable type (or func signature)."""
# We allow empty strring through for semantic reasons.
if vartype is None:
return None
# XXX finish!
# XXX Return (modifiers, type, pointer)?
return str(vartype) | ac74ff3a0624374b4edb49cd705b032bd21672c8 | 665,320 |
from typing import Dict
def timestamp_as_number_formatter(row: Dict, field: str):
"""
Useful for JQGrids where we want to send down time as a timestamp so we can put it in the user's timezone
:param row: JQGrid row object
:param field: field to access row (row[field] should be a timestamp)
:return... | 1a27356aef164959d64cd6195fbf606a6f62b6c4 | 665,321 |
def sign_extend(val, bits=32):
""" Sign extension. High-order bit of val is left extended.
:param val: VexValue
"""
sign_bit = 1 << (bits - 1)
return (val & (sign_bit - 1)) - (val & sign_bit) | 71024f750787be4d80a64b46a34fc73ecc92097d | 665,322 |
import time
def new_time():
"""Create a _new_ time stamp.
This method also makes sure that after retrieving a timestamp that was
*before* a transaction was committed, that at least one second passes so
the packing time actually is before the commit time.
"""
now = anew_time = time.time()
... | 2fecdebe18372ea19e21569c4bdae7ff921f9ee5 | 665,323 |
def safe_union_two_by_name(df1, df2):
"""Combine common fields from two dataframes rowwise.
Note we do not use the ``pyspark.sql.DataFrame.unionByName``
function here because we explicitly reorder columns to the
order of ``take``.
Parameters
----------
df1 : pyspark.sql.DataFrame
f... | 82a341c995c9158010d1576b2e2c4c6faadfe606 | 665,324 |
import os
def parse_input():
"""
Ask user input for input images: pass path to individual images, directory
"""
out = []
while True:
ins = input("Enter path (q to quit):").strip()
if ins in ["q", "quit"]:
break
if not os.path.exists(ins):
print("Erro... | 9e3729a1abaa4d655ab4b1942b04e69e02ccb24d | 665,325 |
import yaml
def load_config():
"""
Loads the config from config.yaml
:returns: Dict of loaded config.yaml
:rtype: dict
"""
with open("config.yaml", "r") as _file:
return yaml.load(_file, Loader=yaml.FullLoader) | 6b938fb87559ce65194cc6fdb035d6bc66f585cd | 665,326 |
from typing import Tuple
from typing import List
def process_train_val_file(cfg)-> Tuple[List[str], List[str]]:
"""
"""
train_file = cfg.data.train_split_file
val_file = cfg.data.val_split_file
with open(train_file) as f:
train_lines = f.readlines()
for i in range(len(train_lin... | 2961797418161572d855d731a012fddfb2dc59d4 | 665,327 |
def is_assignment_processed(db_conn, assignment):
"""
Gets all global ids in the database
:param db: (string) The database to query
:return: List<string> The global ids in the db
"""
c = db_conn.cursor()
c.execute("SELECT GlobalID from assignments where GlobalID=?", (assignment.global_id,))
... | 958e98116f1de72255ab00733b8db612cff72f70 | 665,328 |
def return_list(
incoming) -> list:
"""
Checks to see if incoming is a String or a List. If a String, adds the
string to a list and returns.
"""
url_list = []
if isinstance(incoming, str):
url_list.append(incoming)
elif isinstance(incoming, list):
url_list = incoming
... | d07564b7f5d64cb41309a9aa724593ebef45656e | 665,329 |
import os
def os_pathsep(value):
""" Returns the appropriate path separator based the given value and the host OS.
"""
if os.name != "nt": # Unix
return ':' if ':' in value else ';'
else: # Windows
return ';' | e0e61819472311cd1b3f50b7dcaa7e3b1e87d9e3 | 665,330 |
def make_array(n):
"""Take the results of parsing an array and return an array
Args:
n (None|list): None for empty list
list should be [head, [tail]]
"""
if n is None:
return []
else:
return [n[0]] + n[1] | 965fca898aeac7337afae88a87bc2b54d027623f | 665,331 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.