content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def query(db):
"""Query the database for hosts that require client certificates.
Parameters
----------
db : pymongo.database.Database
The Mongo database connection
Returns
-------
pymongo.cursor.Cursor: Essentially a generator for a list of
dicts, each containing the pshtt sca... | b21f4e47664124dfe613b3579abfc5559c562b80 | 421,611 |
def round_masses(mass):
"""
Round all the masses for the output to 8 digits after comma
"""
if mass == '-':
return '-'
else:
return round(mass, 8) | bb7f3fbbda7fbc2453ab8dfd3060e9c92e1e54cc | 74,673 |
from datetime import datetime
def gen_today_file_name() -> str:
"""
generate today json filename
Returns:
today_in_history-*.json
"""
now = datetime.now().strftime('%m-%d')
file_today: str = 'today_in_history-%s.json' % now
return file_today | 37991e761021a1d5742b82359fbdf88d1d58f975 | 15,745 |
from datetime import datetime
def check_expiration(expiry_date: bytes) -> bool:
"""Check if the MRZ expiry date is older than today's date."""
date = expiry_date.decode("utf-8")
date_obj = datetime.strptime(date, "%y%m%d")
if date_obj.date() < datetime.now().date():
return False
return Tru... | fb0b6af3fd144fa31965074277aff3c9a6b665eb | 321,862 |
def map_val(val, in_min, in_max, out_min, out_max):
"""
Function based on the map function for the arduino
https://www.arduino.cc/reference/en/language/functions/math/map/
"""
return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min | f4caed41e549387966e36904545a5bd18001740c | 589,088 |
def get_list(node, tag):
"""
Get sub-nodes of this node by their tag, and make sure to return a list.
The problem here is that xmltodict returns a nested dictionary structure,
whose substructures have different *types* if there's repeated nodes
with the same tag. So a list of one thing ends up bein... | 1eebf70507960f4f97bb25ec5f4b728e80cd2b2a | 626,529 |
def gymnastics(lis):
""" Returns the average of the list. """
if len(lis) > 2:
lis = sorted(lis)
del lis[-1]
del lis[0]
return int(sum(lis) / len(lis)) | 0e535139be1ed80eee1319b68ad21753f7b4bb17 | 317,165 |
def sum_sequence(sequence):
"""
What comes in: A sequence of integers.
What goes out: Returns the sum of the numbers in the given sequence.
Side effects: None.
Examples:
sum_sequence([8, 13, 7, -5]) returns 23
sum_sequence([48, -10]) returns 38
sum_sequence([]) ... | 78c9a1ddf131ae34f12b051918d787cf9e240c7d | 513,746 |
def readcsv(infile, separator=',', ignoreheader=False):
"""Read a csv file into a list of lists"""
with open(infile, 'r') as f:
list_of_rows = [[x.strip() for x in r.split(separator)]
for r in f.readlines()]
return list_of_rows if not ignoreheader else list_of_rows[1:] | 4d590e9f5881db0d2278336bbb95dfd106416690 | 571,039 |
def _calculate_total_mass_(elemental_array):
"""
Sums the total weight from all the element dictionaries in the elemental_array after each weight has been added (after _add_ideal_atomic_weights_())
:param elemental_array: an array of dictionaries containing information about the elements in the system
... | 1c02c9ecbd09e7a3e74c7207dc435ee4e9ebbcf7 | 639,455 |
def polygon_clip(subject_polygon, clip_polygon):
"""
clip a polygon with another polygon
(ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python)
:param subject_polygon: a list of (x,y) 2d points, any polygon
:param clip_polygon: a list of (x,y) 2d points, has to be *convex*
... | 1145848a7cd5f59352f07dcd02dc0d6df9a91d62 | 295,177 |
def creds_changed(context: dict, identity_code: str) -> bool:
"""
Check whether the credentials were changed by the user.
Args:
context (dict): Integration context from Demisto.
identity_code (str): Lansweeper application identity code.
Returns:
creds_changed (bool): True if cred... | c41810e4a79141bf4213356c736f9551f5bb0254 | 234,685 |
from typing import Sequence
def html_open(style: Sequence[str]) -> str:
"""
HTML tags to open a style.
:param style: sequence of html tags without the '<' and '>'
:return: opening html tags joined into a single string
>>> style = ['font color="red" size="32"', 'b', 'i', 'u']
>>> html_open(st... | 581ef4dc25e4985d6c64bd96ec0d8089ee22d59c | 410,947 |
def _mobius(p, q):
""" Applies the mobius transformation that fixes the line from q to the origin
and sends q to the origin to the point p.
Parameters
----------
p : list of floats, length 2
The coordinate we are applying this transformation to.
q : list of floats, length 2
The ... | 190296816b2bc9403fdfcb362862c6e062502914 | 572,597 |
def is_tty(stream): # taken from catkin_tools/common.py # pragma: no cover
"""Returns True if the given stream is a tty, else False"""
return hasattr(stream, 'isatty') and stream.isatty() | dee3bb24aa2e7cd39fcbf0d63051c9c5a5980b52 | 588,826 |
def take_one(ls):
""" Extract singleton from list """
assert len(ls) == 1
return ls[0] | bfb1abb4a96aa08c6abd95ae53a8e6828730e08c | 560,554 |
def _process_wohand(data: bytes) -> dict[str, bool | int]:
"""Process woHand/Bot services data."""
_switch_mode = bool(data[1] & 0b10000000)
_bot_data = {
"switchMode": _switch_mode,
"isOn": not bool(data[1] & 0b01000000) if _switch_mode else False,
"battery": data[2] & 0b01111111,
... | e15d5d29b98a07155259f898474a2c9a90db7c02 | 530,393 |
import math
def split_list_equally(list_to_split: list, num_inter_lists: int):
"""
Split list_to_split in equally balanced lists among num_inter_lists
"""
if num_inter_lists < 1:
raise Exception("max_items_per_line needs to be greater than 0")
max_list_items = math.ceil(len(list_to_split)... | 4107f8db4e795c5f55e479c43d21757bf7f265e1 | 560,044 |
def make_timestamp_range(start, end):
"""Given two possible datetimes, create the query
document to find timestamps within that range
using $gte for the lower bound and $lt for the
upper bound.
"""
ts_range = {}
if start:
ts_range['$gte'] = start
if end:
ts_range['$lt'] =... | cf450f7f9c3f8dc239ed72924ad660438b677956 | 560,965 |
def reverse_probs(probs):
"""
Reverses the conditional probability assuming that variables are uniformly distributed
Parameters
----------
probs : probs[x][y] = Pr(Y=y | X=x)
Returns
-------
reverse : reverse[y][x] = Pr(X=x | Y=y) assuming X is uniform
"""
reverse = {}
for ... | 20a0b189027c76bbd4bbd1938778399a08a5d981 | 584,577 |
def unpack_twist_msg(msg, stamped=False):
""" Get linear and angular velocity from a Twist(Stamped) message. """
if stamped:
v = msg.twist.linear
w = msg.twist.angular
else:
v = msg.linear
w = msg.angular
return (v.x, v.y, v.z), (w.x, w.y, w.z) | 1182a9c5c9aff25cb2df261a32409d0b7df8d08d | 679,576 |
import random
import string
def get_random_key(n=10):
"""
Randomly generate string key.
:param int n: Length/size of key to generate
:return str: Randomize text key
"""
if not isinstance(n, int):
raise TypeError("Non-integral key size".format(n))
if n < 1:
raise ValueError... | 92fc680c7ad2a98cac8a842a51ef94fec5adfb4e | 307,300 |
def capacity_cost_rule(mod, prj, prd):
"""
The capacity cost of projects of the *fuel_spec* capacity type is a
pre-specified number with the following costs:
* fuel production capacity x fuel production fixed cost;
* fuel release capacity x fuel release fixed cost;
* fuel storage capacity x fuel... | c3c41b4e120c9a53812e1f5ba10bcb3f5325852b | 614,855 |
def get_list_by_separating_strings(list_to_be_processed, char_to_be_replaced=",", str_to_replace_with_if_empty=None):
""" This function converts a list of type:
['str1, str2, str3', 'str4, str5, str6, str7', None, 'str8'] to:
[['str1', 'str2', 'str3'], ['str4', 'str5', 'str6', 'str7'], [], ['str8']]
"... | 7702dd577145c910f4bedc67c85cae6fa7de0854 | 684,900 |
def write_list_to_file(list, file_to_write):
""" Iterates over the entries in a list and writes them to a file,
one list entry corresponds to one line in the file
:param list: the list to be written to a file
:param file_to_write: the file to write to
:return: 0 on success
"""
with open(fil... | ced1adf675d4fce9ef75e3bafe05b8458bf4fc32 | 485,054 |
import torch
def device(tensor=None):
"""
Get the available computaiton device
"""
return 'cuda' if torch.cuda.is_available() else 'cpu' | 0cbd033270d87a132043d64844411be4a75f90ab | 228,397 |
from math import sqrt
def meanstdv(members):
"""
Calculate mean and standard deviation of data x[]:
mean = {\sum_i x_i \over n}
std = sqrt(\sum_i (x_i - mean)^2 \over n-1)
"""
num, mean, std = len(members), 0, 0
for item in members:
mean = mean + item
mean = mean / float(num)
for item in... | d434c3214e2f558ff5b6ef260df0888c06ad4751 | 339,940 |
import struct
def ub32(b):
"""Convert bytes (LSB first) to a 32-bit integer.
Example:
ub32(b'\x12\x34\x56\x78') == 0x78563412
"""
(value, ) = struct.unpack('<I', b)
return value | 73b6e32711ba87d943a20cffb3b705029e8f4e05 | 335,027 |
import json
def dumpJson(path: str, data: dict):
"""
Dump data to json path.
Returns
-------
`tuple(path or exception, True or False)` :
First item in tuple is a path if dumping succeeds, else it's an exceptions. Same thing goes for the second tuple
"""
try:
with open(pat... | 22d568e0833ee325a273967c4752e15ca469c3e8 | 641,128 |
def mb(x):
"""Represent as MB"""
return x / 10**6 | a1300c4ca37d1517e40a4e4d558281eaa7f3848c | 492,233 |
import inspect
def derive_top_level_package_name(package_level=0, stack_level=1):
"""Return top level package name.
Args:
package_level (int): How many package levels down the caller
is. 0 indicates this function is being called from the top
level package, 1 indicates that it'... | e9ff1119cd02f01c355aef1e68fae55db7fbbba0 | 639,304 |
def get_all_sell_orders(market_datas):
"""
Get all sell orders from the returned market data
:param market_datas: the market data dictionary
:return: list of sell orders
"""
sell_orders = []
for _, market_data in market_datas.items():
for order in market_data:
if not orde... | 47fe504b72d9028d4d2e999ee4b748d9dae7f6ee | 101,156 |
import random
def calculate_retry_delay(attempt, max_delay=300):
"""Calculates an exponential backoff for retry attempts with a small
amount of jitter."""
delay = int(random.uniform(2, 4) ** attempt)
if delay > max_delay:
# After reaching the max delay, stop using expontential growth
#... | 7579c9b1a3bced2f9c111354f77c27526b66e066 | 366,548 |
def low_uint_bound_of_half(number):
"""
returns the low unsigned integer bound of a half of a number
(it is simply a right shift method)
"""
return number >> 1 | 76847fbf4a82c47406e983f7e9a1cc7e504c5a7e | 542,087 |
def distortion_correct(
x, y, x_d=3235.8, y_d=2096.1, A=0.0143, B=0.0078, r_d=1888.8):
"""Distortion correct pixel position according to Ken's model
where
x'=x_d+(x-x_d)*(1+A*(r/r_d)**2+B*(r/r_d)**4)
y'=y_d+(y-y_d)*(1+A*(r/r_d)**2+B*(r/r_d)**4)
"""
# calculate the radius of the ... | ee0cdb9411dbf151fdecddd338f75721bc561b37 | 315,685 |
from typing import List
def default_json_dir() -> List:
""" Default json path for access control entities """
return ["/etc/oidc-proxy/acl"] | 6c36e596f7ee0cadfef5e64d4998fb875133ef21 | 243,840 |
def get_env_dimensions(env):
"""
Returns the observation space and action space dimensions of an environment.
"""
return env.observation_space.shape[0], env.action_space.n | 26182dbe7ee76a5da74d939f5c9f3aafeaed4abc | 272,834 |
def version_to_string(version, parts=3):
""" Convert an n-part version number encoded as a hexadecimal value to a
string. version is the version number. Returns the string.
"""
part_list = [str((version >> 16) & 0xff)]
if parts > 1:
part_list.append(str((version >> 8) & 0xff))
i... | c766a2efdede43149d2592fbf3cbea1f6f279b4a | 22,788 |
def array_unique(array):
"""
Removes duplicate values from an array
"""
return list(set(array)) | 028642c36d7a86cf10d20bf9b740539befaa4da8 | 287,586 |
def graphprot_predictions_read_in_ids(predictions_file):
"""
Given a GraphProt .predictions file, read in column 1 IDs in order
appearing in file, and store in list.
>>> test_file = "test_data/test.predictions"
>>> graphprot_predictions_read_in_ids(test_file)
['SERBP1_K562_rep01_2175', 'SERBP1_... | 70b426d3336a694920919647406fae4f06597797 | 364,839 |
from typing import Optional
def convert_cm3(value: int) -> Optional[float]:
"""Convert a value from the ToonAPI to a CM3 value."""
if value is None:
return None
return round(float(value) / 1000.0, 2) | 04f5c21fc51ce1418d3a25c9d6479d417f5ccb1a | 476,375 |
def find_nth_document(homophonesGroupCollection, n):
""" Return nth document from database (insertion order). """
return homophonesGroupCollection.find_one(skip=n) | 2cbc42501943623f7e541f2b73292b165be37b78 | 478,879 |
def _SheriffIsFound(sheriff_key):
"""Checks whether the sheriff can be found for the current user."""
try:
sheriff_entity = sheriff_key.get()
except AssertionError:
# This assertion is raised in InternalOnlyModel._post_get_hook,
# and indicates an internal-only Sheriff but an external user.
return... | 51f7a5d09d55f1f4a75aeaeedccb9dbcf3bbcdf4 | 591,017 |
def blocks_table_l() -> dict[int, int]:
"""The table is the number of blocks for the correction level L.
Returns:
dict[int, int]: Dictionary of the form {version: number of blocks}
"""
table = {
1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 2, 10: 4, 11: 4,
12: 4, 13: 4, 14... | deb53cc3c84de9129dc190d3458bdc7f3050b5c0 | 462,420 |
def merge_dicts(*dict_args, **extra_entries):
"""
Given an arbitrary number of dictionaries, merge them into a
single new dictionary. Later dictionaries take precedence if
a key is shared by multiple dictionaries.
Extra entries can also be provided via kwargs. These entries
have the highest pre... | a670ee5e0333a79e630295f0965c8882910269a2 | 535,948 |
def world2Pixel(geoMatrix, x, y):
"""
Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
the pixel location of a geospatial coordinate
"""
ulX = geoMatrix[0]
ulY = geoMatrix[3]
xDist = geoMatrix[1]
pixel = int((x - ulX) / xDist)
line = int((ulY - y) / xDist)
return ... | ec79dd58ec456c13f1349dd27900c1841c5d6dad | 539,451 |
def is_related(x):
"""Compute whether a journey includes at least one related link click."""
return x > 0 | d3f12f130a3e6823648dcafdec0739e2f2b5cacb | 183,534 |
import six
def get_from_dict_if_exists(key, dictionary, convert_key_to_binary=True):
"""
Get the entry from the dictionary if it exists
Args:
key: key to lookup
dictionary: dictionary to look in
convert_key_to_binary: convert the key from string to binary if true
Returns:
... | 024a00a8e09267ba039f6bc327794288352dd712 | 95,837 |
def cat_ranges_for_reorder(page_count, new_order):
"""
Returns a list of integers. Each number in the list
is correctly positioned (newly ordered) page.
Examples:
If in document with 4 pages first and second pages were
swapped, then returned list will be:
[2, 1, 3, 4]
If first pa... | 219858bb483968826da1dd968a26151703188923 | 279,594 |
def get_object(model, **kwargs):
"""Retrieves a database object of the given class and attributes.
model is the class of the object to find.
kwargs are the parameters used to find the object.
If no object is found, returns None.
"""
try:
return model.objects.get(**kwargs)
e... | 353acfa8675c77da0a4077d5bec6e863c48792e9 | 171,961 |
from pathlib import Path
def assets_dir() -> Path:
"""Path to test assets directory."""
return Path(__file__).parent / "assets" | f71bb99d46424e47997c0233b5fd2c04fb154e24 | 487,428 |
def make_set(str_data, name=None):
"""
Construct a set containing the specified character strings.
Parameters
----------
str_data : None, str, or list of strs
Character string(s) to be included in the set.
name : str, optional
A name to be used in error messages.
Returns
... | e31a3d46586c75aeb7d0eb3ef9e059b12c9febc2 | 543,029 |
from pathlib import Path
def load_groups(input_path: Path) -> list:
"""
Load in the customs quesetionarre response data into a buffer and group
together the responses that are associated with a single group.
Responses belonging to a single group are on contiguous lines,
and groups are separated by... | f23eb0398757e749786a7ba1fdcb8dede18736fd | 37,170 |
from typing import Union
def kelvin_to_celsius(k_degrees: Union[int, float]) -> int:
"""Returns kelvins converted to celsius
:param k_degrees: temperature in kelvins
:type k_degrees: float
:return: temperature converted to celsius without the fractional part
:rtype: int
"""
MIN_TEMP_KELV... | 346d78325228e9eea8367beefcd25bb219e16c40 | 66,229 |
def cumulative_sum(points):
"""
Returns the cumulative sum.
"""
# logger.info('calculating cumulative sum')
csum = [0,]
prev = 0
# logger.info('start appending points')
for p in points:
csum.append(p+prev)
prev = p+prev
# logger.info('returning sum')
return csum | 18407079c0bcf2f4f5e2c0b2d3659afb3b537c08 | 74,989 |
def _prune_array(array):
"""Return an array equivalent to the input array. If the input
array is a view of a much larger array, copy its contents to a
newly allocated array. Otherwise, return the input unchanged.
"""
if array.base is not None and array.size < array.base.size // 2:
return arr... | 2741bca37f97410bac757ec3d0708b71725aa59a | 207,702 |
def region_builder(data):
"""
Takes an instance of a ping result and builds a dictionary ready to
display.
The ping result returns the raw results. This function returns a dictionary
with all the sections formatted.
:param data: dic Result of ping call.
:return dic Result of the ping ready... | 040ca4f28c08a3a4bb437fd0dff56606e3b63fcd | 425,773 |
from typing import List
from typing import Callable
from typing import Iterator
from typing import Dict
def transform(
transformers: List[Callable[[Iterator[Dict]], Iterator[Dict]]], data: Iterator[Dict]
) -> Iterator[Dict]:
"""Call transformers in order."""
for transformer in transformers:
data ... | 38f2ff1c3e3bab3d4d4bf50817a025a4463d4f0f | 153,216 |
import inspect
def clsname(obj):
"""Get objects class name.
Args:
obj (:obj:`object`):
The object or class to get the name of.
Returns:
(:obj:`str`)
"""
if inspect.isclass(obj) or obj.__module__ in ["builtins", "__builtin__"]:
return obj.__name__
return o... | f2787e0f94f95bcafb4668130eb8ab23d84fd7b6 | 616,015 |
def print_error(p, i):
"""
Returns the error message for package installation issues.
:param str p: The name of the package to install.
:param str i: The name of the package when imported.
"""
error_message = f"""
{i} not present. Please do the installation using either:
- pip install ... | b447643c1585f3dd05c2e09f525ecba97a14de5e | 161,982 |
from typing import Match
def replace_one_decorated_callable_start(m: Match) -> str:
"""Define the replacement function used in `correct_all_decorated_callable_starts`."""
start = int(m[5]) + int(m[6]) # number of decorators + line number of the first decorator
return f"{m[1]}/_type={m[2]}{m[3]}{start}:{m... | 819079d96e2aa60b745f16488dae916880dc0ba6 | 648,236 |
def get_numeric_list(numeric_range):
"""Convert a string of numeric ranges into an expanded list of integers.
Example: "0-3,7,9-13,15" -> [0, 1, 2, 3, 7, 9, 10, 11, 12, 13, 15]
Args:
numeric_range (str): the string of numbers and/or ranges of numbers to
convert
Raises:
Att... | 04e690f65db4569e80d43b23f90589da7fa9f254 | 393,899 |
def generate_md_code_str(code_snippet: str, description: str = 'Snippet') -> str:
"""The normal ``` syntax doesn't seem to get picked up by mdv. It relies on indentation based code blocks.
This one liner accommodates for this by just padding a code block with 4 additional spaces.
Hacky? Sure. Effective? Yu... | 4f6f1f61f211292c9f92975fb12659f283f566ef | 674,158 |
def remove_digits(text):
"""
Remove digits in given text
:param text: arbitrary string
:return: digit removed text
"""
text = str(text)
__remove_digits = str.maketrans('', '', '0123456789')
return text.translate(__remove_digits).strip() | 162b984ba951db6a138d6644587a53daf25f43cb | 304,400 |
from datetime import datetime
def _json_decoder_hook(obj):
"""Decode JSON into appropriate types used in this library."""
if "starttime" in obj:
obj["starttime"] = datetime.strptime(obj["starttime"], "%Y-%m-%dT%H:%M:%SZ")
if "endtime" in obj:
obj["endtime"] = datetime.strptime(obj["endtime... | 00b5634770d3bf823811cea3b7b5e9c035706878 | 305,479 |
def selection_sort(alist):
"""
Sorts a list using the selection sort algorithm.
alist - The unsorted list.
Examples
selection_sort([4,7,8,3,2,9,1])
# => [1,2,3,4,7,8,9]
a selection sort looks for the smallest value as it makes a pass and,
after completing the pass, places it in ... | f986addfdfd402403d57524a9f8b0d46751367a9 | 614,631 |
def get_attributes(obj):
"""
Fetches the attributes from an object.
:param obj: The object.
:type obj: object
:returns: A dictionary of attributes and their values from the object.
:rtype: dict
"""
return {k: getattr(obj, k) for k in dir(obj) if not k.startswith("__")} | 6e1cea3ed8ad2fa1c00f7c2eb86efb4a629e9f06 | 17,790 |
from typing import List
def get_requirements() -> List[str]:
"""Returns all requirements for this package."""
with open('requirements.txt') as f:
requirements = f.read().splitlines()
return requirements | fc49b661c07c40ecf1c8d51fb90eb56ee6049a56 | 686,416 |
from typing import Optional
def _filter_key(k: str) -> Optional[str]:
"""Returns None if key k should be omitted; otherwise returns the (possibly modified) key."""
if k.startswith("return_"):
return None
elif k.endswith("_max") or k.endswith("_min"):
return None
else:
k = k.rep... | 2d5cfc3b7fb5ef4e072273c8a46ab9a3b5f1a4ca | 96,855 |
def within_range_list(num, range_list):
"""Float range test. This is the callback for the "within" operator
of the UTS #35 pluralization rule language:
>>> within_range_list(1, [(1, 3)])
True
>>> within_range_list(1.0, [(1, 3)])
True
>>> within_range_list(1.2, [(1, 4)])
True
>>> wi... | b1c448f86f7d584abdbc65ea19315853ad615eec | 170,726 |
import json
def jsonify(value):
"""
Convert a value into a JSON string that can be used for JSONB queries in
Postgres.
If a string happens to contain the character U+0000, which cannot be
represented in a PostgreSQL value, remove the escape sequence representing
that character, effectively st... | 7fff497b302822f8f79f0e68b2576c26458df99c | 706,308 |
def get_phred_query(sample_id, gt_ll, genotype, prefix=" and ", invert=False):
"""Default is to test < where a low value phred-scale is high
confidence for that genotype
>>> get_phred_query(2, 22, "het")
' and gt_phred_ll_het[1] < 22'
>>> get_phred_query(2, 22, "het", prefix="")
'gt_phred_ll_he... | 3b913725bafec554c105173fb4ff720324aa8ae7 | 28,475 |
def has_races(path):
"""Checks if a result file has races."""
with open(path, 'r') as f:
return len(f.readlines()) > 2 | f56913771e1c0df9e0dc04258bd6172b236eb72b | 117,850 |
def gcd(p, q):
"""Implementation of Euclid's Algorithm to find GCD between 2 numbers"""
if q == 0:
return p
return gcd(q, p % q) | 627ad701807223208f3856473d30440d3e82a471 | 309,423 |
def generate_unique_name(pattern, nameset):
"""Create a unique numbered name from a pattern and a set
Parameters
----------
pattern: basestring
The pattern for the name (to be used with %) that includes one %d
location
nameset: collection
Collection (set or list) of existing names... | 6b4860a6733b924939027a349677c88f5e69788c | 117,587 |
def generate_anisotropy_str(anisotropy):
"""Generate a string from anisotropy specification parameters.
Parameters
----------
anisotropy : None or tuple of values
Returns
-------
anisotropy_str : string
"""
if anisotropy is None:
anisotropy_str = 'none'
else:
a... | 2f5a02e20daba73ad89c5465678aa07d1fc92d31 | 470,426 |
from pathlib import Path
def _should_install(session):
"""Decide if we should install an environment or if it already exists.
This speeds up the local install considerably because building the wheel
for this package takes some time.
We assume that if `sphinx-build` is in the bin/ path, the environme... | b21feba715cd5889fd7f4ff3d3547daa9e684b21 | 543,609 |
def get_sequence_from_seq_dict(bedline, seq_dict, bedtools_format=True):
""" Extract the sequence of a specific bedline object from a seq_dict.
The seq dict must contain RNA sequences, i.e. stranded and spliced.
Args:
bedline (bedline): bedline for which we have to get the seqeunce
seq_dict ... | dd4d3e4b8eeba6d743eac47a4059a5b6434e2b20 | 139,785 |
def get_releases(listing: list, specie: str) -> list:
"""
return the list of gencode releases found on the site.
Highest fist.
Parameters
----------
listing : list
list of gencode FTP paths, some ending with "release_nn" or "release_Mnn"
specie : str
mouse of human. mouse r... | bd0844cce447cfdbbbe95dd68b750764b804325b | 90,009 |
def ts_bin_states(df, column):
"""
Binning of states that last for several samples. Basically, it is a
'state_changed' counter. E.g.:
Index: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
State: | a | a | a | a | b | b | b | a | a |
State_bin: | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 2 | 2 |
Parameters... | 84f3160981e9e60289dc54edc12ff18377d988a5 | 436,601 |
import logging
def remove_rn(reference_node_name):
"""
Removes the RN from the end of a reference node's name
:param reference_node_name: node with a reference prefix
:return: Node with reference prefix removed
"""
flg = logging.getLogger("lettuce.xgenSetup.remove_rn")
last_r = reference... | 51763bd9cb99d0172a10741e1604dff6c6baac4a | 578,061 |
def area_square(r):
"""Return the area of a square with side length R."""
return r * r | 4b5a25010e14c956eb14a6365fb047c7cb022d6a | 368,419 |
from bisect import bisect_left
def binary_search(arr: list, item) -> int:
"""
performs a simple binary search on a sorted list
:param arr: list
:param item:
:return: int
"""
i = bisect_left(arr, item)
if i != len(arr) and arr[i] == item:
return i
else:
return -1 | 31c6ddc2c8a23885971fbd5541871d632d24fe90 | 201,876 |
def is_disc_aligned(disc, time_counter, align_offset):
"""Check if disc is aligned."""
return ((disc['cur_position'] + time_counter + align_offset)
% disc['positions'] == 0) | 3dded7fbd062920faa0c80edb3e384543e1e81fa | 87,368 |
def list_to_map(j, k):
"""Turn a list into a map."""
return {entry[k]: entry for entry in j} | 96fbed9a6ffa6683ce6c0ca1b3f211c0c927a91a | 570,224 |
def offline_ap_processing(offline_aps: list):
"""
Args:
offline_aps: list of offline APs from response.json()['list']
Returns:
list with offline AP name
"""
offline_aps_device_names = list()
for offline_ap in offline_aps:
device_data = f"Hostname: <{offline_ap.get('deviceNa... | ac644f6ee3b298a48992cc87530f8be8951cc48e | 115,547 |
import curses
def newwin_after(prev_win, h, w, xstart, y_skip=1):
"""
Create a new curses window starting:
- on the y_skip rows after the prev_win,
- starting at absolute column xstart
:param prev_win : curses.win
:param h : non neg int Height of new window
:param w : non neg int... | 1342b2034dcba019ae365db03f9ad9660f326afc | 481,633 |
import math
def prime_factors(n):
""" return a list prime factors for n """
prime_factors = []
while n % 2 == 0:
prime_factors.append(2)
n = n / 2
# int(math.sqrt(n))+1 is the max to test
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
... | f474e491345a7a8f209239f752cf792abe67f17d | 203,588 |
def is_constant_type(expression_type):
"""Returns True if expression_type is inhabited by a single value."""
return (expression_type.integer.modulus == "infinity" or
expression_type.boolean.HasField("value") or
expression_type.enumeration.HasField("value")) | 66a3237971299df3c7370f039d87a8b5f4ae2be5 | 5,565 |
def set_transformer_in_out(transformer, inputCol, outputCol):
"""Set input and output column(s) of a transformer instance."""
transformer = transformer.copy()
try:
transformer.setInputCol(inputCol)
except AttributeError:
try:
transformer.setInputCols([inputCol])
excep... | 4bf9bd4abeaa6435df5316c9201d62dd97645cd5 | 34,970 |
def rotate_list(alist):
"""Pop the last element of list out then put it into the first of list.
:param alist: A list that want to rotated.
:return alist: A rotated list.
"""
assert type(alist) == list
last = alist.pop()
alist.insert(0, last)
return alist | d3fefe92870aea63e51fff82c274990a0d9151f6 | 637,657 |
import re
def mangle(string):
"""Mangles a string to conform with the naming scheme.
Mangling is roughly: convert runs of non-alphanumeric characters to a dash.
Does not convert '.' to avoid accidentally mangling extensions and does
not convert '+'
"""
if not string:
string = ""
... | e181aeef23814fdabf67f41c35ae3979138f1850 | 527,671 |
def Un(X, Z):
""" Computes Un, full two-sample U-statistic."""
return (X.reshape((-1, 1)) > Z.reshape((1, -1))).mean() | 2fa8b5453ca4ba85c8da4d62b38b043a52513c34 | 477,555 |
from typing import Union
def clamp(value: Union[int, float], min_: Union[int, float], max_: Union[int, float]) -> Union[int, float]:
"""
Clamps the value between minimum and maximum values.
:param value: number to clamp
:param min_: minimum value
:param max_: maximum value
:return: clamped num... | dbd79a8e27d79486e0a05827462ae5fd71fc6818 | 82,960 |
def truncate_recordings(recordings, max_floor, min_length=300):
"""
Truncate the recordings so that they never exceed a
given floor.
This can be used, for example, to train an agent to
solve the beginning of every level.
Args:
recordings: a list of Recordings.
max_floor: the fl... | cb247ab9a741c9ed8754a9a2ff2c5119eb161c7f | 209,047 |
from typing import Optional
from typing import Tuple
def get_paginated_indices(offset: Optional[int], limit: Optional[int], length: int) -> Tuple[int, int]: # pylint: disable=invalid-sequence-index
"""
Given an offset and a limit, return the correct starting and ending indices to paginate with that are valid... | 381557ca08d5ceacbebb739b81f81e4c29d1033a | 481,597 |
def base_repr(number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system... | 1ff4609f475c248bf840c5ac1b82ad42d3c575b3 | 634,255 |
def bits2positions(bits):
"""Converts an integer in the range 0 <= bits < 2**61 to a list of integers
in the range 0 through 60 inclusive indicating the positions of the nonzero bits.
Args:
bits:
int. An integer in the range 0 <= bits < 2 ** 61
Returns:
A list of integers i... | 41d31ec9744aa6b02e55bfe5b9e4b85818bd5765 | 496,104 |
import json
import requests
def create_remote_version(access_token, version_info, tribe_url):
"""
Creates a new version for an already existing geneset in Tribe.
Arguments:
access_token -- The OAuth token with which the user has access to
their resources. This is a string of characters.
vers... | 28704ff0aaca5144674dd82c98d740124f63b527 | 264,554 |
def strip(text, chars=None):
"""
Creates a copy of ``text`` with the leading and trailing characters removed.
The ``chars`` argument is a string specifying the set of characters to be removed.
If omitted or None, the ``chars`` argument defaults to removing whitespace. The ``chars``
argument ... | 1e7857c82d7eaba076e22d29efa6909ca6d8d845 | 366,913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.