content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _get_model_checkpoint_directory(_params):
"""
:param _params: [argparse.Namespace] attr: experiment_name, run_name, pretrained_model_name, dataset_name, ..
:return: model_checkpoint_directory [str]
"""
return join(env_variable("DIR_CHECKPOINTS"), _params.experiment_run_name_nr) | d1f9a0097360e5e344fd29bb6cb9de9057e305cf | 3,619,141 |
def run_clients():
"""Force create driver for client """
clients = request.form.get('clients')
if not clients:
return jsonify({'Error': 'no clients provided'})
result = {}
for client_id in clients.split(','):
if client_id not in drivers:
init_client(client_id)
init_timer(client_id)
result[client_id] ... | 88735ee5485c1e2f9af3cb0da4eb94f909c42b1e | 3,619,142 |
import requests
import logging
def makeDataGetRequest(endpoint, apiKey, data={}):
"""
Helper function to make post request
:param str endpoint: Endpoint to hit
:param str apiKey: Api key to use to build header
:param dict json: Optional json data
"""
headers = {'X-API-KEY': apiKey, 'Conten... | 9ef03d5df5aaba20437d497f62a29eb0edf74d5a | 3,619,143 |
def gauss_pdf(x, a = 1, mu = 0, sigma = 1, bg = 0):
"""using scipy module function
"""
return a*norm.pdf(x, mu, sigma) + bg | d44d43e8cb35b22c500b1e5039b4aa5773a8edf9 | 3,619,144 |
def compute_emissions(tdf, df_with_emission_functions, dict_of_fuel_types_in_tdf):
"""Compute instantaneous emissions with equations used in [Nyhan et al. (2016)].
For each point in a TrajDataFrame, computes instantaneous emissions of 4 pollutants (CO_2, NO_x, PM, VOC).
Parameters
----------
tdf : TrajDataFrame
... | abe44e82a9ea637445c5996185f683f22725fc34 | 3,619,145 |
def _otbn_assemble_sources(ctx):
"""Helper function that, for each source file in the provided context, adds
an action to the context that invokes the otbn assember (otbn-as),
producing a corresponding object file. Returns a list of all object files
that will be generated by these actions.
"""
c... | f7083f17db1383135c28b324e2bc659c64c0f05c | 3,619,146 |
def reset_line_breaks(curr_boundary={}):
"""
Builds a fresh line breaks dictionary while keeping any
information provided concerning line boundaries.
Parameters
----------
curr_boundary: dict
Line boundaries to be preserved
Returns
-------
dict
The newly initialize... | da7f1fc0f206e8a39f0a0d42f1652a3c4bb23200 | 3,619,147 |
def stop(M, i):
"""
Check if the algorithm converged.
:param M: input matrix
:param i: iteration steo
:return: boolean: True if converged
"""
# this saves time, so we dont have to do multiplication in the first 7 iterations
if i > 6:
M_temp = M ** 2 - M
m = M_temp.max() -... | 3fc6cec40db8e52aed6e435a5552a8cf8edb68a1 | 3,619,148 |
def getTurnHold(mouse_x, mouse_y, army):
"""Get hold on list of turn"""
x, y = getTileAtPixel(mouse_x, mouse_y)
if x is not None and y is not None:
direction = getDirectionByPosition(x, y, army)
if direction == UP:
return [[x, y], [x + 1, y], [x - 1, y]]
elif direction ==... | 8e42918447bdc9a7c9346f2f9ccdff439729fcb2 | 3,619,149 |
def sorted_binop_expected_locs(binop_expected_locs):
"""Sorted expected locs when used in tests for sample generation."""
sort_by = attrgetter("lineno", "col_offset", "end_lineno", "end_col_offset")
return sorted(binop_expected_locs, key=sort_by) | 69ea0263716469f50ec4819deb1c1c9f87b11165 | 3,619,150 |
def InrecaMoreIsBetter(caseAttrib, queryValue, jump, weight):
"""
Returns the similarity of two numbers following the INRECA - More is better formula.
"""
try:
queryValue = float(queryValue)
# build query string
queryFnc = {
"function_score": {
"query": {
"match_all": {}
},
"script_score... | 3488ae92e463cdd2baae917e25d91415a44d5ec5 | 3,619,151 |
def sigmoid_prime(x: Tensor) -> Tensor:
"""
Derivation of the sigmoid activation function.
derivation:
f'(x) = f(x) * (1 - f(x))
Args:
x (:obj:`Tensor`): input to the function
Returns:
:obj:`Tensor`: f'(x), applies derivation of activation function
"""
return sigm... | 2d7e4328f29b50225047ccc5dd8f9c527153cef4 | 3,619,152 |
def process_xml(xml_sitemap, regex):
""" extract links from xml """
site_map_paths = set([])
url_paths = set([])
try:
# need to strip namespaces
ns_stripped = ET.iterparse(StringIO(xml_sitemap))
for _, element in ns_stripped:
if '}' in element.tag:
ele... | 848d92e48ec31584f68b43386601d953a84acf2e | 3,619,153 |
def lvar (inlist):
"""
Returns the variance of the values in the passed list using N-1
for the denominator (i.e., for estimating population variance).
Usage: lvar(inlist)
"""
n = len(inlist)
mn = mean(inlist)
deviations = [0]*len(inlist)
for i in range(len(inlist)):
deviations[i] = inlist... | 9ba4b6405569271eab39e4f49bc285a2efc51376 | 3,619,154 |
def sbert_encoder(text_list, pretrained_reference='distilbert-base-nli-stsb-mean-tokens'):
"""
Helper function using sentence_transformers which simplifies the embedding call
Args:
text_list (list): list of strings to embed
pretrained_reference (string, optional): the pretrained model to us... | 6ee99a2fc5a46e9cb5776ad80d004465d3d681e1 | 3,619,157 |
def check_pipeline_config(cfg, pure_pipelines):
"""
Check pipeline configuration, displaying a message in the Notebook
for every problem found. Returns whether the configuration is
usable at all.
"""
(okay, messages) = cfg.is_valid(pure_pipelines=pure_pipelines)
for msg in messages:
... | add7a8dcaa8e857f2b663188ddc2f067b145b728 | 3,619,159 |
def swapAMP(oldAMP, newAMP):
"""
Swap delivery of messages from an old L{AMP} instance to a new one.
This is useful for implementors of L{StoreSpawnerService} since they will
typically want to create one protocol for initializing the store, and
another for processing application commands.
@par... | cf47e038be3b2c89ab9e6f23777cd6b39d073c20 | 3,619,160 |
def get_effective_reminder_time():
""" Isolate this particular use of now() so that the effective reminder time is
practical to patch within tests.
"""
return now() | 510915a3da1914c87da1894439b791a815eccf8e | 3,619,161 |
from datetime import datetime
def do_pack():
"""generates a tgz archive"""
try:
date = datetime.now().strftime("%Y%m%d%H%M%S")
if isdir("versions") is False:
local("mkdir versions")
file_name = "versions/web_static_{}.tgz".format(date)
local("tar -cvzf {} web_static... | 3be153bdf8057e4ef7d780a39127bbd21319aaa4 | 3,619,162 |
def jaccard(box_a, box_b):
"""Compute the jaccard overlap of two sets of boxes.
Args:
box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4]
box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4]
Return:
jaccard overlap: (tensor) Shape: [box_a.size(0), b... | e38e2a52f9fe09ca684f22dbbaf5b65fd39c62ee | 3,619,163 |
def show_states_func(sp):
"""Function returning states for each frame
"""
E0 = sp.params["E0"]
dE = sp.params["dE"]
omega = sp.params["omega"]
return [[E0,"--k"], [E0+dE, "--b"], [E0+dE-omega, "--r"]] | b7d426682c324b08d622efd202b8d5cdf78336cd | 3,619,164 |
def pack_images( images ):
"""Returns the packed images (all of same size)"""
width = images[0].size[0]
height = images[0].size[1]
out_width = min([len(images), 10]) * width
out_height = ((len(images)-1) / 10 + 1) * height
out_image = Image.new("RGBA", (out_width,out_height))
x = 0
y... | 8c55e5646cbb31acd714a809b4f2c8f9f9d2aa97 | 3,619,165 |
import itertools
def makeDelayedFunctionCall(func, args, kwargs):
"""Utility function for creating a lazily-evaluated function call."""
props = set().union(*(requiredProperties(arg)
for arg in itertools.chain(args, kwargs.values())))
def value(context):
subvalues = (valueInContext(arg, con... | 001a63b7b3ec61f8b8bff875e6a22445ac31dbd3 | 3,619,166 |
def elina_scalar_cmp_int(scalar, b):
"""
Compare an ElinaScalar to a double.
Parameters
-----------
scalar : ElinaScalarPtr
Pointer to the ElinaScalar that needs to be compared.
b : c_int
Integer to be compared.
Returns
-------
result : c_int
The res... | 6429bb3d9b7c4dc8c455b175139b2e12116777e8 | 3,619,167 |
def get_extra_idx(metric):
"""Collects the extra indexes added by Operations for the metric tree.
Args:
metric: A Metric instance.
Returns:
A tuple of column names which are just the index of metric.compute_on(df).
"""
extra_idx = metric.extra_index[:]
children_idx = [
get_extra_idx(c) for c... | d3d90bccc9fd13d4fbfdc13893b29d14a82b09cf | 3,619,170 |
def yuv444to420p(img: np.ndarray, inter=cv2.INTER_LINEAR) -> np.ndarray:
"""
yuv444转420p,可自定义方法
:param img: 图像
:param inter: 插值方法
:return: 一维数组
"""
[y, u, v] = img.astype(np.uint8).transpose((2, 0, 1))
w, h = y.shape[1] >> 1, y.shape[0] >> 1
u, v = resize(u, w, h, inter), resize(v, w... | c9a3749c63a0adc4ded13208c853c6c3734a4d30 | 3,619,171 |
import math
def compute_rotation_matrix(w, phi, k, degrees=False):
"""
Computes Rotation matrix from the rotation angle w, phi, k
related to x, y and z.
Returns
-------
r_matrix: Rotational Matrix M
[cos(phi)cos(k) sin(w)sin(phi)cos(k)+cos(w)sin(k) -cos(w)sin(phi)cos(k)+sin(w)sin(... | d8a8c257f7b8c7ab3baead84e1e546274875b829 | 3,619,172 |
def iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no def... | 5a3fdc9be644902e403fce12fd15193a3cc65ef3 | 3,619,173 |
def _album_candidates(items, artist, album, va_likely):
"""Search for album matches. ``items`` is a list of Item objects
that make up the album. ``artist`` and ``album`` are the respective
names (strings), which may be derived from the item list or may be
entered by the user. ``va_likely`` is a boolean ... | 60408c0949be952a3e4e6cab512a5416b2201c60 | 3,619,174 |
def create_disk_v3_onion_service(onion_service_dir, tor_control_port, client_pub_key,
port, ip_address="127.0.0.1", client_name=None):
"""Creates a permanent Tor v3 Onion Service.
Args:
onion_service_dir: A pathlib object containing the path to the Tor Onion Service dir... | cffee272c64ee7a8f48d142309327122ac7a5c53 | 3,619,175 |
def machine_available():
""" Display an input, validate the client choice and returns the corresponding choice. """
client_choice = input(f"What would you like? ({menu_object.get_items()}):").lower()
if client_choice in menu_object.get_items():
menu_item = menu_object.find_drink(client_choice)
... | 3a11cafa4d62c35abc735e9ae1eececbc12c8fec | 3,619,176 |
def strict_type_hints(func):
"""
Enforce type hints on the parameters and return types of the decorated
function.
Also require type hints to be provided for all parmeters and the return
value.
"""
return EnforceTypeHints(func, require_args=True, require_return=True) | 99b341dd8d2015787274185dd51bace79d0aa420 | 3,619,177 |
def initializeCentroids(points, k):
"""returns k centroids from the initial points"""
centroids = points.copy()
np.random.shuffle(centroids)
return centroids[:k] | 54176cef35fbf305edb245c15262705d75f9556c | 3,619,179 |
def split_text(text, sep='\n'):
"""Split text."""
if isinstance(text, bytes):
text = text.decode("utf8")
return [elm.strip() for elm in text.split(sep) if elm.strip()] | 5247919ab151b2e4d1b4e631046d7030e673a68a | 3,619,180 |
def fit_linear_models(train_embs, train_labels, val_embs, val_labels,
model_type='svm'):
"""Fit Log Regression and SVM Models."""
if model_type == 'linear':
_, train_acc, val_acc = fit_linear_model(train_embs, train_labels,
val_embs, val_labels)... | dded20d9d6ce748868e16f6f6bf7d364460cc421 | 3,619,182 |
def jwt_get_secret_key(payload=None):
"""
For enchanced security you may use secret key on user itself.
This way you have an option to logout only this user if:
- token is compromised
- password is changed
- etc.
"""
User = get_user_model() # noqa
if api_settings.JWT_GET... | f330a766386a69c729d14225defa9a78b3617b9c | 3,619,185 |
async def api_will_snow():
"""Find out if it will snow in Berlin soon."""
wx = await get_weather()
return {"willSnow": will_snow(wx), "dataUpdated": wx["currently"]["time"]} | 4b8f5d15c4124dd2dd31a0ad411487e29b97554a | 3,619,186 |
def run(args):
"""Partition command. Prepares models from the specified module for partitioning"""
names = []
mod = args['module']
try:
mod_clss = filter(lambda obj: isinstance(obj, type), __import__(mod, fromlist=mod).__dict__.values())
except ImportError as e:
raise ImportProblemE... | bb84d6423e3a08d222e57fe7052fc94d759ca159 | 3,619,188 |
import yaml
def get_available_configs(config_file_path):
"""Retrieves all of the exiting configurations.
Args:
config_file_path: str, the name or the full path of the config file.
Returns:
A list of available config keys.
"""
with open(_get_config_file_path(config_file_path)) as config_file:
c... | 01660a829d3d4cbfbbf19d9e4fcd060f206535a5 | 3,619,189 |
from . import search
def create_app(test_config=None) -> Flask:
"""Main entry point of the service. The application factory is responsible for
creating and confguring the flask app. It also defines a http ping endpoint and registers blueprints.
Returns:
Flask: the flask app
"""
app = Flas... | e812d285fa09fb74b39083b571014989ccb0b5dd | 3,619,191 |
def dir_is_git_repo(path: str) -> bool:
"""Check if directory is a Git repository.
Args:
path: (str) path to directory.
Returns:
bool: True if successful, False otherwise.
"""
try:
Repo(path)
except InvalidGitRepositoryError:
return False
return True | 05eb624680ce9d7be5cf10644f8f8602b7b600ee | 3,619,192 |
from typing import Sequence
def to_vertices_sequence(points: Sequence[Point[Scalar]],
size: int,
context: Context) -> Sequence[Point[Scalar]]:
"""
Based on chi-algorithm by M. Duckham et al.
Time complexity:
``O(len(points) * log len(points))``
... | e69297f3aba5b7daa22951cba0662e46d5a0a608 | 3,619,193 |
import re
def replace_image_link(target_str):
"""
Replace the shorthand of an image link { image.jpg } with the full link {{ img_tag("image.jpg") | safe }}
:param target_str: String with images in it to be edited
:return: string with images formatted as {{ img_tag("image.jpg") | safe }}
"""
# ... | d72cbaacecec7d2654a20f50098f21059130dbc3 | 3,619,194 |
def ST_Affinediffeo_transformer_batch(U, thetas, out_size):
""" Batch version of the diffeomorphic affine transformer. Applies a batch
of affine transformations to each image in U.
Arguments:
U: 4D-`Tensor` [n_batch, height, width, n_channels]. Input images to
transform.
... | 4097d285223b9a9393a698f22f3c004aafb5edc4 | 3,619,195 |
import scipy.optimize
import esutil
def histoGauss(ax,array):
"""
Plot a histogram and fit a Gaussian to it. Modeled after IDL histogauss.pro.
parameters
----------
ax: Plot axis object
If None, return coefficients but do not plot
array: float array to plot
returns
-------
... | ac05c1dd642cf7102e454ded008c32db008103d3 | 3,619,196 |
from typing import Optional
def _maybe_get_mask(
values: np.ndarray, skipna: bool, mask: Optional[np.ndarray]
) -> Optional[np.ndarray]:
"""
Compute a mask if and only if necessary.
This function will compute a mask iff it is necessary. Otherwise,
return the provided mask (potentially None) when ... | d905dbecef3358e3e6f80edff8a8e72b2d1af2de | 3,619,197 |
def create_option(option, display, window, active=True):
"""
Returns an option `dict` to be used by lottus
:param option `str`: the value of the option
:param option `str`: the value that will be displayed
:param window `str`: the name of the window that this option points to
... | 31eb71dee85a7876997d4b41914f974cbcfcf938 | 3,619,198 |
def arg_fetchlive(args):
"""Parse the fetchlive parameter from the command line."""
fetchlive = 1
if len(args) >= 1 and is_int(args[0]):
fetchlive = 0
dbg_print(1, "Fetchlive: %s" % fetchlive)
return fetchlive | b125d0703420856413a465bb1757f63c64f262cd | 3,619,200 |
import typing
def get_level_1_xml(
node: et.Element,
key: str,
search_keys: typing.List[str],
data_dict: typing.Dict[str, str]
) -> None:
"""
Return the key/value pair for the xml case
<key>
<subkey>value</subkey>
</key>
Arguments:
node - Node in the x... | d6359512a9a26ef93f78a4670b49dc4b856db52f | 3,619,201 |
def boggle(board, trie):
"""Searches for words on the assumed-nonempty board."""
height = len(board)
width = len(board[0])
matches = set()
def dfs(i, j, node):
if not (0 <= i < height and 0 <= j < width):
return
ch = board[i][j]
if ch is None:
return... | f6224aaed0912da409474934d50cf3eb5e577f07 | 3,619,202 |
def run_entrainments(model_particles, bed_particles, event_particle_ids, avail_vertices, unverified_e, h):
""" This function mimics an 'entrainment event' through
calls to the entrainment-related functions.
Uniqueness of entrainments is forced post-event. Particles
which select non-unique entrainm... | abb0b97b524dc5e29f7c27dd07bbb8914c48bb65 | 3,619,203 |
def opamp_voltage_normalizer(supply_voltage):
"""
Normalize supply voltage values.
"""
parse = split_val_condition(supply_voltage)
if parse["value"].startswith("± "):
parse["value"] = parse["value"].replace("± ", "±")
(value, unit) = [i for i in parse["value"].split(" ") if i != ""]
... | f921eccb66f3ab1d1fa21466a2e7efd1e592a4a6 | 3,619,204 |
def get_L_star_CS_d_t(L_star_CS_d_t_i):
"""(32)
Args:
get_L_star_CS_d_t_i: 日付dの時刻tにおける暖冷房区画iの1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
L_star_CS_d_t_i: returns: 日付dの時刻tにおける1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
Returns:
日付dの時刻tにおける1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
"""
return np.sum(L_star_CS... | b232ebab67474ea81349ebbbc4f153b9649b2435 | 3,619,205 |
from typing import List
from typing import Type
from typing import Dict
from typing import Any
from pydantic_factories import ModelFactory
from typing import get_args
def create_function_signature_model(fn: AnyCallable, plugins: List[PluginProtocol]) -> Type[SignatureModel]:
"""
Creates a subclass of Signatur... | 113b73d02c0e5475199c46da3b64c394f487a9ef | 3,619,206 |
import math
def angacc_2_genangacc(angacc, r, dr, angvel):
"""
:param angacc: np.array
:param r: np.array
:param dr: np.array
:param angvel: np.array
:return: np.array
"""
m_rQ = r
m_rDq = dr
V = angvel
W = V
DW = angacc
t = np.linalg.norm(m_rQ)
qw = np.dot(m_r... | a4377bb861d126983f82eb4e7c1a6cd2ca261299 | 3,619,207 |
import re
def remove_proximity_around_booleans(query_str):
"""
Clients like PEP-Web (Gavant) send fulltext1 as a proximity string.
This removes the proximity if there's a boolean inside.
We could have the client "not do that", but it's actually easier to
remove than to parse and add.
>>> ... | b89ac8ab52cf00f1902603c38bc3f4fdd47cbda2 | 3,619,209 |
def extension_from_file(path):
"""Returns extension (like '.jpg') based on content of image file at path.
An empty string is returned if no match is found."""
f = file(path, 'r')
ext = extension_from_data(f.read(11))
f.close()
return ext | 8a1d4814c953a62dbf6490bdd176690698cc790f | 3,619,210 |
def _hyperbolic_distance(x, y):
"""Compute hyperbolic distance between batches x and y.
Args:
x: 2D Numpy array.
y: 2D Numpy array.
Returns:
distances: 2D Numpy array such that distances[i,j] =
hyperbolic(x[i,:], y[j,:]).
"""
sq_norm_x = (x ** 2).sum(axis=1)[:,None]
sq_norm_y = (y ** 2).... | 74a711d31a40fee0f8922ffd7a025cddc33ba649 | 3,619,213 |
from typing import Union
from typing import List
from typing import Tuple
def generalized_intervals_union(
interval_list:Union[List[GeneralizedInterval],Tuple[GeneralizedInterval]],
join_book_endeds:bool=True
) -> GeneralizedInterval:
""" finished, checked,
calculate the union of a list (or tuple) of... | 660aeaaf2d0bfae65d371b12145d6dcb78ba6031 | 3,619,214 |
def _provenance_str(provenance):
"""Utility function used by compare_provenance to print diff
"""
return ["%s==%s" % (key, value) for (key, value) in provenance] | 2cbe1f177122a49bb747cce0ccca3fd715349a6a | 3,619,215 |
def _lines_as_list(path, pattern, ignore_pattern):
"""
Helper function for config. Process lines as list of strings.
"""
try:
# All lines as list of strings
if not pattern and not ignore_pattern:
with open(path, 'r') as input_file:
ret = input_file.readlines()... | 71946764f28ec70f1795dd0473c21b17a100ec5f | 3,619,216 |
def cdmi_str_to_aceflag(cdmi_str):
"""
Return the aceflag from a cdmi string
:param cdmi_str: A comma-separated list of aceflags
:type cdmi_str: str
:return: The aceflag created from the string
:rtype: int
"""
aceflag = 0
ls_flag = cdmi_str.split(",")
for flag in ls_fla... | b7eb671e7201c9913067da71d0ed1aed561723a5 | 3,619,217 |
def group_configurations_list_handler(request, course_key_string):
"""
A RESTful handler for Group Configurations
GET
html: return Group Configurations list page (Backbone application)
POST
json: create new group configuration
"""
course_key = CourseKey.from_string(course_key_st... | d24db460c6621586a945d52081a8d9a779801324 | 3,619,218 |
from typing import Union
def phik_from_binned_array(x: Union[np.ndarray, pd.Series], y: Union[np.ndarray, pd.Series], noise_correction:bool=True, dropna:bool=True, drop_underflow:bool=True, drop_overflow:bool=True) -> float:
"""
Correlation matrix of bivariate gaussian derived from chi2-value
Chi2-value ... | 874e7761a3bf6d5d9a3b7d0e0eb154c786b693d3 | 3,619,219 |
def api_client(application, request):
"""
Fixture that returns api_client
Parameters:
app (Application): Application for which create the client.
Returns:
api_client (HttpClient): Api client for application
"""
def _api_client(app=application, **kwargs):
client = app.api_... | cf2894c8f8c2adb8a8700dfa1b9f3a99e86909d8 | 3,619,220 |
def massCheck(proj, geom, label):
"""
Calculate the total liquid mass and the variation between views.
:param numpy.array(float) proj: Projection data.
:param list(dict): Geometry dict for each line of sight.
:param str label: Label defining the current projection (res/avg, Re).
:returns: Tuple... | bc6522f4e91e2927b328d46f596e5627ebb275eb | 3,619,221 |
def get_store(name=DEFAULT_STORE_NAME, factory=DEFAULT_FACTORY):
"""
Gets store provider from factory
:param factory:
:param store_name:
:return: Storage Provider
:rtype: deployer.services.storage.base.AbstractStore
"""
return factory.get(name) | 5980bb33d640b884ec295e1cbf932425fa7c8561 | 3,619,222 |
def get_domain_adapt_config(cfg):
"""Get the configure parameters for video data for action recognition domain adaptation from the cfg files"""
config_params = {
"data_params": {
"dataset_root": cfg.DATASET.ROOT,
"dataset_src_name": cfg.DATASET.SOURCE,
"dataset_src_t... | d203aa00b3349ec7c2e6043a0496fc7da82f1b08 | 3,619,223 |
def rgb2hex(r,g,b):
"""
Convert a RGB vector to hexadecimal values
"""
hexfmt = "#%02x%02x%02x"%(r,g,b)
return hexfmt | cf0452aa22d9dbdee3158a4926fa0755ca19fbd3 | 3,619,224 |
def commonInitialization(target):
"""
Routine to initialize common variables for both position forms.
"""
target.stdfont = QtGui.QFont()
target.stdfont.setFamily("Arial")
target.stdfont.setPointSize(11)
target.stdfontbold = QtGui.QFont()
target.stdfontbold.setFamily("Arial")
tar... | b7b3d9a83b06512a1fc5090d94b437bf98282aae | 3,619,225 |
def index():
"""
Renders the 'index' page
:return:
"""
return flask.render_template('index.jinja2', my_server=flask.request.url_root) | 5e2620431b0baa1b404bb574fa781d1ff18b2437 | 3,619,226 |
from typing import VT
from typing import Optional
from typing import Callable
from typing import List
from typing import Set
def match_hadamards(g: BaseGraph[VT,ET],
vertexf: Optional[Callable[[VT],bool]] = None
) -> List[VT]:
"""Matches all the H-boxes with arity 2 and phase 1, i.e. all the Hadam... | c85d32a823d69fc7079b74c682b286069ad5dcc2 | 3,619,227 |
def align_right_position(anchor, size, alignment, margin):
"""Find the position of a rectangle to the right of a given anchor.
:param anchor: A :py:class:`~skald.geometry.Rectangle` to anchor the
rectangle to.
:param size: The :py:class:`~skald.geometry.Size` of the rectangle.
:param alignment:... | a7bc5560c7b247abea71833fd8e1c3459d9dce3c | 3,619,228 |
def _parse_docstring_field(field_lines):
"""
@param field_string:
@type field_string:
@return: return pair:
argument name, dict of updates for argument info
@rtype: C{dict}
"""
if field_lines.startswith('@type'):
field_data = field_lines.split(None, 2)
arg_name = fie... | fb10dc1db15d56fc70ee32e733113309eb9b24c3 | 3,619,230 |
def get_discount_rate(n: float, s: float, p: float) -> float:
""""
Повертає значення облікової ставки.
Parameters
----------
n : float
Термін кредиту у роках
s : float
Нарощена сума боргу
p : float
Банківський облік
Returns
-------
d : float Облікова ... | 67bb66be1b7b3e8ac34653fd47ebb960c1152dc6 | 3,619,231 |
from functools import reduce
def _is_num_tuple(t,size):
"""Returns: True if t is a sequence of numbers; False otherwise.
If the sequence is not of the given size, it also returns False.
Parameter t: The value to test
Precondition: NONE
Parameter size: The size of the sequence
Pr... | 64b3795b8e90dc38a7c48cd177d8e2aaffc0aa3d | 3,619,233 |
def resBlock(x,kernelSize,outMaps):
"""
block of resnet units, resolution halves
"""
with tf.variable_scope(None, default_name="resBlock"):
res1 = resLayerStride(x,kernelSize,outMaps)
res2 = resLayer(res1,kernelSize,outMaps)
return res2 | 5db574f64bdfcc817e3f8e526f6ef5069eae2642 | 3,619,234 |
def load_gene_gene_dat(gene_dat_path):
"""
Load gene annotation data (transcript data).
:param gene_dat_path: str, filepath for gene_gene_dat_wsize (Part of ExcisionFinder package).
:return: Refseq gene annotations file.
"""
gene_gene_dat = pd.read_csv(
gene_dat_path,
sep="\t",
... | 78921664deb2c5381ae46a913a972361befe3b5b | 3,619,235 |
def ComputeThickness2(meshes, maximumThickness, sharpAngle, cancelToken, multiple=False):
"""
Compute thickness metrics for this mesh.
Args:
meshes (IEnumerable<Mesh>): Meshes to include in thickness analysis.
maximumThickness (double): Maximum thickness to consider. Use as small a thicknes... | c884c661934535f12e59a7252aaacf512dc80758 | 3,619,236 |
def dfs(adj_matrix, minsize):
""" depth first search
Returns subsets with at least minsize or more nodes.
"""
visited = set()
connected_sets = []
for ind, row in enumerate(adj_matrix):
if ind not in visited:
connected_sets.append(set())
stack = [ind]
... | 91cf71b55e0a6a542432bf3ac932644ad9c2b854 | 3,619,237 |
import warnings
def _fit_and_predict(estimator, X, X_for_test, y, train, test, verbose, fit_params,
method):
"""Fit estimator and predict values for a given dataset split.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
estimator : estimator obje... | 37ed31d4222a8f4c1651353ce89e6ff9e098817e | 3,619,238 |
from typing import Tuple
def clahe(
image,
clip_limit: float = 0.01,
tile_size: Tuple[int, int] = (8, 8),
use_signed_negative: bool = False,
):
"""
Applies CLAHE equalization to input image. Works on color images by
converting to Lab space, performing clahe on the L channel, and converting... | 67d28c1ec1c962225211d567707ae4a6ee98087d | 3,619,241 |
def jsonify_dict(d):
"""Turns python booleans into strings so hps dict can be written in json.
Creates a shallow-copied dictionary first, then accomplishes string
conversion.
Args:
d: hyperparameter dictionary
Returns: hyperparameter dictionary with bool's as strings
"""
d2 = d.copy() # shallow c... | afbf5819fc4fda444076562b02deb22f8146f123 | 3,619,243 |
import json
def delete_floating_ips(request):
"""The deleting floating ips view."""
result = {}
project_id = request.POST['project_id']
user_token = request.POST['user_token']
region = request.POST['region']
floating_ips_dict = remove_project_resource(
region,
project_id,
... | d45661a0327dc832dd2671d8df83a311b5125dc1 | 3,619,244 |
def concat(funcname, args):
"""Return args spliced by sql concat operator."""
return " || ".join(args) | baf8d1a9e128d9c490744a93a90ae00b3072dc24 | 3,619,245 |
def generate_fe_entry(entry, name):
"""add function
"""
java_output = ""
java_output += "\"" + name + "\""
java_output += ", \"" + entry["symbol"] + "\""
if entry["user_visible"]:
java_output += ", true"
else:
java_output += ", false"
if 'prepare' in entry:
java_o... | edb2ca8b4624873a57de4f2cbaf4159e2b58f19b | 3,619,247 |
def seg_file2tensor_4band(f, fir, resize):
"""
"seg_file2tensor(f)"
This function reads a jpeg image from file into a cropped and resized tensor,
for use in prediction with a trained segmentation model
INPUTS:
* f [string] file name of jpeg
OPTIONAL INPUTS: None
OUTPUTS:
* im... | 55432d85847fa8a73d01e0028a67707feaf2dddf | 3,619,248 |
def get_pyshp_field_dtypes(code):
"""Returns a numpy dtype for a pyshp field type."""
dtypes = {'N': np.int,
'F': np.float,
'L': np.bool,
'C': np.object}
return dtypes.get(code, np.object) | 7a3f54131bed276326a0dc75e2f19a1dda53d078 | 3,619,249 |
def totient(num):
"""
Counts the numbers that are relative prime to the number.
This means that if a number 'x' has common divisors with another number 'a' lower than itself,
it is, 'a' is not relative prime to 'x'.
This means that if a number is prime, its totient function is its value - 1, as
... | c944da6dc788a4bda0237c397b763d2ab304e7ad | 3,619,250 |
from pathlib import Path
def _load_requirements(requirements_file, folder="requirements"):
"""Load requirements from a file."""
requirements = []
with open(Path(folder) / Path(requirements_file), "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith(... | e9d56a025986f9a2899b3d070033abcdeec21956 | 3,619,251 |
def img_preprocess(img):
"""
preprocessing on the input image
first crops the image then resizes it
"""
return resize_img(crop_img(img)) | 96798b3779100371a9a48df22913031f4ec80dc8 | 3,619,252 |
def sampled_dropout_average(mlp, inputs, num_masks,
default_input_include_prob=0.5,
input_include_probs=None,
default_input_scale=2.,
input_scales=None,
rng=(2013, 5, 17),
... | 42dff5ffdd34ac4a1723dd574b8163904ba60b7c | 3,619,253 |
def urljoin(url1: str, url2: str) -> str:
""" Custom function to join two url paths
Uses `~urllib.parse.urlparse` and `~urllib.parse.urlunparse`
to join relevant segments of two urls. Does not use `~urllib.parse.urljoin`
as that replaces existing url path with a new path.
Parameters
---------... | 8044a0abe2fc1dd51afe83a9fa2ec2d0c1303218 | 3,619,254 |
def getEvoBibAsBibtex(*keys, **kw):
"""Download bibtex format and parse it from EvoBib"""
res = []
for key in keys:
bib = get_url(
"http://bibliography.lingpy.org/raw.php?key=" + key,
log=kw.get('log')).text
try:
res.append('@' + bib.split('@')[1].split('<... | 1ffdce3077dc067122fcb3674d97a4f33560e939 | 3,619,255 |
def image_distance(x: IMAGE_HASH, y: IMAGE_HASH) -> int:
"""Calculates the distance between to image hashes
Arguments:
x {IMAGE_HASH} -- IMAGE_HASH object for image 1
y {IMAGE_HASH} -- IMAGE_HASH object for image 2
Returns:
int -- hamming distance of two image hashes
"""
r... | 5e038015883e6c52eaf66ae431f61d499a90cabe | 3,619,256 |
from datetime import datetime
import random
def random_date(start_date: str, end_date: str):
"""
This function will return a random datetime between two datetime
objects.
"""
dt_start = datetime.strptime(start_date, "%Y-%m-%d")
dt_end = datetime.strptime(end_date, "%Y-%m-%d")
delta = dt_e... | 5903b50fc79943120e418d619b5faef242609c0f | 3,619,257 |
from datetime import datetime
def oauth2_get_token():
"""Get an oauth2 auth_token for the app to work. May need app approval
"""
params = load_config_file(OAUTH_CONFIG_FILE)
oauth = OAuth2Session(params["client_id"], scope=params["scope"])
token_expires = datetime.utcfromtimestamp(params.get("expi... | 6e1ca4759d998aed02fef843fee02774d2300c8c | 3,619,258 |
def get_emails(notification_rec):
"""
Get list of emails for users listed in the specified notification
"""
# Use a set instead of list as there could be duplicates.
ret = []
for recipient in notification_rec.recipients.all():
ret.append(recipient.email)
return ret | 9c01b1e5615cf3a35fbda0c4d92a1e092cfc3d59 | 3,619,259 |
from typing import Type
import re
def generate_docstring(executable: Type[job_blocks.ExecutableSpec]) -> str:
"""Returns a docstring for a ExecutableSpec factory method."""
docstring = executable.__doc__
if _ATTRIBUTES_SECTION_HEADER not in docstring:
raise Exception(
f'Please add Attributes: sectio... | 91d58a14e9cb0ef4de73f0a1a67e8e916ea53f8f | 3,619,260 |
def _validate_min_max(wave, indep_min, indep_max):
"""Validate min and max bounds are within waveform's independent variable vector."""
imin, imax = False, False
if indep_min is None:
indep_min = wave._indep_vector[0]
imin = True
if indep_max is None:
indep_max = wave._indep_vect... | 1a17b61ad1fdd29a9cc4212f512e50a3c119aed3 | 3,619,261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.