content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import Union
from typing import Tuple
def linear_search(arr: List[Union[int, float, str]], ele: Union[int, float, str]) -> Union[Tuple[bool, int], Tuple[bool, None]]:
"""Linear search algorithm
Args:
arr (List[Union[int,float,str]]): array list to search
el... | 857648c19cd0438c381bb63e3a08209e0aee8de5 | 639,454 |
def _calculate_total_mass_(elemental_array):
"""
Sums the total weight from all the element dictionaries in the elemental_array after each weight has been added (after _add_ideal_atomic_weights_())
:param elemental_array: an array of dictionaries containing information about the elements in the system
... | 1c02c9ecbd09e7a3e74c7207dc435ee4e9ebbcf7 | 639,455 |
def _cleave(
sequence,
sites,
missed_cleavages,
min_length,
max_length,
semi,
clip_nterm_met,
):
"""Digest a protein sequence into its constituent peptides.
Parameters
----------
sequence : str
A protein sequence to digest.
sites : list of int
The cleavag... | 10660bf01ba6ca2fa012b7dbef86031fad1352c4 | 639,456 |
def find_link_href(links: list, rel: str) -> str:
"""Extract link href by rel for linkdto instances."""
return next(l for l in links if l.rel == rel).href | 952d4d9c81c40a5ae31b0f4881e0d46cd9b7f869 | 639,457 |
def is_odd(num: int) -> bool:
"""Returns true when num is odd
Added in version: 0.1.0
"""
return num % 2 != 0 | eef3c5bccbe1da9bace69958e2d1d06cb81531a7 | 639,458 |
def base_url(host, port):
""" base url for unit test invocation of api """
return f"http://{host}:{port}" | b457c3d0a0e6566979a4c6d030cd77f6a89ee559 | 639,459 |
import os
def create_subdir(path: str) -> str:
""" Creates the folder directory
Args:
path (str): the folder to be created
Returns:
str: the path string
"""
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
return path | d0441e4f3f57e479bdcfdedb7615bb586ea360f9 | 639,460 |
def mergedicts(dictionary1, dictionary2):
"""
merges merge_dict into main_dict
"""
output = {}
for item, value in dictionary1.iteritems():
if item in dictionary2:
if isinstance(dictionary2[item], dict):
output[item] = mergedicts(value, dictionary2.pop(item))
... | ca7ec8e8eb828c53459cb566464852e27708deac | 639,461 |
def calculate_weights(errs):
"""
Revers weights calculation.
Weight of estimator established this way:
1) calculate proportion of error for estimator in comparison to sum of errors of estimators
2) take power of -1 from the proportion
3) calculate linear equation (a_1 + a_2 +...+ a_n)x=1, where ... | e5aee1b896287b1ccb0704c7264ed116782898be | 639,462 |
def date_mapper(date: float):
"""
map all dates from 20140101 to increasing naturals every
month
"""
date /= 100
month = int(date) - int(date / 100) * 100
date /= 100
year = int(date) - 2014
return year * 12 + month | 666264dc4d08c3d4f3e4e915d4ed7ee515ea74c4 | 639,463 |
def _no_spaces(string, replace_with='_'):
"""
Remove whitespace from a string, replacing chunks of whitespace with a
particular character combination (replace_with, default is underscore)
"""
return replace_with.join(string.split()) | 3b37de82d840b1057c5d9ad716a32b9fdeddcd12 | 639,464 |
def desc(x):
"""Return array sorted in descending order."""
return x.sort_values(ascending = False).reset_index(drop = True) | 7da423a7060bef15e57b55d6d527f0cc6d946ee1 | 639,465 |
def fuzzy_search(needle, haystack):
"""
判断是否符合模糊匹配的规则,实测性能不如 viml 的实现
"""
flag = 1
tlen = len(haystack)
qlen = len(needle)
if qlen > tlen:
return 0
elif qlen == tlen:
if needle == haystack:
return 1
else:
return 0
else:
needle_l... | 95501be502d809521959502b2aac58b686a3cc1a | 639,466 |
import os
import shutil
import sys
def command_copytree(args):
"""
Copy one or more source directory(s) below a destination directory.
Parts of the destination directory path are created if needed.
Similar to the UNIX command: 'cp -R srcdir destdir'
"""
for srcdir in args.srcdirs:
base... | 2a53c9da13af939ff2cb77c269b8dd34ca91c9bd | 639,467 |
def set_swfac(name: str) -> float:
"""
name is cfmt.vocalfont.name
:param name:
:return:
"""
swfac = 1.0
if name == "Times-Roman":
swfac = 1.00
if name == "Times-Bold":
swfac = 1.05
if name == "Helvetica":
swfac = 1.10
if name == "Helvetica-Bold":
... | e7a28dbc5e9a7bb183d68029f20f8a66eed75616 | 639,468 |
import requests
def get_apod_data(api_key: str, download: bool = False, path: str = ".") -> dict:
"""
Get the APOD(Astronomical Picture of the day) data
Get your API Key from: https://api.nasa.gov/
"""
url = "https://api.nasa.gov/planetary/apod"
return requests.get(url, params={"api_key": api_... | 11c85338d5d1bc6020976b1553bcdd2a612376f3 | 639,469 |
import re
def _read_doc_text_strings(data):
"""Use a heuristic to read in the document text. This is used as a
fallback if reading the text with libreoffice fails.
@param data (str) The read in Office file (data).
@return (tuple) A 2 element tuple where the 1st element is the
strings grabbed fro... | 9e68b33c74f522e6d1d6c85f3de272f0bc034e02 | 639,470 |
def __discretizePoints(x,cut_points):
"""
Function to discretize a vector given a list of cutpoints.
This function dicretizes a vector given the list of points to cut
:param x: a vector composed by real numbers
:param cut_points:a list with the points at which the vector has to be cut
:return: A... | d301a1429f0b79c951fe1b330aef509e46c269ea | 639,471 |
def get_total_number(record_list):
"""获取总数"""
num = 0
for _, v in record_list.items():
num += v
return num | de99881ba5dd35928ea271558c8801e760b1f5ea | 639,472 |
import numpy
def gen_fock_1p(h1, cholvec, rdm1a, rdm1b):
"""Generalised Fock matrix for 1-particle excitation.
F[s,p,q] = < c_{ps} {H,c_{qs}^+} >
"""
nmo = rdm1a.shape[0]
assert len(cholvec.shape) == 3
assert cholvec.shape[1] * cholvec.shape[2] == nmo*nmo
nchol = cholvec.shape[0]
# C... | 397b2e50cc6f1dba4265c1e6d9f38d6c7ef6cce8 | 639,473 |
import csv
def load_cand_genes_file(file_name, format=1):
"""
Loads a candidate gene list from a csv file...
"""
f = open(file_name, "r")
#print(f.readline())
reader = csv.reader(f)
tair_ids = []
gene_names = []
if format == 1:
for row in reader:
tair_ids.append... | bc4cd56afd9ee459e463030ff80115f7c0ef4479 | 639,474 |
import time
def timestamp():
"""
Return our standard timestamp, the unix epic seconds, accurate to 4 decimal places.
:return: str
"""
return float('{0:.4f}'.format(time.time())) | bc7405534a8dfc7450fd98ba05b8e7eab8cf9fee | 639,475 |
import json
import logging
def parse_monitoringlist_positions(args, str_name="monitor_coords",
list_name="monitor_list"):
"""Loads a list of monitoringlist (RA,Dec) tuples from cmd line args object.
Processes the flags "--monitor-coords" and "--monitor-list"
NB This is ... | 74a4487346a87805a44566bd20077677e7b47079 | 639,476 |
import hashlib
import os
def verify_hashes(packages, archives, hash_alg='md5'):
"""
Loop through all given package objects and compare the hashes with hashes in package archive.
Any hash that is supported by Python's hashlib can be used for comparison.
In the interest of speed, files are iterated in... | 3d279ff52e399e5b85a166c206536f5efbc8899a | 639,477 |
import time
def timestamp():
"""
得到当前时间戳,16位十进制数
:return: 16 位十进制时间戳
"""
return int(round(time.time() * 1000000)) | c2a857152b1a41a5d90972f1f1b1068f50169ecf | 639,478 |
from typing import Dict
from typing import Any
def __get_cumulative_cases_count(data_json: Dict[str, Any]) -> int:
"""
Returns the cumulative number of cases stored in the given data point.
"""
try:
return data_json["cumCasesByPublishDate"]
except KeyError:
return 0 | 4e6ceef73880fe3430c92bc5a43deef545b01985 | 639,479 |
def python_parser_only(request):
"""
Fixture all of the CSV parsers using the Python engine.
"""
return request.param() | b5076611859e6acba7535c44816714dac6a2cbbb | 639,480 |
import glob
import os
def maj_min_to_blk(major, minor):
"""
Returns the block device name to the major:minor numbers in the param.
:param major:
The major number of the device
:param minor:
The minor number of the device
:returns:
Block device name.
:rtype:
``s... | 0586106b78356ac66d9ae2865af516d987b43740 | 639,481 |
def recover_escape(text: str) -> str:
"""Converts named character references in the given string to the corresponding
Unicode characters. I didn't notice any numeric character references in this
dataset.
Args:
text (str): text to unescape.
Returns:
str: unescaped string.
"""
... | 7bf5aa165f7105a4fbfa57dc87de5da520f43705 | 639,482 |
def greetings():
"""This allows for testing server health using minimal resources"""
return 'Hello World!' | fe4a21031b4c05afbf78a4ff861093ff8ac94e7f | 639,485 |
def load(fn):
"""Ensure that class will be initialized before method call."""
def inner_wrapper(self, *args, **kwargs):
self.load()
return fn(self, *args, **kwargs)
return inner_wrapper | cdb02c5b547294d05166d01beab2657d16e912a4 | 639,486 |
def compareTo (intValue1, intValue2):
"""Compares two integers.
Assignment:
This functions returns -1 if intValue1 is less than intValue2,
returns 1 if intValue1 is greater than intValue2, or returns 0 if
intValue1 is equal to intValue2.
:param intValue1: The first integer to be compared
:... | 332b0aae2e28365bab964e404a63442433b23df7 | 639,487 |
def direction_decision(i,acc_dir,west_names,east_names,acc_info_full):
"""
Check whether an input column (acc_dir) from the full accident
dataframe (acc_info_full) contains informative information
with regard to direction
"""
# Replace such inputs as 'I-84' with 'I 84', and split item... | 6c4f7f9ab835597b98d8ca5899f3a844efcd7f8b | 639,489 |
from numpy.linalg import pinv
def CFS(Phi, y_train):
""" Return weights of linear regression using closed form solution.
Args:
Phi -- N x M -- float: Design matrix.
y_train -- N -- float: Labels for training.
Returns:
w -- M -- float: Updated weights.
"""
# C... | 39bc3724e6f0c1840c91270b6c83e56c4d471e1d | 639,490 |
def shape_logits(raw_logits):
"""
Shape logits for logsumexp.
"""
return raw_logits.view(raw_logits.shape[0], -1, 2) | 7bfe1c6cdcdb5f3373622d4d837daede8d66f24e | 639,492 |
def pc_settings_filename():
"""
:return: The settings file for PackagesManager
"""
return 'PackagesManager.sublime-settings' | a22246ebe43322755423a123fbb17b3347456873 | 639,494 |
def get_copy(o, copy):
"""Returns copy of object."""
if copy:
return copy(o)
else:
return o | 613ea1f268bad62418970360dd966653aefe2688 | 639,495 |
def games_list(self, _):
"""
:return: list
"""
lst = [{
'name': self.temp.games[i].name,
'creator': self.temp.games[i].creator,
'players': len(self.temp.games[i].players),
'slots': self.temp.games[i].slots,
'config': self.temp.games[i].config
} for i in self.t... | 2f49c195f5daf5ca5a736b42e4bfc829181ecd6d | 639,496 |
def get_ip_context(data):
"""
provide custom context information about ip address with data from Expanse API
"""
geo = {}
if len(data.get('locationInformation', [])) > 0:
if (data['locationInformation'][0].get('geolocation', {}).get('latitude') is not None
and data['locationInform... | ee8a16f18d778ff3d46903649c318a47c3563424 | 639,497 |
from typing import Dict
from typing import Tuple
def calc_nsplits(chunk_idx_to_shape: Dict[Tuple[int], Tuple[int]]) -> Tuple[Tuple[int]]:
"""
Calculate a tiled entity's nsplits.
Parameters
----------
chunk_idx_to_shape : Dict type, {chunk_idx: chunk_shape}
Returns
-------
nsplits
... | ac241f1dc6616830c9bebf0ac0638e6d0fa6ce71 | 639,498 |
import random
def crossover(chromosome1, chromosome2):
"""
Funcao para realizar o crossover entre dois cromossomos
:param: chromosome1 - cromossomo pai
:param: chromosome2 - cromossomo mae
:return: new_chromosome1 - primeiro filho gerado no crossover
:return: new_chromosome... | eff26f95e4f389cf23818d2ac44d8224d4baa4dd | 639,500 |
import typing
def IndentList(num_spaces: int, strings: typing.List[str]) -> typing.List[str]:
"""Indent each string in a list of strings by a number of spaces.
Args:
num_spaces: The number of spacces to indent by. Must be greater than or
equal to zero.
strings: The list of strings to indent.
... | 277e212089cd17f1950239c42557e27918ccac2a | 639,501 |
def overlapped_slices(bbox1, bbox2):
"""Slices of bbox1 and bbox2 that overlap
Parameters
----------
bbox1: `~scarlet.bbox.Box`
bbox2: `~scarlet.bbox.Box`
Returns
-------
slices: tuple of slices
The slice of an array bounded by `bbox1` and
the slice of an array bounded ... | b76ed091489b154db145d7f35f13bb90baedd840 | 639,502 |
import math
def __uto__(hf, han, tempd, rti_m,
rto_m, rco_m, rci_m,
rwb_m, ke_wmc, kcem_wmc, kt_wmc):
"""
Общий коэффициент теплопередачи, состоящий из нескольких частей
:param hf: конвективный коэффициет теплоотдачи в НКТ, Ватт / м2 / С
:param han: конвективный коэффициет теп... | 377ef00b0ec2e58617b369dece4fe72abf43d29b | 639,503 |
import sysconfig
def get_openrk_object_name():
"""Returns the name of the main openrk shared library object"""
ext_suffix = sysconfig.get_config_var('SOABI')
if ext_suffix is None:
filename = '_openrk.so'
else:
filename = '_openrk.{0}.so'.format(ext_suffix)
return filename | 275e256db4d1d7495f185b35f1d6ef8d1afb7920 | 639,505 |
import re
def get_glyph(text):
"""
get the glyph from text
Return a tuple of (glyph, font) from the provided text. raise an error if one of them does not exist
:param text: The text to transform (e.g. "fa fa-folder")
"""
# split the icon name to find the name inside
m = re.match(r"^(fab... | 397980cf0bbd5178ce1cb097b1ba550dac5a87ad | 639,506 |
import os
def protected_path(path):
"""
Take a path, and if the file/dir exist pass back a protected path
(suffixed).
Returns:
string = new file path
Example:
>>> mypath = '/tmp'
>>> new_path = helpers.protected_path(mypath)
>>> new_path
'/tmp.0'
"""... | 548eb5467a9a4766bde3e7881084c2325ddacc0f | 639,507 |
def remove_possible_title_from_text(
text: str, title: str, min_title_length: int = 3, overlap_ratio: float = 0.5
) -> str:
"""
Remove title from text document.
:param text:
text string
:param title:
title to remove
:param min_title_length:
minimum length of title to rem... | 663d4e7ebceea71efb49ec457322f74f6ea43d37 | 639,508 |
def format_list(list1, fmt = '%16s', delimiter = ","):
"""
format list of numbers to string.
delimiter defaults = ','
"""
string1 = delimiter.join(fmt % h for h in list1) + '\n'
return string1 | 65a341b59f27867c7da069314b37dbd2cd95fa1b | 639,512 |
import os
import pickle
def get_local_config_param(key, force_update=False):
"""
Read the local config file to find a parameter. If it's not found, ask for
it and store it for the future.
:param key: What to get
:param force_update: Ask the user regardless of if it's already been stored,
and... | 1207d2b1087f8c0f1a5f7e2c34d445993e583064 | 639,513 |
from typing import List
def piecewise_volume_conversion(
ul: float, sequence: List[List[float]]) -> float:
"""
Takes a volume in microliters and a sequence representing a piecewise
function for the slope and y-intercept of a ul/mm function, where each
sub-list in the sequence contains:
... | 87dc40bd9d09e95081ab6ed49ea550a8e9b59c9e | 639,514 |
from typing import Any
def add_price_in_dollars(row: Any) -> float:
"""
Calculate the price in dollars by converting the value of the 'priceInCents` to dollars.
Args:
row: The pandas row to be analysed
Raises:
N/A
Returns:
dollars: The price in dollars, calculated from the... | 296b0be078f3f084d0dc48f7c51c703662776035 | 639,515 |
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
def get_parser():
"""Get parser object for gen_prob_dist.py."""
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-n",
dest=... | 5d27e06e9cff22383d579c9ed3831c8481d44f34 | 639,516 |
def command_not_found():
"""非关键词回复"""
return u"未识别指令!\n" | af76b9f4abeb25e009682e05c8a3622451cf60ab | 639,517 |
import math
def square_image_shape_from_1d(filters):
"""
Make 1d tensor as square as possible. If the length is a prime, the worst case, it will remain 1d.
Assumes and retains first dimension as batches.
"""
height = int(math.sqrt(filters))
while height > 1:
width_remainder = filters % height
if ... | a39f20e8859dbd22172b4cddc2b59c5a0240b4db | 639,519 |
def filter_per_split(dataset, train=True):
""" Filter samples depending on their split """
return dataset['is_train'] if train else ~dataset['is_train'] | ef68d7bdec9b062027bff0405d4de259dfda64d0 | 639,522 |
def has_dependencies(node, dag):
"""Checks if the node has dependencies."""
for downstream_nodes in dag.values():
if node in downstream_nodes:
return True
return False | 51e31ab6ba283901caeaea7cf1e158b31e3670c2 | 639,523 |
import numpy
def _is_not_skewed(sicd, dimension):
"""
Check if the sicd structure is not skewed along the provided dimension.
Parameters
----------
sicd : SICDType
dimension : int
Returns
-------
bool
"""
if dimension == 0:
if sicd.Grid is None or sicd.Grid.Row i... | 632971f26c77f414bb1b19ccb1d3712bb8ac7e48 | 639,525 |
def pluralize(noun, quantity):
"""
Returns a pluralization of a noun preceded by its quantity by
suffixing a morpheme (limited to the regular plural morphemes
's' and 'es').
:param noun: The noun to be pluralized.
:type noun: str
:param quantity: The quantity of the noun.
:type quantity... | 7c17abff182e5c322b46aece8b8c22b381523a81 | 639,527 |
def count_kmers(seq, k=3):
"""Returns the Count or Frequency of Kmers generated in a sequence"""
# Start with an empty dictionary
counts = {}
# Calculate how many kmers of length k there are
num_kmers = len(str(seq)) - k + 1
# Loop over the kmer start positions
for i in range(num_kmers):
... | 639a7b1ca4298541a4afc370a6f66006d207352e | 639,529 |
def static_vars(**kwargs):
"""
Custom decorator to allow declaration of static variables like this:\n
@static_var(variable = 0)\n
def foo(parameters):\n
foo.variable += 1
"""
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
retu... | 4d7b3c7e8be75bc094007885fca40a6ad74dfe84 | 639,530 |
import sys
def get_custom_platform():
"""
This method gets the custom name of platform ( operating system)
:return: ``name of the operating system``
:rtype: ``string``
"""
_platform = sys.platform
if _platform.startswith('linux'):
platform = 'linux'
elif _platform.startswith('d... | 23b40424266aa64428fbcb5e1409477d9aeed99b | 639,531 |
def margcond_str(marg, cond):
""" Returns a name from OrderedDict values in marg and cond """
marg = list(marg.values()) if isinstance(marg, dict) else list(marg)
cond = list(cond.values()) if isinstance(cond, dict) else list(cond)
marg_str = ','.join(marg)
cond_str = ','.join(cond)
return '|'.join([marg_st... | 09fd81711a530a9a12d3ce9140663f4ad354a0b8 | 639,532 |
import re
def realname(module_name):
"""
Return the real name of a module. The real name of a modules
is in lower snake_case.
Transform a CamelCase name into snake_case name.
"""
reg_first = re.compile(r'(.)([A-Z][a-z]+)')
reg_all = re.compile(r'([a-z0-9])([A-Z])')
s1 = reg_first.sub(r... | 33982291832b0ab30237003c80c9b0a4e2aede68 | 639,533 |
def init_model(ratios, sizes):
"""Initialize the hconstant parameter for each word
and populate the model dict
ratios: the ratios dict, nothing new
sizes: the sizes dict
returns: the updated ratios dict & the initialized model
"""
model = {}
for word in ratios.keys():
ratios... | 9cb5729477e41037eff2673e30514d1c9b487a86 | 639,535 |
def is_callback(func):
"""Check if function is callback."""
return "_pyhap_callback" in getattr(func, "__dict__", {}) | dc74cbb3ba12f836227564ded39fa23102219142 | 639,536 |
def has_points(user, points):
"""Returns True if the user has more than the specified points."""
return user.get_profile().points() >= points | 2907a3dd31ff36adc1010d91c9bcab5db0f1b987 | 639,537 |
def get_fig_size(ratio=None, scale=None):
"""Get size of figure given a ratio and a scale.
Parameters
----------
ratio: float
Something like 16:9 or 4:3
scale: float
A multiplicative factor to ccale the original figure keeping its ratio"""
ratio = 4 / 3.0 if ratio is None else r... | 3ae801bda79702ae095b8ec098ef9c966cf59837 | 639,538 |
def _residual_block(input_tensor,
block_function,
filters,
num_blocks,
strides=(1, 1),
is_first_layer=False,
norm='group',
training=True):
"""Builds a residual block with repeati... | 0fe58769fc481f3095ba87c5dcd6c1a4c647e73d | 639,539 |
def is_article_link(wikilink):
"""Return True is wikilink is an article link.
Parameters
----------
wikilink : str
Wikilink to be tested
Returns
-------
result : bool
True is wikilink is an article link
Examples
--------
>>> is_article_link('[[Danmark]]')
T... | c862c3d9655ac60d97cb4a7b0e102fa7bc3ee9e8 | 639,540 |
def goldsteinpriceFunction(x):
"""
subject to −2 ≤ xi ≤ 2. The global minimum is located at x∗ = f(0,−1), f(x∗) = 3.
"""
x1 = x['IndPosition0']
x2 = x['IndPosition1']
term1 = (x1 + x2 + 1)**2
term3 = (2*x1 - 3*x2)**2
goldsteinpricefunction = (1 + term1*(19 - 14*x1 +3*x1**2 - 14*x2 + 6*x1... | 16aeb3478a765b6354b5b67666b7ce395ae83ce1 | 639,541 |
def find_disappeared_numbers(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
index = abs(nums[i]) - 1
nums[index] = - abs(nums[index])
return [i + 1 for i in range(len(nums)) if nums[i] > 0] | e0f829a8ed13119f090129fa7baa7fafc027ab3b | 639,542 |
from bs4 import BeautifulSoup
def equation(latex: str, id=None):
"""Creates a numbered equation using the <equation> tag."""
if not isinstance(latex, str):
raise TypeError(f'<latex> must be a string containing the latex code for the equation, received object of type {type(latex)}.')
tag = BeautifulSoup(features=... | ff89a810b0109d8b72c8c5e7c620b2bb4da44b2f | 639,543 |
def timeToSeconds(d: int = 0, h: int = 0, m: int = 0, s: float = 0.0) -> float:
""" Return 'seconds' representation of a given time as defined by days, hours,
minutes and seconds.
Args:
d: number of days to add to returned seconds.
h: number of hours to add to returned seconds.
m: n... | 45a5abde77512c14241d48407aacc1569603e35a | 639,544 |
def get_command_text(txt):
"""Возвращает пользовательский текст после /команды или пустоту"""
r = txt.split(' ', 1)
return r[1][0:1024] if len(r) > 1 else '' | cc7d63dea3c33e60710aa849612d4efef6241547 | 639,545 |
def dicts_are_consistent(d1: dict, d2: dict) -> bool:
"""
checks if all items whose keys are in (d1 and d2) are equal.
returns bool.
"""
return all(d1[k] == d2[k] for k in set(d1).intersection(set(d2))) | 645a4901e71a8273109aafec1cb6559e8fa779e8 | 639,546 |
def get_number_line(selected_file: str) -> int:
""" Return a int with the number line from sentences.txt """
with open(selected_file) as f:
return sum(1 for line in f) | 21da131ab2c8a176a86b6d098fea657f9f9e4779 | 639,547 |
import numpy as np
def parse_neb_results(file, traj_in):
"""
Parses NEB.results
:param: file: NEB results
:param: traj_in: TrajectoryData object with final MEP images
:return: Extended trajectory object with NEB data arrays
and estimation of barrier, and number of iterations.
""... | 9a5b6329ce1d22ef1a135fd036bcef3f703bd2e2 | 639,548 |
def make_cvss_scores(metrics):
"""
[
{
"cvss_v2": {
"base_metrics": {
...
},
"vector_string": "AV:N/AC:L/Au:N/C:P/I:P/A:P",
"version": "2.0"
},
"cvss_v3": {
"base_metrics": {
...
... | f0f24297b17adb4cbd8d09cb7e47fc07476fa8c2 | 639,549 |
def order_dict(data):
"""
Order dict by default order
"""
return {k: order_dict(v) if isinstance(v, dict) else v
for k, v in sorted(data.items())} | 51e6c09538b41cfbacae3481374aa218395a4660 | 639,550 |
def get_spv_data(my_core, entityset_ranges, global_id):
"""
Gets the actual data for surfaces per volume
i.e. the number of surfaces each volume handle contains,
as well as the Global ID for the volume
inputs
------
my_core : a MOAB Core instance
spv_data : a dictionary containing ev... | 8178a559b0aa9b32b742a9d1329680e9f05d5e76 | 639,551 |
def zip_search():
"""
Return: valid USA ZIP code used as 'payload' variable.
Description: Loop until user input is a valid ZIP code, then return.
"""
lock = True
while lock:
try:
i_o = int(input('Please enter ZIP code\n-->>> '))
# based on file 'zip-codes.txt' in ... | 02c69df874f2616cadd5df3273819e39bd0d168b | 639,552 |
import os
def setup_download_dir(directory):
""" 设置文件夹,文件夹名为传入的 directory 参数,若不存在会自动创建 """
if not os.path.exists(directory):
try:
os.makedirs(directory)
except Exception as e:
pass
return True | 90ffbcebddf3ccb2c60598c29ca36138a4a2d135 | 639,553 |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
with open(path, mode='r', encoding='utf-8') as data:
content = data.readlines()
for i in range(len(content)):
content[i] = content[i].strip()
return content | 2183619dd542762cf62dc7557319614df0341de1 | 639,554 |
def _GetProcStatusPath(pid):
"""Returns the path for a PID's proc status file.
@type pid: int
@param pid: Process ID
@rtype: string
"""
return "/proc/%d/status" % pid | ba1c6d322b15fcb62594b3f2ad7ff18a30ac1bbd | 639,555 |
def part1(data):
"""
>>> three = [
... SnailfishNumber([[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]),
... SnailfishNumber([[[5,[2,8]],4],[5,[[9,9],0]]]),
... SnailfishNumber([6,[[[6,2],[5,6]],[[7,6],[4,7]]]]),
... SnailfishNumber([[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]),
... ... | 2fcd7eda7c92e8cbb51ebf6a878126c9af0209c0 | 639,556 |
import base64
def to_base16(data):
"""
把字符串转换成BASE16编码
:param data: 字符串
:return: BASE16字符串
"""
return base64.b16encode(data) | db2a6d11fff0a22a169527f9b0cfe3ff582357ba | 639,559 |
import torch
def pad_batch(batch, padding_id, device='cpu', return_lengths=True):
"""
Pad batch into tensor
"""
lengths = [len(example) for example in batch]
maxlen, batch_size = max(lengths), len(batch)
output = torch.zeros(
maxlen, batch_size, device=device, dtype=torch.int64
) +... | 016e0ee23ba3678a4e69d9c34faecc64d23afdc3 | 639,560 |
import os
def default_config_filename():
"""
Return the default filename for storing Weibo keys.
"""
home = os.path.expanduser("~")
return os.path.join(home, ".weibowarc") | 3973652181b2bf3248a78486e351d562b83de4e3 | 639,561 |
import torch
def gaussian_radius(det_size, min_overlap=0.5):
"""Get radius of gaussian.
Args:
det_size (tuple[torch.Tensor]): Size of the detection result.
min_overlap (float): Gaussian_overlap. Defaults to 0.5.
Returns:
torch.Tensor: Computed radius.
"""
height, width = ... | 590a8c1b6c5c31b905d7d253da09664a54625676 | 639,562 |
from sys import stderr
def filter_blast_file(blast_file, reciprocated_table, subject_index):
"""Filter blast file by reciprocal orthologs"""
filtered_blast = []
with open(blast_file) as blast:
for x, line in enumerate(blast):
if ( (x+1)%10000 == 0 ):
stderr.write... | b99d66a457468661eb354f56ab3724e0f30568d0 | 639,563 |
def action_of(origin: str, destination: str) -> int:
"""Finds which action was taken from origin to destination.
If the states origin and destination are separated by one action, it returns
the numeric value of the action taken (0 = up, 1 = right, 2 = down, 3 = left).
It returns -1 if they are separate... | 57a720f348c23dc521dba5dd1602deb424256882 | 639,564 |
import sqlite3
def get_gene_annotations(database):
""" Create a dictionary linking each TALON gene ID to its human-readable
name and accession ID """
gene_name = {}
gene_ID = {}
with sqlite3.connect(database) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
... | 604fee1e07cd09f681494374f9e37254e126fc44 | 639,565 |
def title(name):
""" Write title keyword"""
return [f'*TITLE\n{name:s}\n'] | f9ff12bd0ff64373b7ebf21887b59a1cc3519d0f | 639,566 |
def cli(ctx, library_id="", name="", deleted=False):
"""Get all the libraries or filter for specific one(s) via the provided name or ID. Provide only one argument: ``name`` or ``library_id``, but not both.
Output:
list of dicts each containing basic information about a library
"""
return ctx.gi.librar... | d8ba99409f2510c030cec11344d6272c3ae5bce2 | 639,567 |
def slice_state(arr, hidden_dim):
"""
Used to slice the final state of GRU, LSTM to the suitable part
"""
part = 0
if arr.ndim == 2:
return arr[:, part * hidden_dim:(part + 1) * hidden_dim]
elif arr.ndim == 3:
return arr[:, :, part * hidden_dim:(part + 1) * hidden_dim]
else:
... | 74b7efdc57c8ecb4272fa012853cc77e590e7722 | 639,568 |
def get_resource_requests_from_networktab(networktab):
"""
Parse `networktab` to extract only `ResourceSendRequest` information.
"""
events = networktab['traceEvents']
network_events = []
for event in events:
if event['name'] == 'ResourceSendRequest':
network_events.append(ev... | 97e50596fbdd057878f2febfc49f3f7d81faa9f1 | 639,569 |
def heap_sort(heap):
"""堆排序,将根节点取出与最后一位对调,对前面len-1个节点继续进行对调过程
heap_sort 耗时:520 毫秒
"""
def max_heap(heap, heapsize, root):
"""
调整堆的结构,使其父节点的值大于子节点的值
"""
left = 2 * root + 1
right = left + 1
large = root
if left < heapsize and heap[large] < heap[le... | 067663c7d3fb18418f32ed0c62ecf2c6d5ef66ac | 639,570 |
def Vdiode(Icell, Vcell, Rs):
"""
Calculate Vdiode from current, voltage and series resistance.
:param Icell: cell current [A]
:param Vcell: cell voltage [V]
:param Rs: cell series resistance [:math:`\Omega`]
:return: diode voltage [V]
"""
return Vcell + Icell * Rs | 45f9f7c02be6172c5ed4e36cb804a0199347ef99 | 639,571 |
from functools import reduce
import operator
def product(iterable):
"""
Returns the product of an iterable
If the list is empty, returns 1
"""
product = reduce(operator.mul, iterable, 1)
return product | 20fe35cb8b306b199fc0b85b061511ffcaae0c1a | 639,572 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.