content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import sys
def hyperparams():
"""
Parse hyperparameters from command line
For hidden_layers, input [(3, 8), (3, 8)] as 3_8_3_8
"""
args = sys.argv
hyperparams = {'model': 'scone',
'epochs': 1000,
'learning_rate': 0.001,
'weight_decay': ... | 8ee327ce02a66518b1b780638c343d3632987b8d | 650,970 |
def bruce_max_subarray_sum(arr):
"""暴力求解最大子数组和
Args:
arr(list): 数组
Returns:
max_sum(int): 最大子数组和
"""
max_sum = 0
for i in range(len(arr)):
epoch_sum = 0
for j in range(i, len(arr)):
epoch_sum += arr[j]
if epoch_sum > max_sum:
... | be6a9db8a4a2c7dd3d4adbeb78518b441a4b5dd0 | 650,971 |
def deci_deg_to_deg_min_sec(deci_deg):
"""https://stackoverflow.com/questions/2579535\
/convert-dd-decimal-degrees-to-dms-degrees-minutes-seconds-in-python"""
is_positive = (deci_deg >= 0)
deci_deg = abs(deci_deg)
# divmod returns quotient and remainder
minutes,seconds = divmod(deci_deg*3600,60)... | e4ec2dfca1ae497a6cf3fb5022687c2443e4647f | 650,972 |
def valid_authority(staging_gateway):
"""Override valid authority with authority of the staging gateway"""
return staging_gateway.server_authority | c8159e3b8ba7d8333d12e1333346c60d5d63a1de | 650,973 |
import json
def apigw_non_formated():
""" Generates API GW Event"""
with open('./events/lambda/event_non_formated.json') as f:
data = json.load(f)
return data | 533d840b8a005487dba033f30c0afd6e64b8c904 | 650,974 |
def middle(t):
"""Return everything but the first and last elements of t.
"""
# We can just return the middle slice, leaving out zero and len(t).
# No need to worry about lists of length 2 or less, because
# Python slices will return the empty list in most cases where the
# indices don't make se... | c9389674fb00160c8331192032dfef2ac2faa440 | 650,975 |
def get_z(beam):
"""Used for retrieving data for x-, y- or c-axis of a plot."""
return beam.z | 0f2a1be9518674556e2a1df1ea2f036c046a4a98 | 650,976 |
import os
def ExpandPath(path):
"""Returns path after passing through realpath and expanduser."""
return os.path.realpath(os.path.expanduser(path)) | 5e34ee9781e134fbdc03bc2e2993023334fa408d | 650,977 |
def update(model, *fnames):
""" Return the expected query string to UPDATE the given columns. """
columns = sorted(fnames) + ['write_uid', 'write_date']
return 'UPDATE "{}" SET {} WHERE id IN %s'.format(
model._table,
", ".join('"{}" = %s'.format(column) for column in columns),
) | 9b79f1e7c3a7fd16e4931942ba08d6330e48e966 | 650,978 |
import ast
def load_pyobj(filename):
"""load pyobj"""
with open(filename, 'r', encoding='utf8') as fid:
the_s = fid.readlines()
if isinstance(the_s, list):
the_s = ''.join(the_s)
the_s = the_s.replace('inf', '1e20')
pyobj = ast.literal_eval(the_s)
return pyobj | 7347029344dbcd8f15fd70f31a860b6575bdc8b6 | 650,979 |
def bollinger_bands(price, window_size=10, num_of_std=3):
"""Gets bolinger bands."""
rolling_mean = price.rolling(window=window_size).mean()
rolling_std = price.rolling(window=window_size).std()
upper_band = rolling_mean + (rolling_std * num_of_std)
lower_band = rolling_mean - (rolling_std * num_of_... | 7bf1fcd4c99423bf19893be98fe7aab6afbe7b99 | 650,980 |
from typing import Union
def safe_div(num: Union[int, float], denom: Union[int, float]) -> float:
"""
Return 0 instead of raising DivisionByZero exception when denom is 0.
:param num: [description]
:param denom: [description]
:return: [description]
"""
# https://stackoverflow.com/a/273175... | c60c11b816e6c942a076bcb609130ae2a866b9ca | 650,981 |
def syndic(
request, salt_factories, master_of_masters, minion_1, syndic_master, syndic_minion, minion_2
):
"""
This syndic will run in tandem with master-2, connected to the upstream
master-of-masters master.
"""
assert master_of_masters.is_alive()
assert minion_1.is_alive()
assert synd... | 08d41ce1d994bf09653c340cf7e936201b4315f3 | 650,982 |
import math
def get_foldrate_at_temp(ref_rate, new_temp, ref_temp=37.0):
"""Scale the predicted kinetic folding rate of a protein to temperature T, based on the relationship ln(k_f)∝1/T
Args:
ref_rate (float): Kinetic folding rate calculated from the function :func:`~ssbio.protein.sequence.properties... | c90586cfb0500f82f247444c7767943126a58292 | 650,984 |
import glob
def get_zip_file_list():
"""
Returns a list of all files to be extracted
:return: array
"""
return glob.glob("/app/tmp/*.zip") | 4f2eed5ddadeb6e73df8f9c16a93f436b001b3c1 | 650,985 |
def _find_covering_span(text, annsets, word_boundary=True):
"""Find text span covering giving annotation sets, optionally
extending it to word boundaries."""
flattened = [a for anns in annsets.values() for a in anns]
start = min(a.start for a in flattened)
end = max(a.end for a in flattened)
if ... | 84ba7aac112dffe190617452bff551679c9da40c | 650,986 |
def safeOpen(filename):
"""Open a utf-8 file with or without BOM in read mode"""
for enc in ['utf-8-sig', 'utf-8']:
try:
f = open(filename, 'r', encoding=enc)
except Exception as e:
print(e)
f = None
if f != None:
return f | 59c391e8df2fba38f2620fc579286a13061553bf | 650,987 |
def class_check(vector):
"""
Check different items in matrix classes.
:param vector: input vector
:type vector: list
:return: bool
"""
for i in vector:
if not isinstance(i, type(vector[0])):
return False
return True | e9ac6b9e0ba4bc28bbe7c6f4f6120399d352b0a9 | 650,988 |
import pandas as pd
def compute_weighted_sum(data, weights_dict):
"""
Computes weighted sum for specified columns
Arguments
----------
data : a pandas DataFrame object that contains the columns to be weighted and the
normalized scores for each alternative
weights_dict: a dictionary c... | b60bc3fb6a3a9f8986ad1b8339efdc4a4707fe4f | 650,989 |
def update_q(reward, gamma, alpha, oldQ, nextQ):
""" Where nextQ is determined by the epsilon greedy choice that has already been made. """
newQ = oldQ + alpha * (reward + ((gamma*nextQ) - oldQ))
return newQ | 454ed477dba027f175c025fcb56e4900699b7226 | 650,990 |
def get_ip(request):
"""
Returns ip address or None if the address is in an unexpected format
"""
ip_address = request.META['REMOTE_ADDR']
return ip_address | 02eaedeb9555cbac06c13208d3f74f8de8e48dfd | 650,991 |
def mu_prime(eta, eta_0, Kappa=0.4):
"""
eta = k z, vertical coordinate [Adi.]
Kappa, Von Karman constant (typically 0.4)
"""
return (1/Kappa)*(1/(eta + eta_0)) | b6a94ea0264be0a8ce96f4dfe2984dbb43b6b42a | 650,992 |
def reduce_next_sentence_label_dimension(batch):
"""Change next_sentence_labels's shape from (-1, 1) to (-1,).
Args:
batch: A dictionary mapping keys to arrays.
Returns:
Updated batch.
"""
batch['next_sentence_labels'] = batch['next_sentence_labels'][:, 0]
return batch | 32731bd22eb28693e336ca981d897feaacd8c816 | 650,993 |
def binary_search(array, val):
"""Binary search."""
sorted_array = sorted(array)
i = 0
j = len(array) - 1
while i <= j:
mid = (i + j) // 2
if sorted_array[mid] == val:
return mid
if sorted_array[mid] < val:
i = mid + 1
else:
j = mid... | e0dc1386f9b5c2f8896df0c92419b125ff566add | 650,994 |
def _get_network_layer_sizes(net_params):
"""Infer the architecture of the simply connected network from the parameters"""
dense_params = [p for p in net_params if len(p) > 0]
all_dense_layer_sizes = [p[1].size for p in dense_params]
dim_in = all_dense_layer_sizes[0]
dim_out = all_dense_layer_sizes[... | ea6ab4b6306d36241adfe41e6cd6b9df98b9cfee | 650,995 |
def dict_match(left, right, res=None):
"""Do two nested dictionaries match on nested values?"""
if res is None:
res = [True, ]
if res[0] == False:
return False
for k in right.keys():
if (k in left):
if (isinstance(left[k], dict) and isinstance(right[k], dict)):
... | 1fda3713852c667c0d56dc0aeb8bc690121be1a5 | 650,996 |
from typing import Tuple
def convert_to_pixel_coords(location: Tuple[float, float],
center_of_image_in_global: Tuple[float, float],
center_of_image_in_pixels: Tuple[float, float],
resolution: float = 0.1) -> Tuple[int, int]:
"""
... | 2af3010ba3ceec8d75e62b47182ff92f62580c20 | 650,997 |
def recursion(n):
""" 递归方式返回斐波那契数列某一位f(n)的值 """
if n == 0 or n == 1:
return 1
return recursion(n - 1) + recursion(n - 2) | c2b35272771070c9738f5132b58f194675b269a3 | 650,999 |
def params_from_cmd(args):
"""Extract the parameters for prepare_training_data from the command line and return a dict"""
params = {
"maps_list": args.maps_list,
"xyz_limits": args.xyz_limits,
"output_dir": args.output_dir,
"slices": args.slices_per_axis,
}
return params | 803f3937c747ea15c052e07878c9709905055e26 | 651,000 |
import os
def make_path_compatible(path: str) -> str:
"""Changes forward slashes into backward slashes and the reverse depending on the current platform."""
return os.path.join(*path.replace('/', '\\').split('\\')) | f1106cc84fcccdd72fd6ce3f3da022c84f233f48 | 651,002 |
def power_provision_rule(mod, g, tmp):
"""
Power provision from variable must-take generators is their capacity times
the capacity factor in each timepoint.
"""
return mod.Capacity_MW[g, mod.period[tmp]] \
* mod.Availability_Derate[g, tmp] \
* mod.gen_var_must_take_cap_factor[g, tmp... | 4f440cb0cbdeb604944553f71e80809f76a96173 | 651,003 |
def spherical(r_1, r_2, E_1, E_2, vu_1, vu_2, P_guess=None):
"""Returns the contact parameters for two spheres in contact or for a sphere in contact with a flat surface. In the case of a flat surface, enter None for the radius.
Parameters
----------
r_1 : {None, float}
Radius of sphere... | b09ad3851e144b00343c76a03a6ac2cba61983c0 | 651,004 |
def euclid_distance(value1, value2):
"""
欧几里得距离
:param value1:
:param value2:
:return:
"""
return pow(value1 - value2, 2) | 4853b687322cf012230b8270f2343162b37dae36 | 651,005 |
def read_vol(fname):
"""
REead reference/FF volume from data.(ref/pmd).vol.
"""
with open(fname,'r') as f:
vol = float(f.readline())
return vol | 9fdc783afc6ae894ac79f2eba3ddbd5793e71dc6 | 651,006 |
import posixpath
def split_entry_ext(path):
"""Like os.path.splitext, but take off .tar too.
Taken from `pip._internal.utils.misc.splitext`.
"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | 5e8e412db5b6790123313fb6e5fc34f32a85d839 | 651,007 |
import requests
def check_tcga():
"""
Checks the status of TCGA to ensure it is up
"""
status_endpt = 'https://gdc-api.nci.nih.gov/status'
response = requests.get(status_endpt)
response = response.json()
status = response[u"status"]
if status == u"OK":
return True
else:... | b93b389e297941c3bfa51ac123985ede6aae5cb5 | 651,008 |
import os
def readlist(projectdir):
"""
get all .c file
"""
filepaths=[]
for root,dirs,files in os.walk(projectdir):
for name in files:
if name.endswith(".bc"):
filepath = os.path.join(root,name)
filepaths.append(filepath)
return filepaths | 244905314b30a8772dd3fc1c4877995dd348013b | 651,009 |
import os
import re
def match_regexps_in_file(logpath, log_extracts, return_unmatched=False):
"""
Return a boolean, dict pair indicating whether all log extracts matches,
as well as any named groups they might have matched.
:param logpath: Log file path.
:type logpath: ``str``
:param log_extr... | 1bfe56d7dc1c392d233a742140bda00c4e38d6f7 | 651,010 |
from typing import Any
def string_to_python_object(value: str) -> Any:
"""Return the Python object corresponding to the given string value."""
if value == "None":
return None
if value == "True":
return True
if value == "False":
return False
if value.isdigit():
retur... | 36b726f12862a3af6302bfb75c06d63fa9e0aba8 | 651,011 |
def encode_proto_bytes(val: str) -> bytes:
""" Encodes a proto string into latin1 bytes """
return val.encode('latin1') | 26e46ebec820defdd2226c7446b0b878e6eca3eb | 651,012 |
import numpy
def CollateOutputs(outputs, ind_func=lambda x: x):
"""Converts a list structures into a structure of NumPy arrays.
For example, the output of the function call
CollateOutputs([{'foo': 0.0, 'bar': 22.0},
{'foo': 1.0, 'bar': 22.0}
{'foo': 2.0, 'bar': 22.0}]... | f5ce9b168fbbf3c7b0e219c2b97015cd831e389d | 651,013 |
def compute_shape(coords, reshape_len=None, py_name=""):
"""
Computes the 'shape' of a coords dictionary.
Function used to rearange data in xarrays and
to compute the number of rows/columns to be read in a file.
Parameters
----------
coords: dict
Ordered dictionary of the dimension na... | 6bbbcc85c70614d7f17265b0ebe28657b5c318be | 651,014 |
import os
import fnmatch
def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files
Adapted from Python 2.6 source.
"""
def _ignore_patterns(path, names):
names = [os.path.j... | c2f7afa460073234991d6af2bfe5b463c24059f0 | 651,015 |
import re
def check_uuid(uuid):
"""Check if the string contains a proper UUID.
Supported format: 71769af6-0a39-4242-94be-1f84f04c8a56
"""
regex = re.compile(
r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z',
re.I)
match = regex.match(uuid)
return b... | f44ec3b98453795011b27a9f778a98389f85ae6e | 651,016 |
def lag_spatial(w, y):
"""
Spatial lag operator.
If w is row standardized, returns the average of each observation's neighbors;
if not, returns the weighted sum of each observation's neighbors.
Parameters
----------
w : W
pysal.lib spatial weigh... | a66312ec19815c2f0f33338fbd9f35851408ee2b | 651,017 |
def ts_epoch_with_tz(ts_epoch):
"""Corresponding time in (US/Eastern)"""
return 1451624160000 | be91ca8fd78d0094794f4b6a347583e105239771 | 651,018 |
import requests
def send_message_telegram(msg, chat_id, token):
"""Send a message to a telegram user. The token can be generated talking with @BotFather on telegram.
Args:
msg (str): Message.
chat_id (str): Number.
token (str): Authentication Key.
Returns:
dict: Return me... | f2a514c06b3f6c8c458acf4001b79a87ea45f780 | 651,019 |
def get_mock_html(filename: str) -> str:
"""Мок-метод, который возвращает тело HTML документа из заранее сохранённого"""
with open(filename, mode='r', encoding='utf-8') as file:
res = file.read()
return res | 2efee3e91bdcd2f75bc3522c4ba3d4f61f980151 | 651,020 |
def joinstr( sep, *args ):
"""Join the arguments after converting them to a string"""
return sep.join( map( str, args ) ) | eb2bf997b78182dc6fb2d4e2153d219077d16086 | 651,021 |
def filter_dataframe(df, user=None, begin=None, end=None, rename_columns={}):
"""Standard dataframe preprocessing filter.
This implements some standard and common dataframe preprocessing
options, which are used in very many functions. It is likely
simpler and more clear to do these yourself on the Dat... | 27513297b1915ae0b8840f8245c5e60fd89dc31c | 651,022 |
def tax_input_checker(typed_input):
"""
Returns true if the input string cannot be converted to a float, and false if otherwise
"""
try:
f = float(typed_input)
except ValueError:
return False
return True | a69dbec5b61ef28e615389d63be22ee252ffde55 | 651,023 |
def generate_final_data(status_code, custom_message=False, key=False):
"""
Function to generate the final data dict that needs to be sent back to client.
@param status_code: App specific status_code (string constants)
@param custom_message: Custom string message
@param key: specific key
@return:... | 9695209d1cea58d0f16e5c3873df305c2d207f8a | 651,024 |
def readVector(text):
"""Reads a vector from text 'n v1 ... vn'"""
items = text.split()
if int(items[0])+1 != len(items):
raise ValueError("Invalid number of items")
return [float(v) for v in items[1:]] | ea4b844e1af1a817c24225d107b82e1822845201 | 651,025 |
def get_resource_type(resource_id):
"""Returns resource type"""
lookup = {0: "VM",
1: "Public IP",
2: "Volume",
3: "Snapshot",
4: "Template",
5: "Projects",
6: "Network",
7: "VPC",
8: "CPUs",
... | 71e5b29ca18ac7a2748d8e16dc38961f396065b7 | 651,026 |
import random
import string
def gen_id(value, count=16):
"""Jinja2 filter to generate a random ID string"""
random.seed(value)
letters = string.ascii_uppercase
return ''.join(random.choice(letters) for i in range(count)) | e6b1ff862435c9a7a5664501d29ed01ab03ba27c | 651,027 |
def check_wide_data_for_blank_choices(choice_col, wide_data):
"""
Checks `wide_data` for null values in the choice column, and raises a
helpful ValueError if null values are found.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that is used to record each
... | a9564026133dea68f17ee9b099feec409828707a | 651,028 |
import inspect
from typing import Type
def is_class(the_class: Type) -> bool:
"""
Returns true if the object passed is a class
:param the_class: the class to pass
:return: true if it is a class
"""
return inspect.isclass(the_class) | 0e1be0609a9a0fdbd9677469fef5ee8aa79df181 | 651,029 |
def card_html_id(card):
"""Return HTML id for element containing given card."""
return f'c{card:02d}' | 27f884b9bb407f5f862d1748323eb1eb982178f9 | 651,030 |
def inclusion_comment_item(comment):
""" 一个个评论item """
return {
'comment': comment
} | 95b4c11c624d885c2e986a3a82e526e41902a61d | 651,031 |
def epsilonMaquina(tipoDato):
""" Funcion que trata de calcular el epsilon
de la maquina mediante el algoritmo antes pre_
sentado.
Input:
tipoDato := esta pensado para ser uno de
los tipos proporcionados por la li_
breria numpy.
Output:
Regresa el epsilon d... | 89133c9f3b403a9a04597adc0e586052ba864f85 | 651,032 |
import threading
def daemon_thread(target, *args, **kwargs):
"""Makes a daemon thread that calls the given target when started."""
thread = threading.Thread(target=target, args=args, kwargs=kwargs)
# NOTE(skudriashev): When the main thread is terminated unexpectedly
# and thread is still alive - it wi... | 0534ea32cdaa2fd1de18c56530049932bf8961b4 | 651,033 |
import subprocess
def local(LIST_CMD):
"""
Execute commands on local host
"""
return subprocess.Popen(LIST_CMD).wait() | 8306b92758c56e06de724473c0309006aae01128 | 651,034 |
def _get_var_name(bdd, u):
"""
Given a variable index u in the BDD, return the variable
Name
"""
var_index = bdd["t_table"][u][0]-1
return bdd["var_order"][var_index] | 2d32cf56ea53d4583264baaadbea6d7a81eedecf | 651,035 |
def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool:
"""Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s).
Used primarily for checking against the registered command data from Discord.
Will not work great if values inside the dictionary ca... | 46b537ea1353c29c9ada561a0469b8f6658501c3 | 651,036 |
def read_folds_info(folds_info_file):
"""
Read lines containing 2 sets of comma-separated integers, with sets separated by '|'.
"""
with open(folds_info_file, 'r') as f:
lines = [l[:-1] for l in f.readlines() if '|' in l]
return [dict(
train=[int(n) for n in tr_str.split(',')],
... | 29647a4c89e68015ee6aa962894233183650fe92 | 651,037 |
import re
def well_formatted_reps(exercises: list) -> list:
"""Filter out badly formatted reps from the list of exercises"""
good_format = lambda exc: re.match(r'\d+-\d+', exc[1])
return list(filter(good_format, exercises)) | aa174fe965503d879cb8192e6a1fe06ef8dd52de | 651,038 |
from datetime import datetime
import getpass
import os
def package_metadata(scene, settings):
"""
Add keys to the package metadata file
"""
metadata = {
"date": datetime.now().strftime("%Y-%m-%d_%H%M%S"),
"package_settings": settings,
"source_scene": scene,
"user": getp... | 839cd1215d7d4baf52257c3094700ecc0c654213 | 651,041 |
def exactly_get_hosts(r_config, r_dest):
"""
精确匹配主机组
:param r_config: 主机组配置[dir]
:param r_dest: 目标主机组 [str]
:type r_config: dict
:type r_dest: str
:return: [list]
"""
rst = []
dest_lst = r_dest.split("|")
for dest in dest_lst:
hosts = r_config.get(dest, [])
rs... | af40bc2b8eb5d347f2fb6b58cb59279cc919a9ab | 651,042 |
def storage_max_constraint_rule(backend_model, loc_tech, timestep):
"""
Set maximum stored energy. Supply_plus & storage techs only.
.. container:: scrolling-wrapper
.. math::
\\boldsymbol{storage}(loc::tech, timestep) \\leq
storage_{cap}(loc::tech)
"""
return bac... | a7b21b62da20f0c57d9a86706d13794f9f0bed75 | 651,043 |
import torch
def nll(x_pred, x_true, log_p, t_pred=None, t_xz=None, hidden=None):
""" Negative log likelihood """
return -torch.mean(log_p) | c5b57041a3cf2d17cc182bdce602ba23684a2dfb | 651,044 |
from datetime import datetime
def scp_get_record(card):
# ----------------------------------------------------------------------------
"""
Extract job data from a single record
:param card: data generated in the function main(job, location)
:param title_elem: Job title
:param ... | d8056daf6b3b3cdfeef9dc2955f05dd9a3ee6e0d | 651,045 |
import math
def decay(x):
"""
This decays slowly towards .8.
"""
return math.exp(-x/60. + 1.2) + .8 | 1cd04342312a4763a69fb9b3517e85c79021d511 | 651,046 |
def less_10():
"""
For test limit 10
"""
return [
('1-10', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
('1,2,5,7-13', [1, 2, 5, 7, 8, 9, 10, 11, 12, 13]),
('14(0-8,18)', [14, 15, 16, 17, 18, 19, 20, 21, 22, 32])
] | 7d893eba9082b0ef4323b6e7b0eedf7b2d98853e | 651,047 |
import re
def cleaning(kalimat):
"""
membersih notasi dan simbol serta tanda baca yg tidak mewakili kata
return :
kalimat
"""
kalimat = kalimat.lower().strip() #huruf kecil dan hapus whitespace
kalimat = re.sub(r"\d+", "", kalimat) #hapus nomor/angka
kalimat = re.sub('[%s]' % re.es... | 1168e8d16ae3afa7021260e5dc57563225972451 | 651,048 |
def get_base_url(job):
"""
If a storage system is defined and set as the default, return the default base URL
to be used to gets/puts
"""
base_url = None
token = None
directory = None
if 'storage' in job:
if 'default' in job['storage']:
if 'onedata' in job['storage']... | 040563257164c6d18f488353f2d94aa57f7524f0 | 651,049 |
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet... | bd70e138c6f5508371fc8b25926caee638e3b37c | 651,051 |
def pick_icon(icon):
"""Convert Dark Sky API icon data-point to weather-icons.css format"""
icon = "wi-forecast-io-" + icon
return icon | 5811ce298fbb8dc3840f2b6bcf63405278baeb9a | 651,052 |
def stripdefaults(target, removeempty=list(), removeexact=dict()):
""" Make output dicts smaller by removing default entries. Keys are
removed from `target` in place
Args:
target (dict): dictionary to remove entries from
removeempty (list): Remove keys in this list from target if the key
... | 120727952cbfb8e8393374dfbd1b7e37c04fd071 | 651,053 |
def get_function_result(thread, timeout):
"""Getting the results of executing the functions launched in the thread,
or ExceptionThread if the timeout is exceeded.
Examples:
threads = []
for x in range(0, 10):
threads.append(run_function_in_thread(run_tests, str(x + 1)))
... | f154f1baf8a095c6d898190fc44e5c529c59b16a | 651,054 |
def prep_s3(biodata_bucket, run_bucket, output_folder):
"""Prepare configuration for shipping to S3.
"""
return {"type": "S3", "buckets": {"run": run_bucket, "biodata": biodata_bucket},
"folders": {"output": output_folder}} | 7dbcef7a250bfe5f0fc2a41d779a6cedad074732 | 651,055 |
def apparent_extract_to_real_extract(original_extract, apparent_extract):
"""
Apparent Extract to Real Extract in degrees Plato
:param float original_extract: Original degrees Plato
:param float apparent_extract: Apparent degrees Plato of finished beer
:return: Real degrees Plato of finished beer
... | 2e55fa2f4b1ca3b0f2689db49da8c43438993aa3 | 651,056 |
def envs_to_exports(envs):
"""
:return: line with exports env variables: export A=B; export C=D;
"""
exports = ["export %s=%s" % (key, envs[key]) for key in envs]
return "; ".join(exports) + ";" | ac4d4d187e189cc5432b12fa0891ba97403a06c7 | 651,058 |
from typing import List
def _index_of_first_non_option(tokens: List[str]):
"""
Find the index of the first token that doesn't start with `-`
Returns len(tokens) if none is found.
"""
return next(
(index for index, token in enumerate(tokens) if token[0] != "-"),
len(tokens),
) | 74c6eb41b7fa46a7edf5e151f22fe1dd4503f3b5 | 651,059 |
def ignore_decimals_numbers(match):
"""
Returns string with space after dot
"""
groups = list(match.groups())
groups[0] = groups[0]
groups[3] = groups[3]
if groups[0] and not groups[3]:
return u"{0}. ".format(groups[0])
elif groups[3] and not groups[0]:
return u". {0}".f... | 0bb92de715761f807ec56dba842ee2523429e205 | 651,060 |
import numpy
def asvoid(arr):
"""View the array as dtype np.void (bytes)
This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
http://stackoverflow.com/a/16216866/190597 (Jaime)
http://stackoverflow.com/a/16840350/190597 (Jaime)
Warning:
>>> asvoid([-0.]) == asvoid([0.])
array... | 673ad2827aeec47f7c73f787c62748b96768aef1 | 651,062 |
def to_list(str_rep_list: str) -> list:
"""
Convenience function to change a string representation of a Python list into an actual list object.
:param str str_rep_list: String that represents a Python list. e.g. "['0.5', '2.0']"
:return: The parsed representative string.
:rtype: list
"""
in... | 2c15a7285ce82dad8e21c769b75d46322e1acfe2 | 651,063 |
import re
def get_image_data(ocr_data):
"""
Recebe uma lista de strings capturadas via scaneamento utilizando scan_image(image).
Retorna um objeto javascript:
{
'cep': '12345-678',
'cod-rastreio': 'XX123456789BR'
}
"""
cep_padrao =... | 0ef7273c7c4f5bc842068d6a066ccba0694345fa | 651,064 |
import os
def get_term_environment_variable():
"""
Return the $TERM environment variable.
"""
return os.environ.get("TERM", "") | 5a78741c4de7c5e66e84b58c08c1977fbe7c3411 | 651,065 |
import stringprep
def b1_mapping(char):
"""Do RFC 3454 B.1 table mapping.
:Parameters:
- `char`: Unicode character to map.
:returns: u"" if there is `char` code in the table, `None` otherwise.
"""
if stringprep.in_table_b1(char):
return u""
else:
return None | 1ea68669bfc6508f909cc255f72b97be3f1bd23e | 651,066 |
import inspect
import sys
def _filter_builtin_modules(path, root, children):
"""Filters module children to remove builtin modules.
Args:
path: API to this symbol
root: The object
children: A list of (name, object) pairs.
Returns:
`children` with all builtin modules removed.
"""
del path
... | 15142359d977f48849fa1cb731dfe1971805cf57 | 651,067 |
from functools import reduce
def operate(func, *dicts):
"""Apply func to values of *dicts and return the result."""
result = [value for d in dicts for value in d.values()]
result = reduce(func, result, 1)
return result | 8be9a0f415ef21a82d88334bbe859c62f619feaf | 651,068 |
import time
def timer(func):
"""Wraps func in time logic."""
def _timer(*args):
start_time = time.time()
res = func(*args)
end_time = time.time()
print(end_time - start_time)
return res
return _timer | 3e29d2915eeca0acedb1ea9b90b490781f3dc740 | 651,070 |
def get_altitude_from_level(level_number):
"""Get geopotential altitude from level number.
Args:
level_number (int): Number of level.
Returns:
float: Altitude in meters above mean sea level.
"""
# Altitudes (heights above mean sea level) corresponding to barometric altitude levels... | 2a015d91c787b14491a8952127850d648b3aad1c | 651,071 |
def parse_subcommand(command_text):
"""
Parse the subcommand from the given COMMAND_TEXT, which is everything that
follows `/iam`. The subcommand is the option passed to the command, e.g.
'wfh' in the case of `/pickem wfh tomorrow`.
"""
return command_text.strip().split()[0].lower() | 56fce623c9a51b0c64e8600d2121f6ee531bc4b1 | 651,072 |
def root(classes):
"""get all root classnames
"""
return [c for c in classes if c.startswith("h-")] | 7929c8087ba75131c1f0a66b01621de644e5aca8 | 651,073 |
def calculate_price(index: dict, products: list, shop: int) -> float:
"""
Find the best purchase combination for a fiven list of items in the shop
:param index: Index of shop
:param products: List of items
:param shop: ID of shop
:return: Best price
"""
price = 0.
cp = list(products)... | f140ef4ab308ea6c243f99437a5186eb8f291a6b | 651,074 |
def _account_for_bubble_fields(sg_entity_type, field_name):
"""Detect bubble fields and return the proper entity type and field name.
:param str sg_entity_type: The intput entity type name. If the field name
is a bubbled field notation, this value will be replaced by the
parsed entity type in t... | 677f7d22a2a0422b5f424bddc05c5be054004563 | 651,075 |
def _get_index(indices, index_name):
"""
Get Index from all the indices.
:param indices: DED indices list
:param index_name: Name of the index
:return: DED Index
"""
for index in indices:
if str(index) == index_name:
return index | 6a6704d6b91d80c57d748414b0947e65a6c2697e | 651,076 |
import base64
import hashlib
def edgedb_name_to_pg_name(name: str, prefix_length: int = 0) -> str:
"""Convert EdgeDB name to a valid PostgresSQL column name.
PostgreSQL has a limit of 63 characters for column names.
@param name: EdgeDB name to convert
@return: PostgreSQL column name
"""
if n... | 88987082790f6294a22dad2dfb4defb8c7884539 | 651,077 |
def td_flipy(txtdict, w, h):
"""Mirror along y axis"""
# return txtdict
ret = {}
for y in range(h):
for x in range(w):
ret[(w - x - 1, y)] = txtdict[(x, y)]
return ret | 6c10406f9a0e23a87db4cdf4cc6d35e3c225b2e9 | 651,078 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.