content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def new(key, mode, iv=None):
"""Return a `Cipher` object that can perform ARIA encryption and
decryption.
ARIA is a block cipher designed in 2003 by a large group of South
Korean researchers. In 2004, the Korean Agency for Technology and
Standards selected it as a standard cryptographic technique.
... | 8906d9f5efe36349fc520c8022bf52d888bd37ea | 3,639,832 |
import logging
def keggapi_info(database, verbose=True, force_download=False, return_format = None, return_url = False):
"""KEGG REST API interface for INFO command
Displays information on a given database
for further info read https://www.kegg.jp/kegg/rest/keggapi.html
Parameters
------... | 366e4910d54e725e2f8dc8399e7793604a767449 | 3,639,833 |
def round_to_thirty(str_time):
"""STR_TIME is a time in the format HHMM. This function rounds down to the nearest half hour."""
minutes = int(str_time[2:])
if minutes//30 == 1:
rounded = "30"
else:
rounded = "00"
return str_time[0:2] + rounded | 37e8473dbb6e91fc47a03491c421967db231d4d0 | 3,639,834 |
def remove_uoms(words):
"""
Remove uoms in the form of e.g. 1000m 1543m3
Parameters
----------
words: list of words to process
Returns
-------
A list of words where possible uom have been removed
"""
returnWords=[]
for word in words:
word=word.replace('.', '', 1)
... | cdb2caf274a58b61c57ebe4fba167ec6275ddf6f | 3,639,836 |
from unittest.mock import patch
async def create_wall_connector_entry(
hass: HomeAssistant, side_effect=None
) -> MockConfigEntry:
"""Create a wall connector entry in hass."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: "1.2.3.4"},
options={CONF_SCAN_INTERVAL: 30},
... | 5aa8fdc08b13d7fe26df50312f736e9ec1d4bfdd | 3,639,838 |
def _normalize(data):
"""
Normalizes the data (z-score)
:param data: Data to be normalized
:return: Nomralized data
"""
mean = np.mean(data, axis=0)
sd = np.std(data, axis=0)
# If Std Dev is 0
if not sd:
sd = 1e-7
return (data - mean) / sd | 1fe31f73d9e7fae03997f6caa1a28ebe929e49bd | 3,639,839 |
def chunks(chunkable, n):
""" Yield successive n-sized chunks from l.
"""
chunk_list = []
for i in xrange(0, len(chunkable), n):
chunk_list.append( chunkable[i:i+n])
return chunk_list | d59c6afd85705aa1954d7cc0631e98f2e9e5cdcf | 3,639,841 |
def pass_generate():
"""
Стартовая процедура генератора паролей.
"""
func = generate_pass_block
param = {'min_len': 4, 'max_len': 6}
return f'{func(**param)}-{func(**param)}-{func(**param)}' | e0bb5378c308e0c60568bb2b3701ee90d5bf6a8e | 3,639,842 |
from . import analyzer as anl
def lineSpectrum(pos, image, data, width, scale=1, spacing=3, mode="dual"):
"""
Draw sepectrum bars.
:param pos: (x, y) - position of spectrum bars on image
:param image: PIL.Image - image to draw
:param data: 1D array - sound data
:param width: int - widht of spectrum on ima... | 5ee27565bc83ef275d4882b44b11a3b7cd1407b3 | 3,639,843 |
def _unique_arXiv(record, extra_data):
"""Check if the arXiv ID is unique (does not already exist in Scoap3)"""
arxiv_id = get_first_arxiv(record)
# search through ES to find if it exists already
if arxiv_id:
result = current_search_client.search(
'scoap3-records-record',
... | 6b19a10400da024c5ad87090c87f6099a4018dab | 3,639,844 |
def profile(username):
"""
Профиль пользователя. Возможность изменить логин, пароль.
В перспективе сохранить свои любимые ссылки.
"""
if username != current_user.nickname:
return redirect(url_for('index'))
types = Types.manager.get_by('', dictionary=True)
return render_template('au... | 84bb1304ef5862efdd54ad2402e09d31a8c151a2 | 3,639,845 |
def had_cell_edge(strmfunc, cell="north", edge="north", frac_thresh=0.1,
cos_factor=False, lat_str=LAT_STR, lev_str=LEV_STR):
"""Latitude of poleward edge of either the NH or SH Hadley cell."""
hc_strengths = had_cells_strength(strmfunc, lat_str=lat_str,
l... | b666333bb9b0a54d569df96324dbb55747b33a4c | 3,639,846 |
def make_score_fn(data):
"""Returns a groupwise score fn to build `EstimatorSpec`."""
context_feature_columns, example_feature_columns = data.create_feature_columns()
def _score_fn(context_features, group_features, mode, unused_params,
unused_config):
"""Defines the network to score a group of documents... | 5f95843413ddeb146c080a30b563b74e863cdb07 | 3,639,847 |
def unicode2str(obj):
""" Recursively convert an object and members to str objects
instead of unicode objects, if possible.
This only exists because of the incoming world of unicode_literals.
:param object obj: object to recurse
:return: object with converted values
:rtype:... | 62ef4653fd22b58b463dfce62ff83238f47fb9b5 | 3,639,848 |
def test_elim_cast_same_dtype(tag):
""" test_elim_cast_same_dtype """
fns = FnDict()
cast = P.Cast()
@fns
def fp32_cast_fp32(x, y):
return cast(x, y)
@fns
def after(x, y):
return x
return fns[tag] | 6aa97e39d8bdf4261e212355be85106ee109659f | 3,639,849 |
def getRepository():
""" Determine the SVN repostiory for the cwd """
p = Ptyopen2('svn info')
output, status = p.readlinesAndWait()
for line in output:
if len(line) > 3 and line[0:3] == 'URL':
return line[5:].rstrip()
raise Exception('Could not determine SVN reposi... | 754d2b6a343a4b0283be4ba2846aba80b4d1a95f | 3,639,850 |
import re
def replaceInternalLinks(text):
"""
Replaces internal links of the form:
[[title |...|label]]trail
with title concatenated with trail, when present, e.g. 's' for plural.
See https://www.mediawiki.org/wiki/Help:Links#Internal_links
"""
# call this after removal of external links, ... | 23795baffdaf46883fe08a12861313ed6bc0ee54 | 3,639,851 |
from typing import List
from typing import Any
from typing import Optional
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str:
"""
:param rows: 2D list containing objects that have a single-line representation (via `str`).
All rows must be of the same ... | ecdc9972dfbb05795556a5ba36b6cf4cd55399f8 | 3,639,852 |
def format_value(v):
"""
Formats a value to be included in a string.
@param v a string
@return a string
"""
return ("'{0}'".format(v.replace("'", "\\'"))
if isinstance(v, str) else "{0}".format(v)) | 8b8d5452ecf938b4e9e9956577f1a3f1102e49bc | 3,639,853 |
def worst_solvents(delta_d, delta_p, delta_h, filter_params):
"""Search solvents on the basis of RED (sorted descending) with given Hansen parameters, and with
a formatted string indicating filter parameters. See the function parse_filter_params
for details of filter parameters string."""
results_list... | 91543a738ef86e77336cedf6edd6175794c4bdcb | 3,639,854 |
import textwrap
def log(msg, *args, dialog=False, error=False, **kwargs):
"""
Generate a message to the console and optionally as either a message or
error dialog. The message will be formatted and dedented before being
displayed, and will be prefixed with its origin.
"""
msg = textwrap.dedent... | b204d4205a4fd90b3f0ca7104e3b6dd336b25b46 | 3,639,855 |
def build_frustum_lineset(K, l, t, r, b):
"""Build a open3d.geometry.LineSet to represent a frustum
Args:
pts_A (np.array or torch.tensor): Point set in form (Nx3)
pts_B (np.array or torch.tensor): Point set in form (Nx3)
idxs (list of int): marks correspondence between A[i] and B[id... | 73236b73692b61a7d7c78005f626d0d6b0f2c84e | 3,639,856 |
def postagsget(sent):
"""
sent: Sentence as string
"""
string = ""
ls = pos_tag(list(sent.split()))
for i in ls:
string += i[1] + " "
return string | 077e7261e0a0e296381bcb09578557576fe4c86c | 3,639,858 |
def try_convert_to_list_of_numbers(transform_params):
"""
Args:
transform_params: a dict mapping transform parameter names to values
This function tries to convert each parameter value to a list of numbers.
If that fails, then it tries to convert the value to a number.
For example, if transf... | 14e33630daab0081d39fd533a606a7b561f5b161 | 3,639,859 |
def from_tensorflow(graph):
""" Load tensorflow graph which is a python tensorflow graph object into nnvm graph.
The companion parameters will be handled automatically.
Parameters
----------
graph : GraphDef object
Tensorflow GraphDef
Returns
-------
sym : nnvm.Symbol
... | 9547430c05559eb094dbaf3b1528ec071b1c9b50 | 3,639,860 |
def isequal(q1, q2, tol=100, unitq=False):
"""
Test if quaternions are equal
:param q1: quaternion
:type q1: array_like(4)
:param q2: quaternion
:type q2: array_like(4)
:param unitq: quaternions are unit quaternions
:type unitq: bool
:param tol: tolerance in units of eps
:type t... | 6c903bbb547c9015e949e916d0bccda124bad04c | 3,639,861 |
def MMOE(dnn_feature_columns, num_tasks, task_types, task_names, num_experts=4,
expert_dnn_units=[32,32], gate_dnn_units=[16,16], tower_dnn_units_lists=[[16,8],[16,8]],
l2_reg_embedding=1e-5, l2_reg_dnn=0, seed=1024, dnn_dropout=0, dnn_activation='relu', dnn_use_bn=False):
"""Instantiates the ... | 6be8b400fb58c74d4dc397132327f9ffb819a637 | 3,639,862 |
import numpy
def greater(self, other):
""" Equivalent to the > operator.
"""
return _PropOpB(self, other, numpy.greater, numpy.uint8) | 04d0a6ed3d0023afc3bcea167c67940af9387dc1 | 3,639,863 |
def load_translation_data(dataset, src_lang='en', tgt_lang='vi'):
"""Load translation dataset
Parameters
----------
dataset : str
src_lang : str, default 'en'
tgt_lang : str, default 'vi'
Returns
-------
"""
common_prefix = 'IWSLT2015_{}_{}_{}_{}'.format(src_lang, tgt_lang,
... | f571f8bda3b46dfba7f15f15ac7e46addac6273e | 3,639,864 |
import copy
def objective_function(decision_variables, root_model, mode="by_age", country=Region.UNITED_KINGDOM, config=0,
calibrated_params={}):
"""
:param decision_variables: dictionary containing
- mixing multipliers by age as a list if mode == "by_age" OR
- locati... | 81d2aeacdabeb20e2910e3cf42ece12e112e055b | 3,639,865 |
def kick(code, input):
""" kick <user> [reason] - Kicks a user from the current channel, with a reason if supplied. """
text = input.group(2).split()
if len(text) == 1:
target = input.group(2)
reason = False
else:
target = text[0]
reason = ' '.join(text[1::])
if not ... | 59e8bc095076d9605aaa6b03363894c78d06b730 | 3,639,866 |
def check_invalid(string,*invalids,defaults=True):
"""Checks if input string matches an invalid value"""
# Checks string against inputted invalid values
for v in invalids:
if string == v:
return True
# Checks string against default invalid values, if defaults=True
if defaults ... | 6e9e20beebe8e0b0baed680219fd93453d7f4ce3 | 3,639,867 |
def sse_content(response, handler, **sse_kwargs):
"""
Callback to collect the Server-Sent Events content of a response. Callbacks
passed will receive event data.
:param response:
The response from the SSE request.
:param handler:
The handler for the SSE protocol.
"""
# An SS... | 45e6a1fe058a78e28aeda9e9837a09dce6facd1a | 3,639,868 |
def test_module(client: Client) -> str:
"""Tests API connectivity and authentication'
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:type client: ``Client``
:param client: client t... | c672b29017d415bc3793d6561ed5cd40716c0745 | 3,639,869 |
def get_more_spec_pos(tokens):
"""Return frequencies for more specific POS"""
# adverbs and preps, particles
adverbs = [t for t in tokens if t.full_pos == 'ADV']
apprart = [t for t in tokens if t.full_pos == 'APPRART']
postpos = [t for t in tokens if t.full_pos == 'APPO']
circum_pos = [t fo... | 5ea2ae19d61c84ca8750999aa14a14dd426fe6f7 | 3,639,870 |
def reconcile_suggest_property(prefix: str = ""):
"""Given a search prefix, return all the type/schema properties which match
the given text. This is used to auto-complete property selection for detail
filters in OpenRefine."""
matches = []
for prop in model.properties:
if not prop.schema.is... | 655796e8b00f8b36cae9b373e27f11077ccb49d4 | 3,639,871 |
def make_boxes(df_data, category, size_factor, x, y, height, width, pad=[1,1], main_cat=None):
"""Generates the coordinates for the boxes of the category"""
totals = df_data[size_factor].groupby(df_data[category]).sum()
box_list = totals.sort_values(ascending=False).to_frame()
box_list.columns = ['valu... | a4bc28cf13a330863054fa3b5e514c50ba2c9e98 | 3,639,872 |
import types
import joblib
def hash_codeobj(code):
"""Return hashed version of a code object"""
bytecode = code.co_code
consts = code.co_consts
consts = [hash_codeobj(c) if isinstance(c, types.CodeType) else c
for c in consts]
return joblib.hash((bytecode, consts)) | 43d0094ccb5345ca4f8b30b5fb03d167b8e21aa5 | 3,639,873 |
def us_census():
"""Data Source for the US census.
Arguments:
None
Returns:
pandas.DataFrame
"""
df = us_census_connector()
return us_census_formatter(df) | 8aba9df470ab17a59437897a2e13a80be2b6e9d9 | 3,639,874 |
from pathlib import Path
def get_notebook_path(same_config_path, same_config_file_contents) -> str:
"""Returns absolute value of the pipeline path relative to current file execution"""
return str(Path.joinpath(Path(same_config_path).parent, same_config_file_contents["notebook"]["path"])) | 4b9f8952bdb7c2308fdfa290ec108d432b6b6a0b | 3,639,875 |
import re
import glob
def get_path_from_dependency(
recipe_dependency_value: str,
recipe_base_folder_path: str
) -> str:
""" Searches the base folder for a file, that corresponse to the dependency passed.
:param recipe_dependency_value: Value of the "From:" section from a
... | 79de99c407998193e4ab6b3d760f894d3a5039ab | 3,639,876 |
def about_us():
""" The about us page. """
return render_template(
"basic/about_us.html",
) | 64d94e998855e7c99506ced7b48da36c5cbfa57a | 3,639,877 |
import torch
def sfb1d_atrous(lo, hi, g0, g1, mode='periodization', dim=-1, dilation=1,
pad1=None, pad=None):
""" 1D synthesis filter bank of an image tensor with no upsampling. Used for
the stationary wavelet transform.
"""
C = lo.shape[1]
d = dim % 4
# If g0, g1 are not tens... | c977115b311dbe67f0d72d2990fb3d9a9a206506 | 3,639,878 |
import torch
def preprocess(image, size):
""" pre-process images with Opencv format"""
image = np.array(image)
H, W, _ = image.shape
image = nd.zoom(image.astype('float32'), (size / H, size / W, 1.0), order=1)
image = image - mean_pixel
image = image.transpose([2, 0, 1])
image = np.expand... | c2a928bbebf55587ff83347b572c7d73079cdbae | 3,639,879 |
def delete_notebook(notebook_id: str) -> tuple[dict, int]:
"""Delete an existing notebook.
The user can call this operation only for their own notebooks. This
operation requires the following header with a fresh access token:
"Authorization: Bearer fresh_access_token"
Request parameters:
... | cf7a5074d9814024bc6ed8fa56a8157a0cc4290d | 3,639,880 |
import time
def log_time(logger):
"""
Decorator to log the execution time of a function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
_log_time(lo... | a809eb70488338991636912b4eba33bf4aa93acc | 3,639,881 |
import warnings
def compute_avg_merge_candidate(catavg, v, intersection_idx):
"""
Given intersecting deltas in catavg and v, compute average delta
one could merge into running average. If one cat is an outlier,
picking that really distorts the vector we merge into running
average vector. So, effe... | 25c50ad0ad98e7a6951bd67cae8dc8fe6c78dbbb | 3,639,882 |
def plot_annotations(img, bbox, labels, scores, confidence_threshold,
save_fig_path='predicted_img.jpeg', show=False, save_fig=True):
"""
This function plots bounding boxes over image with text labels and saves the image to a particualr location.
"""
# Default colors and mappin... | f32afb61b9f43fe44b9e78896a51d67e52638eab | 3,639,883 |
def get_registry_image_tag(app_name: str, image_tag: str, registry: dict) -> str:
"""Returns the image name for a given organization, app and tag"""
return f"{registry['organization']}/{app_name}:{image_tag}" | 16c71f99ff3a3c2514c24cb417b93f3b88f7cf42 | 3,639,884 |
def process_file(filename):
"""
Handle a single .fits file, returning the count of checksum and compliance
errors.
"""
try:
checksum_errors = verify_checksums(filename)
if OPTIONS.compliance:
compliance_errors = verify_compliance(filename)
else:
comp... | 36f1723c67ab32a25cd7cba50b9989f00ea3e452 | 3,639,886 |
def solveq(K, f, bcPrescr, bcVal=None):
"""
Solve static FE-equations considering boundary conditions.
Parameters:
K global stiffness matrix, dim(K)= nd x nd
f global load vector, dim(f)= nd x 1
bcPrescr 1-dim integer array containing prescribed ... | 45aedf376f6eb2bdc6ba2a4889628f2584d13db1 | 3,639,888 |
def get_output_names(hf):
"""
get_output_names(hf)
Returns a list of the output variables names in the HDF5 file.
Args:
hf: An open HDF5 filehandle or a string containing the HDF5
filename to use.
Returns:
A sorted list of the output variable names in the HDF5 file.
"""
... | 6607197166c9a63d834398b188e996a811b081ce | 3,639,889 |
def create_hostclass_snapshot_dict(snapshots):
"""
Create a dictionary of hostclass name to a list of snapshots for that hostclass
:param list[Snapshot] snapshots:
:return dict[str, list[Snapshot]]:
"""
snapshot_hostclass_dict = {}
for snap in snapshots:
# build a dict of hostclass+e... | dd568eaeb76fee96a876b5a57d963cd2fc8f870e | 3,639,891 |
from datetime import datetime
def refund_order(id):
"""
List all departments
"""
check_admin()
order = Order.query.filter_by(id=id).first()
payment_id = order.payment_id
try:
payment = Payment.find(payment_id)
except ResourceNotFound:
flash("Payment Not Found", "d... | d0de52c4f69cb933c4344e4f4534934709a9f7cb | 3,639,892 |
def get_dprime_from_regions(*regions):
"""Get the full normalized linkage disequilibrium (D') matrix for n
regions.
This is a wrapper which determines the correct normalized linkage
function to call based on the number of regions. Only two-dimensional
normalized linkage matrices are currently suppo... | 2676c4be712989bf7e1419bf19a83ddf84c0ffec | 3,639,893 |
def get_nav_class_state(url, request, partial=False):
""" Helper function that just returns the 'active'/'inactive'
link class based on the passed url. """
if partial:
_url = url_for(
controller=request.environ['pylons.routes_dict']['controller'],
action=None,
id=... | 1ec83fc46fa04868449d8ebaf611cee9ff88fcd5 | 3,639,894 |
from typing import Tuple
import torch
from typing import List
def tile_image(
image: Image.Image, tile_size: Tuple[int, int], overlap: int
) -> Tuple[torch.Tensor, List[Tuple[int, int]]]:
"""Take in an image and tile it into smaller tiles for inference.
Args:
image: The input image to tile.
... | c5c9e09a5a95cdd63f8f2082e4c5a87e339f18ef | 3,639,896 |
from datetime import datetime
def parse(data):
"""
Parses the input of the Santander text file.
The format of the bank statement is as follows:
"From: <date> to <date>"
"Account: <number>"
"Date: <date>"
"Description: <description>"
"Amount: <amount>"
"Balance... | 267e1769553cebcd28f1c3190107712bebafb53a | 3,639,897 |
def solve_duffing(tmax, dt_per_period, t_trans, x0, v0, gamma, delta, omega):
"""Solve the Duffing equation for parameters gamma, delta, omega.
Find the numerical solution to the Duffing equation using a suitable
time grid: tmax is the maximum time (s) to integrate to; t_trans is
the initial time perio... | b1c246d3eb680852de60c7b9f0c55034d617e71a | 3,639,898 |
def create_prog_assignment_registry():
"""Create the registry for course properties."""
reg = FieldRegistry(
'Prog Assignment Entity', description='Prog Assignment',
extra_schema_dict_values={
'className': 'inputEx-Group new-form-layout'})
# Course level settings.
course_op... | c2f17e812d30abe851ba9cfd18602ca458acec56 | 3,639,899 |
def calculate_keypoints(img, method, single_channel, graphics=False):
"""
Gray or single channel input
https://pysource.com/2018/03/21/feature-detection-sift-surf-obr-opencv-3-4-with-python-3-tutorial-25/
"""
if single_channel=='gray':
img_single_channel = single_channel_gray(img)
... | 18fa71aa824f7ce4ab5468832dbc020e4fc6519d | 3,639,902 |
def plot_pos_neg(
train_data: pd.DataFrame,
train_target: pd.DataFrame,
col1: str = 'v5',
col2: str = 'v6'
) -> None:
"""
Make hexbin plot for training transaction data
:param train_data: pd.DataFrame, features dataframe
:param train_target: pd.DataFrame, target dataframe... | 2a5c27a638d43eb64192b28345edcbafd592825a | 3,639,903 |
def raffle_form(request, prize_id):
"""Supply the raffle form."""
_ = request
prize = get_object_or_404(RafflePrize, pk=prize_id)
challenge = challenge_mgr.get_challenge()
try:
template = NoticeTemplate.objects.get(notice_type='raffle-winner-receipt')
except NoticeTemplate.DoesNotExist:... | c84f6a1824ad0d6991306cb543fdaee439b2d183 | 3,639,904 |
def is_rldh_label(label):
"""Tests a binary string against the definition of R-LDH label
As defined by RFC5890_
Reserved LDH labels, known as "tagged domain names" in some
other contexts, have the property that they contain "--" in the
third and fourth characters but which otherwise co... | c44fef221381abaf0fa88115962ab9946c266090 | 3,639,905 |
def offence_memory_patterns(obs, player_x, player_y):
""" group of memory patterns for environments in which player's team has the ball """
def environment_fits(obs, player_x, player_y):
""" environment fits constraints """
# player have the ball
if obs["ball_owned_player"] == obs["activ... | 18643be138781ae7025e6f021437fd1ac2038566 | 3,639,906 |
from typing import OrderedDict
def _stat_categories():
"""
Returns a `collections.OrderedDict` of all statistical categories
available for play-by-play data.
"""
cats = OrderedDict()
for row in nfldb.category.categories:
cat_type = Enums.category_scope[row[2]]
cats[row[3]] = Ca... | fd4df74e8b3c2f94d41f407c88a3be997913adb4 | 3,639,910 |
from typing import List
import random
import math
def rsafactor(d: int, e: int, N: int) -> List[int]:
"""
This function returns the factors of N, where p*q=N
Return: [p, q]
We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
The pair (N, e) is the public key. As... | 21e655bc3f5b098da0d437a305baf89c70cebd56 | 3,639,911 |
def integrate_prob_current(psi, n0, n1, h):
"""
Numerically integrate the probability current, which is
Im{psi d/dx psi^*} over the given spatial interval.
"""
psi_diff = get_imag_grad(psi, h)
curr = get_prob_current(psi, psi_diff)
res = np.zeros(psi.shape[0])
with progressbar.Prog... | bda6efda2f61d21139011f579398c5363ae53872 | 3,639,912 |
import base64
def getFile(path):
"""
指定一个文件的路径,放回该文件的信息。
:param path: 文件路径
:return: PHP-> base64 code
"""
code = """
@ini_set("display_errors","0");
@set_time_limit(0);
@set_magic_quotes_runtime(0);
$path = '%s';
$hanlder = fopen($path, 'rb');
$res = fread($hanlder, filesize... | e44e3f90e5febee54d2f5de48e35f0b83acf9842 | 3,639,913 |
def rgc(tmpdir):
""" Provide an RGC instance; avoid disk read/write and stay in memory. """
return RGC(entries={CFG_GENOMES_KEY: dict(CONF_DATA),
CFG_FOLDER_KEY: tmpdir.strpath,
CFG_SERVER_KEY: "http://staging.refgenomes.databio.org/"}) | 1b79c9f4d5e07e13a23fe5ff88acf4e022481b42 | 3,639,914 |
import time
def simulate_quantities_of_interest_superoperator(tlist, c_ops, noise_parameters_CZ, fluxlutman,
fluxbias_q1, amp,
sim_step,
verbose: bool=True):
"""
Calculates the propagator and the quanti... | d81737e78a9e58ee160f80c58f70f73250f47844 | 3,639,916 |
def __polyline():
"""Read polyline in from package data.
:return:
"""
polyline_filename = resource_filename(
'cad', join(join('data', 'dxf'), 'polyline.dxf'))
with open(polyline_filename, 'r') as polyline_file:
return polyline_file.read() | 667a8a31decd074b1a8599bcde24caaedfd88d02 | 3,639,917 |
import random
import math
def create_identity_split(all_chain_sequences, cutoff, split_size,
min_fam_in_split):
"""
Create a split while retaining diversity specified by min_fam_in_split.
Returns split and removes any pdbs in this split from the remaining dataset
"""
data... | 2be670c382d93437d22a931314eade6ed8332436 | 3,639,918 |
def get_SNR(raw, fmin=1, fmax=55, seconds=3, freq=[8, 13]):
"""Compute power spectrum and calculate 1/f-corrected SNR in one band.
Parameters
----------
raw : instance of Raw
Raw instance containing traces for which to compute SNR
fmin : float
minimum frequency that is used for fitt... | 8536e0856c3e82f31a99d6d783befd9455054e7d | 3,639,919 |
def get_all_child_wmes(self):
""" Returns a list of (attr, val) tuples representing all wmes rooted at this identifier
val will either be an Identifier or a string, depending on its type """
wmes = []
for index in range(self.GetNumberChildren()):
wme = self.GetChild(index)
if wme.IsI... | fb66aef96ca5fd5a61a34a86052ab9014d5db8a4 | 3,639,920 |
from pathlib import Path
import tqdm
def scan_image_directory(path):
"""Scan directory of FITS files to create basic stats.
Creates CSV file ready to be read by pandas and print-out of the stats if
less than 100 entries.
Parameters
----------
path : str, pathlib.Path
Returns
-------... | aaffe891d9c5879973d18d28eff4a18954f0a348 | 3,639,921 |
def load_mat(filename):
"""
Reads a OpenCV Mat from the given filename
"""
return read_mat(open(filename, 'rb')) | 73faf2d2890a859681abdd6043bb4975516465fb | 3,639,922 |
def connected_components(image, threshold, min_area, max_area, max_features, invert=False):
"""
Detect features using connected-component labeling.
Arguments:
image (float array): The image data. \n
threshold (float): The threshold value. \n
...
Returns:
features (pa... | 541e2e8213681a064b605053033fc9aea095ad69 | 3,639,923 |
from typing import Tuple
def transform_digits_to_string(labels: Tuple[str], coefficients,
offset: Fraction) -> str:
"""Form a string from digits.
Arguments
---------
labels: the tuple of lablels (ex.: ('x', 'y', 'z') or ('a', 'b', 'c')))
coefficients: the pa... | e9486bd7cd1749a4a33e1ca8d29637468dd0d54b | 3,639,926 |
def match_peaks_with_mz_info_in_spectra(spec_a, spec_b, ms2_ppm=None, ms2_da=None):
"""
Match two spectra, find common peaks. If both ms2_ppm and ms2_da is defined, ms2_da will be used.
:return: list. Each element in the list is a list contain three elements:
m/z from spec 1; i... | 253b51abdc9469a411d5ed969d2091929ba20cd6 | 3,639,927 |
from typing import Callable
from typing import List
from typing import Type
from typing import Optional
def make_recsim_env(
recsim_user_model_creator: Callable[[EnvContext], AbstractUserModel],
recsim_document_sampler_creator: Callable[[EnvContext], AbstractDocumentSampler],
reward_aggregator: Callable[[... | 8056be88f9eb24b4ad29aea9c1a518efb07b26a4 | 3,639,928 |
def unflatten(dictionary, delim='.'):
"""Breadth first turn flattened dictionary into a nested one.
Arguments
---------
dictionary : dict
The dictionary to traverse and linearize.
delim : str, default='.'
The delimiter used to indicate nested keys.
"""
out = defaultdict(di... | f052363b8d71afa8bec609497db8646c26107b54 | 3,639,929 |
def read_array(dtype, data):
"""Reads a formatted string and outputs an array.
The format is as for standard python arrays, which is
[array[0], array[1], ... , array[n]]. Note the use of comma separators, and
the use of square brackets.
Args:
data: The string to be read in.
dtype: The data... | cc272b0e71ddec3200075fe5089cdaf2d6eeea29 | 3,639,930 |
def in_ipynb():
"""
Taken from Adam Ginsburg's SO answer here:
http://stackoverflow.com/a/24937408/4118756
"""
try:
cfg = get_ipython().config
if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook':
return True
else:
return False
except Name... | 04c9aece820248b3b1e69eaf2b6721e555557162 | 3,639,931 |
import logging
def load_bioschemas_jsonld_from_html(url, config):
"""
Load Bioschemas JSON-LD from a webpage.
:param url:
:param config:
:return: array of extracted jsonld
"""
try:
extractor = bioschemas.extractors.ExtractorFromHtml(config)
filt = bioschemas.filters.Biosc... | 6b3838260c39023b44423d5bcbc81f91a0113a95 | 3,639,932 |
import collections
def pformat(dictionary, function):
"""Recursively print dictionaries and lists with %.3f precision."""
if isinstance(dictionary, dict):
return type(dictionary)((key, pformat(value, function)) for key, value in dictionary.items())
# Warning: bytes and str are two kinds of collect... | d509e8871c6749be61d7b987e5fa67cd3e824232 | 3,639,933 |
def _tonal_unmodulo(x):
"""
>>> _tonal_unmodulo((0,10,0))
(0, -2, 0)
>>> _tonal_unmodulo((6,0,0))
(6, 12, 0)
>>> _tonal_unmodulo((2, 0))
(2, 0)
"""
d = x[0]
c = x[1]
base_c = MS[d].c
# Example: Cb --- base=0 c=11 c-base=11 11 - 12 = -1
if c - base_c > 6:
... | 50ae6b1eea4a281b32d07f0661837748b066af8d | 3,639,934 |
def get_ncopy(path, aboutlink = False):
"""Returns an ncopy attribute value (it is a requested count of
replicas). It calls gfs_getxattr_cached."""
(n, cc) = getxattr(path, GFARM_EA_NCOPY, aboutlink)
if (n != None):
return (int(n), cc)
else:
return (None, cc) | 82c212d1d6aa68b49cde7ec170a47fdb09d1dd46 | 3,639,935 |
def has_three_or_more_vowels(string):
"""Check if string has three or more vowels."""
return sum(string.count(vowel) for vowel in 'aeiou') >= 3 | 8b0b683ebe51b18bdc5d6f200b41794a4cb3a510 | 3,639,936 |
def lbfgs_inverse_hessian_factors(S, Z, alpha):
"""
Calculates factors for inverse hessian factored representation.
It implements algorithm of figure 7 in:
Pathfinder: Parallel quasi-newton variational inference, Lu Zhang et al., arXiv:2108.03782
"""
J = S.shape[1]
StZ = S.T @ Z
R = jnp... | 1cc279a3fd97d8d1987be532bb3bc3c06a76bea7 | 3,639,937 |
from typing import List
from typing import Dict
from typing import Any
def get_geojson_observations(properties: List[str] = None, **kwargs) -> Dict[str, Any]:
""" Get all observation results combined into a GeoJSON ``FeatureCollection``.
By default this includes some basic observation properties as GeoJSON ``... | b87f3bcff5ea022ef6509c3b29491dd0f3c665be | 3,639,938 |
import signal
def createFilter(fc, Q, fs):
"""
Returns digital BPF with given specs
:param fc: BPF center frequency (Hz)
:param Q: BPF Q (Hz/Hz)
:param fs: sampling rate (Samp/sec)
:returns: digital implementation of BPF
"""
wc = 2*pi*fc
num = [wc/Q, 0]
den = [1, wc/Q, wc**2]
... | 9152d9f89781e1151db481cd88a736c2035b9fbd | 3,639,939 |
def create_uno_struct(cTypeName: str):
"""Create a UNO struct and return it.
Similar to the function of the same name in OOo Basic.
Returns:
object: uno struct
"""
oCoreReflection = get_core_reflection()
# Get the IDL class for the type name
oXIdlClass = oCoreReflection.forNam... | acdb7dfaedc75d25e0592b7edf4928779835e5f4 | 3,639,940 |
import pkg_resources
def get_dir():
"""Return the location of resources for report"""
return pkg_resources.resource_filename('naarad.resources',None) | e9f450e3f46f65fed9fc831aaa37661477ad3d14 | 3,639,941 |
import torch
def SoftCrossEntropyLoss(input, target):
"""
Calculate the CrossEntropyLoss with soft targets
:param input: prediction logicts
:param target: target probabilities
"""
total_loss = torch.tensor(0.0)
for i in range(input.size(1)):
cls_idx = torch.full((input.size(0),), ... | e760fb7a8c85cc32e18bf5c1b5882c0a0682d211 | 3,639,942 |
def composite_layer(inputs, mask, hparams):
"""Composite layer."""
x = inputs
# Applies ravanbakhsh on top of each other.
if hparams.composite_layer_type == "ravanbakhsh":
for layer in xrange(hparams.layers_per_layer):
with tf.variable_scope(".%d" % layer):
x = common_layers.ravanbakhsh_set_l... | f5cc3981b103330eef9d2cf47ede7278eef00bdc | 3,639,943 |
def edit_expense(expense_id, budget_id, date_incurred, description, amount, payee_id):
"""
Changes the details of the given expense.
"""
query = sqlalchemy.text("""
UPDATE budget_expenses
SET
budget_id = (:budget_id),
date_incurred = (:date_incurred),
description = (:description),
... | 83a1e591e71efa9a5f8382c934f9090a737a9d5c | 3,639,944 |
def get_mnist_iterator(batch_size, input_shape, num_parts=1, part_index=0):
"""Returns training and validation iterators for MNIST dataset
"""
get_mnist_ubyte()
flat = False if len(input_shape) == 3 else True
train_dataiter = mx.io.MNISTIter(
image="data/train-images-idx3-ubyte",
l... | 4a042595b30aa2801221607d5605dc41eac7acf4 | 3,639,945 |
def dataset():
"""Get data frame for test purposes."""
return pd.DataFrame(
data=[['alice', 26], ['bob', 34], ['claire', 19]],
index=[0, 2, 1],
columns=['Name', 'Age']
) | 53d023b57f5abdd1226f2dfe22ce1853e405c71f | 3,639,946 |
def get_consumer_key():
"""This is entirely questionable. See settings.py"""
consumer_key = None
try:
loc = "%s/consumer_key.txt" % settings.TWITTER_CONSUMER_URL
url = urllib2.urlopen(loc)
consumer_key = url.read().rstrip()
except (urllib... | 77ac3ce96660c32ce9dc43afa0116b7a6e1e1bc2 | 3,639,947 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.