content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def frange(range_def, sep=','):
"""
Return the full, unabbreviated list of ints suggested by range_def.
This function takes a string of abbreviated ranges, possibly
delimited by a comma (or some other character) and extrapolates
its full, unabbreviated list of ints.
Parameters
----------
range_def : str
The range string to be listed in full.
sep : str, default=','
The character that should be used to delimit discrete entries in
range_def.
Returns
-------
res : list
The exploded list of ints indicated by range_def.
"""
res = []
for item in range_def.split(sep):
if '-' in item:
a, b = item.split('-')
a, b = int(a), int(b)
lo = min([a, b])
hi = max([a, b])
ints = range(lo, hi+1)
if b <= a:
ints = list(reversed(ints))
res.extend(ints)
else:
res.append(int(item))
return res
|
574930029d0ce1fedeea92b1c74c8f87799548a5
| 276,235 |
def digits_to_skip(distinct_letter_pairs: int) -> int:
"""The number of letters which can be skipped (i.e. not being incremented
one by one) depending on the number of distinct letter pairs present."""
if distinct_letter_pairs == 0:
# If no letter pair exists already, we know at least one must be
# among the last two digits. Hence we can set those to 0 and continue
# from there.
return 2
# No optimization possible, have to start at the end.
return 0
|
fa007f80d3396a78de242e989e32d573f5ce9424
| 413,204 |
from typing import Union
def try_num(s: str) -> Union[str, float, int]:
"""Attempt to convert a string to an integer. If that fails, try a float.
If that fails, leave it as a string and return it."""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return s
|
5b0cb3533c7dabafec4abbbf0c7479981433fb51
| 323,063 |
import requests
def fetch_image(session: requests.Session, folder, image):
"""Fetch an image from TibiaWiki and saves it the disk.
Parameters
----------
session: :class:`request.Session`
The request session to use to fetch the image.
folder: :class:`str`
The folder where the images will be stored locally.
image: :class:`WikiImage`
The image data.
Returns
-------
:class:`bytes`
The bytes of the image.
"""
r = session.get(image.file_url)
r.raise_for_status()
image_bytes = r.content
with open(f"images/{folder}/{image.file_name}", "wb") as f:
f.write(image_bytes)
return image_bytes
|
582e1a58e62d517656d61a55be7f0c7e575e9be7
| 441,323 |
import torch
def computeKLD(mean_a_flat, logvar_a_flat, device, mean_b_flat=0.0,
logvar_b_flat=1.0):
"""Compute the kullback-leibler divergence between two Gaussians.
Args:
mean_a_flat: mean of the Gaussian a.
logvar_a_flat: Log variance of the Gaussian a.
mean_b_flat: mean of the Gaussian b.
logvar_b_flat: Log variance of the Gaussian b.
device:
Returns:
LKD between two gausian with given parameters.
"""
# see Appendix B from VAE paper:
# Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
# https://arxiv.org/abs/1312.6114
logvar_b_flat = torch.log(torch.tensor(logvar_b_flat).to(device))
mean_b_flat = torch.tensor(mean_b_flat).to(device)
kl = None
if kl is None:
var_a_flat = torch.exp(0.5 * logvar_a_flat) ** 2
var_b_flat = torch.exp(0.5 * logvar_b_flat) ** 2
kl = - 0.5 * torch.sum(
1. - (var_a_flat + (mean_a_flat - mean_b_flat) ** 2) / var_b_flat
+ logvar_a_flat - logvar_b_flat
)
return kl
|
3c58f945fd003093b55b32a11a8ceb4f4577e368
| 153,410 |
def num_articles(data):
""" Find the number of unique articles in data. """
art = set()
for row in data:
art.add(row[1])
return len(art)
|
7900ffe4f1e1a156ed15b3368cea1faa3b9d3671
| 461,773 |
import functools
def cached_property(fn, *args, **kwargs):
"""
Decorator to make a function a "cached property".
This means that it is a property whose return value is cached after the
first time it is called.
Args:
fn: The function to be made a cached property
*args: Any args for the function
**kwargs: Any kwargs for the function
Returns:
function
"""
return property(functools.lru_cache()(fn, *args, **kwargs))
|
142f240297c9bc2a74b19411dac9c8dc4efa166d
| 491,611 |
from typing import Tuple
from typing import List
def remove_gaps(seq: str) -> Tuple[str, List[int]]:
"""Remove gaps in the given sequence."""
seqout, idx = "", []
for i, char in enumerate(seq):
if char != "-":
seqout += char
idx.append(i)
return seqout, idx
|
201c4d572fa456a46286bc0c6192bc57a3bcec9e
| 353,423 |
def grid_size(config):
""" Get size of grid. """
return int(round((config.radius * 2 + 1) / config.resolution))
|
2e9e72a384b5ae9670fb5752ce80b8d318cce60d
| 364,346 |
def is_subpath(spath, lpath):
"""
check the short path is a subpath of long path
:param spath str: short path
:param lpath str: long path
"""
if lpath.startswith(spath):
slen, llen = len(spath), len(lpath)
return True if slen == llen else lpath[slen] == '/'
return False
|
1ee1d6845d24191282d3546e04b1fa6ce08bcb2f
| 473,583 |
def to_mtcsv(data, path=None, decimals=5):
"""
Save a downloaded ticks dataframe as a csv with a optimized format to be
imported by MetaTrader.
:param data: pandas dataframe with Ask and Bid columns
:param path: file path to save
:param decimals: number of decimals to save
:return: str if path is None
"""
csv = data[['Ask', 'Bid']].to_csv(path, header=False,
float_format='%.{}f'.format(decimals))
return csv
|
48f733878bbd3da6f05dfdd38082fc2c425b690a
| 520,862 |
def sec_to_time(sec):
""" Returns the formatted time H:MM:SS
"""
mins, sec = divmod(sec, 60)
hrs, mins = divmod(mins, 60)
return f"{hrs:d}:{mins:02d}:{sec:02d}"
|
cffe3060a1a98f3dbba53da4666175994c606a31
| 50,002 |
def ez_user(client, django_user_model):
"""A Django test client that has been logged in as a regular user named "ezuser",
with password "password".
"""
username, password = "ezuser", "password"
django_user_model.objects.create_user(username=username, password=password)
client.login(username=username, password=password)
return client
|
20e54603e8154cbf9f6c7e0cbd06a78627beecd0
| 21,077 |
from datetime import datetime
def within_time_range(start_time, end_time, now_time=None):
# pylint: disable=unused-variable
"""Check whether time is in a specific time range."""
now_time = now_time or datetime.utcnow().time()
if start_time < end_time:
return start_time <= now_time <= end_time
return now_time >= start_time or now_time <= end_time
|
0657d43048ef4c9e1a7b98a3a3e3822bc4994be8
| 594,601 |
def wrangle_counties(df):
"""
Wrangle the data to group by county.
Parameters:
-----------
df -- (pandas DataFrame) Cleaned data in a dataframe.
Returns the data grouped by county in a pandas df.
"""
# Group and aggregate the data by Counties
counties_grouped = df.groupby(['county', 'county_id'], as_index=False)
wine_counties = counties_grouped.agg({'points': ['mean'],
'price': ['mean'],
'value_scaled': ['mean'],
'description': ['count']})
wine_counties.columns = wine_counties.columns.droplevel(level=1)
wine_counties = wine_counties.rename(columns={"county": 'County',
"county_id": 'County ID',
"description": "Num Reviews",
"points": 'Ave Rating',
"price": 'Ave Price',
"value_scaled": 'Ave Value'})
return wine_counties
|
8d9aac0cd233db1fa03bc0ccbbb9cbf5cf953671
| 175,815 |
def parse_fasta( f ):
"""Parses a fasta file
f can either be a file name or a file handle.
Returns a dictionary mapping keys to sequences
Not optimised for large files
"""
if str == type( f ):
f = open( f, 'r' )
results = { }
key = None
for line in f:
line = line.rstrip( '\r\n' )
if line.startswith( '>' ):
key = line.lstrip( '> ' )
results[ key ] = ''
else:
results[ key ] += line
return results
|
da06dcc8a5ad75d774228e222ef0c0e085a05d27
| 571,910 |
def calculate_density_after_time(densities, time_0, time_explosion):
"""
scale the density from an initial time of the model to the time of the explosion by ^-3
Parameters:
-----------
densities: ~astropy.units.Quantity
densities
time_0: ~astropy.units.Quantity
time of the model
time_explosion: ~astropy.units.Quantity
time to be scaled to
Returns:
--------
scaled_density
"""
return densities * (time_explosion / time_0) ** -3
|
024f11517a4fcce14a69eed3705a485f1d8940e3
| 361,534 |
def moeda(preco=0, moeda='R$'):
"""
-> Formata um preco com o padrao real brasileiro
:param preco: o valor a ser formatado
:param moeda: a sigla da moeda
:return: retorna uma string formatada de acordo com o padrao monetario do Brasil
"""
return f'{moeda}{preco:.2f}'.replace('.', ',')
|
6ce45b3c045854fe2967532f78021b7dec37a969
| 170,232 |
from datetime import datetime
def parse_windows_timestamp(qword):
"""see http://integriography.wordpress.com/2010/01/16/using-phython-to-parse-and-present-windows-64-bit-timestamps"""
return datetime.utcfromtimestamp(float(qword) * 1e-7 - 11644473600)
|
de21a39f3000049f09b7560e4cddedea8e8a332f
| 123,724 |
def search_content(content_df, content: str):
"""Search with content.
Args:
content_df (DataFrame): Table including content element.
content (str): Content name as a query.
Returns:
(DataFrame): Contents DataFrame including a query content.
"""
mask = content_df["content"].apply(lambda x: content == x)
return content_df[mask]
|
1e104dfc72af098f903dfc5369368fcd76d10299
| 438,526 |
import re
def remove_all_parenthesis_words(text):
"""Return text but without any words or phrases in parenthesis:
'Good morning (afternoon)' -> 'Good morning' (so don't forget
leading spaces)"""
pattern = r"\s*\([\w\.]+\)"
sub_ = re.sub(pattern, "", text)
return sub_
|
b5b045344cfe113dbd0a254871ca5a3876de11f3
| 537,544 |
import re
def available_space(ctx, device):
"""
Determine the available space on device such as bootflash or stby-bootflash:
:param ctx:
:param device: bootflash / stby-bootflash: / harddisk: / stby-harddisk:
:return: the available space
"""
available = -1
output = ctx.send('dir ' + device)
m = re.search(r'(\d+) bytes free', output)
if m:
available = int(m.group(1))
return available
|
2d831e644ed5d843b80397472e2cab65fccced1b
| 680,657 |
def read_tles(tle_path):
"""
Convert TLE text files in a given directory to a list of TLEs.
Parameters
----------
tle_dir : str
Path to the directory containing TLE .txt files.
Returns
-------
sats : List of lists.
Each internal list has the 3 lines of a TLE as its elements.
"""
tles = [line.rstrip() for line in open(tle_path)]
sats = [tles[3*i:(3*i+3)] for i in range(len(tles)//3)]
return sats
|
aa8aae9ec1eb286abf5fd5b4eb1474e807d3f34d
| 641,557 |
def parse_input(input):
"""Seperates the interface input from the user into the name and number ex.
Gi1/0/1 becomes ('Gi', '1/0/1') or GigabitEthernet1/0/1 becomes ('GigabitEthernet', '1/0/1')"""
interface_name = ''
interface_number = ''
x = 0
for letter in input:
if letter.isdigit():
interface_number = input[x:]
break
else:
interface_name += letter
x += 1
return interface_name.strip(' '), interface_number.strip(' ')
|
7c3cc5d759ce1235c9a1d5258c3981d91fddc5dd
| 70,264 |
def average_top_runs(speed_df,rank_column,weapon_column='Weapon',time_column='Time (s)',top_pos=1):
"""
Returns a DataFrame with the average top speedrun times for each weapon class,
as ordered by the 'rank_column' column.
This will take the 'top_pos' times into the average. For top_pos=1, that's
only the fastest time, top_pos=2 means it's the fastest 2 times, etc.
Return value is ordered by time_column, going from fastest to slowest.
"""
#Pick out the top runs
avg = speed_df[speed_df[rank_column]<=top_pos]
#Group by weapon type and get the mean values
avg = avg.groupby(weapon_column).mean().reset_index()
#Simplify time values
avg['Time (s)'] = avg['Time (s)'].apply(lambda x: round(x,2))
#Sort weapons
avg = avg.sort_values('Time (s)',ascending=True)
#Update index to correspond to rankings (ie start at 1 rather than 0)
avg = avg.reset_index()
avg.index += 1
#Return
return avg
|
ff7bd304cf2987f34beba6989d684c9e058f949c
| 327,968 |
def find_delims(s, delim='"',match=None):
"""find matching delimeters (quotes, braces, etc) in a string.
returns
True, index1, index2 if a match is found
False, index1, len(s) if a match is not found
the delimiter can be set with the keyword arg delim,
and the matching delimiter with keyword arg match.
if match is None (default), match is set to delim.
>>> find_delims(mystr, delim=":")
>>> find_delims(mystr, delim='<', match='>')
"""
esc = "\\"
if match is None:
match = delim
j = s.find(delim)
if j > -1 and s[j:j+len(delim)] == delim:
p, k = None, j
while k < j+len(s[j+1:]):
k = k+1
if s[k:k+len(match)] == match and p != esc:
return True, j, k+len(match)-1
p = s[k:k+1]
return False, j, len(s)
|
c99012aed8e7ec1a42a93d7c59e2c9b3bce1f9b4
| 509,423 |
def error404(e):
"""
404 error handler.
"""
return ''.join([
'<html><body>',
'<h1>D20 - Page Not Found</h1>',
'<p>The only endpoint available on this entropy micro-service is <a href="/api/entropy">/api/entropy</a>.</p>',
'<p>For more information including the complete source code, visit <a href="https://github.com/AgalmicVentures/D20">the D20 repository</a>.</p>',
'</body></html>',
]), 404
|
35ab121b88e84295aaf97e2d60209c17acffd84d
| 21,607 |
def keep(pred):
"""Keep only items that do not return None when pred is called. This is for
functions that only return values in certain cases, or which return None
for their false value."""
def generator(coll):
for item in coll:
res = pred(item)
if res is not None:
yield res
return generator
|
a642fb9efc7719c3453c74ab47e1921f2efaf1e3
| 227,574 |
import json
def to_bundle(sparkSession, dataset, resourceTypeUrl):
"""
Converts a dataset of FHIR resources to a bundle containing those resources.
Use with caution against large datasets.
:param sparkSession: the SparkSession instance
:param dataset: a DataFrame of encoded FHIR Resources
:param resourceTypeUrl: the type of the FHIR resource to extract
(Condition, Observation, etc, for the base profile, or the URL of the structure definition)
:return: a JSON bundle of the dataset contents
"""
jvm = sparkSession._jvm
json_string = jvm.com.cerner.bunsen.stu3.python.Functions.toJsonBundle(dataset._jdf,
resourceTypeUrl)
return json.loads(json_string)
|
0a0a6b38be939b7e3ebea4fcd60ab8c1ddfc748c
| 515,511 |
import re
import string
def format_counter_name(s):
"""
Makes counter/config names human readable:
FOOBAR_BAZ -> "Foobar Baz"
foo_barBaz -> "Foo Bar Baz"
"""
def splitCamels(s):
""" Convert "fooBar" to "foo bar" """
return re.sub(r'[a-z][A-Z]',
lambda x: x.group(0)[0] + " " + x.group(0)[1].lower(),
s)
return string.capwords(re.sub('_', ' ', splitCamels(s)).lower())
|
15196d7ec3a435b0ab8f4d6c65002b991e964318
| 192,313 |
def generate_coordinates() -> list:
"""Generates the list of coordinates to populate."""
coordinates = []
for x in range(0, 160):
for y in range(0, 90):
coordinates.append((x, y))
return coordinates
|
68c17f6d5390e966b713af8ba58807ee27519748
| 547,021 |
def is_pos_pow_two(x: int) -> bool:
"""
Simple check that an integer is a positive power of two.
:param x: number to check
:return: whether x is a positive power of two
"""
if x <= 0:
return False
while (x & 1) == 0:
x = x >> 1
return x == 1
|
6bce29e9f06d7b1393f9042894644e0ede68b0e9
| 238,201 |
def udir(obj):
"""
udir : user-dir
Filters all magic methods and private attributes from a dir() call
"""
return [attribute for attribute in dir(obj) if "__" not in attribute]
|
2f627d603b8db46af16f89d36b1aae310ec324f3
| 364,711 |
import torch
def reparametrize(
x_min, x_max, y_min, y_max, reparametrization_h, reparametrization_w,
inplace=False, inverse=False):
"""
If `inverse is False`, scale module's parameters so that their range becomes
approximately [-1; 1]. Otherwise, do the inverse operation.
This hack is unfortunately needed for the parameters to work with variants of SGD.
Without this "reparametrization", box sizes' gradients will be extremely small.
If `not inplace`, returns 4 new tensors, otherwise modifies the given ones.
"""
scalar_h = reparametrization_h if inverse else (1 / reparametrization_h)
scalar_w = reparametrization_w if inverse else (1 / reparametrization_w)
with torch.no_grad():
if inplace:
x_min *= scalar_h
x_max *= scalar_h
y_min *= scalar_w
y_max *= scalar_w
else:
return x_min * scalar_h, x_max * scalar_h, y_min * scalar_w, y_max * scalar_w
|
a2a00117fcfa29b5f95f9237a7b6012706f8a44c
| 400,399 |
def norm(arr):
""" Demean and normalize a given input to unit std. """
if arr.ndim == 1:
arr -= arr.mean()
arr /= arr.std()
else:
arr -= arr.mean(axis=-1, keepdims=True)
arr = (arr.T / arr.std(axis=-1)).T
return arr
|
7d36ebd6aa9162e99db078b436a48604368c1f10
| 468,849 |
def webhook_request(
response_id,
session,
intent_id,
text,
title,
subtitle,
image_url,
buttons,
payload,
quick_replies
):
"""Return a sample WebhookRequest dictionary."""
project_id = 'PROJECT_ID'
return {
'responseId': response_id,
'queryResult': {
'queryText': 'Hi',
'parameters': {},
'allRequiredParamsPresent': True,
'fulfillmentText': 'Hello! How can I help you?',
'fulfillmentMessages': [
{'text': {'text': [text]}},
{'image': {'imageUri': image_url}},
{
'card': {
'title': title,
'subtitle': subtitle,
'imageUri': image_url,
'buttons': buttons
}
},
{'payload': payload},
{'quickReplies': {'quickReplies': quick_replies}}
],
'outputContexts': [
{
'name': f'projects/{project_id}/agent/sessions/{session}/contexts/__system_counters__', # noqa: E501
'parameters': {
'no-input': 0,
'no-match': 0
}
}
],
'intent': {
'name': f'projects/{project_id}/agent/intents/{intent_id}',
'displayName': 'Default Welcome Intent'
},
'intentDetectionConfidence': 1,
'languageCode': 'en'
},
'originalDetectIntentRequest': {
'payload': {},
},
'session': f'projects/{project_id}/agent/sessions/{session}'
}
|
e65c637b45e65ce2b971fa2c1d0074b335f90a83
| 582,013 |
import math
def get_phase_law(N, d, wavelength, phi):
"""Computes a phase law given N (number of elements),
d (spacing between elements in m), wavelength (in m)
and phi (beam steering angle).
"""
phase_law = [];
for n in range(N):
phase_law.append(-2 * math.pi * n * d / wavelength * math.sin(math.radians(phi)));
return phase_law;
|
7a6be2d6b3ff4b583e47f114e8cf15a566dc5864
| 590,744 |
def match_i(instance1,instance2):
"""Return True if given instances match, i.e., contain the same vertex and edge object instances."""
return (instance1.vs == instance2.vs) and (instance1.es == instance2.es)
|
62000889756b79d07932e93b7877792c23f4b89c
| 278,570 |
import random
def randomize_list_of_words(input_words):
"""
Returns the same list of words in a random order.
Input:
-input_words list of strings
Output:
-output_words list of strings
"""
output_words = []
random_order = random.sample(range(len(input_words)), len(input_words))
for i in random_order:
output_words.append(input_words[i])
return output_words
|
cbe19aa8cddddedcb439245cfc9ad67e20d7e382
| 627,536 |
import re
import functools
def rgetattr(obj, attr, *args):
"""
Recursively get an attribute. This is useful for nested subobjects or chained properties.
Examples:
class A(object):
def __init__(self, a=0):
self.a = a
class B(object):
def __init__(self, b):
self.b = b
obj = B(b=A())
rgetattr(obj, 'b.a') # this will access obj.b.a and thus print 0
References:
- https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-subobjects-chained-properties
"""
def _getattr(obj, attr):
search = re.search("\[.*\]", attr) # check for square brackets
if search is not None:
begin_idx, last_idx = search.span()
a = getattr(obj, attr[:begin_idx], *args)
idx = last_idx
while idx != begin_idx:
idx = attr.find(']', begin_idx)
s = attr[begin_idx+1:idx]
if re.match("[0-9]+", s): # check if numeric string
if ':' in s: # check for ':', i.e. slice
sl = slice(*[{True: lambda n: None, False: int}[x == ''](x)
for x in (s.split(':') + ['', '', ''])[:3]])
a = a[sl]
else: # if no slice
a = a[int(s)]
else: # string for dictionary
a = a[s]
begin_idx = idx
return a
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.'))
|
0126f91efb4e34ef27d474119374b148feeb1ec6
| 538,743 |
def make_json_ok_response(data):
"""Returns OK response with json body"""
return data
|
69a855234725b2773682628728ada1a2a1817482
| 505,304 |
def get_bit(byte, bit_num):
""" Return bit number bit_num from right in byte.
@param int byte: a given byte
@param int bit_num: a specific bit number within the byte
@rtype: int
>>> get_bit(0b00000101, 2)
1
>>> get_bit(0b00000101, 1)
0
"""
return (byte & (1 << bit_num)) >> bit_num
|
4f25c4ccdc4c3890fb4b80d42d90bfb94d6799c3
| 8,985 |
from functools import reduce
def concat(l):
"""
>>> concat([[0, 1], [2], [3, 4, 5]])
[0, 1, 2, 3, 4, 5]
"""
return reduce(list.__add__, l, [])
|
a746ad6283466bbd747db4ff2a5ce4e4bedbb0c2
| 430,465 |
def format_params(params):
""" Casts the hyperparameters to the required type and range.
"""
p = dict(params)
p['min_child_weight'] = p["min_child_weight"]
p['colsample_bytree'] = max(min(p["colsample_bytree"], 1), 0)
p['max_depth'] = int(p["max_depth"])
# p['subsample'] = max(min(p["subsample"], 1), 0)
p['gamma'] = max(p["gamma"], 0)
# p['reg_alpha'] = max(p["reg_alpha"], 0)
p['reg_lambda'] = max(p["reg_lambda"], 0)
return p
|
66c6440a6b88ce567ff49bc625e39c3a8ffd67b3
| 282,777 |
import json
def read_json(path):
"""Reads JSON from file.
Args:
path: the path to the JSON file
Returns:
a dict or list containing the loaded JSON
Raises:
ValueError: if the JSON file was invalid
"""
try:
with open(path, "rt") as f:
return json.load(f)
except ValueError:
raise ValueError("Unable to parse JSON file '%s'" % path)
|
dd29df960e2e3699119c3a0cafc256c29624e9cb
| 571,862 |
import shlex
def _parse_tags(tags: str):
"""Takes a string of whitespace seperated tags
and assigns them to a dict. Expects each tag to
be of the format 'tag_name:tag_value'
Args:
tags (str): The tags to parse
Returns:
dict: The parsed tags
"""
return dict(item.split(":") for item in shlex.split(tags))
|
ce907265c5a1706af6a79860abe4453878b3456e
| 81,503 |
def test_astore_model(session, cas_session, change_dir):
"""Ensure the register_sas_classification_model.py example executes successfully."""
# Mock up Session() to return the Betamax-recorded session
def Session(*args, **kwargs):
return session
change_dir('examples')
with open('register_sas_classification_model.py') as f:
# Remove Session import and set CAS session to Betamax-recorded CAS
# session
code = f.read().replace('from sasctl import Session', '')
code = code.replace(
"s = swat.CAS('hostname', 5570, 'username', 'password')", 's = cas_session'
)
# Exec the script.
exec(code)
|
9663ac8c9c1e599c12d9c70a3db4c7fbb39d3413
| 252,537 |
def compare_insensitive(a, b):
"""Compares insensitive if a contains b"""
if a is None or b is None:
return
return b.lower() in a.lower()
|
b60104f687df26dfb3a85923d6ba09aa41c3aa2e
| 131,739 |
def tier_count(count):
"""
If a tier quota is 9999, treat it as unlimited.
"""
if count == 9999:
return "Unlimited"
else:
return count
|
dc702e930377d1533fbacf434a2acd0ddfefc457
| 665,552 |
def element(a):
""" Return the element """
return a.GetSymbol()
|
d2e335aff22978da0ae4627c8cae25f6b80cd602
| 665,238 |
def fix_data(text):
"""Add BOS and EOS markers to sentence."""
if "<s>" in text and "</s>" in text:
# This hopes that the text has been correct pre-processed
return text
sentences = text.split("\n")
# Removing any blank sentences data
sentences = ["<s> " + s + " </s>" for s in sentences if len(s.strip()) > 0]
return " ".join(sentences)
|
b502784e9e8fa8875030730595dcaaae66e2f31b
| 28,083 |
def get_options(options):
"""
Get options for dcc.Dropdown from a list of options
"""
opts = []
for opt in options:
opts.append({'label': opt.title(), 'value': opt})
return opts
|
61df747bf10a08aff481c509fbc736ef406d006f
| 50,832 |
import random
def randChooseWeighted(lst):
"""Given a list of (weight,item) tuples, pick an item with
probability proportional to its weight.
"""
totalweight = sum(w for w,i in lst)
position = random.uniform(0, totalweight)
soFar = 0
# We could use bisect here, but this is not going to be in the
# critical path. If it is, oops.
for w,i in lst:
soFar += w
if position < soFar:
return i
return lst[-1][1]
|
7abb650d9df32f2e12412a31173336507a0b3738
| 586,861 |
def always_true(*args):
"""
A predicate function that is always truthy.
"""
return True
|
b08c44467cd14b572b5a7e404da441e9b74b0e26
| 100,644 |
def slice_by_lev_and_time(
ds,
varname,
itime,
ilev,
flip
):
"""
Slice a DataArray by desired time and level.
Args:
ds: xarray Dataset
Dataset containing GEOS-Chem data.
varname: str
Variable name for data variable to be sliced
itime: int
Index of time by which to slice
ilev: int
Index of level by which to slice
flip: bool
Whether to flip ilev to be indexed from ground or top of atmosphere
Returns:
ds[varname]: xarray DataArray
DataArray of data variable sliced according to ilev and itime
"""
# used in compare_single_level and compare_zonal_mean to get dataset slices
vdims = ds[varname].dims
if "time" in vdims and "lev" in vdims:
if flip:
maxlev_i = len(ds['lev'])-1
return ds[varname].isel(time=itime, lev=maxlev_i - ilev)
return ds[varname].isel(time=itime, lev=ilev)
if ("time" not in vdims or itime == -1) and "lev" in vdims:
if flip:
maxlev_i = len(ds['lev'])-1
return ds[varname].isel(lev=maxlev_i - ilev)
return ds[varname].isel(lev=ilev)
if "time" in vdims and "lev" not in vdims and itime != -1:
return ds[varname].isel(time=itime)
return ds[varname]
|
610c115076e044911a5b6d5f2653cfcae4fce113
| 440,277 |
import hashlib
def calculate_file_hash(f_name):
"""calculate hash of a given file"""
BLOCK_SIZE = 65536 # The size of each read from the file
file_hash = hashlib.sha512() # create the hash object, algo used sha512
with open(f_name, 'rb') as handle: # open the file to read it's bytes
fb = handle.read(BLOCK_SIZE) # read from the file. take in the amount declared in BLOCK_SIZE
while len(fb) > 0: # while there is still data being read from the file
file_hash.update(fb) # update the hash
fb = handle.read(BLOCK_SIZE) # read the next block from the file
return file_hash.hexdigest()
|
fc37486d40e5930dcaaf0b616dfcad81053f0132
| 503,114 |
from typing import OrderedDict
def build_paragraph_marker_layer(root):
"""
Build the paragraph marker layer from the provided root of the XML tree.
:param root: The root element of the XML tree.
:type root: :class:`etree.Element`
:return: An OrderedDict containing the locations of markers, suitable for direct
transformation into JSON for use with the eRegs frontend.
:rtype: :class:`collections.OrderedDict`:
"""
paragraphs = root.findall('.//{eregs}paragraph') # + root.findall('.//{eregs}interpParagraph')
paragraph_dict = OrderedDict()
for paragraph in paragraphs:
marker = paragraph.get('marker')
label = paragraph.get('label')
if marker != '':
marker_dict = {'locations': [0],
'text': marker}
paragraph_dict[label] = [marker_dict]
return paragraph_dict
|
d4b4ae6d0a1be0f4fcb3b550b0a11b2366220912
| 82,233 |
def fromOpt(object, default):
"""
Given an object, return it if not None. Otherwise return default
"""
return object if object is not None else default
|
7aa3190f65d01c8812eb22ca1d9058c81be4d7f1
| 395,655 |
def trans_f_to_c(f):
"""Transform f to c temperature."""
return round((f - 32) * (5.0 / 9), 1)
|
559ad47b721cb211928a6a4403511311feffddf1
| 392,353 |
def torchcrop(x, start_idx, crop_sz):
"""
Arguments
---------
x : Tensor to be cropped
Either of dim 2 or of 3
start_idx: tuple/list
Start indices to crop from in each axis
crop_sz: tuple/list
Crop size
Returns
-------
cropped tensor
"""
dim = len(x.shape) # numpy has .ndim while torch only has dim()!
assert dim >= 1 and dim <=3, 'supported dimensions: 1, 2 and 3 only'
if dim == 1:
return x[start_idx[0]:start_idx[0]+crop_sz[0]]
elif dim == 2:
return x[start_idx[0]:start_idx[0]+crop_sz[0],
start_idx[1]:start_idx[1]+crop_sz[1]]
else:
return x[start_idx[0]:start_idx[0]+crop_sz[0],
start_idx[1]:start_idx[1]+crop_sz[1],
start_idx[2]:start_idx[2]+crop_sz[2]]
|
f7a3ef0eb2e81bb77d194b0e04d8c504979475d7
| 670,369 |
def missing_branch(children):
"""Checks if the missing values are assigned to a special branch
"""
return any([child.predicate.missing for child in children])
|
75dd5f4cd503ae614023bc73c0119bebc9bb561e
| 691,577 |
def add_target_columns(df, targets):
"""
Adds new columns (empty) to the dataframe form each target variable.
"""
for env in targets.values():
for v in env.get("aliases"):
if v not in df.columns: df[v] = None
return df
|
951eb8168415ed5f8b90b1e130b4df69919ec377
| 393,949 |
import torch
def cov(x, ddof=1, dim_n=1, inplace=False):
"""Return the covariance matrix of the data.
Parameters
----------
x : torch.Tensor
A tensor of shape ``(m, n)``, where ``n`` is the number of samples
used to estimate the covariance, and ``m`` is the dimension of
the multivariate variable. If ``dim_n`` is 0, then the expected
shape is ``(n, m)``.
ddof : int, optional
The number of dependent degrees of freedom. The covariance will
be estimated dividing by ``n - ddof``. Default is 1.
dim_n : int, optional
The dimension used to collect the samples. Default is 1.
inplace : bool, optional
If ``True``, the input argument ``x`` is modified to be centered
on its mean. Default is ``False``.
Returns
-------
cov : torch.Tensor
A tensor of shape ``(m, m)``.
"""
if len(x.shape) != 2:
raise ValueError('The function supports only 2D matrices')
if dim_n not in {0, 1}:
raise ValueError('dim_n must be either 0 or 1')
# Center the data on the mean.
if dim_n == 1:
keepdim = True
else:
keepdim = False
mean = torch.mean(x, dim_n, keepdim=keepdim)
if inplace:
x -= mean
else:
x = x - mean
# Average normalization factor.
n = x.shape[dim_n] - ddof
# Compute the covariance matrix
if dim_n == 0:
c = x.t().matmul(x) / n
else:
c = x.matmul(x.t()) / n
return c
|
a5a40fed541a37223da22ce69cabe9ff95a84773
| 381,480 |
def countCheckedItems(widget_list, what_to_count):
"""
Calculation of the amount of records marked in the list.
:param widget_list: the current list for which the number of marked records is counted.
:param what_to_count: A parameter that tells the function what to count, for example: number of checked items.
:returns: boolean or number (of checked items).
"""
def isAtLeastOneItemChecked():
for index in range(widget_list.count()):
if widget_list.item(index).checkState() == 2:
return True
return False
def isAtLeastOneItemNotChecked():
for index in range(widget_list.count()):
if widget_list.item(index).checkState() == 0:
return True
return False
def isNoItemChecked():
for index in range(widget_list.count()):
if widget_list.item(index).checkState() == 2:
return False
return True
def numOfCheckedItems():
counter = 0
for index in range(widget_list.count()):
if widget_list.item(index).checkState() == 2:
counter = counter + 1
return counter
return {'at_list_one_checked': isAtLeastOneItemChecked,
'at_list_one_not_checked': isAtLeastOneItemNotChecked,
'not_items_checked': isNoItemChecked,
'num_of_check_items': numOfCheckedItems
}[what_to_count]()
|
8621448c9150a2b2ab2a131f7a708810ee3c03e8
| 571,157 |
def normalize_text(text, lower=True):
"""
Normalizes a string.
The string is lowercased and all non-alphanumeric characters are removed.
>>> normalize_text("already normalized")
'already normalized'
>>> normalize_text("This is a fancy title / with subtitle ")
'this is a fancy title with subtitle'
>>> normalize_text("#@$~(@ $*This has fancy \\n symbols in it \\n")
'this has fancy symbols in it'
>>> normalize_text("Oh no a ton of special symbols: $*#@(@()!")
'oh no a ton of special symbols'
>>> normalize_text("A (2009) +B (2008)")
'a 2009 b 2008'
>>> normalize_text("1238912839")
'1238912839'
>>> normalize_text("#$@(*$(@#$*(")
''
>>> normalize_text("Now$ this$ =is= a $*#(ing crazy string !!@)# check")
'now this is a ing crazy string check'
>>> normalize_text("Also commata, and other punctuation... is not alpha-numeric")
'also commata and other punctuation is not alphanumeric'
>>> normalize_text(("This goes over\\n" "Two Lines"))
'this goes over two lines'
>>> normalize_text('')
''
"""
if lower:
text = text.lower()
return ' '.join(filter(None, (''.join(c for c in w if c.isalnum())
for w in text.split())))
|
42b0da0abef13972e31f88cdfecfb343dcefaa2f
| 262,150 |
def _check_hospital_unhappy(resident, hospital):
"""Determine whether a hospital is unhappy because they are
under-subscribed, or they prefer the resident to at least one of their
current matches."""
return len(hospital.matching) < hospital.capacity or any(
[hospital.prefers(resident, match) for match in hospital.matching]
)
|
2144e6f553f2b43b01a4f6f61f94e2c4c91cccfb
| 617,004 |
def _el_orb_tuple(string):
"""Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (`str`): The selected elements and orbitals in in the form:
`"Sn.s.p,O"`.
Returns:
A list of tuples specifying which elements/orbitals to plot. The output
for the above example would be:
`[('Sn', ('s', 'p')), 'O']`
"""
el_orbs = []
for split in string.split(','):
splits = split.split('.')
el = splits[0]
if len(splits) == 1:
el_orbs.append(el)
else:
el_orbs.append((el, tuple(splits[1:])))
return el_orbs
|
b56932ce95afb54e3f5d9f01530d50851edab311
| 585,406 |
def calculate_r2_wf(y_true, y_pred, y_moving_mean):
"""
Calculate out-of-sample R^2 for the walk-forward procedure
"""
mse_urestricted = ((y_true - y_pred)**2).sum()
mse_restricted = ((y_true - y_moving_mean)**2).sum()
return 1 - mse_urestricted/mse_restricted
|
f31c729c1f6008484acde73cf4fd208c04d01f41
| 536,191 |
def validateWavelengths(wavelengths: list, bbl: list):
"""
Validate wavelengths and bbl.
Parameters
----------
wavelengths : list of int
List of measured wavelength bands
bbl : list of str/int/bool
List of bbl values that say which wavelengths are measured in
good quality (1) and which are not (0)
Returns
-------
list of int
Validated `wavelengths` list
list of int
Validated `bbl` list
Raises
------
ValueError:
Raised if `wavelengths` and `bbl` are of a different length.
"""
# check for inconsistencies
if len(wavelengths) != len(bbl):
raise ValueError(
"Length of wavelengths ({0}) and bbl ({1}) is not equal.".format(
len(wavelengths), len(bbl)))
# remove zero-wavelength at the beginning
if len(wavelengths) == 139:
return wavelengths[1:], bbl[1:]
return wavelengths, bbl
|
795b33b59c026c2dbdea85b602254fbf82adb091
| 52,911 |
def add_modal(form, error, name, url):
"""Render the given template to provide a modal dialog
that provides a popup form.
Args:
form (Forms) : Django form to render
error (String) : String to add to the form's class attribute
name (String) : Name of the buttons / modal
url (String) : URL to post the form to
"""
return {
'form': form,
'error': error,
'name': name,
'id': name.replace(' ', ''),
'url': url
}
|
f8000e6cb99637ee2d32caf8294a9fcd40e0edfa
| 337,730 |
def check_requirement(line):
"""
Check this line for a requirement, which is indicated by a line betinning with "?? ".
If one is found, return that line with a newline at the end, as requirements are always
a complete line and formatted as a bulleted list. Replace the "??" with a "-" as well
so that the resulting list can later be Markdown formatted.
:param line: the line to check
:return: None or a formatted requirement
"""
if line[0:3] == "?? ":
return "- %s\n" % line[3:]
return None
|
63511288a11a1278d2438f103ae4abae49c4b318
| 276,035 |
def __filter_vertices(k, coreness, *args, **kwargs):
"""
.. function filter_vertices(k, coreness)
Filters coreness mapping for vertex ids in k-core >= k.
:param k: minimum k-core
:param list coreness: vertex -> k-core mapping
:return: vertices in k-core
"""
return list(filter(lambda i: coreness[i] >= k, range(len(coreness))))
|
c12b8c60a0c010bda8accabb30775d15d4272b2c
| 157,194 |
def calc_formation_energy(prod, react):
"""
Calculate formation energy of 'A' in a.u. from 2 lists of energies.
Formation energy = sum(product energy) - sum(reactant energy)
Keyword arguments:
prod (list) - list of product energies
react (list) - list of reactant energies
Returns:
RFE (float) - Reaction formation energy in a.u.
"""
RFE = sum(prod) - sum(react)
return RFE
|
ec2a8f3d4e7fd72ebfce84e2bb58b3f1fd68472c
| 524,222 |
def flipx(tile):
""" Return a copy of the tile, flipped horizontally """
return list(reversed(tile))
|
1203919042cdedd49edd35942d19964d4f1acfdf
| 59,111 |
def _parse_match_info(match, soccer=False):
"""
Parse string containing info of a specific match
:param match: Match data
:type match: string
:param soccer: Set to true if match contains soccer data, defaults to False
:type soccer: bool, optional
:return: Dictionary containing match information
:rtype: dict
"""
match_info = {}
i_open = match.index('(')
i_close = match.index(')')
match_info['league'] = match[i_open + 1:i_close].strip()
match = match[i_close + 1:]
i_vs = match.index('vs')
i_colon = match.index(':')
match_info['home_team'] = match[0:i_vs].replace('#', ' ').strip()
match_info['away_team'] = match[i_vs + 2:i_colon].replace('#', ' ').strip()
match = match[i_colon:]
if soccer:
i_hyph = match.index('-')
match_info['match_score'] = match[1:i_hyph + 2].strip()
match = match[i_hyph + 1:]
i_hyph = match.index('-')
match_info['match_time'] = match[i_hyph + 1:].strip()
else:
match_info['match_score'] = match[1:].strip()
return match_info
|
db0f6bbd6f19902202d7d1b0012812cbd22aeaab
| 278,998 |
def _ids_to_words(ids, dictionary):
"""Convert an iterable of ids to their corresponding words using a dictionary.
Abstract away the differences between the HashDictionary and the standard one.
Parameters
----------
ids: dict
Dictionary of ids and their words.
dictionary: :class:`~gensim.corpora.dictionary.Dictionary`
Input gensim dictionary
Returns
-------
set
Corresponding words.
Examples
--------
.. sourcecode:: pycon
>>> from gensim.corpora.dictionary import Dictionary
>>> from gensim.topic_coherence import text_analysis
>>>
>>> dictionary = Dictionary()
>>> ids = {1: 'fake', 4: 'cats'}
>>> dictionary.id2token = {1: 'fake', 2: 'tokens', 3: 'rabbids', 4: 'cats'}
>>>
>>> text_analysis._ids_to_words(ids, dictionary)
set(['cats', 'fake'])
"""
if not dictionary.id2token: # may not be initialized in the standard gensim.corpora.Dictionary
setattr(dictionary, 'id2token', {v: k for k, v in dictionary.token2id.items()})
top_words = set()
for word_id in ids:
word = dictionary.id2token[word_id]
if isinstance(word, set):
top_words = top_words.union(word)
else:
top_words.add(word)
return top_words
|
2d6328a823e10e686c764aa186bdc10455a9ab85
| 454,308 |
from pathlib import Path
def lglob(self: Path, pattern="*"):
"""Like Path.glob, but returns a list rather than a generator"""
return list(self.glob(pattern))
|
eba1b9d6300a1e1aca5c47bedd6ac456430e4d89
| 9,576 |
def normalizeTransformationMatrix(value):
"""
Normalizes transformation matrix.
* **value** must be an ``tuple`` or ``list``.
* **value** must have exactly six items. Each of these
items must be an instance of :ref:`type-int-float`.
* Returned value is a ``tuple`` of six ``float``.
"""
if not isinstance(value, (tuple, list)):
raise TypeError("Transformation matrices must be tuple instances, "
"not %s." % type(value).__name__)
if not len(value) == 6:
raise ValueError("Transformation matrices must contain six values, "
"not %d." % len(value))
for v in value:
if not isinstance(v, (int, float)):
raise TypeError("Transformation matrix values must be instances "
"of :ref:`type-int-float`, not %s."
% type(v).__name__)
return tuple([float(v) for v in value])
|
3c13d334f82e91dbc0a5a9a01081c1c8a8438f05
| 332,508 |
def named_field(key, regex, vim=False):
"""
Creates a named regex group that can be referend via a backref.
If key is None the backref is referenced by number.
References:
https://docs.python.org/2/library/re.html#regular-expression-syntax
"""
if key is None:
# return regex
return r'(%s)' % (regex,)
if vim:
return r'\(%s\)' % (regex)
else:
return r'(?P<%s>%s)' % (key, regex)
|
b813179e87f8bf6cabc02d7746222787154aed3a
| 684,365 |
def readText(inputfile):
"""Reads a sequence file in text format and returns the file with special character removed."""
with open(inputfile, "r") as seqfile:
# read data
seq = seqfile.read()
# remove special characters \n and \t
seq = seq.replace("\n", "")
seq = seq.replace("\t", "")
return seq
|
489b6a92d70eb68414b4221e51b54f3e3dd07ac3
| 333,237 |
def cumany(x, axis=0):
"""Cumulative any (modeled after np.cumprod)"""
return x.astype(bool).cumsum(axis=axis) > 0
|
62832b89be4e0c746bea2ccceea09118341d9808
| 377,172 |
import re
def copy_from(con, copy_from_sql):
"""
To be used with a 'COPY FROM' statement.
Calls pymapd `execute`, but parses the response to check if it failed or not.
If it fails to do too many rejected records, raise an exception.
If it succeeds, return a dict with loaded, rejected, and time in ms.
"""
rs = con.execute(copy_from_sql).fetchall()
msg = rs[0][0]
if msg.startswith("Loaded:"):
m = re.match(
"Loaded: ([0-9]+) recs, Rejected: ([0-9]+) recs in ([0-9.]+) secs", msg
)
if m:
return {"loaded": m[1], "rejected": m[2], "time": m[3]}
else:
# never seen this, but just in case
return {"message": msg}
elif msg.startswith("Creating ") or msg.startswith("Appending "):
# with geo=true is not very descriptive
return {"message": msg}
else:
raise Exception(str(rs))
|
18dd479b400ae390e24b9e622a10c7184f86a53c
| 149,587 |
def notas(*valores,situacao=False):
"""
-> Funcao para analise das notas e situcao do estudante
: para valores: as notas dos estudantes (aceita varias notas) |
PS: o asterixo no principio da variavel indica a condicao de recebimento de varios valores (*n)
: para situacao: valor opcional (condicao True se quiser visualizar) para demonstracao da situacao do estudante
: return: dicionario com todas as informacoes relevantes sobre o estudante (nº de notas; a maior, a menor, a media e a situacao)
"""
resul = dict()
resul["total"] = len(valores)
resul["maior"] = max(valores)
resul["menor"] = min(valores)
resul["media"] = sum(valores)/len(valores)
if situacao:
if resul["media"] < 10:
resul["situacao"] = "Ruim"
elif resul["media"] >= 10 < 14:
resul["situacao"] = "Boa"
else:
resul["situacao"] = "Muito Boa"
return resul
|
2ae9d59c494415b3d862c86d6ca3500b23ca0631
| 539,019 |
def rep_model(glm_dict, repo_mode):
"""Reporting results from GLM models in glm_dict.
Parameters
----------
glm_dict: :obj: dict of :obj:
GLM models. Like: {tar_var:{'forluma': formula, 'res':res}}
rep_mode: :obj: string
Reporting mode.
Returns
-------
Nothing.
"""
if repo_mode['name']=='all':
print("Display all results:\n")
for k in glm_dict.keys():
print('\n')
print(glm_dict[k]['formula'],'\n')
print(glm_dict[k]['res'].summary2())
if repo_mode['name']=='significant':
col_name = repo_mode['col_name'];
alpha_ = repo_mode['th'];
print("Only display significant results @",str(alpha_),' for ', col_name,' :\n' )
for k in glm_dict.keys():
if glm_dict[k]['res'].pvalues[col_name]<alpha_:
print('\n')
print(glm_dict[k]['formula'],'\n')
print(glm_dict[k]['res'].summary2())
return glm_dict
|
8e15509e397a48e4463d7b3e47167c86ce28e83e
| 536,482 |
from datetime import datetime
def _parse_created(raw_created):
"""Parse a string like 2017-02-14T19:23:58Z"""
return datetime.strptime(raw_created, "%Y-%m-%dT%H:%M:%SZ")
|
711883abcc860f5217556d63099c0c15e9b6c819
| 247,464 |
import json
def _transform_request(request: bytes) -> dict:
"""
Transform bytes posted to the api into a python dictionary containing
the resource routes by tag and weight
:param bytes request: containing the payload to supply to the predict method
:return: dict containing the resource routes by tag and weight
"""
return dict(json.loads(request.decode('utf-8'))['resource_split_tag_and_weight_dict'])
|
f7a9222391ebbbf28c69722196391daef246d54c
| 144,385 |
from typing import List
def build_ip_set(ip_addresses: List[str]) -> str:
"""
Build ip set input for list-cmdb-devices command.
The input wil be a combination of ip-addresses list and ranges. For example,
if ip_address = ['1.1.1.1','3.3.3.3','2.2.2.0-2.2.2.254'], the output will be:
'1.1.1.1,3.3.3.3,2.2.2.0-2.2.2.254'
Args:
ip_addresses (list): List of IP addresses ranges/list.
Returns:
str: Formatted IP addresses for list-cmdb-devices command.
"""
return ','.join(filter(None, ip_addresses))
|
863cb6664b71a424577cd5c28cb76a5d95d1e30f
| 191,693 |
import torch
def sparse_categorical_kl(log_q, p_support, log_p):
"""
Computes the restricted Kl divergence::
sum_i restrict(q)(i) (log q(i) - log p(i))
where ``p`` is a uniform prior, ``q`` is the posterior, and
``restrict(q))`` is the posterior restricted to the support of ``p`` and
renormalized. Note for degenerate ``p=delta(i)`` this reduces to the log
likelihood ``log q(i)``.
"""
assert log_q.dim() == 1
assert log_p.dim() == 1
assert p_support.shape == log_p.shape + log_q.shape
q = log_q.exp()
sum_q = torch.mv(p_support, q)
sum_q_log_q = torch.mv(p_support, q * log_q)
sum_r_log_q = sum_q_log_q / sum_q # restrict and normalize
kl = sum_r_log_q - log_p # note sum_r_log_p = log_p because p is uniform
return kl.sum()
|
2eef54e367be5b2bd360f6b4ef90645fa93a50c2
| 399,493 |
def analogy2query(analogy):
""" Decompose analogy string of n words into n-1 query words and 1 target word (last one)
zips with +-
>>> analogy2query("Athens Greece Baghdad Iraq")
('+Athens -Greece +Baghdad', 'Iraq')
"""
words = analogy.split()
terms, target = words[:-1], words[-1]
pm_terms = [("+" if idx % 2 == 0 else "-") + term
for idx, term in enumerate(terms)]
query = " ".join(pm_terms)
return query, target
|
2040d46f361b56388597c839e8dd78eb1f022d94
| 433,649 |
def div(format, data): # HTML formatting utility function
"""Wraps 'data' inside a div of class 'format' for HTML printing."""
d = '<div class="{}">{}</div>' # Basic div template
return d.format(format, data)
|
0596217cabfeb13b0b77a91697ebcfc42888e6b0
| 82,919 |
from re import search
def img_from_html(html_str: str) -> str:
"""Scrubs the string of a html page for the b64 string of in image
This function uses regex to scan the html template described in the render
image function. It scans this template for the base 64 string encoded png
image and extracts it from the template. This string is then returned.
:param html_str: The string of the html page to be searched
:type html_str: str
:return: The Base 64 string of the png image
:rtype: str
"""
match_obj = search('data:image/png;base64,([^\']+)', html_str)
if match_obj:
match = match_obj.group(1)
return match
else:
return ""
|
5436f6b1b27b90191f6f0461178c343e5b9932c4
| 328,011 |
def tokenize (text):
""" Tokenizes a text sample.
Args:
text (str): The text sample
Returns:
list of str: A list of tokens
"""
replacements = ["\r", "\n", "\t"]
output = text
for replacement in replacements:
output = output.replace(replacement, " ") # Convert whitespace to spaces only.
return list(filter(lambda s: len(s) > 0, output.split(" ")))
|
73e89528f41b34740e7e9583f5f387e248588963
| 418,366 |
def combine_values(uri_list, check_full_titles_for_volume_info, check_copyright_ocr_for_edition_info, check_fm_and_marc_titles_for_differences):
"""
Creates list of check values corresponding to title URIs.
The following Stack Overflow page was helpful in producing this function:
"Merge Two Lists to Make List of Lists,"
https://stackoverflow.com/questions/23327242/merge-two-lists-to-make-list-of-lists (accessed October 28, 2020)
Parameters
----------
uri_list: list
A list of URIs for each title
check_full_titles_for_volume_info: list
A list of check values for volume information corresponding to full title strings.
check_copyright_ocr_for_edition_info: list
A list of check values for edition information corresponding to copyright OCR strings.
Returns
----------
combined_values: list
A list of URIs and volume/edition check values
corresponding to each title.
"""
a = uri_list
b = check_full_titles_for_volume_info
c = check_copyright_ocr_for_edition_info
d = check_fm_and_marc_titles_for_differences
combined_values = [list(x) for x in zip(a, b, c, d)]
return combined_values
|
be9edbee9bcd47e6feccfe5f7d03040813f52567
| 538,025 |
def bits_to_array(num, output_size):
""" Converts a number from an integer to an array of bits
"""
##list(map(int,bin(mushroom)[2:].zfill(output_size)))
bit_array = []
for i in range(output_size - 1, -1, -1):
bit_array.append((num & (1 << i)) >> i)
return bit_array
|
7df0bd8bf3e95770e4eee332df4514581704eef6
| 650,029 |
def linear_search(array, element):
"""
Linear Search
Complexity: O(N)
"""
indices = []
for i in range(len(array)):
if element == array[i]:
indices.append(i)
return indices
|
6de026b74354d4e9d848514aa730a37738c727b0
| 416,691 |
def get_channel_name(sample_rate, is_acceleration=True,
is_vertical=False, is_north=True):
"""Create a SEED compliant channel name.
SEED spec: http://www.fdsn.org/seed_manual/SEEDManual_V2.4_Appendix-A.pdf
Args:
sample_rate (int): Sample rate of sensor in Hz.
is_acceleration (bool): Is this channel from an accelerometer.
is_vertical (bool): Is this a vertical channel?
is_north (bool): Is this channel vaguely pointing north or the channel
you want to be #1?
Returns:
str: Three character channel name according to SEED spec.
"""
band = 'H' # High Broad Band
if sample_rate < 80 and sample_rate >= 10:
band = 'B'
code = 'N'
if not is_acceleration:
code = 'H' # low-gain velocity sensors are very rare
if is_vertical:
number = 'Z'
else:
number = '2'
if is_north:
number = '1'
channel = band + code + number
return channel
|
bf1a845bfa011aa2dbe8b0ba1cb93bfc07b00e69
| 289,687 |
def combineUsers(users):
"""Combine user info into a string with known format."""
res = []
for user in users:
userstr = user['name']
if user.get('email'):
userstr += ' <%s>' % user['email']
if user.get('affiliation'):
userstr += ' (%s)' % user['affiliation']
res.append(userstr)
return '; '.join(res)
|
777672896e730bcacffbf1e2bf958aabb1d33aa8
| 383,619 |
import hmac
import hashlib
def sha256_hmac(key, bytes):
"""Computes a hexadecimal HMAC using the SHA256 digest algorithm."""
return hmac.new(key, bytes, digestmod=hashlib.sha256).hexdigest()
|
eabd8c888ec3adaa9ff60d4aeacbd4cb0a9758d3
| 416,339 |
import requests
def shortenURL(url, key=None):
"""Take a URL and return the shortened one."""
return requests.post(
"https://short.spgill.me/api", data={"url": url, "key": key}
).text
|
b7650f04394f81a48fe413bf0e90e01bb2c4295c
| 418,586 |
import torch
def create_random_dictionary(normalize=False):
"""
Creates a random (normal) dictionary.
:param normalize: Bool. Normalize L0 norm of dictionary if True.
:return: Tensor. Created dictionary
"""
dictionary = torch.rand((64, 512))
if normalize:
dictionary = dictionary.__div__(torch.norm(dictionary, p=2, dim=0))
return dictionary
|
e26dfc122ac8b061a4466f48d267ce67c658e6af
| 342,676 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.