content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def global_fn():
"""
A test global function.
"""
return 'global_fn' | 53c3c2ee395117c156654fa2e3cc73ed76aa718f | 681,693 |
import torch
def assert_tensors_close(a, b, atol=1e-12, prefix=""):
"""If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if torch.allclose(a, b, atol=atol):
return Tr... | 167d065904a505c3007b9d15a7fecc7b81a26ef9 | 681,694 |
import time
def sagemaker_timestamp():
"""Return a timestamp with millisecond precision."""
moment = time.time()
moment_ms = repr(moment).split(".")[1][:3]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment)) | a854f8873cc51b3598652fe2c408be918ce62d24 | 681,695 |
import re
def split_by_punct(segment):
"""Splits str segment by punctuation, filters our empties and spaces."""
return [s for s in re.split(r'\W+', segment) if s and not s.isspace()] | 25e94ca97b13bf163a2f2e3f1c9d6038747a8fea | 681,697 |
import re
def filename_safe(name: str, lower: bool = False) -> str:
"""
Perform the necessary replacements in <name> to make it filename safe.
Any char that is not a-z, A-Z, 0-9, '_', ' ', or '-' is replaced with '_'. Convert to lowercase, if lower=True.
:param lower: If True, apply str.lower() to res... | ba1149d0b375184d326fc03c5b4a7748794254bf | 681,698 |
from typing import Tuple
from typing import Optional
def _parse_key_value_pair(arg: str) -> Tuple[Optional[str], str]:
"""
Parameters
----------
arg : str
Arg in the format of "Value" or "Key=Value"
Returns
-------
key : Optional[str]
If key is not specified, None will be t... | 87170907e969727950320e524f45c9be7045ad9a | 681,699 |
def compute_eigenphase(noisy_ims, lab_uv, xy, wl_mns, window_frac=0.3, ntel=4):
"""Compute the Fourier transform at 7 discrete positions per pupil, producing
19 positions per splodge. """
return None | 1c3e26100e9390e10e04621733da526b69c3e897 | 681,700 |
import random
def randomget(choices_list, target_attr=None, target_value=None):
"""
随机获取某个匹配对象
choices_list: 预期结构为[{}, {}]
:param choices_list:
:param target_attr:
:param target_value:
:return:
"""
if len(choices_list) == 0:
return 'no match data'
if target_attr and tar... | 073f2dfb1e1bedc302349c0459aeb3a21202b515 | 681,701 |
def str_to_bool(val: str) -> bool:
"""Converts a string to a boolean based on its value.
:param val: string being converted
:return: boolean value expressed in the string
:raises: ValueError if the string does not contain a value corresponding to a boolean value
"""
if isinstance(val, str):
... | dbb78367a1db8461b20b44d521bf8522b8d9a048 | 681,702 |
def get_flat1d_size(hist, inc_overflow):
""" Returns the appropriate size of the flattend 1d histo
"""
nbinsx = hist.GetNbinsX()
nbinsy = hist.GetNbinsY()
nbinsz = hist.GetNbinsZ()
return nbinsx*nbinsy*nbinsz if not inc_overflow else hist.GetSize() | 536bf519156056cdc65f307d8b8e0134719bd7dd | 681,703 |
def yes_or_no():
"""
The user must answer with Y or N. Returns a bool
:return: The answer in boolean format
:rtype: bool
"""
answer = None
while answer is None:
answer = input().upper()
if answer == "Y":
answer = True
elif answer == "N":
answer... | aaf664d1f9916080bed974dd0a4836f1ee4bae82 | 681,704 |
import re
def clean_data(data):
"""Processes raw tweets to clean text"""
#Removing URLs with a regular expression
url_pattern = re.compile(r'https?://\S+|www\.\S+')
data = url_pattern.sub(r'', data)
# Remove mentionings
data = re.sub(r'@\w*', '', data)
# Remove special chara... | 9e18ef0292839ba2431dfcabb401fa1238e5abeb | 681,705 |
import functools
def require(required):
""" Decorator for checking the required values in state.
It checks the required attributes in the passed state and stop when
any of those is missing. """
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
... | b92675b5602ad96a68db858b6938c0de40820fec | 681,706 |
def traverse_using(iterator, obj, visitors):
"""visit the given expression structure using the given iterator of
objects.
:func:`.visitors.traverse_using` is usually called internally as the result
of the :func:`.visitors.traverse` function.
:param iterator: an iterable or sequence which will yiel... | 363453fa7d518bac59dedb58c278f62183b03758 | 681,707 |
def tree_intersection(t1, t2):
"""Compare two binary search trees and return a set containing the values that are common to both.
args:
t1: a BST
t2: a BST
returns:
a set with values common to both trees
"""
t1_vals = set()
def visit_t1(node):
if node is None:
... | b7fa9c3acadbbedd88e6ab3f14ece5fea7b4ce9c | 681,708 |
def GetNestedAttr(content, nested_attr, default=None):
"""Get the (nested) attribuite from content.
Get the (nested) attribute from the content dict.
E.X. content is {key1: {key2: {key3: value3}}, key4: value4}
nested_attr = [key1] gets {key2: value2, {key3: value3}}
nested_attr = [key1, key2] gets {key3: va... | a35074088e58739f0ac9cfcf264e8f7f7e3de566 | 681,709 |
import os
def get_npm_name():
"""Get the appropriate npm executable name.
"""
return 'npm.cmd' if os.name == 'nt' else 'npm' | e982e7985975ff0e7a4580aabc212279204f5672 | 681,711 |
import json
def format_json(json_string):
"""Converts a minified JSON str to a prettified JSON str.
Args:
json_string (str): A str representing minified JSON.
Returns:
(str): A str representing prettified JSON.
"""
parsed = json.loads(json_string)
return json.dumps(parsed, in... | cb0d60db6e4f1a0044e24405dafc222a6af5ac1b | 681,712 |
import os
def maxima_version():
"""
Return Maxima version.
Currently this calls a new copy of Maxima.
EXAMPLES::
sage: from sage.interfaces.maxima_abstract import maxima_version
sage: maxima_version()
'5.35.1'
"""
return os.popen('maxima --version').read().split()[-1... | 24fec9ae287a0565e3bdb54e63836b984046d5d1 | 681,713 |
def generate_body_sort_script(sort='desc', **params):
"""生成es权重排序的body数据"""
inline = []
for key in params:
inline.append("doc['{}'].value * params.{}".format(key, key))
inline = "+".join(inline)
body = {
"sort": {
"_script": {
"type": "number",
... | 6dd0ddaa1521be71e040178c8bef33b8eca5a219 | 681,715 |
def wrapped_list(list, which):
"""
Selects an element from a list, wrapping in either direction.
"""
if which < 0:
ix = len(list) + (which % len(list))
else:
ix = which % len(list)
return list[ix] | 122fd9f24969568bd0dc305aa35f3a9912a61af2 | 681,716 |
def get_fakes(infile):
"""
get list of know pypi fakes
"""
print('\t2. Creating list of fake pypi packages.')
with open(infile, 'r') as inf:
return inf.read().replace(" ", "").split(",") | 35a7c9cb734be802312a9e4b650834ae36cfbbde | 681,718 |
def sort_data_in_dict(s_id, sarr, earr, start, end):
"""
Sort the data based on the id and the start and end points (into the sarr
and earr dictionaries
:param s_id: string, ID of this object (will be used as key)
:param sarr: dict, start point list (list of time series data for each
... | 813b60240616973ecea1597fea3fe16c9680faac | 681,719 |
def proper_fractions(n):
"""
Using Euler's Totient Theorem
"""
if n < 2:
return 0
phi = n
i = 2
while i * i <= n:
if n % i == 0:
phi = phi / i * (i - 1)
while n % i == 0:
n /= i
i += 1
if n > 1:
phi = phi... | 6f79c770368830b18779535a1d145a800c1afea5 | 681,720 |
def clean_requirement(requirement):
"""Return only the name portion of a Python Dependency Specification string
the name may still be non-normalized
"""
return (
requirement
# the start of any valid version specifier
.split("=")[0]
.split("<")[0]
.split(">")[0]
... | 2e7cabbc9d3e6bde215944e0189f4666ddcdba40 | 681,721 |
def deploy_command(deb_package, hostname, username = "pasha"):
"""Command for start deployment on `target_hosts` of package.
Args:
deb_package (File): Debian package to install
hostname (str): host for installation
username (str): SSH user for installation process
Returns:
... | 32532499bb801678ff9a542e86edec30d46bcf89 | 681,722 |
def parameter_values(params, **kwargs):
"""Return a copy of the parameter list, substituting values from kwargs.
Usage example::
params = parameter_values(params,
stock='GOOG',
days_back=300
)
Any parameters not supplied will keep their original value.
"""
... | aac886173c6604b317b9ad582beb279adc165b67 | 681,723 |
def existing_query(query):
"""
Returns:
Query: Written to Sync Gateway with no views.
"""
query.create_update()
return query | 312496dcf2ace94e2243d8e6a9592264d75303e8 | 681,724 |
def gf_TC(f, K):
"""
Return trailing coefficient of ``f``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_TC
>>> gf_TC([3, 0, 1], ZZ)
1
"""
if not f:
return K.zero
else:
return f[-1] | 9e478fcbd3eb7daa7d7f300d1d2f2a8155bef8e4 | 681,725 |
import re
def utc_offset_string_to_seconds(utc_offset: str) -> int:
"""match a UTC offset in format ±[hh]:[mm], ±[h]:[mm], or ±[hh][mm] and return number of seconds offset"""
patterns = ["^([+-]?)(\d{1,2}):(\d{2})$", "^([+-]?)(\d{2})(\d{2})$"]
for pattern in patterns:
match = re.match(pattern, utc... | 6b1a0fa73c6cdfd71824a4079d2c5d6e8b4f6ab3 | 681,726 |
async def insert_embed_field_from_dict(message, embed, field_dict, index):
"""
Inserts an embed field of the embed of a message from a dictionary with a much more tight function
"""
if "name" in field_dict and "value" in field_dict and "inline" in field_dict:
embed.insert_field_at(
... | e5fc39fbd0c198cbae8e76a69d3066791f627837 | 681,727 |
def output_to_IOB2_string(output):
"""
Convert Stanford NER tags to IOB2 tags.
"""
iob2_tags = []
names = []
previous_tag = 'O'
for _, tup in enumerate(output):
name, tag = tup
if tag != 'O':
tag = 'E'
if tag == 'O':
iob2_tags.append(tag)
... | 1b31df0b72fff2317f3658c6c085d8ae86f03e9a | 681,728 |
import ipaddress
def get_networks(cidrs):
"""Convert a comma-separated list of CIDRs to a list of networks."""
if not cidrs:
return []
return [ipaddress.ip_interface(cidr).network for cidr in cidrs.split(",")] | e17e9982dc52dad9df96891592aaf1fc423c7d18 | 681,729 |
import os
import unittest
def test_otio():
"""Discovers and runs tests"""
try:
# Clear the environment of a preset media linker
del os.environ['OTIO_DEFAULT_MEDIA_LINKER']
except KeyError:
pass
return unittest.TestLoader().discover('tests') | 1520e3d90683ee0cadb4d1c0f27d2a9d788fa948 | 681,731 |
def is_query_to_be_removed(my_dict, remove_param):
"""
"unit" : {
"in": "query",
"description": "Units",
"type": "string",
"enum": ["C", "F", "K"],
"name": "units",
"x-queryexample" : "/TemperatureResURI?units=C"
}
"""
if isi... | 1fbf93fe4855ede8309e0e700c69803093438aa4 | 681,733 |
def _scale_filters(filters, multiplier, base=8):
"""Scale the filters accordingly to (multiplier, base)."""
round_half_up = int(int(filters) * multiplier / base + 0.5)
result = int(round_half_up * base)
return max(result, base) | c403ffcea74be2e0ebeed64ac587bca8cc0e8169 | 681,734 |
def get_homogenous(data):
"""
Keep only homogenous data
"""
keep = []
for seq in data:
label = seq[0].label
hom = True
for ann in seq:
if ann.label != label:
hom = False
break
if hom:
keep.append(seq)
return... | 51e449097325a9243d7d68776c04f902e1823ff4 | 681,735 |
import numpy
def _s_max_op(cn_array, cn_nodata, result_nodata):
"""Calculate S_max from the curve number.
Parameters:
cn_array (numpy.ndarray): curve number array.
cn_nodata (float): nodata value for cn_array.
result_nodata (float): output nodata value.
Return:
ndarray of... | c03556ff3c32da1b6c1e4154e86632f6511b32ec | 681,736 |
def release_for_relnote(relnote):
"""
Turn a release note dict into the data needed by GitHub for a release.
"""
tag = relnote['version']
return {
"tag_name": tag,
"name": tag,
"body": relnote["text"],
"draft": False,
"prerelease": relnote["prerelease"],
} | 4f7d93a75ab8b130eb62df708df5766c4b39137d | 681,737 |
import os
def create_file_structure(kk=''):
"""
Is set to create and destroy the filestructure needed
to run the program so that the files are not needed in the repo
"""
folders_large = ('output_dump',
'output_final', 'output'+str(kk))
folders_large += (folders_large[-1] ... | 34727e274fa2c198ca118dbba195e2dcb3bdb176 | 681,738 |
import os
import hashlib
def md5_checker(localfile):
"""Check for different Md5 in CloudFiles vs Local File.
If the md5 sum is different, return True else False
:param localfile:
:return True|False:
"""
def calc_hash():
"""Read the hash.
:return data_hash.read():
""... | 2d525b17034b627f27d23240fe812e8a8066eaa7 | 681,740 |
import pytz
def localized_datetime(naive_dt, timezone_name='America/Los_Angeles'):
"""Attaches a timezone to a `naive_dt`
"""
tz = pytz.timezone(timezone_name)
dt = tz.localize(naive_dt)
return dt | e1ea9d7db0778d04e9a8d3a0b08eddc97769d9f1 | 681,741 |
def calJIntegral(I1, I2):
"""
计算在I定义的区域上I1*I2的积分
:param I1: 偏导数1,可为I关于x或t的偏导
:param I2: 偏导数2可为I关于x或t的偏导
:return: I1 * I2 在I定义区域上的积分
"""
I = I1 * I2
Jxx = 0
for i in range(I.shape[0] - 1):
for j in range(I.shape[1] - 1):
Jxx += (I[i, j] + I[i, j + 1] + I[i ... | 1bde9c29a5d09d0231522abc6f31c1433a352fb3 | 681,742 |
import re
def parse_time_window(window):
""" Parse the specified time window and return as (float) minutes, or None if invalid """
regexps = {
'^(\d+):?$': lambda match: float(match.group(1)) * 60,
'^(\d+):(\d+)$': lambda match: float(match.group(1)) * 60 + float(match.group(2)),
'^:(\... | c7d5b5fbd0222bc04e051a913a381c56b183daf2 | 681,743 |
def _preprocess_dom_attrs(attrs):
"""Strip leading underscore from keys of dict.
This hack was used in `webhelpers` library for some attributes,
like `class` that cannot be used because it special meaning in
Python.
"""
return {
key.rstrip('_'): value
for key, value in attrs.ite... | 16cae9a708739bd3f1f48652bee4ebcc2ca0d183 | 681,744 |
def sequence(*decorators):
"""
Helper method which creates a decorator that applies the given
sub-decorators. Decorators are applied in reverse order given.
@decorator_sequence(dec_1, dec_2, ...)
def function(...):
...
is equivalent to:
@dec_1
@dec_2
...
def function(.... | bca2d7fe7aec8d7878780769084f1238df4bd781 | 681,745 |
import re
def continuous_pause(sentence: str) -> str:
"""去除多重断句符号"""
return re.sub('[,。,.]{2,}', ',', sentence) | 240812a507babeabcde414d4681fccb3fbf788a7 | 681,746 |
def get_dim_lengths(X_train, Y_train, Y_test=None):
""" packages data dimensions into one object"""
if Y_train.ndim == 1:
n_outcomes = 1
else:
n_outcomes = Y_train.shape[1]
n_ftrs = X_train.shape[1]
n_obs_trn = Y_train.shape[0]
results = [n_ftrs, n_outcomes, n_obs_trn]
if Y_... | 66a036a457e9f091e10d536c927e93b682fd2810 | 681,747 |
def get_array_objects(dict_obj, xml_text):
"""
Returns all array objects contained in the xml.
:param dict_obj:
:param xml_text:
:return:
"""
arrays = {}
if "array" in xml_text.lower():
for obj in dict_obj.obj.obj:
arrays[obj.attrib["o"]] = []
for var in o... | 56d009e3b9b3084f51b6533b0f6f407d367d568e | 681,748 |
def treat_age(age):
"""Age might encounter 'Y' suffix or be a float"""
age = str(age)
if age.endswith('M'):
age = age.rstrip('M')
age = float(age) / 12
age = ('%.2f' if age != int(age) else '%d') % age
else:
age = age.rstrip('Y')
if age:
# strip all leading 0s... | f391df8ee02872ae0ec57f6e3048cd6901d475ff | 681,750 |
def then_by_descending(collection, selector, context):
""":yaql:thenByDescending
To be used with orderBy or orderByDescending. Uses selector to extract
secondary sort key (descending) from the elements of the collection and
adds it to the iterator.
:signature: collection.thenByDescending(selector)... | 1b6fc79a2e1e225345970295bc1d9475a3d59e5b | 681,751 |
import time
def timestamp():
"""Returns an integer use for run timestamps."""
return int(time.time() * 1000000) | 68fd789b3a1d90b098c0ef45cef338a43348e12e | 681,752 |
def int_or_string(val: str):
"""
Loads a value from MO into either an int or string value.
String is returned if we can't turn it into an int.
"""
new_s = val.replace(",", "")
try:
return float(new_s)
except ValueError:
return val | 00562dedbcd1721f55326fa01630c273c4211253 | 681,753 |
from typing import List
def add_jupyter_args(run_args: List[str]) -> List[str]:
"""
Adds `--ip 0.0.0.0` and `--no-browser` options to run args if those are not
there yet.
Args:
run_args: Existing list of run arguments.
Returns:
Modified list of run arguments.
"""
run_args... | 9a41749f4bf73f0abcdeae9cb207e28fc4084ac3 | 681,755 |
def drop_table_sql(name = "small_peptide"):
"""Generate an SQL statement for droping a table."""
return f"DROP TABLE IF EXISTS {name};" | 0380e7ad99cf589bb851f55eb08d647be9f8a87b | 681,756 |
import numpy
import math
def scaling_matrix(factor, origin=None, direction=None):
"""Return matrix to scale by factor around origin in direction.
Point Symmetry: factor = -1.0
"""
if origin is None: origin = [0,0,0]
o = numpy.array(origin[0:3], dtype=numpy.float64, copy=False)
if direction i... | 55a772d8592ac83e47dd7d8f8257b7b70f45eebb | 681,757 |
def regularise_periapse_time(raw, period):
"""
Change the periapse time so it would be between 0 and the period
"""
res = raw
if res < 0:
res += period
if res > period:
res -= period
return res | 3a135b7f45b99f7bdf8a7107d87f606b1f290e66 | 681,758 |
def crop_image(img, rect):
"""
区域截图,同时返回截取结果 和 截取偏移;
Crop image , rect = [x_min, y_min, x_max ,y_max].
"""
if isinstance(rect, (list, tuple)):
height, width = img.shape[:2]
# 获取在图像中的实际有效区域:
x_min, y_min, x_max, y_max = [int(i) for i in rect]
x_min, y_min = ma... | b96e10776ccef637ac349b3dca8f39c9c561d6ce | 681,759 |
def get_redundant_feature_pairs(feature_distance_series, threshold):
"""
Expects results from a `feature_distances` func. Returns redundant
feature pairs, as determined by passed `threshold` for inter-feature
measurement.
"""
return feature_distance_series[
feature_distance... | b17609575d2f92fa0f5bdd1e3d2fac72259162ab | 681,760 |
def get_forecast_regions(year, get_b_regions=False):
"""Get valid forecast region ids for a given year.
:param year: [String] as YYYY-YY
:param get_b_regions: [Bool] Before te rest of norway was th counties, but now they are called B-regions.
:return:
From email describing ... | 66c78bbf1ee3e5061592b61a91eb5bb7a3f3e588 | 681,761 |
import os
def get_azure_config_dir():
""" Returns the user's Azure directory. """
return os.getenv('AZURE_CONFIG_DIR', None) or os.path.expanduser(os.path.join('~', '.azure')) | a0ba29a0898ef9a1d84347ed709d35c9e3bdbc74 | 681,762 |
def _get_join_indices(left_table, right_table, join_conditions):
"""Given the join conditions, return the indices of the columns used in the join."""
left_indices = []
right_indices = []
for cond in join_conditions:
for join_col_name in (cond.left_operand, cond.right_operand):
left... | 6a42bb08ec1c8b370f2ea3e3bbc4bdce375003ff | 681,763 |
import os
def get_DMP_dict(wb, context):
"""get a list of DMP locations"""
ws = wb[context]
contents = []
for i, row in enumerate(ws.rows):
contents.append([])
for j, cell in enumerate(row):
contents[-1].append((cell.value, cell.hyperlink,))
header = contents[0]
out... | fc9a0fd02b94bd40bbedbe2c24466e0bddd29df0 | 681,764 |
import pandas
def aggregate_auc_qh(
auc: pandas.DataFrame,
subset_column: str = "data.subset_name",
heuristic_column: str = "heuristic.heuristic_name",
auc_column: str = "auc_qh",
) -> pandas.DataFrame:
"""
Aggregate AUC QH.
:param auc:
The dataframe containing AUC-QH values for e... | 9cfa3e918bd4f9bfa6890b140aa93337bb478855 | 681,765 |
import random
def fifty_fifty():
"""
Return 0 or 1 with 50% chance for each
"""
return random.randrange(2) | 3c9e5faa870a0cba95b088082d04236710b7c08e | 681,766 |
def trim(s):
"""Removes whitespace, carriage returns, and new line characters."""
s = s.strip().replace("\n", "").replace("\r", "")
return s | def098990ff997f38b80b94a58f4eab573b225b2 | 681,767 |
from pathlib import Path
from typing import Optional
def default_routing_callback(requested_path: Path) -> Optional[Path]:
"""
Default callback for requested path routing that maps direcotry paths to directory/index.html ones.
"""
if '.' not in requested_path.name:
return requested_path / 'index.html'
else:
... | 54b85724633642b5984a30a0654a066edd26d1da | 681,768 |
import typing
def ignored(method: typing.Callable[..., typing.Any], /) -> typing.Callable[..., typing.Any]:
"""``|decorator|``
Used primarily to ignore and not call a specific method.
Used both from the user side and in the source code
(in places where you do not need to call the main methods,
an... | b45523a27c16c0d952a3b839bdb5ac0b37f8bc0d | 681,769 |
def zone_start_stop_json():
"""Return a response for /zone/<ID>/start and /zone/<ID>/stop."""
return {"statusCode": 0, "message": "OK"} | 711739e5739271fde327e4811b868da48bc74ddd | 681,770 |
def filter_values(function, dictionary):
"""Filter ``dictionary`` by its values using ``function``."""
return {k: v for k, v in dictionary.items() if function(v)} | 64d6370f580fad8ad37e51d62e150f1846073b27 | 681,771 |
def intersection(l1, l2):
"""Return intersection of two lists as a new list::
>>> intersection([1, 2, 3], [2, 3, 4])
[2, 3]
>>> intersection([1, 2, 3], [1, 2, 3, 4])
[1, 2, 3]
>>> intersection([1, 2, 3], [3, 4])
[3]
>>> intersec... | a2d89502b4bc42cb012433e1e9e3b326cf433742 | 681,772 |
def initial_variables(densc, epsc, vxc, vyc, divc, tracerc):
"""Returns the initial variables at t=0"""
return densc, epsc, vxc, vyc, divc, tracerc | 226e5ec45ec63af2646957c6dcd9fac3fa9d2c10 | 681,773 |
import re
def remove_html_a_element_for_dingtalk(s):
"""
Replace <a ..>xx</a> to xx and wrap content with <div></div>.
"""
patt = '<a.*?>(.+?)</a>'
def repl(matchobj):
return matchobj.group(1)
return re.sub(patt, repl, s) | 40d52f7ae7971803aac859ec18c3da2115446bad | 681,774 |
import re
def dist_info_name(distribution, version):
"""Get the correct name of the .dist-info folder"""
escaped_name = re.sub(r"[^\w\d.]+", "_", distribution, flags=re.UNICODE)
escaped_version = re.sub(r"[^\w\d.]+", "_", version, flags=re.UNICODE)
return '{}-{}.dist-info'.format(escaped_name, escaped... | 018a0fa356637fd1867d6476b276b069c43b92d2 | 681,775 |
def has_attribute(module_name, attribute_name):
"""Is this attribute present?"""
init_file = '%s/__init__.py' % module_name
return any(
[attribute_name in init_line for init_line in open(init_file).readlines()]
) | 33d0a8f7e0d692b527a76c36b442fb34f71c7e61 | 681,776 |
def delete_file_generic(ssh_conn, dest_file_system, dest_file):
"""Delete a remote file for a Junos device."""
full_file_name = "{}/{}".format(dest_file_system, dest_file)
cmd = "rm {}".format(full_file_name)
output = ssh_conn._enter_shell()
output += ssh_conn.send_command_timing(cmd, strip_command=... | 1f283e695af9231f74ec655f66980a2ae1dd8710 | 681,778 |
def lexical_distance(a, b):
"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or ... | 62f5df8460975517b9aff4336eb1679b204c9686 | 681,779 |
import os
def has_fork():
"""
Does this OS have the `fork` system call?
"""
return "fork" in os.__dict__ | 252b850adaad523f5ab68cc0da99cbe8ee1a1c3d | 681,780 |
def repr2(x):
"""Analogous to repr(),
but will suppress 'u' prefix when repr-ing a unicode string."""
s = repr(x)
if len(s) >= 2 and s[0] == "u" and (s[1] == "'" or s[1] == '"'):
s = s[1:]
return s | e5eb7ff30ce2e225eab3a8769e7b65a92abede34 | 681,781 |
def is_currently_on_packet(freshman):
"""
Helper method for the search command
Handles the filtering of results
"""
for _ in filter(lambda packet: packet["open"], freshman["packets"]):
return True
return False | b1dcaa39fa1d354e2b1bf261fc25daf621c361d2 | 681,782 |
def getEdgesBetweenThem(nodes,edges):
"""return all edges which are coming from one of the nodes to out of these nodes"""
edg = set([])
for (n1,n2) in edges:
if (n1 in nodes and n2 in nodes):
edg.add((n1,n2))
return edg | 4fde4dca7aab343f3d2187335c802cfd0bc1f35a | 681,783 |
import sys
import platform
def _checkCPython(sys=sys, platform=platform):
"""
Checks if this implementation is CPython.
This uses C{platform.python_implementation}.
This takes C{sys} and C{platform} kwargs that by default use the real
modules. You shouldn't care about these -- they are for testi... | d94045933357a5aa5c6f5f7023f58f2adf1eef64 | 681,784 |
def quadrant(xcoord, ycoord):
"""
Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for
"""
xneg = bool(xcoord < 0)
yneg =... | 1fd54d84b4b91666368b93fad2f403ca8d098ab4 | 681,785 |
def get_fix_string(input_string: str, length: int):
"""
Transforms input_string to the string of the size length.
Parameters
----------
input_string : str
input_string
length : int
length of output_string, if -1 then output_string is the same as input_string
Returns
---... | c450b6a223eab85e1d74ae9ced1aea5251d95fcd | 681,786 |
def get_elements_of_type(xform, field_type):
"""
This function returns a list of column names of a specified type
"""
return [f.get('name')
for f in xform.get_survey_elements_of_type(field_type)] | 8335dc76395a0cb8fd05931b447628634a17408c | 681,787 |
from typing import Sequence
from typing import Tuple
from typing import Optional
import re
def find_token(
string: bytes, pos: int, tokens: Sequence[bytes]
) -> Tuple[Optional[bytes], int]:
"""Find the first occurrence of any of multiple tokens."""
pattern = re.compile(b"|".join(re.escape(token) for token... | 8f2b194a998ef97e34eb96261130fd37fc7f6600 | 681,788 |
def parse_phrase_strings(phrase_strings):
"""Parse a phrase string passed from the JS application and return the
corresponding sequence texts.
"""
sequence_texts = list()
for phrase_string in phrase_strings:
# Split on underscore to remove the unnecessary components, then
# restor... | a450b033079e90a6993dc1cef634bb796325dbb2 | 681,789 |
def get_heatmap_y_sample_sizes(parsed_mutations, sample_sizes):
"""Get sample size y axis values of heatmap cells.
:param parsed_mutations: A dictionary containing multiple merged
``get_parsed_gvf_dir`` return "mutations" values.
:type parsed_mutations: dict
:param sample_sizes: A dictionary co... | 17453adb768fd2acc7ae82f5852a1c8e5eaf4cc7 | 681,790 |
from typing import Callable
import click
def masters_option(command: Callable[..., None]) -> Callable[..., None]:
"""
An option decorator for the number of masters.
"""
function = click.option(
'--masters',
type=click.INT,
default=1,
show_default=True,
help='The... | d9b014e5d4624f6ad15ee0695a3724ab0ec67725 | 681,791 |
def cloudfront_public_lookup(session, hostname):
"""
Lookup cloudfront public domain name which has hostname as the origin.
Args:
session(Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
hostname: name ... | f1d3914f5fa5035c6f3105af052bf3e605cbea7a | 681,793 |
def check_queue(queue, config):
"""
Check length and policy of a single queue
:param queue: Queue form rabbit
:param config: Desired queue state
:return: length of a queue and lists of warnings and errors
"""
warnings = []
errors = []
length = queue['messages_ready']
if length >... | aede6f76f87e62b7972f51d564d1f3080059a327 | 681,794 |
def news_dict(cleaned_articles):
"""
For the cleaned_articles data, extract only the headline and summary.
:param cleaned_articles: List of dictionaries, extract only the target information.
:return: dictionary of Headlines to Summary.
"""
temp_dict = {}
for i in cleaned_articles:
te... | bfde1ebdb1eda9dcba4211fd1bbc3b1f2611fa3a | 681,796 |
import logging
def _create_list_of_class_names(view, label_field):
"""Create list of class names from the label field.
Args:
view (voxel51 view object) - the voxel51 dataset
label_field (str) - label field set in config
Returns:
class_names (list)
"""
logging.info("Extrac... | ee1ac11da75356461657379608648eae357b5864 | 681,797 |
def extend_file_data(data):
""" Extend file data """
ext_data = []
for b in data:
ext_data.extend([b] + [0] * 15)
return bytes(ext_data) | 52312d7b687295cfdb3e7630488888e468394baf | 681,798 |
import torch
def _get_triplet_mask(labels, device):
"""Return a 3D mask where mask[a, p, n] is True iff the triplet (a, p, n) is valid.
A triplet (i, j, k) is valid if:
- i, j, k are distinct
- labels[i] == labels[j] and labels[i] != labels[k]
Args:
labels: tf.int32 `Tensor` with s... | 047012e734461e2305e5d0b28b40392d21bc46a8 | 681,799 |
from typing import OrderedDict
def node_types():
"""
Returns dictionary that provides a mapping between tpDcc object types and DCC specific node types
Can be the situation where a tpDcc object maps maps to more than one MFn object
None values are ignored. This is because either do not exists or there... | a9f13b62f96c64ec11a8970ce087cd9fa7f0e432 | 681,800 |
def _ResolvePortName(args):
"""Determine port name if one was not specified."""
if args.port_name:
return args.port_name
if args.protocol == 'HTTPS':
return 'https'
if args.protocol == 'SSL':
return 'ssl'
if args.protocol == 'TCP':
return 'tcp'
return 'http' | 020d253db9bc0a5ecf5d724206789c0e3880ae2b | 681,801 |
def to_dict_key(k):
"""Recursively convert lists to tuples.
This only looks into lists, which seems to be good enough for testing
"""
if isinstance(k, list):
return tuple(to_dict_key(item) for item in k)
else:
return k | 0601598adbc2d8535f92c56a570bf495c6fc273e | 681,802 |
import binascii
def hex_encode(string):
"""! @brief Return the hexadecimal representation of the binary data."""
return binascii.hexlify(string) | a304826094686a78efa093219eae253c74f43978 | 681,803 |
def check_row(board, num_rows, num_cols):
"""check if any 4 are connected horizontally(in 1 row)
returns bool"""
won = False
for row in range(num_rows):
for col in range(num_cols - 3):
start = board[row][col]
if start == " ":
continue
won =... | 8af52a5de8a744e90dfbfee730014540be474f0e | 681,804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.