content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def isMail(mail):
"""
check if a mail
:param mail: mail
:type mail: str
:return: True of False
"""
if re.compile(r'[^\._][\w\._-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+$').match(mail):
return True
else:
return False | c1fc308a89cefb86b50bff594bc6ed4c85abd3cb | 35,787 |
def get_automl_options_string(args):
""" This function creates a string suitable for passing to another script
of the automl command line options.
The expected use case for this function is that a "driver" script is given
the automl command line options (added to its parser with add_automl_options)... | bfe27e8e76666e0e5ca0f74feef8465234baebe8 | 35,788 |
import torch
def get_normal(xs):
"""Normals of xs.
Args:
xs: tensor [num_xs, 2]
Returns: tensor [num_xs, 2]
"""
return torch.stack([xs[:, 1], -xs[:, 0]], dim=-1) | b8bb383e4750651d391885a898d481e53d80add8 | 35,790 |
import torch
import math
def euler_angles_to_rotation_matrix(car_rotation, is_dir=False):
"""Convert euler angels to quaternions.
Input:
angle: [roll, pitch, yaw]
is_dir: whether just use the 2d direction on a map
"""
roll, pitch, yaw = car_rotation[:,0], car_rotation[:,1], car_rotatio... | bb8c73f9432bfbe3730961ae34ff2d2b9663b0a5 | 35,791 |
def mock_purge_unauth_url(url, request):
"""
Mock a purge request in which the credentials are valid, but the
url that was requested is not allowed
"""
return {'status_code': 403,
'content-type': 'application/json',
'server': 'Apache',
'content': {
... | a15e329f79fb6a004e88624781d8b8e90d438e00 | 35,795 |
import csv
def extract_pids_from_file(pid_file):
"""
Extracts pids from file containing a header and pids in each line
:param pid_file: path to the file containing the pids
:return: list of ints
"""
pids = []
with open(pid_file, 'r') as f:
csv_rows = csv.reader(f)
next(csv... | 77c74ec079d4c55d4c115b5966f415d6ae78e4e6 | 35,796 |
def pythagorean_triplet(a, b, c):
"""
Tests whether a^2 + b^2 = c^2.
"""
return a**2 + b**2 == c**2 | 3bda7322d0a8f4af5d4faa3f4ef5d5c34acbc6d3 | 35,797 |
def process_rows_of_trump_tweets(rows):
"""
"""
text = []
punctuation = [".", ",", "!", '"', "-", "?", ":"]
# a "row" is a list of strings, but only some of them are words
for row in rows[:-1]: # first row is header etc.
for (idx, entry) in enumerate(row):
## get text out of... | a52e49a62c5bfbc90c481b90b85a3b3dc30460ed | 35,798 |
from pathlib import Path
import filecmp
def are_directories_equal(dir1: Path, dir2: Path) -> bool:
"""Compares two directories recursively.
Files in each directory are
assumed to be equal if their names and contents are equal.
Args:
dir1: The first directory.
dir2: The second directo... | 976fe0ba26c50b67204b9888eec4176a328d114e | 35,799 |
import argparse
def get_arguments():
"""
Wrapper function to get the command line arguments. Inserting this piece of code
into its own function for conda compatibility.
"""
parser = argparse.ArgumentParser(
prog='StringMeUp',
usage='stringmeup --names <FILE> --nodes <FILE> [--outp... | 452ac8f1e6edbe8dae67731b1b76275595330bcc | 35,801 |
import sys
import io
def stdout_fileno_available():
"""
Tests if sys.stdout.fileno is available in this testing environment
"""
try:
sys.stdout.fileno()
return True
except io.UnsupportedOperation:
return False | 0b29bb8c0598738efcd6fc91c3159fc5b2acfeb5 | 35,802 |
def int16_to_bits(x):
"""
Unpack a 16 bit integer into binary fields. See the syntax for
this here https://docs.python.org/3/library/string.html#format-specification-mini-language
Parameters
----------
x : int16
single integer.
Returns
-------
List of binary fields alig... | 5993bfdae9666d364f9b2629fbbb862965cedddd | 35,803 |
from typing import Callable
import ast
import importlib
import functools
def str_to_class(module_name: str, function_name: str) -> Callable:
"""Convert a string to a class Base on: https://stackoverflow.com/a/1176180/576363.
Also support function arguments, e.g. ifft(dim=2) will be parsed as a partial and re... | d7a31b2d2a8352262fe36f8d82465801bc211ce3 | 35,804 |
def template(name, types=()):
"""template decorator."""
def identity(f):
return f
return identity | d8d98ead8b89807e46718c9bce662d77f4921521 | 35,805 |
def distsimpleimg(coords):
"""Return distance (mm) from muscle insertion point
to the place where the single image ultrasound was taken
Arguments:
coords {array} -- Array containing x and y coordinates of calibration scale,
insertion point and place of the image.
Returns:
... | 0aeb732895fd40393e4e175adbb493018932b867 | 35,807 |
def remove_redacted(obj):
"""
Removes all string object with the value __redacted__
"""
if isinstance(obj, str):
if obj == "__redacted__":
return True, obj
else:
return False, obj
elif isinstance(obj, list):
for index, item in enumerate(obj):
... | 1ca2ba707b3b64ec29245d122f19b5547141de4b | 35,809 |
def index():
"""[summary]
Hello world function
[description]
This function is only for testing if the web service is in operating
"""
return "Hello, this is the Credential Manager component!" | 11557d0d85eefa8254d49a8cce7d4e805f386a70 | 35,810 |
def permute_observation(obs, perm):
"""Given a permutation, shuffle pixels of the observation."""
return obs.flatten()[perm].reshape(obs.shape) | ac18bce7d344b89cbcba8ea22ebcb92ff3f9c0e9 | 35,812 |
def _check_type_and_items(_converted_item, _control_item, _new_type):
"""This function facilitates testing the :py:func:`khoros.utils.core_utils.convert_set` function."""
_correct_type = True if isinstance(_converted_item, _new_type) else False
_items_present = True
for _item in _control_item:
i... | 8d1b94644f1e8f910c8152d1aed4dc3f35a1db7b | 35,814 |
from typing import Optional
import os
def get_token() -> Optional[str]:
"""
get the token from environment variable
"""
return os.environ.get('WECHATY_PUPPET_SERVICE_TOKEN', None) or \
os.environ.get('TOKEN', None) or \
os.environ.get('token', None) or None | 57ff2a336aace23d399522439e1aaf9f76e82ed0 | 35,815 |
def size_to_bytes(size):
""" Return the size as a bytes object.
@param int size: a 32-bit integer that we want to convert to bytes
@rtype: bytes
>>> list(size_to_bytes(300))
[44, 1, 0, 0]
"""
# little-endian representation of 32-bit (4-byte)
# int size
return size.to_bytes(4, "litt... | 722ab782250570779519f8d8fdca4d5b449324d5 | 35,817 |
def mergetwolist(l1,l2):
"""
This function merges items in two sorted arrays
"""
n = len(l1)
m = len(l2)
if not (l1 and l2):
return
elif not l1 or n==0:
return l2
elif not l2 or m==0:
return l1
l3 = []
j=i=0
while i<n and j<m:
if l1[... | 48d4adc39b24dece6739e0f51eaef790785dbc2f | 35,820 |
def remove_clear_passwd(data):
"""
Removes clear passwords from the data received
:param data: data with clear password
:return: data without the password information
"""
passw = ['password: ', 'passwd: ']
for pattern in passw:
init = data.find(pattern)
while init != -1:
... | d607a025a60e8fa3abadde9724c729f85b03c9c7 | 35,821 |
from typing import Any
def issubclass_safe(candidate: Any, ancestor: Any) -> bool:
"""Returns True the candidate is a subclass of the ancestor, else False. Will return false instead of raising TypeError if the candidate is not a class."""
try:
return issubclass(candidate, ancestor)
except TypeErro... | 54fec7e6861de36015d8264978b76073704080d6 | 35,822 |
import requests
def served(url):
"""Return True if url returns 200."""
r = requests.get(url, allow_redirects=False)
return r.status_code == 200 | 1c4f1025bc36dc6e1b1f7fe1d519e5d557ade813 | 35,823 |
def _compute_adjusted_padding(input_size, output_size, kernel_size, stride, padding, dilation=1):
"""Computes adjusted padding for desired ConvTranspose `output_size`."""
kernel_size = (kernel_size -1) * dilation + 1
if padding == 'SAME':
expected_input_size = (output_size + stride - 1) // stride
... | 009bdc034d019d130dfc6f050c1f814ff2dbac34 | 35,824 |
def czyMur(mapObj, x, y):
"""Zwraca True jesli (x,y) pozycja na mapie jest murem,
w.p.p. zwraca False"""
if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
return False # (x,y) nie sa na mapie
elif mapObj[x][y] in ('#'):
return True # mur na drodze
return False | 617ebf983c41fdcb5399f57b89d126469e93875e | 35,825 |
import numpy
def melody_blocker(snippet):
"""
Makes a mask where anything above the top line of the snippet is 1. Also
enforces empty space a major 2nd above and below the melody. (This means
the optimizer will consider any note above the top line of the melody, or
too close to the melody, wrong... | fed4e3e78f4dc70898f16be93522b8ba9d15635a | 35,826 |
import json
def generate_code(data):
"""
generate a small arduino program code with the switch on and off extracted
from the waveform
"""
if not "on" in data:
return "Please add data"
# extract the data from the swtich on - off store container
switchON = data["on"]
switchOFF... | 081e21629956b34685529506a2d778dd4cee086f | 35,827 |
def get_default_token():
"""
Returns the value of the default auth token
"""
path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
with open(path, "rb") as tokenfile:
token = tokenfile.read()
return token.strip() | 0279b994bec8017c61baa56997d19bf7446e7152 | 35,828 |
def massage_ip(ip: str) -> str:
"""
Prepend 10.10.10 to a string. Allow the user to pass just the last segment of an ipv4 address.
"""
dots = len([c for c in ip if c == "."])
if dots == 0:
return f"10.10.10.{ip}"... | 43335768b3dd931b4bc5aa603a527696c5128001 | 35,829 |
import requests
def does_exist(url: str) -> bool:
"""Determines if a particular file exists on the server."""
resp = requests.head(url)
if resp.status_code == requests.codes.ok:
return True
return False | b506d654e5a89a1a35911e8c8089bcc442169e6b | 35,830 |
from typing import OrderedDict
def build_fhir_id(key1, value1, key2, value2, key3, value3):
"""
Construct an OrderedDict for ID
:param key1:
:param value1:
:param key2:
:param value2:
:param key3:
:param value3:
:return:
"""
id_info = OrderedDict()
id_info[key1] = valu... | f2db277f21683b3ce910b5398b90e607f9cf6a40 | 35,831 |
import argparse
import os
def CheckExtension(choices):
"""Argparse action to check a file extension at loading.
Arguments:
choices (Dictionary): List of allowed extensions {'ext1, ext2, ...'}.
"""
class Act(argparse.Action):
def __call__(self, parser, namespace, fname, option_strin... | 8b6a34c5f80abc1ae920a7bb37bdd8607489d8db | 35,832 |
def trapezint(f, a, b, n):
"""
Uses trapezoid rule to find the integral of a function
"""
sum = 0.0
h = (b - a) / float(n)
for counter in range(int(n)):
sum += (1 / 2.0) * h * (f(a + counter * h) + f (a + (counter + 1) * (h)))
return sum | 3e03f1c53b2d8fbcf150a5d672b384308ef033b8 | 35,833 |
from typing import Dict
import yaml
import os
def load_config(config_filepath: str) -> Dict:
"""
Loads a YAML config file and expands placeholders.
"""
with open(config_filepath, 'r') as stream:
config = yaml.safe_load(stream)
placeholders = {
"${subdir_fname_without_ext}": os.pa... | 89a27a1af35b8a9b0d0283021da43dc43d69668c | 35,835 |
def sum_freq(wl1, wl2):
"""
Input wavelength in nm
"""
return wl1 * wl2 / (wl1 + wl2) | e15ba5feba62c97ef167e753181fffd52ca8f269 | 35,836 |
def is_basic_type(signature):
"""Returns True if the signature is a basic type
'a', '(', '{', and 'v' are not considered basic types because they usually
cannot be handled the same as other types."""
basic_types = ('b','d', 'g', 'i','n','o','q','s','t','u','x','y')
return signature in basic_types | 5a454a699e6e7c0f89806f3cdba12ce78e42477e | 35,838 |
def unique(value):
"""Check that there is only one value in the list, and return it.
>>> kb = KB({'John':{'eye_color': ['blue']}})
>>> unique(kb.get_attribute('John', 'eye_color'))
'blue'
This is handy in the context of KB, where everything's a list but
it's common to expect that there's only one value.
... | c81dc2bfda37b89956aa41ce9646c7ef5a56e86d | 35,839 |
import os
def get_python_path():
""" return folder path """
if os.environ["PYTHONPATH"].endswith(";"):
return os.environ["PYTHONPATH"][:-1]
return os.environ["PYTHONPATH"] | 2ba61aadc96e9be7a728d377e23baf7d65f5973b | 35,840 |
import re
def correct_namespace(name, api_name, env_name) -> bool:
"""
Checks that a name of a thing we want to create in Apigee matches our namespacing conventions.
e.g. for api_name="canary-api" and env_name="internal-dev"
|--------------------------------------------------------------+--------|
... | 8e812a5e2729779837b85eed29ff9bb7a4a05953 | 35,841 |
def str_builtin():
"""str: Immutable strings."""
return str(b"you are my prot\xe9g\xe9", 'latin-1') | e6ffc3850ffc059ecdcf9aedf4e757b60c4e998f | 35,843 |
def get_all_tables() -> str:
"""Generates a list of all the tables in the database.
Returns:
list: [(table_name_1,), (table_name_2,), ...]
"""
return "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;" | 01713329ced8b4dd4e908440d2db8f0ee5963d5d | 35,845 |
def confusion_matrix (dataset,subgroup,targetColumn):
"""Returns the confusion matrix of a dataset with a subgroup."""
total_rows = len(dataset)
#Calculate the complement of the dataset over the subgroup
complement = dataset[~dataset.index.isin(subgroup.index)]
#Elements of confusion matrix
s... | bffd2c8f2aebc7d5e3f41373cfa8291797f122df | 35,846 |
from typing import Iterable
from typing import Tuple
def unparse_accept_header(values: Iterable[Tuple[str, float]]) -> str:
"""Like werkzeug.datastructures.MIMEAccept(values).to_header()."""
parts = []
for value, quality in sorted(values, key=lambda t: t[1], reverse=True):
if quality != 1:
... | 014cdab8c4e623bd505c3319ba3023f8a547543d | 35,847 |
from typing import Any
from typing import Callable
def _map(obj: Any, fn: Callable) -> Any:
"""Recursively maps a function to a nested object.
If the passed object is a list, dictionary, set, or tuple, then all child
elements are recursively mapped.
Args:
obj: The object to map against
... | cecbfec90f2a870624b9f5ff51d5f4b9ed3865c7 | 35,849 |
import yaml
def cmd_checks():
"""
Test fixture setup to load in the relevant test data
"""
with open("tests/data/cmd_checks.yaml", "r") as handle:
checks = yaml.safe_load(handle)
return checks["cmd_checks"] | 0bf627e255ee9aedfdec840c2106f85a19cc222d | 35,850 |
import ipaddress
def is_private_cidr(cidr: str) -> bool:
"""Check if cidr is not too broad and cover public networks."""
return ipaddress.ip_network(cidr).is_private | 22510000fe6584a863a44ee7d4f654bdb2260b46 | 35,851 |
import re
def validate_ip_address_regex(ip: str) -> str:
"""
validates an IP address using REGEX. This will validate where there are leading zeros as is outlined in the problem
description
Time complexity: O(1) because the patterns to match have constant length.
Space complexity: O(1).
"""
... | 19a53f2d3305dc0cd2f07dd4590cbd7b68c0a0f9 | 35,853 |
def str2int(val, base=None):
"""String to integer conversion"""
try:
if isinstance(val, int) or val is None:
return val
elif base:
return int(val, base)
elif '0x' in val:
return int(val, 16)
elif '0b' in val:
return int(val, 2)
... | b4c9a4329670bf28f01b292f1686800f6186d487 | 35,854 |
def fn_number_cols(df):
"""
RECURSO SECUNDÁRIO PARA DETERNINAR O DTYPE POR ANÁLISE DO CONTEÚDO DA COLUNA
"""
lst_cols = []
for n in list(df.columns):
i = df.columns.get_loc(n) # ÍNDICE DA COLUNA
v = df.iloc[:, i] # VALOR NA LINHA ZERO
try:
if float(n): # SE P... | 59ddf56c44322c3c4a550b49768bba90139afc56 | 35,856 |
import token
def is_append_to_all(line):
"""
Check if a line is an __all__.append line()
@see: L{process_append_to_all}
"""
# __all__.append(string)
if (len(line) == 4 and line[0] == (token.NAME, '__all__') and
line[1] == (token.OP, '.') and line[2] == (token.NAME, 'append') and
... | c4225aaed15b5a3c41ef8ff66ba72cbba5646a84 | 35,858 |
def get_commun_films(df_movies,Actor1,Actor2):
"""
Function that gives the movies in which two actors have played
Parameters
----------
df_movies : dataframe
IMDb movie database
Actor1 : string
name of the first actor entered by the user via the Tkinter interface
Actor2 : st... | d716138ff19b3a58c668a1f9b050e16bde927ffe | 35,859 |
def echo_worker(data):
"""
Example of worker that simply echoes back the received data.
:param data: Request data dict.
:returns: True, data
"""
return data | d694b301aefdcb1631567b3e1c269b24aa827824 | 35,860 |
import math
def evaluate(second, minimum=30, incr=15):
"""put the evaluation in a function - this makes it amenable
to testing as an isolated operation.
The approach here avoids transforming numbers to strings.
It also avoids map() and filter() operations, instead
applying Boolean logic - a li... | 2b252e3fdc05888514e138fb5c445d5892dedf19 | 35,861 |
def get_annots_by_chr(gene_coordinates, gene_expressions, gene_types, gene_metadata):
"""Merge coordinates and expressions, return Ideogram annotations
"""
annots_by_chr_by_group = {}
# Some gene types (e.g. pseudogenes) exist in the genome annotation,
# but are never expressed. Don't count these.... | 077a1ec7744b8b92f0066240b7343ecc6a135435 | 35,862 |
from typing import Sequence
from typing import Tuple
def get_default_powerup_distribution() -> Sequence[Tuple[str, int]]:
"""Standard set of powerups."""
return (('triple_bombs', 3), ('ice_bombs', 3), ('punch', 3),
('impact_bombs', 3), ('land_mines', 2), ('sticky_bombs', 3),
('shield',... | 1e125dfe64627b25e56e9f905d4fc8cc1a878684 | 35,863 |
import os
def check_path(pth=None):
"""
use the local directory if not path is give
Args:
pth (str): path to directory
Returns:
str: path to directory
"""
if pth == '':
return pth
elif pth is None:
return ''
elif os.path.isdir(pth):
return pth
... | ad79927a8f24bb51185e6294e174d2428b35e442 | 35,864 |
def make_wellcome_message(login) -> str:
"""This function format message during login procedure."""
return 'hello {}'.format('my love' if login == 'johnny' else login) | 37ad6b7d997876791dc65769753002b368e354b4 | 35,865 |
import math
def calcStep(step):
""" calculate step """
if step == 0:
return 1
fact = math.floor(math.log10(step))
fraction = float(step) / math.pow(10, fact)
if fraction < 1.5:
fraction = 1
elif fraction < 3:
fraction = 2
elif fraction < 7:
fraction = 5
... | 04520d5a0596a0ffd38799d1d1c079561e757c78 | 35,866 |
def get_etr_dash_t(etr_t, C_tol, C_eff, C_bal, C_leak):
"""熱交換型換気設備の補正熱交換効率 (-) (1)
Args:
etr_t(float): 熱交換型換気設備の温度交換効率 (-)
C_tol(float): カタログ表示誤差による温度交換効率の補正係数 (-)
C_eff(float): 有効換気量率による温度交換効率の補正係数 (-)
C_bal(float): 給気と排気の比率による温度交換効率の補正係数 (-)
C_leak(float): 排気過多時における住宅外皮経由の漏気による... | a07177e6da85a93bee25d67cd29a19df48beae4c | 35,867 |
def interpolate(x0, y0, x1, y1, x):
"""Linear interpolation between two values
Parameters
----------
x0: int
Lower x-value
y0: int
Lower y-value
x1: int
Upper x-value
y1: int
Upper y-value
x: int
Requested x-value
Returns
-------
int... | 082cc92c4c170dbba479e396731326e450b5d765 | 35,868 |
def menu(prompt, items):
"""Constructs and shows a simple commandline menu.
Returns an index of the provided items sequence."""
for i in range(len(items)):
print(str(i + 1) + ": " + items[i])
result = None
while True:
result = input(prompt)
try:
result = int(result)
except ValueError:
print("error: I... | 7d7c2218112a617387b34dd89286801dce7d11f8 | 35,870 |
from typing import Dict
from typing import Union
from typing import Any
from typing import List
def key_to_index(values: Dict[Union[str, int], Any], ordered_keys: List[Union[str, int]]) -> Dict[int, Any]:
"""
Replace keys of a `dict` with its index in ordered list.
:param values: A dictionary.
:param... | 86e0f5f34cb1d8d77e15e5a4ec11eda6b8c303ca | 35,872 |
import requests
def requests_adapter(url: str) -> dict:
"""An adapter that encapsulates requests.get"""
resp = requests.get(url)
return resp.json() | f57c03cf6573ba6043390a8a099125ecf3ba3315 | 35,874 |
def decipher(signature, cipher):
"""Decipher the signature."""
signature = list(signature)
cipher = cipher.split(' ')
for operation in cipher:
n = int(operation[1:])
if operation[0] is 's':
signature = signature[n:]
elif operation[0] is 'r':
signature = s... | 4ffb87edab7921912f0db29727d9e888ff2eed52 | 35,876 |
import logging
def validate_params(params):
"""
Args:
params (d):
genome_ref (str)
output_name (str)
"""
for x in ["genome_ref", "output_name"]:
if x not in params:
raise Exception(f"Expecting parameter {x} as an input, but not found. " + ", ".join(p... | 67ff5d52b06ec00aee47d04f7c2d66748ff6f5b2 | 35,877 |
import math
def math_round(number: float, decimals: int = 0) -> float:
"""Округлить математическиим (не банковским) способом.
Работает обычным математическим образом, в отличие от встроенной функции round(),
которая использует банковское округление.
:param number: число, которое требуется округлить
... | a223494af85a016ed8b1c0e3ffe6aa9593bd8da2 | 35,878 |
def indent_string(string, indent=' ', include_first=True, include_last=False):
"""
Indent a string by adding indent after each newline.
:param string: The string to indent
:param indent: The string to use as indentation
:param include_first: Also indent the first line of the string (before the firs... | 95bc16848fe6e095677f4a95a517b43fb10fd315 | 35,879 |
import sys
def package_path():
""" Returns the absolute path to this package base directory
"""
package_name = 'division_detection'
mjhmc_path = [path for path in sys.path if package_name in path][0]
if mjhmc_path is None:
raise Exception('You must include {} in your PYTHON_PATH'.format(p... | ec46a30051ec760c4c33d7a146c42004212a23ef | 35,880 |
def generate_TF(corpus, corpus_dict):
"""
Function to generate TF for queries.
:param corpus: Corpus of words in the queries.
:param corpus_dict: Mapping of query number and its corpus.
:return tf_dict: Term Frequency Mapping.
"""
tf_dict = dict()
for document_number, words_in_it in cor... | 4967f6968c4974fa3c8b400c9fec1a6b39f5ae43 | 35,881 |
import re
def process_en(text):
"""英文字符串预处理"""
text = re.sub('[!!]+', " ", text)
text = re.sub('[??]+', " ", text)
text = re.sub("[\"#\\$%&()◎—""-~()∩*+,-./:;:;;<=>@,。★、…【】《》“”‘’""·[\\]^_`{|}~#\\\]+", " ", text)
text = re.sub("[とに一緒にèéêóも]+", " ", text)
text = re.sub("[0-9]+", " ", text)
f... | 31de255f55298ebdf49e851b5f60046df94fb29c | 35,883 |
def build_feature_dict_mapper(feature_names):
"""Build a function for tf.data.Dataset.map.
Args:
feature_names: List of feature names.
Returns:
A function converting tuples into (dictionary of features, label).
"""
def mapper(*tuple_args):
d = {}
for i in range(len(feature_names)):
d[... | 9b3837cf3d1ff7bcc39242d660c255863a8dc98c | 35,884 |
def reshape_axis(ax, axis_size_pix):
"""reshape axis to the specified size in pixels
this will reshape an axis so that the given axis is the specified size in pixels, which we use
to make sure that an axis is the same size as (or an integer multiple of) the array we're
trying to display. this is to pre... | 5a029753014ebb4af4683be3a1d50ae4130ccc32 | 35,885 |
import numpy
def getClosestRotMat(M):
"""
Computation of the closest rotation matrix R of a given matrix M
(avoids computational errors.)
Attributes:
M: rotation matrix
Return:
R: rotation matrix
"""
u , s , v = numpy.linalg.svd(M)
R = nump... | 15ee28aa9a2df64b342853edba82654b0e3b430f | 35,886 |
def to_str(object):
"""RETURN : None if unable to convert to str"""
return str(object) | f8c68b2cf902135f7b7ae186a52fdabbd2e1faa3 | 35,888 |
def get_cpu_mem_network_usage(querier, query_window):
"""
Performs Prometheus queries relevant to cpu, memory, and network IO usage
:param querier: An object containing information
needed to query the Prometheus API
:param query_window: The window over which rates are computed by Prometheus
:r... | 7861a040d6d1ca8a70b78a6c0f0803c66d22b60c | 35,890 |
import os
from shutil import copyfile
def cfgdir(tmpdir_factory):
"""Prepare configuration directory for cloudselect."""
tmp = tmpdir_factory.mktemp("cloudselect")
src = os.path.join(os.path.dirname(__file__), "fixture", "cloud.json")
dst = os.path.join(str(tmp), "cloud.json")
copyfile(src, dst)
... | eda5c70b89b79509726293cbfd5d519676a69d7f | 35,891 |
import csv
import io
def read_model_analysis_csv(csvfile):
"""
Reads CSV generated from a spreadsheet of the same form as 'EXAMPLE template results spreadsheet v2 warming levels'.
Returns the model analyses as a list of Dicts.
"""
# List of keys corresponding to the column headings for v2 of the ... | 62a32a66ba56c487ee2ef12ac1518f4be92f04d5 | 35,894 |
import os
def __get_dataset_path() -> str:
"""Returns the path to the ratings.jl interim datset."""
src_features_path = os.path.join(os.path.dirname(__file__))
src_path = os.path.dirname(src_features_path)
coffee_analytics_path = os.path.dirname(src_path)
dataset_path = coffee_analytics_path + '/d... | f9121e6540221623f862b000440fbf953fe26eac | 35,895 |
from datetime import datetime
def now():
"""
UTC datetime string with format yyy-mm-ddThh:mm.sssZ
"""
dt = datetime.utcnow()
r = dt.isoformat()
if dt.microsecond:
r = r[:23] + r[26:]
r += 'Z'
return r | 8f6f7c2eb02066c74e3dbf7656efd43ee26ed0ff | 35,897 |
def configure_policy(dims, params):
"""configures the policy and returns it"""
policy = None # SomePolicy(dims, params)
return policy | d64f6990e06fed7ac1236a06650999c6a43a47de | 35,902 |
import typing
import asyncio
async def exec_as_aio(
blocking_fn: typing.Callable[..., typing.Any], *args: typing.Any
) -> typing.Any:
"""Asynchronously run blocking functions or methods.
Args:
blocking_fn (Callable[..., Any]): The blocking function/method.
Returns:
Any: The return va... | 0f8d0eb069ad8f33534931b4b9134486a641fa47 | 35,903 |
import os
def obvers_path(g_speak_home):
"""Assembles the path for the ob-version executable"""
return os.path.join(g_speak_home, 'bin', 'ob-version') | 368d16d0caee347122ad4726f5f5d0c4b6c95a99 | 35,904 |
import re
def did_parse(did):
"""
Parse a DID into it's parts.
:param did: Asset did, str.
:return: Python dictionary with the method and the id.
"""
if not isinstance(did, str):
raise TypeError(f'Expecting DID of string type, got {did} of {type(did)} type')
match = re.match('^di... | a0ed14d68aac933ead173b53ba26a80c1e6c83fd | 35,905 |
import argparse
def create_cli_parser() -> argparse.ArgumentParser:
"""Returns ArgumentParser for command line interface."""
parser = argparse.ArgumentParser()
parser.add_argument("config", nargs="?", help="path to yaml configuration file")
return parser | 24497c28600a67c51cbf49bd6a4a1f3dfc8f5dcc | 35,906 |
def base_uri(host, is_ssl=False):
""" return the host uri """
if is_ssl:
scheme = "https"
else:
scheme = "http"
return "%s://%s" % (scheme, host) | 6992f6b7a4cd1ef73b489b65180dcfa139717fbf | 35,908 |
def multicall2_addr():
"""Address of Multicall2"""
return "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696" | 294afe6f8a48a20fb95f4cb9b29292c178142c95 | 35,909 |
def max_standard_deviation(window):
"""Return the maximal spatial velocity standard deviation in a window over all the times."""
max_std = 0
for i in range(window.shape[1]):
current_std = window[:, i].std()
max_std = max(max_std, current_std)
return max_std | dd99de7170ce942b70b34f44cc50aff7da03091c | 35,910 |
def update_active_output_renditions_metric(ml_channel_id, ml_channel_name, ml_channelgroup_names):
"""Update the metrics of the "Active Output Renditions (avg)" dashboard dashboard widget"""
results = []
for groupname in ml_channelgroup_names:
entry = ["MediaLive", "ActiveOutputs", "OutputGroupName"... | 77f9438b17456db44fc6d1c8c2c6f85896cdcdf3 | 35,911 |
import re
def clean_postcode(postcode):
""" Cleans postcode
Args:
postcode - Postcode; 'v' attribute of addr:postcode
Returns:
Cleaned postcode
"""
verbose = True
pattern = re.compile(r'^\d{5,6}$') # valid codes are 5 or 6-digits
match_result = pattern.search(postcode)
... | 86a332c3ed07410f1e79843ff4e05b7dd403c411 | 35,914 |
import datetime
def get_job_status(job_run_details_list):
"""
Processes the given list of dictionaries of glue job run details.
-----------------------------------------------------------------
Required Parameter: job_run_details_list
Ex -
get_job_status(job_run_details_list)
____... | 08a854cffdb3ce457bf56036d0c12e33517db210 | 35,915 |
def qualities(quality_ids):
""" Get a numeric quality value out of a list of possible values """
def q(qid):
try:
return quality_ids.index(qid)
except ValueError:
return -1
return q | ec2df1665f187928ebbace1b62a046d149378990 | 35,917 |
import random
def prune_non_seed_interactions_at_given_percentage(graph, percentage, reserved_nodes):
"""
Randomly selects percentage% of edges and removes them (provided that they dont
have any connection with a node in reserved_nodes)
"""
new_graph = graph.copy()
nodes = new_graph.nodes()
... | 2adad0e5d3fd7d74b24daa21c6eea341e023996b | 35,922 |
import os
def _num_cpus_windows():
"""Return the number of active CPUs on a Windows system."""
return os.environ.get("NUMBER_OF_PROCESSORS") | eaf81cc77d1047ae42e330fb342491b599a4f524 | 35,924 |
def get_bounds(params):
"""Gets the bounds of the parameters
A list of ``(min, max)`` pairs will be returned. And the None value for the
unbound parameters will be kept.
:param params: An iterable for the model parameters.
:returns: The list of bounds for the parameters.
:rtype: list
"""
... | 5fffe3c863e57de8f141b7a742e1b6ac65c8fc94 | 35,925 |
def collapse(li: list, axis: str) -> list:
"""Collapse a fence to a single element."""
if axis == "hori":
old_tokens = ["+", "-"]
new_token = "|"
elif axis == "vert":
old_tokens = ["+", "|"]
new_token = "-"
else:
raise ValueError("axis must be 'hori' or 'vert'")
... | 877c5d3cf9085a3333cb8707db7ae06bd23d61ca | 35,927 |
def gen_verbinder_map(xmldoc):
"""produce dict with boolean values to check if a given link is a verbinder
:param xmldoc: input VISSIM xml
:type xmldoc: xml.dom.minidom.Document
:return: map of VISSIM link id -> bool flag if link is 'Verbinder'
:rtype: dict
"""
# simple implementat... | bf0c179273e63254e772bdb8cd1ba9a4c4915f3b | 35,929 |
import types
from contextlib import suppress
def EIA_filename_identifier():
"""Create a list of the EIA files identified in the imported modules.
This function takes a list of all of the imported modules and looks
within each for a class called EIAData. If such a class is found,
the strings for the f... | 4af5cdcd4baeacc13d4371de506c2eed1dd731e5 | 35,930 |
def _get_sample_count(*lsts):
"""Get sample count of a dataset.
:param *lsts: variable number of lists.
:return: sample count of this dataset, if all lists match, else None.
"""
if all(len(lst) == len(lsts[0]) for lst in lsts):
sample_count = len(lsts[0])
else:
sample_count = No... | d8190c6b6b8a74f54acb1ca80f23b19ffb4f8e26 | 35,931 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.