content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def admin_download_request_file(lic_id):
"""Generate admin version of the view for downloading request files."""
lic = License.query.get_or_404(lic_id)
response = make_response(lic.request)
response.headers['Content-Type'] = 'application/octet-stream'
response.headers['Content-Disposition'] = (
... | 85ecbb1666a56d6f864a61c29db927e9d90fa7c7 | 74,100 |
import base64
def dict_from_payload(base64_input: str, fport: int = None):
""" Decodes a base64-encoded binary payload into JSON.
Parameters
----------
base64_input : str
Base64-encoded binary payload
fport: int
FPort as provided in ... | 98277b109af80d0bbe24b38ce164d053109875fb | 74,101 |
import requests
def post_service2(url, scale_key_pair):
"""Using our existing user data from s1, we use this function to
send a post request to s2, for a new note pitch.
Keyword Arguments:
url: The url of service 2.
scale_key_pair: A key pair scale list dictionary.
"""
service_2... | 113a47b8f004646007d8ab1b408facc18cf33c23 | 74,102 |
from typing import Set
def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
"""Return True if `leaf` is a star or double star in a vararg or kwarg.
If `within` includes VARARGS_PARENTS, this applies to function signatures.
If `within` includes UNPACKING_PARENTS, it applies to right hand-side
ext... | 0c83dc2993afedebfd80f0213b2a44f8898485a8 | 74,103 |
def mass_function_abc(m, a, b, c):
"""The parametrized surpression function of the halo mass function"""
return (1 + (a / m)**b )**c | d4e0b1d39a67baa121a28fc644b75c9bfd714c5e | 74,104 |
def get_processing_output(
pipeline_execution_arn: str,
step_name: str = "BaselineJob",
output_name: str = "monitoring_output",
):
"""Filters the model packages based on a list of model package versions.
Args:
pipeline_execution_arn: The pipeline execution arn
step_name: The option... | 47f68636abf993ab4c779054a68f1bce39481582 | 74,105 |
def upload_album(
self,
photos,
caption=None,
upload_id=None,
from_video=False,
options={},
user_tags=None,
):
"""Upload album to Instagram
@param photos List of paths to photo files (List of strings)
@param caption Media description (String)
@param upload_id Uniq... | 8b9e0a92c973ea90018f1356c44fe6e9047229f3 | 74,106 |
async def _build_sequence(ctx):
"""Construction d'une séquence-réaction par l'utilisateur"""
reponse = ""
fini = False
while not fini:
message = await ctx.send(
"Réaction du bot : prochain message/commande/média, "
"ou réaction à ce message"
)
ret = await ... | b118ab23c14ac59671592190ecb805671399f45f | 74,107 |
import math
def ffn_layer(x, d, d_o, dropout=None, scope=None, numblocks=None):
"""
FFN layer in Transformer
:param numblocks: size of 'L' in fixup paper
:param scope:
"""
with tf.variable_scope(scope or "ffn_layer",
dtype=tf.as_dtype(dtype.floatx())) as scope:
... | 2f2f3a194042cd1d99f1471a079b8a69f1700e48 | 74,108 |
def retain(foo):
"""This method is very important for live source code manipulation. It ensures, that every reference to an object's
method is going to change when the method has been edited (and therefore been overridden). If a reference to a
method is made by providing the method object without calling re... | f615cd295648bc0ef266e9e1f25e60985cc1a1d5 | 74,109 |
def add_config_template(project_id):
"""add a new Config Template
:param project_id:
:return:
"""
parent_project = Project.query.filter(Project.id == project_id).first_or_404()
form = ConfigTemplateForm(request.form)
if form.validate_on_submit():
try:
config_template =... | bf3a9b37408ba0d19b6c26d60ea99d48270cb5ac | 74,110 |
import torch
def scale_invariant_loss(predicts: torch.Tensor, targets: torch.Tensor, reduction="mean"):
"""
outs: N ( x C) x H x W
targets: N ( x C) x H x W
reduction: ...
"""
predicts = predicts.flatten(start_dim=1)
targets = targets.flatten(start_dim=1)
alpha = (targets - predicts).m... | ee07477c4a380e46b8d27e424d79827b268a3524 | 74,111 |
def convert_tan(node, **kwargs):
"""Map MXNet's tan operator attributes to onnx's tan operator
and return the created node.
"""
return create_basic_op_node('Tan', node, kwargs) | a0f2e904ddf57244cf5c8b89ccaa4f41507c7ec3 | 74,112 |
import logging
def set_logger(log_path):
"""Set the logger to log info in terminal and file `log_path`.
In general, it is useful to have a logger so that every output to the terminal is saved
in a permanent file. Here we save it to `model_dir/train.log`.
Example:
```
logging.info("Starting t... | da915706e363fe8e84be67d7b9dfafe7a4487d14 | 74,113 |
from typing import Optional
from typing import Callable
def drop(
data,
value='NaN',
thresh=0,
direction='>',
axis=0,
include=None,
exclude=None,
copy=True,
messenger: Optional[Callable] = Messenger(
verbose=True, indent=0, msg_fn=print)
):
"""
Drop rows or columns ... | 93c80c1c17a6bcd3d621b1fa9c289af60e540004 | 74,114 |
def is_hinted(value):
"""
Check if a value is a tuple of data item and its type hint.
"""
return (
isinstance(value, tuple)
and len(value) == 2
and issubclass(value[1], IgniteDataType)
) | 7680a6ccbc06ae8fdbfaadeac6b31f04cd2e843f | 74,115 |
def cyclic_index_i_minus_1(i: int) -> int:
"""A helper function for cyclic indexing rotor scans"""
return i - 1 if i - 1 > 0 else -1 | ae133f686eb9145da5ed39d7acf37d1385e2687f | 74,116 |
def runtime(permutation):
"""Calculate and return the estimated runtime of a given permutation of the
job ordering. Also return a trace of how the jobs go through the pipeline."""
queue = list(permutation)
running = {x: build_times[x] for x in queue[:QUEUE_LENGTH]}
del queue[:QUEUE_LENGTH]
t = 0... | c03ceb129c1fc65ef94c65857cabfa5cb8edaf36 | 74,117 |
import torch
def natural_mask(o):
"""Applies natural missingness in a batch to non-nan values in the next sample"""
mask1 = torch.isnan(o)
mask2 = rotate_axis0(mask1)
return torch.logical_and(mask2, ~mask1) | 2794ced9714ab5db3a2448599dbf28eb95460b9f | 74,118 |
import json
def loadMetadata(fn):
"""
Load Metadata JSON File
Parameters:
-------------
fn : str - filename
Returns:
-------------
data : dict
"""
data = json.load(open(fn))
return data | 4fa9aceed53cab0c076d4bdc474a08ebccae5ef6 | 74,119 |
def cancel_query(service, last_query_handle):
"""Cancel a query on a keyboard interrupt from the shell."""
# Cancel sets query_state to EXCEPTION before calling cancel() in the
# co-ordinator, so we don't need to wait.
rpc_result = __do_rpc(lambda: service.Cancel(last_query_handle))
_, status = rpc_... | 6c838f16168d8d344173caf56cd9e8df72a682d8 | 74,120 |
def getCorners(max_cnt):
"""Returns the edges of the contour if the approx polygon is a quadrilateral"""
perimeter = cv2.arcLength(max_cnt, True)
epsilon = 0.1 * perimeter
approx = cv2.approxPolyDP(max_cnt, epsilon, True)
boundary_pts = None
if len(approx) == 4:
x2, y2, x1, y1, x3, y3, ... | 3d9d5fca715c8e2fb4978b2beef49ee1119f4032 | 74,121 |
def __get_regulargrid__(shape, kernelarea, sampling, center):
"""
Create a regular grid through tuple 'center'.
Creates a regular grid of values for the given array shape. Such that
there are approximately n samplings per kernelarea, where n is given by
the sampling parameter. The array will be sam... | e193eb89df58bc221de21641f9d33af18815dc61 | 74,122 |
def read_data_chunked(path, table_name, chunksize, columns=None):
"""
Reads data from hdf5 file given as PATH and yields dataframes for each chunk
"""
return HDFDataIterator(
path,
table_name,
chunksize,
columns,
) | 43900a94c1506a816f3cee2f831a1dca33fa38c0 | 74,123 |
def load_json(json_file_path):
"""
Loads json file.
:param str json_file_path: path of json file that will be loaded
:rtype: list
:return: list of json (dictionary) objects
"""
assert (isinstance(json_file_path, str))
with open(json_file_path) as f:
data = load(f)
return data | b8f5a199765b2a8a5056f806507c306841e4a32e | 74,124 |
def update_tuple(origin_tuple, update_value, update_index):
"""Update tuple/namedtuple for specified update_index and update_value."""
# Namedtuple is inherit from tuple.
if not isinstance(origin_tuple, tuple):
raise ValueError("Only tuple/namedtuple supported. Origin_tuple type: "
"%s." ... | 1956777840fe30db01f1a4526e8e79d0ceac8534 | 74,125 |
def decompose_matrix(matrix):
"""
:param matrix:
:return:
"""
return np.linalg.svd(matrix) | 1e110cfcf62f2e35406a6dbd93ce94e65dff1189 | 74,126 |
def generate_diff_output(board, iostandard, drives, slews):
"""
Generates a design which outputs 100Hz square wave to a number of pins
in which each one has different DRIVE+SLEW setting. The IOSTANDARD is
common for all of them.
"""
num_ports = len(drives) * len(slews)
iosettings = {}
... | 18c1bdbe0afa2093a46a792aced3f7aad5375345 | 74,127 |
def get_variation(variation_key, variations_dict, defaults_dict):
"""Convert a string to a tuple of integers.
If the passed variation_key doesn't follow this pattern '0 100', it will
return default values defined in defaults_dict.
This is currently used for defining the variation data of the A/B
e... | 24e069fabcb9bd4dbfbd3c1ea17e859f27fdcceb | 74,128 |
def _serialize_list_value(value, charset) :
""" Serialize list value """
error_code = Error(errOk)
if value is None :
return error_code, NULL_STRING
result = "["
comma = ""
for child_value in sorted(value.value,
key = lambda value: (value.order_number)) :
result += comma... | db56a4b44b8fca1205add7c155e4810d9dc5b459 | 74,129 |
def get_engine(db_url=None, echo=False):
"""
:param db_url: "mysql://user:password@localhost/mydatabase"
:param echo:
:return:
"""
assert (db_url is not None)
engine = create_engine(db_url, echo=echo)
return engine | f51301f3239b974e8ca68011adc6c78c25181c20 | 74,130 |
import os
import nibabel as nb
from qap.qap_utils import raise_smart_exception
def create_header_dict_entry(in_file, subject, session, scan, type):
"""Gather the header information from a NIFTI file and arrange it into a
Python dictionary.
:type in_file: str
:param in_file: Filepath to the NIFTI raw ... | efebfffe35bd02b5ededf83302df242d137470bb | 74,131 |
def generate_network(dataset):
"""
@params: [dataset (Pandas Dataframe)]
@returns: None
Generates a directed graph networkx between users with edges defined by interaction
types from INTERACTIONS using Pandas dataframe dataset. Saves the graph to
filepath graph_out. Currently not decomposed, to... | add7188913e02608e03621de33bcfbc151d27fd2 | 74,132 |
def standardize(train_data, test_data):
"""
Standardize Data Set
"""
train_mean = train_data.mean()
train_std = train_data.std()
train_data = (train_data - train_mean) / train_std
test_data = (test_data - train_mean) / train_std
return train_data, test_data | b66a363cd37f7ebc2accd021866b7d34c415f528 | 74,133 |
import torch
def spread_feature(container, learned_uv, feature, mask1c):
"""
:param container: B,C,R,R
:param learned_uv: B,2,H,W
:param feature: B,C,H,W aligned with latent uv map
:param mask1c: B,1,H,W used to mask latent uv and feature
:return: container
"""
assert float(mask1c.max(... | 38f7602124792bf3f0e3395cd8952aec428ab43e | 74,134 |
import requests
def add_data_results():
"""
Title: Add data processing
URL: site/add_data_results
Method: POST
"""
webPageTemp = ''
webpage = ''
if 'fastaFileTb' in request.files:
debug(1, 'Fasta file uploaded, processing it')
try:
file1 = request.files['fa... | 2b7ee4582a3894a653407c829de2154933397f30 | 74,135 |
def verify_working_dir(pkg):
"""Verify if a package working directory has uncommitted changes or is
outdated and ask the user what to do. Return True if it's ok to continue.
"""
if is_uncommitted(pkg):
if not utils.ask_yn("""\
Package working directory %s has uncommitted changes that will not b... | 514cbd92220c7c62bc01f4162b03e23054311a6a | 74,136 |
def snap_to_lines(fixation_sequence, text_block, method="warp", **kwargs):
"""
Given a `eyekit.fixation.FixationSequence` and `eyekit.text.TextBlock`,
snap each fixation to the line that it most likely belongs to, eliminating
any y-axis variation or drift. Operates directly on the sequence and does
... | 67c4a6cc70af352654396a921a85c2c6cfc0b93c | 74,137 |
def get_total_paper(boxes):
"""Get all paper needed for a list of boxes"""
return sum(get_box_paper(b) for b in boxes) | 92364ace778c777f85b0ad62c5ded154657d2e41 | 74,138 |
def expected_wrt_occupancy(value, occupancy, miss=0.):
"""
:param value: (N, C, D, H, W) / float
:param occupancy: (N, C, D, H, W)
:param miss: float / (N, C, D, H, W)
:return:
"""
return expected_wrt_prob(value, occupancy_to_prob(occupancy), miss) | 357a2d76d576d4a877c9bff8172667d00e259102 | 74,139 |
import tqdm
def download_url(url, destination=None, progress_bar=True):
"""Download a URL to a local file.
Parameters
----------
url : str
The URL to download.
destination : str, None
The destination of the file. If None is given the file is saved to a temporary directory.
pro... | 12b00d4eb426d2441fdfa419a1ae3c706ff6e783 | 74,140 |
def get_app_runtime(yaml_paths):
"""Examines all app's yamls making sure they specify single runtime.
Raises:
ValueError if multiple (or unknown) runtimes are specified.
"""
runtimes = sorted(set(get_module_runtime(p) for p in yaml_paths))
if len(runtimes) != 1:
raise ValueError('Expecting single run... | 6fa6c19dabcfdc67ea81fcd44275c17a28a0eef0 | 74,141 |
from typing import Optional
def bg(col=None) -> Optional[int]:
"""
Get or set the default background color for space objects.
"""
global BACKGROUND_COLOR
if col is None:
return BACKGROUND_COLOR
else:
BACKGROUND_COLOR = int(col)
return BACKGROUND_COLOR | 90caac2fb037e3d561266179c8d97aca817a624d | 74,142 |
from typing import Tuple
def pink_spatial_transform(
img: np.ndarray, transform: Tuple[np.int8, np.float32], reverse: bool = False
) -> np.ndarray:
"""Applying the PINK spatial transformation to an image
Arguments:
img {np.ndarray} -- Image to spatially transform
transform {Tuple[np.i... | 53862b1d2176fddb1858dec0adda1131c43a090f | 74,143 |
import pandas
from typing import Tuple
from typing import List
def gc_skew_shift_detection(
data: "pandas.DataFrame",
) -> Tuple[List[int], int]:
"""Function to detect GC skew shift.
Parameters:
-----------
data : pandas.DataFrame
For columns table with the GC skew.
Returns:
----... | 26e7c49cecb09f40d8bbfb0a1ff6980d18e19108 | 74,144 |
def proposal_layer_fixate(rpn_bbox_pred, im_info, anchors):
"""
Simply returns every single RoI; LRP-HAI later decides
which are forwarded to the class-specific module.
"""
# Get the bounding boxes
batch_sz, height, width = rpn_bbox_pred.shape[0: 3]
rpn_bbox_pred = rpn_bbox_pred.reshape((-1... | 4e3030721f9b39faddad40fce80b98c11421d84e | 74,145 |
from typing import Concatenate
def dense_block(x, nb_layers, nb_channels, growth_rate, dropout_rate=None, bottleneck=False, weight_decay=1e-4):
"""
Creates a dense block and concatenates inputs
"""
x_list = [x]
for i in range(nb_layers):
cb = convolution_block(x, growth_rate, dropout_... | f15dcb9aeb3d6e46ebf6bf70c090fd7b9c9a6383 | 74,146 |
def corr(data1, data2, max_lag):
"""Calculate correlation of two time series for a range
of lags between them.
Uses pandas.Series.corr() to calculate correlation between
two columns of data (i.e. a pandas.Series), with data2
shifted relative to data1 by a range of lags up to max_lag.
:param da... | d1765bd43c93b37494456ee7dac0bdf2c6a37b36 | 74,147 |
from typing import Union
from pathlib import Path
from typing import Optional
def dril(
learner: OffPolicyAlgorithm,
demo_buffer: Union[DictReplayBuffer, ReplayBuffer, str, Path],
gradient_steps: int = 1000,
n_policies: int = 3,
#q: float = 0.98
print_loss: Optional[int] = None,
) -> OffPolicy... | ca7d91fa8fdc875a80bab1f405e2151019a7e8e9 | 74,148 |
def addingbookmark(userkey):
""" Add the bookmark from form submit by /add """
tags = get_cached_tags(userkey)
if request.method == 'POST':
bookmark = updatebookmark(userkey)
if not bookmark:
return redirect(url_for('addbookmark', userkey=userkey, message='No url provided', tags... | ff9df2eff11ba0b1fea80da16595e4bc8a32eb93 | 74,149 |
def p_independent(N_hypercolumns, units_per_hypercolumn,
X, low_noise=10e-10, normalize=True):
"""
This and that
"""
p = np.zeros((N_hypercolumns, units_per_hypercolumn))
for i in range(units_per_hypercolumn):
p[:, i] = np.sum(X == i, axis=0)
if normalize:
p ... | 1abc4e3a53b6b9e6069900bada1254b03294175f | 74,150 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-o',
'--outfile',
help='Output fi... | 3b6b6c18a7c735d373738c3db92abb509a8de250 | 74,151 |
import re
import itertools
import numpy
def read_cst_ascii(source):
"""
Reads data from ASCII data file, exported by CST Microwave Studio. Since
CST can put multiple signals into a single file, this function returns
a hash of signals, where signal names are keys.
"""
if type(source) is str:
... | fb4557c2065b8cbc16f498b3786cc63a1509d31a | 74,152 |
def get_whitelist_overlap_coef(cti_feed: DataFrame) -> float:
"""
Function calculates whitelist overlapping ratio
The higher ratio = the better feed quality
NOTE: THIS FUNCTION IS A MOCK NOW, JUST FOR
TESTING REASONS
TODO: Make working version of function.
Params: dataframe with CTIfeed, d... | 49528571bbb838d8f64f1e519572d24092dd54af | 74,153 |
import os
def get_stage_file(batch_id, table_name) -> str:
"""Return the full path name of stage file for a batch and table name"""
return os.path.join(STAGE_DIRECTORY_PREFIX + str(batch_id), f"{table_name}.parquet") | 2063b817898787face86b3b3c22a7e1de8cb86e6 | 74,154 |
from pathlib import Path
import subprocess
def check_requirements(
identifier: str, requirements_path: Path = ROOT / "optional_requirements.txt"
) -> int:
"""Checks if the packages specified by the ``identifier`` in the
requirements file at ``requirements_path`` are present on the system. If
``install... | cbbb77667aeecd307cd48727407d5f1ae4921fc7 | 74,155 |
import struct
def check_equiv(ins):
"""Checks whether this instruction can be changed with an equivalent one.
'cbytes' is changed if an equivalent instrucion does exist."""
opcode = ord(ins.bytes[ins.opc_off])
modrm = ord(ins.bytes[ins.modrm_off])
# check for equivalent instructions when both op... | f316b11166e7d9ee152dbc4134477e1c8ccd82ad | 74,156 |
def wkt_to_dataframe(wkt_list, geom_name='geometry'):
"""Convert list of WKT strings to a DataFrame."""
df = pd.DataFrame({'wkt': wkt_list})
df[geom_name] = df['wkt'].apply(wkt.loads)
return df | 6ba1e2a6f253a84d0e31913d8b87c70ca8771b84 | 74,157 |
def fetch_eeprom():
"""
See TRM 3.4.2, 3.4,3.
This function dynamically determines how much data to read for c2 eeprom data and downloads
the eeprom iic file.
"""
assert f.isopen()
# fetch 1st 8 bytes
prom=get_eeprom(0,8)
if prom[0] == '\xc0':
return prom # c0 blocks are 8 bytes long
if prom[0] != '... | 45431548d66eacd0df1d317785243ec127ac91f9 | 74,158 |
def run_testsets(testsets):
""" Execute a set of tests, using given TestSet list input """
request_handle = None
total_results = list()
for testset in testsets:
run_testset(testset, request_handle=request_handle, test_results=total_results)
return total_results | e3daf0a85cdb44e4a22bbf8230c7d4b428f45799 | 74,159 |
def init(id, cfg):
"""Previous version init function.
..note:: This function is still supported for backwards compatibility when
the init_standard function is missing. When init_standard is
present this function SHOULD be omitted to avoid confusion to the
reader.
"""
... | 8076f694908bbe8edb8e0297d62a35b26fc1afcb | 74,160 |
import math
def radiacion_solar_onda_larga(tmax, tmin, p_vapor_real, r_solar, r_solar_cielo_despejado):
"""
calcula la radiación neta de onda larga saliente en MJ/m2 y día
param: tmax : temperatura máxima
param: tmin : temperatura mínima
param: p_vapor_real ... | 5404500ff08e5a886f3e000fd8d301faec78cff7 | 74,161 |
def requirements(filename):
"""Reads requirements from a file."""
with open(filename) as f:
return [x.strip() for x in f.readlines() if x.strip()] | 81e5fa3d2a11b9152be6f55ab879b1875fd0b07d | 74,162 |
import os
def get_annotation_path(doc, annotation, data=False):
"""Construct a path to an annotation file given a doc and annotation."""
if doc:
doc, _, chunk = doc.partition(DOC_CHUNK_DELIM)
elem, attr = split_annotation(annotation)
if data:
if doc:
path = os.path.join(pa... | 61545180f8fdb0569708315b92ab57705693faaf | 74,163 |
import socket
def test_internet(host="8.8.8.8", port=53, timeout=3):
"""Returns True if internet is connected
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host,... | b4d87a122028c398c2a55dc37faa359e930a5dc1 | 74,164 |
def basic_block(inputs, filters, training, strides, data_format):
"""Build basic block for ResNet."""
shortcut = inputs
inputs = batch_norm(inputs, training, data_format)
inputs = tf.nn.relu(inputs)
chn_axis = 1 if data_format == 'channels_first' else 3
in_filters = inputs.get_shape()[chn_axis]... | b10bb19cfacda7fb1c161bd463163a882bfa3e51 | 74,165 |
def branch_uptodate(branch, true_on_missing_origin=True):
"""Return True is branch is up to date with origin, otherwise False,
also returns True if no remote defined"""
if branch['upstream']:
if branch['ahead'] or branch['behind']:
return False
return True
if true_on_missing_... | 2c0db03ea469b6f75e94ab6a73ace360e73948a3 | 74,166 |
import json
def sync_issue_status_server(erpnext_support_user, erpnext_support_issues, bench_site):
"""
returns a dict of support issue statuses
{
"erpnext_support_issue_name_1": [{status}]
"erpnext_support_issue_name_2": [{status}]
}
"""
authenticate_erpnext_support_user(erpnext_support_user)
issues... | 6814f39680773b807504007b6d96ca228e1b10e1 | 74,167 |
import hashlib
import base64
def encode(text):
"""[summary]
Base64 Encoder.
Args:
text (str): String to be encoded.
Returns:
str: base64.urlsafe_b64encode
"""
fill_up = hashlib.blake2s(f"{text}".encode("utf-8"), digest_size=8).hexdigest()
text = f"{ text }::{ fill_up }"
... | f9da7bf0ba9455fd37277c8617332d78b11223bd | 74,168 |
def extra_datefield(_, title, code, doc, sidebar_items):
"""
A Basic Line Chart using QuerySet.extra() with DateField
--------------------------------------------------------
This chart plots sales quantities per day from the first book store.
We're using QuerySet.extra() to format the date value di... | 35406b1a165b700301511a9aed2960e6761349b2 | 74,169 |
from typing import List
from typing import Set
def validate_dataframe(df: pd.DataFrame, columns: List[str]) -> Set[str]:
"""Validates that the input dataframe has all given columns, that the
'time' column has a datetime type, a 'month' column parsed as 1-12 or Jan-Dec,
and that all other columns are float... | d689946c0eeb8f65af87d74c9e51b38efa4f6c08 | 74,170 |
def get_progress_groups(qt_viewer):
"""Given viewer, find all QtProgressBarGroups in activity dialog"""
return qt_viewer.window()._activity_dialog.findChildren(QtProgressBarGroup) | d78338e3face60705cfc2003dae58992c28282cf | 74,171 |
import argparse
def parse_arguments():
"""Parse command line arguments
Args:
Returns:
Command line arguments
Raises:
"""
parser = argparse.ArgumentParser(
prog='pypgmon',
)
parser.add_argument(
'-l',
'--logger',
default='pypgm... | d9f571335611b3170a78dfd03b349ecb56784157 | 74,172 |
def multiply_ith_dimension(Pi, i, X):
"""If Pi is a matrix, multiply Pi times the ith dimension of X and return"""
X = X.swapaxes(0, i)
shape = X.shape
X = X.reshape((shape[0], -1))
# iterate forward using Pi
X = Pi @ X
# reverse steps
X = X.reshape((Pi.shape[0], *shape[1:]))
retur... | 98edc89389910d4361232350b0ad440fd785f74a | 74,173 |
import six
import socket
import contextlib
def is_port_open(port_or_url, timeout=1):
"""Check if TCP port is open."""
if isinstance(port_or_url, six.string_types):
url = six.moves.urllib.parse.urlparse(port_or_url)
port = url.port
host = url.hostname
else:
port = port_or_ur... | ad8d6e80cc2eaee6a5955f4f5bc0e69cac8f60b2 | 74,174 |
import logging
def getRootLogger(logrNameSuffix, handlerList=[], formatter=None, rootRank=0):
"""
Returns logger for logging events from only the MPI process with
rank rootRank.
:type logrNameSuffix: str
:param logrNameSuffix: Name of returned logger is "root." + logrNameSuffix.
:type handler... | 9231af80869a7997f9a88d0da777b95d5e59152b | 74,175 |
def merge_two_dicts(x, y):
"""Given two dicts, merge them."""
z = x.copy()
z.update(y)
return z | d2f6b0afb82b88e8a27fb4204016ddde817bf5ed | 74,176 |
import socket
def find_free_port():
"""Find a free port on the localhost.
Adapted from https://stackoverflow.com/a/45690594
"""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("localhost", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... | faedf9ca89fb68ec045c05b30a9ea0f25e730437 | 74,177 |
def validate_name(*args):
"""validate_name(char name) -> char"""
return _idaapi.validate_name(*args) | b045a03c94fed4395eab2ba662ba57dbf890d587 | 74,178 |
import re
def clean_node(config, ctx, category_data, value, template_fn=None):
"""Expands the node to text, cleaning up any HTML and duplicate spaces.
This is intended for expanding things like glosses for a single sense."""
assert isinstance(config, WiktionaryConfig)
assert isinstance(ctx, Wtp)
a... | 5b10d105173ed8b3d140176d69d592aca9f0df81 | 74,179 |
def BBHBonds(allPos, pepAccInds, pepDonInds, distCut = 2.1, angCut = 30.0):
"""Finds H bonds between two list of acceptors and donors. Intended for just peptide backbone.
Inputs:
allPos - full position array for trajectory frame
pepAccInds - global indics of peptide acceptors
pepDonInds - global i... | ddca9baf77911b94bc1e1bcfe88407162d7c47fc | 74,180 |
def is_possible_cat(arrow_type: DataType, /) -> bool:
"""Check if data type is possibly categorical."""
return (is_boolean(arrow_type) or
is_string(arrow_type) or
is_num(arrow_type)) | 1b9b00e8432a2c7ae01b5e87e946a4435d215cd8 | 74,181 |
def test_bfs():
"""
TODO: Write your unit test for your breadth-first
search here. You should generate an instance of a Graph
class using the 'citation_network.adjlist' file
and assert that nodes that are connected return
a (shortest) path between them.
Include an additional test for... | 8ea5c2d88bcbaa96fc7c4ddef2e06bb75f195be5 | 74,182 |
def lte(value):
"""Matches any value that is less than or equal to given value (`<=`)"""
return Lte(value) | cbb61ff84a2658fad64960b27c67a9037e37bc75 | 74,183 |
import sys
def get_name(category, gender, choice):
"""
Gets the name of the file corresponding to the category, gender, and option requested.
:param category: Type of file. Can be "number", "reason", or "ending".
:param gender: 'm' or 'f'.
:param choice: Specifies the file being requested for.
... | db939f515ea9696e68ae12524b1a8b8783d2f150 | 74,184 |
def should_sync_locations(last_sync, location_db):
"""
Determine if any locations (already filtered to be relevant
to this user) require syncing.
"""
if not last_sync or not last_sync.date:
return True
for location in location_db.by_id.values():
if not location.last_modified or ... | d61612473f2842f69628d273198549a55abf66be | 74,185 |
from typing import Tuple
import re
def parse_prefixed_json(data: str) -> Tuple[str, str]:
"""Find the potential JSON body from `data`.
Sometimes the JSON body is prefixed with a XSSI magic string, specific to the server.
Return a tuple (data prefix, actual JSON body).
"""
matches = re.findall(PR... | b6a7639edcd0f7e3086c44f58c416b3d232a5648 | 74,186 |
import tokenize
async def index(request):
"""Endpoint, that does entity recognition."""
text = request['data']['text']
model = request.app['model']
if text:
result = model.analyze(text, tokenizer=tokenize)
else:
result = {}
return web.json_response(result) | d0730f6b750d15d05a6501e86aa5b472c3d32bad | 74,187 |
def _runs_ending_in_block_range(block, mask):
"""Return the runs that end within the block range and may start before
"""
return [
run for run in _get_black_runs(mask)
if block.start <= run.end and run.end <= block.end
] | 47a9cc109c9fa571df2a56d935eee07592efdf51 | 74,188 |
def tfidf(termFrequency):
""" The student must code this. """
gf = np.sum(termFrequency,axis=1).astype(float)
p = (termFrequency.T/gf).T
g = np.sum(p*np.log(p+1)/np.log(len(p[0,:])),axis=1) + 1
a = (np.log(termFrequency + 1).T*g).T
return a | baa00755682ebca54c48a536d4d04b48bac2b42a | 74,189 |
def local_patch_f(arr, patch_size=7, f=np.mean):
"""local_patch_f(arr, patch_size=7, f=np.mean)
Describe local patches around each value of the array
Parameters
----------
arr : ndarray
The input data.
patch_size : int
The size :math:`w` of the patches.
f : function
... | b16f2c40f83decd1609185e05a6a85f72fce05d3 | 74,190 |
import scipy
def interpolate_precision_recall(precision, recall, nSamples=11):
"""
Interpolates precision as a function of recall p_{interp}(r)
Reduce wiggles in average precision curve by taking interpolated values
along a uniform sample.
References:
http://en.wikipedia.org/wiki/Informa... | 34da282092666a2a6e90935b9242914ac41dfdf3 | 74,191 |
def get_feature_dimensions(parameters):
""" Returns dimensions (`int`s) of all node features.
"""
n_atom_types = len(parameters["atom_types"])
n_formal_charge = len(parameters["formal_charge"])
n_numh = int(
not parameters["use_explicit_H"]
and not parameters["ignore_H"]
) * len(... | f1409d1dc2f4785bb2c2452b9bc08395a598f16d | 74,192 |
from ctypes import POINTER, byref, cdll, c_int, windll
from ctypes.wintypes import LPCWSTR, LPWSTR
def win32_utf8_argv():
"""Uses shell32.GetCommandLineArgvW to get sys.argv as a list of UTF-8
strings.
Versions 2.5 and older of Python don't support Unicode in sys.argv on
Windows, with the underlying ... | 42ca67d04455148134c7027619c4519dcbd70639 | 74,193 |
def removeGenesWithExcessiveReplicationVariance(df_X, max_var=None):
"""
Removes Genes with excessive variation in the variance of their
trinary values. Assumes a single digit replication.
Parameters
----------
df_X: DataFrame
index: str <instance>.replication-digit
ex: T10.2
max_var: floa... | e6b6950e2694792e03940caadbeda85c8e32717c | 74,194 |
def getQuadrantID(d):
"""
Returns a scale factor ID based on direction of the derivative. Index starts
at 1 in direction (1, 0, 0) and progresses in anti-clockwise direction.
:param d: directional derivative
:return: scale factor ID
"""
maps = [(1, 0, 0), (1, 1, 0), (0, 1, 0), (-1, 1, 0), (-... | 33d1bf4ed488d2da2a4925fc21a5a9c2a1cb8ecb | 74,195 |
def make_resource_graph(model):
"""
資源の使用量と残差(容量-使用量)を図示する関数
"""
horizon = 0
for a in model.act:
horizon = max(a.completion, horizon)
#print("planning horizon=",horizon)
count = 0
for res in model.res:
if len(res.terms) == 0: # renwable resource
count += 1
... | 2f88b0315d6d8f4d9efb16665b4c5e9bd21486e0 | 74,196 |
def _StripComments(json_string):
"""Strip comments from a json-with-comments string.
Any line beginning with a pound sign, or with whitespace followed by a pound
sign, is removed. Comments are not allowed on the same line as json
constructs.
Args:
json_string: (str) A json string which may contain comm... | 98a73f251064df1e441abc4f22626418257b3aa7 | 74,197 |
def str_to_py(obj):
"""Encode Python object `obj` as python string.
Parameters
----------
obj : :obj:
Python object to be encoded (typically a str or int).
Returns
-------
str
An encoded python string.
"""
encoding = vim.eval('&encoding') or 'utf-8'
if isinstanc... | af17a88a3b8520343f98d99e62ae15d6f4c9c7a3 | 74,198 |
def extract_entities(text, dates_extractor=None, ner_tagger=None, names_extractor=None):
"""
Extract DATE, ORG, PERSON, COURSE
return info = {
'ORG': first_org in text,
'ORG_TEXT': txt
'DATE': first_date in text,
'NAME': first name in text,
'COURSE': is_courses_block... | d94da496a9d63141dd46a7745d1076d7918d07c2 | 74,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.