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)',
'Referred by friend/relative',
'Referred by health care provider (MD, RN, Social Work)',
]
not_referral = [
'No referral, advocate outreach brought client to HL',
'No referral today, returning client',
'Unknown',
'No referral, marketing materials/signage brought client to HL',
'Negative screen',
]
if client_referral_origin in referral:
return 1
else:
return 0
|
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
hits1.add( (type(hit), hit.index()) )
ncommon = 0
for hit in trk2.hits():
if not hit.isValidHit(): continue
if (type(hit), hit.index()) in hits1:
ncommon += 1
return ncommon
|
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:
int(tx_hash, 16)
return True
except:
return False
|
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 pairs
|
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 decorator if caching for
that object is enabled. To properly use this with the decorator, pass this
function the configuration group and assign the result to a variable.
Pass the new variable to the caching decorator as the named argument
``should_cache_fn``.
:param conf: config object, must have had :func:`configure` called on it.
:type conf: oslo_config.cfg.ConfigOpts
:param group: name of the configuration group to examine
:type group: string
:returns: function reference
"""
def should_cache(value):
if not conf.cache.enabled:
return False
conf_group = getattr(conf, group)
return getattr(conf_group, 'caching', True)
return should_cache
|
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
return word
|
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_shape
# we consider it as a static dimension. Or it is treated as
# dynamic dimension which will be set to -1
dyn = [i if i == j else -1 for i, j in zip(min_inp, max_inp)]
dynamic_shape.append(dyn)
return dynamic_shape
|
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_state_dict'])
epoch = checkpoint['epoch']
train_loss = checkpoint['train_loss']
val_loss = checkpoint['val_loss']
cider = checkpoint['cider']
return epoch, model, optimizer, lr_scheduler, train_loss, val_loss, cider
|
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
List of loaded band numbers.
band_num : INT
Numerical value corresponding to a Landsat-8 band.
Returns
-------
STRING
Returns a string containing the corresponding file path to the input
band_num value.
"""
i = band_numbers.index(str(band_num))
return fnames[i]
|
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_configuration_string = ''
for orbital, name in zip(orbital_configuration, orbital_names):
if orbital > 0:
orbital_configuration_string += f'{name}{orbital}'
return orbital_configuration_string
|
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
:return: evaluates and returns the nth_term of the polynomial in O(k^2), given at least k+1 unique values were provided
"""
if len(x_values) != len(y_values):
raise ValueError('The X and Y values should be of the same length')
res = 0
for i in range(len(x_values)):
x, y = 1, 1
for j in range(len(x_values)):
if i != j:
x *= (nth_term - x_values[j])
y *= (x_values[i] - x_values[j])
res += (x * y_values[i] // y)
return res
|
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): The minimum depth to be considered as a depression.
interval (float): The slicing interval.
resolution (float): The spatial resolution of the DEM.
Returns:
dict: A dictionary containing image parameters.
"""
image_paras = {}
image_paras["no_data"] = no_data
image_paras["min_size"] = min_size
image_paras["min_depth"] = min_depth
image_paras["interval"] = interval
image_paras["resolution"] = resolution
return image_paras
|
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 arguments that should not be assigned to layout
arguments.
Returns:
A tuple of (layout_args, non_layout_args) dictionaries.
"""
layout_args = {'center'}
layout_args.difference_update(skip)
in_args = {k: v for k, v in kwargs.items() if k in layout_args}
out_args = {k: v for k, v in kwargs.items() if k not in layout_args}
return in_args, out_args
|
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 any shape.
xmin, xmax : float
Minimum and maximum values, which will be rescaled to the
boundaries of the unit interval: [xmin, xmax] -> [0, 1].
scale_factor : float, optional
Scale the unit interval by some arbitrary factor, so that
the output tensor values lie in the interval [0, scale_factor].
Returns
-------
y : Tensor
Rescaled version of x.
"""
return scale_factor * (x - xmin) / (xmax - xmin)
|
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(value) != 0:
return float(value) * -1
else:
return 0
|
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 """
if level == 'default':
level = ''
else:
level = 'badge-%(level)s' % locals()
badge = """
<span class="badge %(level)s" id=" ">
%(text)s
</span>""" % locals()
return 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, score)
"""
assert predictions is not None
result = []
slide_id, ROI, mitosis_num, mitosis_location_scores = predictions
for r, c, score in mitosis_location_scores:
result.append((slide_id, ROI, mitosis_num, r, c, score))
return result
|
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
.set_categories(cats, ordered=True))
return df
|
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["value"] for x in isbns][0]
return None
|
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 arguments and returns a default
value to use if not set.
Returns:
A type-checked property.
"""
def get_fn(option):
# pylint: disable=protected-access
if name not in option._options:
option._options[name] = default_factory()
return option._options.get(name)
def set_fn(option, value):
if not isinstance(value, ty):
raise TypeError("Property \"%s\" must be of type %s, got: %r (type: %r)" %
(name, ty, value, type(value)))
option._options[name] = value # pylint: disable=protected-access
return property(get_fn, set_fn, None, docstring)
|
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
return None
|
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.effNum()):
if ds1.effActivation(i) != ds2.effActivation(i):
return True
return False
|
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(string.replace("\xa0", " ").split())
|
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_value': hparams.get(param_name, default_value),
'mode': 'constant'
}
params = hparams.get(param_name + '_params', default_params)
return params
|
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.
"""
return datetime.fromtimestamp(float(epoch)/1000)
|
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, 3, 4, 5, 6, 7, 8, 9]
|
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 = []
while i < len(raw_list):
if raw_list[i] == "" or raw_list[i][0] != '\"':
values.append(raw_list[i])
i = i + 1
else:
if raw_list[i][-1] == '\"':
values.append(raw_list[i][1:-1])
i = i + 1
else:
j = i + 1
entry = raw_list[i][1:]
while j < len(raw_list) and raw_list[j][-1] != '\"':
entry = entry + raw_list[j]
j = j + 1
if j == len(raw_list):
i = j
else:
entry = entry + raw_list[j][:-1]
values.append(entry)
i = j + 1
return values
|
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 the salvage item
4) Return a dictionary of the raw material values in the salvage item and the value of the salvage item
"""
salvageValue_dct = {}
sum_val = 0
if TPCut == True:
TPValue = 0.85
else:
TPValue = 1
for key in droprate_dict:
salvageValue_dct[key] = round(TPValue*droprate_dict[key]*multiplier_dict[key],4)
sum_val = sum_val + salvageValue_dct[key]
return salvageValue_dct,sum_val
|
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 service
:return: The service name, The service version
"""
if ':' in service_name:
return service_name.split(':')
return service_name, 'latest'
|
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 ``(outval, i) -> orig_i``, which allows mapping results back.
So if your `partfunc` returns 'foo' and 'bar', `allseqs` will have ``{'foo': [...], 'bar': [...]}``.
You access `indices` using ``(partout, seq_i)``, where `partout` is 'foo' or 'bar' in this case, and
`seq_i` is the index number from the ``allseqs[partout]`` sequence.
This function is very useful for categorizing a list's entries based on some
function. If your function was binary, you would normally do it using 2 list
comprehensions::
a = [el for el in seq if partfunc(el)]
b = [el for el in seq if not partfunc(el)]
But that quickly gets inefficient and bloated if you have more complicated
partition functions, which is where this function becomes useful.
"""
allseqs = {}
indices = {}
for i, el in enumerate(origseq):
partout = partfunc(el)
seq = allseqs.setdefault(partout, [])
indices[(partout, len(seq))] = i
seq.append(el)
return allseqs, indices
|
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. If the new position is outside the current list of elements,
we can exit
Returns the number of steps it takes to exit
"""
jumps = 0
idx = 0
while 0 <= idx < len(data):
new_idx = idx + data[idx]
if strange and data[idx] >= 3:
data[idx] -= 1
else:
data[idx] += 1
jumps += 1
idx = new_idx
return jumps
|
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 object p containing the parameters of the system.
"""
if len(p.right) == 0:
p.asymmetric = True # to be used when printing last blocks of the Hamiltonian
p.Nxasymmetric = len(p.left) + len(p.middle)
else:
p.asymmetric = False
return p.asymmetric
|
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,
rectangular shape. In the case of out-of-core iterators, this means that the first item
along each dimension would potentially be loaded into memory. Set strict_no_data_load=True
to enforce that this does not happen, at the cost that we may not be able to determine
the shape of the array.
:param data: Array for which we should determine the shape.
:type data: List, numpy.ndarray, DataChunkIterator, any object that support __len__ or .shape.
:param strict_no_data_load: If True and data is an out-of-core iterator, None may be returned. If False (default),
the first element of data may be loaded into memory.
:return: Tuple of ints indicating the size of known dimensions. Dimensions for which the size is unknown
will be set to None.
"""
def __get_shape_helper(local_data):
shape = list()
if hasattr(local_data, '__len__'):
shape.append(len(local_data))
if len(local_data):
el = next(iter(local_data))
if not isinstance(el, (str, bytes)):
shape.extend(__get_shape_helper(el))
return tuple(shape)
# NOTE: data.maxshape will fail on empty h5py.Dataset without shape or maxshape. this will be fixed in h5py 3.0
if hasattr(data, 'maxshape'):
return data.maxshape
if hasattr(data, 'shape'):
return data.shape
if isinstance(data, dict):
return None
if hasattr(data, '__len__') and not isinstance(data, (str, bytes)):
if not strict_no_data_load or isinstance(data, (list, tuple, set)):
return __get_shape_helper(data)
return None
|
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 extra parameters as a python dictionary
Raises
------
ValueError
If parameters cannot be decoded or are None. Or if missing the
required keys: network, network_api_id, network_api_abbreviation
and observation_interval_length.
"""
try:
params = json.loads(metadata.extra_parameters)
except (json.decoder.JSONDecodeError, TypeError):
raise ValueError(f'Could not read extra parameters of {metadata.name}')
required_keys = ['network', 'network_api_id', 'network_api_abbreviation',
'observation_interval_length']
if not all([key in params for key in required_keys]):
raise ValueError(f'{metadata.name} is missing required extra '
'parameters.')
return params
|
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 cell['source'].strip():
return cell
# otherwise return the first cell
return nb.cells[0]
|
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 includes
|
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()
# Getting the store list and placing it in the template
for element, pattern in zip(["a", "b"], ["{{pattern1}}", "{{pattern2}}"]):
f_content = f_content.replace(pattern, element)
return f_content
|
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', filepath, e)
return False
|
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]]
"""
transposed = []
rows = len(table)
cols = max(len(row) for row in table)
for x in range(cols):
transposed.append([])
for y in range(rows):
if x < len(table[y]):
transposed[x].append(table[y][x])
else:
transposed[x].append(None)
return transposed
|
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
"""
nnz = 0
for line in range(height):
for col in range(width):
if ary[line,col] != 0:
nnz = nnz + 1
return nnz
|
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
"""
return isinstance(var, Iterable)
|
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("dimensions of axes and shape do not match")
shape, axes = zip(*(i for i in zip(shape, axes)
if i[0] > 1 or i[1] in skip))
return tuple(shape), ''.join(axes)
|
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 components that are not randomized
print(key)
if key.endswith("bias") or "ln" in key:
return False
else:
return True
|
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 coefficient [units: meter second**-1 pascal**-n].
n (scalar): Propellant burn rate exponent [units: none].
rho_solid (scalar): Solid propellant density [units: kilogram meter**-3].
c_star (scalar): Propellant combustion characteristic velocity [units: meter second**-1].
Returns:
scalar: Ratio of burning area to throat area, :math:`K = A_b/A_t` [units: dimensionless].
"""
return p_c**(1 - n) / (rho_solid * a * c_star)
|
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:
return ''
|
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: "%s.%s.bam.cov" % (assembly, sra), accessions))
|
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.ocean_source.upper()
return ocean_source + land_source
|
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 data:
entities.add(triple[0])
entities.add(triple[2])
relations.add(triple[1])
return len(entities), len(relations), len(entities) + len(relations)
|
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}) raised an exception: {e}",
RuntimeWarning,
)
return ""
else:
return doc.strip()
|
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 = filename.rfind('-')
rel = filename[idx+1:]
filename = filename[:idx]
idx = filename.rfind('-')
ver = filename[idx+1:]
filename = filename[:idx]
idx = filename.find(':')
if idx == -1:
epoch = ''
name = filename
else:
epoch = filename[:idx]
name = filename[idx+1:]
return name, ver, rel, epoch, arch
|
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] > alignment_matrix[max_i][max_j]:
max_i = idx_i
max_j = idx_j
return max_i, max_j
|
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(num_list)
return list_mean
|
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 end-winding length [m].
- Lew : end-winding length on one side for a half-turn
- Lwvent : length of lamination winding in the radial ventilation ducts [m]
Parameters
----------
self: LamSlotWind
a LamSlotWind object
Returns
-------
L_dict: dict
Dictionnary of the length (Lwtot, Lwact, Lew, Lwvent)
"""
# length of the stack including ventilation ducts
L1vd = self.comp_length()
# end-winding length on one side for a half-turn
Lew = self.winding.comp_length_endwinding()
# total end-winding length
Ntspc = self.winding.comp_Ntsp(self.slot.Zs)
qb = self.comp_number_phase_eq()
Lewt = qb * Ntspc * self.winding.Npcp * 4 * Lew
# average length of a lamination winding half-turn (one "go" conductor
# without "return" conductor)
Lwht = L1vd + 2 * Lew
# total length of lamination winding incl. end windings [m]
Lwtot = qb * Ntspc * self.winding.Npcp * 2 * Lwht
# Active length of lamination winding excl. end windings and radial
# ventilation duct [m]
Lwact = qb * Ntspc * self.winding.Npcp * 2 * self.L1
# length of lamination winding in the radial ventilation duct [m]
if self.Nrvd is None or self.Wrvd is None:
Lwvent = 0
else:
Lwvent = qb * Ntspc * self.winding.Npcp * 2 * self.Nrvd * self.Wrvd
return {"Lwtot": Lwtot, "Lwact": Lwact, "Lewt": Lewt, "Lwvent": Lwvent, "Lew": Lew}
|
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 ["31", "21022"]
Returns
-------
list
age sex fields
"""
age_sex = "|".join(fields)
age_sex_fields = list(
participant.find_fields(lambda f: bool(re.match(f"^p({age_sex})$", f.name)))
)
return [f.name for f in age_sex_fields]
|
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 there is an additional crop dimensions, mean across this dimension
"""
if len(y_p.shape) == 2:
return y_p
elif len(y_p.shape) == 3:
return y_p.mean(-1)
else:
raise ValueError("Predictions should be 1 or 2 dimensions in shape (excluding batches)")
|
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"
return shape, chunks
|
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 formatted string with the newly subtracted IP address.
Example:
>>> from netutils.ip import ip_subtract
>>> ip_subtract("10.100.100.100", 200)
'10.100.99.156'
>>>
"""
return str(ipaddress.ip_address(ip) - val)
|
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 then the interpretations.
normalized = []
if element.get('is_section'):
normalized.append(0)
elif element.get('is_appendix'):
normalized.append(1)
elif element.get('is_supplement'):
normalized.append(2)
for part in element['index']:
if part.isdigit():
normalized.append(int(part))
else:
normalized.append(part)
return normalized
return sorted(toc, key=lambda el: tuple(normalize(el)))
|
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.