content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def _replace_labels(html: str) -> str:
"""
Replace Django's question-level labels with legend elements
"""
return re.sub(
"<fieldset><label [^>]+>(.*?)</label>",
lambda m: f'<fieldset><legend class="tdp-question-legend">{m[1]}</legend>', # noqa: B950
html,
) | d69e23cf51fd00b4cec6201b12a2766a8f50a236 | 676,300 |
import math
def tanh(value):
"""
This function calculates the hyperbolic tangent function.
"""
return math.tanh(value) | e3fbb127c5ce2e7cf7fe13884c513c22b96ecf20 | 676,301 |
import warnings
def center_roi_around(center_rc, size_hw):
"""
Return a rectangular region of interest (ROI) of size `size_hw` around the
given center coordinates. The returned ROI is defined as
(start_row, start_column, end_row, end_column)
where the start_row/column are ment to be *include... | daddb578cf5b107d64a1d84df38ddbd3a671f988 | 676,302 |
def conv_lin(a, b=1.0, c=0.0, inverse=False):
"""Simple linear transform
will I think store parameters against each sensor then they are handy
>>> conv_lin(4,2,3)
11
>>> conv_lin(11,2,3.0,True)
4.0
>>>"""
if inverse is False:
return a * b + c
else:
... | a41d3254c933f59a5fb24253dcebc684a4211108 | 676,303 |
def get_param_dict(self):
"""Get the parameters dict for the ELUT of PMSM at the operationnal temperature and frequency
Parameters
----------
self : ELUT
an ELUT_PMSM object
Returns
----------
param_dict : dict
a Dict object
"""
# getting parameters of the abstract ... | 28da77a0bdc35af4920719972d2c528bcccc1510 | 676,307 |
def train_batch(model, x, target, optimizer, criterion):
"""Train a model for one iteration
Args:
model (torch.nn.Module): model to train
x (torch.Tensor): input sample
target (torch.Tensor): output target
optimizer (torch.optim.Optimizer): parameter optimizer
criterion (... | ba9b3160e033af2cf62ab86f9c992acb75efe9b6 | 676,309 |
def patch_init(mocker):
"""
Makes patching a class' constructor slightly easier
"""
def patch_init(*args, **kwargs):
for item in args:
mocker.patch.object(item, '__init__', return_value=None, **kwargs)
return patch_init | b09733feccfc0f443de26f12fd53e1d290f5e26a | 676,310 |
import json
def getCommandsFromLog(inFile,filterList,coverage):
"""
Get commands from a log
Parameters
----------
inFile : str
path to pyrpipe log file.
filterList : str
list of commands to ignore.
coverage : char
type of commands to report all, passed or failed: a... | e9e961f05a263405bb5f7eb4a4f75ad9011bc276 | 676,313 |
def get_panel_groups_at_depth(group, depth=0):
"""Return a list of the panel groups at a certain depth below the node group"""
assert depth >= 0
if depth == 0:
return [group]
else:
assert group.is_group()
return [
p
for gp in group.children()
f... | 1bbd8b94f39d738587262995953c4d7cd5f34dbe | 676,314 |
def get_class(name, defmod=None):
"""Finds a class.
Search a class from its fully qualified name, e.g.
'pyconstruct.domains.predefined.Class'. If the class name is not fully
qualified, e.g. 'Class', it is searched inside the default module.
Parameters
----------
name : str
The ful... | 107aa231aeeae666fa3b6deab67a738fca6f3767 | 676,317 |
def max_endtime(graph):
"""
A method to calculate the maximum endtime of a network.
Parameter(s):
-------------
graph : TemporalDiGraph
A directed, temporal graph.
Returns:
--------
maxEndtime : int
the maximum endtime of a networ... | 6654e32674b309c8034ff94e88e1d040c9b09b74 | 676,320 |
import requests
def get_jobdesc_config(job):
"""Function for extracting job description config file."""
job_desc_url = '%s/job_description.json' % job['job_url']
r = requests.get(job_desc_url, verify=False)
r.raise_for_status()
return job_desc_url | 33d03c0267f8d55a61c25163c586c138e302fee2 | 676,321 |
def ReadableSize(num):
"""Get a human-readable size."""
for unit in ['B', 'KB', 'MB', 'GB']:
if abs(num) <= 1024.0:
return '%3.2f%s' % (num, unit)
num /= 1024.0
return '%.1f TB' % (num,) | 6dfc713a70e36e9fd7fb91c443cf14c139702259 | 676,322 |
def convert_to_tuples(examples):
"""
Convert a list of Example objects to tuples of the form:
(source, translation, language, author, reference).
"""
convert1 = lambda e: e.to_simple_tuple()
return list(filter(bool, map(convert1, examples))) | 20e44c985b00791cd6c8e57c47e483be1c6e57e7 | 676,325 |
def prop_get_nyquistsampling(wf, lamx = 0.0):
"""Funtion determines the Nyquist sampling interval for the current beam,
which is focal_ratio * wavelength / 2.
Parameters
----------
wf : obj
Wavefront class object
lamx : float
Wavelength to use for computing sampling... | a0f4a0fd21a1e8a5d53da664cd780f28f2aedff7 | 676,326 |
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 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 |
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 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 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 getFileId(fname):
"""
Extract the id from a filename
"""
return '_'.join(fname.split('_')[:4]) | be3abfb0ab9940779627dc1f91518a076561c1cd | 676,360 |
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 |
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 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 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 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 |
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 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 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 |
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 |
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 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 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 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 |
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 |
def get_gear_ratio(g: int, gear_ratios: dict):
"""get gear ratio
Args:
g (int): gear
gear_ratios (dict): mapping of gear to gear ratio
Returns:
[float]: gear ratio
"""
return gear_ratios[g]['ratio'] | 79554d5c9b3cab209a69209c2959d053974db0db | 676,444 |
def fill_leaf_values(tree):
"""
Recursive function that populates empty dict leaf nodes.
This function will look for all the leaf nodes in a dictionary
and replace them with a value that looks like the variable
in the template - e.g. {{ foo }}.
>>> fill_leaf_values({'a': {}, 'b': 'c': {}})... | da9d576e3c3f574f7cbb08d8ab9b0a6193ef5e22 | 676,448 |
import json
import collections
def load_json_file(filename, use_ordered_dict=True):
""" Load a dictionary from a file
Parameters
----------
* filename: string
\tThe path to the saved json file.
* use_ordered_dict: bool
\tIf set to True dicts are read as OrderedDicts.
"""
tmp = Non... | c3730c7356689d4bc43c07f4e8c44755613965b4 | 676,452 |
def _all_none(*args):
"""Returns a boolean indicating if all arguments are None"""
for arg in args:
if arg is not None:
return False
return True | 102d3d73dc51d6dd851106e674a4e89a8d925a29 | 676,454 |
def pad(block, block_length):
"""
Pads a block with padding bytes to make it
to the required length, in this case, 128 bits.
PKCS5 padding
Parameters
----------
block : string
Block to be padded written in hexadecimal as string.
block_length : int
Block length in ... | 1bc060071750d3e8892d789118eb008c70b26f3b | 676,456 |
from datetime import datetime
def instantiate_datetime_object(datetime_stamps):
"""Takes a datestamp as a string and instatiates it into an object.
>>> datetime_stamps = [u'2016-09-10T15:35-07:00', u'2016-09-10T16:48-07:00']
>>> instantiate_datetime_object(datetime_stamps)
[datetime.datetime(2016, 9,... | 36f4c8a191bd7bdf3f3ae24f4162b53ed49ce3f0 | 676,459 |
def hr_sub(match):
"""Matches a horizontal rule."""
return '\n\n<hr/>\n\n' | dd0c2f30ab899174df48ee31b81b21058626b7d5 | 676,461 |
def parse_line(line):
"""0 <-> 454, 528, 621, 1023, 1199"""
line = line.split(" ")
return {"id": int(line[0]), 'connected': list(map(lambda num: int(num.replace(",", "")), line[2:]))} | 1ac631ae29fadd06992913ff38f2c7e8b56f2b22 | 676,466 |
import math
def get_objectives(data):
"""Get a list of all first chromosomes' objective values."""
objectives = [math.log(population[0]["objective"]) for population in data]
# objectives = [population[0]["objective"] for population in data]
return objectives | 870138db39a0e4c2b3d9c95bdd236bab20f4935e | 676,467 |
def get_raw_instances(self):
"""
Documentation:
---
Description:
Associate each EC2 instance ID with its EC2 instance object.
---
Returns:
raw_instances : dict
Dictonary where the keys are EC2 instance IDs and the
values ar... | c689d9939e183d353ed8d3c0bc22332952fdbd0c | 676,470 |
import re
def camel_to_snake_case(camel_cased_string):
"""Convert the format of the given string from CamelCase to snake_case.
Args:
camel_cased_string: the string in CamelCase format.
Returns:
the same string, but in snake_case format.
"""
return re.sub(r"(?<!^)(?=[A-Z])", "_", cam... | 7c7e688681c701f1ba6dc0d597bfea4c3fb08f3b | 676,471 |
import types
def is_function(obj):
"""Check if obj is function(lambda function or user defined method) or not"""
return isinstance(obj, (types.FunctionType, types.MethodType,
types.LambdaType)) | 1f912336a594cb4813c420914e3e550529eafe48 | 676,474 |
def _LoadWords(dict_file):
"""Returns a set of all the words in the dict file."""
words = set(word.strip().upper() for word in open(dict_file))
# Remove all single letter words except A, I.
for c in 'BCDEFGHJKLMNOPQRSTUVWXYZ':
words.remove(c)
return words | e5d6e8d6d35177ef5f0ad0cc3a75a5b31c866899 | 676,477 |
def process(data, template_name_key, split_char=";", **kwargs):
"""
Function to split templates. e.g. if ``template_name_key`` value
contains several templates, this processor will split them using
``split_char`` and produce data item for each template coping data
accordingly.
:param data:... | 4b7c3255e1eed60ff4f72b21b9ad414f794c81ba | 676,478 |
def get_required_attribute(el, key):
""" Get attribute key of element *el*.
:raises: :exc:`ValueError` if key not found
"""
val = el.get(key)
if val == None:
raise ValueError('required attribute missing: ' + key)
return val | 007156504130d90dc1001fd661d0094dfbf917e2 | 676,485 |
def calc_histograms(img_to_show):
"""Calculate histograms
Get R, G, B histogram values from an image.
Args:
img_array (image obj): image object to use
Returns:
r (list): list of histogram values for red pixels
g (list): list of histogram values for green pixels
b (list)... | db7fc32f7e29ee407c18a86c0ca920be1e0bd37b | 676,486 |
def get_frame_index(d):
"""Get frame index from the whole dictionary
E.g.,
'{'index': 'data/Deploy/KLAC/KLAC0570/KLAC0570_12.jpg', 'prediction': ..., 'label': ...}'
==> (int) 12
"""
return int(d['index'].split('_')[-1][:-4]) | 4560b4255374784834c5c16c8b365d1b5b1d0fcd | 676,490 |
def q_normalize(q):
"""Return a normalized quaternion"""
mag = (q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3])
if mag != 0:
for i in range(4):
q[i] /= mag;
return q | 9ca0386a9f9c8e48658ba54c4ce619b175790590 | 676,492 |
def get_dc(si, name):
"""
Get a datacenter by its name.
"""
for dc in si.content.rootFolder.childEntity:
if dc.name == name:
return dc
raise Exception('Failed to find datacenter named %s' % name) | 12b075c78f0dd1d999cf783a7933a231e9af1785 | 676,495 |
def granularity_to_ms(time_string):
"""Returns millisecond representation of granularity time string"""
magnitude = int("".join([c for c in time_string if c.isdigit()]))
unit = "".join([c for c in time_string if c.isalpha()])
unit_in_ms = {
"s": 1000,
"second": 1000,
"m": 60000,
... | 91512755af5e990bb03fc225a83f7acd77c015d1 | 676,498 |
def is_curious_fraction(numerator, denominator):
"""
Determine if two numbers form a curious fraction.
A curious fraction is where removing a number common to the numerator and
denominator is equal to the original fraction.
:param numerator: The numerator of the fraction as an int.
:param den... | 346ba10f33725cd9058206c957cb72bd3bfef148 | 676,503 |
import requests
def get_files(master_url, pr_url, headers):
"""
Returns the contents of the current version of the file and
of the modified version of the file in a tuple.
Args:
master_url (str): URL to the current version of the file
pr_url (str): URL to the modified version of the f... | 04a7945136c24efd1d29ef780281a8851fbeb71d | 676,505 |
def contour(ax, x, y, z, labels=True, **kwargs):
"""
Wrapper around Matplotlib's contour plot.
We add a small convenience argument `labels` that allows to simply add
clabels with a simple `labels=True`.
"""
cs = ax.contour(x, y, z, **kwargs)
if labels:
ax.clabel(cs, inline=1, fontsi... | c8e2d87bbaffbf67750da2f1449854361dc9601e | 676,506 |
def gc_content(seq):
""" GC content of a given sequence. """
seq = seq.upper()
return (seq.count('G') + seq.count('C'))/len(seq) | f631d38dca81df3a881c04e13628c68d62880786 | 676,508 |
def get_int(row, key, ignore_start=0, ignore_end=None):
""" row is the csv row to get an integer from,
key is that row's column that we want to cast as int,
start/end is the number of leading/trailing characters to ignore.
return 0 if could not convert
"""
try:
s = row[key][ignore_star... | 1d77fb3f4a0686b045894b4fd31d26c65b87ffd2 | 676,509 |
def binary(dataframe, entity_id, feature_id):
"""
Create binary feature dataframe using provided dataset, entity, and feature.
:param dataframe: Input dataframe to create binary features
:type dataframe: cudf.DataFrame
:param entity_id: Entity ID. Must be a column within `dataframe`
:type entit... | fd54366d6dc0949f701ee70d729f2d85d713bfd4 | 676,510 |
def filterl_index(predicate, List):
"""
Return the index of elements that satisfy the predicate function.
:param predicate:
:param List:
:return:
"""
result = []
for idx, e in enumerate(List):
if predicate(e):
result.append(idx)
return result | 8d71dad89271baedc7f233ef4fd9a8aa8579dece | 676,511 |
def parse_feats(feats):
"""
Helper function for dealing with the feature values that Stanza returns.
They look like "Case=Nom|Gender=Fem|Number=Sing" and we convert it to a dictionary with keys "Case" (e.g. "NOM"), "Gender" (e.g. "FEM"), "Number" (e.g. "SIN"). We capitalize the values and make them 3 charac... | 1d9858fe29220e319bcb92c494c65c719da68ce6 | 676,512 |
import random
def random_agent(network,agent1):
"""
Chooses a random agent relative to another agent. Meaning, if one
picks 'A' and wants another random agent to make a pair, 'A' will not
be chosen. Sets up a connection between two random agents.
Parameters
----------
network: Cayley netw... | b0c9750fda6a17bf85a06e4fc46c9f665f8d6776 | 676,513 |
from typing import List
def fibo(nth: int) -> List[int]:
"""Fibonacci numbers up to the `nth` term starting with 0 and 1."""
fibos = [0, 1]
for _ in range(nth - 2): # - 2 because we already have the first two
fibos.append(fibos[-1] + fibos[-2])
return fibos | e960cd5cf3520be0de343d2e615d7bf3e87d1bea | 676,515 |
def parameterize_cases(argnames, cases):
"""
This is used for parametrizing pytest test cases.
argnames: a comma separated string of arguments that the test expects.
cases: a dictionary of test cases.
"""
argnames_list = [i.strip() for i in argnames.split(',')]
argvalues = [tuple(i[k] for k... | 9c5bd5a3c6ccbdf571291d97253945bcc2aaea45 | 676,517 |
def add_newlines_by_spaces(string, line_length):
"""Return a version of the passed string where spaces (or hyphens) get replaced with a new line if the accumulated number of characters has exceeded the specified line length"""
replacement_indices = set()
current_length = 0
for i, char in enumerate(st... | 326d59fe3d9db67545ed3b9fd4cff487cff51af1 | 676,518 |
from typing import Any
import inspect
def isdata(the_object: Any) -> bool:
"""Check if an object is of a type that probably means it's data."""
return not (
inspect.ismodule(the_object)
or inspect.isclass(the_object)
or inspect.isroutine(the_object)
or inspect.isframe(the_objec... | 89f0a81cdc63859409539ce5eed5153deff80e53 | 676,520 |
def bool_to_pass_fail(value:bool) -> str:
"""Converts a boolean True to "Pass" and False to "Fail"
Parameters
----------
value : bool
A boolean value representing True for Pass and False for Fail
Returns
-------
str
"Pass" or "Fail"
"""
if value:
return "Pa... | 804a343eddc872f704f60732019f74464846ce19 | 676,521 |
def get_logical_switch(client_session, logical_switch_name):
"""
:param client_session: An instance of an NsxClient Session
:param logical_switch_name: The name of the logical switch searched
:return: A tuple, with the first item being the logical switch id as string of the first Scope found with the
... | 970d5d052281091b8f7312dc39986bcd8af4da58 | 676,522 |
import json
def load_json(json_file):
"""
Opens json-file and returns it as dictionary
:param json_file: path to json-file
:type json-file: string
:returns: the content of the json file as dictionary
"""
with open(json_file) as infile:
content = json.load(infile)
ret... | 211623ba735fcc9bbc624814e9d1712eb9f156a1 | 676,527 |
import re
def sanitize_for_url(word):
"""
Sanitizing of a word with a regex search string - everything that is not alphanumeric, a space or a colon is
substituted by an empty set
Args:
word (str): Word to sanitize
Returns:
str: Sanitized string
"""
return re.sub('[^a-zA-Z\s:]', '', word) | e8f6aa8a1e471bd8af2533702bca84ea7f027e5b | 676,528 |
from typing import Counter
def normalize_counts(counts):
"""Return a normalized Counter object."""
normed = Counter()
total = float(sum(list(counts.values()), 0.0))
assert total > 0 # cannot normalize empty Counter
for key, ct in list(counts.items()):
normed[key] = ct / total
return n... | 159479a53d2a0de94f4528674ecb978b692d3df0 | 676,529 |
def set_icon_image(icon):
""" Set Icon image or set None """
# Icon message files: https://stackoverflow.com/questions/37783878/
# is-it-possible-to-get-tkinter-messagebox-icon-image-files
# ::tk::icons::warning
# ::tk::icons::error
# ::tk::icons::information
# ::tk::icons::question
if i... | eefee87244274e06b9ad67899d9d8fe5cb3743e5 | 676,530 |
def read_seq_from_fasta(fasta):
"""retrieves the sequence of a fasta file, returns it as string
"""
with open(fasta, "r") as f:
seq = ""
for line in f:
if line:
if not line.startswith(">"): # ignore header
seq += line.strip()
return seq.up... | 52700ca370e76284bbd839785b14001b81de56fb | 676,533 |
def bump_build_number(d):
"""
Increase the build number of a recipe, adding the relevant keys if needed.
d : dict-like
Parsed meta.yaml, from get_meta()
"""
if 'build' not in d:
d['build'] = {'number': 0}
elif 'number' not in d['build']:
d['build']['number'] = 0
d['b... | d835b5e8467b5b8f02d96ef0f15408f281d880e0 | 676,534 |
def reduce_score_to_chords(score):
"""
Reforms score into a chord-duration list:
[[chord_notes], duration_of_chord]
and returns it
"""
new_score = []
new_chord = [[], 0]
# [ [chord notes], duration of chord ]
for event in score:
new_chord[0].append(event[1]) # Append new note... | cbc363b4f7318bf1cf7823281ace8da61fac2195 | 676,537 |
def _get_prepped_model_field(model_obj, field):
"""
Gets the value of a field of a model obj that is prepared for the db.
"""
try:
return model_obj._meta.get_field(field).get_prep_value(getattr(model_obj, field))
except:
return getattr(model_obj, field) | ec376030896d996bf8e0133645d4e276f50bc7c1 | 676,543 |
import re
def substitute(string, substitutions):
"""
Take each key in the substitutions dict. See if this key exists
between double curly braces in string. If so replace with value.
Example:
substitute("my name is {{name}}.",{version:1,name=John})
> "my name is John"
"""
for key, valu... | 8afc8fafcc34bf138598f8f5cb24a7da6a9b79cf | 676,547 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.