content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def boolean(value: str) -> bool:
"""Convert a "human" boolean (Y, Yes, True, ...) to a Python boolean,
raising a ValueError if it can't be converted.
"""
if value.lower() not in {"y", "yes", "n", "no", "true", "false"}:
raise ValueError('Please enter either "y" or "n".')
return value.lower()... | 8c4bb974a28ca166c5257929658d582457b7fffa | 634,920 |
import numpy as np
def generate_object(seed):
"""Given an integer, create a random numpy vector of 5 elements
using this integer as the random seed.
"""
np.random.seed(seed)
return np.random.rand(5) | b5f4f695924248dcb42e7ffc129a1714135ff982 | 634,921 |
from typing import List
def get_range(min_max: List[int]) -> range:
"""Returns a range with the turtles min max choices.
If the input is None then range(-25, 26) is returned.
Parameters
----------
min_max : List[int]
Returns
-------
min_max : range
"""
if min_max is None:
... | c446656d7b41ae9c87bb57a5b7cb1a695ac5e68d | 634,922 |
def split_list(ls, num):
"""
拆分list
:param ls: 带截取的列表 [0, 1, 2, 3, 4, 5, 6]
:param num: 除最后一个列表之外其他列表长度 3
:return: 所有拆分的列表 [[0, 1, 2], [3, 4, 5], [6]]
"""
a = len(ls)
if a <= num:
return [ls]
quotient = a // num # 商
remainder = a % num # 余数
res_split = []
for i ... | a903e03b38af905f59c6deaf41f4089090146f27 | 634,923 |
import torch
def impute(x, lengths, channels_last=True):
""" Set elements of a batch of a sequence of tensors to zero according to sequence lengths.
:param x: A tensor with shape [batch, time_step, ...] or [batch, ..., time_step]
:param lengths: A tensor with shape [batch]
:param channels_last: A bool... | b1f6fa73a0ce68b726c17fd2a533c2fc41651f12 | 634,924 |
def parse_header(header):
"""Parses the FASTQ header as specified by CASAVA 1.8.2 and returns the fields in a dictionary
@<instrument>:<run number>:<flowcell ID>:<lane>:<tile>:<x-pos>:<y-pos> <read>:<is filtered>:<control number>:<index sequence>
"""
if header[0] != '@':
return None
... | d533f9af13f6b9745757e11125612aafb8c8ec7d | 634,925 |
import math
def pixel_coords_to_tile_address(x,y):
"""Create a tile address from pixel coordinates of point within tile."""
x = int(math.floor(x / 256))
y = int(math.floor(y / 256))
return (x, y) | 774015a77f324abf35e95c4ccc849bd1858f2b59 | 634,926 |
def dict_to_string(m: dict) -> dict:
"""Convert dict values to strings
Parameters
----------
m : dict
Returns
-------
dict
"""
for k, v in m.items():
if isinstance(v, dict):
m[k] = dict_to_string(v)
else:
m[k] = str(v)
return m | 15fc73e47b49c6a39beb7a363d6952fce2b4398e | 634,927 |
def permut_function(L):
"""
The lambda function returns the isomorphic vertex value for the given vertex.
:param L: The isomorphism list.
:return: A function to apply an isomorphism.
"""
return lambda i: L[i - 1] + 1 | 67f499d243b482fba916f1c7ccbd6ddd1325b27d | 634,928 |
import asyncio
import re
async def read_pressure(host: str, port: int, id: int, read_timeout=5) -> bool | float:
"""Reads pressure from a SENS4 device."""
w = None
try:
r, w = await asyncio.wait_for(asyncio.open_connection(host, port), 1)
w.write(b"@" + str(id).encode() + b"P?\\")
... | 639d0a88eed1b72f22e096d4a83942d9470821ce | 634,929 |
def bmi_classify(bmi, format="json"):
"""Helper function to get "BMI Category" and "Health Risk" from the bmi number
Args:
bmi (int): BMI of the concerned person
format (str, optional): Json when for `native loop` method and anything else for `numpy` method. Defaults to "json".
"""
if b... | a5784da836f51a23d26e26a74d2fc6d0686a64cb | 634,930 |
import hashlib
def _password_digest(username, password):
"""Get a password digest to use for authentication."""
if not isinstance(password, str):
raise TypeError("password must be an instance of str")
if len(password) == 0:
raise ValueError("password can't be empty")
if not isinstance(... | 96eceebdbf6d6353e5ba802d7a9f900ef54f31f7 | 634,931 |
def _str_to_bool(s):
"""Convert string to bool (in argparse context)."""
if s.lower() not in ['true', 'false']:
raise ValueError('Need bool; got %r' % s)
return {'true': True, 'false': False}[s.lower()] | 9c4e8e9aff7b885f74ed632788b0ce0426e8265c | 634,932 |
def _explode_full_table_names(in_tables):
"""
Takes a list of schema-qualified names and creates a schema-key, table_list-value dict
:param in_tables: A list of schema-qualified table/view names
:return: schema-key, table_list-value dict
"""
schema_to_table = dict()
for t in set(in_... | 6f67d28fd51d8ea4c9aa08231c8d50232206d427 | 634,933 |
import torch
def restore_checkpoint(structure, state, restore_db=True):
"""
:param structure: experiment structure object
:param state: experiment state object
:param restore_db: Attempt to restore database (true/false)
:return: experiment structure
"""
structure["training_modules"][0].... | 5c2c086a1de874ff84732b43fd31a84fd16c3c4a | 634,934 |
import argparse
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"file_path... | 3e1b9e4317102fe4bada6a7025c82e420f2cbcd4 | 634,936 |
def find_missing(array_1, array_2):
"""Compares two lists passed to it as arguments,
and return the number which is not common to them.
:param array_1:
:param array_2:
:return: number
"""
if len(array_1) is 0 and len(array_2) is 0:
return 0
if len(array_1) > len(array_2):
... | 365544a6ddab33f92516fe24f962602e7bcea3d7 | 634,937 |
import os
def get_json(path):
"""
Get etc-json files from path
"""
files = [
os.path.join(path, file)
for file in os.listdir(path)
if file != "README.html" and file >= "20210319"
] # Make it robust using regex
etc_files = []
for file in files:
for expid in... | 94f1e6d6866880dab58d42b3513c2d51c89b5d25 | 634,938 |
def get_file_name_from_url(url: str) -> str:
"""Get the last part of an URL."""
return url.rsplit('/', 1)[1] | d7647df3d686ef1e72e3c55c413c3c3a1be346fc | 634,939 |
def validate_username(username: str) -> bool:
"""Validate username.
Requisites: Min length = 5."""
return len(username) >= 5 | e5c21e9cba1951a2443d77a9ab8baa78719901e7 | 634,940 |
def PrintMenu() -> int:
"""
Prints in console the menu of the app.
"""
option = 0
print("Select an option from the ones below")
print("1 - Simple Permutation.\n2 - Simple Variation.\n3 - Simple Combination.")
print("4 - Compound Permutation.\n5 - Compound Variation.\n6 - Compound Combination... | 65d066d8cf1cdaa68e57e395445366c15109e685 | 634,942 |
def class_name(cls):
"""Return a string representing the class"""
return cls.__name__.replace('.', '_') | eac9db2409831d60d11abde9092ca063bf568055 | 634,944 |
def eventDbMatch(events, *categoryDicts):
"""
This function is often used in dungeon module parsing. It returns a
generator that returns log entries that have an event that matches
any of the dictionaries passed in. It is used so commonly that this
function is very convenient. Regexes are automat... | 2d2569b3b91547580e7663fbaba2bd1a2574f7ff | 634,945 |
from typing import List
import math
def get_minimum_subintervals_set_math(intvl_upper_limit: int, range_length: int = 1) -> List[int]:
"""
Method that returns the minimal set of placements that cover the full interval. This method uses
the mathematical expresion that minimizes the number of points, howeve... | e4329c35eb93281e14b082f99ffb9d5ce71e6cdb | 634,946 |
import random
def crop_skin(im, height=64, width=64):
"""
randomly crop a portion of original image with height*width from the top-left corner,the top-right corner,
the button-left corner and the button-right corner respectively
"""
h, w, _ = im.shape
pos_x = random.randint(0, 100)
pos_y =... | 73720fd73981962505c6b8d02974ecc3208d5408 | 634,948 |
def update_zones(logger, mongo_connector, rm_connector, update_zone_list):
"""
Copy all the currently known FLDs to the remote database.
"""
logger.info("Starting Zones..")
zones_collection = mongo_connector.get_zone_connection()
remote_zones_collection = rm_connector.get_zone_connection()
... | 5494393f7dd04a5bca4c19f205e14487d8b36056 | 634,949 |
import requests
def get_from_gitlab_no_auth_api(url):
""" """
headers = {
"Accept": "application/json"
}
return requests.get(url, headers) | eeeeab76b6062f6666c2d908a19a69904d13dd3e | 634,950 |
import json
def resolve_json(text, resolver, recursive=True, fill_empty='{}'):
"""
Given a JSON Schema containing `$ref` keys, replace all
referenced URI values with their values using trimesh
Resolver objects.
Parameters
---------------
text : str
JSON text including `$ref` to othe... | 2af30642ac7d3f200498c72783c0f95590b52edc | 634,951 |
import torch
def unpack_episode(episode):
""" Helper function that extracts samples and labels from an episode in numpy
Args:
episode: the episode to unpack
"""
examples = torch.cat([episode["support_images"], episode["query_images"]], 1).numpy()
labels = torch.cat([episode["support_class_... | 1326228e3433dc4eb7cfa0c50256468d02a05b64 | 634,952 |
def get_path_from_source(source_path):
"""
Get file path from source
Args:
source_path (str): relative module path e.g. this.module.Class
"""
file_path = "/".join(source_path.split('.')[:-1]) + '.py'
return file_path | f429e1530c11b942c75ae34374a1d92da88a093a | 634,953 |
def name_to_crate_name(name):
"""Converts a build target's name into the name of its associated crate.
Crate names cannot contain certain characters, such as -, which are allowed
in build target names. All illegal characters will be converted to
underscores.
This is a similar conversion as that wh... | 8550686e5678e4cf7a720dbff1d1bf137317cd96 | 634,954 |
import random
def roulette_wheel(probs, num_samples):
"""Roulette_wheel selection from a prob. distribution
Parameters:
probs (list): Probability distribution
num_samples (int): Num of iterations to sample from distribution
Returns:
out (list): List of samples based on in... | e1c4acda169aa6ef8de6cf0859dd0d289ae9655a | 634,955 |
import random,os
def imageTitle(words=3):
"""
assemble title string
:param opt:
:return:
"""
words_file = os.path.abspath(__file__).replace('\\','/')[0:os.path.abspath(__file__).replace('\\','/').rfind('/')]+'/words.txt'
text_file = open(words_file, 'r')
lines = text_file.read().split(... | c140a7020fdcf39ebba367245112b6f526882fef | 634,957 |
import six
def get_exception_message(exc):
"""
Get the error message of a specific exception
Args:
exec(Exception) : The exception to get error message.
Returns:
the error message of exec
"""
assert exc is not None
if six.PY2:
return exc.message
else:
... | d323da92a460480cec1ebf30b11e9d809dccd241 | 634,958 |
def dbName():
"""
return db name
* set DB_TYPE=custom in .env to activate
"""
return 'custom' | 69548d7b2819c9ec09bf726e1813451a65bc2c69 | 634,959 |
from typing import List
def _extract_docstring_path_specification_comment_from_line(
*, line: str, matches: List[str]) -> str:
"""
Extract a docstring path specification comment
from a specified markdown line text.
Parameters
----------
line : str
Target markdown line text.
... | af9599eb2700279669b32bd09f5ea74d374efde0 | 634,960 |
def _arg_no_mixin(num):
"""Return FindArgNoMixin for num."""
class FindArgNoMixin(object): # suppress(too-few-public-methods)
"""Mixin that provides generate() for finding args by number."""
def generate(self, # suppress(no-self-use)
sub,
other_transf... | f918a05183f265750490e62303173525134eb3ca | 634,961 |
from typing import List
def domains_check(domains: List[str]) -> List[str]:
"""
all input domains should have the same primary,
e.g.
* `example.com`, `a.example.com` are valid
* `example.com`, `a.example1.com` are invalid
* `domains=["a.x.com", "b.x.com"]` will be converted to
`["x.c... | 0815abdb01e531352b75492e5d260792e0496a71 | 634,962 |
def cut_name(matrix: list) -> list:
"""
Clear matrix
:param matrix: matrix to clear
:return: cleared matrix
"""
new_matrix = []
for line in matrix:
new_matrix.append(line[1:])
return new_matrix | 327fd3f5dcfe2ea6aadae5c1f92c85410696d92d | 634,963 |
def generate_report_name(sim_type, talent_string, covenant_string):
"""create report name based on talents and covenant"""
stripped_talents = talent_string.strip("_")
stripped_covenant = covenant_string.strip("_")
talents = f" - {stripped_talents}" if talent_string else ""
covenant = f" - {stripped_... | 4cd1b861a54c6e570174757f3a5b72a6d6b31775 | 634,964 |
def mover_unidade (m, u, n):
"""Esta funcao permite mover, se existir, a unidade u do mapa m para a posicao n"""
for chave in m:
for un in range(len(m[chave])):
if u == m[chave][un]:
m[chave][un][0] = n
return m | 4b71d743c80baba09a4c438671120760fcd3064f | 634,965 |
def isDecimalPalindrome(num):
"""assumes num is an integer
returns True if num in decimal form is a palindrome, else False"""
return str(num) == str(num)[::-1] | 3309b439cb037a22b426155f6497ea389233b17e | 634,966 |
def splinter_webdriver():
"""Splinter webdriver name."""
return "chrome" | 552425f222268b776e925ba32d558191f4dbf415 | 634,967 |
import copy
def _expand_users(device_users, common_users):
"""Creates a longer list of accepted users on the device."""
expected_users = copy.deepcopy(common_users)
expected_users.update(device_users)
return expected_users | 7d4a6f01956e70f6006713631ab8f6b9ecd8819f | 634,968 |
import json
def json_file(filename):
"""
>>> sorted(json_file('test/foo.json').items())
[('bar', 'baz'), ('foo', [1, 2, 3])]
"""
with open(filename) as file:
return json.load(file) | 0d48afd699eb7dac301d6528a5f90b414f7f8774 | 634,969 |
def next_minute(dt):
"""
The next minute (as a datetime) for the given date time
:param dt: the date time
:return: the next minute (as a datetime)
"""
return dt.replace(minute=dt.minute + 1) | 624d772b729671668c5c91396f8c4341409fdce3 | 634,970 |
def get_pl_name(name, steps, counter=1):
"""Add a counter to a pipeline name if already in steps."""
og_name = name
while name.lower() in [elem[0] for elem in steps]:
counter += 1
name = og_name + str(counter)
return name.lower() | 09a1efe6dfdae00a7b158d12455c51b671a86cf4 | 634,971 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Pose Estimation Network on ycb Dataset')
parser.add_argument('--cfg_dir', dest='cfg_dir',
help='directory for configuration files',
... | 1da50e63bf553d8b6d35694181d3adc51a735d36 | 634,972 |
def IsCoverageBuild(env):
"""Returns true if this is a coverage build.
Args:
env: The environment.
Returns:
whether this is a coverage build.
"""
return 'coverage' in env.subst('$BUILD_TYPE') | 9742599d8173812f2d995d801dd6a03688941934 | 634,975 |
def endlessly_recursive_func(n):
"""Call itself recursively with no end."""
# http://stackoverflow.com/questions/871887/using-exec-with-recursive-functions
return endlessly_recursive_func(n-1) | 7a41f861dee66f60bfd58a8ff4b9b673ab74ae3f | 634,976 |
import platform
import subprocess
def ping_ip(host=""):
"""it will ping ip
Args:
host (str, optional): [description]. Defaults to "".
Returns:
bool: True,False
"""
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.c... | 85b5ce3ee24d683d3c2c7468caaf30950cf607df | 634,977 |
import json
def get_json(response):
"""Get JSON from response."""
return json.loads(response.get_data(as_text=True)) | 27f71e963b8352e3e796dee913da53007c6c6d62 | 634,978 |
def prop_keys(obj, public=True, private=False, magic=False, globs=False, exclude=None):
"""
Keys of object property dictionary.
"""
exclude = exclude or []
if globs is False:
exclude += ['globals', 'func_globals', '__builtins__']
keys = [prop for prop in dir(obj) if prop not in exclude]
... | 7c90cdca1b16a69910789878ee87c2a9ac1f75c2 | 634,979 |
def dbdust_tester_cli_builder(bin_path, zip_path, dump_dir_path, dump_file_path, loop='default', sleep=0, exit_code=0):
""" dbust cli tester script included in this package """
return [bin_path, dump_file_path, loop, sleep, exit_code] | 809eea7c8cdfa2a56a9d723e7ee808a3e916ee83 | 634,980 |
def get_pdos_generator_inputs(fixture_code, generate_structure):
"""Generate a set of default inputs for the ``PdosWorkChain.get_builder_from_protocol()`` method."""
return {
'pw_code': fixture_code('quantumespresso.pw'),
'dos_code': fixture_code('quantumespresso.dos'),
'projwfc_code': f... | bf553b2694372f9894dabb999e941b6d718b928c | 634,981 |
def opcode_4nnn(self, x, nn) -> int:
"""4XNN Skip the following instruction if the value of register VX is not equal to NN"""
return self.pc + (4 if self.v[x] != nn else 2) | c0283caa90f42855b6910a577e4826649492d084 | 634,982 |
def is_degenerate(sides):
"""
Check to see if a triangle is 'degenerate'.
:param sides: list[*int] - the length of the three sides of a triangle
:return bool - whether a triangle is degenerate or not
>>> is_degenerate([1, 2, 3])
True
>>> is_degenerate([4, 5, 6])
False
The sum of ... | 821639338a55aafc5900db7e7ac259272dee5b39 | 634,983 |
def dict_key_exists(dic, key):
"""Check if the KEY exist in DIC.
@param { Dictionary } dic : Dictionary use to check.
@param { string } key : Key to check.
"""
return key in dic | 8fbaa43babdffd6ac0bd2c8a952920eabd5be92d | 634,984 |
def merge(x, y):
""" 仅支持一级嵌套
gparam x:
:param y:
:return:
"""
# logger.info('合并配置项,初始值: \n%s', x)
# logger.warning('合并配置项,覆盖值:\n%s' % y)
z = {}
for xk, xv in x.items():
if isinstance(xv, dict):
new_xv = xv.copy()
yv = y.get(xk)
if yv is not... | 6b8a69d785c287c6fff28d19fb1ddccaa6f45440 | 634,985 |
def _both_names(meta, to_prom_name):
"""If the pathname differs from the promoted name, return a string with
both names. Otherwise, just return the pathname.
"""
name = meta['pathname']
pname = to_prom_name[name]
if name == pname:
return "'%s'" % name
else:
return "'%s' (%s)"... | 4c12092bd2dcafe69e58b99d9da0609406d9b0f0 | 634,986 |
def _get_seq_sim_graph_memsave_numba(data, threshold):
""" Returns tuple (row_ind, col_ind) such that for every k row_ind[k] and col_ind[k] are more similar than
threshold. """
n = len(data)
w = data.shape[1]
threshold_as_count = threshold * data.shape[1]
row_ind = []
col_ind = []
for i ... | f3e9deb0aba11961b8792736ddc4e9d451aeb701 | 634,987 |
def class_member_cache(name: str):
"""
类成员缓存
:param name:
:return:
"""
cache_field = f"_{name}"
def class_member_cache_inner(class_func):
def wrapper(self, *args, **kwargs):
cache_member = getattr(self, cache_field, None)
if cache_member:
retu... | 94d637f1a756b2093c915e70e5c60e909cf9fd2d | 634,988 |
def float_repr(value: float) -> str:
""" Pretty print float """
spl = '{:e}'.format(value).split('e')
exp = 'e' + spl[1]
if abs(int(spl[1][-2:])) <= 3:
spl[0] = '{:.8f}'.format(value)
exp = ''
return spl[0].rstrip('0').rstrip('.') + exp | f3a44d483db1221da6d659f81b28f6601029ad31 | 634,989 |
import random
def get_random_color():
"""
Generate a random color.
"""
# Default colors from flatuicolors.com
default_colors = (
'#27ae60', # Nephritis
'#2980b9', # Belize Hole
'#2c3e50', # Midnight Blue
'#8e44ad', # Wisteria
'#d35400', # Pumpkin
... | 2e8b9aeb3e86ba7f15972507f084d70aab8b2ea7 | 634,990 |
def string_7bit(string):
"""Strip hte highest bit of evey character in string"""
s = ""
for c in string: s += chr(ord(c) & 0x7f)
return s | 4ac00bc6d5e170191df775e34dff9fc31c565f12 | 634,991 |
import yaml
def parse_config(config_file: str) -> dict:
""" Parses yaml config file (if indicated)
:param str config_file: config file path
:return: configuration dictionary
"""
if config_file is None:
return {}
with open(config_file) as f:
return yaml.safe_load(f) | ec2dd4e5685563ea6ec0ce4ce7cb465fc49bafc3 | 634,992 |
def get_test_data_rdd(sc, X_test_path):
"""
sc: type sparckContext
X_test_path: type str, the path for the X_test data document, which contains the hash codes
return: type rdd, a rdd where each record contains a document content and its zipped index in ascendind order (the zipped index will be used for ... | 5e666b94e4df755533d3407f7637f46cd7b9a039 | 634,993 |
def remove_zips_and_metas(data):
"""
Function to remove all the zip files from the made database.json
"""
if not isinstance(data, (dict, list)):
return data
if isinstance(data, list):
return [remove_zips_and_metas(val) for val in data]
return {k: remove_zips_and_metas(val) fo... | dde2c3d7a668dfde2109a593db17566b40aa0fa5 | 634,994 |
import pathlib
def is_txt_document(file_path: pathlib.Path) -> bool:
"""
Determins if the file should be included in the processing
"""
result = \
file_path.is_file() and \
file_path.suffix.lower() == '.txt' and \
not file_path.stem.startswith('_')
return result | 462f341f0e18a28c9a63a7060b0c476392755386 | 634,995 |
def correct_input(row):
"""
:param row: str, user input
:return: bool, if the user input is correct
"""
for i in range(len(row)):
if len(row[i]) != 1 or len(row) != 4:
print('Illegal input')
return False
return True | dbaee7f2f6e6c85b421d77ca0fbd02e0b3deb7ec | 634,996 |
import re
def test(pattern, string):
"""Determines whether a given string matches a given regular expression"""
return bool(re.search(pattern, string)) | 5f04cff018207643c38c3a04d69cf9f949feaddb | 634,997 |
def merge(left, right):
"""
deep merge dictionary on the left with the one
on the right.
Fill in left dictionary with right one where
the value of the key from the right one in
the left one is missing or None.
"""
if isinstance(left, dict) and isinstance(right, dict):
for key, v... | 04c2cbdb446c8e8fab4479dd7b6438681472d6f3 | 634,998 |
def subtour(n, edges):
"""
Given a list of edges, finds the shortest subtour.
"""
visited = [False] * n
cycles = []
lengths = []
selected = [[] for _ in range(n)]
for x, y in edges:
selected[x].append(y)
while True:
current = visited.index(False)
thiscycle = [... | efcbd9345176c7f4e2fcfc358fd225a0516b0917 | 634,999 |
import os
def user_image_upload_to(user, filename):
"""Upload images to a sensible location."""
ext = os.path.splitext(filename)[-1]
if filename == 'blob':
ext = '.png'
return 'users/{}/profile{}'.format(
user.email, ext
) | ae5f28aee540e00baa07b798383ce30809a81ed6 | 635,002 |
def batch_fwd(model, batch):
"""Performs the forward pass for a given model and data batch.
Parameters
----------
model : pl.LightningModule
The model to pass data through.
batch : tuple[torch.Tensor]
A tuple of batched input tensors.
Returns
-------
tuple[torch.Tensor]... | 5a14f1595db2d4c6a701d58f7f7eccb6f9dc08d9 | 635,003 |
import binascii
def is_gzip_file(f):
"""
This is an elegant solution to test whether a file is gzipped by reading the first two characters.
I also use a version of this in fastq_pair if you want a C version :)
See https://stackoverflow.com/questions/3703276/how-to-tell-if-a-file-is-gzip-compressed for... | ef1d289960bab6e0f6c534b0cae636e5f98e54c1 | 635,004 |
import json
def load_config():
"""
Loads bot configuration for use.
"""
with open("secrets/secrets.json", 'r') as secrets:
return json.load(secrets) | 0494258f4fdab4cac1f0220df49527113db6b465 | 635,005 |
def get_cpp_footer():
"""Retrieves the C++ footer"""
return "\n} // namespace clblast\n" | 33b9c6ed9fd7b5feff7acb816214052ca6b12373 | 635,006 |
import click
def progress_func(func, char='*'):
"""Use to wrap functions called in parallel. Prints a character for
each function call.
:param lambda-function func: A 'lambda wrapped' function to call
after printing a progress character
:param str char: The character (or multi-char string, if you
... | 6c1b62ec2485bbad8dfcd110a41ccc52f8dcfc70 | 635,007 |
import hashlib
def _rename_property(p,_p):
"""
Return a new short name for p based on the original p as well as
part of a hash of the full URI of the property (for repeatability)
"""
return "%s-%s"%(p,hashlib.md5(_p).hexdigest().upper()[:4]) | 68e13e8895984b40a43dd39a4426ca80df111456 | 635,008 |
import os
def create_filemanager_media_site_root(sender, instance, **kwargs):
"""Create the filemanager when creating a WebSite"""
try:
os.mkdir(instance.media_root())
return True
except OSError:
return False | 0de3a5edc27a8e1f6525cbdbf419aebd2bb8bdf4 | 635,009 |
def name_predicate(name_dict):
"""Only include names that pass this predicate."""
professions = name_dict["primaryProfession"]
return (
professions and
("actor" in professions or
"actress" in professions or
"director" in professions)) | fe09d3066a47022be05b9f05b0bcf3fc0e0974ec | 635,010 |
def index_config(config, path, index_structure=True):
"""Index a configuration with a path-like string."""
key = None
sections = path.split("/")
if not index_structure:
key = sections[-1]
sections = sections[:-1]
for section in sections:
if isinstance(config, dict):
... | 2987a01696e5265822cd2da02fc764f683c396e0 | 635,011 |
def get_item_variants(session, item_id):
"""
商品IDをもとにその商品ごとに存在する色ごとの情報で
必要な情報を取得する
"""
headers = {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/80.0.3987.95 Mobile/15E148 Safari/604.1",
"Accept": "text/html,appl... | 704183bf5fffb39f436c1c274a37a248b7e68f95 | 635,012 |
def vec_print_str(tv, pdvars):
"""
This returns a string that will be used to print a line of code. If the
variable tv has not yet been used before, then the declaration of this
variable must be included in the string. pdvars is the list of variables
that have been previously defined.
tv: ... | a45ae337520ef0a21c2eee51ecff281bb76e614e | 635,013 |
import time
def format_duration(t0):
"""
Adapted from @john-fouhy:
https://stackoverflow.com/questions/538666/python-format-timedelta-to-string
"""
duration = time.time() - t0
hours, remainder = divmod(duration, 3600)
minutes, seconds = divmod(remainder, 60)
return "{:02}:{:02}:{:02}".... | 47eaf71e3067798e386f8380e3d69c84a15c6002 | 635,015 |
def name_to_private(name):
"""makes private version of the name"""
return name if name.startswith('_') else '_' + name | fc17c861fbef0fb80e83e27137e82225e9d5ac07 | 635,016 |
def compute_pool(test_instance, test_relation1, test_relation2,
gold_instance, gold_relation1, gold_relation2,
test_label, gold_label,
node_weight_fn, edge_weight_fn):
"""
compute the possible variable matching candidate (the match which may result in 1)
Args:
test_instance: instance triples in AM... | b9ea44222c588eaee2c01254ea7249b514f7d80c | 635,017 |
def empty_lines(lines, index, extent):
"""
If the 'extent' is negative, the function checks the preceding lines
"""
if extent > 0:
start = min(index + 1, len(lines) - 1)
end = min(index + extent + 1, len(lines))
else:
start = max(0, index + extent)
end = max(0, index)... | 3f006429b6345706c152b763b903e3676145b1b5 | 635,018 |
def combine_files(DATAPATH, cores):
"""
cobmines the image embeddings created by the parallel shell scripts back into 1 large file
:param DATAPATH:
:param cores:
:return:
"""
combi_file, i = "bigger_combi_probfile.csv", 0
with open(DATAPATH + combi_file, 'w') as big_file:
for ... | ab234ddba7ebcebfda56f0bd551517752c545341 | 635,019 |
import argparse
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description='Concatenate reference for display in jbrowse')
parser.add_argument('-s', '--samples', help='input sample file with genetic clusters')
parser.add_argument('-b', '--bed', help='original bed... | 42a51bd5dc2b09d1b5a9d175694068dd92f1b04f | 635,020 |
def channel_name_mapping(name_str):
"""
Turns a string like '1:foo,2:bar' into the dict
{1: 'foo', 2: 'bar'}
May raise an exception if the string doens't follow this format.
Returns {} for an empty string.
"""
mapping_strs = str(name_str).split(',')
str_pairs = [m.split(':') for m in map... | 89bd1235cc2a692f841c90f59bb9bfc7fb2cc22e | 635,022 |
def can_play_stage(stamina, free_slots):
"""
Test to see if the player can play a stage.
(Simulate a player looking at their stamina and free slots to
determine if they can play a stage. For sake of simplicity, assume
players don't want to play a stage if they don't have enough free
slots to ho... | ac4eca7daabc1c2e07974f36e9f6921731c821ae | 635,023 |
def calc_thick_spherical_lens(n, roc1, roc2, d, ne=1):
"""Calculate the properties of a thick spherical lens.
Positive radius of curvature means center is further along the direction of travel. For a biconvex positive lens,
roc1>0, roc2<0. The principal plane distances are from the vertex to the principal... | 307fc47b813f5b3aeeda838c7c51c9ec3171589a | 635,024 |
def nint(a):
"""return the nearest integer to a."""
i = int(a)
if a > 0:
if a - i > 0.5:
i += 1
elif a < 0:
if a - i < -0.5:
i -= 1
return i | 0f22e2872b830dec76393096485ec957a819313c | 635,025 |
def example_group_indices(data, attr, values):
""" Return lists of indices into `data` for each `values` item that matches
the example value at `attr` attribute
Example::
cls_ind1, cls_ind2 = example_group_indices(data, data.domain.classVar, ["Class 1", "Class 2"])
"""
ret = [[] for _ i... | 0a824abd0b94f32762b465dee1d94a87af390c10 | 635,026 |
def longest_common_prefix(strings):
"""
Find the longest common prefix of a list of 2 or more strings.
Args:
strings (collection): at least 2 strings.
Returns:
string: The longest string that all submitted strings start with.
>>> longest_common_prefix(["abcd", "abce"])
'abc'
... | 65924132f44fd3e7affef58f9d172254336e3b76 | 635,027 |
def getxmltagname(tag_name: str) -> str:
"""Transform tag names."""
if tag_name == "source":
return "Source"
elif tag_name == "funcdeclaration":
return "Function"
elif tag_name == "classdeclaration":
return "Class"
elif tag_name == "vardeclaration":
return "Variable"
... | f962215815aa273f0400f5693c53b2209943d0f6 | 635,028 |
def GenerateConfig(context):
"""Creates the SQL instance."""
resources = [{
'name': 'csye6225-cloud-sql',
'type': 'sqladmin.v1beta4.instance',
'properties': {
"state":"RUNNABLE",
"backendType": "SECOND_GEN",
"databaseVersion": "MYSQL_5_6",
"region": "us-e... | 6ca3b1519b522587e0758f28053c3fe745f5201a | 635,029 |
def r_to_rq(r):
"""
reduced coordinate inverse:
(1+rq)
r = ------
(1-rq)
Hernquist & Ostriker 1992 eq. 2.16
"""
return (r-1.0)/(r+1.0); | 72aa09c6395b7a62575883b9cbadfbb21f530635 | 635,030 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.