content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_s3_filename(s3_path):
"""Fetches the filename of a key from S3
Args:
s3_path (str): 'production/output/file.txt'
Returns (str): 'file.txt'
"""
if s3_path.split('/')[-1] == '':
raise ValueError('Supplied S3 path: {} is a directory not a file path'.format(s3_path))
return s... | 2aac60ef8ba854eb2196a37d2da0bedc30611c6b | 257,565 |
def getTableRADecKeys(tab):
"""Returns the column names in the table in which RA, dec coords are stored, after trying a few possible
name variations.
Args:
tab (:obj:`astropy.table.Table`): The table to search.
Returns:
Name of the RA column, name of the dec. column
... | 93807fe56826ac680605b0494af60ddc6a5014a8 | 28,920 |
def decimal_to_binary(n, l=None):
""" Convert n from decimal to binary
Args:
n -- int -- the decimal value
l -- int -- the number of bits for the binary representation
return the binary value of n
"""
binary = bin(n)[2:]
if l != None:
binary = binary.zfill(l)
... | 9ad0ea3b0f253f3e5ab72a232324a02a024c6f9a | 168,036 |
def cli(ctx, job_id):
"""Get dataset outputs produced by a job.
Output:
Outputs of the given job
"""
return ctx.gi.jobs.get_outputs(job_id) | 07ae08ce1b7518429445c8df55caa90dcccd688d | 70,651 |
def seq(start, stop, step=1):
"""Generate a list of values between start and stop every step
:param start: The starting value
:param stop: The ending values
:param step: The step size
:return: List of steps
"""
n = int(round((stop - start) / float(step)))
if n > 1:
return [start ... | 9471500a1dc13cde41beaad31092f7b00c771cca | 63,125 |
def find_snapshots_to_delete(from_front, to_front):
""" Find all snapshots in from_front that has been deleted, but
has not yet been deleted in the clone to_front. """
snapshots_to_delete = []
self_max_rev = to_front.get_highest_used_revision()
already_deleted_snapshots = set(to_front.get_deleted_sn... | e1298e5c9a1c2cb33ae46740b12e4b33980b5d37 | 59,258 |
def qsize(queue):
"""Get the (approximate) queue size where available.
Parameters
----------
queue : :class:`queue.Queue`
Input queue.
Returns
-------
int
Queue size, -1 if `qsize` method isn't implemented (OS X).
"""
try:
return queue.qsize()
except No... | be170990e4f65d00252b0d9016bfd13774bb3ef1 | 102,729 |
from typing import List
def _read_resultset_columns(cursor) -> List[str]:
""" Read names of all columns returned by a cursor
:param cursor: Cursor to read column names from
"""
if cursor.description is None:
return []
else:
return [x[0] for x in cursor.description] | cacefb20b12f327647d1f77bb12216c80388fcd6 | 26,755 |
def floor_div(arr, val):
""" Floor division of array by value. """
return [i // val for i in arr] | 270d2eb53a288773a36d9cb90b44ecf8f421a34f | 625,938 |
def hasDistInfo(call):
"""Verify that a call has the fields required to compute the distance"""
requiredFields = ["mylat", "mylong", "contactlat", "contactlong"]
return all(map(lambda f: call[f], requiredFields)) | 1e89b5f31f1625cf470ceb9431a3cf7964e3e13b | 372,125 |
import hashlib
def digest_file(filepath):
"""
Get the MD5sum for a single file on disk. Files are read in
a memory-efficient fashion.
Args:
filepath (string): a string path to the file or folder to be tested
or a list of files to be analyzed.
Returns:
An md5sum of th... | d3ee1756b0d8fe193a8de434a7d594403c346409 | 205,716 |
def get_test_module_names(module_list, module_prefix='test_'):
""" Return the list of module names that qualify as test modules. """
module_names = [m for m in module_list
if m.startswith(module_prefix)]
return module_names | 5b99d8df9708aaa83127ba1600e728585fdc9275 | 456,088 |
import ipaddress
def parse_ip_and_port(input):
"""
Parse IP and Port number combo to a dictionary::
1.1.1.1:2000
to:
.. code-block:: python
{'ip': IPv4Address('1.1.1.1'), 'port': 2000}
:param string input: IP and port
:return: dictionary with keys ``ip`` and ``port``
... | b4cf51d96a2790f6dec9cc2e7d8ec5c34b6c3600 | 316,504 |
def _floordiv(i, j):
"""Do a floor division, i/j."""
return i // j | 0e874bca33cda089e2ad5eb6ac4b2418e96f0f10 | 522,189 |
def rect_overlap_area(r1, r2):
"""
Returns the number of pixels by which rectangles r1 and r2 overlap.
"""
x1, y1, w1, h1 = r1
x2, y2, w2, h2 = r2
maxleft = max(x1, x2)
minright = min(x1 + w1, x2 + w2)
maxtop = max(y1, y2)
minbottom = min(y1 + h1, y2 + h2)
if minright < maxlef... | ad96f7f816e8ac18f3fd9f37ff37f847555ea19f | 180,639 |
def key_of_min_value(d):
"""Returns the key in a dict d that corresponds to the minimum value of d.
"""
return min(d, key=lambda key_name: d[key_name]) | 6c9ad0370a5b8efc7bb0b409bab9157b1690a4b5 | 531,783 |
def setintersect_ordered(list1, list2):
"""
returns list1 elements that are in list2. preserves order of list1
setintersect_ordered
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import ... | 86c684ec7d17ea581c13c25fbb47381d08b1a558 | 346,718 |
def sqrt_decimal_expansion(n: int, precision: int) -> str:
"""Finds the square root of a number to arbitrary decimal precision.
Args:
n: A positive integer value.
precision: The desired number of digits following the decimal point.
Returns:
A string representation of ``sqrt(n)`` in... | 5165f98a51a0522aa960a532b10fa07191cf9e12 | 693,676 |
def extract_brackets(line):
"""Splits a scroll 'call line' into identifier + suffix."""
ident, _, enil = line[1:].partition("(")
thing, _, _, = enil.rpartition(")")
return ident, thing | 47b35a331ecf01c2772d6289f1ac8171f655573c | 655,442 |
def format_lines(matched_lines, files, flags):
"""
This formats the result of the find if the pattern is in a certain line in a file.
If -n is in the flags the line number will be included in the search result
`-n` Print the line numbers of each matching line.
:param matched_lines: a list with 1... | fb24cb76bcae5063c3dd3e41e4d0d3830d18c56c | 246,913 |
import random
def genPwd(alpha, length):
"""
Generate a random string (a password).
``alpha'' The characters that may be present in the password. Each character in alpha will be equally likely in the generated password.
``length'' The length of the password string.
"""
# be sure t... | ab441f82725a871e31d04957f5eff90cb6c95efa | 295,495 |
import re
def _pythonify_type(text):
"""
Convert valid Copperhead type expression to valid Python expression.
The Copperhead type language is very nearly syntactically valid
Python. To make parsing types relatively painless, we shamelessly
convert type expressions into similar Python expressions... | 67375cd7ca8691b7ffc66c7affac4c79d1260c6d | 610,284 |
import random
def rand(x,y):
"""
Randomizer for augmentation pipepline
Args:
x (int, float): lower_bound
y (int, float): upper_bound
Returns:
random number between bounds
"""
# use uniform if parameters passed are below 1
if all([v < 1 for v in [x,y]]):
return ... | f12fd340e98455b704143f9c637ae947f5210df8 | 538,942 |
def pt_agent_country(country):
"""Clean the country"""
c = country.strip()
if c.lower() == 'unknown':
return ''
return c | e87389b3a6713933b1ee4a578c7d6ab048d1ac0f | 65,501 |
def uppercase(s: str) -> str:
"""
Convert a string to uppercase.
Args:
s (str): The string to be converted.
Returns:
str: The converted uppercase string.
Example:
>>> uppercase('completely different') == 'COMPLETELY DIFFERENT'
True
"""
return s.upper() | f1ecb6e412ea3ce6e46531174881ad230bed3802 | 635,148 |
def load_stopwords(path):
"""Loads stopwords from `path`, assume each word in new line."""
stopwords = set()
with open(path) as f:
for line in f:
stopwords.add(line.strip())
return stopwords | a1bb465f15a6678ab35895a119352d3334a879d6 | 572,693 |
import typing
def get_bool(
raw: typing.Any,
/,
) -> bool:
"""
Parameters
----------
raw: any
The input to get the boolean from.
Returns
-------
bool
Raises
------
ValueError
If it's unclear what the boolean is.
"""
if raw in ["True", "true", "... | dd6d54610f01d2ed88899a52c477d82692b3d1fd | 349,669 |
def dot_product(a,b):
"""
Computes the dot-product of two vectors.
Parameters
----------
a : (x,y) tuple
b : (x,y) tuple
Returns
-------
float
"""
return a[0]*b[0] + a[1]*b[1] | 5c1b5e8f12c5365262c06519f1ef2dae3486774a | 132,122 |
import hashlib
def get_SHA1_from_data(data):
"""Compute image SHA1.
:param data: image buffer
:type data: buffer
:return: image SHA1
:rtype: str
"""
sha1hash = None
try:
sha1 = hashlib.sha1()
sha1.update(data)
sha1hash = sha1.hexdigest().upper()
except:
print("Could not read data to... | 135839fe683897f08817712c98ef493f11c85b4e | 314,046 |
def get_ij_from_index(r, m, n):
"""
The inverse of get_y_indicator_variable_index(): given the indiator
variable index, return the (i ,j) pair for y_{ij} to which it
corresponds. So when we get a solution from MiniSat+, the variable
index given to this function gets converted to (i,j) our y_{ij}, me... | 1202fc62f7a9d18a7e0fec1bc987041d75ef964d | 193,656 |
def splitbycharset(txt, charset):
"""Splits a string at the first occurrence of a character in a set.
Args:
txt: Text to split.
chars: Chars to look for (specified as string).
Returns:
(char, before, after) where char is the character from the character
set whic... | c23577eb96c9621909acaa816e8791e95dbf493d | 699,340 |
def BranchFilter(branch, patch):
"""Used with FilterFn to isolate patches based on a specific upstream."""
return patch.tracking_branch == branch | 65a1a5e09e52d25dc5e949e805e27e5d78a36c7f | 311,524 |
def notas(* num, s=False):
"""
-> Função para coletar notas dos alunos e retornar informações gerais e a situação da turma.
:param num: Notas da turma
:param s: Situação (Boa, Razoável ou Ruim)
:return: dicionário com informações sobre a turma
"""
soma = sum(num)
qtd = len(num)
maior... | 200b7377b7fcbe9aa0ce13e4784018e719374de2 | 561,603 |
def is_above_or_to_left(ref_control, other_ctrl):
"""Return true if the other_ctrl is above or to the left of ref_control"""
text_r = other_ctrl.rectangle()
ctrl_r = ref_control.rectangle()
# skip controls where text win is to the right of ctrl
if text_r.left >= ctrl_r.right:
return False
... | dcc02e8e9424825704682f6b12683bb9de2fe132 | 661,288 |
def __sizeby(df, col, nbr=5, ascend = False):
"""
Count for specific col in a dataframe
Parameters
----------
df : pd.DataFrame
Dataframe containing the col to count from.
col : str
Column name to count from.
nbr : int, optional
Number of value to retrieves. The defa... | af1bdb3904f70a5969d2b58c93dfa58db7346132 | 438,194 |
import re
def get_tag_value(string, pre, post, tagtype=float, greedy=True):
"""
Extracts the value of a tag from a string.
Parameters
-----------------
pre : str
regular expression to match before the the tag value
post : str | list | tuple
regular expression to match after ... | a48fb09863f6e6fdc79053adb57ae7d28524f566 | 218,128 |
def calc_statistics(df):
""" Build cleaned up dataframe with just stats columns. """
stats = df.loc[:,
['date', 'totale_casi', 'totale_positivi', 'nuovi_positivi', 'variazione_totale_positivi', 'deceduti',
'nuovi_decessi', 'terapia_intensiva', 'ingressi_terapia_intensiva','totale_osped... | 33790523ee006a92e40fe6bcc7f73f11688f0805 | 134,665 |
def s3_read_write_policy_in_json(s3_bucket_name):
"""
Define an IAM policy statement for reading and writing to S3 bucket.
:return: an IAM policy statement in json.
"""
return {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"... | b872fd3c833e0384ed891ab3709826a9e9a823bf | 693,764 |
from typing import Tuple
from typing import Optional
import struct
def _unwrap_apdu(
packet: bytes,
) -> Tuple[Optional[int], Optional[bytes], Optional[int], Optional[int], Optional[bytes]]:
"""
Given a packet from the device, extract and return relevant info
"""
if not packet:
return None... | f99e44aa683442eadb7161502e160e86703fc05c | 516,811 |
def map_01_to_16bit(value):
"""Map value from 0-1 range to 0-65535 range."""
# result = None
# result = int(map_bound(value, 0.0, 1.0, 0, 65535))
# return result
# return int(map_bound(value, 0.0, 1.0, 0, 65535))
# result = None
# if value <= 0:
# # result = 0
# return 0
... | 81a5064504e83e2ab952dba5504faf2b1a63e0fe | 547,938 |
def getTZLookup(tzfname='cities15000.txt'):
"""Returns a mapping from gps locations to time-zone names.
The `tzfname` file is read to map gps locations to timezone names.
This is from: http://download.geonames.org/export/dump/cities15000.zip
Returns a list of `((lat, lon), timezone)` pairs.
"""
... | 3dcb3b297be72eb55c2d75ffc0bf269e27775232 | 22,553 |
def get_categories(cat_file):
"""Get categories of plasmids from input file"""
catDict = {}
with open(cat_file, 'r') as infile:
for line in infile:
line = line.strip().split()
catDict[line[0]] = line[1]
return catDict | 2b03c548977bb6d89450da4d0bb2a02e1cdbeb03 | 69,349 |
def intersection(l1:list, l2:list) -> list:
"""Calculates the intersection of l1 and l2; l1 ∩ l2
Parameters
----------
l1 : list
The first list/set
l2 : list
The second list/set
Returns
-------
list
The list of the intersection between L1 and L2
"""
resu... | 581e6a20f990e6552334cc4ece31bb88be1cae4c | 256,749 |
def _xrt_component_package(name, package):
"""
Get component package filename from base XRT package filename.
Args:
name (str): Package component name like 'xrt' or 'aws'.
package (str): Package filename.
Returns:
Component package filename.
"""
return package[::-1].rep... | d46e919811a2e4fdcc0fc7eb75cdc062b32453c9 | 309,204 |
def CONVERT_LAMBDA(x):
"""
Function to convert amount in dollars to a float
"""
return float(x.replace("$", "").replace(",", "")) | 59912840738c946a0c1eaff793fd988cd44977f8 | 139,445 |
def iso2sec(iso: str) -> int:
"""
:param iso: e.g. 1:01:02
:return: sec in int
"""
arr = iso.split(':')
len_arr = len(arr)
if len_arr <= 3:
arr = ['0'] * (3 - len_arr) + arr
else:
raise Exception('len_arr > 3, arr: {}'.format(arr))
return int(arr[0]) * 60 * 60 + int(... | 6e3285955fd7e91071f2d4e7c8b17b5a167a1fef | 512,552 |
def extract_xmax(mfile):
"""
Extract the maximum X-coordinates of the band structure and return
that value.
"""
xmax = 0.0
for line in mfile:
words = line.split()
if len(words) == 0:
return xmax
else:
xmax = float(words[0])
return xmax | ada90d8d1dd40538d177b07a8da177923f8ff49d | 411,630 |
def write_evt_file(ext_files_dir, name, event):
"""
Append event into the evt file of the extension.
:param ext_files_dir: The 'files' directory of the extension.
:param name: Name of the evt file
:param event: The event to append.
:return:
"""
events_dir = ext_files_dir / 'events'
events_dir.mkdir(parents=Tru... | b9bc3ba32964d6ea570c880bddebb615a331dac9 | 403,535 |
def to_bit_list(val, width=16):
"""Convert a number to a list of bits, LSB first"""
return [(1 if val & (1<<n) else 0) for n in range(width)] | 66365917d9c60b10da277b8d777a3060dd70c511 | 91,433 |
def get_all_preconditions(action_set):
"""
Returns a set of all preconditions for the actions in the given set
"""
all_precons = set()
for a in action_set:
all_precons.update(a.precondition)
return all_precons | 1697c2d013b07bbfc24ca6273d16523eb1d83acf | 703,431 |
import json
def get_all_topic_id_and_meta(client):
"""
Execute query to return meta dict for all topics.
This information should take from 'meta' measurement in the InfluxDB database.
:param client: InfluxDB client connected in historian_setup method.
:return: a dictionary that maps topic_id to i... | 0a7ed8d50438f9623eac3ee6d37c5145a11ddd6e | 548,563 |
def separate_files_and_options(args):
"""
Take a list of arguments and separate out files and options. An option is
any string starting with a '-'. File arguments are relative to the current
working directory and they can be incomplete.
Returns:
a tuple (file_list, option_list)
"""
f... | eae2de9cb93308b78ddf279304a73c6c5e1070e2 | 691,482 |
def size(matrix):
"""
:param matrix: the matrix to compute the size
:type matrix: matrix
:return: the size of matrix (number of rows, number of cols)
:rtype: typle of 2 int
"""
return len(matrix[0]), len(matrix) | 7144202b0d341e2f242806f471f50fbee6b7420a | 505,961 |
import re
def parseRange(text):
"""
convert a range string like 2-3, 10-20, 4-, -9, or 2 to a list
containing the endpoints. A missing endpoint is set to None.
"""
def toNumeric(elt):
if elt == "":
return None
else:
return int(elt)
if re.search(r'-', t... | bec19909188ffdb1de1de233a5f33675fa1ea48b | 67,221 |
def filtered_alarm(alarm):
"""
Restructure a CloudWatch alarm into a simpler form.
"""
filtered = {
"AlarmArn": alarm["AlarmArn"],
"AlarmName": alarm["AlarmName"],
"MetricName": alarm["MetricName"],
"Namespace": alarm["Namespace"],
"StateValue": alarm["StateValue"... | 1430fdd6f03d56cb564e5c7b6167679ec554f148 | 397,300 |
def hasShapeType(items, sort):
"""
Detect whether the list has any items of type sort. Returns :attr:`True` or :attr:`False`.
:param shape: :class:`list`
:param sort: type of shape
"""
return any([getattr(item, sort) for item in items]) | 9a1c8dbe0a850cc45d4be0ac9d1327b778dc987a | 682,740 |
def compare_list(list1: list, list2: list) -> bool:
"""Compare two list and ignore \n at the end of two list."""
while list1[-1] == "\n" or list1[-1] == "":
list1.pop()
while list2[-1] == "\n" or list2[-1] == "":
list2.pop()
return list1 == list2 | f7e925116dd952fb64e89c4da5b2256682cfb3a3 | 666,307 |
def get_population(array_islands):
"""
Extract the population size for every island within the island group. Return
those as an array.
"""
pops = []
for index, isle in enumerate(array_islands):
pops.append(isle.m)
return pops | 727f6705f12b03407dcf980c14941883f1327228 | 460,712 |
import click
def locale_option(help_text=None, multiple=True):
"""Option for providing locale(s)."""
if help_text is None:
help_text = 'Locale to target.'
def _decorator(func):
return click.option(
'--locale', type=str, multiple=multiple, help=help_text)(func)
return _deco... | b0ef695a38f5f4c14b665a9e9dd5cf18d60b983f | 493,079 |
from typing import Union
def constrain(value: Union[int, float], max_val: Union[float, int], min_val: Union[float, int]=0):
"""
Constrain given value in given boundaries.
:param value: value to be constrained
:param max_val: value cannot be more than this
:param min_val: returned value won't be l... | 210a7059d58ab0a0d62ad95b41200e4c8d44d6c2 | 435,651 |
def nvmf_create_target(client,
name,
max_subsystems=0):
"""Create a new NVMe-oF Target.
Args:
name: Must be unique within the application
max_subsystems: Maximum number of NVMe-oF subsystems (e.g. 1024). default: 0 (Uses SPDK_NVMF_DEFAULT_MAX_SUBSYS... | 7b10540651b169406f942889caabef95506c4232 | 661,262 |
def ham_dist(s1, s2):
"""
The Hamming distance is defined between two strings of equal length.
It measures the number of positions with mismatching characters.
"""
assert len(s1) == len(s2)
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) | 24294f08c88559a37c51f8151525fce92883f6b8 | 491,168 |
def generateTypeConverter(name, cache, typeConverter):
"""
Type converter
Args:
name (str):
cache:
typeConverter:
Returns:
lambda: Function to convert the type
"""
return lambda value: typeConverter(name, value, cache) | 808c362902ae9a0173b5b7a3bbc12be0306266e9 | 171,865 |
import requests
import csv
def fetch_trac(base_url):
"""
Return a fetcher for a Trac instance
>>> url, n = fetch_trac("https://debathena.mit.edu/trac")("123")
>>> url
u'https://debathena.mit.edu/trac/ticket/123'
>>> n
u'debathena-ssl-certificates should include a CRL'
>>> url, n = fet... | de17fac1de86bd338f3e9ed6f297d0ce9dd80ec9 | 259,552 |
def deal_cards(shuffled_deck):
"""Returns a hand of 13 cards each to four players from a shuffled deck"""
hands = [[], [], [], []]
print("Dealing the cards!")
hands[0] = shuffled_deck[:13]
hands[1] = shuffled_deck[13:26]
hands[2] = shuffled_deck[26:39]
hands[3] = shuffled_deck[39:]
retur... | a41ce5a27e93d364e2f9d0117363804f77afbf5d | 448,466 |
def conjoin(functions, *args, **kwargs):
"""Returns True if all functions return True when applied to args."""
for f in functions:
if not f(*args, **kwargs):
return False
return True | b84746e9f14373153c277727612241a2b11d20de | 599,244 |
def is_canonical_chromosome(chr):
"""Check if chr is 1-22, X or Y (M not included)
Args:
chr (str): chromosome name
Returns:
is_canonical (bool): True if chr is 1-22, X or Y
"""
is_canonical = False
if chr.startswith("chr"):
chr = chr.replace("chr", "")
if chr == "... | fd2467c26fa9b2a0f7abee840b5e12d7fee49ea6 | 162,138 |
from datetime import datetime
def time_ago(date):
"""
Returns a string like '3 minutes ago' or '8 hours ago'
Got this from joltz in #python on freenode. Thanks!
>>> time_ago(datetime.now() - timedelta(seconds=90))
'one minute ago'
>>> time_ago(datetime.now() - timedelta(seconds=900))
'... | 37c30e78540aee715eacfc88586cdeb151920e3a | 426,991 |
from typing import Dict
from typing import List
def make_data_lists(img_pth_to_cap: Dict[str, str], image_paths: List[str]):
"""Make lists of data paths and respective captions
Args:
img_pth_to_cap: Dictionary of image paths to captions
image_paths: List of image paths
Returns:
img... | dafee60e5a6ebcab9046cfd7b90f01a9eda08d02 | 50,303 |
import calendar
def _datetime_to_millis(dtm):
"""Convert datetime to milliseconds since epoch UTC."""
if dtm.utcoffset() is not None:
dtm = dtm - dtm.utcoffset()
return int(calendar.timegm(dtm.timetuple()) * 1000 +
dtm.microsecond // 1000) | e013e835b062173d434b19e4734d028c41e407e2 | 532,279 |
def ConvertToNumber(value):
"""Converts value, a string, into either an integer or a floating point
decimal number.
"""
try:
# int() automatically promotes to long if necessary
return int(value)
except:
return float(value) | a6c2e68d1cbed30d1daaff18ec7a395cd3d1fb62 | 539,437 |
def scienti_filter(table_name, data_row):
"""
Funtion that allows to filter unwanted data from the json.
for this case:
* fields with "FILTRO"
* values with the string "nan"
* passwords
anything can be set here to remove unwanted data.
Parameters:
table_name:str
n... | 03029587e43f4e8aad809b607c45f53149d94fa2 | 652,704 |
from datetime import datetime
def _readable_date(string):
"""
A function that accepts a string formatted date and return a more readable data string format.
:param string: string formatted date
:return: Human readable string formatted date
"""
return datetime.strptime(string, '%Y%m%d').date()... | e53584b0b28ae7c8122d060047cd35f4d625da7a | 465,059 |
def format_code(code):
"""
Generates the string for a code block of the example page, formatted for a
'sphinx-gallery' example script.
Parameters
----------
code : string
The python source code to be formatted.
Returns
-------
string : The formatted string for the example scr... | 668c77a6923236f53c6be5465a22c77a2b1cd5dc | 169,674 |
import re
def remove_all(value):
"""
Remove all whitespaces from a string.
:param value: The value
:type value: str
:return: The value with all whitespaces removed
:rtype: str
"""
return re.sub(r"\s+", "", value) | 84e1c698cfbfae972b06d3af870ed5f664fc8be0 | 576,185 |
def float_or_string(arg):
"""Force float or string
"""
try:
res = float(arg)
except ValueError:
res = arg
return res | 3dd47e9688ae8e4693e76482e041644bb2d8ab4d | 125,697 |
def test_model_accuracy(model, probe_method, test_set, test_answer):
"""
Tests the model on the given set and returns the accuracy
:param model: a trained model
:param probe_method: the models query method, takes an instance as a parameter and returns the prediction
:param test_set: an iterable obj... | 51deef7df7d3fe8926fd7b71706b2af68536e37b | 525,189 |
def find_zetas_from_sigmas(sigmas, m):
"""Find first m complete symmetrical polynomials zetas using 'sigmas'.
For this we use:
zeta_k = \\sum_{i=1}^k (-1)^(i+1) sigmas[i] zetas_{k-i}."""
zetas = [0.] * m
zetas[0] = 1.
for k in range(1, m):
zetas[k] = sum([sigmas[i] * zetas[k - i] * (-1... | 71cbe2580be3299b4bea889e50e5d3e0076cb0bf | 505,864 |
def cmp_individual_scaled(a, b):
""" Compares two individual fitness scores, used for sorting population
Example:
>>> GPopulation.cmp_individual_scaled(a, b)
:param a: the A individual instance
:param b: the B individual instance
:rtype: 0 if the two individuals fitness score are the same,
... | 07fcbaf73621948ec8fe2c48e2e6a4f573203475 | 650,725 |
def bitstring_to_number(bitstring):
"""
Convert a bitstring to a number.
E.g. ``10110101`` gives 181.
Args:
bitstring (str): String of ``1``\ s and ``0``\ s.
Returns:
int: The equivalent integer.
"""
return int(bitstring, 2) | 86db64054deaed761638b97640301e11de8577cc | 397,268 |
def txout_compress(n):
""" Compresses the Satoshi amount of a UTXO to be stored in the LevelDB. Code is a port from the Bitcoin Core C++
source:
https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/compressor.cpp#L133#L160
:param n: Satoshi amount to be compressed.
:type n: int
:return: The ... | 94a10e34cdb3d5abf5da1b97240539b5e3308f93 | 238,919 |
def calculate_rewards_common(covariates, coeffs_common):
"""Calculate common rewards.
Covariates 9 and 10 are indicators for high school and college graduates.
Parameters
----------
covariates : np.ndarray
Array with shape (num_states, 16) containing covariates.
coeffs_common : np.ndar... | 00b268aeddda5fdec4c8faf7b22d897e13cdd8c3 | 91,610 |
def get_package(config):
"""
Returns the package associated with this device
Args:
config (dictionary): configuration dictionary
Return:
(string) package
Raises:
Nothing
"""
#split the device string with "-" and get the second value
package = config["devi... | 5a13e28eafceaaab018373141108d2f8e75f2a37 | 668,876 |
def dispense_cash(amount):
""" Determine the minimum number of ATM bills to meet the requested amount to dispense
Parameters
----------
amount : int
The amount of money requested from the ATM
Returns
-------
int
The number of bills needed, -1 if it can't be done... | a85f56f900b52f4ddd0bdd93ebd97c1d80889c36 | 85,197 |
import requests
def connection_ok(base_url):
"""Check whetcher connection is ok
Post a request to server, if connection ok, server will return http response 'ok'
Args:
none
Returns:
if connection ok, return True
if connection not ok, return False
Raises:
none
... | b4d6bdfe2ec8d511238a65ef359abfbed0b5f86a | 630,101 |
def subsetByDate(data, start, end):
"""Function that takes in a DataFrame and start and end dates, returning the subset of the frame with these dates"""
return data[(data.index > start) & (data.index <= end)] | dcb001350b7e225845aa808068632c7b074f8ad0 | 494,389 |
def is_quoted(str):
""" whether or not str is quoted """
return ((len(str) > 2)
and ((str[0] == "'" and str[-1] == "'")
or (str[0] == '"' and str[-1] == '"'))) | b079bd4a7f3ac8814250faf522d9e38718fce986 | 30,353 |
def format_path(plot_root: str, variant: str) -> str:
"""
Format path.
Convert representation of variant to
a path.
:param plot_root: root path can be url
:param variant: variant
:return: path of variant resource
"""
return f"{plot_root}{variant}.png" | bb3d53b1dee77304fd6952672f25882327b988de | 146,995 |
def is_in_stock(res_obj):
"""Checks if a product is in stock
Args:
res_obj: requests_html response object of a canada computers product page
Returns:
bool: Is the product in stock
"""
selector = '#pi-form > div.col-12.py-2 > div.pi-prod-availability > span:nth-child(2)'
stock ... | 59a560b9d40bd40045fbce4d5f90fa9d0ceb2b1b | 144,582 |
def pad_up(size, factor):
"""Pad size up to a multiple of a factor"""
x = size + factor - 1
return x - (x % factor) | 724673db1d2ba9fecb81e2ea58c224b48541eae8 | 397,469 |
def int_array_to_hex(iv_array):
"""
Converts an integer array to a hex string.
"""
iv_hex = ''
for b in iv_array:
iv_hex += '{:02x}'.format(b)
return iv_hex | f3332b7672a266ad9cae9fc52bc8e1152bcee58b | 709,254 |
def pad_bytes32(instr):
""" Pad a string \x00 bytes to return correct bytes32 representation. """
bstr = instr.encode()
return bstr + (32 - len(bstr)) * b'\x00' | 76c057b64435f2bc9d0c3c92f1b9315fb6252fd9 | 693,015 |
def _apply_nested(structure, fn):
"""Recursively apply a function to the elements of a list/tuple/dict."""
if isinstance(structure, list):
return list(_apply_nested(elem, fn) for elem in structure)
elif isinstance(structure, tuple):
return tuple(_apply_nested(elem, fn) for elem in structure)... | 5c60338c070a8401b72f2d7a6e74205a63e3af83 | 552,297 |
def get_cookie_value( cookiejar, name ):
"""
Retrieves the value of a cookie from a CookieJar given its name.
"""
value = None
for cookie in cookiejar:
if cookie.name == name:
value = cookie.value
break
return value | 95e60548eb149bdd399ca5f3fc84ebc5fbf1eb87 | 544,447 |
def int_to_binary_string(n):
"""
Return the binary representation of the number n
:param n: a number
:return: a binary representation of n as a string
"""
return '{0:b}'.format(n) | 7052b9c1d17c4eb0b67b27b96bb656e996922d02 | 239,489 |
def prefix_sums(A):
"""
This function calculate of sums of eements in given slice (contiguous segments of array).
Its main idea uses prefix sums which
are defined as the consecutive totals of the first 0, 1, 2, . . . , n elements of an array.
Args:
A: an array represents number of mushroom... | d61e49eb4a973f7718ccef864d8e09adf0e09ce2 | 707,913 |
def factorial(n):
"""
Returns the factorial of a number.
"""
fact = 1.0
if n > 1:
fact = n * factorial(n - 1)
return fact | 7c20382a053cc3609fa041d1920d23b884b8aa0b | 32,018 |
def range_check(s: str, mn: int, mx: int) -> bool:
"""Check a numeric str in in a range."""
return mn <= int(s) <= mx | 4b7eda8f0c5ec21dfc70db2176f16231779bbb47 | 227,084 |
import time
def lomuto_partition_scheme(L, draw_data, time_delay, low, high):
"""
Used as a component in quicksort algorithm.\n
Prepares partition such that all values up to index i are smaller than
the pivot and all values from i + 1 are greater than the pivot
"""
i = low - 1
pivot = L[hi... | dceaccda0764666c7e4c5cdc5c9185e5fb1fb139 | 408,999 |
import re
def remove_extra_description_terms(description):
"""
Sometimes the description contains some things we don't want to include
like trailing '.', extra spaces, the string (non-protein coding) and a typo
in the name of tmRNA's. This corrects those issues.
"""
description = re.sub(
... | 73e4ae305fc728a1ce815f040d2f4aa403df30f6 | 630,801 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.