content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def test_figure_saver_instance(debug, expected_filetype):
"""An FigureSaver instance should be used to set defaults, not the class.
This is to avoid unintentionally overriding defaults for different modules.
"""
def get_defaults():
return [
getattr(FigureSaver, attr)
... | f40b77321221781b42d2df17cf2566db8df41350 | 49,300 |
import json
def load_data(raw=None):
""" load data to development workspaces
Parameters
--------------
raw: (bool) if True, function returns cleaned dataset.
return (df) data frame of data and its labels
"""
raw_data = []
with open('./data/cyber_data.json') as f:
for l... | 7ff0051cd7f6f90bb00b24cc2025e0ed88b629ed | 49,301 |
def nearer(lons, lats, lon, lat, tolerance=np.inf, max_sites=None):
"""Nearer stations in (lons, lats) to site (lon, lat).
Args:
lons (array): Longitudes of stations to search.
lats (array): Latitudes of stations to search.
lon (float): Longitude of of station to locate from lons.
... | 5482e59d835094fd31d8eff82d432a93a341af77 | 49,302 |
def draw_perm_reps_diff_mean(x, y, size=1):
"""Generate array of permuation replicates."""
out = np.empty(size)
for i in range(size):
x_perm, y_perm = draw_perm_sample(x, y)
out[i] = np.mean(x_perm) - np.mean(y_perm)
return out | 31bc21ef017e636106a67ad3e32972d7b29abeba | 49,303 |
import torch
def pois_llik(y, eta):
"""Return ln p(y | eta) assuming y ~ Poisson(exp(eta))
This implementation supports broadcasting eta (i.e., sharing parameters
across observations).
:param y: tensor
:param eta: tensor
:returns llik: tensor (y.shape)
"""
return y * eta - safe_exp(eta) - torch.lg... | bd933181b3687a5fc6d4b6d851f34d481739ff3c | 49,304 |
import zipfile
def get_docx_text(path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(path)
xml_content = document.read('word/document.xml')
document.close()
tree = XML(xml_content)
paragraphs = []
for paragraph in tree.ge... | ff0b4d315197573ab6cdfdb22b4b8d62226ef337 | 49,305 |
def config_unconfig_interface_ip_addresses(dut, if_data_list=[], config='add',cli_type='',ip_type=''):
"""
Configure IP addresses on multiple interfaces
Author: Naveena Suvarna (naveen.suvarna@broadcom.com)
:param dut:
:param if_data_list:
:param config:
:return:
"""
if config != 'a... | e73e24cccb3a0458e297daa66a7da0c88546c5b7 | 49,306 |
import random
def compare_with_ties(a, b):
"""
Comparison function for two items with the condition that if they are equal,
one of the two values is randomly selected to be greater than the other.
Arguments
a - the first item to compare
b - the second item to compare
Returns:
... | 9acfacc40d8ca0bc0ec2a4a226e82a5d55bfe440 | 49,307 |
def store(src, rel, dst):
"""
Returns an SQL statement to store an edge into
the SQL backing store.
:param src: The source node.
:param rel: The relation.
:param dst: The destination node.
"""
smt = 'INSERT INTO %s (src, dst) VALUES (?, ?)'
return smt % rel, (src, dst) | 1fcb76ff722fbf0a43c125a4ff42405b12d54ec6 | 49,308 |
def make_node_dict(node_dict, xml_dict, hch_id, hch_tag, parent, classification_orpha):
"""
Recursively parse xml_dict to output a collection of Disorder with all their children
:param node_dict: Dictionary of Disorders i.e.
{2846: {
"Preferred term": "Congenital pericardium anomaly",
"... | 5f0b254122a40240829d016b3cf76f89053a5d00 | 49,309 |
def fateman_poly_F_1(n):
"""Fateman's GCD benchmark: trivial GCD """
Y = [Symbol('y_' + str(i)) for i in range(n + 1)]
y_0, y_1 = Y[0], Y[1]
u = y_0 + Add(*[y for y in Y[1:]])
v = y_0**2 + Add(*[y**2 for y in Y[1:]])
F = ((u + 1)*(u + 2)).as_poly(*Y)
G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 -... | 38413804cc477d9fb3b502b394b78933381e53c0 | 49,310 |
def markdown(value):
""" Converts the specified markdown string to HTML
Args:
value (str): Markdown string
Returns:
string: HTML equivalent
"""
return markdown2.markdown(value) | 225ae6551a717c4844bc33fb6b85f10efed6e67e | 49,311 |
def irpf(base, porcentaje=12.5,prorrateado=False):
"""
irpf (sueldo,porcentaje, prorrateado=boolean)
"""
if prorrateado:
cantidad_prorateada = base/6
if type(base)==float and type(porcentaje)==float:
return (base/100) * porcentaje
else:
return None | cbc3fbb115f9896a5e852126b242a22c49bba66b | 49,312 |
from typing import Optional
import os
def get_data_loader(data_config: dict, split: str) -> Optional[DataLoader]:
"""
Return the corresponding data loader.
Can't be placed in the same file of loader interfaces as it causes import cycle.
:param data_config: a dictionary containing configuration for d... | 4cb8d6cb041887a075e13e92983ef005439ce16e | 49,313 |
import string
def generatepin(length=4):
"""Generates a PIN number of the specified length."""
return generatepass(length, string.digits, exclude_similar_chars=False) | 94d2d4a5b39bf36991f8daac9d29182f63921004 | 49,314 |
def read_p2g(path):
"""Read graph in p2g format from path.
Returns an MultiDiGraph.
If you want a DiGraph (with no self loops allowed and no edge data)
use D=networkx.DiGraph(read_p2g(path))
"""
fh=_get_fh(path,mode='r')
G=parse_p2g(fh)
return G | 76fc8b348f67ac0b5bb52859001335bac279ff17 | 49,315 |
def get_by_index(items, index):
"""
Return an element of a list based on its index.
Usage in template::
{% load list_to_columns %}
{{ items|get_by_index:0 }}
Args:
``items`` (list): A list of elements.
``index`` (int): The position of the element to be returned.
... | a355560ab741ef821c62e9b11e77476d3ab7248c | 49,316 |
from datetime import datetime
def admin_ide_stop_id(id: str):
"""
Stop a specific IDE
:return:
"""
# Search for the theia session
session = TheiaSession.query.filter(
TheiaSession.id == id,
TheiaSession.course_id == course_context.id,
).first()
# Verify it exists
... | c66585753bbac987b5cde340df4d6b7fb06c9cb2 | 49,317 |
import uuid
def lci_instance_id():
"""Id for the low-cost instance."""
return f"lci-instance-{uuid.uuid4().hex[:10]}" | 2c559d27879b418f86e12f00cff7526ce964258a | 49,318 |
from datetime import datetime
def lookup_in_cdx(qurl, target_date=None):
"""
Checks if a resource is in the CDX index, closest to a specific date:
:return:
"""
matches = list_from_cdx(qurl)
if len(matches) == 0:
return None, None, None
# Set up default:
if target_date is None... | 1651bdce6afd2bdd1611e001839e149e53d9322a | 49,319 |
def command_exists(command):
""" Check if the given command was registered. In another words if it
exists.
"""
for category, commands in command_categories.items():
for existing_command in commands:
if existing_command.match(command):
return True
return False | a9ad8c23fb354da395b7fe865e6bda7a3ed68148 | 49,320 |
from typing import Dict
def users_search(client: Client, args: Dict) -> CommandResults:
"""Search users
Args:
client: Client object with request.
args: Usually demisto.args()
Returns:
Outputs.
"""
email = str(args.get('email', ''))
query = str(args.get('query', ''))
... | 0e48fc1b8367146d05fcaa7ec15b9f70445b07be | 49,321 |
def list_files():
"""
List some of the files on the Drive.
:returns: A dictionary containing the list of file-details.
"""
results = file_service.list(
pageSize=10, fields="files(id, name)").execute()
return results | 914649ec9099ea10b0607cb124ff5d6b061222af | 49,322 |
def onwindowcreate(window_name, fn_name, *args):
"""
On window create, call the function with given arguments
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param fn_name: Callback function
@type fn_name: fun... | d2d4e21f5f119be972a34acb3717eb64c01357a1 | 49,323 |
def expand(entity_id):
"""Returns a list of diagrams for the role
---
get:
summary: Expand an entity to get its adjacent entities
description: >-
Get the property-wise list of entities adjacent to the entity
with id `entity_id`.
parameters:
- in: path
name: en... | 46605a8f4c46cf79413881d3ebfb6459497f12bf | 49,324 |
import sys
import inspect
def all_global_vars(x):
"""
Find all globals accessed by an object.
"""
# Define internal recursively called function to enable tracking of the
# recursion level:
def recursive(x, seen=set(), level=0):
# Get locals of scope in which allglobalvars() was invok... | 7628a61437ff84bfedc92a0c4970befde8686a9b | 49,325 |
def get_model_preds(CP):
"""Reads in or generates model predictions.
Parameters
----------
CP : dict
Containins directory locations for loading data and storing
predictions.
Returns
-------
craters : h5py
Model predictions.
"""
n_imgs, dtype = CP['n_imgs'], ... | b789ff9a5c7f40cc6be875b89eec5b73228db934 | 49,326 |
def detach():
"""
Detaches a specified device
"""
scsi_id = request.form.get("scsi_id")
unit = request.form.get("unit")
process = ractl.detach_by_id(scsi_id, unit)
if process["status"]:
flash(_("Detached SCSI ID %(id_number)s LUN %(unit_number)s",
id_number=scsi_id, unit_... | 916db39fd210510ec27d63e61eb5244c5d288731 | 49,327 |
def weld_range(start, stop, step):
"""Create a vector for the range parameters above.
Parameters
----------
start : int
stop : int or WeldObject
Could be the lazily computed length of a WeldObject vec.
step : int
Returns
-------
WeldObject
Representation of this com... | 196ef891804bd9104e9e2e4582f3de5fe19751e7 | 49,328 |
def _capture(which='stdout', printonly=None):
"""private method, should not be called directly
(cf. capture_stdout() and capture_stderr())
"""
assert which in ('stdout', 'stderr'
), "Can only capture stdout or stderr, not %s" % which
if which == 'stdout':
fd = 1
else:
fd ... | 534ad7f1cf0f703936921dd03325096000f65a33 | 49,329 |
def flatten(d):
"""Return a dict as a list of lists.
>>> flatten({"a": "b"})
[['a', 'b']]
>>> flatten({"a": [1, 2, 3]})
[['a', [1, 2, 3]]]
>>> flatten({"a": {"b": "c"}})
[['a', 'b', 'c']]
>>> flatten({"a": {"b": {"c": "e"}}})
[['a', 'b', 'c', 'e']]
>>> flatten({"a": {"b": "c", "... | 9d7f83e8f57c2df9c33b69e46536553092ae1ec1 | 49,330 |
def plot_pair(img, adv, model=None, suptitle=None):
"""
Visualize clean image, purturbation, and adversarial example
# Arguments
img: np.array
The clean image with shape (w, h, 3)
adv: np.array
The adversarial example with shape (w, h, 3)
model: keras model
... | 5a0a23230e9b1696d7ec8ba218ae4b0ad753ed91 | 49,331 |
import _io
def plot2opencv(fig):
"""Convert a pyplot instance to image"""
buf = _io.BytesIO()
fig.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
buf.seek(0)
rawbuf = np.frombuffer(buf.getvalue(), dtype='uint8')
im = cv2.imdecode(rawbuf, cv2.IMREAD_COLOR)
buf.close()
ret... | d1453c6a6f684386730e29d8572b9d3da32a8ce7 | 49,332 |
def write_xls(sheet_name, head, data_list):
"""write listed data into excel
"""
try:
wb = openpyxl.Workbook()
ws = wb.get_active_sheet()
except Exception as e:
logger.error(e)
return None
ws.title = sheet_name
row_num = 0
# write table head
for col_num... | 5046cf12f2175229c871016012d2571f14d47c87 | 49,333 |
import argparse
def setup_argparse(parser: argparse.ArgumentParser) -> None:
"""Setup argument parser for ``cubi-tk sodar landing-zone-create``."""
return CreateLandingZoneCommand.setup_argparse(parser) | 2cd76bcb1bf56f06bbb06cbfd3b4e0c3f4232312 | 49,334 |
def missing_local_with_stage(stage: str, ssm_env: dict, local_env:dict, filter_env: list = []):
"""Returns missing values between ssm stage and local env"""
ssm_env = [x for x in ssm_env.keys() if x not in filter_env]
local_env = [x for x in local_env.keys() if x not in filter_env]
in_ssm = [x for x in ... | b69571464257b02aba1f5e7bdd3a8901c7842f70 | 49,335 |
def _slot_history(tracker_dump):
# type: (Dict[Text, Any]) -> List[Text]
"""Create an array of slot representations to be displayed."""
slot_strs = []
for k, s in tracker_dump.get("slots").items():
colored_value = utils.wrap_with_color(str(s),
utils... | 00a9157ef364217faa54cb7faa4c8f6b54cbbb2b | 49,336 |
from operator import concat
def HTN_classical_partition_function_from_edges(
edges,
beta,
j=1.0,
h=0.0,
site_ind_id="s{}",
site_tag_id="I{}",
bond_tag_id="B{},{}",
):
"""Build a hyper tensor network representation of a classical ising model
partition function by specifying graph ed... | 70539041daa68c4e70dcbf5d15c8f959885ad208 | 49,337 |
def country(cert):
"""
Attempt to get the country from a given certificate.
:param cert:
:return:
"""
try:
return cert.subject.get_attributes_for_oid(
x509.OID_COUNTRY_NAME
)[0].value.strip()
except Exception as e:
sentry.captureException()
current... | e6ba28a61c4f561fb596fccd1cc571f51ad6d320 | 49,338 |
def detect_fns_free_variables(source_code, imports_and_functions="",
step_parameters=None):
"""Return the function's free variables.
Free variable: _If a variable is used in a code block but not defined
there, it is a free variable._
An Example:
```
x = 5
def... | db5df686b118f70899e66c44ef90ebb8595d011e | 49,339 |
def assign(grid: Grid, s: Square, d: Digit) -> MaybeGrid:
"""Eliminate all the other values (except d) from grid[s] and propagate.
if a contradiction is detected, return None
"""
others = grid[s].replace(d, "")
for d in others:
if eliminate(grid, s, d) is None:
return None
r... | c82b31fb25ae9e018090198feee1c42fa62e3d67 | 49,340 |
import shlex
def split_types(query):
""" Split a string of multiple :py:class:`MeasurementType` keys (e.g., one
generated by using addition or subtraction of :py:class:`MeasurementType`
objects and/or strings).
:param query: A :py:class:`MeasurementType` or a string containing
... | 3777a879503aef0925ef239e32731c6fdb93543d | 49,341 |
import re
def get_outcome(output: str, test: Test, sig: int):
"""
Parses out the number of passed and failed tests from cb-test output
"""
test_outcome = TestOutcome()
test_outcome.total = 1
test_outcome.passed = 0
test_outcome.name = test.name
test_outcome.is_pov = test.is_pov
... | fa666ddda9769d65b2c8d6a6b0a437240356844e | 49,342 |
import os
def unzip_image(zip_path):
"""Unzips a file with a img file inside.
:param zip_path: Path to the zip file to uncompress.
:raises Exception: If there is no .img file inside the zip.
:return: Absolute path to an uncompressed .img file from the zip.
"""
print("Unzipping OS image: {}".f... | 23e619218c0a0ba5f89ff2dcaf5326f83314ceea | 49,343 |
import os
from datetime import datetime
import pickle
def evaluate():
"""Evaluate on whole test data for DeepSpeech2."""
data_generator = DataGenerator(
vocab_filepath=args.vocab_path,
mean_std_filepath=args.mean_std_path,
augmentation_config='{}',
specgram_type=args.specgram_t... | 2233c8a87420b895c822df44433a6d8333f50a69 | 49,344 |
def search():
"""
Return search results for a given query
"""
query = request.args.get("query", "")
if query == "":
return redirect(url_for("main.browse"))
page = int(request.args.get("page", 1))
format = request.args.get("format", "")
scan_ids = request.args.get("includeScan... | 8fff27cd059612f0a7dd0b66a2d27efc27f5090b | 49,345 |
def bubble_sort(array):
"""
Sorts a list using bubble sort algorithm
Input: A list of integers
Output: A list containing the same integers as the input, but sorted in
ascending order
Sorts by iterating through a list swapping values that are in the wrong order.
Stops when it is imp... | 5af7e90dd423ac57bd6aa3b27e139d35c814a45f | 49,346 |
def issue_dir(issue_id):
"""
input: 123
output: /path/to/repo/gl/i/123
"""
return DIR / "i" / str(issue_id) | 40f9c063fb1e69f835bfa5615875427de4b7d572 | 49,347 |
from typing import Dict
from typing import Any
def _read_info(info_filename: str) -> Dict[str, Any]:
"""read info into dictionary"""
with open(info_filename, "r") as info_file:
lines = info_file.readlines()
info = {}
for line in lines:
key, val = line.strip().split("\t")
... | 884a0a309380e1b077c5d1830ca3b6803804644b | 49,348 |
def signal_derivs(zc, params, dparams):
"""
Calculate derivatives of signal covariance w.r.t. cosmological parameters.
"""
derivs = []
# Loop over parameters that should be included in Fisher matrix
pnames = dparams.keys()
pnames.sort()
for pname in pnames:
print " Derivati... | 18919688ae1acdda84b0dda004634a32a0533b11 | 49,349 |
def view_coach(request, coach_id):
""" A view to show a particular coaches page and their comments"""
coach = get_object_or_404(Coach, pk=coach_id)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
co... | bbacfd2a0ac978bc0ca4fdda49f08e6a0d8ac3a3 | 49,350 |
def replace(filename, stext, rtext):
""" replace string stext with rtext in file filename """
status = True
try:
_input = open(filename, "r")
except Exception, e:
tolog("!!WARNING!!4000!! Open failed with %s" % e)
status = False
else:
try:
output = open(f... | 43c7441653ed84e935c99101c8ca0d2cbba8dff4 | 49,351 |
def infer_pip_requirements(model_uri, flavor, fallback=None):
"""
Infers the pip requirements of the specified model by creating a subprocess and loading
the model in it to determine which packages are imported.
:param model_uri: The URI of the model.
:param flavor: The flavor name of the model.
... | e8cfdd44781dfdf1cccb2d3194aaaa405e101ed5 | 49,352 |
def get_unlucky_days():
"""Returns the days that had article request fails percentage higher
than 1%."""
query = """SELECT to_char(date, 'FMMonth FMDD, YYYY') as date,
error
FROM request_errors_per_dar
WHERE error > 0.01;"""
return format_query(
'... | beb24244a715656a38c6e7e0da435e4b786f9160 | 49,353 |
def GetGradleSnippet(args):
"""Forms a gradle snippet to add to the build.gradle file.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
A gradle snippet.
"""
repo_path = _GetRepoPath(args)
gradle_template = """\
Please insert follo... | 4ab4444c809040207c33eb7fabc9ccf13306660b | 49,354 |
from typing import Dict
def run(config) -> Dict[str, dict]:
"""
Lowpolyfy one or more images using default or user-provided config.
Returns (Dict[str, dict]): A mapping from file paths to the config used to generate them.
"""
if config.run.mode == "single":
results = single(config)
el... | ec2bbae3803c111b63438a3a4ada861678e0876b | 49,355 |
import importlib
def load_connector(connector_info):
"""instantiate the connector class"""
connector = importlib.import_module(
f"bookwyrm.connectors.{connector_info.connector_file}"
)
return connector.Connector(connector_info.identifier) | e105c74d7f497132df439ff9e561d5492adb4c73 | 49,356 |
def axes_contains(ax, obj_list):
"""
Check that a matplotlib.Axes instance contains certain elements.
Parameters
----------
ax : matplotlib.Axes
Axes instance.
obj_list : list of tuples
List of tuples, one for each type of object to look for. The tuple
should be of the ... | 09da4420a5552902cb0b2da2a38c4e61af092b2f | 49,357 |
import requests
def get_globally_rescoped_token(globaltoken, defaultid):
"""Summary - Get a global project scoped auth token
Returns:
STRING: Globally Scoped Object
Args:
globaltoken (string): valid global token
defaultid (string): default projct id
"""
identityURL = 'htt... | d1e85b80862ab7e4bbe4c735fe5b6632eca64dcb | 49,358 |
def _bessel_ive_bwd(aux, g):
"""Reverse mode impl for bessel_ive."""
v, z = aux
ive = _bessel_ive_custom_gradient(v, z)
grad_z = g * (
_bessel_ive_custom_gradient(v + 1., z) + (v / z - tf.math.sign(z)) * ive)
_, grad_z = _fix_gradient_for_broadcasting(
v, z, tf.ones_like(grad_z), grad_z)
# No g... | 6f57eda2bacdfabe777e7bca9942ca161303f818 | 49,359 |
def compile_cons_check(context):
"""Throw a runtime error if the value in rax is not a cons cell or nil.
Does not modify rax.
See also `compile_list_check`.
"""
error_block = compile_die(b"not a cons cell :(\n", context)
result = []
# mov rdi, rax
result.extend([0x48, 0x89, 0xC7])
... | 6a03fb89b60c15f256ac20ab27eac2412079ca4e | 49,360 |
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
http://..... | 58897a8c5fd5f694579d8a35fb15a993dd40b87b | 49,361 |
import functools
import logging
import traceback
def signin_required(include_gitlab_login=False):
"""Check if the user is signed in or the access token is valid and return the user."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
u... | 0884eb5f7e50111236c14b362f2307c794236518 | 49,362 |
import tempfile
import bisect
import os
def build_dump_structure(path, tensor_name_list, tensor_list, net_name, tensor_info_list):
"""Build dump file structure from tensor_list."""
ranks_run_history = {}
temp_dir = tempfile.mkdtemp(prefix=net_name, dir=path)
for tensor_name, tensor, tensor_info in zip... | a9a30d946d0d81b52a0332c926186fda4294df12 | 49,363 |
def do_encoding(encoder_inputs, seq_len, sett):
"""
"""
rand_unif_init = tf.random_uniform_initializer(-sett.rand_unif_init_mag,
sett.rand_unif_init_mag,
seed=123)
#
with tf.variable_scope('encoder'... | 721466390c58332a365a1562bf7b5d121e995be1 | 49,364 |
import math
def branch_and_bound(c, A_ub, b_ub, A_eq, b_eq, bounds, bnbTreeNode=None):
"""
branch_and_bound 对整数规划问题使用「分支定界法」进行*递归*求解。
底层对松弛问题求解使用 scipy.optimize.linprog 完成,
该算法只是在 scipy.optimize.linprog 求解的基础上加以整数约束,
所以求解问题的模型、参数中的 c, A_ub, b_ub, A_eq, b_eq, bounds
与 scipy.optimize.linprog 的完... | 20521f906600c070b8ea7b7f67c30abedeffc391 | 49,365 |
import math
def nn_layer_fn(in_dim, out_dim, layer_name, fn=tf.nn.relu):
"""Builds a function of an nn layer, fully connected to the previous layer."""
with tf.name_scope(layer_name + '_vars'):
weights_shape = [in_dim, out_dim]
weights_stddev = 1.0 / math.sqrt(float(in_dim)) #Xavier initializa... | ac095171174aeacc8185d6d1d65354d074f98f7d | 49,366 |
def resolve_float_or_constant(input_value, accept_none = True):
"""Resolves an input as either a float or chemistry constant."""
if input_value is None:
if accept_none:
return None
else:
raise ValueError(
f"Received invalid value {type(input_value)}."
)
if isi... | 07ee0a76dcec441a8425837f21053ac1fa241e4d | 49,367 |
def nextfile():
"""
Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before... | 24b01cfbd82396885afa65829c0757ae1aefe091 | 49,368 |
import os
from typing import Dict
def normalizeCMS( Ddata, thinSfx, scenario, putativeMutPop, complikeSfx, likesTableSfx, statsSfx = '',
DdataNeutral = None, pop2name = pop2name, getio = None ):
"""Compute normalized versions of CMS computed assuming selection in $putativeMutPop,
for all SNP... | e058c918cf2f165c1b2f889700b56c5d795f028e | 49,369 |
def get_output_metadata(packer, sample_dim_name):
"""
Retrieve xarray metadata for a packer's values, assuming arrays are [sample(, z)].
"""
metadata = []
for name in packer.pack_names:
n_features = packer.feature_counts[name]
if n_features == 1:
dims = [sample_dim_name]
... | 7a16ed6878d58be45a3cd63b0a5bec515ab6475e | 49,370 |
def local_users_get(handle, dump=False):
"""
This method gets the list of local users configured on the server
Args:
handle (ImcHandle)
dump (bool)
Returns:
List of AaaUser objects corresponding to the local users
"""
aaa_users = _get_local_users(handle)
users = [x... | ba33f95408e6772c9649d744713393365f39cb87 | 49,371 |
def sort_data(PDB_files, data):
"""
Sorts data by name according to PDB files
"""
sort=natsort.natsorted(zip(PDB_files, data))
PDB_files=[tuple[0] for tuple in sort]
if type(data)==list:
data=[tuple[1] for tuple in sort]
else:
data=np.vstack([tuple[1] for tuple in sort])
... | ade7b27ef8a2217181bb3b60884ac8e361288de8 | 49,372 |
def _random_shuffle(*lsts):
"""Randomly shuffle a dataset. Applies the same permutation to each list
(to preserve mapping between inputs and targets).
:param *lsts: variable number of lists to shuffle.
:return: shuffled lsts.
"""
permutation = np.random.permutation(len(lsts[0]))
shuffled = ... | 8d5eea0e0e8d3caca89d0ac15afb3e7585676c27 | 49,373 |
def extract_subgraph(graph, object, task, hop=3):
"""
This function extract n-hop neighbors for an object and task pairs.
ToDo: using the subgraph is slightly more involved since node index in the subgraph needs to be adjusted
:param object:
:param task:
:param hop:
:return:
"""
ob... | 044946c8cac551c41f3e69433abbe0a4f5089ea8 | 49,374 |
def choose_report(account_type):
"""
Choose report object by account type
Args:
account_type(string): account type
"""
if account_type == SecuritiesType.futures:
report_obj = FuturesReport
else:
raise Errors.INVALID_ACCOUNT_TYPE
return report_obj | f3b583d9e0ff34202b4b84fa80dbfe2fdf96de3f | 49,375 |
def search_results(search_request):
"""
Search results from given search paramaters.
"""
ghh, _ = try_ghh(session)
search_users = session["search_users"]
search_orgs = session["search_orgs"]
search_repos = session["search_repos"]
ignore = session["ignore"]
if ghh is not None:
... | abc1ede8adbc01746618346dc6306bf84810f3dd | 49,376 |
def fproperty(func):
"""Decorator for a function that returns (fget, fset, fdel, doc)"""
return _property(*func()) | 43870a74c41d82ed6f8cec0312dc916f667e704f | 49,377 |
def connect_memdb():
"""
:return: Instance of an in memory database.
:rtype: SimpleSQLite
:Example:
:ref:`example-connect-sqlite-db-mem`
"""
return SimpleSQLite(MEMORY_DB_NAME, "w") | f6a31652d11b5133428a10309699757be71ac737 | 49,378 |
import torchvision
def deeplabv3_resnet50_features(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on Coco
"""
model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained=pretrained)
model.classifier._mod... | 80a240e16588c126973358d794150ab5d66e0647 | 49,379 |
import os
def parser(startpath: str) -> tuple:
"""Utility method to parse the filesystem"""
file_and_hash = {}
dirs_list = []
files_lst = []
def parse(startpath1: str) -> tuple:
for root, dirs, files in os.walk(startpath1):
dir_content = []
for dir in dirs:
... | 6d3818d2255bc36ae0269ee0adcc3f92e29b41ad | 49,380 |
def get_multiclass_labels():
"""
0: normal
1: abnormal
2: notable findings/abnormalities that are not relevant or within normal limits (WNL)
:return:
"""
return [0, 1, 2] | 969b1d9a19cafc253eb6403d4e3672522211a9f3 | 49,381 |
def _boundary_spatial_dissim(data, group_pop_var, total_pop_var, standardize=False):
"""Calculation of Boundary Spatial Dissimilarity index.
Parameters
----------
data : a geopandas DataFrame with a geometry column.
group_pop_var : string
The name of variable in data that contains the popul... | db559ef83f6b74fc8e6b85d986ff31d5b25683ba | 49,382 |
def test_skill_template_variables():
"""
Test variable coverage for `parameters_skill.tpl`.
"""
allowed = base.ParametersSkillParser.FIELDS
def is_covered_variable(field):
"""
Check if a skill field is covered during parsing.
"""
# Check for a regularly allowed fie... | 0a70690ee53bfb52f2f4efa56b0d4ce1959896ea | 49,383 |
from typing import Optional
from typing import Dict
from typing import Union
from pathlib import Path
def prepare_switchboard(
audio_dir: Pathlike,
transcripts_dir: Optional[Pathlike] = None,
sentiment_dir: Optional[Pathlike] = None,
output_dir: Optional[Pathlike] = None,
omit_... | 8fcb5397c6f421aeb3c931a321dd8b44f2201cfe | 49,384 |
def k1_mean(success_tag, ms_results):
""" Reports the expected value of k1, the rate constant for
the bimolecular step of a resting-set reaction. """
success_kcolls = np.ma.array(ms_results['kcoll'], mask=(ms_results['tags']!=success_tag))
n = int(np.sum(ms_results['valid']))
n_s = int(np.sum(~success_kcolls.... | 4a3308b6cca33506d6d88e931477006893af44a0 | 49,385 |
def get_request(filename, persistent = True):
"""
Helper function to generate HTTP GET requests.
Not used in application due to python overhead
in string manipulation.
"""
data = 'GET /{} HTTP/1.1\r\n'.format(filename)
data += 'Host: {}:{}\r\n'.format(ADDR,PORT)
data += 'Connection:... | 530e09e1c0133edc8ee879461820624c70c807d9 | 49,386 |
def update_express_route_port_link(cmd, instance, parent, express_route_port_name, link_name,
macsec_cak_secret_identifier=None, macsec_ckn_secret_identifier=None,
macsec_sci_state=None, macsec_cipher=None, admin_state=None):
"""
:param cmd:
... | f7a9ae6a7cb34e0945be907436228919203a9fd0 | 49,387 |
import argparse
def command_line_parser():
""" Hmmm well return all the parser argument
Returns
-------
Return args parser
"""
parser = argparse.ArgumentParser()
parser.add_argument("image_path", type=str,
help="Image you want to extract individual faces")
par... | b6303b3002e5d7631b32fd7cb41e95cb3c1dd259 | 49,388 |
def SendServerCommand(s, command):
""" Send a command to the server and get the response.
Send the command out to the server and pass the response back to the calling
function.
"""
# send the command to the server
s.sendall(command)
# get the response from the server
code, text = GetS... | a3de1396532d9472892d085fd418a05fc1ad354a | 49,389 |
def _or(self, other):
"""Compute the element-wise OR bitwise operation.
Parameters
----------
other : Union[dragon.Tensor, number]
The value to compute with.
Returns
-------
dragon.Tensor
The output tensor.
See Also
--------
`dragon.bitwise.bitwise_or(...)`_
... | 83cdbda4adc375ddd3c09b5cc087b61cd187ad58 | 49,390 |
import os
def zone_shp_overlay(zone_name_shp):
"""Select pumas within a zonal load area
:param str zone_name_shp: name of zone in BA_map.shp
:return: (*pandas.DataFrame*) puma_data_zone -- puma data of all pumas within zone, including fraction within zone
"""
shapefile = gpd.GeoDataFrame(
... | 70e7b46378535bd09eae73959bb3ab7bea1abec8 | 49,391 |
import re
def find_vendor(macs: str, neigh: list):
"""
This function searches for the NIC vendors in the IEEE DB
"""
# local vars
clean_mac_db = []
# Creating MAC DB in Python dictionary format
for entry in macs.splitlines():
if re.match("^[A-Z0-9]+\-", entry):
tc = {}... | f0f95684e2aba25cd14f3923e980ebff530e9410 | 49,392 |
def build_image_features(network_fn, images):
"""Builds the CNN model and extract image features
Args:
network_fn : CNN network
images: images
Returns:
net: extracted image features
end_points: end points
"""
# Extract Image features from CNN networks
features, e... | b70a1935e588f10761e86c59f918f17ad8577005 | 49,393 |
def define_session(module_path=None, **kwargs):
"""Define a session object under ``module_path``."""
module_path = module_path or clients.__name__
module_labels = labels.make_labels(module_path, *SESSION_LABEL_NAMES)
setup_session(
module_labels,
parameters.define(
module_pat... | 9d79a0e3d565b980db3c5e011909d1dd2d5c772d | 49,394 |
def resolve_path_traits(thistrait, value, cwd):
"""Resolve a BasePath-derived trait given an interface spec."""
return _recurse_on_path_traits(_resolve_path, thistrait, value, cwd) | c072affa59a52078050367b8566e58d0ce4165bf | 49,395 |
def return_value(controller_fun):
"""
返回参数
:param controller_fun: 控制层函数
:return:
"""
def __decorator(*args, **kwargs):
ret_value = {
"version": server_config.version,
"success": 0,
"message": u"fail query"
}
ret_data, code = controller... | 4b3da4666612cffffb6ce6293b7c41f3562abf49 | 49,396 |
from ._buffer import buffer_toggle_
from typing import Any
from typing import Callable
from typing import List
def buffer_toggle(
openings: Observable[Any], closing_mapper: Callable[[Any], Observable[Any]]
) -> Callable[[Observable[_T]], Observable[List[_T]]]:
"""Projects each element of an observable sequenc... | af7ec63d77f1023e7568fa05010498eca5e08a0b | 49,397 |
def reverse(*args, **kwargs):
"""Now this is a crazy and silly hack, but it is basically here to
enforce that an empty path always takes precedence over an article_id
such that the root article doesn't get resolved to /ID/ but /.
Another crazy hack that this supports is transforming every wiki url
... | 08a8e5629cc9dddf7f96444f75e19260f6ee33f1 | 49,398 |
def locale_get(handle, name):
"""
Gets the locale
Args:
handle (UcscHandle)
name (string): name of ldap provider
Returns:
AaaLocale : Managed Object OR None
Example:
locale_get(handle, name="test_locale")
"""
dn = ucsc_base_dn + "/locale-" + name
retur... | 8e56ff45efdc533bdef48306087706e204f3ce9a | 49,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.