content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import torch
from typing import Tuple
def find_matching_pairs(
y: torch.Tensor,
a_pair_info: torch.Tensor,
b_pair_info: torch.Tensor) -> Tuple[torch.Tensor,torch.Tensor]:
"""
Given a batch of ground truth label maps, and sampled pixel
pair locations (pairs are across label maps), identify which
pairs are matching vs. non-matching and return corresponding metadata
(basically, partition them).
Args:
- y: Tensor of size (B,H,W) representing 2-d label maps
for B examples.
- a_pair_info:
- b_pair_info:
Returns:
- pos_pair_info: Pytorch tensor containing info about each positive pair (a,b). Contains
(a batch_idx, a row, a col, b batch_idx, b row, b col)
- neg_pair_info: Same as above, but for negative pairs.
"""
batch_dim_a_idxs = a_pair_info[:,0]
px_1d_a_y = a_pair_info[:,1]
px_1d_a_x = a_pair_info[:,2]
batch_dim_b_idxs = b_pair_info[:,0]
px_1d_b_y = b_pair_info[:,1]
px_1d_b_x = b_pair_info[:,2]
# extract category indices
cls_vals_a = y[batch_dim_a_idxs, px_1d_a_y, px_1d_a_x]
cls_vals_b = y[batch_dim_b_idxs, px_1d_b_y, px_1d_b_x]
# compare category indices for equality
is_same_class = (cls_vals_a == cls_vals_b).nonzero().squeeze()
is_diff_class = (cls_vals_a != cls_vals_b).nonzero().squeeze()
a_pos_info = a_pair_info[is_same_class]
a_neg_info = a_pair_info[is_diff_class]
b_pos_info = b_pair_info[is_same_class]
b_neg_info = b_pair_info[is_diff_class]
pos_pair_info = torch.cat([a_pos_info, b_pos_info], dim=1)
neg_pair_info = torch.cat([a_neg_info, b_neg_info], dim=1)
return pos_pair_info, neg_pair_info
|
35310dc7614d6c3f80302b83ca83c87644828150
| 553,483 |
def _js_repr(val):
"""Return a javascript-safe string representation of val"""
if val is True:
return 'true'
elif val is False:
return 'false'
elif val is None:
return 'null'
else:
return repr(val)
|
b5462a172a4aa68cc78e8bf9f9752991d4e7903d
| 142,862 |
import copy
def unravel(l):
"""
Unravel Union node to get all permutations of types for each action
Parameters
----------
list : list of Qiime2.types
Returns
-------
list of lists - list of permuations of types for each action
"""
result = [l]
for i, x in enumerate(l):
if len(list(x[1])) > 1:
members = list(x[1])
temp = copy.deepcopy(result)
# update result with first element of types in member
for each_list in result:
each_list[i][1] = members[0]
# add in other permutations of types in member
for n in range(1, len(members)):
copy_result = copy.deepcopy(temp)
for each_list in copy_result:
each_list[i][1] = members[n]
result += copy_result
return result
|
0c676ff8477b8964cdf0a2885e709e8b27ed066c
| 139,961 |
def actions2trajectory(position, actions):
"""
helper function to map a set of actions to a trajectory.
action convention:
1 - upper left, 2 - up, 3 - upper right
4 - left, 0 - stop, 5 - right
6 - lower left, 7 - down, 8 -lower right
Inputs:
- position: numpy array representing (x, y) position
- actions: list of integers (see convention) describing movement actions
Returns:
- trajectory: list of (x, y) positions created by taking actions, where the
first element is the input position
"""
trajectory = []
x, y = position
trajectory.append((x, y))
for a in actions:
x, y = trajectory[-1]
if a == 0:
trajectory.append((x, y))
elif a == 1:
trajectory.append((x-1, y+1))
elif a == 2:
trajectory.append((x, y+1))
elif a == 3:
trajectory.append((x+1, y+1))
elif a == 4:
trajectory.append((x-1, y))
elif a == 5:
trajectory.append((x+1, y))
elif a == 6:
trajectory.append((x-1, y-1))
elif a == 7:
trajectory.append((x, y-1))
elif a == 8:
trajectory.append((x+1, y-1))
return trajectory
|
27d27e134cb71f930b82d6f8561c71e9f2eccbc8
| 509,187 |
import string
import re
def consonant_sounds(word: str):
"""Return a set with all the consonant sounds in word.
Ex: chatting -> {'ch', 't', 'ng'}. Note that 'tt' becomes 't'."""
consonants = ''.join([c for c in string.ascii_lowercase if c not in 'aeiou'])
pattern = f'[aeiou]*([{consonants}]+)'
match = set(re.findall(pattern, word.lower()))
for cluster in match.copy(): # substitute 'tt' with 't'
if len(cluster) > 1 and len(set(cluster)) == 1:
match.update(cluster[0])
match.remove(cluster)
return match
|
bf7b8706c1c27634b8cd925ff9099d02b788499a
| 234,201 |
def tibetan_leap_month(date):
"""Return 'leap month' element of a Tibetan date, date."""
return date[2]
|
1e4fa5c15ec0556703ff32f162954f2722b1f26a
| 537,588 |
def mean(xs):
"""Returns the mean of the given list of numbers"""
return sum(xs) / len(xs)
|
05404301294bf2ff7c632857d31d33c78741bcfd
| 611,614 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"chain": string,
"rules": [
{
"num" integer,
"pkts": integer,
"bytes": integer, # converted based on suffix
"target": string,
"prot": string,
"opt": string, # "--" = Null
"in": string,
"out": string,
"source": string,
"destination": string,
"options": string
}
]
}
]
"""
for entry in proc_data:
for rule in entry['rules']:
int_list = ['num', 'pkts']
for key in int_list:
if key in rule:
try:
key_int = int(rule[key])
rule[key] = key_int
except (ValueError):
rule[key] = None
if 'bytes' in rule:
multiplier = 1
if rule['bytes'][-1] == 'K':
multiplier = 1000
rule['bytes'] = rule['bytes'].rstrip('K')
elif rule['bytes'][-1] == 'M':
multiplier = 1000000
rule['bytes'] = rule['bytes'].rstrip('M')
elif rule['bytes'][-1] == 'G':
multiplier = 1000000000
rule['bytes'] = rule['bytes'].rstrip('G')
elif rule['bytes'][-1] == 'T':
multiplier = 1000000000000
rule['bytes'] = rule['bytes'].rstrip('T')
elif rule['bytes'][-1] == 'P':
multiplier = 1000000000000000
rule['bytes'] = rule['bytes'].rstrip('P')
try:
bytes_int = int(rule['bytes'])
rule['bytes'] = bytes_int * multiplier
except (ValueError):
rule['bytes'] = None
if 'opt' in rule:
if rule['opt'] == '--':
rule['opt'] = None
return proc_data
|
d4f8b290cbf04de75c148d13331ef46b11405338
| 161,239 |
def acs(concept, paragraph, model, min_length, stop_words=[]):
"""
:param concept: str, the concept word for the concept
:param paragraph: list, a list of the tokens in the paragraph
:param model: gensim.models.Word2Vec, model containing word vectors
:return: float, the distance between the concept and the paragraph
as the sum of the cos distance between each word and the concept
divided by the number of words.
"""
d_sum = 0
word_count = 0
if len(paragraph) == 0:
return d_sum
if len(paragraph) <= min_length:
return -1
for word in paragraph:
if word in model.wv and word not in stop_words:
sim = model.wv.similarity(word, concept)
d_sum += sim
word_count += 1
return d_sum/word_count
|
4af462fb970fed1b7e8f42576e5cceac6b912ad6
| 669,444 |
import re
def camelize(string):
""" Convert string to CamelCase notation (leave first character upper).
>>> camelize('Color_space')
'ColorSpace'
>>> camelize('ColorSpace')
'ColorSpace'
"""
return re.sub(r'_([a-zA-Z])', lambda x: x.group(1).upper(), string)
|
98a6fcfb89d13bc7ea7e065a2e8401eaa43a20ad
| 337,404 |
def convert_float(s):
"""Converts values, handling bad strings."""
try:
return float(s)
except (ValueError, TypeError):
return None
|
f521645d818ab45ba111b538c5169b9817030ee9
| 346,115 |
def rol(x, i):
"""Rotate the bottom 32 bits of x left by i bits."""
return ((x << i) | ((x & 0xffffffff) >> (32 - i))) & 0xffffffff
|
33ecbe3ed9f0806e14c6abbfb75889e916dfc78b
| 658,453 |
import re
def _parse_txt_channel(header: str) -> str:
"""Extract channel and label from text headers and return channels as formatted by
MCDViewer. e.g. 80ArAr(ArAr80Di) -> ArAr(80)_80ArAr
Args:
headers: channel text header
Returns:
Channel header renamed to be consistent with MCD Viewer output
"""
label, metal, mass = re.findall(r"(.+)\(([a-zA-Z]+)(\d+)Di\)", header)[0]
return f"{metal}({mass})_{label}"
|
d286b80b237f03de52d252e4e7f823de2a469a4f
| 374,854 |
def unpackLine(string, separator="|"):
""" Unpacks a string that was packed by packLine. """
result = []
token = None
escaped = False
for char in string:
if token is None:
token = ""
if escaped and char in ('\\', separator):
token += char
escaped = False
continue
escaped = (char == '\\')
if escaped:
continue
if char == separator:
result.append(token)
token = ""
else:
token += char
if token is not None:
result.append(token)
return result
|
f6fff254be36ab9d43184ffdc973c79be323bc51
| 204,588 |
def braced(input):
"""Put braces around a word"""
return '{%s}' % input
|
0c0e3f3518580587c83eac95ba901541291fddc7
| 146,921 |
def override(original, results):
"""
If a receiver to a signal returns a value, we override the original value
with the last returned value.
:param original: The original value
:param results: The results from the signal
"""
overrides = [v for fn, v in results if v is not None]
if len(overrides) == 0:
return original
return overrides[-1]
|
3594a74f569b0d0ea0f2114b35243569b4325a31
| 497,767 |
def parsimony_informative_or_constant(numOccurences):
"""
Determines if a site is parsimony informative or constant.
A site is parsimony-informative if it contains at least two types of nucleotides
(or amino acids), and at least two of them occur with a minimum frequency of two.
https://www.megasoftware.net/web_help_7/rh_parsimony_informative_site.htm
A site is constant if it contains only one character and that character occurs
at least twice. https://www.megasoftware.net/web_help_7/rh_constant_site.htm
Arguments
---------
argv: numOccurences
dictionary with sequence characters (keys) and their counts (values)
"""
# create a dictionary of characters that occur at least twice
d = dict((k, v) for k, v in numOccurences.items() if v >= 2)
# if multiple characters occur at least twice, the site is parsimony
# informative and not constant
if len(d) >= 2:
parsimony_informative = True
constant_site = False
# if one character occurs at least twice and is the only character,
# the site is not parismony informative but it is constant
elif len(d) == 1 and len(numOccurences) == 1:
parsimony_informative = False
constant_site = True
else:
parsimony_informative = False
constant_site = False
return parsimony_informative, constant_site
|
3b547cc72b5cda912c0693df7fd8735c888fee42
| 181,535 |
from typing import Dict
from typing import Tuple
def get_colormap() -> Dict[str, Tuple[int, int, int]]:
"""
Get the defined colormap.
:return: A mapping from the class names to the respective RGB values.
"""
classname_to_color = { # RGB.
"noise": (0, 0, 0), # Black.
"animal": (70, 130, 180), # Steelblue
"human.pedestrian.adult": (0, 0, 230), # Blue
"human.pedestrian.child": (135, 206, 235), # Skyblue,
"human.pedestrian.construction_worker": (100, 149, 237), # Cornflowerblue
"human.pedestrian.personal_mobility": (219, 112, 147), # Palevioletred
"human.pedestrian.police_officer": (0, 0, 128), # Navy,
"human.pedestrian.stroller": (240, 128, 128), # Lightcoral
"human.pedestrian.wheelchair": (138, 43, 226), # Blueviolet
"movable_object.barrier": (112, 128, 144), # Slategrey
"movable_object.debris": (210, 105, 30), # Chocolate
"movable_object.pushable_pullable": (105, 105, 105), # Dimgrey
"movable_object.trafficcone": (47, 79, 79), # Darkslategrey
"static_object.bicycle_rack": (188, 143, 143), # Rosybrown
"vehicle.bicycle": (220, 20, 60), # Crimson
"vehicle.bus.bendy": (255, 127, 80), # Coral
"vehicle.bus.rigid": (255, 69, 0), # Orangered
"vehicle.car": (255, 158, 0), # Orange
"vehicle.construction": (233, 150, 70), # Darksalmon
"vehicle.emergency.ambulance": (255, 83, 0),
"vehicle.emergency.police": (255, 215, 0), # Gold
"vehicle.motorcycle": (255, 61, 99), # Red
"vehicle.trailer": (255, 140, 0), # Darkorange
"vehicle.truck": (255, 99, 71), # Tomato
"flat.driveable_surface": (0, 207, 191), # nuTonomy green
"flat.other": (175, 0, 75),
"flat.sidewalk": (75, 0, 75),
"flat.terrain": (112, 180, 60),
"static.manmade": (222, 184, 135), # Burlywood
"static.other": (255, 228, 196), # Bisque
"static.vegetation": (0, 175, 0), # Green
"vehicle.ego": (255, 240, 245)
}
return classname_to_color
|
069a7c4aff434d72a0d67bc4b59db732589541a7
| 97,675 |
def to_chr(x):
"""chr(x) if 0 < x < 128 ; unicode(x) if x > 127."""
return 0 < x < 128 and chr(x) or eval("u'\\u%d'" % x)
|
1f2eebb014f328e3ff6184a56663db814ebfa34b
| 106,549 |
from typing import Union
def convert_seconds_to_hms(sec: Union[float, int]) -> str:
"""Function that converts time period in seconds into %h:%m:%s expression.
Args:
sec (float): time period in seconds
Returns:
output (string): formatted time period
"""
sec = int(sec)
h = sec // 3600
m = sec % 3600 // 60
s = sec % 3600 % 60
output = '{:02d}h:{:02d}m:{:02d}s'.format(h, m, s)
return output
|
f7b81898e82a13b95a82a22c42470f2df158b0c8
| 459,708 |
def get_cincinnati_channels(major, minor):
"""
:param major: Major for release
:param minor: Minor version for release.
:return: Returns the Cincinnati graph channels associated with a release
in promotion order (e.g. candidate -> stable)
"""
major = int(major)
minor = int(minor)
if major != 4:
raise IOError('Unable to derive previous for non v4 major')
prefixes = ['candidate', 'fast', 'stable']
if major == 4 and minor == 1:
prefixes = ['prerelease', 'stable']
return [f'{prefix}-{major}.{minor}' for prefix in prefixes]
|
e57ad8d26ea0a397e8c3f9edc99174f78b506564
| 701,580 |
def age_bin(age, labels, bins):
""" Return a label for a given age and bin.
Argument notes:
age -- int
labels -- list of strings
bins -- list of tuples, with the first tuple value being
the inclusive lower limit, and the higher tuple
value being the exclusive upper limit
"""
for x in range(len(bins)):
if age < bins[x][1] and age >= bins[x][0]:
return labels[x]
|
9caccc667b55f66824bcf8802161384590cc2a08
| 697,886 |
def read_text(file_location, not_exists_ok=False):
"""Read text from a file
Args:
file_location (str): Location of file
not_exists_ok (bool, optional): If True and file does not exist, will return "" instead of throw an exception. Defaults to False.
Returns:
str: The text in the file, stripped of whitepace at the end
"""
try:
with open(file_location, "r") as f:
return f.read().strip()
except FileNotFoundError:
if not not_exists_ok:
raise
else:
return ""
|
8fe16392a8d8dbdb10c62a9575ee7f7815d4544f
| 370,729 |
def has_alpha(img):
"""Checks if the image has an alpha channel.
Args:
img: an image
Returns:
True/False
"""
return img.ndim == 4
|
15e673deb3024e3a321571b1a1a27d5c310089a1
| 79,752 |
def insert_into_every(dods, key, value):
"""Insert key:values into every subdictionary of dods.
Args:
dods: dictionary of dictionaries
key: key to hold values in subdictionaires
value: value to associate with key
Returns:
dict: dictionary of dictionaries with key:values inserted into each
"""
def update(d, v):
d.update({key: v})
return d
return {k: update(v, value) for k, v in dods.items()}
|
d472702e9ba0f255e07e2e728ed6e52da5d51517
| 339,517 |
def get_errno(e):
"""Get the error code out of socket.error objects
"""
return e.args[0]
|
af8427bf4bfbed62b2641cb1e135505a8c7ddbc9
| 181,724 |
def get_built_config_distribution(built_config, minimal_diffs):
"""
Args:
built_config: Configuration built so far
minimal_diffs: List of all the minimal diffs in built config space
Returns:
A probability distribution over blocks in the built config -- probabilities of next removal
"""
def f(block, minimal_diffs):
diffs_containing_block = list([x for x in minimal_diffs if block in x["built_minus_gold"]])
return len(diffs_containing_block)
# get counts
scores = list([f(x, minimal_diffs) for x in built_config])
# normalize
if not sum(scores) == 0:
normalized_scores = list([float(x)/float(sum(scores)) for x in scores])
else:
normalized_scores = scores
return normalized_scores
|
e956afaa885bfbecc79e002bd3dc25f7ce2e8e12
| 227,839 |
def determine(hand):
"""Returns a list of values, a set of values, a list of suits, and a list of cards within a hand."""
values, vset, suits, all_cards = [], set(), [], []
for x in range(len(hand)):
values.append(int(hand[x]))
vset.add(int(hand[x]))
suits.append(hand[x].suit)
all_cards.append(hand[x])
return sorted(values, reverse=True), vset, suits, all_cards
|
60318bf9c9259f0741caaadb0246d2d8d66ca4f5
| 39,155 |
def state_schema(cfg):
"""Given config data, return the Cerberus schema for the state.
"""
return {
cfg['time_key']: {
'type': cfg['time_type'],
'required': True,
'nullable': True},
'status': {
'allowed': cfg['status_values'],
'required': True},
'episode_start': {
'type': cfg['time_type'],
'required': True,
'nullable': True},
'episode_end': {
'type': cfg['time_type'],
'required': True,
'nullable': True},
'episode_status_max': {
'allowed': cfg['status_values'],
'required': False,
'nullable': True}}
|
f6ec291aee761aac1aabc0ecc47240d68b05ac90
| 557,074 |
import re
def split_into_chunks(code):
"""
Split code into chunks, each chunk being a function definition
"""
# Create an empty list to store chunks
chunks = []
# Create a string to store the current chunk
chunk = ''
# For each line in the code
for line in code.splitlines():
# If the line is a python or java function definition
if re.match(r'^\s*(def|public|private)\s', line):
# Add the current chunk to the list of chunks
chunks.append(chunk)
# And reset the current chunk
chunk = ''
# Add the line to the current chunk
chunk += line + '\n'
# Add the last chunk to the list of chunks
chunks.append(chunk)
# Return the list of chunks
return chunks
|
bc1d44060c14237893c522c04b3a04445dd5ea60
| 603,558 |
import json
import copy
def get_args(request, required_args):
"""
Helper function to get arguments for an HTTP request
Currently takes args from the top level keys of a json object or
www-form-urlencoded for backwards compatability.
Returns a tuple (error, args) where if error is non-null,
the requesat is malformed. Otherwise, args contains the
parameters passed.
"""
args = None
if (
request.requestHeaders.hasHeader('Content-Type') and
request.requestHeaders.getRawHeaders('Content-Type')[0].startswith('application/json')
):
try:
args = json.load(request.content)
except ValueError:
request.setResponseCode(400)
return {'errcode': 'M_BAD_JSON', 'error': 'Malformed JSON'}, None
# If we didn't get anything from that, try the request args
# (riot-web's usage of the ed25519 sign servlet currently involves
# sending the params in the query string with a json body of 'null')
if args is None:
args = copy.copy(request.args)
# Twisted supplies everything as an array because it's valid to
# supply the same params multiple times with www-form-urlencoded
# params. This make it incompatible with the json object though,
# so we need to convert one of them. Since this is the
# backwards-compat option, we convert this one.
for k, v in args.items():
if isinstance(v, list) and len(v) == 1:
args[k] = v[0]
missing = []
for a in required_args:
if a not in args:
missing.append(a)
if len(missing) > 0:
request.setResponseCode(400)
msg = "Missing parameters: "+(",".join(missing))
return {'errcode': 'M_MISSING_PARAMS', 'error': msg}, None
return None, args
|
b44e058590945211ca410005a5be2405b4756ca4
| 703,466 |
import re
def is_jira_issue(string):
"""Returns True if input string is a valid JIRA issue key, else False"""
jira_regex = r"^[A-Z]{1,10}-[0-9]+$"
return bool(re.match(jira_regex, string))
|
854355bfb5ebf02cec68a35220133588a135a2ea
| 264,979 |
def validate_geography(lon: float, lat: float):
"""
Verifies that latitude and longitude values are valid
:param lon: longitude value in degrees
:param lat: latitude value in degrees
:return valid: boolean for whether the lon/lat values are valid
"""
lon_valid = lon >= -180 and lon <= 180
lat_valid = lat >= -90 and lat <= 90
valid = lon_valid and lat_valid
if not valid:
return False
else:
return True
|
00ba1bab9a8fcdfa764da6b23c5be93c087d572d
| 170,785 |
def _rectify_identifier(station, textprod):
"""Rectify the station identifer to IEM Nomenclature."""
station = station.strip()
if len(station) == 4 and station.startswith("K"):
return station[1:]
if len(station) == 3 and not textprod.source.startswith("K"):
return textprod.source[0] + station
return station
|
a4abd3ef40cc2dac718deceabf6d9caa2d8384df
| 556,357 |
def strategy(history, memory):
"""
Defect every few turns, based on the fibonacci sequence.
i.e., defect turn 2 (1), turn 3 (1), turn 5 (2), turn 8 (3), turn 13 (5)
"""
if memory is None:
last_defection_turn = 0
prev_fibonacci = 1
current_fibonacci = 1
else:
last_defection_turn, prev_fibonacci, current_fibonacci = memory
if history.shape[1] == last_defection_turn + current_fibonacci:
last_defection_turn = history.shape[1]
next_fibonacci = prev_fibonacci + current_fibonacci
prev_fibonacci = current_fibonacci
current_fibonacci = next_fibonacci
choice = 0
else:
choice = 1
return choice, (last_defection_turn, prev_fibonacci, current_fibonacci)
|
009710f3fb9eb4c5802b3beb0239afe2de6acdfb
| 44,909 |
def mcfadden_r2(ll_est, ll_null):
"""
McFadden's Pseudo R-squared when the saturated model is not available.
Parameters
----------
ll_est : numpy array
Estimated Log likelihood.
ll_null : numpy array
Null-model log-likelihood.
Returns
-------
m_r2 : float
McFadden Pseudo R-squared.
"""
m_r2 = 1 - (ll_est/ll_null)
return m_r2
|
4a08299368d695f4b760fb118071bbd7a78a86a2
| 335,143 |
import json
def load_labels(label_fpath):
"""
Load stored labels
Params:
label_fpath (str): file-path to stored labels
Returns: the dict containing the report (stored) labels
"""
with open(label_fpath, 'r') as f:
labels = json.load(f)
return labels
|
1f3b9988e2862f2e7a34c423c64488fe10e6956e
| 206,240 |
import time
def is_expired(epoch_time):
"""True if current time has passed the provided epoch_time"""
return time.time() > epoch_time
|
b264fd1d73fe7f9c97592e6bffc27c81574d6bde
| 700,738 |
def zero_penalty(self, real_data, fake_data):
"""
No penalty
"""
return 0
|
9f1c19a5784eb1cee672fbba8fc665aef125570e
| 412,380 |
def dict_append_to_value_lists(dict_appendee, dict_new):
"""
Appends values from dict_new to list of values with same key in dict_appendee
Args:
dict_appendee: dict with value lists (as created by dict_values_to_lists function
dict_new: dict with new values that need to be appended to dict_appendee
Returns:
dict with appended values
"""
if dict_new is None:
return None
for key in dict_new.keys():
if type(dict_appendee[key]) != list:
raise TypeError("Dict value is not a list")
dict_appendee[key] += [dict_new[key]]
return dict_appendee
|
3f39a6bca91c3429a04f0047673f6231d29336eb
| 694,168 |
import torch
def ume_ustat_h1_mean_variance(feature_matrix, return_variance=True,
use_unbiased=True):
"""
Compute the mean and variance of the asymptotic normal distribution
under H1 of the test statistic. The mean converges to a constant as
n->\infty.
feature_matrix: n x J feature matrix
return_variance: If false, avoid computing and returning the variance.
use_unbiased: If True, use the unbiased version of the mean. Can be
negative.
Return the mean [and the variance]
"""
Z = feature_matrix
n = Z.size(0)
assert n > 1, 'Need n > 1 to compute the mean of the statistic.'
if use_unbiased:
# t1 = np.sum(np.mean(Z, axis=0)**2)*(n/float(n-1))
t1 = torch.sum(torch.mean(Z, dim=0)**2).mul(n).div(n-1)
# t2 = np.mean(np.sum(Z**2, axis=1))/float(n-1)
t2 = torch.mean(torch.sum(Z**2, dim=1)).div(n-1)
mean_h1 = t1 - t2
else:
# mean_h1 = np.sum(np.mean(Z, axis=0)**2)
mean_h1 = torch.sum(torch.mean(Z, dim=0)**2)
if return_variance:
# compute the variance
# mu = np.mean(Z, axis=0) # length-J vector
mu = torch.mean(Z, dim=0) # length-J vector
# variance = 4.0*np.mean(np.dot(Z, mu)**2) - 4.0*np.sum(mu**2)**2
variance = 4.0*torch.mean(torch.matmul(Z, mu)**2) - 4.0*torch.sum(mu**2)**2
return mean_h1, variance
else:
return mean_h1
|
ea9d90d96bd8de490c3a9b4533a81a1bd87ef93d
| 344,045 |
def dict_pathsearch(dict, path):
"""
Finds a value inside a dictionary of dictionaries given a path-like string
of keys separated by periods. Raises KeyError if the requested path
doesn't exist.
Example
-------
Given a dictionary like the following:
{
foo : "foo"
bar : "bar"
baz : {
bling: "bling"
spam: {
eggs: "eggs"
ham: "ham"
}
}
}
and a path like:
dict_pathsearch(dict, "baz.spam.ham") returns "ham"
dict_pathsearch(dict, "foo") returns "foo"
dict_pathsearch(dict, "baz.bling") returns "bling"
dict_pathsearch(dict, "python") raises KeyError
"""
pathchunks = path.split('.')
current = dict
for chunk in pathchunks:
if chunk in current:
current = current[chunk]
else:
raise KeyError
return current
|
d1265627ca0e8e349151c6668dc740e224c84a0f
| 561,118 |
def mz_validator(number: str, nr_format: str = "international") -> list:
""" Verify if the given number is valid
Args:
number (str): The phone number to be validated
nr_format (str, optional): The number has international identification code. Defaults to international.
Returns:
list: return a list containing all errors identified. If the list is empty it means the number is valid.
"""
number = number.strip()
network_codes = ["82", "83", "84", "85", "86", "87"]
inter_format = True if nr_format == "international" else False
number_size = 12 if inter_format else 9
error_messages = []
error_type = {
"size": f"The phone number must be :attr: characters long. currently with {len(number)}.",
"format": "The phone number must start with 258.",
"network_code": f"Invalid network code. Valid codes: {network_codes}."
}
if len(number) != number_size:
error_messages.append(
error_type["size"].replace(":attr:", str(number_size)))
if inter_format:
number = number.replace("+", "")
if "258" not in number[:3]:
error_messages.append(error_type["format"])
if number[3:5] not in network_codes:
error_messages.append(error_type["network_code"])
else:
if number[:2] not in network_codes:
error_messages.append(error_type["network_code"])
return error_messages
|
4e89bcadb805b644d852e3a45190a0685f85f2ad
| 207,785 |
def _extract_array(array, shape, position):
"""Helper function to extract parts of a larger array.
Simple implementation of an array extract function , because
`~astropy.ndata.utils.extract_array` introduces too much overhead.`
Parameters
----------
array : `~numpy.ndarray`
The array from which to extract.
shape : tuple or int
The shape of the extracted array.
position : tuple of numbers or number
The position of the small array's center with respect to the
large array.
"""
x_width = shape[1] // 2
y_width = shape[0] // 2
y_lo = position[0] - y_width
y_hi = position[0] + y_width + 1
x_lo = position[1] - x_width
x_hi = position[1] + x_width + 1
return array[y_lo:y_hi, x_lo:x_hi]
|
669d011b861098ee8246758dcc73bba8d1b94ca5
| 540,178 |
from typing import List
def _wraptext(text: str, length: int = 78) -> List[str]:
"""
Wrap long text into several lines of text is smart enough to wrap
words that are too long to a new line
:param text: str, the long text to wrap
:param length: int, the number of characters to wrap at
:return: the list of strings each of less than "length" characters
"""
lines = []
buffer = ''
# split all words in the text
words = text.split(' ')
# loop around words
for word in words:
# offload buffer to lines
if len(buffer) + len(word) >= length:
lines.append(buffer)
buffer = ''
# else add to the buffer
else:
buffer += '{0} '.format(word)
# add the last buffer
lines.append(buffer)
# return the list of strings
return lines
|
cfbc70d061912878f62cde61fbea3df9d0d1649d
| 224,732 |
def _path_to_release(path):
"""Compatibility function, allows us to use release identifiers like "3.0" and "3.1"
in the public API, and map these internally into storage path segments."""
if path == "v3":
return "3.0"
elif path.startswith("v3."):
return path[1:]
else:
raise RuntimeError(f"Unexpected release path: {path!r}")
|
84ea8a22e3a1d82df249161fd76b12c370f70742
| 695,654 |
def sumar_valores_pares(numeros: list) -> int:
""" Sumar valores pares
Parámetros:
numeros (list): Una lista de números enteros.
Retorno:
int: La suma de los números de la lista que sean pares.
"""
suma_par = 0
for numero in numeros:
if numero % 2 == 0:
suma_par += numero
return suma_par
|
f7c9a2838b60e77f04ae83ded46f64e61919691f
| 526,752 |
def float_validator(minimum=None, maximum=None, allow_exponent=False):
""" Creates a callable which will validate text input against the
provided float range.
Parameters
----------
minimum : None or float
The lower bound of allowable values, inlcusive. None indicates
no lower bound.
maximum : None or float
The upper bound of allowable values, inlcusive. None indicates
no upper bound.
allow_exponent : bool
Whether or not to allow exponents like '1e6' in the input.
Returns
-------
results : callable
A callable which takes a single unicode argument and returns
True if the text matches the range, False otherwise.
"""
def validator(text):
try:
value = float(text)
except ValueError:
return False
if minimum is not None and value < minimum:
return False
if maximum is not None and value > maximum:
return False
if not allow_exponent and 'e' in text.lower():
return False
return True
return validator
|
3b3defcbd3593dd879daa3283258cb5cee149992
| 415,162 |
def _as_list(obj):
"""A utility function that treat the argument as a list.
Parameters
----------
obj : object
Returns
-------
If `obj` is a list, return it. Otherwise, return `[obj]` as a single-element list.
"""
if isinstance(obj, list):
return obj
else:
return [obj]
|
7b4ad031afc5f208ad0d58a93a7456ff15586b5b
| 534,261 |
def _any(itr):
"""Similar to Python's any, but returns the first value that matches."""
for val in itr:
if val:
return val
return False
|
a71eb2643af93d76031290d8083a6595b3560084
| 120,701 |
import random
def random_color(s):
"""
The function returns a random RGB color;
It helps to get random colors since the number of variables is not known
"""
number_of_colors = s
color = ["#" + ''.join([random.choice('0123456789ABCDEF') for j
in range(6)])
for i in range(number_of_colors)]
return color
|
e4150e15ddb1ea1843f811929b1de20735e983b4
| 231,084 |
def filename_for(resource):
"""Generate a unique base file name for the given resource.
:param resource: A k8s resource definition dict, expected to have at least
a kind and metadata.name.
:return: A base file name (no directory) that should be unique for the
given resource (assuming the resource is itself unique).
"""
chunks = [resource['kind']]
ns = resource['metadata'].get('namespace')
if ns:
chunks.append(ns)
chunks.append(resource['metadata']['name'])
return '_'.join(chunks) + '.yaml'
|
2feb6589b1b0c7b3dc9d60f5d2b629e221923290
| 433,916 |
def truncate(predictions, targets, allowed_len_diff=3):
"""Ensure that predictions and targets are the same length.
Arguments
---------
predictions : torch.Tensor
First tensor for checking length.
targets : torch.Tensor
Second tensor for checking length.
allowed_len_diff : int
Length difference that will be tolerated before raising an exception.
"""
len_diff = predictions.shape[1] - targets.shape[1]
if len_diff == 0:
return predictions, targets
elif abs(len_diff) > allowed_len_diff:
raise ValueError(
"Predictions and targets should be same length, but got %s and "
"%s respectively." % (predictions.shape[1], targets.shape[1])
)
elif len_diff < 0:
return predictions, targets[:, : predictions.shape[1]]
else:
return predictions[:, : targets.shape[1]], targets
|
183dbe4c3400fbccea8a76850afc29cdf06a84dc
| 85,877 |
from typing import List
from typing import Dict
from typing import Any
import copy
def expected_gui_urls(gui_urls: List[Dict[str, Any]],
haproxy: bool, yarl: bool) -> List[Dict[str, Any]]:
"""Get the expected value of a gui-url list for a single product.
The implementation transforms the list in slightly different ways depending
on context.
Parameters
----------
gui_urls
Expected value, with `href` properties set to the haproxy URL and URLs represented
as :class:`yarl.URL` objects.
haproxy
If false, replace `href` with `orig_href`.
yarl
If false, replace `href` and `orig_href` with plain strings
"""
gui_urls = copy.deepcopy(gui_urls)
for gui in gui_urls:
if not haproxy:
gui['href'] = gui['orig_href']
if not yarl:
gui['href'] = str(gui['href'])
gui['orig_href'] = str(gui['orig_href'])
return gui_urls
|
95cb2a2029463887fe7dc44f3c113ce1f8e58b26
| 518,685 |
def splitOut(aa):
"""Splits out into x,y,z, Used to simplify code
Args:
aa - dictionary spit out by
Returns:
outkx, outky, outkz (numpy arrays) - arrays of the x, y, and values of the points
"""
outkx = aa['x'][::3]
outky = aa['x'][1::3]
outkz = aa['x'][2::3]
return outkx, outky, outkz
|
3be9e1938374a823a78aa6f8478c8cd02e4e9c50
| 690,829 |
def get_stimuli(task_type, sequence):
"""There is some variation in how tasks record session information.
Returns the list of stimuli for the given trial/sequence"""
if task_type == 'Copy Phrase':
return sequence['stimuli'][0]
return sequence['stimuli']
|
1c6cb3aa8433b6494a4035862df642da05d80269
| 345,443 |
import re
def is_re(s):
"""Return True if s is a valid regular expression else return False."""
try: re.compile(s)
except: return False
else: return True
|
c41e682218bab17f8209b6c93c74b9d868ff9be4
| 346,739 |
def merge_stage1(p1, p2):
"""Merge partial statistics."""
p1 = p1.add(p2, fill_value=0)
return p1
|
3dd3e026d58aadc00192ca90dc77e9d98c8689ef
| 524,566 |
import yaml
def get_filenames(filenames_file):
"""Extract the list of file that are required for test, from the input file.
Args:
filenames_file (str): the path of filenames file
Returns:
filenames (list): the filenames extracted from the input file.
"""
with open(filenames_file, 'r') as file:
yaml_content = yaml.safe_load(file)
filenames = []
for files in yaml_content.values():
filenames.extend(files)
return filenames
|
88ce0ab51e423c032569cc143ed18bfc5688070b
| 309,170 |
def set_ceid(country="US", language="en"):
"""Set the base country and language for the RSS Feed
Args:
country (str, optional): Country abbreviation. Defaults to "US".
language (str, optional): Country Language abbreviation. Defaults to "en".
Returns:
ceid (str): acceptable RSS feed query string.
"""
ceid = "?ceid={country}:{language}&hl={language}&gl={country}".format(
country=country, language=language
)
return ceid
|
ad0a008942eee99da95770031e44479e6eb83b6f
| 522,499 |
def graph_return(resp, keys):
"""Based on concepts of GraphQL, return specified subset of response.
Args:
resp: dictionary with values from function
keys: list of keynames from the resp dictionary
Returns:
the `resp` dictionary with only the keys specified in the `keys` list
Raises:
RuntimeError: if `keys` is not a list or tuple
"""
if not (len(keys) and isinstance(keys, (list, tuple))):
raise RuntimeError(f'Expected list of keys for: `{resp.items()}`, but received `{keys}`')
ordered_responses = [resp.get(key, None) for key in keys]
return ordered_responses if len(ordered_responses) > 1 else ordered_responses[0]
|
72cc27e97a53c2533b02f99a4bba8db8a57dc430
| 217,931 |
def state_value(state, address, init=0, end=15):
"""
init and end are included on the desired slice
"""
if state is None:
return 0
binary = format(state[address], '016b')
r_init = len(binary)-1-init
r_end = len(binary)-1-end
kBitSubStr = binary[r_end: r_init+1]
return int(kBitSubStr, 2)
|
c0c1ff7a77ed8b0eac48fbad3fd0e7d3cac16132
| 280,352 |
def hash_copy(space, w_res):
""" Copy hashing context"""
return w_res.deepcopy()
|
7f06334029d2ec3df4d5cdbd682e372f9adaed1d
| 372,815 |
def prettify_date(date_string):
"""
This function receives a string representing a date, for example 2018-07-28T10:47:55.000Z.
It returns the same date in a readable format - for example, 2018-07-28 10:47:55.
"""
date_string = date_string[:-5] # remove the .000z at the end
date_prettified = date_string.replace("T", " ")
return date_prettified
|
43dcbfbc73e7efbbf607e57c7f08a2322d8c7958
| 545,063 |
def format_num(num) -> str:
"""
Examples:
format_num(10000) -> 10,000
format_num(123456789) -> 123,456,789
:param num:
:return:
"""
num = str(num)
ans = ''
for i in range(len(num)-3, -4, -3):
if i < 0:
ans = num[0:i+3] + ans
else:
ans = ',' + num[i:i+3] + ans
return ans.lstrip(',')
|
a6e4059f81edd0cc1afa55eacd7440f4876513e0
| 52,607 |
def getChildElementsListWithSpecificXpath(parent, xpath):
"""
This method takes a parent element as input and finds all the children
containing specified xpath
Returns a list of child elements.
Arguments:
parent = parent element
xpath = a valid xml path value as supported by python, refer https://docs.python.org/2/library/xml.etree.elementtree.html
"""
child_elements = parent.findall(xpath)
return child_elements
|
8576d7236d2328962766bd60946a38897a68471b
| 183,364 |
import math
def distance(point_a, point_b):
"""
Returns the distance between two points given as tuples
"""
x0, y0 = point_a
x1, y1 = point_b
return math.hypot(x0 - x1, y0 - y1)
|
d41cec3978ea62b3b93e1e64b1f1103bce88d231
| 670,544 |
def frange(start, final, increment):
"""Return equally spaced float numbers between two given values."""
numbers = []
while start < final:
numbers.append(start)
start += increment
return numbers
|
df6a34ca11e77b61a697887d46ba10f5813acd58
| 248,209 |
def diffmean(xl, yl):
"""Return the difference between the means of 2 lists."""
return abs(sum(xl) / len(xl) - sum(yl) / len(yl))
|
36a449f68311f6ec8b23698c9c9797501eb73240
| 660,150 |
def degrees_to_miles_ish(dist:float):
""" Convert degrees lat/lon to miles, approximately """
deg_lat = 69.1 # dist_lat_lon(42, 74, 43, 74)
deg_lon = 51.3 # dist_lat_lon(42, 73, 42, 74)
return dist * 60.2
|
f4485060dcba6821f479138f905afe6a008532d4
| 351,056 |
def barycentric_to_cartesian(bary, vertices):
"""
Compute the Cartesian coordinates of a point with given barycentric coordinates.
:param bary: The barycentric coordinates.
:param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the
space)).
:returns: The Cartesian coordinates vector.
:rtype: n-dimensional vector
"""
return vertices[0] * bary[0] + vertices[1] * bary[1] + vertices[2] * bary[2]
|
3576f93d190ef52669a0ba80483dea88c75696ac
| 32,740 |
def time_shift(x, shift):
"""Shift a series by a specified amount"""
xshift = x.copy()
if shift > 0:
xshift[shift:] = x[0:-shift]
elif shift < 0:
xshift[0:shift] = x[-shift:]
elif shift == 0:
pass
return xshift
|
37487ec4557231f2d72f523b1bdbdc0824bea40d
| 202,630 |
def skeleton_df_to_swc(df, export_path=None):
"""
Create an SWC file from a skeleton DataFrame.
Args:
df:
DataFrame, as returned by :py:meth:`.Client.fetch_skeleton()`
export_path:
Optional. Write the SWC file to disk a the given location.
Returns:
``str``
"""
df = df.copy()
df['node_type'] = 0
df = df[['rowId', 'node_type', 'x', 'y', 'z', 'radius', 'link']]
swc = "# "
swc += df.to_csv(sep=' ', header=True, index=False)
if export_path:
with open(export_path, 'w') as f:
f.write(swc)
return swc
|
586476baedfe827be84939aa56e95e2afdb695b2
| 195,508 |
def htmlentities(text):
"""Escape chars in the text for HTML presentation
Args:
text (str): subject to replace
Returns:
str : result of replacement
"""
for lookfor, replacewith in [
("&", "&"),
(">", ">"),
("<", "<"),
("'", "'"),
('"', """),
]:
text = text.replace(lookfor, replacewith)
return text
|
7931032e152f1f971a80efddba0239507df101bc
| 190,594 |
def integer(i):
"""
Parses an integer string into an int
:param i: integer string
:return: int
"""
try:
return int(i)
except (TypeError, ValueError):
return i
|
702f2179eaf82bf1c004eeb7dbc72a0d44dfad5f
| 507,106 |
def is_in_ring(a):
""" Whether the atom is in a ring """
return a.IsInRing()
|
0f0ea015aa4d91ea94d25affd4a937037a0f4ed0
| 579,364 |
def GetPDFMultiByteInt(s, i, fieldlen):
"""Get a multibyte int from a string of bytes
Args:
s: string of bytes
i: int, offset in s to start getting the result
fieldlen: int, how many bytes to get
Returns:
int: accumulated multibyte value (high order byte first in s)
"""
ans = 0
for k in range(i, i + fieldlen):
ans = ans * 256 + ord(s[k])
return (ans, i + fieldlen)
|
2f8021a4a4ff276409a1cfbf37b73d664fb338f5
| 323,564 |
def tlbr2ltwhcs(boxes, scores):
"""
Top-Left-Bottom-Right to Left-Top-Width-Height-Class-Score
"""
new_boxes = []
for box, score in zip(boxes, scores):
new_boxes.append([box[1], box[0], box[3] - box[1], box[2] - box[0], 0, score])
return new_boxes
|
d74c2c99f84bdfa3f1bffbbbf2b5a6c7bf607c56
| 442,717 |
import csv
def load_data(path, delimeter=','):
"""
Reads the data from a CSV file
Skips lines starting with #
Arguments:
path - path of the file to read
(optional) delimeter - delimeter between columns
Returns: Data in form of a 2D array
"""
data = []
with open(path, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=delimeter, quotechar='|')
for row in reader:
if len(row) > 0 and not row[0].startswith('#'):
data.append([float(r) for r in row])
return data
|
2fd0f0a2e6f4d3ef0c83fd818bd900d76455ae4e
| 135,294 |
import pickle
def choices_from_pickle(paths):
"""
Get conformer choices as RDKit mols from pickle paths.
Args:
paths (list[str]): conformer path for each of the two
molecules being compared.
Returns:
fp_choices (list[list[rdkit.Chem.rdchem.Mol]]):
RDKit mol choices for each of the two molecules.
"""
fps_choices = []
for path in paths:
with open(path, "rb") as f:
dic = pickle.load(f)
choices = [sub_dic["rd_mol"] for sub_dic in dic["conformers"]]
for mol in choices:
mol.SetProp("_Name", "test")
fps_choices.append(choices)
return fps_choices
|
5004e7968aeb64c0e37afd2bf595a504387c0a28
| 227,357 |
def empty(piece):
"""To check if given piece is empty
Necessary because an empty position can be both ' ' or '* ' """
if piece == ' ' or piece == '* ':
return True
return False
|
e2dbd54f64e169bba77f13921a53e711f36c4643
| 463,356 |
def config_database_option(config, key, dbname=None, getbool=False):
""" Get database-level config option """
if config is None:
return None
if dbname is None:
return None
section = 'database "{}"'.format(dbname)
if not section in config:
return None
return config[section].get(key, None) if not getbool else config[section].getboolean(key)
|
fd9f42c06ada9fd1a7f846da6e43ddac71e271fd
| 572,091 |
def get_float_formatter_func(precision=None, thousands_sep=False,
zero_string='0'):
"""
Returns a function that gives ``zero_string`` if the float is 0, else
a string with the given digits of precision.
"""
def float_formatter(f):
if isinstance(f, str):
return f
if thousands_sep:
ts = ','
else:
ts = ''
if precision is not None:
prec = '.' + str(precision) + 'f'
elif float(f).is_integer():
prec = '.0f'
else:
prec = ''
fmt = '{:' + ts + prec + '}'
try:
if f == 0:
return zero_string
elif (precision is not None) or (thousands_sep is not None):
return fmt.format(f)
else:
return str(f)
except ValueError:
return f
return float_formatter
|
3e0ff275c1c658710c6363c1dc32e111fdc65483
| 97,174 |
def msg_to_bytes(msg, standard="utf-8"):
"""Encode text to bytes."""
return bytes(msg.encode(standard))
|
634b1482c61773601a899bdd42c055960c03fc3b
| 395,779 |
def get_symmetric_quantization_range_and_scale(activation_is_signed: bool,
activation_n_bits: int,
activation_threshold: float):
"""
Calculates lower and upper bounds on the quantization range, along with quantization scale,
for symmetric quantization (used for the symmetric and power-of-two quantizers),
according to whether the quantization is signed or unsigned.
Args:
activation_is_signed: Whether the quantization is signed or not.
activation_n_bits: Number of bits to use for quantization.
activation_threshold: The quantization threshold.
Returns: range lower bound, range upper bound and quantization scale.
"""
if activation_is_signed:
min_value = -2 ** (activation_n_bits - 1)
max_value = 2 ** (activation_n_bits - 1) - 1
scale = activation_threshold / 2 ** (activation_n_bits - 1)
else:
min_value = 0
max_value = (2 ** activation_n_bits) - 1
scale = activation_threshold / 2 ** activation_n_bits
return min_value, max_value, scale
|
d3a42550d01b51c5e685f9cf8271e48ceb4b8b80
| 270,208 |
import torch
def softplus_inv(x, eps=1e-6, threshold=20.):
"""Compute the softplus inverse."""
y = torch.zeros_like(x)
idx = x < threshold
# We deliberately ignore eps to avoid -inf
y[idx] = torch.log(torch.exp(x[idx]) - 1)
y[~idx] = x[~idx]
return y
|
a03a0eae38e4b23c32dd6264257cba3d9ba8dbc4
| 154,098 |
import string
import random
def generate_password(length=12, ascii_lower=True, ascii_upper=True, punctuation=True,
digits=True, strip_ambiguous=False, strip_dangerous=True):
"""
This function will return a password consisting of a mixture of lower
and upper case letters, numbers, and non-alphanumberic characters
in a ratio defined by the parameters.
:param length: Length of generated password.
:type length: int
:param ascii_lower: Whether to include ASCII lowercase chars.
:type ascii_lower: bool
:param ascii_upper: Whether to include ASCII uppercase chars.
:type ascii_upper: bool
:param punctuation: Whether to include punctuation.
:type punctuation: bool
:param strip_ambiguous: Whether to remove easily-confused (LlOo0iI1) chars
from the password.
:type strip_ambiguous: bool
:param strip_dangerous: Whethr to remove some of the more 'dangerous' punctuation
(e.g. quotes) from the generated password.
:type strip_dangerous: bool
:returns: The generated password.
:rtype: str
"""
pool = []
if ascii_lower:
pool.extend(string.ascii_lowercase)
if ascii_upper:
pool.extend(string.ascii_uppercase)
if punctuation:
pool.extend(string.punctuation)
if digits:
pool.extend(string.digits)
if strip_ambiguous:
pool = set(pool) - set("LlOo0iI1")
pool = list(pool) # Turn it back into a list since random.choice() needs indexing.
if strip_dangerous:
pool = set(pool) - set(r'"\'`')
pool = list(pool)
if not pool:
raise ValueError("No character classes enabled for password generation.")
# Generate the total number of characters for the password
return ''.join([random.choice(pool) for _i in range(length)])
|
05195875abedab2f2c8998c675bc08dd4123ef53
| 339,386 |
import re
def get_categories_from_text(edit):
"""Return the categories contained in a given wikitext."""
cat_pattern = r"\[\[Category:(?P<cat>.+?)(\|.*?)?\]\]"
return [x[0] for x in re.findall(cat_pattern, edit)]
|
81237b0e5c9c3ac7f7db3f3ea84e673576859950
| 182,292 |
import json
def load_input_blocks(path):
""" Load stored blocks from disk e.g.,
load_input_blocks('./testdata/btc_blocks_json_samples/300000--300007')
"""
with open(path) as json_file:
blks = json.load(json_file)
return blks
|
8b6c75411e4dc7e2d429ee57471f06fc3af6fdb0
| 597,758 |
def heading(text, level):
"""
Return a ReST heading at a given level.
Follows the style in the Python documentation guide, see
<https://devguide.python.org/documenting/#sections>.
"""
assert 1 <= level <= 6
chars = ("#", "*", "=", "-", "^", '"')
line = chars[level] * len(text)
return "%s%s\n%s\n\n" % (line + "\n" if level < 3 else "", text, line)
|
43ef5bc1fdfb6c34279e9aa74ac420c1b1110e3a
| 657,939 |
import math
def custom_percent(value):
"""Display a number with a percent after it, or a dash if not valid"""
if math.isnan(value):
return "-"
return str(value) + "%"
|
4f170cf1d4b4d74dfaa993ca996bb8ed0cc51259
| 342,097 |
import itertools
def construct_game_queries(base_profile, num_checkpts):
"""Constructs a list of checkpoint selection tuples to query value function.
Each query tuple (key, query) where key = (pi, pj) and query is
(p1's selected checkpt, ..., p7's selected checkpt) fixes the players in the
game of diplomacy to be played. It may be necessary to play several games with
the same players to form an accurate estimate of the value or payoff for each
player as checkpts contain stochastic policies.
Args:
base_profile: list of selected checkpts for each player, i.e.,
a sample from the player strategy profile ([x_i ~ p(x_i)])
num_checkpts: list of ints, number of strats (or ckpts) per player
Returns:
Set of query tuples containing a selected checkpoint index for each player.
"""
new_queries = set([])
num_players = len(base_profile)
for pi, pj in itertools.combinations(range(num_players), 2):
new_profile = list(base_profile)
for ai in range(num_checkpts[pi]):
new_profile[pi] = ai
for aj in range(num_checkpts[pj]):
new_profile[pj] = aj
query = tuple(new_profile)
pair = (pi, pj)
new_queries.update([(pair, query)])
return new_queries
|
1ffa16ebfd04f468cbde6db264ba33373c1b1d05
| 640,089 |
def SignalSegmentation(X,YSimulated,Cut):
""" Function to split the X and the YEstimated in two slices
according to the Cut point.
Parameters
----------
X: Array of int32
Array containing the abscissa's values that are going to be segmented
YEstimatedy: List
List containing the signal's values that are going to be segmented
Cut: int
Integer that informs the point in X where the signal will be splited
Returns
-------
XEnd: Array of int32
Array containing the points of X that are superior than Cut
YEnd: List
List containing the points of the YEstimated which correspond to a
point of X superior than Cut
"""
XEnd=X[slice(Cut,450,1)]
YEnd=YSimulated[slice(Cut,450,1)]
return [XEnd,YEnd]
|
85ede2094edfacf8fec6dcfbbf816fc980107283
| 184,059 |
from typing import Iterable
def intersection(sets: Iterable[set]):
"""Intersection of sets"""
try:
s = next(sets := iter(sets))
except StopIteration:
return set()
else:
s = set(s)
for x in sets:
s.intersection_update(x)
return s
|
c2fc164516296b87788ae065d787932b914bd489
| 570,576 |
def strip_strings(value):
"""
Strip excess whitespace, on strings, and simple lists
using recursion
"""
if (value == None):
return None
elif (type(value) == list):
# List, so recursively strip elements
for i in range(0, len(value)):
value[i] = strip_strings(value[i])
return value
else:
try:
value = value.replace(" ", " ")
return value.strip()
except(AttributeError):
return value
|
c861855c2db989fe01bcf1f9ec2badd9d2c91b55
| 409,989 |
def get_module_id_from_event(event):
"""
Helper function to get the module_id from an EventHub message
"""
if "iothub-connection-module_id" in event.message.annotations:
return event.message.annotations["iothub-connection-module-id".encode()].decode()
else:
return None
|
e183824fff183e3f95ef35c623b13245eb68a8b7
| 2,828 |
import random
def random_int(min, max):
"""
Get random integer
:param min: Minimum value (included)
:param max: Maximum value (included)
:return: Random integer
"""
return random.randint(min, max)
|
dd0b70b0a7a3957a2bcc4200eb03a28306886dc7
| 94,619 |
def urljoin(*args):
"""Join a set of strs for URL creation
This method is commonly used by appending a URL to the `ENDPOINT`
Parameters
----------
str
URL names to join
Returns
-------
str
The joined URL
"""
return '/'.join(map(lambda a: a.strip('/'), args))
|
67f7bc2f6512253e977b54bbf53cad375a543ded
| 447,709 |
def create_user_lookup(users_json):
"""Create a dictionary containing user profiles keyed to Canvas user ID.log_status.
We'll need this lookup user names for submission commenters.
users_json -- JSON collection of user profiles, as returned by load_users_json().
Returns dictionary.
"""
lookup_dict = {}
for user in users_json:
lookup_dict[user['id']] = user
return lookup_dict
|
69882d1491a44cad3cbd7d11e1b4e0c021b28f59
| 383,821 |
def textfile_contains(filename, marker):
"""
Return True if a textfile contains a string.
"""
try:
with open(filename, 'r', encoding='utf8') as file:
text = file.read();
if marker in text:
return True
except Exception as e:
print(e)
return False
|
c3cc966441fb65c9b5fbc0efdf56ba0f842f0565
| 111,642 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.