content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def set_default_styles(svg_element):
"""
sets fill, stroke, stroke-width to default so that at least the elements
is visibly displayed
:param svg_element:
:return:
"""
assert svg_element is not None
svg_element.set_fill(NONE)
svg_element.set_stroke(RED)
svg_element.set_stroke_wid... | 17,600 |
def float_or_none(string):
""" Returns float number iff string represents one, else return None. TESTS OK 2020-10-24. """
try:
return float(string)
except (ValueError, TypeError):
return None | 17,601 |
def move_release_to_another_collection_folder(user: UserWithUserTokenBasedAuthentication,
username: str,
source_folder_id: int,
destination_folder_id: int,
... | 17,602 |
def test_badbase_error():
"""Test that an error is raised if base is invalid."""
C = classifier.BinaryClassifier(np.zeros(2), 1)
with pytest.raises(TypeError):
core.global_entropy(C, 4) | 17,603 |
def load_region_maps(region_file):
"""Extracts creates a map from PHI region id to a continuous region id."""
region_ids = [] # Used mainly for eval
region_ids_inv = {} # Used in data loader
region_names_inv = {} # Used in eval
for l in region_file.read().strip().split('\n'):
tok_name_id, _ = l.strip()... | 17,604 |
def _find_nearest_idx(a, a0):
"""Element idx in nd array `a` closest to the scalar value `a0`."""
if isinstance(a, list):
a = np.array(a)
idx = np.abs(a - a0).argmin()
return idx | 17,605 |
def build_argument_parser():
"""
Builds the argument parser
:return: the argument parser
:rtype: ArgumentParser
"""
opts = ArgumentParser()
opts.add_argument(dest='filename', help='Filename or release name to guess', nargs='*')
naming_opts = opts.add_argument_group("Naming")
naming_... | 17,606 |
def does_user_have_product(product, username):
"""Return True/False if a user has the specified product."""
try:
instance = adobe_api.AdobeAPIObject(username)
except adobe_api.AdobeAPINoUserException:
return False
return instance.has_product(product) | 17,607 |
def items_for_result(cl, result, form):
"""
Generate the actual list of data.
"""
def link_in_col(is_first, field_name, cl):
if cl.list_display_links is None:
return False
if is_first and not cl.list_display_links:
return True
return field_name in cl.list... | 17,608 |
def system_to_ntp_time(timestamp):
"""Convert a system time to a NTP time.
Parameters:
timestamp -- timestamp in system time
Returns:
corresponding NTP time
"""
return timestamp + NTP_DELTA | 17,609 |
def bcewithlogits_loss(weight=None, size_average=None, reduce=None, reduction='mean', pos_weight=None):
"""Creates a criterion that combines a `Sigmoid` layer and the `BCELoss` in one single
class
Arguments:
weights(Tensor, optional) : A manual rescaling weight given to the loss of each batch e... | 17,610 |
def transition_matrix(
adata: AnnData,
vkey: str = "velocity",
backward: bool = False,
weight_connectivities: Optional[float] = None,
sigma_corr: Optional[float] = None,
scale_by_variances: bool = False,
var_key: Optional[str] = "velocity_graph_uncertainties",
var_min: float = 0.1,
u... | 17,611 |
def bcftools_ann_predict_csv():
"""Open the bcftools.csv file with predictions annotation."""
with open(BCFTOOLS_ANN_PREDICT_CSV) as f:
yield f | 17,612 |
def create_access_token(
subject: Union[str, Any], expires_delta: timedelta = None, is_superuser: bool = False
) -> str:
"""
generate jwt token
:param subject: subject need to save in token
:param expires_delta: expires time
:return: token
"""
if expires_delta:
expire = datet... | 17,613 |
def transparency(wavelength):
"""Returns the sky transparency in [0, 1] for wavelength in [m]"""
wavelength = wavelength / 10**-9
idx = numpy.argmin(numpy.abs(
data_transparency['wavelength'] * 1000 - wavelength))
return data_transparency['fraction'][idx] | 17,614 |
def define_color_dict_for_file_extensions(df, create_map):
"""
Defines a color mapping for file extensions. If create_map is true, it
creates a new map; otherwise it reads an existing file.
:param df (DataFrame): A DataFrame object.
:param create_map (boolean): True to create a new map; False to rea... | 17,615 |
def invert_indices(indices: Iterable[int], size: int) -> Iterator[int]:
"""
Returns the indices that are not in the given indices, up to the given size.
:param indices: The indices to invert.
:param size: The exclusive maximum index.
:return: A inverted indices.
"""
in... | 17,616 |
def split_fortran_files(source_dir, subroutines=None):
"""Split each file in `source_dir` into separate files per subroutine.
Parameters
----------
source_dir : str
Full path to directory in which sources to be split are located.
subroutines : list of str, optional
Subroutines to sp... | 17,617 |
def readcsv(self):
"""
Load the whole csv file and make bar charts for language prevalence and program type.
Codes for making bar chat came from here:
https://stackoverflow.com/questions/19198920/using-counter-in-python-to-build-histogram
"""
# Load the whole csv file.
df = pd.read_cs... | 17,618 |
def selection_error_message():
"""Displays error message if permutations or combinatons checkbuttons state is not active"""
if permutations_checkbox_value.get() == 0 and combinations_checkbox_value.get() == 0 and repeat_checkbox_value.get() == 0 or 1:
messagebox.showerror('User Error', 'Please select Co... | 17,619 |
def parse_all_moves(moves_string):
""" Parse a move string """
moves = []
if not moves_string:
raise ValueError("No Moves Given")
moves_strings = moves_string.split(" ")
for move_string in moves_strings:
move = CubeMove.parse(move_string)
moves.append(move)
return moves | 17,620 |
def merge_samples(samples, nchannels, weight_table=None):
"""
Merges two samples
:param samples: the samples, must have the same sample rate and channel count
:param nchannels: the number of channels
:param weight_table: adds a specific weight to each sample when merging the sound
:return: the m... | 17,621 |
def update_presence():
"""Update presence in Discord
:returns: TODO
"""
activity = base_activity
filename = get_filename()
extension = get_extension()
if filename:
activity['details'] = f"Editing {filename}"
activity['assets']['large_text'] = f"Editing a .{get_extension()} ... | 17,622 |
def get_spam_info(msg: Message, max_score=None) -> (bool, str):
"""parse SpamAssassin header to detect whether a message is classified as spam.
Return (is spam, spam status detail)
The header format is
```X-Spam-Status: No, score=-0.1 required=5.0 tests=DKIM_SIGNED,DKIM_VALID,
DKIM_VALID_AU,RC... | 17,623 |
def _check(isamAppliance, id=None):
"""
Check if the last created user has the exact same id or id exists
:param isamAppliance:
:param comment:
:return:
"""
ret_obj = get_all(isamAppliance)
if id != None:
for users in ret_obj['data']:
if users['id'] == id:
... | 17,624 |
def plot_week_timeseries(time, value, normalise=True,
label=None, h=0.85, value2=None,
label2=None, daynames=None,
xfmt="%1.0f", ax=None):
"""
Shows a timeseries dispatched by days as bars.
@param time dates
@param ... | 17,625 |
def plot_boxes_on_image(image, boxes, color=(0,255,255), thickness=2):
"""
Plot the boxes onto the image.
For the boxes a center, size representation is expected: [cx, cy, w, h].
:param image: The image onto which to draw.
:param boxes: The boxes which shall be plotted.
:return: An image with ... | 17,626 |
def get_text(markup: str) -> str:
"""Remove html tags, URLs and spaces using regexp"""
text = re.sub(r"<.*?>", "", markup)
url_pattern = r"(http|ftp)s?://(?:[a-zA-Z]|[0-9]|[$-_@.&#+]|[!*\(\),]|\
(?:%[0-9a-fA-F][0-9a-fA-F]))+"
text = re.sub(url_pattern, "", text)
text = re.sub(r"\s... | 17,627 |
def intercept_channel(channel, *interceptors):
"""Intercepts a channel through a set of interceptors.
This is an EXPERIMENTAL API.
Args:
channel: A Channel.
interceptors: Zero or more objects of type
UnaryUnaryClientInterceptor,
UnaryStreamClientInterceptor,
StreamUnary... | 17,628 |
def create_static_ip(compute, project, region, name):
"""Create global static IP
:param compute: GCE compute resource object using googleapiclient.discovery
:param project: string, GCE Project Id
:param region: string, GCE region
:param name: string, Static IP name
:return: Operation informatio... | 17,629 |
def stream_trec07p(dataset_path):
"""2007 TREC’s Spam Track dataset.
The data contains 75,419 chronologically ordered items, i.e. 3 months of emails delivered
to a particular server in 2007. Spam messages represent 66.6% of the dataset.
The goal is to predict whether an email is a spam or not.
Par... | 17,630 |
def ctc_loss(encoder_outputs, labels, frame_lens, label_lens, reduction, device):
"""
All sorts of stupid restrictions from documentation:
In order to use CuDNN, the following must be satisfied:
1. targets must be in concatenated format,
2. all input_lengths must be T.
3. blank=0
4. target_... | 17,631 |
def expand_parameters(host, params):
"""Expand parameters in hostname.
Examples:
* "target{N}" => "target1"
* "{host}.{domain} => "host01.example.com"
"""
pattern = r"\{(.*?)\}"
def repl(match):
param_name = match.group(1)
return params[param_name]
return re.sub(patte... | 17,632 |
def p_term(p):
"""term : factor snp_check_precedence_and_create_quadruple_for_op term1""" | 17,633 |
def search_s1(saturation, size, startTime):
"""
First stage for sequential adsorption.
Returns list of circles, current saturation, list of times and list
of saturations.
Keyword arguments:
size -- radius of single circle
saturation -- max saturation
startTime -- start tim... | 17,634 |
def draw_labeled_bounding_boxes(img, labeled_frame, num_objects):
"""
Starting from labeled regions, draw enclosing rectangles in the original color frame.
"""
# Iterate through all detected cars
for car_number in range(1, num_objects + 1):
# Find pixels with each car_number label value
... | 17,635 |
def add_scalebar(
x_units=None,
y_units=None,
anchor=(0.98, 0.02),
x_size=None,
y_size=None,
y_label_space=0.02,
x_label_space=-0.02,
bar_space=0.06,
x_on_left=True,
linewidth=3,
remove_frame=True,
omit_x=False,
omit_y=False,
round=True,
usetex=True,
ax=No... | 17,636 |
def test_config_slack_handler_default_error(monkeypatch):
"""Tests setting the slack handler channel to 'default' raised error.
"""
monkeypatch.setenv('LOGGING_CONFIG_FILE', 'logging_config_slack_default.json')
config_dir = os.path.dirname(__file__)
with pytest.raises(ValueError):
_ = Slack... | 17,637 |
def retweet_fun():
"""
Retweets if there are any particular hastags.
"""
retweet_fav_post(api) | 17,638 |
def get_checks(cur, table):
"""
Gets CHECK constraints for a table, adding them to the table.
:param cur: A cursor to execute commands on.
:param table: The table to get CHECKs for.
"""
cur.execute(f"""select oid, conname, consrc, pg_get_constraintdef(oid)
from pg_constraint
where conrelid = {t... | 17,639 |
def sigint_handler(*args):
"""Handler for the SIGINT signal."""
pg.exit()
exit(0) | 17,640 |
def _skip_comments_and_whitespace(lines, idx):
###############################################################################
"""
Starting at idx, return next valid idx of lines that contains real data
"""
if (idx == len(lines)):
return idx
comment_re = re.compile(r'^[#!]')
lines_slic... | 17,641 |
def load_scalar_attributes(mapper, state, attribute_names):
"""initiate a column-based attribute refresh operation."""
# assert mapper is _state_mapper(state)
session = state.session
if not session:
raise orm_exc.DetachedInstanceError(
"Instance %s is not bound to a Session; "
... | 17,642 |
def named_payload(name, parser_fn):
"""Wraps a parser result in a dictionary under given name."""
return lambda obj: {name: parser_fn(obj)} | 17,643 |
def action_train_protocol(sentence, Train=True):
"""function to train the action prediction model"""
if Train:
training_data = []
with open('datasets/action_dataset.json') as data_file:
data = json.load(data_file)
for line in data:
#fetching training data
... | 17,644 |
def commonModeCSPAD2x2(evt, type, key, mask=None):
"""Subtraction of common mode using median value of masked pixels (left and right half of detector are treated separately).
Adds a record ``evt["analysis"]["cm_corrected - " + key]``.
Args:
:evt: The event variable
:type(str): The ... | 17,645 |
def _SoftmaxCrossEntropyWithLogitsGrad(op, grad_loss, grad_grad):
"""Gradient function for SoftmaxCrossEntropyWithLogits."""
# grad_loss is the backprop for cost, and we multiply it with the gradients
# (which is output[1])
# grad_grad is the backprop for softmax gradient.
#
# Second derivative is just soft... | 17,646 |
def assign_coord_ip_addresses(topo: Topology) -> None:
"""Assigns IP addresses for communication between coordinator, other control services and ASes.
:param topo: Topology with a coordinator. No IP addresses must be assigned yet in the
coordinator's network.
"""
bridge = topo.coordina... | 17,647 |
def prod_finished(job):
"""Check if prod stage is finished."""
try:
step = "prod" + str(job.doc.prod_replicates_done - 1)
except (KeyError, AttributeError):
step = "prod" + "0"
run_file = job.ws + "/run.{}".format(step)
if job.isfile("run.{}".format(step)):
with open(run_fil... | 17,648 |
def PrimaryCaps(layer_input, name, dim_capsule, channels, kernel_size=9, strides=2, padding='valid'):
""" PrimaryCaps layer can be seen as a convolutional layer with a different
activation function (squashing)
:param layer_input
:param name
:param dim_capsule
:param channel... | 17,649 |
async def create_log_file(nats_handler, shared_storage, logger):
"""
Creates CSV for logger outputs
Args:
nats_handler (NatsHandler): NatsHandler used to interact with NATS
shared_storage (dict): Dictionary to persist memory across callbacks
logger (JSONLogger): Logger that can be ... | 17,650 |
def get_font(args):
"""
Gets a font.
:param args: Arguments (ttf and ttfsize).
:return: Font.
"""
try:
return ImageFont.truetype(args.ttf, args.ttfsize)
except:
return ImageFont.load_default() | 17,651 |
def zeros(shape):
"""
Creates and returns a new array with the given shape which is filled with zeros.
"""
mat = empty(shape)
return fill(mat, 0.0) | 17,652 |
def unpack_puzzle_input(dir_file: str) -> tuple[list, list]:
"""
Args:
dir_file (str): location of .txt file to pull data from
Returns:
bingo numbers and bingo cards in list format
"""
with open(dir_file, "r") as file:
content = file.read().splitlines()
bingo_number... | 17,653 |
def blank_response():
"""Fixture that constructs a response with a blank body."""
return build_response(data="") | 17,654 |
def dense_image_warp(image:torch.Tensor, flow:torch.Tensor) -> torch.Tensor:
"""Image warping using per-pixel flow vectors.
See [1] for the original reference (Note that the tensor shape is different, etc.).
[1] https://www.tensorflow.org/addons/api_docs/python/tfa/image/dense_image_warp
Parameters
... | 17,655 |
def test_registration_of_action_on_pointer_of_pointer(workers):
"""
Ensure actions along a chain of pointers are registered as expected.
"""
bob = workers["bob"]
alice = workers["alice"]
tensor = torch.tensor([1, 2, 3, 4.0])
ptr = tensor.send(bob)
ptr = ptr.send(alice)
ptr_action = ... | 17,656 |
def validateRange(rangeStr : str) -> bool:
"""Validates the range argument"""
# type cast and compare
try:
# get range indices
ranges = rangeStr.split(",", 1)
rangeFrom = 0 if ranges[0] == "" else int(ranges[0])
rangeTo = 0 if ranges[1] == "" else int(ranges[1])
# ... | 17,657 |
def update_log_ip_dict_per_ingress_egress_point(flow_ingress_asn, flow_ip, origin_asn, ip_prefix, country_code, flow_bytes, flow_packets, d_ipsrc_level_analysis_perpoint):
"""
Account for unique IPAddresses, BGP prefixes, origin_asn per ingress/egress points.
:param flow_ingress_asn:
:param flow_ip:
... | 17,658 |
def _config_from_file(configfile):
"""Return a dict containing all of the config values found in the given
configfile.
"""
conf = {}
# set from config if possible
if configfile:
with open(configfile, 'r') as fp:
config_yaml = yaml.load(fp)
conf = config_yaml
... | 17,659 |
def error(bot, context, wut):
"""Log Errors caused by Updates."""
print(wut)
logger.warning('Update "%s" caused error "%s"', bot, context.error) | 17,660 |
def odr_planar_fit(points, rand_3_estimate=False):
"""
Fit a plane to 3d points.
Orthogonal distance regression is performed using the odrpack.
Parameters
----------
points : list of [x, y, z] points
rand_3_estimate : bool, optional
First estimation of the plane using 3 random poin... | 17,661 |
def adjust_learning_rate_lrstep(epoch, opt):
"""Sets the learning rate to the initial LR decayed by decay rate every steep step"""
steps = np.sum(epoch > np.asarray(opt.lr_decay_epochs))
if steps > 0:
new_lr = opt.lr_init * (opt.lr_decay_rate ** steps)
return new_lr
return opt.lr_init | 17,662 |
def set_sock_quickack(sock):
"""
open quickack for the socket
I.g.
::
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
"""
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
try:
sock.setso... | 17,663 |
def subplot(n, m, k):
"""
Create a subplot command
Example::
import numpy as np
x = np.linspace(-5, 5, 1000)
figure(1)
subplot(2, 1, 1)
plot(x, np.sin(x), "r+")
subplot(2, 1, 2)
plot(x, np.cos(x), "g-")
show()
"""
global _current_... | 17,664 |
def _create_gdcm_image(src: bytes, **kwargs: Any) -> "gdcm.Image":
"""Return a gdcm.Image from the `src`.
Parameters
----------
src : bytes
The raw image frame data to be encoded.
**kwargs
Required parameters:
* `rows`: int
* `columns`: int
* `samples_per_pi... | 17,665 |
def parallel_upload_chunks(vol, files, bin_paths, chunk_size, num_workers):
"""Push tif images as chunks in CloudVolume object in Parallel
Arguments:
vol {cloudvolume.CloudVolume} -- volume that will contain image data
files {list} -- strings of tif image filepaths
bin_paths {list} -- b... | 17,666 |
def _4_graphlet_contains_3star(adj_mat):
"""Check if a given graphlet of size 4 contains a 3-star"""
return (4 in [a.sum() for a in adj_mat]) | 17,667 |
def _one_day(args):
"""Prompts for index file update
`_need_to_index` has already filtered jpg preferred over other
formats, that is, if there is a duplicate name, it will list the
jpg, not the arw, pcd, etc. in the index.
Args:
args (list): files to index
"""
def _extract_jpg(ima... | 17,668 |
def af4_path() -> Path:
"""Return the abspath of Go bio-target-rna-fusion binary. Builds the binary if necessary"""
global AF4_PATH
if not AF4_PATH:
af4_label = "//go/src/github.com/grailbio/bio/cmd/bio-fusion"
build([af4_label])
AF4_PATH = go_executable(af4_label)
return AF4_PAT... | 17,669 |
def get_sentence_content(sentence_token):
"""Extrac sentence string from list of token in present in sentence
Args:
sentence_token (tuple): contains length of sentence and list of all the token in sentence
Returns:
str: setence string
"""
sentence_content = ''
for word in sente... | 17,670 |
def timestamp_error(item: SensorItem):
"""this function fixes an error when timestamp is logged in a smaller unit then seconds."""
if float(item.timestamp) / 3600 * 24 * 356 > 2019 and \
"." not in str(item.timestamp) and \
len(str(item.timestamp)) > 10:
# this bug has fixed in 2... | 17,671 |
def _parse_filename(filename):
"""Parse meta-information from given filename.
Parameters
----------
filename : str
A Market 1501 image filename.
Returns
-------
(int, int, str, str) | NoneType
Returns a tuple with the following entries:
* Unique ID of the individua... | 17,672 |
def sequence_generator(data, look_back = 50):
"""\
Description:
------------
Input data for LSTM: Convert to user trajectory (maximum length: look back)
"""
train,test, valid = [],[],[]
unique_users = set(data[:,0])
items_per_user = {int(user):[0 for i in range(look_back)] for user... | 17,673 |
def prefit_clf__svm(gamma: float = 0.001) -> base.ClassifierMixin:
"""Returns an unfitted SVM classifier object.
:param gamma: ...
:return:
"""
return svm.SVC(gamma=gamma) | 17,674 |
def option_not_exist_msg(option_name, existing_options):
""" Someone is referencing an option that is not available in the current package
options
"""
result = ["'options.%s' doesn't exist" % option_name]
result.append("Possible options are %s" % existing_options or "none")
return "\n".join(resu... | 17,675 |
def ConverterCommand(options):
"""Convert the default probe statements to project specific statements."""
probe_statement_path = hwid_utils.GetProbeStatementPath(options.project)
converted_results_obj = converter.ConvertToProbeStatement(
options.database, probe_statement_path)
converted_results_data = jso... | 17,676 |
def elslib_CylinderD2(*args):
"""
:param U:
:type U: float
:param V:
:type V: float
:param Pos:
:type Pos: gp_Ax3
:param Radius:
:type Radius: float
:param P:
:type P: gp_Pnt
:param Vu:
:type Vu: gp_Vec
:param Vv:
:type Vv: gp_Vec
:param Vuu:
:type Vuu: ... | 17,677 |
def cmorization(in_dir, out_dir, cfg, _):
"""Cmorization func call."""
cmor_table = cfg['cmor_table']
glob_attrs = cfg['attributes']
# run the cmorization
for var, vals in cfg['variables'].items():
in_files = collect_files(in_dir, var, cfg)
logger.info("CMORizing var %s from input s... | 17,678 |
def main() -> None:
"""Interactive use of task scheduler implementation."""
try:
scheduler = data_input()
result_output(scheduler=scheduler)
except KeyboardInterrupt:
pass | 17,679 |
def get_version_message(version: str):
"""Get the message for the zygrader version from the changelog"""
changelog = load_changelog()
msg = [f"zygrader version {version}", ""]
version_index = 0
for line in changelog:
if line == version:
version_index = changelog.index(line) + 1... | 17,680 |
def handle_right(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negative of the speed in the right entry box.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: ... | 17,681 |
def get_arity(p, b_addr):
"""
Retrieves the arity by inspecting a funciton call
:param p: angr project
:param b_addr: basic block address
:return: arity of the function
"""
return len(get_ord_arguments_call(p, b_addr)) | 17,682 |
def draw_des3_plot():
"""
This function is to draw the plot of DES 3.
"""
objects = ('Singapore', 'Uruguay', 'Chile', 'Belgium', 'Denmark', 'Qatar', 'Portugal', 'Canada', 'Spain', 'Ireland')
y_pos = np.arange(len(objects))
performance = [71, 69, 68, 66, 65, 65, 64, 63, 63, 62]
plt.xkcd()
... | 17,683 |
def main():
"""
This function will use various utility functions, classes, and methods to determine
the location of two Resistance members: Rey and Chewbacca. Nothing is returned from
this function, however a file <updated_information.json> is produced.
Parameters:
None
Returns:
... | 17,684 |
def get_pi_id(rc):
"""
Gets the database id of the group PI
Parameters
----------
rc: runcontrol object
The runcontrol object. It must contain the 'groups' and 'people'
collections in the needed databases
Returns
-------
The database '_id' of the group PI
"""
grou... | 17,685 |
def gather_from_processes(chunk, split_sizes, displacements, comm=MPI.COMM_WORLD):
"""Gather data chunks on rank zero
:param chunk: Data chunks, living on ranks 0, 1, ..., comm.size-1
:type chunk: np.ndarray
:param split_sizes: Chunk lenghts on individual ranks
:type split_sizes: np.ndarray
:pa... | 17,686 |
def pluginExists(name):
"""pluginExists(name) -> True if found, or False if not.
This function is the same as load(), but only checks for the existence of a plugin rather than loading it.
If there is no slash in the name then the pluginPath() is searched for it. If there is a slash then the name is... | 17,687 |
def test_deep_nested_env_no_merge_databag():
"""merge flag is honored"""
data = api.get_env_databag(root_dir, False, "dev/special")
logger.debug(data)
assert data.get("new_value") is None
assert data.get("common_value") is None
assert data.get("special_value") == "special"
assert api.get_out... | 17,688 |
async def publish_file_as_upload(
background_tasks: BackgroundTasks, file_data: UploadFile = File(...)
) -> tp.Union[IpfsPublishResponse, GenericResponse]:
"""
Publish file to IPFS using local node (if enabled by config) and / or pin to Pinata pinning cloud (if enabled by config).
File is accepted as a... | 17,689 |
def edit_collab() :
"""
Endpoint to edit a specified collaboration's member variables. This endpoint requires the requesting user to be an
authenticated user to properly function.
Request Body Parameters:
id: string, JSON, required
owner: string, JSON, optional
size: int, JSON, ... | 17,690 |
def create_lkas_ui(packer, main_on, enabled, steer_alert, defog, ahbc, ahbcramping, config, noipma, stats, persipma, dasdsply, x30, daschime, lines):
"""Creates a CAN message for the Ford Steer Ui."""
values = {
"PersIndexIpma_D_Actl": persipma,
"DasStats_D_Dsply": dasdsply,
"Set_Me_X30": x30,
"Lin... | 17,691 |
def unique(seq, key=identity):
""" Return only unique elements of a sequence
>>> tuple(unique((1, 2, 3)))
(1, 2, 3)
>>> tuple(unique((1, 2, 1, 3)))
(1, 2, 3)
Uniqueness can be defined by key keyword
>>> tuple(unique(['cat', 'mouse', 'dog', 'hen'], key=len))
('cat', 'mouse')
"""
... | 17,692 |
def test_validation(celery_app):
"""Task and shared task decorators must check required `Injector`
attributes."""
with pytest.raises(DependencyError) as exc_info:
@contrib.task
class Container1(Injector):
name = "foo.bar.baz"
run = lambda: None # noqa: E731
me... | 17,693 |
def _contextual_loss(x, y, reduction='mean'):
"""Contextual loss
"""
loss = -torch.log(_contextual_similarity(x, y))
if reduction == 'mean':
loss = loss.mean()
return loss | 17,694 |
def _actual_center(pos, angle):
"""
Calculate the position of the geometric center of the agent
The value of self.cur_pos is the center of rotation.
"""
dir_vec = get_dir_vec(angle)
return pos + (CAMERA_FORWARD_DIST - (ROBOT_LENGTH / 2)) * dir_vec | 17,695 |
def load_one_batch_mnist(batch_size=64, shuffle=True):
"""Return a single batch (inputs, labels) of MNIST data."""
dataloader = get_mnist_dataloder(batch_size, shuffle)
X, y = next(iter(dataloader))
return X, y | 17,696 |
def replace_math_functions(input_string):
""" FIXME: Temporarily replace std:: invocations of math functions with non-std:: versions to prevent linker errors
NOTE: This can lead to correctness issues when running tests, since the correct version of the math function (exp/expf) might not get called.
... | 17,697 |
def __validate_id_key(self, key, value):
"""Shorthand function to validate ID keys."""
test_object = db.get_object_as_dict_by_id(value)
if not test_object:
raise TypeError("No object with the ID given in the key '" + key + "' was found. (" + value + ")")
elif self.id_key_types[key] != "any" and not test_object['o... | 17,698 |
def KmeansInterCompare(k, data, nbTests):
"""Réalisation d'un nombre donné de classification Kmeans.
Le meilleur résultat selon le critère d'inertie inter-groupe est affiché"""
KmeansResults = []
for i in range(0, nbTests):
KmeansResults.append(Kmeans(k, data))
# on maximise l'inertie inter... | 17,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.