content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def normalise_activity_by_sector_month(
topic_activity, sector_month_labels, sector_variable="sector"
):
"""Normalise s.t. each [sector, month] sums to 1."""
norm_factor = (
sector_month_labels.dropna()
.groupby(
[
"month",
sector_variable,
... | 0c9fb4d8cd3b877cc08568bedb7019cbbc40cd90 | 679,806 |
def convert_to_list(something, convert_all=True):
"""convert other types to string."""
out = []
if isinstance(something, (list, tuple)):
for x in something:
out.append(convert_to_list(x, convert_all=False))
else:
if convert_all:
out.append(something)
else:... | d9bd17301138050e7c75cfb33a69e1e4a0cb8e68 | 679,807 |
def is_permutation(a: int, b: int) -> bool:
"""Returns boolean if a and b are permutations of each other."""
s_a, s_b = str(a), str(b)
if set(s_a) != set(s_b):
return False
if len(s_a) != len(s_b):
return False
return sorted(list(s_a)) == sorted(list(s_b)) | e3fa9e013f5794ec44d739282d98f72b8b601ed2 | 679,808 |
import pickle
import time
def persistence(*args):
"""
持久化对象或加载对象
:param args: 持久化参数顺序(对象, 存储文件夹, 文件名标识,'save')
加载参数顺序(文件路径, 'load')
:return:
"""
if args[1] == 'load':
f = open(args[0], 'rb')
obj = pickle.load(f)
return obj
elif args[3] == 'save':
... | 189cdbfd5c6056c29887c700321339e995cbdba5 | 679,811 |
def has_body(headers):
"""
:param headers: A dict-like object.
"""
return 'content-length' in headers | b17dd86a3beeb3024ca51bd69d73cdfcba0417e4 | 679,812 |
from collections import Counter
def related_by_digit_permutation(num_a, num_b):
"""
Check if two numbers are related by digit permutation.
"""
return Counter(str(num_a)) == Counter(str(num_b)) | 9c211d7e93f6fb6e39a07532e412b9ffda1ba96b | 679,813 |
from typing import Dict
from typing import Any
from typing import Optional
def get_name(hook: Dict[Any, Any]) -> Optional[str]:
"""
Creates a name based on the webhook call it recieved
Format: Timestamp_Devicename.mp4
Removes any characters that are not regular characters, numbers, '_' '.' or '-'
... | 2b9a034ee551894adc4a03cebce3711cdbad58d3 | 679,814 |
import sqlite3
def init_db(conn_or_path):
"""
Init the hash table using an open sqlite3 connection.
If the argument is a string, we create/open the database.
In both case, we return the connection object.
"""
# open / get connection
is_file = type(conn_or_path).__name__ == 'str'
if is_... | da11417c30d04c17b146ab0cd68c908683ce06eb | 679,815 |
def iterator(it):
"""
Convenience function to toggle whether to consume dataset and forecasts as iterators or iterables.
:param it:
:return: it (as iterator)
"""
return iter(it) | f0efa7c377aac88eb2d9f849bf00359327e702e9 | 679,816 |
def normalize_date(date):
"""Round datetime down to midnight."""
return date.replace(hour=0, minute=0, second=0, microsecond=0) | d4021f6e984045d9bd0172fd1c7d060acc8054e0 | 679,817 |
import tempfile
import os
def CallWithFile(func, data):
"""Calls func("/path/to/tempfile/containing/data")."""
tmp_file = tempfile.NamedTemporaryFile(delete=False)
try:
tmp_file.write(data)
tmp_file.close()
return func(tmp_file.name)
finally:
os.remove(tmp_file.name) | c8c223b0ea01b353cd7bd4d7473591f8d8cb055f | 679,818 |
import sqlite3
def get_list_of_teams():
"""Get a list of all teams."""
#FINISHED FOR SASO
dbconn = sqlite3.connect('saso.db')
cursor = dbconn.cursor()
teamlist = []
cursor.execute('SELECT * from teams where team_id = 0')
teamlist.append(cursor.fetchone()[1])
for team in cursor.exe... | b171c4b26de1f19593c5ef6766738e61cf755190 | 679,819 |
import math
def hits_to_kill(damage, health):
"""
Returns the number of hits it takes to kill the target.
"""
if damage > 0:
hits = health / damage
else:
hits = math.inf
if hits < 1:
hits = 1
elif hits < math.inf:
hits = math.ceil(hits)
return hits | 4cb87b0216145a42778781be844c4b44c87d355b | 679,820 |
import os
def get_image_filepath(data_dir, row):
""" Get image filepath from row """
return os.path.join(data_dir, f"{row.Species}___{row.Label}", row.Filename) | 058efa4855738b65607f3abb3b947305f588b3f5 | 679,822 |
from textwrap import dedent
def create_script(molecule_name, temperature=273.15, pressure=101325,
helium_void_fraction=1.0, unit_cells=(1, 1, 1),
simulation_type="MonteCarlo", cycles=2000,
init_cycles="auto", forcefield="CrystalGenerator",
input_... | eaef3ef51d2ff019b83b57ed36c2f4bb5a138450 | 679,823 |
import random
def randomTime(*args,**kwargs):
"""Generates a random time between 50.000 and 59.999 in bytes"""
randomBytes = [
128, #finish time indicator
random.randrange(48,57), #thousandth
random.randrange(48,57), #hundreth
random.randrange(48,57), #tenth
random.rand... | 41ba16c4d9c8b553600b8c46f2aa4df7072e7ce9 | 679,824 |
import uuid
def generate_unique_id(text):
"""
Generate a unique UUID based on a string
Args:
text(str): The string to base the uuid on
Returns:
str: The UUID in hex string format
"""
return uuid.uuid3(uuid.NAMESPACE_URL, text).hex | 02e44b594e043314450c85bf86e14349f9a4d87f | 679,825 |
import random
import string
def generate_random_key() -> str:
"""
Creates and returns a randomly generated 10 character alphanumeric string.
:return:
"""
return "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(10)
) | 324a74e50b00ad287838ea7ad10b127f094ca380 | 679,826 |
def _df_meta_to_arr(df):
"""Check what kind of data exists in pandas columns or index. If string return as numpy array 'S' type, otherwise regular numpy array.
"""
if len(df.columns):
if isinstance(df.columns[0], str):
columns = df.columns.values.astype("S")
else:
co... | 17a3b457d97726bf9c540fc9c8cc8fdf650c5d00 | 679,827 |
from pathlib import Path
import yaml
def load_yaml(yamlpath: str):
"""
Loads a yaml file from a path.
:param yamlpath: Path to yaml settings file
:returns: dict settings object """
yamlpath_full = Path(yamlpath).absolute()
with open(yamlpath_full, 'r', encoding="utf-8") as stream:
try... | 7c1e1f7a9a861532e5eafe277299bb4a6d0df41b | 679,828 |
import os
import requests
def validar_config_filepath(path: str) -> bool:
"""
Valida se o ficheiro de config fornecido
é um path existente no sistema, ou se aponta
para o ficheiro de config num repositorio
"""
if not os.path.exists(path):
exists_web: requests.Response = requests.get(
... | fffb51cd57e5f1607dc78f52f4af5aea5f423689 | 679,829 |
def show_version_cmd():
"""Show version.
"""
return ('show_version', {}) | b7a1823d6995f0b1872183382b1b0efe3ad17592 | 679,830 |
import time
def timer_step(func):
"""Timer decorator"""
def wrapper(*args, **kwargs):
start = time.perf_counter()
rv = func(*args, **kwargs)
finish = time.perf_counter()
print(f'\nFinished in {round((finish - start) / 60, 2)} minute(s)')
return(rv)
return(wrapper) | 2a0971fbad124051718c7d29c89d2fda5f7d536d | 679,831 |
def get_framework_and_technology():
"""
Return the framework and its related technology (e.g. Django, python) as
a tuple. Fails with a ``KeyError`` if user didn't choose a framework.
"""
framework_technology = {
'Django': 'python',
'Flask': 'python',
'SpringBoot': 'java',
... | f92f8f39743845748c7b0c450d7efd03a061035c | 679,832 |
import itertools
def get_anagrams(*yarn):
"""Return a list of anagrams for a string."""
# If only one letter came in, return it
if yarn:
if len(yarn[0]) <= 1:
return list(yarn)
else:
raise ValueError("Must provide at least two letters")
# Get all of the words from the ... | ef2d296e9484ec54d99f2a5e4fa2aced4a42e7e6 | 679,833 |
def rjust(value, arg):
"""
Right-aligns the value in a field of a given width.
Argument: field size.
"""
return value.rjust(int(arg)) | 83e351e8cbd831ce62fdc8a3b57517350ca94da9 | 679,834 |
import subprocess
def run_one_shline(shline):
"""Shell out"""
ran = subprocess.run(
shline, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
assert not ran.stderr # because stderr=subprocess.STDOUT
assert ran.returncode is not None
gots = ran.stdout.decode().strip().re... | dd3d50b034e36e52b35b6a57162f9083dcb155a3 | 679,836 |
def has_field(analysis, field):
"""Return true or false if given field exists in analysis"""
for f in field:
try:
analysis = analysis[f]
except:
return False
return True | 29a2a6f1c4a89d282220bd5cbd4c9e6e18ae4440 | 679,837 |
import os
def normalize(path):
"""Converts a path to an absolute path.
Args:
path (str): Input path.
Returns:
str: Absolute path.
"""
return os.path.abspath(path) | ed5e830a488d83b9d3919b5fe01907b8ae39ec30 | 679,838 |
import multiprocessing
def queue_loader(q_list):
"""
Copy values from a List into a SimpleQueue.
"""
q = multiprocessing.SimpleQueue()
for item in q_list:
q.put(item)
return q | 31a41cfc555baeaa0c5c462afdc3596e8f7f714b | 679,839 |
import re
def fuzzyfinder(input, collection, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the `input`.
accessor (functio... | 9abec5ccddedacb6c5ab33b8d6dc168296b735d3 | 679,840 |
def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
... | 08ea4a3d62f034add07c45219da6d96ea3795e8d | 679,842 |
def color_to_int(rgb):
"""Converts a color from floating point range 0-1 to integer range 0-255."""
return tuple(int(round(c * 255)) for c in rgb) | 4ee66330665300c27dda598c070c5519b63eda54 | 679,843 |
import os
from typing import Any
import csv
import numpy
def _csvToHeaderValues(input_csv_filename: str):
"""Given csv file from a TokenSPICE run, creates (header, values).
Args:
input_csv_filename -- absolute path of input csv file
Returns:
header: List[str] -- e.g. 'Tick', 'Second', ..... | 458870f86a947e89fa368cdad8be116c198a973c | 679,844 |
import multiprocessing
import os
def num_processors():
"""Returns the number of processors.
Python on OSX 10.6 raises a NotImplementedError exception.
"""
try:
# Multiprocessing
return multiprocessing.cpu_count()
except: # pylint: disable=W0702
# Mac OS 10.6
return int(os.sysconf('SC_NPROC... | aaa43a9c79187d5adf4a97d96d64867b0038402b | 679,845 |
import re
def _get_before_pronounce_sentence(words, index):
"""Return before pronounce sentence
Args:
words (List[Words]): stanfordnlp word object list.
index (int): Pronounce index.
Return:
sentence (str): target word contains sentence to pronounce.
"""
roots = [(i, w) fo... | 018f8197b7b1fbe2992131dffe941949eb0157a8 | 679,846 |
def _get_kaggle_type(competition_or_dataset: str) -> str:
"""Returns the kaggle type (competitions/datasets).
Args:
competition_or_dataset: Name of the kaggle competition/dataset.
Returns:
Kaggle type (competitions/datasets).
"""
# Dataset are `user/dataset_name`
return 'datasets' if '/' in compet... | 6341c5ecda800b6f5cee260f4ac50d1748b78528 | 679,848 |
def token_response_json(token_response):
"""
Return the JSON from a successful token response.
"""
return token_response.json | a879b95407251c8cc018e132fdd3e0d0ad109867 | 679,849 |
def get_subgraph(G, attribute, attribute_value):
"""
This function returns the subgraph of G with the attribute
attribute_value.
Input:
------
G: networkx graph
attribute: attribute of the nodes
attribute_value: value of the attribute
Output:
-------
subgra... | f84895c73f5b0b8508587b5491cf5d765471429a | 679,850 |
import re
def verifyFormat(ATS_LIST):
"""
Matches a list of input ATS coordinates against the AltaLIS format in a regex.
Returns True if any of the coordinates match the regex,
False if none return.
"""
# Defines a list of expressions to check against the coordinates.
# Anything in s... | aaa20e4ebd3118bb9e761e7d7e8c74dab7d8ea55 | 679,852 |
def SanityCheck(s):
"""
Class performs a simple text-based SanityCheck
to validate generated SMILES. Note, this method
does not check if the SMILES defines a valid molecule,
but just if the generated SMILES contains the
correct number of ring indices as well as opening/closing
brackets.
... | d0cfece50836a3025ae2f45286bee942bd44b27c | 679,853 |
def find(wildcard, of_type=None):
"""
This will take in the given wildcard string and find all elements
whose names match the given wildcard. The filtered list can be further
refined using the 'of_type' variable where you can define the type
of elements to return.
:param wildcard: A wildcard st... | 3a89506f2312ea4c37f0d9dff1befa04027472a6 | 679,854 |
import random
def randint():
"""Return a random 12 digit integer."""
return random.randint(100000000000, 999999999999) | 6bfa62f9bdf623bca8e5deea3d03b82c8a923572 | 679,855 |
def priormonthToDay(freq, j_mth, k_mth):
"""
Consistent w/ Fama and French (2008, 2016), map the prior `(j-k)` monthly return strategy into a daily strategy
(see `Ken French's online documentation <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html>`_).
Parameters
__________... | 124332f879f059a97eb165f26cc3780d97f7c595 | 679,856 |
from typing import List
from typing import Dict
def deps_to_dict(dependencies: List[dict], by: str = 'dependent') -> Dict[int, dict]:
"""Create a dictionary of dependencies, for faster lookups"""
if by not in ('dependent', 'governor', 'label'):
raise ValueError('by must be one of [dependent, governor... | 9d2389a206d7b9a16f502272c8dfcef53ae32f74 | 679,857 |
def sources(graph, n):
""" Determines the set of sources of 'node' in a DAG
:param graph: Graph
:return: set of nodes
"""
nodes = {n}
q = [n]
while q:
new = q.pop(0)
for src in graph.nodes(to_node=new):
if src not in nodes:
nodes.add(src)
... | aa440519826c8499dff0f27ee44960c8f7f6c6be | 679,858 |
import re
def _filter_zones(wanted_zones_prefix, zone_list):
"""Filter unwanted zones from a zone list using a prefix."""
target_zones = []
for zone in zone_list:
for prefix in wanted_zones_prefix:
pattern = re.compile(f'^{prefix}')
if pattern.match(zone):
... | 9ec1f068f819ce0d15879ccd81cf3254aabae654 | 679,859 |
def _cut_if_too_long(text: str, max_length: int) -> str:
"""Cut a string down to the maximum length.
Args:
text: Text to check.
max_length: The maximum length of the resulting string.
Returns:
Cut string with ... added at the end if it was too long.
"""
if len(text) <= max_... | 72745efb8a4fd7d6b2af7356d00e1e5bc554ff62 | 679,860 |
def clean_text(text):
"""
split and clean the text.
:param text: text tokennized.
:return:
"""
#text = re.sub("[A-Za-z0-9]", "", text)
text = [x for x in text.split(" ") if x!='']
return text | a5934d101f166681826289608a46bc30543f238b | 679,861 |
import ipaddress
def is_address(entry):
""" Check if entry is a valid IP address """
try:
_ = ipaddress.ip_address(entry)
except ValueError:
return False
return True | 08e9cc24e7319d03a7a5fc9b9768db4497f76039 | 679,862 |
def find_fragmented_packet(results):
"""
This function searches Tcpdump's standard output and looks for packets
that have a length larger than the MTU(hardcoded to 1500) of the device.
"""
for line in results.decode('utf-8').split('\n'):
pieces = line.split(' ')
if len(pieces) < 2:
... | 75a56cfb2d311d7530fb7247345a7488f51eedda | 679,863 |
import numpy
def find_separation_skycomponents(comps_test, comps_ref=None):
""" Find the matrix of separations for two lists of components
:param comps_test: List of components to be test
:param comps_ref: If None then set to comps_test
:return:
"""
if comps_ref is None:
ncomps = ... | 4772a3efdc166a5a88939ed2165503fe7dd15515 | 679,864 |
import os
def join(a: str, p: str) -> str:
"""Configurable equivalent to `os.path.join`. Only accepts 2 args."""
return os.path.join(a, p) | c5fe3400b19fd75a8457d8b8314f2760010df40c | 679,865 |
def tuple_or_list(target):
"""Check is a string object contains a tuple or list
If a string likes '[a, b, c]' or '(a, b, c)', then return true,
otherwise false.
Arguments:
target {str} -- target string
Returns:
bool -- result
"""
# if the target is a tuple or ... | f29d4685b8e8bbb0c7e5c800a34a226782cdc7ae | 679,866 |
def get_ext(file):
"""Return the extension of the given filename."""
return file.split('.')[-1] | 5ee0d644557a4f7d5fc30727ed9beca6ab4a67f9 | 679,867 |
def add_vertical_area(area):
"""
It opens a vertical area.
"""
area.master.master.master.create()
return 'break' | 03396d1ec6ba017912aae254ea04fb627321e501 | 679,868 |
def splitext(path):
"""Split the extension from a pathname.
Extension is everything from the last dot to the end. Return
"(root, ext)", either part may be empty.
"""
i = 0
n = -1
for c in path:
if c == '.': n = i
i = i+1
if n < 0:
return (path, "")
else:
... | fda8a3079eadae9f9e03ddd1202931071f4a0e65 | 679,869 |
import inspect
def get_wrapped_sourcelines(f):
"""
Gets a list of source lines and starting line number for the given function
:param f: Input function
:return: Source lines
"""
if hasattr(f, "__wrapped__"):
# has __wrapped__, going deep
return get_wrapped_sourcelines(f.__wrapp... | 4ad7c9813e304a77f9f1b5c1096c8a3af379250c | 679,870 |
import logging
def get_logger(level=logging.INFO, filename=None):
"""
use the basics from analytics-mesh for this instead.
"""
log = logging.getLogger()
# we nuke the existing handlers whenever this function is called (else they stack)
log.handlers = []
formatter = logging.Formatter('%(asc... | 46bd0a264838ef9521a004016339e98f9c585542 | 679,871 |
def _reshape_for_est(X_del):
"""Convert X_del to a sklearn-compatible shape."""
n_times, n_epochs, n_feats, n_delays = X_del.shape
X_del = X_del.reshape(n_times, n_epochs, -1) # concatenate feats
X_del = X_del.reshape(n_times * n_epochs, -1, order='F')
return X_del | 80cc198fbe32d2a77bc9ab8d897265c7685d5cac | 679,872 |
import inspect
import ast
import textwrap
def ast_object(obj):
"""Convert a Python object to its AST representation."""
src = inspect.getsource(obj)
# ast wraps always into a module
node = ast.parse(textwrap.dedent(src)).body[0]
return node | ce25f484f289410ccc08a5e42384b707cb418f76 | 679,873 |
def txt2str(filename):
"""Reads the plain text of a .txt file and returns a string"""
with open(filename, 'r') as myfile:
data=myfile.read().replace('\n', '')
myfile.close()
return data | 7b9ba73b6d33654e3be21d6d286fc3109dee0790 | 679,874 |
def _monitor_pvs(*pv_names, context, queue, data_type='time'):
"""
Monitor pv_names in the given threading context, putting events to `queue`.
Parameters
----------
*pv_names : str
PV names to monitor.
context : caproto.threading.client.Context
The threading context to use.
... | cf8e9a09851e5a9edf958b1fce13294fecdf37ae | 679,875 |
def read_files():
"""
Reads from existing .txt files and collects them into a dictionary
There are 81 files all in the same file wih the module
"""
files_all = {}
for i in range(1, 82):
file_name = str(i) + ".txt"
handle = open(file_name, "r", encoding="utf8")
temp = ha... | 61b553cf8af20aaa446fd9e3c12a04ee5368ea62 | 679,876 |
from typing import List
def column_widths(table: List[List[str]]) -> List[int]:
"""Get the maximum size for each column in table"""
return [max(map(len, col)) for col in zip(*table)] | 7f5f601c7d40bc96f257c120adbf6a32ba327789 | 679,877 |
def commands(command):
""" Check if command is to get available Commands (c | commands). """
return (command.strip().lower() == 'c' or command.strip().lower() == 'commands') | ae580a454446af391b17e7c33643160fbce13113 | 679,879 |
def build_concentartion(species_id, number):
"""
Builds the concentration component for each species
Parameters
----------
species_id : int
species id from the species_indices dictionary
number : float
stoichiometric co-eff of the species
... | 4a9a0cbc22e6d9ecf13c86b10d5d5d56baae06dc | 679,880 |
import numpy
def mp3_doubles(D2, I):
"""Return the doubles contribution to the 3rd order energy."""
dX = (1.0/8.0)*numpy.einsum(
'ijab,abcd,cdij,ijab,ijcd->',
I.oovv, I.vvvv, I.vvoo, D2, D2)
dY = (1.0/8.0)*numpy.einsum(
'ijab,klij,abkl,ijab,klab->',
I.oovv, I.oooo, I.vvoo, ... | 59837716b7296afe85cfacd731338a0c6d589ef1 | 679,881 |
import re
def extractOutputOrAction(keyCode1, xmlInput):
"""Sometimes a key starts an action, this will allow replacement of those keys"""
regularExpression = (
r"code=\"" + str(keyCode1) + '"' + r"\s+(output=\".*?\"|action=\".*?\")"
)
output1 = re.search(regularExpression, xmlInput)
if ou... | 7f8cb2c6d0f89de0c10c88af802dc37c2ae5f352 | 679,882 |
from typing import List
def _merge(nums: List[int], left: int, mid: int, right: int,
aux: List[int]) -> int:
"""
Helper function to merge the given sub-list.
:param nums: list[int]
:param left: int
:param mid: int
:param right: int
:param aux: list[int]
:return: int
"""
... | f1549f9beaa068275a82869363ca9db19b3cbb2b | 679,883 |
import uuid
def gen_id(type_, name):
"""Generate a random UUID if name isn't given.
Returns:
string
"""
if name is None:
rand_id = uuid.uuid4()
rand_id = str(rand_id)[:8]
name = type_ + '_' + rand_id
return name | b11d59a2f9f3f488842ba6fa8d4f7b6b9d0d3454 | 679,884 |
def read_from_text(text):
""" Function to extract key words from the sentence """
read = []
for t in text.split(' '):
try:
read.append(float(t))
except ValueError:
pass
return read | a2339ed370d17cfb245b054123241399fa80708d | 679,885 |
def int_to_byte(n):
""" convert int into byte """
return n.to_bytes(1, byteorder='big') | 2be4943d138f27e893cbc8a5eb9b11f480a8fce3 | 679,886 |
def get_coords_from_line(line):
""" Given a line, split it, and parse out the coordinates.
Return:
A tuple containing coords (position, color, normal)
"""
values = line.split()
pt = None
pt_n = None
pt_col = None
# The first three are always the point coords
if l... | 3058feec12847b11b7ffcddb2856bd734e72f109 | 679,887 |
def get_dataset_names(datasets):
"""
Returns the names of the datasets.
Parameters
----------
datasets : tuple
tuple of datasets
Returns
----------
dataset_names : list
list of dataset names
"""
dataset_names = []
for index_dataset, (dataset_name, df_data) in enumerate... | 88d92b1d982e8279a98f1cfd7d10af6fe626d36d | 679,889 |
def angle_offset(base, angle):
"""
Given a base bearing and a second bearing, return the offset in degrees.
Positive offsets are clockwise/to the right, negative offsets are
counter-clockwise/to the left.
"""
# rotate the angle towards 0 by base
offset = angle - base
if offset <= -180:... | 8d71b88c1f96983fc04c22530f4d141bca7a6f3f | 679,890 |
def is_leaf(node):
"""Checks whether the :code:`node` is a leaf node."""
return not isinstance(node, list) | bfcf8d20448d7ec15b2a51c7c47da39a4ec13f7d | 679,891 |
def raiz(x, y):
"""
La raíz enésima de un número.
.. math::
\sqrt[y]{x}
Args:
x (float): Radicando.
y (float): Índice.
Returns:
float: La raíz.
"""
return x**(1/y) | ab3fab67dff08de02ecf1e51692099e519e902d0 | 679,892 |
def is_tar(name):
"""Check if name is a Tarball."""
return (
name.endswith(".tar") or name.endswith(".gz") or name.endswith(".bz2")
) | 4aa5f88ed2412f625d57ba2395d1e2cc932a37a6 | 679,893 |
def format_date(datestring):
"""Convert a long iso date to the day date.
input: 2014-05-01T02:26:28Z
output: 2014-05-01
"""
return datestring[0:10] | 920c37e0d808af3ca79d34b15dc50885933f6bfe | 679,894 |
def diste(p1, p2):
"""
Returns euclidean distance divided by the default NYC speed. Admissible.
Parameters: (p1, p2)
p1 - (lat, lon)
p2 - (lat, lon)
"""
return (pow(abs(p1[0] - p2[0]), 2) + pow(abs(p1[1] - p2[1]), 2)) ** 0.5 / 65 | eeb64707f32b2305bbf011d450588f40a341bb4a | 679,895 |
def adaptative_myers_k(sc_len,edit_frac):
"""Calculate the edit distance allowed as a function of the read length"""
return(float(sc_len*edit_frac)) | 05f3d44dca375791de6fc4e7dfbbbd37624dfaee | 679,896 |
def unescape(str):
"""Undoes the effects of the escape() function."""
out = ''
prev_backslash = False
for char in str:
if not prev_backslash and char == '\\':
prev_backslash = True
continue
out += char
prev_backslash = False
return out | 611a9496def48b2752db71fd5854e5b560ed24e5 | 679,897 |
import os
import re
def display_diff(files, diff):
"""Format header differences into a nice string
Parameters
----------
files: list of files that were compared so we can print their names
diff: dict of different valued header fields
Returns
-------
str
... | 6c2d421edf0cd90bed928037180331340e5194c9 | 679,898 |
import argparse
def parse_args():
"""parse arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--src-path', help='test xml source path')
parser.add_argument('--src-xml', help='test xml source file')
parser.add_argument('--dst-path', help='the copy dest path')
args = parser.pa... | 843ee928881916115b0b387d60b5fbf7471a1311 | 679,899 |
import glob
import os
def get_latest_weights(weights_dir):
""" Gets latest weights file and var pickle from specified directory. """
dir_contents = glob.glob(weights_dir + '/*')
while dir_contents:
latest = max(dir_contents, key=os.path.getctime)
weights_file_list = glob.glob(latest + '/dd... | d92d90991d9e9b564fbe0f8efee91fc2e19b946b | 679,900 |
import torch
def _train_step_ddc(x_batch, y_batch, model):
"""
Single training step for DDC.
Args:
x_batch: Batch of inputs
y_batch: Batch of labels
model: ddc.DynamicDropConnect object
Returns:
Model output, batch loss
"""
# Compute forward pass o... | bd2a6b7ae65f684582b32ce7bb5a4a8944ca58e9 | 679,901 |
from typing import Any
import argparse
def parse_args(prog: str, argv: list) -> Any:
"""Verbose will be determined here"""
parser = argparse.ArgumentParser(prog)
parser.add_argument(
"-t", "--test", action="store_true", dest="TEST", help="run test program"
)
parser.add_argument(
"-... | debcc633c3efb2f2098cc120b02ab7102922ddaa | 679,902 |
def compare_file(file1, file2):
"""
Compare two file, line by line
"""
line1 = True
line2 = True
with open(file1, 'r') as f_1, open(file2, 'r') as f_2:
while line1 and line2:
line1 = f_1.readline()
line2 = f_2.readline()
if line1 != line2:
... | 5bdf12a2a73dba61f52d9d7b01aa674fb50ca47a | 679,903 |
def get_bar_order(plot_params):
"""
Gets which cumulative bars to show at the top of the graph given what level
of detail is being specified
Parameters
----------
plot_params: dict
Dictionary of plotting parameters. Here, `all_pos_contributions`,
`detailed`, `show_score_diffs`, ... | f727568ebf3449219c5651a4680e89cda0c9d7b0 | 679,904 |
def gen_tc_objects(group_types, batch, tc_type, items, gen):
"""Builds new dictionary for groups and indicators to be added to batch."""
if not isinstance(items, list):
items = [items]
tc_type = tc_type.title()
tc_objects = list()
nf = 'summary'
obj_type = 'indicator'
if tc_type in g... | 5e51f689734af8854119ee6e96742efa7f68a628 | 679,905 |
def words():
"""Load test data fixture."""
words = ["cake", "apple", "banana", "cherry", "chocolate"]
return words | cca6ddc25745e0ea43799beee980f9bd54bbfba1 | 679,906 |
def is_overlapped(peaks, chrom, start, end):
"""
check if the promoter of a gene is overlapped with a called peak
:param peaks:
:param chrom:
:param start:
:param end:
:return:
"""
for temp_list in peaks[chrom]:
if (temp_list[0] <= start and start <= temp_list[1] ) or (temp_l... | e5b904e97fe3d4cc0c2e391085a416a7c0302384 | 679,907 |
def tags2parse_results(dicom):
"""Return the expected results that the tags2parse
fixture should return for the dicom fixture.
"""
return {
"ImageLaterality": "L",
"SopInstanceUUUUID": dicom.SOPInstanceUID,
"SopClazzUUID": "foobar",
"study_uid": dicom.StudyInstanceUID,
... | 78647408788b028197687cf9e87aedb30e22b819 | 679,908 |
def totalMenuItems (theDictionary):
"""Calculates the total number of items available on menu
(theDictionary).
:param dict[str, float] theDictionary:
Dict containing menu items as keys and respective prices as
prices.
:return:
Total number of items on the menu.
:rtype: int
... | 00afacf393a216ccd4e20d81a6c2fc31939d1564 | 679,909 |
import builtins
def _ipython_namespaces(ip):
"""
Return the (global) namespaces used for IPython.
The ordering follows IPython convention of most-local to most-global.
@type ip:
C{InteractiveShell}
@rtype:
C{list}
@return:
List of (name, namespace_dict) tuples.
"""
... | a135a8f44bc5576f41b4df7604ccda21af78738d | 679,910 |
from typing import Dict
from typing import Any
def _form_response_get_field(form_response: Dict[str, Any], filed_num: int):
"""
Extracts the value of a certain field from the Mephisto response.
"""
frd = form_response['task_data']
k = 'form_responses'
if k in frd and len(frd[k]) and (filed_num... | 80fd2baba62f18c16283a6ae771723514ed3b8fb | 679,911 |
def emptyCoords():
"""Returns a unit square camera with LL corner at the origin."""
return [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]] | b4fc6bdb99ec8bedbbad070024a48c1a2d63a505 | 679,912 |
def _pad_name(name, pad_num=10, quotes=False):
"""
Pad a string so that they all line up when stacked.
Parameters
----------
name : str
The string to pad.
pad_num : int
The number of total spaces the string should take up.
quotes : bool
If name should be quoted.
... | 19469843abea1c0999dbf2e539ccf0aa60dd232e | 679,914 |
import torch
def final_t(tx, input_cropped1, real_point):
"""
Accepts tx, the transformation mtx, the input_cropped points and the real_points (ground truth)
:param : tx : bs x 4 x 4
:input_cropped1_tmp : (bs, 1, partial_num, 3)
:real_point : (bs, 1, crop_num, 3)
"""
bs = input_cropped1.sh... | a0d2b436c76ee494a6ba94b5d592320276c93823 | 679,915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.