content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def H_to_Rt(H):
"""Converts 4x4 homogeneous transformation matrix into
3x3 rotation matrix and 3x1 translation vector."""
return H[0:3, 0:3], H[0:3, 3] | 06323455de3c837eff9164b82ec7d74b729e705f | 658,146 |
def comparePoEVREQ(po1, po2):
"""
Compare two Package or PackageEVR objects for equality.
"""
(e1, v1, r1) = (po1.epoch, po1.version, po1.release)
(e2, v2, r2) = (po2.epoch, po2.version, po2.release)
if r1 != r2: return False
if v1 != v2: return False
if e1 != e2: return False
return... | 28acb829c88ae715198d06619c215e38e4ac1ef7 | 658,147 |
def _FindRuleTriggerFiles(rule, sources):
"""Find the list of files which a particular rule applies to.
Arguments:
rule: the rule in question
sources: the set of all known source files for this project
Returns:
The list of sources that trigger a particular rule.
"""
rule_ext = rule['extension']
... | f408ce191d64c8e03d724e95a41eed4fb83d9791 | 658,148 |
import yaml
def load_yaml(filename):
"""
Load YAML data from a file
"""
with open(filename) as f:
# yaml.BaseLoader leaves everything as a string,
# so doesn't convert "no" to False
data = yaml.load(f, Loader=yaml.BaseLoader)
return data | 47bec93ca134df2b6d9ee25d3695ab6c111fb784 | 658,149 |
def optimalAlgorithm(memory, processQueue):
"""
This algorithm is the best way to manage memory. But is impossible to implement in real life, because there is no
way to know what process will be in next.
:param memory: memory obj, create previously.
:param processQueue: list with processes to be ex... | f8943983a7fdfb89379144b8919666686170a9ce | 658,150 |
from datetime import datetime
def periode(tahun: int) -> tuple:
"""
input tahun
:param tahun:
:return:
tuple 1 dengan 2 element range tanggal 'start gasal', 'end gasal'
tuple 2 dengan 2 element range tanggal 'start genap', 'end genap'
"""
tahun_ini = tahun
tahun_lalu = tahun_ini - ... | 8780667f286de0b3ae4621663110b68522bc8c98 | 658,151 |
def string(slot):
"""Slot manipulation library
This function prints a slot into a human readable string and returns it.
:param slot: The slot to be print
:return: A human readable string
"""
return '(' + slot[0].isoformat() + ', ' + slot[1].isoformat() + ')' | 456f1cf3511ca85fbc2087001968db968787fa8e | 658,152 |
def aggregate_sart(data, sub_num):
"""
Aggregate data from the SART task.
Calculates various summary statistics for the SART task for a given subject.
Parameters
----------
data : dataframe
Pandas dataframe containing a single subjects trial data for the task.
sub_num : str
... | 6e1185942b503718e9dcae0bcb8547c9d4175eab | 658,153 |
def stat_to_string(name, value, nice_names):
"""
Method that converts a metric object into a string for displaying on a plot
Args:
name: (str), long name of a stat metric or quantity
value: (float), value of the metric or quantity
Return:
(str), a string of the metric name, ... | aff5fc209904fd35a11b8baed6de0972b61f0300 | 658,155 |
def op_ifthenelse(x):
"""Returns branches depending on whether the first element of a vector is truthy."""
if isinstance(x, list) and len(x) == 3:
return x[1] if x[0] else x[2]
raise ArithmeticError("`ifthenelse` is only supported for 3-dimensional vectors") | 36e223eca40d55fc833ff4058d7abeb43a887680 | 658,156 |
from typing import Counter
def pythagorean_triple(max_perimeter: int) -> dict:
"""
Returns a dictionary with keys as the perimeter of a right angled triangle
and value as the number of corresponding triplets.
>>> pythagorean_triple(15)
Counter({12: 1})
>>> pythagorean_triple(40)
Counter({1... | 9802b8b3366b441e686d18af075bd56679e9407e | 658,157 |
def tail(iterable):
"""Returns all elements excluding the first out of an iterable.
:param iterable:
Iterable sequence.
:returns:
All elements of the iterable sequence excluding the first.
"""
return iterable[1:] | e8e3b68f6081dd32374a4ef892273ad3e24ed034 | 658,158 |
def to_title(text):
"""
Description: Convert text to title type and remove underscores
:param text: raw text
:return: Converted text
"""
return str(text).title().replace('_', ' ') | 8ea42ce65725c82d7b41462916170229dc54db96 | 658,159 |
import json
def get_context_products(setup):
"""Obtain PDS4 Context Products.
Obtain the context products from the PDS4 registered context products
template or from the XML configuration file.
:param setup: Setup object already constructed
:return: dictionary with the JSON structure of the bundl... | 5a71e8e4b2f26a979dcad633f02f5b7a43ef86d4 | 658,160 |
def _parse_google_api_response_components(response):
"""Parse Google maps "address_components" into more compact json.
Assumes US address.
Input format described at
https://developers.google.com/places/web-service/details#PlaceDetailsResponses
"""
address_components = response["address_component... | 9d4b55f938b27672ae96047bd6a603d70cd7970b | 658,161 |
import os
def check_file(fpath):
"""Returns absolute path of file if it exists and is readable,
raises IOError otherwise"""
if os.path.isfile(fpath):
return os.path.abspath(fpath)
else:
raise IOError('File not found/readable: {}'.format(fpath)) | 579270ea19777dfddedec6e46f3f596522303109 | 658,163 |
def transaction_type_1():
"""Transaction of type "second signature registration"
"""
data = {
'version': 1,
'network': 30,
'type': 1,
'timestamp': 4895203,
'senderPublicKey': '03a02b9d5fdd1307c2ee4652ba54d492d1fd11a7d1bb3f3a44c4a05e79f19de933',
'fee': 50000000... | 55f7bc9934f174bcfacd27da13671f974f33479c | 658,164 |
import os
def touch_folder(model_dir):
"""
This function returns the absolute path of `model_dir` if exists
otherwise try to create the folder and returns the absolute path.
"""
model_dir = os.path.expanduser(model_dir)
if not os.path.exists(model_dir):
try:
os.makedirs(mod... | 1c74edd9fd3368404efea2ca6d124b5144e6f442 | 658,165 |
from typing import List
import sys
import subprocess
def nics() -> List[str]:
"""Information on installed network interface cards."""
output = []
if sys.platform == 'linux':
try:
# first we try ip addr command
out = subprocess.Popen(["ip", "addr"],
... | efc0fda7a7d1bb6c932e1c6cda948a8a23b0a379 | 658,166 |
def first(x, y):
"""First argument"""
return x | 2ec921a2be88257b7aa5427df8e3b079f3d64bed | 658,167 |
import seaborn as sns
def load2():
"""This loads the data from the internet. Does not work well on the TMC server."""
return sns.load_dataset('iris').drop('species', axis=1).values | f0f0d1b1d1bf844352b3ffe9873d09f4a7564f56 | 658,169 |
import torch
def zip_stack(batch_lists):
"""
returns (stack(feat_1), stack(feat_2)...)
"""
rv = tuple(torch.stack(x) for x in zip(*batch_lists))
return rv | e3e0b45cadf318fadf051f2bfb13bdcc0033a54e | 658,170 |
import os
def read_message(filename):
"""
Assumes file with secrets is
in the same directory as this program
"""
try:
path = f'{os.path.abspath(os.path.dirname(__file__))}{os.sep}{filename}'
with open(path, 'r') as f:
return f.read()
except FileNotFoundError:
... | fa1b9979a42e15a4f503a3680d12bcb753f95f5a | 658,171 |
def getter():
""" Trivial getter. """
return True | e8f15b447b516104922ba436a73a3cb52d1e033b | 658,172 |
def diff_view(str1, str2):
""" Calculate the lengths of the longest common prefix
and suffix between str1 and str2.
Let str1 = axb of length m and str2 = ayb of length n,
then this function finds and returns i and j such that:
str1[0:i] = str2[0:i] = a and str1[m-j:] = str2[n-j:] = b.
In the ca... | 997f5a0ff4d054b59bf08618ba0f15d9c4b2f0d1 | 658,173 |
import os
import random
def _find_video_files(data_dir, labels_file):
"""Build a list of all videos files and labels in the data set.
Args:
data_dir: string, path to the root directory of videos.
Assumes that the image data set resides in video files located in
the following directory structure.... | f5ef5a8f1e0b734080fc34e7bf30d09d80a23707 | 658,175 |
def parse_list_to_string(tags):
"""
Parses a list of tags into a single string with the tags separated by comma
:param tags: A list of tags
:return: A string with tags separated by comma
"""
return ', '.join(tags) | e6443a5941a0ba9a2488735e651c1dcca81dba5f | 658,176 |
def make_name_alliteration(words, divider=' '):
"""Make an alliteration with a set of words, if applicable.
Examples:
java jacket
singing sally
earth engines
...etc
1. Loop through a given array of words
2. group by words with the same first letter
3. combine them and return to new... | 54a93a8993a4c8e00c6e6b3a39f44be37ea542bd | 658,177 |
def normalizeInternalObjectType(value, cls, name):
"""
Normalizes an internal object type.
* **value** must be a instance of **cls**.
* Returned value is the same type as the input value.
"""
if not isinstance(value, cls):
raise TypeError("%s must be a %s instance, not %s."
... | a9addc752ffea788f2e015f0c11e11dee890707c | 658,178 |
def parseResult(rst):
"""Parse the results returned by snopt and convert to a dict."""
return {'flag': rst.flag, 'obj': rst.obj, 'x': rst.sol, 'f': rst.fval} | 38f819e474fa95032917969fb0b80d4ba52c8ad3 | 658,180 |
import logging
def identity_transformation(data):
"""Use default coder is no encoding/decoding."""
logging.log(logging.WARNING, "identity_transformation from connection.py is deprecated now. Please use"
" abstract_moler_connection.py.")
return data | ea50e10c4fe2387cff434a6f6b16bba42caedd51 | 658,181 |
import os
def isNewer(aPath, bPath):
"""
a是否比b新
若a不存在,返回False
若a存在但b不存在,返回True
若a,b都存在则比较最后修改时间
"""
try:
aStat = os.stat(aPath)
except:
return False
try:
bStat = os.stat(bPath)
except:
return True
return aStat.st_mtime > bStat.st_mtime | 0d7315ccb53559bfa6a60e63b6c673c3217dc498 | 658,182 |
def matriz_identidade(ordem: int = 1) -> list:
"""Cria uma matriz identidade."""
matriz = []
for linha in range(ordem):
nova_coluna = []
for coluna in range(ordem):
nova_coluna.append(0) if linha != coluna else nova_coluna.append(1)
matriz.append(nova_coluna)
return m... | f3337fe92da26f5a4a3e8db51c5d0be5f19a59b8 | 658,183 |
import argparse
def parseArguments():
"""
Parse the command-line options
"""
desc = "It process PDB files putting the ligand part of a covalent ligand into the residue that it is attached with."
parser = argparse.ArgumentParser(description=desc)
required_named = parser.add_argument_group('... | e474195aa563248fcd1f942c4e4a6f959c5941ac | 658,184 |
def read(path, mode="rt"):
"""
I think reading an entire file is rather safe across the nfs.
But in case I am wrong, here is the wrapper.
"""
with open(path, mode) as f:
content = f.read()
return content | f4fa26e6892506a4c016c31618b88db5f73e47fd | 658,185 |
def leaderboard(self):
"""
Return top 10 rows' id and value fields
"""
rows = self.cursor.execute("SELECT id,value,rank FROM reputation ORDER BY value DESC LIMIT 10").fetchall()
return rows | b3ecccbef0528dd010eab1f3b6a2c5aeafb83e43 | 658,186 |
def sum_env_dict(envs):
"""Sums counts from the data structure produced by count_envs."""
return sum([sum(env.values()) for env in envs.values()]) | d4525044a50b70a80a73d6f77b366e980ce14de5 | 658,187 |
def has_file_extension(file_path: str, file_extension: str) -> bool:
""" Checks if a file path ends with a given file extension. """
return file_path.lower().endswith('.' + file_extension) | 3d1acc4b915a7c7735420dade97d2b3eb2fc2f4c | 658,188 |
def sekunde_v_format(sek):
"""
Pretvori sekunde `sek` v format hh:mm:ss.
"""
if isinstance(sek, str):
return sek
h = sek // 3600
m = (sek % 3600) // 60
s = sek % 60
return "{:0>2d}:{:0>2d}:{:0>2d}".format(h, m, s) | 4373b8999b665f67fdba1e87c3922e65ad498a0f | 658,189 |
def colon_labels2binary(report_labels):
"""
Convert the pre-defined labels extracted from colon reports to binary labels used for classification
Params:
report_labels (dict(list)): the dict containing for each colon report the pre-defined labels
Returns: a dict containing for each colon report the set of binary... | 04819e1d77821d568320059eff90aefc816d275a | 658,190 |
import os
import io
def get_readme():
"""Returns content of README.rst file"""
dirname = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(dirname, "README.rst")
with io.open(filename, "r", encoding="utf-8") as fp:
long_description = fp.read()
return long_description | d84ffca40bfd373aa4d713c62ae290c2e5745b02 | 658,191 |
def min_max_indexes(seq):
"""
Uses enumerate, max, and min to return the indices of the values
in a list with the maximum and minimum value:
"""
l = sorted(enumerate(seq), key=lambda s: s[1])
return l[0][0], l[-1][0] | f44438187db55f27ca7e09d1524698a81885a4ad | 658,192 |
def get_variable_name(variable, loc):
"""
获得变量的str名称
REF: https://blog.csdn.net/Yeoman92/article/details/75076166
"""
# loc = locals()
# print(loc)
for key in loc:
if loc[key] == variable:
return key | 1425615ebc450c16f41a9fa313e65a0573ea18f2 | 658,193 |
def get_factor(spacegroup, gamma):
"""
Determines bond length multiplication factor.
Depends on spacegroup and gamma angle.
"""
if spacegroup == 12:
return 1.4
elif spacegroup == 33:
return 1.4
elif spacegroup == 167:
return 1.5
elif spacegroup == 194:
ret... | 41b9a14fc6d9825e7d54c799c729bc07091bb3eb | 658,194 |
def grain_to_dry_malt_weight(malt):
"""
Grain to DME Weight
:param float grain: Weight of Grain
:return: DME Weight
:rtype: float
"""
return malt * 3.0 / 5.0 | 168103d8b91e4d5da2db5667d2129f04a290b07d | 658,195 |
import requests
import json
def get_sign():
"""
获取签名值
返回值 svv, stt, suid, jign
:return:
"""
url = 'https://hellodns.coding.net/p/sign/d/jsign/git/raw/master/sign'
res = requests.get(url=url, verify=False, timeout=20)
sign_list = json.loads(res.text)
svv = sign_list['sv']
stt = ... | b31287994303b6e44c63ce4a520d4cb2daa54e5e | 658,197 |
def extension_to_type(kernel):
"""Given a SPICE kernel provide the SPICE kernel type.
:param kernel: SPICE Kernel name
:type kernel: str
:return: SPICE Kernel type of the input SPICE kernel name
:rtype: str
"""
kernel_type_map = {
"TI": "IK",
"TF": "FK",
"TM": "MK",
... | 5397939f596aefe61a849008a03a80159c30449d | 658,198 |
import re
def get_title_display(title: str, year: int, url: str) -> str:
"""
Extract simplified title.
Parameters
----------
title (str): movie title
year (int): date of the movie
url (str): url of the movie poster
Returns
----------
title_display (str): format "title, year, ... | d5990d309b179c464589d2de3ad527cf7862556c | 658,200 |
from typing import List
from typing import TextIO
def read_pvarcolumns(path: str) -> List[str]:
"""Get the column names from the pvar file (not constrained like bim, especially when converted from VCF)"""
f_pvar: TextIO = open(path, 'rt')
line: str = '#'
header: List[str] = []
while line.startswit... | fa2990d0c753048468e22dc0b17c9a0228fe27f5 | 658,201 |
async def get_settings(app):
"""Retrieve breaks settings from the database.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
Returns
-------
breaks : dict
A dictionary with the breaks settings
"""
breaks = (await app["db"].settings... | 471dfd66a7191f9166eee7c5e913ba81c2ec950e | 658,202 |
def is_positive(number):
""" The is_positive function should return "True" if the number
received is positive, otherwise it returns "None". """
if number > 0:
return True
return None | 029ae78c3c79dade877a65bb0f9caf992cef597f | 658,203 |
import os
def remove_extension(path: str) -> str:
"""Remove the extension of a filename if any.
Examples:
>>> remove_extension('a.cpp')
'a'
>>> remove_extension('hello')
'hello'
"""
return os.path.splitext(path)[0] | ee6e2e3ed809a37f8e051e1d44c3cfe8892872ae | 658,204 |
def _get_taxon(tid, taxdump):
"""Get information of a given taxId from taxonomy database.
Parameters
----------
tid : str
taxId to query
taxdump : dict
taxonomy database
Returns
-------
dict
information of taxon
Raises
------
ValueError
If t... | a791b16bca9ade2f1d11f5eee4e282048bfc8832 | 658,205 |
import pathlib
def product_filename_retrieve(filename):
"""
Retrieve information from the standard product filename.
:param filename: file name.
:return: filename information dictionary.
"""
file_name = pathlib.PureWindowsPath(filename)
file_stem = file_name.stem.split("_")
return di... | ad09a431eea489466e0f1622234c5192e9331e30 | 658,206 |
def sum_int(values) :
"""Sum of integer values"""
sum = 0
for v in values :
sum += int(v)
return sum | e63b38b74888b629c3133e5438cab180255cb044 | 658,207 |
def get_num_jobs(emp_intervals_long):
""" Get the number of jobs for each ssn_altkey with >= 1 job, before reduction"""
return emp_intervals_long.groupby(level=0) \
.size() \
.rename("prs_lex_numJobs_c_2014") \
.to_frame() | c6e0d0c47a9feb5f0451f597355a1519582ce332 | 658,208 |
import os
import yaml
def _get_nested_config(config_dir, path):
"""
Collects nested config from between `config_dir` and `path`. Config at
lower level as greater precedence.
:param config_dir: The directory path to the top-level config folder.
:type config_dir: str
:param path: The directory ... | 6759a753348e283c96d9c6a895e3478ee0fce1f7 | 658,209 |
import itertools
def dropwhile():
"""Purge elements before the matching one."""
purged = itertools.dropwhile(lambda x: x != 'C', 'ABCDEF')
return ''.join(purged) | 42bb72432b90bdb034cd817964a59d90db3f432c | 658,210 |
import os
def find_path(plot_name, data_type):
"""Given a plot name recover the location on disk of the correct path"""
#To allow testing, looking for an env var
if "NEONTREEEVALUATION_DIR" in os.environ:
base_dir = os.environ["NEONTREEEVALUATION_DIR"]
else:
base_dir = "data/"
... | 5bdaef01f12f9640652708fce44791e0c8386fc4 | 658,211 |
import os
import yaml
def dump_updated_topology(topology, args):
"""Writes or prints out updated topology file.
:param topology: Topology information with nodes.
:param args: Arguments parsed from command line.
:type topology: dict
:type args: ArgumentParser().parse_args()
:return: 1 if error... | f97f5b05a76ff7ce3ab12428a1ccee932bca9716 | 658,212 |
def get_text_color(background_color):
"""Select the appropriate text color (black or white) based on the luminance of the background color.
Arguments:
background_color (tuple): The record color (RGB or RGBA format).
Returns:
tuple: The chosen text color (black or white).
"""
# Cou... | c31e894f39cb84c505ec7b10d14988a142d3a916 | 658,213 |
import string
import random
def make_random_function_name() -> str:
""" Function names can contain uppercase letters, lowercase letters, numbers and
underscores, but cannot begin with a number. We will arbitrarily limit function names
to 20 characters. We will make their minimum length to 10 characters to... | 431963baa274add7ed4167d2326eb536fc58b073 | 658,214 |
def get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn):
"""
:param subscenarios: SubScenarios object with all subscenario info
:param subproblem:
:param stage:
:param conn: database connection
:return:
"""
c = conn.cursor()
project_zones = c.execute(
... | 0d537f0734cc8f6b3006ae66f1f0c6d603ab004c | 658,215 |
from typing import Callable
from typing import Any
from typing import Tuple
from typing import Dict
import inspect
def _static_method_by_default(
wrapped: Callable,
instance: Any,
args: Tuple[Any],
kwargs: Dict[str, Any],
) -> Callable:
"""
Make decorator behaves like @staticmethod.
If de... | 27529cdc5acd84459a5de815734c292e3ac8fbf0 | 658,218 |
def mtf_order():
"""Solution to exercise R-7.18.
Given the set of element {a, b, c, d, e, f } stored in a list, show the
final state of the list, assuming we use the move-to-front heuristic and
access the elements according to the following sequence:
(a, b, c, d, e, f , a, c, f , b, d, e).
---... | 447f39d4277e24cc33bc7259b64d152344e3b03a | 658,219 |
def transition_filename(tr):
"""Get the part of the filename specifying the transition (e.g. BKstar)
from a transition string (e.g. B->K*)."""
return tr.replace('->', '').replace('*', 'star') | ba653344ccbf88af0d813aebe5e5b5dfb966d4e2 | 658,221 |
def assert_endpoint_capabilities(endpoint, *interfaces):
"""Assert the endpoint supports the given interfaces.
Returns a set of capabilities, in case you want to assert more things about
them.
"""
capabilities = endpoint["capabilities"]
supported = set(feature["interface"] for feature in capabi... | a01ed447a19f589db8b06ff6212aa534b876a6c4 | 658,223 |
def full_adder(aig, a, b, c_in):
"""
>>> for a, b, c in itertools.product((0, 1), repeat=3):
... print( (a, b, c), full_adder(AIG(), a, b, c) )
(0, 0, 0) (0, 0)
(0, 0, 1) (1, 0)
(0, 1, 0) (1, 0)
(0, 1, 1) (0, 1)
(1, 0, 0) (1, 0)
(1, 0, 1) (0, 1)
(1, 1, 0) (0, 1)
(1, 1, 1)... | 8c53e2ea092720345d8808ef63bb1844553c2e7f | 658,224 |
def normalize(numbers, total=1.0):
"""Multiply each number by a constant such that the sum is 1.0 (or total).
>>> normalize([1,2,1])
[0.25, 0.5, 0.25]
"""
k = total / sum(numbers)
return [k * n for n in numbers] | 1114c7831d8c957972a0f80f539661424f04f469 | 658,225 |
def __eq__(self, autre_duree):
"""Test si self et autre_duree sont égales"""
return self.sec == autre_duree.sec and self.min == autre_duree.min | 32993ae9ea6937d2006a3a1364fe7684527ac0d1 | 658,226 |
def convert_ms_object(ms_object):
"""
Converts the list of dictionaries with keys "key" and "value" into
more logical value-key pairs in a plain dictionary.
"""
out_dict = {}
for item in ms_object:
out_dict[item["Key"]] = item["Value"]
return out_dict | 70e005bc2e495b4e891212994142fad2b507ccf5 | 658,228 |
def percentage_scores(hits_list, p_list, nr_of_groups):
"""Calculates the percent score which is the cumulative number of hits below a given percentage.
The function counts the number of hits in the hits_list contains below a percentage of the maximum hit score (nr_of_groups).
It then subtracts the expected... | 601f67fef87418d90e3a699e26f46a7479a253aa | 658,229 |
import collections
def get_interface_config_common(device, mtu=None):
"""
Return the interface configuration parameters that is common to all
device types.
"""
parameters = collections.OrderedDict()
parameters['BOOTPROTO'] = 'none'
parameters['ONBOOT'] = 'yes'
parameters['DEVICE'] = de... | 2ff7818a1f8cdb0ceae0a6cb7c5a8f466037a0e4 | 658,230 |
from typing import List
def get_angles_2qutrit() -> List[str]:
"""Return a list of angles for 2-qutrit gates."""
l = []
l.append("90")
l.append("180")
return l | 318ef86194e119a016459490a07bec1b467684e0 | 658,231 |
from typing import Sequence
def filter_overrides(overrides: Sequence[str]) -> Sequence[str]:
"""
:param overrides: overrides list
:return: returning a new overrides list with all the keys starting with hydra. filtered.
"""
return [x for x in overrides if not x.startswith("hydra.")] | 37750b6a9699e258c7b0f35b24342e56e8a1c34e | 658,232 |
def setup_jwt_manager(app, jwt):
"""Initialize jwt config."""
def get_roles(a_dict):
return a_dict['realm_access']['roles']
app.config['JWT_ROLE_CALLBACK'] = get_roles
jwt.init_app(app)
return | b35e914257a3ac84f8b35552f7516d8b346e6c91 | 658,233 |
def get_attribute_terms(product):
"""
Function to iterate through all variants of a variable product and compile a list of attribute terms from them.
:param product: Variable product and variants information
:return: list of term names
"""
attribute_terms = list()
for variation in product['... | 3a785220eadffe20241116036e08c00b41e232fc | 658,235 |
def convert_feature_to_result_document(feature):
"""
"feature": {
"number": 6,
"type": "number"
},
"feature": {
"api": "ws2_32.WSASocket",
"type": "api"
},
"feature": {
"match": "create TCP socket",
"type": "match"
},
"feature": {
... | 00bb1eefdacaba65af92590d698617e5a546d00d | 658,236 |
def tensor_unsort(sorted_tensor, oidx):
"""
Unsort a sorted tensor on its 0-th dimension, based on the original idx.
"""
assert sorted_tensor.size(0) == len(oidx), "Number of list elements must match with original indices."
backidx = [x[0] for x in sorted(enumerate(oidx), key=lambda x: x[1])]
re... | da1a92565fb13a4e0212c2e54bb4e12a7e1fe510 | 658,237 |
def get_data_path(name):
"""get_data_path
:param name:
:param config_file:
"""
if name == 'cityscapes':
return '../data/CityScapes/'
if name == 'pascal_voc':
return '../data/VOC2012/' | eebe9eff07cec9c91eec7bc9e3cd6c95c57a4163 | 658,238 |
import re
def remove_duplicate_sentencestops(text, stop_chars=".;!?:"):
"""Remove duplicate sentence stops eg hello world... --> hello world.
Args:
text (str or list): text to be cleaned.
stop_chars (str, optional): Sentence stop characters to check for duplicates. Defaults to ".;!?:".
""... | affde0a4ba9e478165c06fcb7c3e53eb0eb0228b | 658,239 |
import re
def list_read_files(accession, reads, subsample):
"""
List read files.
"""
files = []
for fq_url in reads[accession]['url']:
file = re.sub(r'.+\/', '', fq_url)
if subsample and 'subsample' in reads[accession]:
file = file.replace('fastq', 'subsampled.fastq')
... | bf001b61fcbc95368ef0f41665716a732ccd8ed2 | 658,240 |
def check_filenames(data_f):
"""
checks if the science scans have the same DID - this would cause an issue for naming the output demod files
"""
scan_name_list = [str(scan.split('.fits')[0][-10:]) for scan in data_f]
seen = set()
uniq_scan_DIDs = [x for x in scan_name_list if x in seen or seen... | 0ff6b6c0e8c87165c6d108c640c0eeba20df30bc | 658,241 |
def calc_rho_and_rho_bar_squared(final_log_likelihood,
null_log_likelihood,
num_est_parameters):
"""
Calculates McFadden's rho-squared and rho-bar squared for the given model.
Parameters
----------
final_log_likelihood : float.
... | b36a8eb7ab854a038d3e6a0dbc85d976d66a2111 | 658,242 |
def d1r(dx, fc, i):
""" first-order, right-sided derivative at index i """
D = (fc[i+1] - fc[i])/dx
return D | ad3da8382fe32b2279b7d8ffb32dabd35ae2d3c1 | 658,243 |
import re
def get_initial_query_limit(query: str):
"""Returns the LIMIT within a SPARQL query string.
Args:
query (str): SPARQL query string.
Returns:
int: Limit or 0 if no limit.
"""
pattern = r"(LIMIT )([\d]+)"
match = re.search(pattern, query)
if match is None:
... | 71939899919c65ac97c71bb6e93cd33813b6444a | 658,244 |
def split_numerical_value(numeric_value, splitVal):
"""
split numeric value on splitVal
return sub ranges
"""
split_num = numeric_value.split(',')
if len(split_num) <= 1:
return split_num[0], split_num[0]
else:
low = split_num[0]
high = split_num[1]
# Fix 2,2 ... | af21b46a569e6cd3d0642abe8d8c789aff19f85e | 658,245 |
def _update_curr_pos(curr_pos, cmd, start_of_path):
"""Calculate the position of the pen after cmd is applied."""
if cmd[0] in 'ml':
curr_pos = [curr_pos[0] + float(cmd[1]), curr_pos[1] + float(cmd[2])]
if cmd[0] == 'm':
start_of_path = curr_pos
elif cmd[0] in 'z':
curr_pos = start_of_path
eli... | 750337f6df568201177d4ab03153da35ffa56eb9 | 658,246 |
def _get_resource_name(user_id, name):
"""
Get resource name by resource type.
:param str user_id: PipelineAI 8 character user id that uniquely
identifies the user that created the resource
for super users this user_id is not
... | 11ad89677f7a03055fa1593f7aa2b125a43c0ec5 | 658,247 |
def coalesce_volume_dates(in_volumes, in_dates, indexes):
"""Sums volumes between the indexes and ouputs
dates at the indexes
in_volumes : original volume list
in_dates : original dates list
indexes : list of indexes
Returns
-------
volumes: new volume array
dates: new dates array
... | 461c5cc8c3831ef618dbc5e15f4cee2fa468974c | 658,248 |
def is_solution_valid(board, solution):
"""
Check if a generated solution is valid for a given board.
:param board: The original, starting board.
:param solution: A full solution, i.e. a list of Coordinates.
:return: True if the solution is valid; False otherwise.
"""
if not solution:
... | ecd7e0b7784e5317fc9db62a5b5e4a8a4527a4ce | 658,249 |
import requests
def get_prometheus_range(payload):
"""Query prometheus for metrics."""
headers = {"Accept": "application/json"}
print("Executing Prometheus query: ", payload)
r = requests.get("http://prometheus.dfinity.systems:9090/api/v1/query_range", headers=headers, params=payload)
return r | 439b439a1c276ddae0fe250f5e456cd9986c591c | 658,250 |
def map_phred33_ascii_to_qualityscore(phred33_char: str) -> float:
"""Maps a ASCII phred33 quality character to a quality score
>>> map_phred33_ascii_to_qualityscore("#")
2
>>> map_phred33_ascii_to_qualityscore("J")
41
"""
return ord(phred33_char) - 33 | d93bb06bb6f7294260f27f08070fa0dffb7acc74 | 658,251 |
def assert_keys(source_dict, keys):
"""
Check key presence within a dict.
Args:
- source_dict (dict): the dict for which key presence should be checked
- keys (list): the list of keys whose presence should be checked
Returns:
list: empty list if all checks succeeded, list of erro... | f1ee7235ef4922b27c874c2c40076c989136aa50 | 658,252 |
def get_tri_category(score):
"""Get a 3 class integer classification label from a score between 0 and 1."""
if score >= 0 and score < 0.3333333333:
return 0
elif score >= 0.3333333333 and score < 0.6666666666:
return 1
else:
return 2 | 54306667882448925361bcb12e0bade4ddbcacf2 | 658,253 |
def _get_nested(data, key):
"""
Return value for a hierrachical key (like a.b.c).
Return None if nothing found.
If there is a key with . in the name, and a subdictionary,
the former is preferred:
>>> print(_get_nested({'a.b': 10, 'a':{'b': 20}}, 'a.b'))
10
>>> print(_get_nested({'a': {'... | 9b3b86b0f6f4138e2b558820d59104ff98aacd46 | 658,254 |
from pathlib import Path
def build_pwsh_analyze_command(file: Path) -> str:
""" Build command for powershell analyze
Args:
file(Path): files to execute lint
Returns:
str: powershell analyze command
"""
# Invoke script analyzer
command = "Invoke-ScriptAnalyzer"
# Return exi... | 7328938fd84a9b28c0c2122dcf0d37ad7841c72a | 658,255 |
import time
async def db_head_state(context):
"""Status/health check."""
db = context['db']
sql = ("SELECT num, created_at, extract(epoch from created_at) ts "
"FROM hive_blocks ORDER BY num DESC LIMIT 1")
row = await db.query_row(sql)
return dict(db_head_block=row['num'],
... | c921b4fedf8fe2c135f83ad9627d713636cb973f | 658,256 |
def l2i(path):
"""
Formats a list (['bla',0,'bla']) into a IMAS path ('bla[0].bla')
:param path: ODS path format
:return: IMAS path format
"""
ipath = path[0]
for step in path[1:]:
if isinstance(step, int) or step == ':':
ipath += "[%s]" % step
else:
... | 879615b59fa7fb2b9814beb4c794759162314939 | 658,257 |
from pathlib import Path
def get_filename_without_extension(f):
"""
f = '../celeba_man/fake/9992_split.jpg'
get_file_number(f) -> '9992_split'
"""
return Path(f).stem | 74dc85778af34f11c4d836e8247edbd89c5c6059 | 658,258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.