content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import random
def tr_get_asset_ip(params):
"""
return a random host IP, If params is defined as a network address returns an IP from that subnet
:param str params: Network address of the subnet from which to return a host IP
:return: Host IP
:rtype: str
"""
try:
if params ... | cba106ccf0fc4e174e8b92a035f90030a3dc1363 | 647,888 |
from datetime import datetime
def generateNameSuffix():
"""Create time stamp string."""
return datetime.now().strftime("%Y%m%d_%H%M%S") | afbbb8f865a3c0a82d17ce11592a9e58444d6905 | 647,889 |
import click
def validate(dic, option_list):
"""
linode create command validation
"""
for option in option_list:
if not dic[option]:
raise click.UsageError('required option %s is missing' %(option))
return True | aaf6ff91be49c43ec6d326c24cc4a92e0ef60e28 | 647,890 |
def clean_corpus(df):
"""
Clean corpus of text for all documents.
"""
df.Text = df.Text.replace('\s+', ' ', regex=True) # Remove duplicate spaces
df.Text = df.Text.str.encode('ascii', 'ignore').str.decode('utf-8') # Encode in ascii to remove weird characters such as \uf0a7
#df.Text = df.Text.... | 8eddc7ea5f88a5288320619b60351268964dd5db | 647,891 |
import os
def in_sub_dir():
"""Determine if we in the root or sub dir.
A hack for running scripts in the "nitfix" subdirectory vs running it from
the root directory.
"""
return os.getcwd().endswith('nitfix/nitfix') | 1ac05a4b96aa99734a19136022d008c9de47199e | 647,892 |
def transform_chi_eff_chi_a_s1zs2z(mass1, mass2, chi_eff, chi_a):
"""Returns spin1z.
"""
spin1z = (mass1 + mass2) / (2.0 * mass1) * (chi_eff - chi_a)
spin2z = (mass1 + mass2) / (2.0 * mass2) * (chi_eff + chi_a)
return spin1z,spin2z | b63dbfb3ec7c759d35721c5b747de0ec1dd32fc9 | 647,894 |
import argparse
def parse_args():
"""
Parse Arguments from component
"""
parser = argparse.ArgumentParser()
parser.add_argument("--input-model", help="Path of input model to create")
parser.add_argument("--temp-shared-path", help="Temporary shared path for model transfer")
options = parser... | f1fde7d5d3c575ff24685baffd36ef391aaa9b80 | 647,895 |
import torch
def texture_loss(img_pred, img_gt, mask_pred, mask_gt):
"""
Input:
img_pred, img_gt: B x 3 x H x W
mask_pred, mask_gt: B x H x W
"""
mask_pred = mask_pred.unsqueeze(1)
mask_gt = mask_gt.unsqueeze(1)
# masked_rend = (img_pred * mask)[0].data.cpu().numpy()
# masked_... | 97380719eed159173c8b51e2726cd4c46620ee69 | 647,896 |
def list_member(i_list1: list, i_list2: list):
"""
Compute the element common among i_list1 and i_list2;
not common among i_list1 and i_list2
:param i_list1: The source list
:param i_list2: The reference list
:return: (Common list, Not Common list)
"""
if len(i_list1) == 0:
... | 9e60d37aa8b5b0e5d0ce53cb35e84c8fa036ccaa | 647,897 |
def get_4x4_translation(x,y,z):
"""return a matrix 4x4 for translation"""
a= [1,0,0,0]
b= [0,1,0,0]
c= [0,0,1,0]
d= [x,y,z,1]
return [a,b,c,d] | 706d25094e18bf573a58c633723e495ee66b171e | 647,898 |
def decorate_token(t, z_):
"""Make selected text boldface in Markdown format"""
dec = "**" if z_ == 1 else ""
return dec + t + dec | 42769c22547de19771ebd9309fcd723c14ef5359 | 647,899 |
def search_alternate_links(feed):
"""Search for alternate links into a parsed feed."""
if not feed.get("entries", 1):
return [link.get("href") or ""
for link in feed["feed"].get("links") or []
if "rss" in link.get("type")]
return [] | 92b1b98134f8261ee12db112d29f8e6ac8e656fb | 647,900 |
def object_list_types(object_type):
"""return a dictionary of jamf API objects and their corresponding xml keys"""
# define the relationship between the object types and the xml key in a GET request
# of all objects we could make this shorter with some regex but I think this way is clearer
object_list_t... | 5d19b7ca1b6220951dd7937ec1c3aebd4597d441 | 647,901 |
import grp
import pwd
def _get_user_groups(user_name):
"""
Get a list of groups for the user ``user_name``.
"""
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups | b971dc2095f61c179d4cce98f2ccadbc1cbdc125 | 647,902 |
import os
def get_anno_path(voc_path, year, image_id):
"""Get path to image annotation for given year and image id."""
return os.path.join(voc_path, 'VOC{}/Annotations/{}.xml'.format(year,
image_id)) | ee4a8493c977b3108e74f0ebba406c9f725ce654 | 647,904 |
import re
def reg_date(data):
"""匹配日期"""
patt = re.compile(r"(\d{4}-\d{1,2}-\d{1,2})")
ret = patt.findall(data)
if not ret:
patt = re.compile(r"(\d{4}年\d{1,2}月\d{1,2}日)")
ret = patt.findall(data)
return ret[0] if ret else '' | 99f996d440adb06acf68c48e36eef7fe39cd1fa4 | 647,905 |
import os
def get_token(args):
"""
Parse command line arguments
Args:
args: object : Parsed arguments
Returns:
Tellus API token
"""
if args.token is not None:
return args.token
if "TELLUS_API_TOKEN" in os.environ:
return os.environ["TELLUS_API_TOKEN"]
... | b58a30da4124fbddf4e5c5f4fac1bb518c92f532 | 647,907 |
from typing import Dict
from typing import Any
def _inverse_dict_lookup(dict: Dict[str, Any], value: Any):
""" Finds the first key in a dictionary with the input value. """
for k, v in dict.items():
if v == value:
return k
return None | 1b78ba4d56f0c3ac011d07c671c2ce715ad6a06d | 647,908 |
import os
def extension_equals(path_or_view, extension):
"""Compares @path_or_view's extensions with @extension.
Returns `True` if they are the same, `False` otherwise.
Returns `False` if @path_or_view is a view and isn't saved on disk.
"""
try:
if path_or_view.file_name() is None:
... | fa4b6b258337ab74bb38d26aab33bed8ef298be4 | 647,909 |
import re
def get_words(text, dedupe=True):
"""Get the words from a piece of text.
Args:
text: The text from which words should be extracted.
dedupe: Flag indicating if only unique words should be returned. Defaults to true.
Returns:
Iterable over string words found from the input... | 78bb0ab727c825ce177093c1f04a80a4e881f190 | 647,910 |
import multiprocessing
def predict_edge_random_forest(rf, features, n_threads=None):
""" Predict edge probablities with random forest.
Arguments:
rf [RandomForestClassifier] - the random forest
features [np.ndarray] - edge features
n_threads [int] - number of threads (default: None)
... | d518d26afcea961a944ac460b1243caa272927f0 | 647,911 |
def make_off_by_one(matrices, vectors):
"""Arrange so that matrices.ndim = vectors.ndim + 1"""
off_by_one = matrices.ndim - vectors.ndim - 1
return (None,)*(-off_by_one), (None,)*off_by_one | ad43b61c0a1803dd91386e330250059a7d789db8 | 647,912 |
from typing import Optional
def create_year(datum: str) -> Optional[int]:
"""Parse a year from the datum field."""
if datum is None or len(datum) < 4 or not datum[:4].isdigit():
return None
jaar = int(datum[:4])
if 1000 < jaar < 2000:
return jaar
return None | fb6d20fc22fc61dfe0d04345cf8e6e3a0e58d3b2 | 647,913 |
import pickle
def load_pickle(filepath: str) -> object:
"""
Loads a pickle file to memory.
:param filepath: Path pointing to file
"""
with open(filepath, 'rb') as handle:
return pickle.load(handle) | 12e7cc7825814b4e9e1d2e15ac87e95e22315004 | 647,914 |
import zipfile
import os
import shutil
def parsefolder(folder):
"""Parse for all .py files in plugins folder or zip archive"""
filenms=[]
homedir = os.path.expanduser("~")
if os.path.isfile(folder):
#if in zip file, we need to handle that (installer distr)
zf = zipfile.ZipFile(folder,... | 6a72d01d9527abbd5a8ab99fd7250e0abe137b42 | 647,915 |
def netflow_encoding_str(flow, mappings):
"""
The netflow encoding described in Pellegrino, Gaetano, et al. "Learning Behavioral Fingerprints From Netflows Using
Timed Automata."
:param flow: the flow to be given a code
:param df: the dataframe with all flows
:param mappings: dictionary with the... | 4c62aa009a28b1637e7e3027a06071e21a619b12 | 647,916 |
def _TailSet(start_point, listing):
"""Returns set of object name tails.
Tails can be compared between source and dest, past the point at which rsync
was done. For example if test ran rsync gs://bucket1/dir gs://bucket2/dir2,
the tails for listings from bucket1 would start after "dir", while the tails
for l... | d683823020239318e26a5ec19b9b263757cab28f | 647,917 |
def get_colour_set(n_colours, rng):
"""
Generates a (unique) list of randomly generated RGB colours.
# Arguments:
n_colours: the number of colours to generate.
rng: an instance of numpy.random.Generator.
# Returns:
colours: a list of randomly generated colours.
"""
colo... | ff72461744996ced60cc677be56acfbf573f47e7 | 647,918 |
def linear_head_correction(r, V, cutoff):
"""Use a linear function to smoothly force V to a finite value at V(0). """
slope = ((V[cutoff+1] - V[cutoff+2]) / (r[cutoff+1] - r[cutoff+2]))
V[:cutoff + 1] = slope * (r[:cutoff + 1] - r[cutoff + 1]) + V[cutoff + 1]
return V | 97784047de6bd087e62fc44faef47ab8b594c6ce | 647,919 |
import warnings
def ignore_warnings(method):
"""Decorator for ignoring warnings"""
def _inner(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
result = method(*args, **kwargs)
return result
return _inner | b382775eb913b98245944ac0a2e96b8936944a37 | 647,920 |
import base64
def escape_project_name(name):
"""Escapes name for use as a valie pkg_resources project name."""
return str(base64.b16encode(name.encode("utf-8")).decode("utf-8")) | 9098b158a53ba2ebb80bd80fa4856e17451966aa | 647,921 |
import torch
def subsequent_mask(size, device):
"""Mask out subsequent positions (adapted from
http://nlp.seas.harvard.edu/2018/04/03/attention.html)"""
attn_shape = (1, size, size)
subsequent_mask = torch.triu(torch.ones(attn_shape, device=device), diagonal=1)
return subsequent_mask == 0 | d1a8a26476ef9d8f012c9f35947b6a0392f8a2a5 | 647,922 |
def factorial(n):
"""Returns the factorial of a number n > 0.
This is a recursive function.
"""
if n == 0:
return 1
else:
return n * factorial(n-1) | fa2ce021ab09a969522f981f74fb7b0893c58012 | 647,923 |
import string
def is_valid_file_name(str_input):
"""Returns if str is valid file name.
May only contain: ascii_lowercase, ascii_uppercase, digits, dot, dash, underscore
"""
allowed = set(string.ascii_lowercase + string.ascii_uppercase + string.digits + '.-_')
if str_input is not '':
return... | 1f0499245417b7b39283e1be11512c10ac1db367 | 647,925 |
def bt_analysis_tcm(bta, temp_min=300, temp_max=400, doping_min=1e19, doping_max=1e22):
"""
Performs analysis for transparent conductive materials
Focuses on T=300-400K and Doping=1E19-1E22
:param bta: Boltztrap analyzer object
:return: dict of conductivity and effective mass
"""
d = {}
... | a80262ddfd4be0aa99da250ca7b0bd9b2e085b6e | 647,926 |
def path_splitter(path_str, after=''):
""" split a path_str after a certain value and return a string of the
result.
"""
l = path_str.split('/')
idx = l.index(after)
before = '/'.join(l[:idx+ 1])
after = '/'.join(l[idx+1:])
return before, after | 77b8460914da97fd27eba9d238eb7b35d48f1808 | 647,927 |
import requests
def get_page(url):
"""
Get a single page of results.
"""
response = requests.get(url)
if not response.status_code == 200:
err_msg = 'API response status code {}'.format(response.status_code)
if 'detail' in response.json():
err_msg = err_msg + ": {}".form... | bf7834f46478d04a6692237719f6f0a5c596fd73 | 647,929 |
def iterative_topological_sort(graph, start=None):
"""
Get Depth-first topology.
:param graph: dependency dict (like a dask)
{'a':['b','c'],
'c':['b'],
'b':[]}
:param start: str
the node you want to search from.
This is equivalent to the node you want to compute.... | f5c51c9444af7895391744ba02c447707d305dc8 | 647,930 |
def calculate_bmi(weight,height):
"""Function to calculate BMI"""
bmi = weight/(height**2)
return round(bmi,2) | 12235da5e604f387d0a0a0d4b97c79622f0b060d | 647,931 |
import subprocess
def execute(args):
""" Execute in bash, return stdout and stderr in string
Arguments:
args: command and arguments to run, e.g. ['ls', '-l']
"""
process = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr ... | 2521199c539c17986af8b98e3de8bac08f680c0b | 647,932 |
def evaluate(tok_list):
"""
computes result of a parentheses-free expression
example input: ['1','+','3','*','4']
output: '16'
"""
num_or_op='num'
result = None
cur_op = None
i=0
while i < len(tok_list):
# toggle between expecting a num or an op
if num_or_op=='num... | 5d674b3a9a507145a57ddb909d1f19132dbcbba6 | 647,933 |
def jester_mag_v(g_sdss, r_sdss):
"""
Convert from SDSS g,r to Johnson V using the Table 1 of Jester
2005 [astro-ph/0506022] for stars with R-I < 1.15:
V = g_sdss - 0.59(g_sdss-r_sdss) - 0.01
Parameters:
-----------
g_sdss : SDSS g-band magnitude
r_sdss : SDSS r-band magnitude
p... | a034405c928065096e0c10d3486c258af196ce2d | 647,934 |
def is_even(a):
""" Checks if the input integer is even.
Based on the ideea that if the last bit is 0 then the number is even.
"""
return (a & 1) == 0 | e1dde7f4d9c4bbfbf1976a37a7a12d3891273513 | 647,935 |
def clipping_dist(delta):
"""
Returns the average distance between residues i and j, based on experimental data.
Parameters
----------
delta : int
The delta between residue indexes i and j.
Returns
-------
float
The average distance.
"""
if delta == 1:
r... | 395354855944724f20986be3800baa2fbd378fd2 | 647,936 |
def compute_baselines(class_counts, class_labels, N, balanced_purity, class_priors=None):
"""
Get random classifier baselines for completeness and purity
Completeness: 1/ number of classes
Purity: class count/ total count
Balanced Purity: 1/ number of classes
:param N: Number of classes
"""
... | 155b1beec5c48c9961344b187fae30489f63e596 | 647,937 |
def _linestring_to_segments(arr):
"""
Translates line strip to segments
:param arr: numpy.array
Array of line strip vertices
:return: numpy.array
Line segments
"""
return [arr[i / 2] for i in range(0, len(arr) * 2)][1:-1] | e0c642bd245a9f42cc55a8f5e53686a939ba6e3c | 647,939 |
import hashlib
def CalcMd5(data):
"""
calculate the md5 of data
Args:
data : the data to calculate
Returns:
return md5 of data, if fail to calculate return None
"""
try:
md5 = hashlib.md5()
md5.update(data)
return md5.hexdigest()
except BaseExcepti... | 7aaac197fcfac0bbfc1773eeb23096f657be7b90 | 647,940 |
def check_pes(epi_fmaps, pe_dir):
"""Check whether there are images with matched PE."""
opposed_pe = False
matched_pe = False
for _, fmap_pe in epi_fmaps:
if fmap_pe == pe_dir:
matched_pe = True
elif fmap_pe[0] == pe_dir[0]:
opposed_pe = True
if not opposed_... | 6fd666f583e7070d528334f08a484d7ef59eeeb5 | 647,941 |
import os
def CalculateFramesNumberFromYuv(yuv_width, yuv_height, file_name):
"""Calculates the number of frames of a YUV video.
Args:
yuv_width(int): Width of a frame of the yuv file.
yuv_height(int): Height of a frame of the YUV file.
file_name(string): The name of the YUV file.
Return:
(int)... | 2d794e726bae929173a288ccbede921f63b8a28a | 647,943 |
def apigw_event():
"""Generates S3 Event"""
return {
"Records": [
{
"s3": {
"s3SchemaVersion": "1.0",
"bucket": {"name": "vm-gtner-blog"},
"object": {"key": "output.manifest"},
}
}
... | 2e7d5ad3150dbe0d71d82033ac75e651040318d7 | 647,945 |
def hztous(hz):
"""
Convert frame rate in hz to microseconds between frames
"""
return (1/hz)*10**6 | b66f2e2fad781beda2a2ebdae4c1619862f3b621 | 647,946 |
import operator
def invertgroup(group):
"""Flip all the values in the specified group and return it"""
return map(operator.not_, group) | bfa520adfa6d10077ec8c120a17c7ddca59f3b68 | 647,948 |
from typing import Dict
def format_highlight_tags(
recipe_tags: Dict
) -> Dict:
"""
Transforms two separate highlight tag values into an array
returned via the highlightTags attribute
"""
highlight_tag_values = []
for key, value in recipe_tags.items():
if key in ('highlightOne', '... | 4bf2c9389e6404773a6a261c13b285f78ab83206 | 647,949 |
def tri_y2r_para():
"""example_meyers_demo.yaml from SEIRcity v2"""
return [3.0, 4.0, 5.0] | 7b3d78717bc4cca24e4054d780835d195ac1b182 | 647,950 |
def greedy(items, maxWeight, keyFunction):
"""Assumes Items a list, maxWeight >= 0,
keyFunction maps elements of Items to numbers"""
itemsCopy = sorted(items, key=keyFunction, reverse = True)
result = []
totalValue, totalWeight = 0.0, 0.0
for i in range(len(itemsCopy)):
if (totalWeigh... | 4daeb4432cc637ce488a98db4ca60bcbd6a93bc6 | 647,951 |
def get_segment_label(segment, segment_type, segment_text, ns, tokenized):
"""
generates an appropriate node label for a segment (useful for dot
visualization).
"""
segment_prefix = segment_type[0] if segment_type else '_'
if tokenized:
segment_label = u'[{0}]:{1}:segment:{2}'.format(
... | b65ebd811649d9c49622a28fe44993bd73aacb46 | 647,952 |
def format_color(r, g, b):
"""Format a color as a string.
r, g, b -- integers from 0 to 255
"""
return '#{0:02x}{1:02x}{2:02x}'.format(int(r * 255), int(g * 255), int(b * 255)) | c67c52671d661a930f761e106bb79a1c4066f998 | 647,953 |
import yaml
def read_cadence_file(filename):
"""
Parse a cadence file.
Args:
filename (str): Name of cadence file
Returns:
cadence_dict: dictionary containing cadence file contents
"""
with open(filename, 'r') as f:
cadence_dict = yaml.safe_load(f)
... | 38d09e4f7a9dd042b65ff5c46756c02d7b43aff5 | 647,954 |
def get_table_position(screen_layout):
""" return first position of table encountered within screen layout
"""
for _, data in screen_layout.items():
if data.get('table'):
return data['position']
return None | 0fe1f0ef0de3c17e7e0371c428a83a5c407de5a7 | 647,955 |
def same_fringe(tree1, tree2):
""" Detect is the given two trees have the same fringe. A fringe is a list
of leaves sorted from left to right.
"""
def is_leaf(node):
return len(node['children']) == 0
def in_order_traversal(node):
if node == None:
return []
if is... | 5b7f69cae14f7611e558ca7e88a90fa02cc3f893 | 647,958 |
def get_EVR(pkg):
"""
Return 3-tuple EVR (_epoch_, version, release) of the given RPM.
Epoch is always set as an empty string as in case of kernel epoch is not
expected to be set - ever.
The release includes an architecture as well.
"""
return ('', pkg.version, '{}.{}'.format(pkg.release, ... | 084d05ad9a4420ad8ebe888b1cae3033ff7c2a6e | 647,959 |
def get_hi_file_at_long(longitude, sgps_hi_file_list, edge_size=0.5):
"""
Identify the best SGPS file to retrieve data from at the supplied Galactic
longitude. Will try to find a file where the longitude is at least edge_size
away from the edge of the cube, but will fall back to any file with data
c... | 8579f4a5c650d1c73616ae3f2b77120f4fcf4e87 | 647,960 |
def _addCentroidInfo(centroidTree, subsetIdxes, clusterArray):
""" *INTERNAL FUNCTION*
Function to add centroid info to subset tree.
INPUT:
centroidTree - fiber tree containing subset fibers
subsetIdxes - indices corresponding to subset of fibers
clusterArray - array containing cent... | 9e9551bf188ccd205889b0d5eab4e4701f11669f | 647,961 |
def number_of_ad_performance_threads() -> str:
"""The number of threads used to download ad performance"""
return '10' | a00ea3b634dfe33d82566c62da9456c7ee9fd3e6 | 647,962 |
def _explicit_euler(ode_fun, jac_fun, y_olds, t_old, f_old,
dt, args, solver_parameters):
"""
Calculate solution at t_old+dt doing one step with explicit Euler.
Based on II.9.13a of Ref I.
"""
y_older, y_old = y_olds
if(f_old is None):
f_yj = ode_fun(*(y_old, t_old)+... | e0dd4d83206201001d01c253629de597b26b96ad | 647,964 |
import re
def find_num(num):
"""Função para encontrar algarismos de 0-9 dentro de iteráveis
Retornará apenas aa primeira sequência de números encontrados
Esta função não procura por '.'(pontos) podendo alterar os valores
de floats ou números maiores que 999 (1.000)
Esta função retornará float dos ... | 5d517f8521b0bd687a9ffd1cf5a33bdd8484c4db | 647,965 |
def validkey(key):
"""
Check if a tag or a key is valid.
In XML this basically means that the
key does not start with a number.
"""
assert isinstance(key, str), 'Key must be string'
if key[0].isdigit():
raise ValueError('Key cannot start with a number: {}'.format(key))
return ke... | 7954379afbd3c1ea30abb6698d7b3f64924f7a1a | 647,966 |
def formatOneTextRow(fields, values = None, fieldDLM="|@|"):
"""
Parameters in:
fields - a list of fields name
values - a dictionary of values with fields name, Default None
fieldDLM - delimeter of values, default "|@|"
Return:
if values is None, return fields with delimeters... | c4a87c87e83f0e8dcc2b88cff9007eed1586cebf | 647,967 |
def sub_domain_to_tld(domain):
"""
Turn the input domain to get Top Level Domain
Args:
domain: any domain value
Returns:
TLD of input domain
"""
domain_list = domain.split('.')[-2:]
return '.'.join(domain_list) | 676f5c91427e46e662cf94b1764911f7a22e396e | 647,968 |
def is_file_readable(file, strict=False):
"""Check if a file exists and is readable.
Parameters
----------
file : :class:`str`
The file to check.
strict : :class:`bool`, optional
Whether to raise the exception (if one occurs).
Returns
-------
:class:`bool`
Wheth... | cdb8b2c41cf7439dbd8a364cf883fe6d3e4cf845 | 647,969 |
def assert_quality_condition(options, sds_file):
"""Assert that the SDSFile quality is in a list given in the options.
Parameters
----------
options : `dict`
The rule's options.
- ``qualities``: List of qualities to accept (`list` of `str`)
sds_file : `SDSFile`
The file bein... | 3b9ba7653e338f27e509af01a36022aa2369e3a4 | 647,970 |
def sqrt(num):
"""
Calculates the Square root of num
:param num: Number
:return: Square root of num
"""
# Checks if num is equal to zero
if num == 0:
return 0
elif num < 0:
num = num * -1
is_negative = True
else:
is_negative = False
# Newton/baby... | ea5b8f8092f3eba98329aebaff47bc4fbcb7b17d | 647,971 |
def edd_x_spt_pre_sequencing(dataset, w_edd=0.5, w_spt=0.5, *args, **kwargs):
"""
Generates an initial job sequence based on a weighted combination of
the earliest-due-date and the shortest-processing-time
dispatching strategy. The job sequence will be feed to the model.
"""
sequence = [job fo... | 61a3ca65752773cc9778e534e5550fd79c980f47 | 647,972 |
import six
def pretty_unicode(string):
"""
Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed.
"""
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return string.decod... | 3857d63817bd99acc2cf5d0e4106055152d66bc1 | 647,974 |
import pkg_resources
def get_required(dist):
"""Return a set with all distributions that are required of dist
This also includes subdependencies and the given distribution.
:param dist: the distribution to query. Can also be the name of the distribution
:type dist: :class:`pkg_resources.Distribution... | aeb18cb99af0bfc498d87b63dbdc131dad5bcafc | 647,975 |
def cons_merge(car_part, cdr_part):
"""Merge a generic car and cdr.
This is the base/`nil` case with `cdr` `None`; it produces a standard list.
"""
return [car_part] | fcd5aea4b39a1423711f9a83211faf6f191482c9 | 647,977 |
def read_POPI_points(file_name):
"""
Read the Point-validated Pixel-based Breathing Thorax Model (POPI) landmark points file.
The file is an ASCII file with X Y Z coordinates in each line and the first line is a header.
Args:
file_name: full path to the file.
Returns:
(list(tuple)): L... | bcf5f0b447ab0fe5ab0ca7aa93cc129927425730 | 647,978 |
def update_from_dict(obj, update_dict):
"""
A function to update an object instance with values stored in a dictionary.
In some cases preferred over calling filter(pk=pk).update(**dict) because update does not send signals.
:param obj: The object instance to be updated
:param update_dict: A dictiona... | 1f8e96b7de2435edd597409247c69c693420fde0 | 647,979 |
import importlib
def execute(test, args, results):
"""
Executes the test under parallel in module named 'Parallel run' parallely.
It involves the following steps
- Importing of test module based on test
- Running the test module
Args:
test: The test module which needs to be ... | f09368ea63d5d60834a86d4dad9e4ea1f6f78105 | 647,980 |
import math
def haversine_bearing(lat1, lon1, lat2, lon2):
"""
Calculate the bearing from 1 point to 1 other
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
dlon = lon2 - lon1
... | bf9c4064ab47454e243e773f0b5e0959da7c1628 | 647,981 |
import collections
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
d={}
for i,num in enumerate(nums):
if num not in d:
d[num]=[i]
else:
d[num].append(i)
element=float('inf')
max_length=max(collections.Counter(nums).values())
#for i in d:
#max_length = len(d[i... | d3d6738aff2bb6ac74878e13bc40c0eeab7644b1 | 647,982 |
def get_style(line):
""" get plot styles from Line2D object
mostly copied from "Line2D.update_from"
Args:
line (Line2D): source of style
Return:
dict: line styles readily usable for another plot
"""
styles = {
'linestyle': line.get_linestyle(),
'linewidth': line.get_linewidth(),
'color... | 49a239a9934101754b2ef65354e7740369cb7672 | 647,984 |
from typing import Dict
from typing import Any
from typing import Optional
def _process_api_resource(permission_resource: Dict[str, Any], api_operation: str) -> Optional[bool]:
"""Helper method to check if the api action permission is in this API resource
Args:
permission_resource: The dictionary for ... | 43b3cdf7ddb398594651b3b7dce662f851fd5f58 | 647,985 |
def fermeture_groupe():
"""
génère la balise fermante pour un groupe d’éléments
"""
return "</g>" | 4f9558aeebb85a1e4e50b3795b338ec4b616e531 | 647,986 |
def max_(a, b, operator):
""":yaql:max
Returns max from a and b.
:signature: max(a, b)
:arg a: input value
:argType a: number
:arg b: input value
:argType b: number
:returnType: number
.. code::
yaql> max(8, 2)
8
"""
if operator(b, a):
return b
... | f43298bbf7e19e9cafa270164ad0c3b5ec31070c | 647,987 |
def windows_translator(value):
"""Translates a "windows" target to windows selections."""
return {
"@com_github_renatoutsch_rules_system//system:windows_x64": value,
"@com_github_renatoutsch_rules_system//system:windows_x64_msvc": value,
"@com_github_renatoutsch_rules_system//system:wind... | 65d41739f2829249d3012e9da68eb01c1de5741e | 647,988 |
def reshape_to_tf(tensor, dim=3):
"""Reshape the tensor to Tensorflow ordering.
This function assumes that your patch have
the same width for each dimension.
The types of tensors are supported
- Simple 2D patch sample
shape = (n_channels, patch_size, patch_size)
- 2D patch samples corp... | 4ac754cf07e6bdb8cfa38d8f93c93341bbd2c182 | 647,990 |
def numlookup(x, y):
"""
Try to resolve y as a numberic, then try to
look it up a key in dictionary x.
"""
try:
return int(y)
except ValueError:
return x[y] | 98ba8ca401ba4adddde5e01f94e787b2af30d77b | 647,991 |
def depletion_calc(inidep, swhc, df):
"""Does a Wang-Erlandsson deplietion but takes into account the SWHC and the initial depletion condition."""
# dates = df.index.to_list()
# deficit = df['deficit'].to_list()
et = df['eta']
precip = df['precip']
depletion = []
# recharge/runoff i.e. dep... | ca15cf7c346b65397dd1c7fa2a83955a7da99b46 | 647,992 |
from typing import Any
import io
def is_file_like(value: Any) -> bool:
"""Check if a value represents a file like object"""
return isinstance(value, io.IOBase) | 291d72b0ef930951872928a769b7126e35576cdd | 647,994 |
import struct
import socket
def address_in_network(ip, net):
"""
Is an address in a network
ip: 192.168.2.2
net:("192.168.2.0/24",)
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
for cur_net in net:
netaddr, bits = cur_net.split('/')
netmask = struct.unpack('=L',... | b70e5d2a6b5a243d91e7ca7d577d5d63d4aab71f | 647,995 |
from typing import List
def img_tag(movie_id: int, frame: int, box: List[int]):
"""Get a 'standard' image tag as used by the face recognition stack.
"""
# Real example of full file name: 121614:3616:235_183_293_262.jpeg
# Face file names are <tag>.jpeg
return f"{movie_id}:{frame}" + ":{}_{}_{}_{}"... | 54bcc399f73559007e0c8f2470bf03466877cd22 | 647,996 |
def cmp(v1, v2):
"""
A helper function to compare the two values
Parameters:\n
v1: first value
v2: second value
"""
if v1 < v2:
return -1
elif v1 == v2:
return 0
else:
return 1 | d7831c47e5796441b88411608e1d09c6e021a978 | 647,997 |
def self_embeds(url):
"""Does this url generate a usable embed on it's own when sent on discord?"""
return (
url.startswith("https://www.youtube.com")
or url.startswith("https://youtu.be")
or url.startswith("https://imgur.com")
or url.startswith("https://www.imgur.com")
o... | 02516b8661c9f4bdcc6c86c7477b1b9c97e9feeb | 647,998 |
import os
def _AreLayoutNGDirectoriesModified(change): # pylint: disable=C0103
"""Checks whether CL has changes to a layout ng directory."""
layout_ng_paths = [
os.path.join('third_party', 'blink', 'renderer', 'core', 'layout',
'ng'),
os.path.join('third_party', 'blink', ... | ef15faef02dcc5ab932d71e9ad67d6822ca18015 | 647,999 |
def get_object_size_on_humans_retina(distance_to_object, object_height, focus_distance):
"""
Calculates an object size on human's retina
based on the object remoteness and its height
============================================================
The original formula is:
object_height / distanc... | e5432049e8dafba44b84163a50739fe3b9f4a413 | 648,000 |
def w_s_update(u, S):
"""Computes the updates for the proxy of the derivative of u for smoothing
Parameters
----------
u : np.array of shape (None,)
Beamlet radiation distribution u
S : np.array of shape (None, None)
Returns
-------
w_next : list of np.array of shape (None,)
... | e844416fbb1cf5f53cc7cdc3183fd49538d60c71 | 648,001 |
def format_pdf_search_term(search_term, encoding='utf-8'):
"""Converts a unicode string into the way it might actually
exist in the bytes of a pdf document. so we can check if the text
made its way into the final pdf.
An example:
the text
'So\nmany\nlines'
becomes the bytes
... | a72097a03eca825b9dbf61a8aeb3721ea5047ae6 | 648,002 |
import string
def frequency_long(string_code):
""" Performs a frequency analysis """
analyse_list = []
frequency_list = []
counter = 0
for runner_first in string.ascii_letters:
for runner_second in string_code:
if runner_second == runner_first:
counter = counter... | 9d51eb24eaadcd6d0923f5cbf191a9b91ff29825 | 648,003 |
import re
def split_mutation_string(instring):
"""Split a string with letters and numbers in it -- the number still stays a string though
Examples:
>>> split_mutation_string('A123F')
['A', '123', 'F']
"""
return re.split('(\d+)', instring) | a0916b137cc3e36d81d1346519a025be90618e89 | 648,004 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.