content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _exists(name: str):
"""
Checks if a docker instance exists.
:param name: Instance name.
:returns: True if exists. False otherwise.
"""
cs = client.containers.list(filters={'name': name}, all=True)
return len(cs) > 0 | 0ec261e3510ddff603ef250bf5b5c5430a52d2f7 | 62,018 |
def op_lag_fire(
dataset,
model,
split_ratio,
lag_range=[
2,
168],
step_range=[
1,
25],
wind_range: list = [
0.5,
20],
shift_range: list = [
-72,
72],
roll_range: list = [
24,
240],damp_surface='s... | 0ee06c1f8d1bc30e9d5d81fd24ca6eca51dca35c | 62,019 |
import math
def all_frequency_based_dissim_for_modes(mode, metamodes):
"""
My own frequency-based dissimilarity function for clustering of modes
"""
list_dissim = []
# mode.freq[i] is a set of frequencies for all values of attribute i in the original cluster of this mode
# metamode.freq[i]
... | fc113cf8fc5ff8d35a4d66c8f26790fbae50c5c6 | 62,020 |
def get_spc_run_path(run_prefix, spc_info):
""" create species run path
"""
spc_run_fs = autofile.fs.species(run_prefix)
spc_run_fs.leaf.create(spc_info)
spc_run_path = spc_run_fs.leaf.path(spc_info)
return spc_run_path | 7d17575c30a02a56758d7fbeb89a040468ca2e58 | 62,021 |
def print_xm_info(xm_dict, name_re):
"""Print a dictionary of xmethods."""
def get_status_string(m):
if not m.enabled:
return " [disabled]"
else:
return ""
if not xm_dict:
return
for locus_str in xm_dict:
if not xm_dict[locus_str]:
conti... | e2564a5fcb7dc435c3ba1fa71fe82532d2b5083e | 62,022 |
def format_multitask_preds(preds):
"""
Input format: list of dicts (one per task, named with task_name), each having a
'predictions' list containing dictionaries that represent predictions for each sample.
Prediction score is represented by the field {task_name}_score in each of those dicts.
... | 470b23f6a5cc6b8e48ce0becfafd62104e016de8 | 62,023 |
def filter_queryset_metadata_dimension_time(queryset, time_min: str, time_max: str):
""" Filters a given REST framework queryset by a time_min and time_max boundary.
Only keeps the element which can be found in this temporal span.
Args:
queryset: A queryset containing elements
time_min (st... | f76dff18985e5664cbf6a3e7798fec8ec1dcd991 | 62,024 |
def CDLENGULFING(df):
"""
函数名:CDLENGULFING
名称:Engulfing Pattern 吞噬模式
简介:两日K线模式,分多头吞噬和空头吞噬,以多头吞噬为例,第一日为阴线,第二日阳线,第一日的开盘价和收盘价在第二日开盘价收盘价之内,但不能完全相同。
python API
integer=CDLENGULFING(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low = df['low']
close... | 425bff3b4f22955be62d1cdbaf625af87d6c5f1f | 62,025 |
def bot():
"""Respond with the output of the webhook handler."""
payload = request.form['payload']
signature = request.headers['SIGNATURE']
return webhook_handler(payload, signature) | 77c78d2c20821532096cc6a0bb3f4d54f11a3840 | 62,026 |
def msp(items):
"""Yield the permutations of `items`
items is either a list of integers representing the actual items or a list of hashable items.
The output are the unique permutations of the items.
Parameters
----------
items : sequence
Yields
-------
list
permutation of... | a91f2b80997b73cf7dbcbec88a923f855e117c26 | 62,027 |
def get_emissions(scenario_id, emission_dir=None, exclude_emissions=EXCLUDE_EMISSION):
"""Gets an emission file
Parameters:
----------
* scenario_id
* emission_dir
* exclude_emissions
Return:
------
* df pandas.DataFrame
Updates:
-------
* 2019-11-29:Add Column Filter ... | c3f4791b3e0bd97c7e24af0703fc3d370aa1b7e2 | 62,028 |
def createMatrixData(matrix):
"""
Converts the given matrix to an MObject.
:type matrix: om.MMatrix
:rtype: om.MObject
"""
# Check for redundancy
#
if isinstance(matrix, om.MObject):
return matrix
# Create new matrix data object
#
fnMatrixData = om.MFnMatrixData()... | dbc73059cb99459d2d579e79953e172e306bdebe | 62,029 |
def _NormalizeGitPath(path):
"""Given a |path| in a GIT repository (relative to its root), normalizes it so
it will match only that exact path in a sparse checkout.
"""
path = path.strip()
if not path.startswith('/'):
path = '/' + path
if not path.endswith('/'):
path += '/'
return path | f2781ac304d4c15e835fa174d4aa816ea920045f | 62,031 |
def calculate_rhs(flcond, normals):
"""
Calculate the RHS vector.
Parameters
----------
flcond : FlightConditions
Definition of the flight conditions.
normals : np.ndarray, shape (m, n, 3)
Array containing the normal vectors of all wing panels.
Returns
-------
rhs :... | 38fb90e42cb54f14b1c9f2fe1c397d3a68e7226f | 62,032 |
def send(to: str, subject: str, body: str):
"""Sends email
"""
from_email = Email(SENDER_EMAIL)
to_email = To(to)
content = Content("text/plain", body)
mail = Mail(from_email, to_email, subject, content)
response = sg.client.mail.send.post(request_body=mail.get())
return response | 100e6ed40c3b863e280c2259ef24d1033060e54f | 62,033 |
def broadcasted_matmul(A, B):
""" Matmul with fast broadcasting
Args:
A - [n, m]
B - [..., m, k]
Returns:
AB - [..., n, k]
"""
# [n, batch_size, k]
AB = tf.tensordot(A, B, axes=[[-1], [-2]])
# [batch_size, n, k]
rankAB = tf.rank(AB)
return tf.transpose(AB, perm=tf... | 75995f0f681dff203b7ce80dd9d8b03be8af3601 | 62,034 |
def is_scope_owner(scope, account, session=None):
""" check to see if account owns the scope.
:param scope: the scope to check.
:param account: the account to check.
:param session: The database session in use.
:returns: True or false
"""
return True if session.query(models.Scope).filter_b... | 5c7194e8f79bcc959c29b318916234f3d11a4fe9 | 62,035 |
def unpack(t, n):
"""Iterates over a promised sequence, the sequence should support random
access by :meth:`object.__getitem__`. Also the length of the sequence
should be known beforehand.
:param t: a sequence.
:param n: the length of the sequence.
:return: an unpackable generator for the eleme... | 4601cc51b2ae1015a31e8dc525756d8f590c2d8b | 62,036 |
def get_latest_post():
""" Laziness function to return the latest post. """
post_record = app.config['MDB'].posts.find_one(
{'published': True, 'published_on': {'$exists': True}},
sort=[('published_on', -1)]
)
return Post(_id=post_record['_id']) | 8053efa33491e93c1c1c07b736de66f5e21dbbe6 | 62,037 |
import re
def parse_value(expr):
"""Parse text into Python expression.
Args:
expr: String to be converted to Python expression (e.g. a list).
Returns:
Parsed Python expression.
"""
try:
return eval(expr)
except:
return eval(re.sub(r"\s+", ",", expr))
else... | f033e35b77bb3839dc6ccc05e1f96898a1a93c0c | 62,038 |
from typing import List
def pkg_asset_download_urls(url) -> List[str]:
"""
Example URL for release assets:
tarball: https://github.com/ICGC-TCGA-PanCancer/awesome-wfpkgs2/releases/download/fastqc-wf.0.2.0/fastqc-wf.0.2.0.tar.gz
json: https://github.com/ICGC-TCGA-PanCancer/awesome-wfpkgs2/release... | 2e66629efa07c00473f8bfb86f2db816211d24ed | 62,039 |
from colorednoise import powerlaw_psd_gaussian
def create_synthetic_noise_dataset(cfg):
"""
Creates a NoiseDataset instance of sounds with synthetic noise.
"""
betas = np.linspace(cfg['data.mix_synthetic_noise.min_beta'],
cfg['data.mix_synthetic_noise.max_beta'],
... | 5ff012efec4fb203ac74efd54c0a92cfc042c8c5 | 62,040 |
def _grid_out_property(field_name, docstring):
"""Create a GridOut property."""
def getter(self):
self._ensure_file()
# Protect against PHP-237
if field_name == 'length':
return self._file.get(field_name, 0)
return self._file.get(field_name, None)
docstring += "... | 71bb15738528142d4e410811ba021884ed5bb5ef | 62,041 |
def _get_db_subnet_group_arn(region: str, current_aws_account_id: str, db_subnet_group_name: str) -> str:
"""
Return an ARN for the DB subnet group name by concatenating the account name and region.
This is done to avoid another AWS API call since the describe_db_instances boto call does not return the DB s... | 4e04501adf0d006f6915f84b36a1c592879c54de | 62,043 |
import base64
def inchi2svg(inchi):
"""
Converts InChI to SVG vector graphic. This method accepts urlsafe_base64 encoded string containing single or
multiple InChIs. Size is the optional size of image in pixels (default value is 200 px).
Legend is optional label in the bottom of image.
cURL examples:
curl -X... | d0e7be785a3993cc238bef848d57998973b0f66a | 62,044 |
def create_stack_list(input_list):
"""
:param input_list: list (of page visits), duplicates are possible
:return: stack list: loops have been removed, consecutive duplicates also have been removed
"""
# print('#################')
# print(input_list)
stack_list = []
list_of_backward_jump... | d82d4b3825d2d034eb4aad4c39f8c0876fb82c86 | 62,045 |
from array import array
def getSimFeaturesFromFvals(fvals1, fvals2, meths):
"""Returns similarity features computed from the features for two objects.
'meths' is a list of (meth, weight), where meth is one of the following
methods for combining values 'a' and 'b' from the two input feature vectors:
... | 240a35aa2c14e6740ab7bfae6909ebeffa290520 | 62,046 |
from typing import Optional
import functools
def build_training_process(
model_fn: ModelFn,
*, # Callers pass below args by name.
loss_fn: LossFn,
metrics_fn: Optional[MetricsFn] = None,
server_optimizer_fn: OptimizerFn = functools.partial(
tf.keras.optimizers.SGD, 1.0),
client_optimi... | 3d34414b701796a80bde8a988098968a5205ade6 | 62,047 |
def get_system_uptime(device):
"""Return system uptime
Args:
device (obj): Device object
Returns:
str: Returns system uptime in seconds
"""
try:
out = device.parse('show system uptime')
except SchemaEmptyParserError:
return None
seconds = out.get('system-... | e5e2c58d9c28c94d437383ab38f501cccbd8c259 | 62,048 |
def issue_statuses(metric, last_measurement) -> list[dict]:
"""Return the metric's issue statuses."""
last_issue_statuses = last_measurement.get("issue_status", [])
return [status for status in last_issue_statuses if status["issue_id"] in metric.get("issue_ids", [])] | 23d2434727fa1b7a2e06fb621347270efd0627fc | 62,050 |
def TriStrip(p):
"""for backward compatibility only - TriStrip is no longer a type
please use the triStrip() method of the Polygon type instead"""
return p.triStrip() | 6e1f3019acfc1c18deba69d11f3d27ead9d07ca6 | 62,051 |
def change_value(x):
"""Change tags from number to word."""
value = tags_to_name.get(x)
if value is not None:
return value
return x | 0ad571a8244156439484ffa8b033ebf05302bd15 | 62,054 |
def heroUnit(
headline="",
tagline="",
buttonStyle="primary",
buttonText="",
buttonHref="#"
):
"""
*Generate a heroUnit - TBS style*
**Key Arguments:**
- ``headline`` -- the headline text
- ``tagline`` -- the tagline text for below the headline
... | 42826a5d63023b1a87062205255f80a2c85dd0f6 | 62,055 |
def _get_warmup_factor_at_iter(method: str, iter: int, warmup_iters: int,
warmup_factor: float) -> float:
"""
Return the learning rate warmup factor at a specific iteration.
See :paper:`ImageNet in 1h` for more details.
Args:
method (str): warmup method; either "co... | 5b9798cece3ad3f657dcaddbf795501b187f37de | 62,056 |
def direction_finder(direction, exchange):
"""
Uses the 'src' attribute of an "img" tag to find the
direction of flow. In the data source small arrow images
are used to show flow direction.
"""
if direction == "/uflujpot.nsf/f90.gif":
# flow from Argentina
return 1
elif dire... | 076f80729e34c472a8a12aac15007ed3b2a82eea | 62,057 |
from typing import Optional
from typing import List
def get_tests_action(
file_set_producer: Optional[IFileSetProducer],
commands: Optional[List[str]] = None,
stage_name: Optional[str] = "Tests",
) -> ShellStep:
"""
Return shell script action that runs tests.
Parameters
----------
sco... | 6cea2aeabb59633b10867b1220aec4159be2bd45 | 62,058 |
def skip_format_url(format_, url):
"""
Checks whether a give format/url should be skipped and not downloaded.
@param format_: Filename format (extension).
@type format_: str (e.g. html, txt, zip, pdf)
@param url: URL.
@type url: str
@return: True if format/url should be skipped, False oth... | 284e086c1f5350370d415cde64557eccfc3eb6e4 | 62,061 |
def brighten(color, brightness):
"""
Adds or subtracts value to a color.
"""
h, s, v = rgb_to_hsv(*map(down_scale, color))
return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness)))) | 5f4b4ca1f17b6bb78e6e47c1e50c6cd433277525 | 62,062 |
import copy
def swf(wf: dict, data: dict = {}) -> dict:
"""
Calls the dynamic workflow and returns the result
Params:
- wf: the workflow, based on the serverlessworkflow specification, to be executed
- data: the initial workflow data
"""
return execute_swf(wf=wf, data=copy.deepcopy(data)) | 32d207317079a220d8cc762bfea4c3e04b240486 | 62,064 |
def normalize_tf_graph(graph_output, new_graph=True, verbose=False):
"""Use grappler to normalize a graph.
Arguments
---------
graph_output: Tensor
A tensor we want to consider as "output" of a `FuncGraph`.
Returns
-------
The simplified graph.
"""
train_op = graph_output.gra... | fdc9fb782ecab34bfe0cbf6092b9040a22771441 | 62,065 |
def MvNormalLogp():
"""Compute the log pdf of a multivariate normal distribution.
This should be used in MvNormal.logp once Theano#5908 is released.
Parameters
----------
cov : tt.matrix
The covariance matrix.
delta : tt.matrix
Array of deviations from the mean.
"""
cov... | 4b13a04ec82c7b7b914b0c68b0e4e53365792789 | 62,066 |
def createZero4() -> Mat4:
"""
Create a 4x4 zero matrix
"""
return Mat4() | b670ce4fbd12d39dbb5bf234246b0ab2ab230884 | 62,067 |
def ppfBeta(p, q, r, a, b):
"""Returns the evaluation of the percent point function (inverse cumulative
distribution) evaluated at the probability p for a Beta distribution.
Usage:\n ppfBeta(p, q, r, a, b)"""
width = b-a
return stats.beta.ppf(p, q, r, loc=a, scale=width) | 89a446dc56aba086f1522485b8264c48c3b3d1c8 | 62,068 |
def is_valid_msisdn(msisdn):
"""A very basic msisdn validation check"""
return msisdn[0] == "+" and len(msisdn) == 12 | 5a8865182f0ff21eafcd836e5ccc9497bd097f93 | 62,069 |
def which_fib(lst, n):
"""
Returning the index of n in the sequence lst starting from 1
"""
return lst.index(n) + 1 | 5019442188151a9feb0bccbbcff1b4fcacb3a5c1 | 62,070 |
from typing import Tuple
from typing import Any
def subplots(*args, **kwargs) -> Tuple[Any, Any]:
"""Direct wrapper around |subplots|.
"""
return plt.subplots(*args, **kwargs) | 75ba1f4726e00a8399ae2d8b09a47cb8e00876b8 | 62,071 |
import torch
def get_normalized_adj(A):
"""
Returns a tensor, the degree normalized adjacency matrix.
"""
alpha = 0.8
D = np.array(np.sum(A, axis=1)).reshape((-1,))
D[D <= 10e-5] = 10e-5 # Prevent infs
diag = np.reciprocal(np.sqrt(D))
A_wave = np.multiply(np.multiply(diag.reshape((-... | 6293f1f3550fa93a9eeae57dbf13d00a3f9f8a0a | 62,072 |
def simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: список простых делителей числа
"""
d_list = dividers_list(a)
smpl_div_list = []
l = len(d_list)
for i in range(l):
if is_prime(d_list[i]):
smpl_div_list.append(d_list[i])
return smpl_div_list | fd15382cf63e3be85bf540e3269d767bd12645ae | 62,073 |
def PosOpenBracket(text):
"""Returns the position of the right most open bracket in text.
Brackets inside strings are ignored. In case of no open bracket
the returned value is -1
@param text: The line preceding the new line to be indented.
@return res: The position of right most open bracket.
@n... | 664079f284e18478065a12ef62ed76ad60a4601a | 62,074 |
def add_4_side_contrast_mtr(x):
"""Add the contrast of the 4 sides of each pixel value for each rgb channel.
Thus, for each rgb channel, 4 new channels is created s.t. for pixle (r,c):
1) absolute difference between (r,c) and (r-1,c)
2) absolute difference between (r,c) and (r+1,c)
3) ab... | 4e6c5f51f92f8bd21083eb1297033fdafada5eb7 | 62,076 |
def js_roots(n, p1, q1, mu=False):
"""Gauss-Jacobi (shifted) quadrature
Computes the sample points and weights for Gauss-Jacobi (shifted)
quadrature. The sample points are the roots of the `n`th degree shifted
Jacobi polynomial, :math:`G^{p,q}_n(x)`. These sample points and weights
correctly integ... | 3dc29658311aeeb9a0c6662ad4e3098ee831be37 | 62,077 |
import json
def verify_self_signed_jwks(sjwt):
"""
Verify the signature of a signed JWT containing a JWKS.
The JWT is signed by one of the keys in the JWKS.
In the JWT the JWKS is stored using this format ::
'jwks': {
'keys': [ ]
}
:param sjwt: Signed Jason Web T... | 40c6c72673f01ad26fa8fa92e46705d54d3a820f | 62,078 |
import warnings
def deprecated(func):
"""A decorator used to mark functions as deprecated.
Emit a warning when the decorated function is called.
"""
@wraps(func)
def wrapper(*args, **kwargs):
"""Emit a warning, then call ``func``."""
old_name = func.__name__
if old_name =... | 8d3602a322addd3253323d0cfe0ff839ba0b1b5f | 62,079 |
from re import U
def subtract_background(spec, backp, backm):
# type: (ReflData, ReflData, ReflData) -> (np.ndarray, np.ndarray)
"""
Subtract back+ and back- from spec.
if *offset* is 'auto', guess alignment.
Interpolates background measurements to align with the specular. If a
different in... | 8623dcc8cff5c53049c681e72b95522343f9dee8 | 62,080 |
def forwardscan(session, target, nd_period=None, lead_time=None, **kwargs):
"""Forward scan observation.
Call to `scan` method described in this module
Parameters
----------
session: `CaptureSession`
target: katpoint.Target
nd_period: float
noisediode period
lead_time: float
... | 79c0e75e66986504d3f6b3ae9bc6de3709782a3d | 62,081 |
def floyd_warshall(g):
"""Return new graph - transitive closure of g
"""
closure = deepcopy(g)
vertices = list(closure.vertices())
n = len(verts)
for k in range(n):
for i in range(n):
# does edge (i,k) exist in partial closure?
if i!=k and closure.get_edge(verts[i... | 965ebb596a18ab5f4a84e1388bc091582c999125 | 62,082 |
import torch
def load_learning_policy(
optimizer: torch.optim.Optimizer,
learning_policy_type: str,
**kwargs: "other hyper-parameters for learning scheduler"
) -> "learning policy":
"""
default: (100, 105), 110 epochs suggested
null:
STD: (82, 123), 164 epochs suggested
STD-wrn: (60, 1... | 0f2b13e6b2f4f6322d987a68f7dc6a648c5ea34e | 62,084 |
def view_groups(request, *args, **kwargs):
"""View, add, or delete view groups
:param request:
:param args:
:param kwargs:
:return:
"""
page = Page.objects.get(slug=kwargs['slug']).get_content_model()
if request.method == 'POST':
try:
page.add_view_group(Grou... | e10e785de3ff30a41e146d84fe6cef9e1e2c3ffe | 62,087 |
import requests
def __re_any(subreddit):
"""
Gets the most read entries of the Ask Reddit/TIL/IAmA subreddits from the last 24 hours
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Ask Reddit page
"""
posts = []
base_url = f'https://www.reddit.com/r/... | a1eb7111d5f8af1db337f402de1ec35845b29cd7 | 62,088 |
def decode_oh(onehots, postagstype=None):
"""
Convert one-hot representations to POS tags.
"""
postags = list()
if postagstype is None:
postagstype = PosTagsType()
for onehot in onehots:
if onehot >= postagstype.feature_length:
postags.append('UNKNOWN')
else:
... | 5a28abac7050a622d20c1b931091cea6ef4680ec | 62,089 |
from typing import Union
from typing import Any
import time
def get_token(session_: SessionMixin, scope:Union[str,list[str]]) -> tuple[dict[str, Any], bool]:
"""Check if token is currently valid and returns new token if there is no token or it is expired."""
token_valid = False
token_info = session_.get("... | 8d65761b14308b85e9316f2ebf11f890b0347b75 | 62,090 |
def pack_facet_info_numba(active_facets, c_to_f, f_to_c):
"""
Given a list of external facets get the owning cell and local facet
index
"""
facet_info = np.zeros((len(active_facets), 2), dtype=np.int64)
c_to_f_pos, c_to_f_offs = c_to_f
f_to_c_pos, f_to_c_offs = f_to_c
for j, facet in en... | ef0c1be9d16855323d9e79dcaf90e8811760c79f | 62,091 |
def load_text_validation_min(value):
"""load text_validation_min"""
return value | 777ef7221cd6f0153964fc1fe1d277bc514ed41c | 62,092 |
def build_lines_data(lines) -> bytes:
"""
Builds the byte string from given lines to send to the server
:param lines:
:return bytes:
"""
result = []
for line in lines:
result.append(f"{(len(line) + 5 ):04x}".encode())
result.append(line)
result.append(b"\n")
resul... | f5fd900c606b2e44454bbc15cab61e2b34809fab | 62,093 |
def find_folder_on_path(path, target='.git', **kwargs):
"""
Given a path, find the repo root. The root is considered the top-level
folder containing the '.git' folder. This method will traverse up the
tree, searching each level.
If not `.git` folder is found, None is returned. Otherwise the parent... | 317a061210bca432d128a82a8cc7e27b6aa4feee | 62,094 |
def magnitude(v: Vector) -> float:
"""Returns the magnitude (or length) of v"""
return sqrt(sum_of_squares(v)) | 9dda8c202eaae8cd9b6c848d3e7d3bd454363580 | 62,095 |
def var_order(bdd):
"""Return `dict` that maps each variable to a level.
@rtype: `dict(str: int)`
"""
return {var: bdd.level_of_var(var) for var in bdd.vars} | d9f526be705918bfff43d105750ce97d29e15e52 | 62,096 |
def yes_add_customer_event_form_data():
"""gives valid data for a test"""
return {
"title": "event test",
"description": "a short description",
"event_start": "2022-03-09T10:45",
"event_end": "2022-03-09T10:45",
} | 8601f8a91ef0bc0f3a9c3cd399e11449c1193a9f | 62,097 |
def get_camera_serial_and_firmware(console_text):
"""
Scraps console text for serial and firmware information of all connected realsense devices.
Args:
console_text (str): input console text contaning all connected device information
Returns:
Array[dic]: Array item for each connect dev... | 9426522f3815d7e73c12b5081c6308733836528d | 62,099 |
from datetime import datetime
import string
def format_time(date_time: datetime) -> string:
"""
A function that reformats datetime objects into a string usable to find the web element
:param date_time: A datetime object
:return: Returns the formatted date time object
"""
str_date = date_time.s... | e0f63cb03c16d8e5434ef6f3a00b7030052e3051 | 62,102 |
def read_string(file):
"""
Считывает строковое значение из undeflated EFD файла.
:param file: Обрабатываемый файл
:type file: BufferedReader
:return: Строковое значение
:rtype: string
"""
# Длина строки в символах
str_len = unpack('I', file.read(4))[0]
# Длина в байтах. Каждый с... | b00d73c44d803dbd3f0aebd0094f788a769026db | 62,103 |
def findAuROC( genome ):
"""
This function computes the area under the ROC curve of a ChIP-seq experiment
where read count ratios are employed to distinguish between bound and
unbound regions.
"""
labels = np.zeros(genome.shape[0],dtype=np.bool)
direct = genome['binding'] == "direct"
lab... | 520f896c3368ec7fd97c0d6b9f13f45231e3cbfd | 62,104 |
def random_hecke_operator(M, t=None, p=2):
"""
Return a random Hecke operator acting on `M`, got by adding
to `t` a random multiple of `T_p`
INPUT:
- ``M`` - modular symbols space
- ``t`` - None or a Hecke operator
- ``p`` - a prime
OUTPUT: Hecke operator prime
EXAMPLES::
... | b6d2b8cc6defd5245ce26de1512ff946be77df0c | 62,105 |
from typing import Dict
def map_graph(graph: nx.MultiDiGraph, mapping: Dict, preserve: bool = True) -> nx.MultiDiGraph:
"""
Remap node identifiers in a networkx.MultiDiGraph based on a provided mapping.
For nodes, the old identifier is saved as `source_curie` attribute.
In case of edges,
- if the... | 154c71bf4a28144732ba18e09be5fa64ced05b69 | 62,106 |
def is_abstract_method(method):
"""
@type: method: object
@param: A method object.
"""
return getattr(method, '__isabstractmethod__', False) | 09c83f409ec4d9fa1e00d6b60d81f78cb8c8dbd3 | 62,107 |
def register():
""" register route """
try:
# if request is GET method return register page
if request.method == "GET":
return render_template("register.html")
# parse data
schema = AuthRegisterDto()
data = schema.load(parse_request())
username = data... | 936dba69d071d4482305888190f79514096c7afa | 62,108 |
def transfer_from_taoyuanagrichannel_to_ncsist():
"""
Real Name: Transfer From TaoYuanAgriChannel To NCSIST
Original Eqn: Transfer From ShiMenReservoir To HouChiWeir*Ratio NCSIST At HouChiWeir*(1-Channel Transfer Loss Rate)
Units: m3
Limits: (None, None)
Type: component
Subs: None
"""
... | 3af2367af305d65743e95c12f752f1d9f9f01cd0 | 62,109 |
def _get_config_parameter(config, section, parameter_name, default_value):
"""
Get the parameter if present in the configuration otherwise returns default value.
:param config the configuration parser
:param section the name of the section
:param parameter_name: the name of the parameter
:param... | 2431c37eab3396b79f4f9e649a7cc25fc27208dc | 62,110 |
from pathlib import Path
def preprocess_images(files, to_folder, size=None, mode=None, suffix='.png',
pre_crop_rect=None, prepend=True, parent_name=True, verbose=False,
skip_creation=False):
"""Preprocess image files and put them in a folder with prepended serial number... | 309929e96c50f68a239b9dccbc36a807cdd7dcf0 | 62,111 |
def synchronous( tlockname ):
"""A decorator to place an instance based lock around a method """
def _synched(func):
@wraps(func)
def _synchronizer(self,*args, **kwargs):
tlock = self.__getattribute__( tlockname)
tlock.acquire()
try:
return fu... | b18617ab4565a4c2363bac038452a25848867409 | 62,112 |
def project_hidden(x, projection_tensors, hidden_size, num_blocks):
"""Project encoder hidden state into block_dim using projection tensors.
Args:
x: Encoder hidden state of shape [-1, hidden_size].
projection_tensors: Projection tensors used to project the hidden state.
hidden_size: Dimension of the l... | ea8fbac158ac9f16e4db70f34aec3dca5d4a0d7e | 62,113 |
def representatives(poly):
"""should return all crossing non-equvalent representatives of a polyhedron."""
tt = canonical(makesingle(poly))
print("**")
ae = all_embeddings(tt)
print("ae ")
ff = [facesfromrotation(r) for r in ae]
print("ff")
tts = [stringsfromfaces(r) for r in ff]
pri... | b747d50b96eeb69b6541ff19808652b6f69fb4b6 | 62,115 |
def sg2d_fit(x, fwx, fwy, x0, y0, offset, order, amplitude):
"""
2D Super-Gaussian formula to used with curve_fit
"""
X, Y = x[0], x[1]
return amplitude*gauss2D(X, Y, fwx, fwy, x0, y0, offset, order/2, int_FWHM=False) | caeb55880dcfc4e370ef685b361e500fbcd535a5 | 62,116 |
def make_meetings_str(room, start, end, days_yn):
""" Make a string that tells the days and times when a class section meets.
Spaces are filled with @, which need to be fixed once the string has been encapsulated in
a cell.
"""
room_str = f'{room}: ' if room != '' else room
day_list = set()
for i ... | 4898a666399f2d44818ddbabe9158e2c9c05818b | 62,117 |
def _normalize_ab_allele_names(ab_allele_names):
""" A helper for `get_compact_ab_allele_names`
"""
try:
res = mhcnames.parse_classi_or_classii_allele_name(ab_allele_names)
except Exception as e:
msg = str(e)
logger.warning(msg)
return None
if len(res) != 2:... | 2710218b869ad6e47e58164b01dafa01bb37a922 | 62,118 |
def get_all_slidable_moves(starting_hex: tuple, board_piece_locations: set[tuple], is_spider_move: bool = False) -> set[tuple]:
"""
Given a starting hex location, find all hexes that may be slid to. This is relevant to the Ant and Spider pieces.
For the ant, return the exhaustive list of all contiguous slid... | 184b70f88b416f3abf6b834a19fe4240d38fc1ea | 62,119 |
def setup_config(config: dict) -> dict:
"""
Setup configuration for the image generation, many settings are
based on the load_pretrained_ffhq.sh file from the U-NetGAN github.
Don't change these settings if you dont know what you are doing.
Args:
config (dict): Dictionary with the configura... | cb7e75fa1c700dcfb238c071c791e52927056721 | 62,120 |
def map_d2_d1_to_t1(tpdm, opdm):
"""
Map the 2-RDM and 1-RDM to the T1-matrix
:param tpdm:
:param opdm:
:return:
"""
dim = opdm.shape[0]
t1 = np.zeros_like((dim, dim, dim, dim, dim, dim), dtype=tpdm.type)
for p, q, r, i, j, k in product(range(opdm.shape[1]), repeat=6):
# Not... | acbcbcee85d3bddbeae49e1ef94c20d2323bc655 | 62,121 |
import json
import time
def get_dump(url):
"""
Retrieves a json file from the given URL and loads it into memory
"""
for i in xrange(1, 4): # 3 retries
try:
response = urllib2.urlopen(url)
json_str = response.read()
dump = json.loads(json_str)
re... | 6fc054b7b89928edffb962ef5c48613b7f24a0cd | 62,122 |
import requests
def api_retrieve_organization(org_id):
"""
Allows the client to call "retrieve" method on the server side to
retrieve the organization from the ledger.
Args:
org_id (str): The uuid of the organization
Returns:
type: str
String representing JSON obj... | dec1cadc22c39ccaa144f0cfc6dfa6fa86afb8d8 | 62,123 |
def getSnapshotPath(date):
"""
"""
return ql.DATASTORE_PATH + "/%s" % date.strftime("%Y%m%d") | e69e2b573f8ac1f4ff723b96bf26d64c30929406 | 62,124 |
def _build_binned_configs(
condition: list,
min_threshold: float,
windows: list,
agg_func: dict,
bin_size=30,
**kwargs
):
"""
Creates configurations for binned pipelines.
"""
configs = []
for window in windows:
for w in range(window[0], window[1], bin_size):
... | 8baf8d50e3d0a53764a17beea933e36c04fca4fe | 62,125 |
def interp(query, *args):
"""
Interpolate the provided arguments into the provided query, using
the DB-API's default conversions, with the additional 'RAW' support
from modu.sql.RAW2Literal
@param query: A query string with placeholders
@type query: str
@param args: A list of query... | 3050555ff0f990992714acf2374c11360176ccb8 | 62,127 |
import re
def calc_decomp_sz(data):
"""Calculate--without decompressing--the decompressed
size of data when all nested markers are applied.
"""
data = re.sub('\s', '', data)
decomp_sz = 0
while len(data):
marker_start = data.find('(')
if marker_start >= 0:
decomp_sz... | 8b42ce97e02abd09dcf98d80bc5f6bd069d6ce62 | 62,129 |
from typing import Dict
def generate_character_values(
rng: IRandNumGenerator, n_likes: int = 3, n_dislikes: int = 3
) -> CharacterValues:
"""Generate a new set of character values"""
# Select Traits
total_traits: int = n_likes + n_dislikes
traits = [str(trait.value) for trait in rng.sample(list(V... | c060e0b49b6966cc51805598772c0ecc1df7156a | 62,130 |
def collect_output(mr_out_dir, out_file=None):
"""
Return all mapreduce output in ``mr_out_dir``.
Append the output to ``out_file`` if provided. Otherwise, return
the result as a single string (it is the caller's responsibility to
ensure that the amount of data retrieved fits into memory).
"""... | 075fe5f2f44137fd706a6b72285412d119ca093f | 62,131 |
def make_bool(x_var):
"""turn an array of ints into array of bool"""
if x_var > 0:
return True
return False | ce2f4d51d6126df7723aa90b7b717d613feaad2f | 62,132 |
def as_escaped_unicode_literal(
text: str
) -> str:
"""Convert the given ``text`` into a string of escaped Unicode
hexadecimal.
Args:
text (:obj:`str`): The string to convert.
:rtype:
:obj:`str`
A string with each character of the given ``text`` converted
... | 2fc72bb8875023d86561552e9c64e55f5a99dfc1 | 62,133 |
def compute_top_minus_index_spread(mean_returns,
market_index):
"""
Computes the difference between the mean returns of
two quantiles. Optionally, computes the standard error
of this difference.
Parameters
----------
mean_returns : pd.DataFrame
DataFra... | 8da2a1c0d316bd78f5f6efdc93dfdac6ee81a2e7 | 62,134 |
def get_widedeep_net(configure):
"""
Get network of wide&deep model.
"""
wide_deep_net = WideDeepModel(configure)
loss_net = NetWithLossClass(wide_deep_net, configure)
train_net = TrainStepWrap(loss_net)
eval_net = PredictWithSigmoid(wide_deep_net)
return train_net, eval_net | 0d605a5523596a9f7323aee8c423920f3cba5463 | 62,135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.