content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_trips_invalid_profit(rides):
"""
Ignore rides that have profit of more than $150/hr
"""
return rides[rides.profit/(rides.trip_time_in_secs/(60.0*60.0)) < 150] | aa07d094849fb641239206fb6da00de14013bb2c | 650,742 |
def usecase():
"""usecase route"""
return 'hello from usecase_route' | 99fedb33c31f3c1d7eaf2b07f7bda09977ecf5ce | 650,743 |
def max_lens(X):
"""
max_lens
Return: a tuple of which each element is the max length of the elements in
the corresponding dimension of the input X.
Example: max_lens([[1,2,3], [4,5]]) --> [2,3]
"""
if not isinstance(X[0], list):
return tuple([len(X)])
elif not isinstance... | 763e9b31bd09e539fc36fe5f8a7dcb816e17ec0b | 650,744 |
def linearsearch(A, elem):
"""
Linear Search Algorithm that searches for an element in an array with O(n) time complexity.
inputs: Array A and element e, that has to be searched
output: True/False
"""
for a in A:
if a==elem:
return True
return False | 5372e23eba64cacb59532a126b5aac6fdc9efe8f | 650,745 |
import struct
def pack_params(params):
""" Pack sub-packet parameters independently """
packed = struct.pack(u'>qQ',
params[u'be'][u'int64'],
params[u'be'][u'uint64'])
packed += struct.pack(u'<qQ',
params[u'le'][u'int64'],
... | aba8f108fdb62aca86df25ef8b4387c2d9e17de1 | 650,746 |
import os
import csv
def get_original_noise_pairs(directory, dataset='train'):
""" Get the pair directory of original and noise .wav file
The directory is a string representing directory of the csv files
containing the actual file name pairs dataset is one of "train," "test,"
or "validation"
Arg... | 61518183dae8bd5e6a5f3a861d0bdf88473000a7 | 650,747 |
def efficientdet_params(model_name):
""" Map EfficientDet model name to parameter coefficients. """
params_dict = {
'efficientdet-d0': {
'compound_coef': 0,
'backbone': 'efficientnet-b0',
'R_input': 512,
'W_bifpn': 64,
'D_bifpn': 3,
... | 53e434752b2dee6fb63d6ed733babe17a0c8dcd8 | 650,748 |
import readline
import six
def readline_input(prompt, prefill=''):
"""Provide an editable default for ``input()``."""
# see: https://stackoverflow.com/q/2533120/
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return six.moves.input(prompt)
finally:
readline.s... | 0dd2835a1b666325de2c9fd8d016181c5fc994b0 | 650,749 |
import os
def assign_from_env(name, envname, is_bool=False):
"""
Try to read variable from enviromental variables and
assign to name if it exists
"""
try:
if is_bool is True:
evar = "False"
if os.environ[envname] == "true":
evar = "True"
... | 8515950e4c96d15b0be1975ca9089c6fd7d3fc5b | 650,750 |
def spo2SignleMeasurementHandler(data):
"""
For get this answer need to sent AB 05 FF 31 11 00 FF
"""
# Only for testing - no detailed parsing, just form answer
return bytearray([0xAB, 0x04, 0xFF, 0x31, 0x11, 0x22])
pass | 3dc14cba7cd19c6cd4fdbdb6022b8ef24f8f38b4 | 650,751 |
import sys
def get_OpenPypeVersion():
"""Access to OpenPypeVersion class stored in sys modules."""
return sys.modules.get("OpenPypeVersion") | 03d2a0636ef7a4cc67658774673f518f831d77db | 650,753 |
def subset_data_for_overhang(dataframe, overhang, horizontal=True, filter=True):
"""Subset Tatapov dataframe for given overhang.
**Parameters**
**dataframe**
> Tatapov dataset, for example `tatapov.annealing_data["25C"]["01h"]`
**overhang**
> Overhang class instance (`Overhang`)
**horiz... | 760b809429c5bbc62a024759a1cb5aa57709559b | 650,755 |
def get_variables():
"""Create and return a dictionary of test variables for the specified
test case.
:returns: Dictionary of test variables - settings for Honeycomb's SLAAC.
:rtype: dict
"""
slaac_data = {
"address": "10::10",
"prefix": 64,
"slaac_data": {
"... | c006ba483f0632c803eee39e2a214a223d78d5ed | 650,756 |
def eval_sklearn(model, data):
"""Function to evaluate an sklearn model
Args:
model ([type]): [description]
data ([type]): [description]
Returns:
[type]: [description]
"""
return model.model.predict(data.x_data) | 85a2bfa1f052f2fb367abad8d1cd436d2f9b262b | 650,757 |
def __SP (
A0 ,
alpha ,
z = 0.) :
"""
"""
A = A0 / (1. + z )**alpha
return A | 69e0449309daeadad5c5a465bf0c07ad3a24932b | 650,758 |
def maybe_name_or_idx(idx, model):
"""
Give a name or an integer and return the name and integer location of the
column in a design matrix.
"""
if idx is None:
idx = range(model.exog.shape[1])
if isinstance(idx, int):
exog_name = model.exog_names[idx]
exog_idx = idx
#... | ebdbbe3440a14353c910fc0b55639b5acf83b240 | 650,759 |
def is_code_token(text):
"""
True for non-comment, non-whitespace token text.
"""
char0 = text[0]
return char0 != '#' and char0 > ' ' and char0 != '\\' | 31697b7eea1e926c3c594c3de87b07b4db834511 | 650,760 |
def _function_matcher(matcher_func):
"""Safer attribute lookup -- returns False instead of raising an error (PRIVATE)."""
# This comment stops black style adding a blank line here, which causes flake8 D202.
def match(node):
try:
return matcher_func(node)
except (LookupError, Attr... | bbfe5835f8402dc54bbbfb1a7f4039b3761e5918 | 650,761 |
def range_check(df, maximum, minimum):
"""
range_check adds a column to data frame with label if data are out of range.
Arguments:
df: data frame with a column 'raw' of raw data.
maximum: maximum acceptable value - above this value, data are anomalous
minimum: minimum acceptable valu... | d58bcc332e61b252ee3dac9fe500d29fe546cb35 | 650,762 |
def get_axis_chain(axis_table,axisname):
""" get_axis_chain
axis_table is a dictionary indexed by axis names
each row of axis_table is a dictionary with the
following keys:
"id": the axis name
"type": the axis type:
"general"
... | 86839d86a5fb16760f4fb9793c694a7b832e5508 | 650,763 |
def PyDict_Keys(space, w_obj):
"""Return a PyListObject containing all the keys from the dictionary,
as in the dictionary method dict.keys()."""
return space.call_method(space.w_dict, "keys", w_obj) | 369ddad264ecad32dd4a47709f07dc033d57560b | 650,764 |
def get_base_signature(signature, index = 0):
"""Return the base signature i.e. 'i', 'ai', and 'aai' all return 'i'."""
return signature[index:len(signature)].lstrip('a') | 6863af45624a0a189c2eb7e3cb3b57ee4b504b8d | 650,765 |
def get_attr_resolver(obj_type, model_attr):
"""
In order to support field renaming via `ORMField.model_attr`,
we need to define resolver functions for each field.
:param SQLAlchemyObjectType obj_type:
:param str model_attr: the name of the SQLAlchemy attribute
:rtype: Callable
"""
retu... | 23376addb0b5a3ab600e251e512f9174a27a66b6 | 650,766 |
def openFile(file_path):
"""Open file in read mode, return file contents"""
md_file = open(file_path, 'r')
file_contents = md_file.read()
md_file.close()
return file_contents | 3f637474910ff6b3549f22cc7384b6d1a419b5b7 | 650,767 |
import argparse
import sys
def _parse_arguments() -> argparse.Namespace:
"""Plot argument parser.
Arguments:
base_path: Benchmark path prefix.
peak_throughput: Peak throughput of the benchmark system.
peak_bandwidth: Peak bandwidth of the benchmark system.
"""
parser = argparse.ArgumentParser(descripti... | f7f50831f4aebae114d06ba43c5917b5043e3114 | 650,768 |
import os
def which(program, paths=None):
""" takes a program name or full path, plus an optional collection of search
paths, and returns the full path of the requested executable. if paths is
specified, it is the entire list of search paths, and the PATH env is not
used at all. otherwise, PATH env ... | 19811025ad0037056b834780534bdd6b624b670c | 650,769 |
def textarea_to_list(textarea):
"""
Takes a string and returns list of lines, skipping blank lines
"""
list_ = textarea.splitlines()
return [x.strip() for x in list_ if x.strip() != ''] | f7d08a939f38c8e12924acfe727fe9d31831e83a | 650,771 |
import os
def get_supported_filesystems_kernel():
"""
Reads /proc/filesystems (the list of supported filesystems
for the current kernel) and returns a list of (names of)
those filesystems.
"""
PATH_PROCFS = '/proc/filesystems'
if os.path.isfile(PATH_PROCFS) and os.access(PATH_PROCFS, os.R... | 253ff1752e3b76e5993aa59de1c8da41aaa9a829 | 650,772 |
def atomic(fun, *args, **kwargs):
"""Decorator that wraps a function literal for modifying data inside of
generators acting on the instance-data pairs used by the transaction
"""
def new_fun(instance_list, read_list):
return (
(instance, fun(data, *args, **kwargs))
for in... | 9a31ecec1a85ffa3afb482a189d0bbc662fdef5c | 650,773 |
def _get_tensors_from_graph(graph, tensors):
"""Gets the Tensors in `graph` with the name of the tensors in `tensors`.
Args:
graph: TensorFlow Graph.
tensors: List of Tensors.
Returns:
List of Tensors.
"""
new_tensors = []
for orig_tensor in tensors:
new_tensor = graph.get_tensor_by_name(o... | 4bb4066e95c712c262f2b096d5523664d65dd54d | 650,774 |
def ratioTest(kps1, kps2, matches):
"""
Take in two sets of keypoints and the set of matches between them
Perform ratio test to get best matches (60% threshold)
Return surviving matches
"""
ratioMatches = list()
for match in matches:
m1, m2 = match
if m1.distance < 0.60*m2.di... | ddce0908bb1c3999ff6c67e2ff012f3383cdd37b | 650,775 |
def cel2kel(t):
"""Converts from Celsius to Kelvin"""
return t + 274.2 | 04d6d474e9de56a8200a0fc147611906d4e58a16 | 650,776 |
import itertools
def combinate(listoffiles, combnum):
"""
Makes a list of tuples with the N choose combnum options
Parameters
----------
listoffiles: list
list of file names
combnum: int
combination number (N choose combnum)
Returns
-------
combinedlist: list
... | dacd66a4355ae2686d1db960bb3dba3daf935ae4 | 650,778 |
def search(seq, val):
"""Search location of key in a sorted list.
The method searches the location of a value in a list using
binary searching algorithm. If it does not find the value, it return -1.
Args:
seq: A sorted list where to search the value.
val: A value to search for.
Re... | c56ab329059bcb026e5608d9da06cf348ef7663c | 650,779 |
def generate_command_argument(hlwm, command, argument_prefix, steps):
"""
generate the next argument of the command which has the given
argument_prefix.
This function makes at most 'step' many recursive calls.
It returns a list of full arguments starting with the argument_prefix.
"""
if st... | 966a921a760f56b571e875c46a555a945363af53 | 650,780 |
from typing import Optional
import logging
def get_logger(name: Optional[str] = None) -> logging.Logger:
"""Get logger by ``name``.
Returns
-------
:class:`logging.Logger`
Logger that was fetched by ``name``.
"""
return logging.getLogger(name) | 4685667f532707bb279b73740b2d1dd9584646e3 | 650,781 |
def re_case_word(word):
"""
Title case word unless known initialism which should be upper
"""
initialisms = ["DWP", "NHS", "MHCLG", "GDS"]
if word.upper() in initialisms:
re_cased = word.upper()
else:
re_cased = word.title()
return re_cased | c477a952d1bb6931080ec1b52a85ad0ffb9048cf | 650,782 |
import argparse
def func_parser() -> argparse.Namespace:
"""
Defines what arguments the program requires, and argparse will figure out how to parse those out of sys.argv
:return: an instance of the argparse class that can be used to access command line arguments
"""
parser = argparse.ArgumentPar... | a2a3278d9962aac43c31f579a8278efa1f68f489 | 650,783 |
def preprocess_prediction_data(text, tokenizer):
"""
It process the prediction data as the format used as training.
Args:
text (obj:`str`): The input text.
tokenizer(obj: `paddlenlp.data.JiebaTokenizer`): It use jieba to cut the chinese string.
Returns:
input_ids (obj: `list[in... | b5eba0f2db3e68426339156ec3ef75f965f0cba9 | 650,784 |
import inspect
def arguments_of(func):
"""
@returns the list of arguments of func
"""
def v(name):
if ps[name].default == inspect.Parameter.empty:
return {'name': name}
else:
return {'name': name, 'default_value': ps[name].default}
ps = inspect.signature(f... | f7d5e2aa07b67032869cd345e5f9fed59eb6eb44 | 650,785 |
def df_to_records(df):
""" Convert pandas DataFrame to table compatible data aka records. If DataFrame is empty keep the columns.
:type df: pandas.DataFrame
:rtype: list[dict]
"""
if df.empty:
# Return column names in 'records' style.
return [{c: None for c in df.columns}]
r... | 11492828676a820fdcb221707fc10d189f19074b | 650,786 |
from datetime import datetime
def is_datetime(value):
"""Checks, if given value is a datetime.
:param value: The value to check.
:type value: object
:returns: True, if value is a datetime (and not a date), false otherwise.
:rtype: Boolean
>>> from plone.event.utils import is_datetime
>>>... | 47be1dec1585bf6ccfb506fe800a71de03954e4d | 650,788 |
def find_furthest_room(distances):
"""Find furthest room from the distances grid."""
return max(max(row) for row in distances) | 9a8690e50c3f7099070e69e94453dc66ae9fda2c | 650,789 |
import json
def pretty_json(data):
"""Return a pretty formatted json
"""
data = json.loads(data.decode('utf-8'))
return json.dumps(data, indent=4, sort_keys=True) | 941eaa5bcd6ec91596812595b80726ec63b7181d | 650,790 |
import random
import string
def _generate_password(length=16):
"""
Generate password of specified length with at least one digit,
uppercase letter, and lowercase letter. This is used as the
IKEv2 PSK on both sides of the tunnel.
"""
# Need 1 each: uppercase, lowercase, digit
pw_minimum = ... | 962a886ebc17d83544908357579b20b5d7fbaff5 | 650,791 |
def mipmap_size(base_width, base_height, mip_level):
"""Return mipmap width and height
Args:
base_width (int): Width of the base image (mip level 0)
base_height (int): Height of the base image (mip level 0)
mip_level (int): Level of mip to get
Returns:
tuple(mip_width, mip_... | c24775f80dc74ed73b53f388b061d5c5cecb7810 | 650,792 |
import torch
import math
def importance_sample_memory(num_particles, obs, obs_id, generative_model, guide, memory):
"""
Args
num_particles
num_svi_iterations
obs [batch_size, num_timesteps]
obs_id [batch_size]
generative_model
guide
memory
Returns
... | c2c20f69040dcb6dcab9663e968929f6e68ed545 | 650,793 |
def get_examples(section_div, examples_class):
"""Parse and return the examples of the documentation topic.
Parameters
----------
section_div : bs4.BeautifulSoup
The BeautifulSoup object corresponding to the div with the "class"
attribute equal to "section" in the html doc file.
ex... | 93da0bfc7fec2b2f7668fd24825068a91c672398 | 650,794 |
def get_sentence(pk, sentence_dict):
"""
>>> factbank_path=r"/Users/pushpendrerastogi/Dropbox/evsem_data/factbank/data"
>>> d=sentence_dict_maker(factbank_path)
>>> pk = ("ABC19980108.1830.0711.tml", 15,"e30")
>>> assert get_sentence(pk, d)=="And Wong Kwan will be lucky to break even ."
"""
... | 7494bd7587706f7a308e367a8d255a2c80c50fc7 | 650,795 |
import os
import requests
def download_file(url, file_name, output_directory='./'):
"""Download into the current working directory the
file from Box given the direct URL
Parameters
----------
url : str
URL to the file to be downloaded
Returns
-------
download_filename : str
... | 2f5ea2fc9924885fa971724aa2ae46d5d275a024 | 650,796 |
import torch
def depth_pose2flow(depth, ref_in, ref_ex, src_in, src_ex):
"""
:param depth: B x H x W
:param ref_in: B x 3 x 3
:param ref_ex: B x 4 x 4
:param src_in: B x 3 x 3
:param src_ex: B x 4 x 4
:return: B x 2 x H x W
"""
batch = depth.shape[0]
height, width =... | e671ffec213543cd3d52d7e912e1f23c4309dbe3 | 650,797 |
import sys
import ctypes
import os
def alive(pid: int) -> bool:
"""Is the process alive?"""
if sys.platform == 'win32':
# why can't anything be easy...
status = DWORD()
handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,
0,
... | 623de920135fb7a6e53fb98548d3bbfa75763f91 | 650,798 |
def convert_target_counters(x):
"""
This function converts the FxxxGxxx xml format to the final format. E.g: F29G034 -> 29034,
F08G069 -> 8069.
"""
if x[1] == str(0): # If the counter in question is of the F0xx format -> remove 0 and keep the rest of the numbers
cpy = x.replace("F", "").... | 128a79e065e051c2b78a825550ea4a5d2f84f3bf | 650,799 |
def is_hla(chrom):
"""
check if a chromosome is an HLA
"""
return chrom.startswith("HLA") | 2af4c8169910cd445c32bb49e0e118a237f9ffbc | 650,800 |
import re
def find_missing_labels(issue_summary, issue_labels):
"""
Returns the list of strings in square brackets from summary
filtered to feature only the strings not found among labels
"""
found = re.findall(r'\[.*?\]', issue_summary)
found = [item.replace('[', '').replace(']', '') for item... | 30a0e7adb913b5c85e0db3ed8ad7a59be4fdc3c1 | 650,801 |
def delete_type(rows, msg_content):
"""
Function:
delete_type
Description:
A existing event type is deleted from the user's calendar file
Input:
rows: lsit of lines in calendar
msg_content: event type to be deleted
Output:
- A existing event type is deleted... | 975a7e65c781da31b18ffc9ae7ef855514e82954 | 650,802 |
import os
from typing import OrderedDict
def crawl_directory(directory, ignore_hidden = True):
"""
Given a directory, return a dict representing the tree of files under that directory.
:param directory: A string representing a directory.
:return: A dict<file_or_dir_name: content> where:
file_... | 4baa86c3fc50b07d172196494311b0020dca8bde | 650,803 |
def _QuoteCpuidField(data):
"""Add quotes around the CPUID field only if necessary.
Xen CPUID fields come in two shapes: LIBXL strings, which need quotes around
them, and lists of XEND strings, which don't.
@param data: Either type of parameter.
@return: The quoted version thereof.
"""
return "'%s'" % ... | 3f3aa420d77605b0954b0381c3698d39242d7cde | 650,804 |
def swap(x, i, j):
"""
swap bits i and j of x.
"""
mask = (1<<i) | (1<<j)
m = x&mask
if m == 0 or m == mask:
return x
return x^mask | a6a885bad2f2ed20d050a500bc45d640e948b598 | 650,805 |
def _get_mff_vals_unnorm(single_z, single_x, mult_z, mult_x, func):
""" Evaluates mff at the test points with unnormalised coordiantes. """
single_mff_vals = func.mff.eval_at_fidel_single_point(single_z, single_x)
mult_mff_vals = func.mff.eval_at_fidel_multiple_points(mult_z, mult_x)
return single_mff_vals, mul... | e731cdca47ddf0ce4642b54fa829c43312bf8463 | 650,806 |
def has_shebang_or_is_elf(full_path):
"""Returns if the file starts with #!/ or is an ELF binary.
full_path is the absolute path to the file.
"""
with open(full_path, 'rb') as f:
data = f.read(4)
return (data[:3] == '#!/' or data == '#! /', data == '\x7fELF') | 4dd67c8bd9a5d5afd00fed3d564cf32e7551adb0 | 650,807 |
def notas(*num, sit=False):
"""
-> Função para analisar notas e situações de varios alunos.
:param num: uma ou mais notas de vários alunos.
:param sit: valor opcional, indicando se deve ou não adicionar a sítuação da turma.
:return: dicionário com várias informações sobre a sítuação da turma.
""... | 407e8638ff7bb0985f2b66483026bf614c93b811 | 650,808 |
def newArtist(af):
"""asks the user about the artist and returns the string"""
try:
a = input("(" + str(af.tag.artist) + ") New Artist?> ")
except AttributeError:
a = input("(None) New Artist?> ")
if a == None or a == "":
if af.tafg.artist != None:
return af.tag.artis... | 2820a1d890a006cf5e8c8f8c63b33e3470893c61 | 650,809 |
import os
def checkFileName(fn):
"""
Return the next permutation of the specified file name if it exists.
Next permutation is found by adding integer to file name
Input:
fn: String of filename, excluding .csv suffix
Output:
fn_: String of the new filename
"""
... | 10380ea1286cdbf375a246084666fb700a0adb14 | 650,810 |
def gcd(x, y):
"""Find the Greatest Common Devisor (GCD) of the two given integers.
Args:
x (int): some integer
y (int): another integer
Return Value:
The greatest common devisor of the two integers.
"""
while(y):
x, y = y, x % y
return x | 80c9f035c1cfa506f7d2d0e3cec9fc4c90fb198a | 650,811 |
def orientation(a, b, c):
"""Compute the orientation of c relative to the line AB."""
M = [[a[0] - c[0], a[1] - c[1]], [b[0] - c[0], b[1] - c[1]]]
# Return det(M)
return M[0][0] * M[1][1] - M[0][1] * M[1][0] | af107633562bc713e29b55ca686e0f8aab640557 | 650,812 |
import sys
def check_convergence(game, t, stable):
"""Check if game converged"""
if (t % game.tstable == 0) & (t > 0):
sys.stdout.write("\rt=%i" % t)
sys.stdout.flush()
if stable > game.tstable:
print('Converged!')
return True
if t == game.tmax:
print('ERROR! No... | 2782253e0395ded1fa8f0cbce838e62c4795c682 | 650,813 |
def _replace_module_using_policies(model, policies):
""" Traverse model's children recursively and apply any transformations in ``policies``.
Arguments:
model (torch.nn.Module): model to augment
policies (dict): Mapping of source class to replacement function.
Returns:
Modified ``mo... | c9582b7fd74289cf24ead57f0d7e1567fb35a9e4 | 650,815 |
def F(agents, images_in):
"""The stacked agent map.
Takes a list of agents and a list of images and applies each agent
to the corresponding image.
Args:
agents: List of agents
images_in: List of input images
Returns:
List of output images after applying the agents
"""
... | 7c78d6277000968aada8eb2060993c3ca6c08306 | 650,816 |
import functools
def negative_criterion(criterion):
"""Turn maximization into minimization by switching the sign."""
@functools.wraps(criterion)
def wrapper_negative_criterion(*args, **kwargs):
criterion_value, comparison_plot_data = criterion(*args, **kwargs)
return -criterion_value, co... | e9fa94abfb8a67442c3ea0757035c9bdf55649eb | 650,817 |
def to_unicode(obj):
"""
Converts any string values into unicode equivalents.
This is necessary to allow comparisons between local non-unicode strings and the unicode values returned by the api.
:param obj: a string to be converted to unicode, or otherwise a dict, list,
set which will be recursi... | 8751443e87014ca9e5a9ae71be9f41f2d26eadb3 | 650,818 |
from pathlib import Path
def check_paths(vtk_src_dir, application_srcs):
"""
Check that the paths are valid.
:param vtk_src_dir: The path to the VTK source.
:param application_srcs: The user source files to be scanned for modules.
:return: True if paths, files exist.
"""
ok = True
if ... | 213df92072459a55721d386308dc5fe74b0420c7 | 650,820 |
import time
import asyncio
async def wait_host_port(host, port, duration=10, delay=2):
"""Repeatedly try if a port on a host is open until duration seconds passed
from: https://gist.github.com/betrcode/0248f0fda894013382d7#gistcomment-3161499
:param str host: host ip address or hostname
:param int p... | 8d8f71662929b8d917bec27f9dcc1ddb6bb52e13 | 650,821 |
from typing import List
def solution(skill: str, skill_trees: List[str]) -> int:
"""[summary]
가능한 스킬트리인지를 검증. 가능한 스킬트리의 개수를 반환
Args:
skill (str): 선행스킬
skill_trees (List[str]): 제시된 스킬트리
* 선행스킬이 모두 등장하지 않을 수 있다.
Returns:
int: 제시된 스킬트리 중 가능한 스킬트리의 수
"""
answer = 0
... | 4e0e8b0bb746b266b4eba54e47f36ed7bc0dc054 | 650,822 |
def haspropriety(obj, name):
"""Check if propriety `name` was defined in obj."""
attr = getattr(obj, name, None)
return attr and not callable(attr) | fc83254933dba169b9725182d15006cc85d1ef45 | 650,823 |
def match_factory(variable, factories):
"""Match variable to VariableFactory using rank, name, and units.
Args:
variable (Variable): Variable to match.
factories (VariableFactory or tuple of VariableFactory): VariableFactory to
check against.
Returns:
bool: True if a ma... | d83f8ab86fb6aab37eefddb3e5f64115c6079891 | 650,824 |
def insertion_sort(array):
"""
Sort array in ascending order by insertion sort
Insertion sort iterates, consuming one input element
each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element
from the input data, finds the location it belongs within
... | 4445bae0f5dc8c572f83a4eda2958119c23558b4 | 650,825 |
import torch
def validation_loop(model, testloader, criterion):
"""
Returns test loss and accuracy score of a given torch model.
NOTE: divide outputs with the total number of epochs to get
the final values.
Parameters:
model (nn.Module): A torch model
... | 7d7b54d60d20dee68baafd26d29db338c98af517 | 650,826 |
def args(*arglist):
"""DBC helper for reusable, simple predicates for argument-value tests used in preconditions"""
def positional_predicate(s, *ar, **kw):
for pred, arg in zip(arglist, ar):
if not pred(arg):
return False
return True
return positional_predicate | fc845eaf78e610f8a606da9306b29a8d9cba1515 | 650,828 |
def join_sentences_by_label(grouped_sentences_df, label_col="topic_name", sentence_col="sentence"):
"""
Function used to join sentences into texts. Sentences are grouped by topics
---
**Arguments**\n
`grouped_sentences_df` (DataFrame): DataFrame with sentences groped by topics and which contains
... | c30c21d5478b4bdbbd321444e85b8c44fcb61ea6 | 650,829 |
def rotate_image(image):
""" Rotate an image according to it's EXIF info. """
try:
orientation_tag = 274 # 0x0112
exif=dict(image._getexif().items())
if exif[orientation_tag] == 3:
image = image.rotate(180, expand=True)
elif exif[orientation_tag] == 6:
im... | 6843c9e86572d968b3666e348e162b68ef153a6a | 650,830 |
def normalise_mfccs(mfccs, apply_mean=True, apply_stddev=True):
"""
Apply normalisation some cepstral mean variance normalisation (in part or in whole).
"""
mean = 0
stddev = 1
if apply_mean:
mean = mfccs.mean(axis=1).reshape(mfccs.shape[0], 1)
if apply_stddev:
stddev = mfcc... | 3403b73e46f2f83203664e1755cbee844f6d4c7f | 650,831 |
import argparse
def parse_args():
"""
args for training.
"""
parser = argparse.ArgumentParser(description='Parse args for training')
# for train
parser.add_argument('--script', type=str, help='training script name')
parser.add_argument('--config', type=str, default='baseline', help='yaml c... | 46f3b11ff483e0e8145084494eadfe918a717426 | 650,832 |
def replace_token(token, token_replacement, value):
"""
Replace `token` with `token_replacement` in `value`
:param: token: string e.g. : | .
:param: token_replacement: string e.g. _ -
:param: value: dictionary, list, or str
"""
if isinstance(value, str):
return value.replace(token, ... | f8e80d2e95afda7d661e3ed94588a4270c23e1fc | 650,833 |
def getConvertedGeom(self, index):
"""
Return a downcast geom on this space.
"""
return self.getGeom(index).convert() | 7c0605971da905edacc29b688ca2bf08cfbe9f45 | 650,834 |
def cloneDistribution(d):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
This function clones (deep copies) a ProbabilityDistribution object.
Cloning is needed because while separate chains in an MCMC analysis
need to begin with the same random number seed, it is not good... | fb1d3e1bd885dfc55d1c32b3873d86e67aa1aa60 | 650,835 |
def svm_model(r3d_kpc, n0, r_c, beta, r_s=1.0, gamma=3.0, epsilon=0.0, alpha=0.0):
"""
Compute a Simplified Vikhlinin model
Parameters
----------
- r3d_kpc: array of radius in kpc
- r_c : core radius parameter
- n_0 : normalization
- beta : slope of the profile
- r_s : characteris... | 02e532ca1e0af574b4d3c07ffe47e87b9223ca95 | 650,836 |
def hsl_time_to_time(hsltime):
"""
Converts HSL API timestamp to hh:dd format
:param hsltime: HSL API timestamp (hour maybe bigger than 24!)
:return: timestamp in hh:dd format
"""
return "%02d.%02d" % (hsltime / 100 % 24, hsltime % 100) | b229ac63cd69dda366a1cdc77f0513e5f05d6283 | 650,837 |
def _registered(registry, required, provided):
"""
Return the adapter factory for the given parameters in the given
registry, or None if there is not one.
"""
return registry.get(required).selfImplied.get(provided, {}).get('') | 6f29316d9332a5f6b045592a5c288e7a381a5a32 | 650,838 |
def is_ea(email: str) -> bool:
"""
Email domain name is "empacad.org"
"""
eml_domain = email.split('@')[1]
if eml_domain == 'empacad.org':
return True
return False | ae024b4d74fb453a1f5b95163a3f0bfe60d57340 | 650,839 |
import re
def random_state_params(pipe, seed):
"""Crée un dictionnaire constitué de tous les paramètres 'random_state' d'un pipe et leur assigne une valeur unique"""
rs = re.findall(r"[a-zA-Z\_]+_random_state", ' '.join(list(pipe.get_params().keys())))
rs=dict.fromkeys(rs, seed)
return rs | ed975f21f471abbe6dd6edf3fc5faa06400fce7f | 650,840 |
def test_acc_formatter(test_acc: float) -> str:
"""Wrap given test accuracy in a nice text message."""
return f"Test Accuracy: {test_acc}" | 1c5ff2480037350a393995d20e1dd354b5b0499a | 650,841 |
import requests
def post_input_form(input_text):
"""Posts a string as a form field (application/x-www-form-urlencoded)
named 'input' to the REST API and returns the response.
"""
url = 'http://localhost:5000/parse'
return requests.post(url, data={'input': input_text}) | d2e7c9aa97ca7ef0d5f7100a74e83f2cdc6d882b | 650,842 |
def exercise2(n):
"""
Write a recursive Python function that returns the sum of the first n integers.
"""
if n > 0:
return n + exercise2(n - 1)
else:
return 0 | befd299860098d018063218c89d443dc5bc38fb6 | 650,843 |
def remove_from_string(str, tobeRemoveds):
"""
remove list of strings from a string
"""
for sub in tobeRemoveds:
str = str.replace(sub, '')
return str | 800f40c66b3ab146fd7f690513d3a0428f827334 | 650,844 |
from typing import List
from pathlib import Path
from typing import Dict
import os
import hashlib
def _hash_target_files(list_of_files: List[Path]) -> Dict[str, str]:
"""Hash each file in list_of_files.
Given a list of files, return a dict containing the file name as
keys and md5 hash as value for each f... | 31714519a5aeada6c43bed94203984584495d954 | 650,845 |
def date_parser(dates):
"""Return list strings in truncated DateTime format ('yyyy-mm-dd').
Args:
dates (list): A list containing string values,
each value in the (DateTime) format 'yyyy-mm-dd hh:mm:ss'.
Return:
Example:
Input: date_parser(['2019-11-29 12:50:54',... | 6f53f5aa13978330333baf941b7696c86045ed6b | 650,846 |
def manhatten(dx, dy):
"""manhatten heuristics"""
return dx + dy | 297210cf040c40f3dabf7b7eec1151d45882bc56 | 650,847 |
import time
def timestamp() -> float:
"""Create timestamp for current time.
Returns:
int: current time
"""
return time.time() | efd1b20a91798c1aac2b9317315de4e3e33a6466 | 650,848 |
import hashlib
import os
import sys
def _get_sha256_hash_of_file(filepath: str, progress: bool) -> str:
"""Compute the SHA256 checksum of a file."""
hash_f = hashlib.sha256()
chunk_size = 1024 * 1024
with open(filepath, "rb") as file_to_hash:
total_mib = os.fstat(file_to_hash.fileno()).st_siz... | 4b62a13f0984d7c17834e5c14ff336e1d440756d | 650,849 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.