content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_econ_dic(train_word_sequences, tag_sequences_train, tags):
"""
Note: when matching, the text span and tag have been lowercased.
"""
econ_dic = dict()
# exit()
return econ_dic | 0f58f2d5306b4e8d341eef06c2a428005c78f14d | 660,170 |
import sys
from pathlib import Path
import os
import glob
def find_files(directory=None):
"""It finds all the .tif or .shp files inside a folder and
create list of strings with their raw names
:param directory: string of directory's address
:return: list of strings from addresses of all files inside... | 0bdcf4fe2ca2aed520a2b3261519f94fbb2d65bc | 660,171 |
def solve(lst, num, k):
"""In a list <lst> find <num> numbers whose sum amount to <k> and obtain
the product of them.
Recursive generalized 3SUM (k-SUM) algorithm. """
# 1SUM.
if num == 1:
return k if k in lst else None
# Sort list for binary search.
sorted_lst = sorted(lst)
... | 66db8031253cf28a89bb0fb638c14e4226052ae3 | 660,172 |
import argparse
def parse_arguments():
"""
Parse user arguments to modify how the document is generated for tables
:return: parsed args passed by the user or defaults defined below
"""
problem_types = ('analog')
parser = argparse.ArgumentParser(description='Generate shapes to practice measuri... | 8b1f71b20a0c282a62379fd748d1a482a4714975 | 660,174 |
def led2str(buff):
"""
LED format: The eight bits in each byte indicate which segment of the
LED should be turned on (1) or off (0). The relation between the bit
position and the segment is as follows: (note that bit 2 controls the
decimal point to the bottom left of the digit)
--3--
... | 1a8dfc8c1546129ccd9f33b7445ba5cb02503b45 | 660,176 |
def loadw2v(embfile):
"""
To be filled
:param embfile:
:return:
"""
return None | 32fab18d459bcf7cdde78b7223d34b9a83d7961b | 660,177 |
def decode(string):
"""Decode utf-8 hex to utf-8 string
Unfortunately, there is a limit to how many characters Python can display,
and therefore the maximum amount of utf-8 characters it can detect is 1,114,111.
"""
string = string.replace('\\x', '') # remove all '\x'
result = ""
i = 0
... | d95d8c87d776be8f529bf6e51ffe5bde855f7c5d | 660,178 |
def _extract_image(img, x_off, y_off, max_x, max_y):
"""Returns a subsection of the image
Args:
img(numpy array): the source image (with 2 or 3 size dimensions)
x_off(int): the starting X clip position (0th index of image)
y_off(int): the starting Y clip position (1st index of image)
... | 520a72a8b5778e385f93bdfc9d40bec4210b0683 | 660,179 |
def _dict_mixed_empty_parser(v, v_delimiter):
"""
Parse a value into the appropriate form, for a mixed value based column.
Args:
v: The raw string value parsed from a column.
v_delimiter: The delimiter between components of the value.
Returns:
The parsed value, which can either... | b0529b5248fe371f4e6371aa5c7ea9962ac1c928 | 660,180 |
def pow(x, y):
"""Implement `pow`."""
return x ** y | b44cb10e21a95217bea77752660a2b011731e0a6 | 660,181 |
import random
def insert_random_character(s):
"""Returns s with a random character inserted"""
pos = random.randint(0, len(s))
random_character = chr(random.randrange(32, 127))
# print("Inserting", repr(random_character), "at", pos)
return s[:pos] + random_character + s[pos:] | cdbf5b5c28b19f2c408849c903f370af152bdfb8 | 660,182 |
def out(coords, dims):
""" This function recurses through the two lists, adjusting output
if a coord is too big or too small (compared to corresponding dim).
Eg. For coords = (1,3,-2) and dims=(2,2,2), (2,3,4) is returned. """
new_coords = []
for coord, dim in zip(coords, dims):
if coord > ... | 183cfcdf139f25f69e4264fccdacee7a2c8707a2 | 660,184 |
def calc_ifg_delay(master_delay, slave_delay):
"""Calculate the interferometric delay.
Arguments
---------
master_delay : (n,m) ndarray
Matrix containing the atmospheric delay on the master date.
slave_delay : (n,m) ndarray
Matrix containing the atmospheric delay on the slave date.
... | 3fdf12807037c9371f2228c56282b90bab9ac9c3 | 660,185 |
import pathlib
def make_subdirectory(directory, append_name=""):
"""Makes subdirectories.
Parameters
----------
directory : str or pathlib object
A string with the path of directory where subdirectories should be created.
append_name : str
A string to be appended to the directory ... | abf42b0d7f85af9bf6728001eac652de513ffba4 | 660,186 |
def Kt_real_deph(alpha_liq_deph, alpha_cond_deph, sigma_thermpollution_deph):
"""
Calculates the coefficient of heat transfer (Kt).
Parameters
----------
alpha_liq_deph : float
The coefficent of heat transfer(alpha), [W / (m**2 * degrees celcium)]
alpha_cond_deph : float
The coef... | c630f740fb4d295975c4c5b844b0410e0134ec04 | 660,187 |
def strip_2tuple(dict):
"""
Strips the second value of the tuple out of a dictionary
{key: (first, second)} => {key: first}
"""
new_dict = {}
for key, (first, second) in dict.items():
new_dict[key] = first
return new_dict | 20f721da141f75bceb8bfd90d7ab02dbb82a01ce | 660,188 |
def _sparsify_from_mask(X, mask):
"""Make a sparse array even sparser.
Parameters
----------
X : scipy.sparse.csr_matrix
Sparse matrix
mask : scipy.sparse.csr_matrix, bool
Boolean mask expression
"""
S = X.copy()
S.data[mask] = 0.
S.eliminate_zeros()
return S | 40a57cbc435136d663e7e6dac9876aa0233fd2df | 660,189 |
def unnormalize_parameters(normed_parameters, minvals, maxvals):
"""takes in a list of parameters and undoes simple min/max normalization according to min/max values
INPUTS
normed_parameters: length n, containing parameters for a star
minvals: length n, minimum parameter values
maxvals: length n, ma... | f3eae99d765aec6df1e34c03a52f7754374f63ba | 660,190 |
import six
def get_module_defined_k8s_ver(k8s_version_opts, env_name):
"""Return version of Terraform requested in module options."""
if isinstance(k8s_version_opts, six.string_types):
return k8s_version_opts
if k8s_version_opts.get(env_name):
return k8s_version_opts.get(env_name)
if k... | e1930d358cd9a015e09856aae2723d7619067316 | 660,191 |
def toWhitespace(message: str) -> str:
"""encodes morse code into whitespace characters
starts with chr(82139) as a marker
"""
return '{}'.format(chr(8239)) + message.translate(message.maketrans('.-/ ',' \t{}{}'.format(chr(160), chr(8194)))) | 90ffc7dff8d3ecba8d93bf74dadd74fdd854dd8f | 660,192 |
def create_dict(list1, list2, key1, key2):
"""Create list of dictionaries from two lists
"""
list_dict = []
for i in range(len(list1)):
dictionary = {key1 : list1[i], key2 : list2[i]}
list_dict.append(dictionary)
return list_dict | ee83e989ef22925f6db04f0de1078db3c553c965 | 660,193 |
def _num_starting_hashes(line: str) -> int:
"""Return the number of hashes (#) at the beginning of the line."""
if not line:
return 0
for n, char in enumerate(line, start=0):
if char != "#":
return n
return len(line) | 915ed7fbb971f14bcc6795f95d674afe43d41f32 | 660,194 |
def scrub(text):
""" return a string with targeted non-ascii characters replaced, all others replaced with *, white space trimmed """
# """ return a string with non-ascii characters and consecutive spaces converted to one space """
# if not text:
# return ''
# # text = ''.join([i if 31 < ord(i) ... | 8e6ab8cee93ac944e5814fdfff30803a6350f397 | 660,195 |
def greedy_coloring(adj):
"""Determines a vertex coloring.
Args:
adj (dict): The edge structure of the graph to be colored.
`adj` should be of the form {node: neighbors, ...} where
neighbors is a set.
Returns:
dict: the coloring {node: color, ...}
dict: the ... | 23fd23fafabb0bbb5b7facde33ebc7b3c7be6734 | 660,196 |
def position_side_formatter(side_name):
"""
Create a formatter that extracts and formats the long or short side from a
Position
Args:
side_name: "long" or "short" indicating which side of the position to
format
"""
def f(p):
"""The formatting function for the ... | b286d2fee11788934b62522f1fa4492ecd2586e5 | 660,197 |
import csv
def read_csv(filename):
"""
Reads contents of a given file
:param filename:
:return: CSV data
"""
with (open(filename, "r")) as csvfile:
rows = []
csv_reader = csv.reader(csvfile, delimiter=",", quotechar="\"")
for row in csv_reader:
rows.append(r... | 0aa0db799fd3693fa75d25078b0d649c40b0e617 | 660,198 |
import requests
import sys
def get_task_status(ip_address, task_id, token, cluster_id):
"""
Check status of the task submitted to Console
:param ip_address: Console to connect
:type ip_address: str
:param task_id: check the status for
:type task_id: str
:param token: Auth token
:type t... | 15038ebefcea570ebd7c85b5dddb0b535e57a134 | 660,199 |
import re
def setWC(string):
"""
Replaces `WC(a, b)` by `WC('a', S(b))`
"""
p = r'(WC\((\w+), S\(([-+]?\d)\)\))'
matches = re.findall(p, string)
for i in matches:
string = string.replace(i[0], "WC('{}', S({}))".format(i[1], i[2]))
return string | aead8401e0150e36570da8481ea8e4ab6139c761 | 660,200 |
import optparse
def runtime_options():
"""Return a list of optparse.Option objects for any runtime values used
by this module."""
options = [
optparse.make_option("--worker-model", action="store",
help=("controls worker model. Valid values are "
"'inline' and 'processes'.")... | 4d47289250d5bf0865810f1f3db6d993812796db | 660,201 |
def population_archiver(random, population, archive, args):
"""Archive the current population.
This function replaces the archive with the individuals
of the current population.
.. Arguments:
random -- the random number generator object
population -- the population of individual... | dcb60d7aff2f0d5cb6e5032e8831659f6ab1ff51 | 660,203 |
def preprocess(df):
"""This method takes the target dataframe and preprocesses it into vectors for the Algorithm to handle.
Will return a CRS sparse matrix for the matrix operations to be calulated on in the Tensorflow graph.
"""
df = df[['PROPNAME', 'ADDRESS', 'RESNAME']]
return df | d88075086d4d53e663cfdb118edac536704fbfc8 | 660,204 |
def get_mean_score(rating_scores):
"""Compute the mean rating score given a list.
Args:
rating_scores: a list of rating scores.
Returns:
The mean rating.
"""
return sum(rating_scores) / len(rating_scores) | c6c5cc165ed078961c779ccff23db8d948e1c455 | 660,205 |
import os
def buildinfo_file_name(prefix):
"""
Filename of the binary package meta-data file
"""
name = os.path.join(prefix, ".spack/binary_distribution")
return name | 00aa52de24bc50f0ee21883db8f717d6c7b09f29 | 660,206 |
def get_single_addon(addons_dir, addon_name):
"""
:param addon_name: Name of Addon
:return: The changed addon path
"""
target_addon = None
for addon in addons_dir.iterdir():
if addon.name == addon_name:
target_addon = addon
break
return target_addon | 71aa47b0a5fdde3144d6501fa751e0de54c1620f | 660,207 |
def tstv(ts, tv):
"""
Calculate ts/tv, and avoid division by zero error
"""
try:
return round(float(ts) / float(tv), 4)
except ZeroDivisionError:
return 0 | a9a876ef2d8cddae3a8844ac52a611abcbaf4ddd | 660,208 |
def is_convolution_or_linear(layer):
""" Return True if `layer` is a convolution or a linear layer
"""
classname = layer.__class__.__name__
if classname.find('Conv') != -1:
return True
if classname.find('Linear') != -1:
return True
return False | c7bbaedf40aa6b34079eac068bf50ed90734e819 | 660,209 |
def is_none(obj):
"""Method to check if object is None.
Args:
obj : The object.
"""
return bool(obj is None) | a7a594e80bb442c6956fa1c19d0a3e6562ae765f | 660,210 |
def was_last_response_B(last_keypress):
"""this function returns last_response_chose_delayed as True or False,
taking into account the location of the immediate and delayed rewards.
last_keypress is either 'left' or 'right'
"""
if last_keypress == "left":
last_response_chose_B = False
el... | 61a3c54e88c049ebef24144c5cec4224c29391ca | 660,211 |
import requests
from bs4 import BeautifulSoup
def get_chapters_raw(page_url):
"""Return BeautifulSoup object of chapter page"""
r = requests.get(page_url)
return BeautifulSoup(r.text, "lxml") | 02c0653f8369ad74aa6f308c065a9e26ec2c47e5 | 660,212 |
def cli(ctx, job_name="", no_wait=""):
"""Delete orphans Drupal feature nodes
Output:
status
"""
return ctx.gi.feature.delete_orphans(job_name=job_name, no_wait=no_wait) | a3bfad4a7ec6c3f80ffb20c70663e86da9748dde | 660,213 |
def generated_choices(ClassName, field_name):
"""returns the values of the field in a list of tuples"""
return_choices = []
picked_valued = ClassName.objects.values(field_name)
try:
for x in picked_valued:
return_choices.append((x[field_name], x[field_name]))
except:
retu... | 23c10f6f5524996e2d4090391c09ecedc332596c | 660,214 |
import argparse
def parse_arguments():
"""
Parses command line arguments and returns them
:return Parsed arguments in an argparse Namespace object
"""
parser = argparse.ArgumentParser(description='Data scraper for rl-brain')
parser.add_argument('-n', '--num_matches', metavar='NumberOfMatches'... | 370a4b0502ce682649148ca970dc83c4f421008c | 660,215 |
def zero_if_less_than(x, eps):
"""Return 0 if x<eps, otherwise return x"""
if x < eps:
return 0
else:
return x | 67ee0c584eef4432c683b3b568f92605ff55b297 | 660,216 |
def serialize(func, **args):
"""
Serailizes a function that returns a dataframe
"""
data = func(**args)
if (hasattr(data, 'to_json')):
return data.to_json(orient='records', date_format='iso', date_unit='ms')
else:
return data | a1a439f1ecc9ba1116f4e0d53b54ba690d9b1cb7 | 660,217 |
import ast
def custom_tuple(s):
"""
tuple with custom split string.
"""
s = s.split('x')
s = ','.join(s)
return ast.literal_eval(s) | 9f256a791013e172cbd0476eaace2f82bd69e73e | 660,218 |
import os
def getSnapNumToZMapGiz(directory=""):
"""
Searches directory specified and returns a map of snapshot number to
redshift.
Assumes file names are of format GIZMO-NewMDCLUSTER_0001.snap_119.z0.221...
Directory must only contain files with names of this format.
Parameters
--------... | 971539dddf63313a5546f985d956fe4ec65069f6 | 660,219 |
def test_integrity(param_test):
"""
Integrity test has moved to unit_testing/ and is run with pytest
"""
return param_test | 79dfc427e4978d271a57329e4d6a1a995915d775 | 660,220 |
import json
def deserialize(response):
""" deserialize response and look for errors """
deserialized_response = json.loads(response.data)
if 'errors' in deserialized_response.keys():
data = None
errors = deserialized_response['errors'][0]['detail']
else:
data = deserialized_r... | 09583c1a3d994daa9cd1fc0801fbd88d9f2b1c5a | 660,221 |
import ast
def make_obj_for_uploading_return_obj_to_s3(return_object_list):
"""
s3_client.upload("Return")
"""
upload_obj_list = []
for each_input_param in return_object_list:
download_obj = ast.Expr(
value=ast.Call(
func=ast.Attribute(
value... | c54ed4efdf1538d58df5af3620afa9c8aa4e2a30 | 660,222 |
def addPiles(a, b):
"""returns the resulting sandpile of adding sandpile a to sandpile b
and topple afterwards"""
top_left = a[0][0] # assign variable to each cell of pile
top_mid = a[0][1]
top_right = a[0][2]
mid_left = a[1][0]
mid_mid = a[1][1]
mid_right = a[1][2]
bot_left = a... | 42ee19e95a3c2df36fae6c705978a60886a92f73 | 660,223 |
def semver_cmp(ver_1, ver_2):
""" Compares 2 semver tuples, return True if ver_1 > ver_2, False otherwise
"""
for i in range(0, 3):
if ver_1[i] > ver_2[i]:
return True
elif ver_1[i] < ver_2[i]:
return False
return False | d0738bc26adbaf9e823a3034af2dede57aad969e | 660,224 |
import math
def date_to_jd(year,month,day):
"""
Convert a date to Julian Day.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
year : int
Year as integer. Years preceding 1 A.D. should be 0 ... | 2b50233e64361398dd856e237ce791a4aac6b870 | 660,225 |
def create_masked_lm_predictions_force_last(tokens):
"""Creates the predictions for the masked LM objective."""
last_index = -1
for (i, token) in enumerate(tokens):
if token == "[CLS]" or token == "[PAD]" or token == '[NO_USE]':
continue
last_index = i
assert last_index > 0... | e6e2a5e774bfd419bc01f71d5113d0d0adf9e60b | 660,226 |
from typing import Tuple
def deserialize_ecdsa_recoverable(signature: bytes) -> Tuple[int, int, int]:
"""
deserialize recoverable ECDSA signature from bytes to (r, s, recovery_id)
"""
assert len(signature) == 65, 'invalid length of recoverable ECDSA signature'
recovery_id = signature[-1]
asser... | b47bd8e2f117048057a1a03395f78d61a1509346 | 660,227 |
def semi_loss_func(ac, full_ob, semi_dataset, is_relative_actions=False):
"""
get the L2 loss between generated actions and semi supervised actions
:param ac: the semi supervised actions
:param full_ob: the full observations of the semi supervised dataset
:param semi_dataset: the semi supervised dat... | 6718b42cbe86ea75d1593694704ac6a7ffd881f8 | 660,228 |
def make_bag_of_words(df, stemmed):
"""
Create bag of words model.
"""
print("\tCreating Bag of Words Model...")
very_pos = set()
slightly_pos = set()
neutral = set()
slightly_neg = set()
very_neg = set()
# Create sets that hold words in headlines categorized as "slightly_neg" or "slightly_pos" or etc
for... | 40ede3a3bc8df9de5822e43f58ef1e1b765d19be | 660,229 |
def index_generation(crt_i, max_n, N, padding='reflection'):
"""Generate an index list for reading N frames from a sequence of images
Args:
crt_i (int): current center index
max_n (int): max number of the sequence of images (calculated from 1)
N (int): reading N frames
padding (s... | 559f6bb3278de6e920396489b4018dbc80e5f065 | 660,230 |
def NoTestRunnerFiles(path, dent, is_dir):
"""Filter function that can be passed to FindCFiles or FindHeaderFiles in
order to exclude test runner files."""
# NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which
# are in their own subpackage, from being included in boringssl/BUILD files.
re... | 3401046d340c8746b2fd1ee5b49ac47bfa97566c | 660,231 |
def dfs(graph, start):
"""
- stack
"""
visited = []
stack = [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.append(vertex)
# stack.extend(graph[vertex] - set(visited))
stack.extend(graph[vertex])
return visited | b4d37a8a28155eca9b58ba14e747110fa5092a5f | 660,232 |
import numpy
def dt_(typ):
""" return data type conversion
"""
np_typ = numpy.dtype(typ)
if numpy.issubdtype(np_typ, numpy.bool_):
typ = numpy.dtype('bool')
elif numpy.issubdtype(np_typ, numpy.integer):
typ = numpy.dtype('int64')
elif numpy.issubdtype(np_typ, numpy.number):
... | 8933118201335fcecea94be944d8271e950c6984 | 660,233 |
def low_daily_frequency(df):
"""
Checks for weekdays that have less than 600 candles 'G01' OR
Checks for sundays that have less than 60 candles 'G01'
:df dataframe consisting of g01 candles
:return dataframe containing days that have a low frequency of g01 candles
:rtype dataframe
"""
... | e8738c3519ffb9ec86b3618d3a0106c5fac1466e | 660,234 |
import sys
def loadRules(filename):
"""
Returns a list of rules read from the given file. Each rule is itself
a rule of tokens, including the '->' token, with whitespace removed.
Any rules with a '|' on the right side are split/converted to multiple
rules with the same initial token.
"""
... | 249e4b9b8024ac6046bdd83ad041908b331137e9 | 660,235 |
def get_default_num_parties_jouees():
"""
The number of AI self-play games to find out which of two AI is the best one.
"""
num_parties_jouees = 10
return num_parties_jouees | e3d1715b6232062a1b84a41c85cff2189eb04fd6 | 660,236 |
import __main__ as main
def _can_cython_inline():
"""Checks whether we are in a context which makes it possible to compile code inline with Cython.
Currently it is known that standard REPL and IDLE can't do that.
"""
# statically works with IPython
if hasattr(main, 'get_ipython'):
return... | 0bffbed9c7cd03f1c1cdf6f8038e10e4d1decff7 | 660,238 |
import configparser
import os
def parse_config():
"""Parse configuration file, returns a list of servers"""
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser("~"), ".misp"))
servers = {}
for s in config.sections():
try:
info = {
... | 3af92556df4669d809d37f4f1c489bb0be280d29 | 660,239 |
from typing import List
def chunk(s: str, n: int = 80) -> List[str]:
"""Chunk string into segments of specified length.
>>> chunk(('wordsX' * 5), 11)
['wordsXwords', 'XwordsXword', 'sXwordsX']
>>> chunk('x', 80)
['x']
"""
return [s[i:i + n] for i in range(0, len(s), n)] | dcc20fa7323a650c8da72de67946a71406354e14 | 660,240 |
import math
def dist(p1, p2):
"""
Compute euclidean distance
:param p1: first coordinate tuple
:param p2: second coordinate tuple
:return: distance Float
"""
return math.sqrt((p2[0] - p1[0]) ** 2 + (p1[1] - p2[1]) ** 2) | bf82a24ae52bf528bc54c92fbb0afc46d6cd0117 | 660,241 |
import numpy
def _get_predictions(posteriors, task):
"""
Args:
posteriors (numpy.array):
Returns:
"""
if task == "clf":
if posteriors.shape[1] > 1:
predicted = numpy.argmax(posteriors, 1)
else:
predicted = numpy.clip(numpy.sign(posteriors), a_min... | f4a4a71aa445331637fb8c6765d8749d07c55592 | 660,242 |
def get_answer(s):
"""Given a choice (A, B, C, D) this function returns the integer index representation
of that choice (0, 1, 2, 3)"""
return 'ABCD'.index(s) | c8f785642f6ae276fab70705108b589e88e92098 | 660,243 |
def PLANCK_CONSTANT():
"""
The `PLANCK_CONSTANT` function returns the Planck constant (unit is Js)
according to the NIST reference on constants, units and uncertainty.
"""
return 6.626070040e-34 | b9c6ff8081d0fed2b25a9bfe71e49aa554bffd6d | 660,244 |
def int_or_none(v, default=None, get_attr=None):
"""Check if input is int.
Args:
v (int): Input to check.
default (type, optional): Expected type of get_attr. Defaults to None.
get_attr (getter, optional): Getter to use. Defaults to None.
Returns:
int or None: Return int if... | e1c00c6cc80a0035f54ddbe2cf8a5b7c412ec19f | 660,245 |
import sys
import termios
import tty
def getch():
"""Retrieve a single character from stdin with the terminal in raw mode."""
stdin_fd = sys.stdin.fileno()
old_attrs = termios.tcgetattr(stdin_fd)
try:
tty.setraw(stdin_fd)
char = sys.stdin.read(1)
finally:
termios.tcsetattr(stdin_fd, termios.TCSA... | f8038e19cd16658171070fbe985b89bc465f0bb7 | 660,246 |
def bin_mapping(
value_to_classify,
nr_of_classes,
class_bins,
placeholder_zero_color
):
"""Maps values to a bin.
The mapped values must start at 0 and end at 1.
Arguments
---------
value_to_classify : float
Value to classify
class_bins : list
... | 1909cee7f63facfcd010fedd67e55a6caf6604be | 660,247 |
import click
def ensure_valid_type(node_type_choices: click.Choice, node_type: str) -> str:
"""Uses click's convert_type function to check the validity of the
specified node_type. Re-raises with a custom error message to ensure
consistency across click versions.
"""
try:
click.types.conver... | 27d0b57931690066c64fb2343d419dfe8a104d8e | 660,248 |
def get_name():
"""Funcao get and return a name"""
name = input('What is your name? ')
return name | 1112cabf13f192f7549fb2e00749ec14900ea795 | 660,249 |
import re
def _is_internal_request(domain, referer):
"""
Returns true if the referring URL is the same domain as the current request.
"""
# Different subdomains are treated as different domains.
return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer) | ceb214cf3d7cf0cffbad0f0131810271d8a54d4c | 660,250 |
import torch
def _mean_plus_r_var(data: torch.Tensor, ratio: float = 0, **kwargs):
"""
Function caclulates mean + ratio * stdv.
and returns the largest of this value and the smallest element
in the list (can happen when ratio is negative).
"""
return max(
data.min().item(),
dat... | 4a9ea4b23f144d2834b8b972b0a1f70c2a289788 | 660,251 |
def _make_state_field_accessor(name):
"""Return a descriptor that accesses the fields of the state"""
def _getter(self):
state = self._state
return getattr(state, name)
def _setter(self, value):
state = self._state
setattr(state, name, value)
return property(
_... | 7b2f64df66c3c69abe948106e7ccdfdcffcfb501 | 660,252 |
def three_sum(numbers):
"""
Parameters
----------
numbers : list
A list of integers
Returns
-------
list
containing triplets
"""
list_size = len(numbers)
if list_size < 3:
return []
triplets = set()
# sort list
# for each item to n - 2
... | e4dbe93c554b99e7a755efba72dc3f5d3f2b5b19 | 660,253 |
import argparse
def get_arguments():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description="""pipe to rofi a row by row content"""
)
parser.add_argument(
"-c", "--columns", help="""columns number""", dest="columns", default=1
)
parser.add_argument(
... | 5307baf947747c36b2a0b325d11cabaf088af8ae | 660,254 |
import struct
def decode_data(data, *, key_encoding="B"):
"""Helper which decodes length encoded structures into a dictionary with the given key
encoding."""
i = 0
data_dict = {}
key_size = struct.calcsize(key_encoding)
while i < len(data):
item_length = data[i]
i += 1
... | 8b5e471a9eec7a8165ffa38b3381cb3750b6ed09 | 660,255 |
import base64
def b64_to_utf8_decode(b64_str):
"""Decode base64 string to UTF-8."""
return base64.urlsafe_b64decode(b64_str).decode('utf-8') | 21c80f077f52ea1df523a2d0aac8c547f8a7875e | 660,256 |
def roll(l):
"""rolls a list to the right
e.g.: roll([0,1,1]) => [1,0,1]
"""
tmp1, tmp2 = l[:-1], l[-1]
l[1:] = tmp1
l[0] = tmp2
return l | 9a3b1566cac74d78037842455eccda63278a65bc | 660,257 |
def std_pres(elev):
"""Calculate standard pressure.
Args:
elev (float): Elevation above sea-level in meters
Returns:
float: Standard Pressure (kPa)
"""
return 101.325 * (((293.0 - 0.0065 * elev) / 293.0) ** 5.26) | c269f872f038efff6eb26c83cfb931033301a045 | 660,258 |
def CreateAlterAddColumn(table, field, field_data):
"""Create ALTER statement to add this field"""
allow_null = ''
if field_data['Null'] != 'YES':
allow_null = ' NOT NULL'
primary_key = ''
if field_data['Key'] == 'PRI':
primary_key = ' PRIMARY KEY'
auto_increment = ''
if field_data['Extra']:
... | 2c5b994c35e617b8ed2cfef2d663ad62d1fd8839 | 660,259 |
import argparse
def _load_configuration() -> argparse.Namespace:
"""
Parse command line arguments.
Parameters
----------
:return: configuration object
"""
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--password", help="Password to access the DB service.", required=Fa... | 592676b44ef2033e435c471604c2d46872ece7b8 | 660,260 |
import argparse
def parse_args():
"""
Parse Arguments from component
"""
parser = argparse.ArgumentParser()
parser.add_argument("--num-trees", help="Number of trees in the forest")
parser.add_argument("--max-depth", help="Maximum depth of each tree in the forest")
parser.add_argument("--ou... | 92ec73c881252f40d220c9229d652162ba46b02c | 660,261 |
import torch
def complex_mul3(x, y):
"""
Simply multiplication of complex numbers (it also handles
multidimensional arrays of complex numbers). Each complex
number is expressed as a pair of real and imaginary parts.
:param x: the first array of complex numbers
:param y: the second array compl... | a1fc4530b5f5e49e7f103f16c6d4be3a09c78d2c | 660,262 |
import re
def _tokenise_ex(content):
"""Less naive tokenisation, to better take c operators into account"""
pattern = re.compile(r'(\+\+|--|&&|\|\||->|==|>=|<=|!=|>>|<<|\s+|[^#\w])')
return list(filter(lambda tok: len(tok) > 0 and not re.match(r'\s+', tok),
re.split(pattern, conten... | 899c8dfc0a1abfe8de4355c00072fa388dc7c52c | 660,263 |
import json
def load_stashed_config():
""" Load settings dict from the pickle file """
try:
with open('h5config.json', 'r') as f:
cfg = json.load(f)
if not isinstance(cfg, dict):
raise TypeError
except Exception:
return {}
return cfg | 85b8720ed09ed8695b96d08865392ea53809a606 | 660,264 |
def read_fixed(writers_schema, readers_schema, decoder):
"""
Fixed instances are encoded using the number of bytes declared
in the schema.
"""
return decoder.read(writers_schema.size) | 044a80beb37465a91e06e7c9a8b73c230c3b8891 | 660,265 |
def make_sentinel(name="_MISSING", var_name=""):
# type: (str, str) -> object
"""Creates and returns a new **instance** of a new class, suitable for
usage as a "sentinel", a kind of singleton often used to indicate
a value is missing when ``None`` is a valid input.
Args:
name: Name of the S... | 667220b91af8d2dd3ea660d66a0e446a950701cb | 660,266 |
import torch
def collate_fn(data):
"""
ensure images remains the same shape in one batch
permute images axis from [N, H, W, C] to [N, C, H, W]
:param data:
:return:
"""
imgs = [s['img'] for s in data]
annots = [s['annot'] for s in data]
scales = [s['scale'] for s in data]
widt... | 44cd8c7a8a3959ebb89e1d9c8adf136d1001f6e7 | 660,267 |
import uuid
def fake_metadata_runner():
"""Generate the set of claims required for runner to function"""
return {
"tx_id": str(uuid.uuid4()),
"jti": str(uuid.uuid4()),
"schema_name": "2_a",
"ru_ref": "2016-04-04",
"collection_exercise_sid": "test-sid",
"question... | a148526dee6c8d23832e69e837e2891321426047 | 660,268 |
def add_obs_prob_to_dict(dictionary, obs, prob):
"""
Updates a dictionary that tracks a probability distribution over observations.
"""
obs_str = obs.tostring()
if obs_str not in dictionary:
dictionary[obs_str] = 0
dictionary[obs_str] += prob
return dictionary | 24ef9386cc9da12cd0c4a0df145e4fa78b44686d | 660,270 |
def sphere_to_plane_car(az0, el0, az, el):
"""Project sphere to plane using plate carree (CAR) projection.
The target point can be anywhere on the sphere. The output (x, y)
coordinates are likewise unrestricted.
Please read the module documentation for the interpretation of the input
parameters an... | 0af644382f75f7278271ad048d66e8e20492ed8c | 660,272 |
import argparse
def parse_args():
"""
包含了XGBOOST, GBDT, RF, GBDT+LR所有模型的参数
:return:
"""
parser = argparse.ArgumentParser(description='Manpower Loss Forecast.')
parser.add_argument('--model', choices=['XGBOOST', 'GBDT', 'RF', 'LR', 'GBDT+LR', 'RF+LR'], default='XGBOOST')
parser.add_argument... | ac2b6fc4b0e53525c9c2bce8f82676386429329a | 660,273 |
import math
def sqrt(value):
"""Returns the square root of a value"""
return math.sqrt(value) | 52d0b34be5dec7f46392a2ba732438be007fe010 | 660,274 |
def cov_files_by_platform(reads, assembly, platform):
"""
Return a list of coverage files for a given sequencing platform.
"""
accessions = []
if reads is not None:
accessions += [accession for accession in reads if reads[accession]['platform'] == platform]
return list(map(lambda sra: "%... | ae2e5b71e03141e9fb38247a463380ceba80cf3d | 660,275 |
from datetime import datetime
def get_time_delta(start_time: str, end_time: str):
"""Returns the difference between two times in minutes"""
t1 = datetime.strptime(start_time, "%Y-%m-%d_%H-%M-%S")
t2 = datetime.strptime(end_time, "%Y-%m-%d_%H-%M-%S")
delta = t2 - t1
return int(delta.seconds / 60) | 59f8f9742b746ea67d5ef5d954b77f651a3ada0c | 660,276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.