content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def notas(*n, situacao=False):
"""
==> função para analisar a nota e situação de vários alunos.
:param n: valores para analisar a situação (aceita vários números)
:param situacao: analisa a situação como ruim, razoável ou boa,
:return: retorna um dicionário com as informações.
"""
dic = dict... | 919d858b741d0bb8b0abcbdb1026189724e94d76 | 684,639 |
def flipped_generation(img, gt_bboxes, gt_label, gt_num, img_shape):
"""flipped generation"""
img_data = img
flipped = gt_bboxes.copy()
_, w, _ = img_data.shape
flipped[..., 0::4] = w - gt_bboxes[..., 2::4] - 1
flipped[..., 2::4] = w - gt_bboxes[..., 0::4] - 1
return (img_data, flipped, gt_l... | e1bef450ef43396a6c85b17034897d9cb33ea253 | 684,640 |
def _pickle_method(m):
""" Pickles a method; required for multiprocessing compatibility with python 2.x
Args:
m (method): method to be pickled
Returns:
pickled_method: pickled_method
"""
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
... | f550865b7e3bdeae6b57ddb3fa1fd6170ba54edc | 684,641 |
import math
def calc_standard_deviation(counts_dict, expected_value):
"""Returns the standard deviation of the histogram of the counts provided as a dict, if the results can be
interpreted as binary numbers"""
sum = 0
for key in counts_dict.keys():
sum += ((int(key, 2) - expected_value) ** 2)... | d034794021d611ae5bb7bdb2b141eee446f13c7b | 684,642 |
from typing import Tuple
def inv_state(tup: Tuple[int, ...]) -> str:
"""Offset by 100 for temperature."""
if tup[0] == 2:
return "ok"
return f"unknown {tup[0]}" | 654900a1dcc0fe04f16ec33d0a1694a12911140d | 684,643 |
import bisect
def clip_around_detections_instant(detections, time):
"""Return the narrowest sublist of detections (a list of Detections)
containing time. If there is a detection at exactly time, try to
expand in either direction.
"""
times = [d.timestamp for d in detections]
lo = max(bisect.... | fa44890108341437664b420a6251ad2a4f0fb0f7 | 684,644 |
import random
def breeding(population, crossover, rate, elite, random=random):
"""Apply crossover operator to the population at the given rate."""
# Save the elites (Lowest N elements).
result = population[:elite]
# Non-elite population size.
n = len(population) - elite
result += (crossover(me... | 2d029d68c616927b9474b62a6728ab41e1d05b46 | 684,646 |
def calculate_interval(timeout_int):
"""Calculates interval based on timeout.
Some customers require long timeouts and polling every 0.1s results
very longs logs. Poll less often if timeout is large.
"""
if timeout_int > 60:
interval = 3
elif timeout_int > 10:
interval = 1
e... | 402ffe83f667fe2f7ee447cfd216062c3b813d3f | 684,647 |
def get_tree_details(nodes):
"""
Creates pertinent tree details for the given list of nodes.
The fields are:
id parent_id tree_id level left right
"""
if hasattr(nodes, 'order_by'):
nodes = list(nodes.order_by('tree_id', 'left', 'pk'))
nodes = list(nodes)
return '\n'.joi... | 33cb4e63fb33b0755dc6fe4eb72aa6be5c591802 | 684,649 |
def get_attribute(s, ob):
"""
Break apart a string `s` and recursively fetch attributes from object `ob`.
"""
spart = s.partition('.')
f = ob
for part in spart:
if part == '.':
continue
f = f.__getattribute__(part)
return f | bdbd92e0ef1d70f4e031ee0f66292c0de93d8813 | 684,650 |
def left_shift(s, times):
"""left shifting a list
"""
for i in range(times):
s.append(s.pop(0))
return s | 845e3255c1df3a1161c9359609c8cc7e1a449351 | 684,651 |
def make_dict(data_for_dict):
""" takes all text from nanpdb list and makes a dictionary.
data_for_dict: nanpd list created with parse_file()
"""
column_name_list = ['Compound name', 'SMILES']
db_list = data_for_dict
column_list1 = []
column_list2 = []
nanpdb_dict = {}... | 4f9c8a714261fa3e786c6505ff80d111ae3b5128 | 684,652 |
import glob
def get_db_files(db_path="./"):
"""retrieve database file names from the file system"""
db_files = [
file.split("/")[-1]
for file in glob.glob(db_path + "*.db")
if file.split("/")[-1] != "geo_zipcodes.db"
]
return tuple(sorted(db_files)) | c6a1341238aa510a91c5e9482ba0f5e547584672 | 684,654 |
def encode_minute(minute=30, month=10):
"""
>>> quick_hex(encode_minute( ))
'0x9e'
"""
low = month & (0x3)
encoded = minute | (low << 6)
return bytearray( [ encoded ] ) | 81da71cfc0344aae1f732a7c29f5dff0498eefcd | 684,655 |
def desi_proc_command(prow, queue=None):
"""
Wrapper script that takes a processing table row (or dictionary with NIGHT, EXPID, OBSTYPE, JOBDESC, PROCCAMWORD defined)
and determines the proper command line call to process the data defined by the input row/dict.
Args:
prow, Table.Row or dict. Mu... | 13fd9c22c5cdb29aeb1f174100be19c253ba1052 | 684,656 |
import random
def random_string(strlen):
"""Our little helper function for creating a random string
"""
return ''.join([
random.choice('ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789') #Note no O (letter 'OH')
for _ in range(strlen)
]) | a3770bb61943bfb7e2ff83b9368571ac05118933 | 684,657 |
import torch
def accuracy_n(output):
"""
Computes the accuracy over the top n predictions for Nx(K+1) class, N label classification.
We assume that the targets are size (N, K+1) where the first element is positive.
"""
with torch.no_grad():
top_n = output.size(0)
k = output.size(1)... | 50d2b58d49c821a46fe02f0ca1af9ccb3b43c13c | 684,658 |
import time
def gelbooru_tag_judge(post, my_config):
"""
判断待排除的tag
:param post:
:param my_config:
:return:
"""
time.sleep(1)
exclude_tags = my_config['exclude_tags']
if list(set(exclude_tags).intersection(set(post['tags'].strip(' ').split(' ')))):
print(post['id'], ' has ex... | cd6c1c7d17bf25be474b9330e317be230f5d81bb | 684,659 |
def get_gdeploy_cmd(gdeploy_file):
"""
Return process args list for gdeploy run.
"""
gdeploy_command = [
'gdeploy',
'-c',
gdeploy_file
]
return gdeploy_command | f23e0690e23e98652deacef05c5e414596acfd71 | 684,661 |
def process_samples(
pf_cond_list, tree_origin_prob_list, tree_our_prob_list, n_batches=None
):
"""Combine the data corresponding to the sampled trees and output the partition.
Estimate according to the formula in the paper. One can see this as just
a simple weighted average.
Features:
1. ... | a5daec8b46fa93ce27ede887d494a55bb51d6d8b | 684,664 |
import hashlib
def sha256sum_pubkey(der_data: bytes) -> str:
"""Return the SHA-256 digest of `der_data`"""
return hashlib.sha256(der_data.rstrip(b"\x00")).hexdigest() | 3540b5b400be419c3d834b0a1846021e3dfc101d | 684,665 |
def get_review_status(context):
"""Gets the review status of an award"""
FSJ_user = context['FSJ_user']
award = context['award']
return award.get_review_status(FSJ_user) | 126a9eeff9cb1650747130040437d7ae3f88bc17 | 684,667 |
import json
import itertools
def get_dumb(book_name):
"""
make sure both online and local version of word book is stored correctly
:param book_name:
:return:
"""
with open('.\\Books\\{}\\{}.json'.format(book_name, book_name), 'r') as f:
book_online = json.load(f)
book_online = ... | 57aa9994f58e3652f15406512f1b2c17c4f3782e | 684,668 |
import os
def check_files(file_path, ext=""):
"""Check expected file paths and extensions, to ensure compliance with
: tool specifications
"""
is_good = True
head, tail = os.path.split(file_path)
if not os.path.exists(head):
return False
if " " in tail:
return False
if... | b2350cd4e3f1c2c8947cef3162cbba62a20c6936 | 684,669 |
def get_frequencies(res, coverage):
"""
Normalize mutation counts by position-specific read depth (coverage)
:param res: list, mutations for each read/pair
:param coverage: dict, read depth per reference position
:return: dict, relative frequency for every mutation
"""
counts = {}
for... | 687de124b0a17a9c87e5b9090699245d4a8a00ea | 684,670 |
def params_deepTools_plotHeatmap_colorList(wildcards):
"""
Created:
2017-05-07 18:26:4
Aim:
Replace palette function with new rules for paths.
"""
tmp = str(wildcards['deepTools_plotHeatmap_colorList_id']);
#v2.2 style
#colorList = {
# 'whiteRed': ... | f7db64d6652d9cab1e609fffa03ab0f84e041230 | 684,672 |
def sign (x):
"""Returns the sign of `x` as `-1`, `0`, or `+1`."""
return 0 if x == 0 else +1 if x > 0 else -1 | 48dac83efb1e9be1c5936695b0c805535187bcc7 | 684,673 |
def _weighted_unifrac_branch_correction(node_to_root_distances,
u_node_proportions,
v_node_proportions):
"""Calculates weighted unifrac branch length correction.
Parameters
----------
node_to_root_distances : np.ndarray
... | 9eb0fabfcbe07b8150f938d5bcb8d502ca75f499 | 684,674 |
def word_tokenize_mock(sentence):
"""Mock the function nlth.word_tokenize."""
return sentence.split(" ") | e60850cd1ed0660e0f0a153433d63c9a3f570a8f | 684,675 |
def number_of_lines(filename=""):
"""Returns the number of lines of a text file.
Keyword Arguments:
filename {str} -- file name (default: {""})
Returns:
Int -- number of lines of a text file.
"""
with open(filename, mode="r", encoding="utf-8") as file:
return len(file.readl... | 63ffab8fa133356354052591e8b29101ad267ad9 | 684,676 |
import os
import glob
def find_project_info( directory ):
"""Find the project_info.cmake or the info.py file
contained in a directory.
Files are searched using the patterns :
1) <directory>/project_info.cmake
2) <directory>/python/*/info.py
3) <directory>/*/info.py
@type directory: ... | 543bf6012519be3ca2c582c34abbbb892fcc5eed | 684,677 |
def build_data(_data, kwds):
"""
Returns property data dict, regardless of how it was entered.
:param _data: Optional property data dict.
:type _data: dict
:param kwds: Optional property data keyword pairs.
:type kwds: dict
:rtype: dict
"""
# Doing this rather than defaulting th... | 707ce1939e2fb6ce4359ed528fcfeac68d37f6b3 | 684,678 |
import re
def filter_setin_files(file_list,matchstr):
""" filter/search the 'set in' file lists. Note
that this output is not autoescaped to allow
the <p> marks, but this is safe as the data
is file paths
"""
# no filters, show last file (if any)
if matchstr == ":":
if... | e98603bf71de60a4b682d620a40745700ad2a52b | 684,682 |
def GetXMLTreeRoot(tree):
"""Get the root node of an xml tree."""
root = tree.getroot()
return root | aa1f1e353ec010267bd6ec32745e001ea4038850 | 684,683 |
def all_files_fixture(
bad_link, link_dir, link_txt_file, tmp_path, txt_file, jpeg_file, zip_file
):
"""Return a dict of different fixture file cases."""
return {
"bad_link": bad_link,
"link_dir": link_dir,
"link_txt_file": link_txt_file,
"tmp_path": tmp_path,
"txt_fi... | 2618523e5b22be05f13c2389556dbda50b663fd9 | 684,684 |
def get_normalized_bath_function(hw_type, bath_function):
"""表4 評価可能な給湯機/給湯温水暖房機の種類
Args:
hw_type(str): 給湯機/給湯温水暖房機の種類
bath_function(str): ふろ機能の種類
Returns:
str: 評価可能な給湯機/給湯温水暖房機の種類
"""
if hw_type == 'ガス従来型給湯機' or hw_type == 'ガス従来型給湯温水暖房機' \
or hw_type == 'ガス潜熱回収型給湯機'... | 1a2cf5a00ef8afc31b60618baabd7241742c9536 | 684,685 |
import os
def _TransformDexPaths(paths):
"""Given paths like ["/a/b/c", "/a/c/d"], returns ["b.c", "c.d"]."""
if len(paths) == 1:
return [os.path.basename(paths[0])]
prefix_len = len(os.path.commonprefix(paths))
return [p[prefix_len:].replace(os.sep, '.') for p in paths] | eb47d8f98413a5e3586882926eda9396c1ac7b5d | 684,686 |
def data_func_called_dec(evaluated=False):
"""
A decorator for the data functions in the DataHolder class
:param evaluated: if the function will be immediately evaluated or not (False)
:return: method
"""
def decorator(func):
def wrapper(self, *args, **kwargs):
""" Log the fu... | cb4922f7c21e01ff4d1c1f0f4622eb53ee705262 | 684,687 |
def append_unless(unless, base, appendable):
"""
Conditionally append one object to another. Currently the intended usage is for strings.
:param unless: a value of base for which should not append (and return as is)
:param base: the base value to which append
:param appendable: the value to append t... | 0ec77b6a5156f03b598abb793264cab2f6a64528 | 684,688 |
import typing
def override_parameter_in_conf(configuration: typing.Dict, override_parameter: typing.Optional[typing.Dict]):
"""
Given a configuration dict (mapping from hyperparameter name to value), it will override the values using an
override dict (mapping from hyperparameter name to new value)
"""... | a3d8fc79c991bee0b7f3078eef640eef94358b55 | 684,689 |
import argparse
def get_arguments():
"""Parsing the arguments"""
parser = argparse.ArgumentParser(description="",
usage='''
______________________________________________________________________
BiG-MAP Family: creates a redundancy filtered reference fna
______________________________________________... | 4c47c4f69ff45738aa86ac8784768b59e308d036 | 684,690 |
import inspect
import logging
def get_module_logger(sublogger:str=""):
""" Return a logger class for the calling module.
Add a 'sublogger' string to differentiate multiple loggers in a module.
"""
caller = inspect.getmodulename(inspect.stack()[2][1])
if caller is None:
caller = __name__
... | be92b0d1f7ce6574f8d33dce03ac937b007b3fbd | 684,691 |
import re
def paragraph_sub(match):
"""Captures paragraphs."""
text = re.sub(r' \n', r'\n<br/>\n', match.group(0).strip())
return '<p>{}</p>'.format(text) | 6e3efb82e9289c5dc5530895893b9e5c520b9713 | 684,692 |
from typing import OrderedDict
def dict_partition(d, keyfunc, dict=OrderedDict):
"""
Partition a dictionary.
Args:
d (dict): the dictionary to operate on.
keyfunc (function): the function to partition with. It must accept the
dictionary key and value as arguments, and should r... | 33c9c22154e1e15ad637381ffd7aa5bc30f1e7a8 | 684,693 |
def prompt_propositions(proposals, message_add="", integer=False):
""" Asks the user to choose from among the proposals.
The propositions must be in the form of a dictionary keys, options.
The user is asked to enter the key of the desired proposal.
If the answer is not in the dictionary keys of proposa... | 4cdf2bc44705571345055e8448f0619e95f2e5bc | 684,694 |
def check_isinstance(item, clazzes, msg=None):
"""
>>> check_isinstance(1, int)
True
>>> check_isinstance(1.1, (int, float))
True
>>> check_isinstance(1.1, [int, float])
Traceback (most recent call last):
...
TypeError: isinstance() arg 2 must be a type or tuple of types
>>> ... | 0d15585c02c78bbf82e2a0cd071c248fb0eea914 | 684,696 |
def convert_y_domain(mpl_plot_bounds, mpl_max_y_bounds):
"""Map y dimension of current plot to plotly's domain space.
The bbox used to locate an axes object in mpl differs from the
method used to locate axes in plotly. The mpl version locates each
axes in the figure so that axes in a single-plot figure... | f1203fa85fafca0f0e75a7ff0018043b58269c3f | 684,697 |
import logging
def label_correcting(graph, start, target, Queue=None):
"""
Find the shortest path in graph from start to target.
Parameters
----------
graph : object
start : object
Node in the graph.
target : object
Node in the graph.
Queue : class
Datastructur... | 625f785f00755b7d530849bcd8667e52a4a9807b | 684,698 |
def parse_counts_line(line):
"""
Parses the counts line of a molecule and returns it asd a dictionary
aaabbblllfffcccsssxxxrrrpppiiimmmvvvvvv
aaa = number of atoms (current max 255)*
bbb = number of bonds (current max 255)*
lll = number of atom lists (max 30)*
fff = (obsolete)
ccc = ... | 98ffa7c1646552f4e5378c01b8c39667ab7664bb | 684,699 |
def weightedAverage(pixel):
"""
"""
return 0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2] | 267e853e29642e30cea298bda2aaadf24f13ce87 | 684,700 |
def trans_matrix(M):
"""Take the transpose of a matrix."""
n = len(M)
return [[ M[i][j] for i in range(n)] for j in range(n)] | 142baf4664d84e10ab68fe094c4eac510abbcf44 | 684,701 |
def format_version_code(version_code: int) -> str:
"""Converts version code of TheoTown to a version name string. Returns original input string on failure."""
string = str(version_code)
length = len(string)
if length == 3:
return '1.' + string[0] + '.' + string[1:]
if length == 4:
re... | 9c99033a54d2efdd53df3c438a3a32bc696c82d4 | 684,703 |
from typing import Counter
def common_words(tokens):
"""common_words find"""
counter = Counter(tokens)
most_occur = counter.most_common(100)
print("Common words in your text")
print(most_occur)
return most_occur | 9e62f870c545a607d4280a907c2c73b2e9da6486 | 684,704 |
def dict2lists(nested):
""" Returns lists for sparse matrix """
rows = [] # cell coordinate
columns = [] # taxonomy id coordinate
values = [] # count
cell_list = [] # same order as rows
taxid_list = [] # same order as columns
j = 0
for ckey, taxdict in nested.items():
for taxk... | c2f8945801fb7c664fb9a8a8fc6f20d5e503eac5 | 684,705 |
from typing import Callable
from typing import Tuple
from typing import Any
import time
def benchmark(function: Callable) -> Callable:
"""Benchmark a given function.
Decorator to run the given function and return the function name and
the amount of time spent in executing it.
Args:
function:... | 0e8a3adeed2132046ec2a15e503c0b4c93d9538f | 684,706 |
import json
def build_keyboard(items):
"""Constructs the list of items, turning each item into a list to indicate that it should be an entire row of the keyboard"""
keyboard = [[item] for item in items]
reply_markup = {"keyboard": keyboard, "one_time_keyboard": True}
return json.dumps(reply_markup) | 99fe9a9040f8094e675c0975c2647f7dcb5389d6 | 684,707 |
import re
def decontract(phrase):
"""
Substitutes occurrences in the text like
n't to not
're to are
'll to will
eg.
haven't -> have not
must've -> must have
:type phrase : string
:returns phrase : decontracted phrase
"""
phrase = re.sub(r"won't", "wil... | 0c49d8f5e5fdedb4f430744379656a4f8fb3dbce | 684,708 |
def index_startswith_substring(the_list, substring):
"""What is this? What is it used for?"""
for i, s in enumerate(the_list):
if s.startswith(substring):
return i
return -1 | 8599dbeebe7f283e74b75ec3b0457fd60135bb2d | 684,709 |
def soundex(name, len=4):
""" soundex module conforming to Odell-Russell algorithm """
# digits holds the soundex values for the alphabet
soundex_digits = '01230120022455012623010202'
sndx = ''
fc = ''
# Translate letters in name to soundex digits
for c in name.upper():
if c.isalph... | d5b73940e21304a976180eaa6f27c7b80113c9a5 | 684,710 |
def review_features(review):
"""feature engineering for product reviews"""
# CREATE A DICTIONARY OF FEATURES (such as sentiment analysis, product id, helpfulness, etc.)
features = {"sample": 5}
return features | d6490369e9850a2b4df2ae87044b2dde67830704 | 684,711 |
def typename(type):
"""
Get the name of `type`.
Parameters
----------
type : Union[Type, Tuple[Type]]
Returns
-------
str
The name of `type` or a tuple of the names of the types in `type`.
Examples
--------
>>> typename(int)
'int'
>>> typename((int, float))... | 3e1e2068dcb460c949b3de3b2ba41b3aa0f9b447 | 684,712 |
def atom_count(data, **params):
"""
Calculate number of occurrencies of a given atomic element in the data.
Args:
data (list): values.
params (kwargs):
atom: element for which occurencies are counted.
Returns the number of occurencies of the atom in the data.
"""
ato... | 326e66a850e9355fb6494bff4a4288223cb5d172 | 684,713 |
def clean_string(string):
"""Clean a string.
Trims whitespace.
Parameters
----------
str : str
String to be cleaned.
Returns
-------
string
Cleaned string.
"""
assert isinstance(string, str)
clean_str = string.strip()
clean_str = clean_str.replace(" ... | a97946cc578112c52d7b9aef1cf4cca9066318ab | 684,715 |
def generate_gbaoab_string(K_r=1):
"""K_r=1 --> 'V R O R V
K_r=2 --> 'V R R O R R V'
etc.
"""
Rs = ["R"] * K_r
return " ".join(["V"] + Rs + ["O"] + Rs + ["V"]) | afd0fedf7b85c733ba8a9fa95bc20e27e3c2d206 | 684,716 |
def _rindex(seq, element):
"""Like list.index, but gives the index of the *last* occurrence."""
seq = list(reversed(seq))
reversed_index = seq.index(element)
return len(seq) - 1 - reversed_index | f9834a0860c5c2fa107a1af39be91a2c918cbf51 | 684,717 |
import numpy
def manhattan_2d(first, second):
"""
Note that this implementation ignores the zero values for
the problems sake.
"""
manh = 0
for i in range(len(second)):
for j in range(len(second)):
# if second[i, j] != 0: # Remove 'if' if you want a full calculation.
... | ba6a9ed268a882359ac2f708bb674203732bb6c2 | 684,718 |
import re
import keyword
def _make_valid_attribute_name(s):
"""Return a string that is a valid Python attribute name.
Leading digits are prefixed with underscores, non-alpha numeric characters
are replaced with underscores, and keywords are appended with an underscore.
This function ensures the strin... | 877f756d37ca8f22e10febe907e2c9def35dcc8a | 684,719 |
def xor(msg, key):
"""
Visual representation of XOR cipher on binary level.
:returns encoded/decoded message as string
"""
print("Message: {}\nKey:\t {}".format(msg, key))
bin_msg = [format(ord(letter), '08b') for letter in msg]
bin_key = [format(ord(letter), '08b') for letter in key]
xo... | d2657a3c50154e7cdf388abda3bc99072813f03d | 684,720 |
def parse_resolution(resolution_string):
"""
Parse and raise ValueError in case of wrong format
@param resolution_string string representing a resolution, like "128x128"
@return resolution as a tuple of integers
"""
tokens = resolution_string.split('x')
if len(tokens) != 2:
raise Val... | c13244a06170e33db213ebceec689a5cb8c72c4f | 684,721 |
def get_reify_options(defaults=None):
"""Reify-related options
"""
if defaults is None:
defaults = {}
options = {
# Resource ID
'--id': {
'dest': 'resource_id',
'default': defaults.get('resource_id', None),
'help': ("ID for the resource to b... | 60e705452850875d893667030a1d4a9f117a8a3e | 684,722 |
def format_elapsed_time(time_delta):
"""
formats a time into desired string format
"""
return "%.2f seconds" % time_delta.total_seconds() | 3e082e1680dafcfaab535322d5d6561d2578d465 | 684,723 |
def get_previous_season(season):
"""
Convert string e.g. '1819' into one for previous season, i.e. '1718'
"""
start_year = int(season[:2])
end_year = int(season[2:])
prev_start_year = start_year - 1
prev_end_year = end_year - 1
prev_season = "{}{}".format(prev_start_year, prev_end_year)
... | 8805644b03ffbb3d81185f6acaa9225a84a0814b | 684,724 |
def db_entry_list_update(db_entry_list, entry_list):
""" Add/update entries in the database """
changed_list = []
for new_entry in entry_list:
found = False
for pos, old_entry in enumerate(db_entry_list):
if old_entry['id'] == new_entry['id']:
found = True
... | 6b6ffe3561d90fffa1a254ed80ca9a0403fb1bb6 | 684,725 |
import os
def splitpath(path, sep=None):
""" Split the path into a list of items """
return filter(len, path.split(sep or os.path.sep)) | f378df265234e903f7574852b07fb3f3b1b5cb18 | 684,726 |
def test_equalto(value, other):
"""Test to see if two values are the same."""
return value == other | e447d9161deeba39f660bc595ff0ea600d7dc129 | 684,727 |
import os
def _app_path(tm_env, instance, uniq):
"""Return application path given app env, app id and uniq."""
return os.path.join(tm_env().apps_dir,
'%s-%s' % (instance.replace('#', '-'), uniq)) | 6e5af182282fac84bd81202f831591570efe85cf | 684,728 |
import re
import sys
def read_count_file(in_file_name):
"""
Read neutron log file
:param in_file_name: neutron log filename
:return: list with all neutron lines
"""
file_lines = []
with open(in_file_name, 'r') as in_file:
for l in in_file:
# Sanity check, we require a d... | e87ed56f430ac5ae76a6791130f12b1519c41f39 | 684,730 |
import bisect
def _find_closest(sorted_values,
value,
before=False):
"""
Convenience function for finding the list index of the first (leftmost) value greater than x in list sorted_values.
:param sorted_values:
:param value:
:param before: if True then re... | 7964e9353684af3359d1081a527a3ab238876ddd | 684,731 |
def fixt3(fixt1, fixt2):
"""Some really usefull
fixture
"""
return fixt1 * fixt2 | 5ace838f88d73c2531d6867f4e4cc10d111a9535 | 684,732 |
def get_indentation(line):
"""Returns the indentation (number of spaces and tabs at the begining) of a given line"""
i = 0
while (i < len(line) and (line[i] == ' ' or line[i] == '\t')):
i += 1
return i | 1c173c7aca678d62af02de0e077a1ec365ab3e31 | 684,733 |
def val_cm(val):
"""
arg val is tuple (2.0,'mm').
Return just the number in cm.
"""
if val[1] == 'cm':
return val[0]
if val[1] == 'mm':
return val[0]/10.0
if val[1] == 'm':
return val[0]*10
if val[1] == 'nm':
return val[0]/1E8 | a7f25beab01a0f860d8c8a76bb26e6a7e8eb38ea | 684,734 |
import argparse
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test Speed')
parser.add_argument('--img_dir', dest='img_dir',
help='images path',
default='/data/dataset/HRSC2016/HRSC2016/Test/A... | 4781897ecb48c835f2fa91e03e87ee4d2ff159eb | 684,735 |
import random
def fumble():
"""ファンブル表を振る"""
i = random.randrange(1,7,1)
num_to_kanjo = {1:"1: 何か調子がおかしい。そのサイクルの間、すべての行為判定にマイナス1の修正がつく。",
2:"2: しまった! 好きな忍具を1つ失ってしまう。",
3:"3: 情報が漏れる! このゲームであなたが獲得した【秘密】は、他のキャラクター全員の知るところとなる。",
4:"4: 油断した! 術の制御に失敗... | 0d8b200093593ba04ce572e87237f3cf79b011e4 | 684,736 |
def create_indices_slicers(main_slicer, n_procs):
"""Create slicers for individual split units."""
start, stop, step = main_slicer.start, main_slicer.stop, main_slicer.step
limits = [start+stop/n_procs*(i+1) for i in range(n_procs-1)]
limits = [start] + limits + [stop]
limits = [[limits[i], limits[i... | dd2203101d49b21574148291681abdb30ac4f301 | 684,737 |
import socket
import gevent.socket
import warnings
def gevent_monkey_patched():
"""Check if gevent's monkey patching is active."""
# In Python 3.6 importing gevent.socket raises an ImportWarning.
with warnings.catch_warnings():
warnings.simplefilter("ignore", ImportWarning)
try:
... | aa712dc39b936c98820f540a5e5a62a7e9b048d9 | 684,738 |
def merge_diffs(d1, d2):
"""
Merge diffs `d1` and `d2`, returning a new diff which is
equivalent to applying both diffs in sequence. Do not modify `d1`
or `d2`.
"""
if not isinstance(d1, dict) or not isinstance(d2, dict):
return d2
diff = d1.copy()
for key, val in d2.items():
... | 7314ad63a4679308d27bcff956c9b570d89df8a7 | 684,739 |
def findTheDistanceValue(self, arr1, arr2, d):
"""
:type arr1: List[int]
:type arr2: List[int]
:type d: int
:rtype: int
"""
final_count = 0
for i in range(len(arr1)):
count = 0
for j in range(len(arr2)):
diff = abs(arr1[i] - arr2[j])
if diff>d:
... | 036d538cad565eb0c16a5f809d50af2a20374987 | 684,740 |
def binary_search(A, key, low, high):
"""
Implementation of Binary Search Recursive Method
Below function perform sa binary search on a sorted list
and returns the index of the item if it;s present else returns false
:param list: a sorted list
:param key: key to search from given sorted list
... | f9cb6237365519acaebc26e225617e8e60935783 | 684,741 |
import os
import itertools
import subprocess
def test_combinations(log_dir="./morphnet_log",
csv_filename="morphnet_test_results.csv",
num_cuda_device=4):
"""
Test the MorphNet model zoo configuration combinations. Most of the networks and MorphNet regularization co... | e2fd5840f299fb2111f05742c5b6852f38874e1b | 684,742 |
def subsample_image(input_image, zoom_box_coords):
"""
Crops the input image to the coordinates described in the
'zoom_box_coords' argument.
Args:
input_image (numpy.array): The input image.
zoom_box_coords (tuple, list): Coordinates corresponding to the first
(low-resolution)... | 22b7d4e0b4e964c0e97ed5be9b3770f64bc9894b | 684,743 |
import random
import string
def _getText():
"""4位验证码"""
return ''.join(random.sample(string.ascii_letters + string.digits, 4)) | bb9bdc9803f37f41675d5c9320103b9abf757800 | 684,744 |
import requests
def get_auth(url: str, login: str, password: str) -> tuple:
"""
Function get authentication token and user ID from Rocket.Chat.
:param url: Rocket.Chat API login URL
:type: str
:param login: Rocket.Chat user login
:type: str
:param password: Rocket.Chat user password
:... | f7aece915415cd136a042534eee641b3ac7663ff | 684,745 |
def read_part_data(stream, size, part_data=b'', progress=None):
"""Read part data of given size from stream."""
while len(part_data) < size:
bytes_to_read = size - len(part_data)
if bytes_to_read > 16384:
bytes_to_read = 16384
data = stream.read(bytes_to_read)
if not ... | c4f7802048b571430f44b7f03b5e0303dac7c0de | 684,746 |
def split(list_to_split, amount_of_parts):
"""Split a list into equal parts
Args:
list_to_split: Any list
amount_of_parts: Number of equally sized parts
Returns:
splitted list as list of lists
"""
k, m = divmod(len(list_to_split), amount_of_parts)
return (list_to_split... | b5355d1c3f2bd271df969a92c72ffcece7d66bcc | 684,747 |
def input_profile(t, x0):
"""
calculate the user input x as a function of time
x0 is the initial value
ramp down from 100% to 50% load at 5%/min rate
hold for half an hour
ramp up from 50% to 100% load at 5%/min rate
hold for 20 minutes
"""
if t < 60:
x = x0
elif t < 660:... | f69a1fd1afa09b7dfcb9ab5ba7d0111e0ca3022c | 684,748 |
def get_events():
"""Return a JSON object of event data for AJAX"""
return "[]" | 17dac6c8bea6bfe1b7c298cb9d021b8f3f6349ef | 684,749 |
def corr_shift(x, y, x_shift=0, y_shift=0):
"""compute the correlation with shift
Args:
x (series): first series
y (series): second series
x_shift (int, optional): shift of first series. Defaults to 0.
y_shift (int, optional): shift of second series. Defaults to 0.
Returns:... | 3d209c9649cf9084fd2e46108069256bff243afc | 684,750 |
import argparse
def parse_args():
"""Parse input arguments"""
parser = argparse.ArgumentParser(description='Calculate mutual exclusiveness between markers')
parser.add_argument(
'--in_path', dest='in_path', required=True,
help='Path to extracted mean intensities')
parser.add_argument... | 86be42f92b78f6bf0233771ba3042c057dcef076 | 684,751 |
def bond_features_v1(bond, **kwargs):
""" Return an integer hash representing the bond type.
flipped : bool
Only valid for 'v3' version, whether to swap the begin and end atom types
"""
return str((
bond.GetBondType(),
bond.GetIsConjugated(),
bond.IsInRing(),
... | 155970eb707fcfa8dcbb67d97f1be33626856286 | 684,752 |
def GetOperationError(error):
"""Returns a human readable string representation from the operation.
Args:
error: A string representing the raw json of the operation error.
Returns:
A human readable string representation of the error.
"""
return 'OperationError: code={0}, message={1}'.format(
e... | 02d41be83d612c2076c35047e31664127036b0ea | 684,753 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.