content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Deque
def parse_array(tokens: Deque[Token]) -> JSONArray:
"""Parses an array out of JSON tokens"""
array: JSONArray = []
# special case:
if tokens[0].type == 'right_bracket':
tokens.popleft()
return array
while tokens:
value = _parse(tokens)
arr... | 1143b27a57fba5cdb8b5d44f30e78442644d1fc3 | 3,602,319 |
def comfort_chart(data_frame, title, output_path, config, locator):
"""
Main function of comfort chart plot
:param data_frame: results from demand calculation
:type data_frame: pandas.DataFrame
:param title: title of plot
:type title: string
:param output_path: path to output folder
:ty... | 528450aae20b3b29030a2d4fdd7431b357fd4b5e | 3,602,322 |
def remove(ui, repo, *pats, **opts):
"""remove the specified files on the next commit
Schedule the indicated files for removal from the current branch.
This command schedules the files to be removed at the next commit.
To undo a remove before that, see :hg:`revert`. To undo added
files, see :hg:`f... | 71b2cc31ef267b42cb27259d32d57ac8c37185b3 | 3,602,323 |
def test_rendering(data, font_file_name, min_allowed, max_allowed, language=None):
"""Test the rendering of the input data in a given font.
The input data is first filtered for sequences supported in the font.
"""
vhb = Vharfbuzz(font_file_name)
font_characters = set(vhb.ttfont.getBestCmap().keys()... | 34e11178e755f86c585a977e8468f7eb24666632 | 3,602,325 |
def get_values():
"""
Get dictionary of values from the backend
:return:
"""
# First load a mapping between config name and default value
default_initial = ((name, options[0])
for name, options in settings.CONFIG.items())
# Then update the mapping with actually values... | a088a43018189b54f5b149cf6b2b10f319237d8a | 3,602,326 |
def rt_merge(rt_stops, intersect=0):
"""
merge and filt RTStops
filter by threshold for each replicate
Input: RTStop in DataFrame (bed6+)
"""
if len(rt_stops) == 0:
raise ValueError('rtstop file not found')
elif len(rt_stops) == 1:
m = rt_stops[0].rename(index=int, columns={... | e3b3819f15ceb29eb349bd11c2329220438654dc | 3,602,327 |
def kmedian(I,J,c,k):
"""kmedian -- minimize total cost of servicing customers from k facilities
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model, rea... | c66ade62fadec398ac24d60c2997d9cc866ec088 | 3,602,328 |
def totalCost():
"""
Total Cost
This method returns a dictionary of the total price paid for each asset,
which is cost_basis from the Alpaca API.
:return: dictionary
"""
totalcost = dict()
for position in portfolio:
# Strings are returned from API; convert to floating point type
... | a74d1a7aca9bb3036c20ed8e1a8279098f4b82e0 | 3,602,329 |
def absolute_vorticity(u, v, dx=None, dy=None, latitude=None, x_dim=-1, y_dim=-2):
"""Calculate the absolute vorticity of the horizontal wind.
Parameters
----------
u : (..., M, N) `xarray.DataArray` or `pint.Quantity`
x component of the wind
v : (..., M, N) `xarray.DataArray` or `pint.Quan... | 2139f83425a79be306ed5fbbab8c009412944869 | 3,602,330 |
def recipient(request, country, recipient_id, slug):
"""
View for recipient page.
- `country` ISO country, as defined in countryCodes
- `recipient_id` is actually a globalrecipientid in the date
"""
country = country.upper()
if not recipient_id.startswith(country):
raise Http404
... | c0c1f976f38c4562c893e85e63a7338abd360204 | 3,602,331 |
import array
def new_double(*args, **kwargs):
"""Creates a new double ("d") array
Args are the same as :func:`array.array` except for typecode,
which is passed by this module.
Returns:
array.array: New, initialized array
"""
return array.array(DOUBLE_TYPECODE, *args, **kwargs) | 0c31a8e154299dc4cbe06b6766ea0939709be9c4 | 3,602,332 |
def _reduction_output_shape(x, output_shape, reduced_dim):
"""Helper function to reduce_sum, etc."""
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduce... | 2a46e878a69aaf57bd5bda3a410fd752c6c0c9cb | 3,602,333 |
def prepare_data(only_prepare_data,delete_last_row):
"""Loads the data, pivots it and if needed aggregates columns
Args:
only_prepare_data (Boolean): True if ohnly prepares data (aggregates ages and saves data)
delete_last_row (Boolean): Deletes last row (because info is not complete)
Ret... | 17180061c84fe73bc16bb919470c16d71f0845b0 | 3,602,334 |
def connect(user, password, db, host=HOSTNAME, port=PORT):
"""
Returns a connection and a metadata object
:param user: the database username
:param password: the database password
:param db: the database we'd like to connect to
:param host: the database adress/hostname
:p... | d0670cce6bc3aac2b03a5fd82e1bba186f1a861e | 3,602,335 |
def gene_pvalue_sel_nb(df_model):
""" Calculate dNdS selection p-values using a conservative NB model
(NB model integrates over uncertainty in the rate estimate)
"""
PVAL_SYN, PVAL_MIS, PVAL_TRUNC, PVAL_NONSYN = [], [], [], []
for i, row in df_model.iterrows():
p_syn, p_mis, p_trunc, p_n... | 639d53ed13a2514c84d7fb5a5a122d016394f7e4 | 3,602,336 |
def parse_repo_origin_url(repo_url) -> dict:
"""
parse a repository clone url and return a dict containing three keys: owner, repo, domain
:param repo_url: clone url such as # https://github.com/owner/repo/
:return: dictionary
"""
url_details = dict()
try:
if repo_url.startswith(... | 82de5b5144504d53f6c1fd92d6473d8e34047e88 | 3,602,338 |
def modular_power(a, n, p):
"""
计算a^ n % p
if n == 0:
return 1
elif n == 1:
return a % p
temp = a * a % p
if n & 1:
return a % p * modular_power(temp, n // 2, p) % p
else:
return (modular_power(temp, n // 2, p)) % p
原文:https://blog.csdn.net/qq_36921652/art... | f9f234ec6532e13fcd9d393163933967ae6e7da7 | 3,602,339 |
def is_correct_type(item, expected_type):
"""Function for check if a given item has the excpected type.
returns True if the expected type matches the item, False if not
Parameters:
-item: the piece of data we are going to check.
-expected_type: the expected data type for item.
"""
... | 37d23e2c7dc1e630d8ead99fde09250196bd664e | 3,602,340 |
import six
def _get_column_indices(X, key):
"""
Get feature column indices for input data X and key.
For accepted values of `key`, see the docstring of _get_column
"""
n_columns = X.shape[1]
if callable(key):
key = key(X)
if _check_key_type(key, int):
if isinstance(key,... | 492b49fd1291f309ae038289307834736579ee10 | 3,602,342 |
import re
def summary(node, opt):
"""
Backend for creating summary of the node tree.
See :py:func:`~matlab2cpp.qtree` for behavior.
Args:
node (Node): Relative root of the tree
Returns:
str: string representation of the node
See also:
:py:func:`~matlab2cpp.qtree`
"""
nodes = flatten(no... | 9f6508496bd2ddeb23f9129707740364ce88e049 | 3,602,343 |
def is_printable(seq):
"""Returns true is seq consists solely of printable ASCII characters"""
printable, total = count_printable(seq)
return printable == total | 516ef8b906a88a9f6c8b8c539c64822fd8594aac | 3,602,344 |
def is_person(possible_person:dict):
"""Helper for getting party ID"""
return not possible_person.get('value',{}).get('entityRepresentation',{}).get('value',{}).get('personOtherIdentification') is None | 66a193cc491296fc94840c684a7066d5f1541e54 | 3,602,345 |
def scorer_cut_trie_v6(data, trie_offset=None):
"""
Cut scorer file from Mozilla DeepSpeech v0.7.x/v0.8.x into kenlm and trie sections.
"""
if trie_offset is None:
trie_offset = find_trie_v6_offset(data)
kenlm_data, trie_data = data[:trie_offset], data[trie_offset:]
return kenlm_data, tr... | dc65f71d2d9df6d1a13ea1a59fefdc2f76664ae7 | 3,602,347 |
def powmod(x, k, m):
""" fast exponentiation x^k % m """
if k < 0:
x = mulinv(x, m)
k = -k
p = 1
if k == 0:
return p
if k == 1:
return x
while k != 0:
if k % 2 == 1:
p = (p * x) % m
x = (x * x) % m
k //= 2
return p | 7ffc5b742ecc867ba4153410c7720141bf88cb9c | 3,602,350 |
def select_feature(x_train, x_test, y_train):
"""
This function reduces the number of features from the existing
g.t 10,000 to something manageable.
Based on experience with feature selection in homework 1, we do
not expect the selection to result in improved performance. But
we expect a reduction in run-time.
... | 9c27b96beeed0e71326be069a701104871b36fcf | 3,602,351 |
def failure() -> Parser:
"""Parser that always fails.
:return:
A new parser that always fails, consuming nothing.
"""
return Failure() | d05b991b1a7d94b9ffc9a1325ea9ab395a7e0dd9 | 3,602,352 |
def rxb_to_rgb(values, magic):
"""
Take values on some (arbitrarily-defined) color wheel and spit them out as
RGB values. The input values are assumed to be between 0 and 1. The final
RGB values are also been 0 and 1.
Magic defines the coordinate transformation. It should be an 8x3 matrix
(... | 44b1dd1b42dd1319954bd0809e503c8793aa5df2 | 3,602,353 |
import functools
def minimize_main_file(test_runner, testcase_file_path, data):
"""Minimize the main test case file."""
if not can_minimize_file(testcase_file_path):
return data
get_random_file = functools.partial(get_temporary_file, testcase_file_path)
data = (
minimize_file(testcase_file_path, te... | 344dffb85ae3cbf7560ba140041650a519c3300d | 3,602,355 |
from typing import Callable
from typing import Any
from typing import Dict
import typing_extensions
from typing import Annotated
def args_to_matchers(
function: Callable[..., Any],
) -> Dict[str, libcst_typing.Matcher]:
"""Extract node matchers from the function arguments.
Untyped arguments will get a `D... | 2ee267f731e392ef4087242d4c71a5356f4b1117 | 3,602,357 |
def cells_number(rc):
"""
Calculates number of cells in each frame.
Intedend for use on 'cells' or subsets of 'cells' tables.
"""
return rc[['frame', 'cell_id']].groupby('frame').agg(len).reset_index().sort('frame')['cell_id'].values | 91725cc352de6a1aa31cf4f82301ed8de6e11bb4 | 3,602,358 |
def decode_qr(image):
"""
Returns dictionary with key, value pair
Parameters
----------
image: qrcode image
Return
------
dict: key value pair
"""
d = decode(Image.open(image))
data = d[0].data.decode('ascii')
data = data.replace(':', '').split()
dict = {da... | 338ea32c4001be683a0d6db5629b49a3e1737540 | 3,602,359 |
def to_cuda(data):
"""
Move an object to CUDA.
This function works recursively on lists and dicts, moving the values
inside to cuda.
Args:
data (list, tuple, dict, torch.Tensor, torch.nn.Module):
The data you'd like to move to the GPU. If there's a pytorch tensor or
... | 28186b60bd7509d3df76646fbf41babe1a4f76e4 | 3,602,360 |
def __update(self, condition, values):
"""
Returns an updated version of this column.
All entries for which the corresponding **condition** is True,
are updated using the corresponding entry in **values**.
Args:
condition (Boolean column): Condition according to which the update is done
... | 38ed8712249b1cd89c5d740f3b2a5f2e8fae04e6 | 3,602,361 |
import glob
def _ExtractBundleFile(target_dir, bundle_extension):
"""Extract single bundle file with given extension.
Args:
target_dir: string, the direcotry to be fetched bundle file.
bundle_extension: string, the extension of the extracted bundle.
Returns:
string, the path of extracted bundle wh... | 703e3a0d415d1b3578853351241dbe3abcb99cb2 | 3,602,364 |
import random
def vc_crop(image_array: np.ndarray):
# Function to crop an image.
# Pad image by n_pixels on each size, then take random crop of same original size.
"""
image_array: The image to apply transformation on.
"""
n_pixels = 40
pad_mode = random.choice(
[
"... | 3caddb644d69b19f3f9f2c565710266123b0f639 | 3,602,365 |
def get_best_synset_pair(word_1, word_2):
"""
Choose the pair with highest path similarity among all pairs.
Mimics pattern-seeking behavior of humans.
"""
max_sim = -1.0
synsets_1 = wn.synsets(word_1)
synsets_2 = wn.synsets(word_2)
if len(synsets_1) == 0 or len(synsets_2) == 0:
r... | 7568eba4c8e9216569c364257bd5ff352aefdc56 | 3,602,366 |
def all_keys_are_have_numbers(d) -> bool:
"""`has_common_prefix() catches most instances of this, but sometimes hash tables have sets of keys like:
{'00', '01', '02', ...}. This function identifies those"""
for k in d.keys():
m = _td_re.search(k)
if not m:
# This key does not end... | 538bb401510db5602b3ff8440b310538d9582422 | 3,602,367 |
def get_dependency_graph_of(symbol, call_graph):
"""Return a sub-graph of the call graph with symbol as the root element.
"""
dependees = get_dependees(symbol, call_graph)
dependees.add(symbol) # Also include the symbol itself
return {sym : call_graph[sym] for sym in dependees} | cb1d28664867bc7badf5a3b1a1de6b01ceebfa3e | 3,602,369 |
def cpuid(apicid, eax, ecx=0):
"""Run CPUID on the specified CPU. Return a namedtuple containing eax, ebx, ecx, and edx."""
return cpuid_result(*_smp._cpuid(apicid, eax, ecx)) | 06e2bc0fadf7fbee494a9eb1f5e1b67d5df9cc58 | 3,602,370 |
def generate_items(data):
"""Generates a dictionary of Item objects
With the key being the item name.
"""
item_flat_dict = defaultdict(list)
item_dict = defaultdict(Item)
for enchantment in data:
for item in data[enchantment].items:
item_flat_dict[item].append(data[... | dae0be5e429ca04822d29e12d70bc16131e74191 | 3,602,371 |
import numpy
def coordinates(n):
"""
Generate a 1D array with length n,
which spans [-0.5,0.5] with 0 at position n/2.
See also docs for numpy.mgrid.
:param n: length of array to be generated
:return: 1D numpy array
"""
n2 = n // 2
if n % 2 == 0:
return numpy.mgrid[-n2:n2]... | 1371601f991432f1bad0a82fb741f050d9346d4e | 3,602,372 |
import fractions
import decimal
def ensure_expr(value_or_expression: ValueOrExpression) -> Expression:
"""
Takes a Python value or expression and returns an expression.
Implicitly converts floats, integers, and booleans to constant expressions.
Raises :class:`~momba.model.expressions.ConversionError... | e5175985c1e57087883c9d2432762f6e89b03649 | 3,602,373 |
def max_wkend_patterns_init(M):
"""
Compute maximum number of weekend worked patterns
:param M:
:return:
"""
max_patterns = 2 ** (2 * M.n_weeks.value)
return max_patterns | bc3cc554c858d80bbe5f33c3deaf87465ddfe657 | 3,602,374 |
def load_fol(s):
"""
Temporarily duplicated from ``nltk.sem.util``.
Convert a file of first order formulas into a list of ``Expression`` objects.
:param s: the contents of the file
:type s: str
:return: a list of parsed formulas.
:rtype: list(Expression)
"""
statements = []
for... | 89da1c9bae084cc69d3dbcec78d19d6571be2c8e | 3,602,375 |
def convert_to_quint8(arr, q):
"""
Quantize a float NumPy ndarray into a quint8 one with specified params.
:param arr: Input ndarray.
:type arr: :class:`np.ndarray`
:param q: Target data type, should be a quint8.
:type q: :class:`np.dtype`
"""
assert isinstance(arr, np.ndarray)
asse... | a7079c5fd7a5a24fbc368ad237f27be1e18577bd | 3,602,377 |
from typing import List
from typing import IO
import warnings
def get_from_files(fhs: List[IO[str]]) -> List[Package]:
"""
Read packages from a list of file handles.
The version specifier(s) for a package can be written in a number of
ways:
pkg
pkg == 0.1
pkg > 1, <= 3
... | 0012fa19d082952cb17bac956783ec61882c9c9d | 3,602,379 |
def load(textfile, vocab, max_value, max_utterance):
""" Load a dialog text corpus as word Id sequences
Args:
textfile (str): filename of a dialog corpus
vocab (dict): word-id mapping
Return:
list of dialogue : dialogue is (input_id_list,output_id_list)
"""
... | 3c43ce1b6f8c4153d9a4e4bf30d00926ca63cb9b | 3,602,380 |
def main(system, logger):
"""
Returns the IP address of the current Redis Master
"""
sentinel = Sentinel(
[(config.SENTINEL_IP, config.PORT)], socket_timeout=0.1)
master = sentinel.discover_master(config.REDIS_MASTER)
if master[0] == config.REDIS_MASTER_IP:
return 1
else:
... | 388523eb7b3a011f4f23eb03e9b6b73b705bdc51 | 3,602,381 |
def __bond_type_to_sdf(bond):
"""Get bond type in sdf language. Based on:
http://www.nonlinear.com/progenesis/sdf-studio/v0.9/faq/sdf-file-format-guidance.aspx
Args:
bond_type (rdkit.Chem.rdchem.Bond): Bond to be processed
Returns:
str: String representation of the bond type.
"""
... | 7714006c36fd0fd8514a8ba6051bd13637da5484 | 3,602,382 |
import ipaddress
def get_id_addr_port(peer_len):
"""Ask the user for peer, IP address and port to modify as gateway
"""
to_modify = input("Enter 'id' (number) of the REMOTE lightning channel to proxy "
"(any other key to skip): ")
try:
if int(to_modify) <= peer_len:
... | 31ec3aadd11b917d095b063d2075044968db98fd | 3,602,383 |
def filter_files_by_predicate(walk: OsWalk, predicate: WalkPredicate, abs_path: bool = False) -> OsWalk:
"""
Filters a walk's file collection using the given predicate.
If a predicate was not provided, the original walk is returned.
:param walk: The walk 'object' to filter
:param predicate: The co... | b131ba292b24cc6d276d080b703ad2cf2c972cec | 3,602,384 |
def cross_check_sanity(flow0, ids0, ids1, corresp0, corresp1, occlusions0, row0, col0,
verbose=False, output_sanity_type=False):
"""
Cross checks that flow and correspondeces agree, or that the pixel is marked as occluded.
If we follow flow for a non-occluded pixel, then the new locat... | 746549f14c3c703c50e0bd89ef0fc8d5103821f1 | 3,602,385 |
def coo_todense(*args):
"""
coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, signed char Ax,
signed char Bx, int fortran)
coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned char Ax,
unsigned char Bx, int fortran)
coo_todense(int n_row, int n_col, int nnz, int A... | 470959f9fa6bfe2fb35d6e850acc8aa9e0d4e4e6 | 3,602,386 |
def make_saint_s(num_heads, embed_dim, num_layers, d_ff, dropout, dropout_ff=0.1):
"""
Make the Saint-t model by stacking mutlihead attention
and feed forward into the encoder layer
-----------
Paramaters
-----------
num_heads: (int) number of attention heads
embed_dim: (int) size of... | 71640289ed5185d6dd95f6d14302498127161932 | 3,602,387 |
def lnlstm(input_tensor, mask_tensor, cell_state, scope, n_hidden, init_scale=1.0):
"""
Creates a LSTM with Layer Normalization (lnlstm) cell for TensorFlow
:param input_tensor: (TensorFlow Tensor) The input tensor for the LSTM cell
:param mask_tensor: (TensorFlow Tensor) The mask tensor for the LSTM c... | 50f77df8a19518beac5bad015e59254e6a926bf4 | 3,602,388 |
def ReadFemPreg(dct_file='2002FemPreg.dct',
dat_file='2002FemPreg.dat.gz'):
"""Reads the NSFG pregnancy data.
dct_file: string file name
dat_file: string file name
returns: DataFrame
"""
dct = thinkstats2.ReadStataDct(dct_file)
preg = dct.ReadFixedWidth(dat_file, compressio... | 73ef50c677925ba9ef29fd11367873f7b4d5541e | 3,602,390 |
def _download(dest_file, file_id):
"""
returns a function that downloads file from Google Drive
Parameters
------
dest_file : pathlib Path
destination to save the file
file_id : str
file_id for Google Drive file
"""
def download():
gdd.download_file_from_google_... | 6bf21009c83e51e8a6c0c7c94a08a0294f2d52c1 | 3,602,391 |
def indent(s, shift=1, width=4):
"""Indent a block of text. The indentation is applied to each line."""
indented = '\n'.join(' ' * (width * shift) + l if l else ''
for l in s.splitlines())
if s[-1] == '\n':
indented += '\n'
return indented | 34ab969f133429959463903fe7e86e18ee644f20 | 3,602,392 |
import functools
def mutating_storage_method(f):
"""Wrap a method and fail if the instance is readonly."""
@functools.wraps(f)
async def inner(self, *args, **kwargs):
if self.read_only:
raise exceptions.ReadOnlyError("This storage is read-only.")
return await f(self, *args, **... | 451c867fd970b9916e258a7076d8d21275992063 | 3,602,393 |
def parse(tokenQueue):
"""
This function creates the abstract syntax tree by calling the story function.
If the story is parsed successfully, then ast evaluates to True and the ast
is returned. Otherwise, parse returns False.
"""
ast = story(tokenQueue)
if ast != False:
print("Parsing complete")
return ast
... | 4b8947c253c99cff5ffa6beb1682fd6c030e5156 | 3,602,394 |
def graph_append_discounted_rewards(destination, rewards, discount_rate):
"""Discounts episode rewards and appends them to destination."""
ag.set_element_type(rewards, tf.float32)
cdr = 0.0
reverse_discounted = []
ag.set_element_type(reverse_discounted, tf.float32)
for i in range(len(rewards) - 1, -1, -1)... | 52618523a71d3578d60f223bcfd624ca6c04bfdd | 3,602,395 |
def issue_pending_alpha(repo):
"""Create "Alpha Release [pending]" issue
This should be created after the current alpha completes.
"""
r, a = _alpha_pending(repo, assert_exists=False)
if a:
return '#{a.number} {a.title} already exists'
i = r.create_issue(title=_release_title('Alpha', pe... | 80ee19c4060379e781a2ed366c7bbdab1d1bb336 | 3,602,396 |
from typing import Literal
from typing import List
from typing import Tuple
def get_letter_index_pairs(key: str, lang: Literal["EN", "TR"]) -> List[ Tuple[str, str] ]:
"""
Returns a list of tuples where the first element in each tuple is a letter from the given key
and the second element is the position o... | 72e6480b72dac92daaf9c3f0c9134e355bdec533 | 3,602,397 |
from typing import Optional
def get_clusters(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClustersResult:
"""
Retrieve EKS Clusters list
"""
__args__ = dict()
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_ve... | 7dcf91824e28c6992fbfe5f3c2579d3ba32d8819 | 3,602,398 |
def fembed(link: str) -> str:
""" Fembed direct link generator
Based on https://github.com/zevtyardt/lk21
"""
dl_url= Bypass().bypass_fembed(link)
count = len(dl_url)
lst_link = [dl_url[i] for i in dl_url]
return lst_link[count-1] | 4b3c43fe0e6e55f9dd7f0ffe35b89b9cf504390e | 3,602,399 |
import ssl
def generate_ssl_context(server_certificate, server_key, ca_cert):
"""This function generates an ssl context for Tornado handler"""
mySSLContex = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
mySSLContex.load_cert_chain(server_certificate, server_key)
mySSLContex.load_verify_locations... | 29e8cd2bc49948e6e5b509dab312b049d0cc9aaa | 3,602,400 |
def get_page(rb, cand, el_type):
"""
Функция принимает RoboBrowser с открытой страницей результатов голосования по какому-то УИКу rb,
кол-во кандидатов в выборах cand, а также тип выборов el_type и возвращает список, состоящий из номера УИКа,
кол-ва избирателей на УИКе, кол-во проголосовавших на дому и ... | a4fecd2dc60d8438e20870d0e96ce876bb4c1902 | 3,602,402 |
from typing import Optional
def get_storage_class_v2(cluster_id: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStorageClassV2Result:
"""
Use this data source to retrieve information about a Ranche... | f7b1e774e0950ab73daa534a8ede80629c014db0 | 3,602,403 |
import socket
def parse_hub(hub):
"""
Parse a hub specification.
:param hub: The hub specification. Can be either a bare
"hostname" or a "hostname:port". If the hostname is
an IPv6 address, it should be enclosed in brackets,
i.e. "[::1]:4859".
:retur... | ac3978a1646fdd00ddc8ccfcc54bf9e04eae6a1f | 3,602,405 |
import json
def get(url):
""" Queries the NodePing API via GET and returns its results
Accepts a URL to the NodePing API to query and retrieves
data provided by NodePing, and then converts the contents
to a dictionary
:type url: string
:param url: The URL that will be used for GET request
... | b9026456ff67b55d8e2bcdc41bc77541e2b2a6a8 | 3,602,406 |
def makeindexline(url, startpage, total, numonpage=10, pagesonscreen=5):
"""
Make a menu line for a given number of inputs, with a certain number per page.
Will look something like : ::
First Previous 22 23 24 25 26 27 28 29 30 31 32 Next Last
Each number or word will be a link to ... | fdae2d9385f02e3c47fff516b2eb4fe1f931cec8 | 3,602,407 |
def log_loss(
y_hat: np.ndarray,
y: np.ndarray
) -> float:
"""
Log-loss cost function.
:param y_hat: Predicted value (scaled [0, 1])
:param y: Label value (i.e., ground-truth)
:return: loss value
"""
is_one = y * np.log(y_hat)
is_zero = (1.0 - y) * np.log(1.0 - y_hat... | 2c377700dddea65f670db7ce20755d8aa746d847 | 3,602,408 |
import pandas
def optimize_price_index(initial_price_list: pandas.DataFrame) -> pandas.DataFrame:
"""
This pricing function has been made very simple as the main purpose is to serve the use case example.
In real life this would typically be replaced by a more flexible price optimization engine with severa... | 058dedbec73c1fa3dad510a1b6c4a0b56fa94112 | 3,602,409 |
from typing import List
def generate_all_legal_trades_fast(state: State) -> List[ActionTradeGems]:
"""Returns the list of all possible actions of trade in a given current_state"""
gems_board = state.board.gems_on_board
gems_player = state.active_players_hand().gems_possessed
#print(state.active_player... | 94476f06afe4cb27e2abba364251bf165325e609 | 3,602,410 |
def upkey(name):
""" Shortcut for creating an uppercase keyword """
return Keyword(name, caseless=True).setParseAction(upcaseTokens) | 408465622b39971726f90a00bf83a1cf1118ef5c | 3,602,411 |
def get_db_path(spider_dir, db_id):
""" Return path to SQLite database file.
Args:
spider_dir: path to SPIDER benchmark
db_id: database identifier
Returns:
path to SQLite database file
"""
return f'{spider_dir}/database/{db_id}/{db_id}.sqlite' | 9069b673df1b3c929c249319339a84eaaf398c33 | 3,602,412 |
def is_available():
"""[filterツールとenhancd.logが存在することを確認する]
Returns:
[bool]: [実行可能ならTrue]
"""
b1 = filepath.split_filterlist(x_env["ENHANCD_FILTER"]) is not None
b2 = (x_env["ENHANCD_DIR"] / "enhancd.log").exists()
return b1 and b2 | 6dd1fab9e7f4885309b315408d530e9a0b7e1d7c | 3,602,413 |
import hashlib
import base64
def get_pubkey(key):
"""Get the pubkey info corresponding to the given public key.
The md5 hash of the key is used for the query for quicker lookups.
"""
session = get_session()
md5_hash = hashlib.md5(base64.b64decode(key)).hexdigest()
pubkeys = session.query(mode... | f4b2aca9fa93b4cf5a0ad277cb3f52e2b8cce783 | 3,602,415 |
import copy
def init_ball_with_word2vec(vecFile, wordsenseFile, IncDim = 1, d=50, l0 = 10000, r0 = 30, rmin = 0.1):
"""
vecFile is a file of pre-trained word embedding.
:param vecFile:
:param trainFile:
:param IndDim: 0, not to increase the dimension, >0, increase d+1th dimension with the value I... | ec447ab078c251e44223c591ec98ed9eecfd002c | 3,602,416 |
def readable_ternary(first_opernad, condition, second_operand):
"""Same as `first_operand if condition else second_operand`"""
return ternary(condition, first_opernad, second_operand) | 3520bbcbda0881200d5ad5424e1a35286b7c1800 | 3,602,417 |
def execute(qregistry, iterations=1, lines=[], ancilla=None,
useSystem=True, optimize=True):
"""Execute the gates in lines on a qsystem.
Gets repeated the specified number of iterations.
Returns the result of each iteration.
"""
sol = [_executeOnce(qregistry, lines, ancilla, useSystem, ... | d41e1594790aeb9b7899418bc66763b5c8445f67 | 3,602,418 |
def frequency_response(data, fs, uprate):
"""
Parameters
----------
data: ndarray
fs: float
sampling frequency
uprate: int
Returns
-------
(ndarray, ndarray, ndarray)
mag_fre_db, phase_fre_rad, frequnecy
"""
response = fft(data, len(data) * uprate)
mag_d... | d2ba8566924ce9153063498dee30687d1a7b4009 | 3,602,420 |
from typing import Optional
from typing import Sequence
from typing import Mapping
from typing import Any
def get_encode(batch_inputs: Optional[Sequence[Mapping[str, Any]]] = None,
batch_results: Optional[Sequence[Mapping[str, Any]]] = None,
encoded_value: Optional[str] = None,
... | 411ccd95a23cb299a246792561e044fde95167fc | 3,602,421 |
import re
def sanitize_scope_name(name: Text) -> Text:
"""Sanitizes string which will be used as TensorFlow scope name."""
# Add "." to beginning if first character isn't acceptable
name = re.sub("^([^A-Za-z0-9.])", ".\\1", name)
# Replace invalid characters with "_"
name = re.sub("([^A-Za-z0-9._]... | e83b84bf9135caf0a84e34fc380085100152ad7c | 3,602,422 |
def get_entity_bio(seq, id2label):
"""Gets entities from sequence.
note: BIO
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
seq = ['B-PER', 'I-PER', 'O', 'B-LOC']
get_entity_bio(seq)
#output
... | bdaf2da0a7dd819239701af0aa49d69c09ece7f6 | 3,602,423 |
def sparse_euclidean_distance(sp_tensor, tensor2):
""" Computes the euclidean distance between two tensors.
Args:
sp_tensor (`Union[Tensor,SparseTensor]`): a tensor or sparse tensor
tensor2 (`Tensor`): a dense tensor
Returns:
distance (`Tensor`): euclidean dista... | 719d14c8204b5d2ad595368f34ee8e44b6b8cbbc | 3,602,424 |
def pop_indices(lst, indices):
"""
pop the lst given a list or tuple of indices.
this function modifies lst directly inplace.
>>> pop_indices([1,2,3,4,5,6], [0,4,5])
>>> [2, 3, 4]
"""
for n in sorted(indices, reverse=True):
lst.pop(n)
return lst | 4cfeedfd211ba4578d877004acdec061c7727d78 | 3,602,425 |
from typing import Dict
from typing import Any
def delete_user(current_user: User, target_user: User) -> Dict[str, Any]:
"""
Delete the user records and remove the user from all user groups. All user id fields with this user id as values
are set to null.
:param current_user:
:param target_user:
... | 9d1d34c0c2927fd802ecf23551c55a438acb6afb | 3,602,426 |
def plot(xy: PointUnionList, color='black', label=None,
linewidth=None, linestyle=None,
plotter=None) -> Artist:
"""Quick entry to pyplot.plot() for List[Point]"""
plotter = plotter or plt
artist, = plotter.plot(*zip(*xy), color, label=label,
linestyle=linestyle,... | 3a1341ab28551cd5f6a1d52bc2f49e194a41be47 | 3,602,427 |
import json
def login(request):
"""Log user in.
Associate barangay data with authentication data and store in session.
Args:
request: The URL Request.
Returns:
Render form with errors.
"""
data = json.load(request)
auth_data: dict = data.get("payload")
user_col = firesto... | d2472b2ea9ce271c30f09ffea6bccd4a60131df5 | 3,602,428 |
import json
def record_locators(request):
""" View that generates at least one record locator, generating 'n' if
specified through a query parameter. """
num_locators = int(request.GET.get('n', 1))
record_locators = generate_locators(num_locators)
data = {'record_locators': record_locators}
... | 9eb3836b31435aec8579925d5348cc168c6f5de7 | 3,602,429 |
def merge(obj, *sources, **kargs):
"""Recursively merges own enumerable properties of the source object(s)
that don't resolve to undefined into the destination object. Subsequent
sources will overwrite property assignments of previous sources. If a
callback is provided it will be executed to produce the... | 517bfa55419e672f09cc55a5bf0f764c80d9fd61 | 3,602,430 |
def wrapper_early_cav_identif(grid, grid_min, grid_shape, selection_protein, selection_coords,
size_probe = 1.0, maxdistance = 6.0,
radius_cube = 4, min_burial = 8, radius_cube_enc = 3, min_burial_enc = 8, gridspace = 1.0, min_degree = 3,
radius = 2, trim_score = 500, min_points = 40, min_burial_q = 10, quantile = 0... | c6a788b548f67e1f943e769310277191ec3e5212 | 3,602,431 |
def calculate_distance(aux_structures, start, end):
"""
Returns the distance between two nodes.
start and end are node IDs.
"""
start_id_to_coordinate = map_node_id_to_coordinates(aux_structures, start)
end_id_to_coordinate = map_node_id_to_coordinates(aux_structures, end)
dista... | 3565f95538eff326661af3228369e30051994690 | 3,602,432 |
def get_sampling_rate(filename=None):
"""Get the sampling rate in Hz."""
return _fs | a5d5a9a93224543a98ab92128e113201f2ea72c9 | 3,602,434 |
def ls(directory=None):
"""Return a python list of ROOT object names from the given directory."""
if directory == None:
keys = ROOT.gDirectory.GetListOfKeys()
else:
keys = ROOT.gDirectory.GetDirectory(directory).GetListOfKeys()
key = keys[0]
names = []
while key:
obj = ke... | 60239abd729971b944b95e8483f513226e112071 | 3,602,435 |
def is_color_management_enabled():
"""
Returns whether or not color management is enabled
:return: bool
"""
return maya.cmds.colorManagementPrefs(cmEnabled=True, query=True) | 3d89dea2aad26e5c8337db857bc1273d95974e4d | 3,602,436 |
def UNET(input_shape, num_classes, branch_names, BACKBONE, weights,
freeze_backbone=False, activation='sigmoid', decoder_type='upsample',
decoder_filters=[256, 128, 64, 32, 16], input_tensor=None,
name='UNET'):
"""Build a generic UNET model with a given ``BACKBONE`` class.
# Argument... | 2ae9e643392fb65bef869d5ea98b3178a1ea1c05 | 3,602,438 |
def geo2rect(lon: float, lat: float, h: float, r: float, ecc: float = EARTH_SECOND_ECCENTRICITY_2) -> np.ndarray:
"""
Geodetic to Rectangular Coordinates conversion in the e-frame.
Parameters
----------
lon : float
Longitude
lat : float
Latitude
h : float
Height abov... | a0b00fdb8e9e6d478ce245e09a1755a0edd1aaf1 | 3,602,439 |
from typing import Optional
from typing import Set
from pathlib import Path
from typing import Iterable
from typing import List
import logging
def filter_tidy_lints(only_files: Optional[Set[Path]],
git_repo_base: Optional[Path],
diags: Iterable[TidyDiagnostic]) -> List[Tidy... | 9d3a047b8ea8dd7e4a90bd982dbfdee9abc681d8 | 3,602,440 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.