content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_captions_from_dict(img_to_cap_dict):
"""
Extracts captions from the img_to_cap_dict dictionary
and adds them to a list.
Args:
img_to_cap_dict: the dictionary storing image to caption mappings
Returns:
captions: a list storing all captions extracted from the dictionary
"""
captions = []
for image_n... | 2378e8233f6ff5e9d8a96d8773d5fab779eace33 | 61,821 |
def int32_to_octets(value):
""" Given an int or long, return a 4-byte array of 8-bit ints."""
return [int(value >> 24 & 0xFF), int(value >> 16 & 0xFF),
int(value >> 8 & 0xFF), int(value & 0xFF)] | 06ea4d1c47b4a99ef9a8ff530b4e5b2d00abd54d | 61,822 |
def generate_base_code(naval_base: bool,
scout_base: bool,
pirate_base: bool) -> str:
"""Returns a base code, one of:
A -- Naval Base and Scout Base/Outpost
G -- Scout Base/Outpost and Pirate Base
N -- Naval Base
P -- Pirate Base
S -- Scout Base/Outpost
... | 48ea0037fa2dc3e1b1efa9a5ae9b9678ece78551 | 61,825 |
def compDict2List(compDict):
"""
utility function to create a list of component keys and a list of
compoenent values from a component dictionary
"""
return (list(compDict.keys()),list(compDict.values())) | d10baa3bc10b755c024b58067fcbdaff1d7d2775 | 61,828 |
def concatenate(value, arg):
"""Concatenate value and arg"""
return f"{value}{arg}" | 3245fb025a39e0a3ad64d0434b1ec5324ff14f5b | 61,830 |
def extract_pob(loaded_df):
"""
Extracts the place of birth of each row. The coded values are the following:
-1 - Invalid value
1 - Born inside Canada
2 - Born outside Canada
:param loaded_df: The dataframe loaded from the file
:return: A list containing the new values of the place of birth
... | a5a40b5cef4ecc288429f71723fc0277c695c537 | 61,831 |
import calendar
def datetime_to_unix(timestamp, milliseconds=False):
"""Converts a datetime object to a unix timestamp.
Args:
timestamp: A datetime object.
milliseconds: Bool, default False, return result in milliseconds instead.
Returns:
An integer of unit timestamp in seconds.
"""
if millise... | 3e8cac46c5d458202eacc82ef150e51b48cc55d7 | 61,835 |
def edge_threshold(grad_mag, thresh):
"""
Takes the array of gradient magnitude values and suppresses pixels below the threshold value.
grad_mag: Gradient magnitude for an image which is an array of the same shape as the original image.
thresh: Threshold value for which pixels to include in edge detec... | 9182c7d16fbb0f0e22c89ed64de77ebe4f8e899e | 61,840 |
def get_object_map(id_offset: int) -> dict:
"""
Returns ID to communication object mapping of a given CAN node ID.
Map taken from https://en.wikipedia.org/wiki/CANopen#Predefined_Connection_Set[7]
"""
return {
0x000 : "NMT_CONTROL",
0x001 : "FAILSAFE",
... | 7f7ecdb7b6620eb5cde3682865fccd3c927c711f | 61,841 |
def is_number(str):
"""
Checks wether a string is a number or not.
:param str: String.
:type str: string
:returns: True if `str` can be converted to a float.
:rtype: bool
:Example:
>>> is_number('10')
True
"""
try:
float(str)
return True
... | f8391667115f09f90fcdd6593883f10e5c6d2597 | 61,842 |
def construct_error_message(files_dict):
"""Function to construct an error message pointing out where bad latin
phrases appear in lines of text
Arguments:
files_dict {dictionary} -- Dictionary of failing files containing the
bad latin phrases and offending lines
Returns:
{strin... | b2d1f1f0cc677f1797a2706a1c2ed249253f8fda | 61,843 |
def _nofilter(text):
"""Return the supplied text unchanged"""
return text | 3c843e9ea6e00d3a3eaa4dd759732aebefde38b0 | 61,845 |
from pathlib import Path
import json
def template_json(keyboard):
"""Returns a `keymap.json` template for a keyboard.
If a template exists in `keyboards/<keyboard>/templates/keymap.json` that text will be used instead of an empty dictionary.
Args:
keyboard
The keyboard to return a te... | 7949c78a164abfb04ef1b46caaf0897acac88bfc | 61,846 |
import hashlib
import uuid
def generate_uuid_from_string(the_string):
"""
Returns String representation of the UUID of a hex md5 hash of the given string
"""
# Instansiate new md5_hash
md5_hash = hashlib.md5()
# Pass the_string to the md5_hash as bytes
md5_hash.update(the_string.encode("... | 29d29adfacafb27191b6af01da5a9073eb34d4ed | 61,852 |
def doubleVal(input):
"""Return twice the input vallue
"""
return input * 2 | 954ac7fc806b35e7f9ffb1c8244e8b4ed4f15fd6 | 61,853 |
def partition(pred, iterable):
"""Returns [[trues], [falses]], where [trues] is the items in
'iterable' that satisfy 'pred' and [falses] is all the rest."""
trues = []
falses = []
for item in iterable:
if pred(item):
trues.append(item)
else:
falses.append(item... | be96fc0a560a0c2e5bd25e12387622167b4f084b | 61,854 |
def update_template(template, pardict):
"""Makes variable substitution in a template.
Args:
template (str): Template with old style Python format strings.
pardict (dict): Dictionary of parameters to substitute.
Returns:
str: String with substituted content.
"""
return templ... | e8b5c220e7e66b3c0540938d229f2e75104e02bc | 61,857 |
def calculate_shape_keeping_aspect_ratio(height: int, width: int, min_size: int, max_size: int):
"""
The function changes spatial sizes of the image keeping aspect ratio to satisfy provided requirements.
The behavior of this function is equivalent to the output shape calculation of the pre-processor block o... | f61ae6b9c13250093c6d4685e468f7a5634605c6 | 61,860 |
def get_cn_description(cn):
"""
Writes a verbal description of the coordination number/polyhedra based on a given coordination number
:param cn: (integer) rounded coordination number
:return: (String) verbal description of coordination number/polyhedra
"""
rounded_cn = round(cn)
description ... | 832322bb6b3ed26af7fa51bf7036123e93d7efa3 | 61,862 |
def get_attribute(obj: dict, path: list):
"""
Get attribute iteratively from a json object.
:param obj: object to iterate on
:param path: list of string to get sub path within json
:return: the value if the path is accessible, empty string if not found
"""
current_location = obj
for tok... | a21c3d7d58eb11673d46a09ce6e830345be62e96 | 61,867 |
import yaml
def parse_yaml_to_dict(contents):
"""
Parses YAML to a dict.
Parameters
----------
contents : str
The contents of a file with user-defined
configuration settings.
Returns
-------
dict
Configuration settings (one key-value
pair per setting) or... | de97a20c5343ab909351261a3dfafad8590b2f57 | 61,870 |
def get_makefile_name(libname):
"""
Given a library name, return the corresponding Makefile name.
"""
return "Makefile.%s" % libname | 43d9f97f9bed9a7052fbaba10d97afda8ca1da7b | 61,872 |
import re
def validate_string(password_string):
"""
Performs a number of checks to see
if a string can be a valid password
"""
if len(password_string) < 8:
message = "Password must contain atleat 8 characters."
return (message, False)
elif re.search('[0-9]', password_string) is... | 1ddd108daba38de9b8c2b6360bca7e04cb7de75f | 61,875 |
import re
def regex_filter(pattern, list_of_strings):
"""Apply regex pattern to each string and return those that match.
See also regex_capture
"""
return [s for s in list_of_strings if re.match(pattern, s) is not None] | 68437ed5dd9ed4690a22c9da7aa225a596e6b755 | 61,876 |
import ctypes
def c_encode_char(string):
""" ctypes char encoding
Args:
string (str): string to encode as c_char_p
"""
return ctypes.c_char_p(string.encode()) | ff933e7e4e1ec60a28d67cab42542ab198efce26 | 61,877 |
def get_legal_topic_name(topic: str) -> str:
"""Returns a legal Kafka topic name
Special characters are not allowed in the name
of a Kafka topic. This method returns a legal name
after removing special characters and converting each
letter to lowercase
Parameters
----------
topic: str
... | ca313d9ef0f55f15e440d02d7f2f278bf1e9a2ee | 61,882 |
def startswith_token(s, prefix, separators=None):
"""Tests if a string is either equal to a given prefix or prefixed by it
followed by a separator.
"""
if separators is None:
return s == prefix
prefix_len = len(prefix)
if s.startswith(prefix):
if len(s) == prefix_len:
return True
if isinstance(separa... | 07e8bc52ec24bac862281c2efaa4344ea499396a | 61,885 |
def find(question, cur):
"""
Finds a corresponding answer for the input question.
Args:
question: input question row
cur: database cursor
Returns:
Answer row if found, None otherwise
"""
# Query for accepted answer
cur.execute("SELECT Body, OwnerUserId, OwnerDispla... | bdb6c21165a914d6084c7ee2a0f2db0a7b6f7873 | 61,886 |
def get_sheet(book, sheetName=None, sheetIndex=0):
"""Get xlrd sheet object"""
if sheetName is not None:
sheet = book.sheet_by_name(sheetName)
return sheet
else:
sheet = book.sheet_by_index(sheetIndex)
return sheet | 1db384417769299540e892321c029f71f9f4f10b | 61,887 |
def _boto_tags_to_dict(tags):
"""Convert the Tags in boto format into a usable dict
[{'Key': 'foo', 'Value': 'bar'}, {'Key': 'ham', 'Value': 'spam'}]
is translated to
{'foo': 'bar', 'ham': 'spam'}
"""
return {item['Key']: item['Value'] for item in tags} | d4935269864a0cb09ef8d84cbbc44402383e8edb | 61,889 |
def location(text, index):
"""
Location of `index` in the `text`. Report row and column numbers when
appropriate.
"""
if isinstance(text, str):
line, start = text.count('\n', 0, index), text.rfind('\n', 0, index)
column = index - (start + 1)
return "{}:{}".format(line + 1, c... | 5f8026d3d30267833c6014a6d338b9d7fb2e5294 | 61,890 |
def bound_elems(elems):
"""
Finds the minimal bbox that contains all given elems
"""
group_x0 = min(map(lambda l: l.x0, elems))
group_y0 = min(map(lambda l: l.y0, elems))
group_x1 = max(map(lambda l: l.x1, elems))
group_y1 = max(map(lambda l: l.y1, elems))
return (group_x0, group_y0, gro... | 300169c886801845cc17de666ceaacff2c73baa2 | 61,894 |
def split_feature_matrices(x_train, x_test, y_train, y_test, idx):
"""Does the opposite of merge_feature_matrices i.e. when given the
train and test matrices for features and labels, splits them into
train/active, test/active, train/inactive, test/inactive.
Parameters:
- x_train, x_test, y_train... | 41ef3ccbee3cad1fbce2485d02f5d67c9870cfef | 61,898 |
def human_delta(tdelta):
"""
Takes a timedelta object and formats it for humans.
Usage:
# 149 day(s) 8 hr(s) 36 min 19 sec
print human_delta(datetime(2014, 3, 30) - datetime.now())
Example Results:
23 sec
12 min 45 sec
1 hr(s) 11 min 2 sec
3 day(s) 13 hr(s... | c15cdfcc8cc8594e10b08d6cc5180d08d8460053 | 61,900 |
def get_waters(lines):
"""Helper function to extract waters from a PDB file"""
return "".join([line for line in lines if line[17:20] == "HOH"]) | 468fa05f0a1213669eb1a1ac2d29b0191ba96887 | 61,910 |
def ramachandran_type(residue, next_residue) :
"""Expects Bio.PDB residues, returns ramachandran 'type'
If this is the last residue in a polypeptide, use None
for next_residue.
Return value is a string: "General", "Glycine", "Proline"
or "Pre-Pro".
"""
if residue.resname.upper()=="GLY" :
... | 42e06d73a0d00f9f5a623677bc59b7747e150501 | 61,915 |
def clip_curvatures(vals, radius=0.03):
""" Clips principal curvatues to be in a defined range.
A principal of curvature of k corresponds to the curvature
(in one direction) of a sphere or radius r = 1/k. Since
Our mesh has somewhat of a low resolution, so we don't
want to consider c... | 72bc964ce0dd7691304a56ec356a29571b60407f | 61,916 |
def name_to_label(self, class_name):
""" Retrieves the class id given a class name """
return self.name_to_class_info[class_name]['id'] | 5dc630932a5938894a3db6912d0a5469c3e9cbdf | 61,919 |
import torch
def batch_identity(batch_size, matrix_size, *args, **kwargs):
"""
Tile the identity matrix along axis 0, `batch_size` times.
"""
ident = torch.eye(matrix_size, *args, **kwargs).unsqueeze(0)
res = ident.repeat(batch_size, 1, 1)
return res | 412f59ff9e5e8c802c0cfc6c6614fce6f14138ad | 61,927 |
def dec2bin(num, width=0):
"""
>>> dec2bin(0, 8)
'00000000'
>>> dec2bin(57, 8)
'00111001'
>>> dec2bin(3, 10)
'0000000011'
>>> dec2bin(-23, 8)
'11101001'
>>> dec2bin(23, 8)
'00010111'
>>> dec2bin(256)
'100000000'
"""
if num < 0:
if not width:
... | a63cfca8506d23ee69eeb112d489cf9af0542f79 | 61,928 |
def taylor_sin(x:float, order:int):
"""
使用泰勒公式近似sinx
:param x: x
:param order:阶数,越高越准但越慢
:return: 结果
"""
e = x
s = x
for i in range(2, order):
e = -1*e*x*x/((2*i-1)*(2*i-2))
s += e
return s | 2c601bc52db0e6943a8b5e61d5f28d20f6aa545e | 61,931 |
def count_datasets(models):
""" Return the number of datasets on the database """
dataset_model = models["dataset"]
return dataset_model.select().count() | 38916c2116ccb0c9bc96f178e4b78e943eb19328 | 61,937 |
import string
def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers and spaces.
shift: 0 <= int < 26
returns: dict
"""
# initialize empty dictionary
di... | db60e548f8561237f80de70aefe28fa9991f1782 | 61,939 |
def problem_4_6(node1, node2):
""" Design an algorithm and write code to find the first common ancestor of
two nodes in a binary tree. Avoid storing additional nodes in a data
structure. NOTE: This is not necessarily a binary search tree.
Solution: traverse from n1 up to the root; for each ancestor, st... | 155376d952fde5b0292e3404c24f8ecfc03e8a6d | 61,940 |
def is_unique(s):
"""Check if the list s has no duplicate."""
return len(s) == len(set(s)) | 75e831313b855cf9c013ca33360a5611606102b1 | 61,941 |
def numWindows(tot, deltaT):
""" Evaluates the number of windows that will be used
given the total time (tot) of a particular induction.
"""
return int( (tot - deltaT)*60. ) | deb0e9a55ddbf8a0a65148c503b2af56a942aacd | 61,942 |
import torch
def dcg(
outputs: torch.Tensor,
targets: torch.Tensor,
k=10,
gain_function="pow_rank",
) -> torch.Tensor:
"""
Computes DCG@topk for the specified values of `k`.
Graded relevance as a measure of usefulness,
or gain, from examining a set of items.
Gain may be reduced at... | 3c654af98e42292c86203d09b0b3e9f3d1808107 | 61,946 |
def validates(*names, **kw):
"""Decorate a method as a 'validator' for one or more named properties.
Designates a method as a validator, a method which receives the
name of the attribute as well as a value to be assigned, or in the
case of a collection, the value to be added to the collection.
The ... | 214394568bf66ccb9a8267535eac51c4e03731e8 | 61,949 |
from typing import Union
from typing import List
def generic_import(name: Union[str, List[str]]):
"""
Import using string or list of module names
"""
if isinstance(name, str):
components = name.split('.')
else:
assert isinstance(name, list), name
components = name
mod ... | 2c9ef55ab66a0b52ff78c8130057a9dec255ab7c | 61,950 |
import random
def get_texts_sampled(texts, number):
"""Returns a sample of size `number` from `texts`"""
number_of_test_texts = min(number, len(texts))
return random.sample(texts, number_of_test_texts) | d8893fc8835a94a0902df2f5dc04da84786b7d11 | 61,951 |
def create_pids2idxs(dataset):
"""Creates a mapping between pids and indexes of images for that pid.
Returns:
2D List with pids => idx
"""
pid2idxs = {}
for idx, data in enumerate(dataset.data):
pid = data['pid']
if pid not in pid2idxs:
pid2idxs[pid] = [idx]
... | c6ccd42a9a439ad9bed9d200991c4bc12f6a0ae0 | 61,952 |
def kmlCoords(coords):
"""Convert from a sequence of floats to a comma delimited string"""
return ','.join([str(x) for x in coords]) | d957539212d55c60989c80d40f710aff6d1ffc7e | 61,954 |
def get_spaceweather_imageurl(iu_address, iu_date, iu_filename, iu_extension, \
verbose):
"""Returns a complete image url string tailored to the spaceweather site by
concatenating the input image url (iu) strings that define the
address, the date folder, the filename root, and the filename extensio... | 8ba57b53f1af9cb516648fd6df13e2f44b0dd1bd | 61,956 |
def parseDate2solar(date):
"""parse date to solar date (datetime)
:return: year, month, day
"""
if type(date).__name__ == "LunarDate":
date = date.to_datetime()
year = date.year
month = date.month
day = date.day
return year, month, day | aa21db5c136322752fac6ead8cb948e7acdb0516 | 61,960 |
def fast_addition(a, b):
"""This function adds two arguments a,b and returns the result"""
return a + b | 763f0681c708c302e6d8f1d3e141204f97e73fd4 | 61,962 |
def transfer_turn(board):
"""Sets the turn to the opposite player"""
return -board | 74fb9f483b5408894b08cb7efda843a3e3915e1e | 61,964 |
def parse_s3_url(url):
"""
Parses a url with format s3://bucket/prefix into a bucket and prefix
"""
if not url.startswith("s3://"):
raise ValueError("The provided URL does not follow s3://{bucket_name}/{path}")
# Parse into bucket and prefix
bucket = ""
prefix = ""
for index... | 1f8724e00f5205c6747a1dc12db8237939af5830 | 61,965 |
def get_url(path, scheme="http"):
""" Return the full InfoQ URL """
return scheme + "://www.infoq.com" + path | 8e4010d3943514ea293c5ee9b12a68143694042f | 61,966 |
def _formulate_smt_constraints_fully_connected_layer(
z3_optimizer, nn_first_layer, smt_first_layer, top_k, gamma):
"""Formulates smt constraints using first layer activations.
Generates constraints for the top_k nodes in the first hidden layer by setting
the masked activation to be greater than that of the ... | da67ad56d43b0f0574add5333f98b4bf8686241f | 61,967 |
def bdev_ftl_delete(client, name):
"""Delete FTL bdev
Args:
name: name of the bdev
"""
params = {'name': name}
return client.call('bdev_ftl_delete', params) | 9ea5656354953f8b1589dcb13a39ff008129dbf6 | 61,971 |
def tree_as_host_list(current, path):
"""
Args:
current (Node): The root of the subtree.
path (str): path from the root to the current Node.
Returns:
str: The list representation of the hosts in current
"""
if len(current.children) == 0:
return path
p = str()
for i in current.children.values():
... | f2e58e7ef87c100f0a33586348f689cc2c17b686 | 61,974 |
import math
def SE_calc(item1, item2):
"""
Calculate standard error with binomial distribution.
:param item1: parameter
:type item1: float
:param item2: number of observations
:type item2: int
:return: standard error as float
"""
try:
return math.sqrt(
(item1 ... | fcbc06b1bff4bf607dfdff929cb1d67c919e2de9 | 61,978 |
def expand_dups(hdr_tuples):
"""
Given a list of header tuples, unpacks multiple null separated values
for the same header name.
"""
out_tuples = list()
for (n, v) in hdr_tuples:
for val in v.split('\x00'):
if len(val) > 0:
out_tuples.append((n, val))
retu... | 54823b34421a5d1dec693c5507b7a0f7c65b20e0 | 61,985 |
def parse_filename(filename, full_output=False):
"""
Return the basic stellar parameters from the filename.
"""
basename = filename.split("/")[-1]
teff = float(basename.split("t")[1].split("g")[0])
logg = float(basename.split("g")[1].split("k")[0])/10.
feh = float(basename[1:4].replace("p",... | bc88720155f40ce8049966e5db15bdf25fd6c52e | 61,997 |
def sw_archie(res, phi, Rw, a=1.0, m=2.0, n=2.0):
"""
Calculate water saturation using Archie method.
(a * Rw)
Sw = ( ----------- )^(1/n)
phi^m * res
Sw = sw_archie(res, phi, Rw, a, m, n)
Sw = water saturation
res = measured formation res... | c97add62cb41be146915c25a9a7832a628cbb416 | 61,998 |
import re
def extract_blog_content(content):
"""This function extracts blog post content using regex
Args:
content (request.content): String content returned from requests.get
Returns:
str: string content as per regex match
"""
content_pattern = re.compile(r'<div class="cms-rich... | 286a6a978b700342b3fe9905966c41aaacb1ac74 | 62,000 |
def add_colons(df, id_name='', col_types={}):
"""
Adds the colons to column names before neo4j import (presumably removed by `remove_colons` to make queryable).
User can also specify a name for the ':ID' column and data types for property columns.
:param df: DataFrame, the neo4j import data without co... | d7bca92e939c7ca109cd66841bb2a45d2fdbeac0 | 62,001 |
import math
def bound_longitude(lon, rad=False):
"""
Return a value between (-180, 180], handling the wrap-around
"""
if rad:
lon = lon * 180 / math.pi
# Keeps longitude in [0, 360) range
lon = lon % 360
lon[lon > 180] = lon[lon > 180] % 180 - 180
if rad:
lon = lon * ... | 11a18cf36b9a593a8fcc606fd51d3009895e9522 | 62,003 |
def get_all_under_item(item):
"""
Returns all the children of a specific QTreeWidgetItem
:param item: <QTreeWidgetItem>
:return: <list> QTreeWidgetItems
"""
items = []
for index in range(item.childCount()):
items.append(item.child(index))
items.extend(get_all_under_item(item... | 61b6abd2e22cb82ed5b8a3f94087b77beb85530c | 62,005 |
from typing import Union
from typing import NoReturn
from typing import Mapping
def validate_embed_fields(fields: dict) -> Union[bool, NoReturn]:
"""Raises a ValueError if any of the given embed fields is invalid."""
field_validators = ("name", "value", "inline")
required_fields = ("name", "value")
... | c6966ecde743bea7d975db108600729d93fece58 | 62,011 |
def parse_domain_label(domain_label):
""" Parse the list of comma-separated domains from the app label. """
return domain_label.replace(',', ' ').split() | 5273501ae1bea9517f5b9c0a620fdb78feb79112 | 62,013 |
def rankine_to_fahrenheit(temp):
"""
From Rankine (R) to Fahrenheit (ºF)
"""
return temp - 459.67 | 894d74541679979e4432e01a3f263e44725070a6 | 62,016 |
def _ch_disp_name(ch):
"""Convert channel names like 'proc_Plasmid' to 'Plasmid'"""
return '_'.join(ch.split('_')[1:]) | 208e315206fd9046b83d2c5841e581d1fc71ca58 | 62,021 |
def row_to_dict(row):
"""
Translate sql alchemy row to dict
Args:
row: SQL alchemy class
Returns:
data_dict(dict): data as dictionary
"""
if not row:
return {}
if hasattr(row, "__table__"):
return dict((col, getattr(row, col))
for col in row.__... | d5f13b7f582d97328f46960a02ce8007e8bfcaf6 | 62,024 |
import torch
def unnormalise(tensor: torch.Tensor):
""" Converts normalised CxHxW tensor to HxWxC numpy image. """
tensor = tensor.cpu().detach()
min, max = float(tensor.min()), float(tensor.max())
tensor = tensor.clamp_(min=min, max=max)
tensor = tensor.add_(-min).div_(max - min + 1e-5)
image... | 6a41fa9019027b515e7d0bc96815e460fecf5ae7 | 62,027 |
def _add_input_output(input_files=None, output_file=None, pipe=True):
""" Add input and output files to command in the form
'command input_files > output_file', 'command > output_file',
'command input_files |', 'command input_files', 'command |' or 'command'
depending on the given files and the value of... | 1904ea4f9ab6a99c557f296fdb0fe3a93f579dc3 | 62,028 |
import json
def prepare_update_record(record):
"""
Remove unecessary/forbidden attributes from record so it's possible to
reuse on the entity.update API call.
"""
json_loaded = json.loads(record)
not_allowed_keys = ['created']
for key in not_allowed_keys:
del json_loaded[key]
... | 47540650703f9b4190f7e07431c6469ed1237c55 | 62,030 |
def _decimal_to_binary(decimal):
"""Convert decimal to binary"""
return int("{0:b}".format(decimal)) | c92d4d0a8c6487f156f79e735b0fd4b30874f64d | 62,032 |
from typing import List
from typing import Counter
from typing import Optional
def get_most_frequent(tokens: List[str], token_counts: Counter) -> Optional[str]:
"""
Find most frequent token in a list of tokens.
Args:
tokens: a list of tokens
token_counts: a dictionary of token frequenci... | ad35e18a5e430c35a6279d234ce19f851f943ec9 | 62,037 |
from typing import List
import pkg_resources
def _get_all_backends() -> List[str]:
"""
Return the list of known backend names.
"""
return [
entry_point.name
for entry_point in pkg_resources.iter_entry_points(
group='ibis.backends', name=None
)
] | 9d19c19ff34203b4a3bf1df6c91eaa14ca484d58 | 62,039 |
def _short_tag(tag):
"""Helper method to remove any namespaces from the XML tag"""
return tag[tag.rfind('}')+1:len(tag)] | 27d9c8ca4a42ccc8ec168004a5b9fade5ed69a9f | 62,044 |
def get_url(route, base_url="{{base_Url}}"):
"""Adds base_url environment variable to url prefix."""
url = base_url + route
return url | 7627bb75be4319095a922dcce2022121ec559716 | 62,045 |
from datetime import datetime
def is_between_timespan(timespan:tuple) -> bool:
"""Returns if current time is between given timespans"""
return timespan[0] <= datetime.now() <= timespan[1] | ccbac35c37476987e0f9900c6a5aa466e9ea04d8 | 62,046 |
def _crop_image_to_square(image):
"""
Given a PIL.Image object, return a copy cropped to a square around the
center point with each side set to the size of the smaller dimension.
"""
width, height = image.size
if width != height:
side = width if width < height else height
left = ... | 26ddaa8a1fe2a3a87b278b58cd131b45433c2c81 | 62,052 |
def not_between(a, b):
"""Evaluates a not between b[0] and b[1]"""
if not isinstance(b, list):
raise TypeError('other value must be a list of length 2')
result = b[0] <= a <= b[1]
return False if result else True | effc8f05cace0fc3e0aaba8239a82a6985fe65d3 | 62,053 |
def get_origin(manifest):
"""Parse the coordinate of the origin in the manifest file
Args:
manifest: The manifest from which to parse the coordinates of the origin
Returns:
the parsed coordinates (or throw an exception if they could not be parsed)
"""
with open(manifest, "r") as save_f... | 2577ac3d34b739aad2a8aa0deb7cd774b8d85ca0 | 62,057 |
def mjpeg_info_cmp(x,y):
"""
Comparison function for sorting a list of (camera_name, camera_info) pairs.
"""
name_x = x[0]
name_y = y[0]
value_x = int(name_x.replace('camera_', ''))
value_y = int(name_y.replace('camera_', ''))
if value_x > value_y:
return 1
elif value_y > val... | 31d98998bd3ece11a591b841505d50e67af68182 | 62,060 |
import torch
def set_loss_weight(pivot_set,exp):
"""
The weight of the k-th auxiliary loss: gamma_k = \max(0.01, (\frac{L_k}{L_K})^2)
More details can be found in Section 3.2 in "The Shallow End: Empowering Shallower Deep-Convolutional Networks
through Auxiliary Outputs": https://arxiv.org/abs/1611.01... | 8998cf935ae12f6568598152155c7a6b6df99121 | 62,066 |
import unicodedata
def displayText (text):
""" Convert text into a string that is always renderable without combining,
control or invisible characters """
if text is None:
return text
if all (map (lambda x: unicodedata.combining (x) != 0, text)):
# add circle if combining
retur... | 412b646c55a8c498f217a516f207173c2356a3e9 | 62,069 |
def isGenericParamName(name):
"""Check if name is a generic parameter name."""
if name is None:
raise ValueError("parameter name is None")
return name.startswith('param') | 85595ed602db3588d6150a0380b47a9fe8f060e6 | 62,072 |
def parse_hal_binned_tags(hal_binned_tags):
"""Parses the tag information from the output of HAL
Parameters
----------
hal_binned_tags: output of HAL.get_outputs() (list of tuples)
Returns a nested dictionary:
[output_id][dimension] = list of (times, count) tuples
"""
parsed_tags =... | 347952ed53e0c575554293a333f30507101549e7 | 62,073 |
from typing import List
def multiplication_table(n: int) -> List[List[int]]:
"""
A completely unnecessary generation of a multiplication table, which is not needed to solve the problem.
:param n: the size of the table, ranging [1,n] x [1,n].
:return: the multiplication table, where the entry [i][j] = ... | 141e5a6649955785113091f9d66608498344f063 | 62,075 |
import inspect
from typing import OrderedDict
def get_args_kwargs(fct, n_optional):
"""
Extracts arguments and optional parameters of a function.
:param fct: function
:param n_optional: number of arguments to consider as
optional arguments and not parameters, this parameter skips
the ... | 45adbee36983f67486474a0f93730df63a19cf77 | 62,077 |
def quizn_to_index(quizn):
"""See: https://github.com/fielddaylab/jo_wilder/blob/master/src/scenes/quiz.js
For some reason there are 5 quizzes, but there is no quiz numbered 1.
Returns:
The correct quiz number for quizzes 2-5, or 0 for quiz 0.
"""
return quizn - 1 if quizn >= 2 else quizn | b57df8c103d3124872be02eb487772787cb8131e | 62,078 |
def day_in_sec(dy, ml=False):
"""
Convertion d'un nombre de jours en secondes ou milisecondes
:param int dy: nombre de jours
:param bool ml: en millisecondes si True sinon en secondes, dafault False
:return: (milli) secondes
"""
nb = int(dy)
nb = nb * 24 * 60 * 60
return nb * 1000 ... | 08394bc4a04e4a8ca10eb42b6dbb4f425ba44a41 | 62,085 |
def clean_chars(value, cleanchars):
""" Remove chars for cleaning
:param value: String to be cleaned
:param cleanchars: Characters to remove from value
:return value: Cleaned string
"""
for char in cleanchars:
value = value.replace(char, '')
return value | 480d921152f9bc3e6491b4a015d61f53932dd16c | 62,090 |
def makeNeighborLists(position, nRow, nCol):
"""
Build a neighbor list for each cell
This will create a list of all positions in a cell's Moore neighborhood.
Pos is the cell's position, nRow is the maximum width, nCol is the maximum height
"""
r, c = position
neighborList = [(r+a, c+... | 2e8f54f4727a9477bfee9cc8b6d113b0a79deeed | 62,092 |
def ceil4(x):
""" Find the closest greater or equal multiple of 4
Parameters
----------
x: int
The size
Returns
-------
x_ceil: int
The closest greater integer which is a multiple of 4.
"""
return (((x - 1) >> 2) + 1) << 2 | 452cfae5fc9ad92cab7c7e27c1ba1a8442fc5bd4 | 62,094 |
def findRxnName(rxnid, reactionsBiGG):
"""
Retreive (descriptive) name of reaction from BiGG-file.
Returns
-------
String with name (when found), otherwise empty.
"""
if rxnid in list(reactionsBiGG.index):
return(str(reactionsBiGG.loc[rxnid]['name']))
else:
return(str(''... | e21cd364013adb333332167522efb8a34f33f3cf | 62,096 |
def calculate_snr(rx_power, noise_power):
""" Function that calculates SNR in dB!
Args:
rx_power: (numpy array) received power in dB!
noise_power: noise power in dB!
Returns:
snr: (numpy array) Signal-to-Noise ratio in dB!
"""
snr = rx_power - noise_power # rx_power and no... | 0011e261ba7a2df9a9374657caa47040a76a209d | 62,101 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.