content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def find_allergens(candidates):
"""Uses allergens that only have one possible ingredient that could
contain them to rule that ingredient out for other allergens until
all allergens have exactly one ingredient that could contain it.
Returns a dict of allergen name to ingredient name to simplify things.
... | 1c99e837a96c0e0f47bee6955af1149036a836ad | 688,901 |
def null_count(df):
"""This functions returns the number of null values in a Dataframe"""
NullSum = df.isnull().sum().sum()
return NullSum | e2d0126d5ac6f275234263c87b6e80637b7b91d9 | 688,902 |
def type_factor(NT, NP, SC=30.0):
"""
NT - Number of planet types in area
NP - Number of planets in area
SC - a number used to scale how bad it is to differ from the
optimal number of planet types. Lower number means less bad
Returns a number between 0.0 and 1.0 indicating how good the rati... | 8b79f29b17e07528233754bebc996b8701f10e77 | 688,903 |
import pandas as pd
def to_date(x):
"""Convert to timestamp."""
try:
ts = pd.Timestamp(x.split()[0])
return ts
except BaseException:
pass
return x | 41a7b8697dc702f5b78c028dde451940723d1ad3 | 688,905 |
def compute_long_chain(number):
"""Compute a long chain
Arguments:
number {int} -- Requested number for which to compute the cube
Returns:
int -- Value of the cube/long chain for the given number
"""
return number * number * number | 62a214cac43409104d95ff4ca1f8b59beaf534c7 | 688,906 |
import argparse
def args_parse(argv):
"""Parses the argument list"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-pl",
"--listen-port",
dest="listen_port",
help="port on which the server listens for the incoming parsed data "
"generated by the hpx-dash... | 1231f43eaecf91c9be574a2a6569333b972affc3 | 688,907 |
def get_markers_to_contigs(marker_sets, contigs):
"""Get marker to contig mapping
:param marker_sets: Marker sets from CheckM
:type marker_sets: set
:param contigs: Contig to marker mapping
:type contigs: dict
:return: Marker to contigs list mapping
:rtype: dict
"""
marker2contigs =... | 2ed01846d8e6e0c5fd60ec8152e098d1c91d87ab | 688,908 |
def _IsAnomalyInRef(change_point, ref_change_points):
"""Checks if anomalies are detected in both ref and non ref build.
Args:
change_point: A find_change_points.ChangePoint object to check.
ref_change_points: List of find_change_points.ChangePoint objects
found for a ref build series.
Returns:
... | d36686a342be43e786f067e55c10df5612d1c500 | 688,909 |
from typing import Dict
def devel_environ(env_devel_file) -> Dict[str, str]:
""" Environ dict from .env-devel """
env_devel = {}
with env_devel_file.open() as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
key, value = line.split... | 15525a13dd9db37ac9811dc2ab1654922397cea9 | 688,910 |
def _sum(op1, op2):
"""Sum of two operators, allowing for one of them to be None."""
if op1 is None:
return op2
elif op2 is None:
return op1
else:
return op1 + op2 | 6ae3c149af620446dba02ac89b4d7d93a7d1e76d | 688,911 |
def _CheckApiTestFile(input_api, output_api):
"""Checks that the public headers match the API tests."""
api_test_file = input_api.os_path.normpath('fpdfsdk/fpdf_view_c_api_test.c')
def is_api_test_file(f):
return input_api.os_path.normpath(f.LocalPath()) == api_test_file
if all([not is_api_test_file(f) fo... | 5a12ea363547897fcccbd662b2e7751974fa7d63 | 688,912 |
def eyr_valid(passport):
""" Check that eyr is valid
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
:param passport: passport
:return: boolean
"""
return len(passport['eyr']) == 4 and 2020 <= int(passport['eyr']) <= 2030 | 47fe44bcde03c2bf99796fd14da9ad4bbb6b7e0e | 688,913 |
def ParseWorkflow(args):
"""Get and validate workflow from the args."""
return args.CONCEPTS.workflow.Parse() | 0794d6ab478f975a55c773d5a653bd8dccc35a00 | 688,915 |
def file_to_ints(input_file):
"""
Input: A file containing one number per line
Output: An int iterable
Blank lines and lines starting with '#' are ignored
"""
ints = []
with open(input_file) as f:
for line in f.readlines():
line = line.strip()
if line and not ... | cb091f3d48a6770dc2f37529b9243038dbd44411 | 688,916 |
def close_tables(egg_string, target_level=0):
""" The egg string is hierarchically ordered. This function appends curly brackets to close open tables.
It takes the indentation of the last closed bracket as reference for the current level/depth of the hierarchy.
:param egg_string:
:type egg_string: str
... | 04494dd7d5e3ff4ca523ed18bcf20caddef5fe38 | 688,917 |
import math
def _get_batch_size_schedule(minibatch_maxsize):
"""Returns training batch size schedule."""
minibatch_maxsize_targetiter = 500
minibatch_startsize = 1000
div = (float(minibatch_maxsize_targetiter-1)
/ math.log(float(minibatch_maxsize)/minibatch_startsize, 2))
return [
min(int(2.... | 2031127eba280ec726a4a810a31bbe25cdbcc8ee | 688,918 |
def feature_to_tpm_dict(feature_to_read_count, feature_to_feature_length):
"""Calculate TPM values for feature
feature_to_read_count: dictionary linking features to read counts (float)
feature_to_feature_length: dictionary linking features to feature lengths (float)
Return value: dictionary linking fe... | 553a0375d9aec8dc29c47e88064e9f777a3c7614 | 688,920 |
def _get_spot(precursor):
"""
get spot that will be enriched
"""
return 0 | 39985a138074979e947c657e0ee315e13c8058c6 | 688,921 |
def remove_stopwords(texts, stop_words):
"""
Parameters:
- `texts`
a list of documents
- `stop_words`
a list of words to be removed from each document in `texts`
Returns: a list of documents that does not contain any element of `stop_words`
"""
return [[w... | b70828b328abe1e0e59698307adc8ececeac368e | 688,922 |
def get_mapping_pfts(mapping):
"""Get all PFT names from the mapping."""
pft_names = set()
for value in mapping.values():
pft_names.update(value["pfts"])
return sorted(pft_names) | 40fc5d5cbd537db203a240e44a0ef6c0358a7019 | 688,923 |
def encode(token):
"""Escape special characters in a token for path representation.
:param str token: The token to encode
:return: The encoded string
:rtype: str
"""
return token.replace('\\', '\\\\').replace('/', '\\/') | 30db00dc30b267618e1b85905bce3c3436878c95 | 688,924 |
def build_window_title(paused: bool, current_file) -> str:
"""
Returns a neatly formatted window title.
:param bool paused: whether the VM is currently paused
:param current_file: the name of the file to display
:return str: a neatly formatted window title
"""
return f"EightDAD {'(PAUSED)' ... | 736bacb63a5d720b91e15b5812f14c73a1e5dc22 | 688,926 |
from pathlib import Path
def part_two(filename='input.txt'):
"""[summary]
Parameters
----------
filename : str, optional
[description], by default 'input.txt'
Returns
-------
[type]
[description]
"""
lines = Path(filename).read_text().split('\n')
valid_passwo... | bbc1aa29fde1caa98969369d104de40ba5997413 | 688,927 |
import imp
import os
def load_module_by_path(path):
"""Load a python module from its path.
Parameters
----------
path : str
Path to the module source file.
Returns
-------
mod : module
Loaded module.
"""
module_file_basename = os.path.basename(path)
module_na... | 341887d272e0e5641d527084d1e4c7847b9207fd | 688,928 |
def mph_to_kph(mph):
"""Convert mph to kph."""
return mph * 1.609 | 133e54672582deaa9585560592e2d158b4335803 | 688,929 |
def sort_hand(hand, deck):
"""Returns a hand of cards sorted in the index order of the given deck"""
sorted_hand = []
for i in deck:
for card in hand:
if i == card:
sorted_hand.append(card)
return sorted_hand | 79033c383b28dca746d8c113209f85d3ae749ea1 | 688,930 |
def read_from_file():
"""generates the dict from the file
portlist.txt"""
port_dict = {}
with open('../assets/portlist.txt', 'r') as txt_file:
for line in txt_file:
key_value = line.split(' ')
port_dict[key_value[0].encode('utf-8')] =\
key_value[1].encode('utf-8')
return port_dict | 1b840d78c5ecbeab1765aa9abdf4d65940d9aaa8 | 688,931 |
def find_pp(api):
"""Find pretty-printers"""
pps = {}
for symb in api["func"]:
parts = symb.split("_")
dtype = "_".join(parts[:-1])
tail = parts[-1]
if tail in ["str", "fpr", "pr"]:
if dtype not in pps:
pps[dtype] = []
pps[dtype].app... | d6dd36150fa15ad28c2c319d1880978a915bfb5d | 688,932 |
def colName(table, column):
"""Return a string with the name of the column in the current db."""
if column == 'id':
return table.sqlmeta.idName
return table.sqlmeta.columns[column].dbName | 467eda1f9fedbd807bcbe7cce34979ccf5a37c8f | 688,933 |
def clean_path(directory_path) -> str:
"""
Will ensure the path supplied DOES end with / so we can join to a filename without worry
"""
if str(directory_path):
if directory_path[-1:] != "/":
directory_path = directory_path + "/"
return directory_path | c8a0143479f48bccf03e67666db6d3ea43d276b8 | 688,934 |
def get_read_count_type(line):
"""
Return the count number and read type from the log line
"""
data = line.rstrip().split(":")
count = data[-1].strip()
type = data[-3].lstrip().rstrip()
return count, type | ae60a9952118bfd66b4ff3af7446f2a3b2c5d0a9 | 688,935 |
def dif(a, b):
""" copy from http://stackoverflow.com/a/8545526 """
return [i for i in range(len(a)) if a[i] != b[i]] | e600839ef78db7794023808908f5087f919e8ad1 | 688,936 |
def read_text_file(path_to_file):
"""
Read a text file and import each line as an item in a list.
* path_to_file: the path to a text file.
"""
with open(path_to_file) as f:
lines = [line.rstrip() for line in f]
return lines | 0265631258341d29c72e2416a273d6595029f93b | 688,937 |
import requests
def load_text_lines_from_url(url):
"""Load lines of text from `url`."""
try:
response = requests.get(url)
response.raise_for_status()
content = response.text.split("\n")
return [x.strip() for x in content if len(x.strip()) > 0]
except requests.RequestExcepti... | 8e9c991af8b34e6c25a5d5b95f05a9b983972943 | 688,938 |
def x10(S: str, n: int):
"""change float to int by *10**n
Args:
S (str): float
n (int, optional): n of float(S)*10**n (number of shift).
Returns:
int: S*10**n
"""
if "." not in S:
return int(S) * 10**n
return int("".join([S.replace(".", ""), "0" * (n - S[::-1].f... | b2ea4a56580739d04cff44f185196ab27f92b67a | 688,939 |
def present(lists, end):
"""
Given a list of positions of words for a single document,
returns whether all words appear consecutively at least once
"""
p={}
for i in range(len(lists)):
for j in lists[i]:
p[j-i] = p.get(j-i, 0) + 1
for i in p:
if p[i] == e... | 9f8ca057923b2e1dffe72f1f49b88b59b5e414a9 | 688,940 |
import os
def gen_b2_path(filename, sha):
"""Generates the path where a file should be stored in B2 based on name and hash."""
return os.path.join(sha, filename) | ae7367414002a688aabab3b43c878647492791a5 | 688,941 |
def inverter_elementos(iteravel):
"""
Inverte os elementos dentro de um tuplo.
:param iteravel: tuplo
:return: tuplo
Exemplo:
>>> tpl = ("a1", "b3")
>>> inverter_elementos(tpl)
("1a", "3b")
"""
res = ()
for e in iteravel:
res += (e[::-1],)
return res | 5561c0885291bdcf697e5f315b139b66c4a97bda | 688,942 |
def scrapeints(string):
"""Extract a series of integers from a string. Slow but robust.
readints('[124, 56|abcdsfad4589.2]')
will return:
[124, 56, 4589, 2]
"""
# 2012-08-28 16:19 IJMC: Created
numbers = []
nchar = len(string)
thisnumber = ''
for n, char in enumerate(string)... | d6918e8a260f434f4b126244c505fbc4b1c48bbf | 688,943 |
def vm_ready_based_on_state(state):
"""Return True if the state is one where we can communicate with it (scp/ssh, etc.)
"""
if state in ["started", "powered on", "running", "unpaused"]:
return True
return False | f1a31e63d4a527fddd26b403828b2c305c72a086 | 688,944 |
def get_utm_zone(lat,lon):
"""A function to grab the UTM zone number for any lat/lon location
"""
zone_str = str(int((lon + 180)/6) + 1)
if ((lat>=56.) & (lat<64.) & (lon >=3.) & (lon <12.)):
zone_str = '32'
elif ((lat >= 72.) & (lat <84.)):
if ((lon >=0.) & (lon<9.)):
z... | 37887dda8e155f6207a2554732f39e0da0150192 | 688,945 |
def counters(stats):
""" Count all_sentences all_questions all_questions_with_ans & all_corrects
:param stats: list(quintet)
:rtype int, int, int, int
:return: all_sentences, all_questions, all_questions_with_ans, all_corrects
"""
# Initialization of counters.
all_sentences = 0
all_que... | d6edc124e6254b11316a429c84664db1a223b352 | 688,946 |
import torch
def define_device(device_name):
"""
Define the device to use during training and inference.
If auto it will detect automatically whether to use cuda or cpu
Parameters
----------
device_name : str
Either "auto", "cpu" or "cuda"
Returns
-------
str
Eith... | ab1fcf9a4d8907016085935684238d18d3800ddd | 688,947 |
from collections import Counter
def most_common(words, n=10):
"""
Returnes the most common words in a document
Args:
words (list): list of words in a document
n (int, optional): Top n common words. Defaults to 10.
Returns:
list: list of Top n common terms
"""
bow = Co... | c4f0adecdec09cb3b2a83e9edbd39eb1789ad592 | 688,948 |
def is_driver(archive, info):
"""
True if the file in the archive that is specified by info is an admissible driver.
:param archive:
:param info:
:return:
"""
return archive.read(info).startswith(b"#!") | cf09d561372043073203a10d954fa44b3051b38c | 688,949 |
def num_items() -> int:
"""The number of candidate items to rank"""
return 10000 | 437e39083a0abb5f1ce51edd36f7e5bb5e815162 | 688,950 |
import keyword
def pykeyword(operation='list', keywordtotest=None):
"""
Check if a keyword exists in the Python keyword dictionary.
:type operation: string
:param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'.
:type keywordtotest: string
:param keywor... | 63866dbc263d14f5c7455b194d8f525b5fc08bc8 | 688,952 |
import json
def json_dumps(json_obj, indent=2, sort_keys=True):
"""Unified (default indent and sort_keys) invocation of json.dumps
"""
return json.dumps(json_obj, indent=indent, sort_keys=sort_keys) | fdb81417c36c42ae23b72c88041a3be2ea42f0a3 | 688,953 |
def compare(recipe, wanted):
"""Compare recipe against wanted."""
for num1, num2 in zip(wanted, recipe):
if num1 != num2:
return False
return True | a1ca47fa4adb38051e486c94066238a12ac58b89 | 688,955 |
def nonSynonCount(t):
""" count the number of nonsynon labels in the transcript annotations.
"""
count = 0
for a in t.annotations:
for l in a.labels:
if l == 'nonsynon':
count += 1
return count | 886c9ae564fabe434b2f30c9f31c78784a311741 | 688,956 |
def getConfigOrDefault(config, default_config, parameter, default_value=None):
""" Get the configuration from the main config object, or from the default config if missing or empty
"""
value = config.get(parameter)
if (value is None or value == '') and default_config is not None:
value = default... | 5435f4ac7852f52857015c8de9fda359a99a1992 | 688,957 |
import re
def lazy_load_model_classes(app, collection, model_map=None):
"""Lazily load modules as necessary"""
# Ref: http://stackoverflow.com/questions/3372361/dynamic-loading-of-modules-then-using-from-x-import-on-loaded-module
classname = ''.join([ x.capitalize() for x in collection.split('_') ])
... | 0b486fdb95940ad4453ed05e9b3f1bce7b9eae23 | 688,958 |
def postamble():
"""
Return the trailing lines
"""
return """
// all done
return table;
}
// end of file""" | 9c3042e07cc866e01c6e279f1c2358ef482007f2 | 688,959 |
def _make_socket_path(host: str, display: int, screen: int) -> str:
"""
Attempt to create a path to a bspwm socket.
No attempts are made to ensure its actual existence.
The parameters are intentionally identical to the layout of an XDisplay,
so you can just unpack one.
Parameters:
host --... | ea7e36b7058db9291f2ed4b1888bf5fca263ba8d | 688,960 |
def strip_unsupported_schema(base_data, schema):
""" Strip keys/columns if not in SCHEMA """
return [
{key: value for key, value in place.items() if key in schema}
for place in base_data
] | 6faebcbb5b7a7a611ed1befd3daa321d79c925a8 | 688,961 |
def comma_join(items, stringify=False):
"""
Joins an iterable of strings with commas.
"""
if stringify:
return ', '.join(str(item) for item in items)
else:
return ', '.join(items) | 78e823c70fa5896c9cb26140327b485200041369 | 688,962 |
def manUnit_dict(obj, geom=None):
"""Serialize a management unit to a python dictionary
Arguments:
- `obj`: a ManagementUnit instance
"""
item = dict(
id=obj.id,
slug=obj.slug,
label=obj.label,
mu_type=obj.mu_type,
centroid=obj.geom.centroid.wkt,
ext... | d8aa09f84e5b258b5d34dfc627bb10cc3eb4019f | 688,963 |
def get_5primes(bases):
""" 5' ends don't have bases downstream """
return filter(lambda b: b['down'] is None, bases) | f650087c2d898f6309a57cea05dda8bf9ee03146 | 688,964 |
from typing import Set
from typing import Tuple
from typing import Dict
def ensure_one_inbound_connection_per_node(
num_nodes: int,
graph_edges: Set[Tuple[int, int]],
inbound_degrees: Dict[int, int]
) -> Tuple[Set[Tuple[int, int]], Dict[int, int]]:
"""
This function tries to enforce th... | 962aefc99678b6598d52e7d7042c691f4f55ee5e | 688,965 |
import math
def polar_to_cartesian(r, theta, r_ref=0.0, theta_ref=0.0):
"""
Helper function to convert polar coordinates to Cartesian
coordinates (relative to a defined reference point).
:Parameters:
r: float
Radial distance of point from origin.
theta: float
Angular bearing... | a78cc513fc76dcb1a40f12c28310bbe74373c2ff | 688,966 |
def get_request_browser(request):
"""
获取请求用户浏览器信息
:param request: request请求对象
:return: 浏览器信息
"""
family = request.user_agent.browser.family
version_string = request.user_agent.browser.version_string
return family + ' ' + version_string | 75de90cfb7f963e3e305cc22778ae2c95511903d | 688,967 |
def strip_nonvb_chars(s):
"""
Strip invalid VB characters from a string.
"""
# Sanity check.
if (not isinstance(s, str)):
return s
# Strip non-ascii printable characters.
r = ""
for c in s:
if ((ord(c) > 8) and (ord(c) < 127)):
r += c
return r | 77fc7d17e726819ae9d3b44af95f8ae83232af59 | 688,968 |
from pathlib import Path
def make_paths_absolute(value: str, workdir: Path = Path.cwd()) -> str:
"""
Detect if value is a relative path and make it absolut if so.
:param value: Parameter value from arguments
:param workdir: Path to workdir. Default: CWD
:return:
"""
if "../" in value and (... | 00d6809197fc753419ee3abe1cef8d2eb0dd0219 | 688,969 |
from typing import Dict
import math
def position_distance(a: Dict[str, float], b: Dict[str, float]) -> float:
"""Compute the distance between two positions."""
return math.sqrt((a['x'] - b['x'])**2 + (a['y'] - b['y'])**2 + (a['z'] - b['z'])**2) | e945797844132c30bc5c707c2f31f28338c3896c | 688,970 |
import os
def get_path(filename):
"""Given a test filename return its path"""
_path = os.path.join(os.path.split(__file__)[0], 'files', filename)
return _path | 11d3f8827ba5f9a702f45e3b7ed99f201e5b9c57 | 688,971 |
def fix_strength(val, default):
""" Assigns given strength to a default value if needed. """
return val and int(val) or default | e9a2414feb1d3e84fb9a02aa83b085d3845d728d | 688,972 |
def get_refs_from_soup(soup):
"""get_refs_from_soup.
Returns a list of `<cite>` tags from the passed BeautifulSoup object.
:param soup: BeautifulSoup object (parsed HTML)
"""
return soup.find_all('cite', recursive=True) | 5bd7ec0e1884aceaf05800775cc304d59e59c458 | 688,974 |
def loading_prem():
"""Loading per premium
.. note::
This cells is not used by default.
``0.5`` by default.
.. seealso::
* :func:`premium_pp`
"""
return 0.5 | 9792688a2fcf8c474e3f0e966de585c777b9f7c5 | 688,975 |
def get_target_value(data_frame, target_type):
"""
Get the value of a specific target from the engineered features pandas data frame.
:param data_frame: The engineered features pandas data frame.
:param target_type: The name of the prediction target.
:return: The prediction target value.
"""
... | a31661b6feeadc2b8be3013edf57aa07ebac9f1b | 688,976 |
def restore_links(n,ng,links_info,mode):
"""restore links from given info list"""
is_input = (mode=="IN")
for elem in links_info:
nn, _, sidx = elem
dn = ng.nodes.get(nn)
s = dn.outputs[sidx] if is_input else dn.inputs[sidx]
args = (s, n.inputs[0]) if is_i... | 30dc47905df6d9f3b65b7f0280afc4ba62ee2559 | 688,977 |
from pathlib import Path
import os
def normalized_path_obj(path='.') -> Path:
"""
默认支持 ~ 符号
返回的是 Path 对象
:param path:
:return:
"""
if isinstance(path, Path):
return path.expanduser()
elif isinstance(path, str):
if path.startswith('~'):
path = os.path.expand... | 3fcb364d8c96b628827d56d5f8b98a702192a38c | 688,978 |
import string
def filename_from_string(text):
"""Produces a valid (space-free) filename from some text"""
text = text.lower()
valid_chars = "-_." + string.ascii_letters + string.digits
return ''.join(c for c in text if c in valid_chars) | d841923eb4e00f1debb186d7ac3811a5ecfe8f71 | 688,979 |
def get_long_description():
"""
:return: The description for the plugin type.
"""
return """Auth plugins make possible to scan authorization protected web applications.
They make login action in the beginning of the scan, logout - in the end
and check current session action regularly.""" | 9460a0f5854992674f20c3b574794a787184aa35 | 688,980 |
from pathlib import Path
from typing import List
def read_tabular_data(filename: Path) -> List[List[float]]:
"""Reads a tabular data file, skipping comment lines.
Args:
filename (Path): The full path of the file to be read
Returns:
List[List[float]]: The file contents, with comment lines... | ec2d237304d5748e58f6dfcc3282ce32f06ed414 | 688,981 |
def name_test(item):
""" used for pytest verbose output """
return f"{item['params']['interface']}:{item['expected']['optic'] or 'none'}" | 9d8000ae72a22ea89e7b6c03e5847324ae89d2cc | 688,982 |
def _tile_url(tile_format, x, y, zoom):
"""Build S3 URL prefix
The S3 bucket is organized {tile_format}/{z}/{x}/{y}.tif
Parameters
----------
tile_format : str
One of 'terrarium', 'normal', 'geotiff'
zoom : int
zoom level
x : int
x tilespace coordinate
y : int
... | 816512f68958c8b04e724e843ce975ededd118d7 | 688,983 |
def all_sentences(df):
"""
Returns a list of sentences annotated with any domain
"""
sentences = df['sen'].tolist()
return(sentences) | 04381c30873ed5e129d229a942a203d26505b952 | 688,984 |
def parse_opcode(token):
"""Extract the opcode and the mode of all params"""
opcode = token % 100
modes = [0, 0, 0, 0]
if token > 100:
for (i, mode) in enumerate(str(token)[-3::-1]):
modes[i] = int(mode)
return opcode, modes | 90f36fa1b69318739cc8d785639ca9381f8cdb2b | 688,986 |
def _desc_has_possible_number_data(desc):
"""Returns true if there is any possible number data set for a particular PhoneNumberDesc."""
# If this is empty, it means numbers of this type inherit from the "general desc" -> the value
# "-1" means that no numbers exist for this type.
if desc is None:
... | 393f16dee7040f044f26909e524b3e11dbf88c94 | 688,987 |
def complex_norm_l2(xr, xi, dim, keepdim=False, eps=1e-10):
""" a^{H} * a """
return (xr.square() + xi.square()).sum(
dim=dim, keepdim=keepdim).clamp_(eps).sqrt()
# return (xr.square() + xi.square()).clamp_(eps).sqrt() | dc78a067a70f5a9a1c01405c2a23e1151de20be7 | 688,988 |
import os
def find_agent_host_id(thishost):
"""Returns the neutron agent host id for RHEL-OSP6 HA setup."""
host_id = thishost
try:
for root, dirs, files in os.walk('/run/resource-agents'):
for fi in files:
if 'neutron-scale-' in fi:
host_id = 'neut... | 496f225a6bed4c0d74f3e9d6018830f2f77a538b | 688,989 |
import pickle
def load_pickle(path):
"""
Load object from path
:param path: path to pickle file
:type path: str
:return: object
"""
with open(path, 'rb') as f:
obj = pickle.load(f)
return obj | d75d5bdae7dd84c569b450feb5f1349788a2997c | 688,991 |
def has_dtypes(df, items):
"""
Assert that a DataFrame has ``dtypes``
Parameters
==========
df: DataFrame
items: dict
mapping of columns to dtype.
Returns
=======
df : DataFrame
"""
dtypes = df.dtypes
for k, v in items.items():
if not dtypes[k] == v:
... | f542aca7b69116c1c49d09d9ec8a137856d8c4f1 | 688,992 |
def opencsv(path):
"""Read csv in bytes to avoid exceptions from corrupt data and save to an object"""
try:
b = open(path, 'rb')
next(b)
return(b)
except Exception as e:
print(e) | e0ee00ae71093f5a580d0c6aef3867f0e4a38591 | 688,993 |
def are_rects_overlapped(rect1, rect2):
"""Check whether two rects are overlapped or not?"""
overlapped = False
x1, y1, w1, h1 = rect1
x2, y2 = x1+w1, y1+h1
x3, y3, w2, h2 = rect2
x4, y4 = x3+w2, y3+h2
if (x1<x3<x2 or x1<x4<x2 or x3<x1<x4 or x3<x2<x4) and (y1<y3<y2 or y1<y4<y2 or y3<y1<y4 or... | b9ec4dea24d52cbf8d24b0def76cccea2e80f771 | 688,994 |
def is_none(x):
"""
Verifies is the string 'x' is none.
:param x: (string)
:return: (bool)
"""
if (x is None) or ((type(x) == str) and (x.strip() == "")):
return True
else:
return False | e0ca947702b839b83c345331ac9fd498befcbaef | 688,995 |
def parse_filename(filename):
# time_tag=TIME_INFOLDER_TAG,
# time_fmt=TIME_INFILE_FMT,
# ):
"""Parse Hive and RPi number from filename.
Filename e.g.: raw_hive1_rpi1_190801-000002-utc.jpg
"""
prefix, hive_str, rpi_str, t_str = filename.split("_")
... | d4330e5b1123624288b3cb8d4747971e4cee795b | 688,996 |
def getposition(index):
"""
Return (latitude, longitude) as a tuple from a truble containing
the (row, collum) index associated with the numpy matrix meaning
(latitudeIndex, longitudeIndex)
"""
if (index[0] < 0 or index[0] >= 180): raise LookupError('latitude index is out of range')
if (index[1] < 0 or index[1] ... | cc2f4c9a9f163bc784649ef71a316c1e0898143d | 688,997 |
import threading
def 线程_取当前线程():
"""
返回与Thread调用方的控制线程相对应的当前对象。如果未通过threading模块创建调用者的控制 线程,则返回功能有限的虚拟线程对象。
"""
return threading.current_thread() | ce27f63795270c6429160adcc2ac747827f92099 | 688,999 |
import re
def attribute_mapper(attr: str) -> str:
"""
For all the classes defined in the module, this function is called to transform the keyword arguments into HTML tag attributes.
By default, the function replaces underscores (_) by hyphens (-).
"""
return re.sub("^v_(.*)_(.*)$", r"v-\1:\2", attr) | adfff5e8c3c63c1d2002b1b23a43e4487a49b6b9 | 689,000 |
def do_steps_help(cls_list):
"""Print out the help for the given steps classes."""
for cls in cls_list:
print(cls.help())
return 0 | 19ce1585f915183fcb38c2ea268a6f30780830bb | 689,001 |
def bbox_to_pptx(left, bottom, width, height):
""" Convert matplotlib bounding box format to pptx format
Parameters
----------
bottom : float
left : float
width : float
height : float
Returns
-------
left, top, width, height
"""
return left, bottom-height, width, heig... | b32018d50cb022fd65ee87fe258f0cdc9bc04d41 | 689,002 |
import subprocess
def git_hash() -> str:
"""Extracts Git hash from current directory.
Returns:
str -- Git hash encoded as UTF-8.
"""
return (
subprocess.Popen(
["git", "rev-parse", "--verify", "HEAD"], stdout=subprocess.PIPE
)
.communicate()[0]
.de... | 91e9ccd782db3c657dbd1770e45aef9dafd5b074 | 689,003 |
import math
def softmax(vector, temperature=1):
"""The softmax activation function."""
vector = [math.pow(x, temperature) for x in vector]
if sum(vector):
return [float(x) / sum(vector) for x in vector]
else:
return [float(len(vector)) for _ in vector] | a924869dd66b6f0a9c10a300be8cd9265ca82865 | 689,004 |
def get_field_name(format, file_formats):
"""获取文件格式对应所属的上一级标签的名字
parameters:
---------------------------------------------------------
format: string format definition
file_formats: dictionary config scheme definition
"""
statement = format.lower(... | b8c6824151b5cf8027a4f3d34e601bca46e32eac | 689,005 |
def get_ids(cls, inherit=None):
"""Function that returns all the IDs to use as primary key
For a given class, this function will check for the _ids parameter and
call itself recursively on the given class' base classes to append all
other required IDs, thus generating the list of parameters to use as
... | 242036494f91e5ee67a6f92a691ec2fde13c241a | 689,006 |
def get_data():
"""
This function is responsible for the input parameters of the whole program
@:return:
Returns the subject in a format the is usable in requests
Returns the number of videos that will be searched according to the subject
"""
print('Enter what you search: ')
... | 83da90c2d1b971bab85c37b7b8143ef592a13ec8 | 689,007 |
def timeToSnowFlake(endDate):
"""
Takes the UTC end date in '2020-07-02 21:58:00+00:00' format and converts it to a local time epoch then snowflake.
Can also take UTC end date in '2020-07-02 21:58:00' format to convert to epoch and then snowflake
:param endDate: UTC date in '2020-07-02 21:58:00+00:00' o... | 5d867546100926701ca4979bfb5a46746aa8a3b2 | 689,008 |
def concat_things( *args ):
""" Behave kinda like a print statement: convert all the things to strings.
Return the large concatinated string. """
result = ''
space = ''
for arg in args:
result += space + str(arg).strip()
space = ' '
return result | 163665159eab83a3b486ed550eb2d19e33944b4e | 689,009 |
import itertools
def createListWord(n):
"""Creates the list of word with size n on the alphabet {1,2,3,4}."""
temp = [''.join(x) for x in itertools.product('1234', repeat=n)]
L = [int(y) for y in temp]
return L | 7103f269695a77a24c716501b524e1bfddfe2562 | 689,010 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.