content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
def get_all_ports(**kwargs):
"""
Perform a GET call to get a list of all entries in the Port table
:param kwargs:
keyword s: requests.session object with loaded cookie jar
keyword url: URL in main() function
:return: List of all ports in the table
"""
target_url... | 7133f97e8fda6d1be3a416adf1d457beda768f2b | 3,607,000 |
from pathlib import Path
from bs4 import BeautifulSoup
def get_all_go_compartments(dirpath, skip_single_cmp_models=False):
"""
Extracts and returns all unique defined GO compartments from
BioModel SBML files contained inside dirpath.
:param dirpath: Directory containing BioModel SBML files.
:para... | fbee85bbcfb6abe7b69f47458a88daab00c56547 | 3,607,001 |
def decrypt_filename(filename):
"""Break apart a transcription filename into it's various parts."""
filename_regex = current_app.config['FILENAME_REGEX']
filename_match = filename_regex.match(filename)
if filename_match:
return filename_match.groupdict()
return {} | 884ca398de96dd014807e108bf225decfaf0097e | 3,607,002 |
def gen_random_color(min_value=0, max_value=256) -> str:
"""Generate random color for plotly"""
r, g, b = np.random.randint(min_value, max_value, 3)
return f'rgb({r},{g},{b})' | c40653f0dc0ebd23d2816a189adcb0fa635adcb0 | 3,607,003 |
import sys
def GetData(input_data, desc=False):
"""
#################################################################
Get sequence data from file or list with check.
:param input_data: type file or list
:param desc: with this option, the return value will be a Seq object list(it only works in fil... | 8299c1807584539654105dbe93d6084dc48e29cb | 3,607,004 |
def process(request, order_form, order):
"""
Payment handler for the eGate payment gateway.
"""
# Set up the data to post to the gateway.
post_data = {
"vpc_Version": GATEWAY_VERSION,
"vpc_Command": GATEWAY_COMMAND,
"vpc_AccessCode": EGATE_ACCESS_CODE,
"vpc_Merchant"... | 7d094a6dcf04f5059702946929a24bb43742d008 | 3,607,005 |
def hessian(file_prefix):
""" generate hessian DataFile
"""
name = autofile.file.name.hessian(file_prefix)
writer_ = autofile.file.write.hessian
reader_ = autofile.file.read.hessian
return model.DataFile(name=name, writer_=writer_, reader_=reader_) | b52bd64b877a349479eb85e9058d1077421955ac | 3,607,006 |
def config(config_values):
"""
A callback method that loads information from the HaProxy collectd plugin config file.
Args:
config_values (collectd.Config): Object containing config values
"""
module_config = {}
socket = DEFAULT_SOCKET
proxy_monitors = []
excluded_metrics = set()
... | 35ea6f39fd2ac5f844595b71549878f023d3a701 | 3,607,007 |
def retarded_gf(h_ao, s_ao, energy, gamma_left, gamma_right):
"""
Retarded Gf using approx
"""
return np.linalg.inv(energy*s_ao-h_ao+(1j/2.)*(gamma_left+gamma_right)) | 56d21bc8ef6e88dcf204eda35ec40199f3fabc26 | 3,607,008 |
def train_client_model(client, local_epochs, model, train_data, train_labels, val_data, val_labels, val_people,
val_all_labels, weights_accountant, individual_validation):
"""
Utility function training a simple CNN for 1 client in a federated setting and adding those weights to the
we... | 41a68aa36affdf20db3b62e6dfc1903f7e6bca97 | 3,607,009 |
def _parse_config_args(args):
"""
Parse stub configuration arguments, which are strings of the form "KEY=VAL".
`args` is a list of arguments from the command line.
Any argument that does not match the "KEY=VAL" format will be logged and skipped.
Returns a dictionary with the configuration keys and ... | 6295f95ae798445d94ab4575bbb88a57b03b5df4 | 3,607,010 |
def _compute_targets(ex_rois, gt_rois):
"""Compute bounding-box regression targets for an image."""
assert ex_rois.shape[0] == gt_rois.shape[0]
assert ex_rois.shape[1] == 4
# assert gt_rois.shape[1] == 5
return bbox_transform(ex_rois, gt_rois[:, :4]).astype(np.float32, copy=False) | 07b53781d16c8274914956baaba78bb64a9a9562 | 3,607,011 |
import click
import functools
def task_app(make_config, make_tasks):
"""
Create a `Task App` from a function
Decorates a function
:param make_config: callable(index, config, **query)
:param make_tasks: callable(index, config, **kwargs)
:return:
"""
def decorate(app_func):
def ... | 5c0b62ff50177dc1761f328e03b9446c04ba1df0 | 3,607,012 |
def is_proc_similar_to(proc1, proc2) -> bool:
"""
Checks if two processes are similar
"""
if fuzzy_match(proc1.cmdline(),proc2.cmdline(), threshold=90) \
and proc1.cwd() == proc2.cwd():
return True
return False | ffecdef57a7b6e956d81797ee2f4b925b113e18b | 3,607,013 |
def pad(x, max_size, value=0.0):
"""Makes the first dimension of x to be at least max_size.
Args:
x: a 3-D tensor.
max_size: an int32 or int64 tensor.
value: the value that the new elements of x will have.
Returns:
The expanded tensor with shape
[max(x.shape[0], max_size), x.shape[1], x.sh... | 2f5b69b98226df626d4c6d24fc45053f72dc98e7 | 3,607,014 |
def _infer_shape_dtype_and_create_handle(initial_value, shape, dtype, name):
"""Infer shape and dtype from initial_value and create a variable handle."""
with ops.name_scope(name, "Variable", skip_on_eager=False) as name:
handle_name = ops.name_from_scope_name(name)
unique_id = "%s_%d" % (handle_name, ops.u... | 227b9ecc5d3efc6cbcc5e9eaf02b64b962c0fa71 | 3,607,015 |
def region(request):
"""
Pick the oldest types in that region for scanning.
"""
if 'HTTP_EVE_REGIONID' in request.META:
if MapRegion.objects.get(id=request.META['HTTP_EVE_REGIONID']) is not None:
# Pick types based on region and age
region = MapRegion.objects.get(id=requ... | 4abd2e1fc9c62fc03275070136a1beb5f5a02244 | 3,607,016 |
from typing import Sequence
from typing import Any
import torch
from typing import Callable
def batch_states(
states: Sequence[Any], device: torch.device, phi: Callable[[Any], Any]
) -> Any:
"""The default method for making batch of observations.
Args:
states (list): list of observations from an ... | 1238fd234dc6dc09615418c1897f8d14c160df38 | 3,607,017 |
def path_info_run(subj, run, design='standard'):
"""Construct path information dict for current subject/run.
Parameters
----------
subj : int
subject number (1..6 inclusive)
run : int
run number (1..12 inclusive).
design : str, optional
which design to use, defaults to '... | a7dc597b86749d35d07816d778a435384b94d5a9 | 3,607,018 |
def total(raster, crs = None, factor = 1):
"""
Calcule the total valid area.
Parameters
----------
raster : str
Raster filename
crs : str
Coordinate reference system code.
factor : int or float
Multiplicative factor to the area.
"""
square = area(raster, crs,... | a95a05c804b8dfcfa16beccb82768d4d2ded52b3 | 3,607,019 |
def execute(channel, command):
"""Execute command and get remote PID"""
command = command + '& pid=$!; echo PID=$pid'
stdin, stdout, stderr = channel.exec_command(command)
pid = int(stdout.readline().replace("PID=", ""))
return pid, stdin, stdout, stderr | ecefbef4d4ed7b8e954f688006e2356b6fc710ac | 3,607,020 |
def verify(token: str):
"""
View function where a registration can be verified.
"""
if current_user.is_authenticated:
return redirect(url_for("index"))
user_handler.verify_registration(token)
return redirect(url_for(".login")) | 431b587d79d6822a390e8dd2dde0a744ecb4c033 | 3,607,021 |
def find_attributes(dataset: str = "hsapiens_gene_ensembl",
save: bool = False,
output: str = "apybiomart_attributes.csv") -> pd.DataFrame:
"""Retrieve and list available attributes for a given mart.
Args:
dataset: BioMart dataset name (default: "hsapiens_gene_en... | ea4ee215c443da537d9036effb409f7ce1206cca | 3,607,022 |
def readable_bucket_size(bucket):
"""
Returns the number of bytes in a bucket in a human readable form.
"""
return sizeof_fmt(bucket_size(bucket)) | 9b0948e3ea3f53b4e4df0307258ec3cae607fb11 | 3,607,023 |
import time
def wait_to_complete(test_function, *args, **kwargs):
"""
Implements a basic return loop for a given function which is capable of a
True|False output
Args:
test_function: Function which returns a bool once the target
state is reached
delay (int): The number of ... | 84e75876c39a21e8a5d6249a6fd4c3d94895f5d4 | 3,607,024 |
def spell_check(T, w):
"""Spellchecker
:param T: trie encoding the dictionary
:param w: given word
:returns: a closest word from the dictionary
:complexity: linear if distance was constant
"""
assert T is not None
dist = 0
while True: # Try increasing distances
u = search(... | bfeeddeab1615650d1c8355b10146a9b198d51a2 | 3,607,025 |
def bindshell(port):
"""Args: port
Standard bind shell."""
return listen(port), dupsh() | 0dadf3a3f1a62d4cc11745bd6b868188dd9c339f | 3,607,026 |
def add_pylivetrader_imports(code: str) -> str:
"""
add all imports from the pylivetrader api
"""
imports = """
from pylivetrader.api import *
\r\n
"""
return imports + code | 8077a28dff60e00c2f44fe2aaf5a226a5ae15c7c | 3,607,027 |
import re
def get_name(str: str):
"""Get the name of the class object"""
if str.isupper():
return str
return " ".join(re.sub(r"([A-Z])", r" \1", str).split()) | 414d7634459f25549275447fc124a509429fc1b5 | 3,607,028 |
def get_synonyms(wikibase_item):
"""
get the entity aliases
"""
client = Client() # doctest: +SKIP
entity = client.get(wikibase_item, load=True) # get a wikidata.Entity object for Operation Protective Edge
return entity.data['aliases'] | 793ab29dac845c9d3bbe2312f061d88434fc1887 | 3,607,029 |
import os
def create_directory():
"""
Function to create a directory to store the documents.
:return True/False: Creation Successful Flag.
"""
# If it already exists, return True.
if os.path.isdir(TF_IDF_FILES_DIR) is True:
print("Directory to store the tf-idf already exists. Moving on.")
return True
el... | 153efb5a9618b9ac5e76c1613e20a210ed1b06e5 | 3,607,030 |
def convert_legacy_structure(output_types, output_shapes, output_classes):
"""Returns a `Structure` that represents the given legacy structure.
This method provides a way to convert from the existing `Dataset` and
`Iterator` structure-related properties to a `Structure` object. A "legacy"
structure is represen... | f072ce004fc362f8b88b00de0c862a4fc0249bca | 3,607,031 |
def _calculate_languages_ratios(text):
"""
Calculate probability of given text to be written in several languages and
return a dictionary that looks like {'french': 2, 'spanish': 4, 'english': 0}
@param text: Text whose language want to be detected
@type text: str
@return: Dictionary with lang... | ea0a245dcbb5dfb5994177b92bb74442c401b8a4 | 3,607,032 |
def union_intervals(x, y, stacked=True):
""" Union of numeric intervals.
:param array x: Start time of the intervals
:param array y: End time of the intervals
:param bool stacked: Return as matrix
.. code:: python
>> union_intervals([1, 2, 15], [10, 11, 20])
... | b5fedfecddc61635d22cf8703733382c7ce67da1 | 3,607,033 |
from typing import List
from typing import Optional
from typing import Dict
from typing import Union
from pathlib import Path
import codecs
import os
import tqdm
def prepare_fisher_english(
corpus_path: Pathlike,
audio_dirs: List[str] = FISHER_AUDIO_DIRS,
transcript_dirs: List[str] = FISHER_TRANSCRIPT_DIR... | fbabab73c2c29636489d2ef3815235b1ec173166 | 3,607,034 |
import codecs
def export_xlsx(wb, output, fn):
"""
export as excel
wb:
output:
fn: file name
"""
wb.close()
output.seek(0)
response = HttpResponse(output.read(), content_type="application/vnd.ms-excel")
cd = codecs.encode('attachment;filename=%s' % fn, 'utf-8')
response['Co... | 68cebd96c90630c79453b246e755f7cd5223cfa0 | 3,607,035 |
def parse_flowcell_id(flowcell_id):
"""
Return flowcell id and any status encoded in the id
We stored the status information in the flowcell id name.
this was dumb, but database schemas are hard to update.
"""
fields = flowcell_id.split()
fcid = None
status = None
if len(fields) > 0... | 621745aba31ed906e823177d0eebc33a8231843f | 3,607,036 |
def create_server():
"""
Creates a server
"""
return HTTPServer(('127.0.0.1', 3000), SimpleHTTPRequestHandler) | e773e56625a85d94fd5312e449aff32919c759e0 | 3,607,037 |
from typing import Optional
import torch
import math
def generate_geometry_image(size: int,
device: Optional[torch.device] = None):
"""
Generate an spherical geometry image [Gu et al. 2002 and Praun and Hoppe 2003]
of size [2 * size + 1, 2 * size + 1]. This can be used ... | 8403d3525c2b43320c9b7e6c7d55bfcef074a70d | 3,607,038 |
def proc_sched_b(dict_sched_b):
"""
This function processes Part1 Interest and Part2 Ordinary Dividends of the Sched B document.
"""
items = dict_sched_b["Part1_Interest"]["i1"]
i_2 = 0
for i in items:
i_2 += int(i.split("=")[1].strip())
dict_sched_b["Part1_Interest"]["i_2"] = i_2
... | 66d07b785c90b91f64539d49617f8f0be0f31c12 | 3,607,039 |
def _cross_val_predict(estimator, X, y=None, *, groups=None, cv=None,
n_jobs=None, verbose=0, fit_params=None,
pre_dispatch='2*n_jobs', method='predict', safe=True):
"""This is a fork from :meth:`~sklearn.model_selection.cross_val_predict` to allow for
non-safe clon... | 73846fb90c6ac242ee689b26fb3053a4aede8822 | 3,607,040 |
def position_defined():
"""
In case user wants to see a specific packet inside a
specific pcap file, provide file name with the position
-r file.pcap:position
Returns:
True if ctr is good
False: if ctr is not good
"""
return (True if ctr == pos... | d4fd19196988d2f5f5ea7e5e88d640902165e1b7 | 3,607,041 |
import os
from datetime import datetime
import json
def my_twitter_timeline() -> FlaskResponse:
""" Update the locally saved timeline (if too old) and return it. """
screen_name = current_app.config["TWITTER_ACCOUNT"]["screen_name"]
timeline_filename = "timeline_" + screen_name + ".json"
data_store = ... | 545c0c29eac9c44c408a99c3315850a5289cc3d9 | 3,607,042 |
def residual(inputs, outputs, dropout_rate):
"""Residual connection.
Args:
inputs: A Tensor.
outputs: A Tensor.
dropout_rate: A float range from [0, 1).
Returns:
A Tensor.
"""
outputs = inputs + tf.nn.dropout(outputs, 1 - dropout_rate)
outputs = common_layers.la... | 71c850743cc5f62b55fbd372c123238e3de01b2e | 3,607,043 |
from scipy.special import beta
from scipy.misc import comb
def make_categorical_regression(n_samples=100,
n_features=10,
n_informative=10,
n_categories=10,
imbalance=0.0,
... | a8eac2fb164d79257cef2ffdf6d1013287144b73 | 3,607,044 |
def _toeplitz_mult_pd(r, c, x, f_method='std'):
"""Multiply Toeplitz matrix by vector using Pustylnikov's decomposition.
Compute the product y = Tx of a Toeplitz matrix T and a vector x, where T
is specified by its first row r = (r[0], r[1], r[2],...,r[N-1]) and its
first column c = (c[0], c[1], c... | 385f37deb8d345597b46073b7125c1768ac57e25 | 3,607,045 |
def readInstrumentStringToInstrument(ins_line):
"""
Function for reading instrument info to a Instrument object
:param str ins_line: css intrument line
:returns: Instrument object
"""
instrument = [None]*14
instrument[Instrument.INSTRUMENT_NAME] = unidecode.unidecode(ins_line[8:58].strip(... | 76e087ee09ba50c84de7b5489dd486c7cde7381c | 3,607,046 |
def train_model(X_train_aug, y_train,
X_val_aug, y_val,
X_test_aug, y_test,
epochs = epochs):
"""
Main Training function with the following properties:
Optimizer - Nadam
Loss function - Categorical Crossentropy
Batch Size - 128 (any more wi... | 6458000fafef6deca008f451ff28c4b5e0c3657a | 3,607,047 |
import re
def what_lang(filename):
"""
Judge what language the file is written by from filename extention.
"""
langs=[('c|cc|cpp|h', 'c/c++'),
('java', 'java'),
('sh', 'sh'),
('pl', 'perl'),
('rb', 'ruby'),
('py', 'python'),
('xml', 'xm... | 02316266746bfc59cbdc3ad4b84a8be667158109 | 3,607,048 |
def get_random_proxy():
"""
代理
:return:
"""
REDIS_HOST = '192.168.5.242'
REDIS_PORT = 6379
REDIS_DB = 7
REDIS_PASSWORD = 'Gouuse@spider'
redis_1 = Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,
password=REDIS_PASSWORD)
while True:
try:
... | e20bd647b81b453e991387654fd8cd17d81769a2 | 3,607,049 |
def get_text(xml, tag):
"""Return the text from a given tag and XML element.
"""
elem = xml.find(tag)
if elem is not None:
return elem.text.strip() | ece7c28a98f8bf61a3d182a2109875b6a031dbaa | 3,607,050 |
def _get_scores(predictions_dict):
"""Returns the attention scores, sliced by source and target length.
"""
prediction_len = _get_prediction_length(predictions_dict)
source_len = predictions_dict["features.source_len"]
return predictions_dict["attention_scores"][:prediction_len, :source_len] | c3908f0fa721056d540857b09207f055c7a34aa5 | 3,607,051 |
def sample_TPR_given_BA(ba):
"""
Uniformly sample TPR given BA on the interval in which,
BA, TPR and TNR are bounded by [0, 1]. How this is
accomplished is as follows.
The Balanced accuracy is defined as,
BA = 0.5 * (TPR + TNR)
with TPR being the True Positive Rate and TNR being
... | 0ab2ee3bb10387d37da06bbb8b0acc2161b6ba88 | 3,607,052 |
import re
import json
def search(query, source = None, page= 1 , authtoken = None, prints = True):
"""Return array of dictionaries of search results.
:param str query: (required), query to search with
:param str source: (optional), source to search
:param +'ve int: (optional), page number of search
... | 6c17572d6c6a2c208a4458adef3fcbe35cd13413 | 3,607,053 |
from typing import Dict
from typing import Any
from typing import Iterable
from typing import Hashable
def get_in(
dictionary: Dict[Any, Any],
keys: Iterable[Hashable],
default: Any = None,
) -> Any:
"""Traverses a set of nested dictionaries using the keys in
kws, and returns the value assigned to... | af8d88f7f0a9f8af6f201e6d626392aec3f94864 | 3,607,054 |
def extreme(
data,
tech,
var="resource",
how="max",
length="1D",
n=1,
groupby_length=None,
padding=None,
normalize=True,
**kwargs,
):
"""
Returns timesteps for period of ``length`` where ``var`` for the technology
``tech`` across the given list of ``nodes`` is either ... | a0834682c3c85c5a1703652509c3a82b86aeaca2 | 3,607,055 |
def subpixel_translate(inputs, shift, interp_axes=None, output_shape=None):
"""
Translates an image by a subpixel shift value using bilinear interpolation
Args:
inputs (ArrayLike): data to translate
shift (Sequence):
amount to translate each dimension specified by `interp_axes`... | b2480333c8f49ecd1da211a3b535edc228cb073e | 3,607,056 |
import json
def get_export_definition(export_uri):
"""Reads export definition from S3, returns dict"""
s3 = boto3.resource('s3')
parsed_uri = urlparse(export_uri)
logger.info('Downloading export defintion %s', export_uri)
data = s3.Object(parsed_uri.netloc, parsed_uri.path[1:]).get()['Body']
... | d5db1b21053734be160dd7adefd1a7ca6bf999d6 | 3,607,057 |
def resnet_v1_101(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
store_non_strided_activations=False,
reuse=None,
scope... | f44ab414c37d14aaef0a517f721c35d4fc7d4006 | 3,607,058 |
import sqlite3
def getCEA(id):
"""fetch all CEA targets for the given table id"""
with sqlite3.connect(DB_PATH) as conn:
conn.row_factory = dict_factory
db = conn.cursor()
db.execute('SELECT row_id, col_id, mapped FROM cea WHERE table_id=?', [id])
return db.fetchall() | 4d92c1333d137d1bb99f69086f5ff05aab8398cd | 3,607,059 |
def tree_distance(Z1, Z2, weighted=False, norm=zscore):
"""Calculates the squared path-difference distance between two given dendrograms.
Args:
Z1 (ndarray): Linkage of the 1st dendrogram.
Z2 (ndarray): Linkage of the 2nd dendrogram.
weighted (boolean): True if the weighted distance should be calculated; False... | 630a16c6feb2815c17ecd20d676fe548dc346960 | 3,607,060 |
import os
def copy(genome_dir, cds_dir, new_dir, processes=1, verbose=0):
"""
Copy directories with whole genomes and cds to a new location.
Parameters
----------
genome_dir: str
The location of a directory with genomes.
cds_dir: str
The location of the cds directory.
new_... | 7edc4b352eada00b6be9b1976cf676bf808bb1ac | 3,607,061 |
def export_instance(request, instance_id, instance_name, status_check_interval):
"""Export instance image to S3"""
project_id = request.user.tenant_id
aws_access_key_id, aws_secret_access_key, region_name = utils.get_api_keys(project_id)
buckets = s3.list_buckets(request)
if project_id not in bucke... | 8764de8945f6c0ad58356f795d205585e9abe201 | 3,607,062 |
from typing import Optional
def downsample_block(
filters: int,
size: int,
strides: int = 2,
apply_batchnorm: bool = True,
name: Optional[str] = None,
) -> tf.keras.Sequential:
"""Creates a convolutional block.
Conv2D => Batchnorm => LeakyRelu
Adapted from tensorflow github:
/tensorflow_e... | 8503f4a3cbb8dceee2c082aa64f348d6f60e9e05 | 3,607,063 |
def de_underscore(df, which='b'):
"""
remove underscores from index and / or columns, replacing with space
Note, default behavior is to quote underscores
:param df:
:param which: row column b[oth]
:return:
"""
# workers
def de_(n):
"""
replace underscores with space
... | c94353c75eb619b79bc67a946d09ba218491d9cd | 3,607,064 |
from typing import Union
from pathlib import Path
from typing import Tuple
from typing import Dict
def evaluate_metrics_from_files(pred_file: Union[Path, str],
ref_file: Union[Path, str]) \
-> Tuple[Dict[str, float], Dict[int, Dict[str, float]]]:
""" Evaluate the translatio... | e7293cb490bc6b0e0e20811b34c843a422395a9d | 3,607,065 |
def list_emergencies():
"""
List all emergencies contact for each employee that works in the organisation
"""
check_admin()
emergencies=Emergency.query.all()
return render_template('admin/emergencies/show.html',
emergencies=emergencies, title="Emergencies") | a401f3364cdcea2076d8e25519319e7278271254 | 3,607,066 |
from typing import Optional
from typing import Union
from typing import Any
def get_monitor() -> Optional[Union[resource_pb2_grpc.ResourceMonitorStub, Any]]:
"""
Returns the current resource monitoring service client for RPC communications.
"""
monitor = SETTINGS.monitor
if not monitor:
re... | 7b713d1b52a5364618260b55f16eaaf0feb601eb | 3,607,067 |
from twisted.internet import protocol
from twisted.internet import reactor
def get_locker_server(locker, port):
"""Build keytab server protocol.
"""
def _response(success=False, message=None, keytabs=None):
"""Construct response."""
return {
'success': success,
'me... | 99ba3de4a740cef89ae4e483591323c972ed0342 | 3,607,068 |
from datetime import datetime
import math
def list_content(archive, verbose=False):
"""List the contents of an archive"""
with open(archive, 'rb') as f:
while True:
tar_header = TarHeader()
f.readinto(tar_header)
name = tar_header.name
if not name:
... | 6e006d7437078e3270ec53a9fe16040ac2980483 | 3,607,069 |
def calc_best_overlap_from_selected_column_in_df(acc_db, df, experiment_col="interface_score", pred_col="THOIPA"):
"""
Create Bo Curve parameter for protein acc_db and return the output as a dataframe
Parameters
----------
acc_db : str, protein name
prob_pos : the thoipa prediction score for eac... | 1f6b3adb4a2a1ef7ab84757c8b407831380f94e1 | 3,607,070 |
import time
import os
import pickle
def preprocess(inpath, outdir):
"""
Preprocesses the HTML file at the inpath and writes it out with the same
name to the output directory. Returns the number of bytes it processed.
"""
time.sleep(0.8)
with open(inpath, 'r') as f:
# Parse the HTML us... | 4611f0d47be9901e72f81428084f37a59233d793 | 3,607,071 |
import pathlib
import os
def get_default_settings_file()->str:
"""Return the path to the default settings file
Returns:
str: path to settings file
"""
env_file = 'config.env'
root = pathlib.Path(__file__).parent.absolute()
env_path = os.path.join(root, env_file)
return env_pat... | 14fb9005e9b67b2cd1581a04f87ff8df1400c126 | 3,607,072 |
def _unique_in_order(seq):
"""
Utility to preserver order while making a set of unique elements.
Copied from Markus Jarderot's answer at
https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order
Args:
seq : sequence
Returns:
... | e02624dee4275d79dbce8dd67b07429ba3828e86 | 3,607,073 |
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def auth_filter(app):
return OAuth(app, conf)
return auth_filter | 91d538132c618bfe408103404f01b6a503363c51 | 3,607,074 |
def extra_node_ids(a, b):
"""
Return list of nodes in a which aren't in b by id attribute.
:param etree.ElementTree a: ElementTree representing first SVG document.
:param etree.ElementTree a: ElementTree representing second SVG document.
"""
ids_a = set([ el.attrib['id'] for el in a.iter() ])
... | 94728ab3600df1ab31bd2c72e4712eb3540baa5a | 3,607,075 |
def format_hsl(hsl_color):
# type: (_HSL_COLOR) -> str
""" Format hsl color as css color string.
"""
hue, saturation, lightness = hsl_color
return 'hsl({}, {:.2%}, {:.2%})'.format(hue, saturation, lightness) | 6c60950e4abaa124ee1ed7b66c9cd30d2fc3f658 | 3,607,076 |
def get_density(mass:np.array, volume:np.array, atomu=1/constants.Avogadro*10)->np.array:
"""
Calculate the density
Parameters
----------
mass: np.array
volume: np.array
Returns
-------
np.array
resulting density
"""
return atomu * mass / volume | 51e951c4208895f9099f05190080329fc932207f | 3,607,077 |
def authenticate_user(id_: int, paraphrase: str, session: Session) -> bool:
"""Authenticate a user based on the ID and his paraphrase."""
user = None
try:
user = session.query(User).filter(User.id == id_).one()
except NoResultFound:
raise UserNotFound(id_=id_)
hashvalue = user.paraph... | a664760b5a061b2698fceafb979658d954f44243 | 3,607,078 |
def abstractToSentences(abstract):
"""Convert an abstract DOM object to plaintext; returns plaintext and list of sentence bounds
"""
sentences = handleSentence(abstract.firstChild.firstChild, [])
bounds = calculateBounds(sentences)
return ' '.join(sentences), bounds | 9d2cdd84535a497b1f617ac944d2afc7e1b11547 | 3,607,079 |
def student_files(request, fileid, distid=''):
"""
Student file, uploaded by student as professionalskill. Model in students-app
Type3 and 4 (support and profskill) staff can see all studentfiles.
Responsible and assistant of student can view files.
Student itself can view its own files
:param ... | 37473308fab49676c728e110cf61eec68fdbddac | 3,607,080 |
def getAdminAppViewValue(appname, keyname, parsename):
"""This helper method returns the value for the specified application
and key name, as fetched by AdminApp.view().
Parms: appname - the name of the application
keyname - the name of the app parameter, eg CtxRootForWebMod
parsename... | 1afb0dece60871926b33dd7f9f054e4b3019c16a | 3,607,081 |
def runOCcmd(cmd, base_cmd='oc'):
""" log commands through ocutil """
logger.info(base_cmd + " " + cmd)
return ocutil.run_user_cmd(cmd, base_cmd=base_cmd, ) | f8cba9fd1123abb01ff8ba4ab6e836463102dfc3 | 3,607,082 |
from typing import Iterable
def get_score(bits: Iterable[int]) -> int:
"""Get the score.
For each "1" add 1 for each "0" takeaway 1
"""
return sum(-1 if bit == 0 else 1 for bit in bits) | 440e831ca4d02be57a3e394d268b95f7af5fa22e | 3,607,083 |
import random
def _pathway_feature_permutation(pathway_feature_tuples,
permutation_max_iters):
"""Permute the pathways across features for one side in the
network. Used in `permute_pathways_across_features`
Parameters
-----------
pathway_feature_tuples : list(tup(... | 98f65a6bedddfd44122f024f007fc29358a6ca96 | 3,607,084 |
def get_cli_fname(lon, lat, scenario=0):
"""Get the climate file name for the given lon, lat, and scenario"""
# The trouble here is relying on rounding is problematic, so we just
# truncate
lon = round(lon, 2)
lat = round(lat, 2)
return "/i/%s/cli/%03ix%03i/%06.2fx%06.2f.cli" % (
scenari... | 2310bcfc10c2ae5b80d67bed147625e365388fff | 3,607,085 |
from .models import Grid
def ajaxGenerateSimilarity(request):
"""
This function will generate the similarity matrix for concers and alternatives
"""
if request.POST.has_key('gridUSID'):
grid1 = Grid.objects.filter(user=request.user, usid=request.POST['gridUSID'])
if len(grid1) >= 1:
... | ae14fc262b38e63aa827d25991c352d45187f506 | 3,607,086 |
def lambda_rank(input_dim, is_infer=False):
"""
The input data and label for LambdaRank must be sequences.
parameters :
input_dim, one document's dense feature vector dimension
The format of the dense_vector_sequence is as follows:
[[f, ...], [f, ...], ...], f is a float or an int number
... | b67a398f1abe9b3fdbabee629eebfcd5cd06656e | 3,607,087 |
def flow_to_rgb(flow):
"""
Visualizes optical flow in hsv space and converts it to rgb space.
:param flow: (np.array (h, w, c)) optical flow
:return: (np.array (h, w, c)) rgb data
"""
im1 = flow[:, :, 0]
im2 = flow[:, :, 1]
h, w = flow.shape[:2]
# Use Hue, Saturation, Value colour ... | 1975143d1e34a34f9ea9e59611c0766ef3dc00a7 | 3,607,088 |
def bookmark_list():
"""List all bookmarks for the current user"""
client = get_client()
bookmark_iterator = client.bookmark_list()
def get_ep_name(item):
ep_id = item["endpoint_id"]
try:
ep_doc = client.get_endpoint(ep_id)
return display_name_or_cname(ep_doc)
... | 8dd982bd33d78000363ac14a708fd774abac7558 | 3,607,089 |
import dill
import yaml
import os
def load(path: str,
map_location=None,
auto_install=False,
pickle_module=dill,
**pickle_load_args):
"""Load object with state from the given path
Loads a flambe object by using the saved config files, and then
loads the saved state int... | 1b8ba574c32c20e7d297719e0ceecb98c826f077 | 3,607,090 |
from typing import Optional
def checkpoint(
checkpoint_name: Optional[Text] = None
) -> phase_branches.PhaseFailureCheckpoint:
"""Creates a checkpoint phase that checks if all the previous phases passed.
Args:
checkpoint_name: Optional name for the checkpoint phase; if not specified,
this defaults ... | 05462856e21ffd0cdc874173d9e54b4dbadc5850 | 3,607,091 |
def alternate_signal_ww(signals, sample_left, sample_right):
""" stretching/compressing of the signal + resampling"""
# stretch/compress signal to the new window size using the sample to the left and right (for stretching)
orig_size = signals.shape[0]
new_size = int(ww_factor * orig_size)
total_win ... | cd969814387d7544de509024fd5b745328a1991d | 3,607,092 |
from pathlib import Path
import click
def update_file(
path: Path,
text: str,
encoding: str,
verbose: bool,
quiet: bool,
test_run: bool,
in_path: Path,
git_repo,
) -> bool:
"""Update a file."""
changed = False
if not path.exists():
if not test_run:
path... | 546943db9bc02bf27915521c93122ccc3e25dbe8 | 3,607,093 |
from typing import Match
def _new_match():
"""Crate new Match instance."""
oxm_tlv1 = OxmTLV(oxm_class=OxmClass.OFPXMC_OPENFLOW_BASIC,
oxm_field=OxmOfbMatchField.OFPXMT_OFB_ETH_TYPE,
oxm_hasmask=False, oxm_value=b'\x88\xcc')
oxmt_lv2 = OxmTLV(oxm_class=OxmClass.... | a41d3a2b32298dc728574865532ebe96ac5ddcb4 | 3,607,094 |
import json
def get_stooges(stooge_file):
"""Get regular and psychedelic stooges."""
with open(stooge_file) as data:
stooges = json.load(data)
return stooges | afe1fc38886626ab7754f0229fde0531d36421a5 | 3,607,095 |
def sim_triggers(bpg, tpb, signal, trigger_idx, digit_samples, light_det_noise):
"""
Generates digitized waveforms at specified simulation tick indices
Args:
bpg(tuple): blocks per grid used to generate digitized waveforms, `len(bpg) == 3`, `prod(bpg) * prod(tpb) >= digit_samples.size`
... | aeeb469f8757d953b3976633f3dcf15c37f1e298 | 3,607,096 |
import os
import ctypes
from os.path import join, dirname, getmtime, exists, expanduser
def compile_speedup():
"""Tries to compile/link the C version of this module
Like it really makes a huge difference. With a little bit of luck
this should *just work* for you.
You need:
- Python >= 2.5 for ... | c91a1d249a1d6d082c1dbadecc9f764a6b6c2ff3 | 3,607,097 |
import gettext
def lazy_gettext(*args, **kwargs):
"""Lazy gettext.
https://github.com/mrjoes/flask-babelex/pull/8
"""
return make_lazy_string(gettext, *args, **kwargs) | bb3b882f1f67b8b5df8ce38b69146f02965a7a38 | 3,607,098 |
def setup(app):
# type: (Sphinx) -> Dict[str, Any]
"""Sphinx extension setup function.
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.ap... | 7a956377ea5dc20676275c7ed88fd1502b16e059 | 3,607,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.