content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def find_exchange_or_parameter_by_id(dataset, uuid):
"""Find exchange or parameter in ``dataset`` with id ``uuid``.
Raises ``ValueError`` if not found in dataset."""
for exc in dataset['exchanges']:
if exc['id'] == uuid:
return exc
for param in dataset.get('parameters', []):
... | 33619132cc574b8b1e23034138f22c8519e6d2f4 | 608,229 |
import pickle
def load_obj(name, path):
"""
Parameters
----------
name : string
the named of the pkl file that will be loaded.
path : string
the full path of the intended file.
Returns
-------
type of the object within the file
the object in the specified file... | 26e28c6bbc9352535a2ce61bc4b420ca574236ca | 608,231 |
def geometric_depth_of_field(focalLength, fNumber, objDist, coc, grossExpr=False):
"""Returns the geometric depth of field value
Parameters
----------
focalLength : float
focal length in length units (usually in mm)
fNumber : float
F/# of the optical system
objDist : float
... | 2395efd833cfac1c6fb5989d837b140ac1e0be48 | 608,232 |
def url_add_trailing_slash(uri: str) -> str:
"""Add trailing slash to url if this is valid
Parameters
----------
uri : str
Web address to update
Returns
-------
str
uri or updated uri
"""
if len(uri) == 0 or uri[-1] == "/":
return uri
split_uri = str.s... | cf77459af356e6d49dc073cb0865f496dcf4d386 | 608,235 |
def get_investment_data(client):
"""
Fetch investment data from database.
returns a list of datastore entities.
"""
query = client.query(kind="TrendsData")
entities = list(query.fetch()) # a list of every entry of kind TrendsData
return entities | f2c7f518c4d9130b8accedb503b1f29f4fe906a6 | 608,241 |
def get_kernel(layer):
"""Returns the kernel weights of a layer, i.e, w/o biases."""
ret = [x for x in layer.get_weights() if len(x.shape) > 1]
assert len(ret) == 1
return ret[0] | 5e723195ce0f13b58e5a56717a385fa3189d0ad5 | 608,245 |
def inpoly(xv, yv, xt, yt):
"""
Originally in C by Bob Stein and Craig Yap
http://www.visibone.com/inpoly/
Converted to python by Bryan Miller
2013.04.18
Inputs:
xv - x vertices of polygon (does not have to be 'closed', ie. last = first)
yv - y vertices of polygon
xt - x of tes... | bc6f847813620c5ad92a59a56e1d8f643b6d82eb | 608,246 |
def read_vs30_file(vs30_file):
"""Read vs30 file"""
values = dict()
with open(vs30_file) as f:
for line in f:
station, value = line.split()
values[station] = float(value)
return values | 19ec9acdea4a8ec592de67bf06a786f124f13bf3 | 608,250 |
def replace_methodname(format_string, methodname):
"""
Partially format a format_string, swapping out any '{methodname}' or '{methodnamehyphen}' components.
"""
methodnamehyphen = methodname.replace('_', '-')
ret = format_string
ret = ret.replace('{methodname}', methodname)
ret = ret.replac... | 9db13b131fa08347b0ee04bd81e79aa89a93961b | 608,255 |
def print_header(meta, lang, comment):
"""print the header of the lexicon, filled in with WN-LMF meta data"""
header = str()
if comment:
header += ("""<!-- {} -->\n""".format(comment))
header += (""" <Lexicon id="{}" \n""".format(meta['id']+'-'+lang))
header += (""" label="{}"... | 7c1b4d28b7893cc505de7dfb87b2605d8cfecf2e | 608,257 |
def load_points(filename: str) -> set:
"""
Loads a set of x,y points from the specified text file.
Each point should be listed on its own line and be a pair of comma separated integers. Invalid points, whitespace, and
Python style comments are ignored.
:param filename: A string specifying the text... | 52d47436466120a1fe8bd8b16fe7574746e5dcf2 | 608,259 |
def check_unpublished(val: str) -> bool:
"""
Returns True if value is "TBA" or None.
:param val:str:
"""
return val is None or val == "TBA" | c8e7282f153f1753cc23d4d9a4678ed463d38edb | 608,261 |
import requests
def request_data(call_url):
"""
Get the results of an API request.
Args:
call_url (str): URL for the API request specified as a string.
Returns:
list of dictionaries containing results of the API request.
"""
r = requests.get(call_url)
response_dict = r.js... | bf85c562adac92a92e921298ec6ed13f111d1199 | 608,263 |
def get_relevant_keys(agent_key, all_keys_for_role, ontology, direction):
"""Return relevant agent keys for an agent key for refinement finding.
Parameters
----------
agent_key : tuple or None
An agent key of interest.
all_keys_for_role : set
The set of all agent keys in a given sta... | 7f1d062f9369ebea0694287ee56867287fbbbbfd | 608,271 |
def read_dices(string):
"""Read a tuple of dice values from string.
From a given string, values sepaated by ',', are extracted and returned
as tuple.
Arguments:
string: (str) string with comma separated integer values
Returns:
tuple: (tuple) containing read dice values
Exampl... | 06716b6b1416af1aae41356ffd2089e49c464d25 | 608,273 |
def get_allowed_tokens_from_config(config, module='main'):
"""Return a list of allowed auth tokens from the application config"""
env_variable_name = ""
if module == "main":
env_variable_name = 'DM_ANTIVIRUS_API_AUTH_TOKENS'
elif module == 'callbacks':
# though SNS uses the "Basic" auth... | ade52605bf0c390091fc201a01c010ec8d1a0a46 | 608,274 |
import re
def remove_false_titles(text):
"""Removes title lines that don't contain any word.
Args:
text (string): markdown text that is going to be processed.
Returns:
string: text once it is processed.
"""
false_title_regex = re.compile(r'^#+ *([^\-\w¿\?\n]*)$', re.MULTILINE | re.UNICODE)
processed_text ... | 2c2eb13d2e559f8b0c9d653c8b196b37d03b80f0 | 608,277 |
def merge_adjacent(rels):
"""
# Nothing to merge
>>> merge_adjacent([{'target_ids': ['target_1_4'], 'target_names': ['Big'], \
'cont_ids': ['element_30_32'], 'cont_names': ['Ca']}])
[{'cont_ids': ['element_30_32'], 'target_names': ['Big'], 'target_ids': ['target_1_4'], 'cont_nam... | b4debe1176aed8282ae0d34b32dfe5c265bf31ca | 608,280 |
def nb_emprunts(data):
"""
calcule le nombre d'emprunts dans le jeu de données argument
arg: data (list of lists)
return: int
"""
res = 0
for item in data:
res += int(item[-1])
return res | 67532d4deba1902f8376f714d10be80181a120dc | 608,282 |
def parityOddCount(a: int, b: int, char, string):
"""Ensure that the count of occurrences of char in string in positions a & b is exactly 1"""
return (string[a-1] == char) ^ (string[b-1] == char) | 948d72d12b57b2d2e40da1aefeba3f200bdb1fdc | 608,284 |
def with_services(services=[]):
"""
Decorator function
Checks if there specific services available
If not then it throws an error
Examples
--------
Check that specific services exist
@with_services(services=['read_pressure'])
def myfunction(self):
...
self.services.... | ce451a68c6c76fda48ec05033a6efd6df1b70c8d | 608,290 |
def sort_dictionary_by_desc_value(dictionary):
"""sorts a given dictionary in descending order of value"""
return {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1], reverse=True)} | 97da18dfa2ac3f16aec070859934ca46a025ab45 | 608,298 |
def locateFasc(intersections, refPoint, ycalib):
"""
Function that caracterizes each fascicle location by a float value
corresponding to the horizontal distance between
refPoint and the intersection of the fascicles with deep aponeurosis
Ideally, refPoint is the intersection point between the two ap... | d66367a0097e0b383d7d2a432db0a8af88379cae | 608,301 |
def integer_bit_count(number):
"""
Returns the number of set (1) bits in an unsigned integer.
:param number:
An integer. If this is a negative integer, its absolute
value will be considered.
:returns:
The number of set bits in an unsigned integer.
"""
# Licensed under the PSF License.
#... | 81ed42255deb1f459e3164ee4cd5d33537961e53 | 608,302 |
def last(*args):
"""Find the last item of an iterable or series of inputs."""
if len(args) > 1:
l = list(args)
return l[-1]
if type(args[-1]) is int:
return args[-1]
return list(args[0])[-1] | 5555f9a9e80f09babe1c65d9f0091dcd8baa2e67 | 608,303 |
import hashlib
def _h_value(s):
"""H function of the DIGEST-MD5 algorithm (MD5 sum).
:Parameters:
- `s`: a string.
:Types:
- `s`: `str`
:return: MD5 sum of the string.
:returntype: `str`"""
return hashlib.md5(s).digest() | cbe1d8aef7481cdb23dd77c2eed2ecc54d596f68 | 608,305 |
def diff_string(x, y):
""" generated source for method diff_string
x and y are strings
Return a string which consists of all characters in x which are
not in y.
"""
b = [c for c in x if c not in y]
return (''.join(b)) | 85fff7c76bc7deea807dccfb7c9489e8bbd2c9bf | 608,311 |
def children(persons, households):
"""
Indicates the presence of children in the household (0, 1).
"""
min_age = persons.local.groupby(
'household_id')['age'].min().reindex(households.index).fillna(0)
return (min_age < 18).astype(int) | d09ed0d2c3b8c77f7a039b1bc895762e314436b2 | 608,312 |
from typing import List
def get_mid_slice_indices(num_slices: int, mid_slice_range: int) -> List[int]:
"""
Get the indices of the slices around the mid-slice image.
Args:
num_slices: The number of slices of the volume.
mid_slice_range: The number of slices around the mid-slice image on ea... | 59aabfd42153afa77eabe2ea85cf7821af4d1abb | 608,313 |
def submitted_count(drafts):
"""
Get count of submitted services
Defaults to 0 if no submitted services
:param drafts:
:return:
"""
return drafts.get('submitted', 0) | 2e6f17f71bd58e2d08c438b8bb63ca90cf5bf6b0 | 608,314 |
from pathlib import Path
def model_config_dict(path):
"""
Function returning a dictionary with the model configuration inferred from the file name.
Parameters
----------
path :
Path to the model, either string or pathlib.Path object.
Returns
-------
config : dict
Dict... | 83c94954798e0afaef4fe04abff7a922c62329cc | 608,316 |
def get_attn_pad_mask(key):
"""
# pad mask is to shield the padding position, which is used to fill all the samples to the same length.
:param key: [batch_size, len_k], information before embedding
:return: pad_mask: (batch_size, 1, len_k) : means all the queries positions are the same, while every samp... | 29a454ced2db28b36ac32fc807d7af361196debc | 608,320 |
import re
def newickStripNames(newick):
"""
Strips newick code of coordinates
:param newick: Newick code of format comparable to: "((45_92,(28_182,11_182)18_90)19_1)19_1;"
:return: Same code but with leaf and internal node names replaced or removed
"""
P_internalNodes = "(\)\d+_\d+)"
P_lea... | 6a8d1f4521c79e6df4280e29d254b081cbfcae22 | 608,323 |
import re
def version_compare(version_a, version_b):
"""
Compare two versions given as strings, taken from `here`_.
.. _here: http://stackoverflow.com/questions/1714027/version-number-comparison
:param version_a: version a
:type version_a: string
:param version_b: version b
:type... | 1085b6abcaf9de5c7ae86a6ab917811aa04818fb | 608,324 |
import time
def is_open(epoch, specs):
"""Given a list of spec classes (as returned by parse_opening_times),
returns true if the time (in Unix epoch-seconds) is within the specified range"""
t = time.gmtime(epoch)
weekday = t.tm_wday # Monday is 0, same as we use here
hour = t.tm_hour + t.tm_m... | 87b8ee1a26b9d891502d42e9c69d5e174cdb772e | 608,325 |
def _GridSizer_CalcRowsCols(self):
"""
CalcRowsCols() -> (rows, cols)
Calculates how many rows and columns will be in the sizer based
on the current number of items and also the rows, cols specified
in the constructor.
"""
nitems = len(self.GetChildren())
rows = self.GetRows()
c... | a98309d5aa843757072e6bf8a38eb2b0cdb307ef | 608,328 |
from typing import Dict
def vcr_config() -> Dict:
"""A shareable configuration for VCR.use_cassette call."""
return {} | 1cd3a6a437e4ac9933328c4c3bd1f9520d1242c9 | 608,329 |
def remove_none(l: list) -> list:
"""
Returns a list that does not contain any`None` values.
@param l: The list to filter
@return: a new list
"""
return list(filter(None, l)) | 5b91cff982ffaf47c390954601167f60843ae67f | 608,332 |
def _null_cast(dic, key):
"""
Allows the user to load value, given key from the dictionary. If the key
is not found, return "null".
Args:
dic (dict): Dictionary in look for (key, value) pair
key (str): Key to look search in the dictionary
Returns:
type: str
... | 6836a4bc59b3afb6daab53899bdc9550dbe2ff52 | 608,333 |
def b128_decode(data):
"""Performs the MSB base-128 decoding of a given value. Used to decode variable integers (varints) from the LevelDB.
The code is a port from the Bitcoin Core C++ source. Notice that the code is not exactly the same since the original
one reads directly from the LevelDB.
The decodi... | c53b7991026abdcff30107bbe4420388467881e3 | 608,336 |
def get_photo_image_name_from_img_src(img_src, exclude = '_display'):
"""Parses img_src gotten from photologue's .get_display_url() (or thumbnail)
(E.g. "to_del_photo_/media/photologue/photos/cache/ImageName_rndnumbers_display.jpg")
and returns a substring of photo's image's name. (E.g. "ImageName_rndnumber... | 6e76944bc3300544727687fe3710375393a5d940 | 608,339 |
def clean_str(
s: str,
l: list,
r: list,
) -> str:
"""Replace substrings within a given string
Parameters
----------
s : str
The string
l : list
The list of substrings
r : list
The list of replacement substrings
Returns
-------
str
Th... | 1011679d3ad1f600d5bb5b3b6e937001aa59fcc4 | 608,347 |
def format_precincts_percent(num):
"""
Format a percentage for precincts reporting
"""
if num > 0 and num < 1:
return '<1'
if num > 99 and num < 100:
return '>99'
else:
return int(round(num)) | 486c0a313afc43df035333e6519df02ae0ceeb0d | 608,352 |
from typing import List
def list_to_str(a_list: List, sep: str = ', ') -> str:
"""Converts a list to string.
Args:
a_list: The list to convert to string.
sep: Separator between elements.
Returns:
String representation of the list.
"""
return sep.join(a_list) | 264cd1e108e39ef24df65b97175c2ba117112196 | 608,353 |
def paint_houses(n, m, cost):
""" Paint a list of N houses and M colors, each combination has cost,
minimize the total cost without color in row.
Args
n - number of houses
m - number of colors
cost - cost matrix of each combination. Format {color1: {color2: cost}}
Returns:
... | edf061bbd3d7cc8ce07b9080f3fa4eb5768aad37 | 608,356 |
async def hello():
"""Returns a friendly greeting 👋"""
return {"messsage": "Hello World!"} | 67452817228cfbed9e64a3d706aa01fb8ff32c4d | 608,358 |
import torch
def my_around(x, decimals, inplace=True, floor=False):
"""
保留到指定的小数位数。(类似于 np.around() 函数)
round/floor to the given number of decimals.
参数:
x: input tensor
decimals: 要保留的小数位数
可选参数:
floor: 采用四舍... | 7331929f457fdea0cd7e9e461fbe264bc29d153c | 608,361 |
def get_subclasses(classes, level=0):
"""Return the list of all subclasses given class (or list of classes) has.
Also see https://stackoverflow.com/q/3862310/84349.
"""
if not isinstance(classes, list):
classes = [classes]
if level < len(classes):
classes += classes[level].__subcla... | 11e6cdd6d4c49b04524183e6ca99fe8e1d7d1eb8 | 608,366 |
def climbStairs(n, dic = {0:0,1:1,2:2}):
"""
LeetCode-Problem:
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Solution:
Exploring all possible ways to climb the stairs in 1 or 2 s... | cb006101f093b4aaf7f0ecf71b03ed74ec149e12 | 608,367 |
def reshape(a, *args):
"""
Gives a new shape to an array without changing its data.
:param a: (*array_like*) Array to be reshaped.
:param shape: (*int or tuple of ints*) The new shape should be compatible with the original
shape. If an integer, then the result will be a 1-D array of that l... | e369a81ec15a07eac018e68104e65e084a26f622 | 608,369 |
def residual_stddev(
df,
param=[
"BTL_O",
"BTL_C1",
"BTL_C2",
"C1_C2",
"BTL_T1",
"BTL_T2",
"T1_T2",
"BTL_SAL",
"BTL_SAL_UP",
],
):
"""Calculate standard deviations of parameters or residuals.
Input:
df - dataframe containing... | a24bb798c978ea64c1d12a8277edaa3d59236695 | 608,371 |
def color(content, option="match"):
"""
Change color content to color of option:
+ match pattern
+ line-number match pattern
+ path match pattern
"""
if option == "match":
# color same key
return '\033[30;43m{}\033[0m'.format(content)
if option == "line":
... | 10f2c5b76eeecaf2b01ff45bb86ee54405e4173d | 608,373 |
def isInPar(db, chrom, start, end):
""" return None if not in PAR or "1" or "2" if genome is hg19 or hg38 and chrom:start-end is in a PAR1/2 region """
if db not in ("hg19", "hg38"):
return None
if not chrom in ("chrX", "chrY"):
return None
# all coordinates are from https://en.wikipedi... | b2728baa4b1659062276289b34ec1055708f7aaa | 608,374 |
def col_index(s_i: int) -> int:
"""col index [0, 1, ... 8] on the 9x9 board from the state index [0, 1, ... 80]"""
return 3 * ((s_i // 9) % 3) + s_i % 3 | 58b7e6172807dda42f35cd556bcbcc8275fa6e36 | 608,375 |
from pathlib import Path
def star_align_kws(tmpdir):
"""Example kws for star_align."""
output_dir = Path(str(tmpdir / 'out'))
return {
'fastq_path': Path('sample.R1.fastq.gz'),
'index_path': Path('index'),
'output_dir': output_dir
} | a813b5db83ab3f77a5b0e620e848342f41d9986a | 608,381 |
def convert_snake_to_cammelcase_string(snake_str, first_lower = False):
"""
Converts snake to cammelcase
:param snake_str: as described
:param first_lower: if you want to start the string with lowercase as_said -> asSaid
:return: cammelcase string
"""
components = snake_str.split('_')
... | 7e1905dae3b651dbcb06c114168d7b08e529664b | 608,382 |
def parse_stats(tup):
"""
Parses read stats using MP after reading
:param tup: (key, (aln_scores, mapq_scores, sramm_scores)) tuple
:return: read_id, mapq value(s), sramm metric scores
"""
# data[k] = [(int(x[0]), int(x[1])) for x in
# [t.replace('(', '').replace(')', '').sp... | 6b85322429d056ae29daea21c769c51a6b94bf66 | 608,384 |
def by_schema(cls, **kwa):
"""
Will return only those claims that are listed in the Class definition.
:param cls: A subclass of :py:class:´oidcmsg.message.Message`
:param kwa: Keyword arguments
:return: A dictionary with claims (keys) that meets the filter criteria
"""
return dict([(key, va... | 38ca8f6225649684e76723705fef1f2ab0b3f84f | 608,387 |
def arraysIntersect(a1, a2):
"""Tells if two array share at least one element."""
for e in a1:
if e in a2:
return True
return False | f8a17541c8313290c36b40480814b00f32acec38 | 608,388 |
def get_mass(root):
"""Extracts the total ash mass loading - only valid for ash alerts!
Values returned are in this order:
1. Total ash mass
2. Total ash mass unit"""
mass = root.alert.total_mass.attrib.get('value')
mass_unit = root.alert.total_mass.attrib.get('units')
return mass, mass_unit | 284122220bfc7b59e27ca3e0d401583baeb72d47 | 608,391 |
def get_info(information):
"""
Retrieves title of the source
For example, from the information below,
HYPERLINK("https://drive.google.com/open?id=0B9q-Bz2y-5byRWZwRHptZmk0eU0","Baby And Her Health")
Returns `Baby And Her Health`
"""
information = information.lower()
if information.starts... | ff3576efd3cd32cdfbe8c844971021381d5cea93 | 608,394 |
import click
def int_string_tuple(ctx, param, value=None):
"""
Parse a pair of strings that represent a string and a number.
Either number, string or string, number is allowed as input."""
if not value:
return None
assert len(value) == 2
try:
number, string = int(value[0]), v... | d7ce9a34318f2a0b1a9ed0fc3c41fafd31e9c919 | 608,395 |
from pathlib import Path
def no_write_perm_path(tmp_path_factory):
"""
A path with no write permission
"""
# create a conda_env directory
bad_perm_path = tmp_path_factory.mktemp("bad_perm_path")
Path(bad_perm_path).chmod(0o444)
return bad_perm_path.as_posix() | f7b8017cea9813156b872cdd4101c72345fcc803 | 608,396 |
def _reasonable_histogram_range(arr):
"""Return 'range' argument for np.histogram
Fixes problem with too small default ranges
which is roughly arr.max()-arr.min() < 1e-08.
We take 5*e-8 as threshold in order to be safe.
Parameters
----------
arr: array
array to calculate histogram ... | ba4fe05b561d6b854aa966cef5ceecc7b7350a6e | 608,397 |
def strip_additional_byte_order_marks(unicode_contents):
"""
Creditor Reporting System data seems to be in utf-16, but with multiple "Byte Order Marks" (BOMs) per file.
(probably due to cat'ing together several utf-16 files)
There is generally only supposed to be a leading BOM for a Unicode file.
Th... | f6fa80a89814c5493b04f2992423d8b4dbb67098 | 608,399 |
import torch
def create_link_label(pos_edge_index, neg_edge_index):
"""
Create labels for link prediction, based on positive and negative edges
Args:
pos_edge_index (torch.tensor): Positive edge index [2, num_edges]
neg_edge_index (torch.tensor): Negative edge index [2, num_edges]
Re... | e130b4e3f546f631021a266721bcc9787543cdf0 | 608,404 |
def derivative_order(derivative):
""" Rerturn the total order of derivative
.. Example:
>>> derivative_order(Derivative(u,t))
1
>>> derivative_order(Derivative(u,t,2,x,2))
4
"""
order = 0
for item in derivative.args[1:]:
order += item[1]
return order | 74384d62be855da11dd19ceb23dd92633fb813bb | 608,406 |
def replace_cp_in_dict_list(in_list, cp):
"""
Remove the common prefix (cp) for keys of filenames in a list of dictionaries.
e.g. for readme files.
"""
out_list = []
for d in in_list:
key, value = list(d.items())[0]
out_list.append({ key.replace(cp,''): value })
return out_list | 67b47402d0eef6f92a4f7e26199c6cf48d55abfe | 608,407 |
import itertools
def generate_ngrams(iterable, n):
"""Generator that yields n-grams from a iterable."""
return zip(*[itertools.islice(it, i, None) for i, it in enumerate(itertools.tee(iterable, n))]) | 361de8e1d1a2f02d0c38796eef2303449d365e78 | 608,410 |
def binner(min_size, max_size, bin_no):
"""
:param min_size lower bound of the interval to divide into bins
:param max_size upper bound of the interval to divide into bins
:param bin_no the interval will be divided into that many bins
:returns list of tuples, representing the lower and upper limits ... | 47ca3c04c81b892a13e57a235d3f3c4d72dabf4a | 608,411 |
def getProportionalControlDubins(client, cte, he):
""" Returns steering angle command using proportional control
for use with Dubin's car dynamics
Args:
client: XPlane Client
cte: current estimate of the crosstrack error (meters)
he: current estimate of the headi... | 5e55014eb4760376bae79553a9dba131e42cf621 | 608,416 |
def startswith(string, prefixes):
"""Checks if str starts with any of the strings in the prefixes tuple.
Returns the first string in prefixes that matches. If there is no match,
the function returns None.
"""
if isinstance(prefixes, tuple):
for prefix in prefixes:
if string.start... | 9a507aa2c4da6cb187023e5be28084b7b915feba | 608,418 |
def _flip_codons(codon_seq, target_seq):
"""Flips the codon characters from one seq to another."""
a, b = '', ''
for char1, char2 in zip(codon_seq, target_seq):
# no need to do anything if the codon seq line has nothing
if char1 == ' ':
a += char1
b += char2
e... | f5060ecb382b0edac35484a6e6dac2fe7e1e6902 | 608,419 |
def search_by_range(s, start_date=None, start_time=None, end_date=None,
end_time=None):
"""Search records on www.prosodie.com by date range and return session.
Input:
s -- Requestium session (required |
type: requestium.requestium.Session);
start_date -- start da... | 383863252793b2e5830a84210533a489b30d0b3c | 608,421 |
import math
def calc_transmissivity(G_value):
"""
Calculate window transmissivity from its transmittance using an empirical equation from Radiance.
:param float G_value: Solar energy transmittance of windows (dimensionless)
:return float: Transmissivity
[RADIANCE, 2010] The Radiance 4.0 Syntheti... | e5c5346191f6c224a3cc19616266c09e02d8eb06 | 608,425 |
def skip(app, what, name, obj, would_skip, options):
"""
Define which methods should be skipped in the documentation
"""
if obj.__doc__ is None:
return True
return would_skip | a286648f3cd7aba976750616a65b1e0a999caa8e | 608,426 |
def find_parameter(env, param, role=""):
"""
Find a parameter in an environment map and return it.
If paramter is not found return 0.
Supports role parameters too. E.g. given the following
inside of env, with param=CephHciOsdCount and role="",
this function returns 3. But if role=ComputeHCI, th... | 507862516cb99e3e07354c027dc373d24de879ee | 608,428 |
def reverse(list_a: list):
"""Problem 5: Reverse a List.
Parameters
----------
list_a : list
The input list
Returns
-------
list_a : list
The input list reversed
Raises
------
TypeError
If the given argument is not of `list` type
"""
if not isi... | ae7d40fc6e520367d62b2dcf4ceeca9597a7c770 | 608,429 |
def get_index_csv_data(data, entry_dict):
"""Get index of .csv header entries"""
indices = {}
for entry_key in entry_dict:
indices[str(entry_key)] = data[0].index(entry_dict[entry_key])
return indices | 47888e26da7236144dd3d1ae8c9eb3d2827725a2 | 608,433 |
def get_adopters_for_advertisement(adoption_center, list_of_adopters, n):
"""
The function returns a list of the top n scoring Adopters
from list_of_adopters (in numerical order of score)
"""
ranking = []
for ad in list_of_adopters:
ranking.append([ad, ad.get_score(adoption_center)])
... | f46177caa9b1df5d70ffe65d1d210acb0d334dad | 608,436 |
def get_param(dict, key, default):
""" Return value from dictionary if key present, otherwise return default value"""
val = dict[key] if key in dict else default
return val | 891382c280e56f49a2a96db8f03d4e9d0361bf28 | 608,444 |
def _truncate_description(original_description, word_cnt_to_include):
"""
This function will truncate the stripped doc string to a more manageable
length for incorporation into wrapped vistrails functions
Parameters
----------
original_description : list
This object is the original desc... | e6327e0406deb1c5ca5e207508f35fa6d49ab612 | 608,445 |
import math
def error_function(x, decimals=2):
"""
The error function, or `Gauss error function`_.
.. _`Gauss error function`: https://en.wikipedia.org/wiki/Error_function
The function returns the probability that a value in a normal distribution
is between :math:`\\frac{x}{sd\\sqrt{2}}` and :ma... | 0cf156ddccca1437e8450def42d82387faa7c9c3 | 608,447 |
def effect(effect_brushtype="stroke",
effect_scale=2.5,
effect_period=4,
**kwargs):
"""
:param effect_brushtype:
The brush type for ripples. options: 'stroke' and 'fill'.
:param effect_scale:
The maximum zooming scale of ripples in animation.
:param effe... | 4d09c5ecad17b566e38ab65bdd3ea2d30185655b | 608,448 |
def populate_obj(obj, data):
"""
Populates an object with the data passed to it
:param obj: Object to be populated
:param data: The data to populate it with (dict)
:returns: obj populated with data
:rtype: obj.__class__
"""
for name, value in data.items():
if hasattr(obj, name... | 4fbdb43677cf00a6dba1900e35586091ea4980df | 608,449 |
def guess_str_length(string):
"""Guess length of a unicode string (treat non-ascii characters in unicode as 2)"""
length = 0
for char in string:
length = length + 2 if len(char.encode('utf8')) == 3 else length + 1
return length | 482c66bffc0048f616151c09d247e9e7a222f02e | 608,451 |
def get_satisfying_states(model):
"""
>>> from simple_model import *
>>> m = SimpleModel(0.1, 0.95)
>>> get_satisfying_states(m)
set([(1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1)])
>>> from thomas_model import *
>>> m = ThomasModel(0.1, 0.25)
>>> get_satisfying_states(m)
set([(1, 1, 0,... | 9f30c2c9fb6a89a23edec69edef2f1af76247195 | 608,455 |
def make_member_list(members, **attr_map):
"""
Create a dict representation of a list of members which we can use
to serialize the members list. Keyword arguments map the names of
optional attributes to include to the database attribute.
"""
def _fetch_memb(memb, attr_map):
return {k: ... | e4c8b46bd52edbaa991445a019afe452f234c6ab | 608,457 |
def decint2binstr(n):
"""Convert decimal integer to binary string.
"""
if n < 0:
return '-' + decint2binstr(-n)
s = ''
while n != 0:
s = str(n % 2) + s
n >>= 1
return s or '0' | 3e8c58a56a2c4f2f02d11943df20ff6afe1e1efa | 608,458 |
def get_first_index(tokens, exclude_comment=True):
"""Given a list of tokens, find the index of the first token which is
not a space token (such as a ``NEWLINE``, ``INDENT``, ``DEDENT``, etc.) nor
a ``COMMMENT``. If it is desired to include COMMENT, set ``exclude_comment``
to ``True``.
Returns ``No... | b0f9083efba42de8182707c606c9812b9d5d4da3 | 608,459 |
def null_terminated(string):
"""Extract the NULL-terminated C string from the given array of bytes."""
return string.split(b'\0', 1)[0].decode() | 315687e7a6d204086eb9ff561f89bb605cd8b531 | 608,460 |
def _get_equality(analysis_1: dict, analysis_2: dict) -> dict:
"""Compares the two input dictionaries and generates a new dictionary,
representing the equality between the two.
Args:
analysis_1(dict): Eg: {'rs10144418': ['T', 'C'], 'rs1037256': ['G', 'A'],... }
analysis_2(dict): Eg: {'rs101... | 94859d1eb03bdfc656ab8fb70ce6eb4cabe89e35 | 608,461 |
def copy_dict(source, destination):
"""
Populates a destination dictionary with the values from the source
:param source: source dict to read from
:param destination: destination dict to write to
:returns: destination
:rtype: dict
"""
for name, value in source.items():
destina... | 72c97625a926715a7b1a0c7e3aad94fb9bf5ffb9 | 608,462 |
def q_from_m1_m2(mass1, mass2):
"""Return the mass ratio given the samples for mass1 and mass2
"""
return mass2 / mass1 | 7b7b1c1cd5b56261ed1e42d72f85bb7f9daecbc3 | 608,466 |
def build_url_with_cursor(base_url, cursor):
"""
Builds a URL with the given cursor
"""
return f"{base_url}&cursor={cursor}" if cursor else base_url | 594bfade3bf81c2195312771b733387f79a9ebbe | 608,472 |
from pathlib import Path
def valid_hostapd_config() -> str:
"""Get a valid hostapd config to compare."""
hostapd_config_path = Path("tests/data/hostapd/config.txt")
return hostapd_config_path.read_text(encoding="utf-8") | 893d2801525a2365a0abfd31b0ca43e654e9b9c8 | 608,475 |
def get_input_tool_name(step_id, steps):
"""Get the string with the name of the tool that generated an input."""
inp_provenance = ''
inp_prov_id = str(step_id)
if inp_prov_id in steps:
name = steps[inp_prov_id]['name']
if 'Input dataset' in name:
inp_provenance = "(%s)" % nam... | 336926d59b4409d095feac36b4ffe374fcf56755 | 608,476 |
import requests
def load_text_from_url(url, **data):
"""
Loads html from a URL
Parameters:
* url: url of page to load (str)
* timeout: request timeout in seconds (int) default: 20
Returns:
HTML (str)
"""
timeout = data.get("timeout", 20)
results = []
try:
... | 8049003baa840c58889e6702a8118d564a5b2bff | 608,477 |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
return list(name_or_flags), kwargs | 8078cc984c9131564ea6355adeaaafb1babbb434 | 608,480 |
def dist_euclidean_squared(coord1, coord2):
""" euclidean distance between coord1 and coord2"""
(x1, y1) = coord1
(x2, y2) = coord2
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) | 1287400286d306513563ed38f6d388916d916185 | 608,484 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.