content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
from typing import Sequence
import sys
import os
def _application_directory(
directory: Union[str, Sequence[str]], src_path: Union[str, Sequence[str]] = None
) -> str:
"""
Returns a path to a directory that is adjusted depending on whether the program is running in a compiled or a... | 9141841a73426a8719f05b43c2b37a7cc9c58dfa | 3,608,200 |
def teamtsv(req):
"""
Creates teams.tsv on server drive for use with DomJudge.
"""
if req.method == 'GET':
ExportCSV("Team")
return HttpResponseRedirect('/createtsv') | e4d1a154e8f1fad4fd22be1e6a97a74c44347086 | 3,608,201 |
def binary_search(
array: list, element, start_idx: int = None, stop_idx: int = None
) -> int:
"""Code based on https://stackabuse.com/binary-search-in-python/"""
if start_idx is None:
start_idx = 0
if stop_idx is None:
stop_idx = len(array) - 1
if start_idx > stop_idx:
rai... | 03bd00b811f6a8895221fdc7697e96a0d4ae0cd5 | 3,608,202 |
def _urlnode_render_replacement(self, context):
"""Replacement for django's {% url %} block.
This version uses WSGIApplication's url mapping to create urls.
Examples:
<a href="{% url MyPageHandler "overview" %}">
{% url MyPageHandler implicit_args=False %}
{% url MyPageHandler "calendar" %}
{% url MyPa... | 932e38d500aada0cd975a40c8c5b05bf62aa3815 | 3,608,203 |
def InitNN(num_inputs, num_hiddens, num_outputs):
"""Initializes NN parameters.
Args:
num_inputs: Number of input units.
num_hiddens: List of two elements, hidden size for each layer.
num_outputs: Number of output units.
Returns:
model: Randomly initialized n... | f4ca73802e933df7a99fb936029ee4d75d679f5c | 3,608,204 |
def evaluate_and_save_in_background(query, target_directory=None, target_file=None):
"""Like evaluate_and_save, but returns immediately and runs in the background.
Note that the saving occurs on o worker. Eventual remote workers will save the results in their local filesystem.
"""
global _worker_config
... | ea485262b24bf5577c4260849abe71dd85e6f056 | 3,608,205 |
def get_element(dict, key, default=None):
"""" if dict[key] present, return that. Otherwise return default value"""
value = dict[key] if key in dict else default
return value | ac3cc2ea1ff38a42c0e674fee56a43bcb2b71660 | 3,608,206 |
def nmap(value, fr=(0, 1), to=(0, 1)):
"""
Map a value from a two-value interval into another two-value interval.
Both intervals are `(0, 1)` by default. Values outside the `fr` interval
are still mapped proportionately.
"""
value = (value - fr[0]) / (fr[1] - fr[0])
return to[0] + value * (t... | d7968d7661c2535f5c820087b79b7a8e3667e8e8 | 3,608,207 |
from sys import flags
def discounted_rewards(rewards_hn):
"""
Given an array of rewards collected from n trajectories over h
steps, where the first axis is the timestep and the second
is the number of trajectories, returns the discounted cumulative
reward for each trajectory.
"""
discount ... | 95f07285a26e3313226f6bde115823d8ad3fbe14 | 3,608,208 |
def giphy(config, terms):
""" Return giphy for given terms. """
terms = ' '.join(terms)
if terms:
img = translate(terms, api_key=config['giphy']['api_key'])
else:
img = translate('random', api_key=config['giphy']['api_key']) # hack
url = img.fixed_height.downsampled.url
return [... | a4e534bcad8695dacc2943cb7155641eda3e1952 | 3,608,209 |
def get_best_outputs(problem_dir, problem, user):
"""
Gets outputs of best submission.
:param problem_dir: main directory of submissions
:param problem: id of problem
:param user: user who wants to see submission for problem
:return: -1 if no file found, otherwise array of be... | a012b849ec76056067a75a71d80ea2911b2b91fc | 3,608,210 |
import time
def computeStatistics(sqlContext,df):
"""Compute all of the statistics for a given dataframe
Input: sqlContext: to perform SQL queries
df: dataframe with the fields
Station(string), Measurement(string), Year(integer), Values (byteArray with 365 float16 numbers)
returns... | d11f1ab6e462e5d6c48e66a70afddc770df8859c | 3,608,211 |
def ambiguous_count(seq):
"""count the number of possible sequences from ambiguous DNA input"""
d = IUPAC.IUPACData.ambiguous_dna_values
return np.prod([len(d[base]) for base in seq]) | 438970004eeabba3c44b1a33ed28871b15766b62 | 3,608,212 |
def get_default_span_name(environ):
"""Calculates a (generic) span name for an incoming HTTP request based on the PEP3333 conforming WSGI environ."""
# TODO: Update once
# https://github.com/open-telemetry/opentelemetry-specification/issues/270
# is resolved
return environ.get("PATH_INFO", "/") | eba56c691babd88c1d695652f19dc315617d8e8a | 3,608,213 |
import torch
def bmv(mat, vec):
"""batch matrix vector product"""
return torch.einsum('bij, bj -> bi', mat, vec) | e6f2d95a0aec5239eaa96fe0a6dd371216eb741b | 3,608,214 |
import typing
def dc2avsc(
schema,
*,
request=None,
include_fields: typing.List[str] = None,
exclude_fields: typing.List[str] = None,
namespace="inverter",
ignore_required=True,
):
"""
Converts ``dataclass`` to Avro Schema JSON dictionary
:param schema: ``dataclass`` class
... | 4291bd6a7eeb5f5f946bdea2ca7399899ba77ad4 | 3,608,215 |
def initialize(L, H, R,
interface_thickness, solutes, restart_folder,
field_to_subspace,
inlet_velocity, concentration_left,
enable_NS, enable_PF, enable_EC,
**namespace):
""" Create the initial state.
The initial states are specified in... | 2db98a7fab70eda819520c7d820bdfc248cc26bd | 3,608,216 |
def encode_path(file_path):
"""Returns a URL-encoded version of a path
"""
return quote(file_path) | d0d945534cba5400378d6bc83d2d75bedc8914b7 | 3,608,217 |
import os
def rar_decompress(vers, meth, data, declen=0, flags=0, crc=0, psw=None, salt=None):
"""Decompress blob of compressed data.
Used for data with non-standard header - eg. comments.
"""
# already uncompressed?
if meth == RAR_M0 and (flags & RAR_FILE_PASSWORD) == 0:
return data
... | 5fbed65528358f98f718f7ef228e2ded847c2b46 | 3,608,218 |
def log_data_controller(request):
"""
:param request:
:return:
"""
# if request.method == "GET":
# json_log_data = get_log_data()
# return HttpResponse(json.dumps(json_log_data),
# content_type='application/json')
return cc_helper_function_one(request... | 3c9381da3446b15da52b9297e2d1d413f3fa775e | 3,608,219 |
import time
def generate_hash():
"""
Function to generate the attendance token hash.
"""
token = hash(time.time()) % 100000000
return token | 2825549e551e574de5292be1f7b73bc4e180f748 | 3,608,220 |
import weasyprint as weasy # type: ignore
from typing import Optional
from pathlib import Path
def publish_pdf(
page: "Page", filepath: str = "./esparto-doc.pdf", return_html: bool = False
) -> Optional[str]:
"""Save page to PDF.
Args:
page (Layout): A Page object.
filepath (str): Filepath t... | 710b79d0b6d3a617c4192063c9b75c14b03b4644 | 3,608,221 |
def _validate_data_header(X: np.ndarray, y: np.ndarray, n_samples: int,
n_features: int, y_names: np.ndarray) -> bool:
"""
Checks if read-in data are consistent with their csv header.
For details on valid header formatting see the
:func:`fatf.utils.datasets.load_data` document... | 0a8ad0598094a00dc49ecffe9bd275f1e984bf31 | 3,608,222 |
def estimate_centroids(X, k, assoc):
"""
Recalculates centroids.
Inputs
------
X : `np.array`, shape (n, d)
Input data, where rows are examples and columns are features.
k : `int`
Number of k clusters to generate.
assoc : `np.array`, shape (n, )
Index of closest cent... | 30c7f193a814495a35aef4cae556ff7d18f5a8d4 | 3,608,223 |
def get_slackWH():
"""Return a valid SlackWebhook object."""
return SlackWebhook(auth='https://testurl.com', body='message',
attachments=['https://url1.com', 'https://url2.com']) | 2937ec5f4404136546f2f0299cf46071e2c499d8 | 3,608,224 |
from datetime import datetime
def _add_delay(team_id: str, time: str) -> str:
"""Update Modron reminder state
Args:
team_id (str): Name of the team to adjust
time (str): How long to snooze for
Returns:
(str) A reply to give to the user about the status
"""
# Parse the dura... | 076933103318be74bfafd08cac06fcc57d505153 | 3,608,225 |
def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2 ** np.arange(3, 6)):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size]) - 1 # [0,0,15,15]
rati... | 54754295eb0e6571cff25a626e08247d5ee02adb | 3,608,226 |
def mad(data):
""" Calculate the Median Absolute Deviation from the data.
:param data: The data to analyze.
:type data: list(number)
:return: The calculated MAD.
:rtype: float
"""
data_median = median(data)
return float(median([abs(data_median - x) for x in data])) | 565875f252563e4b8cd91c85d4090c1f07f14cb1 | 3,608,227 |
def run_gear_ratios_detections_on_cycle_data(ngears, cycle_df):
"""
Invoke this one if you want to draw the results.
:param pd.DataFrame cycle_df: it must contain (at least) `N` and `V` columns (units: [rpm] and [km/h] respectively)
:return: a list of all :class:`Detekt` tuples sorted with the most pro... | f4169fd37431d94df1533fdbdc96a697967004f9 | 3,608,228 |
import json
def get_user_params(job_id, job_data):
""" Gets User parameters from the input job id and data , sent from codepipeline
:param job_id: Job ID
:param job_data: Job data sent from codepipeline
:return: Parameters sent from codepipeline
:exception: Call put_job_failure to send failure to ... | 49c032ab8d3d3f026e9d2745f38220236235a5d6 | 3,608,229 |
async def async_setup_integration(
hass, wizlight=None, device=None, extended_white_range=None, bulb_type=None
):
"""Set up the integration with a mock device."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id=FAKE_MAC,
data={CONF_HOST: FAKE_IP},
)
entry.add_to_hass(hass)
... | d38550ea3257f2df0a91f84b6a441563c7127671 | 3,608,230 |
import torch
def topk_accuracy(output, target, topk = (1,)):
"""Compute accuracy over top "k" predictions."""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size()[0]
_, pred = output.topk(maxk, dim = 1, largest = True, sorted = True)
pred = pred.t()
correc... | 84f8b38cb7176f752cbd0b63baddc4d4914313ed | 3,608,231 |
def argmax_from_adj(vals, vertex_inds, adj_inds):
""" Indices of local maxima from `vals` given adjacent points
See ``reconstruction_performance`` for optimized versions of this
routine.
Parameters
----------
vals : (N,) array-like
values at all vertices referred to in either of `v... | 5a125c9a26e3280878894fd2076ecf8b6434832b | 3,608,232 |
import os
def align(infile_list, db_prefix_list, output_prefix, remove_temp_output,
bowtie2_path, threads, processors, bowtie2_opts, verbose):
""" Runs bowtie2 on a single-end sequence file or a paired-end set of files.
For each input file set and database provided, a bowtie2 command is generated a... | 56633c8f0c8e19a8ae5b27449e533338597392ef | 3,608,233 |
import torch
def initialize_scrc_transform(is_training):
""" Initialize the scrc transformation.
Args:
is_train: whether is training or evaluation
"""
angles = [0, 90, 180, 270]
def random_rotation(x: torch.Tensor) -> torch.Tensor:
angle = angles[torch.randint(low=0, high=len(an... | 5565161aff24f832158eed7ea5bc7e5853bcc0b6 | 3,608,234 |
def getThreatStatus(cursor, cd_tax):
"""
Get the threat status of a taxon, with the associated references and links
Parameters
-----------
cursor: psycopg2 cursor
cursor of the current operations in the postgres database (need to be of psycopg2.extras.RealDictCursor type, in order to ob... | 0da9214393d9d9c143d09d4b8f6af1dc6fadd0ab | 3,608,235 |
import math
def tokens_del_row(corpus_id, token_id):
"""
:param corpus_id: Id of the corpus
:param token_id: Id of the token
:return:
"""
corpus = Corpus.query.get_or_404(corpus_id)
token = WordToken.query.filter_by(**{"corpus": corpus_id, "id": token_id}).first_or_404()
page = math.f... | ecffc6edf1327019bc7c95f9b2094bb728961638 | 3,608,236 |
def create_formula(rep, add_formula):
"""
Returns the temporal formula corresponding the given theory term.
Throws an error if rep it is not a valid formula.
Arguments:
rep -- Theory term to translate.
add_formula -- Callback to add resulting formuals.
"""
if rep.type == _cling... | 29d8bd40ed8201882cc48d548160fb5534f7b261 | 3,608,237 |
from pecan import conf
def stamp(uri):
"""
Used to stamp the URI of a static resource with a revision-specific
identifier so that when updates are deployed, browser caches are broken,
and users are forced to re-download the latest static resources.
"""
return "%s%s?%s" % (cdn_host(), uri, conf... | f8e5cc2a77b52f3826f9e686e186bb7eb48a4ed6 | 3,608,238 |
import re
from typing import OrderedDict
def read_stm(stm_path, pem_path, glm_path, run_root_path, data_size='300h'):
"""Read transcripts (.stm) & save files (.npy).
Args:
stm_path (string): path to the transcription file
pem_path (string): path to the segmentation file
glm_path (strin... | 6d84d8f4aec11019e5db5301b53fc29eb05dc116 | 3,608,239 |
def computeFraction(feature_1, feature_2 ):
"""
Parameters:
Two numeric feature vectors for which we want to compute a ratio
between
Output:
Return fraction or ratio of feature_1 divided by feature_2
"""
fraction = 0.
if feature_1 ==... | fbce06ab1fea604a3c0e4f0e427dd6560acf80fe | 3,608,240 |
def get_connection():
"""
Get a connection to the database.
This method assumes that you have a tunnel to the database open. See
project readme for an explanation of how to open the tunnel.
Information for the connection read from our config system. This allows
to use the connection e.g. with ... | 73a36c072500177e34c5f62f579ec1eaf8258489 | 3,608,241 |
def isLNM(filename):
"""
Checks whether a file is ASCII Laser-Niederschlags-Monitor file (Thies).
"""
try:
fh = open(filename, 'rt')
temp = fh.readline()
except:
return False
try:
if not temp.startswith('# LNM '):
return False
except:
retu... | a94bc44910ed8924f7e0332ef28155634b2eb7ce | 3,608,242 |
def trivial_detokenize(s,lang='hi'):
"""
Trivial tokenizer for languages in the Indian sub-continent
"""
if lang=='ur':
raise IndicNlpException('No detokenizer available for Urdu')
else:
return trivial_detokenize_indic(s) | 95b3636112831c553869da3af20ab3db299c8cc4 | 3,608,243 |
import inspect
def cluster_stats(hdb, X, n, p=0.0):
"""Compute individual cluster statistics.
Parameters:
-----------
hdb : hdbscan.HDBSCAN object
Trained clustering model with labels.
X : array_like
Input data for clustering.
n : int
Cluster index (must be < len(hdb.l... | 863b422967e898641df9ab84b9726435cf5fbd8d | 3,608,244 |
def final_model(input_dim, cnn_units = 200, kernel_size = 5, padding = 'same', dilation_rate = 2,
num_rnn_layers = 2, rnn_units = 200, merge_mode= 'concat', dense_units = 100,
output_dim = 29):
""" Build a deep network for speech
"""
# Main acoustic input
input_data =... | 143a73f55e0f6ec2c96f1ace9745369ff804de82 | 3,608,245 |
def generate_all_chart_tables(overview_page):
"""Converts a OverviewPage proto to gviz DataTables."""
return [
generate_overview_page_analysis_table(overview_page.analysis),
input_pipeline_proto_to_gviz.generate_step_breakdown_table(
overview_page.input_analysis),
generate_run_environmen... | d6437882ea4b5bcf0b59e055698022f1665f7bca | 3,608,246 |
def fastfit_negbin(observed, tol=1e-4, max_iterations=100):
"""Fit Negatove Binomial.
Parameters
----------
observed: array_like
Observed values
tol: float
Tolerance criterion for stopping
iterations when difference between sucessive estimates
drops below t... | 8410ce43e50d9bf441165a6cb4f3eedda0a9b315 | 3,608,247 |
def _update(dOld, dNew, dType):
"""Function to update the 'prevState' in dOld with the 'prevState' in dNew
Unfortunately this is really similiar to '_rotate', but I didn't want to
jam a square peg in a round hole.
"""
c = 0
# Loop through dictionary
for _d in dOld:
# Loop throu... | 7be61238e7338c591b094dd9e4e346f9dc836f44 | 3,608,248 |
def set_default_labels(func):
"""
Helper decorator to set default labels to X and Y axes for matplotlib plots.
"""
@wraps(func)
def decorator(*args, **kwargs):
f = func(*args, **kwargs)
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
return f
return decorator | de70bd44b989909d05372f092642d2f9479254d3 | 3,608,249 |
def select_option(options, message='', val=None):
""" CLI selection given options. """
while val not in options:
val = input(message)
if val not in options:
logger.error('Invalid choice.')
return val | b17cfa5c4516ba444acd40d4e758307507f2ff83 | 3,608,250 |
def interpolate_np(grid, samples, world2grid):
"""Returns the trilinearly interpolated SDF values using the grid.
Args:
grid: numpy array with shape [depth, height, width].
samples: numpy array with shape [sample_count, 3].
world2grid: numpy array with shape [4,4]. Rigid body transform.
Returns:
... | 341cef96c6339df6bdd4e12c387a0b536168fd5e | 3,608,251 |
def write_column(f, data, selement, compression=None):
"""
Write a single column of data to an open Parquet file
Parameters
----------
f: open binary file
data: pandas Series or numpy (1d) array
selement: thrift SchemaElement
produced by ``find_type``
compression: str, dict, or ... | 462e38b39d4abb151fa7d2c8a1de100629d850f3 | 3,608,252 |
import time
def read_fit(filename):
"""Read Flexible and Interoperable Data Transfer file (FIT).
Parameters
----------
filename : str
Filename
Returns
-------
metadata : dict
Activity metadata
path : dict
Trackpoint data
"""
fitfile = FitFile(filename... | d3b766b7effd52cb4271b5d257b3e2a658aba3f0 | 3,608,253 |
def norm(vals, norm_min=None, norm_max=None, axis=(0,1)):
"""
For visualization purposes scale image with `(vals-norm_min)/(norm_max-norm_min),
with norm_min and norm_max either specified or within 0.01 and 0.99 quantiles of all values
"""
norm_min = ifnone(norm_min, np.quantile(vals, 0.01, axis=axi... | dbefaff2160e74246864b619cd7bdb2665774c18 | 3,608,254 |
import sys
def create_venue_submission():
"""Creates a new venue in the db from a form submission.
Returns:
The template for a list of all venues
"""
form = VenueForm()
if not form.validate():
flash(
list(form.errors.values())[0][0], "error",
)
return r... | 9dfc4fd3ea3afc1781aebeab8eb6566dba6975d4 | 3,608,255 |
import logging
import glob
import os
def get_arch_vv(obsid, version='last'):
"""
Given obsid and version, find archived ASP1 and obspar products and
run V&V. Effort is made to find the obspar that was actually used during
creation of the ASP1 products.
:param obsid: obsid
:param version: 'la... | 251bef6d0d135007cba153ec95d5bd446cd9beed | 3,608,256 |
def pad_image(immy,down_factor = 256,dynamic=False):
"""
pad image with a proper number of 0 to prevent problem when concatenating after upconv
Args:
immy: metaop that produces an image
down_factor: downgrade resolution that should be respected before feeding the image to the network
... | fca01d0bf8cc8c036f1d54d7cde253ffba8f6877 | 3,608,257 |
from typing import Sequence
def remote_cpp_executor_factory(
channels: Sequence[executor_bindings.GRPCChannel],
default_num_clients: int = 0) -> executor_factory.ExecutorFactory:
"""ExecutorFactory backed by C++ Executor bindings."""
py_typecheck.check_type(default_num_clients, int)
def _executor_fn(
... | 05d848cbe1375c9a2a89fb6f31c9aef7daa0fdad | 3,608,258 |
from typing import List
import os
def compute_clusters(base_path: str, threshold: float, hh_ids_uq: List):
"""Compute location clusters of households within the threshold."""
# read in file
distances = pd.read_csv(
os.path.join(base_path, "Data", "KoCo19_Datasets", "Geocodes",
... | 9dee77a99d04351ad7f11c744d220620c614909a | 3,608,259 |
import logging
def remove_extr_freq(corpus, high=0.999, low=5):
"""Removes words with very high and very low frequency
Args:
corpus: tokenised documents
high: high-cile in the token frequency distribution
low: minimum number of occurrences in the corpus
Returns:
A filtered ... | 05c7282a9312575bccd4f76420cb7b3aa5c89c56 | 3,608,260 |
def parse_file(filepath: str) -> list:
"""Parsing content of specified file
:param filepath: Path to file with content for parsing
:type filepath: str
:rtype: list
:raises: ParseException
"""
parsed = create_grammar().parseFile(filepath, parseAll=True)
return parse_tokens(parsed) | 8b8d77caca637db7cfd84e550999ce2ec03fc2f6 | 3,608,261 |
def publication_email_article_do_not_send_list():
"""
Return list of do not send article DOI id
"""
do_not_send_list = [
"00003", "00005", "00007", "00011", "00012", "00013", "00031", "00036", "00047", "00048",
"00049", "00051", "00065", "00067", "00068", "00070", "00078", "00090", "000... | 30b813490c3ccd076fc59dd2090c9861f3ab495f | 3,608,262 |
import types
import numpy
def hpat_pandas_series_count(self, level=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.count
Limitations
-----------
Parameter ``level`` is currently unsupported.
Examples
... | 5768f63b7dbfaaeeef5b583cbdf0dcb0dd77ab34 | 3,608,263 |
import urllib
import json
def get_list_of_titled_players(title):
"""
Downloads a list of players with specified title on Chess.com
:param title: The desired title to use for getting player list
:return list_of_users: Returns the list of all users with this title on Chess.com
"""
try... | 70bd5cde6c5cefb923662e10f147adff1d7d39a0 | 3,608,264 |
import os
def GetCurrentUser():
"""This returns the username, not prefixed by the hostname."""
curr_proc = PsutilGetProcObj(os.getpid())
# u'mymachine\\myuser' on Windows and 'myuser' on Linux.
ps_user = PsutilProcToUser(curr_proc)
# This truncates the hostname if there is one.
# We do not wan... | 37991cb694d4fa1a0f17133590959ddc5951c38f | 3,608,265 |
def disconnect_handler(event):
""" Handle disconnections from WS"""
print("Handling disconnection")
connection_id = event['requestContext']['connectionId']
print(f"From {connection_id}")
murd.delete([MurdMemory(ROW="ws_connections",
COL=connection_id)],
id... | eb82061b1ea485319c5e62f4354860e918f7e94d | 3,608,266 |
def sanity_check_model():
"""
Bare Bones model with one no hidden layer i.e flattened input features
directly connected to output node.
This model is suppose to be used when building pipeline with minimum focus on model
performance.
Returns
---------
keras model
"""
# Initial... | 30522cdd5a33dde523ccd40eb6e9bf47dc44547f | 3,608,267 |
import urllib
def _make_hostport(conn, default_host, default_port, default_user='', default_password=None):
"""Convert a '[user[:pass]@]host:port' string to a Connection tuple.
If the given connection is empty, use defaults.
If no port is given, use the default.
Args:
conn (str): the string ... | b4c99d41435298bdb8badd2294585d073b9a1db4 | 3,608,268 |
import pytest
import os
import errno
def test_output_path(path=None):
"""
Get dir in the suite output_path for the current test case
"""
test_out_dir = os.path.splitext(pytest.config.current_test_log_path)[0]
try:
os.makedirs(test_out_dir)
except OSError as e:
if e.errno != err... | 6e9cc75f35f4e91aaeab4075ce730492114e97cc | 3,608,269 |
def reserve_vlan_id(session):
"""Reserve an unused vlan_id"""
with session.begin(subtransactions=True):
record = (session.query(ovs_models_v2.VlanID).
filter_by(vlan_used=False).
first())
if not record:
raise q_exc.NoNetworkAvailable()
LOG... | 7582ce76403cc1f152f087bf2c85015b9f13301f | 3,608,270 |
def parse_dft_input(input: str):
"""
Returns the positions, species, and cell of a POSCAR file.
Outputs are specced for OTF module.
:param input: POSCAR file input
:return:
"""
pmg_structure = Poscar.from_file(input).structure
flare_structure = Structure.from_pmg_structure(pmg_structur... | c24520882c888e55f91d3fcfd11fbc649ea0a7b0 | 3,608,271 |
import urllib
def getChipForYearByTargetDay(lng, lat, year, day, vis):
"""
get image chip for specified year for plot coordinate.
"""
values = {}
try:
values = getLandsatChipForYearByTargetDay(
(float(lng), float(lat)), year, day, vis)
fp = urllib.request.urlopen(value... | 7268fd5bfbfb04cd43b4eb02050bd8903ce1739d | 3,608,272 |
def make_uniform(dim=2,depth=6,Data=None,xmin=None,xmax=None,**kargs):
"""
Helper function to construct a full tree.
Parameters
----------
nleaves : int
Number of leaves to add to the tree
dim : int
Number of dimensions of the tree
depth : int
The depth of the tree
... | 0047a4d711b4d532831b3f38ddf4025485116f67 | 3,608,273 |
def get_latest_applied_migrations_qs(
connection_obj=None,
) -> "QuerySet[MigrationRecorder.Migration]":
"""Return latest applied migration in all django apps in project"""
if connection_obj is None:
connection_obj = connection
recorder = MigrationRecorder(connection_obj)
migration_qs = reco... | 5723a043416128ec5463d1bbefc881869d7a5c07 | 3,608,274 |
def get_filter(image_file):
""" Read in the filter used on the instrument and get its simple
name.
"""
with fits.open(image_file) as hdu:
prime_header = hdu['PRIMARY'].header
sci_header = hdu['SCI'].header
filter2 = prime_header['FILTER2']
if 'i' in filter2:... | 988273b4f110430ceb2c1d1eb6b861fb79595436 | 3,608,275 |
def compute_score(model, query):
"""Compute and return activity likeness for given query molecule.
"""
fingerprint = compute_representation(query)
return max([similarity_tannimoto(fingerprint, ligand)
for ligand in model]) | 12713c7d84452a302ce4ae8daabf3a014260341e | 3,608,276 |
def _bookmark_name(bookmark):
"""
Given a bookmark dictionary, return back the name of that bookmark. If the
bookmark has no defined name, one will be returned.
"""
if bookmark is None:
return "No bookmark"
if "name" in bookmark:
return bookmark["name"]
pkg_info = help_inde... | b7b3c7aea19740424d121360dc4aef533beabf80 | 3,608,277 |
import base64
import json
def encode_transaction(value):
"""Encode a transaction (dict) to Base64."""
return base64.b64encode(json.dumps(value).encode('utf8')).decode('utf8') | 066fa737b9c2d474be500bf2006ce43adea8d4f8 | 3,608,278 |
def getRawSegments(music21Part, segmentBreaks=SEGMENT_SEGMENTBREAKS):
"""
Takes in a :class:`~music21.stream.Part` and a segmentBreaks list which
contains (measureNumber, offsetStart) tuples. These tuples determine how
the Part is divided up into segments (i.e. instances of
:class:`~music21.braille... | 2a64bb74d41e02fb6262fe0dbbefe011b41b3b07 | 3,608,279 |
def calcAutoArea(img, imn, colourrange, hmatrix=None, threshold=None,
invprojvars=None):
"""Detects areas of interest from a given image, and returns pixel and xyz
areas along with polygon coordinates. Detection is performed from the image
using a predefined RBG colour range. The colour ... | 7b0fea6ddd26ca33c12205a65788beb754416f25 | 3,608,280 |
import os
def OuliersENSOjust(Serie, ENSO, method='IQR', lim_inf=0,
write=True, name=None,
graph=True, label='', title='', pdf=False, png=True, Path_Out=''):
"""
Remove outliers with the function find outliers and justify the values in ENSO periods
INPUTS
Serie... | 8f2cb637b5b2cf109b3d7da7fa918a606b135856 | 3,608,281 |
def _transitive_closure_dense_numpy(A, kind='metric', verbose=False):
"""
Calculates Transitive Closure using numpy dense matrix traversing.
"""
C = A.copy()
n,m = A.shape
# Check if diagonal is all zero
if sum( np.diagonal(A) ) > 0:
raise ValueError("Diagonal has to be zero for matrix computation to be corr... | 41c237ae9d702d69e0e96ea3e812882afab0cfc1 | 3,608,282 |
from typing import Union
import logging
def get_azure_auth(azure_config: AzureConfig) -> Union[DefaultAzureCredential, ClientSecretCredential]:
"""
Returns the authentication object for the azure.identity library,
based on either the chosen Service Principal (if set, and if the password was found), or the... | f2e39c8250622c17f47319fa9aa0e417ffe181f1 | 3,608,283 |
import logging
import urllib
import json
import os
import re
def upload_release_to_git(repo_owner, repo_name, tag, file_path, asset_name
, prerelease=None
, body=None):
"""A convenience method to upload release file to github
:param repo_owner: the repo own... | 8ee18032a30ad3dfa2423d20897df44f13dd5fbf | 3,608,284 |
def init(param_test):
"""
Initialize class: param_test
"""
# initialization
default_args = ['-i t2/t2.nii.gz -c t2 -qc testing-qc'] # default parameters
param_test.fname_seg = 't2_seg.nii.gz'
param_test.fname_gt = 't2/t2_seg_manual.nii.gz'
param_test.dice_threshold = 0.9
# check if... | d1c5db0e548d28a6d5878a78a2b3a81285a13b43 | 3,608,285 |
def residual_transformation(
model,
blob_in,
dim_in,
dim_out,
stride,
prefix,
dim_inner,
dilation=1,
group=1,
):
"""Add a bottleneck transformation to the model."""
# weight_init = None
# weight_init = ('XavierFill', {})
weight_ini... | 2fc21653e4787b7732910d466005ff67c6c61622 | 3,608,286 |
def tfConfigSetup():
"""
:return: Returns tensorflow configuration.
"""
tf_config = tf.ConfigProto(allow_soft_placement=False)
tf_config.gpu_options.allow_growth = True
tf_config.gpu_options.polling_inactive_delay_msecs = 50
return tf_config | 4592291aee5c0d3edb36b899623c7cccffdbee3b | 3,608,287 |
def toposort(dependencies):
"""Returns a tuple of the dependencies dictionary keys sorted by entries
in the dependency lists. Given circular dependencies, sort will impose
an order. Raises MissingDependency if a key is not found.
"""
s = Sorter(dependencies)
return s.sort() | 78c7ba3f56b4ba9e8c03aa953a8ab3ce3eed223a | 3,608,288 |
import random
def shuffle_sequence(sequence):
"""Shuffle sequence.
Parameters
----------
sequence : str
Sequence to shuffle.
Returns
-------
str
Shuffled sequence.
"""
shuffled_sequence = list(sequence)
random.shuffle(shuffled_sequence)
return "".j... | 1acb94516a6ed491359538f2016a22fc6d613499 | 3,608,289 |
def createBorder(image=None,color=(255,255,255),lineThickness=3):
"""
Creates border on the canvas
Arguments:
image = 3D Numpy array; image on which the border has to be added
color = (B,G,R); color of the border
lineThickness = integer; thickness of the border
"""
# If image... | 5f03ce8abf455b5b0d6d97a47fd57fec20d4d745 | 3,608,290 |
def barcode_reader():
"""Barcode code obtained from 'brechmos'
https://www.raspberrypi.org/forums/viewtopic.php?f=45&t=55100"""
hid = {4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm',
17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: '... | a25c83491cbdce81f4f353f23ed808c30d5f8117 | 3,608,291 |
def enable_cloud_admin_access(session, confirm, return_type=None, **kwargs):
"""
Enables the ability of a storage cloud administrator to access the VPSA
GUI of this VPSA to assist in troubleshooting. This does not grant access
to any volume data. Enabled by default.
:type session: zadarapy.sessio... | 5444ba9f4c917a72c666908bcd4db3b8527d596c | 3,608,292 |
import os
def getCivicLabels(data, DATAPATH):
"""
Get CIViC labels along with neutral gene labels
Parameters
----------
data : DataFrame
Must contain columns "Hugo_Symbol", "Chr", "Start", "End", "Ref", and
"Alt".
DATAPATH : str
Path to PIVOT data folder.
Returns
... | 3a980a36d672478d305522cef326b5a243484dd0 | 3,608,293 |
import hashlib
def get_icon_hash(fp, fp_name):
"""Returns a file's hashed, fp is passed as a string"""
sha1 = hashlib.sha1(fp)
return sha1.hexdigest() | 89ecd2292384cf255ecd41bd80006eafbbd13bd9 | 3,608,294 |
def delete_like_feed(id_feed:int, user:User):
"""
Method to dislik feed
:param id_feed: id feed
:type id_feed: int
:param user: user who dislike
:type user: User
"""
try:
like_feed = likes_models.LikeFeed.objects.get(feed__id=id_feed, user=user)
like... | 46805967e5044e7b7652ffa478ee3dfffd8ede18 | 3,608,295 |
def get_collapsed_file_name(psl_point: TPslPoint) -> str:
"""
Create unique file name for collapsed PSL points
"""
file_name = dut_top + psl_point["name"].split(dut_top)[-1]
file_name = file_name.replace(".", "_")
file_name = file_name.replace(" ", "_")
file_name = file_name.replace(")", "_"... | f86345e9b462d1d63f9688f1b54237994d605bc4 | 3,608,296 |
from typing import Dict
import os
def get_screenshot_path(git_hash: str, screenshot: Dict) -> str:
""" Return the full path to the screenshot image on disk for given `git_hash` """
return os.path.join(SCREEN_SHOT_SAVED_TO, git_hash,
'/'.join(screenshot['image_url'].split('/')[-2:])) | 4b5892b4326823d1a92205f4b02b9ae7c8f804af | 3,608,297 |
def _extract_name_from_tags(attributes):
"""
Extract resource instance name from its attributes
:param attributes: dict, with the following structure:
{
"arn": string,
"name": string,
"tags": {
"{tag_name}": string
},
...
}... | d83950151576bb456d8ec76097d7bea2272e4a0a | 3,608,298 |
def affine_stddev(sr: pd.Series):
"""function for calculating standard deviations of affine values"""
d = sr - affine_mean(sr)
u = d / np.array(1, dtype=d.dtype)
s = np.sqrt(np.sum(u**2))
return s * np.array(1, dtype=d.dtype) | 4dcf756e15e518e345e024dd1e6ef73132a3f088 | 3,608,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.