content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import json
import binascii
def command_conversion(dest, command, payload, command_list):
"""
Convert the command info (if known).
http://www.circl.lu/pub/tr-23/
Args:
dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.
command: hex str... | 722d86970cf587d83dc80c487bca2f1583d1183a | 673,973 |
def filter_dict_keys(org_dict, keep_keys):
"""Helper function to keep only certain keys from config.
Pass in a dictionary and list of keys you wish to keep
Any keys not in the list will be removed in the returned dictionary"""
newDict = dict()
# Iterate over all the items in dictionary and filter it... | d4b971f643236d55f76cfd30c844f2ea41feec6e | 673,974 |
import argparse
def argparser() -> argparse.ArgumentParser:
"""Return precompiled ArgumentParser
"""
parser = argparse.ArgumentParser(
description="Compare either two NetCDF files or all NetCDF files in "
"two directories.",
epilog="Examples:\n\n"
"Compare two NetCDF files:... | 4b7158a93a6730bb6e608a22978f4908366fc739 | 673,975 |
import gzip
import re
def readHeader(fname):
"""Read QA4ECV NO2 ASCII data header.
PARAMETERS
----------
fname : str
Path to the filename
RETURNS
-------
header : a list of useful variables: year, month, nlat, nlon, lat_start, lat_end, lon_start, lon_end
"""
f=gzip.open(... | 5c1549b9be220f5875820b14ea6239bfa5d7d10e | 673,976 |
import itertools
def concatenate(*lists) -> list:
"""concatenate inpout lists to new list
Returns
-------
list
concatenated list
"""
return list(itertools.chain(*lists)) | e997a44955d3c60695a034342f2b04b7128904cf | 673,977 |
def is_dirty():
"""Function: is_dirty
Description: Method stub holder for git.Repo.git.is_dirty().
Arguments:
"""
return True | 92bdd6aea20ba404ea65de487134f6acfd7c06bc | 673,978 |
from typing import Any
from typing import Union
def handle_NaN(value1: Any, value2: Union[Any, None]):
"""
Sometimes it could happen that some values are setted as NaN.
However, in this case the value isn't neither None or NaN.
So you have to choose which value set if it's NaN.
Parameters
--... | 166589726882a9ac018cde07ab6f4984fedcb4b0 | 673,979 |
from typing import Set
import click
def get_states_as_set(state_list: str) -> Set:
"""Helper method to parse the state string.
Args:
state_list: comma separated string with codes and states
Returns:
Set with valid state names in upper case
"""
codes_to_states = {
"BF": "B... | af6160cee0f8d84f3e8accbc3a8e949bb21c95bd | 673,980 |
import torch
def MatConvert(x, device, dtype):
"""convert the numpy to a torch tensor."""
x = torch.from_numpy(x).to(device, dtype)
return x | 7507ba95d203ce4c8a25d5ca8de7407a153a4e99 | 673,982 |
def simplifySolutions(optimProbConf, population):
"""
Simplify the solution by removing the modification that not affect the final fitness value.
Args:
optimProbConf (optimProblemConfiguration): The configuration problem.
population (list): List of individuals returned by EA algorithm.
... | 15ec8a49cc0e1c8f99a47228fadc93f42eb669ea | 673,983 |
def transform_globs_into_regexes(globs):
"""Turns glob patterns into regular expressions."""
return [glob.replace("*", ".*").replace("?", ".") for glob in globs] | bda321b2b1cb863bb0e3944bb5c9ef7b77427aae | 673,984 |
def get_iteration_end_time(underlay, overlay, model_size, computation_time):
"""
Compute the end times of next iteration having the end times for current iteration.
:param underlay:
:param overlay:
:param model_size:
:param computation_time
:return:
"""
out_degrees = dict(overlay.ou... | 847ed71981df672933aeb258013072a607489cc9 | 673,985 |
def xywh_to_tlbr(bbox, img_wh):
""" converts xywh format to (tlx, tly, blx, bly) """
(img_w, img_h) = img_wh
if img_w == 0 or img_h == 0:
img_w = 1
img_h = 1
msg = '[cc2.1] Your csv tables have an invalid ANNOTATION.'
print(msg)
#warnings.warn(msg)
#ht = 1
... | 6f51198d3d2d53a541feb934bcd23a5e56a406ca | 673,986 |
def _out_array_shape(count):
"""Return the output array shape given the count array created by getStartCountStride"""
s = list(count.shape[:-1])
out = []
for i, n in enumerate(s):
if n == 1:
c = count[..., i].ravel()[0] # All elements should be identical.
out.append(c)
... | 693d0124e29541c26f6f0a4c05ffec827fe29ff0 | 673,987 |
import os
import re
def _doxyfile_attr_match(project_name, line):
"""
Determines whether there is any 'Doxyfile' options available in 'line'.
Return the updated version if 'line' contains options that need to be
changed; otherwise return None.
"""
arguments = (project_name, line)
if not ... | c41b90f88da10218fd48ce0a55894466b50de090 | 673,988 |
def is_integer(value: str) -> float:
"""Asserts that a value is an integer."""
try:
int(value)
except ValueError as e:
return 0.0
return 1.0 | 65687507cc8044062de2940e74b68286d01220fa | 673,989 |
def trim(text: str, limit: int) -> str:
"""limit text to a certain number of characters"""
return text[: limit - 3].strip() + "..." if len(text) > limit else text | ae2bbc8fe4610f50a5b55ea1edd55d0af5346413 | 673,990 |
def adjust_convention(img, convention):
"""
Inverts (could) the image according to the given convention
Args:
img (np.ndarray): Image numpy array
convention (int): -1 or 1 depending on macros.IMAGE_CONVENTION
Returns:
np.ndarray: Inverted or non inverted (vertically) image.
... | dcd3de247921a338c0356c79ee1828af10713f35 | 673,991 |
def help_response():
"""
Return help documentation to guide the user
"""
help_message = """
<xmp>
___ _ _
/ _ \_ __ ___ _ _ _ __ __| | |__ ___ __ _
/ /_\/ '__/ _ \| | | | '_ \ / _` | '_ \ / _ \ / _` |
/ /_... | bfddac932499255aace1654e37e2ca118f80a33d | 673,992 |
def minAddToMakeValid(self, string):
"""O(n) time | O(1) space"""
not_closed = 0
brackets = 0
for char in string:
if char == ")":
if brackets <= 0:
not_closed += 1
else:
brackets -= 1
else:
brackets += 1
return not_c... | cecd8f07e3f0f672a6220e9b1e811bd17d9fe90d | 673,993 |
def get_blog_filename(title, blog_date):
"""获取保存的博客文件名称
Args:
title: 标题
blog_date: 创建时间
Returns:
博客保存文件名
"""
return r'【%s】%s' % (blog_date, title) | 994f63bac850e7f5cd15226e7d7b86050f4beac8 | 673,995 |
import textwrap
async def snippet_to_embed(file_contents, file_path, start_line, end_line):
"""Given file contents, file path, start line and end line creates a code block"""
split_file_contents = file_contents.splitlines()
if start_line is None:
start_line, end_line = 1, len(split_file_contents... | 9872d32c40b7b0a2c7c388496cab3c83b44023c2 | 673,996 |
def stringify_keys(d):
# taken from https://stackoverflow.com/a/51051641
"""Convert a dict's keys to strings if they are not."""
keys = list(d.keys())
for key in keys:
# check inner dict
if isinstance(d[key], dict):
value = stringify_keys(d[key])
else:
va... | 5e235823af70107eb96ddde91f7175442b32efb3 | 673,997 |
def make_average(fn, num_samples=100):
"""Return a function that returns the average_value of FN when called.
To implement this function, you will have to use *args syntax, a new Python
feature introduced in this project. See the project description.
>>> dice = make_test_dice(3, 1, 5, 6)
>>> avg_... | 940090cb690a84f2feba6f80b261941d2b71ffa0 | 673,998 |
import tempfile
import os
def get_folder(create=False) -> str:
"""Returns the path to the folder where cached files are stored. """
tdir = tempfile.gettempdir()
cdir = os.path.join(tdir, "lciafmt")
if create:
os.makedirs(cdir, exist_ok=True)
return cdir | 16fba0eb6d9b78ff160f688db2c0403403a0453b | 673,999 |
def heirarchical_data_structure():
"""Heirarchical JSON data"""
return [
{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": True,
"members": [
{
... | 2afa7534acb18c28c1693677f81ac1f2e124b150 | 674,000 |
def print_best_vals(evaluation_dict: dict, best_rmse: float, best_mape: float, best_smape: float,
run_number: int) -> tuple:
"""
print and return new best eval vals
:param evaluation_dict: evaluation dictionary
:param best_rmse: current best rmse
:param best_mape: current best ma... | 35e9da2582c89ee9c6b4cd0bbdba3433cc82f30d | 674,001 |
def format_time(total_seconds, hours_fmt=False, precise=False, hours_pad=True):
"""
Convert total_seconds float into a string of the form "02:33:44". total_seconds amounts
greater than a day will still use hours notation.
Output is either in minutes "00:00" formatting or hours "00:00:00" formatting.
... | ddb0555b78cff794b86bd3c36de971c47c123745 | 674,002 |
def get_channels_number(*, mode: str) -> int:
"""
This function return the numbers of channels given a color mode.
Parameters
----------
mode: str
color mode.
Returns
-------
out: int
number of channels associated with the color mode.
"""
if mode == "YCbCr":
... | 8a7d495d04dd731888083730e94af53e73f51c43 | 674,003 |
def _merge_ranges(ranges):
"""
From a list of ranges (i.e.: list of tuples (start_idx, end_idx)
Produce a list of non-overlapping ranges, merging those which overlap.
:param ranges: list of tuples (start_idx, end_idx)
:return: list of tuples (start_idx, end_idx)
"""
if ranges == []:
return []
r... | 6dd284ccefead6fde61f4d7353264a5ebc1553b2 | 674,004 |
def find_when_entered_basement(text):
"""Find position in text when santa enters basement first time."""
cur_floor = 0
for position, floor_change in enumerate(text, start=1):
cur_floor += 1 if floor_change == '(' else -1
if cur_floor < 0:
return position
return -1 | bb3a5d9949297fdba905e9bd596ad64635ab5861 | 674,005 |
from typing import Iterable
from typing import Tuple
from typing import Dict
from typing import List
def adjacency_list(edges: Iterable[Tuple[str, str]]) -> Dict[str, List[str]]:
"""
Convert a sequence of undirected edge pairs into an adjacency "list".
"""
adj = {}
for e1, e2 in edges:
if... | 269599602a44d78287b67fea3aed381d4580fa69 | 674,006 |
from configparser import RawConfigParser
def compare_section_and_name(fn):
"""
Helper function to test if section captions for conf files ever differ from the name option
Parameters
----------
fn: Filename
"""
config = RawConfigParser()
config.read_file(open(fn))
return [
(... | 78d8678a55ebaa9709048c97d29048cbe1e77b8e | 674,007 |
def get_project_import_quota(connection, id, error_msg=None):
"""Get the amount of space, in MB, that can be used for the Data Import
function for a specific project. This is the default value applied to all
users.
Args:
connection: MicroStrategy REST API connection object
id (string): ... | afb5c93ce12386658af05d3a5783142e5a136fa7 | 674,008 |
import string
import random
def randStr(chars = string.ascii_uppercase + string.digits + string.ascii_lowercase, N=42):
"""Generate a random string of len 42 to spoof a reset token"""
return ''.join(random.choice(chars) for _ in range(N)) | ed7d5cfc72a7d7e1e5e269c4ba9af76f2c208408 | 674,009 |
import hashlib
def get_sha1_hash(parts):
"""Gets a normalized sha1 hash LDRPart objects"""
sp = []
for p in parts:
sp.append((p, p.sha1hash()))
sp.sort(key=lambda x: x[1])
shash = hashlib.sha1()
for p in sp:
shash.update(bytes(p[1], encoding="utf8"))
return shash.hexdigest(... | 680664005d4898d19fdefa8950115c28b5829125 | 674,010 |
def _merge(*parts):
"""
Utility function to merge various strings together with no breaks
"""
return ''.join(parts) | d6a7b51677d6c2c8adbeeea1c8e8b2d8b878892b | 674,012 |
import argparse
def cmdLineParse():
"""Command line parser."""
parser = argparse.ArgumentParser(description='Run ISCE 2.3.2 topsApp')
parser.add_argument('-i', type=str, dest='int_s3', required=True,
help='interferogram bucket name (s3://int-name)')
parser.add_argument('-d', ty... | 93a2770f605a82024b03728273bc2f6d4636021e | 674,013 |
def parse_sensors(configuration):
"""
Bake the sensors array to a dict where the telldus id is
the key for easier parsing later on.
"""
result = {}
for sensor in configuration["my_sensors"]:
result[sensor["id"]] = sensor
return result | 396db49ce78cd61c8ce450203a11b2d07798156e | 674,014 |
import sys
def load_config(config_file):
""" given a file path returns the configuration as a list for processing
parameters:
config_file (string): path to the configuration file or show-tech to load.
returns:
list: contents of the device's running-config
"""
try:
with open... | bd0a68b3b0a6200c91a048e62a9e4d3453a6f004 | 674,015 |
import os
def get_config_location() -> str:
"""
Finds the config dir for the system
$XDG_CONFIG_HOME > ~/.config > ~/
"""
try:
return os.environ["XDG_CONFIG_HOME"]
except KeyError:
home = os.path.expanduser("~")
config_dir = os.path.join(home, ".config")
if os.... | dd0a02d9244cd3f8cb2c915a7964f06644dd7230 | 674,016 |
def get_egress_lossless_buffer_size(host_ans):
"""
Get egress lossless buffer size of a switch
Args:
host_ans: Ansible host instance of the device
Returns:
total switch buffer size in byte (int)
"""
config_facts = host_ans.config_facts(host=host_ans.hostname,
... | a2bd17d4d8b522f80e4f3749feb29aa63fd80184 | 674,017 |
def update_eval_metric(
model_configs,
metric):
""" Resets evaluation-specific parameters.
Args:
model_configs: A dictionary of all model configurations.
metric: A string.
Returns: A tuple `(updated_dict, metric_str)`.
"""
if "modality.target.params" in model_config... | 805aa15392dc96743b8f1304605d8d4e8eb4e6cd | 674,018 |
def _getRidOfExtraChars(string):
"""Get rid of characters (like whitespace) that complicate string matching
in input string"""
#what are the characters we want to get rid of?
lstOfBadChars = [' ','_',"'"]
#do it using .replace() string function
for i in lstOfBadChars:
string = string.r... | 1583026f207ffb92ffe104d9e34316d4d14533ed | 674,019 |
import argparse
import os
def parse_args():
"""Creates parser and reads args."""
parser = argparse.ArgumentParser(description='Utility to sync exported bookmark files')
parser.add_argument('--bookmark_file', '-b', type=os.path.expanduser,
help='Compare bookmark file to the current ... | 44dcb6e3123549cada98548c5c8419d1a783940b | 674,020 |
import sys
def get_outputs_of_process(proc):
"""
Returns stdout and stderr of the process.
:return: the output on both streams.
:rtype: unicode, unicode
"""
out, err = proc.communicate()
encoding = sys.stdout.encoding
if out is not None:
out = out.decode(encoding)
if err ... | 0779e47bca615e09391c904c120955b3f117aba1 | 674,022 |
def format_nums(number, decimals):
"""
rounds to a number of decimals and if possible makes a integer from float
:param number: input number
:param decimals: decimals to round to
:return: integer or float
"""
if round(float(number), decimals).is_integer():
return int(f"{number:.0f}... | fe51717404ecd569cfcea63a18bcf4aa3f58214f | 674,023 |
import re
def parse_ranges(s):
"""Return a list of (start, end) indexes, according to what is
specified in s. It is up to the client to interpret the semantics
of the ranges.
Samples:
16 [(16, 16)]
1-6 [(1, 6)]
1,3,5-8,99 [(1, 1), (3, 3), (5, 8), (99, 99)]
"""
... | 07ead1aed5b51fcc28bd508a646fb8d34ef7d617 | 674,024 |
def _totuple(a):
"""
Converts a numpy array into nested tuples, so that each row of the array
is a different tuple.
E.g.
a = [ [0 1 2 3]
[4 5 6 7] ]
out = ((0, 1, 2, 3), (4, 5, 6, 7))
"""
try:
return tuple(_totuple(i) for i in a)
except TypeError:
return a | 518d4a089e449f7e908b2327c98a3588839e4089 | 674,026 |
import csv
def _get_digikey_parts_set(path):
"""
Reads in the digikey part dictionary and yeilds each part.
"""
all_parts = set()
with open(path, "r") as csvinput:
reader = csv.reader(csvinput)
for line in reader:
(part, url) = line
all_parts.add(part)
r... | 52468ff37e73ba38d971e52efdd59058c5e8c783 | 674,027 |
import codecs
import json
def json_read(filename, **json_options):
""" Read an object from a json file ``filename`` """
with codecs.open(filename, 'r', 'utf8') as f:
return json.load(f, **json_options) | 96b7daa4f6f8a909461348d930f0bd86532b54e4 | 674,028 |
from pathlib import Path
def some_dir(tmp_path) -> Path:
"""Folder with some data, representing a given state"""
base_dir = tmp_path / "original"
base_dir.mkdir()
(base_dir / "empty").mkdir()
(base_dir / "d1").mkdir()
(base_dir / "d1" / "f1").write_text("o" * 100)
(base_dir / "d1" / "f2").... | 1fa99d40b102107d39df18f5cbd1337a3163d645 | 674,029 |
def protein_split_dataset(df, fold_seed, frac):
"""
Split by protein
"""
_, val_frac, test_frac = frac
gene_drop = df['Target Sequence'].drop_duplicates().sample(frac=test_frac, replace=False,
random_state=fold_seed).values
test = d... | 833ff621e26a1b645049001dcd08bb94403aee46 | 674,030 |
import subprocess
def ref_exists(ref):
"""Checks if a git ref exists or not using git show.
Args:
ref: the ref to be checked
Returns: True if the ref exists, false otherwise
"""
try:
subprocess.check_output(["git", "show", ref], universal_newlines=True)
except subprocess.CalledProcessError:
return False... | bb3f680b1c7b6c6c7196d56f8599af02e73a38a0 | 674,031 |
def DEFAULT_REPORT_SCRUBBER(raw):
"""Default report scrubber, removes breakdown and properties."""
try:
del raw['breakdown']
del raw['properties']
except KeyError:
pass
return raw | 9fddb184a7ad91172f0dc64d1df3ac968362c6e5 | 674,032 |
def list_of(cls):
"""
Returns a function that checks that each element in a
list is of a specific type.
"""
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l) | 0dc40dc8ec4176f0cd30c508a837aeba5d073e03 | 674,033 |
def get_short_module_name(module_name, obj_name):
""" Get the shortest possible module name """
parts = module_name.split('.')
short_name = module_name
for i in range(len(parts) - 1, 0, -1):
short_name = '.'.join(parts[:i])
try:
exec('from %s import %s' % (short_name, obj_nam... | 407b2cb06653a340764acaee1e736dcc547b1ad1 | 674,034 |
def compare_pval_alpha_tf(p_val, alpha=.05):
""" this functions tests p values vs our chosen alpha returns bool"""
status = None
if p_val > alpha:
status = False
else:
status = True
return status | c4e301e951ab07dc7d3256e8485293c9faf0e22b | 674,035 |
def _task_info(clazz):
"""
from a provided class instance extract task metadata.
This will error if any of the expected fields of the task are missing.
:param clazz: class object you need metadata for
:return: a metadata dictionary
"""
params = []
for e in clazz.parameters:
param... | 66132749b9e30c9b103f39159c0c48c7f47930e0 | 674,036 |
import hashlib
def sha1sum(filename):
"""return the sha1 hash of a file"""
with open(filename, mode='rb') as f:
d = hashlib.sha1()
while True:
buf = f.read(8192)
if not buf:
break
d.update(buf)
return d.hexdigest() | 5eda7df935cd12e827c1e340ea77143a34f4575a | 674,037 |
def get_tokens_from_node(node, result=None):
"""Return the list of Tokens in the tree starting at node."""
if result is None:
result = []
for dtr in node.dtrs:
if dtr.isToken():
result.append(dtr)
get_tokens_from_node(dtr, result)
return result | ff7269b6d042b8d565cfff4ecd30b9d24ae56a91 | 674,038 |
import re
def parse_string_to_int_tuples(tuples):
""" parse a string to tuples, while the string is:
(x, x, x, x), (x, x)...
"""
tuple_list = re.findall('[(](.*?)[)]', tuples)
ret = []
for i in tuple_list:
int_shape = []
shape = i.strip().split(',')
for j in shape:
if j:
int_... | 642f504dda665c062fac59a08be1964c4dced602 | 674,040 |
import os
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
# pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
pipe = os.popen(cmd + ' 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return... | e630b76367fdbb014ab8390eb8478942b43ddd81 | 674,041 |
import sys
import pathlib
def read_source(source=None):
""" Read the data from `source` and return the input as string. """
if source is None:
text = sys.stdin.read()
else:
path = pathlib.Path(source)
if path.exists():
text = path.read_text()
else:
... | 760e3d5ca10b4ec7e8263ddfdc68b53677972f22 | 674,042 |
import torch
import math
def positionalencoding3d(d_model, length, height, width):
"""
:param d_model: dimension of the model
:param length: length of the positions
:param height: height of the positions
:param width: width of the positions
:return: d_model*length*height*width position matrix
... | 6f1954fed67733b8fcb2d208e9eaaa8f7e0d7367 | 674,043 |
import requests
from bs4 import BeautifulSoup
def get_url_from_character_page(url_IDMB,THUMBNAIL_CLASS="titlecharacters-image-grid__thumbnail-link"):
"""
Gets url of image viewer of a serie pictures on IMDB (e.g. https://www.imdb.com/title/tt0108778/mediaviewer/rm3406852864)
Given the url of a character o... | b5dfac0c28ca476e860149e6920cd96fbc419ba0 | 674,044 |
def fibonacci(n, memo = {}):
"""
@details First n stack calls on first branch.
O(n) space for memo. By induction, when unwinding one step "up" in call
stack, the memo can provide turn value for next branch immediately. Thus,
O(n) time.
"""
# Uncomment to see memo.
#print(memo)
i... | dcc7b0b04fcc00dc0cb534fdaee72f0c5d3103c9 | 674,045 |
def leanlauncher_main_menu():
"""
Display a list of selections for the user to choose on the main menu,
and allows the user to choose which one they want.
Returns:
Int corresponding to the action desired.
"""
print("""
Choose one of the following:
1. Launch Minecraft (-WIP-)
2. Launch Minecraft Offli... | 1a2f665229f532718b8fcaf870398b5529e46fcb | 674,047 |
def get_orders_list(orders_dict):
"""Returns orders list from orders dict"""
return orders_dict.get('orders') | 12c6eb7dc8cd774b265bf0e1dd3b7f21a1d52f0b | 674,048 |
def _generate_anchor_configs(min_level, max_level, num_scales, aspect_ratios):
"""Generates mapping from output level to a list of anchor configurations.
A configuration is a tuple of (num_anchors, scale, aspect_ratio).
Args:
min_level: integer number of minimum level of the output feature pyramid.
... | d0bfd58b012965ec42d067c2878d6f1c9f4f35e9 | 674,049 |
import numpy
def note(frequency, length, amplitude=1, sample_rate=44100):
"""
Generate the sound of a note as an array of float elements.
"""
time_points = numpy.linspace(0, length, length*sample_rate)
data = numpy.sin(2*numpy.pi*frequency*time_points)
data = amplitude*data
data=data.resha... | b4396d75b350fd077ef8e5a4d96bf876d0411eb1 | 674,050 |
import copy
def sequences_add_end_id_after_pad(sequences, end_id=888, pad_id=0):
"""Add special end token(id) in the end of each sequence.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
end_id : int
The end ID.
pad_id : int
... | fe03c11a2e583b2bc5be413cda0f632387a763f3 | 674,051 |
import sys
def get_naked_class(cls: type) -> type:
"""
Return the given type without generics. For example, ``List[int]`` will
result in ``List``.
:param cls: the type that should be stripped off its generic type.
:return: a type without generics.
"""
# Python3.5: typing classes have __ext... | fa0021c87d5bc9bef0bb70023ae6c1c32bce8cac | 674,052 |
import requests
def request_with_local(url):
"""通过本机ip直接获取请求,访问失败将抛出异常"""
return requests.get(url).text | 8d33c5694a8b557420816bf8ff5cbe9eced4789b | 674,053 |
import sqlite3
import typing
def get_robot_types(cursor: sqlite3.Cursor) -> typing.List[dict]:
"""Gets all robot types from the db
:param cursor: [description]
:type cursor: sqlite3.Cursor
:return: [description]
:rtype: typing.List[dict]
"""
return cursor.execute(
"SELECT id, nam... | 8aa21cebf8211ecaf8093a3d76e3bbfe48760ee5 | 674,054 |
def freeParameters(self):
"""
Roadrunner models do not have a concept of "free" or "fixed"
parameters (maybe it should?). Either way, we add a cheeky method
to the tellurium interface to roadrunner to return the names
of the parameters we want to fit
"""
return ["k2", "k3"] | 49db4cc394efbc27e52324c7de139e071df40473 | 674,055 |
import os
def input_file(path):
"""Check if input file exists."""
path = os.path.abspath(path)
if not os.path.exists(path):
raise IOError('File %s does not exist.' % path)
return path | 067c0c4c00e1fc31dc2fd1f2f907177b740b04e8 | 674,057 |
import numpy
def calc_ttheta_phi_by_gamma_nu(gamma, nu, flag_gamma: bool = False, flag_nu: bool = False):
"""See the documentation module "Powder diffraction at constant wavelength".
"""
s_ga, c_ga = numpy.sin(gamma), numpy.cos(gamma)
s_nu, c_nu = numpy.sin(nu), numpy.cos(nu)
ttheta = numpy.arcco... | 32dba57cd1c6921aa02452408d86da9582b658aa | 674,058 |
def find_evaluation_steps(accumulation_steps, goal=18):
"""
Compute the evaluation steps to be a multiple of accumulation steps as close possible as the goal.
Args:
accumulation_steps: (int) number of times the gradients are accumulated before parameters update.
Returns:
(int) number of ... | de0b9ac2794021aea9381446940c0f9e7315fae7 | 674,059 |
def default_unit_conversion_factor():
"""
Generate a dictionary of conversion factors for several unit-prefixes.
Returns
-------
Dictionary :
Conversion factors (values) for several unit-prefixes (keys).
Example
-------
{'g/L': 1., 'mg/L': 0.001, 'μg/L': 1e-6}
"""
# un... | 8a3e5795da54b2f81849deb07ddd49be4318e4a4 | 674,062 |
def drop_and_rename(dat, col_name1, col_name2, col_change_dict):
"""
Drop two certain columns change name of last one to constant name
"""
dat = dat.drop([col_name1, col_name2], axis = 1)
return dat.rename(columns = col_change_dict) | 36cff3f2c26af75fadb143e50529f59334006ef7 | 674,064 |
import socket
def _getfqdn(rfam, n=None):
"""INTERNAL: return FQDN given address family (and name)
may raise socket.gaierror"""
p = 80
if n is None:
n = socket.gethostname()
rtype = socket.SOCK_STREAM
for (fam, type, proto, cname, addr) in socket.getaddrinfo(n,p,rfam,rtype):
... | f930d9744ffc9148ae0740942521931053aa0318 | 674,065 |
from typing import Any
import asyncio
def async_test(coro: Any) -> Any:
"""Async test wrapper."""
def wrapper(*args: str, **kwargs: int) -> Any:
loop = asyncio.new_event_loop()
try:
return loop.run_until_complete(coro(*args, **kwargs))
finally:
loop.close()
... | fe6c8121cf6b5274f38d1f566ed684e1aa25918b | 674,066 |
from typing import Sequence
from typing import Dict
def get_tagged_secrets(secrets_manager, secrets_tags: Sequence[str]) -> Dict[str, str]:
"""
Return a dictionary of AWS Secrets Manager names to arns
for any secret tagged with `secrets_tag`.
"""
secrets = {}
paginator = secrets_manager.get_p... | 14637ff1f76e2db5e857d56ce328d3cc6c165d67 | 674,067 |
def usechangesetcentricalgo(repo):
"""Checks if we should use changeset-centric copy algorithms"""
if repo.filecopiesmode == b'changeset-sidedata':
return True
readfrom = repo.ui.config(b'experimental', b'copies.read-from')
changesetsource = (b'changeset-only', b'compatibility')
return readf... | cd3d1d2a1566b24947caf0369d0e09550673ae0b | 674,068 |
import pwd
import os
def GetProvisioningProfilesDir():
"""Gets the provisioning profiles dir in current login user."""
home_dir = pwd.getpwuid(os.geteuid()).pw_dir
path = os.path.join(home_dir, 'Library/MobileDevice/Provisioning Profiles')
if not os.path.exists(path):
os.makedirs(path)
return path | b7b2070b6135424842f4703cdfe7d2f24de2d01b | 674,069 |
def can_zip_response(headers):
"""
Check if request supports zipped response
:param headers: request headers
:return:
"""
if 'ACCEPT-ENCODING' in headers.keys():
if 'gzip' in headers.get('ACCEPT-ENCODING'):
return True
return False | 26021f2778ced4174aae29850a42ea95ea32172a | 674,070 |
from typing import Optional
from typing import Dict
from typing import List
def get_mock_aws_alb_event(
method,
path,
query_parameters: Optional[Dict[str, List[str]]],
headers: Optional[Dict[str, List[str]]],
body,
body_base64_encoded,
multi_value_headers: bool,
):
"""Return a mock AWS... | 63c87da158285482fa242fc36db64865d4355e5d | 674,071 |
def get_artist_names(artist_database, artist_id):
"""
Return the list of names corresponding to an artist
"""
if str(artist_id) not in artist_database:
return []
alt_names = [artist_database[str(artist_id)]["name"]]
if artist_database[str(artist_id)]["alt_names"]:
for alt_name... | 7cac34db693418650530c4551bc52742cd634173 | 674,072 |
import os
def find_testfile(path=None):
"""Recursively find the tests description file."""
if not path:
path = os.path.dirname(os.path.realpath('.'))
if not os.path.isdir(path):
raise ValueError(f"Path name '{path}' is not a directory")
for filename in ['baygon', 't', 'test', 'tests'... | 0550fb54f1531b9b310300769ba73c7894e0bc12 | 674,073 |
def remove_unknowns(x, y):
"""
Remove word pairs from the results where one or two word embedding weren't found.
Args:
x (list): List of similarity scores assigned by humans.
y (list): List of similarity scores assigned by the system.
Returns:
x (list): Purged list of similarity scores assigned by humans.
... | 7444a2a6351d557624ebca9f7d081ead5eeefedb | 674,074 |
def containsAll(str, set):
"""
Checks if a given string contains all characters in a given set.
:param str: input string
:type: string
:param set: set if characters
:type: string
:rtype: boolean
"""
for c in set:
if c not in str: return False
return True | 0d167d9901f9f8b7ace23d58724b87b29af89c48 | 674,075 |
def eigsrt(eigv, x, neq):
"""
Sort the eigenvalues in ascending order
"""
#
for i in range(neq-1):
k = i
p = eigv[i]
# search for lowest value
for j in range(i+1, neq):
if abs(eigv[j]) < abs(p) :
k = j
p = eigv[j]
# ... | 4bfc1793ed17ca08a6ef3214c981a2d881af3575 | 674,076 |
def get_message_id(message_response):
"""
Получает ID сообщения от пользователя в рамках диалога
:param message_response: Структура сообщения
:return: ID сообщения
"""
return message_response['object']['message']['id'] | 7f48c7838d89fa798457acc3a03efa36706eea17 | 674,077 |
import os
import sys
def readFileToCorpus(f):
""" Reads in the text file f which contains one sentence per line.
"""
if os.path.isfile(f):
file = open(f, "r") # open the input file in read-only mode
i = 0 # this is just a counter to keep track of the sentence numbers
corpus = [] # ... | 97082a83ce09720b479221028d352d36337ffcab | 674,078 |
import os
def file_exists(fname):
"""Check if a file exists and is non-empty.
"""
return os.path.exists(fname) and os.path.getsize(fname) > 0 | 666ead26b2232ecaf2b35fb150b7d944ea3276ea | 674,079 |
def format_artist_rating(__, data):
"""Returns a formatted HTML line describing the artist and its rating."""
return (
"<li><a href='{artist_tag}/index.html'>{artist}</a>" " - {rating:.1f}</li>\n"
).format(**data) | 49ebafaff169662f80ff80f2884981ca029d9f08 | 674,081 |
import os
def Path(dirname:str, filename:str) -> str:
""" Joins a directory and filename to create a full path to a file. """
return os.path.join(dirname, filename) | ba4f3986a28ff523299892f8abeeadaf05f51c88 | 674,083 |
def _human_list(listy):
"""
Combines a list of strings into a string representing the list in plain
English, i.e.
>>> _human_list(["a"])
"a"
>>> _human_list(["a", "b"])
"a and b"
>>> _human_list(["a", "b", "c"])
"a, b and c"
"""
if len(listy) == 1:
return listy[0]
... | 4eeae7264368d2c0da33df319a8574cbf17a0bfd | 674,085 |
import hashlib
def _hash_file(fpath, algorithm="sha256", chunk_size=65535):
"""Calculates a file sha256 or md5 hash.
# Example
```python
>>> from keras.data_utils import _hash_file
>>> _hash_file('/path/to/file.zip')
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b8... | abc4874c9284a0e00392cc7668ce9d94e64e94ee | 674,086 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.