content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
import os
def get_size(path: Path,
decimal_places: int = 1) -> float:
"""
Get file size in MB, rounded to decimal_places.
:param path: Path to the file.
:param decimal_places: int, count of sighs after dor in result value.
:return: float, rounded size of the... | 63271b95f353b201a625e76cb4b5c3015d987ae4 | 700,837 |
from datetime import datetime
import time
def formatTimeFromNow(secs=0):
""" Properly Format Time that is `x` seconds in the future
:param int secs: Seconds to go in the future (`x>0`) or the
past (`x<0`)
:return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`)
... | 9723ab0656ff4017412ab1fbd5465375ec8df1af | 700,839 |
def standardize_parameter_type(original_type):
"""Standardize parameter type descriptions
Args:
original_type (str): The original type
Returns:
str: The standarized type name
"""
original_type = original_type.lower()
if 'unc' in original_type:
return 'uncertainty'
i... | 49a93bebd8ee4918bdf420ee8c285d6574a3d3d0 | 700,841 |
from typing import Tuple
import torch
import math
def real_fourier_basis(n: int) -> Tuple[torch.Tensor, torch.Tensor]:
"""Make a Fourier basis.
Args:
n: The basis size
Returns:
An array of shape `(n_domain, n_funs)` containing the basis functions, and an
array containing the spec... | 704aacf8e34f2713ee5e01b8c0de2350c8e03ae2 | 700,844 |
def _define_names(d_t, d_y, treatment_names, output_names):
"""
Helper function to get treatment and output names
Parameters
----------
d_t: tuple of int
Tuple of number of treatment (exclude control in discrete treatment scenario).
d_y: tuple of int
Tuple of number of outcome.
... | a475968ed70070175f5ef164d1748def62548c9d | 700,845 |
def _as_vw_string(x, y=None):
"""Convert {feature: value} to something _VW understands
Parameters
----------
x : {<feature>: <value>}
y : int or float
"""
result = str(y)
x = " ".join(["%s:%f" % (key, value) for (key, value) in list(x.items())])
return result + " | " + x | 89e10d3bb8ad47ad4add6baee83280fa700ca65e | 700,846 |
from numpy import where
def qinit(x,y):
"""
Dam break
"""
eta = where(x<10, 40., 0.)
return eta | aa81ca9782917ce730ec70f4281a7b708c368308 | 700,848 |
import sys
def in_notebook():
"""
Returns ``True`` if the module is running in IPython kernel,
``False`` if in IPython shell or other Python shell.
"""
return "ipykernel" in sys.modules | ca8d703a399dfa8ee0bb0bdb42d9af8e657f5549 | 700,849 |
def _try_parse_int(value: str):
"""
try parse integer from string
param value: string to parse
return int
"""
try:
return int(value)
except ValueError:
raise ValueError("Cannot parse int from string") | 50b4f5c3d3e703c2c6c329e2f1abb25a948e488d | 700,850 |
def index_settings(shards=5, refresh_interval=None):
"""Configure an index in ES with support for text transliteration."""
return {
"index": {
"number_of_shards": shards,
"refresh_interval": refresh_interval,
"analysis": {
"analyzer": {
... | 29028b545da2e5ee2b0239029d34f863d1d9d943 | 700,851 |
import time
def test_approach(approach: str, sample_no: int, func, args: tuple) -> str:
""" For a given Sample #sample_no evaluates an approach by running func with provided args and logs run time """
res = f"{approach.capitalize()} Programming Approach for the Example #{sample_no}\n"
start = time.time()+... | ef34e7552a887fd4bee221a5d80bb3d5ab0003a9 | 700,852 |
def walk(i, j):
"""
Walks through the String without crossing the boundaries,
making sure that i < j-1
"""
if i < j - 1:
i += 1
# It is necessary to check again if i < j-1, after we incremented i
if i < j - 1:
j -= 1
return i, j | 1597c41408179f5a371ec14e36494ec5ee3a7aa0 | 700,853 |
import uuid
def converter_spark_em_pandas(df):
"""
Converte o dataframe Spark em Pandas, adicionando uma coluna
de identificador unico e deterministico para cada linha da tabela
"""
data = df.toPandas()
data["ID_REGISTRO_TABELA"] = data.apply(
lambda row: uuid.uuid5(
uuid.UUID('a658b648-167e-4d4... | 99febbc364025afb39772fa6008f5b4217f394ae | 700,854 |
def kwargs_to_str(kwargs):
""" Returns a string of the form '(kw1=val1, kw2=val2)'. """
if len(kwargs) == 0:
return ""
else:
return "(" + ", ".join(f"{k}={v}" for k, v in kwargs.items()) + ")" | 39d50d77620061b99861fb7a1fea77ae2a2dc376 | 700,855 |
def add_CRUD_pset(pset, sm, model_name):
"""Adds the ServerModel CRUD function to the Primitve Set
Parameters
----------
pset : PrimitiveSet
the primitive set for adding the controller functions
sm : ServerModel
the ServerModel with the CRUD functions
model_name : str
... | f0960c3b96789adfa2e56039ca7c072819438984 | 700,856 |
def to_litres(gallons):
"""Convert US gallons to metric litres"""
return 3.78541 * gallons | d1a7be6f01c89b848128218cbec19913e76658cd | 700,857 |
import requests
def get_nioshtic_wikidata_mapping():
"""
Retrieves a mapping between NIOSHTIC and Wikidata identifiers from the
Wikidata Query Service, query.wikidata.org
@return dictionary {nioshtic: {identifier_label: value}}
"""
prefix = 'http://www.wikidata.org/entity/'
q = (
... | 7216f8ed354bb394e39ceb906d41e19d1e41e589 | 700,858 |
import random
import copy
def distr_labeldata_unequal(label_data, num_workers):
"""
Idea:
1. For each label, distribute disproportionate allocation to workers.
2. Apply the worker's allocation to label_data and store in distr_labeldata,
where the keys are workers and the values are the labeled... | dab112ba98e9d5d68fbb519f1c7e3f2a6ea24e17 | 700,859 |
from typing import Sequence
def all_unique(lst):
"""Returns True if all elements of Sequence `lst` are unique.
False otherwise.
"""
assert isinstance(lst, Sequence)
return bool(len(set(lst)) == len(lst)) | 546d4254d5ca287952eec6af2bda048e60bb6b89 | 700,860 |
def generate_average_csv(fname, fields, trait_list):
""" Generate CSV called fname with fields and trait_list """
csv = open(fname, 'w')
csv.write(','.join(map(str, fields)) + '\n')
csv.write(','.join(map(str, trait_list)) + '\n')
csv.close()
return fname | 43195ea054ea537a4860c07c03c96efc263c472f | 700,861 |
def cal_newpath(dis_mat, path_new, cityNum):
"""
计算所有路径对应的距离
:param dis_mat: 城市距离矩阵 ndarray
:param path_new: 路径矩阵 ndarray
:param cityNum: 城市数量 int
:return: 动态规划最优路径 list
"""
dis_list = []
for each in path_new:
dis = 0
for j in range(cityNum - 1):
dis = dis_mat[each[j]][each[j + 1]] + dis... | 2a4d733e9633a44da3d66d74d54b75efc165d8bf | 700,862 |
def load_input(source):
"""load the input"""
if isinstance(source, str): # pragma: no cover
with open(source, 'r', encoding='utf8') as stream:
return stream.read()
else:
data = source.read()
if isinstance(data, bytes):
return data.decode("utf8")
retur... | fa0a9aac1854af59f400bf2344638c8fb4bee96d | 700,863 |
def is_integer(mark_string):
"""Function to check if a supposed pk is an integer."""
try:
mark_id = int(mark_string)
except ValueError:
return False
return mark_id | 1df4842906452cf5672584e5781e0e8a2d3b367d | 700,864 |
def _extract_command_with_args(cmd):
"""Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
... | 3db8aebab04e32f292e2956412bd81e7a07a471e | 700,865 |
def filtered_secondary_files(unfiltered_secondary_files: dict) -> list:
"""
Remove unprocessed secondary files.
Interpolated strings and optional inputs in secondary files were added to
CWL in version 1.1.
The CWL libraries we call do successfully resolve the interpolated strings,
but add the ... | 89c0906984ca634b8afc3dd4bdf2e9ccbbad504c | 700,866 |
def get_P_rtd_hs(q_rtd_hs, e_rtd):
"""定格消費電力 (4)
Args:
q_rtd_hs(float): 温水暖房用熱源機の定格能力 (W)
e_rtd(float): 当該給湯機の効率
Returns:
float: 定格消費電力
"""
return q_rtd_hs / e_rtd | 61d4a7c2f26b979891936efd6db0195ca3b083b0 | 700,867 |
def cpo(total_cost, total_transactions):
"""Return the CPT (Cost per Order).
Args:
total_cost (float): Total cost of marketing.
total_transactions (int): Total number of transactions.
Returns:
cpt (float) as total cost per order
"""
return total_cost / total_transactions | aaaaf5a96fcbef65e59591954bded1afa13f8c47 | 700,868 |
def rebin_1darray(a, shape, function='sum'):
"""Rebin an array into a new shape by making the sum or mean
"""
sh = shape,a.shape[0]//shape
if function == 'mean':
return a.reshape(sh).mean(-1)
elif function == 'sum':
return a.reshape(sh).sum(-1)
else:
print("WARNING: doing... | 66de60326e081c27aae471281c79c5e86f5180e3 | 700,869 |
def get_ground_truth(obj, image, question):
"""
Get the ground truth value for the image/question combination in reader
study obj.
"""
ground_truths = obj.statistics["ground_truths"]
return ground_truths[image][question] | 522b5550344891e0985bacb9c763c4c52686cb67 | 700,870 |
import os
def get_workspace(strOrigPath, strType_='flatten', strSuff_=''):
""" Return TDIS working (flatten) path given TDIS path. """
if os.path.split(strOrigPath)[1].startswith('TDISm__'):
strScene = strOrigPath.split(os.sep)[-4].split('_')[0]
p, f = os.path.split(strOrigPath)
strWor... | adb28fe59a436a85329c7f7e88412835e6486a38 | 700,871 |
def is_pandas_df(obj):
"""Check if an object is a Pandas dataframe
The benefit here is that Pandas doesn't have to be included
in the dependencies for pydeck
The drawback of course is that the Pandas API might change and break this function
"""
return obj.__class__.__module__ == 'pandas.core.f... | aa226f86d8640903fef4e51121e285ba9c594a3c | 700,872 |
def solve(f, x0):
"""
Solve the equation f(x) = x using a fixed point iteration. x0 is the start value.
"""
x = x0
for n in range(10000): # at most 10000 iterations
oldX = x;
x = f(x);
if abs(x - oldX) < 1.0e-15:
return x; | d5f5409d689c842c1a8c70b95c621360c9ae7c8c | 700,874 |
def p2_allocateByScore(CCA, nameCat, quota, rank, scorelist, final_dic, CCA_dic):
"""
Allocates students to cca where applicants exceed quota
Returns the final dictionaries
"""
cat = ""
for key, value in nameCat.items(): #theoretically it will all be the same anyway
cat = value
quot... | de0ec96eadf396319a7dfbb3942a6917afc6c84c | 700,875 |
def _total_solves(color_info):
"""
Return total number of linear solves required based on the given coloring info.
Parameters
----------
color_info : dict
dict['fwd'] = (col_lists, row_maps)
col_lists is a list of column lists, the first being a list of uncolored columns.
... | 32031f2ba834f7d6ed310b0a71ab43884b424459 | 700,876 |
import argparse
def parse_options():
"""Parses command line options"""
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", help="Output file name (e.g oui.h)")
parser.add_argument("-u", "--url", help="Wireshark oui/manuf file url")
opt = parser.parse_args()
return opt | f01013440685506ef3bef27e6c0d79147c2b896f | 700,877 |
def gettext(msg, domain='python-apt'): # real signature unknown; restored from __doc__
"""
gettext(msg: str[, domain: str = 'python-apt']) -> str
Translate the given string. This is much faster than Python's version
and only does translations after setlocale() has been called.
"""
return "" | a6d83a79110ec233f86878fc6aa9f37f2b3e61fa | 700,878 |
import re
def createPattern(string):
"""Cria um padrão de comandos de bot."""
return re.compile(f"/{string}|{string}") | b2b013dc71d5f49f041402ecf98db8b923f4d22a | 700,879 |
def gnomad_filtered_func(raw_value):
""" We use FILTER in Gnomad3 (GRCh38 only) - need to convert back to bool """
return raw_value not in (None, "PASS") | 6de1d4ef9395e89c11b08cdb43decb045656494b | 700,880 |
import torch
def _project_z(z, project_method='clip'):
"""To be used for projected gradient descent over z."""
if project_method == 'norm':
z_p = torch.nn.functional.normalize(z, p=2, dim=-1)
#elif project_method == 'clip': #not reimplemented yet
# z_p = tf.clip_by_value(z, -1, 1)
else:
raise Value... | 6cabb462dcbfff7ffdc065601f4a68671822f93f | 700,881 |
from datetime import datetime
def __dirnames_matching_format(dirnames, format):
"""
Iterates through dirnames and returns a sorted array of directory names
that match the provided format.
"""
matching_dates = []
for dirname in dirnames:
try:
dt = datetime.strptime(dirname, ... | 52349f0992a0ac0366d75f5328f674ab179246be | 700,882 |
import re
def solve(s):
"""doc"""
return "".join([w.capitalize() for w in re.split(r"(\W+)", s)]) | 28f075dd47c3ec57d6bb2a1675ae77815378786e | 700,883 |
def get_fields_by_name(model_cls, *field_names):
"""Return a dict of `models.Field` instances for named fields.
Supports wildcard fetches using `'*'`.
>>> get_fields_by_name(User, 'username', 'password')
{'username': <django.db.models.fields.CharField: username>,
'password': <django.d... | 8ce9c845adbff9bb53da50c7d7e208aa8077e718 | 700,884 |
def list_of_comments(fname) :
"""Returns list of str objects - comment records from file.
- fname - file name for text file.
"""
#if not os.path.lexists(fname) : raise IOError('File %s is not available' % fname)
f=open(fname,'r')
cmts = []
for rec in f :
if rec.isspace() : conti... | 5aea0668c006b4a4615cab01acd07db8dc1fb2b5 | 700,885 |
import re
def minify(source):
"""
Removes comments from the source code
"""
multiline = re.compile("(/\*.*?\*/)", re.DOTALL)
singleline = re.compile("//.*?\n")
remove_multiline = lambda f: re.sub(multiline, "", f)
remove_singleline = lambda f: re.sub(singleline, "", f)
return map(remove_multiline, ... | 3743e4071485d1ae085037a4bf4cd492f4f81d29 | 700,886 |
import logging
def with_logger(cls):
"""Class decorator to add a logger to a class."""
attr_name = '_logger'
cls_name = cls.__qualname__
module = cls.__module__
if module is not None:
cls_name = module + '.' + cls_name
else:
raise AssertionError
setattr(cls, attr_name, logg... | 77f854ac6d1cbe95ff7804184a1a67a513ac81ae | 700,887 |
from numpy import linspace, meshgrid
def _get_latlons(nlat, nlon):
"""Short summary.
Parameters
----------
nlat : type
Description of parameter `nlat`.
nlon : type
Description of parameter `nlon`.
Returns
-------
type
Description of returned object.
"""
... | f43553b4f758ac2a060f609e2781645b79466cb4 | 700,888 |
from typing import Dict
def convert_to_km(distance: float, print_output: bool = True) -> Dict[str, float]:
"""Convert a miles distance into the double of km.
Args:
distance: a distance (in miles).
print_output: if True, prints the progress.
Returns:
A dictionary with two keys ('o... | 1fb9dbbeb890a348d0feeebaea1a308bc06b039d | 700,889 |
import aiohttp
def aiohttp_socket_timeout(socket_timeout_s):
""" Return a aiohttp.ClientTimeout object with only socket timeouts set. """
return aiohttp.ClientTimeout(total=None,
connect=None,
sock_connect=socket_timeout_s,
... | c17a40a532aee15557b4e507439b0a7b2e98989e | 700,890 |
def getMulitples(indices):
"""Return a subset with no multiples (filters out the bad ones)."""
multiples = []
added = []
for i in range(0, len(indices) - 1):
if indices[i][0] == indices[i + 1][0]:
added.append(indices[i])
elif added:
added.append(indices[i])
... | 4846fe1950f7d1a5379595b93e18c3ed0eb2d160 | 700,891 |
def do_math(a, b, operator):
"""Helper function that performs computation between two numbers."""
if operator == "+":
return int(b) + int(a)
elif operator == "-":
return int(b) - int(a)
elif operator == "*":
return int(b) * int(a)
elif operator == "/":
return int(b)... | 5bffd1db1659c9f3420cc66a28525698de3beef5 | 700,892 |
def deg_to_arcsec(angle: float) -> float:
"""
Convert degrees to arcseconds.
Args:
angle: Angle in units of degrees.
Returns:
angle: Angle in units of arcseconds.
"""
return float(angle) * 3600. | 02fd099627970116bf5513af8b8d2d62bdc8ed41 | 700,893 |
def set_window_width(image, MIN_BOUND=-1000.0, MAX_BOUND=400.0):
"""设置窗宽"""
image[image > MAX_BOUND] = MAX_BOUND
image[image < MIN_BOUND] = MIN_BOUND
return image | 0dfa6e858c74cacc2cc8724d33f9b7fd96835d0c | 700,894 |
import json
def update_chart_info(_figure, chart_data_json_str):
"""
A callback function to set the sample count for the number of samples that
have been displayed on the chart.
Args:
_figure (object): A figure object for a dash-core-components Graph for
the strip chart - triggers... | fd28e28b7b48131bb56d6d9f29e4fe438b33bb7a | 700,895 |
def record_copy_all(node, **kwargs):
""" A default rcd implementation that copies all kwargs to the tape.
the impl is used for the vjp and vjp primitives.
the impl is can be used for the apl primitives if no rcd is given;
but we use 'record_copy_autodiff' to save a much smaller subset
... | e7e957c1d9fb0cc36bf54c1ab431ba4c7892838c | 700,896 |
def read_file(filename):
""" Return the content of a file as a list of strings, each corresponding to a line
:param filename: string: location and name of the file
:return: content of filename
"""
with open(filename, 'r') as ofile:
content = ofile.read().splitlines()
return content | 58a2718265fef848e484178e407aee6f7017a52a | 700,897 |
def score_1(game, player): # 82.14%
"""
Heuristics computing score using #player moves - k * #opponent moves
:param game: game
:param player: player
:return: score
"""
if game.is_winner(player) or game.is_loser(player):
return game.utility(player)
opponent = game.get_opponent(p... | 3995237f5d5474660c752c308e1077aad1743d06 | 700,898 |
def parse_line( line ):
"""Returns data located in the line."""
tokens = line.split()
return int(tokens[1]), tokens[2], (
int(tokens[4]), # n_i
int(tokens[6]), # s_i
) | 487421bcc50e4d542227e54a1362008a8a678b5b | 700,899 |
def strip_ddp_state_dict(state_dict):
""" Workaround the fact that DistributedDataParallel prepends 'module.' to
every key, but the sampler models will not be wrapped in
DistributedDataParallel. (Solution from PyTorch forums.)"""
clean_state_dict = type(state_dict)()
for k, v in state_dict.items():
... | f4cd6917db3df384e70c6b54dc4142dd760dd1d2 | 700,901 |
def _import(module_name, class_name):
"""
Return class of the module_name, where module_name is of the form
package.module (testoob's Asserter, which does simple __import__, returns
package, not package.module in this situation).
"""
mod = __import__(module_name)
components = module_name.spl... | 27a20935b305e3c387c861392429794976d7d866 | 700,902 |
def get_reftypes(exp_type, cal_ver=None, context=None):
"""Based on the exposure type, CAL s/w version, and CRDS context, determine
the list of applicable reference file types.
"""
return [] | ccb08ecd63b85d4602d419fb8fd90e77984c4048 | 700,903 |
def get_CV_current(CV):
"""
Helper function to compute CV current.
Args:
CV (pd.DataFrame): CV segement of charge
Returns:
(float): current reached at the end of the CV segment
"""
if not CV.empty:
return(CV.current.iat[-1]) | 69e32ecadc57d0855eedfe3404db1e5ec9839862 | 700,904 |
import unicodedata
def filter_nick(name):
"""
filter_nick(name) -> String
Process the name and get rid of all whitespace, invisible characters and
make it all lower case.
This function is intended to mimic euphoria's name pinging system, however
it is slightly less pedantic, allowing for pun... | bba506f4b2e84b4f82df8a4b31feb82203db8356 | 700,906 |
def label_name(event_data):
"""Get the label name from a label-related webhook event."""
return event_data["label"]["name"] | 903173b4fd9ddeb0a74a3e10be94626e0685a037 | 700,907 |
def bit_length_power_of_2(value):
"""Return the smallest power of 2 greater than a numeric value.
:param value: Number to find the smallest power of 2
:type value: ``int``
:returns: ``int``
"""
return 2 ** (int(value) - 1).bit_length() | bb49afee83ac255549ce5b5aaab80bb76ad4e337 | 700,908 |
import json
def json_top_atom_count(json_str):
"""Count the number of atoms in a JSON topology used by wepy HDF5."""
top_d = json.loads(json_str)
atom_count = 0
atom_count = 0
for chain in top_d['chains']:
for residue in chain['residues']:
atom_count += len(residue['atoms'])
... | 0e1e23cd4b9e5cedf3e6b5d815ee817798188752 | 700,910 |
def length_squared(point):
"""
square of length from origin of a point
Args:
point (QPointF) the point
Returns
square of length
"""
return point.x()*point.x() + point.y()*point.y() | 0289ca736f087dd75f9b9e0f1347fdc223d03f84 | 700,911 |
def topSort(G):
"""
使用BFS实现拓扑排序。
每次找到入度为0的节点放入列队,遍历与入度为0的点相邻的节点,并将度数减少1,如果度数变为0则放入列队。直到列队为空。
"""
Q = [] # 列队存储每个节点
counter = 0
sort = {}
for i in G:
if i.degree == 0:
Q.append(i)
while len(Q) != 0:
vertex = Q.pop()
sort[vertex] = counter
counter += 1
if vertex.c == None:
continue
for j in... | 3b8662a4adbc32d9a2174b5faf82d0c763d703fe | 700,912 |
import getopt
import sys
def get(params_config, params=None, is_show_help=True):
"""标准化处理参数
根据提供的params_config参数,提供参数params中的字段,返回字典
params_config例:
{
'username':
{'must':False,'data':True,'short':'U','long':'username','default':'root'},
'password':
... | b149a0aeeb246d0b0d5c36c3e9032d0d64563654 | 700,913 |
def get_ancestor(taxid, tree, stop_nodes):
"""Walk up tree until reach a stop node, or root."""
t = taxid
while True:
if t in stop_nodes:
return t
elif not t or t == tree[t]:
return t # root
else:
t = tree[t] | f7841bc5104f96cd66122165a0646b70fc3fd33e | 700,914 |
import os
def file_exists(file):
"""Check if a file exists."""
if not os.path.exists(file):
return False
try:
open(file).close()
except IOError:
return False
return True | 34a3f66e8597cd0cf7b77c9c270407268ac52a70 | 700,915 |
def check_patch_in_bounds(x, y, X_dim, Y_dim):
""" Usage: TrueFalse = check_patch_in_bounds(x, y, X_dim, Y_dim)
determine if the box is within the image
Args:
x: a tuple, list or array (x_start, x_end)
y: a tuple, list or array (y_start, Y_end)
... | 80221a95fda698f31aeed6c91987a5227a21e751 | 700,916 |
def domain(request) -> str:
"""Return AWS domain"""
return request.config.getoption("--domain") or "amazonaws.com" | fbf812dd28eb6aa3ff6a647a4cd1d17b739cb320 | 700,917 |
def read_table(data, coerce_type, transpose=False):
"""
Reads in data from a simple table and forces it to be a particular type
This is a helper function that allows data to be easily constained in a
simple script
::return: a dictionary of with the keys being a tuple of the strings
in the fi... | 6701736354b30d41b4adf7c6a11406f26c21c71b | 700,919 |
import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it trains on the PubMed dataset.
The default hyperparameters give a good quality representation without grid search.
"""
parser = argparse.ArgumentParser(description = "Run .")
parser.add_arg... | 7a4b82373d1d1f7028eb6c228d35d3f35107ce19 | 700,920 |
def cat_arg_and_value(arg_name, value):
"""Concatenate a command line argument and its value
This function returns ``arg_name`` and ``value
concatenated in the best possible way for a command
line execution, namely:
- if arg_name starts with `--` (e.g. `--arg`):
`arg_name=value` is returned (... | bcd99ab465707e594646d2152ad7b10b32956f5e | 700,921 |
import inspect
def unwrap_obj(obj):
""" Gets the actual object from a decorated or wrapped function
@obj: (#object) the object to unwrap
"""
try:
obj = obj.fget
except (AttributeError, TypeError):
pass
try:
# Cached properties
if obj.func.__doc__ == obj.__do... | d158d7ed832823b66e46bea00a96c5799684bd33 | 700,923 |
def get_workspace(repo_context):
"""
Construct the workspace url from the given repo context
:param repo_context: Repo context from context.py
:return: Workspace url for known VCS or None
"""
if not repo_context["repositoryUri"]:
return None
revision = repo_context.get("revisionId",... | ebab3b089c8267932a7a660207b8c7d4b38148f9 | 700,924 |
def plotlify_scatter_js(xy=None, x=None, y=None, xtag=None, ytag=None, description=""):
"""
Update the plot data in plotly format.
:param xy: x and y in a single structure.
:param description: The description of the plotly plot.
:param plot_type: The type of the plotly plot.
:return: A dictiona... | 2ad2e33dde23ec18f162c28425380b99ae3596a6 | 700,925 |
import os
import requests
def retrieve_article(article, output_filename, clobber=False):
"""Download the journal article (preferred) or pre-print version
of the article provided, and save the PDF to disk.
Inputs
------
article : `Article` object
The article to retrieve.
output_filena... | d742068dd76090fb03f222194f66d66b1dc95ffe | 700,926 |
def envelops(reg, target_reg):
"""Given a region and another target region, returns whether the region
is enveloped within the target region."""
return (target_reg.start <= reg.start < target_reg.end) \
and (target_reg.start <= reg.end < target_reg.end) | 716f2e905bdb852d9e0b85ff0482a70a64d325f1 | 700,927 |
from typing import MutableMapping
from typing import Any
def include_filter(
include: MutableMapping[Any, Any],
target: MutableMapping[Any, Any]) -> MutableMapping[Any, Any]:
"""Filters target by tree structure in include.
Args:
include: Dict of keys from target to include. An empty dict matches all
... | f1c10ec383a430700d8e7f58e8c9f6bc5180c844 | 700,928 |
import struct
def readRem(byteStream):
"""The rem - remark/comment type tokens"""
commentLength = struct.unpack('bb', byteStream.read(2))[1]
bytesRead = 2
comment = struct.unpack('%ds' % commentLength, byteStream.read(commentLength))[0].rstrip("\x00")
bytesRead += commentLength
return bytesRea... | 31782ce3a8aa10b306066bd4dc388c62392cc11b | 700,930 |
def get_route_name(route):
"""Returns route name."""
# split once, take last peice
name = route.split("/", 1)[-1]
return name | 3d5c916711a7631d4eb90c5eff6f1f745c97a664 | 700,932 |
import requests
def get_remote_version(url: str) -> str:
"""Gets the remote file and returns it as a long string."""
response = requests.get(url)
if response:
#print("Getting remote version")
s = response.text
return s
else:
return "Url Not Found." | 5d5ef45c5b74b326f9386214229529d9b71aca3d | 700,934 |
def single_number_hashtable(nums: list[int]) -> int:
"""Returns the only element in `nums` that appears exactly once
Complexity:
n = len(nums)
Time: O(n)
Space: O(n)
Args:
nums: array of integers s.t. every element appears twice, except for one
Returns: the only elemen... | f15b06d4f4683b9604e8b5ab6f2fe9be588551a6 | 700,935 |
def metadata(datasets):
"""
Extract datasette metadata from a CLDF dataset.
"""
def iter_table_config(cldf):
for table in cldf.tables:
try:
name = cldf.get_tabletype(table)
except (KeyError, ValueError):
name = None
name = name ... | f4927cea1a5587a417e98453cd7df7bf2f75d507 | 700,936 |
def parse_card(card: str) -> tuple:
"""Separates the card into value and suit.
Args:
card (str): String representing a poker card, in the format ValueSuit, like '9D' (9 of Diamonds).
Returns:
tuple: Returns a tuple of the card, like (Value, Suit). Ex: '9D' -> ('9', 'D').
"""
if le... | de9051906327dfcf01a3b2076acbed216ce43ced | 700,937 |
def _reformat_policy(policy):
"""
Policies returned from boto3 are massive, ugly, and difficult to read.
This method flattens and reformats the policy.
:param policy: Result from invoking describe_load_balancer_policies(...)
:return: Returns a tuple containing policy_name and the reformatted policy... | 4eb5372e233d53e6949a90833350831542c5bd01 | 700,939 |
def checksum1(data, stringlength):
""" Calculate Checksum 1
Calculate the ckecksum 1 required for the herkulex data packet
Args:
data (list): the data of which checksum is to be calculated
stringlength (int): the length of the data
Returns:
int: The calculated checksum 1
... | 504b848b651ae5e8c52c987a6a8e270259e1de44 | 700,942 |
def allZero(buffer):
"""
Tries to determine if a buffer is empty.
@type buffer: str
@param buffer: Buffer to test if it is empty.
@rtype: bool
@return: C{True} if the given buffer is empty, i.e. full of zeros,
C{False} if it doesn't.
"""
allZero = True
for byte ... | 8520e57dcd09a914566622098b196965f547ac6f | 700,943 |
import re
def acad_to_academy(text):
"""
A function to change `Acad` to `Academy`. Smartly. Tries to ignore
instances of `Acad` followed by `emy` or `emies`.
Usage:
from core.utils import acad_to_academy
replace_str = 'Harmony Science Acad (Waco)'
print acad_to_academy(replace_str)
... | 50f515d2b0c67a5a50799c92ea0a51d6828107b9 | 700,944 |
def _earlygetopt(aliases, args):
"""Return list of values for an option (or aliases).
The values are listed in the order they appear in args.
The options and values are removed from args.
>>> args = ['x', '--cwd', 'foo', 'y']
>>> _earlygetopt(['--cwd'], args), args
(['foo'], ['x', 'y'])
>... | 034bf7e4cde24cc45ed888b742361ce0a4ed1a8b | 700,945 |
def chunks(l, n):
"""
https://stackoverflow.com/a/1751478
"""
n = max(1, n)
return (l[i : i + n] for i in range(0, len(l), n)) | 01bcae9d06bf430874717b70039c79de532b9fd4 | 700,946 |
def plugin_zip(p):
"""Maps columns to values for each row in a plugins sql_response and returns a list of dicts
Parameters
----------
p : :class:`taniumpy.object_types.plugin.Plugin`
* plugin object
Returns
-------
dict
* the columns and result_rows of the sql_response in P... | b91e5403fd710875c4588afc0eba3da1b1a82c4a | 700,947 |
import platform
import subprocess
def ping(host):
"""
Returns True if host responds to a ping request
"""
# Ping parameters as function of OS
ping_num_param = "-n" if platform.system().lower() == "windows" else "-c"
# Ping
return subprocess.run(['ping', ping_num_param, '1', host], stdout... | 7665ab5c43380e9b847037c84e03296f00f348a1 | 700,948 |
def get_string_from_ascii(input):
"""
This function is reversed engineered and translated to python
based on the CoderUtils class in the ELRO Android app
:param input: A hex string
:return: A string
"""
try:
if len(input) != 32:
return ''
byt = bytearray.fromhex... | fdf878ac689c614720e9ad5ebeecbd32c9f893b1 | 700,949 |
def split_multiline(value):
"""Special behaviour when we have a multi line options"""
value = [element for element in
(line.strip() for line in value.split('\n'))
if element]
return value | a5eecefb94a79639afe3582e4c3cfb8e7a0adf6f | 700,950 |
def compute_mean_median(all_methods_df):
"""
Computes the mean values and the median values for each column of the Pandas.DataFrame grouped by the methods.
Parameters
----------
all_methods_df : Pandas.DataFrame
Returns
-------
list
- means: Pandas.DataFrame containing the ... | b4397bfcef8e0215e3478f1f50708aa4608a14e2 | 700,953 |
import torch
def get_cosinebased_yaw_pitch(input_: torch.Tensor) -> torch.Tensor:
"""
Returns a tensor with two columns being yaw and pitch respectively. For yaw, it uses cos(yaw)'s value along with
sin(yaw)'s sign.
Args:
input_: 1st column is sin(yaw), 2nd Column is cos(yaw), 3rd Column is si... | ca5c10908de8dfa8b86446a1874b1ef780ae5313 | 700,954 |
import re
def CommitPositionFromBuildProperty(value):
"""Extracts the chromium commit position from a builders got_revision_cp
property."""
# Match a commit position from a build properties commit string like
# "refs/heads/master@{#819458}"
test_arg_commit_position_re = r'\{#(?P<position>\d+)\}'
match =... | c0fdb07ce3be907db3ec8628eaefc3ad1453ef34 | 700,955 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.