content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import time
def timer(f):
"""Calcule et affiche la durée d'exécution d'une fonction unaire"""
def wrapped(x):
start = time.time()
value = f(x)
end = time.time()
print(f"Durée {end - start} secs")
return value
return wrapped | 8c285774e0a0e85dffa6010487a122b5800f1afc | 632,414 |
import re
def columnidentifier_to_tablename(name):
"""
Column's table is determined implicitly
eg. "SELECT value" as opposed to "SELECT a.value" or "SELECT table.value"
"""
match = re.match(r'^`(.*)`\..*$', name)
if match:
return match.groups()[0]
match = re.match(r'^(.*)\..*$', n... | 8d3e2baa1c3d8580e2121e11c8bfe65d6b336157 | 632,415 |
def mystery_1b_nested(n: int, rows_of_nums: list[list[int]]) -> int:
"""Mystery 1b."""
if len(rows_of_nums) > n > 0:
if n == 1:
return 0
elif n in rows_of_nums[n]:
return sum(rows_of_nums[n]) + n
else:
return sum(rows_of_nums[0])
else:
if l... | 04926f667e8182a40f454a2b66486b613b3ca7b6 | 632,416 |
def rendered_source_for_lang(page_pk, lang):
"""Create cache key for rendered page source based on current language"""
return 'powerpages:rendered_source_lang:{0}:{1}'.format(page_pk, lang) | 7ee0eb4e27c2f7274f6ae4ffeac9814fa3babf8c | 632,417 |
def render_comment(comment):
"""
Inclusion tag for rendering a comment.
Context::
Comment
Template::
questions/comment.html
"""
return dict(comment=comment) | 05310537d46ba55e9dd68f117fde3f73d85e968c | 632,418 |
def ensembl_transcripts_response():
"""Return a (cropped) response from ensembl tx api"""
_response = [
{
"biotype": "protein_coding",
"assembly_name": "GRCh38",
"seq_region_name": "7",
"feature_type": "transcript",
"ccdsid": "CCDS5862.1",
... | 1526ec34a0b627da44eb4d82707432c0b96c5f46 | 632,419 |
def reverseWords(self, s): # ! 常规方法
"""
:type s: str
:rtype: str
"""
s_arr = s.split(" ")
result = []
for item in s_arr:
result.append(item[::-1])
return " ".join(result) | ac0ae7ed5fb387fd3ec40dd86418f288a6d5f504 | 632,421 |
def match(line, keyword):
""" If the first part of line (modulo blanks) matches keyword,
returns the end of that line. Otherwise checks if keyword is
anywhere in the line and returns that section, else returns None"""
line = line.lstrip()
length = len(keyword)
if line[:length] == keyword:
... | 8d629ebabe9c476670206c9758732b99d12d70a9 | 632,422 |
def triangle_area(node1,node2,node3):
"""
area of a 2D triangular cell
which is assumed to be ordered counter clockwise.
1 2
o------------o
\ .
\ .
\ .
\ .
o
3
Note: Area... | d60fd45bd1ce2bea455d9b61f9423597dc33c940 | 632,423 |
def extract_spans(indices):
"""
Handles discontinuous, repeated FEs.
In PropBank, the equivalent is reference-style arguments, like R-A0
:param indices: list of array indices with the same FE
:return: list of tuples containing argument spans
"""
indices.sort()
spans = [(indices[0], indic... | 3bfb2f19338322d6ccb8f3447acc6580bd46cf45 | 632,424 |
def convert_bool(column):
"""
Convert text into bool in given column.
- column: series to be converted
- return: converted column
"""
def _convert_bool(text):
if text in ["Y", "y", "1"]:
return True
else:
return False
if column.name in ["acti... | 92bd2a612bda3b1dfb9e5ea3f1ba7fda5fe1d334 | 632,425 |
def vec_dot_star(v1,v2):
""" Returns dot* (dot star) product of 2 2D vectors
the sign of the dot* shows if the v2 is to the left or to the right from the v1"""
dot_star = v1[0]*(v2[1])-v1[1]*v2[0]
return dot_star | 5204caee69af09edb0446a8432e201e293091ee8 | 632,426 |
import copy
def runtime_object(init_value):
"""object with value equal to init_value after each deserialization (for living at run-time objects)"""
def _constructor(*args):
return copy.deepcopy(init_value)
return _constructor | 3158a6345db647f19f906f7266d8e5dd77dad446 | 632,427 |
import random
def get_secret_key():
"""Rturn a 14 lenght random string
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = [alphabet[i] for i in range(52)]
sk = ""
for i in range(14):
temp = random.choice(range(52))
sk = sk + letters[temp]
s... | 3489f90de852492e74daf8b3aade8799416691e3 | 632,428 |
def sum(x, y):
"""Sum x and y
>>> sum(10, 20)
30
>>> sum(-10, 20)
10
>>> sum('10', 20)
Traceback (most recent call last):
...
AssertionError: x needs to be in or float
"""
assert isinstance(x, (int, float)), 'x needs to be in or float'
assert isinstance(y, (int, float)), 'x needs to be in or float'
re... | 9b4691df287c1663aeff4bc001cc5291f1ceaf86 | 632,429 |
def SGD(lr=0.001, momentum=0):
"""SGD Optimiser.
:param lr: Learning rate
:type lr: float
:param momentum: Momentum
:type momentum: float
"""
return {
"optimiser": "SGD",
"opt_args": {
"lr": lr,
"momentum": momentum
}... | 612b06f1f8a6815d80ea4c425fd24922c067ed2b | 632,430 |
import os
import shutil
def copy_dir_tree(src, dst, symlinks=True, ignore=None):
"""
copytree a directory
Args:
src: source directory
dst: destination directory
symlinks: copy symlinks
ignore: ignore
Returns:
True
"""
# https://stackoverflow.com/a/1251... | 77529031dbc376a1df88e1c1c8f1c5fc285974e3 | 632,432 |
def infinite_check(graph_array, distance):
"""Runs the Bellman-Ford algorithm to look for infinite loops."""
## Check for negative-weight cycles:
## For each node_1:
for node_1, edges in enumerate(graph_array):
## For each node_2:
for node_2, edge in enumerate(edges):
## If ... | 8b7d8f8c3ddc1c451b5697defefb43fedc3b39bf | 632,433 |
def get_event_log(isdsAppliance, check_mode=False, force=False):
"""
Get Event Log
"""
return isdsAppliance.invoke_get("Retrieving Event Log", "/events/system") | 63bf90481eb606da6ab0643d2fc60fc8c6d3b166 | 632,434 |
import requests
def add_danmaku(content):
"""
添加弹幕
:param content: 弹幕内容
:return: 是否成功
"""
try:
res = requests.post('http://localhost:12450/danmaku',
json={'content': content})
except:
return False
return res.status_code == 200 | 037ec06f6a6cf7bdd6713b4f7c8ab930995aa17e | 632,436 |
def extract_include_files(args):
"""
Extract include files from command-line arguments.
Recognizes two argument "-include file".
"""
includes = []
prefix = ""
for a in args:
if a == "-include":
prefix = "-include"
elif prefix:
includes += [a]
... | 8e7bafa98f8b39e08a43b8911b5286bf52a3f656 | 632,437 |
from typing import List
def generate_reason(total_points: int, message: str, recipients: List[str]) -> str:
"""
:param total_points: the amount of points that should be distributed
:param message: the message used when awarding points
:param recipients: a list of email addressed for users who should r... | 17185f706949bc92f04c66a65a734badb242d9dd | 632,438 |
def load_data(filename):
"""
读文件,x数据直接补上 bias
"""
x = []
y = []
with open(filename, "r") as fp:
for line in fp:
_x1, _x2, _y = line.split(",")
x.append(list(map(float, [_x1, _x2])))
y.append(float(_y))
return x, y | bc0dd21819e4475dc13819e7874cdfe0288cf780 | 632,439 |
def OneMWDWPatternPerTour_idx_rule(M):
"""
Index based on activeTT so that we can create schedules for any subset
of tour types used in the Phase1 problem.
"""
index_list = []
for s in M.TOURS:
if M.TT_x[s] in M.activeTT and M.WIN_x[s] in M.activeWIN:
index_list.append(s)
... | 72166687100a37c740901a3ed78f83c5149e16c9 | 632,440 |
import argparse
import importlib
from datetime import datetime
def inference_parser_args():
"""
parser_args for inference
"""
parser = argparse.ArgumentParser(description='Inference infos')
parser.add_argument('--config_file',type=str,required=True,help="same as train")
parser.add_argument... | debea7723ddcc265123e1787ce61db46167ee528 | 632,441 |
def convert_to_signed_integer(value, size):
"""
:param int size: number of bits containing this integer
"""
upper_bound = 2 ** size
if not (-upper_bound // 2 <= value < upper_bound):
msg = '{} is out of range of {} bits'.format(value, size)
raise ValueError(msg)
if value >= 0:
... | cc798d34ed051bb7e0d1a811000b07f9813c9486 | 632,442 |
import codecs
def read_conll_char_corpus(path, max_chars=None):
"""
:param path:
:param max_chars:
:return:
"""
dataset = []
textset = []
with codecs.open(path, 'r', encoding='utf-8') as fin:
for payload in fin.read().strip().split('\n\n'):
data = ['<bos>']
... | 82d7ce4fbcdae3ff4255a4b8307736e37acef78f | 632,444 |
import sys
import os
def is_exe_in_path(name):
"""Checks whether an executable is in the user's search path.
This expects a name without any system-specific executable extension.
It will append the proper extension as necessary. For example,
use "myapp" and not "myapp.exe".
This will return True... | 1dae6da2a64e6220170e2fe5c72234fd9a9aadeb | 632,445 |
def elapsed_time_format(seconds):
"""Returns human readable string for elapsed time"""
negative = seconds < 0
seconds = abs(int(seconds))
periods = [
('year', 60 * 60 * 24 * 365),
('month', 60 * 60 * 24 * 30),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('minute', 6... | b70493048d540a99dc459d44ccdb5889ad4c2060 | 632,446 |
def weight_by_order_type(phase_type, order):
""" Calculate the new weight for the order using the perc of orders with this order type for the given phase
as calculated in the dataset. (e.g. 20% of orders in a movement phase are H)
:param phase_type: The current phase type ('M', 'R', 'A')
:pa... | 3a3bdc08622f2894183faeaa947e10781ba92bf6 | 632,447 |
def change_input_str_to_time_list(input_time_str):
"""根据命令行输入的内容创建要下载的时间列表"""
time_list = input_time_str.split(',')
return time_list | 42f9d6ee7ca89aacca21427bd749be621ef463b4 | 632,448 |
def simplify_ft(data, normalize=True):
"""
Remove irrelevant bins and normalize the FT data between 0 and 1
The irrelevant bins are the offset bin and the bins that belong to
the negative frequency spectrum.
@data is a 2D (Nx2) np.array containing the output of a 1D, where N
is the amount of s... | d720c8835825e6f8e072e06c3f84e056c8d1c1cf | 632,449 |
import argparse
def get_args():
"""
Args used for running 3D UNet KITS19
"""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--backend",
choices=["pytorch", "pyto... | 0a0c8b84268eecf07c6ad69c2566b7454678d894 | 632,450 |
import argparse
def positive_int(x):
"""Argument value parser: positive integers."""
try:
n = int(x)
if n <= 0:
raise ValueError()
return n
except ValueError:
raise argparse.ArgumentTypeError(
'invalid positive int value: {}'.format(x),
) | 3e328431cfe98d62d6b2f1b63a09c601de0a106b | 632,452 |
def validate_format(meta, method, type):
"""
Method to check for the metadata structure of the Acumos Model
due to change in tree structure of the input and output with Acumos-Demeter's release
Solution for Issue id: DCAEGEN2-2825
"""
try:
df_name = meta["methods"][method][type]["name"]
... | 09f828574a736f5004e745e0f6750d3b85cdb71d | 632,453 |
import requests
def get_raw_content_from_url(url):
"""
Args:
url: string starts with 'http://'
Returns: string of raw text of the html page
"""
assert url.startswith('http://')
response = requests.get(url=url)
if response.status_code == 200:
response.encoding = 'utf-8'
... | 2fdf146c4b3319c6d5e4c6a04ada734ac17f3e43 | 632,454 |
import hashlib
def get_bytes_hash(bytes, hash_function=hashlib.md5, chunk_size=4096):
"""
Return hash of byte stream.
Adapted from quantumSoup at https://stackoverflow.com/a/3431838.
"""
hash = hash_function()
for chunk in iter(lambda: bytes.read(chunk_size), b""):
hash.update(chunk)
... | 728f5f233d0f92f7e02003d5448e87b0e7fad0d0 | 632,455 |
import torch
from typing import Tuple
def tanh_warp_transform(
coords: torch.Tensor, matrix: torch.Tensor,
warp_factor: float, warped_shape: Tuple[int, int]):
""" Tanh-warp function.
Args:
coords (torch.Tensor): b x n x 2 (x, y). The original coordinates.
matrix: b x 3 x 3. A ... | fd72470444518c4191755fdb34f98e787abfd554 | 632,456 |
import uuid
def get_uuid():
"""
Generates UUID and returns as string. With one caveat,
if app.config[USE_SEQUENTIAL_UUID] is set and True
then uuid_counter is returned and incremented
:return: uuid as string
"""
return str(uuid.uuid4()) | 10e4c9e2cc0a3f4a1a65cfa1af685cbdd73dade3 | 632,458 |
def printOptionByType(option):
"""
Format l'option selon son type
Args:
option: L'option
Returns:
L'option formatee
"""
if option.isdigit() or option == "true" or option == "false":
return option
else:
return '"' + option.replace("\"", "'") + '"' | 8996a130aed5799c7ad657c0ba0c88beb4d7051b | 632,459 |
def _get_installed_version(name, installed_list):
"""Return installed version of package"""
try:
return [x for x in installed_list if x.name == name][0]
except IndexError:
return None | d3499eb511814907b6936c631a23c859041c45a7 | 632,460 |
def request(label, selection, blocklist=()):
"""
Request an input from the user against an allowlist and/or a blocklist.
Will continue to request user until an acceptable value is entered.
...
Parameters
---
label: string
a instruction for the user
... | f94b348b34ee00195072e35088102e45cba52b1e | 632,461 |
from typing import List
def parse_vector(text: str, count: int) -> List[float]:
"""Parse a space-delimited vector."""
parts = text.split()
if len(parts) != count:
raise ValueError(f'{text!r} is not a {count}-dimensional vector!')
return list(map(float, parts)) | c5b60afdb41768d17abacf375bc7e1e7893bedfb | 632,462 |
def screen(a, b, max_possible=255):
"""Blend two arrays together using the 'screen' mode.
Good for combining color-tinted fluorescence images with brightfield, for example.
Parameter 'max_possible' refers to the brightest-possible value in the array.
E.g. 1 for images scaled from 0 to 1, or 255 for ima... | bd971d4a26d5ad6690e1007f3a96ac171fb4bd29 | 632,463 |
import numpy
def indexed(vec, start, offset=1) -> dict:
""" Indexed an array-like object(list,tuple,etc) by integer, auto increment """
assert hasattr(vec, '__iter__')
assert isinstance(vec, (tuple, list, numpy.ndarray))
vec = list(set(vec))
vec.sort()
end = len(vec) * 2 + start
return {k:... | 6e48425cf3c1c1e52468efaebb087b115bfa56f0 | 632,464 |
import numpy
def compute_ax_row_positions(row_heights, ax_spacing=0.1):
"""
Given a sequence of row heights (in inches), and the size of the space to put between
axes (in fractions of total row height), returns a list of bottom coordinates
and heights for each row, suitable for passing to the fig.add_... | ebb334e9973967e99c8023bcd1eeacab4a2c1b6a | 632,465 |
def ansible_module(ansible_adhoc):
"""Return a subclass of BaseModuleDispatcher."""
host_mgr = ansible_adhoc()
return getattr(host_mgr, host_mgr.options['host_pattern']) | 200dab58c72ac81fd3422659de7f289392a03869 | 632,466 |
def populated_attrs(lst):
"""Set with attr names which are not None in all objects in `lst`."""
attr_lists = [[name for name in obj.attr_lst \
if getattr(obj,name) is not None] for obj in lst]
return set.intersection(*(set(x) for x in attr_lists)) | 0003a6f0dc19aa85213709c853d5104a767ebe3e | 632,467 |
def dna_to_rna(dna):
"""
Transcribes dna to rna.
Args:
dna (str): DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T').
Returns:
str: rna where 'T' is replaced by 'U'.
"""
rna = dna.replace("T", "U")
return rna | d4f5b7bfbc6c94e7a2c93ec03737fdd7c1d84324 | 632,468 |
import torch
def mmd_polynomial_kernel(x, y, alpha=2):
"""
compute a polynomial kernel for vector x and y
:param x: data list
:param y: data list
:param alpha: parameter for the polynomial kernel
:return: the polynomial kernel
"""
n, c, h, w = x.size()
x = x.view(n * c, h * w)
... | c7934a4bf2e454961b96f9e77eba6e24c79d47cf | 632,469 |
def lcoh(energy_demand, heat_load, energy_price,
specific_investment_cost, fix_o_and_m, var_o_and_m,
efficiency_heatingsystem, r, lt):
""" This function calculates the Levelized Costs of Heating for a heating
system that has constant variable costs and he... | 4be9ed3c2a7f6f5bd2074b3ed205ce123dce8eb0 | 632,470 |
from sys import path
def load(filename):
""" Load tsv files and convert to a list of dictionary """
dataList =[]
with open(path+filename, 'rU') as f:
lines = f.readlines()
f.close()
header = lines[0].strip().split('\t') # assume all keys are in first line
for i in range(1,len(lines... | 1e40a4067a2e24b94e8789deb3f5f9bca3c600d2 | 632,471 |
import os
def librato_email(email=os.environ.get('LIBRATO_EMAIL')):
"""Return librato email from an environment variable"""
return email | 68e4784d486a46aa7c91d857d1a01dc73b72dc70 | 632,472 |
def _expand_line(line, vars):
"""! Expands a line.
Expands a line by expanding @@[+-]VARNAME@@ to its value in \p vars.
\see expand_file()
"""
for var in vars:
line = line.replace('@@' + var + '@@', vars[var]) \
.replace('@@+' + var + '@@', vars[var].upper()) \
.replace('@@-' + var + '@@', va... | 179000aa7dac24fbbc90bbd8e809319013a1dfe5 | 632,473 |
def load_merge(file_path):
"""Load from merge file"""
merge_file_path = file_path.replace('ann.xml', 'txt.merge')
props = []
with open(merge_file_path) as f:
for line in f:
if line == '\n':
continue
props.append(line.split('\t'))
recovered_string = ''... | 39d771172617918bdeaa0b1456e2ef871449d855 | 632,474 |
from typing import List
def golomb_cl(number: int=1) -> List[int]:
"""Кластера последовательности Голомба
:param number: количество кластеров, defaults to 1
:type number: int, optional
:return: n первых кластеров последовательности Голомба
:rtype: List[int]
"""
sequence = [1, 2, 2]
if... | 2f576809644df7c3791f0f87afd78372e0b0c80c | 632,475 |
import os
import locale
def _get_exception_encoding():
"""Return the encoding we expect messages from the OS to be encoded in"""
if os.name == "nt":
# GZ 2010-05-24: Really want the codepage number instead, the error
# handling of standard codecs is more deterministic
re... | 29009abad30dc2b9f4668223929586c8a7dcf929 | 632,476 |
from typing import Union
import os
import json
def read_service_info(service_info_file: str) -> Union[dict, None]:
"""
Get a dictionary with WebAPI service information:::
{
"port": service-port-number (int)
"address": service-address (str)
"caller": caller-name (st... | 5911547be5c8c51e781607558c47a432231b2cab | 632,477 |
def _preprocess_transcript(phrase):
"""
strip the phrase
Args:
phrase:
Returns:
"""
return phrase.strip().upper() | a29adcf53a186f3672f102708df80252ea9c308d | 632,479 |
import random
def rand_byte(value=(0, 255)):
""" random byte """
if type(value) is int:
return value
elif type(value) is tuple:
return random.randint(value[0], value[1])
return random.randint(0, 255) | 2415a93f3b2ced4bcd027760350bc9c18b9dcd3a | 632,480 |
def add_counters(dic, arr):
"""
Keep track of how many times a type of layer has appeard and
append _counter to their name to maintain module name uniqueness.
"""
ret = []
for el in arr:
name = el[1:-1]
num = dic.get(name, None)
if num is not None:
ret.append(... | f4d27f13a5d27d7d015b0e99a034c849ebb2e177 | 632,481 |
def get_directions(position):
"""Returns all the possible directions of a player in the game as a list.
"""
assert 0 <= position <= 23, "illegal move"
adjacent = [
[1, 3],
[0, 2, 9],
[1, 4],
[0, 5, 11],
[2, 7, 12],
[3, 6],
[5, 7, 14],
[4, 6... | d20e4bd1aa6cd0e00e31cb148f6bf3eca74c3e5e | 632,483 |
def is_tel_link(href=None):
"""Utility function to determine whether the supplied href
attribute is a telephone link."""
print("is_tel_link()")
return href and 'tel:' in href | b113ded3a35d84b83f44f3084b681637897fbdaf | 632,484 |
import os
def get_configin_file(comp_dir):
""" Find Config.in in the specific directory """
config_file = os.path.join(comp_dir, "Config.in").replace("\\", "/")
if os.path.isfile(config_file):
return config_file
else:
return "" | 79edf90e92599c870a84d916de0d99f5bd8af5d3 | 632,485 |
def _check_params(p, speciesDict,xb):
"""
Check to see if any of the parameters in p fall outside the range
given in speciesDict or on the boundaries
**Parameters**
:p: (3,) ndarray
array with form [[N1, b1, z1], ...]
:speciesDict: dictionary
dictionary with properties g... | cc9878194dda367f1d18984e4a77b7b3fabb4284 | 632,486 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_crowdstrike_falcon package"""
reload_params = {"package": u"fn_crowdstrike_falcon",
"incident_fields": [],
"action_fields": [],
"function_params": [u"cs_action_name", u"cs_de... | ec8de8de364fc9885db809bcea5df2b50c2a81d4 | 632,487 |
def stream_set_write_buffer(interp, w_res, buffer):
""" Sets write file buffering on the given stream"""
### mockup only
return interp.space.newint(0) | 4c165d6b525c2bd929a60aab641924e3077f77d3 | 632,488 |
def initialize_tensor_board(dimensions, value):
"""
Initializes board with 0s.
Parameters:
dimensions (tuple): dimensions of the board
Returns: an nD board
"""
# Base case
if len(dimensions) == 1:
return [value for i in range(dimensions[0])]
# Iterative c... | 29109a224e959d8381fdd58a2701ed0adecf6913 | 632,489 |
def to_bytes(object):
"""
Convert an object to bytes-like object.
:param object:<object> The object to be converted.
:return:<bytes> A bytes-like object.
"""
if type(object) is str:
return object.encode()
return bytes(object) | 78af9454a817961826a4fb132ae674b11216ceee | 632,490 |
def render_path(pod, path):
"""Given a pod and a path render the path."""
matched = pod.match(path)
controller = pod.router.get_render_controller(
matched.path, matched.value, params=matched.params)
jinja_env = pod.render_pool.get_jinja_env(
controller.doc.locale) if controller.use_jinja... | 75b2cff133c4912a3c23d1afe606ebbd46754409 | 632,491 |
import os
import json
def readm():
"""
Read the json data extracted by the gen_data commands.
"""
jname = '..' + os.sep + 'gen_data' + os.sep + 'group_picks.json'
with open(jname, 'r', encoding='utf8') as json_file:
jdata = json.load(json_file, encoding='utf-8')
return jdata | a55ec00ec123e6fa4c09e03b9bebc7b57439e04d | 632,492 |
import logging
def foo(s: str) -> float:
"""
Sample function to interpret the given string as a floating-point number,
and return its result when divided by 10.
:param s: str
:return: float
"""
n = int(s)
logging.info(f'n = {n}')
return 10 / n | 70eba99f9a0b759a37e6810af374c6283df32c10 | 632,493 |
import inspect
import sys
def uid_to_sop_class(uid):
"""Given a `uid` return the corresponding SOPClass.
Parameters
----------
uid : pydicom.uid.UID
Returns
-------
sop_class.SOPClass subclass
The SOP class corresponding to `uid`.
Raises
------
NotImplementedError
... | c2b09b8b7ab0d50849046a92e20751682530156f | 632,494 |
import itertools
def decode(data):
"""Decode a DISPLAY REGISTERS screen dump as binary data."""
top_rows = ''.join(data[::2])
bot_rows = ''.join(data[1::2])
all_hex = ''.join(itertools.chain.from_iterable(zip(top_rows, bot_rows)))
return bytes.fromhex(all_hex) | c7ba055356ba8baa2a3737042ab847064cf1280f | 632,495 |
def _path_is_under_fragments(path, path_fragments):
"""Helper for _ensure_asset_types().
Checks that the given path is under the given set of path fragments.
Args:
path: String of the path to check.
path_fragments: List of string to check for in the path (in order).
Returns:
True/Fa... | d267da755b733e815b8ac1bb65557f3b750ee828 | 632,496 |
def n_wise(iterable, n):
"""Use to separate an iterable by n-elements groups"""
a = iter(iterable)
return zip(*[a] * n) | b623d2da3ff5d1b6c1a01c362c0ed70137ed6c7f | 632,497 |
def _equalsIgnoreCase(a, b):
"""
Return true iff a and b have the same lowercase representation.
>>> _equalsIgnoreCase('dog', 'Dog')
True
>>> _equalsIgnoreCase('dOg', 'DOG')
True
"""
return a == b or a.lower() == b.lower() | 82aeac9c4bd7168f823d0b95541512b471893249 | 632,498 |
def _rds_to_list(ws):
"""
Returns filtered list of roads
:param ws:
:return: road_list
"""
roads_ws = ws
rds = []
for row in roads_ws.rows:
vals = [cell.value for cell in row]
rds.append(vals)
rds_no_header = rds[15:] # clip TNM2.5 header
roads = []
f... | 47cb5d406d50507446ebb3aed0c21d4ff1048478 | 632,499 |
import os
def read_responsiveness_per_year(input_folder, json_data):
"""
Reads the responsiveness scores of the corresponding summaries and stores them into the json_data
:param input_folder: The corresponding folder where the data of the year are stored
:param json_data: The data at the form of dicti... | 02cfe9597a9a207a962419c849c2769374ec472d | 632,501 |
def decisioning_engine_ready(decisioning_engine):
"""Checks if decisioning engine is ready"""
return decisioning_engine if decisioning_engine and decisioning_engine.is_ready() else None | fccbf0d9d65cdd4f9f2271f206032bf5dc01dacb | 632,502 |
def get_users_for_manager(manager, valid_users):
"""get_users_for_manager(manager, valid_users)"""
users_for_manager=[]
for user in valid_users:
user_manager_email=user["manager"]
if (user_manager_email == manager["email"]):
users_for_manager.append(user)
return users_for_ma... | 450ad1321a5129c908b3baf28913c23ba1c343c3 | 632,504 |
from operator import xor
def find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, inside_closedpath,
t0=0., t1=1., tolerence=0.01):
""" Find a parameter t0 and t1 of the given bezier path which
bounds the intersecting points with a provided closed
pa... | 7a83732096e565281e8664fbdb02e7bf999ad9a1 | 632,507 |
def add_trailing_slash(path):
"""If path does not have a trailing slash, append one"""
if path[-1] != "/":
path.append("/")
return path | 97e403404d5d44517be622fd6a58ad0b054c8aea | 632,509 |
import requests
def latest(session: requests.Session, package: str) -> str:
"""Find latest version of package on PyPI.
Args:
package: Python package name.
Returns:
Latest package version.
"""
endpoint = f"https://pypi.org/pypi/{package}/json"
with session.get(endpoint) as re... | bbf5301ac89d5a4d58d42dba98ee075d0bd894da | 632,510 |
def confirm(prompt, expected=('yes', 'y')):
""" Prompts the user to continue with the script
:param prompt: What to show the user
:param expected: Valid answers to continue
:return:
"""
response = input(prompt + f": ({'/'.join(expected)}) ")
if response.lower() not in expected:
print... | 229346036cd1dd026d52608df1ea77c64b66773c | 632,511 |
import base64
def load_bytes(storage: str, value: str) -> bytes:
"""
Given a storage, load bytes
Storage may be a 'raw', 'base64', 'base85', 'file'
Value is an encoded string or a path to local file
"""
if storage == 'raw':
return value.encode('utf-8')
if storage == 'base64':
... | b273df280db3e89677522fd9efa4c8c0f225b6a1 | 632,512 |
import json
def __load_json__(file):
"""
"""
try:
with open(file) as rf:
data = json.load(rf)
return data
except:
return {} | 3df39ede3cc9a3ab6f55fbfac6d74edfcbcbc278 | 632,513 |
import random
def nonce():
"""
Return a random int between 0 and (2^32)-1
"""
return random.randint(0, 4294967295) | aae8164480e68c18074265e3e424c6eefee1aaf8 | 632,515 |
def get_nested_keys(data):
"""Return key list for nested structure.
See: https://github.com/ducdetronquito/scalpl/issues/21#issue-700007850
"""
_null_key = object()
def nested_key(data):
if isinstance(data, list):
keys = []
for i in range(len(data)):
... | 2782e214595440554a820e7f0fca20089e1ec2b0 | 632,516 |
def handle_base_indices_arg(base_periods):
"""Converts arg to list if int, or raises error if not int or list."""
if not isinstance(base_periods, list):
if isinstance(base_periods, int):
return [base_periods]
else:
raise ValueError(
"base_periods must be i... | d0160143723f3bf1b8146837c88c20e1c9b1546c | 632,517 |
def camel_case_to_verbose(string):
"""Convert a CamelCaseModelName to Verbose Model Name."""
words = []
start_index = 0
for index, c in enumerate(string):
# Ignore the first character
if c.isupper() and index:
words.append(string[start_index:index])
start_index = ... | b68aa5b7592f882079fa90104e8fca151dca0a80 | 632,518 |
def to_hashable(obj):
"""
Convert nested data structure (e.g. with dicts and lists)
to something immutable and hashable (tuples, ...)
"""
if isinstance(obj, (int, float, str)):
return obj
elif isinstance(obj, (list, tuple)):
return tuple(to_hashable(x) for x in obj)
elif isin... | 6b1dd1bb517c90f9479574079f974ee14dc451a1 | 632,519 |
def parse_label_file(path_to_label_file):
"""Parses file with labels and converts into dict. For object detection."""
labels = open(path_to_label_file)
label_dict = {}
index = 0
for label in labels:
label_dict[str(label.strip())] = index
index = index + 1
return label_dict | 527339353d3c784378789eda47a3fb94c84597bc | 632,522 |
def customiseFor34120(process):
"""Ensure TrackerAdditionalParametersPerDetRcd ESProducer is run"""
process.load("Geometry.TrackerGeometryBuilder.TrackerAdditionalParametersPerDet_cfi")
return process | 812279d18922ad1b3130447697f1010ac85b035e | 632,523 |
def Main(julia):
""" pytest fixture for providing a Julia `Main` name space. """
return julia.Main | 48232948b9411bba9cd357751a4e2928a44a58ea | 632,524 |
import torch
def fake_image_batch(H: int, W: int, C: int) -> torch.Tensor:
"""Fake batch of images."""
return torch.rand(16, C, H, W) | 3fdba70af552a263d039008137329a1c5a031c9b | 632,525 |
def __material_cf(d):
""" Fixed length data fields for computer files. """
return (d[0:4], d[4], d[5], d[6:8], d[8], d[9], d[10], d[11:]) | 4bdc8d4a955c2da37cfd5e3d429d01e0a3eee417 | 632,526 |
def _grep_all_instances(key, pip):
""""Serach patterns in lines `pip` that start with `key` and return all instances as a list"""
value = [] # set up as a list
for line in pip.splitlines(): # search backward
if(key==":CHA"): # search for Rmt's
if line[0:len(key)] == key:
... | 2a6fcb3ccd8b2cb9c1cef27c3bd2da8c9c79743e | 632,527 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser("Process 1995 CSR-IV HUB4 transcripts")
parser.add_argument("--noise-word", type=str, default="<NOISE>",
help="Word to add in-place of noise words")
parser.add_argument("--spoken... | 77268c0148a865cdba48f2d786c6da631e594d92 | 632,528 |
def yes_or_no(question):
"""
Ask the user a question that can be answered with yes or no.
:question: str, The question
:returns: bool, True if the answer was yes, False otherwise
"""
answer = input("{} (y/n): ".format(question)).lower()
if answer == "y":
return True
return False | 1198ac7579f654e237c1f91882f0cb984816d8e8 | 632,529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.