content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def context_to_dict(ctx):
"""Convert Context object into dict containing their info.
Args:
ctx: Context object to be converted.
Returns:
Dict containing information about ctx.
"""
return {
"content": ctx.message.content,
"user": ctx.author.id,
"channel": ctx... | 7a216eafd8dfacaf66e3cd2944375a66a886a70b | 227,892 |
def has_sample(args):
"""Returns if some kind of sample id is given in args.
"""
return args.sample or args.samples or args.sample_tag | c2ae87acb11232d7f56cb9e09eb8509720669058 | 1,807 |
def can_zip_response(headers):
"""
Check if request supports zipped response
:param headers: request headers
:return:
"""
if 'ACCEPT-ENCODING' in headers.keys():
if 'gzip' in headers.get('ACCEPT-ENCODING'):
return True
return False | 26021f2778ced4174aae29850a42ea95ea32172a | 674,070 |
def decay_value(base_value, decay_rate, decay_steps, step):
""" decay base_value by decay_rate every decay_steps
:param base_value:
:param decay_rate:
:param decay_steps:
:param step:
:return: decayed value
"""
return base_value*decay_rate**(step/decay_steps) | c593f5e46d7687fbdf9760eb10be06dca3fb6f7b | 2,366 |
def _serialize_time(val):
"""Create a JSON encodable value of a time object."""
return val.isoformat() | 648d71ab4d23dcba787751591160286223e34bda | 653,253 |
def delta_on_sigma_set(x, a, sigma_set):
"""
Euclidean gradient.
Compute euclidean gradient of function $\dfrac{1}{2}| P_{\Sigma}(X - A)|_F^2$,
equals to P_{\Sigma}(X - A).
Parameters
----------
x : ManifoldElement, shape (M, N)
Rank-r manifold element in which we compute gradient
... | e10f3cc87ba70ac810de5e68ab8a1e0c78471702 | 135,728 |
def partition(pred, iterable):
"""Returns [[trues], [falses]], where [trues] is the items in
'iterable' that satisfy 'pred' and [falses] is all the rest."""
trues = []
falses = []
for item in iterable:
if pred(item):
trues.append(item)
else:
falses.append(item... | be96fc0a560a0c2e5bd25e12387622167b4f084b | 61,854 |
def add(arg1, arg2):
"""Summary line <should be one one line>.
Extended description of function. Can span multiple lines and
provides a general overview of the function.
.. warning::
Use the ``.. warning::`` directive within the doc-string for
any warnings you would like to explicitly s... | 83e4ac1fcdbcc0537b2543b42e7bf18e5b8cf33b | 185,473 |
import functools
def memoize(obj):
"""'Memoize' aka remember the output from a function and return that,
rather than recalculating
Stolen from:
https://wiki.python.org/moin/PythonDecoratorLibrary#CA-237e205c0d5bd1459c3663a3feb7f78236085e0a_1
do_not_memoize : bool
IF this is a keyword arg... | cadb88fafe6d33a3a43d60b77a1c30c80bb2919f | 255,438 |
from typing import Iterable
from typing import Callable
from typing import Optional
from typing import Any
def safe_find(records: Iterable, filter_func: Callable) -> Optional[Any]:
"""
Wrapper around the filter function, to return only the first record when
there is a match, or None instead.
Args:
... | 5d23f994ad894a60c2b548ab34b39528371b4795 | 255,701 |
import json
def read_json(path):
"""
Read the json file from the path and turn it into dict.
Return the data
"""
with open(path, "r") as f:
data = json.load(f)
return data | c4a506735fc3457bd91a028120209e2546ea71d3 | 409,430 |
def RGBStringToList(rgb_string):
"""Convert string "rgb(red,green,blue)" into a list of ints.
The purple air JSON returns a background color based on the air
quality as a string. We want the actual values of the components.
Args:
rgb_string: A string of the form "rgb(0-255, 0-255, 0-255)".
Returns:
... | f94650ed977b5a8d8bb85a37487faf7b665f2e76 | 702,600 |
def get_next_available_port(containers_info):
"""
Find next available port to map postgres port to host.
:param containers_info:
:return port:
"""
ports = [container_info.host_port for container_info in containers_info]
return (max(ports) + 1) if ports else 5433 | 94809b2db3e4279648b33c6ce362ca80acfa081e | 483,916 |
def rsplit(text, token=' ', maxsplit=-1):
"""
Returns a list of the words in the provided string, separated by the delimiter string (starting from right).
:param text: the string should be rsplit
:param token: token dividing the string into split groups; default is space.
:param maxsplit: Number of ... | ef88bad6fb2f2bcf39c8b1367ec7b9722cf95c79 | 593,705 |
def decode_all(res):
"""decode all results fetched from redis"""
return list(map(bytes.decode, res)) | 08670d0dfc1fb341f9c0a21131248361a67f29c4 | 157,591 |
def set_chain(base, key_chain, value):
"""Sets a value in a chain of nested dictionaries. """
if base is None:
base = {}
cur = base
n = len(key_chain)
for i, key in enumerate(key_chain):
if i + 1 < n:
if key not in cur:
cur[key] = {}
cur = ... | 420e279c963524af2895055783b59167569a9951 | 632,933 |
import math
def ExpoCdf(x, lam):
"""Evaluates CDF of the exponential distribution with parameter lam."""
return 1 - math.exp(-lam * x) | 2252ad4715a194b11997d530d2d4dc78fd0f94a6 | 476,949 |
def extract_yields_stats(yields):
"""Extract coverage, mean and std of yields."""
coverage_mask = (yields != 0.0)
return coverage_mask.mean(), yields[coverage_mask].mean(), yields[coverage_mask].std() | 750a842dbf2081744c9031278bfd1a2d9b544007 | 49,725 |
def load(filename):
""" 读文件
Args:
filename: str, 文件路径
Returns:
文件所有内容 字符串
"""
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
return content | ef6e83192bd1f06ff530d8369e2f49a07fe677f1 | 687,049 |
def read_proteome_kmer_file(filename):
"""
Read kmer file used to generate proteome features for machine learning.
"""
out_dict = {}
with open(filename,'r') as infile:
for line in infile:
if line.strip() == "":
continue
col = line.split()
... | 3dabfab0ab86e48106ad05aba32a9b80927508da | 393,546 |
import typing
def is_abstract(cls: typing.Type[typing.Any]) -> bool:
"""
Returns whether ``cls`` is an abstract class.
"""
return hasattr(cls, '__abstractmethods__') \
and len(cls.__abstractmethods__) != 0 | 275cda30ad1909361a9d976e717cab9ee83d3bc2 | 478,123 |
def is_new_style(cls):
"""
Python 2.7 has both new-style and old-style classes. Old-style classes can
be pesky in some circumstances, such as when using inheritance. Use this
function to test for whether a class is new-style. (Python 3 only has
new-style classes.)
"""
return hasattr(cls, '_... | a303d87a5ef790d629dff6fcd07c46d029277530 | 694,267 |
def readId2Name(fin):
"""
Reconstruct a global id=>username dictionary from an open csv file
Reads the globalId2Name file (or equivalent) and constructs an id=>username
dictionary. Input is an open csv.reader file such as the one constructed
by the main method of this module. Returns a dictiona... | e8874e275fc894818467d8c032bdf58bb0314789 | 676,260 |
def gen_resource_arr(search_results: dict):
""" Generates an array which contains only the names of the current selected resources
Args:
search_results (dict): The output of searcher.py
Returns:
list: All resource keys that show up in the search_results dict.
"""
resources = []
... | 497faa9e332a8055603936a7a032a0f867aba328 | 421,479 |
def get_routing(user, routing_strategy):
"""
Get routing key needed by event or listener.
:param user: User to be routed.
:type user: User
:param routing_strategy: How it can compute routing key.
:type routing_strategy: :class:`str`
:return: Routing key for RabbitMQ.
:rtype: :class:`s... | 70569038d25437f5c5b57784637f33c8539387a1 | 515,196 |
def forward_pass(output_node, sorted_nodes):
"""
Performs a forward pass through a list of sorted Nodes.
Arguments:
`output_node`: A Node in the graph, should be the output node (have no outgoing edges).
`sorted_nodes`: a topologically sorted list of nodes.
Returns the output node's v... | 768c90d46ab904a10ae311a43d42078290744153 | 382,021 |
def fix_fits_keywords(header):
"""
Update header keyword to change '-' by '_' as columns with '-' are not
allowed on SQL
"""
new_header = {}
for key in header.keys():
new_key = key.replace('-', '_')
new_header[new_key] = header[key]
return new_header | a73cf1f139b3e7f1ec8366188c42b670b7f2674e | 607,182 |
def parse_stat_args(args_str):
"""Parse the optional value to the '--stat' option.
"""
args = {}
for arg in args_str.split(';'):
arg_parts = arg.split('=')
if len(arg_parts) == 1:
args[arg_parts[0]] = True
else:
args[arg_parts[0]] = arg_parts[1]
return... | 15770804470525d15404fb68028e32611323080f | 289,209 |
def check_layout_layers(layout, layers):
"""
Check the layer widget order matches the layers order in the layout
Parameters
----------
layout : QLayout
Layout to test
layers : napari.components.LayerList
LayersList to compare to
Returns
----------
match : bool
... | 7d5c3ed65e0588f430341345d6e0fb0856aacaeb | 28,784 |
import torch
def squeeze(input, *args, **kwargs):
"""
Returns a tensor with all the dimensions of ``input`` of size 1 removed.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> t1 = torch.randint(100, (2, 1, 2, 1, 2))
>>> t1.shape
torch.Size([2... | f9f24fe67963989fb1835db3684c97ba1795761f | 237,817 |
def set_boundary_conditions(T):
"""
Set dirichlet boundary conditions for the temperature equation
Arguments
-------------
T Temperature of the previous iteration
Returns
-------------
T_b Temperature with boundary condition
"""
T_b = T
bc_0 = 273 # K a... | 1fd549ac76cc9ead48a3ebd2064e0dd442ce7994 | 159,559 |
def pause_slicer(samp: int, width: int) -> slice:
"""Returns a slice object which satisfies the range of indexes for a pause
point.
The incoming numbers for samp are 1-based pixel numbers, so must
subtract 1 to get a list index.
The width values are the number of pixels to affect, including the
... | 9c698ebc3f3125017913e92b68c7eece21a905db | 301,905 |
def typedvalue(value):
"""
Convert value to number whenever possible, return same value
otherwise.
>>> typedvalue('3')
3
>>> typedvalue('3.0')
3.0
>>> typedvalue('foobar')
'foobar'
"""
try:
return int(value)
except ValueError:
pass
try:
retu... | 96f4ae19004202ef2cf2d604e742693ebaebe2ed | 660,984 |
def get_position(maze, element):
"""Get the position of an element in the maze (pony, domokun, or end-point)"""
if element == 'pony':
return int(maze['pony'][0])
elif element == 'domokun':
return int(maze['domokun'][0])
elif element == 'end-point':
return int(maze['end-point'][0]... | dea73e06b39b84ad741b2f287cb3d4540efe12c7 | 103,533 |
def calculate_offset(lon, first_element_value):
"""
Calculate the number of elements to roll the dataset by in order to have
longitude from within requested bounds.
:param lon: longitude coordinate of xarray dataset.
:param first_element_value: the value of the first element of the longitude array ... | a55eee1dd11b1b052d67ab1abadfc8087c1a2fe0 | 709,983 |
def make_list_response(reponse_list, cursor=None, more=False, total_count=None):
"""Creates reponse with list of items and also meta data useful for pagination
Args:
reponse_list (list): list of items to be in response
cursor (Cursor, optional): ndb query cursor
more (bool, optional): w... | ce45f4a13a926bb99d620cd13c707abe296f8d8d | 118,491 |
from math import isnan, fabs, floor
def compute_spatial_reference_factory_code(latitude, longitude):
"""
Computes spatial reference factory code. This value may be used as out_sr value in create image collection function
Parameters
----------
latitude : latitude value in decimal degress that wil... | aaaf58890316a2497bee3f4c41a1b34ed9f64b75 | 485,344 |
def SubclassCount(G, n):
"""Recursive all-subclass count."""
N_sub = 0
for nn in G.successors(n):
N_sub += 1
N_sub += SubclassCount(G, nn)
return N_sub | 127d09996944b7f362d18e91cd9169a67bea2dfb | 582,243 |
import struct
def unpack_word(str, big_endian=False):
""" Unpacks a 32-bit word from binary data.
"""
endian = ">" if big_endian else "<"
return struct.unpack("%sL" % endian, str)[0] | 8da8d168b1828062bd44ca3142c8b389bfd634c7 | 8,146 |
import ssl
def get_sslcontext(use_https, tls_ver=1.1):
"""Create an SSLContext object to use for the connections."""
if not use_https:
return None
if tls_ver == 1.1:
return ssl.SSLContext(ssl.PROTOCOL_TLSv1_1)
elif tls_ver == 1.2:
return ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) | 688df9afe9da9108996fc46e788f22a7ea0f41a8 | 332,418 |
def _get_cost (route, solution, dists):
"""
This method is used to calculate the total distance
associated to a route, once the sequence of its nodes
has been changed using the 2-OPT algorithm.
:param route: The interested route.
:param solution: The nodesin the order in which they are visited.... | 37ccdecec3fc517346bacaac0a762b68f86d4cc5 | 674,860 |
import json
def _read_json(file):
"""Read a JSON file."""
with open(file, 'r') as f:
return json.load(f) | 20e5b53feb4ac4d6b829dd11ddb8b905169b58dd | 441,673 |
import ast
from typing import Optional
def get_assigned_name(node: ast.AST) -> Optional[str]:
"""
Returns variable names for node that is just assigned.
Returns ``None`` for nodes that are used in a different manner.
"""
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
r... | 02d269773d77bdda9e22091eede7e24a838d9ad8 | 333,094 |
def get_msg(feat, mpnn, train_folder):
"""
Create a message telling the user what kind of model we're training.
Args:
feat (bool): whether this model is being trained with external features
mpnn (bool): whether this model is being trained with an mpnn (vs. just with
external features)
... | daca589d7b97e5739ea6dd3f893e8af57ff3be8a | 278,595 |
def definir_orden_builtin(a: str, b: str, c: str) -> str:
"""Devuelve tres palabras en orden alfabético de izquierda a derecha.
:param a: Primera palabra.
:a type: str
:param b: Segunda palabra.
:b type: str
:param c: Tercera palabra.
:c type: str
:return: Las tres palabras en orden alf... | 7cb1a5916a2917b942121de52020c7323c695ba8 | 694,800 |
from datetime import datetime
def Timestamp(year, month, day, hour=0, minute=0, second=0, microsecond=0,
tzinfo=None):
"""Construct an object holding a time stamp value."""
return datetime(year, month, day, hour, minute, second, microsecond,
tzinfo) | ff5d0c130bb55044dfc7c9546f94733fa73dfc3a | 298,168 |
def build_fasttext_wiki_embedding_obj(embedding_type):
"""FastText pre-trained word vectors for 294 languages, with 300 dimensions, trained on Wikipedia. It's recommended to use the same tokenizer for your data that was used to construct the embeddings. It's implemented as 'FasttextWikiTokenizer'. More information:... | 5f85a1d3e5f4a38b24c9a2bc3930810c06174de9 | 509,535 |
from typing import List
def find_dup(numbers: List) -> int:
"""
Solution: Iterate through the list and store items in a set. When an item is found that already exists in the set
return that item.
Complexity:
Time: O(n) - Iterate through our list once
Space: O(n) - We could potentially store each item found
"... | 94620fc5ceb565b417bcf1f0de6f6d7af23968ed | 46,144 |
import re
def get_tokens_to_string(s):
""" divides a (potentially) multi-word string into tokens - splitting on whitespace or hyphens
(important for hyphenated names) and lower casing
returns a single joined string of tokens
"""
tokens = [t.lower() for t in re.split(r'[\s-]', s) if t]
re... | 07c7faa06bfdf7aca299689cd4bcaf7e44398dd2 | 598,828 |
from typing import Dict
from typing import Optional
def compose_custom_response(
resp: Dict,
success_message: str = "Operation successful.",
fail_message: str = "Operation failed.",
) -> Dict:
"""Enhances a dictionarised Misty2pyResponse with `success_message` in case of success and with `fail_message... | 9dfd6fb1be5f4a8d1306ce13d059b3987e9bd551 | 645,639 |
from typing import get_origin
from typing import Literal
def is_literal_type(tp: type) -> bool:
"""
Test if the given type is a literal expression.
"""
# Stolen from typing_inspect
origin = get_origin(tp)
return tp is Literal or origin is Literal | 2f539372c7d5b938f4f7381073d5c19882681d52 | 136,445 |
def fromHex(data,offset=0,step=2):
"""
Utility function to convert a hexadecimal string to buffer
"""
return bytearray([ int(data[x:x+2],16) for x in range(offset,len(data),step) ]) | 5493e999ac2987699fdb569e689891137d45ccc2 | 486,917 |
def arg_auto_int(x):
"""Convert a string representing an integer literal to int."""
return int(x, 0) | 036d2f863ba651324bd154d37b7d4af3ef38fd62 | 204,474 |
def selection_sort(lst):
"""Perform an in-place selection sort on a list.
params:
lst: list to sort
returns:
lst: passed in sequence in sorted order
"""
if not isinstance(lst, list):
raise TypeError('Sequence to be sorted must be list type.')
for i in range(len(lst) - 1)... | d59ffc59eadc5088cc6f5a0f9d6d0802f16d0738 | 199,598 |
import re
def _natural_key(x):
""" Splits a string into characters and digits. This helps in sorting file
names in a 'natural' way.
"""
return [int(c) if c.isdigit() else c.lower() for c in re.split("(\d+)", x)] | 1fab7dffb9765b20f77ab759e43a23325b4441f4 | 703,863 |
def check_workbook_exists(service, spreadsheet_id, tab_name):
"""
Checks if the workbook exists within the spreadsheet.
"""
try:
spreadsheet = service.spreadsheets().get(
spreadsheetId=spreadsheet_id).execute()
sheets = spreadsheet['sheets']
exists = [True for sheet i... | c5fa4daeb3108246052372cda0be6df8fe94d1f0 | 110,744 |
def is_power_of_two(number: int) -> bool:
"""Check if a number is a power of 2"""
return (number & (number - 1) == 0) and number != 0 | 49fbe0f26bfe3e2914b65adabb346181bf74620c | 334,964 |
def make_bed(df, columns="all", outname="filtered_bed"):
"""
function converts input df to
BED 6 file, and retuns filename
paramenters:
df=pandas df
columns=list of target columns
outname=BED filename
"""
if columns != "all":
bed_df = df[columns].copy()
else:
bed... | 692ae4f25aa7a954c6f914cd68e7e6c6cd62b4d5 | 150,179 |
def create_sample_dists(cleaned_data, y_var=None, categories=[]):
"""
Each hypothesis test will require you to create a sample distribution from your data
Best make a repeatable function
:param cleaned_data:
:param y_var: The numeric variable you are comparing
:param categories: the categories ... | 9873653a9aedb7b07e949bdb2cc5442e4de5d902 | 99,190 |
def key_value_list_to_map(list):
"""A function to transform key values lists into maps"""
m = {}
for k,v in list:
m[k] = v
return m | bcc80e5f4fff54ed7ff5f19b1bb9f434dcbf2c9c | 614,343 |
def is_special_name(word):
""" The name is specific if starts and ends with '__' """
return word.startswith('__') and word.endswith('__') | 06efd1c759bb6afb12a6937658e9a2249b82a97e | 180,447 |
def nint(x, n=0):
"""Returns x rounded to the nearast multiple of 10**-n.
Values of n > 0 are treated as 0, so that the result is an integer.
In other words, just like the built in function round,
but returns an integer and treats n > 0 as 0.
Inputs:
- x: the value to round
- n: negative o... | 9f46767bb36e3b0422fa4ca11c66509befb84d08 | 614,055 |
import re
def split_auth_header(header):
"""Split comma-separate key=value fields from a WWW-Authenticate header"""
fields = {}
remaining = header.strip()
while remaining:
matches = re.match(r'^([0-9a-zA-Z]+)="([^"]+)"(?:,\s*(.+))?$', remaining)
if not matches:
# Without qu... | 2a893b5b7f9f197b0a179bc63e741f34ba08d74b | 663,250 |
import dateutil.parser
def parse_datetime(s):
"""
Parses the iso formatted date from the string provided
:param s: An iso date formatted string
:return: A datetime
"""
return dateutil.parser.parse(s) | 3df5648992fa3ad6986e0c722c35a72e8637c535 | 286,745 |
def get_package_version_key(pkg_name, pkg_version):
"""Return unique key combining package name and version."""
return pkg_name + '@' + pkg_version | 275349e48bf436c2f592a009c59385afcefd84b1 | 594,386 |
def check_all_values(base, target, tolerance=1e-15):
"""
Check the deviation of each element of two data arrays.
:param base: usually data arrays
:param target: usually data arrays
:param tolerance: max allowed deviation
:return: boolean, True for pass
"""
rtn = True
# sanity check
... | a7d52231f1484a844b0d40387b42bf74322d3266 | 503,309 |
def split_by_pt(sheet, col):
"""
Function to split up a sheet by patient \n
Takes a pd.DataFrame, specify column as text
"""
patient_dfs = list()
unique_patients = sheet[col].unique()
#Work through the the patients and split into new sheets
for i, j in enumerate(unique_patients):
... | 077d7128be6794bfa650b583d4f55b4a0b348302 | 472,916 |
def dict_to_html_table(a_dict):
"""
Converts a dictionary to a HTML table. Keys become the header of the table.
Useful while sending email from the code
:param dict a_dict: key value pairs in the form of a dictionary
:return: HTML table representation corresponding to the values in the dictionary
... | 8a001b5082ce0396e030f93ae805034aeff9d10d | 298,300 |
def get_target(directions:list[int]) -> tuple[int, int]:
"""Gets the coordinates of the target following directions.
x axis runs E, y runs NE"""
x = y = 0
for direction in directions:
if direction == 0:
x += 1
elif direction == 1:
y += 1
elif direction ==... | 0542756616f8c056a484e0e6f5101ec355081892 | 602,090 |
def node_info(node):
"""
Returns in a list the information (value, left child value, right child
value, parent value) for the specified node.
"""
# Node value
node_value = node.get_value()
# Left node value
left_value = None
if (node.left is not None):
left_value = node.left... | b1d2242bf62016ed153a64a26a1b738bdab14b90 | 227,560 |
import logging
import click
def progressbar(*args, **kwargs):
"""
Slight extension to click's progressbar disabling output on when log level
is set below 30.
"""
logger = logging.getLogger(__name__)
bar = click.progressbar(*args, **kwargs)
if logger.getEffectiveLevel() < 30:
bar.is... | 4f5697a4f0c77111e90f6aa901e4ad08a60331d6 | 520,507 |
import re
import string
def clean_data_1(data):
"""
First step of the pre-processing phase.
Converts String to lower case.
Deletes text between < and >
Removes punctuation from text.
Removes URLs
:param data: Text data to be cleaned.
:return: Cleaned text data.
"""
data = data... | b0c5f3e4840a1119ae4fdc15235940bcaf567c5c | 304,591 |
def unpack_ROS_xform(xform):
""" Unpack the ROS transform message into position and orientation """
posn = [xform.transform.translation.x,
xform.transform.translation.y, xform.transform.translation.z]
ornt = [xform.transform.rotation.x, xform.transform.rotation.y,
xform.transform.rot... | 51d23bd14ba36ea54b11e2db3c53c10ea1234e01 | 533,509 |
import random
def rabinMiller(num: int) -> bool:
"""Rabin-Miller primality test
Uses the `Rabin-Miller`_ primality test to check if a given number is prime.
Args:
num: Number to check if prime.
Returns:
True if num is prime, False otherwise.
Note:
* The Rabin-Miller pr... | 99bd54a171e4cfd5ce1de79c29f3bf9d8e292c9f | 101,534 |
def decode(byte_data, encoding='utf-8'):
"""
Decode the byte data to a string if not None.
:param bytes byte_data: the data to decode
:rtype: str
"""
if byte_data is None:
return None
return byte_data.decode(encoding, errors='replace') | 99f25362da5eaff173318d94b16a0f39cfe5c5ed | 560,507 |
def private_key_path(config):
"""
Path where this framework saves the private test key.
"""
return "%s/%s" % (config.get_state_dir(), "id_rsa_test") | a67cf830d97a6aace68ecc857cff164eb1d04fd9 | 141,155 |
def int_to_array(i, length=2):
"""Convert an length byte integer to an array of bytes."""
res = []
for dummy in range(0, length):
res.append(i & 0xff)
i = i >> 8
return reversed(res) | c51781aae859e3b79a30fbb8080be7f8cace263a | 394,086 |
def transform(subject_number: int, loop_size: int) -> int:
"""Transform a subject number and loop size into a public key
:param subject_number: transformation input value
:param loop_size: number of iterations
:return: key value
"""
value = subject_number**loop_size % 20201227
return value | 65a086cf9d83e525703d6ec4a9f854e97b256116 | 209,448 |
def ort_tag_categories(reisende):
"""Returns all location-day tuples in reisende.
A location-day is the tuple:
(line: str, direction: int, station: str, day: int)
"""
ort_tag = reisende[["Linie", "Richtung", "Haltestelle", "Tag"]].itertuples(
index=False, name=None
)
ort_tag = l... | 848db6bf968fcbe9619b93584789a1eb180d10f2 | 329,965 |
def format_user_results(user: dict):
"""
Formats and truncates the user result from the Slack API
Args:
user: The user response retrieved from the Slack API
Returns:
Formatted and truncated version of the result which is context safe.
"""
return {
'name': user.get('name'... | 1c44bfd46e73357ff78f7411255d39b536a4735a | 606,263 |
def str2boolean(df, col):
"""
Convert string 'True'/'False' into boolean
:param df: DataFrame
:param col: column
:return: DataFrame
"""
df[col] = df[col].apply(lambda x: True if x == 'True' else False)
return df | 7101ae49d51004b3d217ca17365da20280c9084e | 430,885 |
import ctypes
def ushort(val):
"""Return unsigned short value."""
return ctypes.c_ushort(val).value | c7fae9809124868b007154f24c6c2beb3f48ee72 | 162,543 |
def flipDP(directionPointer: int) -> int:
"""
Cycles the directionpointer 0 -> 1, 1 -> 2, 2 -> 3, 3 -> 0
:param directionPointer: unflipped directionPointer
:return: new DirectionPointer
"""
if directionPointer != 3:
return directionPointer + 1
return 0 | 928347a5c1934c822c77434ca9a91d913ef7f3b5 | 702,909 |
def get_validation_data(error):
"""
Returns custom validation message based on error
:param error: {ValidationError} error
:return: {tuple} messsage, errors
"""
errors = None
message = error.schema.get('message') or error.message
messages = error.schema.get('messages')
if messages is... | ee7e8c1e2b7da71b0ee160bf922fe3c733e32fda | 121,683 |
import re
def get_blurb_from_markdown(text, style=True):
"""Extract a blurb from the first lines of some markdown text."""
if not text:
return None
text = text.replace('\r\n', '\n')
lines = text.split('\n\n')
blurb = lines[0]
if style:
return blurb
# Strip style tags
... | 45af45d4d36236aa079c5f636d157422d32a381e | 459,429 |
def isnetid(s):
"""
Returns True if s is a valid Cornell netid.
Cornell network ids consist of 2 or 3 lower-case initials followed by a
sequence of digits.
Examples:
isnetid('wmw2') returns True
isnetid('2wmw') returns False
isnetid('ww2345') returns True
isnetid('w2345') r... | d4ddd91a9a7a7a4e2e7de778525718ec41c42cbc | 700,443 |
import math
def LLR_alt(pdf,s0,s1):
"""
This function computes the approximate generalized log likelihood ratio (divided by N)
for s=s1 versus s=s0 where pdf is an empirical distribution and
s is the expectation value of the true distribution.
pdf is a list of pairs (value,probability). See
http://hardy.uhasselt... | 4140f8c1d9d1d883b003eb3a805be5d752db5919 | 64,436 |
from typing import Tuple
import math
def near_duplicate_similarity_cached(
gold: Tuple[str],
pred: Tuple[str],
threshold: float = 0.1,
) -> float:
"""
Computes the approximate token-level accuracy between gold and pred.
Returns:
token-level accuracy - if not exact match an... | 68734870a9797f8d9eed43704577f5f7df306acb | 633,132 |
import logging
def _setup_logger() -> logging.Logger:
"""Set up the logger."""
FORMAT = "[%(asctime)s][%(levelname)s] %(message)s"
logging.basicConfig(format=FORMAT)
logger_ = logging.getLogger("generate_all_protocols")
logger_.setLevel(logging.INFO)
return logger_ | e4e1d91d32a5f46f9a8f781ebe39f88ecb3bf025 | 621,378 |
import json
from typing import OrderedDict
def build_list_of_dicts(val):
"""
Converts a value that can be presented as a list of dict.
In case top level item is not a list, it is wrapped with a list
Valid values examples:
- Valid dict: {"k": "v", "k2","v2"}
- List of dict: [{"k": "v"... | dfd92f619ff1ec3ca5cab737c74af45c86a263e0 | 4,537 |
def varchar(n):
"""varchar(n) converts an object into a string with less than n
characters or raises a TypeError"""
def check(x):
s = str(x)
if len(s) > n:
raise TypeError('Entered a string longer than %d chars' % n)
return s
check.__name__ = 'varchar(%d)' % n
r... | 11b3a4102a728003e1d51592545d019b6fba31c3 | 487,180 |
def string_to_upper(subject: str = "") -> str:
"""Strips and uppercases strings. Used for ID's"""
subject_clean = subject.strip().upper()
return subject_clean | 6a2b206b82d34a221faa3fbcbe40d73342ab5e82 | 275,733 |
def convert_string_tf_to_boolean(invalue):
"""Converts string 'True' or 'False' value to Boolean True or Boolean False.
:param invalue: string
input true/false value
:return: Boolean
converted True/False value
"""
outvalue = False
if invalue == 'True':
outvalue = True
... | 29c59a95f7f308dadb9ac151b1325069cdfd3cdc | 654,596 |
def _h_n_linear_geometry(bond_distance: float, n_hydrogens: int):
# coverage: ignore
"""Create a geometry of evenly-spaced hydrogen atoms along the Z-axis
appropriate for consumption by MolecularData."""
return [('H', (0, 0, i * bond_distance)) for i in range(n_hydrogens)] | f30d7008f64f586b952e552890cc29bb87c0544c | 663,093 |
def get_top_n_score(listing_scores, size_n=30):
"""
Getting the top scores and limiting number of records
If N = 2, Get the top 2 listings based on the score
{
listing_id#1: score#1,
listing_id#2: score#2
}
TO
[
[listing_id#1, score#1],
[listing_id#2, score#2... | cd1a5d474a926cd870d3a63667aff1e7ce514816 | 313,295 |
def dedupe(iterable):
"""Returns a list of elements in ``iterable`` with all dupes removed.
The order of the elements is preserved.
"""
result = []
seen = {}
for item in iterable:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result | edce6c732128a4de8dad0a5a8a8a714258bbd77a | 489,016 |
def smartconvert(data_string):
"""
Attempts to convert a raw string into the following data types, returns the first successful:
int, float, str
"""
type_list = [int, float]
for var_type in type_list:
try:
converted_var=var_type(data_string.strip())
#Check for... | 42cba2b812bbc43975610483eec9189e42d1f05c | 318,138 |
def format_single_space_only(text):
"""Revise consecutive empty space to single space.
Example::
" I feel so GOOD!" => "This is so GOOD!"
**中文文档**
确保文本中不会出现多余连续1次的空格。
"""
return " ".join([word for word in text.strip().split(" ") if len(word) >= 1]) | 6eb546b9229082c2702c272920aab398a5f614e7 | 536,545 |
def gradient(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Find the gradient of a line between two coordinates
"""
return (y2 - y1) / (x2 - x1) | 46b5afae5816c958a9bcee3d90237aefdb4073eb | 293,445 |
def number_from_label(label):
"""
Coverts a letter label (e.g. plate row label) into a number.
:param label: The label you want to convert.
:type label: :class:`string`
:return: The number corresponding to that label (:class:`int`).
:Note: This function returns a number, not an index. If you wa... | 6480024895084643d7f7bb97699798e2340039fb | 243,936 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.