content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_cnt_sw(g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi, mode):
""" usalbe only when g_wc was used to find pr_wv
"""
cnt_sc = get_cnt_sc(g_sc, pr_sc)
cnt_sa = get_cnt_sa(g_sa, pr_sa)
cnt_wn = get_cnt_wn(g_wn, pr_wn)
cnt_wc = get_cnt_wc(g_wc, pr_wc)
cnt_w... | 069632779f353e28f23a0687e11d00761c8dea19 | 3,635,200 |
def _get_memcache_client():
"""Return memcache client if it's enabled, otherwise return None"""
if not cache_utils.has_memcache():
return None
return cache_utils.get_cache_manager().cache_object.memcache_client | c781bf4d638fc4b094fc0d64943b9305e0ec18b8 | 3,635,201 |
def get_long_description(readme_file='README.md'):
"""Returns the long description of the package.
@return str -- Long description
"""
return "".join(open(readme_file, 'r').readlines()[2:]) | 604c57fce1f9b8c32df4b64dc9df4fe61120d680 | 3,635,202 |
import requests
def extract_dem(
bounds,
out_raster="dem.tif"
):
"""Get 25m DEM for area of interest from BC WCS, write to GeoTIFF
"""
bbox = ",".join([str(b) for b in bounds])
# build request
payload = {
"service": "WCS",
"version": "1.0.0",
"request": "GetCoverage... | 9ff9349df9e3cd129a12111f2f45f151bd2851d0 | 3,635,203 |
def G1DListGetEdgesComposite(mom, dad):
""" Get the edges and the merge between the edges of two G1DList individuals
:param mom: the mom G1DList individual
:param dad: the dad G1DList individual
:rtype: a tuple (mom edges, dad edges, merge)
"""
mom_edges = G1DListGetEdges(mom)
dad_edges = G1DListG... | c61ffa657dfaf3daecfbc66d4166aa57efb6141b | 3,635,204 |
def entropy_approximate(signal, delay=1, dimension=2, tolerance="default", corrected=False, **kwargs):
"""Approximate entropy (ApEn)
Python implementations of the approximate entropy (ApEn) and its corrected version (cApEn).
Approximate entropy is a technique used to quantify the amount of regularity and t... | 5e39f5aa4e571e3e8d452c79b3742520af2644bc | 3,635,205 |
from typing import Tuple
def ir_typeref_to_type(
schema: s_schema.Schema,
typeref: irast.TypeRef,
) -> Tuple[s_schema.Schema, s_types.Type]:
"""Return a schema type for a given IR TypeRef.
This is the reverse of :func:`~type_to_typeref`.
Args:
schema:
A schema instance. The r... | 71ce2deae8caa5a177e0d8ad7df60ce1ba1b1be6 | 3,635,206 |
def get_releases_query(session: db.Session, current_user: UserType, show_legacy=False):
"""Returns the query necessary to fetch a list of releases
If a user is passed, then the releases will be tagged `is_mine` if in that user's collection.
"""
if current_user.is_anonymous():
query = session.qu... | 56732a67eb909f89afe01f6189c516d06bccf518 | 3,635,207 |
def get_total_supply(endpoint=_default_endpoint, timeout=_default_timeout) -> int:
"""
Get total number of pre-mined tokens
Parameters
----------
endpoint: :obj:`str`, optional
Endpoint to send request to
timeout: :obj:`int`, optional
Timeout in seconds
Returnss
-------... | f235be169273a638f042ab661fc88744a0b029ae | 3,635,208 |
def _is_css(filename):
"""
Checks whether a file is CSS waveform data (header) or not.
:type filename: str
:param filename: CSS file to be checked.
:rtype: bool
:return: ``True`` if a CSS waveform header file.
"""
# Fixed file format.
# Tests:
# - the length of each line (283 c... | 57d7b1fdbc244a7d17c905b5f5b5a2aa653f6e13 | 3,635,209 |
def extract_versions():
"""
Extracts version values from the main matplotlib __init__.py and
returns them as a dictionary.
"""
with open('lib/matplotlib/__init__.py') as fd:
for line in fd.readlines():
if (line.startswith('__version__numpy__')):
exec(line.strip())... | b54733ffdae76206400e7203f792e3b809cf6c30 | 3,635,210 |
def check_range(coord, range):
"""Check if coordinates are within range (0,0,0) - (range)
Returns
-------
bool
Success status
"""
# TODO: optimize
if len(coord) != len(range):
raise ValueError(
"Provided coordinate %r and given range %r" % (coord, range)
... | e6e5e5585f02d3c3c6fbec51963d2e637d8643c9 | 3,635,211 |
def make_df(raw_data, add_annotations = True):
"""
Basic preprocessing of data:
* Turn dictionry into a pandas dataframe
* Add annotator column to DF -- stored as string
* Name columns according to body part, etc
"""
df = []
labels = []
seqs = []
for seq_id in raw_data['sequences... | cfc893b3616c879e734cabfd8a2dc420aec095d7 | 3,635,212 |
def cyclic_tdma(lower_diagonal, main_diagonal, upper_diagonal, right_hand_side):
"""The thomas algorithm (TDMA) solution for tri-diagonal matrix inversion with the sherman morison formula applied
Parameters
----------
lower_diagonal: np.ndarray
The lower diagonal of the matrix length n, the fir... | a1fd869d181caad075a14bae061c8ee217ef185f | 3,635,213 |
def lico2_ocp_Ramadass2004(sto):
"""
Lithium Cobalt Oxide (LiCO2) Open Circuit Potential (OCP) as a a function of the
stochiometry. The fit is taken from Ramadass 2004. Stretch is considered the
overhang area negative electrode / area positive electrode, in Ramadass 2002.
References
----------
... | 2c0902e1d1cdec9ac7626038e34092933665bf84 | 3,635,214 |
import doctest
def doctestobj(*args, **kwargs):
"""
Wrapper for doctest.run_docstring_examples that works in maya gui.
"""
return doctest.run_docstring_examples(*args, **kwargs) | 1efccd1a887636bbcf80e762f12934e7d03efe28 | 3,635,215 |
def _return_model_names_for_plots():
"""Returns models to be used for testing plots. Needs
- 1 model that has prediction interval ("theta")
- 1 model that does not have prediction interval ("lr_cds_dt")
- 1 model that has in-sample forecasts ("theta")
- 1 model that does not have in-... | bd180134c5c74f4d1782384bc8e3b13abff8b125 | 3,635,216 |
def _convert_input_type_range(img):
"""Convert the type and range of the input image.
It converts the input image to np.float16 type and range of [0, 1].
It is mainly used for pre-processing the input image in colorspace
convertion functions such as rgb2ycbcr and ycbcr2rgb.
Args:
img (Asce... | 990516e2cb069b9afd4388c6fbb8f1f333893dc9 | 3,635,217 |
from pathlib import Path
def collect_derivatives(derivatives_dir, subject_id, std_spaces, freesurfer,
spec=None, patterns=None):
"""Gather existing derivatives and compose a cache."""
if spec is None or patterns is None:
_spec, _patterns = tuple(
loads(Path(pkgrf('a... | f33353c4c67d847b94f4d8467c6721ecc7dc71fa | 3,635,218 |
def aten_meshgrid(mapper, graph, node):
""" 构造对每个张量做扩充操作的PaddleLayer。
TorchScript示例:
%out.39 : int = aten::mshgrid(%input.1)
参数含义:
%out.39 (Tensor): 输出,扩充后的结果。
%input.1 (Tensor): 输入。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_outputs... | e260855ca6732f9d846cc492c949197e93e9551a | 3,635,219 |
def bearing_example():
"""This function returns an instance of a simple bearing.
The purpose is to make available a simple model
so that doctest can be written using it.
Parameters
----------
Returns
-------
An instance of a bearing object.
Examples
--------
>>> bearing = ... | f4d8e71b0b13aa17f9ad08208e8082ef5827a70c | 3,635,220 |
import os
def parsing_check(dataset, source, attr):
"""
The annotator gets a contextualized patent citation displayed
- the patent citation is highlighted
- the title (h3 + bold + purple) is the value of the parsed attribute (e.g. orgname)
- the citation has an href linking to the patent webpage (... | 9f920f53ddd488a08f63ee7e12b558ebb90c7335 | 3,635,221 |
def create_data():
"""Create some random exponential data"""
#np.random.seed(18)
pure = np.array(sorted([np.random.exponential() for i in range(10)]))
noise = np.random.normal(0,1, pure.shape)
signal = pure + noise
return signal | 613231436fe0faca177106cf80abe5d475510469 | 3,635,222 |
def fetch_accidents(data_home=None):
"""Fetch and return the accidents dataset (Frequent Itemset Mining)
Traffic accident data, anonymized.
see: http://fimi.uantwerpen.be/data/accidents.pdf
==================== ==============
Nb of items 468
Nb of transactions ... | 612a7c67fc5b81297ec7ca37d38e0267d23fed36 | 3,635,223 |
def align_nodes(nodenet_uid, nodespace):
""" Automatically align the nodes in the given nodespace """
return runtime.align_nodes(nodenet_uid, nodespace) | aa9fd5f22d8433d0b15e9b826dba9d4c6fa1b590 | 3,635,224 |
def cindex(y_true: np.array, scores: np.array) -> float:
"""AI is creating summary for cindex
Args:
y_true (np.array): An array of actual values of target
scores (np.array): An array of predicted score of target
Returns:
[float]: Returns C-Index score
"""
return lifelines.u... | e69bc4f2e3b391c4049b6b60936a64bcfff9f27d | 3,635,225 |
def match_tones(
left, right, eps=2000., shift_from_right=0.,
match_col='fr',
join_type='inner'):
"""Return a table with tones matched.
This function makes use the ``stilts`` utility.
Parameters
----------
left: astropy.Table
The left model params table.
right: ... | 0be28ac4727b721f4b8847b6e3bc92fbea95de55 | 3,635,226 |
import logging
def name(ea, string, *suffix, **flags):
"""Renames the address specified by `ea` to `string`.
If `ea` is pointing to a global and is not contained by a function, then by default the label will be added to the Names list.
If `flags` is specified, then use the specified value as the flags.
... | f3f16ba223f45bd74cf4987274a3cda8c5bb0098 | 3,635,227 |
from typing import Tuple
from typing import Optional
from typing import List
from typing import cast
def verify(
symbol_table: intermediate.SymbolTable,
) -> Tuple[Optional[VerifiedIntermediateSymbolTable], Optional[List[Error]]]:
"""Verify that C# code can be generated from the ``symbol_table``."""
error... | c7af0f196cb59022f89f8097f17e98a913fb7615 | 3,635,228 |
import time
def find_workflow_component_figures(page):
""" Returns workflow component figure elements in `page`. """
time.sleep(0.5) # Pause for stable display.
root = page.root or page.browser
return root.find_elements_by_class_name('WorkflowComponentFigure') | 1a56a0a348803394c69478e3443cbe8c6cb0ce9c | 3,635,229 |
def select_best_features(tx, selected_features, rho_exp, w, number_of_select):
"""Selects features by the highest value of the weights
Parameters
----------
tx : np.ndarray
Original features
selected_features : [(int, int)]
Best features from previous iteration
rho_exp : np.nda... | bef855b3685116cec90cfc51194e00d5cee4d3af | 3,635,230 |
def make_pol_lookup(codes):
"""
Returns a lookup table from a list of polarization codes
"""
codes = unique(codes)
codes.sort()
lookup = {}
for code in codes:
if code == 'X' or code == 'XX' or code == 'H':
lookup[code] = -5
elif code == 'Y' or code == 'YY' or code == 'V' or code == 'E':
... | f5c4aece195ff436af8855a5296e1be493c92737 | 3,635,231 |
def _calc_best_estimator_optuna_univariate(
X,
y,
estimator,
measure_of_accuracy,
estimator_params,
verbose,
test_size,
random_state,
eval_metric,
number_of_trials,
sampler,
pruner,
with_stratified,
):
"""Function for calculating best estimator
Parameters
... | 35cbc2458455d7153a1b17c91576c2629baf2ab3 | 3,635,232 |
def get_users_info_async(future_session: "FuturesSession", connection, name_begins,
abbreviation_begins, offset=0, limit=-1, fields=None):
"""Get information for a set of users asynchronously.
Args:
future_session: Future Session object to call MicroStrategy REST
Se... | f2679de38822a12abb2e0e65d102de7876304ccd | 3,635,233 |
import os
import gzip
def load_sparse(fname):
"""
.. todo::
WRITEME
"""
f = None
try:
if not os.path.exists(fname):
fname = fname + '.gz'
f = gzip.open(fname)
elif fname.endswith('.gz'):
f = gzip.open(fname)
else:
f =... | 98fcee3e8ebe0ee76d61e08cb6f32b2c00bc5149 | 3,635,234 |
def site_link_url(request, siteobj):
"""returns a site urls form already given keys"""
return '%s://%s%s/site/%s' % (
presettings.DYNAMIC_LINK_SCHEMA_PROTO,
request.META.get('HTTP_HOST'),
presettings.DYNAMIC_LINK_URL,
siteobj.link_key
) | c0a29c6ac0157e7ac7fae506ea9f87960c03a92e | 3,635,235 |
def get_arguments():
""" All cli arguments. """
p = ap.ArgumentParser()
p.add_argument('mode', type=str, choices=['train', 'predict'])
# files
p.add_argument('--train-file', type=str)
p.add_argument('--dev-file', type=str)
p.add_argument('--test-file', type=str)
p.add_argument('--model-... | e1d426856fcb7fba3e8bf56200748a7354b09797 | 3,635,236 |
import configparser
def get_headers(path='.credentials/key.conf'):
"""Get the authentication key header for all requests"""
config = configparser.ConfigParser()
config.read(path)
headers = {
'Ocp-Apim-Subscription-Key': config['default']['primary']
}
return headers | d40c1b6246efb728040adc47b6180f50aa4dc3e8 | 3,635,237 |
def Sdif(M0, dM0M1, alpha):
"""
:math:`S(\\alpha)`, as defined in the paper, computed using `M0`,
`M0 - M1`, and `alpha`.
Parameters
----------
M0 : ndarray or matrix
A symmetric indefinite matrix to be shrunk.
dM0M1 : ndarray or matrix
M0 - M1, where M1 is a positive defini... | 6463cb04d7dcfaad93358c7db38f4674a51654b2 | 3,635,238 |
import os
def env_world_size():
"""World size for distributed training.
Is set in torch.distributed.launch as args.nproc_per_node * args.nnodes.
For example, when running on 1 node with 4 GPUs per node, the world size is 4.
see: https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.... | 58587f8f4462fd18e156834214385f5dfebfaa2a | 3,635,239 |
def add_entry(entries, folders, collections, session):
"""Add vault entry
Args: entries - list of dicts
folders - dict of folder objects
collections - dict of collections objects
session - bytes
Returns: None or entry (Item)
"""
folder = select_folder(folders)
col... | 7eab6d0b1df5c713c96a2b70dd874345faf28b3f | 3,635,240 |
import sys
import warnings
def make_wsgi_app(services_conf=None, debug=False, ignore_config_warnings=True, reloader=False):
"""
Create a MapProxyApp with the given services conf.
:param services_conf: the file name of the mapproxy.yaml configuration
:param reloader: reload mapproxy.yaml when it chang... | f8c6bf1cb6a7a3fd591e04ad43faa50fb17fb3f3 | 3,635,241 |
def _get_node_by_name(graph_def: rewrite.GraphDef,
node_name: str) -> rewrite.NodeDef:
"""Return a node from a graph that matches the provided name"""
matches = [node for node in graph_def.node if node.name == node_name]
return matches[0] if len(matches) > 0 else None | 8e893b4d51a1fba861f7659ec7edaf8bd794e114 | 3,635,242 |
import requests
def shorten_link(url: str) -> tuple:
"""
Method to shorten a given url using the shrtco.de API
@Parameters
url:str url to be shortened
@Returns
(errorcode:int,result:str)
errorcode: int indicating whether operation succeeded ... | c8acbcb1641d8344ced55e5bd820f0084fc01164 | 3,635,243 |
from typing import Dict
def get_sanitized_bot_name(dict: Dict[str, int], name: str) -> str:
"""
Cut off at 31 characters and handle duplicates.
:param dict: Holds the list of names for duplicates
:param name: The name that is being sanitized
:return: A sanitized version of the name
"""
# ... | 42d432610602b15b1206f0ce1bc007fdaef6b23f | 3,635,244 |
def eval_nmt_bleu(model,dataset,vectorizer,args):
"""
Evaluates the trained model on the test set using the bleu_score method
from NLTK.
Parameters
----------
model : NMTModel
Trained NMT model.
dataset : Dataset
Dataset with Source/Target sentences.
vectorizer : object
... | e26bb0ab39cf7af704a32e8ed36d7df44a799f55 | 3,635,245 |
import yaml
def load_up_the_tests(folder):
"""reads the files from the samples directory and parametrizes the test"""
tests = []
for i in folder:
if not i.path.endswith('.yml'):
continue
with open(i, 'r') as f:
out = yaml.load(f.read(), Loader=yaml.BaseLoader)
... | 5361f7805452471cf65385ddb1901709d69245a7 | 3,635,246 |
from .algorithms.dpll import dpll_satisfiable
from .algorithms.dpll2 import dpll_satisfiable
def satisfiable(expr, algorithm='dpll2', all_models=False):
"""
Check satisfiability of a propositional sentence.
Returns a model when it succeeds.
Returns {true: true} for trivially true expressions.
On ... | 03cfa14bfa2f7812263f7ca5be98e583e7a3136c | 3,635,247 |
def dist_create_samples(net_file, K=Inf, nproc=None, U=0.0, S=0.0, V=0.0, max_iter=Inf, T=Inf, discard=False,
variance=False,
input_vars=DEFAULT_INPUTS, output_vars=DEFAULT_OUTPUTS, dual_vars=DEFAULT_DUALS,
sampler='sample_polytope_cprnd', sampler_... | a012c019374b45e9a657b15f602b2cbc4b9cbc31 | 3,635,248 |
import re
def get_valid_filename(s):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; slashes and colons are converted to
dashes; and anything that is not a un... | 7be8b5080d79b44b167fe2b1cf03108b1a36b169 | 3,635,249 |
import re
def clean_text(text, remove_stopwords = True):
"""
remove artifacts, unneccessary words etc
"""
## regex method - remove '\n'
cleantext = re.sub(r"\\n", " ", text)
## remove '\BA'
cleantext = re.sub(r"\\BA", " ", cleantext)
## remove '\'
... | f7ee64e905b22d62d039e94251347aa126588f09 | 3,635,250 |
def initialise_empty_cells():
"""Initialise empty dictionary of cells for the grid."""
cells = {(x, y): False for x in range(CELL_WIDTH) for y in range(CELL_HEIGHT)}
return cells | eed3b50adefa7c5bf8dff9875ee26f23217e54e5 | 3,635,251 |
def query_left(tree, index):
"""Returns sum of values between 1-index inclusive.
Args:
tree: BIT
index: Last index to include to the sum
Returns:
Sum of values up to given index
"""
res = 0
while index:
res += tree[index]
index -= (index & -index)
... | e293194c86ad1c53a005be290ba61ef2fff097c8 | 3,635,252 |
def deleteCategory(category_name):
""" This endpoint will show category delete confirmation by GET request
and will delet the category by POST request."""
session = DBSession()
category = session.query(Category).filter_by(name=category_name).one()
if request.method == 'POST' and login_session['user... | cf1ef2e0363347125cc270b5c07751da5a5467f8 | 3,635,253 |
def figure_defaults():
"""Generates default figure arguments.
Returns:
dict: A dictionary of the style { "argument":"value"}
"""
plot_arguments={
"fig_width":"6.0",\
"fig_height":"6.0",\
"xcols":[],\
"xvals":"",\
"xvals_colors_list":[],\
"xvals_co... | 262053b3f6d94b5290f869f56cc7d162791166ac | 3,635,254 |
def apply_box_deltas_graph(boxes, deltas, Size=24):
"""Applies the given deltas to the given boxes.
boxes: [N, (z1, y1, x1, z2, y2, x2)] boxes to update
deltas: [N, (dz, dy, dx)] refinements to apply
"""
# center_z, center_y, center_x are the (normalized) coordinates of the centers
center_z... | 9a9c6a8c40f53d0956533a55815e65a2fa94eaf1 | 3,635,255 |
def calculate_number_of_peaks_gottschalk_80_rule(peak_to_measure, spread):
"""
Calculate number of peaks optimal for SOBP optimization
on given spread using Gottschalk 80% rule.
"""
width = peak_to_measure.width_at(val=0.80)
n_of_optimal_peaks = int(np.ceil(spread // width))
return n_of_opti... | 2204222a3df6ebe4bebb62f5e4c53311cadaaa77 | 3,635,256 |
def maxsum(sequence):
"""Return maximum sum."""
maxsofar, maxendinghere = 0, 0
for x in sequence:
# invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]``
maxendinghere = max(maxendinghere + x, 0)
maxsofar = max(maxsofar, maxendinghere)
return maxsofar | 884d8b5dd20a0a35ff79c64bc6151b0d8ae7f5a0 | 3,635,257 |
import torch
def matrix_from_angles(rot):
"""
Create a rotation matrix from a triplet of rotation angles.
Args:
rot: a tf.Tensor of shape [..., 3], where the last dimension is the rotation angles, along x, y, and z.
Returns:
A tf.tensor of shape [..., 3, 3], where the last two d... | 2108cf7d59d5f641ef7a9813f32cae7a33b00322 | 3,635,258 |
from re import X
import sys
def textbox(msg="", title=" ", text="", codebox=0, get_updated_text=None):
"""
Display some text in a proportional font with line wrapping at word breaks.
This function is suitable for displaying general written text.
The text parameter should be a string, or a list or tup... | c017053c98c69c57550d4e7d73b30264c253d5f4 | 3,635,259 |
def get_fov_stats(mrcnn, low_confidence, discordant,
extreme, artifacts,
roi_mask= None, keep_thresh = 0.5,
fov_dims= (256,256), shift_step= 128):
"""
Gets potential FOVs along with their associated
statistics.
Args:
* mrcnn [m, n, 4] - pos... | 767a101900ebdf68e8fbf3fedac8bfaa58b27c15 | 3,635,260 |
import torch
def negative_sampling_loss(pos_dot, neg_dot, size_average=True, reduce=True):
"""
:param pos_dot: The first tensor of SKipGram's output: (#mini_batches)
:param neg_dot: The second tensor of SKipGram's output: (#mini_batches, #negatives)
:param size_average:
:param reduce:
:return:... | 18f05e138010b98ef8abaec35dd37030b08ecfcb | 3,635,261 |
def _has_externally_shared_axis(ax1: "matplotlib.axes", compare_axis: "str") -> bool:
"""
Return whether an axis is externally shared.
Parameters
----------
ax1 : matplotlib.axes
Axis to query.
compare_axis : str
`"x"` or `"y"` according to whether the X-axis or Y-axis is being
... | 6f71975e62ba763e2fece42e4d3d760e12f5ddc5 | 3,635,262 |
def network_size(graph, n1, degrees_of_separation=None):
""" Determines the nodes within the range given by
a degree of separation
:param graph: Graph
:param n1: start node
:param degrees_of_separation: integer
:return: set of nodes within given range
"""
if not isinstance(graph, (BasicG... | f62095abe184d818d25451b38430eaa331a71654 | 3,635,263 |
def get_conserved_sequences(cur):
"""docstring for get_conserved_sequences"""
cur.execute("SELECT sureselect_probe_counts.'sureselect.seq', \
sureselect_probe_counts.cnt, \
sureselect_probe_counts.data_source, \
cons.cons \
FROM sureselect_probe_counts, cons \
WHERE sures... | e518d22b7ac2ba072c75a76f72114009eed6ce7c | 3,635,264 |
from typing import Any
def delete_empty_keys(data: Any):
"""Build dictionary copy sans empty fields"""
# Remove empty field from dict
# https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary#5844700
dic = data.dict()
# if isinstance(data, BaseModel):
# dic = **data... | db190b021bb00ae3870e205bc27bf28dd09e29c3 | 3,635,265 |
import os
def scan_for_images(tmos_image_dir):
"""Scan for TMOS disk images"""
return_image_files = []
for image_file in os.listdir(tmos_image_dir):
filepath = "%s/%s" % (tmos_image_dir, image_file)
if os.path.isfile(filepath):
extract_dir = "%s/%s" % (tmos_image_dir,
... | 0cecfa07c80c75d75af0e15d9277cbb5ab3153c9 | 3,635,266 |
def find_language(article_content):
"""Given an article's xml content as string, returns the article's language"""
if article_content.Language is None:
return None
return article_content.Language.string | 4a228779992b156d01bc25501677556a5c9b7d39 | 3,635,267 |
import json
def loadDictFromFile(f):
"""
Load a DotDict from the JSON-format file *f*.
"""
return dotDict.convertToDotDictRecurse(json.load(f)) | 8b2ddb8f00675a05f129f33328e8d17d5f34a96a | 3,635,268 |
def create_problem_from_type_base(problem):
"""
Creates OptProblem from type-base problem.
Parameters
----------
problem : Object
"""
p = OptProblem()
# Init attributes
p.phi = problem.phi
p.gphi = problem.gphi
p.Hphi = problem.Hphi
p.A = problem.A
p.b = problem.b
... | c631e3f27d49b288e85e6043a81f658f65f962e2 | 3,635,269 |
import re
def geturls(str1):
"""returns the URIs in a string"""
URLPAT = 'https?:[\w/\.:;+\-~\%#\$?=&,()]+|www\.[\w/\.:;+\-~\%#\$?=&,()]+|' +\
'ftp:[\w/\.:;+\-~\%#?=&,]+'
return re.findall(URLPAT, str1) | 3d127a3c4250d7b013d9198e21cfb87f7909de8d | 3,635,270 |
import requests
def get_list(imid: str) -> requests.Response:
""" Return the requests.Response containing
the list of images for a given image-net.org
collection ID.
"""
imlist = requests.get(LIST_URL.format(imid=imid))
return imlist | da63e021e594eff6ee672e3aa234522a3d23e34d | 3,635,271 |
def minimum(x1, x2):
"""Element-wise minimum of input variables.
Args:
x1 (~chainer.Variable): Input variables to be compared.
x2 (~chainer.Variable): Input variables to be compared.
Returns:
~chainer.Variable: Output variable.
"""
return Minimum().apply((x1, x2))[0] | b511edb9c13abf3a0df5dad48d1fffcf1d96c82a | 3,635,272 |
import tokenize
import sys
def retype_file(src, pyi_dir, targets, *, quiet=False, hg=False):
"""Retype `src`, finding types in `pyi_dir`. Save in `targets`.
The file should remain formatted exactly as it was before, save for:
- annotations
- additional imports needed to satisfy annotations
- addi... | a31dc990ef46a1d3dec3e4be6b54c5ce2e310195 | 3,635,273 |
import torch
def train(train_dataset : dict, validation_dataset : dict, batch_size : int = 16,
num_epochs : int = 5000, allow_cuda : bool = True,
use_shuffle : bool = True, save_criterion : callable = None,
stop_criterion : callable = None, save_on_finish : bool = True) -> dict:
"""
... | db0b50be37fe1dd96bffa1c934d5a68d3ac5198e | 3,635,274 |
def reduce_to(n):
"""processor to reduce list"""
def reduce(list):
if len(list) < n:
return n
else:
return list[0:n]
return reduce | b9a1fb6091ef9801957c6cc64cab5485091d6801 | 3,635,275 |
def render(renderer_name, value, request=None, package=None):
""" Using the renderer ``renderer_name`` (a template
or a static renderer), render the value (or set of values) present
in ``value``. Return the result of the renderer's ``__call__``
method (usually a string or Unicode).
If the ``rendere... | 84e172cbb476f12ad6f7e801fa5b995fa2dedc20 | 3,635,276 |
import os
import torch
from ..iotools import check_and_clean
from .iotools import save_checkpoint
def write_cnn_weights(model, source_path, target_path, split, selection="best_acc"):
"""
Write the weights to be loaded in the model and return the corresponding path.
:param model: (Module) the model which ... | 19cba0ff31f39cca575631705cad64b060fb9746 | 3,635,277 |
def validate(number):
"""Check if the number provided is a valid NCF."""
number = compact(number)
if len(number) == 13:
if number[0] != 'E' or not isdigits(number[1:]):
raise InvalidFormat()
if number[1:3] not in _ecf_document_types:
raise InvalidComponent()
elif ... | f9d2f738b020fc49bbecb0a6be9805dd4243121a | 3,635,278 |
def upsampling_d1_batch_normal_act_subpixel(input_tensor,
residual_tensor,
filter_size,
layer_number,
active_function=tf.nn.relu,
... | 12b016e6e0e6d44bf396ccbbd9b4f9c870ea7bbf | 3,635,279 |
def search_ws(sheet, search_term, distance=20, warnings=True, origin=[0,0],
exact = False):
""" Searches through an excel sheet for a specified term.
The function searches along the bottom left to top right diagonals.
The function starts at the "origin" and only looks for values below or to
... | 3228ee48960b255cf042252ca0b5ac2f69c0d259 | 3,635,280 |
import os
def readfiles(meta):
"""
Reads in the files saved in datadir and saves them into a list
Parameters
-----------
meta
metadata object
Returns
----------
meta
metadata object but adds segment_list to metadata containing the sorted data fits files
Notes:
... | be62cd892e25f4b5cd5a1671b734bac6893c1df9 | 3,635,281 |
def obs_all_table_target_pairs_one_hot(agent_id: int, factory: Factory) -> np.ndarray:
"""One-hot encoding for each table target, NOT summed together; length: number of tables x number of nodes"""
num_nodes = len(factory.nodes)
num_tables = len(factory.tables)
table_target_pair = np.zeros(num_nodes * nu... | dc021799fa09e0bf37dac27908996e471b23223d | 3,635,282 |
import sys, spacy
def clean_up(text):
"""
This function clean up you text
and generate list of words for
each document.
It also corrects for unicode problems
with python version 2.
"""
removal=['ADV','PRON','CCONJ','PUNCT','PART','DET','ADP','SPACE']
text_out = []
if sys.... | c9c40992b9bec847dd66f2ef0a36e7356cf242a4 | 3,635,283 |
import logging
def logger(name):
"""
This method is the preferred way to obtain a logger.
Example:
>>> from qiutil.logging import logger
>>> logger(__name__).debug("Starting my application...")
:Note: Python ``nosetests`` captures log messages and only
reports them on fa... | bb876dbe4d7a522b807133427914c2e84ee99c4a | 3,635,284 |
import math
def severe_obesity_wfl(gender, length, weight, units='metric', severity=1):
"""
Returns a boolean indicator for a zscore determining if the reading is classified as severely obese from:
https://jamanetwork.com/journals/jamapediatrics/fullarticle/2667557.
NOTE: This should only be used for ... | c6de69ec90d278b69fb802ce8a435502b1668644 | 3,635,285 |
def calc_Flesh_Kincaid_Grade_rus_flex(n_syllabes, n_words, n_sent):
"""Метрика Flesh Kincaid Grade для русского языка с константными параметрами"""
if n_words == 0 or n_sent == 0: return 0
n = FLG_X_GRADE * (float(n_words) / n_sent) + FLG_Y_GRADE * (float(n_syllabes) / n_words) - FLG_Z_GRADE
return n | 93467f013107660f3b8ad03ac882e857434fbc45 | 3,635,286 |
import signal
def psd(x: np.ndarray, delf: float, type_psd: list, n: float = None) -> np.ndarray:
"""Returns 2d array of PSD computed with specified method
Args:
x (np.ndarray): Values in time domain
delf (float): Sampling Rate
type (list): [x, y] x=0 psd, x=1 psd density && y=0 stand... | 0efeb38798ddda5d09a4e3c762f1ebbed69c50da | 3,635,287 |
def comment(request):
"""留言功能"""
if request.method == "POST":
form = CommentForm(request.POST)
blog_id = request.POST["blog_id"]
user = request.user
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.user = user
new_commen... | a3f8cf5beed1edf3156817aaa0e36e377256d4b1 | 3,635,288 |
def calculate_height_filtration(
graph,
direction,
attribute_in='position',
attribute_out='f',
):
"""Calculate height filtration of a graph in some direction.
*Note*: This function works for *all* vector-valued attributes of
a graph, but in the following, it will be assumed that those
a... | 79010055e4a61862267b4cb9e9f5ebc9c3d1cdca | 3,635,289 |
def read_file(file_name, encoding='utf-8'):
"""
读文本文件
:param encoding:
:param file_name:
:return:
"""
with open(file_name, 'rb') as f:
data = f.read()
if encoding is not None:
data = data.decode(encoding)
return data | 4e4a90512727b4b40d4968930479f226dc656acb | 3,635,290 |
def cbf_qei(gm, wm, csf, img, thresh=0.8):
"""
Quality evaluation index of CBF base on Sudipto Dolui work
Dolui S., Wolf R. & Nabavizadeh S., David W., Detre, J. (2017).
Automated Quality Evaluation Index for 2D ASL CBF Maps. ISMR 2017
"""
def fun1(x, xdata):
d1 = np.exp(-(x[0])*np.po... | d52badc74cc01c615afa0a0a5cdab1d040d110e5 | 3,635,291 |
import sqlite3
def calendar():
"""page for all events"""
events = get_all_events(sqlite3.connect(DB_NAME).cursor())
return render_template("calendar.html", events=events) | bf6c1f12cb2261dc68389c56b8c92a4dbe879fda | 3,635,292 |
def _ui_device_family_plist_value(ctx):
"""Returns the value to use for `UIDeviceFamily` in an info.plist.
This function returns the array of value to use or None if there should be
no plist entry (currently, only macOS doesn't use UIDeviceFamily).
Args:
ctx: The Skylark context.
Returns:
... | 8d6669fcdaf02f1ef254dc77910f2e2e9dfa5126 | 3,635,293 |
def map_amplitude_grid(
ds_ind,
data_columns,
stokes='I',
chunk_size:int=10**6,
return_index:bool=False
):
"""
Map functions to a concurrent dask functions to an Xarray dataset with
pre-computed grid indicies.
Parameters
----------
ds_ind : xarray.dataset
An... | f363f1bc8de2eb58d5d6ecca529e0d8fca255496 | 3,635,294 |
def fetch_query(query, columns):
"""
Creates a connection to database, returns query from specified table
as a list of dictionaries.
Input: query: a SQL query (string)
Returns: pairs: dataframe of cursor.fetchall() response in JSON pairs
"""
# Fetch query
response = fetch_query_records(q... | 75465b0a920a19ca339c732bfe5b8ca4c356a9a5 | 3,635,295 |
import logging
def fetch(key):
"""Gets snapshots referenced by the given instance template revision.
Args:
key: ndb.Key for a models.InstanceTemplateRevision entity.
Returns:
A list of snapshot URLs.
"""
itr = key.get()
if not itr:
logging.warning('InstanceTemplateRevision does not exist: %s... | c567a0e76c602936b7fd018c8824c6d3cce0d70d | 3,635,296 |
def CreateNameToSymbolInfo(symbol_infos):
"""Create a dict {name: symbol_info, ...}.
Args:
symbol_infos: iterable of SymbolInfo instances
Returns:
a dict {name: symbol_info, ...}
If a symbol name corresponds to more than one symbol_info, the symbol_info
with the lowest offset is chosen.
"""
... | 6f6c0ebfdaf103126455d344c199106ee0c0b764 | 3,635,297 |
def EFI(data, period=13):
"""
Elder Force Index
EFI is an indicator that uses price and volume to assess the power behind a move or identify possible turning
points.
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:param int period: period used for indicator calcula... | ae644c82a5dc4fd304fd17f9939e427eccb47468 | 3,635,298 |
def Gdelta(GP, testfunc, firstY, delta=0.01, maxiter=10, **kwargs):
"""
given a GP, find the max and argmax of G_delta, the confidence-bounded
prediction of the max of the response surface
"""
assert testfunc.maximize
mb = MuBound(GP, delta)
_, optx = cdirect(mb.objective, testfunc.bounds, m... | 0a74a922cba87cfccc4a63e1195abe4dca8b6d9c | 3,635,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.