content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def position_check(inlat, inlon):
"""
Simple check to make sure that the latitude and longitude are within the bounds specified
by the ICOADS documentation. Latitude is between -90 and 90. Longitude is between -180 and 360
:param inlat: latitude
:param inlon: longitude
:type ... | 7f9e6d92667cd81ad02b034fcba231fd4763f966 | 10,669 |
def normalize_email(email):
"""
Email Address Normalization.
1. Remove leading and trailing spaces.
2. Convert all ASCII characters to lowercase.
3. In gmail.com email addresses, remove the following characters from the username part of the email address:
1) The period (. (ASCII code 46)).
... | e128952a38cd699dffa55de0e486ee6bb245697a | 10,670 |
def urljoin(url, suffix=""):
"""
Will join url and its suffix
Example:
"https://google.com/", "/" => "https://google.com/"
"https://google.com", "/" => "https://google.com/"
"https://google.com", "api" => "https://google.com/api"
"https://google.com", "/api" =... | cd8a81d7b427678330d1258fa5644f9d4cf631a0 | 10,671 |
import os
import json
def read_credentials():
"""Return a json data containing user's credentials
Read user's credentials from a json file
"""
script_dir = os.path.dirname(__file__)
rel_path = "credentials.json"
abs_file_path = os.path.join(script_dir, rel_path)
with open(abs_file_path) a... | 52c64e487f123a07f30b87509aec07655d766526 | 10,672 |
def construct_dataset(df, past_lags, future_intervals):
"""Construct demand dataset"""
# Total NEM demand for a given week
df_t = df.sum(axis=1).rename('total_demand')
# Add an interval ID
df_t = df_t.reset_index().rename_axis('interval').set_index(['year', 'week'], append=True)
# Get lags
... | ada01368eb23b01ea9c13f11042088818d6dab81 | 10,673 |
def keyphrase_label_from(candidate_span, element, generic_label=True):
"""Receive candidate_span and element from dataset and return keyphrase label"""
label = "NON-KEYPHRASE"
if "keyphrases" in element and\
"keyphrase-id" in candidate_span and \
candidate_span["keyphrase-id"] in ele... | d9f6e4a0697c441f6b597eaf0695cbdc1cc81d61 | 10,675 |
def score_string(lm, s, k, c):
"""k: UID exponent; c: string cost"""
return lm.score_string_UID(s, k) + c * len(s) | 35533d52ec7f1c65f9b49c38b51d52c9fe8c0ef0 | 10,676 |
def get_dot_file_path(gname):
"""
For a graph named gname, this method returns the path to its dot file in
the dot_atlas directory.
Parameters
----------
gname : str
Returns
-------
str
"""
return "dot_atlas/good_bad_trols_" + gname + ".dot" | 4ead9a2c3656718a8c088e879742962a9782ef02 | 10,677 |
def _invert_signs(signs):
""" Shall we invert signs?
Invert if first (most probable) term is negative.
"""
return signs[0] < 0 | 4135340cfbeb4fce67513a160b63304a3199cf1a | 10,678 |
def parse_directive(source_text, directive):
"""
<Purpose>
Given the file source, 'source-text', this function will search for the given directive.
<Arguments>
source_text: The source in which we are searching for a pragma directive.
directive: The pragma directive we are searching for.
<Excep... | 1fb538a75a530ff5c9d368dcc3601be0419fc150 | 10,680 |
def safe_xml_tag_name(
name: str, numeric_prefix: str = "tag-", empty_fallback: str = "empty-tag"
) -> str:
"""
Returns a safe xml tag name by replacing invalid characters with a dash.
:param name: The name that must be converted to a safe xml tag name.
:param numeric_prefix: An xml tag name can't ... | fea34367fbc7f2a4b9dbe23d11c70ecb75dad3da | 10,681 |
def list_multipart_upload(resource, bucket_name, prefix=""):
"""List in-progress multipart uploads"""
client = resource.meta.client
mpupload = client.list_multipart_uploads(Bucket=bucket_name, Prefix=prefix)
return {
"Uploads": mpupload.get("Uploads"),
"CommonPrefixes": mpupload.get("Co... | 669b852a8c38acc58f1a4dad833a03d011bb4e14 | 10,683 |
def tcl_prep_otaver(ota=None):
"""
Prepare variables for OTA versus full check.
:param ota: The starting version if OTA, None if not. Default is None.
:type ota: str
"""
if ota is not None:
mode = 2
fvver = ota
else:
mode = 4
fvver = "AAA000"
return mode,... | b42c9af8abd9b6c2b361d906737429acf967182b | 10,684 |
def pessoa(texto):
"""
:param texto:
:return:
"""
while True:
p = input(texto).strip().upper()
if p.isdigit() or p == '':
print('Erro, digite um nome válido por favor.')
else:
return p | e07755638c291a726b7681dbc013a43b21a3890b | 10,685 |
import numpy
def calculate_weighted_statistics(values, weights, statistics):
"""
Calculates weighted statistics
:param values: pixel values
:params weights: weight of each pixel, where 0 > weight >= 1 (areas of 0 weight should be masked out first). Weights
can be thought of as the proportion of... | 502869b5719aa0db59f16f61ab0eaa1c21a7128a | 10,686 |
def check_sup_x(supp, row_num, z, c):
""" delete unusable numbers from rows """
for x in range(3):
for y in range(3):
for k in row_num:
supp[x+z*3][y+c*3][k] = 0
return supp | f776dd426a11ac806a7c025dd6e88c244f988208 | 10,687 |
def get_name_from_key(key) -> str:
"""Given a dask collection's key, extract the collection name.
Parameters
----------
key: string or tuple
Dask collection's key, which must be either a single string or a tuple whose
first element is a string (commonly referred to as a collection's 'na... | 8a5b46a85000325932c043eb4a94864fef2d6dd4 | 10,688 |
def convert_init_dict(init_dict):
"""Convert an init_dict from an old version of pyleecan to the current one"""
# V 1.0.4 => 1.1.0: New definition for LamSlotMag + SlotMag
if init_dict["__class__"] == "MachineSIPMSM" and "magnet" not in init_dict["rotor"]:
print("Old machine version detected, Updat... | d73718c77b1909b150e254aa1ef4eed7fbf33c35 | 10,690 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data with the following schema:
{
"uid": {
"id": integer,
"name... | b97d35b93ea08d6adcd69e0fa84c9b59be8d4419 | 10,691 |
def get_tag_type(tagtype, pairs):
"""
Given a list of (word,tag) pairs, return a list of words which are tagged as nouns/verbs/etc
The tagtype could be 'NN', 'JJ', 'VB', etc
"""
return [w for (w, tag) in pairs if tag.startswith(tagtype)] | 383515704788e0fd6bcfd7d7f21e77be18397163 | 10,692 |
def read_data_from(file_: str) -> list:
"""Read boarding pass data from file."""
with open(file_, "r") as f:
return f.read().splitlines() | 7315c4c284cdd2e9e1b66776c26eccabe13acdb4 | 10,693 |
import ast
def get_auxiliary_name(node: ast.AST, aux_symbol_id: str) -> str:
"""
Generates a name for auxiliary variables.
:param node: the ast node that originates the auxiliary symbol
:param aux_symbol_id: the id name of the auxiliary symbol
:return: the unique name to the symbol.
"""
r... | d67fc8d70553265a7d5345e97877e07caf36e19a | 10,695 |
def search_for_pod_name(details: dict, operator_id: str):
"""Get operator pod name.
Args:
details (dict): workflow manifest from pipeline runtime
operator_id (str): operator id
Returns:
dict: id and status of pod
"""
try:
if 'nodes' in details['status']:
... | cc5bc532a1875145452fbe71cca54f840257c90d | 10,696 |
def readxmol(ifile,elem,xyz):
"""
read xmol file
"""
lines = ifile.readlines()
nat = int(lines[0])
title = lines[1]
for l in lines[2:]:
type, x, y, z = l.split()
xyz.append([float(x),float(y),float(z)])
elem.append(type)
# xyz.append(l)
return nat | 62be4300fcf30f3b2dee329418352230639ef7a1 | 10,701 |
def dicts_to_matched_tuples(dict1, dict2):
""" Converts pair of dicts to pair of matched tuples so that their elements can be compared.
Throws an exception if the set of keys in both dicts are not the same.
"""
try:
return [(dict1[k], dict2[k]) for k in set(dict1.keys() + dict2.keys())]
... | 496dba21da3766db49934761fd8ec142aed0f1ab | 10,702 |
def key(profile):
"""Get the last name in lower case"""
return profile["name"].split(' ')[-1].lower() | dd778619f601213f3cbae3504277fe6ee21ba3cd | 10,703 |
def solution(a: list, k: int) -> list:
"""
>>> solution([], 0)
[]
>>> solution([], 100)
[]
>>> solution([1] * 100, 100) == [1] * 100
True
>>> solution([1, 3], 1)
[3, 1]
>>> solution([1, 3], 2)
[1, 3]
:param a: An array of integers
:param k: Number of rotations
:r... | f1ff42df2ec1181357732ea7910b8994099dfa65 | 10,704 |
import logging
def _get_logger():
"""
Generate a logger with a stream handler.
"""
logger = logging.getLogger('epc')
hndlr = logging.StreamHandler()
hndlr.setLevel(logging.INFO)
hndlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logger.addHandler(hndlr)
return logger | 8c96d2395e1d907a389346e5e3b94f41c0b62fe3 | 10,705 |
import inspect
def is_mod_class(mod, cls):
"""Checks if a class in a module was declared in that module.
Args:
mod: the module
cls: the class
"""
return inspect.isclass(cls) and inspect.getmodule(cls) == mod | 7a9b228995d2bf46467ef75823a1aad26d16df0e | 10,706 |
from datetime import datetime
def getDateTime(timestamp):
"""
Converts to datetime from timestamp
:param timestamp: string (or integer) value
:return: datetime value
"""
return datetime.fromtimestamp(int(timestamp)/1e3) | 2197806bf7372305cd048295c8c63a0269625262 | 10,707 |
def is_heavy_usage_item_scription(item_description):
"""
CNN1-HeavyUsage:m4.2xlarge
:param item_description:
:return:
"""
return len(item_description.split(";")) == 2 | dd67d8fc192d663bf9e09c4b6325ad3afe09fd0b | 10,708 |
def swapWordCount(wordToFreq):
"""
wordToFreq: the dict linking word to count
return freqToWord: the dict linking count to word
"""
freqToWord = {}
for wdKey in wordToFreq:
if wordToFreq[wdKey] in freqToWord:
freqToWord[wordToFreq[wdKey]].append(wdKey)
else:
... | a1569f20a11303e0aa986a2ae5a1377f0bd1b14a | 10,709 |
def _prepare_quote(quote, author, max_len=78):
"""This function processes a quote and returns a string that is ready
to be used in the fancy prompt.
"""
quote = quote.split(' ')
max_len -= 6
lines = []
cur_line = []
def _len(line):
return sum(len(elt) for elt in line) + len(line) -... | 7669af2c1dd5de482740944937229f5e87c527b5 | 10,710 |
def bt2_out():
"""Static equilibrium results from braced tower 2d."""
output = {}
output["xyz"] = {0: [0.11891271935545733, 0.04623304043571308, 0.0],
1: [-0.14550216351451895, 1.0106420665842952, 0.0],
2: [0.0, 2.0, 0.0],
3: [1.5829003695589805... | 1f5e1ebaea1abb5bd6072f29dca68598a0366905 | 10,713 |
def _get_mass_dict(factor=1000000000, type=int):
"""
Return a Dictionary containing the masses of each aminoacid
We explicitly convert them by a factor of 1 000 000 000 (default) into integers
The values are taken from: https://proteomicsresource.washington.edu/protocols06/masses.php
"""
return... | fabdf445765acb1bde082ba63df9b22b06669ab9 | 10,714 |
import hmac
def is_authenticated(request, secret):
"""
Verify whether the user is authenticated
Args:
request (tornado.httputil.HTTPRequest): The request
secret (str): The secret to use for authentication
"""
# See https://api.slack.com/authentication/verifying-requests-from-slack... | 4d8915018f5d4e97934a581a79bb935533714817 | 10,716 |
def chi2_fun(theta, parameters_to_fit, event):
"""
Calculate chi2 for given values of parameters
Keywords :
theta: *np.ndarray*
Vector of parameter values, e.g.,
`np.array([5380., 0.5, 20.])`.
parameters_to_fit: *list* of *str*
List of names of parameter... | 14f74f3cf64770dc1cb7e335880f445eb75ca007 | 10,719 |
def link(content, target):
"""Corresponds to ``[content](target)`` in the markup.
:param content: HTML that will go inside the tags.
:param target: a full URL, or a local ``filename.html#subtitle`` URL
"""
return '<a href="%s">%s</a>' % (target, content) | c0355f78db31edccf7e904b3696a169980fa796b | 10,720 |
import typing
def calculate_default_layout_uvs(
texture_size: typing.Tuple[int, int],
box_size: typing.Tuple[int, int, int],
offset: typing.Tuple[int, int],
):
"""
Util method for calculating uv's
Cache result whenever possible!
WARNING: currently may not work correctly
:param texture... | 9a9c49711c8dd9ec19e8fd3830e951778aa28737 | 10,724 |
def get_version_details(path):
"""Parses version file
:param path: path to version file
:return: version details
"""
with open(path, "r") as reader:
lines = reader.readlines()
data = {
line.split(" = ")[0].replace("__", ""):
line.split(" = ")[1].strip().... | 6ea7019e4e39b5c315e085369c6ab2bd6729d6bb | 10,727 |
def size_to_bytes(size, largeur=6):
""" Convert a size in a bytes with k, m, g, t..."""
if size > 1073741824*1024:
return b"%*.2fT"%(largeur, size / (1073741824.*1024.))
elif size > 1073741824:
return b"%*.2fG"%(largeur, size / 1073741824.)
elif size > 1048576:
return b"%*.2fM"%(largeur, size / 1048576.)
e... | f05e74d89b710936a8253f13b9e6d804f9004b6b | 10,728 |
import csv
def csv_writer(output_file):
"""
@brief: Get CSV writer
@param output_file: Output file handler
@return: CSV writer
"""
return csv.writer(output_file, delimiter=';', quoting=csv.QUOTE_ALL) | 70a5d6dca84ef2b60c3fb742a38fd6b27724ecfb | 10,729 |
import configparser
def repo_default_config():
"""Defines the config file structure and returns the configparser object"""
# config files is of microsoft INI format
ret = configparser.ConfigParser()
ret.add_section("core")
ret.set("core", "repositoryformatversion", "0")
ret.set("core", "file... | 3b1071caaa0efd967cb075c492544435449e1be2 | 10,730 |
import re
def extractDirective(lineStr: str):
""" :param lineStr:
:return: (directive, directiveArgs) """
match = re.search(r'\.[a-zA-z][a-zA-z\d_]+', lineStr)
return match if not match else match.group() | 390331845733d4f6d5f2c4c8318cbac693730026 | 10,731 |
def make_connect_data(one_data):
"""
接收数据,使用特定的字符拼接,返回拼接好的数据
:param one_data:
:return:
"""
datas = ['' if elem == None else elem for elem in one_data ]
data = "&#@".join([str(elem) for elem in datas])
# print(data)
return data | 58a64cc50778d419a292e1c6ba5c55cd1030de47 | 10,733 |
import requests
def get_token(access_key, access_secret,
auth_url="https://deviceserver.creatordev.io/oauth/token"):
""" Gets device server access token. """
try:
# POST Body Payload for Auth
payload = {
'grant_type': 'password',
'username': access_key,
... | bc401bf6ff441aa17311d12137250150aadeb686 | 10,734 |
import os
def load_kraken_db_metadata(kraken2_db):
"""
Load NCBI taxonomic name mappings to be able to convert taxids into taxonomic strings
Args:
kraken2_db (str): path to kraken2 standard database location
Returns:
names_map (dict[str:str]): the taxonomic names for each taxid node
... | 675c434eb7893b45866b7002c12c142cd0118ac6 | 10,736 |
def excess_entropy_fast(text: str, H_single, H_pair):
"""
Calculates excess entropy of given string in O(n) time complexity
:param text: an input tokenized string
:param H_single: a function that calculates H(i, x_i)
:param H_pair: a function that calculates H(x_i | x_{i-1}) = H(i, x_{i-1}, x_i)
... | 1e590f7577fa9b9185160eea26d3900476f56bf0 | 10,737 |
from typing import Set
import ast
def _h5attr2set(attr: str) -> Set[str]:
"""Convert an HDF5 attribute to a list of strings"""
if not attr or attr == "set()":
return set()
return ast.literal_eval(attr) | 55aa07126efe42fa1f3437ce6206e72db58c7fd3 | 10,738 |
def velmodellayers_sdsu(ifile):
"""
Input a SDSU type velocity model file and return number of layers
as defined by SDSU. This is designed for use in the SDSU code
which required the number of layers in a file.
"""
lincount = 0
infile = open(ifile, "r")
for _ in infile:
lincount ... | 922f9443b3b30cbe58639ab51ab9f183205d0dec | 10,739 |
from typing import Any
def to_qualified_name(obj: Any) -> str:
"""
Given an object, returns its fully-qualified name, meaning a string that represents its
Python import path
Args:
- obj (Any): an importable Python object
Returns:
- str: the qualified name
"""
return obj._... | 45824d1f84a96f254274e7fe40f2ed9546ccb346 | 10,740 |
def factorial(n):
"""Factorial function implementation."""
return n * factorial(n-1) if n else 1 | 3ebaa4cd6c38773e8c8a6e1c247e0163f0d7d50a | 10,741 |
def get_index(search, names):
""" Find index matching search in names list of 'Key|Value' """
for name_index, name in enumerate(names):
if search == name.split('|')[0]:
return name_index
return None | fbfc6b71b75172e2980a604f53e602c9b3cb9a84 | 10,742 |
def separate_callback_data(data):
"""Separa i dati in entrata"""
return [i for i in data.split(";")] | 0cfef1abf910193a7ad8015862614f3659dd40d5 | 10,743 |
def _upgrading(version, current_version):
"""
>>> _upgrading('0.9.2', '1.9.2')
False
>>> _upgrading('0.11.3', '0.11.2')
True
>>> _upgrading('0.10.2', '0.9.2')
True
>>> _upgrading('1.1.3', '1.1.4')
False
>>> _upgrading('1.1.1', '1.1.1')
False
>>> _upgrading('0.9.1000', '50... | 1ff478ed3c55687ddaa0392f6a071915750f8dfa | 10,745 |
import argparse
def parse_args():
"""
parsing arguments
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# required argumnets:... | ded823885e43c3899d2ef5a61c54b0bbeb53c251 | 10,746 |
def add_x_to_plotting_options(plotting_options: dict, option_cat: str, x: str, defaultvalue):
"""
don't override given plotting_options, meaning it only add the default value
if value not already defined in plotting_options
"""
if plotting_options is None:
plotting_options = {}
if option... | 48ff564e58b35b8dc38d529fb27188556401c81c | 10,747 |
def divide(a, b):
"""
Calculates the division of a by b.
If the denominator equals 0, then the result is plus infinity.
--------------------
args:
a (float): the numerator
b (float): the denominator
--------------------
return:
(float): the division of a by b
--... | 2e7f42ed3c92c6ea95798295030262b746e48653 | 10,748 |
def get_colors_for_class_ids(class_ids):
"""Set color for class."""
colors = []
for class_id in class_ids:
if class_id == 1:
colors.append((.941, .204, .204))
return colors | a856d804b893bd9ba440833f178ef8b6c9743c1f | 10,749 |
import pickle
import os
def try_read_cache(dbd_file, dbd_cache_path):
"""
Try to read a cached dbd file from the given path,
return the dbd contents or None if failed or out of date.
"""
try:
with open(dbd_cache_path, "rb") as f:
size,mtime = pickle.load(f)
stat = o... | 207e7568ee2c5eefc90e9d1f7100a636c0c33e42 | 10,752 |
def _map_args(repo, args):
"""
Maps a set of arguments to a predefined set of values. Currently only
__REPO__ is support and will be replaced with the repository name.
:param repo: The repo name used for mapping.
:type repo: str
:param args: An array of arguments to map.
:type args: list
... | 0e31510a764c3f6dca4726daa4e8716bdc7328db | 10,753 |
def R_curv(deltaT_sub, r_min, radius, Q_drop):
""" thermal resistance due drop curvature
Parameters
----------
deltaT_sub: float
temperature difference to the cooled wall in K
r_min: float
minimum droplet radius in m
radius: float
... | 176520b43184e879bb25bcecc50e64e6dabaa6cc | 10,754 |
def problem057():
"""
It is possible to show that the square root of two can be expressed as an
infinite continued fraction.
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/... | 48e0d14be2893dd23e4b13238b56d9939541b526 | 10,755 |
import subprocess
def srun(cmd, check=False):
""" run a commmand in a shell """
return subprocess.run(cmd, shell=True, check=check) | b84827f50b5dec3f17e0d0396b9bdd684e16556f | 10,756 |
def _decode_list(vals):
""" List decoder
"""
return [val.decode() if hasattr(val, 'decode') else val for val in vals] | 852629abaa25e5bc4f2388b273a0676d3afb8337 | 10,757 |
def is_empty(elem):
"""This function is just a helper function for
check whether the passed elements (i.e. list)
is empty or not
Args:
elem (:obj:): Any structured data object (i.e. list).
Returns:
bool: True if element is empty or false if not.
"""
if not elem:
ret... | e449e1f765744bbc21880881550c9e87c8e83bcd | 10,758 |
from pathlib import Path
def get_toplevel_dirpath(path):
"""
Provide the top level directory for the given path.
The top level directory contains the ``controls.json`` file.
This function returns ``None`` if a top level path can not be found.
:param path: absolute or relative path to a file or d... | 324df1ceda2bf5813d65f86f6319dde8819f8fa3 | 10,759 |
def list_pad(l, pad_tok, max_length):
"""
Args:
sequences: a generator of list or tuple
pad_tok: the char to pad with
max_seq_len: max len for padding
Returns:
a list of list where each sublist has same length
"""
result = [l[x] if x < len(l) else pad_tok for x in ran... | b4d3c4875d7a1a411c0e6527ed9f7550e1a01cdb | 10,760 |
def str_(s):
"""
In python 3 turns bytes to string. In python 2 just passes string.
:param s:
:return:
"""
try:
return s.decode()
except:
return s | ee9c65334a201ad37db058c0e3c51a41f0650298 | 10,762 |
import pathlib
def _detect_home_location() -> pathlib.Path:
"""Detects the location of the root directory"""
# path/to/home/backend/core/config_loader.py
path_to_self = pathlib.Path(__file__).absolute()
# path/to/home/backend/core/
path_to_core_module = path_to_self.parent
# path/to/home/ba... | c309656d5a56261fd96c86c179947981dc65dc58 | 10,763 |
def _to_int(hex_digit):
"""turn an hexadecimal digit into a proper integer"""
return int(hex_digit, 16) | 2d9f0a3f5e754fc0fc932349a9a0bcb5f0066cce | 10,765 |
from collections import defaultdict
def empty_dict(old_dict):
""" Return a dictionary of empty lists with exactly the same keys as old_dict
**Parameters**
:old_dict:
Dictionary of lists (identified by the key).
:Author: Sirko Straube
:Created: 2010/11/09
"""
... | fd63ee3e4600bdf8467ece9ea99f5f8e20399802 | 10,766 |
def delete_volume(module, volume):
""" Delete Volume. Volume could be a snapshot."""
if not module.check_mode:
volume.delete()
changed = True
return True | f463b4cd1325c1a67ff26009978e653e1354ebc8 | 10,770 |
def u4u1(u4):
"""
pixel pitch -> mm
u4 = (pitch, pixel)
"""
u1 = round( u4[0] * u4[1], 2)
return u1 | d740975308f8c0723bd4a474cae883e8d6a0290a | 10,771 |
def normalize_numpy(img_256_arr):
"""
Normalizes an image NumPy array so its values lie in the range [0, 1]
Args:
img_256_arr: a NumPy array (intended to be 2D or 3D) whose values lie
in the range [0, 255], representing an image
Returns:
A NumPy array, with the same dimensions... | 50fa2854c53a975487d501e6a6703b63e82def86 | 10,772 |
def keep_only_this_derivation(name_of_set_to_make,connections_list_of_dics):
"""
"""
new_connection_list_of_dics=[]
# print(name_of_set_to_make)
for connection_dic in connections_list_of_dics:
# print(connection_dic["derivation name"])
if (connection_dic["derivation name"]==name_of_set_to_make):
... | 4ec8a010055d6f3740c489184f8b123bcd8780ee | 10,773 |
def make_task(func):
"""make decorated function a task-creator"""
func.create_doit_tasks = func
return func | 4a7d23765aa47f4c87723efc080913ff0c126205 | 10,774 |
import os
import requests
def clapack_header(clapack_h = "clapack.h"):
"""Return the clapack header as string (is downloaded if not found)"""
clapack_url = "http://www.netlib.org/clapack/clapack.h"
if not os.path.exists(clapack_h):
r = requests.get(clapack_url)
assert r.status_code == 200
... | 0a86f5b805430b1434ba28cec423c5d54aa89094 | 10,775 |
def ifelse(condition, then_expression, else_expression):
"""Controls if else logic flow inside a computational graph """
if condition:
output = then_expression
else:
output = else_expression
return output | 69190f0f9c51cd97db97d64203f51ae66370e3ff | 10,776 |
def entradas():
"""faz as perguntas sobre o contato e retorna os dados"""
contato = {}
nome = input("qual o nome do contato: ")
contato['nome'] = nome
contato["numero"] = input("qual o telefone/celular: ")
contato["endereco"] = input("qual o endereço: ")
contato["email"] = input("qual o emai... | dbcb82d91facf4c324db6cff07d2080ca3330c6a | 10,777 |
from pathlib import Path
def read_image_scipy2(input_filename: Path) -> np.array: # type: ignore
"""
Read an image file with scipy and return a numpy array.
:param input_filename: Source image file path.
:return: numpy array of shape (H, W), (H, W, 3).
"""
numpy_array = imageio.imread(input_... | 54d3aa7d8a3043e5a79e2668be1e971b543669d9 | 10,780 |
import os
def parse_lang(filename):
"""
only support python and golang
"""
_, ext = os.path.splitext(filename)
if ext == ".py":
return "python"
elif ext == ".go":
return "go" | a923e048abbe5fff031ae066748e3d2fd094ddb4 | 10,781 |
from typing import List
from typing import Tuple
def sentence_from_tokens(
tokens: List[str], pos_list: List[str]
) -> Tuple[str, List[Tuple[int, int]]]:
"""
Apply some heuristics to create a sensible text text from the tokens.
Unfortunately the original whitespace information is not available.
"... | df212e0324efb4135f7674ea7d598d73fea7d2cb | 10,782 |
import os
import glob
def FindTestFiles():
"""Return a list of all test files in the project."""
file_list = []
pattern = '*_test.py'
module_dir = os.path.join('.', 'plaso')
for directory, _, _ in os.walk(module_dir):
directory_pattern = os.path.join(directory, pattern)
for pattern_match in glob.i... | f13ebfffa6c51cbaa90060356af82aeaba146e34 | 10,783 |
def check_hdr(hdr):
"""
:param hdr:
Header from a NIRPS image to be cheked against a number of QCs
We'll need to add more checks with time.
:return:
"""
keys_to_check = ['OBJECT']
output = ''
for key in keys_to_check:
if key not in hdr:
output+='missing:'+... | 9626f472d5194217a7d6f794e6192aea7112154b | 10,784 |
def process_results(results):
"""
Gets user choice that needs to be played
:param results: stores the results which we got from get_items
:return: user choice
"""
if len(results) >= 1:
temp_data = {}
count = 1
print("Here are the top {} results for your query, which one w... | 23d3087ddf39ab6fa94072fabaa2bcde68add2a9 | 10,786 |
def format_secret(secret):
"""
Format secret to compatible decrypt string
Args:
secret (string): KMS secret hash
Returns:
formatted ef resolvable KMS decrypt string
Raises:
None
"""
return "{{aws:kms:decrypt,%s}}" % secret | 274a0686db07621d657ebc29eda21ec18c1d0afa | 10,787 |
import torch
def le(a, b, square=False, **kwargs):
"""
Encodes the loss function for "a <= b". If square is false d = |a - b| is
used, else d = (a - b)^2.
"""
if square:
return torch.clamp((a - b).sign() * (a - b) * (a - b), min=0)
else:
return torch.clamp(a - b, min=0) | 02c8a2f5255255f754be6335a7ed8c55a1910192 | 10,788 |
from typing import Dict
from typing import Any
import os
import logging
def get_key_value(d: Dict, key, default=None) -> Any:
"""Return value for the key either from the dict or environmental variable or default.
Raises error if value is not found and there is no default."""
if key not in d:
if k... | 57b9a859c8934b16dca5529ec53248f1b44fcec5 | 10,790 |
import sys
def batch_end(segments, bstart, batch_max):
""" Determine the batch end that will keep the
batch length under the given max. """
bi = bstart
blength = 0
while bi < len(segments) and blength < batch_max:
chrom, seg_start, seg_end = segments[bi]
blength += seg_end - seg_start
... | 437729d43c3d569861feb25e0366f84d99f1a943 | 10,791 |
import random
def get_fixed_samples(a_list, num=20000):
"""
固定数量的样本
"""
if num <= 0:
return a_list
a_n = len(a_list)
n_piece = num // a_n + 1
x_list = a_list * n_piece
random.seed(47)
random.shuffle(x_list)
x_list = x_list[:num]
return x_list | fe7c22329001ea0cde155a6077c28aeaffeb0a65 | 10,792 |
import random
from functools import reduce
def diceroll (dice, sides):
"""
Simulate rolling d dice of s sides each
From Python Cookbook1st Edn pg 531
See the Python Cookbook entry on this
function for the non-standard use of 'reduce'
for example diceroll(5, 6) would be 5 rolls
of a 6 sided... | ad51a53a9df1df2c64e7ad7f361365ff8df219c6 | 10,794 |
import functools
import types
def memoize_method(func):
"""
A decorator to remember the result of the method call
"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
name = '_memoize_{}'.format(func.__name__)
try:
return getattr(self, name)
except Att... | f3a43d03e9b34c7a623452868ff2d33fed299dd9 | 10,795 |
from pathlib import Path
import io
from unittest.mock import patch
async def test_upload_view(hass, hass_client, temp_dir, hass_admin_user):
"""Allow uploading media."""
img = (Path(__file__).parent.parent / "image/logo.png").read_bytes()
def get_file(name):
pic = io.BytesIO(img)
pic.nam... | 6bdc05a17a44c4ae016ae8c8fc40bfceb2072c7f | 10,799 |
import argparse
import getpass
def get_args():
""" Get arguments from CLI """
parser = argparse.ArgumentParser(
description='Arguments for VM relocation')
parser.add_argument('-s', '--host',
required=True,
action='store',
hel... | 82e536c056eaa558a1df1ea61d4f36a8a29384de | 10,800 |
def process_stn_activation(df, side):
"""
Calculates STN activation percentage
:param df: dictionary containing STN volume and active STN volume for patients
:param side: side of the brain 'L' or 'R'
:return: STN activation percentage for each side for all patients
"""
#print(list(df))
... | 6ed2a21e547a0ed9f35a77fed02e6f4fbf59cb6a | 10,801 |
def combine_dictionaries(dict1,dict2):
"""append lists that share the same key, and add new keys
WARNING: this only works if the dictionaries have values that are lists"""
outdict = dict1
for key in dict2:
if key in outdict:
assert(isinstance(dict2[key],list))... | bc291bd8b31870ee8d04f4cb13c94c88bb97fea9 | 10,802 |
def greatest_common_divisor(larger_num, smaller_num):
"""This function uses Euclid's algorithm to calculate the Greatest Common Divisor
of two non-negative integers
pre: larger_num & smaller_num are both non-negative integers, and larger_num > smaller_num
post: returns the greatest common d... | 70db69b222f1a4a0d395e9bb1ff87ef031dbbbd6 | 10,803 |
import argparse
def get_args():
"""
Get arguments from command line
"""
parser = argparse.ArgumentParser()
parser.add_argument("image_path", type=str, help="path to image in which to predict class label")
parser.add_argument("checkpoint", type=str, help="checkpoint in which trained mo... | ec468187194d8c2af0182c5464452c614842091a | 10,804 |
def _urlescape(name):
"""Escape the given name for inclusion in a URL.
Escaping is done in the manner in which AutoDuck(?) seems to be doing
it.
"""
name = name.replace(' ', '_')\
.replace('(', '.28')\
.replace(')', '.29')
return name | ec94492778ccdefdde7d657f8fffd953915949ae | 10,808 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.