content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def to_vectors(rgb_image, row_or_col):
"""rgb image -> list of lists of RGB tuples"""
assert(rgb_image.mode == "RGB"), "must be a RGB image"""
assert(row_or_col in (0, 1)), "row = 0, col = 1"
vectors = []
x_size, y_size = rgb_image.size
if(row_or_col == 0):
for y_coord in range(0, y_siz... | c6f640af2501f8529831ad5286c94fdf57c15eda | 608,708 |
import math
def binomial_coefficient(n, k):
"""
Finds the binomial coefficient, given n and k.
Equals:
n! / (k!*(n-1)!)
"""
bin_coeff = (math.factorial(n) // (math.factorial(k) * math.factorial(n - k)))
return bin_coeff | ca9b466eb7956a7bd0ca0674c9ae3ca2faa19907 | 608,712 |
from pathlib import Path
def thumbnail_path(url: str):
"""Create a path to thumbnail using URL"""
thumbnail_path = Path(
"novelreader",
"public",
"imgs",
url.split("/")[-1]
).absolute()
return thumbnail_path | 4717e65b7b3337e736eb03caf798163f0eed8cb8 | 608,717 |
import yaml
def config_to_str(config: dict) -> str:
"""Convert a configuration to string."""
return yaml.dump(config) | 74ab5eadbc62830af7905719b9e95164f59fcd65 | 608,724 |
def value(A):
"""
The heuristic for the 8Queen problem is this:
h(A) = number of attack that the queens have between each
other.
The data structure representation for the chessboard
will be a list of tuples each of them representing the
coordinates of a the position of a queen.
Complexi... | ffe43d022cb79af88186764d84bf52bdf66f7376 | 608,728 |
import itertools
def allcomb(*args, **kwargs):
"""
Compute the Cartesian product of a series of iterables, i.e. the list consisting of all n-tuples
formed by choosing one element from each of the n inputs. The output list will have
have length (P1 x P2 x ... x PN), where P1, P2, ..., PN are the lengt... | e3f9aad9bd4ddf563f2c3d342c5a182b2cc9ca74 | 608,729 |
def has_valid_dimension(l, d=None):
"""Check congruent dimensions in a two-dimensional list."""
if not l:
return False
if d is None:
d = len(l[0])
for sub in l:
if len(sub) != d:
return False
return True | 067f4c8141b636d6cbe989fdb1a60d1573fa5dc9 | 608,730 |
def _CreateOdexLine(java_class_name, type_idx, verification_status):
"""Create a rough approximation of a line of oatdump output."""
return ('{type_idx}: L{java_class}; (offset=0xac) (type_idx={type_idx}) '
'({verification}) '
'(OatClassNoneCompiled)'.format(type_idx=type_idx,
... | 9bb09f78783dae6f5172ba2196572cc6a1cfaf38 | 608,733 |
def check_serie_is_number(serie, max_serie=5000):
"""Check if serie is valid and return boolean.
Check if serie is a integer and if so if it is not
a made up number for research. First check if it can
be converted to a integer and if so check if it has a
smaller value than max_serie. Sometime... | 4f0fd3e873472819f8dceacf769f8ce714ecb701 | 608,735 |
def num_digits(n):
"""How many digits in integer n?"""
return len(str(n)) | de06174897955d33b5bcd99ad75cf24e33e05556 | 608,736 |
def get_gene_to_dcid_list(gene_to_uniprot_list, uniprot_to_dcid):
"""
Args:
gene_to_uniprot_list: a dic mapping gene to a list of UniProt entry
uniprot_to_dcid: a dic mapping UniProt entry to Data Commons DCID
Returns:
A dict mapping gene to a list of protein DCID in Data Commons.
... | 142c5d30a032de550cd01a5ad3048b0d1d74f363 | 608,738 |
def find_words(starting_lv: dict, prefix: str, letters: str = '') -> list:
"""Finds all the words that branch off from a starting level
Args:
starting_lv (dict): The level to perform the search on
prefix (str): The string of characters that you start the search with
letters (str): The s... | faedd726bc1b2d067b637679f986f50871067214 | 608,739 |
def mc_extend(trace, msg, num_samples=None):
"""
:param trace: a partial trace
:param msg: the message at a pyro primitive site
:param num_samples: maximum number of extended traces to return.
:returns: a list of traces, copies of input trace with one extra site
Utility function to copy and ext... | 64c25eb74dec9c97ed36b341023e8416aa62d208 | 608,742 |
def list_find(l, e):
"""
Arguments:
l: a list
e: an element to be searched for.
Returns:
The index of the element e in the list, if found,
And -1 if not found.
"""
for i in range(len(l)):
if e == l[i]:
return i
return -1 | 0dca9e920f9b5285341797390173c53592e022c1 | 608,744 |
def _parseMinusList(fdata):
"""Parse a list of lines starting with '- '."""
rlist = []
tmplist = []
for line in fdata:
if line and line[:2] == '- ':
if tmplist:
rlist.append(' '.join(tmplist))
l = line[2:].strip()
if l:
tmplist[... | 92bd0a9748c30986b8f62d87fbd606ef58b4ee92 | 608,754 |
def pm_to_aqi(pm_val, pm_low, pm_high, aqi_low, aqi_high):
"""PM2.5 reading to AQI via https://forum.airnowtech.org/t/the-aqi-equation/169"""
aqi_range = aqi_high - aqi_low
pm_range = pm_high - pm_low
scale_factor = aqi_range / pm_range
return (pm_val - pm_low) * scale_factor + aqi_low | eee8c0790934d71d26b9321a637c0f57be5548eb | 608,756 |
def fn_k2_TE(h_11,c_11,beta_11):
"""EM coupling factor k^2 for thickness expander mode, as function of:
-- piezoelectric tensor component h_11
-- elastic stiffness tensor component c_11
-- impermittivity tensor component beta_11.
"""
return h_11**2 / (c_11 * beta_11) | df8f1c8d340d3bce182ee8f2e2633b553827dafa | 608,757 |
def dmp_neg(f, u, K):
"""
Negate a polynomial in ``K[X]``.
Examples
=======
>>> R, x, y = ring("x y", ZZ)
>>> R.dmp_neg(x**2*y - x)
-x**2*y + x
"""
if not u:
return [-coeff for coeff in f]
else:
v = u - 1
return [dmp_neg(coeff, v, K) for coeff in f] | 41dab38a0708f9d6aa35525cbaedce3fae509532 | 608,759 |
def hass_supervisor_access_token(hass, hass_supervisor_user, local_auth):
"""Return a Home Assistant Supervisor access token."""
refresh_token = hass.loop.run_until_complete(
hass.auth.async_create_refresh_token(hass_supervisor_user)
)
return hass.auth.async_create_access_token(refresh_token) | 52c5fcb39e48dbaa294b1f8c7887936b2646f9b0 | 608,762 |
import torch
def barycenter(P, T=None, dim=0):
"""
Returns the barycenters of the n-gons if a topology is provided, the
barycenter of the input point set along the specified dimension otherwise
Parameters
----------
P : Tensor
the point set tensor
T : LongTensor (optional)
... | d3e9a4230b5d2bf18d826cda8b77071ee4094590 | 608,766 |
from typing import Tuple
def from_checksum_format(line_bytes: bytes) -> Tuple[str, str]:
"""
Given one line of bytes from a checksums.md5 file,
parses the line and returns the filepath and that file's recorded checksum
We expect a line to look roughly like this:
2eb067afb7ba4eefe89a0416ab16f688 ... | 70cb3e86acf6c4b06f0452a4c7c9b44040ad8e48 | 608,769 |
from typing import Dict
import copy
def drop_feature_ids(collection: Dict) -> Dict:
"""
Given a GeoJSON FeatureCollection, remove the ``'id'`` attribute of each
Feature, if it exists.
"""
new_features = []
for f in collection["features"]:
new_f = copy.deepcopy(f)
if "id" in new... | 4845d2f6555d6235d3006aaf6371c5d264e57fb8 | 608,770 |
def kl_to_prior(means, log_stds, stds):
"""
KL between a Gaussian and a standard Gaussian.
https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians
"""
return 0.5 * (
- 2 * log_stds # log std_prior = 0
- 1 # d = 1
+ stds ... | 3122e85e890ec65255e1e8d4038e17664057f9b4 | 608,771 |
def _BuildForceFieldTrialParamsSwitchValue(trials):
"""Generates --force-fieldtrial-params switch value string.
This is the opposite of _ParseForceFieldTrialParams().
Args:
trials: A list of _TrialParams objects from which the switch value
string is generated.
"""
return ','.join('%s.%s:%s' ... | 4a0e6b434cb330fa891d68406c424bfa3d3d1608 | 608,773 |
def _always_wrap(strategy):
"""Returns whether to always wrap the values in a DistributedValues."""
return strategy.extended._in_multi_worker_mode() or len( # pylint: disable=protected-access
strategy.extended.worker_devices) > 1 | defe53cf2b2da89307da2f1b9b4e1bbcd1da10a5 | 608,780 |
def ValueErrorOnFalse(ok, *output_args):
"""Raises ValueError if not ok, otherwise returns the output arguments."""
n_outputs = len(output_args)
if n_outputs < 2:
raise ValueError("Expected 2 or more output_args. Got: %d" % n_outputs)
if not ok:
error = output_args[-1]
raise ValueError(error)
if... | 78e5199a30b9d3719c4683a904454757e204026b | 608,781 |
def _bond_angles(vectors):
"""
Creates a list of angles (In degrees) between all two-element combinations
in vectors.
Parameters
----------
vectors : scitbx.matrix.col
Returns
-------
list of float
"""
return [(v1, v2, v1.angle(v2, deg=True))
for index, v1 in enumerate(vectors)
... | 55e9923b5173c466bd0323f6f21f16eeae158699 | 608,786 |
def original(s: str) -> str:
"""Returns s."""
return s | f7f3a82dade3674582b560dad9c42e9d0276feae | 608,788 |
def auth_token(token):
"""
A token stored for a user.
Format: token:[token]
"""
return f"token:{token}" | 55f123b5f0e9c5c77754a44408d22e8f51838e18 | 608,790 |
def goal_test(node):
"""Tests if goal is satisfied
Args:
node (dict): Node includes the representation for each state
Returns:
bool: True if goal is satisfied
"""
for row in node['state']:
if any(element != row[0] for element in row):
return False
return Tru... | b8b3c46342a04ccf78bcb682f41104c0d599a411 | 608,794 |
def sample(rng, N, k, i):
"""
Function sampling k indices from the range 0-N without the i index.
"""
S = set()
while len(S) < k:
random_index = rng.randint(0, N - 1)
if random_index == i:
continue
S.add(random_index)
return list(S) | 95c54430c3d1393614c6bf8cd6ac4b5e5ea6ba3c | 608,795 |
def add_multiples(maximum):
"""Add all numbers that are multiples of 3 and 5 below the maximum."""
total = 0
for x in range(maximum):
if x % 3 == 0 or x % 5 == 0:
total += x
return total | 0724e049e6157f463c7a127dca27856eaddb20f3 | 608,796 |
def float_to_text(value, sig):
"""
Convert float to text string for computing hash.
Preseve up to N significant number given by sig.
:param value: the float value to convert
:param sig: choose how many digits after the comma should be output
"""
if value == 0:
value = 0. # Identify... | 2f43348ce9f434dc62064f84b8d61e572a02d7cc | 608,798 |
def NFSaddle_potential(positions, PARAMETERS = None):
"""
Potential energy function for a 2DoF Saddle.
Functional form: V = 1/2(y**2 - x**2), with positions = (x, y).
----------
positions : ndarray, shape(n,)
Points in phase space.
Returns
-------
V : ndarray, shape(n,)
... | fa561002d5c58370013d161c8edd6dec7a7c3ee5 | 608,806 |
def get_num_processes(profileDict):
"""
Returns the number of processes used in the given profile
Args:
profileDict (dict): Dictionary of the JSON format of a MAP profile
Returns:
Number of processes used in the profile passed in
"""
assert isinstance(profileDict, dict)
re... | e28dadcb41836df227671241e162e7cceacf2a1a | 608,810 |
def addr_to_hash(addr):
"""
Creates hashable address representation
"""
return bytes(addr.spend_public_key + addr.view_public_key) | 9a6584c8200c8c4252afb5b4a8c46eb7aa3f7cfd | 608,811 |
def new_result(title, subtitle, argument, valid=True, icon=None):
"""
Generate a singe Alfred result from an input
"""
result = {
"type": "file",
"title": title,
"subtitle": subtitle,
"arg": argument,
"valid": valid
}
if icon is not None:
result["i... | ee10a9e09aa485fbabb0621635bcf7c250555752 | 608,814 |
def returnUncrawledLinks(collectionObject):
"""
Used to get the links which have not been crawled yet.
Parameters
----------
collectionObject : pymongo.collection.Collection
Object which represents a collection in the database.
Returns
-------
uncrawledList : list
L... | eacbf5958bd0546d06a2d0237a0a81053c6adacd | 608,815 |
def make_conn_string(sql_engine, sql_user, sql_password, sql_host, sql_port):
"""
Constructs a connection string.
Arguments:
sql_engine
sql_user
sql_password
sql_host
sql_port
Returns:
connection string
"""
return "%s://%s:%s@%s:%s" % (
s... | 2b573189155abc24c592412141dff52db2ef69ad | 608,817 |
def replace_underscore(string):
"""
Replaces an underscore with a space.
Return: {string}
"""
return string.replace('_', ' ') | 60446c3cbbb9fad35f23f943645ee90a7d7f2449 | 608,821 |
import re
def _match_wildcard(*, string, pattern):
"""
Helper function to check whether a given name matches a pattern
which can contain '*' wildcards.
"""
regexp = '.*'.join(re.escape(part) for part in pattern.split('*'))
return re.fullmatch(pattern=regexp, string=string) is not None | a75d5b45b4426f67f5c6c5b4353a00bcb38d25c4 | 608,823 |
def build_block(chanjo_db, interval_group):
"""Create a new block and add it to the current session.
Args:
chanjo_db (Store): Chanjo store connected to an existing database
interval_group (list): group of related database intervals
Returns:
tuple: superblock id, new database block
"""
block_id, ... | a34393e8289e03c5974b8de79dfbabbaab529b40 | 608,824 |
def _get_poly_with_LT(LT, GB):
"""Gets a polynomial from a Groebner basis with a given leading term
Parameters
----------
LT : ?
Leading term to look for.
GB : list of Polynomials
Groebner basis.
Returns
-------
poly : Polynomial
Polynomial with leading term LT.... | c1910e123292127dccf9d4ade897f83b8dbc379b | 608,830 |
def auto_batch_weight(*batch_arrays):
"""
Automatically inspect the metric weight for an evaluation mini-batch.
Args:
*batch_arrays: Mini-batch arrays. The ``.size`` of the first array
will be used as the weight.
Returns:
The inspected weight, or 1. if any error occurs dur... | afc7e58012243765bd39df78f885e7d6a66b403f | 608,833 |
def tryint(str):
"""
Returns an integer if `str` can be represented as one.
:param str: String to check.
:type str: string
:returns: int(str) if str can be cast to an int, else str.
:rtype: int or str
"""
try:
return int(str)
except:
return str | 0b49d91225c6a90d5fbd80eddd6b763abc4f7bd2 | 608,836 |
def spacify(string, n=2):
"""Add spaces to the beginning of each line in a multi-line string."""
space = n * " "
return space + space.join(string.splitlines(True)) | b6f24ea3dbb1a0102ff32f003279c904d8e312fd | 608,837 |
def get_account_id(x, account_df):
"""
Get account id from account number
"""
return account_df.loc[account_df['account_number'] == str(x)].iloc[0]['id'] | 5f673a34e1d6f44b6d83198dece76c5248be9469 | 608,838 |
def should_replace_pronoun(token, target_gender):
"""
Determine if the word is a pronoun, with male or female gender,
and whether the gender is different from the target gender.
"""
return (
(token.tag_ in ["PRP", "PRP$"])
and (token._.gender in ["m", "f"])
and (token._.gende... | d44f116766b6d115708abb794f7fd34e770a36a2 | 608,839 |
def cm2pt(cm=1):
"""2.54cm => 72pt (1 inch)"""
return float(cm) * 72.0 / 2.54 | fd3aab678cf22e4799cd7d81c1867d912f11683f | 608,842 |
def as_dicts(cursor):
""" Return a list of dictionaries from a result-set.
"""
fields = [k[0] for k in cursor.description]
result = []
rows = cursor.fetchall()
for row in rows:
result.append(dict(zip(fields, row)))
return(result) | be1c4c3dc0b50284a42e19c9308e183ea58d262d | 608,843 |
def apply_threshold(objects, threshold):
"""
Filter out objects below a certain score.
"""
return [obj for obj in objects if obj['score'] >= threshold] | bdeeee671c015f3d2f9c374259e5e27cf8416fbd | 608,844 |
def _ditto(original):
"""Return a ditto string of the same length as original."""
pad = ' ' * ((len(original) - 1) // 2)
return pad + '"' + pad | d116b371d994847baa63fe6d05f154a1614fdb69 | 608,847 |
def read_source_file(filename, skiplines=3):
"""Read the source file, skip the number of given lines."""
txt_list = []
with open(filename, 'r') as infile:
for i, lines in enumerate(infile):
if i >= skiplines:
txt_list.append(lines)
return ''.join(txt_list) | e9e2081e5ea7192a280747edea63b2f247a582e0 | 608,848 |
def ms2knot(ws_ms):
"""
Convert unit of wind speed from meter per seconds to knots.
Examples
---------
>>> ws_knot = kkpy.util.ms2knot(ws_ms)
Parameters
----------
ws_ms : array_like
Array containing wind speed in **m/s**.
Returns
---------
ws_knot ... | 270301d7e30a72653bc74d779bff2dcd96c8f382 | 608,852 |
import re
def trim_whitespaces(string: str) -> str:
"""Replaces all multiple whitespaces with one and calls default strip function on a result
Example:
>>> trim_whitespaces('hello friend')
hello friend
>>> trim_whitespaces(' hello old friend ')
hello old friend
... | cc57741b498951d80191c2920942df519d0cb521 | 608,855 |
def Bulged(strand):
"""
Return absolute position of bulge in input strand if present. Otherwise, return None.
"""
flag=False ; bulgepos=None
for i in range(1,len(strand.bp_data)-1):
prev_res = strand.bp_data[i-1]
res = strand.bp_data[i]
... | c6bb1fb1cbb1636db8d799c368fe77543855b985 | 608,867 |
import functools
def require_account(message=None, reply=False): # lgtm [py/similar-function]
"""Decorate a function to require services/NickServ authentication.
:param str message: optional message to say if a user without
authentication tries to trigger this function
:param boo... | 10e2f6a960e4553cc75f6dec32fda9eb3953ba0d | 608,871 |
import operator
def get_max_index_val(given_list):
"""
Returns the max index and value of a list
"""
return max(enumerate(given_list), key=operator.itemgetter(1)) | 1c0817d4ac8ee7835b42b469ce6d243993401690 | 608,874 |
def split_on_condition(array, condition):
"""
Split an array in two parts based on a boolean mask array `condition`.
"""
return array[condition], array[~condition] | 24e7a9127cf9226d4fae96dfdbb334ff329d7a9a | 608,875 |
from datetime import datetime
def survey_sent(project):
"""Return True if the field for user survey sent is set, fasle otherwise
"""
try:
if type(project.udf['Survey sent']) == datetime.date:
return True
except:
pass
return False | c7c3997344a19b4bd122ce8e37a6029e4fc8e206 | 608,876 |
def get_celery_crontab_parameters_from_crontab_line(crontab_line):
"""
Get a crontab line line '0 1 * * *' and return a dict that can be used in the Celery crontab scheduler
"""
line_split_on_space = crontab_line.split()
return {
"minute": line_split_on_space[0],
"hour": line_split_... | 1953858b38c302f66891048d74971d8642fc877a | 608,877 |
def isplit(start_text, iterator):
"""Returns head, match, tail tuple, where match is the first line that starts with `start_text`"""
head = []
iterator = iter(iterator)
for item in iterator:
if item.startswith(start_text):
return head, item, iterator
head.append(item)
ret... | c488b1f685144cbf25db191f32f8e3d2f0b96075 | 608,878 |
def gcd(a: int, b: int) -> int:
"""
Calculate the greatest common divisor.
Currently, this uses the Euclidean algorithm.
Parameters
----------
a : int
Non-zero
b : int
Non-zero
Returns
-------
greatest_common_divisor : int
Examples
--------
>>> gcd... | 326aa43a8f6acd1fdcf8e22fd9b9950ea14969bc | 608,880 |
def _rgb2rgb(col):
"""
Transform RGB tuple with values 0-255 to tuple with values 0-1
"""
return tuple([ i / 255. for i in col ]) | 9ae21df6651a7df8c9e015a3d36ccac9a5a5538c | 608,884 |
import unittest
import fnmatch
def find_test(entity, pattern):
"""
search for a unit test with a matching wildcard pattern
Looks for the first 'unittest.case.TestCase' instance where its identifier
matches the provided wildcard pattern.
"""
if isinstance(entity, unittest.case.TestCase):
... | f477f87b15c07c9ea81df2f067fca7241075fa63 | 608,886 |
def parseRe(s, regex, message):
"""Parse a regular expression at the head of a string.
[ (s is a string) and
(regex is a compiled regular expression) and
(message is a string describing what is expected) ->
if s starts with a string that matches regex ->
return (head, t... | f5104d1a811df751d4d2904cfb76cb878828c475 | 608,887 |
def sphere(ind):
"""Sphere function defined as:
$$ f(x) = \sum_{i=1}^{n} x_i^{2} $$
with a search domain of $-5.12 < x_i < 5.12, 1 \leq i \leq n$.
The global minimum is at $f(x_1, ..., x_n) = f(0, ..., 0) = 0.
It is continuous, convex and unimodal.
"""
return sum((x ** 2. for x in ind)), | 2870c0b0e97f0ba8f2f3eb38a3e7e2a69dccf887 | 608,889 |
def est_nb_apartments(net_floor_area):
"""
Estimates number of apartments based on net floor area, according to
statistics of TABULA:
[Institut für Wohnen und Umwelt - IWU 2009] INSTITUT FÜR WOHNEN UND
UMWELT - IWU: TABULA Average Buildings: German residential building
stock. http://s2.building-... | 5488a8bcdc715c180e77f7dc5d6a9480a930c287 | 608,892 |
def list_to_string(list):
"""
Converts list to string.
:param list: List to convert.
:return: String
"""
string = ""
for a in list:
string = string + a + " "
return string.strip() | 2ce37a3780782654383c34b0c9594700d0799bef | 608,894 |
def subtract_weights(weights_to_subtract, subtract_from):
"""
Subtract weights from some other number
e.g. useful to convert e.g. from fraction of land to ocean (where
ocean fractions are 100 - land fractions)
Parameters
----------
weights_to_subtract: str
Name of the weights to su... | dabe7969d552c179c779b85a1241ee2872b5a775 | 608,895 |
def _slice_at_axis(shape, sl, axis):
"""
Construct a slice tuple the length of shape, with sl at the specified axis
"""
slice_tup = (slice(None),)
return slice_tup * axis + (sl,) + slice_tup * (len(shape) - axis - 1) | 113bc565cbaae7853ad03ec1891cde7d66eef4a9 | 608,899 |
def split_factory(split_by=',', cast_to=list, remove_empty=True, strip = True):
"""
Creates a uniform function split by a selected expression.
:param str split_by: Splitting expression
:param type cast_to: Result type
:param bool remove_empty: Determines if empty strings should be added to the cont... | fbbefee0743ced82099da1314ab605541c913551 | 608,900 |
def count_images_in_classes(lbls):
"""
Determining number of images in a class for Graph
:param lbls: Labels (different classes)
:return: Dictionary of labels and count
"""
dct = {}
for i in lbls:
if i in dct:
dct[i] += 1
else:
dct[i] = 1
return dc... | a564697ce0f0823926cd5b29a4cad1ff7eedf505 | 608,904 |
def s(b):
"""Convert a bytes object to a str, decoding with latin1 if necessary"""
if isinstance(b, str): # Python 2
return b
elif isinstance(b, bytes): # Python 3
return b.decode('latin1')
else:
return b | 7bfa2937e7ca4498d191a3bba7831d2e9987715f | 608,905 |
import hashlib
def get_file_content_hash(file_path):
"""
Return the file content hash for a file.
"""
with open(file_path, 'rb') as content:
hasher = hashlib.sha256()
hasher.update(content.read())
return hasher.hexdigest() | 07f6ff32632a151699ab455e86527f69624a3cf5 | 608,906 |
def _getDictWithKey(key, dict_list):
""" Returns the first dictionary in dict_list which contains the given key"""
for d in dict_list:
if key in d:
return d
return None | 52ce0870e5589cb9d439b658d4a6f877657ca205 | 608,907 |
def rgb_to_triple(rgb):
"""
Returns triple of ints from rgb color in format #xxxxxx.
>>> rgb_to_triple("#00bd28")
(0, 189, 40)
"""
if rgb[0] == '#':
return (int(rgb[1:3], 16), int(rgb[3:5], 16), int(rgb[5:8], 16))
else:
raise ValueError("Not an rgb value.") | 520be7ebfaf61a80471be967fd38344b223bc3ee | 608,909 |
import asyncio
import io
async def get_stats(socket_path):
""" Reads haproxy statistics from haproxy stats socket.
Args:
socket_path: A str - path to the haproxy socket on the file system.
Returns:
A StringIO buffer containing data from socket.
"""
reader, writer = await asyncio.open_unix_connectio... | 2d0a591e605ea1cb8a642ae0eba9dfa8bbb6a425 | 608,911 |
def get_wordvec_vocab(filename):
"""Load vocab from file
Args:
filename: path to the glove vectors
Returns:
vocab: set() of strings
"""
print("Building vocab...")
vocab = set()
with open(filename) as f:
for line in f:
word = line.strip().split(' ')[0]
... | 1a07b66d6734c17afcceb0300ebbaab76d542e9a | 608,912 |
def low_dim_sim_dist(x, a, b, squared=False):
"""
Smooth function from distances to low-dimensional simiarlity. Compatible with numba.njit
:param x: np.array pairwise distances
:param a: float shape parameter a
:param b: float shape parameter b
:param squared: bool whether input distances are al... | a7062f3bd9c1900541b0701d8adaa91cd13b2bfa | 608,913 |
def encodeXMLName(namespace, name):
"""
Encodes an XML namespace and name into a UTF-8 string.
If namespace is None, returns "name", otherwise, returns
"{namespace}name".
"""
if not namespace:
sname = name
else:
sname = u"{%s}%s" % (namespace, name)
return sname.encode("... | 4ed689c7087a5e5e26156ec0f2fe93cf8ffd23a7 | 608,914 |
def _check_dict_keys(mapping, valid_keys,
key_description, valid_key_source):
"""Check that the keys in dictionary are valid against a set list.
Return the input dictionary if it is valid,
otherwise raise a ValueError with a readable error message.
Parameters
----------
ma... | 5d137fecfc20161460b8d4c289471bf053a91063 | 608,916 |
def getSizeUserIndexes(cursor):
""" Get the size of the user indexes"""
try:
cursor.execute("select sum(leaf_blocks * 0.0078125) from USER_INDEXES")
size = cursor.fetchall()[0][0]
if size == None:
size = 0
except:
size = 0
return size | 97dd856f72ba73e5cc1ec7eca0233c6c8f35510a | 608,920 |
def lon_to_360(lon):
"""This is a function for converting input city's lon from (-180, 180) to (0, 360)
ref: https://gis.stackexchange.com/questions/201789/verifying-formula-that-will-convert-longitude-0-360-to-180-to-180/201793
Parameters
----------
lon : float
longitude ranges from -1... | d84cfacf9dff1a9a15f8f45241b0a008b54d37b3 | 608,921 |
def sanitize_weka(text: str, remove_newlines=True, escape_doublequote=True, escape_singlequote=True,remove_separator=None) -> str:
"""
sanitize this text for weka CSV importer.
Parameters:
remove_newlines(Bool): removes newline charaters and replaces them with blank spaces. Default: Tr... | 4f3ff22636817c42ca6d4283a996160d8337d62c | 608,922 |
import torch
def hamming_distance(logits, targets, cost_scale=1.0):
"""
Computes Hamming distance (https://en.wikipedia.org/wiki/Hamming_distance), which is
defined as the number of positions where two sequences of equal length differ. We apply
Hamming distance locally, incrementing non-gold token sco... | fd0cbe375a7e251fc61b8321ac4d375c78a42fd5 | 608,924 |
def ind_complement(inds, n):
"""Return the indices below ``n`` not contained in ``inds``.
"""
return tuple(i for i in range(n) if i not in inds) | 997530eb84ed61bc260c133a3f5783a72bdd27a0 | 608,928 |
def get_list_by_id(driver, id):
"""Get list of values for Towns or Flats
Args:
driver (webdriver): Selenium Webdriver
id (str): 'Town' or 'Flat'
Returns:
list (str): Returns list of values that can be selected
"""
try:
flat_list = [
a.get_attribute("valu... | f6e2a6d37117427d7ac55922d714113eb1461552 | 608,929 |
import torch
def cardinal_omega(features: torch.Tensor):
"""Compute Card(Omega) based on the target image feature size."""
return features.shape[-1] * features.shape[-2] + 1 | 48079c50395eda553efc517f90f5905946cca228 | 608,931 |
def format_unix_time(unix_time, style=None):
"""
Formats unix time to Discord'stimestamp markdown format.
For formatting details please check out ``TIMESTAMP_STYLES``, which contains the usable styles.
Parameters
----------
unix_time : `int`
The datetime to format.
style :... | 2d1e599729d181432aa88aff61c8ccb40da70230 | 608,933 |
def calculate_threshold(active_count: int) -> int:
"""Calcola la soglia di voti a favore necessari al passaggio di una proposta.
Per ora il criterio è maggioranza assoluta.
:param active_count: totale aventi diritto al voto
:returns: soglia affinchè la proposta passi
:rtype: int
"""
return... | 9c1a3710b08ef1207420a4fe8977b2ed1a3bbd04 | 608,934 |
def dict_of_load_relays(relays, buses_with_loads):
"""
Create dictionaries of the relay keys from the
load elements
"""
load_relays = {k: list() for k in buses_with_loads}
for relay_name, relay in relays.items():
load_relay_mappings = relay['load']
if load_relay_mappings:
... | 59c9744422373a869c5bd005be29aac41f3366e1 | 608,936 |
def staff_client(client, staff_user):
"""Return a Django test client logged in as an staff member."""
client.login(username=staff_user.email, password='password')
return client | 54af2d44a51a69c5d88be8180bcf6d54b336f00a | 608,937 |
def spatial_index(benefit_vector, get_neighbours):
"""
Calculate spatial inequality for a benefit distribution with N elements,
according to the (latex) definition:
\\[
\\frac{
\\sum_{i=1}^{N} \\frac{1}{N_i} \\sum_{j=1}^{N_i} \\left| y_i - y_j \\right|
}{
\\sum_{i=1}^{N} y_i... | 39a60381e7da8ce5d32d12223dca5d2074e9465d | 608,938 |
def get_size_to_pretty(the_size, in_bits=False):
"""
Get a pretty string of a number of bits or bytes
:param the_size: The Size in bits or bytes
:param in_bits: Should the pretty string show bits?
:return: A pretty string, reduced version of the_size
"""
if the_size >= 1000000:
retur... | 6238752d976262398e5a7f418498f7c2ae984253 | 608,939 |
def insert_values(path, instance):
"""
Insert values from object into the path string
Example: "/{test}/" (self.test = "pyon") -> "/pyon/"
:param path: Path string where the values should be inserted
:param instance: Instance (mostly 'self') which includes the values
:return:
"""
return... | 1e0722a58165cc1fb369c8e7e2380a3e7029bb75 | 608,943 |
from pathlib import Path
def firstexisting(filelist, path=Path('.')):
"""Return the first existing file in file list."""
fullpaths = [Path(path) / filename for filename in filelist]
for fullpath in fullpaths:
if fullpath.exists():
return fullpath
raise FileNotFoundError(f'None of ... | 617c4a95019a52ea3d4e5ca169982234dc5318ed | 608,946 |
def get_binary(community):
"""Binary variables for community."""
return [f"y_{org_id}" for org_id in community.organisms.keys()] | 4f92ac9c80dcf3125f9825aacbf304e6fb689605 | 608,952 |
from typing import Union
from typing import Dict
from typing import Any
from typing import List
from typing import Optional
def traverse_json(
obj: Union[Dict[str, Any], List[Dict[str, Any]]], path: Union[str, List[str]]
) -> List[Any]:
"""Extract an element from a JSON file along a specified path.
This ... | 4e7c48cf76b993a7bbdd143223660cc0374c671d | 608,954 |
from typing import List
from typing import Dict
from typing import Optional
def validate(schema: List[Dict],
record: Dict,
quiet: Optional[bool] = False) -> bool:
"""
Validate a metadata record against a schema. This checks that the
key names match and there aren't fewer or more ... | 49f24e410dcc3c84c2d3fff786bba25a9ec86715 | 608,957 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.