content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def connect_to_service(service_name, client=True, env=None, region_name=None, endpoint_url=None):
"""
Generic method to obtain an AWS service client using boto3, based on environment, region, or custom endpoint_url.
"""
env = get_environment(env, region_name=region_name)
my_session = Non... | 364bfd5d1036627187ff8ead8429b776f3656431 | 19,800 |
def hdf_diff(*args, **kwargs):
""":deprecated: use `diff_blocks` (will be removed in 1.1.1)"""
return diff_blocks(*args, **kwargs) | 3c05a908cc32c2ba4e481ff0de41f78249e2ef02 | 19,801 |
import glob
def determine_epsilon():
"""
We follow Learning Compact Geomtric Features to compute this hyperparameter, which unfortunately we didn't use later.
"""
base_dir = '../dataset/3DMatch/test/*/03_Transformed/*.ply'
files = sorted(glob.glob(base_dir), key=natural_key)
etas = []
for ... | a6af243ebeb37e046e9f23c86080822bff4f490d | 19,802 |
def sort_ipv4_addresses_with_mask(ip_address_iterable):
"""
Sort IPv4 addresses in CIDR notation
| :param iter ip_address_iterable: An iterable container of IPv4 CIDR notated addresses
| :return list : A sorted list of IPv4 CIDR notated addresses
"""
return sorted(
ip_address_iterable,
... | 97517b2518b81cb8ce4cfca19c5512dae6bae686 | 19,803 |
def _subattribute_from_json(data: JsonDict) -> SubAttribute:
"""Make a SubAttribute from JSON data (deserialize)
Args:
data: JSON data received from Tamr server.
"""
cp = deepcopy(data)
d = {}
d["name"] = cp["name"]
d["is_nullable"] = cp["isNullable"]
d["type"] = from_json(cp["t... | 4fde9e1eb456fd42b8ad8e49ad893a62ba01eba4 | 19,804 |
def compare_asts(ast1, ast2):
"""Compare two ast trees. Return True if they are equal."""
# import leo.core.leoGlobals as g
# Compare the two parse trees.
try:
_compare_asts(ast1, ast2)
except AstNotEqual:
dump_ast(ast1, tag='AST BEFORE')
dump_ast(ast2, tag='AST AFTER')
... | 32ab70f1fa31f9ae6cab4e9f5ba91ff71a9e79f8 | 19,805 |
import json
def shit():
"""Ready to go deep into the shit?
Parse --data from -X POST -H 'Content-Type: application/json'
and send it to the space background
"""
try:
body = json.loads(request.data)
except Exception as e:
abort(400, e)
if not body:
abort(4... | bdc435566aeaafac8144775188478cb28724802b | 19,806 |
def clear_settings(site_name): # untested - do I need/want this?
"""update settings to empty dict instead of initialized)
"""
return update_settings(site_name, {}) | a6cbd9bc43ce5bc7159bc75d4cab8c703d73e8cd | 19,807 |
def reorder_jmultis_det_terms(jmulti_output, constant, seasons):
"""
In case of seasonal terms and a trend term we have to reorder them to make
the outputs from JMulTi and sm2 comparable.
JMulTi's ordering is: [constant], [seasonal terms], [trend term] while
in sm2 it is: [constant], [trend term], [... | 91fd48e14addf264f00a6e898af8d934bcd84cca | 19,808 |
def test_require_gdal_version_param_values():
"""Parameter values are allowed for all versions >= 1.0"""
for values in [('bar',), ['bar'], {'bar'}]:
@require_gdal_version('1.0', param='foo', values=values)
def a(foo=None):
return foo
assert a() is None
assert a('bar... | de11d8f6f0720c1b3ef6aa957f8386e8436b1e73 | 19,809 |
def nav_get_element(nav_expr, side, dts, xule_context):
"""Get the element or set of elements on the from or to side of a navigation expression'
This determines the from/to elements of a navigation expression. If the navigation expression includes the from/to component, this will be evaluated.
The resu... | db29b0c2e7832c2b386dd602c77d18a37c2c1307 | 19,810 |
def do_pivot(df: pd.DataFrame, row_name: str, col_name: str, metric_name: str):
"""
Works with df.pivot, except preserves the ordering of the rows and columns
in the pivoted dataframe
"""
original_row_indices = df[row_name].unique()
original_col_indices = df[col_name].unique()
pivoted = df.p... | 70df87eb7d1ca19116ec04854bee635a66f02908 | 19,811 |
def batch_norm_for_fc(inputs, is_training, bn_decay, scope):
""" Batch normalization on FC data.
Args:
inputs: Tensor, 2D BxC input
is_training: boolean tf.Varialbe, true indicates training phase
bn_decay: float or float tensor variable, controling moving average weight
scope: ... | e6a13c50b021785ddcb278c449ba6f9be9271106 | 19,812 |
def stat(file_name):
"""
Read information from a FreeSurfer stats file.
Read information from a FreeSurfer stats file, e.g., `subject/stats/lh.aparc.stats` or `aseg.stats`. A stats file is a text file that contains a data table and various meta data.
Parameters
----------
file_name: string
... | bf64bf488d34a32eebcb66472a3fa567bf5a368d | 19,813 |
def _r_long(int_bytes):
"""Convert 4 bytes in little-endian to an integer.
XXX Temporary until marshal's long function are exposed.
"""
x = int_bytes[0]
x |= int_bytes[1] << 8
x |= int_bytes[2] << 16
x |= int_bytes[3] << 24
return x | 7b40bf05c9d47c7921b1377f0d2235c483e6ba2e | 19,814 |
from typing import Union
from typing import Dict
from typing import Any
from typing import Iterable
from typing import Type
from typing import Optional
import dataclasses
from typing import TypeVar
from typing import cast
def parse_model(data: Union[Dict[str, Any], Iterable[Any], Any],
cls: Union[Type... | 85ba92ac4c3e9df8e96612017b94db73ea53d19e | 19,815 |
def findTopEyelid(imsz, imageiris, irl, icl, rowp, rp, ret_top=None):
"""
Description:
Mask for the top eyelid region.
Input:
imsz - Size of the eye image.
imageiris - Image of the iris region.
irl -
icl -
rowp - y-coordinate of the inner circle centre.
rp - radius of the inner circ... | 9c01e0966a1800ed76f5370cbc382a801af08d67 | 19,816 |
def script_with_queue_path(tmpdir):
"""
Pytest fixture to return a path to a script with main() which takes
a queue and procedure as arguments and adds procedure process ID to queue.
"""
path = tmpdir.join("script_with_queue.py")
path.write(
"""
def main(queue, procedure):
queue.put... | 7c2c2b4c308f91d951496c53c9bdda214f64c776 | 19,817 |
import configparser
def readini(inifile):
""" This function will read in data from a configureation file.
Inputs
inifile- The name of the configuration file.
Outputs
params - A dictionary with keys from INIOPTIONS that holds all of
the plotting parameters.
... | eb5800f00cc8e58557e11fb9ff525e7f407c9eab | 19,818 |
def get_param_store():
"""
Returns the ParamStore
"""
return _PYRO_PARAM_STORE | d71ab10f2029fab735268956590094d8c94dd150 | 19,819 |
def secret_add(secret):
"""
Return a lambda that adds the argument from the lambda to the argument passed into secret_add.
:param secret: secret number to add (integer)
:return: lambda that takes a number and adds it to the secret
"""
return lambda addend: secret + addend | 151f1cff9f0e0bbb43650d63592ba0c2cb05611e | 19,820 |
def morseToBoolArr(code, sps, wpm, fs=None):
""" morse code to boolean array
Args:
code (str): morse code
sps: Samples per second
wpm: Words per minute
fs: Farnsworth speed
Returns:
boolean numpy array
"""
dps = wpmToDps(wpm) # dots per second
baseSampleC... | 90b4225a2a9979ac7f813a1f964b64ef9310ee23 | 19,821 |
import csv
import array
def LaserOptikMirrorTransmission(interpolated_wavelengths,refractive_index = "100", shift_spectrum=7,rescale_factor=0.622222):
"""
Can be used for any wavelengths in the range 400 to 800 (UNITS: nm)
Uses supplied calculation from LaserOptik
Interpolate over selected wavelengths: returns a ... | a3eafd7a788ddcfdedd8e25081f6e7cc1fd03cc5 | 19,822 |
import math
def menu(prompt, titles, cols=1, col_by_col=True, exc_on_cancel=None,
caption=None, default=None):
"""Show a simple menu.
If the input is not allowed the prompt will be shown again. The
input can be cancelled with EOF (``^D``).
The caller has to take care that the menu will fit ... | d4d24cddf40f314c31415685c4eecdc51da2aca2 | 19,823 |
from typing import Dict
from typing import Any
def dict_to_annotation(annotation_dict: Dict[str, Any], ignore_extra_keys = True) -> Annotation:
"""Calls specific Category object constructor based on the structure of the `annotation_dict`.
Args:
annotation_dict (Dict[str, Any]): One of COCO Annotation... | 846c353ab4d15a0558c5cabced30e14a57b5ed64 | 19,824 |
def getAggregation(values):
"""
Produces a dictionary mapping raw states to aggregated states in the form
{raw_state:aggregated_state}
"""
unique_values = list(set(values))
aggregation = {i:unique_values.index(v) for i, v in enumerate(values)}
aggregation['n'] = len(unique_values)
re... | 606bee7c7055b8f2a95bc061dc1883713198b506 | 19,825 |
def create_anonymous_client():
"""Creates an anonymous s3 client. This is useful if you need to read an object created by an anonymous user, which
the normal client won't have access to.
"""
return boto3.client('s3', config=Config(signature_version=UNSIGNED)) | 1c321d2c42b41b19a4fad66e67199f63c2b04338 | 19,826 |
def predictionTopK(pdt, k):
"""预测值中topk
@param pdt 预测结果,nupmy数组格式
@param k 前k个结果
@return topk结果,numpy数组格式
"""
m, n = np.shape(pdt)
ret = []
for i in range(m):
curNums = pdt[i]
tmp = topK(curNums.tolist()[0], k)
ret.append(tmp)
return np.mat(ret) | 57740bb3e2f4521d14273194dc024e8a91347241 | 19,827 |
import argparse
import os
from datetime import datetime
import requests
import json
def extract_url(args: argparse.Namespace) -> dict:
"""Extracts data from products.json endpoint from specified args.
Args:
args (argparse.Namespace): Parsed args.
Returns:
dict: Data logged from extractio... | 42967e5bd89b688585d64982f419a19e341232a5 | 19,828 |
def _devive_from_rsrc_id(app_unique_name):
"""Format devices names.
:returns:
``tuple`` - Pair for device names based on the app_unique_name.
"""
# FIXME(boysson): This kind of manipulation should live elsewhere.
_, uniqueid = app_unique_name.rsplit('-', 1)
veth0 = '{id:>013s}.0'.forma... | 452b1c23f56ae048571f4d8a8567585230ed6c91 | 19,829 |
import io
import os
def fit_noise_1d(npower,lmin=300,lmax=10000,wnoise_annulus=500,bin_annulus=20,lknee_guess=3000,alpha_guess=-4,
lknee_min=0,lknee_max=9000,alpha_min=-5,alpha_max=1,allow_low_wnoise=False):
"""Obtain a white noise + lknee + alpha fit to a 2D noise power spectrum
The white no... | c162f2f77ede793827475cbedaa3ead00420902f | 19,830 |
import re
def parseCsv(file_content):
"""
parseCsv
========
parser a string file from Shimadzu analysis, returning a
dictonary with current, livetime and sample ID
Parameters
----------
file_content : str
shimadzu output csv content
Returns
-------
dic
... | cc20a906c23093994ce53358d92453cd4a9ab459 | 19,831 |
def unpackFITS(h5IN, h5archive, overwrite=True):
# ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
""" Package contents of an h5 block to multi-extention FITS files """
"""
MAJOR BUG: This does not like the ExtendLinked HDF5 files one bit... Only
real blocks. No idea why... | c56b9324df4fcf8d0cf265ed671cdf10ac2bb80d | 19,832 |
def s_from_v(speed, time=None):
"""
Calculate {distance} from {speed}
The chosen scheme: speed at [i] represents the distance from [i] to [i+1].
This means distance.diff() and time.diff() are shifted by one index from
speed. I have chosen to extrapolate the position at the first index by
assuming we st... | 42fa996371af55c97235c2260f1c7c873e7e9e5b | 19,833 |
def fake_categorize_file(tmpdir_factory):
"""Creates a simple categorize for testing."""
file_name = tmpdir_factory.mktemp("data").join("categorize.nc")
root_grp = netCDF4.Dataset(file_name, "w", format="NETCDF4_CLASSIC")
n_points = 7
root_grp.createDimension('time', n_points)
var = root_grp.cre... | 17b8e106f19200291bf2a77805542ecf2bb395fe | 19,834 |
def safe_unsigned_div(a, b, eps=None):
"""Calculates a/b with b >= 0 safely.
a: A `float` or a tensor of shape `[A1, ..., An]`, which is the nominator.
b: A `float` or a tensor of shape `[A1, ..., An]`, which is the denominator.
eps: A small `float`, to be added to the denominator. If left as `None`, it... | 7795976eab37ae664306c91f724aa163472430b3 | 19,835 |
def load_unpack_npz(path):
"""
Simple helper function to circumvent hardcoding of
keyword arguments for NumPy zip loading and saving.
This assumes that the first entry of the zipped array
contains the keys (in-order) for the rest of the array.
Parameters
----------
path : string
P... | ae5d573a480a87d3c09e8de783d9b94558870c15 | 19,836 |
import re
def is_valid_email(email):
"""
Check if a string is a valid email.
Returns a Boolean.
"""
try:
return re.match(EMAIL_RE, email) is not None
except TypeError:
return False | 736b3f141e6f3a99644d51c672738d63d64d604e | 19,837 |
import re
def _create_matcher(utterance):
"""Create a regex that matches the utterance."""
# Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL
# Pattern matches (GROUP|OPTIONAL): Change light to [the color] {name}
parts = re.split(r'({\w+}|\[[\w\s]+\] *)', utterance)
# Pattern to... | ecf126488f827c65379efc58794136499dfa87dd | 19,838 |
import os
import glob
def loadTrainingData(path_to_follow):
"""
It loads the images, assuming that these are in the /IMG/ subfolder.
Also, the output is in the CSV file "steering.csv".
:param path_to_follow: is the full path where the images are placed.
:return: a list with (1) a n... | 2e7b4abec48158fb9aa19f17dc219737a56c46f1 | 19,839 |
def top_compartment_air_CO2(setpoints: Setpoints, states: States, weather: Weather):
"""
Equation 2.13 / 8.13
cap_CO2_Top * top_CO2 = mass_CO2_flux_AirTop - mass_CO2_flux_TopOut
"""
cap_CO2_Top = Coefficients.Construction.greenhouse_height - Coefficients.Construction.air_height # Note: line 46 / se... | 7f294de2f669c2224ccbd09d8200e9b91ddd6ebe | 19,840 |
def coning_sculling(gyro, accel, order=1):
"""Apply coning and sculling corrections to inertial readings.
The algorithm assumes a polynomial model for the angular velocity and the
specific force, fitting coefficients by considering previous time
intervals. The algorithm for a linear approximation is we... | 61f57383488d2d42cb6d63fec5d6d99faa8e2cf2 | 19,841 |
def add():
"""Add a task.
:url: /add/
:returns: job
"""
job = scheduler.add_job(
func=task2,
trigger="interval",
seconds=10,
id="test job 2",
name="test job 2",
replace_existing=True,
)
return "%s added!" % job.name | 88ef667e05a37ec190ba6e01df23fd617821afe0 | 19,842 |
def magnitude(x: float, y: float, z: float) -> float:
""" Magnitude of x, y, z acceleration √(x²+y²+z²)
Dispatch <float>
Args:
x (float): X-axis of acceleration
y (float): Y-axis of acceleration
z (float): Z-axis of acceleration
Returns:
float: Magnitude of acceleratio... | ecb0543b52c385a9b294e87e4b17346b9705f3f8 | 19,843 |
def dauth( bot, input ):
"""Toggle whether channel should be auth enabled by default"""
if not input.admin:
return False
if not input.origin[0] == ID.HON_SC_CHANNEL_MSG:
bot.reply("Run me from channel intended for the default auth!")
else:
cname = bot.id2chan[input.origin[2]]
... | a031e1feb45956503c30ddacd40d59a5f65f30ca | 19,844 |
import json
def write_to_disk(func):
"""
decorator used to write the data into disk during each checkpoint to help us to resume the operation
Args:
func:
Returns:
"""
def wrapper(*args, **kwargs):
func(*args, **kwargs)
with open("checkpoint.json", "r") as f:
... | d3614b7b75adf40021c31263fbbcdfdda025d1a3 | 19,845 |
import shlex
import os
import stat
def _get_partition(device, uuid):
"""Find the partition of a given device."""
LOG.debug("Find the partition %(uuid)s on device %(dev)s",
{'dev': device, 'uuid': uuid})
try:
_rescan_device(device)
lsblk = utils.execute('lsblk', '-PbioKNAME,U... | e0a5fbed8764b8c2c822fd25907368e9e08cecf8 | 19,846 |
def get_hourly_total_exchange_volume_in_period_from_db_trades(tc_db, start_time, end_time):
"""
Get the exchange volume for this exchange in this period from our saved version
of the trade history.
"""
# Watch this query for performance.
results = tc_db.query(
func.hour(EHTrade.time... | 7d46327e8c89d928d7e208d9a00d7b199345e636 | 19,847 |
import typing
def descending(sorting_func: typing.Any) -> typing.Any:
"""
Modify a sorting function to sort in descending order.
:param sorting_func: the original sorting function
:return: the modified sorting function
"""
def modified_sorting_func(current_columns, original_columns, sorting_f... | 30afe7202648950af5d415f3a2da3af5e9ab9d8f | 19,848 |
def circleColor(renderer, x, y, rad, color):
"""Draws an unfilled circle to the renderer with a given color.
If the rendering color has any transparency, blending will be enabled.
Args:
renderer (:obj:`SDL_Renderer`): The renderer to draw on.
x (int): The X coordinate of the center of the ... | 6b3475f918cfb0867799710e5c53e5eea326a2c2 | 19,849 |
def _get_ref_init_error(dpde, error, **kwargs):
"""
Function that identifies where the continuous gyro begins, initiates and
then carries the static errors during the continuous modes.
"""
temp = [0.0]
for coeff, inc in zip(dpde[1:, 2], error.survey.inc_rad[1:]):
if inc > kwargs['header'... | 45f4072139f007f65872223c624581b7433ea2aa | 19,850 |
import re
import os
def get_free_hugepages(socket=None):
"""Get the free hugepage totals on the system.
:param socket: optional socket param to get free hugepages on a socket. To
be passed a string.
:returns: hugepage amount as int
"""
hugepage_free_re = re.compile(r'HugePages_... | 81b37320cf70d61b04509c502dd900d2464719d4 | 19,851 |
import subprocess
def umount(path, bg=False):
"""Umount dfuse from a given path"""
if bg:
cmd = ['fusermount3', '-uz', path]
else:
cmd = ['fusermount3', '-u', path]
ret = subprocess.run(cmd, check=False)
print('rc from umount {}'.format(ret.returncode))
return ret.returncode | 1b21cb10c5bf1a4829ea001218ac2fee80e1aa40 | 19,852 |
def parse_internal_ballot(line):
"""
Parse an internal ballot line (with or without a trailing newline).
This function allows leading and trailing spaces. ValueError is
raised if one of the values does not parse to an integer.
An internal ballot line is a space-delimited string of integers of the... | 9433a496f26dd3511ff343686402e941a617f775 | 19,853 |
def get_fratio(*args):
"""
"""
cmtr = get_cmtr(*args)
cme = get_cme(*args)
fratio = cmtr / cme
return fratio | 2a93d1211929346fc333837b711ed0eb01f34b2b | 19,854 |
def _select_by_property(peak_properties, pmin, pmax):
"""
Evaluate where the generic property of peaks confirms to an interval.
Parameters
----------
peak_properties : ndarray
An array with properties for each peak.
pmin : None or number or ndarray
Lower interval boundary for `p... | 12fda9525334d8a2a50e1a4785587dbbb0a70f00 | 19,855 |
def from_period_type_name(period_type_name: str) -> PeriodType:
"""
Safely get Period Type from its name.
:param period_type_name: Name of the period type.
:return: Period type enum.
"""
period_type_values = [item.value for item in PeriodType]
if period_type_name.lower() not in period_type_... | 97feb3bd1f18c1752ba4510628411f23ea77acb1 | 19,856 |
import random
import string
def randomInt(length=4, seed=None):
"""
Returns random integer value with provided number of digits
>>> random.seed(0)
>>> randomInt(6)
874254
"""
if seed is not None:
_ = getCurrentThreadData().random
_.seed(seed)
choice = _.choice
... | 3d37b6410337271c6798cb1b3542189fcdd04226 | 19,857 |
import re
def matchatleastone(text, regexes):
"""Returns a list of strings that match at least one of the regexes."""
finalregex = "|".join(regexes)
result = re.findall(finalregex, text)
return result | 1e0775413189931fc48a3dc82c23f0ffe28b333e | 19,858 |
def safe_string_equals(a, b):
""" Near-constant time string comparison.
Used in order to avoid timing attacks on sensitive information such
as secret keys during request verification (`rootLabs`_).
.. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/
"""
if le... | 6253b747061dfdc82a533b103009f0ab469a76ef | 19,859 |
def DFS_complete(g):
"""Perform DFS for entire graph and return forest as a dictionary.
forest maps each vertex v to the edge that was used to discover it.
(Vertices that are roots of a DFS tree are mapped to None.)
:param g: a Graph class object
:type g: Graph
:return: A tuple of dicts summar... | 7cf500d204b70cbcb9cedf33dda42cb2b717e162 | 19,860 |
def get_keys(mapping, *keys):
"""Return the values corresponding to the given keys, in order."""
return (mapping[k] for k in keys) | e3b8bdbdff47c428e4618bd4ca03c7179b9f4a2b | 19,861 |
def accents_dewinize(text):
"""Replace Win1252 symbols with ASCII chars or sequences
needed when copying code parts from MS Office, like Word...
From the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015)
>>> accents_dewinize('“Stupid word • error inside™ ”')
'"Stupid word - error inside(TM) ... | d34a4cd694b4d713ac7b207680e26d7c79f2b957 | 19,862 |
def spiral_trajectory(base_resolution,
spiral_arms,
field_of_view,
max_grad_ampl,
min_rise_time,
dwell_time,
views=1,
phases=None,
ordering='lin... | b7acf7a14835e63e1f2524a5ac7dd67d16a4eba7 | 19,863 |
def total_examples(X):
"""Counts the total number of examples of a sharded and sliced data object X."""
count = 0
for i in range(len(X)):
for j in range(len(X[i])):
count += len(X[i][j])
return count | faf42a940e4413405d97610858e13496eb848eae | 19,864 |
def convert_and_save(model,
input_shape,
weights=True,
quiet=True,
ignore_tests=False,
input_range=None,
filename=None,
directory=None):
"""
Conversion between PyTor... | 00305f6d9a163b61a963e04e810a8d3808403d23 | 19,865 |
def no_afni():
""" Checks if AFNI is available """
if Info.version() is None:
return True
return False | fc10292bc69ca5996a76227c3bbbd5855eb2520e | 19,866 |
def delta_eta_plot_projection_range_string(inclusive_analysis: "correlations.Correlations") -> str:
""" Provides a string that describes the delta phi projection range for delta eta plots. """
# The limit is almost certainly a multiple of pi, so we try to express it more naturally
# as a value like pi/2 or ... | 3b36d65a3223ca2989ad9607fc2b15b298b1c709 | 19,867 |
import subprocess
def select_gpu(gpu_ids=None, gpu_mem_frac=None):
"""
Find the GPU ID with highest available memory fraction.
If ID is given as input, set the gpu_mem_frac to maximum available,
or if a memory fraction is given, make sure the given GPU has the desired
memory fraction available.
... | cc903bc4adbf63108ce473efdde50d68dd622c6e | 19,868 |
import torch
import random
def load_classification_dataset(
fname,
tokenizer,
input_field_a,
input_field_b=None,
label_field='label',
label_map=None,
limit=None
):
"""
Loads a dataset for classification
Parameters
==========
tokenizer : transformers.PretrainedTokenizer... | 6099426c0a9f5246400e8878715335e0804ee90a | 19,869 |
import os
import lzma
import dill
def test_mnist(args):
""" Calculates error rate on MNIST for a previously saved MulticlassClassifier instance.
Parameters
----------
args : argparse.Namespace
Arguments from command line.
Returns
-------
error_rate : float
The calculated ... | c40cd781c6baefbdf7fd3d524badc10df0e73985 | 19,870 |
def has_content_in(page, language):
"""Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at
"""
if page is None:
return False
return Content.objects.filter(page=page, languag... | 6207583ad110aa098b5f556ad7a13b1b5218a1d3 | 19,871 |
def public_encrypt(key, data, oaep):
"""
public key encryption using rsa with pkcs1-oaep padding.
returns the base64-encoded encrypted data
data: the data to be encrypted, bytes
key: pem-formatted key string or bytes
oaep: whether to use oaep padding or not
"""
if isinstance(key, str):
key = key.en... | 7310a0d408deff30efad2c961518261187a89dbf | 19,872 |
def newton_method(f, x_init = 0, epsilon = 1e-10):
"""
Newton Raphson Optimizer
...
Parameters
---
f: Function to calculate root for
x_init(optional) : initial value of x
epsilon(optional): Adjustable precision
Returns
---
x: Value of root
"""
prev_value = x_init +... | 5801d5f908e30551c321eaf0ec8dfbf42869e005 | 19,873 |
def create_preference_branch(this, args, callee):
"""Creates a preference branch, which can be used for testing composed
preference names."""
if args:
if args[0].is_literal:
res = this.traverser.wrap().query_interface('nsIPrefBranch')
res.hooks['preference_branch'] = args[0]... | 6e6cc013b9d6c645a6a94087fe63b3a186582003 | 19,874 |
def circle(
gdf,
radius=10,
fill=True,
fill_color=None,
name="layer",
width=950,
height=550,
location=None,
color="blue",
tooltip=None,
zoom=7,
tiles="OpenStreetMap",
attr=None,
style={},
):
"""
Convert Geodataframe to geojson and plot it.
Parameters
... | d2f2e066c2f6988f950ffce6a7655b60c91c3cec | 19,875 |
import traceback
def no_recurse(f):
"""Wrapper function that forces a function to return True if it recurse."""
def func(*args, **kwargs):
for i in traceback.extract_stack():
if i[2] == f.__name__:
return True
return f(*args, **kwargs)
return func | cce02b5e8fff125040e457c66c7cc9c344e209cb | 19,876 |
from typing import List
import pandas
from typing import Tuple
def get_tap_number(distSys: SystemClass, names: List[str]) -> pandas.DataFrame:
"""
Get the tap number of regulators.
Args:
distSys : An instance of [SystemClass][dssdata.SystemClass].
names : Regulators names
Returns:
... | a780b151670f261656d938ec48a5ac684c8c9d6d | 19,877 |
def status(app: str) -> dict:
"""
:param app: The name of the Heroku app in which you want to change
:type app: str
:return: dictionary containing information about the app's status
"""
return Herokron(app).status() | f5251469c8388edf885ac9e4ae502549f0092703 | 19,878 |
def GetIPv4Interfaces():
"""Returns a list of IPv4 interfaces."""
interfaces = sorted(netifaces.interfaces())
return [x for x in interfaces if not x.startswith('lo')] | 01fc53160b01e3322af8d18175fde0011d87d127 | 19,879 |
def merge_dicts(source, destination):
"""
Recursively merges two dictionaries source and destination.
The source dictionary will only be read, but the destination dictionary will be overwritten.
"""
for key, value in source.items():
if isinstance(value, dict):
# get node or creat... | dea2d01f2cdf42c38daee8589abcc69a3f82e5c8 | 19,880 |
def create_hive_connection():
"""
Create a connection for Hive
:param username: str
:param password: str
:return: jaydebeapi.connect or None
"""
try:
conn = jaydebeapi.connect('org.apache.hive.jdbc.HiveDriver',
hive_jdbc_url,
... | 48ac2859c9ceec9129d377f722ff96786a1c9552 | 19,881 |
def main():
"""
The main function to execute upon call.
Returns
-------
int
returns integer 0 for safe executions.
"""
print('Hello World')
return 0 | 077df89bc009a12889afc6567bfd97abdb173411 | 19,882 |
def brightness(image, magnitude, name=None):
"""Adjusts the `magnitude` of brightness of an `image`.
Args:
image: An int or float tensor of shape `[height, width, num_channels]`.
magnitude: A 0-D float tensor or single floating point value above 0.0.
name: An optional string for name of... | 52e3016dce51bd5435e2c4085aa0a4d50b9c3502 | 19,883 |
def sitemap_xml():
"""Sitemap XML"""
sitemap = render_template("core/sitemap.xml")
return Response(sitemap, mimetype="text/xml") | 12d954b7f3c88f10e694e0aa1998699322a5602b | 19,884 |
def get_CM():
"""Pertzの係数CMをndarrayとして取得する
Args:
Returns:
CM(ndarray[float]):Pertzの係数CM
"""
# pythonは0オリジンのため全て-1
CM = [0.385230, 0.385230, 0.385230, 0.462880, 0.317440,#1_1 => 0_0
0.338390, 0.338390, 0.221270, 0.316730, 0.503650,
0.235680, 0.235680, 0.24128... | 434bab68e2aa434a79a53dd91a4932e631a6367c | 19,885 |
def remove_sleepEDF(mne_raw, CHANNELS):
"""Extracts CHANNELS channels from MNE_RAW data.
Args:
raw - mne data strucutre of n number of recordings and t seconds each
CHANNELS - channels wished to be extracted
Returns:
extracted - mne data structure with only specified channels
"""
extra... | 7bb04810676a127742d391c518fc505bf7568aac | 19,886 |
from datetime import datetime
import pytz
def save_email_schedule(request, action, schedule_item, op_payload):
"""
Function to handle the creation and edition of email items
:param request: Http request being processed
:param action: Action item related to the schedule
:param schedule_item: Schedu... | 3a14e11a195bcf96ac132d2876e61ce52f0b8ccd | 19,887 |
def slice(
_data: DataFrame,
*rows: NumericOrIter,
_preserve: bool = False,
base0_: bool = None,
) -> DataFrame:
"""Index rows by their (integer) locations
Original APIs https://dplyr.tidyverse.org/reference/slice.html
Args:
_data: The dataframe
rows: The indexes
... | a58d2ae140d1e441100f7f71587588b93ecaa7b4 | 19,888 |
def get_random_color():
"""
Get random color
:return: np.array([r,g,b])
"""
global _start_color, _color_step
# rgb = np.random.uniform(0, 25, [3])
# rgb = np.asarray(np.floor(rgb) / 24 * 255, np.uint8)
_start_color = (_start_color + _color_step) % np.array([256, 256, 256])
rgb = np.a... | 3c9596f264e75c064f76a56d71e06dbe55669936 | 19,889 |
def get_client_ip(request):
"""
Simple function to return IP address of client
:param request:
:return:
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0] # pylint: disable=invalid-name
else:
ip = reque... | 976755d296127a42de5b6d7c39bfc9a607b273ee | 19,890 |
def entropy(wair,temp,pres,airf=None,dhum=None,dliq=None,chkvals=False,
chktol=_CHKTOL,airf0=None,dhum0=None,dliq0=None,chkbnd=False,
mathargs=None):
"""Calculate wet air entropy.
Calculate the specific entropy of wet air.
:arg float wair: Total dry air fraction in kg/kg.
:arg float te... | 4cd0b53bdf549a0f53d2543e693f6b179a0f0915 | 19,891 |
def get_list_item(view, index):
"""
get item from listView by index
version 1
:param view:
:param index:
:return:
"""
return var_cache['proxy'].get_list_item(view, index) | bcb1db741a87bc2c12686ade8e692449030eb9cf | 19,892 |
def interquartile_range_checker(train_user: list) -> float:
"""
Optional method: interquatile range
input : list of total user in float
output : low limit of input in float
this method can be used to check whether some data is outlier or not
>>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10]... | 29eba79cef5c91e491250780ed3fb7ca74d7cace | 19,893 |
def make_linear_colorscale(colors):
"""
Makes a list of colors into a colorscale-acceptable form
For documentation regarding to the form of the output, see
https://plot.ly/python/reference/#mesh3d-colorscale
"""
scale = 1.0 / (len(colors) - 1)
return [[i * scale, color] for i, color in enum... | dabd2a2a9d6bbf3acfcabcac52246048332fae73 | 19,894 |
def background(image_size: int, level: float=0, grad_i: float=0, grad_d: float=0) -> np.array:
"""
Return array representing image background of size `image_size`.
The image may have an illimination gradient of intensity `I` and direction `grad_d`.
The `image_size` is in pixels. `grad_i` expected to be ... | 7fc6d34ec02752604024746e707f70a82ad61450 | 19,895 |
def mapTypeCategoriesToSubnetName(nodetypecategory, acceptedtypecategory):
"""This function returns a name of the subnet that accepts nodetypecategory
as child type and can be created in a container whose child type is
acceptedtypecategory.
Returns None if these two categories are the same (i... | c9a31c571807cd2592340ce685b1f130f99da156 | 19,896 |
def sorted_unique(series):
"""Return the unique values of *series*, correctly sorted."""
# This handles Categorical data types, which sorted(series.unique()) fails
# on. series.drop_duplicates() is slower than Series(series.unique()).
return list(pd.Series(series.unique()).sort_values()) | 3da88962171acd15f3af020ff056afb66d284425 | 19,897 |
import json
def create_query_from_request(p, request):
"""
Create JSON object representing the query from request received from Dashboard.
:param request:
:return:
"""
query_json = {'process_type': DVAPQL.QUERY}
count = request.POST.get('count')
generate_tags = request.POST.get('genera... | 4936376d6d900ca20d2ea9339634d0a7d90ebc2e | 19,898 |
from typing import List
from typing import Any
def create_cxr_transforms_from_config(config: CfgNode,
apply_augmentations: bool) -> ImageTransformationPipeline:
"""
Defines the image transformations pipeline used in Chest-Xray datasets. Can be used for other types of
... | 9d16e844291a69d4b82681c4cdcc48f5a1b3d67f | 19,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.