content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def scale_from_internal(vec, scaling_factor, scaling_offset):
"""Scale a parameter vector from internal scale to external one.
Args:
vec (np.ndarray): Internal parameter vector with external scale.
scaling_factor (np.ndarray or None): If None, no scaling factor is used.
scaling_offset (... | c7f2471d2a7776f8756d709d0288163aab3594ae | 3,622,203 |
def get_temp() -> tuple:
"""
Retrieves the CPU temperature of the Raspberry Pi and turns the fan
on or off based on the read value.
:return: An empty tuple.
"""
cpu_temp = float(get_cpu_temperature())
if cpu_temp > maxTMP:
fan_on()
elif cpu_temp < stopTMP:
fan_off()
r... | e4754d51847961d035860633780f679492b07002 | 3,622,205 |
def level_image(image: Image.Image, adjustments: list[LevelsAdjustment]) -> Image.Image:
"""
Apply the specified levels adjustments to each band of an image.
:param image: The input image, with values in the range [0, 255].
:param adjustments: The levels adjustments to apply for each band.
:return:... | 5cbf10275642f81c0ca5117bce192a8e9fa9e57c | 3,622,207 |
def extract_network_information(shape, properties, fid, zoom):
"""
Take the triples of (route_type, network, ref) from `mz_networks` and
extract them into two arrays of network and shield_text information.
"""
mz_networks = properties.pop('mz_networks', None)
if mz_networks is not None:
... | 0bfb0926c5eef46734cfd87c8ab03891c91d5110 | 3,622,208 |
def filter_pre_string(_string: str, lines_to_cut: int) -> str:
"""
Filter the xml out of html
:param str _string:
:param int lines_to_cut:
"""
filtered_array = _string.splitlines()[lines_to_cut:]
filtered_string = "".join(filtered_array)
filtered_string = filtered_string.strip()
re... | 1bde68fbfa3f87360b47ece45b64782dcc3bcde6 | 3,622,209 |
def extract_ontology_terms(spark_session: SparkSession, input_path) -> DataFrame:
"""
:param spark_session:
:param ontologies_path:
:return:
"""
ontology_terms = []
if ImpcConfig().deploy_mode in ["local", "client"]:
for ontology_desc in ONTOLOGIES:
print(f"Processing {o... | 91f37011ed95470be98e6613868d61718f843cf2 | 3,622,210 |
def get_one_example_from_examples_path(source, proto=None):
"""Get the first record from `source`.
Args:
source: str. A pattern or a comma-separated list of patterns that represent
file names.
proto: A proto class. proto.FromString() will be called on each serialized
record in path to parse it.... | 384194d68f22f73ece806cf0b0aabd0721e5bd5f | 3,622,211 |
def ssum(self, **kwargs):
"""Calculates and prints the sum of element table items.
APDL Command: SSUM
Notes
-----
Calculates and prints the tabular sum of each existing labeled result
item [ETABLE] for the selected elements. If absolute values are
requested [SABS,1], absolute values are u... | 299a14a2e21454a304d6d023d2b3a3709b24eb18 | 3,622,212 |
def get_nth_combination(
iterable,
*,
items: int,
index: int,
):
"""
Credit to:
https://docs.python.org/3/library/itertools.html#itertools-recipes
Examples:
>>> wallet = [1] * 5 + [5] * 2 + [10] * 5 + [20] * 3
>>> get_nth_combination(wallet, items=3, index=... | 6ed186d260ca86c0f16d383576e69402d079ed9b | 3,622,213 |
def fft2(x, shape=None, axes=(-2, -1), overwrite_x=False):
"""Compute the two-dimensional FFT.
Args:
x (cupy.ndarray): Array to be transformed.
shape (None or tuple of ints): Shape of the transformed axes of the
output. If ``shape`` is not given, the lengths of the input along
... | a86c2fbac32debe754ed283b2b5f63d8ccfb5cba | 3,622,214 |
def equalize(pair, bias_axis, word_to_vec_map):
"""
Debias gender specific words by following the equalize method described in the figure above.
Arguments:
pair -- pair of strings of gender specific words to debias, e.g. ("actress", "actor")
bias_axis -- numpy-array of shape (50,), vector correspon... | 858f6f43d799973c3314aa184e64caed3cdbc77a | 3,622,215 |
def test_text_angle_30(region, projection):
"""
Print text at 30 degrees counter-clockwise from horizontal
"""
fig = Figure()
fig.text(
region=region,
projection=projection,
x=1.2,
y=2.4,
text="text angle 30 degrees",
angle=30,
)
return fig | 1add55f5465c5285bfb7b626f6c4259d4189240d | 3,622,216 |
def edit_cmd(args):
"""Builds and returns 'edit' command."""
cmd = commands.Edit(args.args, color=args.color)
return cmd | 11e766fd1e348584f5aed965788c06b54dca551c | 3,622,217 |
def get_image_band(filepath, modis_config=None):
"""Helper function to get bands for a particular modis scene
Args:
modis_config (dict): dictionary of configuration for a particular MODIS datasource
filepath (str): path to file to get image band for
"""
bands = list(modis_config["bands"... | 796734a9e666e2e6a5467c8ae2d80ffceab6e9d7 | 3,622,218 |
import six
from datetime import datetime
import re
def create_mock_engine(bind, stream=None):
"""Create a mock SQLAlchemy engine from the passed engine or bind URL.
:param bind: A SQLAlchemy engine or bind URL to mock.
:param stream: Render all DDL operations to the stream.
"""
if not isinstance... | 7ad7e528041a899268bdf796893d633909a6ea54 | 3,622,219 |
from typing import Tuple
from typing import List
def rst_table(header: Tuple[str, ...], rows: List[Tuple[str, ...]]) -> List[str]:
"""Create a ReST table from header and rows."""
blocks = [".. list-table::\n :header-rows: 1\n"]
num_columns = len(header)
for row in [header] + rows:
template =... | 461ecb7bbe99752d1ef5c9341cd53c2c7c3752bf | 3,622,220 |
def get_model(args):
""""Get model according to args.arch"""
print("==> Creating model '{}'".format(args.arch))
model = models.__dict__[args.arch](args)
return model | ed4d1a8eb5dad2beb0968be5318dd706a3f34cf3 | 3,622,221 |
def truncate_note_sequence_op(sequence_tensor, truncated_length_frames,
hparams):
"""Truncates a NoteSequence to the given length."""
def truncate(sequence_tensor, num_frames):
sequence = music_pb2.NoteSequence.FromString(sequence_tensor)
num_secs = num_frames / hparams_frames_... | 34276444a0e338c0fa81f6cde8d5932e86bfa1a4 | 3,622,222 |
def compute_mse_labels(params, delta, X, Y, labels, use_sigmoid):
"""
assume a, b, c, delta, X, Y are all in the right dimensions
"""
if use_sigmoid:
sig0, sig1 = params
else:
a,b,c = params
N_patients, N_visits, N_dims = Y.shape
all_mse = 0.
for i in range(... | 6c8778cd40ef6af6949089afed3adfcb56b945c4 | 3,622,223 |
def produce_columns(df):
"""Reports columns for use in model."""
columnsNames = []
for i in df.columns:
if i == 'Survived' or i == 'PassengerId':
pass
else:
columnsNames.append(i)
return columnsNames | ce527118fc099ac05d20dbb981f5f3231e9070fa | 3,622,224 |
def fixture_ref_6_2_3_5():
"""Reference for (load, bins) of 6, [2, 3, 5]."""
ref = {
"load": 6,
"bins": [2, 3, 5],
"solutions": {
key: [(3, 3)] for key in ["length", "capacity", "combo"]
}
}
return ref | 7b7121e404b4daf3277a4ab6f33eb955cd6d47e7 | 3,622,225 |
import time
def read_variable_bounds(filename, verbose=False):
"""Read permissible lower and upper bounds for decision variables used in forcefields optimization
:param filename: Name of text file listing bounds for each decision variable that must be optimized
:type filename: str
:param verbose: Pr... | c8207d291ce0b698bbf1eacb920d0c787d2b7eb3 | 3,622,227 |
def parse_spec_storage_location(location: str) -> SpecStorageLocation:
"""
Parse the spec storage location into components.
Args:
location: The spec storage location to parse.
Returns:
The parsed spec storage location.
"""
sub, spec_id, filename = location.split("/")
versi... | 96f70c82bcaf3f971d109e043794815760529d45 | 3,622,228 |
def datastore(plugin, key, string=None, hex=None, mode="must-create", generation=None):
"""Add/modify a {key} and {hex}/{string} data to the data store,
optionally insisting it be {generation}"""
key = normalize_key(key)
khex = key_to_hex(key)
if string is not None:
if hex is not None:
... | 428adb35c4fe58c4f794055f20735aa42f93d0e8 | 3,622,229 |
def recreate_knob_from_optimizer_values(variables, opti_values):
""" recreates knob values from a variable """
knob_object = {}
# create the knobObject based on the position of the opti_values and variables in their array
for idx, val in enumerate(variables):
knob_object[val] = opti_values[idx]
... | 8c253ea75f1dbb8c27cde21b2208b5386d75930e | 3,622,230 |
def make_cube_marker(box_center, box_dim):
""" a reasonable default box marker.
"""
marker = CubeMarker(box_dim)
marker.set_translation(box_center)
marker.set_color_float([1., 0., 0.])
marker.set_alpha(0.80)
return marker.to_msg() | f3c643c9f52fb0876643fc1b3acc3dcbfc12dce2 | 3,622,231 |
def KDPReadPhysMEM(address, bits):
""" Setup the state for READPHYSMEM64 commands for reading data via kdp
params:
address : int - address where to read the data from
bits : int - number of bits in the intval (8/16/32/64)
returns:
int: read value from memory.
... | 7eae9f5a74e5788775c132d8766e244e8d2878f1 | 3,622,232 |
from typing import List
from typing import Optional
from typing import Iterable
def combine(
meshes: List[pv.PolyData],
data: Optional[bool] = True,
clean: Optional[bool] = False,
) -> pv.PolyData:
"""
Combine two or more meshes into one mesh.
Only meshes with faces will be combined. Support ... | b219f9d408c4494373e65048d59ff62fae92d422 | 3,622,235 |
def magician(*cards, n=1):
"""Determine the fifth card with only four cards."""
# Obviously not a random card, put your code here instead.
show = cards[(n-1)%4]
pile1 = [i for i in cards]
pile1.pop((n-1)%4)
pile2 = deepcopy(pile1)
pile2.sort(key = lambda i: (RANKS.index(i[:i.index(' ')]),SU... | 5181658579b41d8676e7af78175f1d6eba13af7d | 3,622,236 |
from typing import List
def create_users_from_csv(connection: "Connection", csv_file: str) -> List["User"]:
"""Create new user objects from csv file. Possible header values for the
users are the same as in the `User.create()` method.
Args:
connection: MicroStrategy connection object returned by
... | 32c991cd82c0c314e4c9ec2bfe6ba586e0e26425 | 3,622,237 |
def catl_keys_prop(catl_kind, catl_info='members', return_type='list',
Program_Msg=fd.Program_Msg(__file__)):
"""
Dictionary key sfor the different galaxy/group properties of
catalogues
Parameters
----------
catl_kind: string, optional (default = 'data')
type of catalogue to use
... | f57c7316d0cc7a418a699d00535af63ea9c9dd5b | 3,622,238 |
def pa_max_pool(in_dict):
"""Implement `local max pooling` as `masking + global max pooling`.
Args:
feat: pytorch tensor, with shape [N, C, H, W]
mask: pytorch tensor, with shape [N, pC, pH, pW]
Returns:
feat_list: a list (length = pC) of pytorch tensors with shape [N, C]
vis... | 39d78b691f9358b3e6820ace54fbb69845934a9f | 3,622,239 |
def _create_validate(cls, validators):
"""
Create a new validate method with extra validator functions.
"""
def validate(self, value):
super(cls, self).validate(value)
for validator in validators:
validator(value)
validate.__doc__ = validators[0].__doc__
return vali... | a3f8b1ef5255f1c2f359b82539aa911b6d136514 | 3,622,240 |
def predict_roi(roi, ground_truth, model, device, in_trans=None, batch_size=1, tile_size=256, overlap=0, n_jobs=1,
zoom_level=0):
"""
Parameters
----------
roi: BaseCrop
The polygon representing the roi to process
ground_truth: iterable of Annotation|Polygon
The groun... | 9c55c3b0f87a2b23794eaaf6ff8d364955ab6404 | 3,622,241 |
from typing import Iterable
from typing import Type
def get_ceed_stages(
stage_factory: StageFactoryBase) -> Iterable[Type[StageType]]:
"""Returns all the stage classes defined and exported in this file
(currently none for the internal plugin).
:param stage_factory: The :class:`~ceed.function.Fun... | 41717ed8f700cd08e2d1728616259a09b8a8434f | 3,622,242 |
import logging
def scale_quote_of_type(
df: pd.DataFrame, mapping: dict, file_type: str = "quotes"
) -> (pd.DataFrame, dict):
"""
Scales quote values of quotes of a specified type
This function appends an extra row (__adjusted_quote) to a dataframe that contains quotes that have been scaled by
a ... | 85d7edc762fc29eb03d77495a4100b57f2d735ea | 3,622,243 |
def mysql_metadata_connection_config(host: Text, port: int, database: Text,
username: Text, password: Text
) -> metadata_store_pb2.ConnectionConfig:
"""Convenience function to create mysql-based metadata connection config.
Args:
host: The... | 9349f5a720b99629e1f24a2367cd35b9246fadbb | 3,622,244 |
def _status(self):
"""status -> Returns the Shot status. None if no Status is set."""
status = None
tags = self.tags()
for tag in tags:
if tag.metadata().hasKey('tag.status'):
status = tag.metadata().value('tag.status')
return status | eb8fd85218f6e745f09e4984db8b6c74ba464dcb | 3,622,245 |
def convert_onnx_less(operator, device=None, extra_config={}):
"""
Converter for `ai.onnx.Less`.
Args:
operator: An operator wrapping a `ai.onnx.Less` model
device: String defining the type of device the converted operator should be run on
extra_config: Extra configuration used to s... | 62c15f872efad8a30496a6cd018ae085d0a790b4 | 3,622,246 |
def capped(value, minimum=None, maximum=None, key=None, none_ok=False):
"""
Args:
value: Value to cap
minimum: If specified, value should not be lower than this minimum
maximum: If specified, value should not be higher than this maximum
key (str | None): Text identifying 'value' ... | 663a63041699f4e4f52886adbd49423bf52c0282 | 3,622,248 |
def conditional_MARC21(record, rule):
"""Function takes a conditional and a mapping dict (called a rule)
and returns the result if the test condition matches the antecedient
Parameters:
record -- MARC21 record
rule -- Rule to match MARC field on
"""
output = []
if rule.has_key('cond... | 5618fbe5bec61379b106c3caa2b3330fa5900b89 | 3,622,249 |
def row(ctx):
"""Get this cell's row."""
return ctx["cell"].row | 4cfc89daa3ca771359acd762d716316209ca0eb4 | 3,622,250 |
def get_external_admin_connection_string(db_name=None, db_prefix=None):
"""Get an admin connection string for access from outside the cluster"""
admin_user, admin_password, admin_db_name = get_admin_db_credentials(db_prefix=db_prefix)
if not db_name:
db_name = admin_db_name
db_host, db_port = ge... | b0678960aa9f7e8b3bb1ba33245d761281ce2c8e | 3,622,252 |
import math
def calc_room_positions_square(side_length, num_rooms):
"""
Calculate the central positions of the square rooms.
"""
sqrt_num_rooms = int(math.sqrt(num_rooms))
if sqrt_num_rooms ** 2 != num_rooms:
raise ValueError("num_rooms must be a perfect square number")
int_positions... | c4e2cc4338339ce10877ad920500124beb612aa5 | 3,622,253 |
def logout(request: HttpRequest, default_redirect="/"):
"""
This function logs a user out and redirect him to a certain location
:param request: the current HTTP request
:param default_redirect: The location to redirect if no next GET request is given
:return: The HTTP_RESPONSE containing the redire... | b53bc3de1973a67792da7e5623930772545929bc | 3,622,254 |
def cell_slice(payload):
"""Retrieve the next cell from the payload and truncate that one.
:param payload: bytearray
"""
payload_len = len(payload)
if payload_len < 7: # (payload too small, need data)
return None, payload
cmd = cell_get_cmd(payload)
if cell_is_variable_length(cmd):... | 79208936e020dabde1e99507d3886fd09c134948 | 3,622,255 |
def calc_entropy(logits):
"""
Calculates the entropy of the output values of the network
:param logits: (TensorFlow Tensor) The input probability for each action
:return: (TensorFlow Tensor) The Entropy of the output values of the network
"""
# Compute softmax
a_0 = logits - tf.reduce_max(i... | d60c4e1fba7098167d9e48ae8bdcfcfd6a159ba8 | 3,622,257 |
def make_environment(domain_name, task_name, rng, frame_stack, action_repeat):
"""Create a visual DMC environment"""
env = suite.load(
domain_name=domain_name,
task_name=task_name,
environment_kwargs={"flat_observation": True},
task_kwargs={"random": rng},
)
camera_id = 2... | 7c55e3d7e0829287c8b9dd69c3c8f4821584b715 | 3,622,258 |
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
label_map = {label: i for i, label in enumerate(label_list)}
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
... | a77ffa87357c5615d8435dc6903a857607bea4e4 | 3,622,259 |
def get_post_by_id(request, post_id):
"""Read: Get a post with given event_id
e.g. http://127.0.0.1:8000/api/post/2
"""
if request.method == 'GET':
# key_flag = len(request.GET['eventID'])
# if key_flag:
# record = GISource.objects.filter(event_id=post_id)
# ser... | b86751630ceb018889cbc2abef8f6f6fa3ee7d8e | 3,622,261 |
def fetch_created_ruleset(creator_id):
"""
Get a user ID that want to filter the ruleset that this user make and return a list of ruleset
with the User object of that ruleset.
If the program cannot find the User object,it will append `None` to the return value.
:param creator_id: A user ID
... | 7513ed96af4cb69f6176c63ddef85bf4662ff2ef | 3,622,262 |
from datetime import datetime
import copy
import logging
def Run(benchmark_spec):
"""Executes the given jar on the specified Spark cluster.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of sample.Sample objects.
""... | 12e9e31349434cffb90a1c89ac599666e4ee348e | 3,622,263 |
def threshold_stats_img(stat_img=None, mask_img=None, alpha=.001, threshold=3.,
height_control='fpr', cluster_threshold=0,
two_sided=True):
""" Compute the required threshold level and return the thresholded map
Parameters
----------
stat_img : Niimg-like... | a29da195a4178b798da929b25bb0c28715d55ae1 | 3,622,264 |
import pathlib
def _export_doc_requirements(toml: dict, file: pathlib.Path, *packages) -> int:
"""
Export the provided packages versions.
Return values:
0 no changes
1 exported new requirements
2 file does not exist
3 invalid packages
"""
file = pathlib.Path(file)
if not file.... | bc1eb73737b4674f9e66590d714614da04e77bdf | 3,622,265 |
import re
def _extract_function_from_js(name, js):
""" Find a function definition called `name` and extract components.
Return a dict representation of the function.
"""
dbg("Extracting function '%s' from javascript", name)
fpattern = r'function\s+%s\(((?:\w+,?)+)\)\{([^}]+)\}'
m = re.searc... | 74159764aff104d7910d258644a6272f1d33e1ac | 3,622,266 |
def above_the_line(x_array, x1, x2):
"""
Return states above a specified line defined by (x1, x2).
We assume that a state has only two coordinates.
Parameters
----------
x_array: `np.array`
A 2-d matrix. Usually, an embedding for data points.
x1: `np.array`
A list or array ... | d20b5d462b7254a93f7896b592ae25eae26075a7 | 3,622,269 |
import torch
def cel_num_div(cel_mat: Tensor, rc: float) -> Tensor:
"""Number of percel for each direction.
Args:
cel_mat: cell.
rc: cutoff radius.
Returns:
num_div(int[bch, dim]): number of percel for each direction.
"""
num_div = ((cel_mat / rc).norm(p=2, dim=-1) - 1e-4... | 768a10cb68243f17a8e51f10092d90bb119c9a47 | 3,622,271 |
def confusion_samples(prediction, truth, names):
""" Computes the confusion matrix and returns a list with
the TP/FP/TN/FN names
"""
confusion_vector = prediction / truth
# Element-wise division of the 2 tensors returns a new tensor which holds a
# unique value for each case:
# 1 wher... | 6d3bd82f1ea695345a30a75be6642328a393a1de | 3,622,272 |
def post_upload_finished(uid):
"""
ask the server to finish the upload
:param uid: upload session ID
:return: status of upload
"""
uploaded = require_integer_array_json_parameter("uploaded")
with slycat.web.server.upload.get_session(uid) as session:
return session.post_upload_finishe... | 4d8ea1b6283e9de339010ce1adc275f76edc78b4 | 3,622,273 |
def info():
"""Returns information about a worker.
Useful for testing that the system is functioning.
Returns
-------
metadata: :class:`dict`
A collection of key-value pairs containing information describing the
local worker.
"""
return buildcat.info() | 0f3f75555e2ec289b1422e17e8f06c2ce45565e3 | 3,622,274 |
def parse_xml(path):
""" Returns representation of the root node in the XML file. """
try:
return XMLElement(ET.parse(path).getroot())
except ET.ParseError as e:
raise XMLParseError(str(e)) | 3e129e3ba5a66560c3f9a67df0e6cc76ecefbb47 | 3,622,275 |
def fastq_pe_pipeline(project, sample_identifier=None, end_identifier=None):
"""Functional profiling pipeline for entire project
Args:
project (:obj:Project): current project
sample_identifier (str, optional): sample identifier
end_identifier (str, optional): end identifier
"""
... | b7046214ee156497e869fd37f5c5ab8c17c3c085 | 3,622,276 |
from pathlib import Path
def test_data_path() -> Path:
"""Fixture to Fetch reports for unit testing."""
return repo_path / 'tests' / 'data' | b7ad565f0e77bba6d3ff74ba0318df8742061597 | 3,622,278 |
def createSequentialVector(size, vector_type, communicator=None):
"""Create a sequential vector in petsc format.
:param int size: vector size.
:param int vector_type: vector type for parallel computations.
:param str communicator: mpi communicator.
:return: sequential vector.
:rtype: petsc sequ... | 15328b4ac90754ee7ff8c4c2556aee859a2f252e | 3,622,279 |
def create_gunicorn_worker():
"""
follows the gunicorn application factory pattern, enabling
a quay worker to run as a gunicorn worker thread.
this is useful when utilizing gunicorn's hot reload in local dev.
utilizing this method will enforce a 1:1 quay worker to gunicorn worker ratio.
"""
... | cea3812243406b069049ed9c9965713514e80bae | 3,622,280 |
import tensorflow as tf
def downsampler_gpu(input, down_scale, kernel_name='bspline', normalize_kernel=True, a=-0.5, default_pixel_value=0):
"""
Downsampling wiht GPU by an integer scale
:param input: can be a 2D or 3D numpy array or sitk image
:param down_scale: an integer value!
:param kernel_na... | c92641aae2ced49b84c33bdb4b272bb4ce255f90 | 3,622,281 |
from unittest.mock import patch
async def test_setup_component_with_config(hass, config_entry):
"""Test setup of the netatmo component with dev account."""
fake_post_hits = 0
async def fake_post(*args, **kwargs):
"""Fake error during requesting backend data."""
nonlocal fake_post_hits
... | fb012643ab460de3c50cbb69ace113933a6ee4f1 | 3,622,282 |
def numerical_grad(theta, f, dx=1e-3, order=1):
""" return numerical estimate of the local gradient
The gradient is computer by using the Taylor expansion approximation over
each dimension:
f(t + dt) = f(t) + h df/dt(t) + h^2/2 d^2f/dt^2 + ...
The first order gives then:
df/dt = (f(t +... | bc9686f264acb5cf8a643355e95386b99b8c554b | 3,622,283 |
def putIterationsPerSec(frame, iterations_per_sec):
"""Add iterations per second text to lower-left corner of a frame."""
cv2.putText(frame,
"{:.0f} iterations/sec".format(iterations_per_sec),
(10, 450),
cv2.FONT_HERSHEY_SIMPLEX,
1.0,
... | 56172565ba2fc8c08eb9d13464f8c866caecc4de | 3,622,284 |
def _filter_by_filename(kind, universe, include_files, exclude_files):
"""
Filters out what tests to run solely by filename.
Returns either the set of files from 'universe' that are present in 'include_files', or the
set of files from 'universe' that aren't present in 'exclude_files', depending on whic... | af646932ee740e63e630ebd885f4d6b708876f6a | 3,622,285 |
def eqPoints(POINT):
"""
Get point and make all combinations of ones and zeros by addding numbers in binary
"""
zera = np.where(POINT == 0)[0]
ilepow = 2**zera.size
mylist = np.empty((ilepow-1,3))
for n in range(1,ilepow):
val = f"{n:b}"
jkl = zera.size - len(val)
... | a68ab7cc64f21bf2bd67a0b5918267e6f1873893 | 3,622,286 |
def clip(base, color):
"""Gamut clipping."""
channels = util.no_nan(color.coords())
gamut = color._range
fit = []
for i, value in enumerate(channels):
a, b = gamut[i]
is_bound = isinstance(gamut[i], GamutBound)
# Wrap the angle. Not technically out of gamut, but we will cl... | 8603da1fbe00747f21284fdb4ce077c819d47825 | 3,622,287 |
def clustal_omega_alignment(seqrecs, preserve_order=True, **kwargs):
"""Align sequences using Clustal Omega
:param seqrecs: a list or dict of SeqRecord that will be aligned to ref
:param preserve_order: if True, reorder aligned seqrecs to match input order.
:param **kwargs: additional arguments for ali... | d756f5c9b1a6986f75ff89f89f6ab96a15e8b515 | 3,622,289 |
def hass_tz_info(hass):
"""Return timezone info for the hass timezone."""
return dt_util.get_time_zone(hass.config.time_zone) | 1cea4a41e283bba104fb125b35ca66d0e1ebf989 | 3,622,291 |
def _get_lq_l(m: np.ndarray) -> np.ndarray:
""" Calculate L term from LQ decomposition, ensuring the diagonal is non-negative.
Parameters
----------
m
Matrix to process.
Returns the L term in the LQ decomposition, using the convention that all diagonal
elements are non-negative. This i... | 99cac99cd3ac88c938bc41be1eb271a4e81267ed | 3,622,292 |
def csv_serving_input_fn():
"""Build the serving inputs."""
csv_row = tf.placeholder(shape=[None], dtype=tf.string)
features = _decode_csv(csv_row)
features.pop(constants.LABEL_COLUMN)
return tf.estimator.export.ServingInputReceiver(features,
{'csv... | dec6901f279ff555322a9fb6cd90f075d6281f3f | 3,622,293 |
def fix_literals(args):
"""make up argument names for literals in call"""
res = args[:]
index = 0
for i, el in enumerate(res):
if not (identifier(el) or keyword_argument(el)):
while f'arg{index}' in res:
index += 1
res[i] = f'arg{index}'
return res | 872f720768331a714abaa88e9b3ac92fe10014c5 | 3,622,294 |
def complete_graph(n):
""" returns a complete graph with n vertices
"""
return wgraph_from_adjacency(np.ones((n, n))) | a9ce64cc77412942b6ce428f32f64fa22831a49f | 3,622,298 |
def get_P_HP_cm_d(q_HP_sum_std_test, q_HP_win_std_test, A_p, B_p, theta_hat_bw_cm_d, theta_ex_Nave_d,
theta_star_bw_std, theta_star_ex_sum, P_HP_sum_std_test):
"""日付dにおける制御モードcmのヒートポンプの消費電力(13)
Args:
q_HP_sum_std_test(float): 試験時の夏期標準加熱条件におけるヒートポンプの加熱能力
q_HP_win_std_test(float): 試... | 498beb875396ec43140aaf0612984fb6520ac08e | 3,622,299 |
def data_process(num=250):
"""
从数据集中获取实验评估数据,默认为250条,将数据加载到句子1和2对应的列表中并进行返回
:param num: 实验数据的条数,默认为250
:return: 句子1组成的集合,句子2组成的集合
"""
content = pd.read_csv(util.data_path(), sep='\n', header=None)
content = content.head(num)
sen1_list = []
sen2_list = []
print("开始处理实验数据")
fo... | d40640fabb01af9ac1a916313fb9ba5d1ae826c0 | 3,622,301 |
import gc
def sample_from_distance_matrix(dist_matrix, dist_mul=1, const_mul=8500, start=None, end=None, **kwargs):
"""Sample TSP qubo from given distance matrix and return lowest-energy sdolution.
This is basically the same as :py:func:`sample_from_locations` except it skips
calculation of distance matr... | bd68b425a694cb373980a5aae76889a02288100a | 3,622,302 |
import torch
def _add_embedding_layer(model_1, model_2):
"""
Returns an embedding layer with a weight matrix
of the follwing structure:
[MODEL_1 EMBEDDING MATRIX ; MODEL_2 EMBEDDING MATRIX]
"""
result_layer = torch.nn.Embedding(
model_1.num_embeddings, model_1.embedding_dim + model... | 2b4f4f3e36d56c57302cdcbf07c6cbbdb5165e11 | 3,622,303 |
def generate_key_lu_dict(
dict_tuple_keys,
unique_identifier,
enduses,
sectors,
technologies
):
"""Generate look_up keys to position in 'load_profiles'
Arguments
----------
dict_tuple_keys : dict
Already existing lu keys
unique_identifier : string... | adc2fd7357d16b3026ae7d0d8f363919b61f8525 | 3,622,304 |
from io import StringIO
def dumps(obj):
"""
Similar method to json dumps, prepending data with message length
header. Replaces pickle.dumps, so can be used in place without
the memory leaks on receiving side in pickle.loads (related to
memoization of data)
NOTE: Protocol is ignored when json ... | d5607df3e894fa9031da1cd0ce01ec18b5c441da | 3,622,305 |
from typing import Optional
from typing import Union
from typing import List
def load_tensor(name: Text) -> Optional[Union["tf.Tensor", List["tf.Tensor"]]]:
"""Load tensor or set it to None"""
tensor_list = tf.get_collection(name)
if not tensor_list:
return None
if len(tensor_list) == 1:
... | e0160ecd7126ea49325d86143bc03445f23312da | 3,622,306 |
def rdns_domain(network):
"""Transform :py:class:`netaddr.IPNetwork` object to rDNS zone name"""
if network.prefixlen == 0:
return "ip6.arpa" if network.version == 6 else "in-addr.arpa"
if network.version == 4:
return ".".join(map(str, reversed(
network.ip.words[:network.prefixle... | b94656f270d39ac175efb8bc8a99af0d29dad7df | 3,622,307 |
def make_dataset(dataset_type, path, args, **kwargs):
"""function to create datasets+tokenizers for common options"""
return get_dataset_by_type(dataset_type, path, args) | 220cbd2515fc359b6adcd7ff8420947abc301596 | 3,622,308 |
def to_undirected(graph):
"""Returns an undirected view of the graph `graph`.
Identical to graph.to_undirected(as_view=True)
Note that graph.to_undirected defaults to `as_view=False`
while this function always provides a view.
"""
return graph.to_undirected(as_view=True) | 96ceb4e2d7dbe2a9c120b8e1ac7cad0ef2b2c6ae | 3,622,309 |
def CDLUNIQUE3RIVER(df):
"""
函数名:CDLUNIQUE3RIVER
名称:Unique 3 River 奇特三河床
简介:三日K线模式,下跌趋势中,第一日长阴线,第二日为锤头,最低价创新低,第三日开盘价低于第二日收盘价,收阳线,收盘价不高于第二日收盘价,预示着反转,第二日下影线越长可能性越大。
python API
integer=CDLUNIQUE3RIVER(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low... | b85e213bb16ab902f9c48232ea50fe64e2b57dcd | 3,622,311 |
def single_leg_credit(trade):
"""Generate a message for a single leg credit trade."""
action = "closed" if trade['close_date'] else "opened"
trade_type = trade['type'].lower()
user = trade['User']['username']
strike = trade['short_put'] if "put" in trade_type else trade['short_call']
symbol = tr... | 8425e24e45fff6d694d593c39fa9277fa21da0e1 | 3,622,312 |
def remove_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (impute)
xlabel = "Max fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 9
"""
return __run_measure(measures.remove_mask, X, y, model_generator... | d3cfbac378c8811f9c22b1e433c6470dccca9ab8 | 3,622,313 |
def getText(rng):
"""
Get the pure text that is included in a js range
@param range js range to get the text of
@return string of the range's text
"""
return rng.toString() | 71c7c2eccb850ab1d807496d8033bb426b467492 | 3,622,314 |
def create_rain_array(rain_file, values):
"""Shuffles the rain distribution columns and creates an array of fractional values the same
length as the precip input. This can be passed to the chop_daily_to_hourly_precip function
Every 24 values should sum to ~1.0.
:param rain_file: path to .csv ppt distri... | 821911ff9f7b035f1eaec0a5083be0b7ed08ae60 | 3,622,315 |
def get_Xy_v6(filename='./data/train.csv'):
"""Data Encoding
Version 5
* same as version 4 except encode 3rd class as the number 4
* to better reflect the added difficultly of being in 3rd class
"""
def extract_title(x):
title = x.split(',')[1].split('.')[0].strip()
if title no... | bdc48e6ae796148282625a3da850ac147146da03 | 3,622,316 |
def _asarray1d(arr, copy=False):
"""Ensure 1D array for one array.
"""
if copy:
return asarray(arr).flatten()
else:
return asarray(arr).ravel() | b6f8bfc1ec2e411017f5da84d23674345f315dfb | 3,622,319 |
from typing import Iterable
import torch
def pssm1D(seq: Iterable, pssm=None, return_type='Array', **kwargs):
"""Obtain pssm given sequence."""
if pssm is None:
pssm = read_pssm(return_type=return_type, **kwargs)
pssm_values = [pssm[i, aa2index(aa)] for i, aa in enumerate(seq)]
return torch.t... | 76d6d12754a326bc0042c5434c7e786b34b74dfb | 3,622,321 |
def _chain_validator(*funcs):
"""Chain a series of validators."""
def chained(value):
for func in funcs:
value = func(value)
return value
return chained | 40082602f92a28160306bfff4d7b61703ea2e962 | 3,622,322 |
from typing import MutableMapping
from typing import Any
def remove_keys(
_dict: MutableMapping[str, Any] | None, keys: list[str]
) -> MutableMapping[str, Any]:
"""Remove keys from a dictionary."""
if not _dict:
return {}
new = dict(_dict)
for key in keys:
new.pop(key, None)
re... | 7a0ee8482eea69b0be7f7ecfd41355206adcf01c | 3,622,323 |
def delete_contact(id):
"""Removes contact by ID."""
contact = current_user.get_contact_or_404(id)
if contact.is_primary:
flash('Cannot delete primary contact.')
elif list(contact.attendance):
flash('Cannot delete contact involved in events.')
else:
with db.transaction as ses... | 314a2d449aa5ddbe78258bc5e7a9bc6a55af6f65 | 3,622,324 |
def concat_coords_maps(x: TENSOR_OR_SEQ_OF_TENSORS_T, channel_dim: int = 1) -> TENSOR_OR_SEQ_OF_TENSORS_T:
""" Concats N new features maps of euclidian coordinates (1D, 2D, ..., ND coordinates if `x` has N dimensions after `channel_dim`'s dimension) into given `x` tensor. Coordinates are concatenated at `channel_di... | 338035184e88fcd0baf65dc970e95a667c7b0713 | 3,622,325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.