content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def build_extensions(available_extensions):
"""
Builds websocket extensions header from the given extension values.
Parameters
----------
available_extensions : `list` of `Any`
Each websocket extension should have the following `4` attributes / methods:
- `name`, type `str`. The... | dfdfaa0df96bace4b9f52eb5e45efdbdcca1f850 | 636,002 |
def _byte_pad(data, bound=4):
"""
GLTF wants chunks aligned with 4 byte boundaries.
This function will add padding to the end of a
chunk of bytes so that it aligns with the passed
boundary size.
Parameters
--------------
data : bytes
Data to be padded
bound : int
Length ... | e396b24078dcd487df2b9aea4a54669b90e8e624 | 636,003 |
def _get_num_reads(ngs_alignment):
""" Returns the number of reads in the template of an NCBI/NGS alignment
Args:
ngs_alignment (ngs.Alignment): aligned read
Returns:
int: the number of reads in the template
"""
if ngs_alignment.hasMate():
return(2)
else:
retur... | 93a3e9076a758c0e0943b8d6b9426e9de463b52f | 636,015 |
def group(container, multiple=True):
"""
Splits a container into a list of lists of equal, adjacent elements.
>>> from sympy.utilities.iterables import group
>>> group([1, 1, 1, 2, 2, 3])
[[1, 1, 1], [2, 2], [3]]
>>> group([1, 1, 1, 2, 2, 3], multiple=False)
[(1, 3), (2, 2), (3, 1)]
... | 27977e2e3096942121691fc2f7a0ca11f7541730 | 636,018 |
def Count(Spaces):
"""
returns tuples *(space, count)* where *count* states how often *space* occurs in *Spaces*.
"""
dummy = [tuple(sorted(x.items())) for x in Spaces]
unique = set(dummy)
result = []
for x in unique:
result.append((dict(x), dummy.count(x)))
return resu... | 2412db01a117009ef3b984e2cd8b29ba3823135e | 636,020 |
from typing import Tuple
def rgba_to_html_string(rgba: Tuple[int, int, int, float]) -> str:
"""Create an HTML code from an RGBA tuple
Parameters
----------
rgba : Tuple[int, int, int, float] | Tuple[int, int, int]
RGB values and an optional alpha value between 0 and 1.
Returns
------... | 94f16f7c5d9694422a676cc179c9406cd016453b | 636,021 |
def augment_data(train_ds, data_augmentation):
"""
:param train_ds: raw train_ds
:param data_augmentation: data augmentation sequence
:return: an augmented training set
"""
print("Augmenting the train_ds")
augmented_train_ds = train_ds.map(lambda x, y: (data_augmentation(x), y))
# augmen... | 99330ac50babd57ef06d665d18a95bdbcba20485 | 636,023 |
import aiohttp
async def get_tg_dm_player_json():
"""
Helper function for pulling the top 10,000 AoE2 players' info.
"""
async with aiohttp.ClientSession() as session2:
async with session2.get("https://aoe2.net/api/leaderboard?game=aoe2de&leaderboard_id=1&start=1&count=10000") as r:
... | 75c59e34b5dc4d03f36b3e32ceb5decde09c6bf3 | 636,024 |
def copy_of(board):
"""
Returns a copy of a board
"""
copy = []
for row_num in range(10):
row = []
for col_num in range(10):
row.append(board[row_num][col_num])
copy.append(row)
return copy | dc4f383455165f7b2cc9f7d7ec900485d4cf539e | 636,028 |
def average_bmi(df):
""" Returns average BMI, rounded to to d.p. """
return round(df.bmi.mean(), 2) | 529771e226de6de1f58572a62054863a678ebfc4 | 636,035 |
def get_mesh_cell_array(mesh, array_name):
"""Retrieve a cell array from the mesh."""
cell_data = mesh.GetCellData()
return cell_data.GetArray(array_name) | d58ff0669d28011095bc448a44db9145aa12f166 | 636,038 |
import json
def get_config_from_json(json_file):
"""
Get the config from a json file
:param json_file:
:return: config(dictionary)
"""
# parse the configurations from the config json file provided
with open(json_file, 'r') as config_file:
config_dict = json.load(config_file)
return config_dict | 1b400d0c6b8939ceadb729171a3bb2132a872f5c | 636,043 |
def count_orphan_resource_providers(db):
"""Count all orphan resource providers in the nova_api database."""
sql = '''\
SELECT COUNT(*)
FROM nova_api.resource_providers rp JOIN nova.compute_nodes cn
ON cn.hypervisor_hostname = rp.name
WHERE cn.deleted = 0
AND rp.uuid != cn.uuid
... | 18875ee9f6afd788198f9044397cec8a6383f05d | 636,046 |
def traverse_map(input_map, right=3, down=1):
"""Travel down the input map by heading right and down a fixed amount each
iteration.
The map consists of clear ground '.', and trees '#'.
The map repeats to the right infinitely.
Get the number of trees that would be encountered travelling from the top
... | 9844c795581e285f26e81258f19381efb0a705ba | 636,047 |
def _date_to_string(d):
"""Make string of date in Nexus format
Args:
d (datetime): Date object
Returns:
String with date
"""
id = d.day
im = d.month
iy = d.year
if im < 10:
st = '0' + str(im)
else:
st = str(im)
st = st + r'/'
if id < 10:
... | 3deb73805f5123f7b7c1cb92bde1169f573f6fae | 636,048 |
def _quoted(arg):
"""Check if arguments to framework functions are wrapped in quotes.
Args:
arg (str): The target argument
Returns:
bool: True if `arg` is quoted
"""
return arg.startswith("\"") and arg.endswith("\"") | 117d8bbd1e90a6fdaba8a22bcb62643cc98a7dfe | 636,051 |
def cnmr_match_tag(text):
"""Detect Carbon NMR data from splitted spectral sample text
param text:splitted spectral sample text
return:string related to Carbon NMR data
"""
cnmr_data = []
for data_block in text:
cnmr_patterns = ["13C NMR", "13C{1H}"]
for pattern in cnmr_patterns:... | 600b411e74e49ca083d7ced069a1e5c77bbb0288 | 636,053 |
def _bool(raw_bool):
""" Parse WPS boolean string."""
return raw_bool == "true" | 52ea61e35844395f54fae0757c2e27f28fedb76c | 636,054 |
import re
def search_last_letter(input_string):
"""
Returns the last letter in a string
:param input_string: str, string to search for a letter
:return: str, last letter in the string
"""
match = re.findall('[_a-zA-Z]+', input_string)
if match:
return match[-1][-1] | d8b1566ed5c0c9777a90664c47d1fd379838bb0d | 636,056 |
def img2rgb(img):
"""
Convert the image into rgb mode for displaying
:param img: input img
:return: output img
"""
img_rgb = (img / 255)[:, :, [2, 1, 0]]
return img_rgb | 80c231e4e0d395ed6b5f90d8a9e39b81d0e2c87b | 636,058 |
def get_bbox_from_shapely(shapely_object):
"""
Accepts shapely box/poly object and returns its bounding box in coco and voc formats
"""
minx, miny, maxx, maxy = shapely_object.bounds
width = maxx - minx
height = maxy - miny
coco_bbox = [minx, miny, width, height]
coco_bbox = [round(point... | 18ba6f37de016817c8218a042b3dc1248ab64b35 | 636,059 |
def pb_config(pb2):
"""Returns an instance of config of *_pb2 package"""
return pb2.PrefixConfig() | 72fa5d45ca3b77fa538c9491bcb77a4a02904ee8 | 636,062 |
def _remove_proper_feature(human_readable: str) -> str:
"""Removes proper feature from human-readable analysis."""
human_readable = human_readable.replace("+[Proper=False]", "")
human_readable = human_readable.replace("+[Proper=True]", "")
return human_readable | 37a07a16a022e380c9f7cdedf8b1d9fb88d25f0c | 636,064 |
def get_data(string: str) -> list[list[int]]:
"""Take char string of numbers and convert to integer list of lists."""
new_list = list(string.split("\n"))
final_list = []
for i in new_list:
lst = list(i.split(" "))
ints = []
for j in lst:
ints.append(int(j))
fi... | d48c78f1a3983e714ffdb92e09a51bbd7b640ef3 | 636,065 |
def flatten_lists(list_of_lists):
""" This function flattens a list of lists into a single list.
Args:
list_of_lists (list): the list to flatten
Returns:
list: the flattened list
"""
return [item for sublist in list_of_lists for item in sublist] | d87a55be373f47081e2d60fcfaf75021e579209c | 636,067 |
def cable_type(request):
"""Dualtor cable type."""
return request.param | f706c51b2003fc73a76c91c6ccd261ae52498a76 | 636,071 |
from typing import List
from typing import Tuple
from pathlib import Path
def parse_benchfile(f) -> List[Tuple[Path, Path]]:
"""Parse the given file into benchmark cases.
On each line in the file, there should be a path to a map,
a colon and a space-separated list of scenarios which should
be benchma... | 5b673c663e19093c7cf9d6b3fb93f8fd5d247087 | 636,073 |
def is_in_list(list_one, list_two):
"""Check if any element of list_one is in list_two."""
for element in list_one:
if element in list_two:
return True
return False | 5cb3569b552557909c58e9892f29261d60a20271 | 636,074 |
def SortClassAdsByElement(classads, element_name):
"""
Sort the classads (or any dictionary really) by an attribute
@param classads: list of classad objects
@param element_name: string of element name
"""
sorted_ads = sorted(classads, key=lambda ad: int(ad[element_name]))
return sorted_... | dcf43f0fb0f4839752664f0e0e2fcd368734395a | 636,080 |
def get_process_command(cmd_args):
"""Get command-line text for task process."""
# Join arguments into command string, escaping any with spaces.
cmd = ''
for arg_index, arg in enumerate(cmd_args):
if arg_index > 0:
cmd += ' '
if ' ' in arg:
cmd += '"' + arg + '"'
else:
cmd += arg
... | a2fb1041155145c1c80057bbb404852593e94cb9 | 636,081 |
def correct_german_spellings(spelling):
"""Correcting the exceptions in German spellings.
Aeseses -> Aseses
Eeseses -> Eseses
Heseses -> Beses
Aeses -> Ases
Eeses -> Eses
Heses -> Bes
Hes -> B
Aes -> As
Ees -> Es
----------
H♭♭♭ -> B𝄫
H𝄫 -> B♭
H♭ -> B
"""
... | 60142a64965615a45f6ea654aeeb57658cbe1067 | 636,083 |
def lambda_handler(event, context):
"""Lambda function to generate the Map input state for LQP Run Base
Parameters
----------
event: dict, required
Input event to the Lambda function
context: object, required
Lambda Context runtime methods and attributes
Returns
------
... | 7c17c28432ed87123dbedbae22efb7070324a7e3 | 636,084 |
def text_block(text, margin=0):
"""
Pad block of text with whitespace to form a regular block, optionally
adding a margin.
"""
# add vertical margin
vertical_margin = margin // 2
text = "{}{}{}".format(
"\n" * vertical_margin,
text,
"\n" * vertical_margin
)
... | b045b82bf3d3b2c215d862ef0894b30d72b73d29 | 636,089 |
import shlex
def convert_arg_line_to_args(arg_line):
"""argparse helper for splitting input from config
Allows comment lines in configfiles and allows both argument and
value on the same line
"""
return shlex.split(arg_line, comments=True) | e0391ed18c2849d5201c36db7264e7c73e98c27d | 636,090 |
import torch
def load_ckpt(modules_optims, ckpt_file, load_to_cpu=True, verbose=True):
"""
load state_dict of module & optimizer from file
Args:
modules_optims: A two-element list which contains module and optimizer
ckpt_file: the check point file
load_to_cpu: Boolean, whether to t... | 29a3131e41236d19c556c955f7f319c19747b7d8 | 636,092 |
def slice_detections(all_ground_truth_bboxes, slice_mode):
""" Find indices of detections of interest and modify the ground truth detections based on
slice mode.
Params:
all_ground_truth_boxes (List of xml.etree.ElementTree.Element): List of all ground
truth bounding boxe... | f3da6f6a5c84c973c92add16dd65afb4c0763f18 | 636,093 |
def get_attr_value(attrs, key):
"""Read attr value from terncy attributes."""
for att in attrs:
if "attr" in att and att["attr"] == key:
return att["value"]
return None | 73ec422f8a0a48890fa9faf5e0f8d8044dd156f2 | 636,094 |
def ec2_entities(job_name):
"""
Returns the name of basic ec2_entities.
* Keypair name
* Security group for slaves
* Security group for master
@param job_name: User given name of the Job.
@type job_name: string
"""
keypair_name = "multistack-" + job_name
sec_slave = "multistack... | 95ebdc4bd4a3ffb875df77e89dac0b762e188e8c | 636,098 |
def contar_caracteres_repetidos(cadena: str) -> int:
""" Caracteres Repetidos
Parámetros:
cadena (str): La cadena que se debe revisar.
Retorno:
int: La cantidad de caracteres diferentes que aparecen repetidos en la cadena.
"""
caracteres_cadena = {}
diferentes_repetidos = 0
for c... | e107df83fc5f6525f3aba76c920c38669318ce3f | 636,099 |
import math
def resize_bytes(input_bytes: bytes, length: int):
"""Takes in a byte string and an integer. Outputs the byte string repeated till it is of length integer"""
multiplier = math.ceil(length / len(input_bytes))
raw_output = input_bytes * multiplier
return raw_output[:length] | 8a056dc8b7fed2054049ab3b7d4671a62a7a3939 | 636,101 |
def lmap(v, x, y) -> float:
"""Linear map of value v with range x to desired range y."""
return y[0] + (v - x[0]) * (y[1] - y[0]) / (x[1] - x[0]) | 0e8b272fab0e4f1397c2e21631dd7b88b6eb8d31 | 636,103 |
def get_folder_id(path, c):
"""Query the folder id of the directory."""
sql = '''
SELECT folder_id
FROM folders
WHERE path = ?
'''
c.execute(sql, (path, ))
return c.fetchone()[0] | 4f958498007e618ca23f0cbe386f1ed1d4a2e7bd | 636,104 |
def node_restore_all(self, flag=0) :
"""
Restores a all device from the configuration in ISY
args :
flag 0 or 1
Flag :
0 = All shall be restored from the configuration files in ISY
1 = Does not regenerate groups/scenes - good for testing
... | ef7f63ee26b9e08e23e3ac26971729e008322858 | 636,108 |
import torch
def FloattoRGB(images):
"""Converts a 0-1 float image with an alpha channel into RGB"""
if len(images.size()) < 4:
images = torch.unsqueeze(images, 0)
return torch.clip(images[:,:3,:,:] * images[:,3,:,:] * 255 + (1-images[:,3,:,:])*255, 0, 255).type(torch.uint8) | 9ae3e06d6168c8100fda6f35f1074fbcd53a1794 | 636,109 |
def _uuencode_int6(n):
"""uuencode a 6-bit element into a char"""
if n == 0:
return '`'
else:
return chr(0x20 + n) | 2b2dd55fb3440e3ec56c4cdb6650c32380e31f4f | 636,115 |
import six
def _MergeDicts(a, b):
"""Shallow merge two dicts.
If both dicts have values for a same key and both are lists, it concats them.
Args:
a: a dict object. This will be updated with merged items.
b: a dict object.
Returns:
a merged dict object.
"""
for key, value in six.iteritems(b)... | 4bf7a5ba20806003e7cd92fc6f9aa415301d8bc6 | 636,116 |
def _time_hms(datetime_obj):
"""
Return datetime_obj formatted as mm/dd HH:MM:SS.
"""
return '{time:%m/%d %H:%M:%S}'.format(time=datetime_obj) | a08bafac2c9d40ef2b08d5eba5475972cc12adc1 | 636,117 |
def _get_set_name(test_data):
"""Get the set_name from test_data
Return the value of 'set_name' key if present in the data
If set_name it is not present in data, return the value of the first key.
If there's no data, leave set_name as ''
"""
set_name = ''
if 'set_name' in test_data:
... | 8b02fe1c6bb53afba312fe228966b58bc083d63a | 636,121 |
def _phi(speciation_initiation_rate,
speciation_completion_rate,
incipient_species_extinction_rate):
"""
Returns value of $\varphi$, as given in eq. 6 in Etienne et al.
(2014).
Parameters
----------
speciation_initiation_rate : float
The birth rate, b (the incipient speci... | dcd56555661f565d5a6648734125fb3f2e997aad | 636,122 |
def create_cmd(parts):
"""Join together a command line represented as list"""
sane_parts = []
for part in parts:
if not isinstance(part, str):
# note: python subprocess module raises a TypeError instead
# of converting everything to string
part = str(part)
... | c7fe6e58d32c96fe4d70a3cc1290638170351b88 | 636,123 |
def trim_pv(pv):
"""
Strip anything after +git from the PV
"""
return "".join(pv.partition("+git")[:2]) | 8061a761de8c18a1465c6c9274de43ce99a2ad15 | 636,127 |
def APs2mAP(aps):
"""
Take a mean of APs over all classes to compute mAP
"""
num_classes = 0.
sum_ap = 0.
for _, v in aps.items():
sum_ap += v
num_classes += 1
if num_classes == 0:
return 0
return sum_ap/num_classes | 807df1ff7b64824855cec16cc8ce39b55d03ca17 | 636,131 |
def bounding_box(points):
"""
The function calculates bounding_box from the coordinates. XY - Min , XY - Max
:param points: coordinates list
:return: List of bounding box.
"""
x_coordinates, y_coordinates = zip(*points)
return [(min(x_coordinates), min(y_coordinates)), (max(x_coordinates), m... | 1bc25ef347284cecf167b9067e9d20fd9ec273ad | 636,143 |
def image_data_to_dict(image_data):
"""
Converts a desktop notification image data array into a dict.
"""
result = {}
result['width'] = image_data[0]
result['height'] = image_data[1]
result['rowstride'] = image_data[2]
result['has_alpha'] = image_data[3]
result['bits_per_sample'] = image_data[4]
result['chan... | 26363d8cb183133c975cc9d2612d0731a5a86e3b | 636,144 |
import re
import pathlib
def get_library_folders(steam_path, library_index_path):
"""
Reads the library index file `libraryfolders.vdf` to get a list of all
Steam library locations on your system.
Because of the lazy way in which the RegEx is written, it only supports
up to 100 Steam librarie... | c53004126426c5ab37c211c365f0d1ce40a3a29d | 636,146 |
def filter_str(check_str):
"""
过滤无用字符
:param str check_str:待过滤的字符串
:return str temp:过滤后的字符串
"""
temp = ''
for i in check_str:
if i != '\n' and i != '\x00':
temp = temp + i
return temp | 2787d1455beb491b85ce3db17232503565b76693 | 636,149 |
import torch
def cosine_cont(repr_context, relevancy, norm=False):
"""
cosine siminlarity betwen context and relevancy
Args:
repr_context - [batch_size, other_len, context_lstm_dim]
relevancy - [batch_size, this_len, other_len]
Return:
size - [batch_size, this_len, context_lstm... | 990b1fa659ce7d00b951b4bf1a6e389c7333adcc | 636,150 |
import requests
def obtener_pais(codigo: str) -> str:
"""Obtiene el nombre del país a partir del código.
:param codigo: Código del país.
:codigo type: str
:return: Nombre del país.
:rtype: str
"""
url = f"https://restcountries.com/v3/alpha/{codigo}"
response = requests.get(url)
... | 399e08b7bfd9546c6a4d122e9bca451fe6f00840 | 636,151 |
def merge_proteins(proteins):
""" Merge all isozymes that catalyze a given reaction.
Automatically removes all isozymes with missing score.
Args:
proteins (pandas.Series): list of proteins
Returns:
str: boolean rule
"""
proteins = set(proteins.dropna())
if not proteins:
... | b22b798f9aa66549181dea6020bbaeff5d03888b | 636,152 |
def extract_stats_from_uartlog(uartlogpath):
""" read a uartlog and get sim perf results """
elapsed_time = -1
sim_speed = -1
cycles = -1
with open(uartlogpath, 'r') as f:
readlines = f.readlines()
for line in readlines:
if "time elapsed:" in line and "simulation speed" in line:
... | c37dd9b850ed6045a5c2eb4628a3341301a1b23b | 636,153 |
def c(x, y):
"""Returns 1 if x < y and -1 if x > y."""
return (y - x) // abs(y - x) | f8cb7afafefaf9ba4bd4813f5c5f730a08734aa3 | 636,156 |
def partition_node(node):
"""Split a host:port string into (host, int(port)) pair."""
host = node
port = 27017
idx = node.rfind(':')
if idx != -1:
host, port = node[:idx], int(node[idx + 1:])
if host.startswith('['):
host = host[1:-1]
return host, port | 6730f44dfbecf819fa394f165efdf2e1faf51bc8 | 636,166 |
def indented(contentstring, indent=-1):
"""
Return indented content.
indent >= 0 prefixes content with newline + 2 * indent spaces.
indent < 0 returns content unchanged
Docstrings:
>>> indented("foo bar", -1)
'foo bar'
>>> indented("foo bar", 0)
'\\nfoo bar'
>>> indented("foo ... | 7f772df69457355711f4743651f93553ebed8b1e | 636,169 |
def count_lines(filename):
"""
Count the number of lines in filename.
:param str filename: Path to the filename.
:return: The number of lines in the file.
:rtype: int
"""
lines = 0
buf_size = 1024 * 1024
with open(filename, 'rb') as fd:
read_f = fd.read # loop optimization... | b5555fb94777682503c94eacf14a7a216b94448b | 636,173 |
def bpm_from_beatspace(btsp):
"""
Convert a beatspace to a BPM
Provided as convenience; the operation is the same as bpm_to_beatspace.
:param btsp: beatspace to convert
:return: beatspace converted to BPM
"""
return 60000.0 / btsp | 4be4397a2a63b7cade8aa9b9e9843a811c41dda0 | 636,175 |
def is_list(a):
"""Check if argument is a list"""
return isinstance(a, list) | 3f0a7ee7f5ff02fa2949938e7c0269bff069e472 | 636,177 |
def conflict_annotation(expt, loc):
"""
Returns conflict rate of an experiment as a string percentage. Only does
this if the experiment is EPaxos, as MPaxos has no conflict rate.
"""
if expt.is_epaxos():
conflict_rate = '{}%'.format(round(expt.conflict_rate(loc)*100, 1))
return confl... | 620939565f5bac3bb278c74cb085d85faba2bdbc | 636,180 |
def unpack3(var, struct_var, buff):
"""
Create an unpack call on the ``struct.Struct`` object with the name
``struct_var``.
:param var: variable the stores the result of unpack call, ``str``
:param str struct_var: name of the struct variable used to unpack ``buff``
:param buff: buffer that the ... | 64af84415b6ea6a97bab0797ad5e44923d457fcb | 636,181 |
import torch
def mulaw_encode(x, quantization_channels, scale_to_int=True):
"""Adapted from torchaudio
https://pytorch.org/audio/functional.html mu_law_encoding
Args:
x (Tensor): Input tensor, float-valued waveforms in (-1, 1)
quantization_channels (int): Number of channels
scale_to_i... | 76677853d2aea08999d977b7105e25093f6b9fa5 | 636,184 |
import torch
def bbox_intersection(bboxes1, bboxes2, aligned=False):
"""
Compute the intersections among bounding boxes.
Args:
bboxes1 (:obj:`nn.Tensor[N, 4]`): Bounding boxes to be computed. They
are expected to be in ``(x1, y1, x2, y2)`` format.
bboxes2 (:obj:`nn.Tensor[M, 4... | f7473e948a95093ee30881474737ba164e49280c | 636,186 |
from pathlib import Path
def _get_file_contents(file_path: Path) -> str:
"""
Helper function to get README contents
"""
with open(file_path, encoding="utf-8") as file:
return file.read() | b62bafc433ad019fa9f103afef84a3ca4096b421 | 636,191 |
def _format_name(m_name: str, sep: str = '_') -> str:
"""Formats name for url
Parameters
----------
m_name : str
Name of movie
sep : str
Word seperator to use '-' or '_' typically
Returns
-------
str
movie name formatted for url insertion
"""
# enfo... | c1d2d5b24d27fa3828d16a85832cd8bbab4efb39 | 636,193 |
def get_tricks_taken(active_players):
"""Determines how many tricks currently have been taken"""
tricks_taken = 0
for player in active_players:
tricks_taken += player.curr_round_tricks
return tricks_taken | 0a681d520a05aa7cbeccf3fd7a764381217165cb | 636,198 |
from typing import Optional
def get_qname(uri: Optional[str], name: str) -> str:
"""
Returns an expanded QName from URI and local part. If any argument has boolean value
`False` or if the name is already an expanded QName, returns the *name* argument.
:param uri: namespace URI
:param name: local ... | 6c9e0cf3dff8d78f5ada5aa35135314cbfb41ad5 | 636,202 |
def arrange_array_size(batch_size: int, array_size: tuple):
"""
Decide array size given batch size and array size [batch_size, height, width, channel].
:param batch_size: batch size
:param array_size: array (img) size
:return: final array size
"""
output = list(array_size)
output.insert(... | 8290aca4e72c742dc26b2b09c0cc33dd5a67c52b | 636,204 |
def bam_is_processed_by_program(alignments, program='bamtagmultiome'):
"""Check if bam file has been processed by the supplied program
This function checks if there is an entry available in the 'PG'
block in header of the bam file where PN matches the program supplied.
Args:
alignments(pysam.A... | 41b22392992728caa58740c51178dbdbbfb77247 | 636,205 |
def convert_define_to_arg(input_define):
"""
Convert from a #define to a command line arg.
Parameters
----------
input_define : str
String in the format of "#define variable value".
Returns
-------
output_str : str
String in the format of "-Dvariable=value".
"""
... | dd2085ae6ede8dd7df7edad09404ab1e3ee77da5 | 636,206 |
def get_subclasses(*args):
"""Gets the subclasses of the parameters.
Parameters
----------
*args : :class:`type`
The types to get the subclasses of.
Returns
-------
:class:`set`
The subclasses of ``*args``.
"""
ret = set()
for arg in args:
tmp = set(ar... | 9361c72656a1fb8c872d4aadfbe8483891573717 | 636,208 |
def field_to_ysv_column(field: Field) -> list: # type: ignore
"""Convert a Field instance to ysv column definition."""
return [
{'input': field.field}
] | d7d73da9cc5bd1fa9af8d2cd7728c9a67454dd3a | 636,209 |
def grab_cite_data(template, supported_templates):
"""Check for supported templates and extract citation data"""
template_name = str(template.name).lower().strip().capitalize()
if template_name in supported_templates:
data = {
str(para.name).lower().strip(): str(para.value)
... | 0b5a6b7caeeff41d4f3b9a6ddf54883146c12b8f | 636,210 |
def with_self(method, network, args, kwargs):
"""Wraps a method with ``with network:``.
This makes it easy to add methods to a network that create new
Nengo objects. Instead of writing ``with self`` at the top of the method
and indenting everything over, you can instead use this decorator.
Example... | 1433508ccc4290288d508fd7d7d82a9ca2f5620a | 636,211 |
def select_bucket_region(
custom_bucket, hook_region, cfngin_bucket_region, provider_region
):
"""Return the appropriate region to use when uploading functions.
Select the appropriate region for the bucket where lambdas are uploaded in.
Args:
custom_bucket (Optional[str]): The custom bucket na... | 40d77327dfd69a9363ef29c4f7c50c04a4c0cfee | 636,212 |
from typing import Iterable
from typing import List
def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable) -> List[str]:
"""
Basic tab completion function that matches against a list of strings without considering line contents
or cursor position. The args required by ... | d27052d1fc26095215f9f153a5a789d84c9e66d2 | 636,213 |
def get_subject_name_from_csv(full_subject_name):
"""This function gets subject name from csv
Args:
full_subject_name (str): Full subject name with format XXX_YYY_ZZZ
Return:
subject_name (str): Subject name
"""
full_subject_name_list = full_subject_name.split("_", 3)
subject_n... | 8a63dd724c840e23dc008b1ac416f61721876417 | 636,216 |
import hashlib
def hash_string(string, salt=None):
"""Get MD5 hash from a string.
Parameters
----------
string : str
Some string.
salt : str, False or None
Optional salt added to the string for additional obfuscation.
"""
if salt is not None:
string += salt
ret... | 4d3768aa56a97289d35878aa8ac32762f2efe481 | 636,217 |
def generate_connection_string(account_name: str,
account_key: str,
protocol: str = 'https') -> str:
"""Generates the connection string for Microsoft Azure."""
connection_string = (f'DefaultEndpointsProtocol={protocol};'
f'AccountN... | 58479d78cfb6aec42bb5f22bec14ad2dedde6448 | 636,219 |
from typing import OrderedDict
def parse_metadata(text):
"""parse yaml metadata on raster layers
Parameters
----------
text: str
text in yaml format
Returns
-------
OrderedDict:
layer name: raster attribute number
"""
text = text.rstrip()
metadata ... | b3e7e85b26451dd584f04c1e638b03f4b812b9a1 | 636,221 |
import io
import zipfile
def zip_dict(data, **kwargs):
"""
Zips a dictionary ``{ str: bytes }``.
@param data dictionary
@param kwargs see :epkg:`*py:zipfile:ZipFile`
@return bytes
"""
if not isinstance(data, dict):
raise TypeError("data must b... | b344c169c19da3cebeb97768f0f880068d7dd947 | 636,222 |
def invalid_br_vsby(v):
"""Checks if visibility is inconsistent with BR"""
return not 0.6 < v < 6.1 | 8bf770d9a4ca6d1c1c95ab1c04e69464d91fcd10 | 636,223 |
def _read_code(message):
"""
Read the verification code from given email message
Inputs
:param message: <str> verification message sent
Outputs
:returns: <str> verification code that was sent
"""
# print("Message Recieved: '%s'" % message)
code = message.content.split("... | dd8b323bf62e5be80af16c626bed3409149ca550 | 636,224 |
def system_address(accounts):
"""Address pretending to be the system address."""
return accounts[0] | 933a6bd9de823f968ddd820fc5be49f3b326879b | 636,225 |
def add_dummy_multiver(post, pkg_dir, config):
"""Add a dummy multiver=False value."""
return {'multiver': False} | abb8ac274c97e1d73b675b5736ba957914566d61 | 636,228 |
def ParsingAddress(raw_location_list):
"""
A supporting function that parses the raw location info from Yelp Fusion API to make it more readable.
Parameters
----------
raw_location_list : pandas.core.series.Series
Required. A pd.Series of dictionaries containing address information in the JSO... | 88cf27ed13b1bc9ad4b171827b7263e1d06e8067 | 636,230 |
def get_port_numbers(ports):
"""
Get all port number from response and make comma-separated string
:param ports: Port portion from response.
:return: Comma-separated port numbers.
"""
return ', '.join([str(port['number']) for port in ports]) | 3ebd1c2ac324c83f061b3306832941b845404c41 | 636,231 |
def square2(value):
""" Return the square of a value"""
new_value = value ** 2
return new_value | ca170c3063b249fe3fb9983a1ff171c6174141c6 | 636,233 |
import pickle
def restore_model(path_to_ckpt):
"""
Loads model from a ckpt file.
"""
with open(path_to_ckpt, 'rb') as fp:
data = pickle.load(fp)
return data['model'] | ff66ed5caf2d296fae17abe38b14bf59c1c72698 | 636,237 |
def cast_element_ids_to_s(hash_element_ids, elements):
"""
Cast a hash of element ids to a string of element ids.
:param hash_element_ids: node/relation/way ids
:type hash_element_ids: hash
:param elements: OSM element to search
:type elements: array
:returns: a string of node/relation/wa... | 48fb92aa479dd8e2ae641744cc52adfbaa249caa | 636,238 |
def remove_colons(hexstr):
"""Removes colons from a string"""
return ''.join(hexstr.split(':')) | a4e870539f9c1a3cb86d4d92ff2e367f92a7125c | 636,239 |
import copy
def deep_merge_dict(dict_x, dict_y, path=None, local_overwrite=True,
merge_only_exist=False, raise_exception=True):
""" Recursively merges dict_y into dict_x.
Args:
dict_x: A dict.
dict_y: A dict.
path:
local_overwrite: Whether to overwrite the ... | 71dc0d75291cc8b83794b995f2cfb4d4d380f0a7 | 636,240 |
def datahash(*arrays):
"""Hash the data buffers of some arrays."""
hashstr = ''
for arr in arrays:
w = arr.flags.writeable
arr.flags.writeable = False
hashstr += '[{}{}]'.format(hash(bytes(arr)), arr.shape)
arr.flags.writeable = w
return hash(hashstr) | 8190ba810365ac7e201a1be5542fea95785f4499 | 636,246 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.