content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def find_parent_by_name(element, names):
"""
Find the ancestor for an element whose name matches one of those
in names.
Args:
element: A BeautifulSoup Tag corresponding to an XML node
Returns:
A BeautifulSoup element corresponding to the matched parent, or None.
For example, assuming the follow... | b55aa8704c78c9bfbb30e691ccd33ded10aa2fe6 | 515,328 |
import fractions
def change_to_rational(number):
"""convert a number to rantional
Keyword arguments: number
return: tuple like (1, 2), (numerator, denominator)
"""
f = fractions.Fraction(str(number))
return (f.numerator, f.denominator) | 96b581ad5fb5ce0880210eea274e7aa5477d40a4 | 318,962 |
def pybel_to_inchi(pybel_mol):
"""
Convert an Open Babel molecule object to InChI
"""
inchi = pybel_mol.write('inchi', opt={'F': None}).strip() # Add fixed H layer
return inchi | 6facb16bbaeb1b37074d2eb106f9b2769cb1a9a0 | 321,562 |
def tofloat(v):
"""Check and convert a string to a real number"""
try:
return float(v) if v != '.' else v
except ValueError:
raise ValueError('Could not convert %s to float' % v) | 9345a55bcd4f4e8e57aef9d456eb6ba7e0b26646 | 640,376 |
def parabola_through_three_points(p1, p2, p3):
"""
Calculates the parabola a*(x-b)+c through three points. The points should be given as (y, x) tuples.
Returns a tuple (a, b, c)
"""
# formula taken from http://stackoverflow.com/questions/4039039/fastest-way-to-fit-a-parabola-to-set-of-points
# A... | 477c3a4190dc04c26edd4eedf7232e1f64003834 | 642,682 |
import requests
def get_csv_zip_url(table_id)->str:
"""
Returns the url for a table_id to extract raw data from Stats Canada.
Parameters
--------
table_id : int
Statistics Canada Table ID
Returns
--------
str
http address for downloading zipped csv file
Refer... | 9292c2e09f2c29f1c234499e7a0632b5c5605c58 | 608,654 |
def preprocess_examples(examples, mode='train'):
"""
For training set and dev set, treat each utterance of the first speaker as
the response, and concatenate the goal, knowledge and the dialog’s previous
utterances as the history. In this way, multiple history-response pairs
are constructed.
... | 99beb7b61f7c6af00d30f751ddddc87be4fdabde | 590,498 |
def edit_is_rejected_addition(edit):
"""
Returns boolean whether an edit is a rejected addition.
"""
return edit.EditType == 'A' and edit.ReviewStatus == 'R' | 7b4b8e0e91f477513c9c27e9ead926489872ef2c | 388,583 |
import json
def get_es_config(file_path):
"""
Reads a json file containing the elastic search credentials and url.
The file is expected to have 'url', 'username' and 'password' keys
"""
with open(file_path) as stream:
credentials = json.load(stream)
return (credentials['url'],
... | cdf3e7a3566604445cff1257b57486072c11a469 | 90,439 |
def getFormatName(qry, fmt):
"""
Retrieves a format name, given a format
"""
return qry["searches"][fmt]["name"] | 486fa840246136f07b9ee8011cda7660eb473b15 | 524,618 |
def group4_forward_branch(layer, in_tensor):
"""Defines group 1 connections.
Args:
layer (torch.nn.Module):
Network layer.
in_tensor (torch.Tensor):
Input tensor.
Returns:
torch.Tensor: Output of group 1 layer.
"""
a = layer["up1"](in_tensor)
re... | 3a8ce771ac18fe00b033233482b8084c0692de00 | 602,127 |
def chunk(input_data, size):
"""
Chunk given bytes into parts
:param input_data: bytes to split
:param size: size of a single chunk
:return: list of chunks
"""
assert len(input_data) % size == 0, \
"can't split data into chunks of equal size, try using chunk_with_remainder or pad dat... | 83bb4ad9a4e3b51e9063d532ed35794e8d051334 | 237,359 |
def convert_float_coord_to_string(coord, p=2):
"""Convert a (lon,lat) coord to string."""
lon, lat = round(coord[0], p), round(coord[1], p)
LA, LO = 'n', 'e'
if lat < 0: LA = 's'
if lon < 0: LO = 'w'
lat_s = "%.2f" % round(abs(lat),2)
lon_s = "%.2f" % round(abs(lon),2)
coord_s = '%s%s%s%... | eba6a21b91f03c7b4fbf785e869f06a25c68a70c | 373,127 |
def base_url(host, port):
"""
Provides base URL for HTTP Management API
:param host: JBossAS hostname
:param port: JBossAS HTTP Management Port
"""
url = "http://{host}:{port}/management".format(host=host, port=port)
return url | 3c132c461bb25a497e774f06cfc0b7a159fbb4e3 | 547,800 |
def mutindex2pos(x, start, end, mut_pos):
"""
Convert mutation indices back to genome positions
"""
if x == -.5:
return start
elif x == len(mut_pos) - .5:
return end
else:
i = int(x - .5)
j = int(x + .5)
return (mut_pos[i] + mut_pos[j]) / 2.0 | 06e09a0a3281ab2de076e28a32cc08e37c610fce | 634,718 |
def gene_catalogue(db):
"""Get list of genes from database."""
cur = db.cursor()
cur.execute('SELECT entrez, gene '
'FROM genes;')
results = cur.fetchall()
# format into single list
genes = []
for item in results:
genes.append([item[0], item[1]])
return genes | fdaadf567ea81953333f6c32f987794d1c5b6ac7 | 443,883 |
def bi_var_equal(var1, unifier1, var2, unifier2):
"""Returns True iff variable VAR1 in unifier UNIFIER1 is the same
variable as VAR2 in UNIFIER2.
"""
return (var1 == var2 and unifier1 is unifier2) | 315639eddf62184e070b62a8f83ebe22c16c4d0c | 234,643 |
def _index_ranges_without_offsets(index_ranges_with_offsets):
"""Return index_ranges excluding the offset dimension."""
return index_ranges_with_offsets[1:] | 414d2ed39c32a4df7b28f1f26e9bef5d720659bc | 450,324 |
from unittest.mock import Mock
def theme_mock(name='example-theme'):
"""Get a mock representing a theme object.
:param name: a name of a theme represented by the mock
:returns: the mock.
"""
theme = Mock()
theme.name = name
return theme | 9ace283d551f834dc28977de6409c4ce16f11c4f | 502,013 |
def xywh_from_bbox(minx, miny, maxx, maxy):
"""Convert a bounding box from a numeric list to a numeric dict representation."""
return {
'x': minx,
'y': miny,
'w': maxx - minx,
'h': maxy - miny,
} | e6116c805e65dd43231e33bf5a5e7d64ccc28cec | 180,218 |
import re
def valid_email(email=None):
"""Returns True if argument is a string with valid email adddress"""
if not email:
return False
pattern = r"[^@]+@[^@]+\.[^@]+"
p = re.compile(pattern)
if p.match(email):
return True
return False | 1c6cd70d8eb6bb0053dee25b7cb0f9f4055395b3 | 67,389 |
from typing import TextIO
from typing import Dict
def read_rank_file(input_fh: TextIO, max_records=-1) -> Dict[str, int]:
"""Reads lines and returns a dictionary where each key is a line and each value is the rank / line number.
Repeated lines are ignored.
"""
output_ranks = {}
line_number = 1
... | a45e7829862fe6b2aed0e3e70035a57296e1c608 | 474,948 |
def twiddle_bit(bb, bit):
""" Flip a bit from on to off and vice-versa """
return bb ^ (1 << bit) | b2520909ce0165d46a72b84cadbb065da2ebd8c2 | 572,023 |
import collections
def __units_seen(states, army_type):
"""Identifies units seen, adding to dictionary in the order seen
Args:
states (list): list of game states.
army_type (string): "Commanding" or "Opposing".
Returns:
Dictionary: { unit_... | d0dcb1c7f2db5b3ec0c243c415758cf29efb7cc5 | 244,560 |
def list_parser_dest(parser, exclude=('help',)):
"""
Return parser list of ``dest``.
Parameters
----------
parser : argparse.ArgumentParser
Parser.
exclude : list, tuple, default=('help',)
Brick name.
Returns
-------
args : list
Parser list of ``dest``.
... | 1c67770b68dd22be82e097afad321e25b969fe1d | 528,848 |
def _uint32(x):
"""Transform x's type to uint32."""
return x & 0xFFFFFFFF | 8b7547738f69b7aa39b40e85852ebbf03cc6fbfa | 43,749 |
def tasks(tmpdir):
"""
Set up a project with some tasks that we can test displaying
"""
task_l = [
"",
" ^ this is the first task (released)",
" and it has a second line",
" > this is the second task (committed)",
" . this is the third task (changed, not yet com... | 64104bde2aab55021cf0d49fbb1d47670d0e4e0d | 704,376 |
def url_gen_dicter(inlist, filelist):
"""
Prepare name:URL dicts for a given pair of names and URLs.
:param inlist: List of dictionary keys (OS/radio platforms)
:type inlist: list(str)
:param filelist: List of dictionary values (URLs)
:type filelist: list(str)
"""
pairs = {title: url f... | 36d4e066524903f7a5a19f5ca402502561d7ff52 | 36,970 |
def translate_table(fields):
"""Parse form fields into a list addresses"""
addrs = list()
for f in sorted(fields):
if f.startswith('addr') and fields[f]:
addrs.append(fields[f])
return addrs | a5648e43fb58723a51d28d328c15bfa05d0e1639 | 235,758 |
def reduce_deg(deg):
""" Return *deg* in the range [-180, 180) """
return (deg+180) % 360 - 180 | 2a11f2281c9a1937052ad800c82a545f0f0d0946 | 349,550 |
import socket
def create_rawsock(iface):
"""Creates a new raw socket object.
The socket sends/receives data at the link layer (TCP/IP model)/data-link
layer (OSI model).
Args:
iface: A string specifying the name of the network interface to which
the raw socket should be ... | ea56408403ada6b9750265547677028c197ae933 | 695,946 |
def format_with_default_value(handle_missing_key, s, d):
"""Formats a string with handling of missing keys from the dict.
Calls s.format(**d) while handling missing keys by calling
handle_missing_key to get the appropriate values for the missing keys.
Args:
handle_issing_key: A function that t... | 957b851dcacfc98c5bcdb5f1c76850014f8262f5 | 22,559 |
def validate_float(data):
"""
Checks if data contains something that can be used as float:
- string containing float
- int
- float itself
and converts it to float.
Return:
- float if possible
- 0.0 if empty string
- None if float not possible
"""
if isinstance(data, str):
if len(data) > 0:
if data.ls... | d64e6bcdb6c730dc486284ca98e9f79efbcec9e4 | 257,112 |
def expression_split(src):
"""
parse a string and return a list of pair with
open and close parenthesis
The result is generated in the order that the inner-most and left-most
parenthesis will be at the start of the list, which logically should be processed first
:param:
... | 92a8a604abbb1b4a8099bdb8969eef702b44fc38 | 230,714 |
def remove_white_spaces_a_comment(mystr):
"""
Remove all the whitespaces in a comment
"""
mystr = ' '.join([x.strip() for x in mystr.split()])
return mystr | 58ded95d7c02c86459e13180d83db7cfaf86145a | 366,043 |
from typing import Dict
from typing import Any
from typing import Optional
def get_name(hook: Dict[Any, Any]) -> Optional[str]:
"""
Creates a name based on the webhook call it recieved
Format: Timestamp_Devicename.mp4
Removes any characters that are not regular characters, numbers, '_' '.' or '-'
... | 2b9a034ee551894adc4a03cebce3711cdbad58d3 | 679,814 |
import math
def i4_bit_lo0(n):
"""
I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer.
Example:
+------+------------+----
| N | Binary | BIT
+------+------------+----
| 0 | 0 | 1
| 1 | 1 | 2
| 2 | 10 | ... | f8766d351183ecb9fe74b836a4bbf226e8db1501 | 591,364 |
def binary(val):
""" validates if the value passed is binary (true/false)"""
if type(val) == bool:
return val
else:
raise ValueError("random seed is a boolean flag") | fd5c5f8229fb9b227b5aff9a50b063463b51147c | 680,643 |
def pad_sents(sents, padding_token_index):
"""
Pad the sents(in word index form) into same length so they can form a matrix
# 15447
>>> sents = [[1,2,3], [1,2], [1,2,3,4,5]]
>>> pad_sents(sents, padding_token_index = -1)
[[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]]
"""
... | 0063d8716f7081644e4353de662d58f0dc04e8fe | 13,550 |
import json
def build_search_body(event):
"""Extract owners and filters from event."""
owners = json.loads(event["Owners"])
filters = json.loads(event["Filters"])
return {"Owners": owners, "Filters": filters} | 07818f59cd992cb10e5dd28d112873c136bf5dc1 | 625,885 |
def brws_show_url(driver, _):
"""Shows the current url"""
return driver.current_url | 9fb018919b3c68263aae8a0dcbae7a40571fe413 | 160,834 |
def get_crop_margins(page, crop_percent, side='both'):
""" Get the margins to remove from all sides using the crop_percent """
width, height = page.mediaBox.upperRight
w_diff, h_diff = float(width) * (crop_percent / 2), float(height) * (crop_percent / 2)
scale = (width / (width - w_diff * 2))
if sid... | a2b4ecd86b9bf4922c33f856f3f7eb4d242a0d9f | 600,517 |
from typing import Dict
import yaml
import click
def _load_yaml(filepath: str) -> Dict:
"""
Read content from yaml file.
:param filepath: str path to yaml file.
:return: dict YAML content
"""
with open(filepath, "r") as f:
try:
return yaml.safe_load(f)
except yaml... | 69e0f84d9fddf0a2bdc9d151be9baebe4d658b9f | 77,143 |
def humancoords_to_0interbase( start, stop ):
"""
The typical human-readable coordinate system, such as found in GBK flat files,
has a start and stop coordinate only. They are 1-based, on-base coordinates
and features on a reverse strand are indicated by having start > stop. This
transforms them i... | 9ef3230b0b9fbc3b4c8d993a8ecf091f3b2b85e6 | 494,284 |
def post_directory_path(instance, filename):
"""
file will be uploaded to MEDIA_ROOT/post_<post_id>/<filename>
:param instance:
:param filename:
:return:
"""
return 'post_{0}/{1}'.format(instance.post_id, filename) | b0bb740cfc3c5e5739bbd188741ff3c167bffd0e | 417,905 |
def confopt_bool(confstr):
"""Check and return a boolean option from config."""
if isinstance(confstr, str):
if confstr.lower() in ['yes', 'true', '1']:
return True
else:
return False
else:
return bool(confstr) | 9303c1944b13d390b3b06eed0d4cc13b4b764e8e | 200,276 |
def get_rt(user_input, bound):
"""
Get reproduction rate from scenario choice.
"""
rules = {
"estavel": lambda x: x, # cenario estavel
"positivo": lambda x: x / 2, # cenario positivo
"negativo": lambda x: x * 2, # cenario negativo
}
return rules[user_input["strategy"... | 42180ef08f21c081df5c74b6aab6deed3eeefc8f | 270,075 |
def get_type(line):
"""
Returns either a string, indicating whether this is a wired, wireless,
or loopback interface, or None if this can not be determinted.
:param line: line of output from: ip a
"""
if "fq_codel" in line:
return "wired"
if "mq" in line:
return "wireless"
... | e80d55dbb71540e1b8027258635e0273ddde95a2 | 301,473 |
def get_head(observation):
"""Given the current state of the snake environment, finds where the head of the snake is.
Args:
observation (numpy array): a 4xMxN ndarray.
Returns:
tuple: a tuple of length 2 representing the location of the head of the snake on a 2D grid.
"""
one_hot_head = observ... | fe0c846133741ce5ff5b713e957aa03b98052750 | 196,844 |
import re
def valid_manifest_key(key):
"""Validate manifest key to make sure only top level manifests are processed"""
result = re.search(r'\d{8}-\d{8}\/((?:\w+-)+\w+)\.json$', key)
if result:
return True
return False | afc8fc998206166bd676b58f8b989a904702404d | 411,729 |
def el (name, content):
"""Write a XML element with given element tag name (incl. element attributes) and the element's inner content."""
return "<%s>%s</%s>" % (name, content, name.partition(" ")[0]) | 8100779aa7935eb3ca0ea0c720508c1728c1874d | 46,287 |
import click
def parse_rangelist(rli):
"""Parse a range list into a list of integers"""
try:
mylist = []
for nidrange in rli.split(","):
startstr, sep, endstr = nidrange.partition("-")
start = int(startstr, 0)
if sep:
end = int(endstr, 0)
... | 321496a1170b81d02b8378d687d8ce6d6295bff6 | 6,303 |
def compute_precision(confusionMatrix):
"""
Compute precision based on a Confusion Matrix
with prediction on rows
and truth on columns.
precision = true positive / (true positive + false positive)
"""
precision = []
for i in range(confusionMatrix.shape[0]):
tot = 0
... | 24f51be1de97ed9a7257ba63787f84425e920f2f | 209,319 |
def store_till_end_callback_factory(destination=lambda m: None):
"""
A :func:`callback_factory` which stores the messages in a list
and send them to the destination at the last message
Parameters
----------
destination : callable (Default : destination=lambda m: None)
A function which t... | 6cd687569eb107c9c786186610926a708d4f83d5 | 168,362 |
def grade_stability(avg_smape):
"""Qualitative label for the average symmetric mean absolute percentage
error (SMAPE).
Parameters
----------
avg_smape : float (> 0)
The average absolute relative difference.
Returns
-------
qualitative_label : str
The qualitativ... | 663916d6f52a86514dfd8b418e7f5b7f354ed84e | 348,982 |
def normalize_brightness_dict(brightness_dict):
"""Usually the distribution of the character brightness for a given font
is not as diverse as we would like it to be. This results in a pretty
poor result during the image to ASCII art conversion (if used as-is).
Because of this it's much better to normal... | fa857be51d983c96ec03856da252935eb44cb6be | 677,036 |
def catplot_abscissa(x_order, hue_order=None, xtype='center'):
"""
Returns a dict that contains, for each possibly combination of x and hue
values, the abscissa of the corresponding bar in any Facet of a
seaborn 'bar' catplot called with x_order and hue_order as arguments.
Depending on the val... | c62dfe26027bc4d9be97c599df9dd374e2e551a2 | 567,681 |
def sdp_term_p(f):
"""Returns True if `f` has a single term or is zero. """
return len(f) <= 1 | 1fbefa0f751d0583f4c20b81289df2b4ca4dfca6 | 47,063 |
def get_dataset_json(met, version):
"""Generated HySDS dataset JSON from met JSON."""
return {
"version": version,
"label": met['data_product_name'],
"starttime": met['sensingStart'],
"endtime": met['sensingStop'],
} | 7eebf6cb13d6c38a953fdc033b58890f32b2eefd | 336,552 |
def _allocate_expr_id(allocator, exprmap):
""" Allocate a new expression id checking it is not already used.
Args:
allocator: Id allocator
exprmap: Map of existing expression names
Returns:
New id not in exprmap
"""
id = allocator.allocate()
while id in exprmap:
... | 98321e169d354e97e650e0ea9a5235315529c1dc | 105,167 |
import torch
def _make_square(mat):
"""Transform a compact affine matrix into a square affine matrix."""
mat = torch.as_tensor(mat)
shape = mat.size()
if mat.dim() != 2 or not shape[0] in (shape[1], shape[1] - 1):
raise ValueError('Input matrix should be Dx(D+1) or (D+1)x(D+1).')
if shape[... | a95064218ef26d89920066525283466716aa7739 | 422,967 |
def udfize_def_string(code: str) -> str:
"""Given an unindented code block that uses 'input' as a parameter, and output as a
return value, returns a function as a string."""
return """\
def udf(input):
{}
return output
""".format(
" ".join(line for line in code.splitlines(True))
) | 71084f68ff268eaaa2eec2f8f22394e963fdd894 | 39,858 |
import requests
def send_query(query_dict):
"""Query ChEMBL API
Parameters
----------
query_dict : dict
'query' : string of the endpoint to query
'params' : dict of params for the query
Returns
-------
js : dict
dict parsed from json that is unique to the submitte... | 0708e2672c8c2a9571661661e0bef062718993c2 | 538,602 |
def FTCS(Uo, diffX, diffY=None):
"""Return the numerical solution of dependent variable in the model eq.
This routine uses the explicit Forward Time/Central Space method
to obtain the solution of the 1D or 2D diffusion equation.
Call signature:
FTCS(Uo, diffX, diffY)
Parameters
------... | 4b02749f3f50a2cff74abb75146159289d42b99e | 706,387 |
from typing import List
def _format_active_bus_response(response: dict) -> List:
"""
Formats response with currently active buses.
Args:
response: not processed response with currently active buses.
Returns:
list of dicts with active buses data.
"""
return response['result'] | 728e82cdb6de7190da35e645d1cb93350531475a | 458,716 |
from typing import Type
from typing import Any
def is_new_type(type_: Type[Any]) -> bool:
"""
Check whether type_ was created using typing.NewType
"""
# isinstance(type_, test_type.__class__) and hasattr(type_, "__supertype__")
return type_.__name__ == "Unique" | 562578502db4ff873eda6e0b0e137e041f048043 | 558,772 |
def rect_center(rect):
"""Return the centre of a rectangle as an (x, y) tuple."""
left = min(rect[0], rect[2])
top = min(rect[1], rect[3])
return (left + abs(((rect[2] - rect[0]) / 2)),
top + abs(((rect[3] - rect[1]) / 2))) | dc9060634c66bfa5fdf22db40604fab077ba35e8 | 254,993 |
def get_label(audio_config):
"""Returns label corresponding to which features are to be extracted
e.g:
audio_config = {'mfcc': True, 'chroma': True, 'contrast': False, 'tonnetz': False, 'mel': False}
get_label(audio_config): 'mfcc-chroma'
"""
features = ["mfcc", "chroma", "mel", "contrast", ... | 5f8b0bbe9966fd50e34e5bdb23cf915970f2170f | 82,793 |
def effective_authority(request):
"""
Return the authority associated with an request.
This will try the auth client first, then will return the results of
`default_authority()`.
"""
if request.identity and request.identity.auth_client:
return request.identity.auth_client.authority
... | 648c51d3afda3eb324e413bbdc1d8bb6323faada | 501,709 |
def probSingle(x: int, _: None) -> float:
"""Probability of Dice X=x"""
return 1 / 6 | 7a063e02f4a9bc7344147fd9cff06be30f96418a | 304,014 |
def eratosthenes_sieve(n):
"""
Sieve of Eratosthenes
Complexity: O(NloglogN)
We can find all the prime number up to specific
point. This technique is based on the fact that
the multiples of a prime number are composite numbers.
That happens because a multiple of a prime number will
alwa... | e4b0446d93d7ad6df8b98ed976a53f77ec21067a | 70,410 |
def parse_tcp_uri(uri):
"""Parse tcp://<host>:<port>.
"""
try:
if uri[:6] != 'tcp://':
raise ValueError
address, port = uri[6:].split(':')
return address, int(port)
except (ValueError, TypeError):
raise ValueError(
f"Expected URI on the form tc... | 76120575341b5cba71304c544fdb5a759ed5fcd2 | 432,712 |
def calculate_maximum_position(velocity: int) -> int:
"""Calculate the maximum position if `velocity` decreases by one after each step"""
final_position = (velocity * (velocity + 1)) // 2 # Gauss summation strikes again
return final_position | a883c6596f7248a3b6fee283621af129e984d736 | 123,081 |
def update_sptype(sptypes):
"""
Function to update a list with spectral types to two characters (e.g., M8, L3, or T1).
Parameters
----------
sptypes : np.ndarray
Input spectral types.
Returns
-------
np.ndarray
Updated spectral types.
"""
sptype_list = ['O', 'B... | 59eaddbea9aeb49f8d65d132839d2ac3f1fa7043 | 388,466 |
import socket
def pick_port(*ports):
"""
Returns a list of ports, same length as input ports list, but replaces
all None or 0 ports with a random free port.
"""
sockets = []
def find_free_port(port):
if port:
return port
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... | 94a4251145da6687358bc9a2eb478d13e89832e4 | 592,689 |
def ensure_prefix(symbol: str, _prefix: str = 'O:'):
"""
ensuring prefixes in symbol names. to be used internally by forex, crypto and options
:param symbol: the symbol to check
:param _prefix: which prefix to check for. defaults to ``O:`` which is for options
:return: capitalized prefixed symbol.
... | f711d52f573f8140dd2f8e522d8d8e1f077c865b | 176,845 |
import math
def get_count_digits(number: int):
"""Return number of digits in a number."""
if number == 0:
return 1
number = abs(number)
if number <= 999999999999997:
return math.floor(math.log10(number)) + 1
count = 0
while number:
count += 1
number //= 10
... | 9b9e8cfdce3e348234f1a293a2593178b9c90d0f | 248,661 |
import math
def block32_ceil_num_bytes(curr_len):
"""Returns the number of bytes (n >= curr_len) at the next 32-bit boundary"""
num_blks = float(curr_len) / 4.0
num_blks_pad = int( math.ceil( num_blks ))
num_bytes_pad = num_blks_pad * 4
return num_bytes_pad | 4cd257aaee029479cfcad605aa6ab4f4ca6ba0f3 | 568,131 |
from typing import Any
from pathlib import Path
def r(obj: Any, ignoreintkey: bool = True) -> str:
"""Convert a python object into R repr
Examples:
>>> True -> "TRUE"
>>> None -> "NULL"
>>> [1, 2] -> c(1, 2)
>>> {"a": 1, "b": 2} -> list(a = 1, b = 2)
Args:
ignorei... | 5c907ee0725ac49958f01ee0fe59f2b9deb7a4fd | 95,546 |
def _dump_multipoint(obj, fmt):
"""
Dump a GeoJSON-like MultiPoint object to WKT.
Input parameters and return value are the MULTIPOINT equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(fmt % c for c in pt) for pt in coords)
... | cdea05b91c251b655e08650807e3f74d3bb5e77b | 889 |
import json
def serialize_json_data(data, ver):
"""
Serialize json data to cassandra by adding a version and dumping it to a
string
"""
dataOut = data.copy()
dataOut["_ver"] = ver
return json.dumps(dataOut) | 1e2bdc63204c7b64044056c15c34e7a4bb62e919 | 667,286 |
async def get_modification_stats(db, index_id):
"""
Get the number of modified otus and the number of changes made for a specific index.
:param db: the application database client
:type db: :class:`~motor.motor_asyncio.AsyncIOMotorClient`
:param index_id: the id of the index to return counts for
... | cbeadb2e7d194b57a9b47e664f3d1cbdbe412bf7 | 635,669 |
def transform_mac_address_to_string_mac_address(string_mac_address):
"""
It transforms a MAC address from raw string format("\x00\x11\x22\x33\x44\x55") to a human readable
string("00:11:22:33:44:55").
"""
return ':'.join('%02x' % ord(b) for b in string_mac_address) | 43a3996a0f89638356f3f9f9e3e3500fd90d6389 | 454,221 |
def sheet_as_dict(worksheet):
"""
Take an xsrd worksheet and convert it to a dict, using the first
row as a header (to create keys for the subsequent rows).
"""
keys = worksheet.row_values(0)
value_range = range(1, worksheet.nrows)
def to_dict(values):
return dict(zip(keys, values))... | d3d48c30444e4059fcb358f3bc3990f92f4374f4 | 619,551 |
def node_below_adjacent_elements(node, surface):
"""
node_below_adjacent_elements determines if a node is below any element adjacent to it in the surface.
Consider the following layout:
*-*-*-* Here, the nodes are shown as * and node (0,0) as X. Elements are shown as o and neighboring
|O|O|o| ele... | 71d0e2765f57095fae713e7afd8df108a3dfb490 | 657,254 |
def sound_match(sound, features):
"""
Match a sound by a subset of features.
.. note::
The major idea of this function is to allow for the convenient matching of
some sounds by defining them in terms of a part of their features alone.
E.g., [m] and its variants can be defined as ["... | ab11449691e1d496e76c9a01d3b7c75c3498ba93 | 360,929 |
def IsYaml(path):
"""Is path a yaml file or not."""
return path.endswith('.yaml') | 974b7b9cbf0e515ed815dddf33bb3bc9b68042a0 | 549,182 |
def round_channels(channels, divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns:
-------
int
Weighted number ... | 605bf4f3e291541c9bd9eea1d4f346fe672c0083 | 539,205 |
import pathlib
import importlib
def config_dict_from_python_fpath(fpath: str = 'config.py', include_dunder_keys: bool = False) -> dict:
"""Use importlib and pathlib to take a string file path of a python config
file and return a dictionary of the config values for key:value.
By default the config dicti... | c2e705d00a7a076b18e27c39ddd39ea8c4efadd3 | 190,982 |
from typing import Counter
def build_vocab(tokenized_src_trg_pairs):
"""
Build the vocabulary from the training (src, trg) pairs
:param tokenized_src_trg_pairs: list of (src, trg) pairs
:return: word2idx, idx2word, token_freq_counter
"""
token_freq_counter = Counter()
for src_word_list, tr... | 28bcb5faa8976380873d9ea9c74b2eecd3bb4c8b | 231,302 |
def request_info(request):
""" Return commonly used information from a django request object.
user_agent, remote_ip, location, resolution.
"""
user_agent = request.META.get('HTTP_USER_AGENT', '')
remote_ip = request.META.get('REMOTE_ADDR', '')
location = request.POST.get('location', 'No Loca... | 83f5b201602f619d2eba939ca4ee14a2b537d43b | 463,305 |
def float_sec_to_int_sec_nano(float_sec):
"""
From a floating value in seconds, returns a tuple of integer seconds and
nanoseconds
"""
secs = int(float_sec)
nsecs = int((float_sec - secs) * 1e9)
return (secs, nsecs) | 671a38791ae12ff4d006f9d262303d3e0f94f2c1 | 364,227 |
def HINGED_PROPERTIES(ELEMENTS):
"""
This function creates an array with the hinge properties per node.
Input
ELEMENTS | Elements properties | Py Numpy array
| Node 0 ... Node (N_NODES - 1), Material ID, |
| Geometry ID, Hinge ID n... | 80a604bda28a69f40c6b8028d92b62249eb0607b | 615,492 |
def strftime(datetime, formatstr):
"""
Uses Python's strftime with some tweaks
"""
# https://github.com/django/django/blob/54ea290e5bbd19d87bd8dba807738eeeaf01a362/django/utils/dateformat.py#L289
def t(day):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'r... | bc748022e5e85c52c70f781c2c5b3bdfdaa1ecc6 | 624,647 |
def xor(a, b):
"""
Returns the exclusive or (XOR) of the two input bits.
"""
assert a in [0, 1]
assert b in [0, 1]
return (a + b) % 2 | c98f871b64244846e5a04058b54ce871c70428a9 | 244,864 |
from datetime import datetime
def time_of_day(start: datetime) -> str:
"""Get time of day period"""
s = start
if s.hour < 4:
return "Night"
if s.hour < 9:
return "Morning"
if s.hour < 16:
return "Day"
if s.hour < 21:
return "Evening"
return "Night" | eb0325d0ed4d42db1bdbe11b3479561fa3e06b02 | 464,295 |
def _scan_real_end_loop(bytecode, setuploop_inst):
"""Find the end of loop.
Return the instruction offset.
"""
start = setuploop_inst.next
end = start + setuploop_inst.arg
offset = start
depth = 0
while offset < end:
inst = bytecode[offset]
depth += inst.block_effect
... | 9cff8ab77563a871b86cdbb14236603ec58e04b6 | 706,067 |
def get_d_max(tasks):
"""
Get the maximum relative deadline among the given periodic tasks.
Parameters
----------
tasks : list of pSyCH.task.Periodic
Periodic tasks among which the maximum relative deadline needs to be
computed.
Returns
-------
float
Maximum rel... | 7d60d0ff7f850a03a83bc992dd5e3828816991d2 | 231,626 |
import copy
def _normalize_barcodes(items):
"""Normalize barcode specification methods into individual items.
"""
split_items = []
for item in items:
if item.has_key("multiplex"):
for multi in item["multiplex"]:
base = copy.deepcopy(item)
base["descr... | 6f576d7789cc045b81abe8535942cf0c0abd912a | 21,213 |
def normalize_stdout(stdout):
"""Make subprocess output easier to consume
Decode bytes to str, strip unnecessary newlines produced by most commands.
:param stdout: return value of `subprocess.check_output` or similar
>>> normalize_stdout(b'/foo/bar\n')
'/foo/bar'
"""
return stdout.decode(... | 0cf202b7611e672de0f681d72873908081256967 | 231,716 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.