content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def multihead_self_attention_incremental(query_antecedent,
prev_k,
prev_v,
step_num,
name="multihead_attention"):
"""Incremental self-attention (one decod... | 941c6918893060e480642daf1089073813ff0d56 | 53,906 |
from openff.toolkit.typing.engines.smirnoff import ForceField
from typing import Optional
from typing import Tuple
import copy
import numpy
def system_subset(
parameter_key: ParameterGradientKey,
force_field: "ForceField",
topology: "Topology",
scale_amount: Optional[float] = None,
) -> Tuple["openmm.... | 5e3923b1498b5b813622110a0ea49968d00e274f | 53,907 |
import torch
def tensor_to_numpy(data):
"""Transform torch tensort arrays to numpy arrays."""
if hasattr(data, 'detach'):
data = data.detach()
if type(data) is torch.Size:
return np.array(data)
return data.cpu().numpy() | e0ebabae325b46cc75a81a6c74a9521bd944681f | 53,908 |
def get_default_resolution_attribute(attribute_name, default_value=None):
"""
Internal function that returns value of the given attribute of the default resolution Maya node
:param attribute_name: str, name of the attribute to get
:param default_value: object, value that is returned if the attribute doe... | db3f11f55f4d68e269a0b3cd8b41dd80c3a5365b | 53,910 |
async def resolve_subscription_user(event, info, id):
"""Resolver function for user subscriptions"""
user = event["user"]
mutation = MutationEnum(event["mutation"]).value
return {"user": user, "mutation": mutation} | c2337c93f8ef5eaae0e6dfa5edc40705973911a3 | 53,915 |
def _install(pkgs, pkg_manager):
"""Return instructions to install system packages."""
installers = {
'apt': _apt_install,
'yum': _yum_install,
}
if pkg_manager not in installers.keys():
raise ValueError(
"package manager '{}' not recognized".format(pkg_manager))
... | 81556b5795e1ed2c846411fbe0fa3faccede8395 | 53,916 |
def gsutil_command(arguments, *args, parallel=True, **kwargs):
"""Executes a gsutil command with |arguments| and returns the result."""
if environment.get('FUZZ_OUTSIDE_EXPERIMENT'):
logger.info('FUZZ_OUTSIDE_EXPERIMENT set, not running \'gsutil %s\'.',
' '.join(arguments))
r... | d6bc542d24be72500491c077d7fe2aa21678b27a | 53,917 |
def parse_account(s):
""" parse entity and account string """
return s.strip().split('.') | acb14bd71a670e67b306f022792702dc2677539a | 53,918 |
import scipy
def sbm_adjmat(cluster_sizes, prob_mat_q, directed=False, self_loops=False):
"""
Generate a graph from the stochastic block model.
The list cluster_sizes gives the number of vertices inside each cluster and the matrix Q gives the probability of
each edge between pairs of clusters.
F... | 704293eb57cbe0b841a9957b591a6dd96f98ea0a | 53,919 |
def distribution(Data, N, kernel=False, ccdf=True):
""" This function calculates the pdf and ccdf of Data, either by histogram or by gaussian kernels.
N:
If histogram is used, N is the number of bins to separate the data into.
If kernel is used, N gives the number of data points.
ccdf: if true, retu... | 8f5d32abd3475b37e61420938f326657728756b3 | 53,920 |
import torch
def to_pil_image(pic, mode=None):
"""Convert a tensor or an ndarray to PIL Image.
See :class:`~torchvision.transforms.ToPIlImage` for more details.
Args:
pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
mode (`PIL.Image mode`_): color space and pixel depth of... | cfc2fd887c9da9d473db8e7dee1cae5194da244b | 53,921 |
import uuid
from typing import Optional
from typing import Dict
from typing import Any
async def update_issue_pr(
db_session: Session,
repo_id: uuid.UUID,
comments_url: str,
terminal_hash: Optional[str] = None,
entry_id: Optional[str] = None,
comments: Optional[Dict[str, Any]] = None,
) -> Git... | deb7d6916a0e5d740c1797f40f9c15eb1c4d7333 | 53,922 |
def uniqPeptides(peptFile):
"""
create a fasta-file of non-redundant peptide sequences from peptFile.
(return: path to created file)
peptFile: peptide sequences (fasta-format)
"""
outfile = os.path.dirname(peptFile) + "/uniq_" + os.path.basename(peptFile)
newls = []
peps = []
n_peps = 0
print "reading pept... | cf008bca2a1e643e20837d8c5386e8d7e64e3ecd | 53,923 |
import logging
import pkg_resources
def run_phenorank(omim_obs, phenotypes_obs=None, nperm=1000, r=0.1, ni=20, gene_mask=None, include_h=True, include_m=True, dir_data="data_phenorank", filename_output="~"):
"""
run the main PhenoRank function
Args:
omim_obs: OMIM ID for the disease of interest
phenoty... | 8a240c22fd6bc1690df4b9a54339ae1380db73fe | 53,924 |
def http_404_view(request, *args, **kwargs):
"""View for HTTP 404 page."""
response = render(request, "system/404.html", {})
response.status_code = 404
return response | db2f82b30b838bcdb59c3315d34a783055fddae3 | 53,925 |
import collections
def isEquivalentData(values1, values2):
"""
Determines if two values are equivalent
:param Iterable/object values1, values2:
:return bool:
"""
if cell_types.isStr(values1) and cell_types.isStr(values2):
result = values1 == values2
elif isinstance(values1, collections.Iterable) \
... | 6b2f8d98f04d4a4a18bad25e42283fb7afb5b6ba | 53,926 |
def default_errorhandler(error):
"""
Handler function for a logging all errors
"""
APP.logger.exception()
return {'message': error.message}, 500 | faa53ba4e65c11a43b64577034936986075bcbff | 53,928 |
import torch
def chunk_rays(rays,start,delta):
"""
rays: a dictionary
"""
rays_chunk = {}
for k,v in rays.items():
if torch.is_tensor(v):
v = v.view(-1, v.shape[-1])
rays_chunk[k] = v[start:start+delta]
return rays_chunk | 8015d1d69b77e2a7fab6b33d30a104982aedfa9c | 53,929 |
import socket
def _get_my_ip():
"""Return the actual ip of the local machine.
This code figures out what source address would be used if some traffic
were to be sent out to some well known address on the Internet. In this
case, a Google DNS server is used, but the specific address does not
matter... | 6ed019bf007386d1427b4bf874e6aaf71f44e706 | 53,930 |
def _sph2cartMTX(vizMTX):
"""Converts the spherical vizMTX data to named tuple containing .xs/.ys/.zs.
Parameters
----------
vizMTX : array_like
[180 x 360] matrix that hold amplitude information over phi and theta
Returns
-------
V : named_tuple
Contains .xs, .ys, .zs cart... | a983021fa8a0ade0fe1d695fc723751ae0973499 | 53,931 |
def string_to_TaskStatusCode(status):
"""Converts the given Mesos status string to an integer
:param status: The status as a string
:type status: string
:returns: The status as an integer
:rtype: int
"""
return mesos_pb2.TaskState.Value(status) | 32d8a95d479fc08485fef1292b8229c59632fd62 | 53,932 |
def concat_data_chunks(*args):
"""Concatenates data-chunks together based on their keys."""
data_chunk = DataChunk()
for k in args[0]:
data_chunk[k] = []
for arg in args:
for k, v in arg.items():
data_chunk[k].append(v)
for k, v in data_chunk.items():
data_chun... | 465eef76106a71ba0b2246e16c584be0262890e3 | 53,933 |
def normalize_job_id(job_id):
"""Convert the job id into job_id, array_id."""
job_id = job_id.split('.')[0]
if '[' in job_id:
job_id, array_id = job_id.split('[')
job_id = job_id.strip('[]')
array_id = array_id.strip('[]')
if not array_id:
array_id = None
else... | 6eb83b54f8a0cec8c094372a5e5446334a1863c3 | 53,934 |
def get_ingredient(name):
"""Find an ingredient by its name.
Args:
name (string): The name of the ingredient.
Returns:
IngredientDto: The ingredient with the given name, or None.
"""
ingredient_entity = IngredientEntity.query.filter_by(name=name).first()
if ingredient_entity is... | 606fa9cbcb5c80afebab05ba8e8283a18c81d0bd | 53,935 |
def get_ydim(da, errors="warn", **kwargs):
"""Get the dimension of Y type
It is a simple call to :func:`get_dims` with ``dim_types="y"``
Parameters
----------
da: xarray.DataArray
Array to scan
positions: str
Default position per type starting from the end.
{errors}
kwa... | 70e4b7f24f0b31f0d9da9e6c584e880ba15094db | 53,936 |
def create_import_data_json(import_data_dict, event_tree):
"""
create_import_data_json:
This function converts data in event tree into json format.
Parameters:
import_data_dict: This parameter holds the event tree data
event_tree: This parameter holds the event tree data
@see #gener... | 2a8745e9fbe387afd63c912d860b0a762770394a | 53,937 |
import scipy
def power_split(y, x, x_max, n):
"""
Computes the indexes corresponding to equal integral values for a function y and x values
:param y: function value array
:param x: function x values array
:param x_max: maximum x value
:param n: number of integral bins
:return: indexes of t... | 98207f6eb29601a681b2d7ac39077b21250305ed | 53,938 |
import random
def select_ip_from_network(network):
"""
Randomly selects an IP address from a particular network
:param network: Network from which to select the IP address
:return: IP address as integer from network
"""
max_address = network.address | ((1 << (32 - network.prefix)) - 1)
ret... | 7356b6cedd5bc78933484e0cba9a8f84d1507b07 | 53,939 |
def ONE_OR_MORE(*grammar, **kwargs):
"""
This is a synonym for ``REPEAT(*grammar, min=1)``
"""
kwargs.update(min=1, max=None)
return REPEAT(*grammar, **kwargs) | 704125e64e948361641bf28b235f80560454966e | 53,940 |
def kwtype_to_annotation(kw):
"""Convert type to a KnownType"""
data = {}
for name, type in kw.items():
if isinstance(type, str) and ',' in type:
for x in type.split(','):
data[_clean_name(x.strip())] = _get_type(name)
else:
data[_clean_name(name)] = ... | ed50e6bccdfcc2c1f121e71437a45ae6180e7b24 | 53,941 |
def parse_extinst_instruction(lexer, set_id):
"""Parse instruction field of OpExtInst instruction."""
assert set_id.inst.op_name == 'OpExtInstImport'
_, tag = lexer.get_next_token(peek=True)
if tag == 'INT':
return parse_literal_number(lexer)
elif tag == 'NAME':
token, _ = lexer.get_... | 48fd7103fc87be4581a16c17d840e4c6adef5b42 | 53,942 |
import json
import requests
def query(query, experiment_id, host, verify_cert=True):
"""
Query the MDML for an example of the data structure that your query will return. This is aimed at aiding in development of FuncX functions for use with the MDML.
Parameters
----------
query : list
Des... | 3080ab6322a2756fdc6cb4da8ccc81b96154cbb4 | 53,943 |
def interlock(word_list, word):
"""Checks whether a word contains two interleaved words.
word_list: list of strings
word: string
"""
evens = word[::2]
odds = word[1::2]
return in_bisect(word_list, evens) and in_bisect(word_list, odds) | 001652981626b4f24af2f3c4acf155e76f68412c | 53,945 |
from sudachipy import dictionary, tokenizer
def try_sudachi_import(split_mode="A"):
"""SudachiPy is required for Japanese support, so check for it.
It it's not available blow up and explain how to fix it.
split_mode should be one of these values: "A", "B", "C", None->"A"."""
try:
split_mode = ... | d0bc779bc3c7d45d8e573f8382ba57cb92074be3 | 53,946 |
def ask_type(question, ans_type, loop=True):
"""
Used to ask and assert that the response to the question will be an integer
:param question: what to ask
:return: the result, of type specified
"""
answer = ask(question)
if loop:
# Loops until the user
while loop:
... | 33f0eef3e3173e74a713cfc3b2de985d69495b45 | 53,947 |
def unload_nodenet(nodenet_uid):
""" Unload the nodenet.
Deletes the instance of this nodenet without deleting it from the storage
Arguments:
nodenet_uid
"""
if not nodenet_uid in nodenets:
return False
if nodenets[nodenet_uid].world:
nodenets[nodenet_uid].wo... | aae97308c825cbf0b3f4a5b002ac75856ce41088 | 53,948 |
def verifyBundleStructure(expected, actual, currentPath):
"""
Function to verify if an uploaded bundle follows IBM defined structure
@param expected the JSON representation of the IBM defined structure
@param actual the JSON representation of the actual structure of the uploaded bundle
@p... | c758d132950986c5cdb97ceb9e34fe99cd21e8bc | 53,949 |
def fix_coordinates(df, cols):
"""
For coordinate column which require fixing, we it here
"""
to_fix_or_not_cols = check_if_coordinates_colums_need_fixing(df=df,
cols=cols)
if to_fix_or_not_cols:
fix_col = to_fix_or_not_cols["c... | e16aaace0f5dbeb3645f86b3112d8de81e45bedb | 53,950 |
from .pyicu import segment
from .multi_cut import segment
from .newmm import mmcut as segment
from .longest import segment
from .pylexto import segment
from .deepcut import segment
from .wordcutpy import segment
def word_tokenize(text, engine='newmm',whitespaces=True):
"""
:param str text: the text to be tokeni... | 96260aa4ea57a19a904a17d5e8a7968b605042e0 | 53,952 |
def choose_best_seqs(dist_matrix, all_genes, groups, medoid):
"""
Defines the medoid of a distance matrix
:param dist_matrix: The numpy array (symmetrical) distance matrix
:param groups: sp -> groups of genes
:param all_genes: A list of the row/colnames of the distance matrix
:param medoid: the ... | da68a172732f42a2781673c26034ccb26f7bfff9 | 53,953 |
def oracle_service_def():
"""
Provides the Docker service definitions for running an instance of Oracle Express Edition, result is converted to
YAML file and then used to create a Docker compose file. Note this assumes the existence of a container image named
'oracle/database:18.4.0-xe' in a registry th... | f68c340a71f795630578ac6a689a620cf96e895a | 53,955 |
def get_kmsauth_config(region, bless_config):
""" Return the kmsauth config values for a given AWS region
Args:
region (str): the AWS region code (e.g., 'us-east-1')
bless_config (BlessConfig): config from BlessConfig
Retruns:
A dict of configuation values
"""
alias_code = bl... | c8fcc4ab0a125f1ed068a865872d3421280b21ab | 53,956 |
def get_utility_command_execution_order(name):
"""
Should the given utility command be executed before or after the payload?
:param name: utility name (string).
:return: execution order constant (UTILITY_BEFORE_PAYLOAD or UTILITY_AFTER_PAYLOAD)
"""
# example implementation
if name == 'moni... | 301deca503fc890322363d1c8c9f2e6ff9ff9af3 | 53,957 |
def bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value)) | 7a58a45509749c0633e648096d199359872e9919 | 53,958 |
import time
def int_product(size=DEF_MATRIX, rep=DEF_REP):
"""
Returns the execution time of performing a product of random integer
matrices.
Parameters
----------
size : int
The dimension of the square matrices that will be used in the
operation.
... | 5b898de1a719060701b250bd6982c0994c2e18f0 | 53,959 |
def project_waveforms(waveforms, method='pca', selection=None, catalogueconstructor=None, **params):
"""
"""
if selection is None:
waveforms2 = waveforms
else:
waveforms2 = waveforms[selection]
if waveforms2.shape[0] == 0:
return None, None, None
... | ff23fddfa122524ffc8c895ba8c1db879e22f6e7 | 53,961 |
def high_low_estimator(high, low, window):
"""
Estimates volatility using Parkinson's method
:param high: a series of high prices
:param low: a series of low prices
:param window: length of the rolling estimation window
:return: volatility estimate
"""
log_high_low = np.log(high / low)
... | bab9ecc9a17e72d38c1a6c7bd4f7ef302b818459 | 53,962 |
def replace_decorator(node, capture, filename):
"""
Replaces usage of ``@slowTest`` with ``@pytest.mark.slow_test``
"""
return utils.rewrite_decorator(node, DECORATOR, MARKER) | 12200443d5683c06fe1703277c23974f632ea55c | 53,964 |
def GetPercentage(number, total):
"""Returns the float percentage that a number is of a total."""
if not number:
return 0
return float(number) / total * 100 | 46e2a5b2b4a3fa648792a461852f84e886810a7f | 53,965 |
def _store_path(path, ctx, imports):
"""Given a path, prepend the workspace name as the zappent directory"""
# It feels like there should be an easier, less fragile way.
if path.startswith("../"):
# External workspace, for example
# '../protobuf/python/google/protobuf/any_pb2.py'
st... | 5713f8c6ca5471ec6a4bb5b352a199dc004286fc | 53,966 |
def create_custom_program_attribute(driver):
"""Creates a custom text attribute for a program object
Args:
driver (lib.base.CustomDriver)
"""
modal = dashboard.AdminDashboard(driver) \
.select_custom_attributes() \
.select_programs() \
.add_new_custom_attribute()
test_utils.ModalNewPr... | 3b562889b54fc8e9618ee0411ccdf3644f110669 | 53,968 |
import re
def parse_billing_code_col(s:str):
"""Split billing code into separate fields for code_type and code. E.g., 'MSDRG .... 001'."""
l:list = s.split()
if 'MS-DRG' in s:
code_type, code = l[0], l[4]
elif re.search('CPT|HCPCS', s):
code_type, code = l[0], l[1]
else:
co... | 78865842a457c0226184ace94334d0934a0e0a5c | 53,969 |
def munsell_colour_to_munsell_specification(munsell_colour: str) -> NDArray:
"""
Retrieve a normalised *Munsell* *Colorlab* specification from given
*Munsell* colour.
Parameters
----------
munsell_colour
*Munsell* colour.
Returns
-------
:class:`numpy.ndarray`
Norma... | 693d64e6d4ebd19d775186be6ec57f019e46c550 | 53,970 |
def predict(market,profit,hold,cur_profit_present,stop):
"""
一个极其简单的示例策略,如果空仓则买入,如果有仓位就卖出
"""
if hold==0:
return {'if_buy':1}
else:
return {'if_buy':0} | 53ae9a2b1e4017b9d8ac79c8e058ed5881934f9e | 53,971 |
from typing import List
def inject_params(lines: str, params: dict) -> List[str]:
"""Replace placeholders with parameters.
Args:
lines: A file content including placeholders (`{{ ... }}`).
params: A mapping a name of placeholders to a value.
Returns:
A file content replaced plac... | 74614fb6cdf8ba85cf057920db22e7bf5854c288 | 53,972 |
def load_depth(file):
"""
Load a depth map from file
Parameters
----------
file : str
Depth map filename (.npz or .png)
Returns
-------
depth : np.array [H,W]
Depth map (invalid pixels are 0)
"""
if file.endswith('npz'):
return np.load(file)['depth']
... | 9b1a672143980424b09ad5d483d032dfbdde3211 | 53,973 |
def close_story(request):
"""Close an open story.
---
story_id:
in: path
type: string
required: true
"""
auth_context = auth_context_from_request(request)
# Only available to Owners for now.
if not auth_context.is_owner():
raise PolicyUnauthorizedError("Only Own... | 26a28846f19b665b599d5e2ef00f486be6e226c7 | 53,974 |
def parthandler(parttype, params=()):
"""decorator that register a function as a bundle2 part handler
eg::
@parthandler('myparttype', ('mandatory', 'param', 'handled'))
def myparttypehandler(...):
'''process a part of type "my part".'''
...
"""
def _decorator(fu... | 511ebba63b65639d72bac62080e19ddb2dbd0c91 | 53,975 |
def get_field_instance(field_name: str) -> FieldInstance:
"""
Return a FieldInstance object for the given field name.
Args:
field_name: The name of the field to get a FieldInstance for.
Returns:
A FieldInstance object for the given field name.
"""
info = _FIELD_INFO_MAP[field_n... | fc5bbd61d58e15f817eda554f12e5429f99fab02 | 53,976 |
def DetermineLocaleType(locale_str):
"""Determines the locale 'type' for a given locale name.
Returns:
(string) Always one of the following strings,
'world' If the locale name refers to the world.
'country' If the locale name looks like a country ID.
'region' If the locale name ... | 52ac86d8e011d9d01b6f31ed6a27d535a55b26a4 | 53,977 |
def m_to_recruitment(seq, args=None):
"""
返回bool值0/1
:param seq: 任意值
:param args: 可不传 传时seq==args为1
:return: 0/1
example:
:seq '11'
:args '00'
:return 0
"""
if seq:
seq = "统招"
else:
seq = "非统招"... | 983e41ec210e8708605016477e1457b237693af4 | 53,978 |
def spread_segment_wise(starts, input_data):
"""
Generalized version of :func:`spread_residue_wise()`
for residues and chains.
Parameters
----------
starts : ndarray, dtype=int
The sorted start indices of segments.
Includes exclusive stop, i.e. the length of the corresponding
... | 2d99f76a0c05a9cde44af3ef4b56c585b7d04c68 | 53,979 |
def get_model(instance):
"""Get model by instance."""
return instance._meta.model | e386449ecd49d5874fb704c683c17d4492ea6f6c | 53,980 |
def encode(bananaFactory, obj):
"""
Banana encode an object using L{banana.Banana.sendEncoded}.
@param bananaFactory: A no-argument callable which will return a new,
unconnected protocol instance to use to do the encoding (this should
most likely be a L{banana.Banana} instance).
@param... | 40204f4bf93d115e0fa10f09587a2a891a30f6a6 | 53,981 |
def crossSpecgram(x, y, NFFT=256, Fs=2, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None) :
"""
Use matplotlib.mlab function, _spectral_helper, to calculate cross power between x and y in short time bins.
USAGE:
Pxy,freqs,t=crossSpe... | b2ac6372a2c2f442314d721693636656e90fe49d | 53,982 |
def force_slashend(path):
"""
Return ``path`` suffixed with ``/`` (path is unchanged if it is already
suffixed with ``/``).
"""
if not path.endswith('/'):
path = path + '/'
return path | 2e2be0dbb88fb380e581f49af532ea7b5724d918 | 53,983 |
from typing import Tuple
import re
def cell_to_num(x: str) -> Tuple[int, int]:
"""Converts a cell to a row, column index
:param x: Name of the cell (e.g. A2)
:type x: str
:return: Row, column index
:rtype: tuple
"""
regex = re.compile("([A-Z]*)([0-9]*)")
output = regex.search(x)
... | 6ad2b0b2d33e65a790a13f580f546bf2655a5dec | 53,985 |
def line_path_error_function(x, y, xerr, yerr, xa=-inf, xb=inf, samplefac=10):
"""Compute the probability that the data points actually lie along a
line given the x and y value of the data point, the errors
on the data, and the line parameters. If desired, compute only for the
segment extending from xa ... | 4673f952552e9d429a808c0f3c0520a93f2450ea | 53,986 |
def scoreboard(self: Client) -> ScoreboardProxy:
"""Delegates to a
:py:class:`mcipc.rcon.be.commands.scoreboard.ScoreboardProxy`
"""
return ScoreboardProxy(self, 'scoreboard') | 6c7c48a656fb5cc3c8e9d27f8deecb13767ce906 | 53,987 |
def apply_key_map(new_record: dict, old_record: dict, key_ref: dict):
"""
Apply key mapping between two records based on a key reference.
Example:
Given `key_ref`: `{'column1':'column2'}`.
Extracts values from `old_record['column1']` to `new_record['column2']`.
Parameters
----------
... | 8dbe68f182c1f0a425a1908a00e71214e4d186e3 | 53,989 |
def semantic_segmentation_labelling(img, label_config):
"""One-hot encoder for semantic segmentation problem
Parameters
----------
img : ndarray
Batched input image data of size (batch_size, image_size, image_size, 1)
label_config : dict
Label contained into the dataset
Returns... | aa559a2f13a4195305e67e28e616983037d8df87 | 53,991 |
def attack(y, k, s, m, a, c):
"""
Recovers the states associated with the outputs from a truncated linear congruential generator.
More information: Frieze, A. et al., "Reconstructing Truncated Integer Variables Satisfying Linear Congruences"
:param y: the sequential output values obtained from the trunc... | 3a2f9bbc1fb08af25c46ef1501f8784a7101e90b | 53,992 |
def inverse_odds(x, epsilon=EPSILON):
"""
Calculate probability from odds, and regularize returned probability to range [epsilon, 1-epsilon]
:param x: odds value
:return: probability value
"""
p = x/(1+x)
p = np.minimum(np.maximum(p, epsilon), 1 - epsilon)
return p | 10a14cefdd9a3af98729cfbb8c762485bfac6e2b | 53,993 |
def below_threshold(mat, threshold):
"""
:param mat: input image
:param threshold: threshold value
:return: values above the threshold are set to zero, and values less than or equal to the threshold are unchanged
"""
return cv2.threshold(mat, threshold, 0, cv2.THRESH_TOZERO_INV)[1] | 181057c6585a81bb32b0990b7fe5a6dc07e20b81 | 53,994 |
def read_pip():
""" Read and Return the pip dependencies """
datei = open('requirements.txt','r')
output_stream = []
for zeile in datei:
zeile = zeile.replace("\n", "")
output_stream.append(zeile)
datei.close()
return output_stream | 9b21b52fe702d77e1372cb9afbf985ac1e8ec914 | 53,995 |
from typing import Sequence
def interpret_quantity(value, expect_sequence):
"""Interpret a value as a pint Quantity via pisa.ureg
Parameters
----------
value : scalar, Quantity, or sequence interpretable as Quantity
expect_sequence : bool
Specify `True` if you expect a sequence of quantit... | 1b28f9b8f10f8eb79b67bd534ba105ac6399eb9d | 53,996 |
def either_sqrt(num):
"""What if we want to send some custom error message back instead of just
giving back an inscrutable Nothing? We can use the Either Monad!"""
if num < 0:
return either.Either.Left(
"You can't take the square root of a negative number!")
else:
return eith... | 0d0ec05b61bac26669899dc791e6713937430b5a | 53,997 |
def psy_ta_rh(tdb, rh, patm=101325):
""" Calculates psychrometric values of air based on dry bulb air temperature and
relative humidity.
For more accurate results we recommend the use of the the Python package
`psychrolib`_.
.. _psychrolib: https://pypi.org/project/PsychroLib/
Parameters
-... | 568b1bced541ec16c2490825838f4a8c80ef8a26 | 53,999 |
def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
"""
internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
"""
fmt = u("{%s}")
pairs = []
pfmt = u("%s: %s")
if max_seq_items is False:
nitems = len(seq)
els... | 2ed161c2d9e15b5636dd1c554a313f3e771320f9 | 54,000 |
import time
def acquire_lock(conn, lockname, identifier, acq_timeout=ACQ_TIMEOUT,
timeout=DEFAULT_TIMEOUT):
"""
Wait for and acquire a lock. Returns identifier on success and False
on failure.
Args:
conn: redis connection object
lockname: name of the lock
iden... | 4a9daca713b22ec9ad66aac9cd39a5addf133dfe | 54,002 |
def make_entries(screen, settings):
"""This function makes entries with keys, default values and labels from
settings. It returns a dictionary with entry widgets as values."""
entries = dict()
# For each setting, create a text field and put it next to the
# corresponding label.
for i, (key, def... | 80ee191b355b7802759848bd9dc5a40ef38d4788 | 54,003 |
def template_view_factory(template_name, context={}):
"""Returns a generic view which renders a template using the optional
context and request. """
return lambda request: render_to_response(template_name, context, request) | 3972d19a2884aadc848e62629ba6434cd505a118 | 54,004 |
from typing import Sequence
from typing import Mapping
from typing import Counter
def calculate_resource_utilization_for_kube_nodes(
nodes: Sequence[V1Node], pods_by_node: Mapping[str, Sequence[V1Pod]],
) -> ResourceUtilizationDict:
""" Given a list of Kubernetes nodes, calculate the total available
resou... | 6d3a8b6123d778975d33ad7fcf6e75354e125e0c | 54,005 |
def unfuse_right(A, shp):
"""
Reverses fuse_right.
"""
d, chiL, chiR = shp
A = A.reshape((chiL, d, chiR)).transpose((1, 0, 2))
return A | 31d2e50d3a5ca715dc04ee9305db76cbc566de3e | 54,006 |
from saq.database import get_db_connection
def delete_password(key):
"""Deletes the given password from the database. Returns True if the password was deleted."""
with get_db_connection(name=saq.CONFIG['global']['encrypted_passwords_db']) as db:
c = db.cursor()
c.execute("DELETE FROM `encrypte... | 4c00f0b70075a031cfb458dec62f10d478d16a67 | 54,007 |
def gaussion_f(mu, sigma2, x):
"""
Gaussian function
:param mu:
:param sigma2:
:param x:
:return:
"""
return 1 / sqrt(2 * pi * sigma2) * exp(-0.5 * (x - mu) / sigma2) | dbd299debe98d2c5dcc135edcab311f83881c93f | 54,008 |
def validate_owner_repo(ctx, param, value):
"""Ensure that owner/repo is formatted correctly."""
# pylint: disable=unused-argument
form = 'OWNER/REPO'
return validate_slashes(param, value, minimum=2, maximum=2, form=form) | 685bd4a14ee5e5fbb9df0627624ce37bf63d790b | 54,009 |
def squiggleFig(x1,y1,d1,a1,w1, x2,y2,d2,a2,w2):
"""Return a rounded bezier curve -- something like ~.
This is the naive implementation, using 2 identical slightly-offset
bezier curves to outline the figure. It looks uneven or calligraphic.
xn,yn = endpoints
dn = distance of control point from end... | d85b0a9d311fed24b95b2cf55feae58c53f5277d | 54,010 |
def check_free_space(min_free_space: int) -> bool:
"""
Check available free space in filesystem and return True/False if there is enough free space
or not.
min_free_space is measured in kB
"""
if not any([isinstance(min_free_space, int), isinstance(min_free_space, float)]):
log.warning(... | 8aa34685790fe3444a97795cbd7522969b10f0ac | 54,011 |
def spechum2mixr(q):
"""
Calculate mixing ratio from specific humidity.
**Inputs/Outputs**
Variable I/O Description Units
-------- --- ----------- -----
q I Specific humidity kg/kg
r O Mixing ratio kg/kg
"""
return q/(1-q) | 88a5109c00dedaba03f6f323437f661ef72b794e | 54,012 |
def get_formato_series(series, entidades):
"""
Convierte groupby a formato tidy (columnas son estados e indice es la fecha).
Input:
- series:
DataFrame en formato groupby agrupada for una columna que corresponde a
entidades federativas y otra columna que corresponde a una fecha.
- e... | 391202594898864390e52acd2806ef80cb96f9d0 | 54,013 |
def numpy_image_to_float(img, out_range=(0, 1)):
"""
Convert a numpy image (3d tensor, h x w x channels) into float format where
the output range is as given in out_range.
Return a numpy array.
"""
# http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.img_as_float
new_img = s... | 223340546802b966754b2eba02c62d44c9d6d657 | 54,014 |
def dataset_get_table_table_name_post(tableName): # noqa: E501
"""Returns the specified table
Returns the HTML Representation of the table. # noqa: E501
:param tableName: Should be equal to either bitcoin, bitconnect, dash, ethereum, iota, litecoin, monero, nem, neo, numeraire, omisego, qtum, ripple, str... | 3219a03cce5527da6d96271679e4c645cb949f45 | 54,015 |
def timeEvolutionMatrix(n, E, G, Q, Q_decay, tau, laser_wavelength, laser_intensity,
tau_f = None, detuning = None, symbolic_print = None, numeric_print = None,
rabi_scaling = None, rabi_factors = None, atomic_velocity = None):
"""Function to create and populate the co... | 77bf2bba3fff1fe3d9f644eedc3df8320171d3ef | 54,016 |
def load_focalplanes(args, comm, schedules, verbose=False):
""" Attach a focalplane to each of the schedules.
Args:
schedules (list) : List of Schedule instances.
Each schedule has two members, telescope
and ceslist, a list of CES objects.
Returns:
detweights (dict)... | 103010dcd05d9b37c10cb16c5e79789cf22901bd | 54,017 |
def in_cluster_scvelo_coh(adata, k_cluster, k_confidence, return_raw=False):
"""In-Cluster Confidence Score.
Args:
adata (Anndata): Anndata object.
k_cluster (str): key to the cluster column in adata.obs DataFrame.
k_confidence (str): key to the column of cell velocity confidence in... | 0032d75b447d03dfbf3d104d61bca585808a428e | 54,018 |
import asyncio
async def discover():
"""Discover and return devices on local network."""
discover = TuyaDiscovery()
try:
await discover.start()
await asyncio.sleep(DEFAULT_DISCOVER_TIMEOUT)
except Exception:
_LOGGER.exception("failed to discover devices")
finally:
d... | 7e30507ee4dc994971642c6b051820e5cbbf965b | 54,019 |
import time
import re
import types
def serve_responses(responses, passwords, pubkeys, port):
"""
Return a threading TCP based SocketServer listening on ``port``.
Used as a fake SSH server which will respond to commands given in
``responses`` and allow connections for users listed in ``passwords``.
... | a4c4b8950151a75476f68a7e3b81495a732165c4 | 54,020 |
def svn_client_mkdir2(*args):
"""svn_client_mkdir2(apr_array_header_t paths, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t"""
return _client.svn_client_mkdir2(*args) | 9a7a2e39f331c757d0be4e234d6452efccd16044 | 54,021 |
def factory_share_class(business_identifier: str):
"""Create a share class."""
business = factory_business(business_identifier)
share_class = ShareClass(
name='Share Class 1',
priority=1,
max_share_flag=True,
max_shares=1000,
par_value_flag=True,
par_value=0.8... | 7c2cf069e91c36ce3f314c753c8ddb8f86a9abb4 | 54,022 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.