content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def vectorize(sentence, idf_weight, vocab, convey='idf'):
"""
idf_weight: {word: weight}
vocab: {word: index}
"""
vec = np.zeros(len(vocab), dtype=np.float32)
for word in sentence:
if word not in vocab:
continue
if convey == 'idf':
vec[vocab[word]] += idf_... | a245bfb82be2193dabb219fd24fd8cf035d3a1a9 | 3,636,400 |
import re
async def director_v2_service_mock(
aioresponses_mocker: AioResponsesMock,
) -> AioResponsesMock:
"""mocks responses of director-v2"""
# computations
create_computation_pattern = re.compile(
r"^http://[a-z\-_]*director-v2:[0-9]+/v2/computations$"
)
get_computation_pattern =... | 2b09e504fc3d1520be220dc81fc403ef63b1e797 | 3,636,401 |
def test_validation_unset_type_hints():
"""Test that unset type hints are handled correctly (and treated as Any)."""
@my_registry.optimizers("test_optimizer.v2")
def test_optimizer_v2(rate, steps: int = 10) -> None:
return None
config = {"test": {"@optimizers": "test_optimizer.v2", "rate": 0.1... | d4816ee06e05fb2332f35a60f336dd1bf75eb2bd | 3,636,402 |
def get_online_featurestore_connector(featurestore=None):
"""
Gets a JDBC connector for the online feature store
Args:
:featurestore: the feature store name
Returns:
a DTO object of the JDBC connector for the online feature store
"""
if featurestore is None:
featurestore ... | ada51764b823c0959571ea928d6bddc6b2dbee7b | 3,636,403 |
def create_multipoint_geometry(u, v, osr_spref):
"""
wrapper; creates multipoint geometry in given projection
Parameters
----------
u : list of numbers
input coordinates ("Rechtswert")
v : list of numbers
input coordinates ("Hochwert")
osr_spref : OGRSpatialReference
... | cea52b749e7e60a9fea192fd5ff288bced7be388 | 3,636,404 |
def open_tif_image(input_path):
# type: (function) -> np.array
"""Function to open tif images.
Parameters:
input_path (string) = path where the image file is located;
return
np.array of the tif image"""
# get the image_path.
image_path = input_path
# rea... | ab834b5b2ab983cab3f79dd1fc1acfe1394df50b | 3,636,405 |
import requests
def get_icd(url: str) -> requests.Response:
"""Get an ICD API endpoint."""
return requests.get(url, headers=get_icd_api_headers()) | 2a7ce491004cd0b69e7d988e8aaca56b4130b261 | 3,636,406 |
def evaluate(words,labels_pred, labels):
"""
labels_pred, labels, words: are sent-level list
eg: words --> [[i love shanghai],[i love u],[i do not know]]
words,pred, right: is a sequence, is label index or word index.
Evaluates performance on test set
"""
# true_tags = ['PER', 'LOC', 'ORG', 'PERSON', 'person', ... | d1c98e5c7cbe94fdc5bd502e6ea33673cead1a7d | 3,636,407 |
import string
def getApproximateArialStringWidth(st: str) -> float:
"""Calculate rough width of a word in a variable width font.
By https://stackoverflow.com/users/234270/speedplane
Args:
st (str): The string you need a width for
Returns:
float: The rough width in picas
To make ... | d37cc49e4ffd347ddace5de1d420bc8c3c37b615 | 3,636,408 |
def prepare_text(input_string):
"""Converts an input string into a list containing strings.
Parameters
----------
input_string : string
String to convert to a list of string.
Returns
-------
out_list : list
List containing the input string.
"""
# ... | ddf060728127380ef3ec689f7ee8104b9c12ebea | 3,636,409 |
def TDF_Tool_TagList(*args):
"""
* Returns the entry of <aLabel> as list of integers in <aTagList>.
:param aLabel:
:type aLabel: TDF_Label &
:param aTagList:
:type aTagList: TColStd_ListOfInteger &
:rtype: void
* Returns the entry expressed by <anEntry> as list of integers in <aTagList>.... | 92cc1ffb20dad5bd0d49c818cae899fdbc9fafc0 | 3,636,410 |
import re
def img(header, body=None):
"""Alternate to Markdown's image tag. See
http://octopress.org/docs/plugins/image-tag/ for usage."""
attrs = re.match(__img_re, header).groupdict()
m = re.match(__img_re_title, attrs['title'])
if m:
attrs['title'] = m.groupdict()['title']
att... | 8745d00f576bb24d94dbeff465be9f2d82388034 | 3,636,411 |
def conexao_bd():
"""
Função que se conecta a um banco de dados MySQL
"""
# Pedido de senha caso o acesso ao BD necessite
# caso contrario so dar ENTER
conexao = sql.connect(
host='localhost',
user='root',
password=senha
)
cursor = conexao.cursor()
return c... | 2db6a7aaef02639d506c4ec393851abc3c9f278d | 3,636,412 |
def fill_bin_content(ax, sens, energy_bin, gb, tb):
"""
Parameters
--------
Returns
--------
"""
for i in range(0,gb):
for j in range(0,tb):
theta2 = 0.005+0.005/2+((0.05-0.005)/tb)*j
gammaness = 0.1/2+(1/gb)*i
text = ax.text(theta2, gammaness, "... | aa2121697429d330da3ec18f08f36248e3f57152 | 3,636,413 |
def blackbody1d(temperature, radius, distance=10*u.pc,
lambda_min=2000, lambda_max=10000, dlambda=1):
"""
One dimensional blackbody spectrum.
Parameters
----------
temperature : float or `~astropy.units.Quantity`
Blackbody temperature.
If not a Quantity, it is assume... | 80bef199c3a11d19f60204913cb44dbf6f40b47f | 3,636,414 |
def expm1_op_tensor(x):
"""
See :func:`oneflow.expm1`
"""
return Expm1()(x) | dc844e014a806ae507052618eccd889a9a0b589d | 3,636,415 |
import os
def get_unique_filepath(stem):
"""NOT thread-safe!
return stems or stem# where # is the smallest
positive integer for which the path does not exist.
useful for temp dirs where the client code wants an
obvious ordering.
"""
fp = stem
if os.path.exists(stem):
n = 1
... | 29f853bcb1df4bd2b989948ad2b7b8985bff83e9 | 3,636,416 |
from onnxruntime import __version__ as onnxruntime_version
import os
def optimize_model(input,
model_type='bert',
num_heads=0,
hidden_size=0,
optimization_options=None,
opt_level=None,
use_gpu=False,
... | 71a2780da98aedda2072fabb5a38cf7999968c53 | 3,636,417 |
def transect_rotate(adcp_transect,rotation,xy_line=None):
"""
Calculates all possible distances between a list of ADCPData objects (twice...ineffcient)
Inputs:
adcp_obs = list ADCPData objects, shape [n]
Returns:
centers = list of centorids of ensemble locations of input ADCPData object... | bc493c8cf93cbfdbe614ed39f973ee735fbe3294 | 3,636,418 |
def F(x, t, *args, **kwds):
"""
F(x) = ddx
"""
return -kwds.get('μ', 1) * x / np.sum(x**2)**(3/2) | bbe4afa78dab5aafa27c26a09f31fa8bcc37d989 | 3,636,419 |
from typing import List
from typing import Dict
def get_capacity_potential_per_country(countries: List[str], is_onshore: float, filters: Dict,
power_density: float, processes: int = None):
"""
Return capacity potentials (GW) in a series of countries.
Parameters
... | f68285a349c147c773d8053afa377e674b0e585a | 3,636,420 |
import ast
from typing import Set
def all_statements(tree: ast.AST) -> Set[ast.stmt]:
"""
Return the set of all ast.stmt nodes in a tree.
"""
return {node for node in ast.walk(tree) if isinstance(node, ast.stmt)} | 9f7cc367f01ec3bb90869879e79eb9cbe6636820 | 3,636,421 |
def calc_predicted_points_for_pos(
pos, gw_range, team_model, player_model, season, tag, session
):
"""
Calculate points predictions for all players in a given position and
put into the DB
"""
predictions = {}
df_player = None
if pos != "GK": # don't calculate attacking points for keepe... | da30553d3cfe0bacd4198f3ae949466596d130a5 | 3,636,422 |
def image_preprocess2(img):
"""
image preprocess version 2
using: yellow threshold, white threshold, sobelX, sobelY, ROI
Parameters
----------
img: image (np.array())
Return
----------
the source points
"""
# set white and yellow threshold
... | 8581865049d7c0b9e33936e09bd034d4981f4d57 | 3,636,423 |
from typing import Dict
def get_all_feeds(cb: CbThreatHunterAPI, include_public=True) -> Dict:
"""Retrieve all feeds owned by the caller.
Provide include_public=true parameter to also include public community feeds.
"""
url = f"/threathunter/feedmgr/v2/orgs/{cb.credentials.org_key}/feeds"
params ... | e8cfea478a43919cf8753e0c1c9b8bb3228db736 | 3,636,424 |
from typing import Tuple
import ctypes
def spkltc(
targ: int, et: float, ref: str, abcorr: str, stobs: ndarray
) -> Tuple[ndarray, float, float]:
"""
Return the state (position and velocity) of a target body
relative to an observer, optionally corrected for light time,
expressed relative to an ine... | 46ad18c4fbf0c654771a7e6568831e6551f52e44 | 3,636,425 |
def remove_outlier_from_time_average(df, time=4, multiplier=3):
"""
Remove outliers when averaging transients before performing the fitting routines, used to improve the signal to noise ratio in low biomass systems.
The function sets a time window to average over, using upper and lower limits for outl... | c3c92e25514e02b6baa425672b31c8ec45b4f7fc | 3,636,426 |
import json
def parse_tb_file(path, module):
"""
Parse a translation block coverage file generated by S2E's
``TranslationBlockCoverage`` plugin.
"""
with open(path, 'r') as f:
try:
tb_coverage_data = json.load(f)
except Exception:
logger.warning('Failed to p... | dac9567c0c931ce9921eb5c766d00b3faa305887 | 3,636,427 |
def load(filename):
""" Load nifti2 single or pair from `filename`
Parameters
----------
filename : str
filename of image to be loaded
Returns
-------
img : Nifti2Image or Nifti2Pair
nifti2 single or pair image instance
Raises
------
ImageFileError: if `filenam... | e537f81883b27da4add0a7c16addc3c4f7f66e4b | 3,636,428 |
from sys import path
import pickle
import time
def run_sklearn(args, out_dir, out_flp, ldrs):
"""
Trains an sklearn model according to the supplied parameters. Returns the
test error (lower is better).
"""
# Unpack the dataloaders.
ldr_trn, _, ldr_tst = ldrs
# Construct the model.
prin... | d1d6929eed42c53ac43b15d4f4e7702e57c24738 | 3,636,429 |
def create_softmax_loss(scores, target_values):
"""
:param scores: [batch_size, num_candidates] logit scores
:param target_values: [batch_size, num_candidates] vector of 0/1 target values.
:return: [batch_size] vector of losses (or single number of total loss).
"""
return tf.nn.softmax_cross_en... | a4b10b9f72f0e7e38474c5ec887ed3be215fc7fb | 3,636,430 |
def page_not_found(e):
"""
Catches 404 errors and render a 404 page stylized with the design of the web app.
Returns 404 static page.
"""
return render_template('404.html'), 404 | abf420f299f63a2ab3bccfca578f46be040590fd | 3,636,431 |
def effort_remaining_after_servicing_tier_2_leads():
"""
Real Name: Effort Remaining after Servicing Tier 2 Leads
Original Eqn: MAX(Effort Remaining after Servicing Existing Clients - Effort Devoted to Tier 2 Leads, 0)
Units: Hours/Month
Limits: (None, None)
Type: component
Subs: None
H... | 2ab3ee8968bb6e667bdf53cf4629ad0b1ecd732d | 3,636,432 |
def sliceThreshold(volume, block_size = 5):
"""
convert slice into binary using adaptive local ostu method
volume --- 3D volume
block_size --- int value
"""
if type(volume) != np.ndarray:
raise TypeError('the input must be numpy array!')
x, y, z = volume.shape
... | b66d4a46025ccc9fe6c15e61dcd57e060437f91e | 3,636,433 |
def rastrigin_d_dim(x: chex.Array) -> chex.Array:
"""
D-Dim. Rastrigin function. x_i ∈ [-5.12, 5.12]
f(x*)=0 - Minimum at x*=[0,...,0]
"""
A = 10
return A * x.shape[0] + jnp.sum(x ** 2 - A * jnp.cos(2 * jnp.pi * x)) | a7ac23b0a2b76afceb193629aad265186664c012 | 3,636,434 |
def fMaxConfEV(arr3_EvtM_bol, arr3_Evt, arr3_Conf):
""" Return highest confidence and its corresponding timing, given
arr3_EvtM_bol already masked to year of interest.
Something in this fuction or calling it is broken.
"""
print('\t\tStats (max conf)...', end='')
arr3_ConfM_bolY ... | 84a701fde4243c588de43582b3c7aa6c37dd434c | 3,636,435 |
def regex_validation_recursion(node: dict) -> (bool, str):
"""
Validates the regex inside a singular node of a Spcht Descriptor
:param dict node:
:return: True, msg or False, msg if any one key is wrong
:rtype: (bool, str)
"""
# * mapping settings
if 'map_setting' in node:
if '$... | 53f7e605c7bcd83cacba85e8aa0c5dc25e26d05c | 3,636,436 |
import os
def get_beat_times(audio_file, beats_folder, include_beat_numbers=False):
"""
Read beat times from annotation file.
:param audio_file: path to audio files
:param beats_folder: folder with preanalysed beat times (in .beats.txt format per track)
:return: beat times in seconds
"""
... | a996513c5ec535be0f092a05f2ccd0d433a77296 | 3,636,437 |
def build_probability_matrix(graph):
"""Get square matrix of shape (n, n), where n is number of nodes of the
given `graph`.
Parameters
----------
graph : :class:`~gensim.summarization.graph.Graph`
Given graph.
Returns
-------
numpy.ndarray, shape = [n, n]
Eigenvector of... | 44cf85a02d95df8d2d1a7580714e90cab0f087dc | 3,636,438 |
def yuanshanweir_transfer_loss_amount():
"""
Real Name: YuanShanWeir Transfer Loss Amount
Original Eqn: (Tranfer From YuanShanWeir To DaNanWPP+Transfer From YuanShanWeir To BanXinWPP)/(1-WPP Transfer Loss Rate)*WPP Transfer Loss Rate
Units: m3
Limits: (None, None)
Type: component
Subs: None
... | d5e028fb4450258f7fbdd708e7948f80eda04d2f | 3,636,439 |
def create_request(request: Request) -> Request:
"""Create a database entry (mongo Document based Request object) from a brewtils
Request model object. Some transformations happen on a copy of the supplied Request
prior to saving it to the database. The returned Request object is derived from this
trans... | fc4ec6033545ad26db1b5ef375b38f79e5879e9a | 3,636,440 |
def _gifti_to_array(gifti):
""" Converts tuple of `gifti` to numpy array
"""
return np.hstack([load_gifti(img).agg_data() for img in gifti]) | 363cf55a7509acf842b1d2dcbfb4ff45980e6692 | 3,636,441 |
from typing import List
from typing import Type
from typing import Union
def learn_naive_factorization(
data: np.ndarray,
distributions: List[Type[Leaf]],
domains: List[Union[list, tuple]],
scope: List[int],
learn_leaf_func: LearnLeafFunc,
**learn_leaf_kwargs
) -> Node:
"""
Learn a lea... | ef79c457d7c3a0630b8b8734bb892d1b1937e6ab | 3,636,442 |
def opt_IA_search_assist(fun, lbounds, ubounds, budget):
"""Efficient implementation of uniform random search between
`lbounds` and `ubounds`
"""
lbounds, ubounds = np.array(lbounds), np.array(ubounds)
dim, x_min, f_min = len(lbounds), None, None
opt_ia = optIA.OptIA(fun, lbounds, ubounds, ssa=... | b8d496ce403ae4882dc5a54947febdf1a7f298b4 | 3,636,443 |
def load_investigation(fp):
"""Used for rules 0005
:param fp: A file-like buffer object pointing to an investigation file
:return: Dictionary of DataFrames for each section
"""
def check_labels(section, labels_expected, df):
"""Checks each section is syntactically structured correctly
... | a53928a2b6e13cb21d9e76db2792fdba349aba98 | 3,636,444 |
def _fi18n(text):
"""Used to fake translations to ensure pygettext retrieves all the strings we want to translate.
Outside of the aforementioned use case, this is exceptionally useless,
since this just returns the given input string without
any modifications made.
"""
return text | e505b58f4ff1e64c07b4496f69bee8b6e86b5129 | 3,636,445 |
def is_required_version(version, specified_version):
"""Check to see if there's a hard requirement for version
number provided in the Pipfile.
"""
# Certain packages may be defined with multiple values.
if isinstance(specified_version, dict):
specified_version = specified_version.get("versio... | 6c8bfe0fe77f7a7d14e1ca2dd8005a8d82d0998c | 3,636,446 |
async def cmd_project_uninstall(ls: TextXLanguageServer, params) -> bool:
"""Command that uninstalls a textX language project.
Args:
params: project name
Returns:
True if textX project is uninstalled successfully, otherwise False
Raises:
None
"""
project_name = params[0... | cc460057b5ecaf0c97bd715fc98020c9cfbe960f | 3,636,447 |
def _check_load_mat(fname, uint16_codec):
"""Check if the mat struct contains 'EEG'."""
read_mat = _import_pymatreader_funcs('EEGLAB I/O')
eeg = read_mat(fname, uint16_codec=uint16_codec)
if 'ALLEEG' in eeg:
raise NotImplementedError(
'Loading an ALLEEG array is not supported. Please... | 384c0034230167ccf66c91aa048a0ef048d2e2bd | 3,636,448 |
def local_desired_velocity(env, veh_ids, fail=False):
"""
Encourage proximity to a desired velocity.
We only observe the velocity of the specified car.
If a collison or failure occurs, we return 0.
"""
vel = np.array(env.k.vehicle.get_speed(veh_ids))
num_vehicles = len(veh_ids)
if any... | 6df0ba2c2bc481ca7364aafc1cb05cfd197cfba2 | 3,636,449 |
def All(q, value):
"""
The All operator selects documents where the value of the field is an list
that contains all the specified elements.
"""
return Condition(q._path, to_refs(value), '$all') | b31db5f1c6cf26b339a5de6656db3318eff0c5f1 | 3,636,450 |
def key(i):
"""
Helper method to generate a meaningful key.
"""
return 'key{}'.format(i) | 04658ebead9581ff97406111c9b85e361ee49ff8 | 3,636,451 |
def svn_repos_fs_change_rev_prop3(*args):
"""
svn_repos_fs_change_rev_prop3(svn_repos_t repos, svn_revnum_t rev, char author, char name,
svn_string_t new_value, svn_boolean_t use_pre_revprop_change_hook,
svn_boolean_t use_post_revprop_change_hook,
svn_repos_authz_func_t authz_read_func,... | 7c49ab3ff13a3b078831a6ad0214849ae8ee5d8b | 3,636,452 |
def pretty_ct(ct):
"""
Pretty-print a contingency table
Parameters
----------
ct :
the contingency table
Returns
-------
pretty_table :
a fancier string representation of the table
"""
output = StringIO()
rich_ct(ct).to_csv(output)
output.seek(0)
try... | 547e3d36bb91f2ab2c53783099da04ef3bda1497 | 3,636,453 |
def mark(symbol):
"""Wrap the symbol's result in a tuple where the first element is `symbol`.
Used where the information about "which branch of the grammar was used"
must be propagated upwards for further checks.
"""
def mark_action(x):
return (symbol, x)
return mark_action << symbol | 3180c96d4d2a68df2909f23a544879918016fb37 | 3,636,454 |
def restore_dimensions(array, from_dims, result_like, result_attrs=None):
"""
Restores a numpy array to a DataArray with similar dimensions to a reference
Data Array. This is meant to be the reverse of get_numpy_array.
Parameters
----------
array : ndarray
The numpy array from which to ... | 401015b3e33f17bb7e5be078270391efb0543bfa | 3,636,455 |
import collections
def _combine_qc_samples(samples):
"""Combine split QC analyses into single samples based on BAM files.
"""
by_bam = collections.defaultdict(list)
for data in [utils.to_single_data(x) for x in samples]:
batch = dd.get_batch(data) or dd.get_sample_name(data)
if not isi... | b9fb88f7fae9c6dda8f2435b8c7fcfab5ab15ad2 | 3,636,456 |
import os
import shutil
def prepare_outdir():
"""
prepares the directory structure on disk,
returns output directory as well as the s3 destination folder
"""
out_dir, s3_dest_folder = file_destination()
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir)
... | c16143441d7c589f589925cad217ecdeb8ba99fc | 3,636,457 |
import re
def doc(
package_name: str,
plugin_name: str,
long_doc: bool = True,
include_details: bool = False,
) -> str:
"""Document one plug-in
Documentation is taken from the module doc-string. If the plug-in is not part of the
package an UnknownPluginError is raised.
Args:
... | a6c3a1c03936262815299657c6264f70be1e92ba | 3,636,458 |
def microsecond(dt):
""":yaql:property microsecond
Returns microseconds of given datetime.
:signature: datetime.microsecond
:returnType: integer
.. code::
yaql> datetime(2006, 11, 21, 16, 30, 2, 123).microsecond
123
"""
return dt.microsecond | 31d195fa4ceb468bb5666751e56b836fbec8f822 | 3,636,459 |
import math
def decompose_label_vector(label_vector, n_xgrids, n_ygrids, mean_lwh,
xlim=(0.0, 70.0), ylim=(-50.0,50.0), zlim=(-10.0,10.0),
conf_thres=0.5, nms=True, iou_thres=0.1):
""" Build the ground-truth label vector
given a set of poses, classe... | 0cf34bad28a5c8dc335110be95ace5e41d8fa534 | 3,636,460 |
def gen_delay_phs(fqs, ants, dly_rng=(-20, 20)):
"""
Produce a set of mock complex phasors corresponding to cables delays.
Args:
fqs (array-like): shape=(NFREQS,), GHz
the spectral frequencies of the bandpasses
ants (iterable):
the indices/names of the antennas
... | 3e9d2b6bab886c8d6b7b3ef5869d74cf21689e06 | 3,636,461 |
def sharpen(img, bg=None, t='laplace', blur_radius=30, blur_guided_eps=1e-8,
use_guidedfilter='if_large_img'):
"""Use distortion model to deblur image. Equivalent to usharp mask:
1/t * img - (1-1/t) * blurry(img)
Then, apply guided filter to smooth result but preserve edges.
img - im... | fd6b3a5e3464cf1948d2dc9de94b1924f484a3e8 | 3,636,462 |
def what_to_add(qtype, origword, newword, terminate):
"""Return a qtype that is needed to finish a partial word.
For example, given an origword of '\"frog' and a newword of '\"frogston',
returns either:
terminate=False: 'ston'
terminate=True: 'ston\"'
This is useful when calculating tab... | c5b06aa1db322e0f6c6d041562ea3585482d789b | 3,636,463 |
def intersect(start1, end1, start2, end2):
"""Return the intersection point of two lines, else return None.
Ideas:
For parallel lines to intercept (equal slope and y-intercept),
they must be overlapping segments of the same infinite line.
Intersection point is given by solving line equation 1 = line... | cd5affbdc57d48783cf50f188b979ad24f117c37 | 3,636,464 |
def start(update, context):
"""Displays welcome message."""
# choose_lang = True
# If we're starting over we don't need do send a new message
if not context.user_data.get(START_OVER):
user = update.message.from_user
try:
context.user_data[LANG] = user.language_code
... | cbb8e0f49f35de1dbd0f47e71b114b2c22ed5ec0 | 3,636,465 |
def model_dir_str(model_dir, hidden_units, logits, processor=lambda: pc.IdentityProcessor(),
activation=tf.nn.relu, uuid=None):
"""Returns a string for the model directory describing the network.
Note that it only stores the information that describes the layout of the network - in partic... | 00ee6a98dfc1f614f335a187f3f998edc908e25d | 3,636,466 |
def validate_search_inputs(row_id, search_column, search_value):
"""Function that determines if row_id, search_column and search_value are defined correctly"""
return_value = {
"valid": True,
"msg": None
}
a_search_var_defined = True if search_column or search_value else False
if r... | ce85ce1b973beab6b0476dfc05edc594fac8c420 | 3,636,467 |
def B1(i,n,t):
"""Restituisce il polinomio di Bernstein (i,n) valutato in t,
usando la definizione binomiale"""
if i < 0 or i > n:
return 0
return binom(n,i)* t**i * (1-t)**(n-i) | ac97d943494e3b194d71de9ae1864633268499ec | 3,636,468 |
def get_text_between(text, before_text, after_text):
"""Return the substring of text between before_text and after_text."""
pos1 = text.find(before_text)
if pos1 != -1:
pos1 += len(before_text)
pos2 = text.find(after_text, pos1)
if pos2 != -1:
return text[pos1:pos2].strip... | 4ec7f1900881422599b05f64b1c8eec8c992452d | 3,636,469 |
import os
def avi_common_argument_spec():
"""
Returns common arguments for all Avi modules
:return: dict
"""
credentials_spec = dict(
controller=dict(default=os.environ.get('AVI_CONTROLLER', '')),
username=dict(default=os.environ.get('AVI_USERNAME', '')),
password=dict(defa... | dfac1913e3b5af435ce8e9e8b53bf2d0d00aad11 | 3,636,470 |
def _get_functional_form_section(input_string):
""" grabs the section of text containing all of the job keywords
for functional form of PIPs
"""
pattern = (escape('$functional_form') + LINE_FILL + NEWLINE +
capturing(one_or_more(WILDCARD, greedy=False)) +
escape('$end')... | d4f2061f355c6a09ec564b0d60b0cf6b82d022b8 | 3,636,471 |
def rfftn(a, s=None, axes=None):
"""Multi-dimensional discrete Fourier transform for real input.
Compute the multi-dimensional discrete Fourier transform for real input.
This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.rfftn`,
with an interface similar to that of :func:`numpy.fft.rfftn... | 9df68b5655d624d6f095b8a33ce31bc706c7ac7a | 3,636,472 |
from pathlib import Path
import pathlib
import requests
import asyncio
async def ChannelLogoAPI(
channel_id:str = Path(..., description='チャンネル ID 。ex:gr011'),
):
"""
チャンネルのロゴを取得する。
"""
# チャンネル情報を取得
channel = await Channels.filter(channel_id=channel_id).get_or_none()
# 指定されたチャンネル ID が存在しな... | ab0e149141cd678b7890927b5b9e50bb9c34a91e | 3,636,473 |
import pathlib
def ImportFromNpb(
db: bytecode_database.Database, cmake_build_root: pathlib.Path
) -> int:
"""Import the cmake files from the given build root."""
bytecodes_to_process = FindBitcodesToImport(cmake_build_root)
i = 0
with sqlutil.BufferedDatabaseWriter(db, max_buffer_length=10) as writer:
... | 3f8635fe64c7bfcd306e847334badcc5a2c5b2e0 | 3,636,474 |
def _partial_ema_scov_init(n_dim=None, r:float=0.025, n_emp=None, target:float=None)->dict:
""" Initialize object to track partial moments
r: Importance of current data point
n_emp: Discouraged. Really only used for tests.
This is the number of samples for which empirical is u... | 5c73db5f3758781a7a47cc72ad85784ada6e57fa | 3,636,475 |
def inner(thing):
""" one level """
if isinstance(thing, DataPackage):
return thing,
else:
return list(thing) | 17eb8b2a272144b4a1732d8f6ce1f40c18f79b8a | 3,636,476 |
def load_dataset(data_name):
"""Load dataset.
Args:
data_name (str): The name of dataset.
Returns:
dataset (pgl.dataset): Return the corresponding dataset, containing graph information, feature, etc.
data_mode (str): Currently we have 's' and 'm' mode, which mean small dataset a... | f99dcc9d64085ef545658d34deb4936f37305f11 | 3,636,477 |
def require_dataset(hdf5_data, path, shape, dtype, maxshape=(None)):
"""
Create or update a dataset, making sure that its shape is resized
if needed
Args:
hdf5_data: object, an already opened hdf5 file
path: string, the path to the dataset
shape: tuple of integers, the shape of t... | dc9b3b4db56854cc2c770875a754474bbc5f56a3 | 3,636,478 |
def findquote(lrrbot, conn, event, respond_to, query):
"""
Command: !findquote QUERY
Section: quotes
Search for a quote in the quote database.
"""
quotes = lrrbot.metadata.tables["quotes"]
with lrrbot.engine.begin() as pg_conn:
fts_column = sqlalchemy.func.to_tsvector('english', quotes.c.quote)
query = sql... | 1d61f7c416d51d6c362b212b0217d1717ef79aa4 | 3,636,479 |
import re
def find_first_in_register_stop(seq):
"""
Find first stop codon on lowercase seq that starts at an index
that is divisible by three
"""
# Compile regexes for stop codons
regex_stop = re.compile('(taa|tag|tga)')
# Stop codon iterator
stop_iterator = regex_stop.finditer(seq)
... | 56741828c42ecf0cb96044d03c8d1b6bc4994e01 | 3,636,480 |
from scipy import integrate as scint
import os
def computeScaling( filt1, filt2, camera1=None, camera2=None ) :
"""determine the flux scaling factor that should be multiplied to
filt1 to match the throughput of filt2. This returns just a
single number, effectively assuming the source SED is flat across
... | 4ac04ff6e2013b0898e7414c743d72e7e0e6afba | 3,636,481 |
def greet_person(person: Person) -> str:
"""Return a greeting message for the given person.
The message should have the form 'Hello, <given_name> <family_name>!'
>>> david = Person('David', 'Liu', 110, '110 St. George Street')
>>> greet_person(david)
'Hello, David Liu!'
"""
return f'Hello,... | 3050e78295dfeee2d80c4d17fa7acc4bbfcb4d41 | 3,636,482 |
def sw(s1, s2, pen, matrix):
"""
Takes as input two sequences, gap penalty, BLOSUM or PAM dictionary
and returns the scoring matrix(F) and traceback matrix(P)
"""
N = len(s1) + 1
M = len(s2) + 1
F = [] #initialize scoring matrix(F) and traceback matrix(P)
P = []
F = [[... | c466997476259c4f2736ae0dec892f5f8e5f20e7 | 3,636,483 |
from datetime import datetime
from sys import path
import re
import os
def open_data(num=None, folder=None, groupname="main", datasetname="data", date=None):
"""Convenience Load data from an `AuspexDataContainer` given a file number and folder.
Assumes that files are named with the convention `ExperimentN... | 1c70d9c8b81a7ca40e0ee5e691a0f811cfb02d33 | 3,636,484 |
def random_multiplex_ER(n,l,p,directed=False):
""" random multilayer ER """
if directed:
G = nx.MultiDiGraph()
else:
G = nx.MultiGraph()
for lx in range(l):
network = nx.fast_gnp_random_graph(n, p, seed=None, directed=directed)
for edge in network.edges(... | 9a70997fb3de5db225b0282a3b217eb4e33f0a8c | 3,636,485 |
def compare_structures(structure_a, structure_b):
"""Compare two StructureData objects A, B and return a delta (A - B) of the relevant properties."""
delta = AttributeDict()
delta.absolute = AttributeDict()
delta.relative = AttributeDict()
volume_a = structure_a.get_cell_volume()
volume_b = str... | 93a7b2a5d28abe844b9daabce840afe275ed851e | 3,636,486 |
from typing import Callable
def parse_response(expected: str) -> Callable:
"""
Decorator for a function that returns a requests.Response object.
This decorator parses that response depending on the value of <expected>.
If the response indicates the request failed (status >= 400) a dictionary
cont... | 2d50fb98553e1803ef86056a0455a864c17bb065 | 3,636,487 |
def find_parents(candidate, branches):
"""Find parents genre of a given genre, ordered from the closest to
the further parent.
"""
for branch in branches:
try:
idx = branch.index(candidate.lower())
return list(reversed(branch[:idx + 1]))
except ValueError:
... | 17934d9ee1d3098cc3d08f38d9e3c387df6b7c19 | 3,636,488 |
import torch
def swig_ptr_from_FloatTensor(x):
""" gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
assert x.is_contiguous()
assert x.dtype == torch.float32
return faiss.cast_integer_to_float_ptr(
x.storage().data_ptr() + x.storage_offset() * 4) | d1cdf905fcd45053e9cf42306a68408fa68d1ddf | 3,636,489 |
def generate_reference_user_status(user,references):
"""Generate reference user status instances for a given set of references.
WARNING: the new instances are not saved in the database!
"""
new_ref_status = []
for ref in references:
source_query = ref.sources.filter(userprofile=user.userprofile)\
... | a0d859d06ee4f4a8f47aaad4e6814ae232e6d751 | 3,636,490 |
def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2):
"""Read a file by chrom name into a bitset"""
bitset = BinnedBitSet( MAX )
for line in f:
if line.startswith("#"): continue
fields = line.split()
if fields[chrom_col] == chrom:
start, end = int( ... | 4e45b58d56f0dcb290995814666db36fa0fca0c7 | 3,636,491 |
def timeperiod_contains(
timeperiod: spec.Timeperiod,
other_timeperiod: spec.Timeperiod,
) -> bool:
"""return bool of whether timeperiod contains other timeperiod"""
start, end = timeperiod_crud.compute_timeperiod_start_end(timeperiod)
other_start, other_end = timeperiod_crud.compute_timeperiod_star... | 62c0f48b30e550a6c223aa46f0e63bf7baac9f4d | 3,636,492 |
import copy
def asdict(obj, dict_factory=dict, filter_field_type=None):
"""
Version of dataclasses.asdict that can use field type infomation.
"""
if _is_dataclass_instance(obj):
result = []
for f in fields(obj):
if filter_field_type is None:
continue
... | 2f5f60bbe7cef89cd13dbde1ffc1c3e11f8e2152 | 3,636,493 |
def process_pdb_file(pdb_file, atom_info_only=False):
"""
Reads pdb_file data and returns in a dictionary format
:param pdb_file: str, the location of the file to be read
:param atom_info_only: boolean, whether to read the atom coordinates only or all atom data
:return: pdb_data, dict organizing pdb... | c3328ec0123d49e2776aee84a1fdce56fb9dc84c | 3,636,494 |
def get_insns(*, cls=None, variant: Variant = RV32I):
"""
Get all Instructions. This is based on all known subclasses of `cls`. If non
is given, all Instructions are returned. Only such instructions are returned
that can be generated, i.e., that have a mnemonic, opcode, etc. So other
classes in the ... | 8f0947ebd5750e19f557959f9ccbe6c9e0ee944e | 3,636,495 |
def _assert_all_equal_and_return(tensors, name=None):
"""Asserts that all tensors are equal and returns the first one."""
with backend.name_scope(name or 'assert_all_equal'):
if len(tensors) == 1:
return tensors[0]
assert_equal_ops = []
for t in tensors[1:]:
assert_equal_ops.append(check_ops... | 2c3043aceebd3bf44a0c2aecb4ed188a4a3d6629 | 3,636,496 |
def _get_igraph(G, edge_weights=None, node_weights=None):
"""
Transforms a NetworkX graph into an iGraph graph.
Parameters
----------
G : NetworkX DiGraph or Graph
The graph to be converted.
edge_weights: list or string
weights stored in edges in the original graph to be kept i... | f444eac372d11c289bf157a24e9fccb5583ce500 | 3,636,497 |
def rename(isamAppliance, instance_id, id, new_name, check_mode=False, force=False):
"""
Deleting a file or directory in the administration pages root
:param isamAppliance:
:param instance_id:
:param id:
:param name:
:param check_mode:
:param force:
:return:
"""
dir_id = Non... | a9d645bdbdc4d5804b57fe93625eba558a9c9c14 | 3,636,498 |
def deepset_update_global_fn(feats: jnp.ndarray) -> jnp.ndarray:
"""Global update function for graph net."""
# we want to sum-pool all our encoded nodes
#feats = feats.sum(axis=-1) # sum-pool
net = hk.Sequential(
[hk.Linear(128), jax.nn.elu,
hk.Linear(30), jax.nn.elu,
hk.Linear(11)]) # numbe... | 34fd3038ed56a494d2a09fa829cfe48d583cea49 | 3,636,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.