content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def new_Rt(b,c,a,Rt):
"""
@params
b : transimition rate, normal value 0.45(or 0.5), masks shops 0.3 , masks closed spaces 0.2 , masks everywhere 0.1-0.05
c : contracts per person : normal value : 15, work from home 10 , closed bars 8 , closed restaurants 7, lockdown 5, strict lockdown :3
a : goverme... | 25ea66aeff808547a0dc2c52f9bf3bcc96cfea8a | 631,486 |
def _signature_get_bound_param(spec):
""" Private helper to get first parameter name from a
__text_signature__ of a builtin method, which should
be in the following format: '($param1, ...)'.
Assumptions are that the first argument won't have
a default value or an annotation.
"""
assert spec... | 6c5e560e001968a9e84b24df266a30771732f275 | 631,487 |
import glob
import os
def get_newest_file(directory, exclude=None):
"""
Finds the newest file name, excluding those that contain an "exclude" expression
:param directory: STR of directory
:param exclude: STR of filetypes to exclude, e.g., ".txt"
:return: STR of newest file names
"""
file_l... | c7cc2e93ee5cc69363db4c419e21ca8d78bdc9e4 | 631,488 |
def mock_get_user_data(valid_oauth_token, social_user_data):
"""
Функция-заглушка для вызова API социальных сетей. Возвращает данные
гипотетических пользователей.
"""
def get_json(self, url, *args, **kwargs):
token = kwargs['params']['access_token']
if url.startswith('https://api.vk... | 69ae4010a077b62b65a44d3c33da4a0b5e9f6b35 | 631,489 |
def using_split2(text, _len=len):
"""
LEGACY
Takes a text in input and returns a list of tuples with surface, start and end offsets for each token.
From: http://stackoverflow.com/questions/9518806/how-to-split-a-string-on-whitespace-and-retain-offsets-and-lengths-of-words
:param text: a string of t... | dd70fadca81248d2277e9e86d12f7cfd8f25c08b | 631,490 |
from pathlib import Path
import importlib
import inspect
def create_init_line_library(module_path: str, lib_name: str) -> str:
"""Creates an __init__ entry of the library dir for the corresponding metadatablocks file"""
# Get the module name from file
module_name = Path(module_path).stem
# Import pa... | fb1d1cd713cc1bd39aed4de7441d9c801a255ece | 631,491 |
def to_wkt(geom):
"""Konverter en GeoJSON-agtig geometri til WKT."""
def coords_to_wkt(coords):
format_str = " ".join(("%.8f",) * len(coords[0]))
return ",".join([format_str % tuple(c) for c in coords])
coords = geom["coordinates"]
if geom["type"] == "Point":
return "POINT (%s)... | 35ab249af96aeacbd5e4c5d728af9bdfb9ea161e | 631,492 |
def bytes_2_human_readable(number_of_bytes, precision=1):
"""
流量bytes转换为kb, mb, gb等单位
"""
if number_of_bytes < 0:
raise ValueError("!!! number_of_bytes can't be smaller than 0 !!!")
step_to_greater_unit = 1024.
number_of_bytes = float(number_of_bytes)
unit = 'bytes'
if (number... | 1df26e332aa455c2662c414cc04fd33c626f7e2b | 631,493 |
def get_object_string(host, namepath):
"""given an host name and a name path as described in register_object_name,
return a corba string identifier
"""
strname = '/'.join(['.'.join(path_elt) for path_elt in namepath])
return 'corbaname::%s#%s' % (host, strname) | f47fc68382f085b750eafb6a9bd3635ed4ee324e | 631,494 |
def get_success_message(action, task_uri):
"""
message for different types of raid actions
"""
msg = "Successfully submitted {0} volume task.".format(action)
status_message = {"msg": msg}
if task_uri is not None:
task_id = task_uri.split("/")[-1]
status_message.update({"task_uri"... | a860c729140e8c7b52908fa1eb3478f903da70a7 | 631,496 |
def classify_status_code(status_code):
"""
Prometheus recomends to have lower number of cardinality,
each combination creates a new metric in datastore,
to reduce this risk we store only the class of status code
"""
if 200 <= status_code < 300:
return "2xx"
if 300 <= status_code < 4... | 6ad20ac6a931bdb58997782542221b3c5fe7f8c1 | 631,498 |
import contextvars
def _get_parallel_context():
"""Return parallel context based on contextvars
with all the user context variables cleared
to None.
"""
ctx = contextvars.copy_context()
# clear any user context variables to None
for var in ctx.keys():
if not var.name.startswith("_t... | 13d5f00127b2f15fd5a58f98247d191dacbd9365 | 631,499 |
def decode_bin(bin_array):
"""Takes in an array of bits and returns the number associated"""
bitstring = ''.join(bin_array)
number = int(bitstring, 2)
return number | 04b3944db60d29214141afd4e458ad7dad66ccf6 | 631,500 |
import numpy
import math
def func(x):
""" function to integrate"""
fx = numpy.sin(math.pi*x)
return fx | 6991e44178f1bee2afc7c4c6c2e989eb4fefcbec | 631,501 |
def responsive_navigation_bar(
shade='dark',
brand=False,
brandLink="#",
outsideNavList=False,
insideNavList=False,
htmlId=False,
onPhone=True,
onTablet=True,
onDesktop=True,
):
""" *Create a twitter bootstrap responsive nav-bar component*
**Key Arguments:**
- ``shad... | eb14db69155e2c94a997349ef31d6c63763e8a71 | 631,502 |
def invertKey(key):
"""
Inverts a substitution cipher key so that an encryption key becomes a decryption key and vice versa.
"""
invkey = {}
for (key, subst) in key.items():
if subst in invkey: raise Exception("Duplicate key " + subst)
invkey[subst] = key
return invkey | 0060473f680781603bdc845a63fe2ed2f455e4ca | 631,504 |
import time
def wait_for_data_to_be_processed(udp_server, expected_stats, timeout=120):
"""
helper function for udp server tests to wait for metrics to be processed
"""
timeout_ts = time.time() + timeout
while time.time() < timeout_ts:
with udp_server.lock:
if len(udp_server.st... | 09aa944734f95218776866edcb7eb437110e379c | 631,505 |
import numpy
def convert_to_one_hot(y):
"""
converts y into one hot reprsentation.
Parameters
----------
y : list
A list containing continous integer values.
Returns
-------
one_hot : numpy.ndarray
A numpy.ndarray object, which is one-hot representation of y.
"""... | 55bada1a3c8a52913ad64b71d8f119575edb4acc | 631,507 |
import re
def remove_s(sentence):
"""
Remove all the ocurrence </s>.
:sentence: string
"""
return re.sub('</s>', '', sentence) | 612a2f1df56533aaaae31f131c1ca3ea5e257efc | 631,508 |
def max_degree(g):
"""
Returns the maximum number of edges of any node in the graph
"""
return max([g.degree[n] for n in g]) | 0184e4c795e326bb09c5ecb4830cfb489fc7b419 | 631,509 |
import re
def natural_sort(item):
"""
Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
if item is None:
... | f121cf37b0dfc24f01fcb4d798d491b664048a00 | 631,510 |
def parse_torrent_id(arg):
"""Parse an torrent id or torrent hashString."""
torrent_id = None
if isinstance(arg, int):
# handle index
torrent_id = int(arg)
elif isinstance(arg, float):
torrent_id = int(arg)
if torrent_id != arg:
torrent_id = None
elif isin... | 77fb43d78faf2dd44055685dc996f54bbc82fa29 | 631,511 |
def dataset_shape(name: str):
""" Returns the number of classes followed by the shape of a sample in a
given dataset. """
name = name.strip().lower()
g = globals()
options = [n[5:] for n in g if n.startswith('load_') and n != 'load_dataset']
if name not in options:
raise NameError('... | 57f042b6436ba05f51dcda5e6984d7efbac64d5e | 631,512 |
def _recenter(x, fcn_mean, zscore, axis=-1):
"""Recentering function."""
_std = x.std(axis=axis, keepdims=True) if zscore else 1.
return (x - fcn_mean(x, axis=axis, keepdims=True)) / _std | cc7d012d252cfb02e2ecd67ff569078c39ffa3e4 | 631,513 |
def build_alignment_param_metrics(align):
""" Transform alignment param dict -> alignment metrics for output to json"""
aln_param_metrics = {}
for key, value in align.iteritems():
aln_param_metrics['alignment_' + key] = value
return aln_param_metrics | 6adf44805776ae5b3e93a08888050e34d5e9a92a | 631,514 |
def _reduce_sampled_fluxes(sampled_fluxes, reactions):
"""
Reduces the input dataframe of sampled fluxes to a subset of
selected reactions.
Parameters
----------
sampled_fluxes : pandas.Dataframe
The calculated fluxes, output of sampling. For each reaction,
n fluxes will be calc... | b6d6a618a0435b9e4f28fe4b10c611e9d269b698 | 631,515 |
import pwd
def uidFromString(uidString):
"""
Convert a user identifier, as a string, into an integer UID.
@type uid: C{str}
@param uid: A string giving the base-ten representation of a UID or the
name of a user which can be converted to a UID via L{pwd.getpwnam}.
@rtype: C{int}
@retu... | d83a6c9dff5bc193335f1719b7f0e7395aacc2fd | 631,517 |
def istrue(value):
"""
Accepts a string as input.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
``False``.
``istrue`` is not case sensitive.
Any other input ... | b1b14852cb814c9ed64a4074b32dffe6e4c0de49 | 631,518 |
import struct
def pack_tone_tail(tone_bin, b_format):
"""
pack fixed tail
"""
if b_format == 1:
tone_bin += struct.pack("<H", 0xDFAC)
return tone_bin | b8a01b9a78bb600a4c27251ca11cc8bb8cb21232 | 631,519 |
import argparse
def parse_cmdline(argv):
"""Parse the commandline into known and pipeline arguments.
The known arguments are required for this specific program to function,
and the other pipeline arguments can be used to configure beam and the
specific beam backend being used. See
https://github.com/apach... | d561af3d704297041fcc7d8d7dd9cadf5ea174d8 | 631,520 |
def _getDstDataShape(srcVar, dstGrid):
"""
Get the shape of the dst data
Parameters
----------
srcVar
the variable from which all axes other than lat/lon will be taken from
dstGrid
target, horizontal grid
Returns
-------
list
"""
shp = srcVa... | edd7a0e00f796576e54769f905d5713d13c4d7ad | 631,521 |
def declare_draw_if_no(player_one, player_two):
"""
Return True to continue
"""
if player_one.find('no') > 1:
return None
elif player_two.find('no') > 1:
return None
else:
return True | 7e8091ba634a1b38c8101f81b8af4611cbc4eb40 | 631,522 |
def true_pred():
"""Returns a predicate that always returns ``True``."""
def new_pred(*args):
return True
return new_pred | 3ecece45a6fb233f558e918a09f130693019c7a3 | 631,523 |
import os
import yaml
def load_settings_file(settings_file):
"""Load a yaml settings file"""
if os.path.isfile(settings_file):
with open(settings_file, 'r') as ymlfile:
return yaml.load(ymlfile, Loader=yaml.SafeLoader)
else:
return None | 51c28179256dea38eea8f84d7250fc20a078ad35 | 631,524 |
def larger_than_prev_count(input_):
"""Takes in input file which is a list of numbers
Returns the number of occurences of a measurement being larger than the previous measurement"""
sum = 0
for i in range(1, len(input_)):
if input_[i] > input_[i-1]:
sum += 1
return sum | cb39715c6ca0f7322b1404ba9933762b6d82f454 | 631,527 |
import re
def decode_bytes(data: bytearray) -> str:
"""
Decodes a bytes array from a file upload
:param data: a UTF-8 encoded byte array
:return: a cleaned string
"""
pattern = re.compile('\r', re.UNICODE)
res = data.decode('utf-8', 'ignore')
res = pattern.sub('', res)
return res | 0ec48f84da9acfdb68363fffbdf81546523588fb | 631,528 |
def slice_for_range(data, fromVal, toVal):
"""
Returns a slice indicating the region [fromVal, toVal] in a 1D ndarray data
Example:
>>> data = linspace(1, 50, 50)
>>> s = slice_for_range(data, 4, 10)
>>> data[s]
array([ 4., 5., 6., 7., 8., 9., 10.])
"""
if (data[-1] - da... | 44cb009d01cb1bf4415aa867cd4cc9e2685e8d4c | 631,529 |
import dill
def load(filename):
"""
This function opens a serialized file and returns the object.
Parameters:
----------
filename: str, the name of the serialized file to be opened.
Returns:
-------
obj: The object contained in the serialized file.
"""
input_file = open(filename, 'rb')
obj = dill.load(... | 47b4dd55ac3cc37ea466407e5581e6826f24b29e | 631,531 |
def timesTwo(input_array):
"""
Multiples the input array times two.
"""
return 2*input_array | 4aa7c9408d1ea6f608dcdde6e297e571579f735d | 631,532 |
def get_login_tokens(login_response_body_dict):
"""Creates dictionary of login keys to use to make additional request calls to USPS
Args:
login_response_body_dict: response body (type dictionary) returned by the USPS logon endpoint.
Returns:
Dictionary containing logon key and... | 7e4fc7f7564fbc85ffa62fb31709f29154ae4f61 | 631,533 |
def url_strip_appendix(url):
""" removes trailing stuff behind a url definition
"""
lst = url.split('/')
return lst[0] + '//' + lst[2] | 17e8c9c138929085916fa1cc1af8d974d3137354 | 631,534 |
import torch
def from_tanh_space(x, box=(-1., 1.)):
"""
Convert a batch of tensors from tanh-space to oridinary image space.
This method complements the implementation of the change-of-variable trick
in terms of tanh.
:param x: the batch of tensors, of dimension [B x C x H x W]
:param box: a ... | 4331e6d353e26c17ebc9721cbf8ebf49807a6ff7 | 631,535 |
def read_file_str(filename):
"""Read the file and return as a string."""
with open(filename, "r") as f:
file_str = f.read()
return file_str | 973939c2173ae374c12ca4dd8e325ef0adb03b95 | 631,536 |
import requests
from pathlib import Path
import tempfile
import shutil
def download_file(url: str) -> str:
"""
Download ngrok binary file to local
Args:
url (:code:`str`):
URL to download
Returns:
:code:`download_path`: str
"""
local_filename = url.split("/")[-1]
... | 93f4f6acbd6e08272d8dc9fd9b0f079be0c8ab94 | 631,537 |
from typing import Dict
from typing import List
def compute_recall_at_k(
question_id_to_docs: Dict[str, List[dict]], k: int, relevance_threshold: float
) -> float:
"""
Given a dictionary mapping a question id to a list of docs, find the recall@k.
We define recall@k = 1.0 if any document in the top-k ... | d912809c1aa96b0a7da05e5ab23a4e823e804923 | 631,538 |
import numpy as np
def calculate_plane_coords(coords_list, infile_dims):
"""Calculate the coordinates of the triangular plane spanning from roughly
around the participant's nose, down to roughly below the rear of the neck.
:type coords_list: list
:param coords_list: A list of lists, describing the th... | e01cb3065c6e71048ee027773739837afac948a5 | 631,539 |
def _(s, truncateAt=None):
"""Nicely print a string to sys.stdout, optionally
truncating it a the given char."""
if truncateAt is not None:
s = s[:truncateAt]
return s | 3d4cf40e19c3412d6c7fd6fb68077291c067ff6c | 631,540 |
from typing import List
import warnings
def find_warning(caught: List[warnings.WarningMessage], msg: str) -> bool:
"""Return whether exactly one matching warning was caught.
This only works for UserWarning subclasses.
Arguments:
caught: The messages to check.
msg: The warning message str... | b9bda98135bd97028880b015c5f3a9af625efdaa | 631,542 |
def get_files() -> list:
"""Gets a list of paths of files the user wants to compare"""
files = []
while True:
file = input("Enter the path of a file to compare (or enter to quit): ")
if file == "":
break
files.append(file)
return files | d47a95448f6b69acbc517e48f2862371e3f09208 | 631,543 |
def _atomic_hotspot_ins(jobname, probename, settings):
"""
template for atomic hotspot input file (SuperStar ins)
:param str jobname: general format (<probe_type>.ins)
:param str probename: probe identifier
:param `hotspots.atomic_hotspot_calculation.AtomicHotspot.Settings`settings:
:return: str... | 242f6a0b47221000f77862ef76dcabbcc0d8a08a | 631,544 |
def handle(editor,ch):
""" hook called for each keystroke, can be used for auto-indent or auto-complete """
return ch | 9c293b5d1e72760dbdc06378a10072a7864ba476 | 631,545 |
def all_anagrams(chars: str) -> list[str]:
"""
Returns:
A list of all permutations of a given string of characters, without
character repetition.
Example:
>>> print(all_anagrams('abc'))
>>> ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
"""
result: list[str] = []
if len(cha... | 77bfcfce65cb21998de8c5f9fc0fe4e5dd8bb8bf | 631,546 |
def _inject_encrypted_credentials(dataproc, project, region, cluster_name,
cluster_uuid, credentials_ciphertext):
"""Inject credentials into the given cluster.
The credentials must have already been encrypted before calling this method.
Args:
dataproc: The API client for ca... | 951e3cec056be3a119449b809132ba5bc21c7c5b | 631,547 |
import argparse
import sys
def parser(default_args, args):
"""Return parsed command line arguments."""
parser = argparse.ArgumentParser(
description=(
'Watch the specified ONETEP jobs and write out a simple log or\n'
'notify the user via email with relevant information.\n'),
... | 62a315497d00f577262118b7db7013972055bf56 | 631,548 |
def servers_by_hosts(nova, hosts):
""" Get a map of host names to VMs using the Nova API.
:param nova: A Nova client.
:type nova: *
:param hosts: A list of host names.
:type hosts: list(str)
:return: A dict of host names to lists of VM UUIDs.
:rtype: dict(str: list(*))
"""
resu... | 65a0b5575615c6495b5922182487ac573e94c562 | 631,549 |
def from_file(filename):
"""Open a file and read its first line.
:param filename: the name of the file to be read
:returns: string -- the first line of filename, stripped of the final '\n'
:raises: IOError
"""
with open(filename) as f:
value = f.readline().rstrip('\n')
return value | 35c0e5cd7461e990ba0c5e33b9ace4b18dfb649b | 631,550 |
import yaml
def _build_data(data, tmpdir):
"""
Helper method to create a dummy config file
"""
f = tmpdir.join("custom_eventsd")
f.write(yaml.dump(data))
return f | db594213f410ce6608c6e1753f98c7a8674790a0 | 631,551 |
def psf_sample_to_pupil_sample(psf_sample, samples, wavelength, efl):
"""Convert PSF sample spacing to pupil sample spacing.
Parameters
----------
psf_sample : float
sample spacing in the PSF plane
samples : int
number of samples present in both planes (must be equal)
wavelength... | 420196a40438b4aaf1fb2dfe6075418a99d1a614 | 631,552 |
def average(data):
"""
Calculate the average of values of the data.
Args:
data (list): values.
Returns the average of values of the data.
"""
return 1.0*sum(data)/len(data) | b65754c225d311a46877dba3f59db1e6cc3ae1e1 | 631,553 |
def od2list(od):
"""Convert an ordered dictionary to a list."""
return list(od.values()) | 711af62676ec35b4bb3be447b507901fbc5317b9 | 631,554 |
def I(x):
"""Returns its argument as it is.
This allows to call Python code within the formula interface.
Examples
----------
>>> x + I(x**2)
>>> x + {x**2}
>>> {(x + y) / z}
"""
return x | 02d2172c3ffdfd020a137b3259f721de3e214221 | 631,555 |
def get_group(name, match_obj):
"""return a blank string if the match group is None"""
try:
obj = match_obj.group(name)
except:
return ''
else:
if obj is not None:
return obj
else:
return '' | 8ea0e942e6c9fbf7eadbfeb5bbac20b01d2a5750 | 631,556 |
def setGauss(points):
""" Create a system of equations for gaussian elimination from
a set of points. """
n = len(points) - 1
A = [[0 for i in range(n+2)] for j in range(n+1)]
for i in range(n+1):
x = points[i]["x"]
for j in range(n+1):
A[i][j] = x**j
A[i][n+... | 48f80a4b69a29b71330685cf18195c739861bca8 | 631,557 |
import os
def msvc_batch_key(action, env, target, source):
"""
Returns a key to identify unique batches of sources for compilation.
If batching is enabled (via the $MSVC_BATCH setting), then all
target+source pairs that use the same action, defined by the same
environment, and have the same targe... | 182abca0e6e30d3505c60d8db5d77669e10d2665 | 631,558 |
def expireAfter(resource, value):
"""
Check if the expirationTime attribute of the resource is chronologically after the specified value.
:param resource:
:type resource:
:param value:
:type value:
:return:
:rtype:
"""
try:
return resource.expirationTime > value
exce... | 9bfd6e240523a06f8f60f57d9ddec4bd48d0ab82 | 631,559 |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
if not input_list:
return []
if len(input_list) == 0 or len(input_list) == 1:
return input_list
lo ... | 6e8eec5aa32448d80dcce469a39a4265cde9b16b | 631,560 |
from pathlib import Path
def _mklib(topdir: str, pkgname: str, libname: str) -> Path:
"""Make a for-testing library.
Args:
topdir: the toplevel directory in which the package will be created.
This directory must already exist.
pkgname: the name of the package to create in the top... | c800e94baef515e304616225f0e6df4829a712be | 631,561 |
def deprecated_or_revoked(obj):
"""
Return true if object has a truthy "revoked" or "deprecated" attribute,
otherwise False
"""
return getattr(obj, "revoked", None) or getattr(obj, "deprecated", None) | 5be93df40a7bd2364b0668fcc5273fa814729b28 | 631,562 |
def _get_signs(string):
"""
Modifies the x, y integer coordinates with direction or multiplication by 0.
:param string: (str)
:return:
"""
x, y = 0, 0
if 'up' in string or 'montez' in string:
y = 1
elif 'down' in string or 'descendez' in string:
y = -1
if 'right' in ... | 2e864ce4fc03c4e69b14243d454ab698a8b8b05a | 631,563 |
def prepare_search_string(string: str) -> list:
""" Transform a search string into a list of strings if "|" was used inside the string
Agrees with escaped pipes.
:param string: String to prepare
:return: List of strings to search for
"""
value = string.replace('\\|', '¤$¤')
value = [v.repl... | 93373680115d8a88721a48dd90a34d3fd7784b42 | 631,564 |
def build_plural_mappings(special_mappings, resource_map):
"""Create plural to singular mapping for all resources.
Allows for special mappings to be provided, for particular cases..
Otherwise, will strip off the last character for normal mappings, like
routers -> router, unless the plural name ends wit... | 98380e93a91d1c1f85da186c876fe9e9325de702 | 631,566 |
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
... | ecdca60064fca3d023c86f683bf0a69216614c55 | 631,569 |
def get_next_match_pick_first_available(population):
""" Decides next two player indexes who will play against each other next, iterating over the list
and picking the very first available"""
p1 = None
for player in population:
if player.available:
if p1 is not None:
... | 6fb751a2596bc5d9245dfd967ec5f41b5d85a5f9 | 631,570 |
def rank(tensor):
"""Get tensor rank as python list"""
return len(tensor.shape.as_list()) | 9d62e91b9fd4a540ce2cc2e5d8ecaf1dfdcc21d2 | 631,571 |
def json_set(item, path, value):
"""
Set the value corresponding to the path in a dict.
Arguments:
item (dict): The object where we want to put a field.
path (str): The path separated with dots to the field.
value: The value to set on the field.
Return:
(dict): The update... | 185e8f060c695d0b0b0391917b339b7809d17521 | 631,572 |
import six
def binary(v, encoding='utf-8', errors='strict'):
"""cast value to binary type,
Args:
v (typing.Any): value
encoding (str, optional): encoding when value is not binary. Defaults to 'utf-8'.
errors (str, optional): errors setting when value is not binary. Defaults to 'strict... | 523015253a2fea2c690ee2d57fd932ccccf05e63 | 631,573 |
import re
def process_question(question):
"""Process question.
Keep punctuations and use lower cases.
Args:
question: a string of a sentence
Returns:
question_words: a list of words in this sentence
"""
question_words = re.findall(r"[\w']+|[.,!?;]", question)
return [w.encode('utf-8').lower()... | bf9086ce0e4c31fb90908f7e6e434c5dbd8bedb1 | 631,574 |
def str_or_none(value):
"""Returns string casted value if given value is not None"""
return str(value) if value is not None else value | f92c0399c62ce2355a09c5d346e4053d669c6cae | 631,575 |
def semi_deviation(r):
"""
Returns the semi deviation, aka negative semi deviation of r
r must be a Series or a DataFrame
"""
is_negative = r < 0
return r[is_negative].std(ddof=0) | 6302924e80948948db0a93b8d1b4736bdac88227 | 631,576 |
from typing import List
from typing import Tuple
def row_col_cell_ids(tiling: List[List[int]]) -> List[Tuple[int, int, int]]:
"""
Infers absolute rows and columns for every cell from the tiling of a table.
:param tiling: A list of list of tiling of a table as returned from the :meth:`_tile_table`
:re... | 914c898dbe74c3d15ffb906ecc194be487a1c125 | 631,577 |
def step_factor(t):
""" Euler integration suppression factor."""
return (1+t) | 106d41bb761d7dcaf7b313e9647ce3ec20e66ee3 | 631,578 |
def sort_func(version):
"""
Sort func for versions
:Example:
>>> sort_func('1.2.3')
[1, 2, 3]
>>> sort_func('1.2.q')
ValueError: invalid literal for int() with base 10: 'q'
:param version: version of git repository
:type version: str
:rparam split_version: split version and t... | a7459e4024d1fcb85e62f2fe5ed7f1d41d6f79c9 | 631,579 |
import requests
def get_public_ip():
"""Return the current public IP from https://ipify.org."""
r = requests.get('https://api.ipify.org?format=json')
r.raise_for_status()
ip_dict = r.json()
if "ip" in ip_dict:
return ip_dict["ip"]
else:
raise ValueError("Error getting public IP... | ac0cee7e7578cb6e5a719f9e66a65085fd70932b | 631,580 |
def GetHealthAlertRecipients(builder_run):
"""Returns a list of email addresses of the health alert recipients."""
recipients = []
for entry in builder_run.config.health_alert_recipients:
if '@' in entry:
# If the entry is an email address, add it to the list.
recipients.append(entry)
return re... | 4e3bfe74a91ba9fce126d7df021b530c30cb7b43 | 631,581 |
def case_check(inp: str):
"""
A function to check if the value entered via console is 'y' or 'n'
Args:
inp(str): Input string
Returns:
lower.inp(str): lower function on the input string
"""
return inp.strip().lower() | 15b3b843418ca0f892b6bd3ce8bdb1613b46c257 | 631,582 |
def set_fixstim_color(stim, color):
"""Set the fill and line color of a stim."""
stim.setFillColor(color)
stim.setLineColor(color)
return stim | 9973643ef3736ed29423cff20de56695d65b6e34 | 631,583 |
def buscar_posicion_minimo(lista, i):
"""Devuelve la posición del elemento mínimo en lista[i:]"""
posicion_minimo = i
while i < len(lista):
if lista[i] < lista[posicion_minimo]:
posicion_minimo = i
i += 1
return posicion_minimo | 2a2feb608fb8b0e52ea6f38da690f432eed7d26f | 631,585 |
def is_init_st(id):
"""Used in p_one_line()
---
Checks if id begins with i or I.
"""
return id[0] in {'i','I'} | c4ac5d5de18099e437e3a1e1f03a511fdb3e6465 | 631,586 |
import torch
import math
def closest_angle_error(angle_a: torch.Tensor, angle_b: torch.Tensor) -> torch.Tensor:
""" Finds the closest angle between angle_b - angle_a in radians.
:param angle_a: a Tensor of angles in radians
:param angle_b: a Tensor of angles in radians
:return: The relative angle err... | 89073a2d4e69cccecf733f26f301ee43929f7c14 | 631,587 |
def auth(req, **kwargs):
"""
:kwargs: None
"""
return {'status': True, 'msg': 'Login Verified.'} | a5187b0877fc7c736253d2b88f78281e04f8bc98 | 631,588 |
def hasattr(object, name):
"""Return whether the object has an attribute with the given name.
:type name: str
:rtype: bool
"""
return False | 2895261668f12a83d4f42cc8eb87e7d2f7aac1ca | 631,589 |
def to_numbers(string_array):
""" Convert an array of strings to floating point numbers """
return [float(string) for string in string_array] | c757207939a812a51abd1f09552cf8c752168bec | 631,590 |
def get_tenant_verify(tenant):
"""Return whether to turn on SSL verification."""
# sandboxes and the develop instance have a self-signed certs
if 'SANDBOX' in tenant.upper():
return False
if tenant.upper() == 'DEV-DEVELOP':
return False
return True | bfed1bea0fba22f40d1c5e92a7ad5a06ef52f9a4 | 631,592 |
def span_overlap(span_indices1, span_indices2):
"""Boolean check if two spans overlap.
This does an exclusive overlap check (i.e. (0-2) and (2-3) does not overlap).
"""
return span_indices1[0] < span_indices2[1] and span_indices2[0] < span_indices1[1] | 7641ad1875555e5a4419bd2b9b87c4eeec959b27 | 631,593 |
import operator
def sort_vocab_by_frequency(vocab_freq_map):
"""
sorts vocab_freq_map by count
args:
vocab_freq_map: dict<str term, int count>, vocabulary terms with counts.
returns
list<tuple<str term, int count>>, sorted by count, descending
"""
return sorted(vocab_freq_map... | 9a7c692054f9b6a90b65149aa70c997aefd3d5d0 | 631,594 |
def zipdict(ks, vs):
"""Returns a dict with the keys mapped to the corresponding vals."""
return dict(zip(ks, vs)) | cb00e2ed7810c3cbebe1ef749fc6019b564db84e | 631,595 |
import multiprocessing
def _check_n_jobs(n_jobs):
"""Check n_jobs in particular for negative values
Parameters
----------
n_jobs : int
The number of jobs.
Returns
-------
n_jobs : int
The checked number of jobs. Always positive.
"""
if not isinstance(n_jobs, int):... | 09473f851f957495044439364fa62e339afc78d3 | 631,596 |
import subprocess
import json
import sys
def run_osquery(sql):
"""take sql command you'd like json output for from osquery"""
cmd = ['/usr/local/bin/osqueryi', '--json', sql]
jsony_out = subprocess.check_output(cmd)
try:
jsony_dictlist = json.loads(jsony_out)
except ValueError:
sys... | 265fd61aa82e389c6fa169da94e8f3bf77dcb050 | 631,597 |
import itertools
def range_(start, stop=None):
""":yaql:range
Returns sequence from [start, stop).
:signature: start.range(stop => null)
:receiverArg start: value to start from
:argType start: integer
:arg stop: value to end with. null by default, which means returning
iterator to se... | 03f805ecec6f8b39dfbc7b8539d5d2c73ccbfe0d | 631,599 |
def copy(src, dest):
"""
Copy a file using -f so it doesn't fail if the destination exists.
:type src: string
:param src: Source file.
:type dest: string
:param dest: File destination.
"""
return ["cp -f %s %s" % (src, dest)] | f5293e61be8d2a7dd127a2e6adfc3846885054be | 631,602 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.