content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import argparse
def parse_args():
"""
command args
"""
parser = argparse.ArgumentParser(description='Model training')
# params of training
parser.add_argument(
"--config", dest="cfg", help="The config file.", default=None, type=str)
parser.add_argument(
'--batch_size',
... | c771b90a0b266f10ab069c727c619a543231c033 | 679,021 |
def c(x):
"""首字母大写"""
return x.title() | 7055e5da2ee6c724adf27bbe9d993f52c2ba13fe | 679,022 |
def mark_paragraphs(txt: str) -> str:
""" Insert paragraph markers into plaintext, by newlines """
if not txt:
return "[[]]"
return "[[" + "]][[".join(t for t in txt.split("\n") if t) + "]]" | 2453873bf4508a910640f503f872a9e520de618d | 679,023 |
def any(seq, pred=None):
"""Returns True if pred(x) is true for at least one element in the iterable"""
for elem in filter(pred, seq):
return True
return False | 3f878aeceb4f924b5209738f6336e674feb39209 | 679,024 |
def box_decoration_break(keyword):
"""``box-decoration-break`` property validation."""
return keyword in ('slice', 'clone') | c42e9ed127825c14d2a11cd97483c76c6a96f75c | 679,025 |
def pow_mod2(n, k, mod):
"""
Exponentiation by squaring
https://atcoder.jp/contests/atc002/tasks/atc002_b
:return: n ** k
"""
r = 1
while k > 0:
if k & 1:
r = r * n % mod
n = n * n % mod
k >>= 1
return r | af044244fcb5f8a5da2fb4f759bbfddbfb01de6d | 679,026 |
import os
def tag_scan(folder, categories):
""" Scan all existing blog articles and extract the tags """
# print(folder)
results = []
for category in categories:
# print(category)
path = os.path.join(folder, category)
blog_files = [
f for f in os.listdir(path) if f.... | 1efc7989678b389254cb2874e67b0187532b763f | 679,027 |
def vectorize(tokens, vocab):
"""
Covert array of tokens, to array of ids
Args:
tokens (list): list of tokens
vocab (Vocab):
Returns: list of ids
"""
ids = []
for token in tokens:
if token in vocab.tok2id:
ids.append(vocab.tok2id[token])
else:
... | da0c86638f898cf1fff594a3e85b9988a79cd9d3 | 679,028 |
def generate_symbol_definitions_direct(symbols, prefix):
"""Generate a listing of definitions to point to real symbols."""
ret = []
for ii in symbols:
ret += [ii.generate_rename_direct(prefix)]
return "\n".join(ret) | 50eed2e86d50462dcb4c16ed335692422349f85c | 679,029 |
import re
def cleanOfSpaces(myString):
"""Clean a string of trailing spaces"""
myString = re.sub("^( )+", "", myString)
myString = re.sub("( )+$", "", myString)
return myString | 587945d3afd294622b5a407271e2785a2ac4dd1e | 679,030 |
def get_build_os_arch(conanfile):
""" Returns the value for the 'os' and 'arch' settings for the build context """
if hasattr(conanfile, 'settings_build'):
return conanfile.settings_build.get_safe('os'), conanfile.settings_build.get_safe('arch')
else:
return conanfile.settings.get_safe('os_b... | 0411ba597fc770bbc6a8c77da27c33b87d32857c | 679,031 |
def observe_rate(rate, redshift):
"""Returns observable burst rate (per day) from given local rate
"""
return rate / redshift | 13be6db3b3db0763a73be2b8381acb98f6f0ad54 | 679,033 |
def add_security_headers(resp):
"""Add headers to routes
See also:
- <https://content-security-policy.com>
- <https://flask.palletsprojects.com/en/2.0.x/security/>
- <https://scotthelme.co.uk/tough-cookies/>
Some of these may be redundant with CSP? Hard to keep track.
"""
headers = {
... | 83611f3472c91c17adc1a6213dbd94a9a744753c | 679,034 |
import os
import json
def read_json(path_to_json = 'Inż/'):
"""
Reads jsons in the specified dir
Parameters
----------
path_to_json : string
Returns
-------
List of jsons.
"""
data = []
for file_name in [file for file in os.listdir(path_... | b7cef140f80869c7504782abc44dd4a698ffb3a4 | 679,035 |
from typing import Counter
def find_occurrences(number_list):
"""Finds how many times every number in a list occurs."""
counter = Counter(number_list)
occurrences = counter.most_common()
return occurrences | 26c6931d7652d2f60469c36ae6b9c29c3bcb49a9 | 679,036 |
def add_vectors(v1, v2):
"""
Adds 2 vector
:param v1: vector 1
:param v2: vector 2
:return: v1 + v2
"""
return tuple([v1[i] + v2[i] for i in range(0, len(v1))]) | 491448bd744638af2ee8b1382d6b4797f29578ed | 679,038 |
def _get_issue_tracker(obj):
"""Get issue_tracker dict from obj if dict is based on existing tracker"""
if not obj:
return None
ret = obj.issue_tracker
if not ret.get('_is_stub'):
return ret
return None | 8e8d490f48d51be88706bf83121c4055c46ac5fd | 679,039 |
def instancer(_class):
"""
Create a dummy instance each time this is imported.
This serves the purpose of allowing us to use all of pandas plotting methods
without aliasing and writing each of them ourselves.
Parameters
----------
_class : object
Returns
-------
object
... | 7411888d1051cc9cdbe5c784584862fd0e83b2b9 | 679,040 |
import random
def lipsum(count=50):
"""
This function generates lorem ipsum junk, use with caution ;)
"""
lipsum = """
Donec ultrices ultricies libero, et tristique dolor euismod et. Cras volutpat nulla in turpis consequat et dignissim nunc rhoncus. Class aptent taciti sociosqu ad litora t... | a80a3e256426b913f950c5f0b192e716392f931b | 679,041 |
import random
def ordered(parent1, parent2, point=None):
"""Return a new chromosome using ordered crossover (OX).
This crossover method, also called order-based crossover, is suitable for
permutation encoding. Ordered crossover respects the relative position of
alleles.
Args:
parent1 (Li... | 11d551c79a92b3f592b223a08c2d177eb2c26dd2 | 679,042 |
def check_batch_shape(images, batch_size):
"""
Image sizes should be the same width and height
"""
shapes = [image.shape for image in images]
if len(set(shapes)) > 1:
raise ValueError("Images don't have same shape")
if len(shapes) > batch_size:
raise ValueError("Batch size hi... | 95227e8d4a02709aca9bc64f06964ced8e312eac | 679,043 |
def get_from_dict( d, **kw ):
"""
crea un nuevo dicionario usando el kw
la llave del kw es la llave del dicionario
y el valor de kw es el nombre de la nueva llave
Parameters
==========
d: dict
kw: dict
Examples
========
>>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' }
>>>ge... | 83e70b4686750da940cd121dd0e884e549af96ad | 679,044 |
from optparse import OptionParser
def process_args(just_print_help = False):
"""
Processes the command line arguments o FITSCombine.py data reduction script.
@param just_print_help: will print help
@type: boolean
@return: parsed commmand line options
"""
parser = OptionParser()
pa... | 38f3b7ff9eb9c2657a69565a74eee66a2f104a68 | 679,045 |
def _weighted_sum(*args):
"""Returns a weighted sum of [(weight, element), ...] for weights > 0."""
# Note: some losses might be ill-defined in some scenarios (e.g. they may
# have inf/NaN gradients), in those cases we don't apply them on the total
# auxiliary loss, by setting their weights to zero.
return su... | 2fd019caacb8fa36df676dae27243e2962c2cb4a | 679,047 |
def rh_from_avp_svp(avp, sat_vp):
"""
Calculate relative humidity as the ratio of actual vapour pressure
to saturation vapour pressure at the same temperature.
See Allen et al (1998), page 67 for details.
:param avp: Actual vapour pressure [units do not matter so long as they
are the same ... | 8ea0832133bae4705371ee98f2aaff35847cb92e | 679,048 |
def identifier(frame):
""" A string identifier from a frame
Strings are cheaper to use as indexes into dicts than tuples or dicts
"""
if frame is None:
return 'None'
else:
return ';'.join((frame.f_code.co_name,
frame.f_code.co_filename,
... | 1c9523c627404bc6418f33c741a956c466b67d0b | 679,049 |
def condense(S, S_tilde, graph, sorted_snv, psi):
""" Condensation step in the algorithm. Condenses parents and children according to OR or AND tree in a greedy way."""
# Create new entry in graph for the condensed node
item = tuple(sorted(S + S_tilde))
graph[item] = {}
graph[item]['parents'] = gra... | 5a74c9ae9fe61508da743d1b0901f3f9d734f3ad | 679,050 |
def get_name_strings(windows):
"""Format a list of tuples representing genomic windows (chrom, start, stop)
as a list of UCSC-like location strings "chrom:start-stop"
:param list windows: List of tuples in the format (chromosome, start_coord, stop_coord)
:returns: List of UCSC formatted location string... | a3ed86fb9cf1ebc0f7662556f00f01499c9063b1 | 679,051 |
def fibonacci(n):
"""n is the index in the fibonacci sequence."""
assert n >= 0 and int(n) == n, 'The number must be a positive integer only'
if n in [0, 1]:
return n
else:
return fibonacci(n-1) + fibonacci(n-2) | a781c52c709d488c5f3ff71f87a194edad23b17d | 679,052 |
import torch
def sigmoid_mean_and_variance(gate_mean,gate_std,K=50):
""" assumes input is of shape (a,b,c), computes E[Sigmoid(z)] and Var[Sigmoid(z)]
for z ~ N(gate_mean,gate_std)"""
icdf = torch.distributions.normal.Normal(gate_mean[None], gate_std[None]).icdf
unif = ((torch.arange(K).float().to... | f860f69bb21f91c625866abb246716c300f2f5da | 679,053 |
def read_file(file_name):
"""
Read a file and store all the data to a string
then splits all the data with the criteria '\r\n' as each tweet ends
with that and so it is easier to identify
"""
split_criteria = r'\r\n"'
with open(file_name, 'r') as fr:
all_data = fr.read(... | e301053dbb8421b489dfaab9801c1dff7964cec8 | 679,054 |
import numpy
def chi_square_distance_numpy(object1, object2):
"""!
@brief Calculate Chi square distance between two vectors using numpy.
@param[in] object1 (array_like): The first vector.
@param[in] object2 (array_like): The second vector.
@return (float) Chi square distance between two objects.... | 0c27f8bbf0c93442852fae37876a82c38a12e171 | 679,055 |
from datetime import datetime
def str_to_timestamp(time_as_str, time_format) -> float:
"""转换时间字符串为unix时间戳
Args:
time_as_str: 时间字符串, 比如: 2019-09-10 15:20:25
time_format: 时间格式, 比如: %Y-%m-%d %H:%M:%S
Returns:
unix时间戳, 类型: float
"""
datetime_ = datetime.strptime(time_as_str, ti... | f7a4b9458533a32f2e9ebe21645aa11928233ca2 | 679,056 |
import os
def make_output_path(**kwargs):
""" Build the output path for a particular set of data
"""
kwargs['ordinal_str'] = "%06i" % kwargs['ordinal']
return os.path.join(kwargs.get('root_folder_out', '.'),
kwargs['image_type'],
"MC_{date}_{ordinal_str}... | 018938f8b5fdd4e8c69ccc71f7f938421117bbe6 | 679,057 |
from typing import OrderedDict
def remove_signature_parameters(s, *param_names):
"""
Removes the provided parameters from the signature s (returns a new signature instance).
:param s:
:param param_names: a list of parameter names to remove
:return:
"""
params = OrderedDict(s.parameters.it... | d6cd0a9f5da055a4e278915c892c730eb04ee36a | 679,059 |
def write_identifier_section(rslt):
"""This function prints the information about the estimation results in the output
file.
"""
file_ = ""
fmt_ = "\n {:<10}" + "{:>10}" + " {:>18}" + "{:>16}" + "\n\n"
file_ += fmt_.format(*["", "", "Start", "Finish"])
fmt_ = (
" {:<10}"
... | fd08e8fc8a466d920f4612353b123b03b43fb56b | 679,060 |
def get_gene_name(line):
"""
Input: A line read in from a txt or csv file from some proteomic data
that contains a 'GN=' part before the gene name
Output: The gene name pulled out of the line
"""
gene = ""
start = line.find("GN=")
while line[start+3] != " ":
gene += line[sta... | 518870057be903f14eab448adad87660622b3f34 | 679,061 |
def frequencies_imp(word_list):
"""
Takes a list of words and returns a dictionary associating
words with frequencies of occurrence
"""
word_freqs = {}
for w in word_list:
if w in word_freqs:
word_freqs[w] += 1
else:
word_freqs[w] = 1
return word_freqs | 78c4628da3a280d621086745849e6260e68176fe | 679,062 |
def xyzproperty(index):
"""Helper function to easily create Atom XYZ-property."""
def getter(self):
return self.position[index]
def setter(self, value):
self.position[index] = value
return property(getter, setter, doc="XYZ"[index] + "-coordinate") | 34536862e3db3d49ac05556b73a171a43fa53e47 | 679,063 |
def transforms_are_applied(obj):
""" Check that the object is at 0,0,0 and has scale 1,1,1 """
if (
obj.location.x != 0 or
obj.location.y != 0 or
obj.location.z != 0
):
return False
if (
obj.rotation_euler.x != 0 or
obj.rotation_euler.y != 0 or
obj.rotation_euler.z != 0
):
retu... | 411a5c0211c6a0b6833352e8566814958a8adaab | 679,064 |
import argparse
import os
def parse_qa(optlist=None):
"""Parse QA options.
This parses either sys.argv or a list of strings passed in. If passing
an option list, you can create that more easily using the
:func:`option_list` function.
Args:
optlist (list, optional): Optional list of argu... | a095fd360b521779a24f7379118e9119933bdb69 | 679,065 |
def get_distinct_values(df, key):
"""Get the distinct values that are present in a given column."""
return sorted(list(df[key].value_counts().index.values)) | 0833a6024f34faa28fb45d73b7ad7e22ac7ba541 | 679,066 |
def get_path_array(node):
"""
Takes an end node and gives you every node (in order) for the shortest path to it.
PARAMS:
node (node): end node
RETURNS:
array[nodes]: every note you need to visit (in order)
"""
if node.shortest_path_via == None:
return [node]
else:
... | 0633fc9bb7e043e57a8356a23807495c7c975d14 | 679,067 |
def regex_for_field(field_name):
"""Machine Type: Flashforge Finder"""
return field_name + ': ?(.+?)\\r\\n' | c3e5c346235abd791044450cb0e961eaa4527c41 | 679,068 |
from typing import Union
from typing import Tuple
import struct
import zlib
def add_dpi_to_png_buffer(image_bytes: bytes, dpi: Union[int, Tuple[int, int]] = 300) -> bytes:
"""
adds dpi information to a png image
see https://stackoverflow.com/questions/57553641/how-to-save-dpi-info-in-py-opencv/57555123#5... | 4611786231f3a8e2263dd3eb7ab329798e167ac8 | 679,071 |
def kwplan(self, wn="", korig="", kxax="", kplan="", **kwargs):
"""Defines the working plane using three keypoints.
APDL Command: KWPLAN
Parameters
----------
wn
Window number whose viewing direction will be modified to be normal
to the working plane (defaults to 1). If WN is a ne... | 586ff35c631916b51ea8092e5f26447ea740fb97 | 679,072 |
def decode_prefix(byte):
"""Decode a byte according to the Field Prefix encoding
scheme.
Arguments:
byte: the encoded representation of the prefix
Return:
fixedwidth: Is the field fixed width (bool)
variablewidth: if not fixed width, the number of bytes
needed to en... | 7808dafcec1dca1dfb28733ccc9822f0b543531e | 679,074 |
import requests
def ct_get_lists(api_token=""):
"""Retrieve the lists, saved searches and saved post lists of the dashboard associated with the token sent in
Args:
api_token (str, optional): you can locate your API token via your crowdtangle dashboard
under Settings... | 6d3e0c5524f217a1c24bc6b7dd02710393e77329 | 679,075 |
import re
def cols_possible_nums(df, cat_cols, threshold = 5):
""" Return column names if column item are in the following format:
*) ' xx.x% '
==> Note: The regex search should return True/False accordingly
for the following case:
{'12.323%': True,
... | 22c988578f9c3e8353c7d32c521a050f60ab5a53 | 679,076 |
def from_feed(entry):
"""
"""
new_image = "<img src=\"{src}\" title=\"{title}\" class=\"card-img-top\" />"
for link in entry.get('links'):
if link['type'] in ('image/jpeg', 'image/png', 'image/jpg', 'image/gif') and link['rel'] == 'enclosure':
new_image = new_image.format(src=link['... | c9c8d12c2c7a1b9b71c6ec21af3a931e530f34c0 | 679,077 |
def build_endpoint_description_strings(
host=None, port=None, unix_socket=None, file_descriptor=None
):
"""
Build a list of twisted endpoint description strings that the server will listen on.
This is to streamline the generation of twisted endpoint description strings from easier
to use command lin... | c0434271ca8fc73ea81daea3936d827c520adbf9 | 679,078 |
def force_charge_fit(mol, current_rule, match):
"""
Forces the formal charges of a rule to match the formal charges of a molecule.
Parameters
----------
mol: rdkit.Chem.Mol
RDKit molecule object.
current_rule: rdkit.Chem.Mol
RDKit molecule object of rule
match: tuple
... | 885f145a8d5dbadc2c416263dc12180e10bb8ddb | 679,079 |
def dataframe_map_module_to_weight(row) -> int:
"""
Return the weight of a given module from a dataframe row based on the
module level and the module name (since the final project is worth more).
Args:
row (dataframe row): A row from a dataframe containing at least two
... | 13457032a2a5b65d64bf0824ff44cc7258ac6a2e | 679,080 |
def f(s, e):
"""Returns the slope function for the given (start, end) indices f(x_s, x_e)
For example, `f(x₀, x₁, x₂) = f(0, 2)` (starts at 0, ends at 2)"""
if s > e:
raise ValueError('The starting index `s` must be ≤ index `e`')
if s == e:
# End and start are the same, so it's t... | ace73c313b58313bd724b01eff2ca1389ea77c92 | 679,081 |
def drop_fail(rank1_df):
"""
Save only successes.
Parameter:
rank1_df -- Dataframe
Return:
None
"""
rank1_df = rank1_df.loc[rank1_df['succ'] == True]
rank1_df.reset_index(drop=True, inplace=True)
return rank1_df | af5e207884f6bb33b1a04d6fe69c1b11122b4d79 | 679,082 |
def bernardsEstimate(x):
"""
Quick estimate for median ranks of the unreliability of sample data.
*Same as solving the cumulative beta binomial equation for P = 0.50 , but
much less intensive*
``x`` = set of sample data
"""
mr = []
i = 0
while i < len(x):
mr.append(((i+1)-... | 8c4fd2646e8d37feddf48e8a1bc3d335853d5e02 | 679,083 |
import types
from enum import Enum
def default_handler(obj):
"""JSON handler for default query formatting."""
if isinstance(obj, (set, frozenset, filter, types.GeneratorType)):
return list(obj)
if isinstance(obj, Enum):
return obj.value
raise TypeError("Object of type %s with value of ... | 7c4e6fb900172bcfee0334ab3b07ee510ed1ce28 | 679,084 |
def is_foreign_key(col):
"""Check if a column is a foreign key."""
if col.foreign_keys:
return True
return False | e702484a7b87da5ff7ef3e605934b83355d99156 | 679,085 |
from typing import List
def parse_to_table(text: str) -> List[str]:
"""To parse text to list of strings
:param text: input string
:return: list of string
:rtype: List[str]
"""
return [t.strip() for t in text.splitlines()] | bd6254e9f89a4d18293141dd6026710505ac3a8f | 679,086 |
import configparser
import platform
def ini_read_text(file_ini):
""" Konfiguracja FotoKilofa """
# słownik wyjściowy
dict_return = {}
config = configparser.ConfigParser()
config.read(file_ini, encoding="utf8")
try:
text_on = config.getint('Text', 'on')
except:
text_on = ... | 8f01d37e24246379512cc958bacc6f9e3f3efe2f | 679,087 |
def sort_timesheet(func):
"""
Accepts any timesheet that have an array of timesheets with column `start_date`
:param func:
:return:
"""
def inner(*args):
filters = args[0]
data = func(*args)
data.sort(key=lambda x: x['start_date'], reverse=filters.get('date_ascending', Fa... | 01f4e20a09b15b9a7eb769f62b26762092987ed2 | 679,088 |
import os
import sqlite3
def make_dataset_tuple(dataset_files, local_path):
""" Calculates the total size of the dataset and the size of each dataset file """
dataset_file_size_list = []
dataset_size = 0
for dataset_file in dataset_files:
meta_file = os.path.basename(dataset_file) + '.db'
... | 9eb74f4c84c43265569efae72c87b2152b788e42 | 679,089 |
def _build_body(res):
"""
Build the body of the Exchange appointment for a given Reservation.
:type res: resources.models.Reservation
:return: str
"""
return res.event_description or '' | e2f25393560acb803e4002019ca95f27491a6013 | 679,090 |
def mm_as_m(mm_value):
"""Turn a given mm value into a m value."""
if mm_value == 'None':
return None
return float(mm_value) / 1000 | 7c5525b1e16801f67ee76484a2471ac3f6c17c40 | 679,091 |
import itertools
def opt_to_dict(opts):
"""Transform option list to a dictionary.
:param opts: option list
:returns: option dictionary
"""
if isinstance(opts, dict):
return
args = list(itertools.chain.from_iterable([x.split("=") for x in opts]))
opt_d = {k: True if v.startswi... | 905754993871a87861238db12a1ab1338954fb95 | 679,092 |
def verify_positive(value):
"""Throws exception if value is not positive"""
if not value > 0:
raise ValueError("expected positive integer")
return value | 7ee10a0a7d760972e791a0e8b2d0f82e38ec297c | 679,093 |
def get_devices_dict(version, image=None, arch=None, feature=None):
"""Based on version and image, returns a dictionary containing
the folder location and the patterns of the installation files for
each device type
:param version: build version, e.g. 6.2.3-623
:param image: optional, 'Autotes... | 104fb35f8abe4cbe2e6cb1297a3cc778d229d0ed | 679,094 |
import os
def GetAvailableDirectory(suggestion, suggestGiven = True):
"""GetAvailableDirectory(suggestion) -> str
Gets the next available directory name given the suggestion. It returns
suggestion if suggestion does not correspond to a directory and
suggestGiven is True. Othewise it will return... | 7cf4dad54a78ad989f2d5575b2990952918e7553 | 679,095 |
def sort_by_frequencies(alphas):
"""
sorts string by frequencies
"""
items = []
temp = [alphas[0]]
for x in range(1, len(alphas)):
if alphas[x] == alphas[x - 1]:
temp.append(alphas[x])
else:
items.append(''.join(temp))
temp = [alphas[x]]
it... | 35fe61fe10e2fd7c676b1e980a29d51c4aa105e9 | 679,096 |
from bs4 import BeautifulSoup
def new_version_tag():
"""
Creates and returns the following XML tag:
<bqbiol:isVersionOf>
<rdf:Bag>
</rdf:Bag>
</bqbiol:isVersionOf>
:rtype: bs4.Tag
"""
# BeautifulSoup's xml parser requires valid namespace definitions.
re... | ba48cad20be38ce05e30e27ea2b9e126a634200f | 679,097 |
import re
def preprocess_docstring(docstring: str) -> str:
"""
1. Remove cluttered punctuation around parameter references
2. Set '=', ==' to 'equals' and set '!=' to 'does not equal'
3. Handle cases of step two where the signs are not separate tokens, e.g. "a=b".
Note ordered dict since "=" is a ... | 09e600e0975a6fb021802c9b19cd697200458f0c | 679,098 |
import os
def is_pyi_directory_init(filename):
"""Checks if a pyi file is path/to/dir/__init__.pyi."""
if filename is None:
return False
return os.path.splitext(os.path.basename(filename))[0] == "__init__" | ff07ba392e90ca76c2980ab5a68ce02d07e5754c | 679,099 |
def close_enough(v1,v2):
"""
Helper function for testing if two values are "close enough"
to be considered equal.
"""
return abs(v1-v2) <= 0.0001 | d52322cf9ac3bbe17af51af73bf52d8308071c18 | 679,100 |
def dict_to_insert_sql(model={}):
"""
insert模式
"""
return ",".join(model.keys()), ",".join(['%s' for i in model.keys()]) | f23c4f28ece7acdb173797b1e8d78bfb9c263b9a | 679,101 |
from datetime import datetime
def scrapeStart(soup):
""" Scrapes ICO start date from SmithAndCrown listing """
date_string = soup \
.findAll("td")[4] \
.text \
.translate({ ord(x): "" for x in [ "\n", "\r", "\t" ] }) \
.strip()
return datetime.strptime(date_string, "%b %d, %Y") | 09ccd996652adaaad20f0ceeeac54ddbe50660c9 | 679,102 |
def dic2hyperheader(dic):
"""
Convert a Python dictionary into a hypercomplex block header list.
Does not repack status from bit flags.
"""
head = [0] * 9
head[0] = dic["s_spare1"]
head[1] = dic["status"]
head[2] = dic["s_spare2"]
head[3] = dic["s_spare3"]
head[4] = dic["l_spare... | 7d1ef8b585796f9ddebfe966d276c0d7c9d40760 | 679,104 |
def map_onto_scale(p1, p2, s1, s2, v):
"""Map value v from original scale [p1, p2] onto standard scale [s1, s2].
Parameters
----------
p1, p2 : number
Minimum and maximum percentile scores.
s1, s2 : number
Minimum and maximum intensities on the standard scale.
v : number
... | 4b51f16ba7fada925ca9c98169b2064791c7d027 | 679,105 |
def _read_phone(text_path):
"""Read phone-level transcripts.
Args:
text_path (string): path to a transcript text file
Returns:
transcript (string): a text of transcript
"""
# Read ground truth labels
phone_list = []
with open(text_path, 'r') as f:
for line in f:
... | 594377ccf4fd3c10425d05b7c73492f12ddf65b3 | 679,106 |
def check_and_return_json(fn):
"""Helper function. Checks status codes and returns the body in dict format if status code was 200."""
def wrapped(*args, **kwargs):
r = fn(*args, **kwargs)
if r.status_code == 400:
raise ValueError(r.json()['message'])
if r.status_code != 200:
... | 81d44f0c6f658b8028a337af30e1204f59a55f87 | 679,107 |
def pytorch_array_to_scalar(v):
"""Implementation of array_to_scalar for pytorch."""
if v.is_cuda:
v = v.cpu()
return v.detach().numpy() | a920e6f75583e75c9dbd21977bed00ee9f5f3920 | 679,108 |
def getStat(tw, _type):
"""Get stats about Tweet
"""
#logging.info("[<] " + str(datetime.now()) + ':: tweet+getStat')
st = f"ProfileTweet-action--{_type} u-hiddenVisually"
return tw.find("span", st).find("span")["data-tweet-stat-count"] | 4b1c5d0b2c491b3ddb571123a91ababfb8d9e2b2 | 679,109 |
def run_services(
container_factory, config, login, make_salesforce_server, waiter
):
""" Returns services runner
"""
def _run(service_class, responses):
"""
Run testing salesforce server and the tested example service
Before run, the Streaming API server server is preloaded wi... | 54805da41754fd8118a6d7fc37dbe80035bf8ee4 | 679,112 |
def create_tagging_decorator(tag_name):
"""
Creates a new decorator which adds arbitrary tags to the decorated functions and methods, enabling these to be listed in a registry
:param tag_name:
:return:
"""
def tagging_decorator(*args, **kwargs):
# here we can receive the parameters hand... | 26a6b424700dfd79057c1387e108c182e43ef4b5 | 679,113 |
import os
def normalize_source_path(source):
"""
cmake needs this, and nothing else minds
"""
return os.path.normpath(source).replace('\\', '/') | 34704a9316ff5ee5b2f16aaf27ddbc5cb7336063 | 679,114 |
import torch
def scale(x):
""" sample-wise scaling between 0 and 1 of images in batch
:param sample: batch of input images
:return: scaled batch of images
"""
for i in range(x.size(0)):
min = torch.min(x[i, :])
max = torch.max(x[i, :]-min)
x[i, :] = ((x[i, :] - min) / max)... | befb94904ba8acb719fa9d0d4ddc7a2a96cf1aaf | 679,115 |
def update(current_draw, line1, nr_frames, number_of_updates):
""" Draws the vertical line that moves through
the plots from left to right. """
proportion_finished = current_draw / number_of_updates
current_frame = int(nr_frames * proportion_finished)
line_coord = [current_frame, current_frame]... | 304fa27628e472ec190fc063b41468ae62b1dca5 | 679,116 |
def incr(num):
"""
Increment its argument by 1.
:param num: number
:return: number
"""
return num + 1 | fd6e1868329b056edeaeab2741030f973a4ea704 | 679,117 |
from datetime import datetime
def convertDateToUnix(dstr):
"""
Convert a given string with MM/DD/YYYY format to millis since epoch
"""
d = datetime.strptime(dstr, '%m/%d/%Y')
return int((d - datetime.utcfromtimestamp(0)).total_seconds() * 1000) | a477a20575d05bb268f41e302623b0de721d0856 | 679,119 |
def add_tables_data_warehouse(table_name: str, zone: str):
"""
# ADD TABLES ON DATA WAREHOUSE
The main function to save the data into the storage and create a table in the data warehouse.
Parameters
----------
data
The information to be saved on the storage.
file_format : str
... | 3fb8fd8b758e76c640899b57ef82932653bf821d | 679,120 |
def split_text(txt, trunc=None):
"""Split text into sentences/words
Args:
txt(str): text, as a single str
trunc(int): if not None, stop splitting text after `trunc` words
and ignore sentence containing `trunc`-th word
(i.e. each sentence has len <= trunc)... | f900d3b75dc541e1aed1326674939f65fc3b0900 | 679,121 |
def escaped_size(string):
"""
>>> escaped_size(r'""')
6
>>> escaped_size(r'"abc"')
9
>>> escaped_size(r'"aaa\\"aaa"')
16
>>> escaped_size(r'"\\x27"')
11
"""
return len(string) + 2 + string.count('"') + string.count('\\') | a9d4a077783ce06720dc6d758fe2f93e4d887136 | 679,122 |
def get_auth_dict(auth_string):
"""
Splits WWW-Authenticate and HTTP_AUTHORIZATION strings
into a dictionaries, e.g.
{
nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"',
opaque : "34de40e4f2e4f4eda2a3952fd2abab16"',
realm : "realm1"',
qop : "auth"'
}
"""
amap =... | adb2c6dbcea429ae94c133b5b00148236da216e2 | 679,124 |
def build_anthology_id(collection_id, volume_id, paper_id=None):
"""
Transforms collection id, volume id, and paper id to a width-padded
Anthology ID. e.g., ('P18', '1', '1') -> P18-1001.
"""
if (
collection_id.startswith("W")
or collection_id == "C69"
or (collection_id == "D... | 6dd268b3de74a92849a14db99190588e7c7eb36f | 679,125 |
import os
def needs_compile(src, obj):
"""!
Checks if a source file should be recompiled.
\param src The source file path to check for compile
\param obj The object file path the source needs to be compiled to
\return True if the source file should be recompiled, false if not
\thr... | 92b4a1c957c8730910c7bdd657732ac3ab528fab | 679,126 |
from typing import Any
def assert_key_for_scope(scope: str):
"""Checks that a key of the given name and type is present in a config."""
def assert_key(config: dict, key: str, instance: Any) -> None:
if not isinstance(config.get(key), instance):
raise KeyError(f"Missing {key} in {scope}")
... | 55ab2c307b1c81b65cad9d1e7a487983924e008e | 679,127 |
def ensure_list(list_ensured):
""" ensure_list """
return list_ensured if isinstance(list_ensured, list) else [list_ensured] | 9f61aa1f743acdabba186197e2f6661fe452989b | 679,128 |
def get_city_description(city, country, population=''):
"""Print the city and the country"""
if population:
city_description = city.title() + ", " + country.title() + " - population " + population
else:
city_description = city.title() + ", " + country.title()
return city_description | 6db9761b080ba244604252d0747f77c963f55154 | 679,129 |
def BFSUtility(obj,visited,vertex):
"""Utility function for Breadth First Search Algorithm."""
stack = []
subGraph = []
stack.insert(0,vertex)
visited[vertex] = True
while(stack):
subGraph.append(stack.pop())
for nbrVertex in obj.adjList[subGraph[-1]]:
if visited[nbrV... | cd3beec5e9afaa23a8989728957658680422bf23 | 679,130 |
def initialize_object_list(inp, cls):
""" Utility function to return list of objects from a valid input (a single object or list of objects where each object is of the class ``cls``).
If invalid input ``None`` is returned.
:param inp: Input.
:paramtype inp: (list, cls) or cls
:param cls: ... | fd8047b7c0862e02f583ab0b41887b973f04ec16 | 679,131 |
def get_string_before_delimiter(string, delimiter):
"""
Returns contents of a string before a given delimiter
Example: get_string_before_delimiter("banana-kiwi", "-") returns "banana"
"""
if delimiter in string:
return (string[:string.index(delimiter)]).strip()
else:
retu... | 97b5da492834a62c5648f76002e690b659d3ab38 | 679,132 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.