content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import subprocess
def ping(host: str) -> bool:
"""
ping host once, return True if successful
"""
rc = subprocess.run(["ping", "-4", "-c", "1", host],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).returncode
return rc == 0 | ee01504739758993db95669e22b46748e1b0583f | 685,978 |
import re
def _agg_removing_duplicates(agg_elem):
"""Aggregate while removing the duplicates.
Aggregate the labels or alt labels together as a single element
can have several Wikidata entities that need to be merged.
Args:
agg_elem (list of string): elem to aggregate
Returns:
st... | f0b17d9acdd97452a728ed990f8150a72cbbe0f8 | 685,980 |
def sudo_wrap_command(command):
"""adds a 'sudo' prefix to command to run as root.
no support for sudo'ing to configurable users/groups"""
# https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L605-L623
# https://github.com/mathiasertl/fabric/blob/master/fabric/state.py#L374-L376
... | ab16a412ab238c4bc6737434bfc0125837578f6d | 685,982 |
def get_aps_in_grid_inorder(ue_location, neighboring_aps_in_grid_unordered):
"""
Function to retrieve a list of neighboring APs in the increasing order
of ue_ap distance
"""
def distance(p1, p2):
return((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)
neighboring_aps_in_grid = sorted(
neighbo... | 8da92da801a15f966febbb62ac8040b678ab3cd7 | 685,983 |
def hamming_distance(s, target):
"""Return the Hamming distance between two input strings.
Shamelessly taken from Wikipedia article on Hamming Distance."""
if len(s) != len(target):
raise ValueError("Strings must be same length.")
return sum(bool(ord(c1) - ord(c2)) for c1, c2 in zip(s, target)) | 2ec5c268007367d81ad96c36f166d53aa7a9fd7c | 685,984 |
def get_elbs(**kwargs):
"""
Fetches one page elb objects for a given account and region.
"""
client = kwargs.pop('client')
return client.describe_load_balancers(**kwargs) | 1b6e863deec698009c3b3909973dd4df40adb234 | 685,985 |
def processbytes(rawdata):
"""
# Scenario good data:
>>> s = "jürgen" gooddata = s.encode('utf-8') gooddata b'j\xc3\xbcrgen'
>>> rawdata = gooddata
>>> step1 = rawdata.decode("utf-8") step1 'jürgen'
>>> step2 = step1.encode("raw_unicode_escape") step2 b'j\xfcrgen' # code
>>> point U+00FC... | 7e2c4e8d0ee2b2f06cc1dd9c3fc0d8e637a1aff8 | 685,986 |
import re
def is_git_error(txt):
"""
Whether response from the git command includes error
:param str txt:
:return:
:rtype: bool
"""
b_error = re.findall(r'^(.*?(\bfatal\b)[^$]*)$', txt, re.I | re.MULTILINE) \
or re.findall(r'^(.*?(\bCONFLICT\b)[^$]*)$', txt, re.I | re.MULTIL... | 777469746ba999abd36ad1228d53f25a0a9cadaf | 685,987 |
import shutil
def del_dir(directory):
"""Delete directory"""
try:
shutil.rmtree(directory)
return 0
except FileExistsError:
return 1 | cc0df5c61eea1979e44b74909cbb479a68c9d5a0 | 685,988 |
import six
import re
def mask_passwords(input):
"""
The regex pattern covers both json string and python dictionaries. Note that an open quota
in a key parameter can be either ' or "
:return a printable string with masked passwords
"""
if isinstance(input, dict):
input = str(input)
... | 60e3b26684ca734c0f8694aa0a34a9b715044a3c | 685,989 |
def mro_lookup(cls, attr, stop=(), monkey_patched=[]):
"""Return the first node by MRO order that defines an attribute.
:keyword stop: A list of types that if reached will stop the search.
:keyword monkey_patched: Use one of the stop classes if the attr's
module origin is not in this list, this to ... | 7cdcb8a67a80c5cf07d562e827d4bfef6ddc4672 | 685,990 |
def writeonly(func):
"""Marks an API function as write-only"""
func._write_only_ = True
return func | c53124fb28668ddf0750ea5646633963effbf7d2 | 685,991 |
def drawmaze(maze, set1=[], set2=[], c='#', c2='*'):
"""returns an ascii maze, drawing eventually one (or 2) sets of positions.
useful to draw the solution found by the astar algorithm
"""
set1 = list(set1)
set2 = list(set2)
lines = maze.strip().split('\n')
width = len(lines[0])
heig... | 1ce8d557a322edd341b9f201390a19c7b100543a | 685,992 |
def calc_l2distsq(x, y):
"""
Calculate L2 distance between tensors x and y.
"""
d = (x - y)**2
return d.view(d.shape[0], -1).sum(dim=1) | 1e8689ef4605a3a23f9aef0e1e0cbd1a2546851e | 685,994 |
def define(func):
"""Execute a function and return its result.
The idea is to use function scope to prevent pollution of global scope in
notebooks.
Usage::
@define
def foo():
return 42
assert foo == 42
"""
return func() | a2791c5124620e85156d8900b11567745e004966 | 685,995 |
def parse_string_to_list(line):
"""Parse a line in the csv format into a list of strings"""
if line is None:
return []
line = line.replace('\n', ' ')
line = line.replace('\r', ' ')
return [field.strip() for field in line.split(',') if field.strip()] | e1b5346c77be8a870b11fa880ae31b985cae1aa8 | 685,996 |
def credentials_are_valid(credentials):
"""check the credentials by accessing LDAP or whatever"""
return True | ae12ce0ffb9ba8b8439c30e827345932096fab44 | 685,997 |
def find_creation_sequence(G):
"""
Find a threshold subgraph that is close to largest in G.
Returns the labeled creation sequence of that threshold graph.
"""
cs = []
# get a local pointer to the working part of the graph
H = G
while H.order() > 0:
# get new degree sequence on su... | 18d406dfa8b2b49dae2f7f36f2cd1cbcb757d538 | 685,998 |
def tlv_type(field):
"""Returns the tlv type."""
if field.is_map:
return 'map <{0}, {1}>'.format(
tlv_type(field.map_key), tlv_type(field.map_value))
if field.enum_type and field.is_array and field.enum_type.is_bitmask:
return 'uint'
if field.is_array:
return 'array'
if field.struct_ty... | 534c99edc12798c8ebd9ae678b0ff7f16f799c34 | 685,999 |
import math
def get_entropy(labels):
"""
0 entropy means that all of the classifications in the data set are the same
1 equal number of labels
:param set:
:return:
"""
total = len(labels)
num_positive = 0
num_negative = 0
for element in labels:
if element == 0:
... | 5732da2788bce53cbf58c3168764009efe9b1d79 | 686,001 |
from typing import Optional
import re
def parseResourceId(resource_uri: str, resource_type: str) -> Optional[str]:
"""Parses the resource ID of the given type from the given URI, or returns None if not found."""
matches = re.search('{}/([^/]+)'.format(resource_type), resource_uri)
if not matches:
... | fffc96ffda64266cc7cebd7606006702b5bb1150 | 686,002 |
def _get_manifest_path(repository, manifest=None):
"""Return the path for a manifest, or list of manifests if manifest is empty.
"""
if manifest:
return '/acr/v1/{}/_manifests/{}'.format(repository, manifest)
return '/acr/v1/{}/_manifests'.format(repository) | 3f6d6e368805651fc78fefd64ea51d081aaeb77d | 686,003 |
def replicate_z_samples(t, n_z_samples):
"""Replicates a tensor `n_z_samples` times on a new first dim."""
return t.unsqueeze(0).expand(n_z_samples, *t.shape) | 9285dddb7029e05382a46613ce4cf0d3b7244393 | 686,005 |
def _invalid_chars_in_crate_name(name):
"""Returns any invalid chars in the given crate name.
Args:
name (str): Name to test.
Returns:
list: List of invalid characters in the crate name.
"""
return dict([(c, ()) for c in name.elems() if not (c.isalnum() or c == "_")]).keys() | d2d2d05a9d94c77dcaff6b9f05c3dc2543ab0a15 | 686,006 |
def make_lookup_phrase(row):
"""Return full name and address for google geo api text search."""
address_text = "{} {}".format(row[1], row[2])
return address_text | b361fab034f05602d6902cc4d36bd823f2301fc1 | 686,007 |
from typing import Tuple
def _func_to_class_and_method(fn) -> Tuple[str, str]:
"""Returns the names of the function's class and method."""
split = fn.__qualname__.split('.')
if len(split) >= 2:
class_name = split[-2]
method_name = split[-1]
else:
module_name = fn.__module__
class_name = module... | 1549230164fd1d923fcd3f475ba4626893f71081 | 686,009 |
def get_properties(title):
"""
Bykov, p. 40
Density normal, kg/m3: T = 273 K, p = 101300 Pa.
Density standard, kg/m3: T = 293 K, p = 101300 Pa.
Molar mass, kg/kmole.
"""
if title == 'methane':
return {'formula': 'CH4', 'density_normal': 0.717, 'density_standard': 0.66... | 72ec46e685f09cbf80aa72ed34576b13ae74a169 | 686,010 |
def hex_to_rgb(_hex):
"""
Convert a HEX color representation to an RGB color representation.
hex :: hex -> [000000, FFFFFF]
:param _hex: The 3- or 6-char hexadecimal string representing the
color value.
:return: RGB representation of the input HEX value.
:rtype: tuple
"""
_hex = _hex.... | ea3e9eb18a1811077b095b766fc5e179e048c0ba | 686,011 |
def create_training_data(algorithm_env, n=5):
"""Samples from algorithm env and creates 4 variants per sample.
- executable code sample (Estimator class)
- executable code sample (Estimator instance)
- non-executable partially randomized code
- non-executable fully randomized code
"""
train... | b5e68cd8d272e4b4081fe7d45c46039531eb7c36 | 686,012 |
def check_streams(streams='*'):
"""
Checks that the streams given are a list containing only possible streams, or is all streams - '*'.
"""
possible_streams = ['prices_ahead', 'prices', 'temperatures', 'emissions', 'generation-mix']
if isinstance(streams, list):
unrecognised_streams = list... | 3d96377b7b519e438841aab66dbc1cbdd492a1a1 | 686,013 |
import copy
def is_subsequence(seq1, seq2):
"""Check if seq1 is a subsequence of seq2
>>> is_subsequence(((2,), (3, 5)), ((2, 4), (3, 5, 6), (8,)))
True
>>> is_subsequence(((1,), (2,)), ((1, 2), (3, 4)))
False
>>> is_subsequence(((2,), (4,)), ((2, 4), (2, 4), (2, 5)))
True
"""
seq... | 30b0c884123ab15358a67e01afc5bbdf4059fe3f | 686,014 |
def truncate(source, max_len: int, el: str = "...", align: str = "<") -> str:
"""Return a truncated string.
:param source: The string to truncate.
:param max_len: The total length of the string to be returned.
:param el: The ellipsis characters to append to the end of the string if it exceeds max_len.
... | fae74fa46f1e3aaf06c9b2d7cf4be6f31fce2596 | 686,015 |
def is_parser_function(string):
"""Return True iff string is a MediaWiki parser function."""
# see https://www.mediawiki.org/wiki/Help:Extension:ParserFunctions
return string.startswith('#') # close enough for our needs | aa729ecade5db57870535a6acf0a366541fb64b4 | 686,016 |
def get_scores(database, person, multi=True):
"""
Return a string representing the scores a person has in the database.
The parameter `multi' is to specify whether the scores are used for
displaying the scores of a single person or multiple people.
"""
indent = ' ' if multi else ''
retu... | 1f3320473dbef113b6aeed0a84d745b852f86008 | 686,017 |
def split_b64_file(b64_file):
"""Separate the data type and data content from a b64-encoded string.
Args:
b64_file: file encoded in base64
Returns:
tuple: of strings `(content_type, data)`
"""
return b64_file.encode('utf8').split(b';base64,') | 011a5d5f38b8ba2914fb89439314081949d3113b | 686,018 |
import os
import subprocess
def _kubectl(args):
"""
Executes kubectl with args as arguments
"""
snap_bin = os.path.join(os.sep, "snap", "bin")
env = os.environ.copy()
env["PATH"] = os.pathsep.join([snap_bin, env["PATH"]])
cmd = ["kubectl", "--kubeconfig=/home/ubuntu/config"]
cmd.extend... | ce2fed75da56f8aa10f41e9a6aed0a7b163a439f | 686,019 |
def _dequantized_var_name(var_name):
"""
Return dequantized variable name for the input `var_name`.
"""
return "%s.dequantized" % (var_name) | 5bb8747a5681ed6bd4dce8ba726c260f8b32bace | 686,020 |
def effecticeInterestRate():
"""
This program help you to find the effective interest rate!
"""
rate = float(input("What is your interest rate:\n"))
compound = int(input("How many times in a year you give interest:\n"))
EIR = (1 + ((rate/100)/compound))**compound - 1
eir = EIR*100
retur... | 2f35299797a977f000556846611568e8a3abc9b1 | 686,021 |
def get_ylabel(cube, inargs):
"""get the y axis label"""
if inargs.ylabel:
ylabel = inargs.ylabel
else:
ylabel = str(cube.units)
if ylabel == 'kg m-2 s-1':
ylabel = '$kg \: m^{-2} \: s^{-1}$'
return ylabel | c18a635e24ce4479eab97daa4f61d5b5ccf75d8c | 686,022 |
def get_bytes_from_blob(val) -> bytes:
""" 不同数据库从blob拿出的数据有所差别,有的是memoryview有的是bytes """
if isinstance(val, bytes):
return val
elif isinstance(val, memoryview):
return val.tobytes()
else:
raise TypeError('invalid type for get bytes') | 24792b4c62d4f8d2c4dc2a574eda4857e5f65816 | 686,023 |
def arcs2d(arcs):
"""Convert arcseconds into degrees."""
return arcs / 3600.0 | 0570463fa2c0a2723959f43767319b9a8d6c75e4 | 686,024 |
def hamming_distance(a, b):
"""Returns the Hamming distance between two strings of equal length"""
try:
assert len(a) == len(b)
return sum(i != j for i, j in zip(a, b))
except AssertionError as error:
print('Barcode lengths are not equal for {}. {}'.format(a, b))
raise(error) | f7fef64e7030faea466aa9e60a45f98807218cd0 | 686,025 |
import os
def header_dir():
"""Return the path to the C header directory"""
return os.path.join(os.path.abspath(os.path.dirname(__file__)), "include") | 83c8f28c2408e1a93e48da1457331699edce01f1 | 686,026 |
def tf_binary(dtm):
"""
Transform raw count document-term-matrix `dtm` to binary term frequency matrix. This matrix contains 1 whenever
a term occurred in a document, else 0.
:param dtm: (sparse) document-term-matrix of size NxM (N docs, M is vocab size) with raw term counts.
:return: (sparse) bina... | 7df0af552f70e8e38d86b01de6871d6db8b79b35 | 686,027 |
def get_slurm_url(slurm_config: dict, url_type: str):
"""get_slurm_nodes_url Get Slurm Nodes Url
Get the url for reading nodes info from slurm
Args:
slurm_config (dict): Slurm Configuration
url_type: Url type. nodes or jobs
"""
base_url = f"http://{slurm_config['ip']}:{slurm_config... | 3474688f0f0b53ec3b15864ecd76e4d872493131 | 686,028 |
import os
def normalized_path(value, must_exist=False):
"""Normalize and expand a shorthand or relative path."""
if not value:
return
norm = os.path.normpath(value)
norm = os.path.abspath(os.path.expanduser(norm))
if must_exist:
if not os.path.exists(norm):
raise ValueE... | e6f9fded3793959ef4dce8b3cf577d1c03a05cda | 686,029 |
def unzip(iterable):
"""
Unzip iterable of tuples into tuple of iterables
:param iterable: Any iterable object yielding N-tuples
:return: A N-tuple of iterables
"""
return zip(*iterable) | 7029d87b55febbfedeae87c4471891c4a54e3885 | 686,030 |
import re
def strip_characters(string: str, regex: str = r"[]") -> str:
"""
Remove everything that is not in the list of allowed chars
"""
return re.sub(regex, "", string) | b35c175db6d7d1a07500f1b839253b80b6ea42ad | 686,031 |
import random
def add_salt(string):
"""处理数据加盐"""
_ = [i + str(random.randint(0, 9)) for i in string]
res = "".join(_)
return res | ea5b17f06a5c64e116b0fd5f4570b34aaf537916 | 686,032 |
def make_matrix(num_rows, num_cols, entry_fn):
"""构造一个第 [i, j] 个元素是 entry_fn(i, j) 的 num_rows * num_cols 矩阵"""
return [
[
entry_fn(i, j) # 根据 i 创建一个列表
for j in range(num_cols)
] # [entry_fn(i, 0), ... ]
for i in range(num_rows)
] | e76598f8b87a50b99da6214cd18f37479ef64724 | 686,033 |
def get_id_from_url(url: str) -> str:
"""Get the id of the image from the url.
The url is of the format https://sxcu.net/{image_id},
so we simply split the url by `/` and return the last part.
Parameters
----------
url : str
The original url.
Returns
-------
str
The... | 31abdbcbac9c05c1b396b0b6d7c578cf0a7b3b9c | 686,034 |
def replace_from_map(data, encode):
"""replace substrings in DATA with replacements defined in ENCODING"""
for pattern, replacement in encode.items():
data = data.replace(pattern, replacement)
return data | 278c60afb25f3db2fd65a5ac34da9c1ce0ac0494 | 686,035 |
def extract_var_key(raw_line: str, var_id: str) -> str:
"""
Extract the key from an line in the form "dict['key']" or
"dict.get('key', *args)".
"""
line = raw_line.strip()[len(var_id) :]
state_var = ""
if line[0] == "[":
state_var = line[2:-2]
elif line[0:4] == ".get":
ca... | 425a4fee878b262c52cb744ae93cd0730416ea37 | 686,036 |
def inherits_from(obj, a_class):
"""
Function that determine if a class is an inherited class.
Args:
obj (object any type): The object to analyze.
a_class (object any type): The reference object.
Returns:
Returns True if the object is an instance of a class that
inher... | 40152435e607594a628be05615a76471d948c0b3 | 686,037 |
def get_resource_by_path(path, resources):
"""gets the resource that matches given path
Args:
path (str): path to find
resources (list(str)): list of resources
Returns:
dict: resource that matches given path, None otherwise
"""
return next(
(x for x in resources if ... | 6af716de44b8450ad01b2be402aae12aeb63e4f5 | 686,038 |
def get_vigra_feature_names(feature_names):
"""
For the given list of feature names, return the list of feature names to compute in vigra.
Basically, just remove prefixes and suffixes
For example: ['edge_vigra_mean', 'sp_vigra_quantiles_25'] -> ['mean', 'quantiles']
"""
feature_names = list... | ca73810bb66b092046f83e39ccc54a1beb395c36 | 686,039 |
def search_triples(token, conceptnet_triples, limit=20):
"""检索出头或者尾部包含该词的三元组"""
triples = []
core_entitys = set()
# search triples
for triple in conceptnet_triples:
head, rel, tail = triple[0], triple[1], triple[2]
if token in head.split("_") or token in tail.split("_"):
... | b013aa58a9e970a3477a9b266fe18cda047a2aff | 686,040 |
def getmeta_altafsir(fname, cfg, madhab_mapping, tafsir_mapping):
""" Get metadata info of fname.
Args:
fname (str): filename from which to get metadata.
cfg (Config): configuration data.
madhab_mapping (dict): madhab metadata.
tafsir_mapping (dict): tafsir metadata.
Return... | 9cb6749182d45f0d13c63629dcf742dd169e9847 | 686,041 |
def default_wire_map(ops):
"""Create a dictionary mapping used wire labels to non-negative integers
Args:
ops Iterable[Operation]
Returns:
dict: map from wires to sequential positive integers
"""
# Use dictionary to preserve ordering, sets break order
used_wires = {wire: None ... | 30357e173d9e19a69a142c0070d51d6b96de125d | 686,043 |
def bestMutation(shape, model, cycles=50, startHeat=100, heatDiv=1.01, alpha=.5):
"""
Mutates a shape for a given number of cycles and returns the best scoring change
:param shape: The shape to mutate
:param model: The model object
:param cycles: The number of cycles (attempts at mutation)
:para... | c064f803b755cbe0e97923d3bf5245e8793ccbbd | 686,044 |
def get_common_name(names):
"""Find left substring common to all names, by splitting names on spaces,
and possibly ignoring certain common words.
>>> get_common_name([
'Polyfield Soft Vinyl Patient Pack with small gloves',
'Polyfield Soft Vinyl Patient Pack with medium gloves',
'Pol... | 1dfb76c19791963dba7dbfcd18c53b4215e14544 | 686,045 |
def allow_timefloor(submitmode):
"""
Should the timefloor mechanism (multi-jobs) be allowed for the given submit mode?
:param submitmode: submit mode (string).
"""
return True | 7659db621177ad2dcd53cf2198555915d2dc8c43 | 686,046 |
def get_base_worker_instance_name(experiment):
"""GCE will create instances for this group in the format
"w-|experiment|-$UNIQUE_ID". 'w' is short for "worker"."""
return 'w-' + experiment | 81ecd22a33608e1c2aafb97905684311c6b33241 | 686,047 |
import os
def get_exit_status(status):
"""Get the exit status of a child from an os.waitpid call.
Args:
status: The return value of os.waitpid(pid, 0)[1]
Returns:
The exit status of the process. If the process exited with a signal,
the return value will be 128 plus the signal num... | 99d270c568779cd101e1eb3e071d597a92465849 | 686,048 |
import random
def generate_seed_indicator(seed_symbol: list) -> str:
"""
Generate a special character to separate the seed and code from the `seed_symbol`.
"""
seed_indicator: str = seed_symbol[random.randint(0, len(seed_symbol) - 1)]
seed_symbol.remove(seed_indicator)
return seed_indicator | 03b4fb87353912561337ea687c2f6b7e46ce98af | 686,049 |
import torch
def objective(expec_t, look_back=20000):
"""
Creates the objective function to minimize.
Args:
expec_t (list): time-dependent quantum yield
look_back (int): number of previous time steps
over which to average the yield
Returns:
obj (torch.Tensor): obje... | ba023a48c462225814325e8c823ae527e51da10f | 686,050 |
def format_loading_percent(f, ndigits=0):
"""format .0001 as "<1%" instead of 0%"""
limit = 10 ** -(ndigits + 2)
if limit > f > 0:
return f"<{limit:.{ndigits}%}"
if 1 > f > (1 - limit):
return f">{1 - limit:.{ndigits}%}"
return f"{f:.{ndigits}%}" | 3f9867a2487c838c5b1c54e652e9394f1c14891d | 686,051 |
import requests
import json
async def get_items(dumpDataToFile=False):
"""
get and return all items that could be sold
"""
items = {}
weapons_data = requests.get("https://valorant-api.com/v1/weapons").json().get("data")
if dumpDataToFile:
with open("data/weapons_data.json", ... | 0bb8554e8dea9dc20da572bd37e01bac197b5965 | 686,052 |
def compare_dict_keys(dict_1, dict_2):
"""Check that two dict have the same keys."""
return set(dict_1.keys()) == set(dict_2.keys()) | 47bb95d242a968fafbef17a960bbd4724ddaa02e | 686,053 |
from typing import Type
import importlib
def import_class(module: str, cls_name: str) -> Type:
"""Returns the class given as string."""
mod = importlib.import_module(module)
cls = getattr(mod, cls_name)
return cls | a57283658cfb43b28ce5b412225040e69370fca6 | 686,054 |
def read_file(filename, mode='r', encoding='utf-8'):
"""读取文件数据"""
contents, labels = [], []
with open(filename, mode=mode, encoding=encoding, errors='ignore') as f:
for line in f:
try:
label, content = line.strip().split('\t')
if content:
... | fd82ece2b5368c48be180431d221d2d59a5d3496 | 686,055 |
def clipping(y,miny=-5,maxy=5):
""" clipping of signal
inputs:
y - signal [V] array of floats
miny, maxy - lowest, highest values [V], scalar floats, default -5 ..+5 [Volt]
outputs:
y - clipped signal [V]
better use: numpy.clip
"""
y[y < miny] = miny
y[y > maxy] = ... | 11de5d21fdf711ddcd24e61c80196fdcda23c779 | 686,057 |
def get_price_estimate(client, coordinates):
"""Returns the price estimate data for the given `coordinates`.
:param client: :class:`UberRidesClient <UberRidesClient>` object.
:param client: :class:`Coordinates <Coordinates>` object.
:return: price estimate data
:rtype: list of dictionaries
"""
... | bdbe3d03cddb9649a6a0c942e7ed131a732b1414 | 686,059 |
def get_hyper(h, method):
"""Get hyper sweep."""
sweeps = {'implicit': [h.sweep('alpha', h.discrete([0.01, 0.1, 0.25, 0.5]))]}
return h.product([
h.sweep('num_tasks', h.discrete([100, 1_000, 10_000, 100_000,
1_000_000])),
# h.sweep('batch_size', h.discrete([32,... | 61859d0083366defb85e97be73245ea0e59d2b01 | 686,060 |
def get_ident():
"""Dummy implementation of _thread.get_ident().
Since this module should only be used when _threadmodule is not
available, it is safe to assume that the current process is the
only thread. Thus a constant can be safely returned.
"""
return 1 | f52dbf23499c127a84451a5e74ac643c0d9eb843 | 686,061 |
def readFile(_file):
"""
Name: readFile
Purpose: If the user chooses to enter a file this function will return a list of the contents
Returns: List of contetns of the file
"""
contents = []
with open(_file, 'r') as f:
contents = f.readlines()
for line in contents:
... | 6d6a8149c832067b9548e1a72efb3e2a7316f57c | 686,062 |
from bs4 import BeautifulSoup
def slide_factory(tag, id: int, classes: list = []):
"""
Factory for creating slides from a given Beautifulsoup tag, id, and list of classes to use for the slide.
Args:
tag (_type_): The tag to put into the slide.
id (int): The id of the slide (used for the J... | 5a3b4d38f390fe32d753bbafaab35edf00d4fab9 | 686,063 |
import re
def remove_optional_regex(pattern, name):
"""Removes an optional part of the regex by capture name
Must be of the format '(?:[anything](?P<[name]>[anything])[anything])?'
"""
return re.sub("\(\?:[^(]*\(\?P<{}>[^)]*\)[^)]*\)\?".format(name), "",
pattern) | 663f98b0bb4f178105895a3d9773b4626ec55f67 | 686,064 |
def column_selection(names, columns):
"""
select the columns that contain any of the value of names
Args:
names (TYPE): DESCRIPTION.
columns (TYPE): DESCRIPTION.
Returns:
features (TYPE): DESCRIPTION.
"""
features = []
for col in columns:
if any([name in co... | ceec497ea8753636d492633a3b0e72d7a7154bd8 | 686,065 |
def remove(inputvtk,outputvtk):
"""Scan the inputvtk file line by line until the keyword VERTICES is found and remove corresponding lines
"""
fout=open(outputvtk, 'w')
with open(inputvtk,'r') as fin:
skip_lines = 0
for line in fin.readlines():
if line[:8] == "VERTICES":
line = line.split()
skip_line... | ed34cc3d51157239313c4bb68c56910b95d842b9 | 686,066 |
def buildPattern(nspecies, s, members=None):
"""build a present/absent pattern for species
in set s.
"""
pattern = []
for x in range(nspecies):
if x in s:
if members:
pattern.append(str(len(members[x])))
else:
pattern.append("1")
... | 9d4ab7d2e3753c238a2e62d26fe73e049249b83a | 686,067 |
def _clean_key(root_key, filekey):
"""Return the cleaned key 'filekey', using 'root_key' as the root
Args:
root_key (str): root_key for accessing object store
filekey (str): filename to access in object store
Returns:
str: Location to access the file
"""
i... | bf39e95a182506900b0cdb110f1fea2566e85520 | 686,068 |
def get_pipe_parent(job):
"""Check if the job has a pipe_from parent and if so return that. If
the does does not have any pipe targets, the job itself is returned.
:param job: the job
:type job: :class:`jip.db.Job`
:returns: pipe source job or the job itself if no pipe parent is found
"""
i... | 62195fa0b1b83bc778e780d7e40e66519754cb81 | 686,069 |
def _shift_twelve(number):
"""Shifts the number by 12, if it is less than 0.
Parameters
----------
number : int
Returns
-------
int
"""
return number + 12 if number < 0 else number | cca6689a7caabbaae0e352b4e91b64ebb1f63ad7 | 686,070 |
import copy
def add_include_date_flags_to_columns(covariate_definitions):
"""
Where one column is defined as being the date generated by another column
we need to tell that "source" column that it should calculate a date as
well, which we do by supplying a flag.
The sharp-eyed may notice that thi... | 6b40dfe0e6355bd744a7d8b82039d75117b80fec | 686,071 |
def typeDevice(data):
"""
Determina que tipo de Dispositivo GPS es dueña de la data.
Usage:
>>> import devices
>>>
>>> data='>REV041674684322+0481126-0757378200000012;ID=ANT001<'
>>> devices.typeDevice(data)
'ANT'
>>>
... | 6cafc1fe8e586ffa5c45912a27dd086b1e6bda58 | 686,072 |
import logging
def volume_available(all_volumes, mount_path):
""" Returns available storage of the volume mounted at mount_path in MB """
try:
return int(all_volumes[mount_path]['available']) / 1024
except KeyError:
#print "Volume '%s' not found" % mount_path
logger = logging.getLo... | 7546018dea87295731e96b281c78040097624d5d | 686,073 |
def get_affiliate_code_from_request(request):
"""
Helper method that gets the affiliate code from a request object if it exists
Args:
request (django.http.request.HttpRequest): A request
Returns:
Optional[str]: The affiliate code (or None)
"""
return getattr(request, "affiliate... | b0ccd20442ff23660a487451a9a379e44a359786 | 686,074 |
import os
def getScripts(basedir=''):
"""
Returns a list of scripts for Twisted.
"""
scriptdir = os.path.join(basedir, 'bin')
if not os.path.isdir(scriptdir):
# Probably a project-specific tarball, in which case only this
# project's bins are included in 'bin'
scriptdir = o... | 849307ea2c2b0ddaf75125c73c4b061b79e64a21 | 686,075 |
def nub(l, reverse=False):
"""
Removes duplicates from a list.
If reverse is true keeps the last duplicate item
as opposed to the first.
"""
if reverse:
seen = {}
result = []
for item in reversed(l):
if item in seen: continue
seen[item] = 1
result.append(item)
return revers... | 77591958634f0ef6ff2463616d7ab5507e32c272 | 686,076 |
def setPercentage(pt):
"""
@param pt: The new percentage threshold
@type pt: Float between 1 and 100
@return: 1 value is not correct
"""
if 1 <= pt <= 100:
global PERCENTAGE
PERCENTAGE = pt
else:
return 1 | 7d868b7b1fa725fca918e3ad57194c8310b860a8 | 686,077 |
def _validate_bool(value, default):
"""Validate a boolean value parsed from the config file.
@type value: any
@param value: Raw value read from config.
@type default: bool
@param default: Default value to use if the input value isn't valid.
@rtype: bool
@return: Value to use.
"""
... | d14e733086d9e7dc79504086bcbde098a44874ad | 686,078 |
def diff21(n):
"""
dado um inteiro n retorna a diferença absoluta entre n e 21
porém se o número for maior que 21 retorna o dobro da diferença absoluta
diff21(19) -> 2
diff21(25) -> 8
dica: abs(x) retorna o valor absoluto de x
"""
if n > 21:
return abs(n - 21) * 2
return abs(... | 73746d33afa22c3fc2ce324098a3ea60de7a88ea | 686,079 |
def write_score_summary(scores, analogy_types, filename):
"""
Write score summary to a string
:param scores: list of pairs
(number of correctly answered questions in category, number of questions in category)
:param analogy_types:
:param filename:
:return: score summary (strin... | 0c013095ef5b0082dcb54bdf8d2497b0dc282610 | 686,080 |
def permutations(l):
"""
Return all the permutations of the list l.
Obivously this should only be used for extremely small lists (like less
than 9 members).
Paramters:
l - list to find permutations of
Return value:
list of lists, each list a permutation of l.
"""
if len(l) ... | 4bb957a5837752f909257c13a63d0b0944116fbb | 686,081 |
def empty_statement(_evaluator, _ast, _state):
"""Evaluates empty statement."""
return None, False | 92748988c357a60a8886cb1e9d319f1c42ccf178 | 686,082 |
from pathlib import Path
def oss_artifact() -> Path:
"""
Return the path to a build artifact for DC/OS OSS master.
"""
return Path('/tmp/dcos_generate_config.sh') | 66b82ef40d8f7c98cd27d3805b206a6634e5486d | 686,083 |
def contains(value, substring):
"""
Because in Jinja templates you can't use the 'in' operator.
"""
return substring in value | f61e5049737f8223630836e5f940b779f49c1007 | 686,084 |
def get_roles_mapping(request, iface):
"""Gets the role mapping for the resource."""
# Unpack.
registry = request.registry
roles_mapping = registry.roles_mapping
return roles_mapping.get(iface, None) | c5129742b5508e377e1fb9042215720efa9fc23f | 686,085 |
def all_possible_rcts_prds(rxn):
"""
rxn: string with an unformatted reaction
returns rcts_all, prds_all: list of all possible reactants and products
-formatted-
ex. ['A+B','B+A'], ['A+A','2A']
"""
if ('<=>' in rxn):
rxn = rxn.replace('<=>', '=')
elif ('=>' in rxn):
rxn =... | 6a4f9a86ab3bd7fa0728e2d1274469313668cb0f | 686,086 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.