content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
from collections import namedtuple
def extract_image_id_from_longitudinal_segmentation(freesurfer_id):
"""Extract image ID from longitudinal segmentation folder.
This function will extract participant, session and longitudinal ID from `freesurfer_id`.
Example:
>>> from clinica.utils.freesurfer import extract_image_id_from_longitudinal_segmentation
>>> extract_image_id_from_longitudinal_segmentation('sub-CLNC01_ses-M00')
image_id(participant_id='sub-CLNC01', session_id='ses-M00', long_id='')
>>> extract_image_id_from_longitudinal_segmentation('sub-CLNC01_long-M0018')
image_id(participant_id='sub-CLNC01', session_id='', long_id='long-M0018')
>>> extract_image_id_from_longitudinal_segmentation('sub-CLNC01_ses-M00.long.sub-CLNC01_long-M00M18')
image_id(participant_id='sub-CLNC01', session_id='ses-M00', long_id='long-M00M18')
"""
image_id = namedtuple("image_id", ["participant_id", "session_id", "long_id"])
# Case 'sub-CLNC01_ses-M00.long.sub-CLNC01_long-M00M18'
if ".long." in freesurfer_id:
participant_id = freesurfer_id.split(".long.")[0].split("_")[0]
session_id = freesurfer_id.split(".long.")[0].split("_")[1]
long_id = freesurfer_id.split(".long.")[1].split("_")[1]
# Case 'sub-CLNC01_long-M00M18'
elif "long-" in freesurfer_id:
participant_id = freesurfer_id.split("_")[0]
session_id = ""
long_id = freesurfer_id.split("_")[1]
# Case 'sub-CLNC01_ses-M00'
else:
participant_id = freesurfer_id.split("_")[0]
session_id = freesurfer_id.split("_")[1]
long_id = ""
return image_id(participant_id, session_id, long_id) | 9b5a2c0149c64dedb07b9005c80ad3e16604250e | 198,618 |
import random
def d5() -> int:
"""Roll a D5"""
return random.randint(1, 5) | 9029c0b9962aeffb412e1b131e0731f0bb69d042 | 413,302 |
def invertMask(mask):
"""
Inverts a numpy binary mask.
"""
return mask == False | f6a668a9b2f0928e2a71dc7e4de4d1e04cf307de | 23,978 |
def options(arg):
"""Extract options from given arg string"""
opts = []
for par in arg.split():
if len(par) > 0 and par[0] == '-':
opts.append(par)
return opts | abe33aaeb7642b0ccac5ecdb2b88441acc92405c | 612,892 |
from functools import reduce
def multiply_list_elements(in_list):
"""
Multiply list elements together, e.g. [1,2,3,4,5,6] -> 1*2*3*4*5*6=720.
"""
return reduce(lambda x, y: x*y, in_list) | 076e3f83c872fccb904495abf9f89ad088fdd0cf | 332,083 |
def esc_format(text):
"""Return text with formatting escaped
Markdown requires a backslash before literal underscores or asterisk, to
avoid formatting to bold or italics.
"""
for symbol in ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']:
text = str(text).replace(symbol, '\\' + symbol)
return text | 12770a69da56cd6e9de92a6a301857d42ee1381b | 685,345 |
def crop_op(x, cropping, data_format="NCHW"):
"""Center crop image.
Args:
x: input image
cropping: the substracted amount
data_format: choose either `NCHW` or `NHWC`
"""
crop_t = cropping[0] // 2
crop_b = cropping[0] - crop_t
crop_l = cropping[1] // 2
crop_r = cropping[1] - crop_l
if data_format == "NCHW":
x = x[:, :, crop_t:-crop_b, crop_l:-crop_r]
else:
x = x[:, crop_t:-crop_b, crop_l:-crop_r, :]
return x | 8071f0863b24def71b4643cee4385beb39d4a0d7 | 506,141 |
def n_considered_cells(cc, look_at):
"""
Calculates the number of considered cells
"""
count = 0
for p in cc:
if not look_at[p]:
continue
if p==0 or cc[p]==0:
continue
count += 1
return count | b969422cd3f1fff0bfa2c5aaa27fd386238e9027 | 216,423 |
def decimal_to_base(n, base):
"""Convert decimal number to any base (2-16)"""
chars = "0123456789ABCDEF"
stack = []
is_negative = False
if n < 0:
n = abs(n)
is_negative = True
while n > 0:
remainder = n % base
stack.append(remainder)
n = n // base
result = ""
while stack:
result = result + chars[stack.pop()]
if is_negative:
return "-"+result
else:
return result | 5d94af3d37eaa3d18e3e6f56e0c278668ce118e1 | 689,980 |
import socket
def validate_ipv6(ip):
"""
Validate an ipv6 address
:param ip: The string with the ip
:return: True ip if it's valid for ipv6, False otherwise
"""
ip = str(ip)
try:
socket.inet_pton(socket.AF_INET6, ip)
except socket.error:
return False
return True | 020570f461e17e2003b9385fb7219434fba283fa | 620,652 |
def is_grouped_by_project(parameters):
"""Determine if grouped or filtered by project."""
group_by = list(parameters.parameters.get("group_by", {}).keys())
return [key for key in group_by if "project" in key] | 2c77ff48b66cbb38d1ce8ab1c170c623497340ba | 508,549 |
import math
def distance_between_points(p1, p2):
"""Computes the distance between two Point objects.
p1: Point
p2: Point
returns: float
"""
dx = p1.x - p2.x
dy = p1.y - p2.y
dist = math.sqrt(dx**2 + dy**2)
return dist | c9d9706a98580bccbfa4f8b6819d195e11a94601 | 472,320 |
import unicodedata
def maketrans_remove(accents=("COMBINING ACUTE ACCENT", "COMBINING GRAVE ACCENT")):
""" Makes a translation for removing accents from a string. """
return str.maketrans("", "", "".join([unicodedata.lookup(a) for a in accents])) | 516114526f6d7d36b2b454cd07e40302bd7a83f7 | 49,424 |
def uptime_seconds(uptime_list):
"""
Convert a list of the following form:
[years, weeks, days, hours, minutes]
To an uptime in seconds
"""
years = uptime_list[0]
weeks = uptime_list[1]
days = uptime_list[2]
hours = uptime_list[3]
minutes = uptime_list[4]
# No leap day calculation
days = years*365 + weeks*7 + days
minutes = days*24*60 + hours*60 + minutes
seconds = minutes*60
return seconds | abf29658193ab373c8e7e8c722fe308d3642c176 | 40,835 |
from datetime import datetime
def now_str() :
"""
easily returns current time in human readable format
use the real `datetime` package if you need sophisticated control over formatting.
"""
return datetime.now().strftime("%d %H:%M") | da4c3c389851c61025534676700d5941eeb27017 | 323,419 |
def param_group(pattern, **kwargs):
"""A helper function used for human-friendly declaration of param groups."""
return (pattern, kwargs) | da44d58e982f812e940c00ff0a21792cfeffd731 | 316,626 |
def number_of_pluses_before_an_equal(reaction):
"""
Args:
reaction (str) - reaction with correctly formatted spacing
Returns (int):
number_of - the number of pluses before the arrow `=>`
Example:
>>>number_of_pluses_before_an_equal("C6H12O6 + 6O2=> 6CO2 + 6H2O")
1
"""
number_of = 0
# so we don't have to worry about (i - 1) < 0
reac = reaction.strip()
for i in range(1, len(reaction)):
if reaction[i] == "=":
return number_of
if i > 0:
# and reaction[i+1] == " " is omitted because of formatting reasons
if reaction[i] == "+" and reaction[i-1] == " ":
number_of += 1
return number_of | f532ee41dee797d7c2ae1639fae9f1cb61c3f037 | 25,260 |
def diff_complex(x_re, x_im, y_re, y_im):
"""Difference of complex vectors"""
return x_re - y_re, x_im - y_im | 0c7dd4308294ec93eb25580fcb1a7c616640e00a | 454,629 |
def lower_list(li):
""" Convert all element of a list to lowercase"""
if li:
return [x.lower() for x in li]
else:
return None | 0fbe2b8390c468d27a0733613121dc544059ae2e | 102,554 |
def transitions_in_episode_batch(episode_batch):
"""Number of transitions in a given episode batch.
"""
shape = episode_batch['u'].shape
return shape[0] * shape[1] | 7734eb329046603c1e0336cb22435e579a087e02 | 455,543 |
def _expand_ranges(ranges_text, delimiter=',', indicator='-'):
""" Expands a range text to a list of integers.
For example:
.. code-block:: python
range_text = '1,2-4,7'
print(_expand_ranges(range_text)) # [1, 2, 3, 4, 7]
:param str ranges_text: The text of ranges to expand
:returns: A list of integers
:rtype: list[int]
"""
results = set()
for group in filter(None, ranges_text.split(delimiter)):
group = group.strip()
if indicator not in group:
if not group.isdigit():
raise ValueError((
"group '{group}' could not be interpreted as a valid digit"
).format(**locals()))
results.add(int(group))
else:
(start, finish,) = list(filter(None, group.split(indicator)))
if not start.isdigit() or not finish.isdigit():
raise ValueError((
"group '{group}' could not be interpreted as a valid range"
).format(**locals()))
for entry in range(int(start), (int(finish) + 1), 1):
results.add(entry)
return sorted(list(results)) | ab63ef63e9ac545a4566259fe9a2a78c7c2d57fb | 334,824 |
def get_releases(events):
"""
Get all target releases from a list of events.
:return: List of (major, minor) release tuples, sorted in ascending order
"""
return sorted({event.to_release for event in events}) | adbf665c3b7a0068810a44c3c916bfcad6a3ef14 | 47,973 |
def extract_wikiproject_templates(templates):
"""
Iterates over a list of templates and returns WikiProject related templates
from them
"""
wikiprojects = []
for tpl in templates:
if tpl['title'].startswith("Template:WikiProject"):
wikiprojects.append(tpl['title'])
return wikiprojects | c077b3b246a9895dce33ac450f2e182f298a9284 | 414,975 |
import fnmatch
def _fnmatch_lower(name: str | None, pattern: str) -> bool:
"""Match a lowercase version of the name."""
if name is None:
return False
return fnmatch.fnmatch(name.lower(), pattern) | e04d207de691dd3ee5d35dccf88a8c0ed8e5fc3c | 656,000 |
def jaccard_index_calc(TP, TOP, P):
"""
Calculate Jaccard index for each class.
:param TP: true positive
:type TP : int
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:return: Jaccard index as float
"""
try:
return TP / (TOP + P - TP)
except Exception:
return "None" | 13f5a53ca114db2b3af928db0ab9fac885ad2923 | 52,565 |
def format_timedelta(td):
"""Format td in seconds to HHH:MM:SS."""
td = int(td)
hours, remainder = divmod(td, 3600)
minutes, seconds = divmod(remainder, 60)
return '{:03}:{:02}:{:02}'.format(hours, minutes, seconds) | b8febccac40fe17a061e0cdba255b9a8b420cabb | 587,780 |
import torch
def optimizer_creator(model, config):
"""Constructor of one or more Torch optimizers.
Args:
models: The return values from ``model_creator``. This can be one
or more torch nn modules.
config (dict): Configuration dictionary passed into ``TorchTrainer``.
Returns:
One or more Torch optimizer objects.
"""
return torch.optim.SGD(model.parameters(), lr=config.get("lr", 1e-4)) | ea006e131ecd356793a596efe6e32c28bce6be40 | 513,831 |
import re
def unescape(value):
""" Removes escapes from a string
"""
return re.sub(r'\\(.)', r'\1', value) | 8bcba66fde82d0af226e36405cad44fe78474bc3 | 124,570 |
def compute_52_week_range(df, column_source_low, column_source_high, column_target_low, column_target_high):
"""
Compute 52 Week Range (Low~High).
:param df: dataframe (sorted in ascending time order)
:param column_source_low: name of source column in dataframe with low values to compute
:param column_source_high: name of source column in dataframe with high values to compute
:param column_target_low: name of target column in dataframe for low range results to add to dataframe
:param column_target_high: name of target column in dataframe for high range results to add to dataframe
:return: modified dataframe
"""
# compute rolling 52 week range and add result back to dataframe
df[column_target_low] = df[column_source_low].asfreq("D").rolling(window=52*7, min_periods=1).min();
df[column_target_high] = df[column_source_high].asfreq("D").rolling(window=52*7, min_periods=1).max();
return df | 0d65c7ea9656585632045519a2c72f08261ecf46 | 343,457 |
def fst(t):
"""Return first element of a tuple"""
return t[0] | 7d5ad11dd9ba6a220395c5e049a3ec614ee4cbc1 | 167,283 |
def is_strf_param(nm):
"""Check if a parameter name string is one of STRF parameters."""
return any(n in nm for n in ("rates_", "scales_", "phis_", "thetas_")) | 995ab39c2ac86d2213a6180fb2bac427e041b110 | 621,087 |
import re
def normalize_subject(subject):
"""
Strips any leading Re or Fwd from the subject, and returns it. This is
sometimes useful for grouping messages.
"""
return re.sub(r'(?i)(re:|fw:|fwd:)\s+', '', subject) | 2e03d5f332734982b65d441f5bc7e0d9f3fcb7e8 | 505,903 |
def find_nums_within_range_for_current_row(row, minimum, maximum):
"""Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
count = 0
for n in row:
if minimum <= n <= maximum:
count = count + 1
return count | 4f12c34c84f102e058c5906222dd304ed8f3a9ea | 426,460 |
def _relative_path(path):
"""Strips leading slash from a path.
Args:
path - a file path
Returns:
string
"""
if path.startswith('/'):
return path[1:]
return path | effe58ffc230ac026a8467d41a45568e7b14f069 | 359,490 |
def snapPath(basePath, snapNum, chunkNum=0):
""" Return absolute path to a snapshot HDF5 file (modify as needed). """
snapPath = basePath + '/snapdir_' + str(snapNum).zfill(3) + '/'
filePath = snapPath + 'snap_' + str(snapNum).zfill(3)
filePath += '.' + str(chunkNum) + '.hdf5'
return filePath | 0f1839f2249ea104b17c0b876d146a77dda2fb79 | 256,376 |
def demo_to_dict(demo):
"""
Convert an instance of the Demo model to a dict.
:param demo: An instance of the Demo model.
:return: A dict representing the demo.
"""
return {
'id': demo.id,
'name': demo.name,
'guid': demo.guid,
'createdAt': demo.createdAt,
'users': demo.users
} | 5c3f00e963ba5bf92e8b79e69434a9494fd4a784 | 284,733 |
def find_ccs(unmerged):
"""
Find connected components of a list of sets.
E.g.
x = [{'a','b'}, {'a','c'}, {'d'}]
find_cc(x)
[{'a','b','c'}, {'d'}]
"""
merged = set()
while unmerged:
elem = unmerged.pop()
shares_elements = False
for s in merged.copy():
if not elem.isdisjoint(s):
merged.remove(s)
merged.add(frozenset(s.union(elem)))
shares_elements = True
if not shares_elements:
merged.add(frozenset(elem))
return [list(x) for x in merged] | 4bff4cc32237dacac7737ff509b4a68143a03914 | 1,827 |
def _effect_brightness(brightness: int) -> int:
"""Convert hass brightness to effect brightness."""
return round(brightness / 255 * 100) | 0822678465f3cb3924e6e8e7b8946df8e74b8635 | 342,882 |
def dict_to_arg_flags_str(flags_dict):
"""
Converts a dictionary to a commandline arguments string
in the format '--<key0>=value0 --<key1>=value1 ...'
"""
return ' '.join(
['--{}={}'.format(k, flags_dict[k]) for k in flags_dict.keys()]) | e7becc710f0ad8b040cd005434ebcf478a7a3aee | 167,725 |
def _map_captured_resources_to_created_resources(
original_captures, resource_map):
"""Maps eager resources captured by a function to Graph resources for export.
Args:
original_captures: A dictionary mapping from resource tensors captured by
the function to interior placeholders for those resources (inside the
function body).
resource_map: A dictionary mapping from resource tensors owned by the eager
context to resource tensors in the exported graph.
Returns:
A dictionary mapping from interior placeholders in the function body to
exterior stand-in resource tensors which belong to the exported graph.
Raises:
AssertionError: If the function references a resource which is not part of
`resource_map`.
"""
export_captures = {}
for exterior, interior in original_captures.items():
mapped_resource = resource_map.get(exterior, None)
if mapped_resource is None:
raise AssertionError(
("Tried to export a function which references untracked stateful "
"object {}. Stateful TensorFlow objects (e.g. tf.Variable) must "
"be tracked by the main object. Objects may be tracked by "
"assigning them to an attribute of another tracked object, or to "
"an attribute of the main object directly.")
.format(interior))
export_captures[interior] = mapped_resource
return export_captures | 9acb1816ff1ec14970961103b4451f1f61568d45 | 509,712 |
def _format_path_with_rank_zero(path: str) -> str:
"""Formats ``path`` with the rank zero values."""
return path.format(
rank=0,
local_rank=0,
node_rank=0,
) | 7ce5bca2317cda83ffcba08236c2c9ff51e01f19 | 300,911 |
def colourfulness_correlate(F_L, C_94):
"""
Returns the *colourfulness* correlate :math:`M_94`.
Parameters
----------
F_L : numeric
Luminance adaptation factor :math:`F_L`.
numeric
*Chroma* correlate :math:`C_94`.
Returns
-------
numeric
*Colourfulness* correlate :math:`M_94`.
Examples
--------
>>> F_L = 1.16754446414718
>>> C_94 = 0.12105083993617581
>>> colourfulness_correlate(F_L, C_94) # doctest: +ELLIPSIS
0.1238964...
"""
M_94 = F_L ** 0.15 * C_94
return M_94 | ba723f2e68d6e0ed576f3aa340b17af11df63de7 | 470,734 |
import logging
def error(line):
"""Log error"""
return logging.error(line) | afdd6ca2b58bd0eb10b411c2052aeb3cbde66a82 | 481,230 |
import traceback
def _FormatException(exc):
"""Format an Exception the way it would be in a traceback.
>>> err = ValueError('bad data')
>>> _FormatException(err)
'ValueError: bad data\n'
"""
return ''.join(traceback.format_exception_only(type(exc), exc)) | 42041266fa83c727c95b726eeeb22b7d928b0f04 | 415,506 |
def list_datasets(print_list=True):
"""Print available datasets in the cptac.pancan module.
Parameters:
print_list (bool, optional): Whether to print the list. Default is True. Otherwise, it's returned as a string.
"""
datasets = [
"PancanBrca",
"PancanCcrcc",
"PancanCoad",
"PancanGbm",
"PancanHnscc",
"PancanLscc",
"PancanLuad",
"PancanOv",
"PancanUcec",
"PancanPdac"
]
str_result = "\n".join(datasets)
if print_list:
print(str_result)
else:
return str_result | 037e101a9c907fbb0a773c845a1a2b4af3ff2504 | 618,820 |
def escape_attribute_value(attrval: str):
"""
Escapes the special character in an attribute value
based on RFC 4514.
:param str attrval: the attribute value.
:return: The escaped attribute value.
:rtype: str
"""
# Order matters.
chars_to_escape = ("\\", '"', "+", ",", ";", "<", "=", ">")
for char in chars_to_escape:
attrval = attrval.replace(char, "\\{0}".format(char))
if attrval[0] == "#" or attrval[0] == " ":
attrval = "".join(("\\", attrval))
if attrval[-1] == " ":
attrval = "".join((attrval[:-1], "\\ "))
attrval = attrval.replace("\0", "\\0")
return attrval | bcb06fba8799904897f80a3a55ea3892024a6d83 | 144,009 |
def get_FOV_ends(cent, FOV):
"""Take center of FOV and FOV in degrees [0-360]
and return low and high endpoints in degrees.
"""
l = (cent - FOV/2) % 360
h = (cent + FOV/2) % 360
return [l,h] | bd79c1f42b978c09a7cd0d8fbb7a20230f78e842 | 511,428 |
def deduplicate(reply):
"""
list deduplication method
:param list reply: list containing non unique items
:return: list containing unique items
"""
reply_dedup = list()
for item in reply:
if item not in reply_dedup:
reply_dedup.append(item)
return reply_dedup | 2f3f6368e8c525e3fdc31cd88bbe13923b4416cf | 565,135 |
from pathlib import Path
def extract_sequence(fasta: Path, target_contig: str) -> str:
"""
Given an input FASTA file and a target contig, will extract the nucleotide/amino acid sequence
and return as a string. Will break out after capturing 1 matching contig.
"""
sequence = ""
write_flag = False
write_counter = 0
with open(str(fasta), 'r') as infile:
for line in infile:
if write_counter > 1:
break
if line[0] == ">": # This is marginally faster than .startswith()
if target_contig in line:
write_counter += 1
write_flag = True
else:
write_flag = False
elif write_flag:
sequence += line
else:
continue
return sequence.replace("\n", "") | 547ba39dc3658e6c28c77012eba79393c01690ee | 652,612 |
def format_decimal_as_string(value):
"""
Convert a decimal.Decimal to a fixed point string. Code borrowed from
Python's moneyfmt recipe.
https://docs.python.org/2/library/decimal.html#recipes
"""
sign, digits, exp = value.as_tuple()
if exp > 0:
# Handle Decimals like '2.82E+3'
return "%d" % value
result = []
digits = list(map(str, digits))
build, next = result.append, digits.pop
for i in range(-exp):
build(next() if digits else '0')
build('.')
if not digits:
build('0')
while digits:
build(next())
if sign:
build('-')
return ''.join(reversed(result)) | f31cf34006ea44969213d3810c6a70a38f19a307 | 615,114 |
from typing import Iterable
from typing import Any
from functools import reduce
def concat(*it: Iterable[Any]) -> Any:
"""
Concatenation of iterable objects
Args:
it: Iterable object
Examples:
>>> fpsm.concat([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
"""
return reduce(lambda x, y: x + y, map(list, it)) | e2b9d1604630198486fa0649d62784078547031a | 11,675 |
import torch
import itertools
def pit_loss(
estimate: torch.Tensor,
target: torch.Tensor,
axis: int,
loss_fn=torch.nn.functional.mse_loss,
return_permutation: bool = False
):
"""
Permutation invariant loss function. Calls `loss_fn` on every possible
permutation between `estimate`s and `target`s and returns the minimum
loss among them. The tensors are permuted along `axis`.
Does not support batch dimension. Does not support PackedSequence.
Args:
estimate: Padded sequence. The speaker axis is specified with `axis`,
so the default shape is (T, K, F)
target: Padded sequence with the same shape as `estimate` (defaults
to (T, K, F))
loss_fn: Loss function to apply on each permutation. It must accept two
arguments (estimate and target) of the same shape that this function
receives the arguments.
axis: Speaker axis K. The permutation is applied along this axis. axis=-2
and an input shape of (T, K, F) corresponds to the old default
behaviour.
return_permutation: If `True`, this function returns the permutation
that minimizes the loss along with the minimal loss otherwise it
only returns the loss.
Examples:
>>> T, K, F = 4, 2, 5
>>> estimate, target = torch.ones(T, K, F), torch.zeros(T, K, F)
>>> pit_loss(estimate, target, 1)
tensor(1.)
>>> T, K, F = 4, 2, 5
>>> estimate, target = torch.ones(T, K, F), torch.zeros(T, F, dtype=torch.int64)
>>> pit_loss(estimate, target, 1, loss_fn=torch.nn.functional.cross_entropy)
tensor(0.6931)
>>> T, K, F = 4, 2, 5
>>> estimate, target = torch.ones(K, F, T), torch.zeros(K, F, T)
>>> pit_loss(estimate, target, 0)
tensor(1.)
>>> T, K, F = 4, 2, 5
>>> estimate = torch.stack([torch.ones(F, T), torch.zeros(F, T)])
>>> target = estimate[(1, 0), :, :]
>>> pit_loss(estimate, target, axis=0, return_permutation=True)
(tensor(0.), (1, 0))
>>> K = 5
>>> estimate, target = torch.ones(K), torch.zeros(K)
>>> pit_loss(estimate, target, axis=0)
tensor(1.)
>>> A, B, K, C, F = 4, 5, 3, 100, 128
>>> estimate, target = torch.ones(A, B, K, C, F), torch.zeros(A, B, K, C, F)
>>> pit_loss(estimate, target, axis=-3)
tensor(1.)
"""
axis = axis % estimate.ndimension()
sources = estimate.size()[axis]
assert sources < 30, f'Are you sure? sources={sources}'
if loss_fn in [torch.nn.functional.cross_entropy]:
estimate_shape = list(estimate.shape)
del estimate_shape[1]
assert estimate_shape == list(target.shape), (
f'{estimate.shape} (N, K, ...) does not match {target.shape} (N, ...)'
)
else:
assert estimate.size() == target.size(), (
f'{estimate.size()} != {target.size()}'
)
candidates = []
filler = (slice(None),) * axis
permutations = list(itertools.permutations(range(sources)))
for permutation in permutations:
candidates.append(loss_fn(
estimate[filler + (permutation, )],
target
))
min_loss, idx = torch.min(torch.stack(candidates), dim=0)
if return_permutation:
return min_loss, permutations[int(idx)]
else:
return min_loss | feabf5b625e915a1bee86df13394a49bfdf6f6f9 | 88,387 |
def _input_wrap(prompt, default=None):
"""
Run input() with formatted prompt, and return
The while loop can be used to ensure correct output
"""
understood = False
while not understood:
result = input(prompt.format(default=default)).lower().strip()
if result in {"y", "yes"}:
return True
if result in {"n", "no"}:
return False
if not result:
return default
if result in {"quit", "q", "exit"}:
raise RuntimeError("User quit.")
if not isinstance(default, bool):
return result
print("Error: answer not understood. You can 'quit' or hit ctrl+c to exit.") | 112e1bf613e1fc79d570107e881edbb8f721076c | 633,738 |
def point_partners_to_partner_indices(point_partners, n_partners):
"""
Convert the partner indices for each point to a list of lists with the
indices for all partners.
"""
partner_indices = [[] for i in range(n_partners)]
for i, partner_index in enumerate(point_partners):
if partner_index != -1:
partner_indices[partner_index].append(i)
return partner_indices | 2255b367c03802d9606ec5893654985a9fe18b9d | 467,485 |
from unittest.mock import patch
def patch_bond_device_state(return_value=None, side_effect=None):
"""Patch Bond API device state endpoint."""
if return_value is None:
return_value = {}
return patch(
"homeassistant.components.bond.Bond.device_state",
return_value=return_value,
side_effect=side_effect,
) | a200f10ad5c8451fecefce2506e63ab371dfc886 | 435,455 |
def check_instance_tag(tag_key, tag_value, app):
"""
Check if instance tag given matches the application configuration
:param tag_key:
:param tag_value:
:param app:
:return: bool
>>> my_app = {'_id': '123456789', 'name': 'webapp', 'env': 'dev', 'role': 'webfront'}
>>> check_instance_tag('app', 'nope', my_app)
False
>>> check_instance_tag('env', 'prod', my_app)
False
>>> check_instance_tag('app', 'webapp', my_app)
True
>>> check_instance_tag('app_id', '123456789', my_app)
True
>>> check_instance_tag('color', 'green', my_app)
False
>>> check_instance_tag('Name', 'ec2.test.front.webapp', my_app)
False
"""
if tag_key == 'app_id':
return tag_value == app['_id']
if tag_key == 'app':
return tag_value == app['name']
if tag_key == 'env':
return tag_value == app['env']
if tag_key == 'role':
return tag_value == app['role']
if tag_key == 'color':
return tag_value == app.get('blue_green', {}).get('color')
if tag_key.startswith('aws:'):
return True
instance_tags = {t['tag_name']: t['tag_value'] for t in app.get('environment_infos', {}).get('instance_tags', [])}
return tag_value == instance_tags.get(tag_key) | eb41647f7bb999ea734e124e68f6d78ac0f952ec | 298,992 |
def requires_reload(action, plugins):
"""
Returns True if ANY of the plugins require a page reload when action is taking place.
"""
for plugin in plugins:
plugin_class = plugin.get_plugin_class_instance()
if plugin_class.requires_reload(action):
return True
return False | 5ecc2a004e3a25d85435909acc4a04d9ee727b5e | 329,206 |
def _join(c):
"""Return `str` with one element of `c` per line."""
return '\n'.join(str(x) for x in c) | 516fc920996e6bb58836c7cefe0d3e70b16e6db8 | 224,926 |
import re
def eliminate_newlines_after_function_definition_in_string(code: str) -> str:
"""Eliminates all newlines after the function definition in a string, e.g.
def foo(a):
return a + 1
will become:
def foo(a):
return a+1"""
return re.sub(
pattern=r"(def \w+\([^:]*\):)(\s*)\n",
repl=r"\1\n",
string=code,
flags=re.M | re.S,
) | 1a664c4aa798f066b5d7b0fcf81abb9c75342708 | 322,871 |
def doy(dt):
""" Find the day of year of the datetime.
The returned DoY is in the range [1-366].
"""
date = dt.date()
jan01 = date.replace(month=1, day=1)
doy = (date - jan01).days + 1
return doy | b81e54432113bb51ce5fa3ae0e770a892f3110bc | 156,560 |
def intersection(bb1, bb2):
""" Calculates the Intersection of two aabb's
"""
min_w = min(bb1[2], bb2[2])
min_h = min(bb1[3], bb2[3])
if bb1[0] < bb2[0]:
leftbb, rightbb = bb1, bb2
else:
leftbb, rightbb = bb2, bb1
if bb1[1] < bb2[1]:
topbb, bottombb = bb1, bb2
else:
topbb, bottombb = bb2, bb1
w = min(min_w, max(leftbb[0] + leftbb[2] - rightbb[0], 0))
h = min(min_h, max(topbb[1] + topbb[3] - bottombb[1], 0))
return w * h | 368177cc00fcfff507198f39be3184fc2eed1855 | 29,040 |
def get_group_detail(groups):
"""
Iterate over group details from the response and retrieve details of groups.
:param groups: list of group details from response
:return: list of detailed element of groups
:rtype: list
"""
return [{
'ID': group.get('id', ''),
'Name': group.get('name', '')
} for group in groups] | dc56db5bb7fb4775a6b3d778fc22a20b90029137 | 475,176 |
def duplicate_count(counts):
""" Return the number of entries in COUNTS with a value of 2 or more. """
count = 0
for v in counts.values():
if v > 1:
count += 1
return count | c2b4fd6800f92b8aea5d17ae93d3e1fa1ac035ee | 339,511 |
def _false(*args):
"""
Returns ``False`` (used internally as a default method).
"""
return False | a363b75ec087c037555f3fa6f38b6c64963c08c9 | 536,755 |
def extract_titles(row):
"""Creates a list of dictionaries with the titles data and alternatives if exists
Args:
list: row[1:5].values
Return:
list of dictionaries with title and title type
"""
data = [
{"title":row[0], "type": "OriginalTitle"}
]
for item in set(row[1:]):
if item and item != row[0]:
data.append(
{"title":item,"type":"AlternativeType"}
)
return data | c0b505d7d3617361f044f1025e29aa67f19a521f | 160,643 |
def capital_recovery_factor(interest_rate, years):
"""Compute the capital recovery factor
Computes the ratio of a constant loan payment to the present value
of paying that loan for a given length of time. In other words,
this works out the fraction of the overnight capital cost you need
to pay back each year if you were to use debt to
pay for the expenditure.
Arguments
---------
interest_rate: float
The interest rate as a decimal value <= 1
years: int
The technology's economic lifetime
"""
if float(interest_rate) == 0.:
return 1. / years
else:
top = interest_rate * ((1 + interest_rate) ** years)
bottom = ((1 + interest_rate) ** years) - 1
total = top / bottom
return total | 4a92ca527557087537973e2adfedd48279a7c59e | 36,625 |
def get_all_users(client):
"""
Get all current Zulip users.
:param client: A Zulip client object
:return: Dictionary containing all current users.
"""
result = client.get_members()
return result | d0bd98e503db8fe50d7e489fd68cc8c23dfb5f2c | 267,546 |
def chunker(seq, size):
"""
Iterate over an iterable in 'chunks' of a given size
Parameters
----------
seq : iterable,
The sequence to iterate over
size : int,
The number of items to be returned in each 'chunk'
Returns
-------
chunk : seq,
The items of the chunk to be iterated
Examples
--------
>>> x = [0,3,4,7,9,10,12,14]
>>> for i in chunker(x, 3):
>>> print(i)
[0, 3, 4]
[7, 9, 10]
[12, 14]
"""
return (seq[pos:pos + size] for pos in range(0, len(seq), max(1, size))) | f483646d9bc8b8de0bd817e510ddc67becc5ff29 | 521,166 |
import fnmatch
def getLabels(source, path):
"""Get all labels for given path
:param source: Labels definition
:type path: dict
:param path: File full path
:type path: string
:return: Labels
:rtype: list[string]
"""
result = []
for label, patterns in source.items():
for pattern in patterns:
if fnmatch.fnmatch(path, pattern):
result.append(label)
break
return result | 0310e38b185016f781ff2a958f4e6bbd82d86d39 | 660,352 |
import random
def roll(dice):
"""Takes arguments in the format "{#}d{#}", e.g. 2d6 returns the total"""
try:
num, die = dice.split('d')
total = 0
for i in range(0,int(num)):
roll = random.randint(1,int(die))
print("rolling... " + str(roll))
total += roll
return total
except Exception as e:
print("Error: " + str(e))
return "Something went wrong! Check your input." | 3ba2284b49895ed57116e336c65199f643fc1a14 | 275,967 |
def get_df_attr(df, attr_name, default_val):
""" Get Dataframe attribute if exists otherwise default value
:return: Dataframe attribute
"""
return df.__dict__.get(attr_name, default_val) | 501caef9d2f8dbe721d4fe03879423d3bbe091ab | 399,653 |
import random
def random_seq(length: int,
charset: str = "ATCG") -> str:
"""Get a random sequence.
:param length: Length of sequence.
:param charset: Char population.
:return: Random sequence
"""
return "".join(random.choices(charset, k=length)) | 036742e9777d15a813b99b61e54dfb03f8a7ab80 | 48,674 |
def fade_copies_right(s):
""" Returns the string made by concatenating `s` with it's right slices of
decreasing sizes.
Parameters
----------
s : string
String to be repeated and added together.
Returns
-------
output : string
String after it has had ever decreasing slices added to it.
"""
# Initialisations
s_list = list(s)
output_list = [ ]
for i in range(len(s)):
output_list += s_list
s_list = s_list[1:]
output = "".join(output_list)
return output | 1c2612da69b12e245d87f9df3c57e7a399191398 | 436,121 |
def verify_social_media_platform(platform_name: str) -> bool:
"""
A helper function to make verifying social media platform strings easier
Parameters
----------
platform_name: str
The name of the social media platform to be verified.
Valid inputs are: 'f', 't', 'i', 'a'
Returns
----------
bool: Returns true if the provided social media platform is a valid social media platform
"""
return bool(
platform_name.lower() == "f"
or platform_name.lower() == "t"
or platform_name.lower() == "i"
or platform_name.lower() == "a"
) | c6a52430ff5c2d0c6bf71fe3d8717b7628ccc897 | 586,164 |
def collect_nodes(kind, collection, gen):
"""
Collects nodes with a given kind from a generator,
and puts them in the provided list.
Returns the first node from the generator that does not
match the provided kind.
"""
tail = None
for node in gen:
if node.kind is not kind:
tail = node
break
else:
collection.append(node)
return tail | 7f2a996bea6c222c6fca045490be21f34177b030 | 154,801 |
def convert_number_to_month(month_int):
"""
Return a month as string given a month number
:param month_int: int
:return: str
"""
months = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
month_int -= 1
if month_int < 0 or month_int > 11:
return
return months[month_int] | 2b43ee6d7978a1a131e3a4a5560fe37e3d1ae98f | 381,114 |
def extractGeom(lineList):
"""
Function used by loadPd_q to extract the geometries.
:lineList: line with geometries in clean format, partial charges and energies
:return: list of geometry in format [['H',-0.5,0.0,0.0,'H',0.5,0.0,0.0], ['H',-0.3,0.0,0.0,'H',0.3,0.0,0.0]...
"""
geomPart = lineList[1:22]
atomLab = ["C","H","H","H","H","C","N"]
finalGeom = []
for i in range(len(atomLab)):
finalGeom.append(atomLab[i])
for j in range(3):
finalGeom.append(float(geomPart[3*i+j]))
return finalGeom | f4b84b96a58ebe4dc286bb9c41d86ffedbeb0334 | 493,240 |
def linear_interpolation(left, right, alpha):
"""
Linear interpolation between `left` and `right`.
:param left: (float) left boundary
:param right: (float) right boundary
:param alpha: (float) coeff in [0, 1]
:return: (float)
"""
return left + alpha * (right - left) | c4b75b9143d066d298d83628881442e2946c6d41 | 211,931 |
def mediana(valores):
"""
Encontra a mediana de 'valores', isto é, o valor que ocupa a posição
central da lista ordenada. Quando a lista tem tamanho par,
definimos a mediana como o valor da primeira posição na segunda
metada da lista ordenada.
Parâmetros: lista de floats.
Retorna: a mediana de 'valores'.
"""
valores.sort()
if (len(valores) % 2 == 1):
mediana = valores[int(((len(valores)+1) / 2) - 1)]
else:
mediana = valores[int((len(valores) / 2))]
return mediana | 01897bf8cecf7292c3d02148e4fb8f1f8cd44195 | 539,713 |
import requests
def get_sequence(UniprotID):
"""Get protein sequence from UniProt Fasta (using REST API).
"""
# collect UniProtID data
fasta_URL = 'https://www.uniprot.org/uniprot/'+UniprotID+'.fasta'
request = requests.post(fasta_URL)
request.raise_for_status()
fasta_string = request.text.split('\n')
sequence = ''.join(fasta_string[1:])
return sequence | ede837154bda738dc8e7e83c97c5f81b284db17c | 73,574 |
def _match_first_key(skip_first_axis=None, feature=""):
"""Helper function to match and remove skip_first_axis from feature
:param skip_first_axis: True or string. if set, ignore first axis of input histogram(s)
:param feature: input feature
:return: match and (rest of) feature
"""
assert isinstance(feature, str)
karr = feature.split(":")
begin = karr[0]
rest_key = ":".join(karr[1:])
if isinstance(skip_first_axis, bool):
return skip_first_axis, rest_key if skip_first_axis else feature
elif isinstance(skip_first_axis, str) and len(skip_first_axis) > 0:
match = begin == skip_first_axis
return match, rest_key if match else feature
return False, feature | 8dd0278a2754cc6d9e31b34a83477cd4396a920b | 416,238 |
def count_trajectories(n: int) -> int:
"""
The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
How many possible trajectories does the grasshopper have to get to position n?
If n<=1, consider that the Grasshopper has 0 possible trajectory.
>>> count_trajectories(0)
0
>>> count_trajectories(1)
0
>>> count_trajectories(2)
1
>>> count_trajectories(3)
2
>>> count_trajectories(4)
3
>>> count_trajectories(7)
20
>>> count_trajectories(-3)
0
"""
if n <= 1:
return 0
trajectories = [0, 0, 1, 2, 3] + [0] * (n - 4)
for i in range(5, n + 1):
trajectories[i] = trajectories[i - 1] + trajectories[i - 2] + trajectories[i - 3]
return trajectories[n] | d9c0127e2a21346872783d6b4b9ea44fc2bde285 | 672,815 |
def egcd(a,b): # a > b > 0
""" Extended great common divisor, returns x , y
and gcd(a,b) so ax + by = gcd(a,b) """
if a%b==0: return (0,1,b)
q=[]
while a%b != 0:
q.append(-1*(a//b))
(a,b)=(b,a%b)
(a,b,gcd)=(1,q.pop(),b)
while q:(a,b)=(b,b*q.pop()+a)
return (a,b,gcd) | fe0f1738d46e1371e144f328c70fe480c219584f | 316,860 |
def is_valid_label(label, all_labels):
"""a function to return whether the input "label" exist in the all_labels, which is a list of string"""
return label in all_labels | dbd7e05b9a097a96940a6f95dcde042274121cf4 | 504,539 |
import re
def get_readable_path_str(original_path, max_len):
"""
Truncates path to max_len characters if necessary
If the result is a path within nested directory, will remove partially
truncated directories names
"""
if len(original_path) < max_len:
return original_path
truncated_name = original_path[-(max_len - 5):]
if "/" not in truncated_name:
return "[...]" + truncated_name
return "[...]" + re.sub("^[^/]+", "", truncated_name) | f2d8bd7499a087f561a1b3830f06c983751fe642 | 523,836 |
def empty_name(got):
""" Empty name error. """
return "Expected non-empty name, got {}.".format(repr(got)) | ec621d1833afca1a164ab11f99b8693ba0472fa1 | 247,015 |
def square(x: int) -> int:
""" This function squares numbers. You can use it like that:
:code:`square(5)`.
Args:
`x` (int): number to square
Returns:
int: squared number
:Example:
>>> square(3)
9
>>> square(10)
100
"""
return x**2 | f32d838ef011c97bd17eee16a6d731ad044ede12 | 591,793 |
def duration_to_string(value):
"""Converts the given timedelta into an appropriate ISO-8601 duration format for JSON. Only handles positive
durations correctly. Fractional seconds are rounded.
:param value: The timedelta to convert
:type value: :class:`datetime.timedelta`
:returns: The ISO-8601 duration format
:rtype: string
"""
result = 'P'
if value.days > 0:
result += '%dD' % value.days
result += 'T'
hours = value.seconds // 3600
minutes = (value.seconds - (3600 * hours)) // 60
seconds = value.seconds - (3600 * hours) - (60 * minutes)
if value.microseconds >= 500000:
seconds += 1 # Round fractional seconds
if hours > 0:
result += '%dH' % hours
if minutes > 0:
result += '%dM' % minutes
result += '%dS' % seconds
return result | 06bc74c30de00ac223c208db06f0b48cd0cb2ad5 | 664,603 |
def convert_pandas_dtypes_to_builtin_types(col_type):
"""Convert pandas data types to python builtin ones, like pandas object to python str."""
col_type = str(col_type)
if "str" in col_type:
return str
elif "int" in col_type:
return int
elif "float" in col_type:
return float
elif "bool" in col_type:
return bool
else:
return str | b53cc870ef947c4630b9990535289b5d00de3eca | 122,852 |
def seq_type(seq):
"""
Determines whether a sequence consists of 'N's only
(i.e., represents a gap)
"""
return 'gap' if set(seq.upper()) == {'N'} else 'bases' | 5555e5cd0ccdbf8f5e7b475c5c983ab54a17fb07 | 9,475 |
def user_exists(cursor,username):
"""
Test whether a user exists, from its username
Parameters:
==========
cursor: Psycopg2 cursor
Cursor of type RealDict in the postgres database
username: Str
Name of the user
"""
SQL = "SELECT count(*) AS nb FROM users WHERE username=%s"
cursor.execute(SQL,[username])
res = bool(cursor.fetchone()['nb'])
return(res) | c221cbb6dd3c99d1eacfc88c8f2161276680b938 | 17,646 |
def _conv_type(s, func):
"""Generic converter, to change strings to other types.
Args:
s (str): String that represents another type.
func (function): Function to convert s, should take a singe parameter
eg: int(), float()
Returns:
The type of func, otherwise str
"""
if func is not None:
try:
return func(s)
except ValueError:
return s
return s | e72cab10a0256cb57cddfad7da7f5f1239476852 | 586,488 |
def true_or_false(in_str):
"""Returns True/False if string represents it, else None."""
in_str = in_str.lower()
if in_str.startswith(('true', 'y', '1', 'on')):
return True
elif in_str.startswith(('false', 'n', '0', 'off')):
return False
else:
return None | e23adf40237d6111cb0a6388a95aab79ba2aa35b | 607,138 |
def convert_to_number(string):
"""
Tries to cast input into an integer number, returning the
number if successful and returning False otherwise.
"""
try:
number = int(string)
return number
except:
return False | 30110377077357d3e7d45cac4c106f5dc9349edd | 708,626 |
def unauthorized_update_message_text(update_message_text):
"""Fixture for mocking an incoming update of type message/text that is not in our `allowed_chat_ids`."""
update_message_text["message"]["from"]["id"] = 1234
update_message_text["message"]["chat"]["id"] = 1234
return update_message_text | a846e3cc2f2752c58c8a61749536a9f89d85fb73 | 317,794 |
import random
def randomLabels(intree, p_speciation=0.7):
"""
Function to assign random speciation and duplication nodes to a tree.
Returns a new tree (leaves the input tree unchanged)
:param intree: a tree as Dendropy object
:param p_speciation: probability of a speciation node.
"""
t = intree.clone(depth=1)
for n in t.internal_nodes():
if random.random() < p_speciation:
n.label = 'speciation'
else:
n.label = 'duplication'
t.seed_node.label = None
return(t) | f73e26b53a2b40ef48ad661fb287ebcc47d7bfbe | 220,026 |
def custom_admin_notification(session, notification_type, message, task_id=None):
"""
Function for implementing custom admin notifications.
notifications are stored in session and show to user when user refreshes page.
A valid session object must be passed to this function with notification type and message
Type of notifications:
* success
* info
* warning
* error
message is able to parse html so we can use html tags and classes while creating message
"""
notification = {"type": notification_type, "message": message}
messages = []
if task_id:
notification["task_id"] = task_id
if "notifications" in session:
messages = session['notifications']
messages.append(notification)
session['notifications'] = messages
return session | 6ab3b478c5109a821fc64201c9468e3d8d132cff | 635,646 |
import bz2
import gzip
def open_output(output, opts):
"""Open output file with right compression library
"""
if opts.bzip:
return bz2.open(output, 'wt')
elif opts.gzip:
return gzip.open(output, 'wt')
else:
return open(output, 'w') | 9f830afb3422f0707ef6b49c9b2000a35b4bc0a0 | 57,036 |
def sizes(ranges):
"""Get a list with the size of the ranges"""
sizes = []
for r in ranges:
sizes.append(r[1] - r[0]) # 1: end, 0: start
return sizes | c612ec12172d7c6e0eac14cbd8ef262a3ee8efe2 | 330,798 |
def restore_training(fn, netclass, trainclass, valclass, valdata, gpu=True):
"""Restore training from file.
:param fn: filename to load
:param netclass: :class:`.network.Network` class to use
:param trainclass: :class:`TrainAlgorithm` class to use
:param valclass: :class:`.validate.Validation` class to use
:param valdata: list of :class:`.data.DataPoint` to validate with
:param gpu: (optional) whether to use GPU or CPU
:return: network object, training algorithm object, and validation object
"""
n = netclass.from_file(fn, groupname='checkpoint', gpu=gpu)
t = trainclass.from_file(fn)
v = valclass.from_file(fn)
v.d = valdata
return n, t, v | c9fcfb9e0635ca911a86f93e25f57ad779eee4ff | 181,656 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.