content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fuzzy_lookup_item(name_or_id, lst):
"""Lookup an item by either name or id.
Looking up by id is exact match. Looking up by name is by containment, and
if the term is entirely lowercase then it's also case-insensitive.
Multiple matches will throw an exception, unless one of them was an exact
mat... | 5,352,800 |
def _make_output_dirs(root_output_dir, experiment_name):
"""Get directories for outputs. Create if not exist."""
tf.io.gfile.makedirs(root_output_dir)
checkpoint_dir = os.path.join(root_output_dir, 'checkpoints', experiment_name)
tf.io.gfile.makedirs(checkpoint_dir)
results_dir = os.path.join(root_output_di... | 5,352,801 |
def fantasy_pros_ecr_scrape(league_dict=config.sean):
"""Scrape Fantasy Pros ECR given a league scoring format
:param league_dict: league dict in config.py used to determine whether to pull PPR/standard/half-ppr
"""
scoring = league_dict.get('scoring')
if scoring == 'ppr':
url = 'https:... | 5,352,802 |
def lda(X, y, nr_components=2):
"""
Linear discrimindant analysis
:param X: Input vectors
:param y: Input classes
:param nr_components: Dimension of output co-ordinates
:return: Output co-ordinates
"""
print("Computing Linear Discriminant Analysis projection")
X2 = X.copy()
X2.fl... | 5,352,803 |
def _flatten_value_to_list(batch_values):
"""Converts an N-D dense or sparse batch to a 1-D list."""
# Ravel for flattening and tolist so that we go to native Python types
# for more efficient followup processing.
#
batch_value, = batch_values
return batch_value.ravel().tolist() | 5,352,804 |
async def test_option_flow_input_floor(hass):
"""Test config flow options."""
entry = MockConfigEntry(domain=DOMAIN, data={}, options=None)
entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] == "form"
assert result["step_id"] == ... | 5,352,805 |
def sun_position(time):
"""
Computes the sun's position in longitude and colatitude at a given time
(mjd2000).
It is accurate for years 1901 through 2099, to within 0.006 deg.
Input shape is preserved.
Parameters
----------
time : ndarray, shape (...)
Time given as modified Jul... | 5,352,806 |
def verify_shape_batch_pair(orig_sample: Tuple[torch.Tensor, torch.Tensor],
new_sample: Tuple[torch.Tensor, torch.Tensor], p_row: float, p_col: float) -> None:
"""Verify the shape of a transformed batch of images."""
N, C, H_o, W_o = orig_sample[0].shape
H_t = int((1 - p_row) *... | 5,352,807 |
def register_config(app):
"""配置文件"""
"""
暂时兼容旧注册配置文件,后续废除。
"""
# 旧注册配置文件
# app.config.from_object(config_obj[app_conf()]) # 环境配置
# config_obj[app_conf()].init_app(app)
# 新注册配置文件
app.config.from_object(config_obj['config']) # 环境配置
app.logger.info(str(config_obj['config']))
... | 5,352,808 |
def get_assay_description(assay_id, summary=True, attempts=10):
""" Get the description of an assay in JSON format.
Parameters
----------
assay_id : int
The id of the bioassay.
summary : bool, optional
If true returns a summary of the description of ... | 5,352,809 |
def acos(expr):
"""
Arc cosine -- output in radians.
It is the same that :code:`arccos` moodle math function.
"""
return Expression('acos({0})'.format(str(expr))) | 5,352,810 |
def validate_api_declaration(api_declaration):
"""Validate an API Declaration (§5.2).
:param api_declaration: a dictionary respresentation of an API Declaration.
:returns: `None` in case of success, otherwise raises an exception.
:raises: :py:class:`swagger_spec_validator.SwaggerValidationError`
... | 5,352,811 |
def node_compat_sdk2203():
"""Replace old arm_logic_id system with tree variable system."""
for tree in bpy.data.node_groups:
if tree.bl_idname == 'ArmLogicTreeType':
# All tree variable nodes
tv_nodes: dict[str, list[arm.logicnode.arm_nodes.ArmLogicVariableNodeMixin]] = {}
... | 5,352,812 |
def visualize_ranked_results(distmat, dataset, save_dir='log/ranked_results', topk=20):
"""
Visualize ranked results
Support both imgreid and vidreid
Args:
- distmat: distance matrix of shape (num_query, num_gallery).
- dataset: a 2-tuple containing (query, gallery), each contains a list of (i... | 5,352,813 |
def test_scope_works(tmpdir):
"""
scripts which define variables in the global scope should
have access to them.
"""
SCRIPT = """
import os
from surgen import Procedure
class Scope(Procedure):
def operate(self):
print(os.path)
return __file__
""".strip()
cls = from_st... | 5,352,814 |
def annotate_genes(gene_df, annotation_gtf, lookup_df=None):
"""
Add gene and variant annotations (e.g., gene_name, rs_id, etc.) to gene-level output
gene_df: output from map_cis()
annotation_gtf: gene annotation in GTF format
lookup_df: DataFrame with variant annotations, indexed by 'v... | 5,352,815 |
def y_gate():
"""
Pauli y
"""
return torch.tensor([[0, -1j], [1j, 0]]) + 0j | 5,352,816 |
def extract_tarball(tarball, install_dir):
"""Extract tarball to a local path"""
if not tarball.path.is_file():
raise IOError(f"<info>{tarball.path}</info> is not a file!")
try:
with tarfile.open(tarball.path, "r:gz") as f_tarball:
extraction_dir = [
obj.name
... | 5,352,817 |
def compose_matrix(scale=None, shear=None, angles=None, translation=None, perspective=None):
"""Calculates a matrix from the components of scale, shear, euler_angles, translation and perspective.
Parameters
----------
scale : [float, float, float]
The 3 scale factors in x-, y-, and z-direction.... | 5,352,818 |
def start(event):
"""move to the start"""
global timestep
timestep = 0
plot_figure(varnames, var, timestep, False)
slider.set_val(var.time[timestep]) | 5,352,819 |
def validate_get_build_request(req):
"""Validates rpc_pb2.GetBuildRequest."""
if req.id:
if req.HasField('builder') or req.build_number:
_err('id is mutually exclusive with builder and build_number')
elif req.HasField('builder') and req.build_number:
validate_builder_id(req.builder)
else:
_err... | 5,352,820 |
def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items())) | 5,352,821 |
def EucDistIntegral(a, b, x):
"""[summary]
Calculate Integrated Euclidean distance.
Args:
a (float): a value
b (float): b value
x (float): x value
Returns:
val: Integration result
"""
asq = a * a
bsq = b * b
xsq = x * x
dn = (6 * (1 + asq)**(3 ... | 5,352,822 |
def _VarintSize(value):
"""Compute the size of a varint value."""
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value ... | 5,352,823 |
def play_again():
"""Re-Start Game.
Question if want to play again or not.
"""
again = input("Would you like to play again? (y/n)").lower()
if again == "y":
typing_game("\n\n\nExcellent! Restarting the game ...\n\n\n")
play_the_game()
elif again == "n":
typing_ga... | 5,352,824 |
def convert_addmm(g, op, block):
"""Operator converter for addmm."""
input_x = g.get_node(op.input("Input")[0])
x = g.get_node(op.input("X")[0])
y = g.get_node(op.input("Y")[0])
alpha = op.attr("Alpha")
beta = op.attr("Beta")
dtype = block.var(op.output("Out")[0]).dtype
dtype = str(dty... | 5,352,825 |
def store_trajectory_plot(graph, fname):
""" Store the resulting plot.
"""
create_controller_output_dir(CONTROLLER_OUTPUT_FOLDER)
file_name = os.path.join(CONTROLLER_OUTPUT_FOLDER, fname)
graph.savefig(file_name) | 5,352,826 |
def send_to_hipchat(
message,
token=settings.HIPCHAT_API_TOKEN,
room=settings.HIPCHAT_ROOM_ID,
sender="Trello",
color="yellow",
notify=False): # noqa
"""
Send a message to HipChat.
Returns the status code of the request. Should be 200.
"""
payload = {
'auth_token': ... | 5,352,827 |
def input(*requireds, **defaults):
"""
Returns a `storage` object with the GET and POST arguments.
See `storify` for how `requireds` and `defaults` work.
"""
from cStringIO import StringIO
def dictify(fs): return dict([(k, fs[k]) for k in fs.keys()])
_method = defaults.pop('_method', '... | 5,352,828 |
def systemctl_master(command='restart'):
""" Used to start, stop or restart the master process
"""
run_command_on_master('sudo systemctl {} dcos-mesos-master'.format(command)) | 5,352,829 |
def nodes_and_edges_valid(dev, num_nodes, node_names, rep):
"""Asserts that nodes in a device ``dev`` are properly initialized, when there
are ``num_nodes`` nodes expected, with names ``node_names``, using representation ``rep``."""
if not set(dev._nodes.keys()) == {"state"}:
return False
if not... | 5,352,830 |
def is_android(builder_cfg):
"""Determine whether the given builder is an Android builder."""
return ('Android' in builder_cfg.get('extra_config', '') or
builder_cfg.get('os') == 'Android') | 5,352,831 |
def twoSum(self, numbers, target): # ! 这个方法可行
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
numbers_dict = {}
for idn, v in enumerate(numbers):
if target - v in numbers_dict:
return [numbers_dict[target - v] + 1, idn + 1]
numbers_... | 5,352,832 |
def test_get_bound_pressure_height(pressure, bound, hgts, interp, expected):
"""Test getting bounds in layers with various parameter combinations."""
bounds = _get_bound_pressure_height(pressure, bound, heights=hgts, interpolate=interp)
assert_array_almost_equal(bounds[0], expected[0], 5)
assert_array_a... | 5,352,833 |
def not_after(cert):
"""
Gets the naive datetime of the certificates 'not_after' field.
This field denotes the last date in time which the given certificate
is valid.
:return: Datetime
"""
return cert.not_valid_after | 5,352,834 |
def checkout():
"""fetch from home directory on server"""
local('unison {source} {dest} -force {source} {uflags}'.format(
source = REMOTE + REPO,
dest = ROOT_PATH,
uflags = UFLAGS),
capture = False) | 5,352,835 |
def parse_time_string(time_str: str) -> datetime.time:
"""Parses a string recognizable by TIME_REGEXP into a datetime.time object. If
the string has an invalid format, a ValueError is raised."""
match = TIME_REGEXP.match(time_str)
if match is None:
raise ValueError("time string {} has an invali... | 5,352,836 |
def dig(start, outdir, depth=2, max_duration=360):
"""
Crawls YouTube for source material (as mp3s).
Args:
- start: the starting YouTube url
- outdir: directory to save download tracks to
- depth: how many levels of related vids to look through
- max_duration: only dl videos... | 5,352,837 |
def get_roc_curve(y_true, y_score, title=None, with_plot=True):
"""
Plot the [Receiver Operating Characteristic][roc] curve of the given
true labels and confidence scores.
[roc]: http://en.wikipedia.org/wiki/Receiver_operating_characteristic
"""
fpr, tpr, thresholds = sklearn.metrics.roc_curve(... | 5,352,838 |
def read_err_songs():
""" read song data from xml file to a list of dictionaries """
songfile = open('/home/gabe/python/selfishmusic/errors.xml')
soup = BS.BeautifulSoup(songfile.read())
songsxml = soup.findAll('song')
songs = []
for song in songsxml:
sd = {}
sd['songnum'] = int(... | 5,352,839 |
def test_dummy_user_service_current_user():
"""
Tests that get_current_user() works on a dummy user service.
"""
user = XBlockUser(full_name="tester")
user_service = SingleUserService(user)
current_user = user_service.get_current_user()
assert current_user == user
assert current_user.ful... | 5,352,840 |
def p_useStmt(t):
"""useStmt : R_USE ID"""
t[0] = instruction.useDataBase(t[2], t.slice[1].lineno, t.slice[1].lexpos)
repGrammar.append(t.slice) | 5,352,841 |
def word_value(word: str) -> int:
"""Returns the sum of the alphabetical positions of each letter in word."""
return (0 if word == '' else
word_value(word[:-1]) + alpha.letter_index_upper(word[-1])) | 5,352,842 |
def show_ads(args, api=None):
"""
Print list of all ads
"""
if not api:
api = kijiji_api.KijijiApi()
api.login(args.ssid)
all_ads = sorted(api.get_all_ads(),
key=lambda k: k[args.sort_key], reverse=args.sort_reverse)
print(" id ", "page", "views", " ... | 5,352,843 |
def test_ec_number_retrieval(df_series, null_logger):
"""Test 'get_ec_numbers'."""
get_uniprot_proteins.get_ec_numbers(df_series, null_logger) | 5,352,844 |
def status():
"""
Returns json response of api status
Returns:
JSON: json object
"""
status = {
"status": "OK"
}
return jsonify(status) | 5,352,845 |
def celcius_to_farenheit(x):
"""calculate celcius to farenheit"""
farenheit = (9*x/5) + 32
return farenheit | 5,352,846 |
def CheckFlags(node_name, report_per_node, warnings, errors,
flags, warning_helper, error_helper):
"""Check the status flags in each node and bookkeep the results.
Args:
node_name: Short name of the node.
report_per_node: Structure to record warning/error messages per node.
Its type ... | 5,352,847 |
def EnrollmentTransaction():
"""
:return:
"""
return b'\x20' | 5,352,848 |
def nonCommonWords(words):
"""
Calculate seven most frequent that arnt common
"""
print("\nSeven most frequent words, that arn't common")
with open("common-words.txt") as dFile:
res = list()
lst = dFile.readlines()
# lst = [re.sub('[^a-zA-Z]+', '', x) for x in lst]
ls... | 5,352,849 |
def map_inheritance_and_composition(list_of_include_groups, use_old_discovery_mode):
"""
This function maps the relationships between the files which are related and fills the global
"includes" and "inheritance" lists with tuples of the form: (includer, included).
This function also populates the "class... | 5,352,850 |
def sentinel_id(vocabulary, return_value=None):
"""Token ID to use as a sentinel.
By default, we use the last token in the vocabulary.
Args:
vocabulary: a t5.data.vocabularies.Vocabulary
return_value: an optional integer
Returns:
an integer
"""
if return_value is not None:
return return_va... | 5,352,851 |
def goodFits(bestfitloc='posteriorpdf.fits', Nfits=12, Ngood=5000,
cleanup=True, interactive=True, showOptical=False, threshold=1.2):
"""
Read posterior PDF and draw Nfits realizations from the final Ngood models
at random. Plot the model from each realization and compare to the data.
Also pl... | 5,352,852 |
def create_loompy_raw_counting(hybridizations_infos,converted_positions,
hybridization,flt_rawcnt_config,hyb_dir,
processing_hyb,counting_gene_dirs):
"""
Function used to write the counting results in a loom file
Parameters:
-----------
hybridiza... | 5,352,853 |
def create_signature(api_key, method, host, path, secret_key, get_params=None):
"""
创建签名
:param get_params: dict 使用GET方法时附带的额外参数(urlparams)
:return:
"""
sorted_params = [
("AccessKeyId", api_key),
("SignatureMethod", "HmacSHA256"),
("SignatureVersion", "2"),
("Tim... | 5,352,854 |
def test_pi():
"""Check that PI has expected value on systemcd """
import math
assert math.pi == 3.141592653589793 | 5,352,855 |
def measure_fwhm(image, plot=True, printout=True):
"""
Find the 2D FWHM of a background/continuum subtracted cutout image of a target.
The target should be centered and cropped in the cutout.
Use lcbg.utils.cutout for cropping targets.
FWHM is estimated using the sigmas from a 2D gaussian fit of the... | 5,352,856 |
def classFactory(iface): # pylint: disable=invalid-name
"""Load MappiaPublisher class from file MappiaPublisher.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
from .mappia_publisher import MappiaPublisherPlugin
return MappiaPublisherPlugin() | 5,352,857 |
def mongo_insert_canary(mongo, db_name, coll_name, doc):
""" Inserts a canary document with 'j' True. Returns 0 if successful. """
LOGGER.info("Inserting canary document %s to DB %s Collection %s", doc, db_name, coll_name)
coll = mongo[db_name][coll_name].with_options(
write_concern=pymongo.write_co... | 5,352,858 |
def is_dict_specifier(value):
# type: (object) -> bool
""" Check if value is a supported dictionary.
Check if a parameter of the task decorator is a dictionary that specifies
at least Type (and therefore can include things like Prefix, see binary
decorator test for some examples).
:param value:... | 5,352,859 |
def logging(nb_buckets, hidden_sizes, denoising_rate):
"""
Print on console some information
"""
print("_"*30)
print("")
print('{:^30}'.format(" KFOLD %s"%nb_buckets))
print("_"*30)
print("{:^30}".format("Hidden_sizes: %s"%hidden_sizes))
print("{:^30}".format("Denoising rate: %s"%de... | 5,352,860 |
def rm_path():
"""
Remove input directory options.input_path
:return: void
"""
shutil.rmtree(options.input_path) | 5,352,861 |
def parse_star_count(stars_str):
"""Parse strings like 40.3k and get the no. of stars as a number"""
stars_str = stars_str.strip()
return int(float(stars_str[:-1]) * 1000) if stars_str[-1] == 'k' else int(stars_str) | 5,352,862 |
def test_auto_loss_scaling_clip_final_loss_scale(w_dtype, loss_dtype_str,
loss_scaling):
"""Test whether the final loss scale is correctly clipped at 2^15, when the
weights are in fp16 or the loss (and final loss scale) are in fp16. Also
check whether the u... | 5,352,863 |
def test_propery_address_create_from_string():
"""
Property address should be able to create from a string
"""
address_full = Address.create_from_string(
'City, test street, Test region, Country')
address_short = Address.create_from_string('City, Country')
address_country = Address.creat... | 5,352,864 |
def execute_reactivation_event(prng, cells):
"""
Randomly choose between reactivating a random quiescent cell
(i.e. make it a cycling cell) versus leaving it alone.
This function modifies the list of cells in place.
"""
Q_cells = [cell for cell in cells if cell.cell_cycle_state == 'quiescent']... | 5,352,865 |
def is_libreoffice_sdk_available() -> bool:
""" do we have idlc somewhere (we suppose it is made available in current path var.) ? """
return shutil.which("idlc") is not None | 5,352,866 |
def set_metrics_file(filenames, metric_type):
"""Create metrics from data read from a file.
Args:
filenames (list of str):
Paths to files containing one json string per line (potentially base64
encoded)
metric_type (ts_mon.Metric): any class deriving from ts_mon.Metric.
For ex. ts_mon.Gau... | 5,352,867 |
def sortino_ratio_nb(returns, ann_factor, required_return_arr):
"""2-dim version of `sortino_ratio_1d_nb`.
`required_return_arr` should be an array of shape `returns.shape[1]`."""
result = np.empty(returns.shape[1], dtype=np.float_)
for col in range(returns.shape[1]):
result[col] = sortino_rati... | 5,352,868 |
def format_env_var(name: str, value: str) -> str:
"""
Formats environment variable value.
Formatter is chosen according to the kind of variable.
:param name: name of environment variable
:param value: value of environment variable
:return: string representation of value in appropriate format
... | 5,352,869 |
def update_item(namespace, item_def):
"""
Update item to namespace
"""
db, namespace_name = namespace
log_operation.info(f"Update item: {item_def} to namespace {namespace_name}")
db.item_upsert(namespace_name, item_def) | 5,352,870 |
def evenly_divisible(n):
""" Idea:
- Find factors of numbers 1 to n. Use DP to cache results bottom up.
- Amongst all factors, we have to include max counts of prime factors.
- For example, in in 1 .. 10, 2 has to be included 3 times since 8 = 2 ^ 3
"""
max_counts = Counter()
for n in ra... | 5,352,871 |
def test_adafactor_compile2():
""" test adafactor compile """
inputs = Tensor(np.ones([1, 64]).astype(np.float32))
label = Tensor(np.zeros([1, 10]).astype(np.float32))
net = Net()
net.set_train()
loss = nn.SoftmaxCrossEntropyWithLogits()
optimizer = AdaFactor(net.trainable_params(), learnin... | 5,352,872 |
def gradients(vals, func, releps=1e-3, abseps=None, mineps=1e-9, reltol=1,
epsscale=0.5):
"""
Calculate the partial derivatives of a function at a set of values. The
derivatives are calculated using the central difference, using an iterative
method to check that the values converge as step... | 5,352,873 |
def do_open(user_input):
"""identical to io.open in PY3"""
try:
with open(user_input) as f:
return f.read()
except Exception:
return None | 5,352,874 |
def likely_solution(players):
""" Return tuples of cards with the
number of players who don't have them
"""
likely = likely_solution_nums(players)
return sorted([(ALLCARDS[n], ct) for n, ct in likely],
key=lambda tp: tp[1], reverse=True) | 5,352,875 |
def cns_extended_inp(mtf_infile, pdb_outfile):
"""
Create CNS iput script (.inp) to create extended PDB file
from molecular topology file (.mtf)
Parameters
----------
mtf_infile : str
Path to .mtf topology file
pdb_outfile : str
Path where extended .pdb file will be stored
... | 5,352,876 |
def index(request, response_format='html'):
"""Sales index page"""
query = Q(status__hidden=False)
if request.GET:
if 'status' in request.GET and request.GET['status']:
query = _get_filter_query(request.GET)
else:
query = query & _get_filter_query(request.GET)
or... | 5,352,877 |
def getDroppableFilename(mime_data):
"""
Returns the filename of a file dropped into the canvas (if it was
accepted via @see isDroppableMimeType).
"""
if mime_data.hasUrls():
# Return the first locally existing file
for url in mime_data.urls():
fpath = url.toLocalFile()
... | 5,352,878 |
def team_points_leaders(num_results=None, round_name=None):
"""Returns the team points leaders across all groups, as a dictionary profile__team__name
and points.
"""
size = team_normalize_size()
if size:
entries = score_mgr.team_points_leaders(round_name=round_name)
else:
entries... | 5,352,879 |
def with_color(text, color, bold=False):
"""
Return a ZSH color-formatted string.
Arguments
---------
text: str
text to be colored
color: str
ZSH color code
bold: bool
whether or not to make the text bold
Returns
-------
str
string with ZSH color... | 5,352,880 |
def sample_test():
"""Return sample test json."""
return get_sample_json("test.json") | 5,352,881 |
def dataframe_from_inp(inp_path, section, additional_cols=None, quote_replace=' ', **kwargs):
"""
create a dataframe from a section of an INP file
:param inp_path:
:param section:
:param additional_cols:
:param skip_headers:
:param quote_replace:
:return:
"""
# format the secti... | 5,352,882 |
def compositional_stratified_splitting(dataset, perc_train):
"""Given the dataset and the percentage of data you want to extract from it, method will
apply stratified sampling where X is the dataset and Y is are the category values for each datapoint.
In the case each structure contains 2 types of atoms, th... | 5,352,883 |
def is_inside_line_segment(x, y, x0, y0, x1, y1):
"""Return True if the (x, y) lies inside the line segment defined by
(x0, y0) and (x1, y1)."""
# Create two vectors.
v0 = np.array([ x0-x, y0-y ]).reshape((2,1))
v1 = np.array([ x1-x, y1-y ]).reshape((2,1))
# Inner product.
prod = v0.transp... | 5,352,884 |
def transition_soil_carbon(area_final, carbon_final, depth_final,
transition_rate, year, area_initial,
carbon_initial, depth_initial):
"""This is the formula for calculating the transition of soil carbon
.. math:: (af * cf * df) - \
\\frac{1}{(1 ... | 5,352,885 |
def make_global_config():
"""load & augment experiment configuration, then add it to global variables"""
parser = ArgumentParser(description='Evaluate TRE model.', formatter_class=ArgumentDefaultsHelpFormatter)
# parser.add_argument('--config_path', type=str, default="1d_gauss/20200501-0739_0")
parser.... | 5,352,886 |
def dijkstra(graph, source):
"""Find the shortest path from the source node to every other node in the given graph"""
# Declare and initialize result, unvisited, and path
result = {i: sys.maxsize if i != source else 0 for i in graph.nodes} # placeholder, by default set distance to maxsize
path = dict... | 5,352,887 |
def _snr_approx(array, source_xy, fwhm, centery, centerx):
"""
array - frame convolved with top hat kernel
"""
sourcex, sourcey = source_xy
rad = dist(centery, centerx, sourcey, sourcex)
ind_aper = draw.circle(sourcey, sourcex, fwhm/2.)
# noise : STDDEV in convolved array of 1px wide annulus... | 5,352,888 |
def create_pipeline(training_set, validation_set, test_set):
"""
Create a pipeline for the training, validation and testing set
Parameters: training_set: Training data set
validation_set: Validation data set
test_set: Test data set
Returns: bat... | 5,352,889 |
def invalid_request() -> Tuple[Any, int]:
"""Invalid request API response."""
return jsonify({API.Response.KEY_INFO: API.Response.VAL_INVALID_REQUEST}), 400 | 5,352,890 |
def _add_hyperparameters(
ranges_path: Path, defaults_path: Path
) -> List[Dict[str, Any]]:
"""Returns a list of hyperparameters in a format that is compatible with the json
reader of the ConfigSpace API.
The list is created from two files: a hp_space file that defines the ranges of the
hyperparame... | 5,352,891 |
def softreset_magic(kernel, args):
"""Reset microcontroller. Similar to pressing the reset button.
Purges all variables and releases all devices (e.g. I2C, UART, ...).
Example:
a = 5
%softreset
print(a) # NameError: name 'a' isn't defined
"""
with kernel.device as repl:
if not args.quiet:... | 5,352,892 |
def setup(app):
"""Setup extension."""
app.add_domain(StuffDomain)
app.connect("builder-inited", generate_latex_preamble)
app.connect("config-inited", init_numfig_format)
app.add_css_file("stuff.css")
app.add_enumerable_node(
StuffNode,
"stuff",
html=(html_visit_stuff... | 5,352,893 |
def _save_finite_diffs(
file_name: str,
file_override: bool,
fin_diff_base_benchmarks: List[str],
fin_diff_shift_benchmarks: List[List[str]],
fin_diff_epsilon: float,
) -> None:
"""
Save finite differences between benchmarks into a HDF5 data file
Parameters
----------
file_name:... | 5,352,894 |
def call_extend_index_yaml() -> None:
"""Calls the extend_index_yaml.py script."""
print('\033[94m' + 'Extending index.yaml...' + '\033[0m')
extend_index_yaml.main() | 5,352,895 |
def has_checksum(path: Path, csum: str,
csum_fun: typing.Optional[Checksum] = None) -> bool:
"""
:return: True if the file at the path `path` has given checksum
"""
return get_checksum(path, csum_fun=csum_fun) == csum | 5,352,896 |
def test_void_transaction_with_param(single_transaction_purchase_invoice, auth_client):
"""Test if we can void a purchase invoice transaction by passing type into param."""
include = {'documentType': 'PurchaseInvoice'}
result = auth_client.void_transaction('DEFAULT', single_transaction_purchase_invoice, {'code':'Doc... | 5,352,897 |
def export_housing(filename_or_response):
"""
:param filename_or_response: can be a real filename or a django response
:return:
"""
def export(writer):
row = ['unit_id', 'address', 'apartment', 'city', 'state', 'zip_code']
writer.writerow(row)
for unit in Unit.objects.all():
... | 5,352,898 |
def remove_outliers(column):
"""
:param column: list of numbers
:return:
"""
if len(column) < 1:
return []
import numpy as np
clean_column = []
q1 = np.percentile(column, 25)
q3 = np.percentile(column, 75)
#k = 1.5
k = 2
# [Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)]
lo... | 5,352,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.