content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def delete_ref(profile, ref):
"""Delete a ref.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
ref
The ref to ... | 38,100 |
def mean_ratio_reversion_test(hd1, hd2, n=20, offset=20, hold_time=30, return_index=False):
"""
Tests over the time period offset:offset-hold_time to see if the price ratio of the
price pair reverts to the mean.
"""
#Get initial price ratio
init_pr = hd1.close[offset]/hd2.close[offset]
#Get... | 38,101 |
def list_contents(path, root):
"""
@return list of relative paths rooted at "root"
"""
cmd = "svn ls %s/%s" % (root, path)
code, out = util.execute(cmd, return_out=True)
dirs = out.strip().split('\n')
return dirs | 38,102 |
def evaluate_voting():
"""Evaluates the Voting-Results in the instance_dict. Returns Array with the Player-ID(s)"""
poll_dict = {}
for ip in instance_dict.keys():
if 'poll' in instance_dict[ip]:
if instance_dict[ip]['poll'] in poll_dict:
old = poll_dict[instance_dict[ip][... | 38,103 |
def mmd(x1, x2, sigmas):
"""the loss of maximum mean discrepancy."""
x1 = torch.reshape(x1, [x1.shape[0], -1])
x2 = torch.reshape(x2, [x2.shape[0], -1])
# print('x1x2shape:', x1.shape)
diff = torch.mean(gaussian_kernel(x1, x1, sigmas)) # mean_x1x1
diff -= 2 * torch.mean(gaussian_kernel(x1, x2, ... | 38,104 |
async def api_audio_summaries() -> str:
"""Turn audio summaries on or off."""
assert core is not None
toggle_off = (await request.data).decode().lower() in ["false", "off"]
if toggle_off:
# Disable
core.disable_audio_summaries()
_LOGGER.debug("Audio summaries disabled.")
... | 38,105 |
def get_image():
"""Gets an image file via POST request, feeds the image to the FaceNet model then saves both the original image
and its resulting embedding from the FaceNet model in their designated folders.
'uploads' folder: for image files
'embeddings' folder: for embedding numpy files.
... | 38,106 |
def choose(n,r):
"""
number of combinations of n things taken r at a time (order unimportant)
"""
if (n < r):
return 0
if (n == r):
return 1
s = min(r, (n - r))
t = n
a = n-1
b = 2
while b <= s:
t = (t*a)//b
a -= 1
b += 1
return t | 38,107 |
def _bisearch(ucs, table):
"""
Auxiliary function for binary search in interval table.
:arg int ucs: Ordinal value of unicode character.
:arg list table: List of starting and ending ranges of ordinal values,
in form of ``[(start, end), ...]``.
:rtype: int
:returns: 1 if ordinal value uc... | 38,108 |
def get_xml_serial_number (root):
"""
Get the serial number from the system global settings XML.
Parameters:
root -- An XML element to the root of the system global settings.
Return:
The serial number.
"""
return get_xml_string_value (root, "serialNumber", "ser... | 38,109 |
def ParseMachineType(resource_parser, machine_type_name, project, location,
scope):
"""Returns the location-specific machine type uri."""
if scope == compute_scopes.ScopeEnum.ZONE:
collection = 'compute.machineTypes'
params = {'project': project, 'zone': location}
elif scope == comput... | 38,110 |
def redirect_to_default():
"""
Redirects users to main page if they make a GET request to /generate
Generate should only be POSTed to
"""
log("Received GET request for /generate, returning to default page")
return redirect(url_for("default")) | 38,111 |
def headless(argv: List[str]) -> None:
"""
Ugly isn't it ?
"""
try:
opts, args = getopt.getopt(argv[1:], "hu:t:p:",
["help", "udp_port=", "tcp_port=", "port="])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
tcp_port = 4269... | 38,112 |
def client_credential_grant_session():
"""Create a Session from Client Credential Grant."""
oauth2credential = OAuth2Credential(
client_id=None,
redirect_url=None,
access_token=ACCESS_TOKEN,
expires_in_seconds=EXPIRES_IN_SECONDS,
scopes=SCOPES_SET,
grant_type=auth... | 38,113 |
def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True, proxies=None):
"""Formats and performs the query against the API.
:param server: The MyGeotab server.
:type server: str
:param method: The method name.
:type method: str
:param parameters: The parameters to send wi... | 38,114 |
def raft_jh_signal_correlations(raft_name):
"""JH version of raft-level signal-correlation analysis."""
import os
import logging
import numpy as np
import matplotlib.pyplot as plt
import siteUtils
from bot_eo_analyses import bias_filename, make_file_prefix, \
append_acq_run, glob_pat... | 38,115 |
def volume_update(context, volume_id, values):
"""Set the given properties on an volume and update it.
Raises NotFound if volume does not exist.
"""
return IMPL.volume_update(context, volume_id, values) | 38,116 |
def get_E_Elc_microwave_d_t(P_Elc_microwave_cook_rtd, t_microwave_cook_d_t):
"""時刻別消費電力量を計算する
Parameters
----------
P_Elc_microwave_cook_rtd : float
調理時の定格待機電力, W
t_microwave_cook_d_t : ndarray(N-dimensional array)
1年間の全時間の調理時間を格納したND配列, h
d日t時の調理時間が年開始時から8760個連... | 38,117 |
def write_local(path,music_paths):
"""
There is nothing to say about this.
"""
open_path = open(path,mode='w')
for music_path in music_paths:
open_path.write(music_path)
open_path.flush()
open_path.close()
print('KuGou Spider Over!') | 38,118 |
def set_up_text_location(
image: ImageDraw, img_opened: Image, text: str, font: ImageFont
) -> Tuple[Any, Any]:
"""
Returns coordinates of text location on the image
:param image: ImageDraw object
:param img_opened: opened PIL image
:param text: text
:param font: ImageFont
:return: Tuple... | 38,119 |
def service_detail(request, service_id):
"""This view shows the details of a service"""
service = get_object_or_404(Service, pk=service_id)
job_statuses = (
enumerations.QUEUED,
enumerations.IN_PROCESS,
enumerations.FAILED,
)
resources_being_harvested = HarvestJob.objects.fil... | 38,120 |
def convolutional_block(X, f, filters, stage, block, s):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
... | 38,121 |
def h2ocluster_get_status():
"""
Python API test: h2o.cluster().get_status(), h2o.cluster().get_status_details()
"""
table = h2o.cluster().get_status()
details = h2o.cluster().get_status_details()
table.show()
details.show() | 38,122 |
def process_input(values, puzzle_input, u_input):
"""Takes input from the user and records them in the location specified
by the "value", and returns the resulting puzzle input
"""
puzzle_input[values[0]] = u_input
return puzzle_input | 38,123 |
def send_telegram_message(title, url):
"""
发送telegram消息通知
:param title: 标题
:param url: 地址
"""
try:
BOT.send_message(CHANNEL_NAM,
text="[{}]({})".format(title, url),
parse_mode=ParseMode.MARKDOWN,
disable_web_page_... | 38,124 |
def init_store():
"""
Function to initialize the store listener.
Parameters
----------
Returns
-------
dict
request response
"""
challenge_id = str(request.form.get('challenge_id'))
flag = str(request.f... | 38,125 |
def PyLong_AsSsize_t(space, w_long):
"""Return a C Py_ssize_t representation of the contents of pylong. If
pylong is greater than PY_SSIZE_T_MAX, an OverflowError is raised
and -1 will be returned.
"""
return space.int_w(w_long) | 38,126 |
def validate_prmtop(prmtop, target_dir=None, override=False):
"""
Check that file exists and create a symlink if it doesn't have a
prmtop extension (often *.top is used but mdtraj cant't detect type
with ambiguous extensions).
Parameters
----------
prmtop : str
Path to supposed prmt... | 38,127 |
def ci():
"""
Used in conjunction with travis for Continuous Integration testing
:return:
"""
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
import base64
from django.core.files.uploadedfile ... | 38,128 |
def make_dataset(image_fp: List[str], titles: List[str], im_size: Tuple[int, int], batch_size: int) -> tf.data.Dataset:
"""
Parameters
----------
image_fp: List[str]
List of image filepaths.
titles: List[str]
List of book titles, matching the order of the image_fp.
im_size: Tupl... | 38,129 |
def getssa_handler() -> Response:
"""Software Statement Assertion retrieval"""
if request.method == 'POST':
try:
r = requests.get(
'{}/tpp/{}/ssa/{}'.format(
cache.get('tpp_ssa_url'),
cache.get('tpp_id'),
cache.get... | 38,130 |
def run_models(args, csv_cols, models, task_sequence):
"""Run models and save predicted probabilities to disk.
Args:
args: Command-line arguments.
csv_cols: List of column headers for the CSV files (should be 'Path' + all pathologies).
models: List of (ckpt_path, is_3class) tuples to us... | 38,131 |
def train(epochs,n_snps,batch,ratio,width,path,deterministic,debug):
"""Train the model on the simulated data"""
from net import Net
from dataset import DatasetPhenosim,DatasetPhenosim
json_update('width',width)
n_samples = json_get('samples')
device = torch.device("cuda:0" if torch.cuda... | 38,132 |
def dataTeapotShallow():
"""
Values set interactively by Dave Hale. Omit deeper samples.
"""
txf = [
30, 69,0.50, 99, 72,0.50,
63, 71,0.90, 128, 72,0.90,
29,172,0.35, 97,173,0.35,
63,173,0.75, 127,174,0.75,
33,272,0.20, 103,270,0.20,
70,271,0.60, 134,268,0.60]
n = len(txf)/3
t = ze... | 38,133 |
def count_labels(l_path, selected_class,num_workers=4):
"""Calculate anchor size.
Args:
l_path: path to labels.
selected_class: class to be calculated.
Returns:
(w, l, h)
"""
def count_single_label(label_file):
size = []
z_axis = []
num = 0
with open... | 38,134 |
def sorted_chromosome(all_samples):
"""
sorted_chromosome(AllSamples) -> list
:return: list of chromosome found in all samples
"""
sorted_chromosome_list = sorted(all_samples.chr_list.keys())
print(sorted_chromosome_list)
return sorted_chromosome_list | 38,135 |
def adjust_bb_size(bounding_box, factor, resample=False):
"""Modifies the bounding box dimensions according to a given factor.
Args:
bounding_box (list or tuple): Coordinates of bounding box (x_min, x_max, y_min, y_max, z_min, z_max).
factor (list or tuple): Multiplicative factor for each dimen... | 38,136 |
def test_iso8601():
"""
Test datetime ISO 8601 helpers
"""
# dts = datetime.datetime.now(datetime.timezone.utc).isoformat()
dts = '2020-08-22T20:34:41.687702+00:00'
dt = helping.fromIso8601(dts)
assert dt.year == 2020
assert dt.month == 8
assert dt.day == 22
dtb = b'2020-08-22T2... | 38,137 |
def round_dt64(t,dt,t0=np.datetime64("1970-01-01 00:00:00")):
"""
Round the given t to the nearest integer number of dt
from a reference time (defaults to unix epoch)
"""
return clamp_dt64_helper(np.round,t,dt,t0) | 38,138 |
def sample_async_batch_annotate_images(input_image_uri, output_uri):
"""Perform async batch image annotation"""
client = vision_v1.ImageAnnotatorClient()
# input_image_uri = 'gs://cloud-samples-data/vision/label/wakeupcat.jpg'
# output_uri = 'gs://your-bucket/prefix/'
if isins... | 38,139 |
def distill_base():
"""Set of hyperparameters."""
# Base
hparams = common_hparams.basic_params1()
# teacher/student parameters
hparams.add_hparam("teacher_model", "")
hparams.add_hparam("teacher_hparams", "")
hparams.add_hparam("student_model", "")
hparams.add_hparam("student_hparams", "")
# Distill... | 38,140 |
def authorize(*args, **kwargs):
"""Handle for authorization of login information."""
next_url = url_for('oauth.authorize', **{
'response_type': request.args.get('response_type'),
'client_id': request.args.get('client_id'),
'redirect_uri': request.args.get('redirect_uri'),
'scope'... | 38,141 |
def download_repos():
"""
Download all repos listed in the enabled files
"""
git_repo_url = set_github_url()
repos = get_repo_list()
for repo in repos:
git_ops(repo) | 38,142 |
def summary_stats(r, riskfree_rate=0.027):
"""
Return a DataFrame that contains aggregated summary stats for the returns in the columns of r
"""
ann_r = np.round(r.aggregate(annualize_rets, periods_per_year=4), 2)
ann_vol = np.round(r.aggregate(annualize_vol, periods_per_year=4), 2)
ann_sr = np.... | 38,143 |
def mid_longitude(geom: Geometry) -> float:
"""Return longitude of the middle point of the geomtry."""
((lon,), _) = geom.centroid.to_crs("epsg:4326").xy
return lon | 38,144 |
def test_scalar_to_list():
"""Test that dictionary values are all converted to lists/tuples."""
data = {
"x": 1,
"y": "string",
"z": {2, 3, 4},
"a": (26, 50),
"b": None,
"c": 1.2,
"d": True,
"e": False,
}
expected = {
"x": [1],
... | 38,145 |
def unique_count_weight(feature):
"""Normalize count number of unique values relative to length of feature.
Args:
feature: feature/column of pandas dataset
Returns:
Normalized Number of unique values relative to length of feature.
"""
return len(feature.value_counts()) / len(featu... | 38,146 |
def write_mol_block_list_to_sdf(mol_block_list, filepath):
"""Write a list of mol blocks as string into a SDF file.
Args:
mol_block_list (list): List of mol blocks as string.
filepath (str): File path for SDF file.
Returns:
None.
"""
with open(filepath, "w+") as file:
... | 38,147 |
def mode_glass(frame_bg, frame_fg, args_glass):
"""
Description: In glass mode, your eyes will be located with a pair of glass.
Params:
frame_bg: The background layer.
frame_fg: The canvas layer.
args_glass: The arguments used in glass mode.
"""
frame_bg = wear_glasses.wear_g... | 38,148 |
def create_db_comments_from_models(models):
"""Populate comments for model tables"""
with connection.cursor() as cursor:
for model_class in models:
# Doing the check for abstract is a bit weird, we have to create an instance of the class, we
# can't check it on the class definit... | 38,149 |
def line_meshes(verts, edges, colors=None, poses=None):
"""Create pyrender Mesh instance for lines.
Args:
verts: np.array floats of shape [#v, 3]
edges: np.array ints of shape [#e, 3]
colors: np.array floats of shape [#v, 3]
poses: poses : (x,4,4)
Array of 4x4 transform... | 38,150 |
def check_crd_deleted(crd_version):
"""
Function for checking CRD (Custom Resource Defination) is deleted or not
If CRD is not deleted in 60 seconds,function asserts
Args:
None
Returns:
None
Raises:
Raises an exception on kubernetes client api failure and ass... | 38,151 |
def isPrime(n):
"""
check if the input number n is a prime number or not
"""
if n <= 3:
return n > 1
if n % 6 != 1 and n % 6 != 5:
return False
sqrt = math.sqrt(n)
for i in range(5, int(sqrt)+1, 6):
if n % i == 0 or n % (i+2) == 0:
return False
return... | 38,152 |
def seqprob_forward(alpha):
"""
Total probability of observing the whole sequence using the forward algorithm
Inputs:
- alpha: A numpy array alpha[j, t] = P(Z_t = s_j, x_1:x_t)
Returns:
- prob: A float number of P(x_1:x_T)
"""
prob = 0
###############################... | 38,153 |
def center_filter(gt_boxes, rect):
"""
过滤边框中心点不在矩形框内的边框
:param gt_boxes: [N,(y1,x1,y2,x2)]
:param rect: [y1,x1,y2,x2]
:return keep: 保留的边框索引号
"""
# gt boxes中心点坐标
ctr_x = np.sum(gt_boxes[:, [1, 3]], axis=1) / 2. # [N]
ctr_y = np.sum(gt_boxes[:, [0, 2]], axis=1) / 2. # [N]
y1, x1,... | 38,154 |
def named_entities(s, package="spacy"):
"""
Return named-entities.
Use Spacy named-entity-recognition.
PERSON: People, including fictional.
NORP: Nationalities or religious or political groups.
FAC: Buildings, airports, highways, bridges, etc.
ORG: Companies, agencies, inst... | 38,155 |
def get_premium_client():
"""Get a connection to the premium Minio tenant"""
return __get_minio_client__("premium") | 38,156 |
def test_nb_regression_fixture_check_fail(testdir):
"""Test running an nb_regression.check that fails."""
# create a temporary pytest test module
testdir.makepyfile(
"""
def test_nb(nb_regression):
nb_regression.check("{path}")
""".format(
path=os.path.join(PATH,... | 38,157 |
def ensure_empty(path):
"""
Check if a given directory is empty and exit if not.
:param path: path to directory
:type path: str
"""
try:
if os.listdir(path):
msg = 'You asked to restore backup copy in directory "%s". ' \
'But it is not empty.' % path
... | 38,158 |
def get_all_versions(lang: str) -> List[Tuple[int, int, int]]:
"""Return the list of version available for a given lang"""
versions = []
for filename in os.listdir(GRAMMAR_PACKAGE):
match = VERSION_REGEX.match(filename)
if match:
if match['name'] == lang:
version... | 38,159 |
def chunk_sample_text(path: str) -> list:
"""Function to chunk down a given vrt file into pieces sepparated by <> </> boundaries.
Assumes that there is one layer (no nested <> </> statements) of text elements to be separated."""
# list for data chunks
data = []
# index to refer to current chunk
... | 38,160 |
def describe_dag_diffs(x, y):
"""Returns a list of strings describing differences between x and y."""
diffs = []
# A pair of dictionaries mapping id(x_val) or id(y_val) to the first path at
# which that value was reached. These are used to check that the sharing
# stucture of `x` and `y` is the same. In pa... | 38,161 |
def summarize(manager: WebManager):
"""Summarize the contents of the database."""
click.echo(f'Users: {manager.count_users()}')
click.echo('Roles: {}'.format(manager.session.query(Role).count()))
click.echo('Projects: {}'.format(manager.session.query(Project).count()))
click.echo('Reports: {}'.forma... | 38,162 |
def test_grdfilter_file_in_file_out():
"""
grdfilter an input grid file, and output to a grid file.
"""
with GMTTempFile(suffix=".nc") as tmpfile:
result = grdfilter(
"@earth_relief_01d",
outgrid=tmpfile.name,
region=[0, 180, 0, 90],
filter="g600",... | 38,163 |
def ec_cert(cert_dir):
"""Pass."""
return cert_dir / "eccert.pem" | 38,164 |
def get_expiries(body):
"""
:type body: BeautifulSoup
"""
_ex = body.find_all('select', {'id': 'date', 'name': 'date'})
ex = []
for ch in _ex:
for _e in ch:
try:
ex.append(datetime.strptime(_e.text, '%d%b%Y').date())
except ValueError:
... | 38,165 |
def _add_experimental_function_notice_to_docstring(doc):
"""Adds an experimental notice to a docstring for experimental functions."""
return decorator_utils.add_notice_to_docstring(
doc, '',
'EXPERIMENTAL FUNCTION',
'(experimental)', ['THIS FUNCTION IS EXPERIMENTAL. It may change or '
... | 38,166 |
def format_args(args):
"""Formats the command line arguments so that they can be logged.
Args:
The args returned from the `config` file.
Returns:
A formatted human readable string representation of the arguments.
"""
formatted_args = "Training Arguments: \n"
args = args.__dict_... | 38,167 |
def generate_id() -> str:
"""Generates random string with length of `ID_LENGTH`"""
return int_to_base36(uuid.uuid4().int)[:LENGTH_OF_ID] | 38,168 |
def run_make_distrib():
"""Run CEF make_distrib script."""
print("[automate.py] Make CEF binary distribution")
script_ext = "bat" if WINDOWS else "sh"
base_script = "make_distrib.{ext}".format(ext=script_ext)
tools_dir = os.path.join(Options.cef_build_dir, "chromium", "src", "cef",
... | 38,169 |
def getHG37PositionsInRange(chromosome, startPos, endPos):
"""Return a DataFrame containing hg37 positions for all rsids in a range.
args:
chromosome (int or str): the chromosome number
startPos (int or str): the start position on the chromosome
endPos (int or str): the ... | 38,170 |
def spherical_from_cart_np(xyz_vector):
"""
Convert a vector from cart to spherical.
cart_vector is [idx][x, y, z]
"""
if len(xyz_vector.shape) != 2:
xyz_vector = np.expand_dims(xyz_vector, axis=0)
expanded = True
else:
expanded = False
sph_vector = np.zeros(xyz_vect... | 38,171 |
def _execute_query(connection, query):
"""Executes the query and returns the result."""
with connection.cursor() as cursor:
cursor.execute(query)
return cursor.fetchall() | 38,172 |
def mediaValues(x):
"""
return the media of a list
"""
return sum(x)/len(x) | 38,173 |
def _plot_NWOE_bins(NWOE_dict, feats):
"""
Plots the NWOE by bin for the subset of features interested in (form of list)
Parameters
----------
- NWOE_dict = dictionary output of `NWOE` function
- feats = list of features to plot NWOE for
Returns
-------
- plots of NWOE for each fea... | 38,174 |
def gather_clinical_features(record, gene_finding, gene_disease):
"""
update gene_finding and gene_disease dictionary using information from a VCF record
"""
geneinfo = record.info["GENEINFO"].split("|")[0].split(":")[0]
if "CLNDISEASE" in record.info:
clndisease = record.info["CLNDISEASE"][... | 38,175 |
def send_message(body):
""" Sends text message using argument as body."""
client.messages.create(
to=to_phone,
from_=from_phone,
body=body
) | 38,176 |
def keycloak_client_secret_get(realm_name, client_id, token_user, token_password, token_realm_name):
"""client sercret 取得
Args:
realm_name (str): realm name
client_id (str): client id
toekn_user (str): token 取得用 user name
toekn_password (str): token 取得用 user password
toek... | 38,177 |
def test_str():
"""
Converting an info panel to a string should return the panel's
title.
"""
panel = models.InfoPanel(title="Test Panel")
assert str(panel) == panel.title | 38,178 |
def net_model_fn(features, labels, mode, model,
resnet_size, weight_decay, learning_rate_fn, momentum,
data_format, resnet_version, loss_scale,
loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE,
conv_type=resnet_model.DEFAULT_CONV_TYPE,
... | 38,179 |
def vectorvalued(f):
""" Decorates a distribution function to disable automatic vectorization.
Parameters
----------
f: The function to decorate
Returns
-------
Decorated function
"""
f.already_vectorized = True
return f | 38,180 |
def remove_diacritics(input_str: str) -> str:
"""Remove diacritics and typographical ligatures from the string.
- All diacritics (i.e. accents) will be removed.
- Typographical ligatures (e.g. ffi) are broken into separated characters.
- True linguistic ligatures (e.g. œ) will remain.
- Non-latin scr... | 38,181 |
def extract_model_field_meta_data(form, attributes_to_extract):
""" Extract meta-data from the data model fields the form is handling. """
if not hasattr(form, 'base_fields'):
raise AttributeError('Form does not have base_fields. Is it a ModelForm?')
meta_data = dict()
for field_name, field_data... | 38,182 |
def beam_search(image, encoder, embedder, attention, decoder,
beam_width=30, max_length=18, redundancy=0.4,
ideal_length=7, candidates=0, as_words=True):
"""
beam_search is a breadth limited sorted-search: from root <start> take next
best beam-width children out of vocab_size... | 38,183 |
def strip_leading_and_trailing_lines(lines, comment):
"""
Removes and leading and trailing blank lines and comments.
:param lines: An array of strings containing the lines to be stripped.
:param comment: The block comment character string.
:return: An updated array of lines.
"""
comment = ... | 38,184 |
def bold(msg: str) -> str:
"""Bold version of the message
"""
return bcolors.BOLD + msg + bcolors.ENDC | 38,185 |
def test_compare_versions(expression, expected):
"""
This test is suppose to test if the compare_versions returns
expected values for different expressions.
"""
assert version.compare_versions(expression) == expected | 38,186 |
def create(**kwargs):
"""Create a new key pair."""
r, w = os.pipe()
with contextlib.closing(os.fdopen(r, 'r')) as r:
with contextlib.closing(os.fdopen(w, 'w')) as w:
w.write('''
Key-Type: rsa
Key-Length: 4096
Key-Usage: sign
Name-Real: %(name)s
Name-Email: %(email)s
Name-Comment: %(comme... | 38,187 |
def escape(value):
"""
extends the classic escaping also to the apostrophe
@Reviewer: Do you please have a better way?
"""
value = bleach.clean(value)
value = value.replace("'", "'")
return value | 38,188 |
def login(request):
"""
:param request:
:return:
"""
if request.user.is_authenticated:
return redirect('/')
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=passw... | 38,189 |
def plot_date_randomisation(
ax: plt.axes,
replicates: np.array or list,
rate: float,
log10: bool = True
) -> plt.axes:
""" Plot distribution of substitution rates for date randomisation test
:param ax: axes object to plot the date randomisation
:param replicates: list of replicate substit... | 38,190 |
def plot_hist(run_dir, cur_nimg, nimgs=None, **kwargs):
"""
Plots three histograms of the pixel value distribution of two arrays of images (overlapping) and saves it to path
First histogram with all 255 values, second with all values on log scale and the third histogram with value 30 cut out
run_di... | 38,191 |
def read_gap_scenes(d_scenelets, no_pickle=False, filter_fn=None):
"""
Args:
filter_fn (function):
Returns true, if we want to keep the scenelet. Takes scenelet
name as argument.
"""
is_pickled = False
p_scenelets_pickle = os.path.join(d_scenelets, 'scenes_db.pickle')... | 38,192 |
def dict(filename, cols=None, dtype=float, include=None, exclude='#',
delimiter='', removechar='#', hmode='1', header_start=1,
data_start=0, hsep='', lower=False):
"""
Creates a dictionary in which each chosen column in the file is an
element of the dictionary, where keys correspond to col... | 38,193 |
def save_chkpt_vars(dic, path):
"""
Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
"""
logger.info("Variables to save to {}:".format(path))
keys = sorted(list(dic.keys()))
logger.info(pp... | 38,194 |
def solution(p, flux, error, line, cont, sens, model_wave, coeffs, fjac=None):
""" Fitting function for mpfit, which will minimize the returned deviates.
This compares the model stellar spectra*sensitivity to observed spectrum
to get wavelength of each pixel."""
# Convert pixels to wavelengths
xre... | 38,195 |
def filter_image(image, model, scalings):
"""
Filter an image with the first layer of a VGG16 model.
Apply filter to each scale in scalings.
Parameters
----------
image: 2d array
image to filter
model: pytorch model
first layer of VGG16
scalings: list of ints
dow... | 38,196 |
def gen_init_params(m_states: int, data: np.ndarray) -> tuple:
"""
Generate initila parameters for HMM training.
"""
init_lambda = gen_sdm(data, m_states)
init_gamma = gen_prob_mat(m_states, m_states)
init_delta = gen_prob_mat(1, m_states)
return init_lambda, init_gamma, init_delta | 38,197 |
def generate_temp_csvfile(headers: list, data: list) -> object:
"""
Generates in-memory csv files
:param
headers: list
A list of file headers where each item is a string
data: list
A list containing another list representing the rows for the CSV
:returns: IO
... | 38,198 |
def task_run_stack():
"""Make products stack"""
pass | 38,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.