content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_client_referred(row):
"""
Applied to a dataframe
Returns whether a client was referred to HL
"""
client_referral_origin = row['How Was Client Referred to HL?']
referral = [
'Referred by non-clinical staff (medical asst., registration, legal services, etc)',
... | 8332901a91391eb073593577bbb11d6044097ae3 | 381,052 |
from functools import reduce
def min_from_iterable(iterable):
"""
Return the min in the iterable
>>> min_from_iterable([1, -2, 35, 11, 28])
-2
"""
return reduce(min, iterable) | ac7aaa4c521a3f326029d604736efc4de46cb2da | 566,737 |
def CrlfReplacer(line, file_path, line_number):
"""Replaces CRLF with LF."""
if '\r\n' in line:
print('Replacing CRLF with LF in %s:%s' % (file_path, line_number))
return line.replace('\r\n', '\n') | c2b82fecaf662a2d0ad2ec30c33c464e8fe5b7c8 | 538,452 |
def _commonHits(trk1, trk2):
"""Returns the number of common hits in trk1 and trk2. Matching is
done via the hit type and index, so effectively the matching is
done by clusters. Invalid hits are ignored.
"""
hits1 = set()
for hit in trk1.hits():
if not hit.isValidHit(): continue
... | ede7ad9f9bdca3ca95464abcf3513cbe89a43665 | 198,018 |
def find_key(dic, val):
"""Return the keys of dictionary dic with the value val."""
return [k for k, v in dic.iteritems() if v == val] | 158060d8be64d8f547bc5c3762452861a5ba0bec | 649,902 |
def dmp_zero(u):
"""
Return a multivariate zero.
Examples
========
>>> from sympy.polys.densebasic import dmp_zero
>>> dmp_zero(4)
[[[[[]]]]]
"""
r = []
for i in range(u):
r = [r]
return r | adf836cc5f59da00702c218c0018b17f9c478e86 | 434,946 |
def is_valid_transaction_hash(tx_hash):
"""Determines if the provided string is a valid Stellar transaction hash.
:param str tx_hash: transaction hash to check
:return: True if this is a correct transaction hash
:rtype: boolean
"""
if len(tx_hash) != 64:
return False
try:
... | 8a9f6e2e09cc758b61a50ff27a0030fe98db6853 | 389,910 |
from typing import Tuple
def _split_sampling_rate_byte_11_2(sampling_rate_byte: int) -> Tuple[int, int]:
"""Separate sampling rate into its own byte."""
return sampling_rate_byte & 0x0F, sampling_rate_byte & 0xF0 | 126e64fe194802661e012c4d01f06a654ff96d0f | 109,879 |
def listupper(t):
"""
Capitalizes all strings in nested lists.
"""
if isinstance(t, list):
return [listupper(s) for s in t]
elif isinstance(t, str):
return t.upper()
else:
return t | 4fb773d819671e7989a2c976da7be928f9d2e703 | 401,945 |
def _timex_pairs(timexes):
"""Return a list of timex pairs where the first element occurs before the
second element on the input list."""
pairs = []
for i in range(len(timexes)):
for j in range(len(timexes)):
if i < j:
pairs.append([timexes[i], timexes[j]])
return... | f0d232e138da377b1e07d866e0472752911b99f5 | 591,578 |
def is_merged(cell):
"""Whether the cell is merged."""
return True if type(cell).__name__ == 'MergedCell' else False | 0f980b13ec0ae69da905a01a87cc9a709ae50396 | 209,264 |
def _get_should_cache_fn(conf, group):
"""Build a function that returns a config group's caching status.
For any given object that has caching capabilities, a boolean config option
for that object's group should exist and default to ``True``. This
function will use that value to tell the caching decora... | 7a11124c640bfb3ced28e2d9395593b70dc85a0a | 1,128 |
def fry(word):
"""Drop the `g` from `-ing` words, change `you` to `y'all`"""
if word.lower() == 'you':
return word[0] + "'all"
if word.endswith('ing'):
if any(map(lambda c: c.lower() in 'aeiouy', word[:-3])):
return word[:-1] + "'"
else:
return word
ret... | 8aafe9e9c94b76fc55d93e9069732dbce5fcdb8e | 172,604 |
def get_dynamic_shape(min_shape, max_shape):
"""
Determine which dimension should be set to -1 according to min/max shape
"""
assert len(min_shape) == len(max_shape)
dynamic_shape = []
for min_inp, max_inp in zip(min_shape, max_shape):
# If one dimension is same between min_shape and max... | 0dcfe958e94c5a570d07f1141bdf9e340964cc80 | 201,472 |
def count_diff(str1, str2):
"""
Counting the number of different chars between two string.
Assuming len(str1) == len(str2)
"""
count = 0
for i in range(len(str1)):
if str1[i] != str2[i]:
count += 1
return count | de9411ff2c233d30972cb92598d4d317614438c7 | 575,416 |
import torch
def load_ckp(model, optimizer, lr_scheduler, path):
"""load training checkpoint"""
checkpoint = torch.load(path)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
lr_scheduler.load_state_dict(checkpoint['lr_scheduler_... | f758d3fb2ad6d7a4c0263a3958c50d9339b009b0 | 376,786 |
def get_single_band(fnames,band_numbers,band_num):
"""
Function to return the file path for a single band, given a band number and
list of input file paths.
Parameters
----------
fnames : LIST
List of band file locations, as generated by get_filenames().
band_numbers : LIST
... | 12f51ae740fe50a0deb0ceb959329a6e98e49ff8 | 620,707 |
def axial_to_oddq(axial_coordinates):
"""
convert axial coordinates to column row coordinates
"""
cube_z = axial_coordinates[0] + axial_coordinates[1]
col = axial_coordinates[0]
row = int(cube_z + (axial_coordinates[0] - (axial_coordinates[0] & 1)) / 2)
return [col, row] | e4fd6a3a73f3c7fba4de30d4da8d2c40027f7632 | 358,047 |
def cell_edge(subidx, subncol, cellsize):
"""Returns True if highres cell <subidx> is on edge of lowres cell"""
ri = (subidx // subncol) % cellsize
ci = (subidx % subncol) % cellsize
return ri == 0 or ci == 0 or ri + 1 == cellsize or ci + 1 == cellsize | 5e9e0b912d163686b4fa845535157e41ec01d027 | 177,240 |
import re
def match_mm3_improper(mm3_label):
"""Matches MM3* label for improper torsions."""
return re.match('[\sa-z]5', mm3_label) | f1cf55d00858a8a805247e1d72b6a35a7e9da613 | 130,545 |
def format_orbital_configuration(orbital_configuration: list) -> str:
"""Prettily format an orbital configuration.
:param orbital_configuration: the list of the number of s, p, d and f orbitals.
:return: a nice string representation.
"""
orbital_names = ['s', 'p', 'd', 'f']
orbital_configurati... | b7aed38ae25db8b44d76cbbc6942b92b2a3d26b7 | 549,531 |
from typing import Any
def verbatim(text: Any) -> str:
"""
Returns the main string argument as-is.
It produces a TypeError if input text is not a string.
"""
if not isinstance(text, str):
raise TypeError("argument to verbatim must be string")
return text | 0f735833f1514f0f5bd45efc07af783ffc72cbd3 | 37,210 |
def lagrange(x_values, y_values, nth_term):
"""
If a polynomial has degree k, then it can be uniquely identified if it's values are known in k+1 distinct points
:param x_values: X values of the polynomial
:param y_values: Y values of the polynomial
:param nth_term: nth_term of the polynomial
:r... | b7f2b44eaa70dee7984ac4ad73ccfb4316cf93ed | 57,619 |
def set_image_paras(no_data, min_size, min_depth, interval, resolution):
"""Sets the input image parameters for level-set method.
Args:
no_data (float): The no_data value of the input DEM.
min_size (int): The minimum nuber of pixels to be considered as a depressioin.
min_depth (float): ... | 0387e31e47cee78f2439de4fca6b1555e1e25c56 | 171,905 |
def split_layout_args(kwargs, skip=()):
"""
Split a dictionary of arguments into arguments that should be applied to
layout from arguments that should be passed forward.
Args:
kwargs (mapping):
A mapping of names to values
skip (sequence):
A optional set of argu... | 41a64a37db620c9efd16b3342d1efc972ee04f43 | 294,502 |
def unit_interval(x, xmin, xmax, scale_factor=1.):
"""
Rescale tensor values to lie on the unit interval.
If values go beyond the stated xmin/xmax, they are rescaled
in the same way, but will be outside the unit interval.
Parameters
----------
x : Tensor
Input tensor, of a... | 4083e1904eefeec606e8a22e53485f7007257e71 | 37,489 |
def neg_btn(value):
"""Return the current value multiplied by -1."""
if value.count(" "):
val_list = value.split()
num1 = val_list[0]
math_symbol = val_list[1]
num2 = float(val_list[2]) * -1
num2 = str(num2)
return f"{num1} {math_symbol} {num2}"
elif float(val... | 9732a671f6249e40950c8ba998a5efc6e52c88e7 | 330,515 |
def badge(text='', level='default'):
""" *Generate a badge - TBS style*
**Key Arguments:**
- ``text`` -- the text content
- ``level`` -- the level colour of the badge [ "default" | "success" | "warning" | "important" | "info" | "inverse" ]
**Return:**
- ``badge`` -- the badge """
... | c0b80d36c9e0d9c9c5f33f6f100780b612f2232b | 298,288 |
def mean_total_reward(rollouts):
"""
Get the mean of the total rewards.
"""
return sum([r.total_reward for r in rollouts]) / len(rollouts) | 58752e1369d089eebff6ae504621e477986cdbcb | 66,784 |
def flat_result_2_row(predictions):
""" flat the mitosis prediction result into rows
Args:
predictions: a tuple of (slide_id, ROI, mitosis_num,
mitosis_location_scores), where mitosis_location_scores is a list
of tuples (r, c, score)
Return:
a list of tuples(slide_id, ROI, mitosis_num, r, c, ... | f8bed3158f2db6d998f32de2bfdb25fd241f8ad7 | 285,293 |
def order_salaries(df):
"""Turn salary range into ordered variable."""
df = df.copy()
cats = ['< 10k', '10k to 20k', '20k to 30k',
'30k to 40k', '40k to 50k', '50k to 60k',
'60k to 70k', '70k to 80k', '> 80k']
df['salary_range'] = (df.salary_range.cat
.s... | 36e0f39ed3ff7aa67e433e55952de268f686955f | 572,151 |
def get_isbn(raw):
"""
Extract ISBN(s).
@param raw: json object of a Libris edition
@type raw: dictionary
"""
identified_by = raw["mainEntity"].get("identifiedBy")
if identified_by:
isbns = [x for x in identified_by
if x["@type"].lower() == "isbn"]
return [x... | 55f4f0ea6d8b1b70544dc5b74f703646427f1f81 | 683,144 |
def create_option(name, ty, docstring, default_factory=lambda: None):
"""Creates a type-checked property.
Args:
name: The name to use.
ty: The type to use. The type of the property will be validated when it
is set.
docstring: The docstring to use.
default_factory: A callable that takes no arg... | abf646c7b8ddbd71bf7761c8f94989bcbc9f107b | 65,317 |
from typing import Union
from typing import Dict
def _get_if(interfaces, index) -> Union[Dict, None]:
"""
Get interface configuration based on interface index
:param index:
:return:
"""
for interface in interfaces:
if int(interface['ifindex']) == index:
return interface
... | 25104482fe9884a1d48f8ba7b0e913a4cc81b0a4 | 396,944 |
def isNewPhase(ds1, ds2):
"""
Check if two dynamicsState have the same contacts
:param ds1:
:param ds2:
:return: True if they have the same contacts, False otherwise
"""
assert ds1.effNum() == ds2.effNum(), "The two dynamic states do not comes from the same model."
for i in range(ds1.ef... | b6bf21106024991256a3a53b887bf73f83e7c037 | 39,264 |
def normalize_space(string):
"""Normalize all whitespace in string so that only a single space
between words is ever used, and that the string neither starts with
nor ends with whitespace.
>>> normalize_space(" This is a long \\n string\\n") == 'This is a long string'
True
"""
return ' '.join(str... | 54823031616267fdc0d9f7afdadf0af5a5b22a7c | 142,395 |
import torch
def alpha_sigma_to_log_snr(alpha, sigma):
"""Returns a log snr, given the scaling factors for the clean image and for
the noise."""
return torch.log(alpha**2 / sigma**2) | 834a1b269fb9d7aa6180d53dff41402d5c0a13c9 | 164,150 |
def get_weight_param(hparams, param_name, default_value=1.0):
"""Returns params dict for a parameter value based on what is set in hparams.
Args:
hparams: configDict.
param_name: str; Name of the weight parameter.
default_value: float; Value used if not set.
"""
default_params = {
'initial_va... | e41fd5e9c78f8a20f07b8b8ecbdbd1d6ba6a84d5 | 451,993 |
def docker_compose_file(mock_dir):
"""
Path to docker-compose configuration files used for testing
- fixture defined in pytest-docker
"""
fpath = mock_dir / 'docker-compose.yml'
assert fpath.exists()
return str(fpath) | e32eb5ede50b47c562d48dee5dfb6958f2a49817 | 591,830 |
def is_variant(call):
"""Check if a variant position qualifies as a variant"""
if call == 1 or call == 3:
return True
else:
return False | b09bda05a58aec66a8be56896c6a7e1da70642ee | 620,925 |
def check_validity(passport):
"""Check if a passport is valid."""
return len(passport) == 8 or len(passport) == 7 and "cid" not in passport | 2bee1afea0f77e5c7bc5f8f576991432f479bab2 | 514,919 |
from typing import Union
from datetime import datetime
def epoch_to_datetime(epoch: Union[int, float, str]) -> datetime:
"""Converts an epoch timestamp to a datetime object.
Args:
epoch - (int) Epoch time.
Returns:
datetime - Datetime equivalent of the epoch provided.
"""
ret... | bcfc1968b705fc88d8e01a6ba626a27943a7f926 | 599,475 |
def check_unique_list(input):
"""
Given a list, check if it is equal to a sorted list containing 1-9
Return True if the given list is unique, False otherwise
"""
# convert list string into list of int and sort it
int_list = list(map(int, input))
int_list.sort()
return int_list == [1, 2, ... | 0448d3c054063076b4bcd3eb37def9cc5e1edfed | 62,735 |
def _sh_cmd(system, *args):
"""
Helper function to build a local shell command
"""
if len(args) == 0:
return None
return args | 232653f8f1170fb5715860206678e560a40000e3 | 657,196 |
def rewrite_arcs (label_map, nfa):
"""Rewrite the label arcs in a NFA according to the input remapping."""
states = [[(label_map[label], tostate) for (label, tostate) in arcs]
for arcs in nfa[2]]
return (nfa[0], nfa[1], states, nfa[3], nfa[4]) | 2bd9911a5c65ce7711848746614a3a6ceb37f8d2 | 13,141 |
def get_values_from_line(line):
"""Get values of an observation as a list from string,
splitted by semicolons.
Note 1: Ignore ';' inside \"...\". E.g. consider \"xxx;yyy\" as one value.
Note 2: Null string '' for NA values.
"""
raw_list = line.strip().split(';')
i = 0
values = []
whi... | 585c6c9484f6ad145f7265613dc189351cc2d556 | 698,551 |
def compute_result(droprate_dict,multiplier_dict,TPCut):
"""This is very straightforward so not much is needed to explain here.
1) Decide is the TP cut is required during calculation
2) Determine the value per raw material in each salvage item given item droprate and item value
3) Determine the sum of t... | 0dc8d12f424ac4a4c2fee2fea06b0589f587492d | 213,820 |
def __parse_version_from_service_name(service_name):
"""
Parse the actual service name and version from a service name in the "services" list of a scenario.
Scenario services may include their specific version. If no version is specified, 'latest' is the default.
:param service_name: The name of the ser... | 7fc634b7159e7141e99cbec090275388f00e27c5 | 650,120 |
def partitionByFunc(origseq, partfunc):
"""Partitions a sequence into a number of sequences, based on the `partfunc`.
Returns ``(allseqs, indices)``, where:
- `allseqs` is a dictionary of output sequences, based on output values
of `partfunc(el)`.
- `indices` is a dictionary of ``(outv... | 3c0c8777c4c953a688c54b57e0f0143c6bff5336 | 205,230 |
def get_steps_to_exit(data, strange=False):
"""
Determine the number of steps to exit the 'maze'
Starting at the first element, move the number of steps based on
the value of the current element, and either bump it by one, or
if 'strange' is True and the value is over three, decrease it by
one.... | a1ba7c9374cbba9d6a0a8ad091a7fbfcbe71744a | 58,559 |
def check_asymm_device(p):
"""
Check if device is asymmetric (one Al strip) or symmetric (two Al strips).
Returns
-------
p.asymmetric : Boolean
Is used later in naming files and plot titles, and initiates saving the size p.Nxasymmetric of the SC strip and middle retion altogether to the Simplenamespace obj... | 506c7a3509b5bafb92f1159208d11bd7da514434 | 207,316 |
def get_data_shape(data, strict_no_data_load=False):
"""
Helper function used to determine the shape of the given array.
In order to determine the shape of nested tuples, lists, and sets, this function
recursively inspects elements along the dimensions, assuming that the data has a regular,
rectang... | 2f1f37703ebe8783a9badcfa57a946d90c82962b | 549,832 |
import json
def decode_extra_parameters(metadata):
"""Returns a dictionary parsed from the json string stored
in extra_parameters
Parameters
----------
metadata
A SolarForecastArbiter.datamodel class with an extra_parameters
attribute
Returns
-------
dict
The ... | d86603fe86ed5944d22c616200ca77af24e54b1f | 576,977 |
def getArgumentValue(args, key):
"""Returns the value for the argument 'key' in the list of Moses
arguments 'args'.
"""
split = args.split()
for i in range(0, len(split)):
if i > 0 and key == split[i-1].strip():
return split[i].strip()
return None | de0cc29a9a058cbf363f640aaafde4a0936bf263 | 179,272 |
def i_to_n(i, n):
"""
Translate index i, ranging from 0 to n-1
into a number from -(n-1)/2 through (n-1)/2
This is necessary to translate from an index to a physical
Fourier mode number.
"""
cutoff = (n-1)/2
return i-cutoff | a6db34613794a5a6cc30210e735a014f0e6bd6eb | 273,168 |
def _entity_string_for_errors(entity):
"""Derive a string describing `entity` for use in error messages."""
try:
character = entity.character
return 'a Sprite or Drape handling character {}'.format(repr(character))
except AttributeError:
return 'the Backdrop' | dbad020eda009aff0d7d7dc2bf2204f486292454 | 560,985 |
def get_free(page):
"""Get the taxon description."""
tag = page.select_one('#tr-carregaTaxonGrupoDescricaoLivre')
tag = tag.get_text()
return ' '.join(tag.split()) | 0d9d4f93a28e53b70e8d1d8464592c8801f80aa4 | 140,844 |
def format_subject(subject):
# type: (str) -> str
"""
Escape CR and LF characters.
"""
return subject.replace('\n', '\\n').replace('\r', '\\r') | a68864de7b736719c0fcde1ade4253b2071e8a53 | 480,897 |
def _get_last_cell(nb):
"""
Get last cell, ignores cells with empty source (unless the notebook only
has one cell and it's empty)
"""
# iterate in reverse order
for idx in range(-1, -len(nb.cells) - 1, -1):
cell = nb.cells[idx]
# only return it if it has some code
if cel... | e99ab592a480c015f028e622dad587bd1bf5fdcb | 672,609 |
def literal2char(literal):
"""Convert a string literal to the actual character."""
usv = literal.group(1)
codepoint = int(usv, 16)
char = chr(codepoint)
return char | d6c11112b37d91ab94452669a493f1a3704b5684 | 292,687 |
import random
def seed_story(text_dict):
"""Generate random seed for story."""
story_seed = random.choice(list(text_dict.keys()))
return story_seed | 0c0f41186f6eaab84a1d197e9335b4c28fd83785 | 2,444 |
import traceback
def get_task_imports(ext):
"""Return a list of task modules provided by an extension."""
try:
includes = ext.obj.task_imports()
except Exception:
traceback.print_exc()
print('Problem instantiating plugin %s, skipping' % ext.name)
includes = []
return in... | c925b331f41118712d458e3bd2d2fc6a5af15c61 | 197,589 |
def get_template(path):
"""
Gets the HTML template and replaces patterns in a "template-like" manner
:param str path: Path to the initial HTML template/file
:return: The updated HTML content as string
:rtype: str
"""
with open(path, "r", encoding="utf-8") as f:
f_content = f.read()
... | c6bd9af2ce702f2ac9db0daac1a14983406d1dc1 | 103,832 |
import itertools
def flatten(iterable):
"""Flatten the input iterable.
>>> list(flatten([[0, 1], [2, 3]]))
[0, 1, 2, 3]
>>> list(flatten([[0, 1], [2, 3, 4, 5]]))
[0, 1, 2, 3, 4, 5]
"""
return itertools.chain.from_iterable(iterable) | 6860f65582952819ae56178cf97cd2eb2133bbf1 | 25,710 |
import logging
def _write(filepath, content):
"""Writes out a file and returns True on success."""
logging.info('Writing in %s:\n%s', filepath, content)
try:
with open(filepath, mode='wb') as f:
f.write(content)
return True
except IOError as e:
logging.error('Failed to write %s: %s', filepat... | 1784a3378bebdf1fbc0eaf9342c8c61ee659c8ad | 513,755 |
def weight(alpha, beta, x):
"""The weight function of the jacobi polynomials for a given alpha, beta value."""
one_minus_x = 1 - x
return (one_minus_x ** alpha) * (one_minus_x ** beta) | 66d5395e1fc5639c2417519c22d4ab318e2dd3b8 | 582,944 |
def get_tip_cost(meal_cost: float, tip_percentage: int) -> float:
"""Calculate the tip cost from the meal cost and tip percentage."""
PERCENT = 100
return meal_cost * tip_percentage / PERCENT | cdaca6993169e4c156d038d2d5eb1520ce2e9b65 | 408,006 |
def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
... | d53dc20a9eff391560269e818e99d41f8dc2ce94 | 7,689 |
def numba_array2d_nnz(ary, width, height):
"""
Function will return the number of nonzero values of the full matrix.
Inputs:
ary : input matrix
width : number of columns of the matrix
height : number of rows of the matrix
Outputs:
nnz : number of nonzero values... | ee7cd2ed1718ff144c3a1c03688f1fb732f9a42f | 503,455 |
import operator
def is_ordered(lst, key=None, strict=False):
"""True if input list is (strictly) ordered."""
if key is None:
key = lambda item: item
cmp = operator.lt if strict else operator.le
return all(cmp(key(x0), key(x1)) for x0, x1 in zip(lst, lst[1:])) | 6c7e405134149b248f0b0bd4970e4d49bdb036e4 | 129,843 |
def _strip_match(matchobj):
"""Strip whitespace from a RE-match-object
Parameters
----------
matchobj : re.Match
Match-object of regular-expression.
Returns
-------
str
Stripped string
"""
return matchobj.group(0).strip() | 77565857853069194696ab9e50f51d1f48090376 | 615,886 |
def is_c19_narrative (narratives):
""" Check a dict of different-language text for the string "COVID-19" (case-insensitive) """
for lang, text in narratives.items():
if "COVID-19" in text.upper():
return True
return False | db4dedcf0b41f6547c704b7bc6f478a3b6af7672 | 126,105 |
from typing import Iterable
def is_iterable(var):
"""Test if a variable is an iterable.
Parameters
----------
var : object
The variable to be tested for iterably-ness
Returns
-------
is_iter : bool
Returns ``True`` if ``var`` is an ``Iterable``, ``False`` otherwise
"... | 97dc90ee078835bd8924c64a1197701d14217e0c | 149,428 |
def read_log(fname):
"""Read a log file.
Args:
fname (str): Name of log file
Returns:
str. Command log
"""
log_file = open(fname, 'r')
log = log_file.read()
return log | aa3f2a34251a968b05b90cb7bb21cb4267dfb52a | 608,985 |
def _startswithax(item):
"""
Helper function to filter tag lists for starting with xmlns:ax
"""
return item.startswith('xmlns:ax') | 12be6223b8ea816f5fff8b4faa4c01dff5a7a1c0 | 538,333 |
def squeeze_axes(shape, axes, skip='XY'):
"""Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX')
"""
if len(shape) != len(axes):
raise ValueError("... | ca359ee31ecf3000d9afc7afd1ebbf779ce528a3 | 673,124 |
def intersection(lst1, lst2):
"""
Intersection of two sets
:param lst1: first input list
:param lst2: second input list
:return: intersection in list format
"""
return list(set(lst1) & set(lst2)) | 139b03c17754fa891b497209296406bcdff086e9 | 565,638 |
def is_randomized(key):
"""
Helper to determine if the key in the state_dict() is a set of parameters that is randomly initialized.
Some weights are not randomly initalized and won't be afffected by seed, particularly layer norm
weights and biases, and bias terms in general.
"""
# regexes for co... | 06b9fe782e4d0f22dac8d062f033d25932a288f6 | 150,980 |
def burn_area_ratio(p_c, a, n, rho_solid, c_star):
"""Get the burn area ratio, given chamber pressure and propellant properties.
Reference: Equation 12-6 in Rocket Propulsion Elements, 8th edition.
Arguments:
p_c (scalar): Chamber pressure [units: pascal].
a (scalar): Propellant burn rate ... | 3dfc4bb8cd8cb94351ecb74066960d51854d2524 | 330,886 |
def left_clust(nd):
"""
Returns the id of the left cluster belonging to a node
Args:
nd (node): NOde from nodelist in scipy.cluster.hierarchy.to_tree
Returns:
id or '' if the node is just a datapoint and not a cluster
"""
try:
return nd.get_left().get_id()
except... | 23f4e6a244f79e43d758c014d2fcf913bda5e914 | 529,191 |
def yes_or_no(question):
"""Convert user input from yes/no variations to True/False"""
while True:
reply = input(question + " [y/N] ").lower().strip()
if not reply or reply[0] == "n":
return False
if reply[0] == "y":
return True | 1143752127a4d40c507aa593d99c3c8346d5c789 | 352,074 |
def cov_files_by_platform(reads, assembly, platform):
"""
Return a list of coverage files for a given sequencing platform.
"""
accessions = []
if reads is not None:
accessions += [accession for accession in reads if reads[accession]['platform'] == platform]
return list(map(lambda sra: "%... | ae2e5b71e03141e9fb38247a463380ceba80cf3d | 660,275 |
def name_sources(meta, mode):
"""
From the meta data and the mode, create a filename fragment
that names the sources used.
"""
land_source = ''
ocean_source = ''
if mode in ('land', 'mixed'):
land_source = '.GHCN'
if mode in ('ocean', 'mixed'):
ocean_source = '.' + meta... | eac20e44493af751e7fbc54f8a42275a9f601cc9 | 86,006 |
def calculate_normalized_ged(data):
"""
Calculating the normalized GED for a pair of graphs.
:param data: Data table.
:return norm_ged: Normalized GED score.
"""
norm_ged = data["ged"]/(0.5*(len(data["labels_1"])+len(data["labels_2"])))
return norm_ged | b599d7c5ba0c5b75759a304abcad6d18604b8027 | 569,820 |
def get_stats(data):
"""
Returns some statistics about the given data, i.e. the number of unique entities, relations and
their sum.
Args:
data (list): List of relation triples as tuples.
Returns:
tuple: #entities, #relations, #entities + #relations.
"""
entities = set()
relations = set()
for triple in d... | 6496db5be15b330de84345d862a66a16c0ebc969 | 36,236 |
from typing import Any
import inspect
import warnings
def _safe_getdoc(obj: Any) -> str:
"""Like `inspect.getdoc()`, but never raises. Always returns a stripped string."""
try:
doc = inspect.getdoc(obj) or ""
except Exception as e:
warnings.warn(
f"inspect.getdoc({obj!r}) raise... | 41650701f70d5a5db63441b0db5e22dd0f860db9 | 466,755 |
import pickle
import base64
def deserialise_pickle(args):
"""Deserialise *args* using base64 and pickle, returning the Python object.
"""
return pickle.loads(base64.b64decode(args)) | 6c40588081d47c054de9f6aa03cf992ab90a9a10 | 354,957 |
def splitRpmFilename(filename):
"""
Split an rpm filename into components:
package name, version, release, epoch, architecture
"""
if filename[-4:] == '.rpm':
filename = filename[:-4]
idx = filename.rfind('.')
arch = filename[idx+1:]
filename = filename[:idx]
idx = filenam... | 8bed2a53f8df4e7bbdc3f45bce9c165f1ee0284d | 263,056 |
def max_index(alignment_matrix):
"""
Helper function that computes the index of the maximum in the
alignment matrix.
"""
max_i = 0
max_j = 0
for idx_i in range(len(alignment_matrix)):
for idx_j in range(len(alignment_matrix[0])):
if alignment_matrix[idx_i][idx_j] > alignm... | eae87a9a72ac36ae234b6781d30eb04f4d3f921e | 168,243 |
def mean2(num_list):
"""
description -- computes the mean of a list.
Parameters
----------
num_list: list
A list of numbers whose mean is to be computed
Returns
-------
list_mean: float
Mean of the list of numbers
"""
s = 0
for i in range(len(num_list)):
s = s + num_list[i]
list_mean = s/len(n... | 2722bc9411f5580fec186757803e884ebfccffe5 | 474,198 |
def comp_lengths_winding(self):
"""Compute the lengths of the Lamination's Winding.
- Lwtot : total length of lamination winding incl. end-windings and
radial ventilation ducts [m].
- Lwact : active length of lamination winding excl. end-windings and
radial ventilation ducts [m].
- Lewt : total ... | d2a2c48f71a55fc48f497c2de3b83cc47ee94194 | 84,824 |
import random
def gen_port(num=1):
"""
Generate a port number or a list
"""
ports_list = [random.randrange(10000, 60000) for x in range(num)]
if num == 1:
# s.bind((Network.get_ip(4), 0)) is enough
return ports_list[0]
else:
return ports_list | aba2ad59d7d4154bbdb7c4379815fa723ac28052 | 608,630 |
import re
def get_age_sex(participant, fields=["31", "21022"]) -> list:
"""Create a list of age and sex field names
Parameters
----------
participant : UKB Spark df
participant df
fields : list, optional
list of age and sex fields. Defaults are necessary for PHESANT, by default ["... | 030a80cfc164ef0339a03e3577aadce49ccfd01e | 427,498 |
def _handle_cropped(y_p):
"""
A straightforward helper that simply averages multiple crops if they are present.
Parameters
----------
y_p: np.ndarray
The predicted values with shape batch x targets (x <optional crops>)
Returns
-------
y_p_mean: np.ndarray
If ther... | 08154669c6b3f284c2bdf1ffab654bb2f196b1df | 234,884 |
def _get_like_function_shapes_chunks(a, chunks, shape):
"""
Helper function for finding shapes and chunks for *_like()
array creation functions.
"""
if shape is None:
shape = a.shape
if chunks is None:
chunks = a.chunks
elif chunks is None:
chunks = "auto"
... | c56187a7fc92b1a69f75d7defe9a57bb6376515c | 649,235 |
from datetime import datetime
def __get_current_datetime() -> str:
"""Returns the current datetime in a format compatible with messaging.
Returns:
{str} -- The current datetime.
"""
return datetime.now().isoformat(timespec="seconds") | 0b477898c23ea34cb5dedba13dd6a5d2a3bfa15e | 547,768 |
import ipaddress
def ip_subtract(ip, val):
"""Subtract an integer to an IP address.
Args:
ip (str): An IP address in string format that is able to be converted by `ipaddress` library.
val (int): An integer of which the IP address should be subtracted by.
Returns:
str: IP address ... | 0372ba4f14f6a3722ea7843a8c36c5470890004d | 645,439 |
def sort_toc(toc):
""" Sort the Table of Contents elements. """
def normalize(element):
""" Return a sorting order for a TOC element, primarily based
on the index, and the type of content. """
# The general order of a regulation is: regulation text sections,
# appendices, and t... | 8e9c4f6f922ac8a815898ef822f2b453ffa15fd6 | 193,192 |
def revert_step(time_step_duration, equations, distance, distance_old):
"""Revert the time step.
"""
time_step_duration = time_step_duration * 0.1
for eqn in equations:
eqn.var[:] = eqn.var.old
distance[:] = distance_old
return time_step_duration | 88fd2027d1bd3659af871b1db71f58ab68a4b8d6 | 146,439 |
import re
def error_fullstop(value):
"""Checks whether there is a fullstop after a digit"""
return bool(re.match(r'.*\d+\.', value)) | 4a67cc1a577c7206decd86e7a01fc48e6fbeb8ef | 528,254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.