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.channel.id,
"guild": ctx.guild.id if ctx.guild is not None else None,
"message_id": ctx.message.id
} | 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
a : sparse matrix, shape (M, N)
Matrix that we need to approximate -- it has nonzero entries only
on sigma_set
sigma_set : array_like
set of indices in which matrix a can be evaluated
Returns
-------
grad: sparse matrix, shape (M, N)
Gradient of our functional at x
"""
if x.shape != a.shape:
raise ValueError("shapes of x and a must be equal")
return x.evaluate(sigma_set) - a | 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)
return trues, falses | 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 state. For example,
if this method will be deprecated in the next release.
Parameters
----------
arg1 : int
Description of arg1.
arg2 : str
Description of arg2. Note how there is no space between the
previous parameter definition. Also note that lines are being
wrapped at 72 characters.
Returns
-------
int
Description of return value. This description ends with a
sentence, and we also don't name the return value.
Examples
--------
>>> from ansys.product.library import add
>>> add(1, 2)
3
See Also
--------
:class:`ExampleClass <ansys.product.library.ExampleClass>`
"""
return arg1 + arg2 | 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 argument (kwarg) in the function, and it is true,
then just evaluate the function and don't memoize it.
"""
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
if 'do_not_memoize' in kwargs and kwargs['do_not_memoize']:
return obj(*args, **kwargs)
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer | 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:
records: List to iterate over
filter_func: Function that will be appliead on each record
Returns:
First occurrence found or None
Examples:
>>> safe_find([{'a': 'T', 'b': 'H'}, {'a': 'F'}], lambda rec: rec.get('a') == 'F')
{'a': 'F'}
>>> safe_find([1, 2, 3], lambda rec: rec > 0)
1
>>> safe_find([{'a': 'T'}], lambda rec: rec.get('a') == 'F') is None
True
"""
try:
return next(filter(filter_func, records))
except StopIteration:
return None | 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:
list of the 3 strings representing red, green, and blue.
"""
return rgb_string[4:-1].split(',') | 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 splits to do; default is -1 which splits all the items.
:return: list of string elements
"""
if maxsplit == 0:
result = [text]
else:
components = text.split(token)
if maxsplit > 0:
desired_length = maxsplit + 1
result = []
if len(components) > desired_length:
result.append('')
for index, value in enumerate(components):
if index < len(components) - maxsplit:
if index > 0:
result[0] += token
result[0] += value
else:
result.append(value)
else:
result = components
return result | 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 = cur[key]
else:
cur[key] = value
return base | 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()
out_dict[col[0]] = int(col[1])
return out_dict | 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, '__class__') and ('__dict__' in dir(cls)
or hasattr(cls, '__slots__')) | 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 dictionary of id=>username
"""
retDict = {}
fin.readrow()
for iden, name in fin:
retDict[iden] = name
return retDict | 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 = []
# only wms and dataset might have downloadable content
for search_results_key, search_results_val in search_results.items():
resources.append(search_results_key)
return 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:`str`
"""
routing = routing_strategy.split('.')
source = user
if routing[0] == 'user':
routing = routing[1:]
for route in routing:
source = getattr(source, route)
return str(source) | 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 value
"""
for n in sorted_nodes:
n.forward()
return output_node.value | 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 args | 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
Boolean if layout matches layers
"""
layers_layout = [
layout.itemAt(2 * i - 1).widget().layer
for i in range(len(layers), 0, -1)
]
return layers_layout == list(layers) | 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, 1, 2, 1, 2])
>>> ttorch.squeeze(t1).shape
torch.Size([2, 2, 2])
>>> tt1 = ttorch.randint(100, {
... 'a': (2, 1, 2, 1, 2),
... 'b': {'x': (2, 1, 1, 3)},
... })
>>> tt1.shape
<Size 0x7fa4c1b05410>
├── a --> torch.Size([2, 1, 2, 1, 2])
└── b --> <Size 0x7fa4c1b05510>
└── x --> torch.Size([2, 1, 1, 3])
>>> ttorch.squeeze(tt1).shape
<Size 0x7fa4c1b9f3d0>
├── a --> torch.Size([2, 2, 2])
└── b --> <Size 0x7fa4c1afe710>
└── x --> torch.Size([2, 3])
"""
return torch.squeeze(input, *args, *kwargs) | 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 at the bottom of the snowpack
bc_1 = 253 # K snow atmosphere interface
T_b[0] = bc_0
T_b[-1] = bc_1
return T_b | 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
pause point pixel. If positive they start with the pause point pixel
and count 'up.' If negative, they start with the pause point pixel
and count 'down.'
"""
# We don't need to protect for indices less than zero or greater than the
# length of the list, because slice objects can take values that would not
# be valid for item access.
if width > 0:
s_start = samp - 1
s_stop = s_start + width
else:
s_start = samp + width
s_stop = samp
return slice(s_start, s_stop) | 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:
return float(value)
except ValueError:
pass
return value | 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])
return None | 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 to roll to.
"""
# get resolution of data
res = lon.values[1] - lon.values[0]
# calculate how many degrees to move by to have lon[0] of rolled subset as lower bound of request
diff = lon.values[0] - first_element_value
# work out how many elements to roll by to roll data by 1 degree
index = 1 / res
# calculate the corresponding offset needed to change data by diff
offset = int(round(diff * index))
return offset | 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): whether there's more items in terms of pagination
total_count (int, optional): Total number of items
Returns:
dict: response to be serialized and sent to client
"""
return {
'list': reponse_list,
'meta': {
'nextCursor': cursor.urlsafe() if cursor != None else None,
'more': more,
'totalCount': total_count
}
} | 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 will be used to compute UTM zone
longitude : longitude value in decimal degress that will be used to compute UTM zone
Returns
-------
factory_code : spatial reference factory code
"""
zone = 0
if (isnan(longitude) or isnan(latitude) or fabs(longitude) > 180.0 or fabs(latitude) > 90.0):
raise RuntimeError("Incorrect latitude or longitude value")
zone = floor((longitude + 180)/6) + 1
if (latitude >= 56.0 and latitude < 64.0 and longitude >= 3.0 and longitude < 12.0):
zone = 32;
if (latitude >= 72.0 and latitude < 84.0):
if (longitude >= 0.0 and longitude < 9.0):
zone = 31;
elif (longitude >= 9.0 and longitude < 21.0):
zone = 33;
elif (longitude >= 21.0 and longitude < 33.0):
zone = 35;
elif (longitude >= 33.0 and longitude < 42.0):
zone = 37
if(latitude>=0):
srid = 32601
else:
srid = 32701
factory_code = srid + zone -1
return factory_code | 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.
:param dists: The matrix of distances between nodes.
:return: The total distance.
"""
cnode, cost = route.source.id, 0
for node in solution:
cost += dists[cnode, node.id]
cnode = node.id
cost += dists[cnode, route.depot.id]
return cost | 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):
return node.id
if isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Store):
return node.attr
if isinstance(node, ast.ExceptHandler):
return getattr(node, 'name', None)
return None | 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)
train_folder (str): path to the training folder
Returns:
msg (str): the message
"""
msg = "Training a ChemProp model with "
if feat:
msg += "set features "
if feat and mpnn:
msg += "and "
if mpnn:
msg += "an MPNN "
msg += f"in folder {train_folder}\n"
return msg | 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 alfabético de izquierda a derecha.
:rtype: str
"""
return ", ".join(sorted([a, b, c], key=str.lower)) | 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: https://fasttext.cc/docs/en/pretrained-vectors.html.
Args:
embedding_type: A string in the format `fastext.wiki.$LANG_CODE`. e.g. `fasttext.wiki.de` or `fasttext.wiki.es`
Returns:
Object with the URL and filename used later on for downloading the file.
"""
lang = embedding_type.split('.')[2]
return {
'file': 'wiki.{}.vec'.format(lang),
'url': 'https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/wiki.{}.vec'.format(lang),
'extract': False,
} | 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
"""
numbers_seen = set()
for num in numbers:
if num in numbers_seen:
return num
numbers_seen.add(num)
raise Exception("No duplicate 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]
return ''.join(tokens) | 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` otherwise.
Args:
resp (Dict): The dictionarised Misty2pyResponse.
success_message (str, optional): A message/keyword to append in case of success. Defaults to `"Operation successful."`.
fail_message (str, optional): A message/keyword to append in case of failure. Defaults to `"Operation failed."`.
Returns:
Dict: The enhanced version.
"""
def compose_str(
main_str: str, potential_str: Optional[str], fallback: Optional[str] = None
) -> str:
"""Composes a single string from main_str, potential_str and fallback.
- If `potential_str` and `fallback` are both `None`, the final string is `main_str`.
- If `potential_str` is a string, the final string is `main_str` followed by a space and `potential_str`.
- If `potential_str` is `None` and `fallback` is a string, the final string is `main_str` followed by a space and `fallback`.
"""
if isinstance(potential_str, str):
return "%s %s" % (main_str, potential_str)
if isinstance(fallback, str):
return "%s %s" % (main_str, fallback)
return main_str
success = resp.get("overall_success")
dct = {"overall_success": success}
potential_resp = resp.get("rest_response")
if potential_resp:
potential_message = potential_resp.get("message")
if success:
message = compose_str(success_message, potential_message)
else:
message = compose_str(
fail_message, potential_message, fallback="No further details provided."
)
dct["rest_response"] = {
"success": potential_resp.get("success"),
"message": message,
}
return dct | 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):
min_idx = i + 1
for j in range(min_idx, len(lst)):
if lst[j] < lst[min_idx]:
min_idx = j
if lst[min_idx] < lst[i]:
lst[i], lst[min_idx] = lst[min_idx], lst[i]
return lst | 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 in sheets if sheet['properties']
['title'] == tab_name]
return True if exists else False
except Exception as e:
print(f'Failed to check workbook {tab_name} for spreadsheet '
f'{spreadsheet_id}')
raise(e) | 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_df = df
bed_df.to_csv(outname, sep="\t", header=False, index=False)
return outname | 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 whose means you are comparing
:return: a list of sample distributions to be used in subsequent t-tests
"""
htest_dfs = []
# Main chunk of code using t-tests or z-tests
return htest_dfs | 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 of power of 10 to which to round (e.g. -2 => round to nearest 100)
Error Conditions:
- raises OverflowError if x is too large to express as an integer (after rounding)
"""
return int (round (x, min(n, 0)) + 0.5) | 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 quotes
matches = re.match(r'^([0-9a-zA-Z]+)=([^",]+)(?:,\s*(.+))?$', remaining)
if not matches:
raise ValueError("Unable to parse auth header {}".format(repr(header)))
key, value, remaining = matches.groups()
fields[key] = value
return fields | 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
if len(base) != len(target):
return False
for idx in range(len(base)):
deviation = abs(base[idx] - target[idx])
if deviation > tolerance:
print("Deviation is larger than tolerance!!")
rtn = False
return rtn | 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):
temp_df = sheet.loc[sheet[col] == j, :]
patient_dfs.append(temp_df)
return patient_dfs | 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
:rtype: str
"""
body = ""
keys = sorted(a_dict.keys())
for key in keys:
body += "<tr><th>%s</th><td>%s</td></tr>\n" % (str(key), str(a_dict[key]))
return "<table>%s</table>" % body | 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 == 2:
x -= 1
y += 1
elif direction == 3:
x -= 1
elif direction == 4:
y -= 1
elif direction == 5:
x += 1
y -= 1
return x, y | 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.get_value()
# Right node value
right_value = None
if (node.right is not None):
right_value = node.right.get_value()
# Parent node value
parent_value = None
if (node.parent is not None):
parent_value = node.parent.get_value()
return [node_value, left_value, right_value, parent_value] | 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_hidden = True # type: ignore
return bar | 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.lower()
data = re.sub('<.*?>', '', data)
data = re.sub('[%s]' % re.escape(string.punctuation), '', data)
data = re.sub(r'http\S+', '', data)
return 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.rotation.z, xform.transform.rotation.w]
return posn, ornt | 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 primality test relies on unproven assumptions, therefore it can return false positives when
given a pseudoprime.
.. _Rabin-Miller:
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""
if num % 2 == 0 or num < 2:
return False # Rabin-Miller doesn't work on even integers.
if num == 3:
return True
s = num - 1
t = 0
while s % 2 == 0:
# Keep halving s until it is odd (and use t
# to count how many times we halve s):
s = s // 2
t += 1
for trials in range(5): # Try to falsify num's primality 5 times.
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1: # This test does not apply if v is 1.
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v ** 2) % num
return True | 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 = list(set(ort_tag))
return ort_tag | 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'),
'id': user.get('id'),
'profile': {
'email': user.get('profile', {}).get('email', ''),
'real_name': user.get('profile', {}).get('real_name', ''),
'display_name': user.get('profile', {}).get('display_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 not None:
validator = error.validator if error.validator in messages else 'default'
if messages.get(validator) is not None and error.path[0]:
message = messages.get(validator)
errors = { error.path[0]: [ messages.get(validator) ] }
return message, errors | 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
p = re.compile(r'<style>[\w\W]+</style>', re.MULTILINE)
matches = p.findall(blurb)
for m in matches:
blurb = blurb.replace(m, '')
return blurb | 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') returns False
isnetid('WW345') returns False
Parameter s: the string to check
Precondition: s is a string
"""
assert type(s) == str
var1 = s[:2]
var2 = s[2:]
var3 = s[:3]
var4 = s[3:]
result = ((var1.isalpha() and var1.islower() and var2.isnumeric() and
('-' not in s)) or (var3.isalpha() and var3.islower() and
var4.isnumeric() and ('-' not in s)))
return result
#pass | 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.be/Toga/computeLLR.pdf
"""
r0,r1=[sum([prob*(value-s)**2 for value,prob in pdf]) for s in (s0,s1)]
return 1/2*math.log(r0/r1) | 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 and mismatching tokens <= threshold;
0 - otherwise.
"""
mismatch_allowed = int(math.ceil(threshold * min(len(gold), len(pred))))
# Check length difference
if abs(len(gold) - len(pred)) >= mismatch_allowed:
return 0
# Count number of mismatches
mismatch_count = 0
max_len = max(len(gold), len(pred))
for i in range(max_len):
if i >= len(gold):
mismatch_count += len(pred) - i
break
if i >= len(pred):
mismatch_count += len(gold) - i
break
if gold[i] != pred[i]:
mismatch_count += 1
if mismatch_count >= mismatch_allowed:
return 0
if mismatch_count >= mismatch_allowed:
return 0
else:
return 1 - mismatch_count / max_len | 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"}, {"k2","v2"}]
- JSON decodable string: '{"k": "v"}', or '[{"k": "v"}]'
- List of JSON decodable strings: ['{"k": "v"}', '{"k2","v2"}']
Invalid values examples:
- ["not", "a", "dict"]
- [123, None],
- [["another", "list"]]
:param val: Input value
:type val: Union[list, dict, str]
:return: Converted(or original) list of dict
:raises: ValueError in case value cannot be converted to a list of dict
"""
if val is None:
return []
if isinstance(val, str):
# use OrderedDict to preserve order
val = json.loads(val, object_pairs_hook=OrderedDict)
if isinstance(val, dict):
val = [val]
for index, item in enumerate(val):
if isinstance(item, str):
# use OrderedDict to preserve order
val[index] = json.loads(item, object_pairs_hook=OrderedDict)
if not isinstance(val[index], dict):
raise ValueError("Expected a list of dicts")
return val | 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
return check | 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
return(outvalue) | 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]
]
"""
sorted_listing_scores = [[key, listing_scores[key]] for key in sorted(listing_scores, key=listing_scores.get, reverse=True)][:size_n]
return sorted_listing_scores | 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 inifinite values:
if converted_var == float('Inf'):
converted_var = 1e6;
return converted_var
except ValueError:
pass
#No match found
return str(data_string.strip()) | 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 want to
work with indices, make sure to decrease the number by one
before using it.
"""
row_number = 0
row_label_chars = list(label.upper())
for i, c in enumerate(reversed(row_label_chars)):
colnum = ord(c) - 64
row_number += colnum * pow(26, i)
return row_number | 6480024895084643d7f7bb97699798e2340039fb | 243,936 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.