content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def stt_mapper(result):
"""Returns the corrected text"""
best = result
variations = filter_stopwords(get_substrings(result))
n_grams = generate_n_grams(variations)
changed = []
for substring in n_grams:
no_change = False
for phrase in changed: #checks if a particular phrase has ... | c0650ed9f5e248628aa061e71ec3665edfcbf148 | 3,622,100 |
from re import T
import os
def delete():
""" Object delete handler """
app = get_app()
filename = '/'.join(request.args)
sender = request.vars.sender
if isinstance(sender, list): # ## fix a problem with Vista
sender = sender[0]
dialog = FORM.confirm(T('Delete'),
... | 3e65e3e6db9b90ea8019e4f2094ca77afdd5453a | 3,622,101 |
def create_neutron_subnet(shade_client, network_name_or_id, cidr=None,
ip_version=4, enable_dhcp=False, subnet_name=None,
tenant_id=None, allocation_pools=None,
gateway_ip=None, disable_gateway_ip=False,
dns_nameserv... | 289c2877e9907439c23cbc9035e05e981cef7f86 | 3,622,102 |
from typing import Callable
from typing import List
from typing import Dict
import concurrent
def batch_get_data(lookup_ids: str, func: Callable[[object, List[str], str], Dict]):
"""Retrieve details for the list of AIDs provided.
Arguments
---------
lookup_ids: str
List of IDs to retrieve dat... | b033f3ef9d23ff0a4b2890e2f5374dcdd2711a68 | 3,622,103 |
def search_parameters_in_collection_value(item_id, item, attr_path=""):
""" Return the Parameter content of a single object in a collection.
This can be used to search for the parameter content of a list, dict,
tuple, series, dataframe and anything that can contain complex values and
have a unique iden... | 290db10485cd490f63b238660ea71a0a609ea936 | 3,622,104 |
def test_plot3d_varying_transparency():
"""
Plot the data using z as transparency using 3-D column symbols.
"""
x = np.arange(1, 10)
y = np.arange(1, 10)
z = np.arange(1, 10) * 10
fig_ref, fig_test = Figure(), Figure()
# Use single-character arguments for the reference image
with GM... | 082fe17bd0612c34418900e96a0867bc850e9918 | 3,622,105 |
def set_trace_file_desc(*args):
"""
set_trace_file_desc(filename, description) -> bool
Change the description of the specified trace file.
@param filename (C++: const char *)
@param description (C++: const char *)
"""
return _ida_dbg.set_trace_file_desc(*args) | 5cb2e316d0c813442645d15666117be29335aacb | 3,622,106 |
def _get_group_on_off(state):
""" Determine the group on/off states based on a state. """
for states in _GROUP_TYPES:
if state in states:
return states
return None, None | 87cf5b915f857eec26abd4957475c5df86aad56c | 3,622,107 |
import torch
def compatibility_scores(h1, h2, dataset, device="cpu"):
"""
Args:
h1: Reference Pytorch model.
h2: The model being compared to h1.
dataset: Data in the form of a list of batches of input/target pairs.
device: A string with values either "cpu" or "cuda" to indicate... | aeb73246e429c288d2bc74e021e964c801a23767 | 3,622,108 |
def reflect_image(w):
"""Reflects the image of the Evans function across the imaginary axis,
returning a numpy array that contains both the old points and the
reflected points.
"""
return np.concatenate((w,np.flipud(np.conj(w)))) | 76f563302011b683fbd5c8a7d75d388b8427b6aa | 3,622,109 |
from desiutil.log import get_logger
import os
import io
import time
def select_targets(infiles, numproc=4, cmxdir=None):
"""Process input files in parallel to select commissioning (cmx) targets
Parameters
----------
infiles : :class:`list` or `str`
A list of input filenames (tractor or sweep ... | 2646a32fbf3efa08fd631746ec29f0f42b0f77c7 | 3,622,110 |
from typing import Optional
def get_pipeline(slug: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPipelineResult:
"""
## # Data Source: pipeline
Use this data source to look up properties on a specific pipeline. This is
particularly useful for looki... | aadbd84f3231ceabfc0ed4d82e0b2d64e777838e | 3,622,111 |
def flatten_list(unflattened_list):
"""
Take list of iterables/non-iterables and outputs a list of non-iterables.
"""
flattened_list = []
for item in unflattened_list:
if hasattr(item, '__iter__') and not isinstance(item, str):
flattened_list.extend(item)
else:
... | cbf7297bd10312a47487fd814575323881940ef5 | 3,622,112 |
def CDLGRAVESTONEDOJI(equity, start=None, end=None):
"""Gravestone Doji
:return:
"""
opn = np.array(equity.hp.loc[start:end, 'open'], dtype='f8')
high = np.array(equity.hp.loc[start:end, 'high'], dtype='f8')
low = np.array(equity.hp.loc[start:end, 'low'], dtype='f8')
close = np.array(equity... | 4fc169952f8dd5ab1c1ae31451830e4c890da470 | 3,622,113 |
from xarray.core.ops import get_op
def threshold_count(da, op, thresh, freq):
"""Count number of days above or below threshold.
Parameters
----------
da : xarray.DataArray
Input data.
op : {>, <, >=, <=, gt, lt, ge, le }
Logical operator, e.g. arr > thresh.
thresh : float
Th... | 36496b009b40db3bb217b09f41c6a09e7d1980d7 | 3,622,114 |
def _kill(app_id, scale, host):
"""
:param app_id: the id of the application
:type app_id: str
:param: scale: Scale the app down
:type: scale: bool
:param: host: Kill only those tasks running on host specified
:type: string
:returns: process return code
:rtype: int
"""
client... | b47fc0ca61488fe7555f4b244dd66f9f40132fe7 | 3,622,115 |
def depth_per_node(tree):
"""
calculcates depth per node in binary tree
Arguments:
----------
tree :
tree object with the same structure as
`sklearn.ensemble.DecisionTreeClassifier`
Returns:
--------
depth_vec : int array
vector of depth for each node
"""
... | 9200ab0570655e934f913f1013dacf326d4a51c8 | 3,622,116 |
def client(**kwargs):
"""Interface for building a client instance"""
return WoopraTracker(**kwargs) | 8c52f30717411f235274b7f13fa6f96a25742fca | 3,622,117 |
import os
import inspect
import logging
def common_meta(**kwargs):
"""Common meta setter
"""
caller = os.path.basename(inspect.stack()[2][1])
caller = caller[:caller.rfind(".")]
line_no = inspect.stack()[2][2]
kwargs['extra'] = {'_module': caller, '_lineno': line_no}
return logging.getLogg... | c9d25b11b86a341bd14a28581cf83466133b2ef1 | 3,622,118 |
from typing import Tuple
def read_ptn(
partition_filename: str
) -> Tuple[tuple, int, list, list, list]:
"""
Read partition file (.ptn) and extract information.
Parameters
----------
partition_filename : str
The filename of the .ptn partition file.
Returns
-------
... | 70fd1e3f7977abc688b8403b8319f64dedf5184f | 3,622,119 |
import glob
import os
def get_load_dir(dataset_lvl_dir, obj_type):
"""
Get load directory.
:param dataset_lvl_dir: dataset level directory
:param obj_type: objective function type
:returns load_dir: loading directory
"""
load_dir_list = glob(os.path.join(dataset_lvl_dir, obj_type, '*'))
... | d05f912bb4c4a8b4900f81530ab5d8b05104c173 | 3,622,120 |
def sector_code_map(industry_code):
"""
国证行业分类映射为部门行业分类
国证一级行业分10类,转换为sector共11组,单列出房地产。
"""
if industry_code[:3] == 'C01':
return 309
if industry_code[:3] == 'C02':
return 101
if industry_code[:3] == 'C03':
return 310
if industry_code[:3] == 'C04':
r... | 73d55282c0e6228747d91b09b5ee733aecf4766c | 3,622,121 |
import torch
def gen_normalized_adjs(dataset):
""" returns the normalized adjacency matrix
"""
row, col = dataset.graph['edge_index']
N = dataset.graph['num_nodes']
adj = SparseTensor(row=row, col=col, sparse_sizes=(N, N))
deg = adj.sum(dim=1).to(torch.float)
D_isqrt = deg.pow(-0.5)
D_... | e17c208f1da10455c8eb7aaf20dc6bcbc4baeda9 | 3,622,122 |
def flatten_deep(array):
"""Flattens a nested array recursively. This is the same as calling
``flatten(array, is_deep=True)``.
Args:
array (list): List to process.
Returns:
list: Flattened list.
Example:
>>> flatten_deep([[1], [2, [3]], [[4]]])
[1, 2, 3, 4]
.... | 5a8748453bb4786e48efcce59de061dc64c9badd | 3,622,123 |
def aten_transpose(mapper, graph, node):
""" 构造矩阵转置的PaddleLayer。
TorchScript示例:
%715 : Tensor = aten::transpose(%x.21, %704, %705)
参数含义:
%715 (Tensor): 输出,转置后的矩阵。
%x.21 (Tensor): 需要转置的Tensor。
%704 (int): 转置的维度1。
%705 (int): 转置的维度2。
"""
scope_name = mapper... | 3922de1a23ce0725b4a8fa6d1f748ad1ad3bcf81 | 3,622,124 |
from typing import Tuple
import json
def prepare_record(record: dict) -> Tuple[dict, dict]:
"""
Convert record data for DynamoDB insertion
record: updated record with json dumps fields for nested record values
original_nested_data: untouched nested key record data
"""
original_nested_data = {}... | cf30d602115c52c929237ea4fe5a2f3ed42f7e97 | 3,622,125 |
from typing import Dict
from typing import OrderedDict
def retrieve_by_id(location_id: int,
database_connection: mysql.connector.connect,
pre_validated_id: bool = False) -> Dict:
"""Returns an OrderedDict with location information based on
requested location ID
Argum... | a86e0ae24ed5e67a739bb3aff985f96339c05954 | 3,622,126 |
def get_syst ( syst , *index ) :
"""Helper function to decode the systematic uncertainties
Systematic could be
- just a string
- an object with index: obj [ibin]
- a kind of function: func (ibin)
"""
if isinstance ( syst , str ) : return syst
elif syst and hasattr ( syst , '... | 37b2b39245587da16345752e02759d2c94c93415 | 3,622,127 |
def extract_doc_from_source(quiet=False):
"""
Write internal (pickled) TeX doc mdoc files and example data in docstrings.
"""
if not quiet:
print(f"Extracting internal doc data for {version_string}")
try:
return load_doc_data(settings.get_doc_tex_data_path(should_be_readable=True))
... | 8744545db6d7f78ba0ce069f388005963b2de840 | 3,622,128 |
from typing import Optional
from typing import List
def create_train_net_stats_function() -> TrainReturnFiller:
"""
Note:
Here the _TrainNNStatsElement objects are not process sensitive! Thus their id must
differ based on the process, so package_pos don't merge between proc... | f691681545120d5abae2232d4fccf119756893cf | 3,622,129 |
import os
import trace
import yaml
import copy
def load_invariants(ws_path):
"""
invariants yaml schema (incomplete):
Reachability: [{Ingress, Egress, DstIp, SrcIp, Protocol, DstPort, SrcPort, MaxFailures}]
"""
iv_path = os.path.join(ws_path, 'traces/invariants/'+trace+'.yml')
with open(iv_p... | 2887a9560df1e4fc3c9903e1a3c6670f9f2d0bca | 3,622,130 |
def fKzt(r,m,nout=2):
""" Returns Kzt according to yaw article """
fOye = 0.5 * (r + 0.4 * r ** 3 + 0.4 * r ** 5)
vr = r
Kzt = np.zeros(vr.shape)
Kztnum = np.zeros(vr.shape)
if m == 0:
raise Exception('Not intended for m==0')
k2 = ((1 - r) ** 2) / ((1 + r) ** 2)
m1 = (np.sqrt(1 +... | 846eb1a3c34afc97511ae4b508ddcf430246249d | 3,622,131 |
def run_main(i_datastore_json, i_trf_fn, o_svsig_gz_fofn):
"""
i_datastore_json is a datastore json of multiple AlignmentSet or ConsensusAlignmentSet files.
Split each *AlignmentSet file to multiple chunked files, each of which must contain reads from
only one movie. Call `pbsv discover` on each chunk ... | ed46038068fb255cce932621363890f6333faf15 | 3,622,132 |
import weakref
def weak_arg(arg):
""" Create a weak reference to arg and wrap the function so that the dereferenced
weakref is passed as the first argument. If arg has been deleted then the
funcion is not called.
"""
# Create the weak reference
weak_arg = weakref.ref(arg)
def decorator(f... | 90da143dada896fe7988b4f3003110a3b678b5ab | 3,622,133 |
def feature_manager():
""" Return a feature manager """
return FeatureManager() | 065b29700219b5db3e96b54107e5f41b5d2d6c37 | 3,622,134 |
def square_image(image, pad_value=0):
"""Pad image array image such the shorter dimension is the same
as the longer one. Dimensions may be different (by 1 pixel)
if the longer dimension is odd.
Args:
image (np.array): 2D or 3D image array
pad_value (int): padding constant
... | 804efbec0e445d73196789dbced4c38989effc83 | 3,622,135 |
def infer_freq(av_seconds, tolerance=0.1):
"""Infer frequency of a time data series."""
if approx_equal(1, av_seconds, tolerance):
freq = 'S'
elif approx_equal(60, av_seconds, tolerance):
freq = 'T'
elif approx_equal(3600, av_seconds, tolerance):
freq = 'H'
elif approx_equal... | 381e17089312be53c2ebf3dcfaca30a174d41938 | 3,622,136 |
import re
def get_method_args_from_code(args, line):
"""Parse arguments from a stringified arguments list inside parentheses
Parameters
----------
args : list
A list where it's size matches the expected number of parsed arguments
line : str
Stringified line of code with method arg... | 3150eed5d634977d708e052ea65434d554a64859 | 3,622,137 |
def export_xmp(filename):
"""Exports an .xmp sidecar file from the image."""
try:
xmpfile = XMPFiles(file_path=filename)
except:
return None
return xmpfile.get_xmp() | f92e7be668b896de7f1062e37c1907b6cae00e0a | 3,622,138 |
import os
def gnmi(call, *args, **kwargs):
"""
Function to interact with devices using gNMI protocol utilising one of supported plugins.
:param call: (str) (str) connection object method to call or name of one of extra methods
:param plugin: (str) Name of gNMI plugin to use - pygnmi (default)
:pa... | db3193c25b6f9f4e4df619ceb2e90623b5237162 | 3,622,139 |
from datetime import datetime
import requests
from bs4 import BeautifulSoup
import pandas
def get_disclosure_interests(code, start_date: datetime.date, end_date: datetime.date):
"""
http://sdinotice.hkex.com.hk/di/NSSrchCorp.aspx?src=MAIN&lang=ZH&in=1&
:param code:
:param start_date: datetime.date
... | e33981e2791c0477cdafa91f769194e482d80783 | 3,622,140 |
def string_to_slice(string):
"""convert a string into a slice"""
s = request_slice()
if string != '':
memory_values[s] = list(map(lambda x: ord(x.encode('utf-8')), list(string)))
memory_size[s] = len(memory_values[s])
else:
set_slice_last_index(s, -1)
return s | ed6c28e6e66ccb04a82b2039a42cc989e3e52aa8 | 3,622,141 |
import logging
def check_3(df, nm):
"""
Checks that nm, amount adsorbed in the monolayer, is in the range of
data points used in BET analysis.
Parameters
----------
df : dataframe
Dataframe of imported experimental isothermal adsorption data.
nm : array
2D array of BET sp... | 5807fd2b2cbc6c20c12294c2fa35385cba6ddefc | 3,622,142 |
import pickle
def load_flow(vid_path, fps, start_time, offset_sec=0):
"""
load optical flow given a video.
Args:
vid_path: str, video path
fps: float, fps
start_time: int, start time unixtime in milliseconds
offset_sec: float, start offset in seconds
Returns:
d... | f097e09fcec3613678b266b3d6f5c33a9b1ed64e | 3,622,143 |
import re
def get_open_dns_resolvers(input_stream, whitelist_domains, whitelist_networks):
"""
Gets used open dns resolvers from input stream
:param input_stream: Input flows
:param whitelist_domains: Regex containing all whitelisted domains
:param whitelist_networks: Array with all whitelisted n... | e001ccbe2c2b16c254b1663acf48f0121ee09a6d | 3,622,144 |
import re
def get_repo(repo, **kwargs):
"""
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
"""
_check_apt()
ppa_auth = kwargs.get("ppa_a... | 5a07b48c6c257c18382cfc19e081f197eeded338 | 3,622,145 |
def create_nic(network_client):
"""Create a Network Interface for a VM.
"""
# Create public ip
creation_result = create_public_ip_address(network_client)
print("------------------------------------------------------")
print(creation_result)
# Create VNet
print('\nCreate Vnet')
async... | 434091989218e253738a1f7528f9402714b6c9da | 3,622,146 |
def dya(series, n=1):
"""Difference over n years, annualized"""
return (series-series.shift(n*series.index.freq.periodicity)) / n | 4f414beec19d9d6b5acfc87890b7ea2681f8d251 | 3,622,147 |
def new_entry(sector: dict, trying: str) -> bool:
"""
Checks if the text need a new entry.
"""
return sector["color"] is not None and color.__contains__(trying) | 42fa4a6474ef746d395821dfa01fbb7317e9345d | 3,622,148 |
def node(env, node_name):
"""Display a dashboard for a node showing as much data as we have on that
node. This includes facts and reports but not Resources as that is too
heavy to do within a single request.
:param env: Ensure that the node, facts and reports are in this environment
:type env: :obj... | 6450370bcc95a86818a92dd5171bace725ab7df4 | 3,622,149 |
def Tanh(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None):
"""
Tanh stub
"""
inputRNN = RNNCell(1, input_size, hidden_size, _rnn_impls['RNN_TANH'], 1, bias, output_size)
inputRNN = RNNCell(1, input_size, hidden_size, RNNTanhCell, ... | 69ce203142387bac06217563cd982315048b3eb7 | 3,622,150 |
from typing import List
from typing import Dict
from typing import Any
def combine_config(input_configs: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Combine multiple dcm2bids config dicts into a single config dict.
Args:
input_configs (list[dict[str, Any]]): A list of dcm2bids configs (dicts)
Re... | 008fa715323dd1c25592ba55db3270a4610b6c21 | 3,622,151 |
def dup_gegenbauer(n, a, K):
"""Low-level implementation of Gegenbauer polynomials."""
seq = [[K.one], [K(2)*a, K.zero]]
for i in range(2, n + 1):
f1 = K(2) * (i + a - K.one) / i
f2 = (i + K(2)*a - K(2)) / i
p1 = dmp_mul_ground(dup_lshift(seq[-1], 1, K), f1, 0, K)
p2 = dmp_m... | 11deeff9f4273a6dce8d397a85c8e44da7804de9 | 3,622,152 |
def find_projects(company_name, project_list):
"""returns list of projects associated with company_name
:param company_name: name of company to return projects for
:type company_name: str
:param project_list: list of projects as dictionaries
:type project_list: list
:return: list
"""
re... | e2e193aa103bec6620fb17679ff02de92c3f299e | 3,622,153 |
import logging
def log_to_stdout(level=15):
"""
Adds the stdout to the logging stream and sets the level to 15 by default
"""
logger = logging.getLogger("fetch_data")
# remove existing file handlers
for handler in logger.handlers:
if isinstance(handler, logging.StreamHandler):
... | ec5f18ca6349664687621f298c17122b6733c8be | 3,622,154 |
def dh_to_trans_mats(dh_params: np.ndarray) -> np.ndarray:
"""Convert Denavit–Hartenberg parameters into relative transformation
matrices.
Args:
dh_params (np.ndarray): An #Nx4 array of DH parameters, which are
expected to have rows which correspond to the joints, and columns
... | 2b38b46dae92dded68b482de18d9f416ced96d6e | 3,622,155 |
import asyncio
from typing import Counter
import itertools
def train(args):
"""Sets up connector to train two agents forever.
Args:
args: Command-line arguments.
Returns:
Game connector.
"""
weighted_heuristics = _get_weighted_heuristics(args)
transposition_table = _get_trans... | 2de298498e09181346260bcaa15c7932d15872d9 | 3,622,156 |
def get_text_width_px(window, text_str):
"""Using window settings, find width in pixels of a text str.
Args:
window (wx.Window): Window to contain string using default font
text_str (str): string to find the width of
Returns:
(int) width of text_str in pixels in the given window
... | 2b37be97d789e13f7841f2355388a5c0268bd76c | 3,622,157 |
def post_jobs():
"""
Create a job to create preferences/predictions for a custom sequence using the specified model(model_name).
request['sequence_id'] str: uuid of the custom sequence to process
request['job_type'] str: see config.DataType properties for values
request['model_name'] str: name of th... | dce127b40155884f8ae520d66d20582b5915f77d | 3,622,158 |
def fjv_fev(m1, m2, m3, jv, ev, e_out, f_out):
"""Computes the expansion terms from Luo et al. (2016)
See there: eq.(31) and Appendix B1
"""
# Expressions from Appendix B1 in Luo et al. (2016)
Jf0 = (3/4) * np.array([
( -5*ev[1]*ev[2] +... | 0bdce3e0d907d4140f6d4e338759d3413da7bbe8 | 3,622,159 |
def join_lines(lines):
"""Joins `lines` with newlines and returns a single string.
You would think you could do that with
| join("\n")
but you can't — see https://github.com/debops/ansible-sshkeys/issues/4
"""
return ''.join("%s\n" % l for l in lines) | e0041b302e662e02b153bc7b0ff8b3cb558bb7a5 | 3,622,160 |
def infotodict(seqinfo):
"""Heuristic evaluator for determining which runs belong where
allowed template fields - follow python string module:
item: index within category
subject: participant id
seqitem: run number during scanning
subindex: sub index within group
"""
info = {}
run... | a07290b674b6f18bdc50b62ee1b9b9d30357894b | 3,622,161 |
def stringlength_dat(x, m, tps, norm='default', isFreq=False, closed=True):
"""
Compute string length for data set.
Parameters
----------
x, m : arrays
x and y coordinates of data points.
tps : tuple or array
The trial periods (or frequencies): Either a three-tuple specifyin... | 69b2aefe11c7d3d84fda1f3d3fee8b65d8d1ae00 | 3,622,162 |
import uuid
def create_attached_file(comment=None, name=None, data=None):
"""Creates a attached file instance."""
if name is None:
name = str(uuid.uuid4()) + '.txt'
if data is None:
data = uuid.uuid4().bytes
return AttachedFile(comment, name, data) | dcc4c70fbc5e04ad6b153fefdb26b2593cb09bd8 | 3,622,163 |
import shutil
import sys
def withprogressbar(func):
"""Decorates ``func`` to display a progress bar while running.
The decorated function can yield values from 0 to 100 to
display the progress.
"""
def _func_with_progress(*args, **kwargs):
max_width, _ = shutil.get_terminal_size()
... | 143fed7cbb36d6d1f01525967ed825d5fa0c6346 | 3,622,164 |
def b_makeselects(bselected=None, sweep=None):
"""bselected - optional pre-selected bacctid
sweep - optional, shows investment election (ielectionid)
"""
dbcon = mysql.connector.connect(**moneywatchconfig.db_creds)
cursor = dbcon.cursor(dictionary=True)
markup = ''
# sweep
if sweep:
... | f7ee93c4c317279d2f1d056c0253f4eb0ad71dec | 3,622,165 |
def international_gravity(lat: float, epoch: str = '1980') -> float:
"""
International Gravity Formula
Estimate the normal gravity, :math:`g`, using the International Gravity
Formula [Lambert]_, adapted from Stokes' formula, and adopted by the
`International Association of Geodesy <https://www.iag-... | 4a82c6a745b75cfbeff41ab47e0da1cf2ff634b2 | 3,622,166 |
def eclean_pkg(
destructive=False,
package_names=False,
time_limit=0,
exclude_file="/etc/eclean/packages.exclude",
):
"""
Clean obsolete binary packages
destructive
Only keep minimum for reinstallation
package_names
Protect all versions of installed packages. Only meani... | ec82a3c3a97fc4c037e93dc37a9547ed8178ce2e | 3,622,167 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
action_list = list()
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] ==EMPTY:
action_list.append((i,j))
return action_list | 77a1f4822eda61d39024e7895807458ed0a53898 | 3,622,168 |
def health():
""" Serve React App """
return "Hello World!" | ef7938daeadd74361d954153c723dd136590962b | 3,622,169 |
import math
import re
import sys
def validate_name(string, name_type):
"""
Validates the node & property names
"""
if type(string) != str and math.isnan(string):
return None
match = None
if name_type == 'node':
match = re.search('''[^a-zA-Z_]''', string)
elif name_type ... | 122ac61657d088a5dccbacc3bae8fc80183ce3d2 | 3,622,170 |
import ray
import dataclasses
import tqdm
def compile_all(stages, num_micro_batches, default_as_option):
"""
Compile all input stages.
"""
num_cpus = int(
min(max(ray.available_resources()["CPU"] // 2, 1), len(stages)))
compile_workers = CompileWorkerPool(num_cpus)
for stage_id, (_, s... | e57faff072b55b443489665c6f397525b69b65f6 | 3,622,171 |
def reconcile(*arrays, order=0):
"""
Make sure 1D arrays are the same length. If not, stretch them to match
the longest.
Args:
arrays (ndarray): The input arrays.
order (int): The order of the interpolation, passed to
scipy.ndimage.zoom. Suggestion: 0 for integers and 1 for ... | f974cef81e89e5d6d667221dfd3235d760d9dd61 | 3,622,172 |
def create_supervised_tbptt_trainer(
model,
optimizer,
loss_fn,
tbtt_step,
dim=0,
device=None
):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computationally intensive as
it requires to process the whole seq... | 14670e22a26c65b5bab92c7ffd1e47f22a2e6d74 | 3,622,173 |
def ImpulseNoise(p=0, name=None, deterministic=False, random_state=None):
"""
Creates an augmenter to apply impulse noise to an image.
This is identical to ``SaltAndPepper``, except that per_channel is always set to True.
dtype support::
See ``imgaug.augmenters.arithmetic.SaltAndPepper``.
... | 258c67ebd4f0f08ce9122b015fe663ac086a1dd1 | 3,622,174 |
import sys
def is_indy_sdk_module_installed():
"""Check whether indy (indy-sdk) module is installed.
Returns:
bool: Whether indy (indy-sdk) is installed.
"""
try:
# Check if already imported
if "indy" in sys.modules:
return True
# Try to import
r... | 8dc17e302c7a07482fdc43853d6a535a1ef2d847 | 3,622,175 |
import random
def generate_filenames(img, key, width=0):
"""
Generate a list of file names corresponding to the lines of image,
with each one containing the given key.
width will be calculated if not given or too small.
"""
needwidth = max(len(l) for l in img)
if width < needwidth + 2:
width = max(needwidt... | adf6ff6ab43cca6cc34faabfaa19993e18e661c5 | 3,622,176 |
from re import U
def _tfNormalizerDecorator(cls):
""" A decorator to reuse the Normalizer classes by building a tensorflow
graph equivalence of OnlineNormalizer.normalize """
assert issubclass(cls, OnlineNormalizer)
class _tfNormalizerParams(tfObject):
""" a wrapper for maintaining the tf var... | 6b9b07c6f16b17636f2f45346a23464805011f3d | 3,622,177 |
def create_user(email, password, first_name, last_name):
"""
Creates a new user
:param email: string
:param password: string
:param first_name: string
:param last_name: string
:return object:
"""
user = User(email=email, first_name=first_name, last_name=last_name)
user.hash_pass... | 3df3079aecf7f905af6d1c89aed8830a9c26def0 | 3,622,178 |
def doVar(*args):
"""
doVar(ea_t ea, bool isvar=True)
doVar(ea_t ea)
"""
return _idaapi.doVar(*args) | 7dcf989393e41c19442cb18ca75787777611f547 | 3,622,179 |
def show_past_outfits():
"""Show user's past outfits on the calendar"""
#make fake data for history of outfits so that prior dates have shit
return render_template("past_outfits.html") | c68820bfbb86e0a65fe496aefbfd345678ea0ed8 | 3,622,180 |
def simplify_using_aff(kernel, expr):
"""
Simplifies *expr* on *kernel*'s domain.
:arg expr: An instance of :class:`pymbolic.primitives.Expression`.
"""
deps = get_dependencies(expr)
inames = deps & kernel.all_inames()
# FIXME: Ideally, we should find out what inames are usable and allow
... | 336a9394e08dde52e3ec166e9361b0c3edd304c4 | 3,622,181 |
import numpy
def addition(rct_zmas, prd_zmas, rct_tors=()):
""" z-matrix for an addition reaction
"""
ret = None
dist_name = 'rts'
dist_val = 3.
count1 = automol.zmatrix.count(rct_zmas[0])
if len(rct_zmas) == 2:
count2 = automol.zmatrix.count(rct_zmas[1])
if count1 == 1 or... | e874f6d69db39d914a7ac0c78a9d65592d69fc9f | 3,622,182 |
def check_mag_outliers(datafr, bands, systems):
"""Returns a list with all the types of outliers found for each photometric system.
Parameters
----------
datafr: Pandas DataFrame containing the magnitudes from different photometric systems
for the stars in a given carton
bands: total list o... | 503c207b3be000867247dc8d45123e6398c776c4 | 3,622,183 |
def temp_powlaw( V_a, T0, eos_d ):
"""
Return temperature for debye model
V_a: sample volume array
T0: temperature at V=V0
"""
# get parameter values
param_d = eos_d['param_d']
V0 = param_d['V0']
gamma0 = param_d['gamma0']
q = param_d['q']
gamma_a = gamma_powlaw( V_a, eos_d ... | 111995ef824c7f2917c3dc0585576ac2440e123f | 3,622,184 |
def hypergeometric_pmf(N, K, n, k, approx=False):
"""
Calculates the hypergeometric probability mass function.
See https://en.wikipedia.org/wiki/Hypergeometric_distribution
Parameters
----------
N : float
The population size.
K : float
The number of success states in the po... | 87585a5859188c6a9e435f067cded1e8d6596e98 | 3,622,185 |
import pwd
import os
import grp
import tarfile
import io
import time
def to_tarball(alert_generator, **tarfile_kwargs):
"""
Write alert dicts to a tar archive
"""
uid = pwd.getpwuid(os.geteuid()).pw_name
gid = grp.getgrgid(os.getegid()).gr_name
euid = os.geteuid()
egid = os.getegid()
w... | 671e8f6de844da48326f65449ad66d0771ae32fd | 3,622,186 |
from typing import Any
def is_iterable(x: Any) -> bool:
"""Check if a value is iterable, which is not a scalar"""
return not is_scalar(x) | 6c092497eb3a194683208098bff93f9ccd1f0fab | 3,622,187 |
def process(tile, image, scale, vmin, vmax, nbin, nodata, all_valid,
ignore_alpha):
""" Process one tile. """
# pylint: disable=too-many-arguments
tile = tile & image # clip tile to the image extent
if ignore_alpha:
tile = tile.set_z(tile.size.z - 1)
b_data = image.read(Block(ima... | 552b2714d46de21635e77c4b1fadf944fd407a1c | 3,622,188 |
import torch
def _softmax(x: Tensor, dim: int) -> Tensor:
"""(F.softmax())
:param x: shape = (N, In)
:param dim: int. 一般dim设为-1
:return: shape = x.shape"""
return torch.exp(x) / torch.sum(torch.exp(x), dim, keepdim=True) | 157cc9391c97223363469cfc99a92de49cbaf113 | 3,622,189 |
def add_legend(ax=None,colors=[],labels=[],styles='solid',\
widths=0.7,anchor=(0,1), ncol=3,loc='lower left',fontsize='small',frameon=False,**kwargs):
"""
- Adds custom legeneds on a given axes,returns None.
- **Parameters**
- ax : Matplotlib axes.
- colors : List of ... | 8a5eae81dddf704da47ff59b7c4f04ccb48a066e | 3,622,190 |
def test_retrieve_and_encode_simple(test_client, test_collection_name):
"""Test retrieving documents and encoding them with vectors.
"""
VECTOR_LENGTH = 100
def fake_encode(x):
return test_client.generate_vector(VECTOR_LENGTH)
# with TempClientWithDocs(test_client, test_collection_name, 100)... | 4fb6b1ea0278575ff53778dbefe8fb4f12a9abc2 | 3,622,191 |
def get_scale_name(model_path, scale=None):
""" try to get model scale from model name"""
rlt_scale = None
scale_name = str(osp.basename(model_path)[0:2]).lower()
if 'x' in scale_name:
try:
rlt_scale = int(scale_name.replace('x', ''))
except ValueError:
rlt_scale... | c5de89118224a7a3ad3773ce68ac2483fbed38f3 | 3,622,192 |
import time
def rbox_overlaps(anchors, gt_bboxes, use_cv2=False):
"""
Args:
anchors: [NA, 5] x1,y1,x2,y2,angle
gt_bboxes: [M, 5] x1,y1,x2,y2,angle
Returns:
"""
assert anchors.shape[1] == 5
assert gt_bboxes.shape[1] == 5
gt_bboxes_ploy = [rbox2poly_single(e) for e in g... | f72f719ad74e1ffc12dbfcc87d35dc5858049de3 | 3,622,193 |
import os
import json
def load_model_data(root_dir, model_name):
"""
Used for models split in several files.
Loads subscripts_dic, namespace and modules dictionaries
Parameters
----------
root_dir: str
Path to the model file.
model_name: str
Name of the model without fil... | f26a491003c43224e08daf361bf95a6be3756f36 | 3,622,194 |
from typing import Union
from typing import Tuple
def split_and_check(
s: str, separator: str, n: Union[int, Tuple[int, ...]]
) -> Tuple[str, ...]:
"""Turn string into tuple, checking that there are exactly as many parts as expected.
:param s: String to parse
:param separator: Separator character
... | 2d2d67245e08eb9d919f1b6acd0b7b0d0269c8b6 | 3,622,195 |
def make_random_gate_statement(
*, count=None, parameter_types=None, return_params=False
):
"""Make a gate statement with random arguments based on
a GateDefinition."""
definition, _, parameters = make_random_gate_definition(
parameter_count=count, parameter_types=parameter_types, return_params=... | 72ffbad68f23c027ef4a20a4dc03569f0e232f75 | 3,622,196 |
def run():
"""Run example"""
return 'running...' | 702a6af69b98326b8a557929e06d2e8bc4308660 | 3,622,197 |
from typing import Type
from typing import Optional
from abc import ABC
def _get_kind(type_: Type[TData]) -> Optional[TypeKind]:
"""Extract kind information from type."""
if ABC in type_.__bases__:
return TypeKind.Abstract
elif Record not in type_.mro():
return TypeKind.Element
else:
... | 9fb9a801f56dbd7e5209808a2071c669a41959a7 | 3,622,198 |
def calculate_voting_power(error_rate):
"""Given a classifier's error rate (a number), returns the voting power
(aka alpha, or coefficient) for that classifier."""
if error_rate == 0:
return INF
elif error_rate == 1:
return -INF
else:
return make_fraction(1,2) * ln((1-error_r... | 46a6e580a07c1efd8367715960f62e8facda7f0c | 3,622,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.