content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def is_dir_inside(dir, check_dirs):
"""
Check to see if dir is a subdirectory of (or matches) check_dir
directories. Return True if the dir is a subdirectory of or matches any of
the check directories.
:param dir: String path of directory that may or may not be a
subdirectory of... | ceb48c09d444ec9c0d8aa5180a1beea67a48c6f6 | 634,245 |
import math
def euclidian_distance(x, y):
"""Get euclidian distance between two segments.
Parameters
----------
x : float
length of the first edge
y : float
length of the second edge
Return: float
euclidian distance between the two edges
"""
return math.sqrt(x... | 10256318199800de45077d5ad081bd0bd4868deb | 634,246 |
import getopt
import sys
import os
def parse_cmd(argv):
""" Parse the command line arguments """
file_name = ''
verbose = False
force_extension_pic = False
try:
opts, args = getopt.getopt(argv,"hvi:e",["file=","EDPIC"])
except getopt.GetoptError:
print('checkOpenPMD_h5.py -i <f... | 534bda8c6a41626d9b25f4d5d0d89fabd34a239e | 634,247 |
def get_overlaps(inds_1, inds_2): #verified.
"""
Calculate the overlaps between two reads and the distance spanned by them.
The reads are each assumed to comprise two arms, a left and a right arm.
inds_1 and inds_2: [left start, left stop, right start, right stop]
Returns overlap_l, overlap_r, span_... | ff969b0d4d364d85b7af525c4f21e782c7516ed4 | 634,248 |
import random
def get_random_cluster_service_component(client, cluster, service) -> dict:
"""
Get random cluster service component
Args:
client: ADCM client API objects
cluster: some cluster object
service: some service object in cluster
Raises:
:py:class:`ValueError`... | 93ccbc71b7ff4ad88a0de0d08f222ea8d90b88fe | 634,249 |
def no_mask_cols(ts_info, seq):
"""do not apply temporal masks"""
neg_mask_cols = [i for i, e in enumerate(ts_info['columns']) if 'mask' not in e]
return seq[:, :, neg_mask_cols] | aac5a5a9fbcfab2213fb17d9cb627ab2ecc52508 | 634,250 |
import torch
def full_cosine_similarity(matrix1, matrix2):
"""
Expect 2 matrices P and Q of dimension (d, n1) and (d, n2) respectively.
Return a matrix A of dimension (n1, n2) with the result of comparing each
vector to one another. A[i, j] represents the cosine similarity between
vectors P[:, i] ... | 75f3c52d55761782606896eeb2a3bf3fb27c2cee | 634,251 |
def abstract_elements_by_type(ifc_values):
"""Converts ifcOpenShell's returned objects into separated tuples containing the lines for each element
Args:
ifc_values (dict): Dictionary with points, edges and tags for each element.
Returns:
lines_for_type (dict): Dictionary with lines for eac... | d05ac432a00c649954e892727269dcf1798f40c6 | 634,252 |
import sys
def to_shared_lib(name):
"""Return library name depending on platform.
Parameters
----------
name : str
Name of library.
Returns
-------
str
Name of library with extension.
"""
if sys.platform.startswith('linux'):
return name + '.so'
elif s... | e3d141e3e576d1156f942aa149da30722bc51839 | 634,254 |
def base_repr(number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system... | 1ff4609f475c248bf840c5ac1b82ad42d3c575b3 | 634,255 |
def stringify(obj):
"""Converts all objects in a dict to str, recursively."""
if isinstance(obj, dict):
return {str(key): stringify(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [stringify(value) for value in obj]
else:
return str(obj) | f150c6593065675ae220deac7bff5524cee0a4c0 | 634,256 |
def make_c_string(string):
"""Render a Python string into C string literal format."""
if string == None:
return "\"\""
string = string.replace("\n", "\\n")
string = string.replace("\t", "\\t")
string = string.replace('"', '\\"')
#string = string.replace("'", "\\'")
string = '"' + str... | 7744ff18ddbff9839dcb03d1ddd24558b1300f16 | 634,257 |
def get_fromtos_line(linestring_coords):
"""
Converts a list of linestring coordinates to a list of 'from-to'
dictionaries.
"""
line_coordinates_list_froms = linestring_coords[:-1]
line_coordinates_list_tos = linestring_coords[1:]
i = 0
fromtos = []
for i, val in enumerate(line_coo... | 2a05362815a71a718c300b4c05e2a3d4ef8796d0 | 634,258 |
def get_bucket_names(s3):
"""
Purpose:
Return an Bucket Names in S3
Args:
s3 (S3 Resource Object): S3 Object owning the Bucket
Return:
bucket_names (List of Strings): Name of buckets in S3
"""
return [bucket.name for bucket in s3.buckets.all()] | 4341d3d4c06d0ca54848d2af9395ed90610233aa | 634,259 |
import torch
def generate_coordinates(w, h):
"""
Arguments:
w, h: integers.
Returns:
a float tensor with shape [1, 2, h, w].
"""
y, x = torch.meshgrid(
torch.arange(0, h, dtype=torch.float32),
torch.arange(0, w, dtype=torch.float32)
)
c = torch.stack([y, x]... | 6fbfa0d8621e196b486647cfb96e5799116c9096 | 634,260 |
def to_camel(string: str):
"""Schema helper function to export models with camelCase properties."""
pascal_cased = ''.join(word.capitalize() for word in string.split('_'))
return f'{pascal_cased[0].lower()}{pascal_cased[1:]}' | cd8ec8425712076b509907373b685d862d20d430 | 634,262 |
def get_element_tag(element):
"""Returns the tag name string without namespace of the passed element."""
return element.tag.rsplit('}')[1] | 6b5ace48209a711db1c1d33e5acc28f7e245ea3e | 634,263 |
def is_wave_raise_up_normal(prices):
"""
主升浪模式
:param prices: 按时间降序
:return:
"""
if len(prices) < 2:
return False
elif len(prices) == 2:
if prices[0] > prices[1]:
return True
else:
return False
elif len(prices) == 3:
if prices[0] < ... | c820b2ef53bcb98dabf9de500e1ccfb7e254b5fd | 634,264 |
def linestrings_intersect(line1, line2):
"""
To valid whether linestrings from geojson are intersected with each other.
reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js
Keyword arguments:
line1 -- first line geojson object
line2 -- second line geojson object
if(lin... | 8dd2e1b2adc520ef0197f840ad1e58ccf6612e69 | 634,265 |
def set_axis_index(axis):
"""Set index of axis in the XYZ basis
Args:
axis (str): chose axis, among X, Y and Z
Returns:
int: index of the chosen axis in the XYZ basis
"""
if axis.upper() == "X":
return 0
elif axis.upper() == "Y":
return 1
elif axis.upper() =... | 1e00d1e31387058e829501becdc472a6f651f7f7 | 634,266 |
import re
def clean_len(s):
"""
Calculate the length of a string without it's color codes
"""
s = re.sub(r'\x1b\[[0-9;]*m', '', s)
return len(s) | 5148d6fe580e45e5e3ce11b6bbcda602d3886305 | 634,268 |
import math
def toPolar(p):
""" convert 2-d cartesian coordinates to polar coordinates """
x, y = p
return math.sqrt(x**2+y**2), math.atan2(y, x) | 2b6c2f571cd268d4729d76b171f45776ecf77455 | 634,269 |
def get_models(model_key: str, model_type, json_dict: dict) -> list:
"""This converts json lists into a list of the specified SUSHI model type
:param model_key: The target key to get the list of JSONObjects
:param model_type: The target model type, e.g PerformanceModel
:param json_dict: The JSON dict t... | f84e9622823024fc0c94bd2dadb7fde6d14e05e8 | 634,271 |
import os
def fishgrid_files(filepathes, channel, grid_sizes):
"""
Expand file pathes for fishgrid data to appropriate traces-*.raw file names.
Parameters
----------
filepathes: string or list of strings
path to a fishgrid data directory, a file in a fishgrid data directory,
or fi... | 285358acb88eec542718f0a54516740c08080fff | 634,272 |
def remove_dash(item):
"""
Remove the first character in a string.
:param item: String
:return: input string, with first character removed
"""
return item[1:] | 2fbabb1b2359f6e89b69fd1d65a411e4b1012e6d | 634,273 |
def func_calc_density(M,T,Tc,Pc,Vc,Tb):
"""
Function to calculate density
Parameters:
Tc : Critical temperature (K)
Pc : Critical pressure (bar)
Vc : Critical molar volume (cm^3/mol)
Tb : Normal boiling temperature (K)
M : Molecular weight (g/mol)
... | e94ab19fd9ec1cf00752d5c642fb4d80b3a559ba | 634,274 |
import subprocess
def _nproc_method1():
"""
Used subprocess to determine the number of processeors available
:rtype: int
:return: number of processors
"""
# Check if the command `nproc` works
if not subprocess.getstatusoutput('nproc')[0] == 0:
raise EnvironmentError
num_proc ... | 3f85a3c9f88da6f384d1ca6ad214f9b6311ead6b | 634,276 |
def replace_in_result(phrase, replace_with, key=None):
"""Replaces string values in list with given string."""
def the_decorator(fn_decorated):
def proxy(*args, **kwargs):
res = fn_decorated(*args, **kwargs)
if res:
if not key:
return [
... | 9593a412066cddb035e44fd3db36f31947bf1d5b | 634,277 |
import torch
def collate_fn(batch):
"""Collate function used for Dataloader.
:param batch: Dataloader sends a batch of items
:return: modified batch
"""
sentence1 = [item[0] for item in batch]
sentence2 = [item[1] for item in batch]
label = [item[2] for item in batch]
label = torch.te... | f5901ff0465d2e7e32c8e72eafa8dbe1619c7d32 | 634,278 |
def create_auto_profile(role_session, user_session, session_name, source_profile_name, role_arn):
"""Create the profile that'll be stored in the credentials file for autoawsume.
Parameters
----------
- role_session - the session credentials from the assume-role api call
- user_session - the session... | a80e7058c0902ebfb7b5ce1ea556319dfb96851c | 634,279 |
def monthly_savings(future_savings, years_to_retirement, interest_rate, compounds_per_year=2, startwith=0):
"""
Calculates how much you need to save per month to retire given the parameters
"""
r, m, n = interest_rate, compounds_per_year, years_to_retirement * 12
efr = (1 + r/m) ** (m / 12) - 1
... | 9cc8c08f5c5371c985cb39f2c2831ad2f22d25fe | 634,281 |
def subject_module_id() -> str:
"""Return the Protocol Engine module ID of the subject."""
return "subject-module-id" | d7b184ac7432924a3496eec71a42c25d16daa62c | 634,282 |
from typing import List
from typing import Dict
def sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]:
"""Sorts a list of dictionaries by their first key."""
return sorted(dicts, key=lambda d: list(d.keys())[0]) | 623e16f0fbffeb47aecd2153143de2d258ebf4b7 | 634,283 |
import logging
def GFFAddIDAttributes(gff_data):
"""
Construct & insert a ID attribute for all features without one
For each feature in the input GFF data that doesn't
already have an an ID attribute, insert one of the form:
ID=<feature>:<Parent>:<n>
where <feature> is the feature type (e.g... | a172c66772f3106e20cfc6dafd9d7d1c834feb91 | 634,284 |
import functools
def simple(func):
"""
Simple Decorator
This is a simple decorator function. It takes the function
being decorating as input and returns a wrapped version of that
function as output. This makes it possible to inject custom
logic berore and after the function execution.
"""... | ae1fa12a64d91cfc41f765382475d266c8f36221 | 634,285 |
from datetime import datetime
def convert_time(y):
"""Convert time string and reformat
:param str y: Time string to convert
:return: Time string
:rtype: datetime
"""
time = datetime.strptime(y, '%H:%M:%S').time()
return time | 241ec82cae2ca48c7b1174b2241d324fcf4c3072 | 634,286 |
from typing import List
import glob
import os
def listdir(directory, fullpath=True) -> List[str]:
"""List directory content. Not recursive. No hidden files. Lexicographically
sorted.
Args:
directory: Directory to traverse.
"""
filepaths = sorted(glob.iglob(os.path.join(directory, '*')))
... | c705a7e147c15f1002ada426a158f50062d4a28c | 634,287 |
def detokenize(sent):
""" Roughly detokenizes (mainly undoes wordpiece) """
new_sent = []
for i, tok in enumerate(sent):
if tok.startswith("##"):
new_sent[len(new_sent) - 1] = new_sent[len(new_sent) - 1] + tok[2:]
else:
new_sent.append(tok)... | f90bc9dd20428a47c08ac26bc970bcac5323e550 | 634,288 |
def in_side_select_layer(fsti, layer):
"""
fst = "FullSingleTokenInfo[]"
"""
new_side = []
for f in fsti:
new_side_obj = {}
for k, v in f.items():
if k == 'embeddings' or k == 'contexts':
v = f[k][layer]
new_side_obj[k] = v
new_side.... | f51b98f0d0c7e2ffdfd7fe1c3d1d116fc8505204 | 634,289 |
def gformat(value):
"""
Format value for directory name.
:param value: value
:type value: float
:return: str
:rtype: str
"""
return ('%.7f' % float(value)).rstrip('0').replace('.', '') | 37d71117f9739b9afa4cc8431bfb939dc395bd56 | 634,290 |
def sanitize_str(value, subs=('slice', '=', '(', ')', ' ')):
"""Sanitize characters from string."""
for s in subs:
value = value.replace(s, '')
return value | b2d0107e96baf801e244501bbe947f1735f7df64 | 634,293 |
def get_timeout(run_type):
"""Get timeout for a each run type - daily, hourly etc
:param run_type: Run type
:type run_type: str
:return: Number of seconds the tool allowed to wait until other instances
finish
:rtype: int
"""
timeouts = {
'hourly': 3600 / 2,
'daily': 24... | 40c07cb61bb3fa4c43538c0bf265990fe763a929 | 634,294 |
def _get_var_names(posterior):
"""Extract latent and observed variable names from pyro.MCMC.
Parameters
----------
posterior : pyro.MCMC
Fitted MCMC object from Pyro
Returns
-------
list[str], list[str]
observed and latent variable names from the MCMC trace.
"""
sample_... | 63d263b1a6d8836c3f3c36e9181e79edddcf5bab | 634,295 |
import csv
def transform_csv(input_file, output_file, header_fx=None, row_fx=None):
"""
Transforms a csv using streaming technique. Calls a header function that
allows the caller to modify the header; also calls a row function that
allows the caller to modify each row in csv.
Allows the caller to pass arbitrar... | 9a722ddd5616a25aff23e7e2480202036b6bd5ab | 634,297 |
def pronoun_formsets_are_valid(formsets):
"""Tests if all formsets are valid"""
for pronoun, formset in formsets:
if not formset.is_valid():
return False
return True | af80a79adfeeb8c10fedb283842654d4fdeef308 | 634,299 |
import os
def is_aws_environment():
"""
:return: heuristically determine rather we're running on an aws environment.
"""
return bool(os.environ.get("AWS_LAMBDA_FUNCTION_VERSION")) | bae94d0e4adf5a340aa2a4cb1eb7304157079fcb | 634,301 |
import inspect
import sys
def _describe(obj) -> str:
"""Produce a short description of the given object.
Inspired by pydoc.describe.
"""
if inspect.ismodule(obj):
if obj.__name__ in sys.builtin_module_names:
return "built-in module"
if hasattr(obj, "__path__"):
... | 7ad664a3ffa23e16f764fe65efcc2983a6e608b3 | 634,302 |
def preconvert_discriminator(discriminator):
"""
Converts the given `discriminator` to an acceptable value by the wrapper.
Parameters
----------
discriminator : `str` or `int`
The discriminator of an user to convert.
Returns
-------
discriminator : `int`
Raises... | ed13f11db04a05fac7eb4810a0c95bd5d8452bb8 | 634,303 |
def unpop(state):
"""Given the before, stack, and after tuples, returns the (one-step) preimage.
"""
after,stack,before = state
if after and after[-1] and (not stack or after[-1] < stack[-1]):
return (after[:-1], stack+(after[-1],), before)
else:
return | 72ea02a260821a19b63fe55133da0d562798aaab | 634,304 |
import os
def check_for_json_folder(check_path):
"""Check folder hierarchy for a JSON or _JSON folder. Output to same folder structure outwith JSON
folder if it exists,
e.g. /path/to/JSON/folder/subfolder/my.plist.json ==> /path/to/folder/subfolder/my.plist
Note there is no reverse option at this time... | 04fe4cd84e0028b5cf86554e3590709a16546263 | 634,305 |
def compare_overlaps_greedy(context, synsets_signatures):
"""
Calculate overlaps between the context sentence and the synset_signatures
and returns the synset with the highest overlap.
Note: Greedy algorithm only keeps the best sense,
see https://en.wikipedia.org/wiki/Greedy_algorithm
Only use... | b16aebaf027b48576f93fa36ae231fd8237c270a | 634,306 |
def xact_name(xact):
"""Returns the payee of a transaction"""
return xact["name"] | beb6652a25ce51789c0d70fbf08927e0f9e45699 | 634,307 |
def c2o_preprocess(text: str) -> str:
"""Preprocess text."""
# preprocessing...
for _ in (
# special xml characters
("&", "&"),
("<", "<"),
(">", ">"),
# special spacing characters
("~", "\u00a0"),
(r"//", '<lb type="x-optional" />'),
... | 6537aa916d18adb1abe8c644be84e75af50ac6f8 | 634,308 |
def removeall(item, seq):
"""
Returns a generator of the elements of `seq` that are not `==` to `item`.
I was being 'clever' trying to use `type(seq)(x for x ...)` to ensure that
the result was of the same type as `seq`, but it turns out that that's
not the smartest idea. (Hint: try it with `rang... | 5864a502a4dc0871f37e96743caea06f28b89bbf | 634,309 |
def find_total_mass_gain(battery):
"""finds the total mass of air that the battery
accumulates when discharged fully
Assumptions:
Earth Atmospheric composition
Inputs:
battery.max_energy [J]
battery.
mass_gain_factor [kg/W]
Outputs:
mdot [kg]
... | 5ebfa84a079e2e37e2231a1e0bfbbaa86a587e39 | 634,310 |
import torch
import math
def idft(F, top=None):
"""
Args:
F [List]: Fourier transform of some signal
top [Optional[int]]: If given only top components will be used for reconstruction
Returns:
Reconstructed signal: f[n] = Sum(F(k).e(j.2pi.nk/N))
"""
N = F.shape[0]
if top... | a1d902a48844de68ed459e3d109925470ee7a3a5 | 634,312 |
import pickle
def cargar_objeto(nombre_archivo):
"""
Carga un objeto en Python, desde un archivo Pickle cuya ubicación es determinada por el usuario.
:param nombre_archivo: (str). Ubicación del archivo que contiene el objeto que se desea cargar.
:return: (objeto Python). Objeto en Python contenido e... | ac44003d1396d6c389260f683e282fb0eecab356 | 634,313 |
def leftlimit(minpoint, ds, tau):
"""
Find left limit.
Args:
minpoint (int): x coordinate of the local minimum
ds (list): list of numbers representing derivative of the time-series signal s
tau (int): threshold to determine a slope 'too sharp'
Returns:
minpoint (int): x coord... | 6d42f1a796a7715926194023a8019e0a620c470f | 634,314 |
def rectangular_fit(geom):
"""This functions computes the rectangular_fit of a geometry. \
Rectangular fit is defined as:
.. math:: RectFit = (AR - AD) / AO
where AO is the area of the original object, AR is the area of the \
equal rectangle (AO = AR) and AD is the overlaid difference between \
... | a20f708b2b7222bad891189b016ca7500d5d18ee | 634,315 |
import operator
def sorted_dict_items(d, reverse=False):
"""Sorted (key, value) pairs by value.
"""
result = sorted(d.items(), key=operator.itemgetter(1))
if reverse:
return result[::-1]
else:
return result | f1f0a19e8ee94ff38005de7b72e899d7badbabd7 | 634,316 |
def identify_climate_scenario_run(scen_info, target_scen):
"""Identify the first matching run for a given climate scenario.
Returns
----------
* str or None, run id
"""
for scen in scen_info:
if target_scen in scen_info[scen]['climate_scenario']:
return scen
# End for
... | 71c68e8e5ff8023c7edd65598b9861be2d0b5c85 | 634,317 |
import torch
def create_coref_tensors(pos_coref_mention_pairs, pos_eds,
neg_coref_mention_pairs=None, neg_eds=None):
""" Combines positive and negative corefeference samples into tensors """
neg_coref_mention_pairs = neg_coref_mention_pairs if neg_coref_mention_pairs else []
neg_e... | 272615e8c0416714772317ed95723e55624f7699 | 634,318 |
def merge(*objs):
"""Recursively merges objects together."""
def _merge(a, b):
if a is None:
a = {}
elif not isinstance(a, dict):
return a
else:
a = dict(a)
for key, value in b.items():
if isinstance(value, dict):
va... | bd59c930a15e92c99d870e09e476da5690c0d427 | 634,319 |
import re
def to_kebabcase(string):
"""
Converts the given string to kebab-case.
>>> to_kebabcase('HelloWorld')
'hello-world'
>>> to_kebabcase('__Init__File__')
'init-file'
>>> to_kebabcase('')
''
>>> to_kebabcase('already-kebab-case')
'already-kebab-case'
>>> to_kebabcase... | e964981195dc9679f7beb4c21d1cee234ae67599 | 634,321 |
def read_fasta(in_f):
"""Read fasta file.
Not polished version, just for test."""
f = open(in_f, "r")
content = f.read().split(">")
f.close()
del content[0]
name_to_seq = {}
for elem in content:
lines = elem.split("\n")
header = lines[0]
seq = "".join(lines[1:])
... | cbcfd39091fb86c8d604b0f8bab7059401e17312 | 634,322 |
import torch
def batch_mse_torch(estimation, origin):
"""
batch-wise mse caculation for multiple audio files.
estimation: (batch, nsource, frames, freq_bins)
origin: (batch, nsource, frames, freq_bins)
nsource = 2
"""
mse1 = torch.sqrt(torch.pow(estimation - origin, 2).mean([3])).mean([1,2... | daa0ee46dfe3b55d535e8fc625e36e358af2d461 | 634,324 |
import re
def split_msg(msg):
"""
splits msg
example: this: is, some msg -> [this, is, some, msg]
"""
return re.findall(r"[^\s]+", msg) | 5b892b67b3e4e6aff4cd8949032d03948eccab55 | 634,326 |
def direction_color_red_green(val: str) -> str:
"""Adds color tags to the Direction information: Buy -> Green, Sell -> Red
Parameters
----------
val : str
Direction string - either Buy or Sell
Returns
-------
str
Direction string with color tags added
"""
color = "g... | 6fdefe9e5d3b37facb2789747a87932f7961f91b | 634,327 |
import os
def render_path(p, pkg_vars):
"""Renders ${...} substitutions in paths, converts them to native slash."""
for k, v in pkg_vars.iteritems():
assert '${' not in v # just in case, to avoid recursive expansion
p = p.replace('${%s}' % k, v)
return p.replace('/', os.sep) | 670d58b825fb9ccceaca72841040497b8e037ef1 | 634,328 |
def wait_while_ready(*, module, **kwargs):
"""Mock mutations of a successful module validation."""
module.status = 'READY'
module.status_info = ['Something went very right.']
return module | 1ec360067eb2a4148231e70e9e86d1cccc579411 | 634,329 |
import time
def btc_climber(target,altcoin):
"""Will trade your current coin once the ratio and current market has buyer to take your
for btc
Args:
target (float): float
altcoin (string): string
Returns:
string: Sucess status string and time
"""
i=0
while i<3:
tim... | c4ee9219a01a77e5c27d5594ddbb86109ef613d9 | 634,330 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
res = []
i = 0
while i < len(lines):
N = int(lines[i])
notes = [tuple(map(int, l.split(" "))) for l in lines[i + 1:i + N + 1]]
res.append((N, notes))
i += N + 1
return res | cbe348636d439f48ae5da7e28c06c0c59f9c91d9 | 634,331 |
def hashing(file,pp):
""" Map an input file and a postprocessing config to an unique hash.
The hash is used to store the item in the database. It
needs to be persistent across different python implementations
and platforms, so we implement the hashing manually.
"""
file = file.lower()
file... | 82afc2e8a996cf1b893dc6bffe1f2553d772df01 | 634,333 |
def user_api_headers(user):
"""Authorisation headers for a client acting as the fixture user."""
t = user.token
return {'Authorization': 'Bearer %s' % t.decode('ascii')} | f47f89462fe428e9318e640fa387f25281ecc61e | 634,334 |
def _mapping_table_for(domain_table):
"""
Get name of mapping table generated for a domain table
:param domain_table: one of the domain tables (e.g. 'visit_occurrence',
'condition_occurrence')
:return: mapping table name
"""
return '_mapping_' + domain_table | 13488c7235b7c1052226d96c1c785ce5154d6aa5 | 634,335 |
def url_get_parent(url):
"""
http://one/two/three => http://one/two
http://one => http://one
"""
index = url.rfind("/")
if index > 8: # avoid https://
return url[0:index]
else:
return url | d7f7931384825febab86b7d59bfd1df972c7304a | 634,336 |
from typing import Tuple
import math
def get_xy_components(lon: float, lat: float) -> Tuple[int, int]:
"""For a given longitude and latitude, returns the relevant
components of the name of the zip file containing the SRTM data (for
example "35" and "02" in "srtm_35_02.zip").
"""
mod_lon = (int(mat... | 076a4339278766f59c91338fb95953455e4ae0eb | 634,337 |
def get_last_contiguous_byte(parts):
"""
given a parsed list of min/max byte ranges in ascending order,
figure out what is the max contiguous byte range uploaded so far.
We use this to determine what part of the upload we can stream back to the
client. Since there's no guarantee what order the uploa... | 75b04906b629b7a0260fd71b537529d85d92dc1a | 634,338 |
def recursive_merge(original, addition):
"""Merge the content of ``addition`` into ``original``, recursing when
both arguments have a dictionary for the same key.
"""
for key, value in addition.iteritems():
if key in original:
source = original[key]
if isinstance(source,... | 471c0a8731dc90a11d92e9a50a12975e2001a234 | 634,339 |
from typing import Dict
from typing import Any
def second_person(faker) -> Dict[str, Any]:
"""Returns dict for some `Person`."""
return {
"first_name": faker.first_name(),
"last_name": faker.last_name(),
"salary": 1000,
"currency": "€",
"date_of_birth": faker.date_objec... | fb9b2dc8d411cc5cc90923be956d955a3f3a455b | 634,340 |
def _convert_type(typename, obj):
"""Converts the specified object to the corresponding type
denoted by the specified type name."""
if obj == "null":
return None
if typename == "byte":
return int(obj)
elif typename == "short":
return int(obj)
elif typename in ("int", "in... | badd5f06123c520c1f5762a6016d55bee1779abd | 634,341 |
def ci_report(ci, with_offset=True, ndigits=5):
"""return text of a report for confidence intervals
Parameters
----------
with_offset : bool (default `True`)
whether to subtract best value from all other values.
ndigits : int (default 5)
number of significant digits to show
Ret... | 7437dea67eac6a72f29c9e74e47c32b8f715cb82 | 634,342 |
import subprocess
def get_added(merge_commit, target):
"""Get all lines added between start and end git ids."""
diff = subprocess.check_output(['git', 'diff', '{}...{}'.format(target, merge_commit)])
return '\n'.join(line for line in diff.decode('utf-8').split('\n')
if line.startswith... | b841204647713e5b4d24375ad5842d195849d910 | 634,343 |
def _old_node_test(node_info):
"""
Test the first entry of the first tuple in the tuple
"""
return node_info[0][0] | 58f125d2b71eb657c8e122b3dd51ecb6680db98e | 634,344 |
import torch
def bounding_box_x0y0x1y1_to_xcycwh(bounding_boxes: torch.Tensor) -> torch.Tensor:
"""
This function converts a given bounding bix of the format
[batch size, instances, 4 (x0, y0, x1, y1)] to [batch size, instances, 4 (x center, y center, width, height)].
:param bounding_boxes: Bounding b... | c365ac94068836d78d728e430812a39c3cfc80f9 | 634,345 |
def feats_combination(training_x_char_embedding, char_bigram_embedding, char_pos_embedding, char_pos_score_embedding,
char_pmi_embedding, dependences_embedding):
"""
特征的embedding合并
:param training_x_char_embedding:[[[char_embedding]]]
:param char_bigram_embedding:[[[char_bigram_emb... | 5446c42c9cddc57804f4a6efd83d49af74803b4d | 634,347 |
from typing import Any
from typing import MutableSequence
from typing import Tuple
def is_edge_list(item: Any) -> bool:
"""Returns whether 'item' is an edge list."""
return (isinstance(item, MutableSequence)
and all(isinstance(i, Tuple) for i in item)
and all(len(i) == 2 for i in item... | a164a34e1287b36250084aa76ebebad60f3346da | 634,348 |
import collections
def getDictFromAngles(angles):
"""
Converts angles of a JointState() to a dictionary
:param angles (sensor_msgs.msg.JointState): angles to be converted
:return (dict): dictionary with angles
"""
d=dict(zip(angles.name,angles.position))
return collection... | d919c0c52c25b8d6f6e894c8897b554190e8b88a | 634,349 |
import sys
import ctypes
def memfd_create(name):
"""
Create an anonymous memory backed file descriptor on Linux
http://man7.org/linux/man-pages/man2/memfd_create.2.html
"""
# make sure we are on 64 bit linux, otherwise this is probably the wrong syscall id
assert sys.platform == "linux" and s... | 81f256a012f9f821b9474ff039b4141da261e1d5 | 634,350 |
def process_status(pid, run):
"""
Return the status of a process, obtained using the ps command.
The run option is used to run the command (so it could run on
a remote machine). The result is a dictionary; it is empty if
the given process is not running.
"""
fields = ['%cpu', '%mem', 'etime... | 86acac06e3316631c275c1569c39d1a6b1d6eaca | 634,351 |
def freq_str(freq_list):
"""
Function that transforms the array of frequency values into a string
of comma separated entries.
The array is converted into a string and the square brackets are removed
form it. The resulting string will be the list of frequencies to sweep
over, organized into com... | c7a92e6226139459512fbbd765ef04137e0b148f | 634,352 |
def pd2(shellmound_model):
"""Perioddata defined with start_date_time, frequency and nper.
"""
m = shellmound_model
m.cfg['tdis']['options']['end_date_time'] = None
m.cfg['tdis']['perioddata']['perlen'] = None
m.cfg['tdis']['dimensions']['nper'] = 11
m.cfg['tdis']['perioddata']['freq'] = 'D'... | 4f271dbba3800b64916ae614859ff90c97253f57 | 634,353 |
import json
def incident_to_incident_context(incident):
"""
Creates an incident context of a incident.
:type incident: ``dict``
:param incident: Single detection object
:return: Incident context representation of a incident
:rtype ``dict``
"""
... | 28f4f9d34a9dbb23fd09bdd253a9328d32892b3b | 634,354 |
def _create_context_notification(context_responses=None, originator=None, subscription_id=None):
"""
Function to create the context notification model
:param context_responses: List with all context responses from server
:param originator: String with the originator identifier
:param subscription_i... | f26e423adc521b69231efa653beca6b9f91e9e5f | 634,355 |
import pandas
def get_first_column_from_excel(path):
"""
get first column of excel by path of excel
:param path:
:return:
"""
sheet = pandas.read_excel(path, header=None, usecols="A")
data = pandas.DataFrame(sheet)
values = [j.values[0] for i, j in data.iterrows()]
return values | 5ffdaefaebea47efdd1da1ce33245a4f0bab1c7a | 634,356 |
import os
def read_environment():
"""Load credentials from environment configuration."""
email_config = os.getenv("EMAILME_CONFIG", None)
if email_config is None:
return None
user, pw, hostname, host, port = email_config.split(":::")
return user, pw, hostname, host, port | e8639f3a869106b021a19fd2c19e0f57d9c3162e | 634,357 |
def getSelectionShape(selection):
""" Return the shape of the given selection.
Examples (selection -> returned shape):
[(3,7,1)] -> [4]
[(3, 7, 3)] -> [1]
[(44, 52, 1), (48,52,1)] -> [8, 4]
"""
shape = []
rank = len(selection)
for i in range(rank):
s = selection[i]
... | 6918660af077e04ea28ade739dbaebce739963f6 | 634,358 |
from datetime import datetime
def make_sim_exp_name(config):
"""Helper to create a simulator directory name using datetime and config"""
time = datetime.now().strftime('%Y%m%d_%H%M%S')
n_nonmot = config['exp_params']['n_non_motile']
n_mot = config['exp_params']['n_motile']
return f'{time}_sim_ma... | bf23d6d461897081f2a4c95c22876839532e400e | 634,359 |
def group_coadds(fname_to_spats: dict):
"""
Groups coadds. Destroys input.
Takes in dict mapping filenames to a list of integer spatial positions
Returns list of dicts mapping 'fnames' to a list of filenames and 'spats'
to a list of integer spatial positions.
"""
# input is dict mapping... | 9c2a313925ff30ee266b03e364be33571c9efff7 | 634,360 |
def _remove_extension(path, extension):
""" Removes the extension from a path. """
return path[:-len(extension)] if path.endswith(extension) else path | e819949ec396f70029df40e4a4aa3469e28ea613 | 634,361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.