content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def async_entries_for_config_entry(
registry: DeviceRegistry, config_entry_id: str
) -> List[DeviceEntry]:
"""Return entries that match a config entry."""
return [
device
for device in registry.devices.values()
if config_entry_id in device.config_entries
... | 17af1610631e6b0f407883fa8386082a694f9cd2 | 3,641,789 |
from pathlib import Path
import yaml
def load_material(name: str) -> Material:
"""Load a material from the materials library
Args:
name (str): Name of material
Raises:
FileNotFoundError: If material is not found, raises an error
Returns:
Material: Loaded material
"""
... | aa53eac4889d6c44e78d8f3f6e3b5c2099a7bb53 | 3,641,790 |
def reportBusniessModelSummaryView(request):
""" รายงาน สรุปจำนวนผู้สมัครตามสถานะธุรกิจ ทุกขั้นตอน"""
queryset = SmeCompetition.objects \
.values('enterpise__business_model', 'enterpise__business_model__name') \
.annotate(step_register=Count('enterpise__business_model')) \
.annotate(step... | a0bcb8e0b9d51fc1ed9070857ef9db2c4641ddd6 | 3,641,791 |
def _get_announce_url(rjcode: str) -> str:
"""Get DLsite announce URL corresponding to an RJ code."""
return _ANNOUNCE_URL.format(rjcode) | 997b82270fcb115f8510d0ded1e1b6204e835e92 | 3,641,792 |
import torch
def get_r_adv(x, decoder, it=1, xi=1e-1, eps=10.0):
"""
Virtual Adversarial Training
https://arxiv.org/abs/1704.03976
"""
x_detached = x.detach()
with torch.no_grad():
pred = F.softmax(decoder(x_detached), dim=1)
d = torch.rand(x.shape).sub(0.5).to(x.device)
d = _... | 7613e59d88117a8ed263aad76139b1e4d808582c | 3,641,793 |
def get_factors(shoppers, n_components=4, random_state=903, **kwargs):
"""
Find Factors to represent the shopper-level features in compressed space.
These factors will be used to map simplified user input from application
to the full feature space used in modeling.
Args:
shoppers (pd.DataFr... | 966ca305b87b836d9caa5c857608bc6b16120e26 | 3,641,795 |
def cols_to_array(*cols, remove_na: bool = True) -> Column:
"""
Create a column of ArrayType() from user-supplied column list.
Args:
cols: columns to convert into array.
remove_na (optional): Remove nulls from array. Defaults to True.
Returns:
Column of ArrayType()
"""
... | a33e9b907d95fc767c2f247e12c22bdac9ad7585 | 3,641,796 |
def _git_repo_status(repo):
"""Get current git repo status.
:param repo: Path to directory containing a git repo
:type repo: :class:`pathlib.Path()`
:return: Repo status
:rtype: dict
"""
repo_status = {
'path': repo
}
options = ['git', '-C', str(repo), 'status', '-s']
... | c35a20b7350dcf20bedcd9b201fd04a46c83449b | 3,641,797 |
def _parseList(s):
"""Validation function. Parse a comma-separated list of strings."""
return [item.strip() for item in s.split(",")] | 5bf9ac50a44a18cc4798ed616532130890803bac | 3,641,798 |
def true_segments_1d(segments,
mode=SegmentsMode.CENTERS,
max_gap=0,
min_length=0,
name=None):
"""Labels contiguous True runs in segments.
Args:
segments: 1D boolean tensor.
mode: The SegmentsMode. Returns the start of each... | 801541b7c3343fd59f79a3f3696c3cb17ab41c31 | 3,641,799 |
def get_user_language_keyboard(user):
"""Get user language picker keyboard."""
buttons = []
# Compile the possible options for user sorting
for language in supported_languages:
button = InlineKeyboardButton(
language,
callback_data=f'{CallbackType.user_change_language.val... | b297f5f796f84d5a89849017d29f4a841e3fa2f3 | 3,641,800 |
def splitDataSet(dataSet, index, value):
"""
划分数据集,取出index对应的值为value的数据
dataSet: 待划分的数据集
index: 划分数据集的特征
value: 需要返回的特征的值
"""
retDataSet = []
for featVec in dataSet:
if featVec[index] == value:
reducedFeatVec = featVec[:index]
reducedFeatVec.extend(fe... | 814a54fe13d832e69d8df32af52d882d4a15c4ba | 3,641,801 |
def spam(a, b, c):
"""The spam function Returns a * b + c"""
return a * b + c | 356a2bc2c108bc7458bfd67608695412f045035f | 3,641,802 |
def in_skill_product_response(handler_input):
"""Get the In-skill product response from monetization service."""
""" # type: (HandlerInput) -> Union[InSkillProductsResponse, Error] """
locale = handler_input.request_envelope.request.locale
ms = handler_input.service_client_factory.get_monetization_servi... | 9452ac1498ff0e6601df9fc419df0cfdd6b9171e | 3,641,803 |
import typing
def ipaddr(
value: typing.Union[str, int],
query: typing.Optional[str] = None,
) -> str:
"""Filter IP addresses and networks.
.. versionadded:: 1.1
Implements Ansible `ipaddr filter
<https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters_ipaddr.html>`_.
"""
... | c0830db91a2ba6ffbb8ec8eab4da90136283110e | 3,641,804 |
def npoints_between(lon1, lat1, depth1, lon2, lat2, depth2, npoints):
"""
Find a list of specified number of points between two given ones that are
equally spaced along the great circle arc connecting given points.
:param float lon1, lat1, depth1:
Coordinates of a point to start from. The first... | bd4032f655d6f296f372a89848e7b7ffa431e4ee | 3,641,805 |
def maxPoolLayer(x, kHeight, kWidth, strideX, strideY, name, padding = "SAME"):
"""max-pooling"""
return tf.nn.max_pool(x, ksize = [1, kHeight, kWidth, 1],
strides = [1, strideX, strideY, 1], padding = padding, name = name) | 6fd68582db359a2c113925f0aef5d7b5a79e8fe4 | 3,641,806 |
import torch
def coo2st(coo):
"""
transform matrix in sparse coo_matrix to sparse tensor of torch
INPUT
coo - matrix in sparse coo_matrix format
OUTPUT
coo matrix in torch.sparse.tensor
"""
values = coo.data
indices = np.vstack((coo.row, coo.col))
i = torch.LongTensor(indice... | 4b516f8df8829873c6160fdb8e35403f914ebc8b | 3,641,807 |
def make_dataset(data, nafc):
"""Create a PsiData object from column based input.
Parameters
----------
data : sequence on length 3 sequences
Psychometric data in colum based input,
e.g.[[1, 1, 5], [2, 3, 5] [3, 5, 5]].
nafc : int
Number of alternative choices in forced choi... | cdf88db4c04373aae6a4655aeba9b2fa53f9b394 | 3,641,809 |
def TorchFFTConv2d(a, K):
"""
FFT tensor convolution of image a with kernel K
Args:
a (torch.Tensor): 1-channel Image as tensor with at least 2 dimensions.
Dimensions -2 & -1 are spatial dimensions and all other
dimensions are assumed ... | fefdfbb19d8d4cb5d785f80e8197cf19e05c3cb6 | 3,641,810 |
def pad(obj, pad_length):
"""
Return a copy of the object with piano-roll padded with zeros at the end
along the time axis.
Parameters
----------
pad_length : int
The length to pad along the time axis with zeros.
"""
if not isinstance(obj, Track):
raise TypeError("Suppo... | 9d124a06002941078e648707015b3698a290abe7 | 3,641,811 |
def stat_mtime(stat):
"""Returns the mtime field from the results returned by os.stat()."""
return stat[8] | 1f7fec9a54a97bb63141d63db706b2885913dadb | 3,641,812 |
def from_yaml_dictionary(yaml_gra_dct, one_indexed=True):
""" read the graph from a yaml dictionary
"""
atm_dct = yaml_gra_dct['atoms']
bnd_dct = yaml_gra_dct['bonds']
atm_dct = dict_.transform_values(
atm_dct, lambda x: tuple(map(x.__getitem__, ATM_PROP_NAMES)))
bnd_dct = dict_.transf... | 6d98ba4ff8821cb3072d42a7d672b70e69234fa8 | 3,641,813 |
def classifier_train(
X_train,
y_train,
X_val,
y_val,
clf,
k_fold_no=10,
uo_sample_method=None,
imbalance_ratio=1,
print_results=False,
train_on_all=False,
):
"""Trains a sklearn classifier using k-fold cross-validation. Returns the ROC_AUC score, with other
parameters i... | 1dc33fc2e0c53f4c1e8a079ddb6c305f66888226 | 3,641,814 |
def html_code_envir(envir, envir_spec):
"""
Return html tags that can be used to wrap formatted code
This method was created to enhance modularization of code. See latex_code_envir in latex.py
:param tuple[str, str, str] envir: code blocks arguments e.g. ('py','cod','-h')
:param str envir_spec: opt... | 1efa2f8e1a295a49b03241ac99e4c139c10b5f58 | 3,641,815 |
def calc_very_restricted_wage_distribution(df):
"""Compute per-period mean and std of wages for agents under two choice restrictions."""
return (
df.query("Policy == 'veryrestricted' and Choice == 'a' or Choice == 'b'")
.groupby(["Period"])["Wage"]
.describe()[["mean", "std"]]
) | 3ca8a2f0061e456a3158b4ee8a128a5a7439af3f | 3,641,819 |
from typing import Iterable
def distrib_one_v_max(
adata: anndata,
celltype: str,
ax,
gene_highlight: Iterable[str],
partition_key: str = "CellType",
):
"""
Parameters
----------
adata
The corrected expression data.
celltype
Celltype to be plotted
gene_hi... | af622c3cd7910691fe208420884bf7097b5807a2 | 3,641,821 |
def create_angler(request, report_a_tag=False):
"""This view is used to create a new tag reporter / angler.
when we create a new angler, we do not want to duplicate entries
with the same first name and last name by default. If there
already angers with the same first and last name, add them to the
... | 8493f7d1f0bdc34ed16a7ca9270364bde2611d1a | 3,641,822 |
def peak_1d_binary_search_iter(nums):
"""Find peak by iterative binary search algorithm.
Time complexity: O(logn).
Space complexity: O(1).
"""
left, right = 0, len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] < nums[mid + 1]:
# If mid... | 320ce5ae1c0dd1756a609639b3daaa6598a194b5 | 3,641,823 |
def add_site_users_sheet(ws, cols, lnth):
"""
"""
for col in cols:
cell = "{}1".format(col)
ws[cell] = "='Total_Sites_MNO'!{}".format(cell)
for col in cols[:2]:
for i in range(2, lnth):
cell = "{}{}".format(col, i)
ws[cell] = "='Total_Sites_MNO'!... | decd1b0c65c6962371826258d3b981483115e790 | 3,641,824 |
def process(document, rtype=None, api=None):
""" Extracts named entities in specified format from given texterra-annotated text."""
entities = []
if annotationName in document['annotations']:
if rtype == 'entity':
for token in document['annotations'][annotationName]:
ent... | b554f9c4166d7386d11a33b735033eb13de5bc89 | 3,641,825 |
def get_out_hmm_path(new_afa_path):
"""Define an hmm file path for a given aligned fasta file path.
"""
new_exten = None
old_exten = new_afa_path.rsplit('.', 1)[1]
if old_exten == 'afaa':
new_exten = 'hmm'
elif old_exten == 'afna':
new_exten = 'nhmm'
# Check that it worked.
... | 08a56612588cf756720c14f80d186cc815283b07 | 3,641,826 |
import copy
def transformer_decoder_block(name,
n_layers,
x,
x_mask,
output_size,
init,
**kwargs):
"""A transformation block composed of... | 74203fa3282392e1c5a579ac242c857d7619c786 | 3,641,827 |
from typing import Union
def compute_rolling_norm(
signal: Union[pd.DataFrame, pd.Series],
tau: float,
min_periods: int = 0,
min_depth: int = 1,
max_depth: int = 1,
p_moment: float = 2,
) -> Union[pd.DataFrame, pd.Series]:
"""
Implement smooth moving average norm (when p_moment >= 1).
... | ef6eabe3c63c22896ea17308fc54e11e734487f3 | 3,641,828 |
def msort(liste, indice):
"""
This function sorts a vector regarding values of the indice 'indice'
Indice start from 0
"""
tmp = [[tbl[indice]]+[tbl] for tbl in liste]
tmp.sort()
liste = [cl[1] for cl in tmp]
del tmp
return liste | 7f4caff9a74f4d118877e335513e68ecd54986d8 | 3,641,829 |
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs):
"""
Forward pass: prepare inputs and run the net forward.
Take
blobs: list of blobs to return in addition to output blobs.
kwargs: Keys are input blob names and values are blob ndarrays.
For formatting inputs for Caffe,... | 790baa0fc8529e3cad45bd8236060bad591ab4a4 | 3,641,830 |
def mre(actual: np.ndarray, predicted: np.ndarray, benchmark: np.ndarray = None):
""" Mean Relative Error """
# return np.mean( np.abs(_error(actual, predicted)) / (actual + EPSILON))
return np.mean(_relative_error(actual, predicted, benchmark)) | c293bf49968feaa01823ea29a7e39a150338c06d | 3,641,832 |
def _get_fusion_kernel(patch_size, fusion='gaussian', margin=0):
"""
Return a 3D kernel with the same size as a patch
that will be used to assign weights to each voxel of a patch
during the patch-based predictions aggregation.
:param patch_size: int or tuple; size of the patch
:param fusion: str... | d57ddb880d31bc726d6a01e37867b91fa8acbbe5 | 3,641,833 |
def transforma(
vetor: list, matriz_linha: bool = True, T: callable = lambda x: transposta(x)
) -> list:
"""Transforma um vetor em uma matriz linha ou matriz coluna."""
matriz = []
if matriz_linha:
matriz.append(vetor)
else:
matriz.append(vetor)
matriz = T(matriz)
return ... | 7aefed2cda94767b9713c7ee71b9fc79f8065b04 | 3,641,834 |
import json
def post(event, context):
"""
:param event: AWS Log Event.
:param context: Object to determine runtime info of the Lambda function.
See http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html for more info
on context.
Process an AWS Log event and post it to a Slack ... | a379c5801bb03d096660070194684a119b0243dd | 3,641,835 |
def process_docstrings(docstrings):
"""Process the docstrings into a proper structure"""
docs = {}
# First we'll find all of the modules and prepare the docs structure
for chunk in docstrings:
if chunk[2].startswith("==="):
# This is a module definition
modulename = chun... | 7f3179b06ba702a039ccf4e7f29a03ae20696cfe | 3,641,836 |
def create_deck(request: HttpRequest):
""" Форма для кода колоды + ее отображение """
deck, deckstring_form, deck_save_form = None, None, None
title = _('Hearthstone | Decoding the deck code')
if request.method == 'POST':
if 'deckstring' in request.POST: # код колоды отправлен с формы D... | 2268867d85c4a2e440e1e8a4dde9e931d924c069 | 3,641,837 |
def read_completed_flag(uarm, flag_type):
"""
Read Complete Flag from EEPROM
:param uarm: uArm instance
:param flag_type: protocol.CALIBRATION_FLAG, protocol.CALIBRATION_LINEAR_FLAG, procotol.CALIBRATION_SERVO_FLAG
:return:
"""
if flag_type == CALIBRATION_FLAG:
if uarm.get_rom_data(C... | 90bb0410b078a8b320697121854fbb163c962a12 | 3,641,838 |
def zpves(output_string):
""" Reads the zero-point energies for each of the
hindered rotors from MESS output file string.
:param output_string: string of lines of MESS output file
:type output_string: str
:return zpves: zero-point energy for each of the rotors
:rtype: list(f... | 16d43d7bc78573074b1d0f414957a31ed162bea6 | 3,641,839 |
from typing import Any
from typing import Optional
from typing import Callable
def _get_cast_type(field_type: type, value: Any) -> Optional[Callable]:
"""Get a casting callable for a field type/value."""
if type(value) is dict:
return _get_cast_type_for_dict(field_type)
if type(value) is str:
... | 05e57bb93c154d77433db596c3659a190d7acd7a | 3,641,840 |
import re
def read_data(filepath , strict_lang='en'):
"""Read data in csv format in order to preprocess.
Args:
filepath (str): a filepath to a csv file with twitter data.
strict_lang (str, optional): whether to select only tweets with explicit language metadata.Defaults to 'en'.
... | 93cfd820b42d3e2030d869f5317ff71491dc98d7 | 3,641,841 |
async def absent(hub, ctx, name, resource_group, connection_auth=None, **kwargs):
"""
.. versionadded:: 4.0.0
Ensure the specified disk does not exist in a resource group.
:param name: The name of the disk.
:param resource_group: The name of the resource group containing the disk.
:param con... | e71c0e536187556a4aec6746f45442a568a7d4aa | 3,641,842 |
def _update_dicts(name_scope,
model_layer,
input_to_in_layer,
model_name_to_output,
prev_node_name):
"""Updates input_to_in_layer, model_name_to_output, and prev_node_name
based on the model_layer.
Args:
name_scope: a string representing... | dbaee780b0f81caa72cb1ba84a2ec976fc50d180 | 3,641,845 |
def geomance_results(session_key):
"""
Looks in the Redis queue to see if the worker has finished yet.
"""
rv = DelayedResult(session_key)
if rv.return_value is None:
return jsonify(ready=False)
redis.delete(session_key)
result = rv.return_value
return jsonify(ready=True, result... | 2ab92d54a61c50bc10514a31aac6d80ca388db83 | 3,641,846 |
def _return_dataframe_type(dataframe, dataframe_type):
"""
Helper method for returning te dataframe in spark/pandas/numpy/python, depending on user preferences
Args:
:dataframe: the spark dataframe to convert
:dataframe_type: the type to convert to (spark,pandas,numpy,python)
Returns:
... | 665353dc91e389da399eb90926a6114053514e92 | 3,641,847 |
from typing import Tuple
def split_dataset(
raw: pd.DataFrame,
train_ratio: float,
val_ratio: float,
lags: int,
verbose: bool = False
) -> Tuple[np.ndarray]:
"""
Generate and split the prepared dataset for RNN training into training, testing and validation sets.
Args:
raw:
... | d662f45ab3468814e2161f69ff8e253c864bf188 | 3,641,848 |
def create_ranking_model() -> tf.keras.Model:
"""Create ranking model using Functional API."""
context_keras_inputs, example_keras_inputs, mask = create_keras_inputs()
context_features, example_features = preprocess_keras_inputs(
context_keras_inputs, example_keras_inputs, mask)
(flattened_context_featur... | 94a2754b21ce8696262e1dc92e924ae1cdaf08df | 3,641,849 |
def to_count_matrix(pair_counts, vocab_size):
"""
transforms the counts into a sparse matrix
"""
cols = []
rows = []
data = []
for k, v in pair_counts.items():
rows.append(k[0])
cols.append(k[1])
data.append(v)
# setting to float is important, +1 for UNK
# COO... | 639957d8b280a0a84d1a64810e82b5d86deae14d | 3,641,850 |
from typing import List
from typing import Optional
import time
def create_dataset(genres_types: List[str],
sp: spotipy.Spotify,
genius: Genius,
limit: Optional[int] = 50,
how_many_in_genre: Optional[int] = 2_000,
sleep_tim... | 49f887612e9ce69e312bf9d43da3db7764eb3b7d | 3,641,851 |
def get_enum_type_definition(ua_graph: UAGraph, data_type_id: int):
"""Given a UAGraph object and a internal id of an enum type,
the definition of the enumeration will be produced. The form
of the definition may vary based on the enumeration.
Args:
ua_graph (UAGraph): UAGraph where the enum defi... | 7464b99f4140ed8908dcc6b966fad917856edd36 | 3,641,852 |
def create_classification_of_diseases():
"""
:param qtty: number of objects to create
"""
fake = Factory.create()
return ClassificationOfDiseases.objects.create(
code=randint(1, 1000), description=fake.text(),
abbreviated_description=fake.text(max_nb_chars=100),
parent=None... | 7e1cea3f80d9e5559e33ce10c702d3429f6dd31b | 3,641,853 |
def cmpversion(a, b):
"""Compare versions the way chrome does."""
def split_version(v):
"""Get major/minor of version."""
if '.' in v:
return v.split('.', 1)
if '_' in v:
return v.split('_', 1)
return (v, '0')
a_maj, a_min = split_version(a)
b_maj, b_min = split_version(b)
if a_maj... | 226191f2a72d4cb65198ddcb779b130b7a524034 | 3,641,856 |
def get_dict_json(attr_name: str, possible_dict: dict) -> dict:
"""
returns a {key : item}. If the item is a np.ndarray then it is converted to a list
Parameters
----------
attr_name
possible_dict
Returns
-------
"""
if type(possible_dict[0]) == np.ndarray:
output_tail... | 0b883cd4153593036df4ced924ffc09f6f000177 | 3,641,857 |
def eulers_totient_phi(num):
"""
Euler's totient (a.k.a. phi) function, φ(n).
Count the number of positive integers less than or equal
to "n" that are relatively prime (coprimes) to "n".
Coprimes: if the only positive integer that evenly divides
two numbers is 1. This is the same thi... | ccf90dc5f0b3b73eeffff8cb78430f049128eb01 | 3,641,858 |
from datetime import datetime
def create_nav_btn(soup,date,text):
"""
Helper functions for month_calendar, generates a navigation button
for calendar
:param soup: BeautifulSoup parser of document
:param date: Date to create nav button
:param text: Text for button
"""
nav_th = soup.new... | 6f49e5173980a9da01e4d92e2f5adfeb73a4a4d0 | 3,641,859 |
def pad_with_dots(msg, length=PAD_TEXT):
"""Pad text with dots up to given length.
>>> pad_with_dots("Hello world", 20)
'Hello world ........'
>>> pad_with_dots("Exceeding length", 10)
'Exceeding length'
"""
msg_length = len(msg)
if msg_length >= length:
return msg
msg = m... | bfae02036c7773fba47576432f0c1f4f32a797e1 | 3,641,861 |
import itertools
def get_top_10_features(target_params, results, importance_type="weight"):
"""Gets the top 10 features of each XGBoost regressor.
Parameters
----------
target_params: dictionary
Should contain a dict with with params for each target label.
results : dictionary
... | 8735513250411e64ab787427727b32569c352a10 | 3,641,862 |
def index():
"""
Class check list view
"""
new_class_check_form = NewClassCheckForm()
upload_csv_form = UploadCSVForm()
classes = ClassCheck.query.all()
return render_template('index.html',
new_class_check_form=new_class_check_form,
upload_csv_form=upload_csv_form,
cl... | b5475177637e7e887f8505c5db7c81b0b0abc49e | 3,641,863 |
import tempfile
import shutil
def main(args):
"""Main function called when run from command line or as part of pipeline."""
usage = """
Usage: split_by_taxa.py
--genomes-a=FILE file with genome GenBank Project ID and Organism name on each line for taxon A
--genomes-b=FILE file with genome GenBan... | 29f6251f2ebbc5ee7e05bd4a0859b61da74a6266 | 3,641,865 |
def nrmse(y_true, y_pred, MEAN_OF_DATA):
"""
Calculates the normalized root mean square error of y_true and y_pred
where MEAN_OF_DATA is the mean of y_pred.
"""
y_true = y_true.squeeze()
y_pred = y_pred.squeeze()
std = np.sum(np.square(y_true - MEAN_OF_DATA))
errors = np.sum(np.square(y... | 641566ac6ed60543463b107f53d964a4864e4901 | 3,641,867 |
def field_references(
model_tuple,
field,
reference_model_tuple,
reference_field_name=None,
reference_field=None,
):
"""
Return either False or a FieldReference if `field` references provided
context.
False positives can be returned if `reference_field_name` is provided
without ... | 89719c1aa2dc4065f10d952b0b7b42c30e49be72 | 3,641,868 |
def friendlist_embed(friendlist, guild):
"""
:param friendlist: The friendlist of the source guild
:param guild: Soruce guild
:return: Embedded friendlist
"""
embed = Embed()
embed.set_author(
name=guild.name,
icon_url=guild.icon_url
)
friends_field = '\n'.join(
... | 8f32fa75cdfd5d06ae83686e7df6c97587534e8e | 3,641,870 |
def find_contours(img):
"""
Find all contours in the image
"""
_, thresh = cv2.threshold(img,127,255,0)
_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return contours | 90064f0e7e3d5aece0e6dc9fd58a202a52e2bfaa | 3,641,871 |
import numpy
def _split_binline(binline):
"""Internal function to read the line of bin specs
Returns bin width and array of bin lower edges
"""
bin_strings = tabmatch.split(binline.strip())
# Grab the first float from each binspec, we'll return lower edges
# Note that commas must be stripped... | bfc89d5b32dfe19cd90cd90a8c04ae6fd9353419 | 3,641,872 |
import re
def parse_name(content):
"""
Finds the name of the man page.
"""
# Create regular expression
name_regex = re.compile(r"^([\w\.-]*)")
# Get name of manual page
just_name = name_regex.search(content)
name_str = ""
if just_name is not None:
name_str = just_name.... | c3a1f32beb96d39d4490681bf90d54115597ffe5 | 3,641,873 |
def albanian_input_normal(field, text):
"""
Prepare a string from one of the query fields for subsequent
processing: replace common shortcuts with valid Albanian characters.
"""
if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'):
return text
text = text.replace('ё', 'ë')
... | 6bd4e7a1e764feada04ae5e95465fb4d7cbb29fb | 3,641,874 |
import re
def extract_share_id_from_url(public_base_url: str) -> str:
"""
Extracts the Airtable share id from the provided URL.
:param public_base_url: The URL where the share id must be extracted from.
:raises ValueError: If the provided URL doesn't match the publicly shared
Airtable URL.
... | 5aad99b5bf022a2b957f10fcb09793188051340c | 3,641,875 |
def load_data(file_path):
"""
读取地名文件,解析出外文和中文的字符总数(去重后),做成字符和索引映射表。
加工地名数据,首尾增加开始和结束标记。
:param file_path: 文件路径
:return: 字符和索引映射表, 地名列表
"""
df = pd.read_table(file_path)
df.columns = ['source', 'chinese']
# 获取外文和中文字符数组
characters_source = sorted(list(set(df.source.unique().sum()))... | 490712dd2786d45497246f03a3b7d463faea7494 | 3,641,876 |
def verify_portchannel_member(dut, portchannel, members, flag='add', cli_type=""):
"""
This API is used to verify the members of portchannel
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:param dut:
:param portchannel:
:param members:
:param flag:
:return:
... | 826d7df22bec748bd948329327920f302b67761f | 3,641,877 |
def adjust_learning_rate(optimizer, epoch, args):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if args.lr_policy == 'decay':
lr = args.lr * (args.lr_decay ** epoch)
elif args.lr_policy == 'poly':
interval = len([x for x in args.lr_custom_step if epoch >= x])
... | c247c81a90476e737ff54c2a7ca45f5c42dccd38 | 3,641,878 |
def refresh_well_known_oidc(realm):
"""
Refresh Open ID Connect .well-known
:param django_keycloak.models.Realm realm:
:rtype django_keycloak.models.Realm
"""
server_url = realm.server.internal_url or realm.server.url
# While fetching the well_known we should not use the prepared URL
o... | 44861d479c6fbc737cb729c4b857b17bed86be7b | 3,641,879 |
import requests
def get_access_token(jwt_token: str) -> str:
"""
Gets an access token, used for fully-authenticated app actions
"""
installations = requests.get(
"https://api.github.com/app/installations", headers=GH_JWT_HEADER(jwt_token)
)
response = requests.post(
installati... | 63fdcaa237be937924d3e0d4a941ce90bd7e1f1c | 3,641,880 |
def donation_process_subscription_deleted(event):
"""
:param event:
:return:
"""
donation_manager = DonationManager()
data = event['data']
subscription = data['object']
subscription_ended_at = subscription['ended_at']
subscription_canceled_at = subscription['canceled_at']
custom... | 0b6de4695cf5c8eaa8699dc7fb7c3e1fd27c0659 | 3,641,881 |
from pathlib import Path
def get_most_probable_strand(filenames, tolerance, sample_name):
"""Return most propable strand given 3 feature count files (strand of 0,1, and 2)
Return the total counts by strand from featureCount matrix folder, strandness and
probable strand for a single sample (using a tolera... | 72913c171a64d3639398db871a799d0cbf938522 | 3,641,882 |
def listBlogs(username, password, serverURL=None):
"""Get a list of your blogs
Returns: list of dictionaries
[{"blogid": ID_of_this_blog,
"blogName": "name_of_this_blog",
"url": "URL_of_this_blog"}, ...]
Arguments:
- username: your weblog username
- password: yo... | 573bb643bb808bef17d76e92a8ed5c8b12735c65 | 3,641,883 |
def find_lineup_no_optimization(set1, set2):
"""
Find the approximate offset between two GPS data sets without range start optimization.
This algorithm first identifies a primary data set and a secondary one based
on which starts later. The offset is then applied to the secondary data set.
After ma... | 46ae35c2a9c7bf8de22df044acc1fc184c5820a8 | 3,641,884 |
def matching_plots_nn(plots_0, plots_1, K):
"""
:param plots_0:
:param plots_1:
:param K:
:return:
"""
M, N = plots_0.shape[0], plots_1.shape[0]
mapping = {}
cost_mat = np.zeros((M, N), dtype=np.float32)
for i, plot_0 in enumerate(plots_0):
for j, plot_1 in enumerate(plo... | 8d4baff1927591b84757f34b48070966c03a82b3 | 3,641,885 |
def find_file_start(chunks, pos):
"""Find a chunk before the one specified which is not a file block."""
pos = pos - 1
while pos > 0:
if chunks[pos][0] != 0x100 and chunks[pos][0] != 0x102:
# This is not a block
return pos
else:
pos = pos - 1
return pos | b0fb280a847dea3cd589d59863888d1087d4982f | 3,641,886 |
def navigation_children(parser, token):
"""Navigation"""
args = token.contents.split()
kwargs = extract_kwargs(args)
if len(args) < 2:
raise template.TemplateSyntaxError(
_("navigation_children requires object as argument and optionally tree={{tree_name}}")
)
return Navig... | 6057946c15c65f1d1f7887055c7b42f831b887cc | 3,641,887 |
def get_all_ann_index(self):
""" Retrieves all annotation ids """
return list(self.ann_infos.keys()) | 4375c9dbc14bf50575c8a5e42ce0ae8749820dfb | 3,641,888 |
def file_to_list(file_path):
"""
读取文件到lists
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
@author: jhuang
@time:1/22/2018
"""
lists... | a0aba732c121f4380d603f44d3cef5690df24d06 | 3,641,889 |
def reverse_words(str):
"""Reverses the letters in each word of a string."""
words = str.split()
new_words = reverse(words[0])
for word in words[1:]:
new_words += ' ' + reverse(word)
return new_words | 6da77e9f214bdbfb3e20b7fe13d43fb63763a5b6 | 3,641,890 |
def parse_www_authenticate_header(value, on_update=None):
"""Parse an HTTP WWW-Authenticate header into a :class:`WWWAuthenticate`
object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every time a
value on the :class:`WWWA... | 69b5b9e5a1cf591eb761a58d62fc53ca48aefffc | 3,641,891 |
def get_image_feature_column(X: pd.DataFrame) -> str:
""" Get only the image feature column name from X """
X = X.select_dtypes(object)
img_features_col_mask = [X[col].str.startswith("/9j/", na=False).any() for col in X]
# should have just one image feature
assert sum(img_features_col_mask) == 1, "... | 9d178887c0b118c57379e91b7c1b7ed6d8c996ea | 3,641,892 |
def merge_sort(sez):
"""urejamo z zlivanjem, torej nazačetku razdelimo seznam na 2 dela, potem pa jih
zlijemo tako da imenično jemljemo manjše elemente z enega ali drugega seznama.
Nakoncu naredimo nov seznam, ki je urejen"""
n=len(sez)
if n<=1:
return sez
levo = merge_sort(sez[:n//2])
desn... | 024ae3362681f3e4e65cd083c86e3df0d52ea720 | 3,641,894 |
def get_pairs(l, k):
"""
Given a list L of N unique positive integers, returns the count of the total pairs of numbers
whose difference is K. First, each integer is stored into a dictionary along with its frequency.
Then, for each integer I in the input list, the presence of the integer I+K is checked w... | 90fd199c75431c1d20076cea04358b3ca5872810 | 3,641,896 |
import collections
def numba_to_jax(name: str, numba_fn, abstract_eval_fn, batching_fn=None):
"""Create a jittable JAX function for the given Numba function.
Args:
name: The name under which the primitive will be registered.
numba_fn: The function that can be compiled with Numba.
abstract_e... | 9b56fe14c98a47746d51a6debb602e84066133b6 | 3,641,897 |
from ..meta import with_metadata
from typing import Iterable
from re import T
from typing import Any
from typing import Iterator
def zip_metadata(iterable: Iterable[T], keys: Iterable[str], values: Iterable[Any]) -> Iterator[T]:
"""
Adds meta-data to each object in an iterator.
:param iterable: The ob... | 18202ba46f143c76b387cb7fa99db33a8ff34655 | 3,641,898 |
import time
def get_projects_query_flags(project_ids):
"""\
1. Fetch `needs_final` for each Project
2. Fetch groups to exclude for each Project
3. Trim groups to exclude ZSET for each Project
Returns (needs_final, group_ids_to_exclude)
"""
project_ids = set(project_ids)
now = time.ti... | f01ca44282ba211bf7ac1d16f6a5e07b3e905473 | 3,641,899 |
def openTypeNameVersionFallback(info):
"""
Fallback to *versionMajor.versionMinor* in the form 0.000.
"""
versionMajor = getAttrWithFallback(info, "versionMajor")
versionMinor = getAttrWithFallback(info, "versionMinor")
return "%d.%s" % (versionMajor, str(versionMinor).zfill(3)) | 370ab06aedd9909cc1b5d0e7f2211a554695c268 | 3,641,900 |
def get_quoted_text(text):
"""Method used to get quoted text.
If body/title text contains a quote, the first quote is considered as the text.
:param text: The replyable text
:return: The first quote in the text. If no quotes are found, then the entire text is returned
"""
lines = text.split('\n... | 3ac1801edcaf16af45d118918cb548f41d9a08fb | 3,641,901 |
def pad_sequences(sequences, pad_tok):
"""
Args:
sequences: a generator of list or tuple
pad_tok: the char to pad with
Returns:
a list of list where each sublist has same length
"""
max_length = max(map(lambda x: len(x), sequences))
sequence_padded... | 077d80424607864d6e0fa63d3843f80b9c822d1e | 3,641,902 |
def get_username_for_os(os):
"""Return username for a given os."""
usernames = {"alinux2": "ec2-user", "centos7": "centos", "ubuntu1804": "ubuntu", "ubuntu2004": "ubuntu"}
return usernames.get(os) | 579ebfa4e76b6660d28afcc010419f32d74aa98c | 3,641,903 |
import copy
def stats_getter(context, core_plugin, ignore_list=None):
"""Update Octavia statistics for each listener (virtual server)"""
stat_list = []
lb_service_client = core_plugin.nsxlib.load_balancer.service
# Go over all the loadbalancers & services
lb_bindings = nsx_db.get_nsx_lbaas_loadbal... | 65ebac76b6543683103584c18a7c06d2ea453e0a | 3,641,904 |
from typing import List
def track_to_note_string_list(
track: Track,
) -> List[str]:
"""Convert a mingus.containers.Track to a list of note strings"""
final_note_list = []
for element in track.get_notes():
for note in element[-1]:
final_note_list.append(note_to_string(note))
r... | 71b4fab66d18242e67a4ea59998e94341531f77a | 3,641,905 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.