content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def license(soup):
"""
Find the license text
"""
license = None
try:
license_section = get_license_section(soup)
license = extract_node_text(license_section[0], "license-p")
except(IndexError):
return None
return license | c7f677e369b7170623968cdfe0d0a85d75e4a339 | 23,992 |
def filter_nofix(df,NoFrames):
"""
Filter for immobilized origami with DNA-PAINT based tracking handle (TH) as described in `spt`_.
Positives are groups
- with a trajectory within the first 5 frames after the start of the measurement
- and number localizations within group are greater... | e115cc479c984037adbe3dd662bed1aa70acaafd | 23,993 |
def read_array(cls, start=None,end=None,weight=None,use_datetime = False, convert_delta = False):
"""
Read arrays of values for start, end and weight values that represent either the cummulative value of the data steps or the direct step
values seperately, indexed by the start and possibly end arrays.
... | 98b97a53883ed39d762849313cab64f29fadfd8d | 23,994 |
def store_nugget_nodes(gold_nuggets, sys_nuggets, m_mapping):
"""
Store nuggets as nodes.
:param gold_nuggets:
:param sys_nuggets:
:param m_mapping:
:return:
"""
# Stores time ML nodes that actually exists in gold standard and system.
gold_nodes = []
sys_nodes = []
# Store t... | 659eeccc244d7dfe7fc1c4b9813844d70973b5dc | 23,995 |
def return_union_item(item):
"""union of statements, next statement"""
return " __result.update({0})".format(item) | 60fff47ff948f5b62ff6c6793b9dd339c23ecfd7 | 23,996 |
def normalize_basename(s, force_lowercase=True, maxlen=255):
"""Replaces some characters from s with a translation table:
trans_table = {" ": "_",
"/": "_slash_",
"\\": "_backslash_",
"?": "_question_",
"%": "_percent_",
... | 8b6c6fee3a55b3d704294d8bdaa7f72101ac477b | 23,997 |
import re
def _get_toc_string_from_log(file_handle):
"""
Returns a toc string or None for a given log file (EAC or XLD)
Copyright (c) 2018 Konstantin Mochalov
Released under the MIT License
Original source: https://gist.github.com/kolen/765526
"""
def _filter_toc_entries(file_handle):
... | 1b8152171dcc5a512ea92df96bdc63497f01499a | 23,999 |
def _matrix_M_entry(row, col):
"""Returns one entry for the matrix that maps alpha to theta.
See Eq. (3) in `Mรถttรถnen et al. (2004) <https://arxiv.org/pdf/quant-ph/0407010.pdf>`_.
Args:
row (int): one-based row number
col (int): one-based column number
Returns:
(float): transf... | 12b2d7b458d8b940504c108cd5704795184400a9 | 24,000 |
def get_environment_variable_names():
"""Helper to return names of environment variables queried.
Returns:
tuple: name of environment variable to control log level,
name of environment variable to control logging to file
"""
__log_file_environment_variable_name = mwi_env.get_env... | 58457a843eeda900261fcecdb41a938ea59ff0c4 | 24,001 |
import pynvml
def get_device_total_memory(index=0):
"""
Return total memory of CUDA device with index
"""
pynvml.nvmlInit()
return pynvml.nvmlDeviceGetMemoryInfo(
pynvml.nvmlDeviceGetHandleByIndex(index)
).total | 11fb76c85393531cf01d9193adddaeec59e5f5c5 | 24,002 |
def repeat_elements(x, rep, axis):
"""Repeats the elements of a tensor along an axis, like `np.repeat`.
If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output
will have shape `(s1, s2 * rep, s3)`.
# Arguments
x: Tensor or variable.
rep: Python integer, number of times to repeat.... | 3a4e3617021afa59de1b980e9cebc7a40e4f32db | 24,003 |
def deconv4x4_block(in_channels,
out_channels,
stride=1,
padding=3,
ext_padding=(2, 1, 2, 1),
out_padding=0,
dilation=1,
groups=1,
bias=False,
... | 6f2274b8c23f2b649a274d8bec7d99174da785f4 | 24,004 |
def get_package_requirements():
""" Used to read requirements from requirements.txt file.
:return: list of requirements
:rtype: list
"""
requirements = []
for line in read_file_contents("requirements.txt").splitlines():
line = line.strip()
if line == "" or line.startswith("#"):
... | 0fea0b1ce42afdf6e4c130c6a5d5f22dbead5222 | 24,005 |
def graph2tree(mat, root, closedset=None):
"""Convert a graph to a tree data structure"""
if closedset is None:
closedset = set()
tree = Tree()
def walk(name):
node = TreeNode(name)
node.dist = 0
closedset.add(name)
for child in mat[name]:
if child n... | 70981e1ff28e6ce1c6278ec35206a1953499855d | 24,008 |
import re
def is_hex(hex_str):
"""Helper function to verify a string is a hex value."""
return re.fullmatch('[0-9a-f]+', hex_str) | c5a53ccbcec36d77bee88d9c81aea46d2a0eec2d | 24,009 |
def jet(data, range=None, exp=1.0):
"""
Creates a JET colormap from data
Parameters
----------
data : np.array [N,1]
Data to be converted into a colormap
range : tuple (min,max)
Optional range value for the colormap (if None, use min and max from data)
exp : float
Ex... | 6945558dd6fc53c458f0c5c3e3f98fd5a1486a10 | 24,011 |
def collatz_seq(n, collatz_dict={}):
""" Takes an integer n and returs the resulting Collatz sequence as a list. """
seq = [n]
while n > 1:
n = next_collatz(n)
if n in collatz_dict:
seq.extend(collatz_dict[n])
collatz_dict[seq[0]] = seq
return seq
... | ae7ec3a77c39262c15cde9f18a24d60ca237284e | 24,012 |
def create_app():
"""
Create a Flask application using the app factory pattern.
:param settings_override: Override settings
:return: Flask app
"""
app = Flask(__name__)
app.config.from_object('config.settings')
app.register_blueprint(contact)
return app | 3af4d596fe8fd32f88f06e860cae2e929aa799e7 | 24,013 |
def get_prebuilt_piccolo():
"""
:return: pair of picollo feature model filename and fm.json as a string
"""
DEFAULT_PREBUILT_PICCOLO = f'/home/besspinuser/tool-suite/tutorial/piccolo-simple-pregen.fm.json'
with open(DEFAULT_PREBUILT_PICCOLO, 'r') as f:
feature_model = f.read()
return 'p... | 90a1ecf20c6d6614b813250ff464b6f308c588dc | 24,014 |
from datetime import datetime
def conflict_algorithm_session(date, start_time, end_time, venue):
#converting string to datetime type variable
"""
conflict_algorithm_session:
this algorithm is used to find if there any avaiable slot for the given date , stat_time ,end_time and venue
from the session_info to... | 06fffa780ed4a9afa7cc2cc078bf64dada9b4f21 | 24,015 |
def get_income_share_summary(df_centile, k):
"""
:param df_centile: pd.DataFrame
preprocessed {region}_{unit}_centile.csv !! (rank is 1~100)
:param k: str
key
"""
centile_range = {
'ํ์ 20%': (0, 20),
'๋ค์ 30%': (20, 50),
'ํ์ 50%': (0, 50),
'์ค์ 30%': (50... | 63f9a1e3f813a21681ad6d0061cd97e49485b885 | 24,016 |
def _get_cmdline_descriptors_for_hashtree_descriptor(ht):
"""Generate kernel cmdline descriptors for dm-verity.
Arguments:
ht: A AvbHashtreeDescriptor
Returns:
A list with two AvbKernelCmdlineDescriptor with dm-verity kernel cmdline
instructions. There is one for when hashtree is not dis... | a57a33e50a8888781ed9a0fd1cddada12acea69e | 24,017 |
from datetime import datetime
def assign_time():
"""Get latest time stamp value"""
return datetime.strftime(datetime.now(), format='%Y-%m-%d %T') | 2096222b23f5eb0d0aa11a6db4f3751b0a207463 | 24,018 |
def read_pb2(filename, binary=True):
"""Convert a Protobuf Message file into mb.Compound.
Parameters
----------
filename : str
binary: bool, default True
If True, will print a binary file
If False, will print to a text file
Returns
-------
root_compound : mb.Compound
... | 29c128020eab6b6a33fd1e4f36be395c0672c3b4 | 24,020 |
import logging
def _OneSubChunk(wav_file):
"""Reads one subchunk and logs it.
Returns:
Returns a chunk if a chunk is found. None otherwise.
"""
chunk_id = _ReadChunkId(wav_file)
if not chunk_id:
return None
size = _ReadSize(wav_file)
data = wav_file.read(size)
logging.in... | c43cb5fb9367d4d255475ec8f1fc41df3ea422cc | 24,021 |
def _convert_tensorshape_to_tensor(value, dtype=None):
"""Copied from TF's TensorShape conversion."""
if not value.is_fully_defined():
raise ValueError(
'Cannot convert a partially known TensorShape to a Tensor: {}'.format(
value))
value_list = value.as_list()
int64_value = 0
for dim i... | bc5cc28b6694faf1676aaf4f523a5c135a9bb0d0 | 24,022 |
def get_upside_capture(
nav_data,
benchmark_nav_data,
risk_free_rate=None,
window=250 * 3,
annualiser=250,
tail=True,
):
"""
The up-market capture ratio is the statistical measure of an investment manager's overall
performance in up-markets. It is used to evaluate how well an investm... | 7828b6c6e222fe4e6886d4ebf4c3bec2cbf3e795 | 24,024 |
import ssl
import urllib
import json
def generateToken(username, password, portalUrl):
"""Retrieves a token to be used with API requests."""
context = ssl._create_unverified_context() if NOSSL else None
params = urllib.urlencode({'username' : username,
'password' : password, 'client' : 'refere... | ba4cc48f88b088c899de9d278795706dee014c94 | 24,025 |
def get_logreg(prof, tm, j, prods):
"""
Train logistic regression (Markov-chain approach).
prof: task-mode data generated using lhs.py
tm: task-mode
j: name of unit
prods: list of products
"""
# Filter relevant data
dfj = prof.loc[prof["unit"] == j, ].copy()
dfj["... | ff5279d3cb82e769abcff64fa7573b2601da31bb | 24,026 |
def slowness2speed(value):
"""invert function of speed2slowness"""
speed = (31 - value) / 30
return speed | 54d192b2db667ee05b9c5bdd636af23313b72246 | 24,027 |
def complex_covariance_from_real(Krr, Kii, Kri):
"""Summary
Parameters
----------
Krr : TYPE
Description
Kii : TYPE
Description
Kri : TYPE
Description
Returns
-------
TYPE
Description
"""
K = Krr + Kii + 1j * (Kri.T - Kri)
Kp = Krr - Kii ... | 0c3e7b01bb06ba6b5bbae50f1fab98cb8bd63f45 | 24,028 |
def is_in_cap(objs, radecrad):
"""Determine which of an array of objects lie inside an RA, Dec, radius cap.
Parameters
----------
objs : :class:`~numpy.ndarray`
An array of objects. Must include at least the columns "RA" and "DEC".
radecrad : :class:`list`, defaults to `None`
3-entr... | e85abee591dd2956ed8d9be5c47eafaa9c249cb2 | 24,029 |
from typing import Any
from typing import List
import numbers
def _ensure_list(value: Any) -> List[Any]:
"""If value is a scalar, converts it to a list of size 1."""
if isinstance(value, list):
return value
if isinstance(value, str) or isinstance(value, numbers.Number):
return [value]
raise TypeErro... | e9cb9814060d9f2f2ad15fe42d0f6bbe192cc60e | 24,031 |
import types
from typing import Callable
import copy
def _ExtractMetaFeature( # pylint: disable=invalid-name
extracts: types.Extracts,
new_features_fn: Callable[[types.FeaturesPredictionsLabels],
types.DictOfFetchedTensorValues]
) -> types.Extracts:
"""Augments FPL dict with n... | 14ad08a2e2158989ec48d605dd954311cac30cfe | 24,032 |
import re
def parse_notebook_index(ntbkpth):
"""
Parse the top-level notebook index file at `ntbkpth`. Returns a list of
subdirectories in order of appearance in the index file, and a dict
mapping subdirectory name to a description.
"""
# Convert notebook to RST text in string
rex = RSTEx... | 74ce532c577df8b5ecf02cbe4163422a80360bf6 | 24,033 |
from pathlib import Path
def import_requirements():
"""Import ``requirements.txt`` file located at the root of the repository."""
with open(Path(__file__).parent / 'requirements.txt') as file:
return [line.rstrip() for line in file.readlines()] | ee22aaa76e13c150a2a7981d171ba227887fbceb | 24,034 |
from typing import Literal
def _get_timestamp_range_edges(
first: Timestamp,
last: Timestamp,
freq: BaseOffset,
closed: Literal["right", "left"] = "left",
origin="start_day",
offset: Timedelta | None = None,
) -> tuple[Timestamp, Timestamp]:
"""
Adjust the `first` Timestamp to the prec... | a1d5a9998fb8e88badd354779c50be0e26be37f8 | 24,035 |
def create_export(request, username, id_string, export_type):
"""
Create async export tasks view.
"""
owner = get_object_or_404(User, username__iexact=username)
xform = get_form({'user': owner, 'id_string__iexact': id_string})
if not has_permission(xform, owner, request):
return HttpRes... | d94b674409b094693470132cc84b63c33bd657a1 | 24,036 |
def draft_bp(app):
"""Callable draft blueprint (we need an application context)."""
with app.app_context():
return BibliographicDraftResource(
service=BibliographicRecordService()
).as_blueprint("bibliographic_draft_resource") | e0c1846e74399d9a946b11cd68a586c55e93cb3a | 24,037 |
import tarfile
import io
def _unpack(stream: bytes, path: str) -> str:
"""Unpack archive in bytes string into directory in ``path``."""
with tarfile.open(fileobj=io.BytesIO(stream)) as tar:
tar.extractall(path)
return path | 81a05c0a60fb06d43592a0a4f4d30cf62d406e01 | 24,038 |
def create_client(client):
"""Creates a new client."""
rv = client.post('/v1/oauth/', follow_redirects=True, data={
'submit': 'Add Client',
})
db.app = jobaddservice.app
oauth_clients = Client.query.all()
client_id = oauth_clients[0].client_id
return client_id | 4de5a7e9feae199c8424871962d1a11a5a9f34c8 | 24,039 |
def FPS(name, sort, explicit_name=None):
"""
Creates a floating-point symbol.
:param name: The name of the symbol
:param sort: The sort of the floating point
:param explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:return: ... | 137595ce164b72438c16fa8f74838270b43fb3db | 24,041 |
def _calc_cat_outlier(df: dd.DataFrame, col_x: str, threshold: int = 1) -> Intermediate:
"""
calculate outliers based on the threshold for categorical values.
:param df: the input dataframe
:param col_x: the column of df (univariate outlier detection)
:return: dict(index: value) of outliers
"""
... | 3b2c7ea6a7491fd81b2467d1f2b5faad36523177 | 24,045 |
def add_precursor_mz(spectrum_in: SpectrumType) -> SpectrumType:
"""Add precursor_mz to correct field and make it a float.
For missing precursor_mz field: check if there is "pepmass"" entry instead.
For string parsed as precursor_mz: convert to float.
"""
if spectrum_in is None:
return None... | 297fbb280aa00992d7658dc47306c4c98018d19e | 24,046 |
import functools
import click
def echo_result(function):
"""Decorator that prints subcommand results correctly formatted.
:param function: Subcommand that returns a result from the API.
:type function: callable
:returns: Wrapped function that prints subcommand results
:rtype: callable
"""
... | 7a4956eea317f77ec816d7c68ff61749a971b025 | 24,047 |
import numpy
def load_cifar10():
""" Load the CIFAR-10 dataset.
"""
def post(inputs, labels):
return inputs.astype(numpy.float32) / 255, labels.flatten().astype(numpy.int32)
return NumpySet.from_keras(tf.keras.datasets.cifar10.load_data, post=post) | 436411f1258803a45d0ba4f570dc80c5ec0cd4b8 | 24,048 |
def parse_names(filename):
"""
Parse an NCBI names.dmp file.
"""
taxid_to_names = dict()
with xopen(filename, 'rt') as fp:
for n, line in enumerate(fp):
line = line.rstrip('\t|\n')
x = line.split('\t|\t')
taxid, name, uniqname, name_class = x
... | cca9249333c373a56c1829557caff876df210859 | 24,049 |
def parse(pm, doc):
""" Parse one document using the given parsing model
:type pm: ParsingModel
:param pm: an well-trained parsing model
:type fedus: string
:param fedus: file name of an document (with segmented EDUs)
"""
pred_rst = pm.sr_parse(doc)
return pred_rst | 4389ac7993d370f2a7d404e5668eb7522ee4db70 | 24,051 |
def two_sum(nums, target):
"""
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution, and you
may not use the same element twice.
:type nums: List[int]
:type target: int
:... | ac72eb7137eb0f7161c26b172cd07553c984b5a8 | 24,052 |
def remove_columns(tx, header, columns_to_remove):
"""
Removes the given features from the given set of features.
Args:
tx: the numpy array representing the given set of features
header: the header line of the .csv representing the data set
columns_to_remove: The indices of the featu... | d7f2ed3092fc094ccc48f27813ad8a77358dfc19 | 24,053 |
def pangenome(groups_file, fasta_list):
#creating the len_dict
"""
The len_dict is used to remember all of the common names and lengths of EVERY gene in each species, which are matched to the arbitrary name.
The len_dict is in form len_dict = {speciesA:{arb_name1:[com_name, length], arb_name2:[com_name,len... | 9b9fd884ab6e464b5e40ae84d01801743da222be | 24,054 |
import torch
def argmin(x):
"""Deterministic argmin.
Different from torch.argmin, which may have undetermined result if the are
multiple elements equal to the min, this argmin is guaranteed to return the
index of the first element equal to the min in each row.
Args:
x (Tensor): only supp... | 93efe99e616f2266c14c94fb81d9251d8bcfba18 | 24,055 |
import json
def check_geometry_size(footprint):
"""
Excessive large geometries are problematic of AWS SQS (max size 256kb) and cause
performance issues becuase they are stored in plain text in the JSON
blob.
This func reads the geojson and applies a simple heuristic to reduce the
footprint s... | b2525958a1440fc1ce0d2560150b7fe28b3ec450 | 24,056 |
def get_global_comments():
"""Returns all global comments"""
return GlobalComment.query.all() | f7dcf7be712187aac784787e4745c366e0759cf5 | 24,057 |
def is_descending(path):
"""
Return ``True`` if this profile is a descending
profile.
"""
return _re_search(path, _re_descending) | 6afb24abc76fa1fa1b33793aca14b1d425664e7e | 24,058 |
def mises_promo_gain_cote(cotes, mise_minimale, rang, output=False):
"""
Calcule la rรฉpartition des mises pour la promotion "gain en freebet de la cote gagnรฉe"
"""
mis = []
gains = cotes[rang] * 0.77 + mise_minimale * cotes[rang]
for cote in cotes:
mis.append((gains / cote))
mis[rang... | 6dfbb9305e769982257a05cb41800a6d2656767b | 24,059 |
def recalculateResult(request, question_id):
"""Called when poll owner wants to recalculate result manually."""
question = get_object_or_404(Question, pk=question_id)
getPollWinner(question)
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) | 32e21808f8fd63b1f02981c966c58a6fdeecf6a5 | 24,060 |
def covden_win(cov_resampled, lut):
"""
Method to associate resampled vegitation coverage to PRMS covden_win
Parameters
----------
cov_resampled : np.ndarray
lut : dict
Returns
-------
gsflow.prms.ParameterRecord object
"""
covden = covden_sum(cov_resampled, lut)
c... | 5289954b2be41539981ad8af73bc683835c13bde | 24,061 |
def login_webauthn_route():
"""login webauthn route"""
user = User.query.filter(User.id == session.get('webauthn_login_user_id')).one_or_none()
if not user:
return login_manager.unauthorized()
form = WebauthnLoginForm()
if form.validate_on_submit():
try:
assertion = cbo... | d1f31035e696f539f58019c8a37c650089e92d23 | 24,062 |
def generate_feature_matrix(genotypes, phenotypes, reg_type,phewas_cov=''): # diff - done
"""
Generates the feature matrix that will be used to run the regressions.
:param genotypes:
:param phenotypes:
:type genotypes:
:type phenotypes:
:returns:
:rtype:
"""
feature_matrix = np.zeros((3, genotypes.s... | 95abe0e89060145b90abe4debe7dfd23ba6a4969 | 24,063 |
def get_entity(db: SQLAlchemy, id: str) -> EntityOut:
"""Get and entity by id."""
db_session = db.session_class()
entry = repository.get_entity(db_session, id)
if not entry:
raise exc.NotFound()
return EntityOut(entry) | 16b64a90251eee3dfa79ede4d5524ecfb28a1a82 | 24,064 |
def cov(sources):
"""
Given the array of sources for all image patches, calculate the covariance
array between all modes.
Parameters
----------
sources : numpy array (floats)
The {NUM_MODES x NUM_PATCHES} array of sources.
Returns
-------
numpy array (floats)
The {N... | 268dfbc98a5b443e92aadd27ba577f7911ca398f | 24,065 |
import json
def VerifierMiddleware(verifier):
"""Common wrapper for the authentication modules.
* Parses the request before passing it on to the authentication module.
* Sets 'pyoidc' cookie if authentication succeeds.
* Redirects the user to complete the authentication.
* Allows t... | 1b8d62830ba57bf7761b77ac271a19c5a486bb20 | 24,066 |
def hls_stream(hass, hass_client):
"""Create test fixture for creating an HLS client for a stream."""
async def create_client_for_stream(stream):
stream.ll_hls = True
http_client = await hass_client()
parsed_url = urlparse(stream.endpoint_url(HLS_PROVIDER))
return HlsClient(http... | ca759edc6bf819ba8788e20d8d44da96bfaa73fe | 24,067 |
def AsinhNorm(a=0.1):
"""Custom Arcsinh Norm.
Parameters
----------
a : float, optional
Returns
-------
ImageNormalize
"""
return ImageNormalize(stretch=AsinhStretch(a=a)) | fecc3bfec6e14033f5d29fb044fb099bddb8b4b3 | 24,068 |
def sub(x, y):
"""sub two numbers"""
return y-x | 345279da515a877c1f08a8b54ff8f2e7d6a95fec | 24,069 |
def addSplashScreen(splashSDKName, decompileDir):
""" add splash screen
channel hasn't Splash if channel["bHasSplash"] = 0
otherwise channel["bHasSplash"] express orientation and color
"""
channelHasSplash ="0";
try:
#read has splash to funcellconfig.xml
config =... | 52964383a6ee440a9b18a2e1ab35a25d5f376753 | 24,070 |
def get_k8s_helper(namespace=None, silent=False):
"""
:param silent: set to true if you're calling this function from a code that might run from remotely (outside of a
k8s cluster)
"""
global _k8s
if not _k8s:
_k8s = K8sHelper(namespace, silent=silent)
return _k8s | 81104cf72709a15fc56edca6d4e6fc005412ae75 | 24,072 |
def authenticate():
"""Authorize."""
return redirect(Vend().authenticate()) | f34d8df5e69b9552592349db71fac1b193effce1 | 24,073 |
import re
def non_device_name_convention(host):
"""
Helper filter function to filter hosts based targeting
host names which do NOT match a specified naming convention
Examples:
- lab-junos-08.tstt.dfjt.local
- dfjt-arista-22.prd.dfjt.local
- lab-nxos-001.lab.dfjt.local
:p... | ecb455eb61e3917ee41ebc5a6cacfd8829d6e3f6 | 24,074 |
def recursive_swagger_spec(minimal_swagger_dict, node_spec):
"""
Return a swager_spec with a #/definitions/Node that is
recursive.
"""
minimal_swagger_dict['definitions']['Node'] = node_spec
return Spec(minimal_swagger_dict) | be13e07689378b46964c45830b1ac5eb2f30be14 | 24,075 |
import json
def _get_base_parts(config):
"""
Builds the base ip array for the first N octets based on
supplied base or on the /N subnet mask in the cidr
"""
if 'base' in config:
parts = config.get('base').split('.')
else:
parts = []
if 'cidr' in config:
cidr = conf... | 9257db10a07a9468ea81912e0818e220be240beb | 24,076 |
def diff_exp(counts, group1, group2):
"""Computes differential expression between group 1 and group 2
for each column in the dataframe counts.
Returns a dataframe of Z-scores and p-values."""
mean_diff = counts.loc[group1].mean() - counts.loc[group2].mean()
pooled_sd = np.sqrt(counts.loc[group1].va... | be70eb9c843d9cfd72efb9c85f023b91c3a6730e | 24,077 |
def load(source):
"""HTSใใซใณใณใใญในใใฉใใซ(Sinsy็จ)ใ่ชญใฟๅใ
source: path, lines
"""
song = HTSFullLabel()
return song.load(source) | 5cc2c7cfdf4e04071fc6d6525803c09592c7889f | 24,078 |
def _binary_clf_curve(y_true, y_score, pos_label=None):
"""Calculate true and false positives per binary classification threshold.
Parameters
----------
y_true : array, shape = [n_samples]
True targets of binary classification
y_score : array, shape = [n_samples]
Estimated probabil... | 0dd0f1bb711b0df052c115534b886b93ae8e59f3 | 24,079 |
def term_open_failed(data=None):
"""
Construct a template for a term event
"""
tpl = term()
tpl.addKey(name='event', data="open-failed")
if data is not None:
tpl.addKey(name='data', data=data)
return tpl | 7eae9e897294a545c4aaf27fe4204a6fd8b106a1 | 24,080 |
def create_error_payload(exception, message, endpoint_id):
"""
Creates an error payload to be send as a response in case of failure
"""
print(f'{exception}: {message}')
error_payload = {
'status': 'MESSAGE_NOT_SENT',
'endpointId': endpoint_id if endpoint_id else 'NO_ENDPOINT_ID',
'message': f'{ex... | 90f266d22429d385e828dcdd92fca3d7b2e6df48 | 24,081 |
def has_columns(df, columns):
"""Check if DataFrame has necessary columns.
Args:
df (pd.DataFrame): DataFrame.
columns (list(str): columns to check for.
Returns:
bool: True if DataFrame has specified columns.
"""
result = True
for column in columns:
if column no... | d2752099fb13cf3fb220cb0c8402917488c32ef1 | 24,082 |
def render(template, **kwargs):
"""Render template with default values set"""
return JINJA_ENV.get_template(template).render(
autograde=autograde,
css=CSS,
favicon=FAVICON,
timestamp=timestamp_utc_iso(),
**kwargs
) | a523822c6c3bb9ff2b41a63091d2c89f612b18b4 | 24,083 |
def _cytof_analysis_derivation(context: DeriveFilesContext) -> DeriveFilesResult:
"""Generate a combined CSV for CyTOF analysis data"""
cell_counts_analysis_csvs = pd.json_normalize(
data=context.trial_metadata,
record_path=["assays", "cytof", "records"],
meta=[prism.PROTOCOL_ID_FIELD_NA... | 21ca42e0d53f602c09a3901b6287d0d970bc7d7b | 24,084 |
def get_field(name, data):
"""
Return a valid Field by given data
"""
if isinstance(data, AbstractField):
return data
data = keys_to_string(data)
type = data.get('type', 'object')
if type == "string":
return StringField(name=name, **data)
elif type == "boolean":
r... | 61abdb216ff76f54c752878023bc3c60128e18f4 | 24,085 |
def data_context_connectivity_context_connectivity_serviceuuid_namevalue_name_get(uuid, value_name): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_namevalue_name_get
returns tapi.common.NameAndValue # noqa: E501
:param uuid: Id of connectivity-service
:type uuid: str
... | f703f90bfbd4f476b58f7aacceecca9a444835e4 | 24,086 |
def open_alleles_file(N0, n, U, Es, mmax, mwt, mutmax, rep):
"""
This function opens the output files and returns file
handles to each.
"""
sim_id = 'N%d_n%d_U%.6f_Es%.5f_mmax%.2f_mwt%.2f_mutmax%d_rep%d' %(N0, n, U, Es, mmax, mwt, mutmax, rep)
data_dir = '../SIM_DATA'
outfile = open("%s/alleles_%s.csv" %(data_di... | 62455b1ba4dd65b6ef78f3b4cfdb31efd8433db6 | 24,087 |
def approximateWcs(wcs, camera_wrapper=None, detector_name=None,
obs_metadata=None,
order=3, nx=20, ny=20, iterations=3,
skyTolerance=0.001*LsstGeom.arcseconds, pixelTolerance=0.02):
"""
Approximate an existing WCS as a TAN-SIP WCS
The fit is perform... | a0dbf47c197033291541d3afc19406e161173b81 | 24,088 |
def parse_table_column_names(table_definition_text):
"""
Parse the table and column names from the given SQL table
definition. Return (table-name, (col1-name, col2-name, ...)).
Naรฏvely assumes that ","s separate column definitions regardless of
quoting, escaping, and context.
"""
match = _... | 3ec88640a0411799e35b25987a809b1489f4a03b | 24,089 |
def show_all_positions():
"""
This leads user to the position page when user clicks on the positions
button on the top right and it is supposed to show user all the positions
in the database
"""
db=main()
conn = create_connection(db)
mycur = conn.cursor()
post=mycur.execute("SELECT *... | df59bf0f97e46cf79d23d93037972513759942d3 | 24,091 |
import copy
def get_subtree_tips(terms: list, name: str, tree):
"""
get lists of subsubtrees from subtree
"""
# get the duplicate sequences
dups = [e for e in terms if e.startswith(name)]
subtree_tips = []
# for individual sequence among duplicate sequences
for dup in dups:
# c... | 7bebf86ba95ede46f4e4c3ad0926784d4755124b | 24,092 |
def pressure_to_cm_h2o(press_in):
"""Convert pressure in [pa] to [cm H2O]
Returns a rounded integer"""
conversion_factor = 98.0665
return int(round(press_in / conversion_factor)) | cabf905a71747c0e053356d89beebad7f03e85e7 | 24,093 |
def parse_deceased_field(deceased_field):
"""
Parse the deceased field.
At this point the deceased field, if it exists, is garbage as it contains First Name, Last Name, Ethnicity,
Gender, D.O.B. and Notes. We need to explode this data into the appropriate fields.
:param list deceased_field: a list... | f87faed7b9def61f0533dc0d3bdd7823490031cf | 24,094 |
def rate(epoch, rate_init, epochs_per_order):
""" Computes learning rate as a function of epoch index.
Inputs:
epoch - Index of current epoch.
rate_init - Initial rate.
epochs_per_order - Number of epochs to drop an order of magnitude.
"""
return rate_init * 10.0 ** (-epoch /... | cc1c7850d4bd98d30b97c7915ceb96eaeadef327 | 24,095 |
import networkx
def has_loop(net):
"""
Check if the network is a loop
"""
try:
networkx.algorithms.cycles.find_cycle(net)
return True
except networkx.exception.NetworkXNoCycle:
return False | 8141b0609e780297ba3ecabc1d9bd97ca7ea09c3 | 24,096 |
def get_query_name(hmma):
"""
get the panther family name from the query target
"""
hmma_list = hmma.split ('.')
if len(hmma_list) > 2:
hmm_fam = hmma_list[0]
hmm_sf = hmma_list[1]
something_else = hmma_list[2]
elif len(hmma_list) == 2:
hmm_fam = hmma_list[0]
... | cdb7bc6f9db022842872e710266937c872768407 | 24,097 |
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
return user_passes_test(
lambda u: u.is_active and u.is_st... | bf62abb607e5fcef5a71938dce2fd8c0f008d9cf | 24,098 |
from typing import Dict
def get_event_listeners(ctx: Configuration) -> Dict:
"""List of events that is being listened for."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_EVENTS)
return req.json() if req.status_code == 200 else {} # type: ignore
except (HomeAssistantCliError, ValueErr... | aebe497010e1719a815274e2f0e6ebb6177650d5 | 24,099 |
def process_tce(tce):
"""Processes the light curve for a Kepler TCE and returns processed data
Args:
tce: Row of the input TCE table.
Returns:
Processed TCE data at each stage (flattening, folding, binning).
Raises:
IOError: If the light curve files for this Kepler ID cannot be found.
"""
# R... | f20e62b48828c7c4d9fac8697035f058f48f5799 | 24,100 |
def _build_kwic(docs, search_tokens, context_size, match_type, ignore_case, glob_method, inverse,
highlight_keyword=None, with_metadata=False, with_window_indices=False,
only_token_masks=False):
"""
Helper function to build keywords-in-context (KWIC) results from documents `docs`... | d6252c716831bf51342f06aaab343d0f88f6811d | 24,101 |
from datetime import datetime
import pytz
import logging
def filter_records(records,
arns_to_filter_for=None,
from_date=datetime.datetime(1970, 1, 1, tzinfo=pytz.utc),
to_date=datetime.datetime.now(tz=pytz.utc)):
"""Filter records so they match the given co... | 6a3f14e577cef4a2a883781f50d3c695e11f8c82 | 24,103 |
from typing import Tuple
from typing import Dict
from operator import inv
def generate_prob_matrix(A: int, D: int)\
-> Tuple[Dict[Tuple[int, int], int], Dict[Tuple[int, int], int], np.ndarray]:
"""Generate the probability outcome matrix"""
transient_state, absorbing_state = generate_states(A, D)
t... | 00f8074f19436fcd9031af5c553f8b307b6008ba | 24,104 |
import threading
import time
def _prepare_func(app_id, run_id, train_fn, args_dict, local_logdir):
"""
Args:
app_id:
run_id:
train_fn:
args_dict:
local_logdir:
Returns:
"""
def _wrapper_fun(iter):
"""
Args:
iter:
Retu... | 93ec02a10e9dedd00787e302db5cca716e2d4f37 | 24,105 |
import re
def convert_camel_to_snake(string, remove_non_alphanumeric=True):
"""
converts CamelCase to snake_case
:type string: str
:rtype: str
"""
if remove_non_alphanumeric:
string = remove_non_alpha(string, replace_with='_', keep_underscore=True)
s1 = _first_cap_re.sub(r'\1_\2', string)
result = _all_cap... | ed21ab5a58b08f2bc8b00d9b1cd5aa812b4e4148 | 24,106 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.