content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_compiled_with_npu():
"""
Whether paddle was built with WITH_ASCEND_CL=ON to support Ascend NPU.
Returns (bool): `True` if NPU is supported, otherwise `False`.
Examples:
.. code-block:: python
import paddle
support_npu = paddle.device.is_compiled_with_npu()
"... | 54bf625843a098bfee93d8c1ac5b79bd562602fe | 19,900 |
def odd_occurrence_parity_set(arr):
"""
A similar implementation to the XOR idea above, but more naive.
As we iterate over the passed list, a working set keeps track of
the numbers that have occurred an odd number of times.
At the end, the set will only contain one number.
Though the worst... | 57f9362e05786724a1061bef07e49635b1b2b142 | 19,901 |
import time
def larmor_step_search(step_search_center=cfg.LARMOR_FREQ, steps=200, step_bw_MHz=5e-3, plot=False,
shim_x=cfg.SHIM_X, shim_y=cfg.SHIM_Y, shim_z=cfg.SHIM_Z, delay_s=1, gui_test=False):
"""
Run a stepped search through a range of frequencies to find the highest signal response
Used to find... | 647d67a491cf787dbc092a621c9ba5ad8097b21e | 19,902 |
from typing import Optional
def get_role_tempalte(context: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRoleTempalteResult:
"""
Use this data source to access information about an existing resource.
... | edc2bdaba9f287995f6c4323a4acb45935be02e4 | 19,903 |
from sklearn.metrics import roc_curve, roc_auc_score
def threshold_xr_via_auc(ds, df, res_factor=3, if_nodata='any'):
"""
Takes a xarray dataset/array of gdv likelihood values and thresholds them
according to a pandas dataframe (df) of field occurrence points. Scipy
roc curve and auc is generated to p... | 6415b7aa7298c7d2bf6488d5c9f0834facbd4300 | 19,904 |
def kd_or_scan(func=None, array=None, extra_data=None):
"""Decorator to allow functions to be call with a scan number or kd object """
if func is None:
return partial(kd_or_scan, array=array, extra_data=extra_data)
@wraps(func)
def wrapper(scan, *args, **kwargs):
# If scan number given... | 8eda0c54717293f57cd817f20a6f008abae6b825 | 19,905 |
def matching_intervals(original: DomainNode, approx: DomainNode, conf: float) -> bool:
""" Checks if 2 intervals match in respect to a confidence interval."""
# out_of_bounds = (not matching_bounds(original.domains[v], approx.domains[v], conf) for v in original.variables)
# return not any(out_of_bounds)
... | bb2540872d0406b88551ec5b3a9ef28fbc39d366 | 19,906 |
def _make_label_sigmoid_cross_entropy_loss(logits, present_labels, split):
""" Helper function to create label loss
Parameters
----------
logits: tensor of shape [batch_size, num_verts, num_labels]
present_labels: tensor of shape [batch_size, num_verts, num_labels]; labels of labelled verts
spl... | 290364255222f20ef864636ef2ac8df51599a587 | 19,907 |
import copy
def _merge_meta(base, child):
"""Merge the base and the child meta attributes.
List entries, such as ``indexes`` are concatenated.
``abstract`` value is set to ``True`` only if defined as such
in the child class.
Args:
base (dict):
``meta`` attribute from the base... | ba219b8091244a60658bee826fbef5003d3f7883 | 19,908 |
from typing import Dict
from typing import Any
def _parse_quotes(quotes_dict: Dict[str, Dict[str, Dict[str, Any]]]) -> "RegionalQuotes":
"""
Parse quote data for a :class:`~.DetailedProduct`.
:param quotes_dict:
"""
quotes: RegionalQuotes = RegionalQuotes()
for gsp, payment_methods in quotes_dict.items():
... | 82ea906391b5e3d23a40619eefc19eaa353e18bc | 19,909 |
def train_validation(train_df, valid_df, epochs=100, batch_size=512, plot=False,
nn_args={}):
"""
Wrapper for training on the complete training data and evaluating the
performance on the hold-out set.
Parameter:
-------------------
train_df: df,
train df... | 7dffa50d427c0e74fe4f6e6a8ff1e0198304de2a | 19,910 |
import subprocess
def retrieve_email() -> str:
"""
Uses the Git command to retrieve the current configured user email address.
:return: The global configured user email.
"""
return subprocess.run(
["git", "config", "--get", "user.email"],
capture_output=True,
text=True,
... | 4d2308f3b9376b9b7406f9594c52b8a8ebba04f5 | 19,911 |
import warnings
import inspect
def bootstrap_compute(
hind,
verif,
hist=None,
alignment="same_verifs",
metric="pearson_r",
comparison="m2e",
dim="init",
reference=["uninitialized", "persistence"],
resample_dim="member",
sig=95,
iterations=500,
pers_sig=None,
compute... | 1a419d129419d15276f21f6f09bbd613a8e662da | 19,912 |
def description_for_number(numobj, lang, script=None, region=None):
"""Return a text description of a PhoneNumber object for the given language.
The description might consist of the name of the country where the phone
number is from and/or the name of the geographical area the phone number
is from. Th... | d67d53528c99c8b3ce6323c7e4eb5170603660c1 | 19,913 |
def _construct_new_particles(samples, old_particles):
"""Construct new array of particles given the drawing results over the old
particles.
Args:
+ *samples* (np.ndarray):
NxM array that contains the drawing results, where N is number of
observations and M number of part... | ec511554074f637466d47d24c449eda8a263100e | 19,914 |
def trunc(x, y, w, h):
"""Truncates x and y coordinates to live in the (0, 0) to (w, h)
Args:
x: the x-coordinate of a point
y: the y-coordinate of a point
w: the width of the truncation box
h: the height of the truncation box.
"""
return min(max(x, 0), w - 1), min... | 3edecdfbd9baf24f8b4f3f71b9e35a222c6be1ea | 19,915 |
import os
import sys
def testInputLog(log_file):
""" Test the user input for issues in the DNS query logs """
# if the path is a file
if os.path.isfile(log_file):
pass
else:
print("WARNING: Bad Input - Use a DNS (text) log file which has one domain per row without any other data or punctuation.")
print("Ex... | c50900dbef8d978e3f7b8349a7ae072c2bab3415 | 19,916 |
def exact_match(true_labels, predicts):
""" exact_match
This is the most strict metric for the multi label setting. It's defined
as the percentage of samples that have all their labels correctly classified.
Parameters
----------
true_labels: numpy.ndarray of shape (n_samples, n_target... | ebcc1d6ce96ff8b5933e16ce69f5e143e371bf28 | 19,917 |
def dimred3(dat):
"""convenience function dimensionally reduce input data, each row being an
element in some vector space, to dimension 3 using PCA calcualted by the
SVD"""
return dimred(dat, 3) | 5151ee8bb0e8bcfe6dbb1633d95e9b355714ae35 | 19,918 |
def render_orchestrator_registrations(
driver: Driver = None,
collab_id: str = None,
project_id: str = None
):
""" Renders out retrieved registration metadata in a custom form
Args:
driver (Driver): A connected Synergos driver to communicate with the
selected orchestrator.
... | 14a84029ff20a09d2c8c6e41007827f96fb35f60 | 19,919 |
def check_nan(data, new_data):
"""checks if nan values are conserved
"""
old = np.isnan(data)
new = np.isnan(new_data)
if np.all(new == old):
return True
else:
return False | d1dafaadd6e37848aa147b6714cce74f6097e074 | 19,920 |
def Var(poly, dist=None, **kws):
"""
Element by element 2nd order statistics.
Args:
poly (chaospy.poly.ndpoly, Dist):
Input to take variance on.
dist (Dist):
Defines the space the variance is taken on. It is ignored if
``poly`` is a distribution.
Ret... | 6ec5e867ed7287f90584e0c134d29b8daf4f9b9c | 19,921 |
def op_par_loop_parse(text):
"""Parsing for op_par_loop calls"""
loop_args = []
search = "op_par_loop"
i = text.find(search)
while i > -1:
arg_string = text[text.find('(', i) + 1:text.find(';', i + 11)]
# parse arguments in par loop
temp_args = []
num_args = 0
# parse each op_arg_dat
... | 826bb5cd58e4b34846419fc47977caa73fd5573c | 19,922 |
def bin_to_hex(bin_str: str) -> str:
"""Convert a binary string to a hex string.
The returned hex string will contain the prefix '0x' only
if given a binary string with the prefix '0b'.
Args:
bin_str (str): Binary string (e.g. '0b1001')
Returns:
str: Hexadecimal string zero... | 0f44311a600a7b5eac52d3716db4b116302c97ac | 19,923 |
def exp_value_interpolate_bp(prod_inst, util_opti,
b_ssv_sd, k_ssv_sd, epsilon_ssv_sd,
b_ssv, k_ssv, epsilon_ssv,
b_ssv_zr, k_ssv_zr, epsilon_ssv_zr,
states_vfi_dim, shocks_vfi_dim):
"""interpolate va... | e8d698834186efa779bbd81b042e9cf4caa1276a | 19,924 |
from typing import Union
from typing import List
def remove_non_protein(
molecule: oechem.OEGraphMol,
exceptions: Union[None, List[str]] = None,
remove_water: bool = False,
) -> oechem.OEGraphMol:
"""
Remove non-protein atoms from an OpenEye molecule.
Parameters
----------
molecule: oe... | 6afa4df25cbcf504b2ac06325a3e89291e9a0e4f | 19,925 |
import json
def configure_connection(instance, name='eventstreams', credentials=None):
"""Configures IBM Streams for a certain connection.
Creates an application configuration object containing the required properties with connection information.
Example for creating a configuration for a Streams inst... | 5f263af94590e7237e27dc90f2e502b952d010fc | 19,926 |
def setup(app):
"""
Any time a python class is referenced, make it a pretty link that doesn't
include the full package path. This makes the base classes much prettier.
"""
app.add_role_to_domain("py", "class", truncate_class_role)
return {"parallel_read_safe": True} | 69660fd86216dfe0a5642b0885dbdb0704ce8ffc | 19,927 |
def transects_to_gdf(transects):
"""
Saves the shore-normal transects as a gpd.GeoDataFrame
KV WRL 2018
Arguments:
-----------
transects: dict
contains the coordinates of the transects
Returns:
-----------
gdf_all: gpd.GeoDataFrame
... | a2e1c517a7d4d86618a08da07459686fa947d597 | 19,928 |
def deduce_final_configuration(fetched_config):
""" Fills some variables in configuration based on those already extracted.
Args:
fetched_config (dict): Configuration variables extracted from a living environment,
Returns:
dict: Final configuration from live environment.
"""
final_c... | 30d21a8eb0bd1d282dbd127551e55fc7061e82ed | 19,929 |
def total_benchmark_return_nb(benchmark_value: tp.Array2d) -> tp.Array1d:
"""Get total market return per column/group."""
out = np.empty(benchmark_value.shape[1], dtype=np.float_)
for col in range(benchmark_value.shape[1]):
out[col] = returns_nb.get_return_nb(benchmark_value[0, col], benchmark_value... | 74d2924031dc4f0251b346555bc473d8d225453d | 19,930 |
def young_modulus(data):
"""
Given a stress-strain dataset, returns Young's Modulus.
"""
yielding = yield_stress(data)[0]
"""Finds the yield index"""
yield_index = 0
for index, point in enumerate(data):
if (point == yielding).all():
yield_index = index
... | f41d4c358ae58760055d72e0364a3f79b7258512 | 19,931 |
def generateODTableDf(database: pd.DataFrame, save: bool = True) -> pd.DataFrame:
"""生成各区间OD表相关的数据集
Args:
database (pd.DataFrame): 经初始化的原始数据集
save (bool, optional): 是否另外将其保存为csv文件. Defaults to True.
Returns:
pd.DataFrame: 各区间OD表相关的数据集
"""
table4OD: np.ndarray = fetchTable4O... | 9660d1c604e0f3514bb9a168ef91b3f29d7ba8b9 | 19,932 |
import typing
def check_datatype(many: bool):
"""Checks if data/filter to be inserted is a dictionary"""
def wrapper(func):
def inner_wrapper(self, _filter={}, _data=None, **kwargs):
if _data is None: # statements without two args - find, insert etc
if many: # statements... | c5300507936db04b2ae5e4190421cc354f6ac2d4 | 19,933 |
def login():
"""Login Page"""
if request.cookies.get('user_id') and request.cookies.get('username'):
session['user_id'] = request.cookies.get('user_id')
session['username'] = request.cookies.get('username')
update_last_login(session['user_id'])
return render_template('main/index.... | e8f02d520c5913e8d8d2c99d1a98b9c546a9a220 | 19,934 |
def _get_index_train_test_path(split_num, train = True):
"""
Method to generate the path containing the training/test split for the given
split number (generally from 1 to 20).
@param split_num Split number for which the data has to be generated
@param train Is true if the ... | 201ac816085211b1f6500e2b84d5e9b293dd8c2e | 19,935 |
def mock_socket() -> MagicMock:
"""A mock websocket."""
return MagicMock(spec=WebSocket) | a3b8e53d2c929566e2bc9419cfb1d56ca3f25032 | 19,936 |
import os
def extract_annotations_objtrk(out_path, in_image, project_id, track_prefix, **kwargs):
"""
out_path: str
in_image: BiaflowsCytomineInput
project_id: int
track_prefix: str
kwargs: dict
"""
image = in_image.object
path = os.path.join(out_path, in_image.filename)
data, ... | 0fb1ec074ae01d536fcf9a8e63536e6d8f02bdf8 | 19,937 |
def gen_device(dtype, ip, mac, desc, cloud):
"""Convenience function that generates devices based on they type."""
devices = {
# sp1: [0],
sp2: [
0x2711, # SP2
0x2719,
0x7919,
0x271A,
0x791A, # Honeywell SP2
0x2720, # SP... | 07c9ff4ee594bf0c94aa95efc05f63306811e996 | 19,938 |
import subprocess
def berks(berks_bin, path, action='update'):
"""
Execute various berks commands
:rtype : tuple
:param berks_bin: path to berks bin
:param path: path to change directory to before running berks commands (berks is a dir context aware tool)
:param action: berks action to run, e.... | c0f20cccc3a9be747f45f6253a61b455bef69f2c | 19,939 |
def container_clone(request, pk):
"""
Make a clone of the container.
Todo: show params on OPTIONS call.
Todo: permissions
:param pk pk of the container that needs to be cloned
:param name
:param description
"""
params = {}
data = request.data
if not data.get('name'):
... | c546d2810dd62b88b737477df3ad836c4aabb20b | 19,940 |
def parse_multi_id_graph(graph, ids):
"""
Parse a graph with 1 to 3 ids and return
individual graphs with their own braced IDs.
"""
new_graphs = ''
LEVEL_STATE.next_token = ids[0]
pid1 = LEVEL_STATE.next_id()
split1 = graph.partition('({})'.format(ids[1]))
text1 = combine_bolds(split... | 3dc693e359573ec1a2e71400856e0383653a5533 | 19,941 |
import os
def filter_multimappers(align_file, data):
"""
It does not seem like bowtie2 has a corollary to the -m 1 flag in bowtie,
there are some options that are close but don't do the same thing. Bowtie2
sets the XS flag for reads mapping in more than one place, so we can just
filter on that. Th... | 76e55ca8f29eee13d50bb74249cc25ae91f56d22 | 19,942 |
import types
import inspect
def try_run(obj, names):
"""Given a list of possible method names, try to run them with the
provided object. Keep going until something works. Used to run
setup/teardown methods for module, package, and function tests.
"""
for name in names:
func = getattr(obj, ... | d35377eecd31ce70ae8e4588ac04320d8b48845f | 19,943 |
import os
import requests
def download_file(url, path=None, clobber=False):
"""
thanks to: https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py
path : str
local path to download to.
"""
if path is None:
local_filename = os.path.join(di... | 54076659f79fb35305eb5a5ea3d0dd1eba402bc7 | 19,944 |
def param_to_secopt(param):
"""Convert a parameter name to INI section and option.
Split on the first dot. If not dot exists, return name
as option, and None for section."""
sep = '.'
sep_loc = param.find(sep)
if sep_loc == -1:
# no dot in name, skip it
section = None
opt... | 7d7e2b03cb67ed26d184f85f0328236674fa6497 | 19,945 |
from typing import List
from typing import Dict
import json
def load_contracts(
web3: web3.Web3, contracts_file: str, contracts_names: List[str]
) -> Dict[str, web3.contract.Contract]:
"""
Given a list of contract names, returns a dict of contract names and contracts.
"""
res = {}
with open(co... | 6f6c47c5742de0c61eddacfd9358b6d86eefb525 | 19,946 |
import logging
def removecandidate(_id=''):
"""
Remove a candidate from the candidate list
Use with the lexcion's identifiers
/removecandidate?identifier=katt..nn.1
"""
lexicon = request.args.get('lexicon', C.config['default'])
lexconf = lexconfig.get_lexiconconf(lexicon)
try:
... | 55d9cfede364a35e44cf44b597653de598867d55 | 19,947 |
def outlier_dates_correction(series, coef=2.0):
"""Corrects the dates that are outliers.
It receives all the dates in which samples were collected,
for example for a patient and tries to (i) identify
outliers and (ii) correct them with the best possible
date.
.. note: Using mean/std for outlie... | fa371b682f943801affa47d3f1a13f5daac9323a | 19,948 |
def svn_log_entry_dup(*args):
"""svn_log_entry_dup(svn_log_entry_t log_entry, apr_pool_t pool) -> svn_log_entry_t"""
return _core.svn_log_entry_dup(*args) | 223e7aa1dbf890eae3c5aa86a08cac287ce796c8 | 19,949 |
from typing import IO
from io import StringIO
def input_stream() -> IO:
"""Input stream fixture."""
return StringIO(
"""mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0"""
) | 6e9e65754478b0ff69d220f683140675d3f6efdc | 19,950 |
def get_lr_scheduler(optimizer: Optimizer, cfg: CfgNode, start_epoch: int = 0):
"""Returns LR scheduler module"""
# Get mode
if cfg.TRAIN.LOSS.TYPE in ["categorical_crossentropy", "focal_loss"]:
mode = "min"
else:
raise NotImplementedError
if cfg.TRAIN.SCHEDULER.TYPE == "ReduceLROn... | 59bbb672ac74fcc0331e5cba5bd722ce41049a5d | 19,951 |
async def create_and_open_pool(pool_name, pool_genesis_txn_file):
"""
Creates a new local pool ledger configuration.
Then open that pool and return the pool handle that can be used later
to connect pool nodes.
:param pool_name: Name of the pool ledger configuration.
:param pool_genesis_txn_file... | eb05893870ff1b8928391c0e748d21b9eb8aef66 | 19,952 |
def rotate_char(c, n):
"""Rotate a single character n places in the alphabet
n is an integer
"""
# alpha_number and new_alpha_number will represent the
# place in the alphabet (as distinct from the ASCII code)
# So alpha_number('a')==0
# alpha_base is the ASCII code for the first letter of ... | b1259722c7fb2a60bd943e86d87163866432539f | 19,953 |
def subset_language(vocabulary, vectors, wordlist, N=32768):
"""
Subset the vocabulary/vectors to those in a wordlist.
The wordlist is a list arranged in order of 'preference'.
Note: we hope the vocabulary is contained in the wordlist,
but it might not be. N is the number of words we require.
If... | 17c5718134f25f1ef7b6ed8fb0086fc1f45d058b | 19,954 |
def compile_subject(*, subject_id, date_of_birth, sex):
"""Compiles the NWB Subject object."""
return Subject(subject_id=subject_id, date_of_birth=date_of_birth, sex=sex) | 86fc69318cfac98f44b11fa4f4c2a47423da317d | 19,955 |
from typing import Any
def circulation(**kwargs: Any) -> str:
"""Url to get :class:`~pymultimatic.model.component.Circulation` details."""
return _CIRCULATION.format(**kwargs) | 021d28b92cfac9a69723796d2ee29f53dc16039d | 19,956 |
def split_parentheses(info):
"""
make all strings inside parentheses a list
:param s: a list of strings (called info)
:return: info list without parentheses
"""
# if we see the "(" sign, then we start adding stuff to a temp list
# in case of ")" sign, we append the temp list to the new_info ... | 37006936d52abe31e6d5e5d264440ab4950d874b | 19,957 |
from typing import Optional
from typing import Callable
import inspect
def event(
name: Optional[str] = None, *, handler: bool = False
) -> Callable[[EventCallable], EventCallable]:
"""Create a new event using the signature of a decorated function.
Events must be defined before handlers can be registered... | ce7821bbe67c3c776f8dfa4b69a4bed25ab814e3 | 19,958 |
import sys
def getcallargs(func, *positional, **named):
"""Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'."""
args, vara... | a693bed0b7c5f6d6ab8caf2b669f4368b56c8ea8 | 19,959 |
import re
def add_target_to_anchors(string_to_fix, target="_blank"):
"""Given arbitrary string, find <a> tags and add target attributes"""
pattern = re.compile("<a(?P<attributes>.*?)>")
def repl_func(matchobj):
pattern = re.compile("target=['\"].+?['\"]")
attributes = matchobj.group("... | 4650dcf933e9b6e153646c6b7f3535881e4db1f8 | 19,960 |
def calcInvariants(S, R, gradT, with_tensor_basis=False, reduced=True):
"""
This function calculates the invariant basis at one point.
Arguments:
S -- symmetric part of local velocity gradient (numpy array shape (3,3))
R -- anti-symmetric part of local velocity gradient (numpy array shape (3,3))
... | 2ce8407843947c4f7c9779d061971822707f147e | 19,961 |
def with_uproot(histo_path: str) -> bh.Histogram:
"""Reads a histogram with uproot and returns it.
Args:
histo_path (str): path to histogram, use a colon to distinguish between path to
file and path to histogram within file (example: ``file.root:h1``)
Returns:
bh.Histogram: his... | c03e7c7054a550769c23c904892c0c327b2bcafa | 19,962 |
def slide5x5(xss):
"""Slide five artists at a time."""
return slidingwindow(5, 5, xss) | 56374e53384d2012d2e6352efcd0e972ff3d04bf | 19,963 |
def compute_consensus_rule(
profile,
committeesize,
algorithm="fastest",
resolute=True,
max_num_of_committees=MAX_NUM_OF_COMMITTEES_DEFAULT,
):
"""
Compute winning committees with the Consensus rule.
Based on Perpetual Consensus from
Martin Lackner Perpetual Voting: Fairness in Long... | 0dd12aa8faab485a62cdeccfaf87385df85b0b7f | 19,964 |
def addcron():
"""
{
"uid": "张三",
"mission_name": "定时服务名字",
"pid": "c3009c8e62544a23ba894fe5519a6b64",
"EnvId": "9d289cf07b244c91b81ce6bb54f2d627",
"SuiteIdList": ["75cc456d9c4d41f6980e02f46d611a5c"],
"runDate": 1239863854,
"interval": 60,
"alwaysS... | 87aca95b6486bbbd9abd9277aa3e2eb39b7bbdad | 19,965 |
def dict_expand(d, prefix=None):
"""
Recursively expand subdictionaries returning dictionary
dict_expand({1:{2:3}, 4:5}) = {(1,2):3, 4:5}
"""
result = {}
for k, v in d.items():
if isinstance(v, dict):
result.update(dict_expand(v, prefix=k))
else:
result[k]... | 842503eaffca7574f127b731216b5f5b10ddf86f | 19,966 |
def parse_config_list(config_list):
"""
Parse a list of configuration properties separated by '='
"""
if config_list is None:
return {}
else:
mapping = {}
for pair in config_list:
if (constants.CONFIG_SEPARATOR not in pair) or (pair.count(constants.CONFIG_SEPARATOR) != 1):
raise Valu... | 12ab7dc51420196a60ef027ea606a837da3b1b59 | 19,967 |
def collaspe_fclusters(data=None, t=None, row_labels=None, col_labels=None,
linkage='average', pdist='euclidean', standardize=3, log=False):
"""a function to collaspe flat clusters by averaging the vectors within
each flat clusters achieved from hierarchical clustering"""
## preprocess data
if log:
data = np.l... | 879ba2e9469831b096f716dbbb38047580d76844 | 19,968 |
from typing import Union
def iapproximate_add_fourier_state(self,
lhs: Union[int, QuantumRegister],
rhs: QRegisterPhaseLE,
qcirc: QuantumCircuit,
approximation: int = None) -> Ap... | 3e1ccb2576e8babdb589c60aec51f585001bdd9a | 19,969 |
import itertools
def _get_indices(A):
"""Gets the index for each element in the array."""
dim_ranges = [range(size) for size in A.shape]
if len(dim_ranges) == 1:
return dim_ranges[0]
return itertools.product(*dim_ranges) | dc2e77c010a6cfd7dbc7b7169f4bd0d8da62b891 | 19,970 |
def calculateOriginalVega(f, k, r, t, v, cp):
"""计算原始vega值"""
price1 = calculatePrice(f, k, r, t, v*STEP_UP, cp)
price2 = calculatePrice(f, k, r, t, v*STEP_DOWN, cp)
vega = (price1 - price2) / (v * STEP_DIFF)
return vega | 7b90662003231b50c4d758c3a7beb122b90c05e7 | 19,971 |
from typing import Optional
from typing import Dict
import sys
import os
import subprocess
def run_ansible_lint(
*argv: str,
cwd: Optional[str] = None,
executable: Optional[str] = None,
env: Optional[Dict[str, str]] = None
) -> CompletedProcess:
"""Run ansible-lint on a given path and returns its ... | 9d4911f903727a7fab33eced48d3856ad592e8e9 | 19,972 |
def to_numpy(tensor):
""" Converts a PyTorch Tensor to a Numpy array"""
if isinstance(tensor, np.ndarray):
return tensor
if hasattr(tensor, 'is_cuda'):
if tensor.is_cuda:
return tensor.cpu().detach().numpy()
if hasattr(tensor, 'detach'):
return tensor.detach().numpy()... | c5186918fe7a07054607df500d61b32ae1b0037f | 19,973 |
import glob
import os
def show_tables():
"""
Load all available data files that have the right format.
All files will be assumed to have the same 8 fields in the header.
This demonstrates pulling a specific file name as well as
wildcard file search in the uploads/ directory.
And as an example,... | f815eb657a97c76b2c872ebda3774080de7cbd33 | 19,974 |
import os
import sys
def _redirect_io(inp, out, f):
"""Calls the function `f` with ``sys.stdin`` changed to `inp`
and ``sys.stdout`` changed to `out`. They are restored when `f`
returns. This function returns whatever `f` returns.
"""
oldin, sys.stdin = sys.stdin, inp
oldout, sys.stdout = ... | 30c00128826789ca008e2ca4dcc8fe5f754fe4f6 | 19,975 |
def _maybe_to_dense(obj):
"""
try to convert to dense
"""
if hasattr(obj, 'to_dense'):
return obj.to_dense()
return obj | a2f18aec19bd0bad58a35e772180b94d649262e1 | 19,976 |
def update_visit_counter(visit_counter_matrix, observation, action):
"""Update the visit counter
Counting how many times a state-action pair has been
visited. This information can be used during the update.
@param visit_counter_matrix a matrix initialised with zeros
@param observation the state... | 418097d34f194c81e38e3d6b122ae743c7b73452 | 19,977 |
from datetime import datetime
def pandas_time_safe(series):
"""Pandas check time safe"""
return (series.map(dt_seconds)
if isinstance(series.iloc[0], datetime.time)
else series) | f802d7ad4cd9c9dbf426b2c1436c41402b24da0b | 19,978 |
def binary_cross_entropy_loss(predicted_y, true_y):
"""Compute the binary cross entropy loss between a vector of labels of size N and a vector of probabilities of same
size
Parameters
----------
predicted_y : numpy array of shape (N, 1)
The predicted probabilities
true_y : numpy array o... | ba72db9051976a9d07355a1b246a22faea43b2b1 | 19,979 |
def money_flow_index(high, low, close, volume, n=14, fillna=False):
"""Money Flow Index (MFI)
Uses both price and volume to measure buying and selling pressure. It is
positive when the typical price rises (buying pressure) and negative when
the typical price declines (selling pressure). A ratio of posi... | bd2cbb7b18c7be8d5c0ec0a984c4f3cadf295eec | 19,980 |
def parse_args(args=[], doc=False):
"""
Handle parsing of arguments and flags. Generates docs using help from `ArgParser`
Args:
args (list): argv passed to the binary
doc (bool): If the function should generate and return manpage
Returns:
Processed args and a copy of the `ArgPa... | 355d8e8722171ab64ebdc02d1fe39db7521a497b | 19,981 |
def gaussian_kernel_dx_i_dx_j(x, y, sigma=1.):
""" Matrix of \frac{\partial k}{\partial x_i \partial x_j}"""
assert(len(x.shape) == 1)
assert(len(y.shape) == 1)
d = x.size
pairwise_dist = np.outer(y-x, y-x)
x_2d = x[np.newaxis,:]
y_2d = y[np.newaxis,:]
k = gaussian_kernel(x_2d, y_2d, ... | 626f38a5a5e1e7c7dd98c92636a424c74fc7146b | 19,982 |
from pathlib import Path
import tarfile
def clone_compressed_repository(base_path, name):
"""Decompress and clone a repository."""
compressed_repo_path = Path(__file__).parent / "tests" / "fixtures" / f"{name}.tar.gz"
working_dir = base_path / name
bare_base_path = working_dir / "bare"
with tarf... | bbd733b079ebedb91687597180b0f98825f6ed6c | 19,983 |
def slices(series, length):
"""
Given a string of digits, output all the contiguous substrings
of length n in that string in the order that they appear.
:param series string - string of digits.
:param length int - the length of the series to find.
:return list - List of substrings of specif... | ea2d1caf26a3fc2e2a57858a7364b4ebe67297d6 | 19,984 |
from where.models.delay import gnss_range # Local import to avoid cyclical import
def get_flight_time(dset):
"""Get flight time of GNSS signal between satellite and receiver
Args:
dset(Dataset): Model data
Return:
numpy.ndarray: Flight time of GNSS signal between satellite and rec... | 503bfb55fc10bef9f610291aa0f35e0530c8b0f2 | 19,985 |
def textToTuple(text, defaultTuple):
"""This will convert the text representation of a tuple into a real
tuple. No checking for type or number of elements is done. See
textToTypeTuple for that.
"""
# first make sure that the text starts and ends with brackets
text = text.strip()
if t... | 89fed32bff39ad9e69513d7e743eb05a3bf7141a | 19,986 |
def m2m_bi2uni(m2m_list):
""" Splits a bigram word model into a unique unigram word model
i=11, j=3 i=10, j=3 i=9,10,11,12, j=3,4,5,6
###leilatem### ###leilatem### ###leilatem###
###temum### ###temum### ###temum###
^ ... | 37f1644dc16bc0e4dd47acd7a69f1c2d6fbfc6d5 | 19,987 |
import time
def time_func(func):
"""Times how long a function takes to run.
It doesn't do anything clever to avoid the various pitfalls of timing a function's runtime.
(Interestingly, the timeit module doesn't supply a straightforward interface to run a particular
function.)
"""
def timed(*a... | 3506ad28c424434402f3223a43daff4eb51b7763 | 19,988 |
def GetPhiPsiChainsAndResiduesInfo(MoleculeName, Categorize = True):
"""Get phi and psi torsion angle information for residues across chains in
a molecule containing amino acids.
The phi and psi angles are optionally categorized into the following groups
corresponding to four types of Ramachandran plo... | 07295d99f3f2150e4a9e0782bf376ac1aa22a499 | 19,989 |
def generate_data(n_samples=30):
"""Generate synthetic dataset. Returns `data_train`, `data_test`,
`target_train`."""
x_min, x_max = -3, 3
x = rng.uniform(x_min, x_max, size=n_samples)
noise = 4.0 * rng.randn(n_samples)
y = x ** 3 - 0.5 * (x + 1) ** 2 + noise
y /= y.std()
data_train = p... | f7d2f5637327119d5f08fe2ccbfe2d4f41a34c5c | 19,990 |
def get_element_event(element_key):
"""
Get object's event.
"""
model = apps.get_model(settings.WORLD_DATA_APP, "event_data")
return model.objects.filter(trigger_obj=element_key) | bd177573035209e97110a2213cbe98b3b2eadafb | 19,991 |
import operator
def get_seller_price(sellers,seller_id,core_request):
"""
sellers is a list of list where each list contains follwing item in order
1. Seller Name
2. Number of available cores
3. Price of each core
4. List of lists where length of main list is equal to number of cores. Length of minor list will ... | a1103b05409cdab20dd1982f5839a712939c3c3f | 19,992 |
def create_affiliation_ttl(noun_uri: str, noun_text: str, affiliated_text: str, affiliated_type: str) -> list:
"""
Creates the Turtle for an Affiliation.
@param noun_uri: String holding the entity/URI to be affiliated
@param noun_text: String holding the sentence text for the entity
@param affiliat... | d641a5aa77860dad48c605b3486bc83c0250d551 | 19,993 |
from typing import Tuple
def get_subpixel_indices(col_num: int) -> Tuple[int, int, int]:
"""Return a 3-tuple of 1-indexed column indices representing subpixels of a single pixel."""
offset = (col_num - 1) * 2
red_index = col_num + offset
green_index = col_num + offset + 1
blue_index = col_num + of... | cb4a1b9a4d27c3a1dad0760267e6732fe2d0a0da | 19,994 |
def sigmoid(x):
""" This function computes the sigmoid of x for NeuralNetwork"""
return NN.sigmoid(x) | 534391dc7b39aede21e6a66692bc1ca2ea1ce8b6 | 19,995 |
def extractTranslatingSloth(item):
"""
'Translating Sloth'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
tagmap = [
('娘子我才是娃的爹', 'Wife, I Am the Baby\'s Father', 'translated'),
... | 0ed9f5d4ae4c69fae2dc46e0260e29d1c97225af | 19,996 |
def human(number: int, suffix='B') -> str:
"""Return a human readable memory size in a string.
Initially written by Fred Cirera, modified and shared by Sridhar Ratnakumar
(https://stackoverflow.com/a/1094933/6167478), edited by Victor Domingos.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z'... | b41e9014ee7afbacb40115f85223ae89b08094a8 | 19,997 |
def _get_field_names(field: str, aliases: dict):
"""
Override this method to customize how
:param field:
:param aliases:
:return:
"""
trimmed = field.lstrip("-")
alias = aliases.get(trimmed, trimmed)
return alias.split(",") | cb732c07018c33a546bf42ab1bf3516d2bd6c824 | 19,998 |
def get_answer(question_with_context):
"""
Get answer for question and context.
"""
# Create pipeline
question_answering_pipeline = pipeline('question-answering')
# Get answer
answer = question_answering_pipeline(question_with_context)
# Return answer
return answer | ba560ecf5aa07a59b697465e0c34c8b32ddf64e6 | 19,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.