content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def file_selector():
"""Function enables the user to select the txt files that they have downloaded.
returns:
"""
layout = [[sg.Text("Choose a file: "),sg.Input(key="-IN2-" ,change_submits=True), sg.FileBrowse(key="-IN-")],
[sg.Button("Submit")]]
window = sg.Window("File... | 8fe699f164ebf8f75eb2bde5a5fd9a52a7f196a5 | 3,612,700 |
import yaml
def connect_cursor(USERPATH):
"""Connect a cursor to database.
Input: Path to authorized user "secrets.yaml" file that is
expected to include connection parameters
Output: Database cursor object
Future consideration:
enable user to input latest year of available data inste... | 4a3869c703f73c21fc205e0cf203bfbeb92edf80 | 3,612,701 |
from typing import Dict
from typing import List
def avoid_other_snakes(my_head: Dict[str, int], snakes: List[dict], possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates of the Battlesnake head.
e.g. {"x": 0, "y": 0}
snakes: List of dictionaries containing informa... | 2e2db43353f3bc16c6a064ecd6999c9226931237 | 3,612,702 |
def calculateJitterPercent(data):
"""
calculate jitter in percent
"""
return calculateJitterRatio(data) / 10.0 | 631903f270532b062e62aee8b4f0cebbfb406b4f | 3,612,703 |
import os
import re
def create_sim_openmm(model, anchor, output_filename, state_prefix=None):
"""
Take all relevant model and anchor information and generate
the necessary OpenMM objects to run the simulation.
Parameters
----------
model : Model()
The Model which contains the anch... | 2b958e93cafe69dc8c7f1f5d1d4b8a11138988e7 | 3,612,704 |
def process_tenant(aci_session, tenant, override=False, fetch_endpoints=False):
"""
:param aci_session: ACI session
:param tenant: Cisco Tenant Object
:param override: Purge existing configurations for this Tenant in BAM
:param fetch_endpoints: Boolean - Import endpoints
:return:
"""
if... | 8cf8640848c8830ea9e78f326672965806451483 | 3,612,705 |
def get_supported_formats(request):
"""Return a dictionary of possible conversions between image formats.
CSRF protection is not required on GET request."""
if request.method == "GET":
return JsonResponse(data=SUPPORTED_FORMATS)
else:
return HttpResponse(content="Use GET method", status=... | cf3c2e8341cdd41ef1129eec8603fe222bd43d6c | 3,612,706 |
import functools
def tf_cache_template(function, scope=None, *args, **kwargs):
"""
A decorator for class methods that define TensorFlow operations.
The function is first wrapped in a variable_scope() that allows
us to specify a initializer, regularizer etc.
The result is then wrapped in a make_t... | 8b0d23cc9d249b79c1d7ceb67545fbee45c6b87c | 3,612,707 |
def nms(dets, thresh, soft_nms=False):
"""Dispatch to either CPU or GPU NMS implementations."""
if dets.shape[0] == 0:
return []
elif soft_nms:
return cpu_soft_nms(dets, thresh, method = 1)
else:
return cpu_nms(dets, thresh) | 9a1c67f35a9cdb0ff6cb2e95b97818f2cae90028 | 3,612,708 |
def mean_expression(df, annotation, stage_regex=r".*", normal=False):
"""Return the mean expression values of the subset of samples.
Parameters
----------
df: pandas.DataFrame
Each row is a gene and each column is a sample.
annotation: pandas.DataFrame
A data frame w... | 7e404aa4a69b7b967d830463d21d611e0cd47b36 | 3,612,709 |
def get_contract_stat():
"""
获取合同金额
:return: 合同数、总计金额
"""
mongo_db.connect_db('ext_system')
contracts = do_search('contract_t', {})
_count = len(contracts)
_total = 0.
for _r in contracts:
if (len(_r[u'金额']) > 0) and ((_r[u'金额'].replace('.', '')).isdigit()):
_tota... | 9112fbd59c2637b393d42484ea857b62c03d7815 | 3,612,710 |
from typing import List
def split_env_items(env_string: str) -> List[str]:
"""Splits space-separated variable assignments into a list of individual assignments.
>>> split_env_items('VAR=abc')
['VAR=abc']
>>> split_env_items('VAR="a string" THING=3')
['VAR="a string"', 'THING=3']
>>> split_env... | 2f62989c25987f40cd9515f39092d3ef05375fc6 | 3,612,711 |
def tree2diagram(tree, dom=Ty()):
"""
Takes a depccg.Tree in JSON format,
returns a :class:`discopy.biclosed.Diagram`.
"""
if 'word' in tree:
return Word(tree['word'], cat2ty(tree['cat']), dom=dom)
children = list(map(tree2diagram, tree['children']))
dom = Ty().tensor(*[child.cod for... | bfa5e34ae2c41dfd72e7e8e45758767de7908798 | 3,612,712 |
def intersection_over_box(chips, boxes):
"""
intersection area over box area
:param chips: C
:param boxes: B
:return: iob, CxB
"""
M = chips.shape[0]
N = boxes.shape[0]
if M * N == 0:
return np.zeros([M, N], dtype='float32')
box_area = bbox_area(boxes) # B
inter_... | 52710d712dcb7d5025a8ee29590477916144f4a5 | 3,612,713 |
def get_past_seasons(num_seasons):
"""
Go back num_seasons from the current one
"""
season = CURRENT_SEASON
seasons = []
for i in range(num_seasons):
season = get_previous_season(season)
seasons.append(season)
return seasons | 26f66725ea5fb08b4686a6fbbf2ee6f7ee57312b | 3,612,714 |
def signup(request):
"""
A method to add another user to the known users
:param request:
:return:
"""
# logger.debug("signup")
if request.method == 'POST':
# logger.debug("signup, method POST")
form = SignUpForm(request.POST)
if form.is_valid():
# logger.d... | 95a8347b9cb300b510aa4d0e5460656579539e07 | 3,612,715 |
from typing import List
import logging
def _CollectGpuSamples(
vm: virtual_machine.BaseVirtualMachine) -> List[sample.Sample]:
"""Run CUDA memcpy on the cluster.
Args:
vm: The virtual machine to run the benchmark.
Returns:
A list of sample.Sample objects.
"""
if not nvidia_driver.CheckNvidiaSm... | 4ebf827517ddd645cf361453401451eaf97f1d6a | 3,612,716 |
def remove_host(config, sync_name, name):
""" remove sync """
sync = get_sync(config, name)
sync['hosts'].remove(get_host(config, sync_name, name))
return True | e14133e6dc174906a3fd35ce975cfc2af3510d57 | 3,612,717 |
import time
def slow_function():
"""
模拟思考过程
:return: 结果
"""
time.sleep(3)
return 43 | ca6b8333f39f497a441ff335670d51a1ca37450f | 3,612,718 |
import random
def full_jitter(value):
"""Jitter the value across the full range (0 to value).
This corresponds to the "Full Jitter" algorithm specified in the
AWS blog's post on the performance of various jitter algorithms.
(http://www.awsarchitectureblog.com/2015/03/backoff.html)
Args:
... | 0a5c233d3e0e58873d29de7e3d878fbcf3d0c47a | 3,612,719 |
def get_lldp_neighbors(device):
"""Get current LLDP neighbor information.
Return a two-level dictionary with the LLDP neighbor information..
The first-level key is the local port (aka interface) name.
The second-level keys are 'system' for the remote system name
and 'port' for the remote port ID. O... | 5ac62b9e29b7e8814a41585ad0db9af85ef80989 | 3,612,720 |
def _get_temporal_concepts(world: owlready2.World) -> set:
"""
Fetches all classes, data and object properties that are used within the definition (equivalence or subclass) of
some temporal criticality phenomenon. Also regards SWRL rules.
:param world: World to get temporal concepts in.
:return: A s... | b29d858bdc155a3ba35453bf72fc59302b042ab7 | 3,612,721 |
def _pathcontains_filter(files, pathcontains):
"""Filtre par chemin"""
filtered_files = []
for file in files:
if pathcontains in file:
filtered_files.append(file)
return filtered_files | 9a37b1e361cc37e8a046b297115a6374c78abd2f | 3,612,722 |
import os
def test_dev_requirements_sorted():
"""
Check that dev-requirements.in is sorted (within sections).
"""
with open(os.path.join(REPO_DIR, 'dev-requirements.in'), 'r') as f:
lines = f.readlines()
def is_comment_or_empty(line):
return not line.strip() or line.lstrip().start... | 8a4538d1dd97764e7cdcd5eab84c8c605d139939 | 3,612,723 |
import numpy as np
from scipy.stats import norm
from typing import List
def dprime(y_true, y_pred, pmarg: float = 0.01, outputs: List[str] = ['dprime', 'bias', 'accuracy']) -> tuple:
"""
Calculate D-Prime for binary data.
70% for both classes is d=1.0488.
Highest possible is 6.93, but effectively 4.65... | 8bbbbc746558e392d569e0c484605f83bcfaae34 | 3,612,724 |
def main():
"""Main function. Set up widgets, calculate, plot."""
st.set_page_config(layout='wide')
# Set up sidebar input widgets
with st.sidebar:
P_des, n_des, p, r, n_max = params()
complementary, inclusive, out_txt = range_cond()
# Proportions of output screen
left_col... | 9039593ee1b807192015e33a7649750a545ed8da | 3,612,725 |
def function_to_be_decorated():
"""This is documentation for function_to_be_decorated."""
return True | ebb9602ba27e98750300e27dedfc9dd2c94f896d | 3,612,726 |
def read_file_utf8(data_file, mode='more'):
"""
读文件, 原文件和数据文件
:return: 单行或数组
"""
try:
with open(data_file, 'r', encoding='utf8') as f:
if mode == 'one':
output = f.read()
return output
elif mode == 'more':
output = f.rea... | 6b0275766783e648ac3f7099a345dbae289dc8a1 | 3,612,727 |
from typing import Optional
from typing import Dict
from typing import Any
async def load_fake_data(quantity: Optional[int] = 0) -> Dict[str, Any]:
"""loading fake data
Returns:
redirect to root path /
"""
await API_functools.insert_default_data(quantity=quantity)
return RedirectResponse(... | 7c7733cf81f4322c65f854cc34aeeecef6063df8 | 3,612,728 |
import requests
def sync_send(msg: SMSMessage, secret: str) -> str:
"""Synchronously send an SMSMessage, using the requests library.
Returns:
The response from the server.
Raises:
SMSSendError if sending failed.
"""
headers = {"X-Profile-Secret": secret}
data = msg.as_dict()
... | 4614bf85898d108dbd7b24eb3fc3ef547fab2fa6 | 3,612,729 |
def expmap(u, x0):
"""
This function maps a vector u lying on the tangent space of x0 into the manifold.
Parameters
----------
:param u: vector in the tangent space
:param x0: basis point of the tangent space
Returns
-------
:return: point on the manifold
"""
if np.ndim(x0)... | 97bf21fc96c0ec3cf8f1b566f7747c764fc4efcc | 3,612,730 |
import os
import tempfile
import shutil
def zip_py(module_dir='fncore'):
"""Zips python module for submission to Spark"""
root_dir = os.path.abspath(os.path.join(module_dir, os.pardir))
base_dir = os.path.relpath(module_dir, root_dir)
temp_dir = tempfile.gettempdir()
zippath = os.path.join(temp_d... | f53160af7fcb5d62ddd8ce6b431b65e6c0948ab8 | 3,612,731 |
from typing import Dict
def get_abertura_context(document: Dict, max_size: int = 4000) -> str:
"""Returns the abertura content of the document_text.
"""
document_text = document['text']
max_size = update_max_size(document, max_size=max_size)
context = document_text[:max_size]
return context | 3183ec016606f2781f63809a1416a85b6e76cfd2 | 3,612,732 |
def page(cursor=None, limit=None, user=None):
"""# Retrieve paged Webhooks
Receive a list of up to 100 Webhook objects previously created in the Stark Bank API and the cursor to the next page.
Use this function instead of query if you want to manually page your requests.
## Parameters (optional):
- ... | 84c0fc0861222b85187025399b14006372966be4 | 3,612,733 |
def integer_at_least(actual_value, expected_value):
"""Assert that actual_value is an integer of at least expected_value."""
result = isinstance(actual_value, int)
if result:
result = actual_value >= expected_value
if result:
return result
else:
raise AssertionError(
... | c4f601dd983d96a10372feabd67258a0515ac887 | 3,612,734 |
def calculate_his3p_small_wh_coefficients():
"""
Calculate the Walsh-Hadamard coefficients of the His3p(small) fitness functions.
"""
return _calculate_wh_coefficients_complete('his3p_small') | c6cc09a5719a94dfa38a2998cef03bb75fc15102 | 3,612,735 |
def eq(a, b, n):
"""Euler's quadratic formula"""
## : coefficient: a, b int
## : n int | n >= 0
rst = n**2 + a*n + b
return rst | c5f9619e22d3131b905eba6bfe509020d1f7c917 | 3,612,736 |
import math
def generate_lattice(ltype, volume, minvec=tol_m, minangle=pi/6, max_ratio=10.0, maxattempts = 100, **kwargs):
"""
Generates a lattice (3x3 matrix) according to the space group symmetry and
number of atoms. If the spacegroup has centering, we will transform to
conventional cell setting. If... | 098d028e72b1c66bf7c43d213b6cf1842a4deac1 | 3,612,737 |
def is_unqdn(cfg, name):
"""
Returns True if name has enough elements to
be a unqdn (hostname.realm.site_id)
False otherwise
"""
parts = name.split(".")
if len(parts) >= 3:
return True
else:
return False | 28e530816ea418473858d2cb59e572d25a9f2d81 | 3,612,738 |
def get_proj(geom, proj_list=None):
"""Determine best projection for input geometry
"""
out_srs = None
if proj_list is None:
proj_list = gen_proj_list()
#Go through user-defined projeciton list
for projbox in proj_list:
if projbox.geom.Intersects(geom):
out_srs = proj... | 8d63c8a9642a0b78063f039553c5bcd9072f9958 | 3,612,739 |
def format_vertex(body: Json) -> Json:
"""Format vertex data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
vertex: Json = body["vertex"]
if "_oldRev" in vertex:
vertex["_old_rev"] = vertex.pop("_oldRev")
if "new" in body or "old" in bo... | a0fc806c9bba67b2044fc10e99e5b96a131c0ac1 | 3,612,740 |
def get_tag_list(frmt):
"""
Gets a list of tags from the XML conversion output of a specific document.
:param frmt: format/extension of the input document (document must be present in the tests/in folder)
:return: list of element tags
"""
oxobj = OxGaWrap(f'tests/in/test.{frmt}')
tree = oxob... | 83c4b94c839c0499e57a2bd6f2eb630da253be7a | 3,612,741 |
import scipy
def get_window(window, Nx, fftbins=True):
"""Compute a window function.
This is a wrapper for `scipy.signal.get_window` that additionally
supports callable or pre-computed windows.
Parameters
----------
window : string, tuple, number, callable, or list-like
The window sp... | 3ef4a05cc30431df2725d326dcee17bf52e5b511 | 3,612,742 |
def haversine(pt, lat2=42.355589, lon2=-71.060175):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
lon1 = pt[0]
lat1 = pt[1]
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])... | 38d5b0ab53485f8267e4e06a15fcd533a158883c | 3,612,743 |
import logging
from typing import Tuple
import os
import ftplib
def download_using_ftp(username: str,
password: str,
public_address: str,
remote_file: str,
log: logging.Logger,
download_path: str = video... | e860f4d37662090149182fbf9898b379947b70cf | 3,612,744 |
def check_ip(ip):
"""Checks whether given IP address is valid or not.
Implements only basic checking."""
if ip is not None:
iplst = ip.split('.')
if len(iplst) != 4:
return False
for num in iplst:
if int(num) > 255 or int(num) < 0:
return False... | a0342cfb91c1b8759dc22b5ece90f6bf6203f951 | 3,612,745 |
def adcp_earth_vertical(w):
"""
Description:
Wrapper function to compute the Upward Velocity Profile (VELPROF-VLU)
from Earth coordinate transformed velocity profiles as defined in the
Data Product Specification for Velocity Profile and Echo Intensity -
DCN 1341-00750.
Impl... | a80444f3f0585156570d609160245a89873cab23 | 3,612,746 |
import re
def to_comma_type(numpy_type):
"""
convert a single numpy type to comma type
numpy arrays are unrolled and converted to a prefixed comma type
>>> from comma.csv.format import *
>>> to_comma_type('f8')
'd'
>>> to_comma_type('S12')
's[12]'
>>> to_comma_type('3u4')
'3u... | e17ea2da06031643dbf1a5227b4ed7c0e8d44342 | 3,612,747 |
def is_valid_medialive_channel_arn(mlive_channel_arn):
"""Determine if the ARN provided is a valid / complete MediaLive Channel ARN"""
if mlive_channel_arn.startswith("arn:aws:medialive:") and "channel" in mlive_channel_arn:
return True
else:
return False | c2ddbdef180eabbc4f22399dd895b99555bb05d6 | 3,612,748 |
def Faculty4(request):
"""
Returns the render for the sdg graph
"""
data = dataFrameSDG().drop(columns = "Misc")
data2 = data.T
data3 = data2.reset_index(level = 0)
data4=data3.rename(columns=data3.iloc[0]).drop(data3.index[0])
figure = px.bar(data4, x = "Faculty", y = FacultyIndex["... | 55965277447557f361445b790f1501d900c6ce92 | 3,612,749 |
def est_vega(S, K, r, sigma, T):
""" Define a function to calculate the vega
which is also the derivative of option with respect to sigma
"""
d = (np.log(S/K) + (r + 0.5 * sigma* sigma)* T) / (sigma * np.sqrt(T))
vega = S * np.sqrt(T) * norm.pdf(d)
return vega | 91c1a7c390edeff4ed79028098fd8073481ce2a4 | 3,612,750 |
from typing import Tuple
def generate_a_pair() -> Tuple[int, int]:
"""
Generate private ephemeral a and public key A.
Returns:
Tuple (private a (int), public A (int))
"""
prime = _get_srp_prime()
generator = _get_srp_generator()
a = _to_int(_generate_random_bytes(32)) # RFC-5054... | a806f7fcd89f991881d21862c590d8f6f8234c1a | 3,612,751 |
def perform_data_filtering_q3(data):
"""
Takes the original DataFrame.
Returns the altered DataFrame necessary for Q3.
"""
df = data
angina_presence = df['cp'] <= 2
df['cp'] = np.where(angina_presence, 1, 0)
return df | 1806defe886da659a2f1c34758051720dc7883bc | 3,612,752 |
def reload_config(test_run: RunnerEnvironment) -> dict:
"""Load configuration of test as JSON-object."""
return load(open(test_run.test_env.config_file, 'r')) | f94389fabc8e60d55992d30a176e9c439e1ae9f7 | 3,612,753 |
def generate_random_particle(_id, input_size, neurons):
"""Function to generate random particle to init PSO algorithm"""
position = []
speed = []
n_neurons = sum(neurons)
n_weights = input_size * neurons[0]
for i in range(len(neurons) - 1):
n_weights = n_weights + neurons[i]*neurons[i+1]... | b65f452a396d55ea44c696976894f750ea5719d7 | 3,612,754 |
import six
import math
def model_fn(model,
features,
mode,
hparams,
problem_names,
train_steps=100000,
worker_id=0,
worker_replicas=1,
eval_run_autoregressive=False,
decode_hparams=None):
"""Builds t... | c45ed0d7d6999e0238f0bd0eee3fe96710c09cc6 | 3,612,755 |
def convert_tf_to_crowdsourcing_format(images, detections):
"""
Args:
images: dictionary {image_id : image info} (images from Steve's code)
detections: detection output from multibox
Returns:
dict : a dictionary mapping image_ids to bounding box annotations
"""
image_annotation... | ba25ee0cb2eb570f745326dfe85c2bda972a3659 | 3,612,756 |
import scipy
def horn_schunk_flow(img0,img2,lambada,max_iter,epsilon):
"""
:param img0: first frame
:param img2: second frame
:param lambada: hyper parameter
:param max_iter: threshold for iterations
:param epsilon: decay rate
:return: flow and gradient
"""
decay=10000
i=0
... | 5ac1ce6a97389a32bd71ac3469bcf9c217ae3aac | 3,612,757 |
from typing import Any
def true_pred_hist(
y_true: NumArray,
y_pred: NumArray,
y_std: NumArray,
ax: Axes = None,
cmap: str = "hot",
bins: int = 50,
log: bool = True,
truth_color: str = "blue",
**kwargs: Any,
) -> Axes:
"""Plot a histogram of model predictions with bars colored ... | 4d47cbda361f3dde0261ef34880736c77f4131d1 | 3,612,758 |
from typing import List
from typing import Union
def read_typetree(
nodes: List[Union[dict, TypeTreeNode]], reader: EndianBinaryReader
) -> dict:
"""Reads the typetree of the object contained in the reader via the node list.
Parameters
----------
nodes : list
List of nodes... | 4f90326d31c7d11270cf72b798a110bc798118c8 | 3,612,759 |
import sqlite3
from typing import cast
def read_bip32_keys_gap_size(db: sqlite3.Connection, account_id: int,
masterkey_id: int, prefix_bytes: bytes) -> int:
"""
Identify the trailing BIP32 gap (of unused keys) at the end of a derivation sequence.
For now we create keys in a BIP32 sequence sequent... | ab9cbc8445fe1f762420a635d73ece26fa8c8634 | 3,612,760 |
from typing import Optional
from typing import Dict
from typing import Any
def convert_bool_to_0_or_1(
params: Optional[Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
"""Converts all bool values in dict to "0" or "1".
Slack APIs safely accept "0"/"1" as boolean values.
Using True/False (bool in Pytho... | cfce80e67a7251a2d85506386cc2507dd9702dd0 | 3,612,761 |
def calc_kin_temp(vel, nums, masses, kB):
"""
Calculates the kinetic energy and temperature.
Parameters
----------
kB: float
Boltzmann constant in chosen units.
masses: numpy.ndarray
Mass of each species.
nums: numpy.ndarray
Number of particles of each species.
... | 003231602a831e11befaf891fee46ee2897b0658 | 3,612,762 |
def calc_P_remain(
P_avail: pd.DataFrame,
P_req: pd.Series,
gidx: wio.GearMultiIndexer,
):
"""Return `p_avail - p_req` for all gears > g2 in `gwot`. """
c = wio.pstep_factory.get().cycle
## Drop pandas axis or else substraction would fail with:
# ValueError: cannot join with no overla... | 56bb46c12a861d3f6eb711abe069a655f3efc988 | 3,612,763 |
import os
def prefix_path(path,src_list):
"""
prefix the path to every file in the src_list
"""
return [os.path.join(path,e) for e in src_list] | 379c3fbb6648978e9b58e015740587ec5473037d | 3,612,764 |
def load_user(user_id: str) -> User:
"""Return the current JWT user."""
return user_domain_logic.get_user(user_id) | cbf6566e7ceabaac8c5a5cc9293b5650562d7337 | 3,612,765 |
def _process_exp(client, job_id="test", worker_id=None, bonus_mode="random", clear_session=True, url_kwargs=None):
"""
:param client: (flask.testclient)
:param job_id: (str)
:param worker_id: (str)
:param bonus_mode: (str: random|full|none)
:param clear_session: (bool)
"""
exp_value = in... | fc0fd430fd67902f8f3528335b64cce03a88eb49 | 3,612,766 |
def get_argparser():
"""
Returns an argument parser for this script
"""
parser = ArgumentParser(description='Predict using a U-Time model.')
parser.add_argument("--folder_regex", type=str, required=False,
help='Regex pattern matching files to predict on. '
... | 27cdcfb8f0bd5dc0df6898b4f8e2fddb408d48d1 | 3,612,767 |
from typing import Callable
def remove_empty_routes(operator: Callable[..., Solution]):
"""
Wrapper function that removes empty routes from the returned solution
instance. These routes may come into existence because all customers have
been removed by e.g. a destroy operator.
"""
@wraps(operat... | 4f3ce6731404b1edb76ccfe7dc6f1857576b017b | 3,612,768 |
import sys
def _get_zipname(platform):
"""Determine zipfile name for platform.
Parameters
----------
platform : str
Platform that will run the executables. Valid values include mac,
linux, win32 and win64. If platform is None, then routine will
download the latest asset from... | f0a5729f93a9b5da6a1eb6bde75baad6fc0a7f08 | 3,612,769 |
from typing import Optional
def interleaved_gate_fidelity_bounds(irb_decay: float, rb_decay: float, dim: int,
unitarity: Optional[float] = None):
"""
Use observed rb_decay to place a bound on fidelity of a particular gate with given interleaved
rb decay.
Optionall... | 90c1a2e25770333a510ec0d63bd4ceb0de689b46 | 3,612,770 |
def session_factory_from_settings(settings):
"""
Convenience method to construct a ``MongoSessionFactory`` from Paste config
settings. Only settings prefixed with "mongo.sessions" will be inspected
and, if needed, coerced to their appropriate types (for example, casting
the ``timeout`` value as an `... | b75dd42876bd271da6f1cf0acf0528a91984080c | 3,612,771 |
def f_stock():
"""
Real Name: b'F Stock'
Original Eqn: b'INTEG ( F Acquisition Rate-F Shipment Rate, 400)'
Units: b'SKU'
Limits: (None, None)
Type: component
b''
"""
return integ_f_stock() | 1fc8b905d16543787aab4128d6dc973b8ae19daf | 3,612,772 |
def deep_ensemble_predict(x,
models,
training_setting,
uncertainty_type='entropy'):
"""Deep Ensembles uncertainty estimator.
Args:
x: `numpy.ndarray`, datapoints from input space, with shape [B, H, W, 3],
where B the batch size... | a5fb73b4c1a8e3e3230a612783cad54766f7531f | 3,612,773 |
def tsPredFig(df, item, predictDays):
"""
This function is to predict the community demand using Prophet Time Series Algorithms.
Args:
df (dataframe) : dataset
item (str) : product type that was selected
predictDays(int): days for prediction
Returns:
forecast : da... | 0c7fdedf7fd5de803654b1d5e3754ab4554480ab | 3,612,774 |
from typing import Optional
from typing import Tuple
from typing import Set
def remove_redundant_latents(
graph: nx.DiGraph, tag: Optional[str] = None
) -> Tuple[nx.DiGraph, Set[str]]:
"""Remove redundant latent variables.
:param graph: A latent variable DAG
:param tag: The tag for which variables ar... | 0250b9f01e872b70f277eaa05561e094199382fe | 3,612,775 |
from typing import OrderedDict
def get_chattering_species(atom_followed="C"):
"""
return chattering species
the chatteing reaction infomation is just for reference, will not use it
as long as the paired chattering species is provided, should be fine
better make them in the same order
"""
f... | 264702e1b1ca474c6cfe45035d9d5aad2e653d07 | 3,612,776 |
def word_accuracy(predictions, labels):
"""predictions and labels are of shape Batches x NUM_Digits_Pred and Batches x NUM_Digits_Label
"""
predictions, labels = pad_pred_label(predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
if labels.dtype != predictions.d... | 0d26ba91fb90ff9d71241b5181bddccad71efce9 | 3,612,777 |
import types
def inherit_doc(cls):
"""
This decorator simply add docstrings from parent class to subclass methods if no documentation
exists on the subclass method.
"""
for name, func in vars(cls).items():
if isinstance(func, types.FunctionType) and not func.__doc__:
for parent... | c3e35190b9f604e39119c21bd791e699f392f81e | 3,612,778 |
import pickle
def editSearch(request, search_id=None):
"""
Handler for editing an existing search
"""
#load the search passed in
if search_id:
search = Search.objects.get(id=search_id)
if search.user != request.user and search.isPublic == False:
return HttpResponse("<p... | 2df04456a07a5329347a72b0ebcc09193b83beda | 3,612,779 |
def predict_squad(input_file_path, output_file, vocab_file,
doc_stride, predict_batch_size, max_query_length,
max_seq_length, do_lower_case,
version_2_with_negative=False)->int:
"""Makes predictions for a squad dataset."""
eval_examples = read_squad_examples(
... | aef196b459519c1c3a71189b7fec187fa5a40e17 | 3,612,780 |
def solution(A):
"""
This one is a tricky one as the solution requires doing a bit of research on
how to best detect overlapping ranges (a circle projected onto a axis
becomes simply a range from A to B).
The best performance can be achieved with the following approach:
1. First pre-process all... | 05634fef061e7e9f1462614219e976161fd8c675 | 3,612,781 |
def patched_novoed_api(mocker):
"""Patches NovoEd API functionality"""
return mocker.patch("novoed.tasks.api") | 9bd7b15a6b34c9c659755fb36e422698a82be063 | 3,612,782 |
def create_layer_with_task_specific_linear_heads(num_classes_for_tasks):
"""Returns a `pathnet_lib.ComponentsLayer` with linear task specific layers.
This is a small helper function to create a layer of fully connected
components for multiple classification tasks (with possibly different
numbers of classses). ... | 2c064cf350d56188c0c54952b4d74e6e770720ce | 3,612,783 |
from rastervision.pipeline.file_system import download_if_needed
from re import A
def deserialize_albumentation_transform(tf_dict: dict) -> A.BasicTransform:
"""Deserialize an albumentations transform serialized by
`serialize_albumentation_transform()`.
If the input dict contains a `lambda_transforms_pat... | 630e20a612b89f5bc5a3513cda159714d4825bad | 3,612,784 |
def increment(version, major=False, minor=False, patch=True):
"""
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying pa... | 2e76cc90dd8e1967c2ae6be21230746132a2de09 | 3,612,785 |
def fpn_classifier_graph(rois, feature_maps, image_meta,
pool_size, num_classes, train_bn=True):
"""Builds the computation graph of the feature pyramid network classifier
and regressor heads.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates... | f34d1fbd9aafa525cb6c892e788870fa1de54871 | 3,612,786 |
import os
def is_binary_file(path):
"""
:type path: str
:rtype: bool
"""
assume_text = set([
'.cfg',
'.conf',
'.crt',
'.css',
'.html',
'.ini',
'.j2',
'.js',
'.json',
'.md',
'.pem',
'.ps1',
'.psm... | e1cc55a8be412d6424f0dab346f57c625636e64a | 3,612,787 |
def make_matcher(patterns):
"""Returns a function that evaluates if a path match one of the patterns.
The compared paths are first converted to unicode and decomposed.
This is neccesary because the way `os.walk` read unicode paths could vary.
For instance, it might returns a decomposed unicode string r... | abaecdba1f28cbdad53b7afd9d447b7a2bdd5be6 | 3,612,788 |
from datetime import datetime
def preprocess(count, df):
"""
Preprocesses CSV file where only words, hashtags, and emojis are kept
"""
num_tweets = len(df)
cleaned_tweets = []
print("Beginning processing of ",num_tweets," tweets at: ",str(datetime.now()))
for i in range(num_tweets):
... | 11a8f5e97a1134bf7c28b79dfd17b804f93063b4 | 3,612,789 |
def load_data(database_filepath):
"""Parameters:
database_filename: string. Filename of SQLite database containing the cleaned message data.
Returns:
X: Dataframe containing messages used as the predictive column.
Y: Dataframe containing the categories we are trying to predict.
category_... | 3ab386833fa8a8edab0406a8d596f007155045bd | 3,612,790 |
def validate_truthy(name, val):
"""Validate that ``val`` is truthy.
Validate that ``val`` is truthy according to
https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean... | 718b321f03a970995c4928727785c155be50322b | 3,612,791 |
def fundamentals(
symbol, period="quarter", token="", version="stable", filter="", format="json"
):
"""Pulls fundamentals data.
https://iexcloud.io/docs/api/#advanced-fundamentals
Updates at 8am, 9am UTC daily
Args:
symbol (str): Ticker to request
period (str): Period, either 'annu... | ae08578705b8209d007752c3c9b3737f52bb0501 | 3,612,792 |
def create_mask(indexer, shape, data=None):
"""Create a mask for indexing with a fill-value.
Parameters
----------
indexer : ExplicitIndexer
Indexer with -1 in integer or ndarray value to indicate locations in
the result that should be masked.
shape : tuple
Shape of the arra... | 687916ada68b4ddec669998e3957f65e70272a6e | 3,612,793 |
def _expand_to_beam_size(data, beam_size, batch_size, state_batch_axis=None):
"""Tile all the states to have batch_size * beam_size on the batch axis.
Parameters
----------
data : A single mx.np.ndarray or nested container with mx.np.ndarray
Each mx.np.ndarray should have shape (N, ...) when st... | 4eae5f5a6e5fd68081f618450d979fd2a765b073 | 3,612,794 |
def get_simple_gadgets(input_file):
"""Checks if a dump of the gadgets already exists and loads them. Otherwise,
it finds all the gadgets in the current input file, dumps them and also
returns them (simple form)."""
try:
gad_in = util.open_gadgets(input_file, "rb")
simple_gadgets = pickle.load(gad_in)
... | 2395fbfc622a8e6b8f73754625baf09222867f2d | 3,612,795 |
def warningIndex():
"""
Build an object that is a wrapper around the warning channel index from the C++
extension. i.e. {pyre::journal::warning_t::index_t}
"""
#
return Index(lookup=journal.lookupWarningInventory, inventory=Enabled) | 647a84ed38555e3ab24815822c77e65dd3229b86 | 3,612,796 |
import glob
def gen_lm1b_train_dataset(file_pattern, num_step):
"""
Returns: The training dataset (tf.data.Dataset) that has been repeated
and shuffled
"""
file_names = []
for file_name in glob.glob(file_pattern):
file_names.append(file_name)
if not file_names:
raise ValueE... | e99ed398e625b97e2abffb0f3dcffef6f3a86be4 | 3,612,797 |
import platform
def setup():
""" creates necessary c-level types
"""
names = populate_inttypes()
result = []
for name in names:
tp = platform.types[name.upper()]
globals()['r_' + name] = platform.numbertype_to_rclass[tp]
globals()[name.upper()] = tp
tpp = lltype.Ptr... | 4c33e95f7948892ca41e94753504f3c8558f9034 | 3,612,798 |
def profile_redirect():
"""In use to redirect after login complete.
Flask-login does not allow us to redirect dynamically to the current
language so we set that fake view to proper redirect.
"""
# Do not use `current_user.detail_url` here as we do not have
# a current language yet, hence guessi... | 4918ee3f375386fb414d90f2ca51da25813a9073 | 3,612,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.