content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def randomize_quaternion_along_z(
mujoco_simulation: RearrangeSimulationInterface, random_state: RandomState
):
""" Rotate goal along z axis and return the rotated quat of the goal """
quat = _random_quat_along_z(mujoco_simulation.num_objects, random_state)
return rotation.quat_mul(quat, mujoco_simulati... | 9bc29520ca8f00debf819bf4dee55cce43bb8483 | 1,370 |
from io import StringIO
import json
def init(model):
"""
Initialize the server. Loads pyfunc model from the path.
"""
app = flask.Flask(__name__)
@app.route("/ping", methods=["GET"])
def ping(): # pylint: disable=unused-variable
"""
Determine if the container is working and h... | 525ffd789be94c1e70d987c4b64c8876d9260d72 | 1,371 |
def sample_tag(user, name='Comedy'):
"""Creates a sample Tag"""
return Tag.objects.create(user=user, name=name) | 2288d8344fcf931a9e932b46db9a65275425b427 | 1,372 |
from typing import Tuple
def _middle_point(p1: np.ndarray, p2: np.ndarray) -> Tuple[int, int]:
"""Returns the middle point (x,y) between two points
Arguments:
p1 (np.ndarray): First point
p2 (np.ndarray): Second point
"""
return tuple((p1 + p2) // 2) | dcca1c1eeb0fea8c9adebfc9cccca94cb7ab7a43 | 1,373 |
def filter_with_prefixes(value, prefixes):
"""
Returns true if at least one of the prefixes exists in the value.
Arguments:
value -- string to validate
prefixes -- list of string prefixes to validate at the beginning of the value
"""
for prefix in prefixes:
if value.startswith(prefi... | 56b9bacedaa7aa06023e29d45809f6e9661ee483 | 1,374 |
def is_seq(x, step=1):
"""Checks if the elements in a list-like object are increasing by step
Parameters
----------
x: list-like
step
Returns
-------
True if elements increase by step, else false and the index at which the condition is violated.
"""
for i in range(1, len(x)):
... | 032e12b86aa7e50dfba2ddccd244475f58d70b29 | 1,376 |
def delete_editor(userid):
"""
:param userid: a string representing the user's UW NetID
:return: True if request is successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if the request failed or an error code has been returned.
"""
url = _make_del_account... | 494211289faa4b16206b9687d6f7f94a8adc992a | 1,378 |
def ecio_quality_rating(value, unit):
"""
ECIO (Ec/Io) - Energy to Interference Ratio (3G, CDMA/UMTS/EV-DO)
"""
if unit != "dBm":
raise ValueError("Unsupported unit '{:}'".format(unit))
rating = 0
if value > -2:
rating = 4
elif -2 >= value > -5:
rating = 3
elif ... | 4cc21012464b8476d026f9dfbc35b8b1ea3c2d85 | 1,379 |
def normalizeFilename(filename):
"""normalizeFilename(filename)
Replace characters that are illegal in the Window's environment"""
res = filename
rep = { "*":"_", "\"":"\'", "/":" per ", "\\":"_", ",":"_", "|":"_", ":":";" }
for frm, to in rep.iteritems():
res = res.replace(frm, to)
ret... | 84239d7d4fd982b27a4e0f5d20f615f3f288af85 | 1,380 |
def __virtual__():
"""
Check if macOS and PyObjC is available
"""
if not salt.utils.platform.is_darwin():
return (False, 'module: mac_wifi only available on macOS.')
if not PYOBJC:
return (False, 'PyObjC not available.')
return __virtualname__ | 46d21f3546234984890ff147a300ee8241b69ae6 | 1,381 |
def rearrange_kernel(kernel, data_shape=None):
"""Rearrange kernel
This method rearanges the input kernel elements for vector multiplication.
The input kernel is padded with zeroes to match the image size.
Parameters
----------
kernel : np.ndarray
Input kernel array
data_shape : tu... | a5117d56f520c3a8f79ba2baea68d0b4d516158c | 1,382 |
def exportTable(request_id, params):
"""Starts a table export task running.
This is a low-level method. The higher-level ee.batch.Export.table object
is generally preferred for initiating table exports.
Args:
request_id (string): A unique ID for the task, from newTaskId. If you are
using the cloud A... | e4dd22264c070315351bc3dd51061bc4948c9bda | 1,383 |
def template_check(value):
"""Check if a rendered template string equals true.
If value is not a string, return value as is.
"""
if isinstance(value, str):
return value.lower() == "true"
return value | 3733db5c107068e815bac079fdef1a450f7acdc9 | 1,385 |
def return_npc(mcc, mnc):
"""
Format MCC and MNC into a NPC.
:param mcc: Country code.
:type mcc: int
:param mnc: Network code.
:type mnc: int
"""
return "{0}{1}30".format(str(mcc).zfill(3), str(mnc).zfill(3)) | 0ae5952fd7b026c2c90c72046f63ca4d08dacf06 | 1,386 |
import math
def class_to_bps(bw_cls):
"""
Convert a SIBRA bandwidth class to bps (Bits Per Second). Class 0 is a
special case, and is mapped to 0bps.
:param float bw_cls: SIBRA bandwidth class.
:returns: Kbps of bandwidth class
:rtype: float
"""
if bw_cls == 0:
return 0
bw... | 02d0b4fbf5655318e6807bdd8c41fdfb59010ba4 | 1,387 |
def _get_capacity():
"""Return constant values for dam level capacities.
Storage capacity values are measured in million cubic metres
i.e. Megalitres or Ml.
Source: https://en.wikipedia.org/wiki/Western_Cape_Water_Supply_System
@return capacity: Dict object containing maximum capacities of Wester... | 01d1a5e7470d578296e285e2e00cd44eaf00d15c | 1,388 |
def login_required(f):
"""
Decorator to use if a view needs to be protected by a login.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not 'username' in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function | d09069e65c64c06885708b10ca70f5f319389c7a | 1,389 |
def test_bare_except() -> None:
"""Bare `except` to handle any uncaught exceptions."""
def reciprocal_of(value: float) -> float:
try:
return 1 / value
except ZeroDivisionError:
raise
except:
raise
pytest.raises(TypeError, reciprocal_of, "a") | 8cce2efcd850ca546f092ec0988d69e8d576e500 | 1,390 |
def _get_image_blob(im):
"""Converts an image into a network input.
Arguments:
im (ndarray): a color image in BGR order
Returns:
blob (ndarray): a data blob holding an image pyramid
im_scale_factors (list): list of image scales (relative to im) used
in the image pyramid... | 61a10be02f258680b0c103398deee9d72870035b | 1,391 |
def toiter(x):
"""Convert to iterable. If input is iterable, returns it. Otherwise returns it in a list.
Useful when you want to iterate over something (like in a for loop),
and you don't want to have to do type checking or handle exceptions
when it isn't a sequence"""
if iterable(x):
return... | ef9716b65893ca614dd53cc6fa7ae17b6cce2a35 | 1,393 |
def ap_date(value):
"""
Converts a date string in m/d/yyyy format into AP style.
"""
if not value:
return ''
bits = unicode(value).split('/')
month, day, year = bits
output = AP_MONTHS[int(month) - 1]
output += ' ' + unicode(int(day))
output += ', ' + year
return outp... | 4ca1dab0775141f548946072e0208502d54bc784 | 1,394 |
def dump_sql(fp, query: str, encoding="utf8"):
"""
Write a given query into a file path.
"""
query = ljustify_sql(query)
for line in query:
fp.write(bytes(line, encoding=encoding))
return fp | b6a847dbfccb17c0cf7bd3590eee69783d83030c | 1,395 |
def make_design_matrix(stim, d=25):
"""Create time-lag design matrix from stimulus intensity vector.
Args:
stim (1D array): Stimulus intensity at each time point.
d (number): Number of time lags to use.
Returns
X (2D array): GLM design matrix with shape T, d
"""
padded_stim = np.concatenate([np... | 5b1759076b9e0f44ea338a4e72d2f1a76d3ccc3b | 1,396 |
def _fit_subpixel_2d(image, coord, radius, voxel_size_yx, psf_yx):
"""Fit a gaussian in a 2-d image.
Parameters
----------
image : np.ndarray
Image with shape (y, x).
coord : np.ndarray, np.int64
Coordinate of the spot detected, with shape (2,). One coordinate per
dimension ... | 6e05b395ae93319de599283fe041f681b5ee039c | 1,397 |
def density(sisal,temp,pres,salt=None,dliq=None,chkvals=False,
chktol=_CHKTOL,salt0=None,dliq0=None,chkbnd=False,useext=False,
mathargs=None):
"""Calculate sea-ice total density.
Calculate the total density of a sea-ice parcel.
:arg float sisal: Total sea-ice salinity in kg/kg.
:arg fl... | 40a365ea0d4c79813394790ef3df6c8eb21727b8 | 1,398 |
def prod_non_zero_diag(x):
"""Compute product of nonzero elements from matrix diagonal.
input:
x -- 2-d numpy array
output:
product -- integer number
Not vectorized implementation.
"""
n = len(x)
m = len(x[0])
res = 1
for i in range(min(n, m)):
if (x[i][i] != 0):
... | 13e9f6cc9ea22e7901d454b23297a2e9c5da3a3a | 1,399 |
def LoadSparse(inputfile, verbose=False):
"""Loads a sparse matrix stored as npz file to its dense represent."""
npzfile = np.load(inputfile)
mat = sp.csr_matrix((npzfile['data'], npzfile['indices'],
npzfile['indptr']),
shape=tuple(list(npz... | 80dfeb5c48ab2c3905b78ba37226eb98fde5de45 | 1,400 |
def chain_decomposition(G, root=None):
"""Return the chain decomposition of a graph.
The *chain decomposition* of a graph with respect a depth-first
search tree is a set of cycles or paths derived from the set of
fundamental cycles of the tree in the following manner. Consider
each fundamental cycl... | 603fffdd2530bbaf296bb628ec59ce0d7a9a8de2 | 1,402 |
def dup_lcm(f, g, K):
"""Computes polynomial LCM of `f` and `g` in `K[x]`. """
if K.has_Field or not K.is_Exact:
return dup_ff_lcm(f, g, K)
else:
return dup_rr_lcm(f, g, K) | f5b6a7f3d0aa7155bfffd03b3bcb3d01e716855c | 1,403 |
import urllib
import json
def add_tag_translation(request, tag_id, lang, text):
"""Adds a translation to the given Tag."""
tag = get_object_or_404(Tag, id=tag_id)
text = urllib.unquote(text)
data = {}
langs = tag.site.get_languages(lang)
if len(langs) == 0:
data['error'] = 'No languag... | 2fe49be5bee9b6b13104ed1465ea6c993db9eb51 | 1,404 |
def simpson(x, with_replacement=False):
"""For computing simpson index directly from counts (or frequencies, if with_replacement=True)
Parameters
----------
x :
with_replacement :
(Default value = False)
Returns
-------
"""
total = np.sum(x)
if with_repla... | 282de607ee722d95db830ca7185a2d3519dcb78f | 1,405 |
async def setup_automation(hass, device_id, trigger_type):
"""Set up an automation trigger for testing triggering."""
return await async_setup_component(
hass,
AUTOMATION_DOMAIN,
{
AUTOMATION_DOMAIN: [
{
"trigger": {
... | e06d8c38ccfb76b5c89d002407d400bf0135749b | 1,406 |
def generate_html_tutor_constraints(sai):
"""
Given an SAI, this finds a set of constraints for the SAI, so it don't
fire in nonsensical situations.
"""
constraints = set()
args = get_vars(sai)
# selection constraints, you can only select something that has an
# empty string value.
... | d6201e80574f766ae57609707bad8f617d908682 | 1,407 |
def info(email):
"""Information about a specific email."""
with db_session() as db:
user = db.query(User).filter(User.email == email).first()
if user:
return [user.email, user.api_key, user.grabs]
else:
return None | d9624f33f18dd507c2fceb4e7f917d9cd695dea9 | 1,410 |
import networkx
def TetrahedralGraph():
"""
Returns a tetrahedral graph (with 4 nodes).
A tetrahedron is a 4-sided triangular pyramid. The tetrahedral
graph corresponds to the connectivity of the vertices of the
tetrahedron. This graph is equivalent to a wheel graph with 4 nodes
and also a co... | b39014244ae2750b2e118d2b7cfe4b7d7cd55997 | 1,411 |
import logging
def build_resnet_v1(input_shape, depth, num_classes, pfac, use_frn=False,
use_internal_bias=True):
"""Builds ResNet v1.
Args:
input_shape: tf.Tensor.
depth: ResNet depth.
num_classes: Number of output classes.
pfac: priorfactory.PriorFactory class.
use_frn: ... | f72a48fcd0df9c7b3b2ea0c5c5db9d3dffad55b6 | 1,412 |
def lr_recover_l1(invecs, intensities, nonneg=True, **kwargs):
"""Computes the low-rank matrix reconstruction using l1-minimisation
.. math::
\min_Z \sum_i \vert \langle a_i| Z | a_i \rangle - y_i \vert \\
\mathrm{s.t.} Z \ge 0
where :math:`a_i` are the input vectors and :math:`y... | 6551f8e3ff146831d51d338c00c5f2e8b3d7acef | 1,413 |
import pickle
def start_view_data(trans_id):
"""
This method is used to execute query using asynchronous connection.
Args:
trans_id: unique transaction id
"""
limit = -1
# Check the transaction and connection status
status, error_msg, conn, trans_obj, session_obj = \
chec... | 0c4c5797578abc0623805d269043c6fb3c0512a9 | 1,415 |
def fft_resize(images, resize=False, new_size=None):
"""Function for applying DFT and resizing.
This function takes in an array of images, applies the 2-d fourier transform
and resizes them according to new_size, keeping the frequencies that overlap
between the two sizes.
Args:
images: a numpy a... | 64846e58fa8ad422b4668062b09458110feed7f5 | 1,416 |
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Sequential(nn.ReplicationPad2d(1), nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=0, groups=groups, bias=False, dilation=dilation)) | 4b23699e4766f341262499608680f5f1f2b6cd26 | 1,418 |
def get_inbound_layers_without_params(layer):
"""Return inbound layers.
Parameters
----------
layer: Keras.layers
A Keras layer.
Returns
-------
: list[Keras.layers]
List of inbound layers.
"""
return [layer for layer in get_inbound_layers(layer)
if n... | 9671b9277cb690dc54ffbcb35a4e22672b81748d | 1,419 |
def orders_matchresults(symbol, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
"""
:param symbol:
:param types: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param start_date:
:param end_date:
:param _from:
:param direct: 可选值{prev 向前... | 61121dc12bed75236622e45fb6c96b2595008e64 | 1,420 |
def precision(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positiv... | 3979236388aecaa32452958bf344632a1c781181 | 1,421 |
def _is_grpc_unary_method(attr):
"""Check if attribute is a grpc method that returns unary."""
return isinstance(attr, (grpc.UnaryUnaryMultiCallable, grpc.StreamUnaryMultiCallable)) | cb20221038ea2754d259fca22941ba91944aceb8 | 1,422 |
def gridcorner(
D,
xyz,
labels=None,
projection="max_slice",
max_n_ticks=4,
factor=2,
whspace=0.05,
showDvals=True,
lines=None,
label_offset=0.4,
**kwargs
):
"""Generate a grid corner plot
Parameters
----------
D: array_like
N-dimensional data to plot... | 37c929a5b323deb1968ba6504113141bfc8ee830 | 1,423 |
from ._standard_montage_utils import _str_names, _str
def read_dig_hpts(fname, unit='mm'):
"""Read historical .hpts mne-c files.
Parameters
----------
fname : str
The filepath of .hpts file.
unit : 'm' | 'cm' | 'mm'
Unit of the positions. Defaults to 'mm'.
Returns
-------... | e5159900f5eb6e846f4028a237884fb0f85323f3 | 1,424 |
def GetTaskAttr( fname, attrName, defaultVal = None ):
"""Return the specified attribute of a task, or the specified default value if the task does not have this attribute."""
for line in SlurpFile( fname ).rstrip('\n').split('\n'):
arg, val = line.split('\t')
if arg == attrName: return coerceVa... | ab4e8ca8286e94895afe78353b98283b7ab7e890 | 1,425 |
def print_board(white, black):
"""Produce GnuGO like output to verify board position.
Args:
white (np.array): array with 1's for white
black (np.array): array with 1's for black
Returns:
str: gnugo like output (without legend)
"""
s = ''
for x in xrange(19):
for... | 5d6143ffd1964cbe41d7d9e0a9c9b7696e7d5008 | 1,426 |
from typing import List
def get_repositories_containing_graph(name: str) -> List[str]:
"""Returns the repositories containing a graph with the given graph name.
Parameters
----------------------------
name: str,
The name of the graph to retrieve.
Returns
----------------------------
... | 16d2135e1d68fe699fa68b7786f7363dd06e5ab5 | 1,427 |
def build_query(dct):
"""Build SQL with '?' and value tuples from clause dictionary"""
if (dct is not {}):
str_clauses = ''
tpl_values = ()
bln_start = True
#print dct
for str_field, dct_op_val in dct.iteritems():
if (str_field is not None):
if... | ac49014c8e629d2fdc12472f2b8b345cbee8ce18 | 1,428 |
def load_secrets(fn=".env", prefix="DJANGO_ENV_", **kwargs):
"""Load a list of configuration variables.
Return a dictionary of configuration variables, as loaded from a
configuration file or the environment. Values passed in as
``args`` or as the value in ``kwargs`` will be used as the
configurati... | 6f18ba641e4c23383e47c7422efaaa990af4cc6a | 1,429 |
import itertools
def dependency_chain(pkgname):
"""Return an ordered list of dependencies for a package"""
depends = recurse_depends(pkgname)
return set(list(depends.keys()) + list(itertools.chain.from_iterable(depends.values()))) | 208226f2d771f4fa278a0295997fc53df55caa8f | 1,430 |
from typing import Callable
import click
def with_input(func: Callable) -> Callable:
"""
Attaches a "source" argument to the command.
"""
return click.argument(
"source", type=click.Path(exists=True), required=True
)(func) | 3117f183ac4e4d459a718b59fc9a3ba00b36e291 | 1,431 |
def check_loop_validity(inst_list):
""" Given a list of instructions, check whether they can form a valid loop.
This means, checking for anything that could create an infinite loop.
We are also disallowing double loops right now"""
for i, c in enumerate(inst_list):
if c in [5, 6, 16, 25]:
... | a58923e014947d1406165a831a57b73fcb9ab226 | 1,432 |
def target_channel_id_name_list(
conversations_list: list=None, including_archived: bool=False):
"""extract targeted channels id list from conversations_list response.
Returns:
id_list, name_list
"""
id_list = []
name_list = []
for ch in conversations_list:
if includi... | be2ec76242367a170deac2e577ec90c435046ef9 | 1,433 |
def NETWORKDAYS(*args) -> Function:
"""
Returns the number of net working days between two provided days.
Learn more: https//support.google.com/docs/answer/3092979
"""
return Function("NETWORKDAYS", args) | f93f34ef173a6f3f552062f33b599988ea63cb8a | 1,434 |
def calc_high_outlier(values) -> float:
"""Calculates the high outlier from a pandas Series"""
q1, q3 = [values.quantile(x, 'midpoint') for x in (0.25, 0.75)]
return q3 + 1.5 * (q3 - q1) | 8ee929aec1cb4af9a90d04893f8f94444d00ad22 | 1,435 |
def get_sql_delete_by_ids(table: str, ids_length: int):
"""
获取添加数据的字符串
:param table:
:return:
"""
# 校验数据
if not table:
raise ParamError(f"table 参数错误:table={table}")
if not ids_length or not isinstance(ids_length, int):
raise ParamError(f"ids_length 参数错误:ids_length={ids_le... | f9980c92f5fa1064a99823655be4ea8aed619db3 | 1,436 |
def Float(request):
"""
A simple form with a single integer field
"""
schema = schemaish.Structure()
schema.add('myFloatField', schemaish.Float())
form = formish.Form(schema, 'form')
return form | 18ddcaa697dca96ea321a1aba51d4d2fb0fed47c | 1,437 |
def pca(X):
"""
Returns the eigenvectors U, the eigenvalues (on diagonal) in S.
Args:
X: array(# of training examples, n)
Returns:
U: array(n, n)
S: array(n, n)
"""
# Get some useful values
m, n, _, _ = X.shape
# Init U and S.
U = np.zeros(n)
S = np.z... | cf6304615b3d75b730235f238822c347342a4cbd | 1,438 |
import imp
def read_py_version(script_name, search_path):
"""Read the version of a script from a python file"""
file, pathname, desc = imp.find_module(script_name, [search_path])
try:
new_module = imp.load_module(script_name, file, pathname, desc)
if hasattr(new_module.SCRIPT, "version"):
... | b69d9ff9f6f718c418fac1b0cd77355d8d4ffd1d | 1,439 |
def post_check_variable(team_id, source_id, check_id):
"""
.. :quickref: POST; Lorem ipsum."""
if not TeamPermission.is_manager_or_editor(team_id):
abort(403)
payload = get_payload()
payload.update({"team_id": team_id, "source_id": source_id, "check_id": check_id})
variable = VariableC... | 5c187a5cfec19409c155068c6c8212217adb3632 | 1,440 |
import re
def diff_re(a, b, fromfile='', tofile='',
fromfiledate='', tofiledate='', n=3, lineterm='\n'):
"""
A simple "diff" of two sets of lines when the expected lines
are regular expressions. This is a really dumb thing that
just compares each line in turn, so it doesn't look for
c... | 802dd3287502c3d3fe85242ba51043e4b5769cd5 | 1,441 |
import pickle
def storeAgent(sess, agentObj):
"""
INPUT : session object
OUTPUT : Updated agent Onject
DESCRIPTION : Updates the agent object in that session
"""
currAgents = getCurrGen(sess)
lock(sess)
try:
if(sess.mode == 'SAFE'):
tpfp = open(GA_U... | 57b74d722141f008332a8fa129018f0b72fcc26d | 1,442 |
def info(device):
"""
Get filesystem geometry information.
CLI Example:
.. code-block:: bash
salt '*' xfs.info /dev/sda1
"""
out = __salt__["cmd.run_all"]("xfs_info {}".format(device))
if out.get("stderr"):
raise CommandExecutionError(out["stderr"].replace("xfs_info:", "")... | 96b1f91c921f607c0e348b8dd4355699fc12c5f0 | 1,443 |
from typing import Union
from typing import Dict
from typing import Tuple
from typing import Any
def serialize_framework_build_config(dict_: Union[Dict[str, str], str]) -> Tuple[Any, ...]:
"""Serialize a dict to a hashable tuple.
Parameters
----------
dict_: Dict[str, str]
Returns
-------
... | 365b413ff21bf4fb7f5d153dbe74801ee125108f | 1,444 |
def _check_columns(data: pd.DataFrame,
features: list) -> pd.DataFrame:
"""
Given a dataframe and a list of expected features, print missing columns and return new dataframe
with only valid features
Parameters
-----------
data: Pandas.DataFrame
DataFrame for checking... | ad0c0eb17b7afeaad7505d69f77336820607d77b | 1,445 |
def get_confidence(imgfilename):
"""
1003_c60.jpg -> c6
"""
if not imgfilename:
return ''
return 'c' + imgfilename.split('/')[-1][0:1] | 7c98f2abd2119b41d7e2501823985a894da5a1a1 | 1,446 |
def get_connection(hostname: str,
port: int,
username: str,
password: str):
"""
DBへのコネクションを取得します。
Returns:
Connection: コネクション
"""
return pymysql.connect(
host=hostname,
port=port,
user=username,
passwo... | c2036f9b5ea2e69e6d0cd94fdcf0aa55e69d5d6f | 1,447 |
def get_alleles_existing_alleleinterpretation(
session, allele_filter, user=None, page=None, per_page=None
):
"""
Returns allele_ids that has connected AlleleInterpretations,
given allele_filter from argument.
Supports pagination.
"""
# Apply filter using Allele table as base
allele_id... | d7b42ac327f284d5905c5dc5b6893cbf0c18714e | 1,448 |
import logging
def _get_session(db_uri, use_batch_mode=True, echo=False):
"""Helper to get an SQLAlchemy DB session"""
# `use_batch_mode` is experimental currently, but needed for `executemany`
#engine = create_engine(db_uri, use_batch_mode=use_batch_mode, echo=echo)
engine = create_engine(db_uri, ech... | d9b3455b601c86face0683ac0d8f3d8763180093 | 1,449 |
def has_extension(experiment: Experiment, name: str) -> bool:
"""
Check if an extension is declared in this experiment.
"""
return get_extension(experiment, name) is not None | 6bf7630634be8802364e1a2fa38e58df523f82d9 | 1,450 |
def min_max_median(lst):
""" a function that takes a simple list of numbers lst as a parameter and returns a list with the min, max, and the median of lst. """
s = sorted(lst)
n = len(s)
return [ s[0], s[-1], s[n//2] if n % 2 == 1 else (s[n//2 - 1] + s[n//2]) / 2] | 59b1ceef5796d77cc039a42593ddb3d1d2244bd7 | 1,452 |
import copy
def assign_read_kmers_to_contigs_new(kmer_ii, ambiguous_kmer_counts, unambiguous_contig_counts, contig_abundances):
"""
Assign ambiguous read k-mers based on contig averages counts.
"""
contig_counts = copy.deepcopy(unambiguous_contig_counts)
contig_location_tuples = []
total_abu... | a2d7a133183b7d020f461989065c132fb87bf336 | 1,454 |
def cremi_scores(seg, gt, border_threshold=None, return_all=True):
"""
Compute the cremi scores (Average of adapted rand error, vi-split, vi-merge)
Parameters
----------
seg: np.ndarray - the candidate segmentation
gt: np.ndarray - the groundtruth
border_threshold: value by which the border... | 9781eeb38885fe5efc3e052a15e418e39acdcc3c | 1,455 |
def sign_transaction(transaction_dict, private_key) -> SignedTransaction:
"""
Sign a (non-staking) transaction dictionary with the specified private key
Parameters
----------
transaction_dict: :obj:`dict` with the following keys
nonce: :obj:`int` Transaction nonce
gasPrice: :obj:`in... | 735de56f1a2b9557cc09b9e589586eb92196936c | 1,456 |
def integralHesapla(denklem):
"""
Polinom kullanarak integral hesaplar.
:param denklem: İntegrali hesaplanacak polinom.
"""
a,b=5,len(anaVeriler)
deltax = 0.1
integral = 0
n = int((b - a) / deltax)
for i in range(n):
integral += deltax * (denklem.subs({x:a}) + denklem.subs({x... | 01bb7ebc5b678dc255e311c03c76415b0ac6f2db | 1,457 |
def fmt(text,*args,**kwargs):
"""
String formatting made easy
text - pattern
Examples
fmt("The is one = %ld", 1)
fmt("The is text = %s", 1.3)
fmt("Using keywords: one=%(one)d, two=%(two)d", two=2, one=1)
"""
return _fmt(text,args,kwargs) | a03a367d116bcde83bd0ff41ca8eb181af4c8aed | 1,458 |
def value_to_class(v):
"""
Return the label of the pixel patch, by comparing the ratio of foreground
to FOREGROUND_THRESHOLD
Input:
patch (numpy.ndarray): patch of a groundtruth image
size:(PATCH_SIZE, PATCH_SIZE)
Output:
the label of the patch:
... | fe50615d7ed3567bb3e7de8987ce07f5736a0a5c | 1,459 |
def mc(cfg):
""" Return the MC (multi-corpus) AAI model, trained on the dysarthric and cross corpora.
3 BLSTM layers, and two single linear regression output layers to obtain articulatory trajectories corresponding to each corpus.
Parameters
----------
cfg: main.Configuration
user configur... | e93ca764185b9a2bd60929e9cf50574432bcf97f | 1,461 |
from typing import Callable
def gradient_dxyz(fxyz: tf.Tensor, fn: Callable) -> tf.Tensor:
"""
Function to calculate gradients on x,y,z-axis of a tensor using central finite difference.
It calculates the gradient along x, y, z separately then stack them together
:param fxyz: shape = (..., 3)
:par... | cc6e4660a2bfff22d04a2d05e3ff6b1dd7e5846a | 1,462 |
import multiprocessing
def get_chunk_range():
"""
Get the range of partitions to try.
"""
n_chunks = multiprocessing.cpu_count()
if n_chunks > 128:
raise NotImplementedError('Currently we consider the num. procs in machine to '
'be < 128')
chunk_... | 4de86cbeba03550d5bcd7bae68c054495136a398 | 1,463 |
def train(data_base_path, output_dir, label_vocab_path, hparams_set_name,
train_fold, eval_fold):
"""Constructs trains, and evaluates a model on the given input data.
Args:
data_base_path: str. Directory path containing tfrecords named like "train",
"dev" and "test"
output_dir: str. Path to... | 7df17924a7be5ec07009658a7aaf25e79f8f4663 | 1,466 |
def _enzyme_path_to_sequence(path, graph, enzymes_sites):
"""Converts a path of successive enzymes into a sequence."""
return "".join(
[enzymes_sites[path[0]]]
+ [graph[(n1, n2)]["diff"] for n1, n2 in zip(path, path[1:])]
) | a3de9de5dc37df641e36d09d07b49c402fa17fd1 | 1,468 |
def profile_to_section(profile_name):
"""Converts a profile name to a section header to be used in the config."""
if any(c in _WHITESPACE for c in profile_name):
profile_name = shlex_quote(profile_name)
return 'profile %s' % profile_name | c9c50556409c4840c7f530e8645b52b60b3f8fa7 | 1,469 |
def BytesFromFile(filename: str) -> ByteList:
"""Read the EDID from binary blob form into list form.
Args:
filename: The name of the binary blob.
Returns:
The list of bytes that make up the EDID.
"""
with open(filename, "rb") as f:
chunk = f.read()
return [int(x) for x ... | bfb899c2d1114f43ccbe4b317496111372e4bf2c | 1,470 |
def array_to_patches(arr, patch_shape=(3,3,3), extraction_step=1, normalization=False):
#Make use of skleanr function extract_patches
#https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/feature_extraction/image.py
"""Extracts patches of any n-dimensional array in place using strides.
Given an n-d... | 2c8e3660c0a9d67794e3d0e869ee87ea690bedc2 | 1,471 |
from typing import Optional
from typing import Tuple
def directory_select(message: str, default: Optional[str] = None, cli_flag: Optional[str] = None,
force_interactive: bool = False) -> Tuple[int, str]:
"""Display a directory selection screen.
:param str message: prompt to give the user... | 093a29a03c00c21b5612f78ac4548b0c6db6974c | 1,472 |
def trade_from_kraken(kraken_trade):
"""Turn a kraken trade returned from kraken trade history to our common trade
history format"""
currency_pair = kraken_to_world_pair(kraken_trade['pair'])
quote_currency = get_pair_position(currency_pair, 'second')
return Trade(
# Kraken timestamps have f... | 6b18a1d396605450f1af6fc1cfb2231852c964a9 | 1,473 |
def _create_instancer_mesh(positions: np.ndarray, name="mesh_points", *, bpy):
"""Create mesh with where each point is a pseudo face
(three vertices at the same position.
"""
assert positions.ndim == 2
assert positions.shape[1] == 3
if name in bpy.data.meshes:
raise RuntimeError("Mesh '... | d60cd53cd6b00e0c17df8ee33be38f48aafebe8e | 1,474 |
def bound_to_nitorch(bound, as_type='str'):
"""Convert boundary type to niTorch's convention.
Parameters
----------
bound : [list of] str or bound_like
Boundary condition in any convention
as_type : {'str', 'enum', 'int'}, default='str'
Return BoundType or int rather than str
R... | 9767dbc3693fd105fed9d89b15340d2ba4d1c5dd | 1,475 |
def Amp(f: jnp.ndarray, theta: jnp.ndarray) -> jnp.ndarray:
"""
Computes the Taylor F2 Frequency domain strain waveform with non-standard
spin induced quadrupoole moment for object two.
Note that this waveform assumes object 1 is a BH and therefore uses the
chi * M_total relation to find C
Not... | d618b760d8be0fe9e597eb3a2deefec455489349 | 1,477 |
def spol(f, g):
"""
Compute the S-polynomial of f and g.
INPUT:
- ``f, g`` -- polynomials
OUTPUT: the S-polynomial of f and g
EXAMPLES::
sage: R.<x,y,z> = PolynomialRing(QQ)
sage: from sage.rings.polynomial.toy_buchberger import spol
sage: spol(x^2 - z - 1, z^2 - y ... | fff84c00b85fda2f4ebfc3e8bbf1caa68b206490 | 1,479 |
import functools
def evaluate_baselines(experiment,
seed,
num_pairs,
samples_per_pair,
loop_size=None):
"""Helper function to evaluate the set of baselines."""
gumbel_max_joint_fn = functools.partial(
coupling_util.j... | 555ea777ff1f694fd2ed2846f1e8cb1ca01cccd7 | 1,480 |
def generate_template_mask(protein):
"""Generate template mask."""
protein['template_mask'] = np.ones(shape_list(protein['template_domain_names']),
dtype=np.float32)
return protein | f92304249db66b4d7a28336c60c0fd4ce803da0f | 1,481 |
from scipy.interpolate import InterpolatedUnivariateSpline as spline
def minimal_rotation(R, t, iterations=2):
"""Adjust frame so that there is no rotation about z' axis
The output of this function is a frame that rotates the z axis onto the same z' axis as the
input frame, but with minimal rotation abou... | a1bd333ec9a01825a5355f47a80e14e37d510fae | 1,482 |
def get_info(api_key: hug.types.text, hug_timer=20):
"""Return 'getinfo' data from the Gridcoin Research client!"""
if (api_key == api_auth_key):
# Valid API Key!
response = request_json("getinfo", None)
if (response == None):
return {'success': False, 'api_key': True}
else:
return {'success': True, 'ap... | ff4eb5df57cf9faa0464040d9f51040742a8f549 | 1,483 |
def get_output_col_names(perils, factors):
"""Column names of the output data frame that contains `perils` and `factors`"""
return (
PCon.RAW_STRUCT['stem']['col_names'] +
[per + PCon.OUTPUT_DEFAULTS['pf_sep'] + fac
for per, fac in pd.MultiIndex.from_product(
[perils, [PCon... | ce455a87aeba1f7d4f02b7f1b0e25c4d3eafdd0f | 1,484 |
def _get_real_path(workspace_path):
"""Converts the given workspace path into an absolute path.
A tuple of a real path and an error is returned. In this tuple, either
the real path or error is present. The error is present in the returned tuple
either if no workspace dir is given or the generated real path is... | 75e0d08b288cc947987b96787f368daeef586612 | 1,485 |
import string
def simple_caesar(txt, rot=7):
"""Caesar cipher through ASCII manipulation, lowercase only."""
alphabet = string.ascii_lowercase # pick alphabet
shifted_alphabet = alphabet[rot:] + alphabet[:rot] # shift it
table = str.maketrans(alphabet, shifted_alphabet) # create m... | eb8d86d37d8a8902663ff68e095b3b822225859c | 1,486 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.