content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def json_response(status_code: HTTPStatus, detail: str, body: str) -> JSONResponse:
"""json response from status, detail & body
:param status_code: http status code
:param detail: exception name in detail
:param body: error stacktrace
:return: JSONResponse object
"""
return JSONResponse(
... | 43d0b199c5ff78a0c3eeb4ee1e547715e886fbc6 | 3,602,200 |
import requests
def request_hk(url,path):
"""获取恒生指数与恒生国企指数PE"""
response = requests.get(url)
df = pd.DataFrame(response.json())
df = df.fillna('')
if not df.empty:
df.columns = ['trade_date','PE','close']
df.to_csv(path,index=False)
else:
df = None
return df | bba2c1b678d82252dcca5de61ac035629b41f665 | 3,602,201 |
def aff_trans(matrix, points):
"""Affine transform a 3D set of points"""
if not matrix.shape == (4,4):
raise ValueError("Matrix needs to be a 4x4 array")
if points.shape[1] == 3:
transpose = True
points = points.T
else:
transpose = False
p = np.ones((4, poin... | 9e206a113886a552ea062e6be9145c0e9e23c540 | 3,602,202 |
def make_null_mask(array):
"""Given a numpy array, return a numpy array of int64s containing the
indices of `array` where the value is either invalid or null.
Invalid values are:
- None
- numpy.nat
- numpy.nan
Args:
array (:obj:`numpy.array`)
"""
mask = []
... | f3511370a89e2575268392895ee98287422dffe5 | 3,602,203 |
def _tf_while_stmt(test, body, init_state, opts):
"""Overload of while_stmt that stages a TF while_stmt."""
if opts is None:
opts = {}
return control_flow_ops.while_loop(test, body, init_state, **opts) | 9d32518f47ae4a043f313e7bc4f9d837daef62f9 | 3,602,204 |
def get_patch(
image: np.ndarray, size: int, stride: int, patch_index: int
) -> np.ndarray:
"""
Returns a single patch from the input image.
The patch index should be a number in the interval [0, patch_count).
Patches are numbered in row-major ordering.
Patch 0, ..., <# of patch columns> is on ... | d68215dcc9725fb0e70593bc302a8ce05155af94 | 3,602,205 |
def modified_bisection(f, a, b, eps=5e-6):
"""
Function that finds a root using modified Bisection method for a given function f(x).
On each iteration instead of the middle of the interval, a random number is chosen as the next guess for the
root.
The function finds the root of f(x) ... | 54903a6c1fbe7bfabba43ada92df8b15360f098c | 3,602,206 |
def _range_checker(ip_check, first, last):
"""
Tests whether an ip address is within the bounds of the first and last address.
:param ip_check: The ip to test if it is within first and last.
:param first: The first IP in the range to test against.
:param last: The last IP in the range to test again... | 924e617374fdbc4cabc28cb18e63c45192da3b4c | 3,602,207 |
def get_pressed(joystick, button):
"""
Return whether or not a joystick button is pressed, or
:const:`False` if the requested joystick or button does not exist.
Arguments:
- ``joystick`` -- The number of the joystick to check, where ``0``
is the first joystick, or the name of the joystick to... | 507457ba44412986e90084b5588bc0b1c0e9b267 | 3,602,208 |
def ndcg_score(y_true, y_score, k=10, gains="exponential"):
"""Normalized discounted cumulative gain (NDCG) at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k... | 8a1eef843f3f1ac2c2b258c4c6c2cf88a9bfb4e0 | 3,602,209 |
import tqdm
def _copy_file_list_internal(file_list, message, callback):
"""
Takes a list of tuples (src, dest, size) and copies the data in parallel.
Returns versioned URLs for S3 destinations and regular file URLs for files.
"""
if not file_list:
return []
total_size = sum(size for _... | 406134569e45581218aa120fcfb3f7e2bb79d5c4 | 3,602,210 |
from typing import Container
def get_cont_config(cont_id):
"""
Fetches VM information for the given ID.
Creates a map of parameters and corresponding display strings
@param vm_id: VM ID
@type vm_id: C{int}
@return: Map of vm parameters an its display values.
@rtype: C{map}
""... | 940a0552574ac5daedac1fa56ff2371c3c0eeeaa | 3,602,211 |
import logging
import collections
def file_based_convert_examples_to_features(examples,
label_list,
max_seq_length,
tokenize_fn,
output_file,
... | 4e3b7e1fcaa94dbd832afbe8c164ee2caa6b89c7 | 3,602,212 |
def _build_signatures(graph: tf.Graph, signature_def_map: dict) -> dict:
"""
Turn a signature map into a proper argument for ``add_meta_graph`` by
creating tensor info for each output name given in ``signature_def_map``.
Args:
graph: TF Graph instance
signature_def_map: Dictionary that ... | d212e6e759387676000d15434b27f32535f51ba6 | 3,602,213 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_urlhaus]
url=https://urlhaus-api.abuse.ch/v1
# these are needed for submitting malware urls
submit_url=https://urlhaus.abuse.ch/api/
# ... | ae09bac3b31cef4b7a6204b1baa1886b6457498d | 3,602,214 |
def optional_nrrdvector(inp):
"""Parse a vector from a nrrd header that can also be none."""
if (inp == "none"):
return inp
else:
return nrrdvector(inp) | 1f98c1bf43c5de3a3bf6e22a7b7d7d70bbc88328 | 3,602,215 |
def crr_m(ksigma, msf, crr_m7p5):
"""Cyclic resistance ratio corrected for m_w and confining stress"""
return crr_m7p5 * ksigma * msf | 76b271ac72b29ec583aa8a23aeb22e8dbf248365 | 3,602,216 |
import re
def concatenate_lines(lines, pattern):
""" concatenate lines
>>> import re
>>> pattern = re.compile(r"(^\s+)(.+?)")
>>> lines = [u"a", u" b", u" c", u" d", u"e"]
>>> concatenate_lines(lines, pattern)
[u'a', u' b c d', u'e']
>>> lines = [u"a", u" b", u" c", u" d", u"e"]
>>> ... | eb21d40771d16d33754aceab106770c8047a83fa | 3,602,217 |
def median_polish_group_wise(data:NDFrame, rtol:float=1e-05, atol:float=1e-08) -> NDFrame:
"""Apply Median polish group-wise.
Args:
data (NDFrame) : Input data. Shape = ( ``n_samples``, ``n_features`` )
rtol (float, optional) : [description]. Defaults to ``1e-05``.
atol (float, ... | 5b962b6757e8f6cd04f77c32fb35a2a19f80f241 | 3,602,218 |
from typing import Union
from typing import Mapping
import os
def numpy_to_arkouda(
A: np.ndarray, tmp_dir: str = ""
) -> Union[pdarray, Strings, Mapping[str, Union[pdarray, Strings]]]:
"""
Convert from numpy to arkouda using disk rather than sockets.
"""
rng = np.random.randint(2**64, dtype=np.ui... | 5cee0a52e2acfd60a2df5ad25edd1457d2b35678 | 3,602,219 |
def _is_value(v):
"""
Returns True if the given value is a @value.
:param v: the value to check.
:return: True if the value is a @value, False if not.
"""
# Note: A value is a @value if all of these hold True:
# 1. It is an Object.
# 2. It has the @value property.
return _is_object... | 9c2b46677f9734cc6c78a5c0068ea3ed833382b7 | 3,602,220 |
import zlib
def get_message(conn, deco):
"""
Handle a received TCP message, synchronously reading it to completion.
Argument: conn
TCP connection
Argument: deco
ZLIB decompression object
Return: updated decompression object in the case where compression was
reset
"""
... | 643d4f98b553cd510b9cd99caaab414c82aaf29b | 3,602,221 |
def restriction(mesh, submesh):
"""
Return a Python function `r` of the form
r: f -> f_submesh
whose first argument `f` is either a `dolfin.Function` or a
`numpy.array` and which returns another `dolfin.Function` or
`numpy.array` which has the same values as `f` but is only
defined on `... | b1c07d5c4c1ef7afbc87c68cb16fae09d397dd30 | 3,602,222 |
def collapse_taxa(feature_table_artifact, taxonomy_artifact, collapse_level="asv"):
"""
Collapse feature table to user specified taxa level (ASV by default).
Input:
- QIIME2 artifact of type FeatureData[Taxonomy]
Returns:
- pd.DataFrame
(taxa/ASV as rows, samples as columns, numeric index, appends 'Taxon' ... | 872a1a0629bf8e81c6fdc59f98edfc8109a4ca30 | 3,602,223 |
import os
def load_configs(filepath, group=None):
"""
:param filepath: (JSON) file path contains parsed results
:raises: ValueError, TypeError
"""
if group is not None:
filepath = group_config_path(filepath, group)
if not os.path.exists(filepath):
raise IOError("File not found... | 530a066b950486099d61054c6fdc9be97c119605 | 3,602,224 |
import os
import shutil
def create_mesh(name, shape, cl, folder = "./meshes", delete_prev = False, draw = False):
"""
Generates a 2D mesh with characteristic length cl.
Supported shapes:
'square' A square from (0,0) to (1,1).
'circle' A cirlce located at (0,0) with radius 1.
... | 9f24a20a92eceaa0c7995cfbff6bd5ac8f06ab06 | 3,602,225 |
from bs4 import BeautifulSoup
def parse_words(html):
"""解析 html 源码,返回汉字列表"""
soup = BeautifulSoup(html)
a_list = soup.find_all('a', attrs={'target': '_blank'})
return [x.text for x in a_list if x.text] | 629ccc8be01699ea747061c3340772569109d109 | 3,602,226 |
import attr
def stacked(graph):
"""Turn a graph into a stacked graph."""
return attr.assoc(
graph,
lineWidth=0,
nullPointMode=G.NULL_AS_ZERO,
stack=True,
fill=10,
tooltip=G.Tooltip(
valueType=G.INDIVIDUAL,
),
) | fcdf6c8a6df0dbda16f3cd4f32ae1b548ce3946f | 3,602,227 |
def DeconvolutionalBlock(
kernel_size=(2, 2),
activation=None,
padding="valid",
strides=2,
normalization=False,
norm_kwargs={},
**kwargs,
):
"""A single 2d deconvolutional layer.
Accepts arguments of keras.layers.Conv2DTranspose.
Parameters
----------
kernel_size : int
... | a6d2e53edb84b7d00b9180c7ad53cdd264ff0b59 | 3,602,228 |
def SSLChannels_ATR(dataframe, length=7):
"""
SSL Channels with ATR: https://www.tradingview.com/script/SKHqWzql-SSL-ATR-channel/
Credit to @JimmyNixx for python
"""
df = dataframe.copy()
df['ATR'] = ta.ATR(df, timeperiod=14)
df['smaHigh'] = df['high'].rolling(length).mean() + df['ATR']
... | 3adeb4d37b84c453b4f559afa115c669244fcd88 | 3,602,229 |
def translate_status(sbd_status):
"""Translates the sbd status to fencing status.
Key arguments:
sbd_status -- status to translate (string)
Return Value:
status -- fencing status (string)
"""
status = "UNKNOWN"
# Currently we only accept "clear" to be marked as online. Eventually we... | 2274ff63aea9249cecacf455598a57fba1245ace | 3,602,230 |
def format_generic_number(event_value, attribute):
"""
Creates a filter format string for a generic number attribute.
:param str event_value: String that is used to generate the filter string.
:param str attribute: The attribute that is used in the filter.
:return: A string that can be used in a LQ... | eb27e70aa5b2b0dff5ff0428c3e84a6320fa3c9d | 3,602,231 |
from src.praxxis.display import display_rulesengine
from src.praxxis.util.error import EmptyHistoryError
import sys
from src.praxxis.display import display_error
def what_next(args, user_info_db, current_scene_db, library_db, rulesengine_db, query_start, query_end):
"""calls prediction query_endpoints to get next... | 4a359c86f3b4a21c38c161aa2462522abf802689 | 3,602,232 |
from typing import cast
def is_null_ptr(p) -> bool:
"""[Internal] Return if the passed pointer is NULL"""
return not cast(p, c_void_p).value | 8a0bce41ebe2aacd984e408f4add4ccecbe27b26 | 3,602,233 |
def MergeFilesCoverageDataForPerCL(a, b):
"""Merges coverage data files for per-cl coverage data.
The original data includes 'uncovered blocks', but this merge function drops
it because it's non-trivial to merge them, and it won't be useful at all
unless Gerrit decides to support displaying them, and it's stil... | 2332df9adcfa8a1c9debe25f6543df44015ec027 | 3,602,234 |
def subset_multidimensional_raster(input_multidimensional_raster,
variables=None,
dimension_definition='ALL',
dimension_ranges=None,
dimension_values=None,
... | 980a4fa7309ebaac1c6ef042317728edb15189a7 | 3,602,235 |
def html_confirmation_email(confirmation_link: str):
"""
render template for email to confirm email address
:param confirmation_link: link with token created by itsdangerous
:return: rendered email html for email confirmation
"""
return render_template("emails/confirm_email.html", confirmation_l... | 6becc3235d6615027fdc6e4f1ec900f7f3cd9009 | 3,602,236 |
def get_computation_matrix(a, copy_bcm=False,
check_col_vector=False,
return_ndim=False,
isVector=False):
"""get_computation_matrix"""
if not isinstance(a, FrovedisBlockcyclicMatrix):
if type(a).__name__ == 'matrix':
... | d7052a6f69c2c6b67012d80ee82136f27f551913 | 3,602,237 |
def indentedBox(widget, sep=20, orientation=Qt.Vertical, **misc):
"""
Creates an indented box. The function can also be used "on the fly"::
gui.checkBox(gui.indentedBox(box), self, "spam", "Enable spam")
To align the control with a check box, use :obj:`checkButtonOffsetHint`::
gui.hSlider... | 52f7fac4b534c01d0076b36b86306ab95936e24f | 3,602,238 |
def toggle_mode(request):
"""
Toggles between Tetris/grid.
"""
session_check = _check_session_valid(request)
if session_check:
return session_check
request.session["analytics"].toggle_mode()
return JsonResponse({}) | 6f1abf6507b5ab0f364009e88679a75d74c25f34 | 3,602,239 |
def theta_k(circumbody,k=0,i=0):
"""
This is from the Section 4 of the paper [Sadraddini and Tedrake, 2020].
Inputs:
* AH-polytope: ``circumbody``
* int ``N``: the number of columns added to the subspace of ``U``.
For more information, look at the paper.
*Default* ... | 237673dd600ca4def26ce9f8ece9b7a39b1b5126 | 3,602,240 |
def hybridization(atom: Atom) -> HybridizationType:
"""Hybridisation (HybridizationType).
"""
return atom.GetHybridization() | 011762f6745daeb0e094d2de84a9cff6d3d88bba | 3,602,241 |
import time
def yolo_eval(yolo_outputs, anchors, num_classes, image_shape, score_threshold=.5, iou_threshold=.45):
"""
Obtain predicted boxes axis and corresponding scores
Args:
yolo_outputs: output (3 feature maps) of YOLO V3 model, sizes are 1*13*13*18; 1*26*26*18; 1*52*52*18 seperately
... | 755cb87380ba252bb6843e6dfdf87e5d2e397a8d | 3,602,242 |
from pathlib import Path
def get_js_libs_from_yaml():
"""
Get all npm package names from the /udfs/js_libs/js_libs.yaml
file.
:return: dict representation of the js_libs.yaml file
"""
js_libs_yaml_path = Path('./js_libs/js_libs.yaml')
if js_libs_yaml_path.is_file():
with open(js_l... | dcd8d56dc80e097227ca89661ececcdbabf94b3a | 3,602,243 |
def create_resource(
resource: "definitions.Resource", namespace: str = None, echo: bool = False
) -> ResponseInfo:
"""..."""
try:
status = resource.create_resource(namespace)
response = ResponseInfo(resource, "+", "Created", status=status)
except ApiException as error:
response ... | 55e11d595c4bfb012e732ee205c21a78ee57d36f | 3,602,244 |
def _get_locations(request):
"""
Get's the user desired location from the query
Args:
request (Request): contains info about the conversation up to this point
(e.g. domain, intent, entities, etc)
Returns:
list(string): resolved locations entity
"""
return [e for e in re... | 9e6c4d642053cfaa5120fb8fa020020f3f724193 | 3,602,245 |
def register_functions(prefix):
"""Construct a dict of certain functions defined in a module. This lets
scripts that import the module access these functions dynamically using a
dict rather than using getattr messiness, importlib (which makes imports
invisible to htools requirements.txt builder), or eva... | c702c326874e96538e85e31e4c46608f267f6111 | 3,602,246 |
def queue_import_task(
account: str, operation_id: str, manifest: InternalImportManifest
) -> bool:
"""
Queue the task for analysis
:param account:
:param manifest:
:return:
"""
# Replace this is a state watcher, similar to the image state handlers
logger.debug(
"Queueing im... | b724ea9480e782c2ae038a0c12a742ad9c755e31 | 3,602,247 |
def moving_average_exp(input, n_points):
"""
Calculate Exponential Moving Average
Paremeters:
input: ndarray
input signal
n_points: int
numbers of moving average points
Returns:
result: ndarray
moving-averaged signal
"""
alpha = 2.0 / (n_points... | acd3035e1e6dd25f76453eeab0c3730be70bef4b | 3,602,248 |
def whitelist_add(request):
"""
API endpoint to add a whitelist item
"""
user = request.user
success = False
errors = {}
data = None
_type = request.POST.get('form_type', None)
if request.POST and request.is_ajax():
if _type == "whitelist":
url = request.POST.ge... | 708da564a67c137db37739c632337b635c29cfc4 | 3,602,249 |
import os
def save_image(bucket_name, file_name, image):
"""Saves an image.
Saves the image by uploading it to the BUCKET_NAME.
Args:
bucket_name:
Dictionary that contains data specific to the bucket.
file_name:
Dictionary that contains data specific to the event.
... | 7e05de289ee9b2512eb8d0b3a095ca8b31a939d7 | 3,602,250 |
def version(*names, **kwargs):
"""
Common interface for obtaining the version of installed fileset/rpm package.
CLI Example:
.. code-block:: bash
salt '*' pkg.version vim
salt '*' pkg.version foo bar baz
"""
return __salt__["pkg_resource.version"](*names, **kwargs) | 8b5bbf766119614b43485378530688b5c2aef6aa | 3,602,251 |
import itertools
def generate_transitions_dictionary(education_levels):
"""build a lookup table for next education targets
Example frame looks like..
ETH.group,MB.0,M0.1,M1.2,...,M98.99,M99.100,M100.101p,FB.0,F0.1,F1.2,...F98.99,F99.100,F100.101p
BAN,Less than GCSE,
BAN,GCSE,
BAN,CSE,
BA... | b47018d0701f5674724d01a708a099fc34012044 | 3,602,252 |
import math
def entropy(data):
"""
Calculate informational entropy.
"""
entropy = 0.0
frequency = {}
for instance in data:
p_instance = int(round(instance/5) * 5)
if p_instance in frequency:
frequency[p_instance] += 1
else:
frequency[p_instance] ... | 4b96c229e4cc0318a764990569d2951003447a72 | 3,602,253 |
def get_transformed_bounds(img, transform):
"""
Returns the transformed bounds of an image, after applying the given affine transformation.
Two points are returned: the new origin of the image and the new diagonal. Their coordinates are relative to the original origin point.
"""
maxX, maxY = img.sh... | cb40ebeb2771c52198ea3fc6e1dd0404a7e1f4ca | 3,602,254 |
import os
import pandas
def load_nf_overview_data(sport):
""" Load the most recent overview data from Numberfire.
Includes individual player-to-slug mappings so downloading history is feasible.
:return DataFrame: overview data
"""
overview_data_dir = get_overview_file_dir(sport)
overview_files = [os.path... | 36626a05c18a4ebb6c3b78ec3e822fa72b949335 | 3,602,255 |
def rate_scheduler(lr=.001, decay=0.95):
"""Schedule the learning rate based on the epoch.
Args:
lr (float): initial learning rate
decay (float): rate of decay of the learning rate
Returns:
function: A function that takes in the epoch
and returns a learning rate.
""... | 5808da433b8752921551c8149346374d83634461 | 3,602,256 |
def get_pdb_data(pdb, data_dir="", assembly=1, skip_download=0):
"""Function to get atom coordinates and atom/residue metadata from pdb structures.
Args:
pdb (str): pdb ID
data_dir (str): path to pdb directory
assembly (int): 0/1 indicator of whether to use biological assembly or ... | 59dfc3e3fb7e57966939c6949fa1d4c1ca51d9e2 | 3,602,257 |
def _compute_initial_position_alt_2(A, a, B, b):
"""
This is an alternative implementation to _compute_initial_position
using Rainer's line of thought.
"""
rows = cols = (0,1,2,3,6)
AL = A[rows,:][:,cols]
BL = B[rows,:][:,cols]
AR = np.array([
[ 0, 0, 0, 0],
[-1, 0, 0, ... | e76ea795febb90bd78221bafe5f29b31d85ca8b2 | 3,602,258 |
from re import TEMPLATE
def get_workbook(args):
"""Load the excel workbook from the template and set initial data."""
wb = openpyxl.load_workbook(TEMPLATE)
cover = wb["Cover"]
cover["E13"] = args.name
cover["E14"] = args.tax_ref
cover["E15"] = args.year
summary = wb["Summary"]
summary[... | 208d7b8b230e393766330ac058333c8a34432cb0 | 3,602,259 |
def _set_options(options):
"""Sets default options if none are given"""
if options is None:
# Set defaults
options = ''
if SHOW_HOST_NAMES:
options += 'show_hostnames,'
return options | 97ee0d9f3639144e8c2e92ebdcd6353097e997b1 | 3,602,260 |
def get_dsproc_logger() -> Logger:
"""Attach the logger of this module"""
return get_default_logger('DSProc') | e30be30daac005f6ec87ed6cb57f49cd118fddf4 | 3,602,261 |
def tsp(edges, time_limit=5, concorde=False, precision=0) -> list:
"""Compute TSP solution
Args:
edges (list): List of tuple (source, target, weight)
time_limit (int, optional): Time limit to run. Default to 5 seconds.
concorde (bool, optional): Shall we run concorde? Defaults to False.... | 9b9fa8470d523c375b6853cc168a194351f5b0a3 | 3,602,262 |
import jinja2
def check_template(template_string):
"""
Check the syntax of a template. Return an error tuple (line number,
message) if the template is invalid or None if it is valid.
"""
try:
jinja2.filters.FILTERS['multi_sort'] = multi_sort
jinja2.Template(template_string)
exc... | 08281ecab5e2acd4d63a1a6dbe181477288cc1fb | 3,602,263 |
def _GetPseudoAAC1(ProteinSequence, lamda=10, weight=0.05):
"""
#######################################################################################
Computing the first 20 of type I pseudo-amino acid compostion descriptors based on
[_Hydrophobicity,_hydrophilicity,_residuemass].
#################... | cd1b83b3c4cc8b7c60b9460c8f4bedafb066bb25 | 3,602,264 |
def plot_scatter(ax, prng, nb_samples=100):
"""Scatter plot."""
for mu, sigma, marker in [(-0.5, 0.75, "o"), (0.75, 1.0, "s")]:
x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples))
ax.plot(x, y, ls="none", marker=marker)
ax.set_xlabel("X-label")
ax.set_title("Axes title")
re... | 02f23849ed4f2dded875866027eead00ebd1f0dc | 3,602,265 |
def get_nzs1170p5_hazard():
"""Retrieves the NZS1170p5 hazard for the station"""
server.app.logger.info(f"Received request at {const.NZS1170p5_HAZARD_ENDPOINT}")
cache = server.cache
(ensemble_id, station, im), optional_values_dict = au.api.get_check_keys(
flask.request.args,
("ensemble... | 97bcbdb1b8d46072ec4cfd55fa9667239edf8204 | 3,602,266 |
import os
def read_sample_names(data, slow_names=True):
"""
Reads in sample names for dataset
Some data input formats do not support fast ways to read sample names (h5ad) and when slow_names is False, reading them will be skipped.
"""
if len(data) == 1:
ext = os.path.splitext(data[0])[-1]... | c2b052cfeda13d7be0c31e1aa9cc82913ad69fc7 | 3,602,267 |
def findGlobals(pool_name, auth_identity, classad_type, additional_constraint=None):
"""
Query the given pool to find the globals classad.
Can be used to query glidefactoryglobal and glidefrontendglobal classads.
"""
status_constraint = '(GlideinMyType=?="%s")' % classad_type
# identity checki... | 0def2bcb7a7a48bb98b4c4948a3ff5760562fe21 | 3,602,268 |
def getBestReinforcement(
user: User,
mine: Game,
maxPrice: Tus,
teamConfig: ConfigTeam = None,
lootingOrMining: TeamStatus = None,
) -> CrabForLending:
"""
Find best crab to borrow for the given mine and at the given max price,
using the first suitable Reinforce strategy provided in the... | f2f7ab28d5c168396e2d643274ea80bed248dfb1 | 3,602,269 |
def do_or(node: Node) -> bool:
"""
Evaluate the value of an OR expression.
Parameters
----------
node
The ast representing an or expression.
Returns
-------
bool
The expression's evaluated value.
"""
return any((visit_tree(child) for child in node.children)) | 38059b61e032d07e146cd26c1d840fb4cb2bd6ac | 3,602,270 |
def create_db_from_files(files, database_name=":memory:"):
"""Creates a database with the data extracted for a list fo files.
The file must be an estimators.dat-type file. A new database is created.
The database is created in memory if no database_name is provided.
Parameters
----------
filen... | 5d3be702c53a9cef4e4c9f6e3db59cb18ce9aca2 | 3,602,271 |
def s2c_stereographic(sph):
"""
Stereographic projection from the sphere to the plane.
"""
u = sph[..., 0]
v = sph[..., 1]
w = sph[..., 2]
return (u + 1j*v)/(1+w) | 1aff6cf6accd6bb26c647f014dc964404e84b979 | 3,602,272 |
def compute_param_matrix(parameters, t):
"""Calculate all the possible parameters for a set of search values
Parameters
----------
t : nd vector
time vector from the data
Returns
-------
generator
each iter returns a tuple of 2 (gaussian) or 3 (gamma) values
tuple of 2 ... | 48e75e6307c98d74bb89e9694f42b844c126bcd6 | 3,602,273 |
def create_parser(plugins, args):
"""Create parser."""
helpful = HelpfulArgumentParser(args, plugins)
# --help is automatically provided by argparse
helpful.add(
None, "-v", "--verbose", dest="verbose_count", action="count",
default=flag_default("verbose_count"), help="This flag can be ... | e9668c8e2cbc354d8f638f04a2a0c92a90a3fb9b | 3,602,274 |
def geomdbset(tab, minlon=None, minlat=None, maxlon=None, maxlat=None,
source_name='__GENERIC__', tags=[], zoom_level=None, classic_tile=True, geom='geom'):
"""
tab @pydal.table : DB table to query.
minlon @float : Bounding box left limit longitude coordinate.
minlat @float : Bounding box bottom lim... | e4ceed909c892711544a4220992251410ca5c376 | 3,602,275 |
import time
def simulation(models: dict, ts_data: SimulationDataset, retrain_frequency: int):
"""Run one portfolio simulation over the input DataFrame.
:models: Dictionary of ("Model Name", "Model Object") key-value pairs. Will look for "Model Name".pkl files to load pre-trained models.
:ts_data: DataFram... | cf1ee477317efb4366a40956beeb9115b85852a4 | 3,602,276 |
def text(node):
"""
Get all the text of an Etree node
Returns
-------
str
"""
return ''.join(node.itertext()) | f5000a6220da74059230a499dc2b48057e5c4ada | 3,602,277 |
def periodic(x, axis, depth):
""" Copy a slice of an array around to its other side
Useful to create periodic boundary conditions for overlap
"""
left = ((slice(None, None, None),) * axis +
(slice(0, depth),) +
(slice(None, None, None),) * (x.ndim - axis - 1))
right = ((sli... | 71713988cab28cfa04f711f4f0887b8a134e176b | 3,602,278 |
def plot_results(results, plot_order, method_legend_colour_marker_dict, x_label,
y_label, x_bounds=None, y_bounds=None, to_plot_legend=True,
true_maxval=None, outlier_frac=0.0, plot_title=None, options=None):
# pylint: disable=too-many-arguments
""" Plots the results using Matp... | c4fe18dec7c28cd8cd821714515d2636c71791b9 | 3,602,279 |
import yaml
def update_metadata(workspace_path, profile, verb, new_data=None, no_init=False, merge=True):
"""Update the catkin_tools verb metadata for a given profile.
:param workspace_path: The path to the root of a catkin workspace
:type workspace_path: str
:param profile: The catkin_tools metadata... | 7577fe9c2a0d9ae79628de0b38a52a603c5c07c8 | 3,602,280 |
from typing import Union
from typing import Callable
def fully_qualified_name(thing: Union[type, Callable]) -> str:
"""Construct the fully qualified name of a type."""
return thing.__module__ + '.' + thing.__qualname__ | eacbffdcda78fa38667af0b9d7bc0c53c2fbdb1f | 3,602,281 |
def remove_whitespace(text):
# type: (str) -> str
"""strips all white-space from a string"""
if text is None:
return ""
return "".join(text.split()) | 747538de63b11e49d498b2f4ccb8286975019ec8 | 3,602,282 |
def draw_at_bottom_left_of_raft_number_float(img_bgr, rafts_loc, neighbor_count_wt, num_of_rafts):
"""
write a subscript to indicate nearest neighbor count or weighted nearest neighbor count
"""
font_face = cv.FONT_ITALIC
font_scale = 0.5
font_color = (0, 165, 255) # BGR
font_thickness = 1
... | aa32e138693ca299a31b50f78332d765aab96614 | 3,602,283 |
import requests
import sys
def rubrik_get(api_version, api_endpoint):
""" Connect to a Rubrik Cluster and perform a GET operation """
AUTHORIZATION_HEADER = {'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic ' + b... | 297ab1994662997a73ae8f7509701cf77e0af4ec | 3,602,284 |
def sol(board):
"""
Plain backtracking, find which cell is empty and assign the number.
Return on first True
"""
row, col = None, None
row, col = findEmptyCell(board)
if row == None and col == None:
# Careful about using 'not row'
return True
for num in range(1, 1... | 824ddcc27372d70c3d31eb7d9a5b72dc9eb9521a | 3,602,285 |
import re
def address_line1(a):
"""Return only the main part of a multipart address
Warnings:
- Only works on canonicalized addresses. Call canonicalize() first.
- Returns addresses that are incorrect!
- Only use the output of this function for fuzzy matching.
>>> address_line1('1910 south m... | 453e68ed2889e899ef339def772191c32f7997bc | 3,602,286 |
from typing import Dict
def _invert(mapping: Dict) -> Dict:
"""Invert dictionary {k: v} -> {v: k}."""
return {target: source for source, target in mapping.items()} | 013894d56e95a5df273a5bed6a7acc9c49c18d10 | 3,602,287 |
def multilabel_sample(
y_labels: npt.ArrayLike,
size: float or int = 1000,
min_count: int = 5,
seed: int = None,
) -> npt.NDArray[np.int_]:
"""
Takes a pd.DataFrame or np.ndarray matrix of binary labels `y_lables`
and returns sorted np.ndarray of indices for the sample of size `size`
if ... | aa84d31bd21342d5e770d534b8ccd8546e0fa655 | 3,602,288 |
def pesquisa_candidatos_nome(padrao_busca, cargo):
"""Pesquisa os candidatos de acordo com o nome"""
lista_retorno = []
# retorna todos os candidatos de acordo com o cargo
if(padrao_busca == "all"):
for i in candidatos:
if(candidatos[i][4].lower() == cargo.lower()):
l... | 80618d9e8bfe300ec97e3af838ea26f0d077b869 | 3,602,289 |
import six
def stamp_parameter_in_graph(parameter_name, parameter_type, graph):
"""Stamps a parameter of a given type in the given tf.Graph instance.
Tensors are stamped as placeholders, sequences are stamped as data sets
constructed from string tensor handles, and named tuples are stamped by
independently s... | 9a9092c569f5ca5b14e5ef66bcc68437819d7a4d | 3,602,290 |
def near_edge(img, contour):
"""Check if a contour is near the edge in the given image."""
x, y, w, h = cv2.boundingRect(contour)
ih, iw = img.shape[:2]
mm = 80 # margin in pixels
return (x < mm
or x + w > iw - mm
or y < mm
or y + h > ih - mm) | d4c2aa20dbec1ff89020c509e27ea28077397e53 | 3,602,291 |
def convert_to_radians(value):
"""method converts an individual value to radians"""
try:
return value * pi / 180
except:
print('An unexpected error occurred! Please try again.')
exit() | 59659cd52acdb5af9ea87979be68861adb6f3d0b | 3,602,292 |
from typing import Optional
from typing import Tuple
def result_with_template(fun, **results: Optional[TelQueryResult]) -> Tuple[ClauseElement, ClauseElement]:
"""
Apply the function to each result's `.sql` and `.template`, returning a tuple of both results.
:param fun: function accepting as many ClauseEl... | 86cfc9362200ee3003a26918e06c95050da71257 | 3,602,293 |
import torch
def greedy_decode(model,bert,tokenizer,
sent,glyph2ix,
pinyin2ix,pos2ix,
ix2glyph,device):
"""
Generate a Couplet Sentence through Greedy Approach
Output dimension is glyph dim.
return in list format e.g.(['1','2','3'])
"""
... | 8d50a9cd2a4b8f1a5b343170044783ff05eac8fc | 3,602,294 |
def _process_rget_with_transform(func, ignore_errors=False):
"""Post process the JSON result (if successful) with F(json_d) -> T"""
def wrapper(total_url, headers=None):
j = _process_rget(total_url, ignore_errors=ignore_errors, headers=headers)
return func(j)
return wrapper | 3f31cb677d25c57b9e8f569178dd2d4e2df14e47 | 3,602,295 |
def test_case(request, user_test_id, test_id):
"""
Shows information about test before user could start it.
Check if test is exists and available for current user (@return(option 1)).
When user starts test (@return(option 2)):
- if test has time limit add to request.session expire time (if not exis... | 66742d41b7bc5ef1984779541946cd9bf1e22a02 | 3,602,296 |
from typing import Dict
from typing import Any
def flatten_array(arr: jnp.ndarray, shape: Dict[str, Any]):
"""Flatten array."""
s = shape
assert arr.shape[-len(s['shape']
):] == s['shape'], f'{arr.shape} incompat {s["shape"]}'
arr = arr.reshape(arr.shape[:-len(s['shape'])] + (s['size'],... | c0e1b314c5b999388f7470efd5afa104878b1c3b | 3,602,297 |
from datetime import datetime
import tempfile
import os
def at(command, when, queue = 'a'):
""" Execute command at when.
command may be anything interpreble by /bin/sh. If you need features
specific to another shell, create a script and then make the command
<path to shell> <path to scrip... | 565f6846dc2fb76364a6fe4f9d5b3164a80f30cf | 3,602,298 |
def mock_role_form_data(model, data):
"""
In order for form to don't fail submission, all permission fields need
to receive values. This function populates data dict with default values
for permissions, making form validation pass
"""
for form in get_permissions_forms(model):
for field i... | 0b79aa35dc2275a81d6dc8628c549b7faed169d0 | 3,602,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.