content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def replace_path(oumap, path):
""" Replace path UIDs with readable OU names"""
pattern = re.compile(r'\b(' + '|'.join(oumap.keys()) + r')\b')
result = pattern.sub(lambda x: oumap[x.group()], path)
return u'{}'.format(result) | 9a3acff87731b64c5be650a8ff2a5cf10fe741fb | 676,330 |
def _len_arg(typ):
"""Returns the length of the arguments to the given type."""
try:
return len(typ.__args__)
except AttributeError:
# For Any type, which takes no arguments.
return 0 | 15b3df3687af903cb1600fdd39ac406ab42e746a | 676,331 |
def to_str(str_or_bytes):
"""if input type is bytes, cast to string; return"""
if type(str_or_bytes) is str:
return str_or_bytes
elif type(str_or_bytes) is bytes:
return str_or_bytes.decode('utf-8')
else:
raise ValueError("str_or_bytes is not type str or bytes") | 4f812718617897dd8063692a84bbcd1c1f27c7e9 | 676,332 |
import random
def microtest(hyp, point, dimension_count, distance_metric, threshold, rng=random):
"""
Returns true if the hypothesis has any centroids within the threshold
distance of the point as calculated by the given distance metric.
Positional arguments:
hyp -- a hypothesis
point -- a po... | eaae67a237945a5152083d5ce36b0232f9295960 | 676,333 |
def cal_types(calendar_type):
"""
Define the julian date of the hijra and the intercalary years, according to the different
calendar types: see http://www.staff.science.uu.nl/~gent0113/islam/islam_tabcal.htm
and http://www.staff.science.uu.nl/~gent0113/islam/islam_tabcal_variants.htm
"""
calendar_types = {"1" : [... | d7b48ac21a6ad3cf5f283d5fa53874d3c6726fcb | 676,334 |
def load_input(filename):
"""
Load input file
"""
with open(filename) as f:
return [word[1:-1] for word in "".join(f.readlines()).strip().split(",")] | 3709d997f4ce6fcab5e1010047dc8b3ce027c7fd | 676,335 |
def merge_comp_optional_depends(optional_deps):
""" merge the condition for the dependency of same component name """
merge_depends = []
if optional_deps:
optional_deps.sort(key=lambda x: x["comp_name"])
last_dep = ""
for dep in optional_deps:
# print("optional dependency... | de6924274e1a6883d192712165d54a1617ab6ded | 676,336 |
def all_true(funcs):
"""Combine several ``is_independent`` functions into one
Parameters
----------
funcs : list-like
A list of ``is_independent`` functions
Returns
-------
combined_func : function
A new function which returns true of all the input functions are true
""... | faf9d57e2ffd1cdcbac87214569631c118fce55b | 676,337 |
def gen_cppcheck_enables(enables):
"""生成cppcheck的enable参数
格式:enable1, enable2, ...
"""
# 每个enable参数用逗号隔开
return '--enable={}'.format(','.join(enables)) | 638e2a979ab68c22b594e30d99e3ad9b5562facb | 676,338 |
def get_file_text(path, encoding):
"""Returns all text contents of a file at the given path in the form of a string."""
with open(path, mode='r', encoding=encoding) as f:
return f.read() | 7aef0cf434451a4131252f7ac797aba3f2c80225 | 676,339 |
def load(filename):
"""
读取文件中的数据
"""
x_data = []
y_data = []
with open(filename, "r") as fp:
for line in fp:
line = line.strip()
x, y = line.split(",")
x_data.append(float(x.strip()))
y_data.append(float(y.strip()))
return x_data, y_d... | 8a55b769aa23002cd8a614f7f4eb6eedfe1aa196 | 676,340 |
import os
def get_files_in_dir(startPath):
""" gets a recursive list of relative paths inside this directory """
working = [""]
results = []
while len(working) > 0:
current = working.pop(0)
p = os.path.join(startPath, current)
if (os.path.isfile(p)):
results.append(... | faabc234119239b714fcce4a42ad292bcd74afdb | 676,341 |
def voto(idade=0):
"""
=> Funcao calcula elegibilidade do votante
param idade: recebe a idade do votante
default value: 0
return: retorna elegibilidade do votante
"""
if idade < 18:
elegibilidade = 'NAO PODE VOTAR'
elif idade > 65:
elegibilidade = 'VOTO OPCIONAL'
else:
elegibilidade = 'VOTO OBRIGATORIO'
... | b7ee7d5d051e056da66daeb8171e6e042cb0cd85 | 676,343 |
def get_feature_orders():
"""
Returns an ordered list of features to use on webpage
and for model prediction (dataframe columns must be in correct order so that
model.predict(dataframe) will perform correctly)
"""
feature_order = [
"property_type",
"room_type",
"accommod... | 7c64fd679992dfdc312370f65b6e3914ed0bd7d9 | 676,344 |
def print_blank_history_window(min, max, terminal):
"""Figures out the first row under the header, and writes until it reaches the row above the footer.
:param min: integer number describing the height of the header
:param max: integer number describing the height of the footer
:param width: overall wi... | 22fc4aaf3dac450fa97f5b98f2a5b62a30f9c4e3 | 676,345 |
def standard_program_roles():
"""
Standard service roles that every week.
"""
standard_program_roles = [
"presider",
"vocalist1",
"vocalist2",
"vocalist3",
"pianist",
"guitarist",
"drummer",
"bassist",
"audio",
"powerpoint",... | fe0b22363acb740e9a0770143d207beac5da1f80 | 676,346 |
def lowest_common_ancestor(t, u, v):
"""Find the lowest common ancestor of two nodes
Parameters
----------
t : an `Ultrametric` tree or `nx.DiGraph`
The tree or directed acyclic graph on which to find ancestors.
u, v : int
The node IDs in `t` for which to find the common ancestor
... | b8f7d44b7f1aa9d38402ad8b70b09bec76682dfe | 676,347 |
import importlib
def call_module_function(*arguments):
""" Dynamically calls specified function from specified package and module, on the given image. The three arguments
of the function represent, in order: the input image, any extra input images (necessary in the case of many-to-
operations, empty other... | 47170d34e863d7698f11c08b21a8b36ce2956712 | 676,348 |
def get_dict_from_list(smu_info_list):
"""
Given a SMUInfo array, returns a dictionary keyed by the SMU name with SMUInfo as the value.
"""
smu_info_dict = {}
for smu_info in smu_info_list:
smu_info_dict[smu_info.name] = smu_info
return smu_info_dict | ce419960d1e791d6fdcb7c42a6881596cf2d12d9 | 676,349 |
def _c_null_pointer(p):
"""Returns true if ctypes pointer is null."""
return (not bool(p)) | 126023c7811d11a2e67df31750ed97048c2ba484 | 676,351 |
def sysv_hash(symbol):
"""sysv_hash(str) -> int
Function used to generate SYSV-style hashes for strings.
"""
h = 0
g = 0
for c in symbol:
h = (h << 4) + ord(c)
g = h & 0xf0000000
h ^= (g >> 24)
h &= ~g
return h & 0xffffffff | 342fb96bb84d17e066081cdbf6b1379cffecab61 | 676,352 |
def get_rev_recon(tree, recon, stree):
"""
Returns a reverse reconciliation
A reverse reconciliation is a mapping from nodes in the species tree to
lists of nodes in the gene tree.
"""
rev_recon = {}
nodes = set(tree.postorder())
for node, snode in recon.iteritems():
if node not... | 0fc2d2449a6d84a4e25eafaa08c72c67ac7c5eec | 676,353 |
def _unshaped_initializer(fn,
**kwargs):
"""Build a flax-style initializer that ignores shapes.
Args:
fn: Callable that takes a random number generator and some keyword
arguments, and returns an initial parameter value.
**kwargs: Arguments to pass to fn.
Returns:
Call... | 9c7815e46f94d2aee3c30b6651e1362d0f572c4a | 676,354 |
def parse_boundary_position_indicator(element):
"""
Parameters
----------
element :
The node-element instance.
Returns
-------
indicator :
'corner|6NEF' : For example, the 8 corners of the crazy mesh.
'corner-edge|2NEF.6NEB' : For example, at the 12 domain edge (ex... | cdb8613045812054ad3af84b3d017430fae8f59c | 676,355 |
def get_consecutive_num(arr):
"""
Method to get indices of second number in a pair of consecutive numbers
Note: solve_90f3ed37 uses this function
"""
rows = []
for i in range(len(arr) - 1):
if (arr[i] + 1) == arr[i + 1]:
rows.append(arr[i + 1])
return rows | 24417126d4133db62519dd044f7e0b9498d1ad0f | 676,356 |
def validatePath(path):
"""Returns the validated path"""
return path | 11403ff68e2f0c2b180f0a17f06fb59b47d24642 | 676,357 |
from typing import Counter
def _eigenvals_triangular(M, multiple=False):
"""A fast decision for eigenvalues of an upper or a lower triangular
matrix.
"""
diagonal_entries = [M[i, i] for i in range(M.rows)]
if multiple:
return diagonal_entries
return dict(Counter(diagonal_entries)) | 1579e31b9b00eb80271cb1fe39c953975d9575ea | 676,358 |
def context_from_mentions(mentions):
"""Returns IDs of medical concepts that are present."""
return [m['id'] for m in mentions if m['choice_id'] == 'present'] | ca6d997e03956f65f60ca6268db54e8ef0e18d5f | 676,359 |
def getFileId(fname):
"""
Extract the id from a filename
"""
return '_'.join(fname.split('_')[:4]) | be3abfb0ab9940779627dc1f91518a076561c1cd | 676,360 |
import logging
def convert_postprocessing_metric(metric, value, inUnit, outUnit):
""" If GME testbench metrics have either degrees Celsius or Fahrenheit,
convert data from Kelvin to desired units.
"""
logger = logging.getLogger()
logger.info('Converting ' + metric + ' of ' + str(value) + ' ' +... | c7244f3ce108c0fc896c1e99250a0cfada906927 | 676,361 |
def station_name(f):
"""
From the file name (f), extract the station name. Gets the data
from the file name directly and assumes the file
name is formatted as Data/Station_info.csv.
"""
return f.split('/')[1].split('_')[0] | 8498ef30a0067bf3984578c3dfe7c081a19c9e3a | 676,362 |
def string_to_values(input_string):
"""Method that takes a string of '|'-delimited values and converts them to a list of values."""
value_list = []
for token in input_string.split('|'):
value_list.append(float(token))
return value_list | 31addd1e12130b151b59d323745217b68d50490d | 676,363 |
def generate_reference(model, gen, field='reference', prefix='', max_retries=10):
"""
Generate a unique reference given:
:param model: the class of the django model
:param gen: a function without arguments that returns part or all the reference
:param field: reference field of the model that needs ... | 2d16c7da40b2a3e224a5cc0bf2dc6c202e17e2a3 | 676,364 |
import pickle
def load_ami_data(ami_id, data_type):
"""
ami_id:
191209 = manual transcription
asr-200214 = Linlin's ASR output (CUED internal, WER = 20%)
asr-200124 = AMI ASR Official Release
"""
path = "/home/alta/summary/pm574/summariser1/lib/model_data/ami-{}.{}.pk.bin".... | 4d0b77ea1d32b5198b94df2d7077ee1e85ea38cc | 676,365 |
def pivoting(tableaux,_colPivot, _linePivot):
"""
[function to make a pivonting from tableaux matrix]
Arguments:
tableaux {[matrix]} -- [description]
_colPivot {[int]} -- [index of column pivot]
_linePivot {[int]} -- [index of line pivot]
Returns:
[matrix] -- [t... | f309fa0d9983dedb9355369817ae9c04668ecf2a | 676,366 |
def extract_dep_contexts(doc):
"""Extract dependency contexts as key:val pairs
Given a word in a sentence, return it's modifiers:dependency and
it's head:dependency with this relation being labeled as INV.
Example:
{'austrailian': 'scientists amod-INV'}
{'scientists': 'austrailian amod'}
s... | 9894f75b5002ca49102ce71b8aa8b4d02bbb35ba | 676,367 |
def _has_eval_results_call(cls):
"""Return True if cls has a __call__ decorated with @eval_results
"""
return getattr(getattr(cls, '__call__', None), '_eval_results', False) | 3466ff2594f58d2ee9405e57cdb77bafbf3b9529 | 676,368 |
def add_desc_features(df):
""" Feature engineering with description
:param df:
:return:
"""
general = ['elevator', 'hardwood', 'doorman', 'dishwasher', 'no fee', 'reduced fee' 'laundry', 'fitness', 'cat', 'dog',
'roof', 'outdoor space', 'dining', 'internet', 'balcon', 'pool', '... | 39c19c5f4a7233bbefcf9bc2dbc87a687461922c | 676,369 |
import time
def _idle_since(device_dict):
"""Get .
Args:
device_dict: Device information dictionary
Returns:
idle_since: Dict of idle since values per port
"""
# Initialize key variables
idle_since = {}
# Get all the status of all the Ethernet ports
if 'layer1' in d... | e6bd957504c9c5ab6898b9269f20d3be421d8d33 | 676,370 |
def get_first_series(series_list):
"""
For each iterable of BIDSFiles get the minimum series number
"""
return min(series_list, key=lambda x: x.series_num).series_num | 4b2c3ed3ef58244c80901e00713fa04b63d60f86 | 676,371 |
def get_quantized_ints_block(dct_width, quantized_block):
"""
Store quantized block as integers.
The 4 float values of each row are stored as 1 byte each in an int.
First row value is stored in least significant byte.
Results in a list of 4 ints.
"""
ints_block = []
for y_index in range(... | 92a177c8417164166bacb5cde84f335098504fb7 | 676,372 |
import math
def trunc_method():
"""math.trunc(obj): Round to the integer nearest to zero."""
class _MinusPi:
def __trunc__(self):
return -3
return math.trunc(_MinusPi()) | 144f85839c0df5e0e3d457eb8f8c7faf117e2b78 | 676,373 |
def CommonSymbolsToOrder(symbols, common_symbols):
"""Returns s -> index for all s in common_symbols."""
result = {}
index = 0
for s in symbols:
if s not in common_symbols:
continue
result[s] = index
index += 1
return result | b10766d22e826dd62cedd21803e71ab2e075d48c | 676,374 |
import torch
def sdd_bmm_diag_torch(t1, t2):
"""
Perform bmm and diagonal for sparse x dense -> dense. The diagonalized result is returned in vector tensor.
With s_t1.shape = (b, x, s), d_t2.shape = (b, s, x), the output shape is (b, x).
This method avoids a temporal (b, x, x) for memory efficiency.
... | b10f19d2777198c021e4c9e115fbf6177062ec3f | 676,375 |
def ip_pool_to_dict(ipp):
"""Convert an IPPool object to a dict"""
return {
'input': ipp.input[0],
'unused': [str(x) for x in ipp.pool.iter_cidrs()],
} | dee5d8af7532cccc1256d85bcbed311720635e6a | 676,376 |
def flat_list(l):
""" Convert a nested list to a flat list """
try:
return [item for sublist in l for item in sublist]
except:
return l | 4fd398feb98b795af2b66e8b5f6b0f66fa29147f | 676,377 |
import os
def get_data_dirs(data_dir=None):
""" Returns the directories in which modl looks for data.
This is typically useful for the end-user to check where the data is
downloaded and stored.
Parameters
----------
data_dir: string, optional
Path of the data directory. Used to force... | a7e6a89fe52ba1c758d366ec0560e98be6888854 | 676,378 |
import re
import itertools
def _java_hex(uuid):
"""Java Mongo Driver transfers byte representation of UUIDs in little endian format.
See also https://jira.mongodb.org/browse/JAVA-403
:param uuid:
:return: reordered hex sequence
"""
_hex = re.sub(r'[{}-]', '', uuid)
bytes = list(zip(_hex[0:... | 69ab43034aff95805bcd6987c85a18b03847c649 | 676,379 |
def fibonacci(n):
"""フィボナッチ数を求める関数
:param n: ``n`` 番目のフィボナッチ数を求める
:returns: n番目のフィボナッチ数
:raises: ``ValueError`` when ``n`` is less than 0
"""
if n < 0:
raise ValueError('nは0以上を指定してください')
if n in (0, 1):
return n
return fibonacci(n - 1) + fibonacci(n - 2) | ac7d29793037e8f277f1f6153c677bf73a2d150b | 676,380 |
def bigint_to_int(mtime):
"""Convert bytearray to int"""
if isinstance(mtime, bytes):
return int.from_bytes(mtime, 'little', signed=True)
return mtime | 3cf552614ad41afee99fcd5c5f437e77e6fd1dfb | 676,381 |
import sys
def fix_tag(value):
"""Make a FIX tag value from string, bytes, or integer."""
if sys.version_info[0] == 2:
return bytes(value)
if type(value) is bytes:
return value
if type(value) is str:
return value.encode('ASCII')
return str(value).encode('ASCII') | e5ea2c33b788ad5e8fe2d382e788fdf9a6a17752 | 676,382 |
def world_to_basis(active, ob, context):
"""put world coords of active as basis coords of ob"""
local = ob.parent.matrix_world.inverted() @ active.matrix_world
P = ob.matrix_basis @ ob.matrix_local.inverted()
mat = P @ local
return(mat) | 60127ee0fc99884ee23a65324147d6e8c4530818 | 676,383 |
def clean_github_repository(repo):
"""
get the username/repository from a Github url
:param repo:str the Github url of the repository
:return: username/repository
"""
if repo is None:
return None
repo = repo.replace("http://github.com/", "") \
.replace("https://github.com/", ... | 8f3500a2841161c9baade2df553f00f083fe5a2b | 676,384 |
def str2bool(value):
"""Returns a boolean reflecting a human-entered string."""
return value.lower() in (u'yes', u'1', u'true', u't', u'y') | 84771452abe131121b6a7c1ad3fe245f899aab70 | 676,385 |
def filter_low_swh(ds):
"""Remove all records with low significant wave heights."""
return ds['sea_state_30m_significant_wave_height_spectral'] > 1.0 | 93c872885f446c0db87c6b3616b549a677ef5af8 | 676,386 |
import os
def normaljoin(path, suffix):
"""
Combine the given path with the suffix, and normalize if necessary to shrink the path to avoid hitting path length limits
"""
result = os.path.join(path, suffix)
if len(result) > 255:
result = os.path.normpath(result)
return result | a7a7c3995cb91eef3347bd262afeb9b588033d69 | 676,388 |
import os
def get_executable_path(py_binary_name):
"""Returns the executable path of a py_binary.
This returns the executable path of a py_binary that is in another Bazel
target's data dependencies.
On Linux/macOS, the path and __file__ has the same root directory.
On Windows, bazel builds an .exe file an... | 59fb8a837106bfe5d03affe01d62723054f23c72 | 676,389 |
import numpy
def chabrierIMF(mass, log_mode=True, a=1.31357499301):
"""
Chabrier initial mass function. Put the reference for the formula here.
INPUTS:
mass: stellar mass (solar masses)
log_mode[True]: return number per logarithmic mass range, i.e., dN/dlog(M)
a[1.31357499301]... | 0df6cf8bd8e91d9c65794d788a8214a34b5d8a07 | 676,390 |
def obtenerPendiente(y1,y2,factor):
"""
Funcion que calcula la pendiente que es usada para la interpolación
Recibe un valor y1, un valor y2 y el factor de interpolacion
"""
return float((y2-y1)/(factor)) | b2bfeb2dd189f6822f4dc4c745c35026c056d9eb | 676,391 |
def _unique_retrieval(element_list, elem_identifier, search_identifier):
"""
Get the text from a ResultSet that is expected to have a length of 1.
Parameters
----------
element_list : bs4.element.ResultSet
Result of a `findAll`
elem_identifier : str
An identifier for the element... | 5d0a73c2044cd2b87f839504e5c0a93f6fce6820 | 676,392 |
def time_to_knx(timeval, dow=0):
"""Converts a time and day-of-week to a KNX time object"""
knxdata = [0, 0, 0]
knxdata[0] = ((dow & 0x07) << 5) + timeval.hour
knxdata[1] = timeval.minute
knxdata[2] = timeval.second
return knxdata | 5f6e00f5e2770412b8c543047450a3e81bec1270 | 676,393 |
def prepare_cell_align_type(in_cell_align):
"""
Basic function that renames the cell alignment
string from the ArcGIS Pro UI and makes it dea
aws stac query compatible.
Parameters
-------------
in_cell_align : str
The ArcGIS Pro UI string for stac cell alignment.
Exampl... | dda7baf6c01a52eb2af9e34627474e1c671ab44a | 676,394 |
def play(context):
"""
The original MPD server resumes from the paused state on ``play``
without arguments.
"""
return context.core.playback.play().get() | 02e45a4eb38b23fbfa6c56b7b9d363528a7e5b66 | 676,396 |
def pd_reindex_fill(pd, index, keys):
"""
dataframe resort row with index as presented in keys
if key not exist then fill with nan
"""
pd = pd.pivot_table(index=index)
return pd.reindex(keys) | a1c54b56c9ec077b874a5f85e4ee9ca9e6c5da9f | 676,397 |
def zone_clique(x, y, pos_x, pos_y, taille):
"""
renvoie true les coordonnées (x;y) se trouve dans la plage de la pos_x à la pos_x
"""
return pos_x <= x <= pos_x+taille and pos_y <= y <= pos_y + taille | 48492e0fd39369644b8d2dd5b5b3f97bf2abcddb | 676,398 |
def remove_repeating(diags):
""" Removes any diagrams containing a repeating element
:param diags: List of labelled diagrams
:returns: diags: List of labelled diagtrams, where those with repeating structures are removed...
"""
diags = [diag for diag in diags if not diag.repeating]
return diags | f78524229322d1b98108a1790fd8a83da3ee2a1a | 676,399 |
import csv
import statistics
def medians(file):
"""
Given a csv file, find the medians of the categorical attributes for the whole data.
params(1):
file : string : the name of the file
outputs(6):
median values for the categorical columns
"""
fin = open(file, "r")
reader = ... | 784d6816b3c7310d221294e2f2b58c9da2e40329 | 676,400 |
def update_instance(instance, attrs):
"""Updates instance with given attrs dict"""
for key, value in attrs.items():
setattr(instance, key, value)
instance.save()
return instance | 6bc7786d4655a7a4db194cb9e1216ce5b81d34c0 | 676,401 |
def addDataDisk(samweb, mount_point):
""" Add a new data disk to the database
arguments:
mount_point: The mount point for the new disk
"""
return samweb.postURL('/values/data_disks', {'mountpoint': mount_point}, secure=True, role='*') | 4449723e77b8664233ce6ba108c4f24736772dc4 | 676,403 |
def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
"""Verify that the parameters represent a valid array within
the bounds of the allocated memory:
char *mem: start of the physical memory block
memlen: length of the physical memory block
offset: (char *)buf... | e0bf076d04858b0cacc5942884f6defec0425868 | 676,404 |
def get_pretrain_stop_metric(early_stopping_method, pretrain_tasks):
"""
Get stop_metric, which is used for early stopping.
Parameters
-------------------
early_stopping_method: str,
pretrain_tasks: List[Task]
Returns
-------------------
stop_metric: str
"""
if early_s... | 75284e95f83182629a4def003fdcf059a97516ff | 676,406 |
def partitions():
"""Fixture to set up test partition information."""
return [
{
"device": "sda",
"partid": 5,
"mountpoint": "/",
"size": 1024,
"fstype": "ext4",
"options": "host_options",
},
{
"device": "sda",
"partid": 6,
"mountpoint": "/var",
"size": 0,
"fstype": "ext4",
},... | c333aea28fb9475f1606be101353ee0a351f48e9 | 676,407 |
import itertools
def _seperate(state_sets):
"""Return the unconflicted and conflicted state. This is different than in
the original algorithm, as this defines a key to be conflicted if one of
the state sets doesn't have that key.
"""
unconflicted_state = {}
conflicted_state = {}
for key i... | 760cd836b4f294bc0b8c9ca9ff075fa767215d58 | 676,409 |
import os
def listdict2envdict(listdict):
"""Dict of lists --> Dict"""
for key in listdict:
if isinstance(listdict[key], list):
listdict[key] = os.path.pathsep.join(listdict[key])
return listdict | d29ef35ec8417576370b0365b363ce542b77709f | 676,410 |
def read_D(filename):
"""reads an upper triangular matrix with phylogentic distances
between species.
Returns a dictionary with distances for species names."""
D = {}
f = open(filename)
cols = f.readline().rstrip().split('\t')
for line in f:
elems = line.strip().split('\t')
... | f542d939ee1ceed29c4265a1f77c2ccb5c99d00a | 676,411 |
def get(isamAppliance, check_mode=False, force=False):
"""
Get SNMP Monitoring v1/2
"""
return isamAppliance.invoke_get("Get FIPS Settings",
"/fips_cfg") | 0d138ad1db80dfcde9493053238d80fdd9371095 | 676,412 |
from pathlib import Path
import os
from typing import Optional
import shutil
import sys
def get_gdal_dir() -> Path:
"""
This function finds the base GDAL directory.
"""
gdal_dir_environ = os.environ.get("GDAL_DIR")
gdal_dir: Optional[Path] = None
if gdal_dir_environ is not None:
gdal_d... | da07fbdef89fbfc3e330f0aa9fb6cf59127c0300 | 676,413 |
import tempfile
import requests
import sys
def request_raster_from_url(url, verbose=False):
""" returns :class:`tempfile.NamedTemporaryFile` object """
# pylint: disable=R1732
tmpfile = tempfile.NamedTemporaryFile()
with open(tmpfile.name, 'wb') as f:
response = requests.get(url, stream=True)
... | ceda2ffa2a8040a07bc684e412b95919e1daf2bc | 676,414 |
import torch
def centroids(XW, Y, k, device="cpu"):
"""
==========================================================================
Return the number of selected genes from the matrix w
#----- INPUT
XW : (Tensor) X*W
Y : (Tensor) the labels
k ... | 942227245f5b99a3a64601e5b14f2e2311b7dfc4 | 676,415 |
import torch
def corn_labels_from_logits(logits):
"""
Returns the predicted rank label from logits for a
network trained via the CORN loss.
Parameters
----------
logits : torch.tensor, shape=(n_examples, n_classes)
Torch tensor consisting of logits returned by the
neural net.
... | a69597e7f3bf274ef487bca2bd7dc9b2c0d4d69c | 676,416 |
def tol():
"""
The convergence tolerance.
"""
return 1e-6 | 3744aa01b5de33758bd68b12c4d1a83e93732e53 | 676,417 |
def __get_level_color(level: int) -> tuple[int, int, int]:
"""
根据等级获取相应等级颜色
:param level: 等级
:return: (int, int, int): RGB 颜色
"""
level_color: dict[int, tuple[int, int, int]] = {
0: (136, 136, 136),
1: (102, 102, 102),
2: (153, 204, 153),
3: (221, 204, 136),
... | 0b1965ef95aa74a8b54336ae700ef6b01cd8e527 | 676,418 |
import yaml
def read_yml(filepath: str) -> dict:
"""Load a yml file to memory as dict."""
with open(filepath, 'r') as ymlfile:
return dict(yaml.load(ymlfile, Loader=yaml.FullLoader)) | 9199bb64d82c8885daf0982eb0357c2bd27b920e | 676,419 |
import json
def load_json_file(filename):
"""Load data from a json file."""
data = {}
print('Loading file "{}"'.format(filename))
with open(filename, 'r') as infile:
data = json.load(infile)
return data | a49b363df60bd6d885092e3013be392f8ead4444 | 676,420 |
def get_thredds_opendap_link(folder, sub_folder, processing_level, prefix, station_name, year, month):
"""
:param station_name: string
:param folder: string
:param sub_folder: string
:param processing_level: int
:param prefix: string
:param year: int
:param month: int
:return: strin... | 946782cea06307e063457f6fb71e489d4dcb555d | 676,421 |
def num_nodes_with_name (root,name,recurse=True):
###############################################################################
"""
Count nodes with certain name in an XML tree
>>> xml = '''
... <root>
... <a/>
... <sub>
... <a/>
... </sub>
... </root>
... ... | 8c049e78db3d619232a16a47cc321ae5f15e8dae | 676,422 |
def binary_freq(data, expression, feature_name=str, analyze=True):
"""Search data for occurrences of a binary feature as a regex.
Args:
data (pd.Series): a series with text instances.
expression (re.compile): a regex or string to search for.
feature_name (str, optional): a name for the... | 3211b7bfb37aae912816e81f8eb92792afd7a4e1 | 676,425 |
def confirm_mirror(uri):
"""Check if line follows correct sources.list URI"""
deb = ('deb', 'deb-src')
proto = ('http://', 'ftp://')
if (uri and (uri[0] in deb) and
(proto[0] in uri[1] or
proto[1] in uri[1])):
return True
return False | 9c83bad8599cb3c7f78c965ab5c20c8454824022 | 676,426 |
import re
def sum_of_integers_in_string(s: str) -> int:
""" This function calculates the sum of the integers inside a string """
return sum([int(i) for i in re.findall(r'\d+', s)]) | 159572608e8a6c48a6a877a4ac7f915e94eab2b8 | 676,427 |
def collectFromFile(F):
"""
A simple method to collect all integers from a file and return a list-object
:param file: a file on the system, preferably made by makeNewFile(file,list)
:return: list of integers
"""
returnList=[]
with open(F,'r') as f:
for line in f:
returnList.a... | 1c6b4e4a43f0f5f9f7ddc2397850500a1044c6ef | 676,428 |
def divide(left, right):
"""/"""
return left / right | 33ac187fd75c94d7bb9ba1943fd6511d9425f11f | 676,429 |
def add_nonN_count(df, nonN_count_file):
"""Count number of nonambiguous nucleotides per sequence and
add counts to dataframe"""
count_dict = {}
with open(nonN_count_file, 'r') as f:
for line in f:
id, count = line.rstrip('\n').split('\t')
count_dict[id] = int(count)
... | 7a918d2eb80b8db0c9a9d37987db4c539aa14396 | 676,430 |
from typing import Sequence
import re
def list_to_patt(lst: Sequence[str], name: str) -> str:
"""
Create a regex pattern in string form capable of matching each element
in a list.
Beware of having empty string in lst!
Arguments:
lst: list of strings for which a regex pattern is to be deter... | 43925e7fc0cbe5b427faf679064b63e96683dad7 | 676,434 |
import torch
def pad_packed_sequence(inputs):
"""Returns speechbrain-formatted tensor from packed sequences.
Arguments
---------
inputs : torch.nn.utils.rnn.PackedSequence
An input set of sequences to convert to a tensor.
"""
outputs, lengths = torch.nn.utils.rnn.pad_packed_sequence(
... | 5371ba0abcf6b8d053a963a3aa50d9c77f43ea5f | 676,435 |
import struct
def parse_linkidandlinkedbehavior(number):
"""
Returns a link ID index and behavior tuple for the given number.
"""
number = int(number)
byteval = struct.pack('>i', number)
(linkid, junk, behavior) = struct.unpack('>bbH', byteval)
return (linkid, behavior) | 6bc9c8570a39955ec5d718cfe0b348acd66b78a7 | 676,436 |
import time
import os
import json
def echo(event, context):
"""Echo handler."""
event["ts"] = time.time()
event["os.environ"] = dict(os.environ)
print(json.dumps(event, indent=4))
return event | 6b6e6b572a0e723fa7644947347bc43b718ce355 | 676,437 |
import numpy
import warnings
def sequentialPrecision(data):
"""
Calculate percentage sequential precision for each column in *data*. Sequential precision for feature :math:`x` is defined as:
:math:`\mathit{{sp(x)}} = \\frac{\sqrt{(\\frac{1}{n-1} \sum_{i=1}^{n-1} (x_{i+1} - x_i)^2)/2}}{\mu_{x}} \\times 100`
:par... | 0c4814c4b63b548b49a56ba1a75e4b69ee3dbe2f | 676,438 |
def echo(text):
"""create job that just prints text"""
return ['echo', text] | bb1336f474da68ed1ce7ae82fb00dadc6a642104 | 676,439 |
def create_cast_date_column_query(dbms: str, date_format: str, date_column: str) -> str:
"""
Create query that cast date column into yyyy-MM-dd format
:param dbms: data warehouse name
:param date_format: format of date column
:param date_column: name of the column with periods
:return: query to... | 35d0fcfdeac33c22d6ce92e73f31953c4a24c6ee | 676,440 |
def build_geometry(self, sym=1, alpha=0, delta=0):
"""Build the geometry of the machine
Parameters
----------
self : Machine
Machine object
sym : int
Symmetry factor (1= full machine, 2= half of the machine...)
alpha : float
Angle for rotation [rad]
delta : complex
... | 670e7ae40e6f02d386cba477cd6bc6dfcf2f42e9 | 676,441 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.