max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
815 | <gh_stars>100-1000
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import contextlib
from typing import Optional, Sequence, Tuple, Union
import numpy as np
import torch
@contextlib.contextmanager
def temp_seed(rng: np.random.RandomState, seed: Optional[Union[int, Tuple[int, ...]]]):
"""A context manager for temporarily adjusting the random seed."""
if seed is None:
try:
yield
finally:
pass
else:
state = rng.get_state()
rng.seed(seed)
try:
yield
finally:
rng.set_state(state)
class MaskFunc:
"""
An object for GRAPPA-style sampling masks.
This crates a sampling mask that densely samples the center while
subsampling outer k-space regions based on the undersampling factor.
When called, ``MaskFunc`` uses internal functions create mask by 1)
creating a mask for the k-space center, 2) create a mask outside of the
k-space center, and 3) combining them into a total mask. The internals are
handled by ``sample_mask``, which calls ``calculate_center_mask`` for (1)
and ``calculate_acceleration_mask`` for (2). The combination is executed
in the ``MaskFunc`` ``__call__`` function.
If you would like to implement a new mask, simply subclass ``MaskFunc``
and overwrite the ``sample_mask`` logic. See examples in ``RandomMaskFunc``
and ``EquispacedMaskFunc``.
"""
def __init__(
self,
center_fractions: Sequence[float],
accelerations: Sequence[int],
allow_any_combination: bool = False,
seed: Optional[int] = None,
):
"""
Args:
center_fractions: Fraction of low-frequency columns to be retained.
If multiple values are provided, then one of these numbers is
chosen uniformly each time.
accelerations: Amount of under-sampling. This should have the same
length as center_fractions. If multiple values are provided,
then one of these is chosen uniformly each time.
allow_any_combination: Whether to allow cross combinations of
elements from ``center_fractions`` and ``accelerations``.
seed: Seed for starting the internal random number generator of the
``MaskFunc``.
"""
if len(center_fractions) != len(accelerations) and not allow_any_combination:
raise ValueError(
"Number of center fractions should match number of accelerations "
"if allow_any_combination is False."
)
self.center_fractions = center_fractions
self.accelerations = accelerations
self.allow_any_combination = allow_any_combination
self.rng = np.random.RandomState(seed)
def __call__(
self,
shape: Sequence[int],
offset: Optional[int] = None,
seed: Optional[Union[int, Tuple[int, ...]]] = None,
) -> Tuple[torch.Tensor, int]:
"""
Sample and return a k-space mask.
Args:
shape: Shape of k-space.
offset: Offset from 0 to begin mask (for equispaced masks). If no
offset is given, then one is selected randomly.
seed: Seed for random number generator for reproducibility.
Returns:
A 2-tuple containing 1) the k-space mask and 2) the number of
center frequency lines.
"""
if len(shape) < 3:
raise ValueError("Shape should have 3 or more dimensions")
with temp_seed(self.rng, seed):
center_mask, accel_mask, num_low_frequencies = self.sample_mask(
shape, offset
)
# combine masks together
return torch.max(center_mask, accel_mask), num_low_frequencies
def sample_mask(
self,
shape: Sequence[int],
offset: Optional[int],
) -> Tuple[torch.Tensor, torch.Tensor, int]:
"""
Sample a new k-space mask.
This function samples and returns two components of a k-space mask: 1)
the center mask (e.g., for sensitivity map calculation) and 2) the
acceleration mask (for the edge of k-space). Both of these masks, as
well as the integer of low frequency samples, are returned.
Args:
shape: Shape of the k-space to subsample.
offset: Offset from 0 to begin mask (for equispaced masks).
Returns:
A 3-tuple contaiing 1) the mask for the center of k-space, 2) the
mask for the high frequencies of k-space, and 3) the integer count
of low frequency samples.
"""
num_cols = shape[-2]
center_fraction, acceleration = self.choose_acceleration()
num_low_frequencies = round(num_cols * center_fraction)
center_mask = self.reshape_mask(
self.calculate_center_mask(shape, num_low_frequencies), shape
)
acceleration_mask = self.reshape_mask(
self.calculate_acceleration_mask(
num_cols, acceleration, offset, num_low_frequencies
),
shape,
)
return center_mask, acceleration_mask, num_low_frequencies
def reshape_mask(self, mask: np.ndarray, shape: Sequence[int]) -> torch.Tensor:
"""Reshape mask to desired output shape."""
num_cols = shape[-2]
mask_shape = [1 for _ in shape]
mask_shape[-2] = num_cols
return torch.from_numpy(mask.reshape(*mask_shape).astype(np.float32))
def calculate_acceleration_mask(
self,
num_cols: int,
acceleration: int,
offset: Optional[int],
num_low_frequencies: int,
) -> np.ndarray:
"""
Produce mask for non-central acceleration lines.
Args:
num_cols: Number of columns of k-space (2D subsampling).
acceleration: Desired acceleration rate.
offset: Offset from 0 to begin masking (for equispaced masks).
num_low_frequencies: Integer count of low-frequency lines sampled.
Returns:
A mask for the high spatial frequencies of k-space.
"""
raise NotImplementedError
def calculate_center_mask(
self, shape: Sequence[int], num_low_freqs: int
) -> np.ndarray:
"""
Build center mask based on number of low frequencies.
Args:
shape: Shape of k-space to mask.
num_low_freqs: Number of low-frequency lines to sample.
Returns:
A mask for hte low spatial frequencies of k-space.
"""
num_cols = shape[-2]
mask = np.zeros(num_cols, dtype=np.float32)
pad = (num_cols - num_low_freqs + 1) // 2
mask[pad : pad + num_low_freqs] = 1
assert mask.sum() == num_low_freqs
return mask
def choose_acceleration(self):
"""Choose acceleration based on class parameters."""
if self.allow_any_combination:
return self.rng.choice(self.center_fractions), self.rng.choice(
self.accelerations
)
else:
choice = self.rng.randint(len(self.center_fractions))
return self.center_fractions[choice], self.accelerations[choice]
class RandomMaskFunc(MaskFunc):
"""
Creates a random sub-sampling mask of a given shape.
The mask selects a subset of columns from the input k-space data. If the
k-space data has N columns, the mask picks out:
1. N_low_freqs = (N * center_fraction) columns in the center
corresponding to low-frequencies.
2. The other columns are selected uniformly at random with a
probability equal to: prob = (N / acceleration - N_low_freqs) /
(N - N_low_freqs). This ensures that the expected number of columns
selected is equal to (N / acceleration).
It is possible to use multiple center_fractions and accelerations, in which
case one possible (center_fraction, acceleration) is chosen uniformly at
random each time the ``RandomMaskFunc`` object is called.
For example, if accelerations = [4, 8] and center_fractions = [0.08, 0.04],
then there is a 50% probability that 4-fold acceleration with 8% center
fraction is selected and a 50% probability that 8-fold acceleration with 4%
center fraction is selected.
"""
def calculate_acceleration_mask(
self,
num_cols: int,
acceleration: int,
offset: Optional[int],
num_low_frequencies: int,
) -> np.ndarray:
prob = (num_cols / acceleration - num_low_frequencies) / (
num_cols - num_low_frequencies
)
return self.rng.uniform(size=num_cols) < prob
class EquiSpacedMaskFunc(MaskFunc):
"""
Sample data with equally-spaced k-space lines.
The lines are spaced exactly evenly, as is done in standard GRAPPA-style
acquisitions. This means that with a densely-sampled center,
``acceleration`` will be greater than the true acceleration rate.
"""
def calculate_acceleration_mask(
self,
num_cols: int,
acceleration: int,
offset: Optional[int],
num_low_frequencies: int,
) -> np.ndarray:
"""
Produce mask for non-central acceleration lines.
Args:
num_cols: Number of columns of k-space (2D subsampling).
acceleration: Desired acceleration rate.
offset: Offset from 0 to begin masking. If no offset is specified,
then one is selected randomly.
num_low_frequencies: Not used.
Returns:
A mask for the high spatial frequencies of k-space.
"""
if offset is None:
offset = self.rng.randint(0, high=round(acceleration))
mask = np.zeros(num_cols, dtype=np.float32)
mask[offset::acceleration] = 1
return mask
class EquispacedMaskFractionFunc(MaskFunc):
"""
Equispaced mask with exact acceleration matching.
The mask selects a subset of columns from the input k-space data. If the
k-space data has N columns, the mask picks out:
1. N_low_freqs = (N * center_fraction) columns in the center
corresponding tovlow-frequencies.
2. The other columns are selected with equal spacing at a proportion
that reaches the desired acceleration rate taking into consideration
the number of low frequencies. This ensures that the expected number
of columns selected is equal to (N / acceleration)
It is possible to use multiple center_fractions and accelerations, in which
case one possible (center_fraction, acceleration) is chosen uniformly at
random each time the EquispacedMaskFunc object is called.
Note that this function may not give equispaced samples (documented in
https://github.com/facebookresearch/fastMRI/issues/54), which will require
modifications to standard GRAPPA approaches. Nonetheless, this aspect of
the function has been preserved to match the public multicoil data.
"""
def calculate_acceleration_mask(
self,
num_cols: int,
acceleration: int,
offset: Optional[int],
num_low_frequencies: int,
) -> np.ndarray:
"""
Produce mask for non-central acceleration lines.
Args:
num_cols: Number of columns of k-space (2D subsampling).
acceleration: Desired acceleration rate.
offset: Offset from 0 to begin masking. If no offset is specified,
then one is selected randomly.
num_low_frequencies: Number of low frequencies. Used to adjust mask
to exactly match the target acceleration.
Returns:
A mask for the high spatial frequencies of k-space.
"""
# determine acceleration rate by adjusting for the number of low frequencies
adjusted_accel = (acceleration * (num_low_frequencies - num_cols)) / (
num_low_frequencies * acceleration - num_cols
)
if offset is None:
offset = self.rng.randint(0, high=round(adjusted_accel))
mask = np.zeros(num_cols)
accel_samples = np.arange(offset, num_cols - 1, adjusted_accel)
accel_samples = np.around(accel_samples).astype(np.uint)
mask[accel_samples] = 1.0
return mask
class MagicMaskFunc(MaskFunc):
"""
Masking function for exploiting conjugate symmetry via offset-sampling.
This function applies the mask described in the following paper:
<NAME>. (2019). Offset Sampling Improves Deep Learning based
Accelerated MRI Reconstructions by Exploiting Symmetry. arXiv preprint,
arXiv:1912.01101.
It is essentially an equispaced mask with an offset for the opposite site
of k-space. Since MRI images often exhibit approximate conjugate k-space
symmetry, this mask is generally more efficient than a standard equispaced
mask.
Similarly to ``EquispacedMaskFunc``, this mask will usually undereshoot the
target acceleration rate.
"""
def calculate_acceleration_mask(
self,
num_cols: int,
acceleration: int,
offset: Optional[int],
num_low_frequencies: int,
) -> np.ndarray:
"""
Produce mask for non-central acceleration lines.
Args:
num_cols: Number of columns of k-space (2D subsampling).
acceleration: Desired acceleration rate.
offset: Offset from 0 to begin masking. If no offset is specified,
then one is selected randomly.
num_low_frequencies: Not used.
Returns:
A mask for the high spatial frequencies of k-space.
"""
if offset is None:
offset = self.rng.randint(0, high=acceleration)
if offset % 2 == 0:
offset_pos = offset + 1
offset_neg = offset + 2
else:
offset_pos = offset - 1 + 3
offset_neg = offset - 1 + 0
poslen = (num_cols + 1) // 2
neglen = num_cols - (num_cols + 1) // 2
mask_positive = np.zeros(poslen, dtype=np.float32)
mask_negative = np.zeros(neglen, dtype=np.float32)
mask_positive[offset_pos::acceleration] = 1
mask_negative[offset_neg::acceleration] = 1
mask_negative = np.flip(mask_negative)
mask = np.concatenate((mask_positive, mask_negative))
return np.fft.fftshift(mask) # shift mask and return
class MagicMaskFractionFunc(MagicMaskFunc):
"""
Masking function for exploiting conjugate symmetry via offset-sampling.
This function applies the mask described in the following paper:
<NAME>. (2019). Offset Sampling Improves Deep Learning based
Accelerated MRI Reconstructions by Exploiting Symmetry. arXiv preprint,
arXiv:1912.01101.
It is essentially an equispaced mask with an offset for the opposite site
of k-space. Since MRI images often exhibit approximate conjugate k-space
symmetry, this mask is generally more efficient than a standard equispaced
mask.
Similarly to ``EquispacedMaskFractionFunc``, this method exactly matches
the target acceleration by adjusting the offsets.
"""
def sample_mask(
self,
shape: Sequence[int],
offset: Optional[int],
) -> Tuple[torch.Tensor, torch.Tensor, int]:
"""
Sample a new k-space mask.
This function samples and returns two components of a k-space mask: 1)
the center mask (e.g., for sensitivity map calculation) and 2) the
acceleration mask (for the edge of k-space). Both of these masks, as
well as the integer of low frequency samples, are returned.
Args:
shape: Shape of the k-space to subsample.
offset: Offset from 0 to begin mask (for equispaced masks).
Returns:
A 3-tuple contaiing 1) the mask for the center of k-space, 2) the
mask for the high frequencies of k-space, and 3) the integer count
of low frequency samples.
"""
num_cols = shape[-2]
fraction_low_freqs, acceleration = self.choose_acceleration()
num_cols = shape[-2]
num_low_frequencies = round(num_cols * fraction_low_freqs)
# bound the number of low frequencies between 1 and target columns
target_columns_to_sample = round(num_cols / acceleration)
num_low_frequencies = max(min(num_low_frequencies, target_columns_to_sample), 1)
# adjust acceleration rate based on target acceleration.
adjusted_target_columns_to_sample = (
target_columns_to_sample - num_low_frequencies
)
adjusted_acceleration = 0
if adjusted_target_columns_to_sample > 0:
adjusted_acceleration = round(num_cols / adjusted_target_columns_to_sample)
center_mask = self.reshape_mask(
self.calculate_center_mask(shape, num_low_frequencies), shape
)
accel_mask = self.reshape_mask(
self.calculate_acceleration_mask(
num_cols, adjusted_acceleration, offset, num_low_frequencies
),
shape,
)
return center_mask, accel_mask, num_low_frequencies
def create_mask_for_mask_type(
mask_type_str: str,
center_fractions: Sequence[float],
accelerations: Sequence[int],
) -> MaskFunc:
"""
Creates a mask of the specified type.
Args:
center_fractions: What fraction of the center of k-space to include.
accelerations: What accelerations to apply.
Returns:
A mask func for the target mask type.
"""
if mask_type_str == "random":
return RandomMaskFunc(center_fractions, accelerations)
elif mask_type_str == "equispaced":
return EquiSpacedMaskFunc(center_fractions, accelerations)
elif mask_type_str == "equispaced_fraction":
return EquispacedMaskFractionFunc(center_fractions, accelerations)
elif mask_type_str == "magic":
return MagicMaskFunc(center_fractions, accelerations)
elif mask_type_str == "magic_fraction":
return MagicMaskFractionFunc(center_fractions, accelerations)
else:
raise ValueError(f"{mask_type_str} not supported")
| 7,427 |
661 | <gh_stars>100-1000
from .resnet import *
from .efficientnet import *
from .mobilenet import *
from .effnet import *
from .shufflenet import *
from .densenet import *
from .inception_v2 import InceptionV2
from .darknet import *
from .regnet import * | 82 |
2,609 | <reponame>vuvdoan/mockoon
{
"welcomeShown": true,
"analytics": true,
"logSizeLimit": 10000,
"maxLogsPerEnvironment": 50,
"truncateRouteName": true,
"environmentMenuSize": 100,
"routeMenuSize": 200,
"fakerLocale": "en",
"fakerSeed": null,
"lastChangelog": "9999.9.9",
"environments": [
null,
"unknown",
{ "uuid": "", "path": "/home/username/file1.json" }
],
"enableTelemetry": true,
"unknown": true
}
| 184 |
400 | <gh_stars>100-1000
from lahja import BaseEvent, BroadcastConfig, ConnectionConfig
from lahja.exceptions import NoSubscribers
from lahja.tools import drivers as d
class Event(BaseEvent):
pass
def test_endpoint_broadcast_from_client_to_server(ipc_base_path, runner):
server_config = ConnectionConfig.from_name("server", base_path=ipc_base_path)
server = d.driver(d.serve_endpoint(server_config), d.wait_for(Event))
client = d.driver(
d.run_endpoint("client"),
d.connect_to_endpoints(server_config),
d.wait_any_then_broadcast(Event()),
)
runner(server, client)
def test_endpoint_broadcast_from_server_to_client(ipc_base_path, runner):
server_config = ConnectionConfig.from_name("server", base_path=ipc_base_path)
server = d.driver(
d.serve_endpoint(server_config), d.wait_any_then_broadcast(Event())
)
client = d.driver(
d.run_endpoint("client"),
d.connect_to_endpoints(server_config),
d.wait_for(Event),
)
runner(server, client)
def test_broadcast_without_listeners_throws(ipc_base_path, runner):
server_config = ConnectionConfig.from_name("server", base_path=ipc_base_path)
server_done, client_done = d.checkpoint("done")
server = d.driver(d.serve_endpoint(server_config), server_done)
client = d.driver(
d.run_endpoint("client"),
d.connect_to_endpoints(server_config),
d.wait_until_connected_to("server"),
d.throws(d.broadcast(Event()), NoSubscribers),
client_done,
)
runner(server, client)
def test_broadcast_without_listeners_explicitly_allowed(ipc_base_path, runner):
server_config = ConnectionConfig.from_name("server", base_path=ipc_base_path)
server_done, client_done = d.checkpoint("done")
server = d.driver(d.serve_endpoint(server_config), server_done)
client = d.driver(
d.run_endpoint("client"),
d.connect_to_endpoints(server_config),
d.wait_until_connected_to("server"),
d.broadcast(Event(), BroadcastConfig(require_subscriber=False)),
client_done,
)
runner(server, client)
| 855 |
884 | <gh_stars>100-1000
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
import os
import unittest
from cdm.enums import CdmStatusLevel
from tests.common import async_test, TestHelper
class JsonSemanticVersionTest(unittest.TestCase):
"""Set of tests to verify behavior of loading a document with different semantic versions."""
# The path between test_data_path and test_name.
tests_subpath = os.path.join('Persistence', 'CdmFolder', 'JsonSemanticVersionTest')
@async_test
async def test_loading_unsupported_version(self):
"""Test loading a document with a semantic version bigger than the one supported."""
corpus = TestHelper.get_local_corpus(self.tests_subpath, 'test_loading_unsupported_version')
error_count = 0
def callback_resolved(level, message):
nonlocal error_count
if 'This ObjectModel version supports json semantic version' in message and level == CdmStatusLevel.WARNING:
error_count += 1
# Test loading a resolved document.
corpus.set_event_callback(callback_resolved, CdmStatusLevel.WARNING)
await corpus.fetch_object_async('local:/resolvedDoc.cdm.json') # type: CdmDocumentDefinition
if error_count != 1:
self.fail('Should have logged a warning.')
error_count = 0
def callback_logical(level, message):
nonlocal error_count
if 'This ObjectModel version supports json semantic version' in message and level == CdmStatusLevel.ERROR:
error_count += 1
# Test loading a logical document.
corpus.set_event_callback(callback_logical, CdmStatusLevel.ERROR)
await corpus.fetch_object_async('local:/logicalDoc.cdm.json') # type: CdmDocumentDefinition
if error_count != 1:
self.fail('Should have logged an error.')
error_count = 0
def callback_missing(level, message):
nonlocal error_count
if 'jsonSemanticVersion is a required property of a document.' in message and level == CdmStatusLevel.WARNING:
error_count += 1
# Test loading a document missing the jsonSemanticVersion property.
corpus.set_event_callback(callback_missing, CdmStatusLevel.WARNING)
await corpus.fetch_object_async('local:/missingDoc.cdm.json') # type: CdmDocumentDefinition
if error_count != 1:
self.fail('Should have logged a warning for missing property.')
@async_test
async def test_loading_invalid_version(self):
"""Test loading a document with an invalid semantic version."""
corpus = TestHelper.get_local_corpus(self.tests_subpath, 'test_loading_invalid_version')
error_count = 0
def callback_resolved(level, message):
nonlocal error_count
if 'jsonSemanticVersion must be set using the format <major>.<minor>.<patch>.' in message and level == CdmStatusLevel.WARNING:
error_count += 1
# Test loading a version format "a.0.0".
corpus.set_event_callback(callback_resolved, CdmStatusLevel.WARNING)
await corpus.fetch_object_async('local:/invalidVersionDoc.cdm.json') # type: CdmDocumentDefinition
if error_count != 1:
self.fail('Should have logged a warning.')
error_count = 0
# Test loading a version format "1.0".
corpus.set_event_callback(callback_resolved, CdmStatusLevel.WARNING)
await corpus.fetch_object_async('local:/invalidFormatDoc.cdm.json') # type: CdmDocumentDefinition
if error_count != 1:
self.fail('Should have logged a warning.')
| 1,402 |
3,100 | package com.airbnb.airpal.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import java.net.URI;
@Path("/")
public class RedirectRootResource {
@GET
public Response redirectToApp()
{
return Response.temporaryRedirect(URI.create("/app"))
.status(Response.Status.MOVED_PERMANENTLY)
.build();
}
}
| 190 |
1,893 | """
Defines API paths for textractor endpoints.
"""
from typing import List
from fastapi import APIRouter, Body
from .. import application
router = APIRouter()
@router.get("/textract")
def textract(file: str):
"""
Extracts text from a file at path.
Args:
file: file to extract text
Returns:
extracted text
"""
return application.get().pipeline("textractor", (file,))
@router.post("/batchtextract")
def batchtextract(files: List[str] = Body(...)):
"""
Extracts text from a file at path.
Args:
files: list of files to extract text
Returns:
list of extracted text
"""
return application.get().pipeline("textractor", (files,))
| 262 |
2,151 | /* Generated by wayland-scanner 1.13.0 */
#ifndef GAMING_INPUT_UNSTABLE_V2_CLIENT_PROTOCOL_H
#define GAMING_INPUT_UNSTABLE_V2_CLIENT_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-client.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @page page_gaming_input_unstable_v2 The gaming_input_unstable_v2 protocol
* @section page_ifaces_gaming_input_unstable_v2 Interfaces
* - @subpage page_iface_zcr_gaming_input_v2 - extends wl_seat with gaming input devices
* - @subpage page_iface_zcr_gaming_seat_v2 - controller object for all gaming devices of a seat
* - @subpage page_iface_zcr_gamepad_v2 - gamepad input device
* @section page_copyright_gaming_input_unstable_v2 Copyright
* <pre>
*
* Copyright 2016 The Chromium Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* </pre>
*/
struct wl_seat;
struct zcr_gamepad_v2;
struct zcr_gaming_input_v2;
struct zcr_gaming_seat_v2;
/**
* @page page_iface_zcr_gaming_input_v2 zcr_gaming_input_v2
* @section page_iface_zcr_gaming_input_v2_desc Description
*
* A global interface to provide gaming input devices for a given seat.
*
* Currently only gamepad devices are supported.
*
* Warning! The protocol described in this file is experimental and
* backward incompatible changes may be made. Backward compatible changes
* may be added together with the corresponding uinterface version bump.
* Backward incompatible changes are done by bumping the version number in
* the protocol and uinterface names and resetting the interface version.
* Once the protocol is to be declared stable, the 'z' prefix and the
* version number in the protocol and interface names are removed and the
* interface version number is reset.
* @section page_iface_zcr_gaming_input_v2_api API
* See @ref iface_zcr_gaming_input_v2.
*/
/**
* @defgroup iface_zcr_gaming_input_v2 The zcr_gaming_input_v2 interface
*
* A global interface to provide gaming input devices for a given seat.
*
* Currently only gamepad devices are supported.
*
* Warning! The protocol described in this file is experimental and
* backward incompatible changes may be made. Backward compatible changes
* may be added together with the corresponding uinterface version bump.
* Backward incompatible changes are done by bumping the version number in
* the protocol and uinterface names and resetting the interface version.
* Once the protocol is to be declared stable, the 'z' prefix and the
* version number in the protocol and interface names are removed and the
* interface version number is reset.
*/
extern const struct wl_interface zcr_gaming_input_v2_interface;
/**
* @page page_iface_zcr_gaming_seat_v2 zcr_gaming_seat_v2
* @section page_iface_zcr_gaming_seat_v2_desc Description
*
* An object that provides access to all the gaming devices of a seat.
* When a gamepad is connected, the compositor will send gamepad_added event.
* @section page_iface_zcr_gaming_seat_v2_api API
* See @ref iface_zcr_gaming_seat_v2.
*/
/**
* @defgroup iface_zcr_gaming_seat_v2 The zcr_gaming_seat_v2 interface
*
* An object that provides access to all the gaming devices of a seat.
* When a gamepad is connected, the compositor will send gamepad_added event.
*/
extern const struct wl_interface zcr_gaming_seat_v2_interface;
/**
* @page page_iface_zcr_gamepad_v2 zcr_gamepad_v2
* @section page_iface_zcr_gamepad_v2_desc Description
*
* The zcr_gamepad_v2 interface represents one or more gamepad input devices,
* which are reported as a normalized 'Standard Gamepad' as it is specified
* by the W3C Gamepad API at: https://w3c.github.io/gamepad/#remapping
* @section page_iface_zcr_gamepad_v2_api API
* See @ref iface_zcr_gamepad_v2.
*/
/**
* @defgroup iface_zcr_gamepad_v2 The zcr_gamepad_v2 interface
*
* The zcr_gamepad_v2 interface represents one or more gamepad input devices,
* which are reported as a normalized 'Standard Gamepad' as it is specified
* by the W3C Gamepad API at: https://w3c.github.io/gamepad/#remapping
*/
extern const struct wl_interface zcr_gamepad_v2_interface;
#define ZCR_GAMING_INPUT_V2_GET_GAMING_SEAT 0
#define ZCR_GAMING_INPUT_V2_DESTROY 1
/**
* @ingroup iface_zcr_gaming_input_v2
*/
#define ZCR_GAMING_INPUT_V2_GET_GAMING_SEAT_SINCE_VERSION 1
/**
* @ingroup iface_zcr_gaming_input_v2
*/
#define ZCR_GAMING_INPUT_V2_DESTROY_SINCE_VERSION 1
/** @ingroup iface_zcr_gaming_input_v2 */
static inline void
zcr_gaming_input_v2_set_user_data(struct zcr_gaming_input_v2 *zcr_gaming_input_v2, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zcr_gaming_input_v2, user_data);
}
/** @ingroup iface_zcr_gaming_input_v2 */
static inline void *
zcr_gaming_input_v2_get_user_data(struct zcr_gaming_input_v2 *zcr_gaming_input_v2)
{
return wl_proxy_get_user_data((struct wl_proxy *) zcr_gaming_input_v2);
}
static inline uint32_t
zcr_gaming_input_v2_get_version(struct zcr_gaming_input_v2 *zcr_gaming_input_v2)
{
return wl_proxy_get_version((struct wl_proxy *) zcr_gaming_input_v2);
}
/**
* @ingroup iface_zcr_gaming_input_v2
*
* Get a gaming seat object for a given seat. Gaming seat provides access
* to gaming devices
*/
static inline struct zcr_gaming_seat_v2 *
zcr_gaming_input_v2_get_gaming_seat(struct zcr_gaming_input_v2 *zcr_gaming_input_v2, struct wl_seat *seat)
{
struct wl_proxy *gaming_seat;
gaming_seat = wl_proxy_marshal_constructor((struct wl_proxy *) zcr_gaming_input_v2,
ZCR_GAMING_INPUT_V2_GET_GAMING_SEAT, &zcr_gaming_seat_v2_interface, NULL, seat);
return (struct zcr_gaming_seat_v2 *) gaming_seat;
}
/**
* @ingroup iface_zcr_gaming_input_v2
*
* Destroy gaming_input object. Objects created from this object are
* unaffected and should be destroyed separately.
*/
static inline void
zcr_gaming_input_v2_destroy(struct zcr_gaming_input_v2 *zcr_gaming_input_v2)
{
wl_proxy_marshal((struct wl_proxy *) zcr_gaming_input_v2,
ZCR_GAMING_INPUT_V2_DESTROY);
wl_proxy_destroy((struct wl_proxy *) zcr_gaming_input_v2);
}
/**
* @ingroup iface_zcr_gaming_seat_v2
* @struct zcr_gaming_seat_v2_listener
*/
struct zcr_gaming_seat_v2_listener {
/**
* gamepad added event
*
* Notification that there is gamepad connected at this seat.
* @param gamepad new connected gamepad
*/
void (*gamepad_added)(void *data,
struct zcr_gaming_seat_v2 *zcr_gaming_seat_v2,
struct zcr_gamepad_v2 *gamepad);
};
/**
* @ingroup iface_zcr_gaming_seat_v2
*/
static inline int
zcr_gaming_seat_v2_add_listener(struct zcr_gaming_seat_v2 *zcr_gaming_seat_v2,
const struct zcr_gaming_seat_v2_listener *listener, void *data)
{
return wl_proxy_add_listener((struct wl_proxy *) zcr_gaming_seat_v2,
(void (**)(void)) listener, data);
}
#define ZCR_GAMING_SEAT_V2_DESTROY 0
/**
* @ingroup iface_zcr_gaming_seat_v2
*/
#define ZCR_GAMING_SEAT_V2_GAMEPAD_ADDED_SINCE_VERSION 1
/**
* @ingroup iface_zcr_gaming_seat_v2
*/
#define ZCR_GAMING_SEAT_V2_DESTROY_SINCE_VERSION 1
/** @ingroup iface_zcr_gaming_seat_v2 */
static inline void
zcr_gaming_seat_v2_set_user_data(struct zcr_gaming_seat_v2 *zcr_gaming_seat_v2, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zcr_gaming_seat_v2, user_data);
}
/** @ingroup iface_zcr_gaming_seat_v2 */
static inline void *
zcr_gaming_seat_v2_get_user_data(struct zcr_gaming_seat_v2 *zcr_gaming_seat_v2)
{
return wl_proxy_get_user_data((struct wl_proxy *) zcr_gaming_seat_v2);
}
static inline uint32_t
zcr_gaming_seat_v2_get_version(struct zcr_gaming_seat_v2 *zcr_gaming_seat_v2)
{
return wl_proxy_get_version((struct wl_proxy *) zcr_gaming_seat_v2);
}
/**
* @ingroup iface_zcr_gaming_seat_v2
*
* Destroy gaming_seat object. Objects created from this object are
* unaffected and should be destroyed separately.
*/
static inline void
zcr_gaming_seat_v2_destroy(struct zcr_gaming_seat_v2 *zcr_gaming_seat_v2)
{
wl_proxy_marshal((struct wl_proxy *) zcr_gaming_seat_v2,
ZCR_GAMING_SEAT_V2_DESTROY);
wl_proxy_destroy((struct wl_proxy *) zcr_gaming_seat_v2);
}
#ifndef ZCR_GAMEPAD_V2_BUTTON_STATE_ENUM
#define ZCR_GAMEPAD_V2_BUTTON_STATE_ENUM
/**
* @ingroup iface_zcr_gamepad_v2
* physical button state
*
* Describes the physical state of a button that produced the button
* event.
*/
enum zcr_gamepad_v2_button_state {
/**
* the button is not pressed
*/
ZCR_GAMEPAD_V2_BUTTON_STATE_RELEASED = 0,
/**
* the button is pressed
*/
ZCR_GAMEPAD_V2_BUTTON_STATE_PRESSED = 1,
};
#endif /* ZCR_GAMEPAD_V2_BUTTON_STATE_ENUM */
/**
* @ingroup iface_zcr_gamepad_v2
* @struct zcr_gamepad_v2_listener
*/
struct zcr_gamepad_v2_listener {
/**
* gamepad removed
*
* Removed event is send when the gamepad is disconnected. The
* client should expect no more event and call destroy.
*
* This event cannot be used as destructor as requests (e.g.
* vibration) might be added to this interface.
*/
void (*removed)(void *data,
struct zcr_gamepad_v2 *zcr_gamepad_v2);
/**
* axis change event
*
* Notification of axis change.
*
* The axis id specifies which axis has changed as defined by the
* W3C 'Standard Gamepad'.
*
* The value is calibrated and normalized to the -1 to 1 range.
* @param time timestamp with millisecond granularity
* @param axis axis that produced this event
* @param value new value of axis
*/
void (*axis)(void *data,
struct zcr_gamepad_v2 *zcr_gamepad_v2,
uint32_t time,
uint32_t axis,
wl_fixed_t value);
/**
* Gamepad button changed
*
* Notification of button change.
*
* The button id specifies which button has changed as defined by
* the W3C 'Standard Gamepad'.
*
* A button can have a digital and an analog value. The analog
* value is normalized to a 0 to 1 range. If a button does not
* provide an analog value, it will be derived from the digital
* state.
* @param time timestamp with millisecond granularity
* @param button id of button
* @param state digital state of the button
* @param analog analog value of the button
*/
void (*button)(void *data,
struct zcr_gamepad_v2 *zcr_gamepad_v2,
uint32_t time,
uint32_t button,
uint32_t state,
wl_fixed_t analog);
/**
* Notifies end of a series of gamepad changes.
*
* Indicates the end of a set of events that logically belong
* together. A client is expected to accumulate the data in all
* events within the frame before proceeding.
* @param time timestamp with millisecond granularity
*/
void (*frame)(void *data,
struct zcr_gamepad_v2 *zcr_gamepad_v2,
uint32_t time);
};
/**
* @ingroup iface_zcr_gamepad_v2
*/
static inline int
zcr_gamepad_v2_add_listener(struct zcr_gamepad_v2 *zcr_gamepad_v2,
const struct zcr_gamepad_v2_listener *listener, void *data)
{
return wl_proxy_add_listener((struct wl_proxy *) zcr_gamepad_v2,
(void (**)(void)) listener, data);
}
#define ZCR_GAMEPAD_V2_DESTROY 0
/**
* @ingroup iface_zcr_gamepad_v2
*/
#define ZCR_GAMEPAD_V2_REMOVED_SINCE_VERSION 1
/**
* @ingroup iface_zcr_gamepad_v2
*/
#define ZCR_GAMEPAD_V2_AXIS_SINCE_VERSION 1
/**
* @ingroup iface_zcr_gamepad_v2
*/
#define ZCR_GAMEPAD_V2_BUTTON_SINCE_VERSION 1
/**
* @ingroup iface_zcr_gamepad_v2
*/
#define ZCR_GAMEPAD_V2_FRAME_SINCE_VERSION 1
/**
* @ingroup iface_zcr_gamepad_v2
*/
#define ZCR_GAMEPAD_V2_DESTROY_SINCE_VERSION 1
/** @ingroup iface_zcr_gamepad_v2 */
static inline void
zcr_gamepad_v2_set_user_data(struct zcr_gamepad_v2 *zcr_gamepad_v2, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zcr_gamepad_v2, user_data);
}
/** @ingroup iface_zcr_gamepad_v2 */
static inline void *
zcr_gamepad_v2_get_user_data(struct zcr_gamepad_v2 *zcr_gamepad_v2)
{
return wl_proxy_get_user_data((struct wl_proxy *) zcr_gamepad_v2);
}
static inline uint32_t
zcr_gamepad_v2_get_version(struct zcr_gamepad_v2 *zcr_gamepad_v2)
{
return wl_proxy_get_version((struct wl_proxy *) zcr_gamepad_v2);
}
/**
* @ingroup iface_zcr_gamepad_v2
*/
static inline void
zcr_gamepad_v2_destroy(struct zcr_gamepad_v2 *zcr_gamepad_v2)
{
wl_proxy_marshal((struct wl_proxy *) zcr_gamepad_v2,
ZCR_GAMEPAD_V2_DESTROY);
wl_proxy_destroy((struct wl_proxy *) zcr_gamepad_v2);
}
#ifdef __cplusplus
}
#endif
#endif
| 4,903 |
571 | <filename>src/de/gurkenlabs/litiengine/environment/tilemap/TmxProperty.java
package de.gurkenlabs.litiengine.environment.tilemap;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation identifies which name is used by the map-object property related to the annotated member.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TmxProperty {
/**
* The name of the annotated member in the context of the TMX map.
*
* @return The name of the TMX map-object property.
*/
String name();
}
| 227 |
20,995 | // Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/cppgc/allocation.h"
#include "src/base/macros.h"
#include "src/heap/cppgc/marker.h"
#include "src/heap/cppgc/marking-visitor.h"
#include "src/heap/cppgc/stats-collector.h"
#include "test/unittests/heap/cppgc/tests.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cppgc {
namespace internal {
namespace {
class WeakContainerTest : public testing::TestWithHeap {
public:
using Config = Marker::MarkingConfig;
void StartMarking() {
CHECK_EQ(0u,
Heap::From(GetHeap())->AsBase().stats_collector()->marked_bytes());
Config config = {Config::CollectionType::kMajor,
Config::StackState::kNoHeapPointers,
Config::MarkingType::kIncremental};
GetMarkerRef() = MarkerFactory::CreateAndStartMarking<Marker>(
Heap::From(GetHeap())->AsBase(), GetPlatformHandle().get(), config);
}
void FinishMarking(Config::StackState stack_state) {
GetMarkerRef()->FinishMarking(stack_state);
marked_bytes_ =
Heap::From(GetHeap())->AsBase().stats_collector()->marked_bytes();
GetMarkerRef().reset();
Heap::From(GetHeap())->stats_collector()->NotifySweepingCompleted();
}
size_t GetMarkedBytes() const { return marked_bytes_; }
private:
size_t marked_bytes_ = 0;
};
template <typename T>
constexpr size_t SizeOf() {
return RoundUp<kAllocationGranularity>(sizeof(T) + sizeof(HeapObjectHeader));
}
class TraceableGCed : public GarbageCollected<TraceableGCed> {
public:
void Trace(cppgc::Visitor*) const { n_trace_calls++; }
static size_t n_trace_calls;
};
size_t TraceableGCed::n_trace_calls = 0u;
class NonTraceableGCed : public GarbageCollected<NonTraceableGCed> {
public:
void Trace(cppgc::Visitor*) const { n_trace_calls++; }
static size_t n_trace_calls;
};
size_t NonTraceableGCed::n_trace_calls = 0u;
void EmptyWeakCallback(const LivenessBroker&, const void*) {}
template <typename T>
V8_NOINLINE T access(volatile const T& t) {
return t;
}
} // namespace
} // namespace internal
template <>
struct TraceTrait<internal::TraceableGCed>
: public internal::TraceTraitBase<internal::TraceableGCed> {
static TraceDescriptor GetWeakTraceDescriptor(const void* self) {
return {self, Trace};
}
};
template <>
struct TraceTrait<internal::NonTraceableGCed>
: public internal::TraceTraitBase<internal::NonTraceableGCed> {
static TraceDescriptor GetWeakTraceDescriptor(const void* self) {
return {self, nullptr};
}
};
namespace internal {
TEST_F(WeakContainerTest, TraceableGCedTraced) {
TraceableGCed* obj =
MakeGarbageCollected<TraceableGCed>(GetAllocationHandle());
TraceableGCed::n_trace_calls = 0u;
StartMarking();
GetMarkerRef()->Visitor().TraceWeakContainer(obj, EmptyWeakCallback, nullptr);
FinishMarking(Config::StackState::kNoHeapPointers);
EXPECT_NE(0u, TraceableGCed::n_trace_calls);
EXPECT_EQ(SizeOf<TraceableGCed>(), GetMarkedBytes());
access(obj);
}
TEST_F(WeakContainerTest, NonTraceableGCedNotTraced) {
NonTraceableGCed* obj =
MakeGarbageCollected<NonTraceableGCed>(GetAllocationHandle());
NonTraceableGCed::n_trace_calls = 0u;
StartMarking();
GetMarkerRef()->Visitor().TraceWeakContainer(obj, EmptyWeakCallback, nullptr);
FinishMarking(Config::StackState::kNoHeapPointers);
EXPECT_EQ(0u, NonTraceableGCed::n_trace_calls);
EXPECT_EQ(SizeOf<NonTraceableGCed>(), GetMarkedBytes());
access(obj);
}
TEST_F(WeakContainerTest, NonTraceableGCedNotTracedConservatively) {
NonTraceableGCed* obj =
MakeGarbageCollected<NonTraceableGCed>(GetAllocationHandle());
NonTraceableGCed::n_trace_calls = 0u;
StartMarking();
GetMarkerRef()->Visitor().TraceWeakContainer(obj, EmptyWeakCallback, nullptr);
FinishMarking(Config::StackState::kMayContainHeapPointers);
EXPECT_NE(0u, NonTraceableGCed::n_trace_calls);
EXPECT_EQ(SizeOf<NonTraceableGCed>(), GetMarkedBytes());
access(obj);
}
TEST_F(WeakContainerTest, PreciseGCTracesWeakContainerWhenTraced) {
TraceableGCed* obj =
MakeGarbageCollected<TraceableGCed>(GetAllocationHandle());
TraceableGCed::n_trace_calls = 0u;
StartMarking();
GetMarkerRef()->Visitor().TraceWeakContainer(obj, EmptyWeakCallback, nullptr);
FinishMarking(Config::StackState::kNoHeapPointers);
EXPECT_EQ(1u, TraceableGCed::n_trace_calls);
EXPECT_EQ(SizeOf<TraceableGCed>(), GetMarkedBytes());
access(obj);
}
TEST_F(WeakContainerTest, ConservativeGCTracesWeakContainer) {
TraceableGCed* obj =
MakeGarbageCollected<TraceableGCed>(GetAllocationHandle());
TraceableGCed::n_trace_calls = 0u;
StartMarking();
GetMarkerRef()->Visitor().TraceWeakContainer(obj, EmptyWeakCallback, nullptr);
FinishMarking(Config::StackState::kMayContainHeapPointers);
EXPECT_EQ(2u, TraceableGCed::n_trace_calls);
EXPECT_EQ(SizeOf<TraceableGCed>(), GetMarkedBytes());
access(obj);
}
TEST_F(WeakContainerTest, ConservativeGCTracesWeakContainerOnce) {
NonTraceableGCed* obj =
MakeGarbageCollected<NonTraceableGCed>(GetAllocationHandle());
NonTraceableGCed* copy_obj = obj;
USE(copy_obj);
NonTraceableGCed* another_copy_obj = obj;
USE(another_copy_obj);
NonTraceableGCed::n_trace_calls = 0u;
StartMarking();
GetMarkerRef()->Visitor().TraceWeakContainer(obj, EmptyWeakCallback, nullptr);
FinishMarking(Config::StackState::kMayContainHeapPointers);
EXPECT_EQ(1u, NonTraceableGCed::n_trace_calls);
EXPECT_EQ(SizeOf<NonTraceableGCed>(), GetMarkedBytes());
access(obj);
}
namespace {
struct WeakCallback {
static void callback(const LivenessBroker&, const void* data) {
n_callback_called++;
obj = data;
}
static size_t n_callback_called;
static const void* obj;
};
size_t WeakCallback::n_callback_called = 0u;
const void* WeakCallback::obj = nullptr;
} // namespace
TEST_F(WeakContainerTest, WeakContainerWeakCallbackCalled) {
TraceableGCed* obj =
MakeGarbageCollected<TraceableGCed>(GetAllocationHandle());
WeakCallback::n_callback_called = 0u;
WeakCallback::obj = nullptr;
StartMarking();
GetMarkerRef()->Visitor().TraceWeakContainer(obj, WeakCallback::callback,
obj);
FinishMarking(Config::StackState::kMayContainHeapPointers);
EXPECT_NE(0u, WeakCallback::n_callback_called);
EXPECT_EQ(SizeOf<TraceableGCed>(), GetMarkedBytes());
EXPECT_EQ(obj, WeakCallback::obj);
}
} // namespace internal
} // namespace cppgc
| 2,466 |
7,883 |
# This recipe changes attributes of different type of blueprint actors.
# ...
walker_bp = world.get_blueprint_library().filter('walker.pedestrian.0002')
walker_bp.set_attribute('is_invincible', True)
# ...
# Changes attribute randomly by the recommended value
vehicle_bp = wolrd.get_blueprint_library().filter('vehicle.bmw.*')
color = random.choice(vehicle_bp.get_attribute('color').recommended_values)
vehicle_bp.set_attribute('color', color)
# ...
camera_bp = world.get_blueprint_library().filter('sensor.camera.rgb')
camera_bp.set_attribute('image_size_x', 600)
camera_bp.set_attribute('image_size_y', 600)
# ...
| 200 |
23,220 | package com.alibaba.otter.canal.adapter.launcher.monitor.remote;
/**
* 配置对应对象
*
* @author rewerma 2019-01-25 下午05:20:16
* @version 1.0.0
*/
public class ConfigItem {
private Long id;
private String category;
private String name;
private String content;
private long modifiedTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public long getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(long modifiedTime) {
this.modifiedTime = modifiedTime;
}
}
| 429 |
381 | <filename>jaxrs/src/main/java/org/jboss/aerogear/unifiedpush/rest/registry/applications/iOSTokenVariantEndpoint.java
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.aerogear.unifiedpush.rest.registry.applications;
import org.jboss.aerogear.unifiedpush.api.PushApplication;
import org.jboss.aerogear.unifiedpush.api.iOSTokenVariant;
import org.jboss.aerogear.unifiedpush.message.jms.APNSClientProducer;
import org.jboss.aerogear.unifiedpush.rest.annotations.DisabledByEnvironment;
import org.jboss.aerogear.unifiedpush.rest.annotations.PATCH;
import org.jboss.aerogear.unifiedpush.rest.util.error.ErrorBuilder;
import org.jboss.aerogear.unifiedpush.service.impl.SearchManager;
import javax.inject.Inject;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
@Path("/applications/{pushAppID}/{ignore:iostoken|ios_token}")
@DisabledByEnvironment({"ios_token", "iostoken"})
public class iOSTokenVariantEndpoint extends AbstractVariantEndpoint<iOSTokenVariant> {
@Inject
protected APNSClientProducer producer;
// required for RESTEasy
public iOSTokenVariantEndpoint() {
super(iOSTokenVariant.class);
}
// required for tests
iOSTokenVariantEndpoint(Validator validator, SearchManager searchManager) {
super(validator, searchManager, iOSTokenVariant.class);
}
/**
* Add iOS Variant
*
* @param iOSVariant new iOS Token Variant
* @param pushApplicationID id of {@link PushApplication}
* @param uriInfo uri
* @return created {@link iOSTokenVariant}
* @statuscode 201 The iOS Variant created successfully
* @statuscode 400 The format of the client request was incorrect
* @statuscode 404 The requested PushApplication resource does not exist
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response registeriOSVariant(
iOSTokenVariant iOSVariant,
@PathParam("pushAppID") String pushApplicationID,
@Context UriInfo uriInfo) {
// find the root push app
PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID);
if (pushApp == null) {
return Response.status(Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build();
}
// some model validation on the entity:
try {
validateModelClass(iOSVariant);
} catch (ConstraintViolationException cve) {
logger.trace("Unable to create iOS variant entity");
// Build and return the 400 (Bad Request) response
ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());
return builder.build();
}
logger.trace("Register iOS token variant with Push Application '{}'", pushApplicationID);
// store the iOS variant:
variantService.addVariant(iOSVariant);
// add iOS variant, and merge:
pushAppService.addVariant(pushApp, iOSVariant);
return Response.created(uriInfo.getAbsolutePathBuilder().path(String.valueOf(iOSVariant.getVariantID())).build()).entity(iOSVariant).build();
}
/**
* List iOS Variants for Push Application
*
* @param pushApplicationID id of {@link PushApplication}
* @return list of {@link iOSTokenVariant}s
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response listAlliOSVariantsForPushApp(@PathParam("pushAppID") String pushApplicationID) {
final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID);
if (application == null) {
return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build();
}
return Response.ok(getVariants(application)).build();
}
/**
* Update iOS Variant
*
* @param pushApplicationId id of {@link PushApplication}
* @param iOSID id of {@link iOSTokenVariant}
* @param updatediOSVariant updated version of {@link iOSTokenVariant}
* @return updated {@link iOSTokenVariant}
* @statuscode 204 The iOS Variant updated successfully
* @statuscode 404 The requested Variant resource does not exist
*/
@PATCH
@Path("/{iOSID}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateiOSVariant(
@PathParam("pushAppID") String pushApplicationId,
@PathParam("iOSID") String iOSID,
iOSTokenVariant updatediOSVariant) {
final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationId);
if (application == null) {
return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build();
}
iOSTokenVariant iOSTokenVariant = (iOSTokenVariant) variantService.findByVariantID(iOSID);
if (iOSTokenVariant != null) {
// apply update:
// merge the values and validate the new model
try {
updatediOSVariant.merge(iOSTokenVariant);
validateModelClass(iOSTokenVariant);
} catch (ConstraintViolationException cve) {
// Build and return the 400 (Bad Request) response
ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());
return builder.build();
}
logger.trace("Updating text details on iOS Variant '{}'", iOSID);
variantService.updateVariant(iOSTokenVariant);
return Response.noContent().build();
}
return Response.status(Status.NOT_FOUND).entity(ErrorBuilder.forVariants().notFound().build()).build();
}
/**
* Update iOS Variant
*
* @param pushApplicationId id of {@link PushApplication}
* @param iOSID id of {@link iOSTokenVariant}
* @param updatediOSVariant new info of {@link iOSTokenVariant}
* @return updated {@link iOSTokenVariant}
* @statuscode 200 The iOS Variant updated successfully
* @statuscode 400 The format of the client request was incorrect
* @statuscode 404 The requested iOS Variant resource does not exist
*/
@PUT
@Path("/{iOSID}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateiOSVariant(
iOSTokenVariant updatediOSVariant,
@PathParam("pushAppID") String pushApplicationId,
@PathParam("iOSID") String iOSID) {
final PushApplication application = getSearch().findByPushApplicationIDForDeveloper(pushApplicationId);
if (application == null) {
return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forPushApplications().notFound().build()).build();
}
var variant = variantService.findByVariantID(iOSID);
if (variant != null) {
if (!(variant instanceof iOSTokenVariant)) {
return Response.status(Response.Status.NOT_FOUND).entity(ErrorBuilder.forVariants().notFound().build()).build();
}
iOSTokenVariant iOSTokenVariant = (iOSTokenVariant) variant;
// merge the values and validate the new model
try {
updatediOSVariant.merge(iOSTokenVariant);
validateModelClass(iOSTokenVariant);
} catch (ConstraintViolationException cve) {
// Build and return the 400 (Bad Request) response
ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());
return builder.build();
}
// update performed, we now need to invalidate existing connection w/ APNs:
logger.trace("Updating iOS Variant '{}'", iOSTokenVariant.getVariantID());
variantService.updateVariant(iOSTokenVariant);
producer.changeAPNClient(iOSTokenVariant);
return Response.ok(iOSTokenVariant).build();
}
return Response.status(Status.NOT_FOUND).entity(ErrorBuilder.forVariants().notFound().build()).build();
}
}
| 3,458 |
5,079 | from django.conf.urls import include, url
from django.views import View
def view1(request):
pass
def view2(request):
pass
class View3(View):
pass
nested = ([
url(r'^view1/$', view1, name='view1'),
url(r'^view3/$', View3.as_view(), name='view3'),
], 'backend')
urlpatterns = [
url(r'^some/path/', include(nested, namespace='nested')),
url(r'^view2/$', view2, name='view2'),
]
| 173 |
387 | #pragma once
#include <string>
#include "Keys.h"
namespace WinSys {
enum class ThreadState : uint32_t {
Initialized = 0,
Ready = 1,
Running = 2,
Standby = 3,
Terminated = 4,
Waiting = 5,
Transition = 6,
DeferredReady = 7,
GateWaitObsolete = 8,
WaitingForProcessInSwap = 9
};
enum class WaitReason : uint32_t {
Executive,
FreePage,
PageIn,
PoolAllocation,
DelayExecution,
Suspended,
UserRequest,
WrExecutive,
WrFreePage,
WrPageIn,
WrPoolAllocation,
WrDelayExecution,
WrSuspended,
WrUserRequest,
WrEventPair,
WrQueue,
WrLpcReceive,
WrLpcReply,
WrVirtualMemory,
WrPageOut,
WrRendezvous,
WrKeyedEvent,
WrTerminated,
WrProcessInSwap,
WrCpuRateControl,
WrCalloutStack,
WrKernel,
WrResource,
WrPushLock,
WrMutex,
WrQuantumEnd,
WrDispatchInt,
WrPreempted,
WrYieldExecution,
WrFastMutex,
WrGuardedMutex,
WrRundown,
WrAlertByThreadId,
WrDeferredPreempt,
MaximumWaitReason
};
struct ThreadInfo {
friend class ProcessManager;
public:
const std::wstring& GetProcessImageName() const {
return _processName;
}
uint64_t KernelTime;
uint64_t UserTime;
uint64_t CreateTime;
uint32_t WaitTime;
uint32_t Id, ProcessId;
int32_t Priority;
int32_t BasePriority;
uint32_t ContextSwitches;
ThreadState ThreadState;
WaitReason WaitReason;
int32_t CPU;
void* StartAddress;
void* StackBase, *StackLimit;
void* Win32StartAddress;
void* TebBase;
ProcessOrThreadKey Key;
private:
std::wstring _processName;
};
}
| 663 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Saint-Maigrin","circ":"4ème circonscription","dpt":"Charente-Maritime","inscrits":446,"abs":266,"votants":180,"blancs":14,"nuls":1,"exp":165,"res":[{"nuance":"REM","nom":"<NAME>","voix":93},{"nuance":"LR","nom":"<NAME>","voix":72}]} | 113 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Migny","circ":"2ème circonscription","dpt":"Indre","inscrits":97,"abs":53,"votants":44,"blancs":5,"nuls":5,"exp":34,"res":[{"nuance":"LR","nom":"<NAME>","voix":24},{"nuance":"MDM","nom":"<NAME>","voix":10}]} | 108 |
473 | /*
Copyright (c) 2009-2016, <NAME>
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef EL_LAPACK_FUNCS_C_H
#define EL_LAPACK_FUNCS_C_H
#include <El/core/DistMatrix.h>
#include <El/lapack_like/factor.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
EL_SIGN_SCALE_NONE,
EL_SIGN_SCALE_DET,
EL_SIGN_SCALE_FROB
} ElSignScaling;
typedef struct {
ElInt maxIts;
float tol;
float power;
ElSignScaling scaling;
bool progress;
} ElSignCtrl_s;
EL_EXPORT ElError ElSignCtrlDefault_s( ElSignCtrl_s* ctrl );
typedef struct {
ElInt maxIts;
double tol;
double power;
ElSignScaling scaling;
bool progress;
} ElSignCtrl_d;
EL_EXPORT ElError ElSignCtrlDefault_d( ElSignCtrl_d* ctrl );
typedef struct {
ElInt maxIts;
float tol;
float power;
bool progress;
} ElSquareRootCtrl_s;
EL_EXPORT ElError ElSquareRootCtrlDefault_s( ElSquareRootCtrl_s* ctrl );
typedef struct {
ElInt maxIts;
double tol;
double power;
bool progress;
} ElSquareRootCtrl_d;
EL_EXPORT ElError ElSquareRootCtrlDefault_d( ElSquareRootCtrl_d* ctrl );
/* Hermitian function
================== */
/* Real Hermitian function
----------------------- */
EL_EXPORT ElError ElRealHermitianFunction_s
( ElUpperOrLower uplo, ElMatrix_s A, float (*func)(float) );
EL_EXPORT ElError ElRealHermitianFunction_d
( ElUpperOrLower uplo, ElMatrix_d A, double (*func)(double) );
EL_EXPORT ElError ElRealHermitianFunction_c
( ElUpperOrLower uplo, ElMatrix_c A, float (*func)(float) );
EL_EXPORT ElError ElRealHermitianFunction_z
( ElUpperOrLower uplo, ElMatrix_z A, double (*func)(double) );
EL_EXPORT ElError ElRealHermitianFunctionDist_s
( ElUpperOrLower uplo, ElDistMatrix_s A, float (*func)(float) );
EL_EXPORT ElError ElRealHermitianFunctionDist_d
( ElUpperOrLower uplo, ElDistMatrix_d A, double (*func)(double) );
EL_EXPORT ElError ElRealHermitianFunctionDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A, float (*func)(float) );
EL_EXPORT ElError ElRealHermitianFunctionDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A, double (*func)(double) );
/* Complex Hermitian function
-------------------------- */
EL_EXPORT ElError ElComplexHermitianFunction_c
( ElUpperOrLower uplo, ElMatrix_c A, complex_float (*func)(float) );
EL_EXPORT ElError ElComplexHermitianFunction_z
( ElUpperOrLower uplo, ElMatrix_z A, complex_double (*func)(double) );
EL_EXPORT ElError ElComplexHermitianFunctionDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A, complex_float (*func)(float) );
EL_EXPORT ElError ElComplexHermitianFunctionDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A, complex_double (*func)(double) );
/* Inverse
======= */
/* General
------- */
EL_EXPORT ElError ElInverse_s( ElMatrix_s A );
EL_EXPORT ElError ElInverse_d( ElMatrix_d A );
EL_EXPORT ElError ElInverse_c( ElMatrix_c A );
EL_EXPORT ElError ElInverse_z( ElMatrix_z A );
EL_EXPORT ElError ElInverseDist_s( ElDistMatrix_s A );
EL_EXPORT ElError ElInverseDist_d( ElDistMatrix_d A );
EL_EXPORT ElError ElInverseDist_c( ElDistMatrix_c A );
EL_EXPORT ElError ElInverseDist_z( ElDistMatrix_z A );
/* After LU factorization with partial pivoting
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
EL_EXPORT ElError ElInverseAfterLUPartialPiv_s
( ElMatrix_s A, ElConstPermutation P );
EL_EXPORT ElError ElInverseAfterLUPartialPiv_d
( ElMatrix_d A, ElConstPermutation P );
EL_EXPORT ElError ElInverseAfterLUPartialPiv_c
( ElMatrix_c A, ElConstPermutation P );
EL_EXPORT ElError ElInverseAfterLUPartialPiv_z
( ElMatrix_z A, ElConstPermutation P );
EL_EXPORT ElError ElInverseAfterLUPartialPivDist_s
( ElDistMatrix_s A, ElConstDistPermutation P );
EL_EXPORT ElError ElInverseAfterLUPartialPivDist_d
( ElDistMatrix_d A, ElConstDistPermutation P );
EL_EXPORT ElError ElInverseAfterLUPartialPivDist_c
( ElDistMatrix_c A, ElConstDistPermutation P );
EL_EXPORT ElError ElInverseAfterLUPartialPivDist_z
( ElDistMatrix_z A, ElConstDistPermutation P );
/* Hermitian Positive-Definite
--------------------------- */
EL_EXPORT ElError ElHPDInverse_s( ElUpperOrLower uplo, ElMatrix_s A );
EL_EXPORT ElError ElHPDInverse_d( ElUpperOrLower uplo, ElMatrix_d A );
EL_EXPORT ElError ElHPDInverse_c( ElUpperOrLower uplo, ElMatrix_c A );
EL_EXPORT ElError ElHPDInverse_z( ElUpperOrLower uplo, ElMatrix_z A );
EL_EXPORT ElError ElHPDInverseDist_s( ElUpperOrLower uplo, ElDistMatrix_s A );
EL_EXPORT ElError ElHPDInverseDist_d( ElUpperOrLower uplo, ElDistMatrix_d A );
EL_EXPORT ElError ElHPDInverseDist_c( ElUpperOrLower uplo, ElDistMatrix_c A );
EL_EXPORT ElError ElHPDInverseDist_z( ElUpperOrLower uplo, ElDistMatrix_z A );
/* Hermitian
--------- */
EL_EXPORT ElError ElHermitianInverse_c( ElUpperOrLower uplo, ElMatrix_c A );
EL_EXPORT ElError ElHermitianInverse_z( ElUpperOrLower uplo, ElMatrix_z A );
EL_EXPORT ElError ElHermitianInverseDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A );
EL_EXPORT ElError ElHermitianInverseDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A );
/* TODO: Expert version */
/* Symmetric
--------- */
EL_EXPORT ElError ElSymmetricInverse_s( ElUpperOrLower uplo, ElMatrix_s A );
EL_EXPORT ElError ElSymmetricInverse_d( ElUpperOrLower uplo, ElMatrix_d A );
EL_EXPORT ElError ElSymmetricInverse_c( ElUpperOrLower uplo, ElMatrix_c A );
EL_EXPORT ElError ElSymmetricInverse_z( ElUpperOrLower uplo, ElMatrix_z A );
EL_EXPORT ElError ElSymmetricInverseDist_s
( ElUpperOrLower uplo, ElDistMatrix_s A );
EL_EXPORT ElError ElSymmetricInverseDist_d
( ElUpperOrLower uplo, ElDistMatrix_d A );
EL_EXPORT ElError ElSymmetricInverseDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A );
EL_EXPORT ElError ElSymmetricInverseDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A );
/* TODO: Expert version */
/* Triangular
---------- */
EL_EXPORT ElError ElTriangularInverse_s
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElMatrix_s A );
EL_EXPORT ElError ElTriangularInverse_d
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElMatrix_d A );
EL_EXPORT ElError ElTriangularInverse_c
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElMatrix_c A );
EL_EXPORT ElError ElTriangularInverse_z
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElMatrix_z A );
EL_EXPORT ElError ElTriangularInverseDist_s
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElDistMatrix_s A );
EL_EXPORT ElError ElTriangularInverseDist_d
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElDistMatrix_d A );
EL_EXPORT ElError ElTriangularInverseDist_c
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElDistMatrix_c A );
EL_EXPORT ElError ElTriangularInverseDist_z
( ElUpperOrLower uplo, ElUnitOrNonUnit diag, ElDistMatrix_z A );
/* Pseudoinverse
============= */
/* General
------- */
EL_EXPORT ElError ElPseudoinverse_s( ElMatrix_s A );
EL_EXPORT ElError ElPseudoinverse_d( ElMatrix_d A );
EL_EXPORT ElError ElPseudoinverse_c( ElMatrix_c A );
EL_EXPORT ElError ElPseudoinverse_z( ElMatrix_z A );
EL_EXPORT ElError ElPseudoinverseDist_s( ElDistMatrix_s A );
EL_EXPORT ElError ElPseudoinverseDist_d( ElDistMatrix_d A );
EL_EXPORT ElError ElPseudoinverseDist_c( ElDistMatrix_c A );
EL_EXPORT ElError ElPseudoinverseDist_z( ElDistMatrix_z A );
/* TODO: Expert version */
/* Hermitian
--------- */
EL_EXPORT ElError ElHermitianPseudoinverse_s
( ElUpperOrLower uplo, ElMatrix_s A );
EL_EXPORT ElError ElHermitianPseudoinverse_d
( ElUpperOrLower uplo, ElMatrix_d A );
EL_EXPORT ElError ElHermitianPseudoinverse_c
( ElUpperOrLower uplo, ElMatrix_c A );
EL_EXPORT ElError ElHermitianPseudoinverse_z
( ElUpperOrLower uplo, ElMatrix_z A );
EL_EXPORT ElError ElHermitianPseudoinverseDist_s
( ElUpperOrLower uplo, ElDistMatrix_s A );
EL_EXPORT ElError ElHermitianPseudoinverseDist_d
( ElUpperOrLower uplo, ElDistMatrix_d A );
EL_EXPORT ElError ElHermitianPseudoinverseDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A );
EL_EXPORT ElError ElHermitianPseudoinverseDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A );
/* Sign
==== */
/* General
------- */
EL_EXPORT ElError ElSign_s( ElMatrix_s A );
EL_EXPORT ElError ElSign_d( ElMatrix_d A );
EL_EXPORT ElError ElSign_c( ElMatrix_c A );
EL_EXPORT ElError ElSign_z( ElMatrix_z A );
EL_EXPORT ElError ElSignDist_s( ElDistMatrix_s A );
EL_EXPORT ElError ElSignDist_d( ElDistMatrix_d A );
EL_EXPORT ElError ElSignDist_c( ElDistMatrix_c A );
EL_EXPORT ElError ElSignDist_z( ElDistMatrix_z A );
/* TODO: Expert version */
EL_EXPORT ElError ElSignDecomp_s( ElMatrix_s A, ElMatrix_s N );
EL_EXPORT ElError ElSignDecomp_d( ElMatrix_d A, ElMatrix_d N );
EL_EXPORT ElError ElSignDecomp_c( ElMatrix_c A, ElMatrix_c N );
EL_EXPORT ElError ElSignDecomp_z( ElMatrix_z A, ElMatrix_z N );
EL_EXPORT ElError ElSignDecompDist_s( ElDistMatrix_s A, ElDistMatrix_s N );
EL_EXPORT ElError ElSignDecompDist_d( ElDistMatrix_d A, ElDistMatrix_d N );
EL_EXPORT ElError ElSignDecompDist_c( ElDistMatrix_c A, ElDistMatrix_c N );
EL_EXPORT ElError ElSignDecompDist_z( ElDistMatrix_z A, ElDistMatrix_z N );
/* TODO: Expert version */
/* Hermitian
--------- */
EL_EXPORT ElError ElHermitianSign_s( ElUpperOrLower uplo, ElMatrix_s A );
EL_EXPORT ElError ElHermitianSign_d( ElUpperOrLower uplo, ElMatrix_d A );
EL_EXPORT ElError ElHermitianSign_c( ElUpperOrLower uplo, ElMatrix_c A );
EL_EXPORT ElError ElHermitianSign_z( ElUpperOrLower uplo, ElMatrix_z A );
EL_EXPORT ElError ElHermitianSignDist_s
( ElUpperOrLower uplo, ElDistMatrix_s A );
EL_EXPORT ElError ElHermitianSignDist_d
( ElUpperOrLower uplo, ElDistMatrix_d A );
EL_EXPORT ElError ElHermitianSignDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A );
EL_EXPORT ElError ElHermitianSignDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A );
/* TODO: Expert version */
EL_EXPORT ElError ElHermitianSignDecomp_s
( ElUpperOrLower uplo, ElMatrix_s A, ElMatrix_s N );
EL_EXPORT ElError ElHermitianSignDecomp_d
( ElUpperOrLower uplo, ElMatrix_d A, ElMatrix_d N );
EL_EXPORT ElError ElHermitianSignDecomp_c
( ElUpperOrLower uplo, ElMatrix_c A, ElMatrix_c N );
EL_EXPORT ElError ElHermitianSignDecomp_z
( ElUpperOrLower uplo, ElMatrix_z A, ElMatrix_z N );
EL_EXPORT ElError ElHermitianSignDecompDist_s
( ElUpperOrLower uplo, ElDistMatrix_s A, ElDistMatrix_s N );
EL_EXPORT ElError ElHermitianSignDecompDist_d
( ElUpperOrLower uplo, ElDistMatrix_d A, ElDistMatrix_d N );
EL_EXPORT ElError ElHermitianSignDecompDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A, ElDistMatrix_c N );
EL_EXPORT ElError ElHermitianSignDecompDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A, ElDistMatrix_z N );
/* TODO: Expert version */
/* Square-root
=========== */
/* General
------- */
EL_EXPORT ElError ElSquareRoot_s( ElMatrix_s A );
EL_EXPORT ElError ElSquareRoot_d( ElMatrix_d A );
EL_EXPORT ElError ElSquareRoot_c( ElMatrix_c A );
EL_EXPORT ElError ElSquareRoot_z( ElMatrix_z A );
EL_EXPORT ElError ElSquareRootDist_s( ElDistMatrix_s A );
EL_EXPORT ElError ElSquareRootDist_d( ElDistMatrix_d A );
EL_EXPORT ElError ElSquareRootDist_c( ElDistMatrix_c A );
EL_EXPORT ElError ElSquareRootDist_z( ElDistMatrix_z A );
/* TODO: Expert version */
/* Hermitian Positive Semi-Definite
-------------------------------- */
EL_EXPORT ElError ElHPSDSquareRoot_s( ElUpperOrLower uplo, ElMatrix_s A );
EL_EXPORT ElError ElHPSDSquareRoot_d( ElUpperOrLower uplo, ElMatrix_d A );
EL_EXPORT ElError ElHPSDSquareRoot_c( ElUpperOrLower uplo, ElMatrix_c A );
EL_EXPORT ElError ElHPSDSquareRoot_z( ElUpperOrLower uplo, ElMatrix_z A );
EL_EXPORT ElError ElHPSDSquareRootDist_s
( ElUpperOrLower uplo, ElDistMatrix_s A );
EL_EXPORT ElError ElHPSDSquareRootDist_d
( ElUpperOrLower uplo, ElDistMatrix_d A );
EL_EXPORT ElError ElHPSDSquareRootDist_c
( ElUpperOrLower uplo, ElDistMatrix_c A );
EL_EXPORT ElError ElHPSDSquareRootDist_z
( ElUpperOrLower uplo, ElDistMatrix_z A );
/* TODO: Expert version */
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* ifndef EL_LAPACK_FUNCS_C_H */
| 4,522 |
1,144 | package de.metas.rest_api.dataentry.impl;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.adempiere.util.lang.impl.TableRecordReference;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import de.metas.cache.CCache;
import de.metas.cache.CCache.CacheMapType;
import de.metas.cache.CacheIndex;
import de.metas.cache.CacheIndexDataAdapter;
import de.metas.dataentry.DataEntrySubTabId;
import de.metas.dataentry.data.DataEntryRecord;
import de.metas.dataentry.data.DataEntryRecordId;
import de.metas.dataentry.data.DataEntryRecordQuery;
import de.metas.dataentry.data.DataEntryRecordRepository;
import de.metas.dataentry.model.I_DataEntry_Record;
import de.metas.util.Check;
import de.metas.util.collections.CollectionUtils;
import lombok.NonNull;
import lombok.ToString;
import lombok.Value;
/*
* #%L
* de.metas.business.rest-api
* %%
* Copyright (C) 2019 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
final class DataEntryRecordCache
{
private final DataEntryRecordRepository recordsRepo;
private final CacheIndex<DataEntryRecordId/* RK */, CacheKey/* CK */, DataEntryRecord/* V */> //
cacheIndex = CacheIndex.of(new DataEntryRecordIdIndex());
private final CCache<CacheKey, DataEntryRecord> cache;
public DataEntryRecordCache(@NonNull final DataEntryRecordRepository recordsRepo, final int cacheCapacity)
{
this.recordsRepo = recordsRepo;
this.cache = CCache.<CacheKey, DataEntryRecord> builder()
.tableName(I_DataEntry_Record.Table_Name)
.cacheMapType(CacheMapType.LRU)
.initialCapacity(cacheCapacity)
.invalidationKeysMapper(cacheIndex::computeCachingKeys)
.removalListener(cacheIndex::remove)
.additionListener(cacheIndex::add)
.build();
}
public DataEntryRecordsMap get(
final int recordId,
@NonNull final Set<DataEntrySubTabId> subTabIds)
{
Check.assumeGreaterOrEqualToZero(recordId, "recordId");
Check.assumeNotEmpty(subTabIds, "subTabIds is not empty");
final Collection<DataEntryRecord> records = cache.getAllOrLoad(toCacheKeys(recordId, subTabIds), this::loadRecords);
return DataEntryRecordsMap.of(records);
}
private static Set<CacheKey> toCacheKeys(
final int recordId,
@NonNull final Set<DataEntrySubTabId> subTabIds)
{
return subTabIds.stream()
.map(subTabId -> CacheKey.of(recordId, subTabId))
.collect(ImmutableSet.toImmutableSet());
}
private Map<CacheKey, DataEntryRecord> loadRecords(final Collection<CacheKey> keys)
{
final DataEntryRecordQuery query = toDataEntryRecordQuery(keys);
final List<DataEntryRecord> records = recordsRepo.stream(query)
.map(DataEntryRecord::copyAsImmutable)
.collect(ImmutableList.toImmutableList());
if (records.isEmpty())
{
return ImmutableMap.of();
}
final Map<CacheKey, DataEntryRecord> recordsMap = Maps.uniqueIndex(
records,
record -> CollectionUtils.singleElement(cacheIndex.extractCacheKeys(record)));
return recordsMap;
}
private static DataEntryRecordQuery toDataEntryRecordQuery(final Collection<CacheKey> keys)
{
final int mainRecordId = CollectionUtils.extractSingleElement(keys, CacheKey::getMainRecordId);
final ImmutableSet<DataEntrySubTabId> subTabIds = extractSubTabIds(keys);
return DataEntryRecordQuery.builder()
.dataEntrySubTabIds(subTabIds)
.recordId(mainRecordId)
.build();
}
private static ImmutableSet<DataEntrySubTabId> extractSubTabIds(final Collection<CacheKey> keys)
{
final ImmutableSet<DataEntrySubTabId> subTabIds = keys.stream()
.map(CacheKey::getSubTabId)
.collect(ImmutableSet.toImmutableSet());
return subTabIds;
}
@VisibleForTesting
int getDataEntryRecordIdIndexSize()
{
return cacheIndex.size();
}
@Value(staticConstructor = "of")
private static final class CacheKey
{
int mainRecordId;
DataEntrySubTabId subTabId;
}
@ToString
@VisibleForTesting
static final class DataEntryRecordIdIndex implements CacheIndexDataAdapter<DataEntryRecordId, CacheKey, DataEntryRecord>
{
@Override
public DataEntryRecordId extractDataItemId(final DataEntryRecord dataItem)
{
return dataItem.getId().get();
}
@Override
public ImmutableSet<TableRecordReference> extractRecordRefs(final DataEntryRecord dataItem)
{
final DataEntryRecordId id = dataItem.getId().orElse(null);
return id != null
? ImmutableSet.of(TableRecordReference.of(I_DataEntry_Record.Table_Name, id))
: ImmutableSet.of();
}
@Override
public List<CacheKey> extractCacheKeys(final DataEntryRecord dataItem)
{
final CacheKey singleCacheKey = CacheKey.of(dataItem.getMainRecord().getRecord_ID(), dataItem.getDataEntrySubTabId());
return ImmutableList.of(singleCacheKey);
}
}
}
| 1,868 |
1,273 | package org.broadinstitute.hellbender.tools.dragstr;
import org.broadinstitute.hellbender.utils.Utils;
import java.util.*;
import java.util.stream.Collectors;
/**
* Collection of Dragstr Locus cases constraint to a particular period and (minimum) repeat-length
*/
public final class DragstrLocusCases extends AbstractList<DragstrLocusCase> {
private final List<DragstrLocusCase> cases;
private final int period;
private final int repeatLength;
/**
* Creates a new collection with default initial capacity.
* @param period the collection cases period.
* @param repeatLength the collection cases (minimum) repeat-length.
*/
public DragstrLocusCases(final int period, final int repeatLength) {
this(100, period, repeatLength);
}
@Override
public DragstrLocusCase get(final int index) {
return cases.get(index);
}
/**
* Creates a new dragstr cases collection providing it period and repeat-length constraints.
* @param initialCapacity the expected maximum number of members in the collection.
* @param period the member case period constraint. Only cases with this period are allowed.
* @param repeatLength the member case repeat-length constraint. Only cases with a repeat-length
* as large are allowed.
*/
public DragstrLocusCases(final int initialCapacity, final int period, final int repeatLength) {
Utils.validateArg( initialCapacity >= 0, "the initial capacity must be 0 or greater");
Utils.validateArg(period >= 1, "the period cannot be less than 1");
Utils.validateArg(repeatLength >= 1, "the repeat-length cannot be less than 1");
this.period = period;
this.repeatLength = repeatLength;
cases = new ArrayList<>(initialCapacity);
}
private DragstrLocusCases(final int period, final int repeatLength, final List<DragstrLocusCase> cases) {
this.period = period;
this.repeatLength = repeatLength;
this.cases = cases;
}
/**
* Adds a case to the collection.
* <p>
* This method makes sure that you don't add cases with a different period. The input repeat-length might be
* larger than the collection's to accomodate the special case of the "maximum" analyzed repeat-length.
* </p>
* @param caze the case to add.
* @throws IllegalArgumentException if the input is {@code null} or has the wrong period or repeat-length.
* @return always {@code true}.
*/
public boolean add(final DragstrLocusCase caze) {
Utils.validateArg(caze.getPeriod() == period, "the input case has the wrong period");
// We allow for larger repeat lengths since that might be the case for the "maximum" analyzed repeat-length.
Utils.validateArg(caze.getRepeatLength() >= repeatLength, "the input case has a repeat-length smaller than this collections");
return cases.add(caze);
}
public boolean addAll(final Collection<? extends DragstrLocusCase> more) {
for (final DragstrLocusCase caze : more) {
add(caze);
}
return true;
}
public boolean addAll(final DragstrLocusCases other) {
return addAll(other.cases);
}
public int getPeriod() {
return period;
}
public int getRepeatLength() {
return repeatLength;
}
public int size() {
return cases.size();
}
/**
* Returns a new collection that contains only those cases are qualify for parameter estimation given
* the required constraints.
* @param minDepth minimum depth admissible.
* @param minMQ minimum mapping quality admissible.
* @param maxSup maximum number of supplementary alignments admissible.
* @return never {@code null}.
*/
public DragstrLocusCases qualifyingOnly(final int minDepth, final int minMQ, final int maxSup) {
final List<DragstrLocusCase> newCases = cases.stream()
.filter(caze -> caze.getDepth() >= minDepth && caze.getMinMQ() >= minMQ && caze.getNSup() <= maxSup)
.collect(Collectors.toList());
return new DragstrLocusCases(period, repeatLength, newCases);
}
}
| 1,472 |
749 | <filename>roboticstoolbox/mobile/Animations.py
"""
Python Vehicle
@Author: <NAME>
@Author: <NAME>
"""
from abc import ABC, abstractmethod
import warnings
from math import pi, sin, cos, tan, atan2
import numpy as np
from scipy import integrate, linalg, interpolate
from pathlib import Path
import matplotlib.pyplot as plt
from matplotlib import patches, colors
import matplotlib.transforms as mtransforms
from spatialmath import SE2, base
from roboticstoolbox import rtb_load_data
"""
Class to support animation of a vehicle on Matplotlib plot
There are three concrete subclasses:
- ``VehicleMarker`` animates a Matplotlib marker
- ``VehiclePolygon`` animates a polygon, including predefined shapes
- ``VehicleIcon`` animates an image
These can be used in two different ways, firstly::
a.add()
a.update(q)
adds an instance of the animation shape to the plot and subsequent calls
to ``update`` will animate it.
Secondly::
a.plot(q)
adds an instance of the animation shape to the plot with the specified
configuration. It cannot be moved, but the method does return a reference
to the Matplotlib object added to the plot.
Any of these can be passed to a Vehicle subclass object to make an animation
during simulation::
a = VehiclePolygon('car', color='r')
veh = Bicycle()
veh.run(animation=a)
"""
class VehicleAnimationBase(ABC):
"""
Class to support animation of a vehicle on Matplotlib plot
There are three concrete subclasses:
- ``VehicleMarker`` animates a Matplotlib marker
- ``VehiclePolygon`` animates a polygon, including predefined shapes
- ``VehicleIcon`` animates an image
These can be used in two different ways, firstly::
a.add()
a.update(q)
adds an instance of the animation shape to the plot and subsequent calls
to ``update`` will animate it.
Secondly::
a.plot(q)
adds an instance of the animation shape to the plot with the specified
configuration. It cannot be moved, but the method does return a reference
to the Matplotlib object added to the plot.
Any of these can be passed to a Vehicle subclass object to make an animation
during simulation::
a = VehiclePolygon('car', color='r')
veh = Bicycle()
veh.run(animation=a)
"""
def __init__(self):
self._object = None
self._ax = None
def add(self, ax=None, **kwargs):
"""
Add vehicle animation to the current plot
:param ax: Axis to add to, defaults to current axis
:type ax: Axes, optional
A reference to the animation object is kept, and it will be deleted
from the plot when the ``VehicleAnimation`` object is garbage collected.
"""
if ax is None:
self._ax = plt.gca()
else:
self._ax = ax
self._add(**kwargs)
def update(self, q):
"""
Update the vehicle animation
:param q: vehicle configuration
:type q: ndarray(2) or ndarray(3)
The graphical depiction of the vehicle position or pose is updated.
For ``AnimationMarker`` only position can be depicted so the third element
of ``q``, if given, is ignored.
"""
self._update(q)
def plot(self, q, **kwargs):
"""
Add vehicle to the current plot
:param q: vehicle configuration
:type q: ndarray(2) or ndarray(3)
:return: reference to Matplotlib object
A reference to the animation object is kept, and it will be deleted
from the plot when the ``VehicleAnimation`` object is garbage collected.
"""
self.add(**kwargs)
self.update(q)
return self._object
def __del__(self):
if self._object is not None:
self._object.remove()
# ========================================================================= #
class VehicleMarker(VehicleAnimationBase):
def __init__(self, **kwargs):
"""
Create graphical animation of vehicle as a Matplotlib marker
:param kwargs: additional arguments passed to matplotlib ``plot``.
:return: animation object
:rtype: VehicleAnimation
Creates an object that can be passed to a ``Vehicle`` subclass to depict
the moving robot as a simple matplotlib marker during simulation.
For example, a blue filled square, is::
a = VehicleMarker(marker='s', markerfacecolor='b')
veh = Bicycle(driver=RandomPath(10), animation=a)
veh.run()
.. note:: A marker can only indicate vehicle position, not orientation.
:seealso: :func:`~Vehicle`
"""
super().__init__()
if len(kwargs) == 0:
kwargs = {
'marker': 'o',
'markerfacecolor': 'r',
'markeredgecolor': 'w',
'markersize': 12
}
self._args = kwargs
def _update(self, x):
self._object.set_xdata(x[0])
self._object.set_ydata(x[1])
def _add(self, x=None, **kwargs):
if x is None:
x = (0, 0)
self._object = plt.plot(x[0], x[1], **self._args)[0]
# ========================================================================= #
class VehiclePolygon(VehicleAnimationBase):
def __init__(self, shape='car', scale=1, **kwargs):
"""
Create graphical animation of vehicle as a polygon
:param shape: polygon shape as vertices or a predefined shape, defaults to 'car'
:type shape: ndarray(2,n) or str
:param scale: Length of the vehicle on the plot, defaults to 1
:type scale: float
:param kwargs: additional arguments passed to matplotlib patch such as
``color`` (face+edge), ``alpha``, ``facecolor``, ``edgecolor``,
``linewidth`` etc.
:raises ValueError: unknown shape name
:raises TypeError: bad shape argument
:return: animation object
:rtype: VehicleAnimation
Creates an object that can be passed to a ``Vehicle`` subclass to
depict the moving robot as a polygon during simulation.
For example, a red filled car-shaped polygon is::
a = VehiclePolygon('car', color='r')
veh = Bicycle()
veh.run(animation=a)
``shape`` can be:
* ``"car"`` a rectangle with chamfered front corners
* ``"triangle"`` a triangle
* an Nx2 NumPy array of vertices, does not have to be closed.
The polygon is scaled to an image with a length of ``scale`` in the units of
the plot.
:seealso: :func:`~Vehicle`
"""
super().__init__()
if isinstance(shape, str):
h = 0.3
t = 0.8 # start of head taper
c = 0.5 # centre x coordinate
w = 1 # width in x direction
if isinstance(shape, str):
if shape == 'car':
self._coords = np.array([
[-c, h],
[t - c, h],
[w - c, 0],
[t - c, -h],
[-c, -h],
]).T
elif shape == 'triangle':
self._coords = np.array([
[-c, h],
[ w, 0],
[-c, -h],
]).T
else:
raise ValueError('unknown vehicle shape name')
elif isinstance(shape, np.ndarray) and shape.shape[1] == 2:
self._coords = shape
else:
raise TypeError('unknown shape argument')
self._coords *= scale
self._args = kwargs
def _add(self, **kwargs):
# color is fillcolor + edgecolor
# facecolor if None is default
self._ax = plt.gca()
self._object = patches.Polygon(self._coords.T, **{**self._args, **kwargs})
self._ax.add_patch(self._object)
def _update(self, x):
if self._object is not None:
# if animation is initialized
xy = SE2(x) * self._coords
self._object.set_xy(xy.T)
# ========================================================================= #
class VehicleIcon(VehicleAnimationBase):
def __init__(self, filename, origin=None, scale=1, rotation=0):
"""
Create graphical animation of vehicle as an icon
:param filename: Standard icon name or a path to an image
:type filename: str
:param origin: Origin of the vehicle coordinate frame, defaults to centre
:type origin: 2-tuple
:param scale: Length of the vehicle on the plot, defaults to 1
:type scale: float
:param rotation: Vehicle icon heading in degrees, defaults to 0
:type rotation: float
:raises ValueError: Icon file not found
:return: animation object
:rtype: VehicleAnimation
Creates an object that can be passed to a ``Vehicle`` subclass to
depict the moving robot as a polygon during simulation.
For example, the image of a red car is::
a = VehicleIcon('redcar', scale=2)
veh = Bicycle()
veh.run(animation=a)
``filename`` can be:
* ``"greycar"`` a grey and white car (top view)
* ``"redcar"`` a red car (top view)
* ``"piano"`` a piano (top view)
* path to an image file, including extension
.. image:: ../../rtb-data/rtbdata/data/greycar.png
:width: 200px
:align: center
.. image:: ../../rtb-data/rtbdata/data/redcar.png
:width: 300px
:align: center
.. image:: ../../rtb-data/rtbdata/data/piano.png
:width: 300px
:align: center
The car is scaled to an image with a length of ``scale`` in the units of
the plot.
The vehicle rotates about its ``origin`` which is expressed in terms of
normalized coordinates in the range 0 to 1. By default it is in the
middle of the icon image, (0.2, 0.5) moves it toward the back of the
vehicle, (0.8, 0.5) moves it toward the front of the vehicle.
.. note::
- The standard icons are kept in ``roboticstoolbox/data``
- By default the image is assumed to contain a car parallel to
the x-axis and facing right. If the vehicle is facing upward
set ``rotation`` to 90.
:seealso: :func:`~Vehicle`
"""
super().__init__()
if '.' not in filename:
try:
# try the default folder first
image = rtb_load_data(Path("data") / Path(filename + ".png"), plt.imread)
except FileNotFoundError:
raise ValueError(f"{filename} is not a provided icon")
else:
try:
image = plt.imread(filename)
except FileNotFoundError:
raise ValueError(f"icon file {filename} not found")
self._rotation = rotation
self._image = image
# figure size of bounding box the image will fill in data coordinates
if origin is None:
origin = [0.5, 0.5]
self._origin = origin
if image.shape[0] >= image.shape[1]:
# width >= height
self._width = scale
self._height =scale * image.shape[1] / image.shape[0]
else:
# width < height
self._height = scale
self._width = scale * image.shape[0] / image.shape[1]
def _add(self, ax=None, **kwargs):
def imshow_affine(ax, z, *args, **kwargs):
im = ax.imshow(z, *args, **kwargs)
x1, x2, y1, y2 = im.get_extent()
# im._image_skew_coordinate = (x2, y1)
return im
self._ax = plt.gca()
extent = [ -self._origin[0] * self._height,
(1 - self._origin[0]) * self._height,
-self._origin[1] * self._width,
(1 - self._origin[1]) * self._width
]
self._ax = plt.gca()
args = {}
if 'color' in kwargs and self._image.ndim == 2:
color = kwargs['color']
del kwargs['color']
rgb = colors.to_rgb(color)
cmapdata = {'red': [(0.0, 0.0, 0.0), (1.0, rgb[0], 0.0)],
'green': [(0.0, 0.0, 0.0), (1.0, rgb[1], 0.0)],
'blue': [(0.0, 0.0, 0.0), (1.0, rgb[2], 0.0)]
}
cmap = colors.LinearSegmentedColormap('linear', segmentdata=cmapdata, N=256)
args = {'cmap': cmap}
elif self._image.ndim == 2:
args = {'cmap': 'gray'}
if 'zorder' not in kwargs:
args['zorder'] = 3
self._object = imshow_affine(self._ax, self._image,
interpolation='none',
extent=extent, clip_on=True,
**{**kwargs, **args})
def _update(self, x):
# center_x = self._width // 2
# center_y = self._height // 2
center_x = 0
center_y = 0
T = (mtransforms.Affine2D()
.rotate_deg_around(center_x, center_y, np.degrees(x[2]) - self._rotation)
.translate(x[0], x[1])
+ self._ax.transData)
self._object.set_transform(T)
if __name__ == "__main__":
from math import pi
from roboticstoolbox import Bicycle, RandomPath
V = np.diag(np.r_[0.02, 0.5 * pi / 180] ** 2)
v = VehiclePolygon()
# v = VehicleIcon('greycar2', scale=2, rotation=90)
veh = Bicycle(covar=V, animation=v, control=RandomPath(10), verbose=False)
print(veh)
odo = veh.step(1, 0.3)
print(odo)
print(veh.x)
print(veh.f([0, 0, 0], odo))
def control(v, t, x):
goal = (6,6)
goal_heading = atan2(goal[1]-x[1], goal[0]-x[0])
d_heading = base.angdiff(goal_heading, x[2])
v.stopif(base.norm(x[0:2] - goal) < 0.1)
return (1, d_heading)
veh.control=RandomPath(10)
p = veh.run(1000, plot=True)
# plt.show()
print(p)
veh.plot_xyt_t()
# veh.plot(p)
# t, x = veh.path(5, u=control)
# print(t)
# fig, ax = plt.subplots()
# ax.set_xlim(-5, 5)
# ax.set_ylim(-5, 5)
# v = VehicleAnimation.Polygon(shape='triangle', maxdim=0.1, color='r')
# v = VehicleAnimation.Icon('car3.png', maxdim=2, centre=[0.3, 0.5])
# v = VehicleAnimation.Icon('/Users/corkep/Dropbox/code/robotics-toolbox-python/roboticstoolbox/data/car1.png', maxdim=2, centre=[0.3, 0.5])
# v = VehicleAnimation.icon('car3.png', maxdim=2, centre=[0.3, 0.5])
# v = VehicleAnimation.marker()
# v.start()
# plt.grid(True)
# # plt.axis('equal')
# for theta in np.linspace(0, 2 * np.pi, 100):
# v.update([0, 0, theta])
# plt.pause(0.1) | 6,775 |
3,521 | <filename>kube_hunter/core/__init__.py<gh_stars>1000+
# flake8: noqa: E402
from . import types
from . import events
| 44 |
586 | # Generated by Django 2.2.12 on 2020-04-08 15:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('friendship', '0003_block_unique_together'),
]
operations = [
migrations.AlterModelOptions(
name='block',
options={'verbose_name': 'Blocked Relationship', 'verbose_name_plural': 'Blocked Relationships'},
),
]
| 170 |
10,876 | {
"name": "ttauri",
"version": "0.5.0",
"maintainers": "@takev",
"description": "A portable, low latency, retained-mode GUI framework written in C++.",
"homepage": "https://github.com/ttauri-project/ttauri",
"license": "BSL-1.0",
"supports": "windows & x64",
"dependencies": [
"vulkan",
"vulkan-memory-allocator"
]
}
| 135 |
1,781 | package com.marshalchen.common.uimodule.listviewanimations.itemmanipulation;
// TODO integrate in ExpandableListItemAdapter
public interface ExpandCollapseListener {
public void onItemExpanded(int position);
public void onItemCollapsed(int position);
}
| 77 |
544 | <gh_stars>100-1000
//
// NSDate+Format.h
// LFCategory
//
// Created by WangZhiWei on 16/5/19.
// Copyright © 2016年 youku. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDate (LFFormatAdditions)
#pragma mark - 日期格式化
///=============================================================================
/// @name 日期格式化
///=============================================================================
/**
将日期格式化成字符串
支持格式:http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
@param format 格式,例如 @"yyyy-MM-dd HH:mm:ss"
*/
- (NSString *)lf_stringWithFormat:(NSString *)format;
/**
将日期格式化成字符串
支持格式:http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
@param format 格式,例如 @"yyyy-MM-dd HH:mm:ss"
*/
- (NSString *)lf_stringWithFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale;
/**
以 ISO8601 格式化日期。例如: "2010-07-09T16:13:30+12:00"
*/
- (NSString *)lf_stringWithISOFormat;
/**
从字符串解析出日期 (解析失败则返回nil)
@param dateString 日期字符串,例如 "2010-07-09 16:13:30"
@param format 日期格式,例如 "yyyy-MM-dd HH:mm:ss"
*/
+ (NSDate *)lf_dateWithString:(NSString *)dateString format:(NSString *)format;
/**
从字符串解析出日期 (解析失败则返回nil)
@param dateString 日期字符串,例如 "2010-07-09 16:13:30"
@param format 日期格式,例如 "yyyy-MM-dd HH:mm:ss"
*/
+ (NSDate *)lf_dateWithString:(NSString *)dateString format:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale;
/**
将 ISO8601 格式的字符串解析成日期。
@param dateString 时间字符串,例如 "2010-07-09T16:13:30+12:00"
*/
+ (NSDate *)lf_dateWithISOFormatString:(NSString *)dateString;
@end
| 871 |
4,339 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.cache.jta.jndi;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;
import javax.cache.configuration.Factory;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.TransactionManager;
import org.apache.ignite.IgniteException;
import org.apache.ignite.internal.util.typedef.internal.U;
/**
* Implementation of {@code Factory<TransactionManager>} interface that is using JNDI names to find TM.
* <p>
* Note that {@link #create()} method iterates by JNDI names and returns the first found
* {@link TransactionManager} instance at context.
*/
public class CacheJndiTmFactory implements Factory<TransactionManager> {
/** */
private static final long serialVersionUID = 0;
/** */
private String[] jndiNames;
/** */
private Map<?, ?> environment;
/**
* Creates uninitialized jndi TM lookup.
*/
public CacheJndiTmFactory() {
/* No-op. */
}
/**
* Creates generic TM lookup with given jndi names.
*
* @param jndiNames JNDI names that is used to find TM.
*/
public CacheJndiTmFactory(String... jndiNames) {
this.jndiNames = jndiNames;
}
/**
* Gets a list of JNDI names.
*
* @return List of JNDI names that is used to find TM.
*/
public String[] getJndiNames() {
return jndiNames;
}
/**
* Sets JNDI names used by this TM factory.
*
* @param jndiNames JNDI names that is used to find TM.
*/
public void setJndiNames(String... jndiNames) {
this.jndiNames = jndiNames;
}
/**
* Gets initial context environment map.
*
* @return Initial context environment map.
*/
public Map<?, ?> getInitialContextEnvironment() {
return environment;
}
/**
* Sets initial context environment map that will be used
* in {@link InitialContext#InitialContext(Hashtable)} constructor.
*
* @param environment Initial context environment map.
*/
public void setInitialContextEnvironment(Map<?, ?> environment) {
this.environment = environment;
}
/** {@inheritDoc} */
@SuppressWarnings("UseOfObsoleteCollectionType")
@Override public TransactionManager create() {
assert jndiNames != null;
assert jndiNames.length != 0;
InitialContext ctx;
try {
ctx = new InitialContext(environment == null ? null : new Hashtable<>(environment));
}
catch (NamingException e) {
throw new IgniteException("Failed to instantiate InitialContext: " + environment, e);
}
for (String s : jndiNames) {
Object obj;
try {
obj = ctx.lookup(s);
}
catch (NamingException e) {
U.warn(null, "Failed to lookup resourse: " + e);
continue;
}
if (obj != null && obj instanceof TransactionManager)
return (TransactionManager)obj;
}
throw new IgniteException("Failed to lookup TM by: " + Arrays.toString(jndiNames));
}
}
| 1,473 |
532 | <filename>Bindings/Python/tests/test_simulation_utilities.py
import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
class TestSimulationUtilities(unittest.TestCase):
def test_update_kinematics(self):
model = osim.Model(
os.path.join(test_dir, 'gait10dof18musc_subject01.osim'))
kinematics_file = os.path.join(test_dir, 'std_subject01_walk1_ik.mot')
# updatePre40KinematicsStorageFor40MotionType() is not wrapped.
osim.updatePre40KinematicsFilesFor40MotionType(model,
[kinematics_file])
| 297 |
2,406 | <filename>src/plugins/intel_gpu/include/intel_gpu/primitives/scatter_elements_update.hpp
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "primitive.hpp"
namespace cldnn {
/// @addtogroup cpp_api C++ API
/// @{
/// @addtogroup cpp_topology Network Topology
/// @{
/// @addtogroup cpp_primitives Primitives
/// @{
/// @brief
/// @details
struct scatter_elements_update : public primitive_base<scatter_elements_update> {
CLDNN_DECLARE_PRIMITIVE(scatter_elements_update)
enum scatter_elements_update_axis {
along_b,
along_f,
along_x,
along_y,
along_z,
along_w
};
/// @brief Constructs scatter_elements_update primitive.
/// @param id This primitive id.
/// @param dict Input data primitive id.
/// @param idx Input indexes primitive id.
/// @param idupd Input updates primitive id.
/// @param axis Gathering axis.
scatter_elements_update(const primitive_id& id,
const primitive_id& data,
const primitive_id& idx,
const primitive_id& idupd,
const scatter_elements_update_axis axis,
const primitive_id& ext_prim_id = "",
const padding& output_padding = padding())
: primitive_base(id, {data, idx, idupd}, ext_prim_id, output_padding), axis(axis) {}
/// @brief ScatterElementsUpdate axis
scatter_elements_update_axis axis;
};
/// @}
/// @}
/// @}
} // namespace cldnn
| 709 |
3,690 | #define CATCH_CONFIG_MAIN
#include "../Catch/single_include/catch.hpp"
#include "solution.h"
TEST_CASE("Longest Common Prefix", "[longestCommonPrefix]")
{
Solution s;
SECTION( "common" )
{
std::vector<std::string> vec{"hello", "helo", "heat", "hey"};
REQUIRE( s.longestCommonPrefix(vec) == "he" );
}
SECTION( "less than first" )
{
std::vector<std::string> vec{"aa", "a"};
REQUIRE( s.longestCommonPrefix(vec) == "a" );
}
}
| 219 |
1,025 | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file pdStringConstants.h
///
//==================================================================================
//------------------------------ pdStringConstants.h ------------------------------
#ifndef __PDSTRINGCONSTANTS
#define __PDSTRINGCONSTANTS
// Debug log messages:
#define PD_STR_unexpectedEventDuringFunctionExecution L"Error: Got unexpected event during function execution. Event id: "
#define PD_STR_exceptionDuringFunctionExecution L"Error: Got exception during function execution. Exception type:"
#define PD_STR_gdbErrorDuringFunctionExecution L"Error: Got GDB error during function execution."
#define PD_STR_FailedToAddInstallDirToPath L"Failed to add the installation directory to the path"
#define PD_STR_FailedToGetTheCurrentProcessPath L"Failed to get the current process path"
#define PD_STR_FailedToGetLoadedModuleSize L"Failed to get loaded module size: "
#define PD_STR_makeThreadExecuteFunctionStarted L"pdProcessDebugger::makeThreadExecuteFunction started working"
#define PD_STR_makeThreadExecuteFunctionEnded L"pdProcessDebugger::makeThreadExecuteFunction ended"
#define PD_STR_remoteFuncFailed L"Remote thread executed function failed"
#define PD_STR_win32DebuggerError L"A Win32 debugger error occurred"
#define PD_STR_win32DebuggerFatalError L"The Win32 debugger error will fail the debugged process"
#define PD_STR_UnknownDebugEventError L"Error: Recieved an unknown debug event"
#define PD_STR_cannotGetNVIDIADriverSize L"Error: Cannot get the NVIDIA driver size"
#define PD_STR_cannotGetATIDriverSize L"Error: Cannot get the ATI driver size"
#define PD_STR_addressInsideLoadedModule L"Address %p found inside debugged process module "
#define PD_STR_addressIsNotInsideLoadedModule L"Cannot find a module containing the address %p"
#define PD_STR_cannotGetSpySize L"Error: Cannot get the CodeXL OpenGL server size"
#define PD_STR_driverThreadCreation L"A driver thread was created"
#define PD_STR_failedToLaunchGDB L"Error: Failed to launch the gdb debugger"
#define PD_STR_failedToLaunchGDBASCII "Error: Failed to launch the gdb debugger"
#define PD_STR_processRunWasSuspended L"Debugged process run was suspended or breakpoint was hit"
#define PD_STR_afterGDBProcessSuspensionActionsStarts L"afterGDBProcessSuspensionActions starts"
#define PD_STR_afterGDBProcessSuspensionActionsEnds L"afterGDBProcessSuspensionActions ends"
#define PD_STR_resumingDebuggedProcessRunInternally L"Resuming, internally, the debugged process run"
#define PD_STR_brokenPipeSignalReceived L"Broken pipe signal received"
#define PD_STR_unknownSignalReceived L"The debugged process received an unknown signal"
#define PD_STR_gotOGLServerAPIThreadId L"Got OpenGL server API thread id"
#define PD_STR_errorReadingFromGDB L"Error while reading gdb output. OS error is: "
#define PD_STR_debuggedProcessPID L"Debugged process pid is: "
#define PD_STR_debuggedProcessCurrentTID L". current thread id is: %p"
#define PD_STR_parsingGDBOutput L" Parsing GDB output: "
#define PD_STR_endedParsingGDBOutput L"Ended parsing GDB output: "
#define PD_STR_waitingForGDBCommandPrompt L"Waiting for gdb prompt..."
#define PD_STR_gotGDBCommandPrompt L"Got GDB command prompt: "
#define PD_STR_executedGDBCommand L"Executed GDB command: "
#define PD_STR_parsingGDBOutputLine L"Parsing GDB output line: "
#define PD_STR_parsingThreadLine L"Parsing thread line: "
#define PD_STR_parsingCallStack L"Parsing call stack: "
#define PD_STR_parsingCallStackLine L"Parsing call stack line: "
#define PD_STR_failedToParseGDBOutput L"Failed to parse GDB output"
#define PD_STR_waitingForGDBOutputs L"Waiting for GDB outputs ..."
#define PD_STR_endedParsingGDBOutputs L"Ended parsing GDB outputs - "
#define PD_STR_debuggedProcessWasSuspended L"Debugged process was suspended"
#define PD_STR_debuggedProcessWasTerminated L"Debugged process was terminated"
#define PD_STR_debuggedProcessIsStillRunning L"Debugged process is still running"
#define PD_STR_startedListeningToGDBOutputs L"Started listening to GDB outputs"
#define PD_STR_listenerThreadStartedWaitingForCondition L"pdGDBListenerThread started waiting for condition"
#define PD_STR_listenerThreadEndedWaitingForCondition L"pdGDBListenerThread ended waiting for condition"
#define PD_STR_AskingTheListenerThreadToExit L"Asking pdGDBListenerThread's thread to exit"
#define PD_STR_AskingTheListenerThreadToExitFailed L"Failed to make pdGDBListenerThread's thread to exit"
#define PD_STR_exitingTheListenerThread L"Exiting pdGDBListenerThread's thread"
#define PD_STR_outputReaderThreadOutputFilePrefix L"CXLAppOutput-"
#define PD_STR_outputReaderThreadStartedReading L"Starting to read debugged application's output"
#define PD_STR_gotDebuggedProcessTerminationMessage L"Got debugged process termination message"
#define PD_STR_debuggingAppAddressSpaceSize L"Debugging %ls (%d-bit)"
#define PD_STR_iPhoneOnDeviceSetupCreationScriptInvoked L"Invoked iPhone on-device setup project creation script. Output was: "
#define PD_STR_iPhoneOnDeviceSetupConfigurationScriptInvoked L"Invoked iPhone on-device setup configuration script. Output was: "
#define PD_STR_iPhoneOnDeviceCleanupScriptInvoked L"Invoked iPhone on-device cleanup script. Output was: "
#define PD_STR_iPhoneOnDeviceTemporaryProjectNameSuffix L"-CodeXL-temp"
#define PD_STR_iPhoneOnDeviceProcessCreationFailureScriptFailed L"Automatic configuration failure."
#define PD_STR_RemoteDebuggingStartFailure L"Unable to start remote debugging.\nPlease verify that:\n1. CodeXL and CodeXL Remote Agent are not blocked by a firewall.\n2. The given IP address and ports are valid, and the remote machine is accessible from the local machine.\n3. CodeXL Remote Agent is running on the remote machine."
#define PD_STR_OutputDebugStringMaxPrintoutsReached L"Maximal amount of debug string reached (%d strings). Additional debug strings will be ignored"
#define PD_STR_GDBStringMaxPrintoutsReached L"Maximal amount of GDB strings reached (%d strings). Additional GDB strings will be ignored"
#define PD_STR_DebuggedProcessOutputDebugStringMaxPrintoutsReached L"Maximal amount of debugged process output string reached (%d strings). Additional debugged process output strings will be ignored"
#define PD_STR_AMD_OCL_BUILD_OPTIONS_IgnoredWarning L"AMD_OCL_BUILD_OPTIONS & AMD_OCL_BUILD_OPTIONS_APPEND are ignored"
// Remote process debugger:
#define PD_STR_remoteProcessDebuggerSharedMemoryObject L"AMDTPDSharedMemObj"
#define PD_STR_remoteProcessDebuggerEventsSharedMemoryObject L"AMDTPDEventsSharedMemObj"
#define PD_STR_remoteDebuggingServer64ExecutableFileName L"CXLRemoteDebuggingServer-x64" AMDT_DEBUG_SUFFIX_W AMDT_BUILD_SUFFIX_W
// ProcessDebuggerESLauncher (iPhone launcher):
#if AMDT_BUILD_CONFIGURATION == AMDT_DEBUG_BUILD
#define PD_ES_LAUNCHER_MODULE_NAME L"libGRProcessDebuggerESLauncher_d.dylib"
#elif AMDT_BUILD_CONFIGURATION == AMDT_RELEASE_BUILD
#define PD_ES_LAUNCHER_MODULE_NAME L"libGRProcessDebuggerESLauncher.dylib"
#else
#error Unknown build configuration
#endif
#define PD_LAUNCH_IPHONE_SIMULATOR_WITH_APP_FUNCTION_NAME L"pdLaunchiPhoneSimulatorWithApplication"
// Note: this should be identical to GD_STR_iPhoneSimulatorIsNotInstalled
#define PD_STR_iPhoneSimulatorIsNotInstalled L"The iPhone Simulator application is not installed on the local computer.\nPlease install the iPhone SDK on the local computer to enable iPhone applications debugging."
// Environment variables:
#define PD_STR_AMD_OCL_BUILD_OPTIONS L"AMD_OCL_BUILD_OPTIONS"
#define PD_STR_AMD_OCL_BUILD_OPTIONS_APPEND L"PD_STR_AMD_OCL_BUILD_OPTIONS_APPEND"
#endif // __PDSTRINGCONSTANTS
| 2,297 |
9,425 | <reponame>babs/salt<gh_stars>1000+
"""
Event constants used by listeners and servers, to be imported elsewhere in Salt code.
Do NOT, import any salt modules (salt.utils, salt.config, etc.) into this file,
as this may result in circular imports.
.. versionadded:: 3000
"""
# Constants for events on the minion bus
MINION_PILLAR_REFRESH_COMPLETE = "/salt/minion/minion_pillar_refresh_complete"
MINION_MOD_REFRESH_COMPLETE = "/salt/minion/minion_mod_refresh_complete"
| 153 |
309 | <reponame>cw00dw0rd/pyGeno
import unittest
from pyGeno.Genome import *
import pyGeno.bootstrap as B
from pyGeno.importation.Genomes import *
from pyGeno.importation.SNPs import *
class pyGenoSNPTests(unittest.TestCase):
def setUp(self):
# try :
# B.importGenome("Human.GRCh37.75_Y-Only.tar.gz")
# except KeyError :
# deleteGenome("human", "GRCh37.75_Y-Only")
# B.importGenome("Human.GRCh37.75_Y-Only.tar.gz")
# print "--> Seems to already exist in db"
# try :
# B.importSNPs("Human_agnostic.dummySRY.tar.gz")
# except KeyError :
# deleteSNPs("dummySRY_AGN")
# B.importSNPs("Human_agnostic.dummySRY.tar.gz")
# print "--> Seems to already exist in db"
# try :
# B.importSNPs("Human_agnostic.dummySRY_indels")
# except KeyError :
# deleteSNPs("dummySRY_AGN_indels")
# B.importSNPs("Human_agnostic.dummySRY_indels")
# print "--> Seems to already exist in db"
self.ref = Genome(name = 'GRCh37.75_Y-Only')
def tearDown(self):
pass
# @unittest.skip("skipping")
def test_vanilla(self) :
dummy = Genome(name = 'GRCh37.75_Y-Only', SNPs = 'dummySRY_AGN')
persProt = dummy.get(Protein, id = 'ENSP00000438917')[0]
refProt = self.ref.get(Protein, id = 'ENSP00000438917')[0]
self.assertEqual('ATGCAATCATATGCTTCTGC', refProt.transcript.cDNA[:20])
self.assertEqual('HTGCAATCATATGCTTCTGC', persProt.transcript.cDNA[:20])
# @unittest.skip("skipping")
def test_noModif(self) :
from pyGeno.SNPFiltering import SNPFilter
class MyFilter(SNPFilter) :
def __init__(self) :
SNPFilter.__init__(self)
def filter(self, chromosome, dummySRY_AGN) :
return None
dummy = Genome(name = 'GRCh37.75_Y-Only', SNPs = 'dummySRY_AGN', SNPFilter = MyFilter())
persProt = dummy.get(Protein, id = 'ENSP00000438917')[0]
refProt = self.ref.get(Protein, id = 'ENSP00000438917')[0]
self.assertEqual(persProt.transcript.cDNA[:20], refProt.transcript.cDNA[:20])
# @unittest.skip("skipping")
def test_insert(self) :
from pyGeno.SNPFiltering import SNPFilter
class MyFilter(SNPFilter) :
def __init__(self) :
SNPFilter.__init__(self)
def filter(self, chromosome, dummySRY_AGN) :
from pyGeno.SNPFiltering import SequenceInsert
refAllele = chromosome.refSequence[dummySRY_AGN.start]
return SequenceInsert('XXX')
dummy = Genome(name = 'GRCh37.75_Y-Only', SNPs = 'dummySRY_AGN', SNPFilter = MyFilter())
persProt = dummy.get(Protein, id = 'ENSP00000438917')[0]
refProt = self.ref.get(Protein, id = 'ENSP00000438917')[0]
self.assertEqual('ATGCAATCATATGCTTCTGC', refProt.transcript.cDNA[:20])
self.assertEqual('XXXATGCAATCATATGCTTC', persProt.transcript.cDNA[:20])
# @unittest.skip("skipping")
def test_SNP(self) :
from pyGeno.SNPFiltering import SNPFilter
class MyFilter(SNPFilter) :
def __init__(self) :
SNPFilter.__init__(self)
def filter(self, chromosome, dummySRY_AGN) :
from pyGeno.SNPFiltering import SequenceSNP
return SequenceSNP(dummySRY_AGN.alt)
dummy = Genome(name = 'GRCh37.75_Y-Only', SNPs = 'dummySRY_AGN', SNPFilter = MyFilter())
persProt = dummy.get(Protein, id = 'ENSP00000438917')[0]
refProt = self.ref.get(Protein, id = 'ENSP00000438917')[0]
self.assertEqual('M', refProt.sequence[0])
self.assertEqual('L', persProt.sequence[0])
# @unittest.skip("skipping")
def test_deletion(self) :
from pyGeno.SNPFiltering import SNPFilter
class MyFilter(SNPFilter) :
def __init__(self) :
SNPFilter.__init__(self)
def filter(self, chromosome, dummySRY_AGN) :
from pyGeno.SNPFiltering import SequenceDel
refAllele = chromosome.refSequence[dummySRY_AGN.start]
return SequenceDel(1)
dummy = Genome(name = 'GRCh37.75_Y-Only', SNPs = 'dummySRY_AGN', SNPFilter = MyFilter())
persProt = dummy.get(Protein, id = 'ENSP00000438917')[0]
refProt = self.ref.get(Protein, id = 'ENSP00000438917')[0]
self.assertEqual('ATGCAATCATATGCTTCTGC', refProt.transcript.cDNA[:20])
self.assertEqual('TGCAATCATATGCTTCTGCT', persProt.transcript.cDNA[:20])
# @unittest.skip("skipping")
def test_indels(self) :
from pyGeno.SNPFiltering import SNPFilter
class MyFilter(SNPFilter) :
def __init__(self) :
SNPFilter.__init__(self)
def filter(self, chromosome, dummySRY_AGN_indels) :
from pyGeno.SNPFiltering import SequenceInsert
ret = ""
for s in dummySRY_AGN_indels :
ret += "X"
return SequenceInsert(ret)
dummy = Genome(name = 'GRCh37.75_Y-Only', SNPs = 'dummySRY_AGN_indels', SNPFilter = MyFilter())
persProt = dummy.get(Protein, id = 'ENSP00000438917')[0]
refProt = self.ref.get(Protein, id = 'ENSP00000438917')[0]
self.assertEqual('XXXATGCAATCATATGCTTC', persProt.transcript.cDNA[:20])
# @unittest.skip("skipping")
def test_bags(self) :
dummy = Genome(name = 'GRCh37.75_Y-Only')
self.assertEqual(dummy.wrapped_object, self.ref.wrapped_object)
# @unittest.skip("skipping")
def test_prot_find(self) :
prot = self.ref.get(Protein, id = 'ENSP00000438917')[0]
needle = prot.sequence[:10]
self.assertEqual(0, prot.find(needle))
needle = prot.sequence[-10:]
self.assertEqual(len(prot)-10, prot.find(needle))
# @unittest.skip("skipping")
def test_trans_find(self) :
trans = self.ref.get(Transcript, name = "SRY-001")[0]
self.assertEqual(0, trans.find(trans[:5]))
# @unittest.skip("remote server down")
# def test_import_remote_genome(self) :
# self.assertRaises(KeyError, B.importRemoteGenome, "Human.GRCh37.75_Y-Only.tar.gz")
# @unittest.skip("remote server down")
# def test_import_remote_snps(self) :
# self.assertRaises(KeyError, B.importRemoteSNPs, "Human_agnostic.dummySRY.tar.gz")
def runTests() :
try :
B.importGenome("Human.GRCh37.75_Y-Only.tar.gz")
except KeyError :
deleteGenome("human", "GRCh37.75_Y-Only")
B.importGenome("Human.GRCh37.75_Y-Only.tar.gz")
print "--> Seems to already exist in db"
try :
B.importSNPs("Human_agnostic.dummySRY.tar.gz")
except KeyError :
deleteSNPs("dummySRY_AGN")
B.importSNPs("Human_agnostic.dummySRY.tar.gz")
print "--> Seems to already exist in db"
try :
B.importSNPs("Human_agnostic.dummySRY_indels")
except KeyError :
deleteSNPs("dummySRY_AGN_indels")
B.importSNPs("Human_agnostic.dummySRY_indels")
print "--> Seems to already exist in db"
# import time
# time.sleep(10)
unittest.main()
if __name__ == "__main__" :
runTests()
| 2,762 |
998 | <gh_stars>100-1000
// Copyright 2021 Phyronnaz
#include "Factories/VoxelDataAssetFromMeshImporterFactory.h"
#include "VoxelAssets/VoxelDataAsset.h"
#include "VoxelAssets/VoxelDataAssetData.h"
#include "VoxelFeedbackContext.h"
#include "VoxelImporters/VoxelMeshImporter.h"
#include "VoxelMessages.h"
#include "Engine/StaticMesh.h"
#include "Framework/Notifications/NotificationManager.h"
#include "Widgets/Notifications/SNotificationList.h"
UVoxelDataAssetFromMeshImporterFactory::UVoxelDataAssetFromMeshImporterFactory()
{
bEditAfterNew = true;
bEditorImport = true;
SupportedClass = UVoxelDataAsset::StaticClass();
}
UObject* UVoxelDataAssetFromMeshImporterFactory::FactoryCreateNew(UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn)
{
FVoxelMessages::Info("Converting meshes to voxels requires Voxel Plugin Pro");
return nullptr;
}
FString UVoxelDataAssetFromMeshImporterFactory::GetDefaultNewAssetName() const
{
return MeshImporter->StaticMesh->GetName();
} | 379 |
1,144 | package org.adempiere.ad.dao.impl;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.adempiere.ad.dao.IQueryInsertExecutor;
import org.adempiere.model.InterfaceWrapperHelper;
import com.google.common.base.MoreObjects;
import de.metas.util.Check;
class QueryInsertExecutor<ToModelType, FromModelType> implements IQueryInsertExecutor<ToModelType, FromModelType>
{
private final Class<ToModelType> toModelClass;
private final String toTableName;
private final AbstractTypedQuery<FromModelType> fromQuery;
private final Class<FromModelType> fromModelClass;
// Mapping
private final Map<String, IQueryInsertFromColumn> toColumn2fromColumn = new HashMap<>();
private final Map<String, IQueryInsertFromColumn> toColumn2fromColumnRO = Collections.unmodifiableMap(toColumn2fromColumn);
// Options
private boolean createSelectionOfInsertedRows = false;
QueryInsertExecutor(final Class<ToModelType> toModelClass, final AbstractTypedQuery<FromModelType> fromQuery)
{
super();
Check.assumeNotNull(toModelClass, "toModelClass not null");
this.toModelClass = toModelClass;
this.toTableName = InterfaceWrapperHelper.getTableName(toModelClass);
Check.assumeNotNull(fromQuery, "fromQuery not null");
this.fromQuery = fromQuery;
this.fromModelClass = fromQuery.getModelClass();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("toTableName", toTableName)
.add("fromModelClass", fromModelClass)
.add("fromQuery", fromQuery)
.add("mapping", toColumn2fromColumnRO)
.add("createSelectionOfInsertedRows", createSelectionOfInsertedRows ? Boolean.TRUE : null)
.toString();
}
@Override
public QueryInsertExecutorResult execute()
{
return fromQuery.executeInsert(this);
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> mapCommonColumns()
{
final Set<String> fromColumnNames = InterfaceWrapperHelper.getModelColumnNames(fromModelClass);
final Set<String> toColumnNames = new HashSet<>(InterfaceWrapperHelper.getModelColumnNames(toModelClass));
toColumnNames.retainAll(fromColumnNames);
for (final String toColumnName : toColumnNames)
{
final String fromColumnName = toColumnName;
final IQueryInsertFromColumn from = new QueryInsertFromColumn(fromColumnName);
mapColumn(toColumnName, from);
}
return this;
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> mapColumn(final String toColumnName, final String fromColumnName)
{
final IQueryInsertFromColumn from = new QueryInsertFromColumn(fromColumnName);
mapColumn(toColumnName, from);
return this;
}
private final QueryInsertExecutor<ToModelType, FromModelType> mapColumn(final String toColumnName, final IQueryInsertFromColumn from)
{
this.toColumn2fromColumn.put(toColumnName, from);
return this;
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> mapColumnToConstant(final String toColumnName, final Object constantValue)
{
final IQueryInsertFromColumn from = new ConstantQueryInsertFromColumn(constantValue);
mapColumn(toColumnName, from);
return this;
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> mapColumnToSql(final String toColumnName, final String fromSql)
{
final IQueryInsertFromColumn from = new SqlQueryInsertFromColumn(fromSql);
mapColumn(toColumnName, from);
return this;
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> mapPrimaryKey()
{
final String toColumnName = getToKeyColumnName();
final IQueryInsertFromColumn from = new PrimaryKeyQueryInsertFromColumn(getToTableName());
mapColumn(toColumnName, from);
return this;
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> creatingSelectionOfInsertedRows()
{
this.createSelectionOfInsertedRows = true;
return this;
}
/* package */ boolean isCreateSelectionOfInsertedRows()
{
return createSelectionOfInsertedRows;
}
/* package */String getToKeyColumnName()
{
return InterfaceWrapperHelper.getKeyColumnName(toModelClass);
}
/**
*
* @return "To ColumnName" to "From Column" map
*/
/* package */ Map<String, IQueryInsertFromColumn> getColumnMapping()
{
return toColumn2fromColumnRO;
}
/* package */ boolean isEmpty()
{
return toColumn2fromColumn.isEmpty();
}
/* package */ String getToTableName()
{
return toTableName;
}
/* package */ Class<ToModelType> getToModelClass()
{
return toModelClass;
}
}
| 1,695 |
412 |
int main(void)
{
int x = 1;
int y = 3;
int nondet;
if(nondet)
y = 4;
if(nondet)
x = 5;
__CPROVER_assert(x != y, "x != y");
__CPROVER_assert(y != x, "y != x");
__CPROVER_assert(!(x != y), "!(x != y)");
__CPROVER_assert(!(y != x), "!(y != x)");
__CPROVER_assert(x == y, "x == y");
__CPROVER_assert(y == x, "y == x");
__CPROVER_assert(!(x == y), "!(x == y)");
__CPROVER_assert(!(y == x), "!(y == x)");
}
| 227 |
32,544 | <filename>spring-cloud-data-flow/batch-job/src/test/java/com/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java
package com.baeldung.spring.cloud;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = JobConfiguration.class)
public class BatchJobApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
| 190 |
11,356 | <reponame>Bpowers4/turicreate
#ifndef BOOST_FSM_EVENT_INCLUDED
#define BOOST_FSM_EVENT_INCLUDED
// Copyright <NAME> 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include "base_event.hpp"
namespace fsm { namespace aux {
template< typename Derived >
struct event
: base_event
{
public:
typedef base_event base_t;
private:
#if defined(BOOST_NO_CXX11_SMART_PTR)
virtual std::auto_ptr<base_event> do_clone() const
{
return std::auto_ptr<base_event>(
new Derived(static_cast<Derived const&>(*this))
);
}
#else
virtual std::unique_ptr<base_event> do_clone() const
{
return std::unique_ptr<base_event>(
new Derived(static_cast<Derived const&>(*this))
);
}
#endif
};
}}
#endif // BOOST_FSM_EVENT_INCLUDED
| 452 |
1,133 | <reponame>vincentschut/isce2
//
// Author: <NAME>
// Copyright 2016
//
#ifndef AMPCOR_METHODS_H
#define AMPCOR_METHODS_H
#include <complex>
#include <ctime>
#include <vector>
#include "AmpcorFFT.h"
#include "Constants.h"
struct AmpcorMethods {
std::vector<double> filter;
double beta = .75;
double relfiltlen = 6.;
double pedestal = 0.;
int filtercoef;
int decfactor = 4096;
int hasWeight = 1;
std::clock_t innerStart, outerStart;
// Storing in here as Ampcor only has one line call (looped), but the fourn2d method needs more direct access
AmpcorFFT aFFT;
AmpcorMethods() : filter(MAXINTLGH) {};
void fill_sinc(int&,float&,std::vector<float>&);
void startOuterClock();
void startInnerClock();
double getOuterClock();
double getInnerClock();
void correlate(std::vector<std::vector<float> >&,std::vector<std::vector<float> >&,int,int,int,int,int,int,float&,
std::vector<float>&,std::vector<std::vector<float> >&,int&,int&,std::vector<int>&,int,bool);
void derampc(std::vector<std::complex<float> >&,int,int);
void fourn2d(std::vector<std::complex<float> >&,std::vector<int>&,int);
};
#endif
| 489 |
563 | package com.gentics.mesh.util;
import static com.gentics.mesh.core.rest.error.Errors.error;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
/**
* Utility which contains date and time related methods.
*/
public final class DateUtils {
private static final Logger log = LoggerFactory.getLogger(DateUtils.class);
static ZoneOffset zoneOffset;
static {
OffsetDateTime odt = OffsetDateTime.now(ZoneId.systemDefault());
zoneOffset = odt.getOffset();
}
/**
* Convert the provided unixtimestamp (miliseconds since midnight, January 1, 1970 UTC) to an ISO8601 string. Use the fallback timestamp if the provided
* timestamp is null.
*
* @param timestampInMs
* @param fallback
* @return
*/
public static String toISO8601(Long timestampInMs, long fallback) {
long time = timestampInMs == null ? fallback : timestampInMs;
return toISO8601(time);
}
/**
* Convert the provided unixtimestamp (miliseconds since midnight, January 1, 1970 UTC) to an ISO8601 string.
*
* @param timeInMs
* @return
*/
public static String toISO8601(long timeInMs) {
return toZonedDateTime(timeInMs).format(DateTimeFormatter.ISO_INSTANT);
}
/**
* Convert the provided unixtimestamp (miliseconds since midnight, January 1, 1970 UTC) to zoned date time
*
* @param timeInMs
* @return
*/
public static ZonedDateTime toZonedDateTime(long timeInMs) {
return Instant.ofEpochMilli(timeInMs).atZone(ZoneOffset.UTC);
}
/**
* Convert the given data string from ISO8601 format back to a unixtimestamp.
*
* @param dateString
* @return
*/
public static Long fromISO8601(String dateString) {
return fromISO8601(dateString, false);
}
/**
* Converts the provided date string into an unixtimestamp value.
*
* @param dateString
* @param failOnFormatError
* @return Unixtimestamp value or null if the provided date string was also null.
*/
public static Long fromISO8601(String dateString, boolean failOnFormatError) {
if (dateString == null) {
return null;
}
try {
OffsetDateTime odt = OffsetDateTime.parse(dateString);
return odt.toInstant().toEpochMilli();
} catch (DateTimeParseException e) {
if (log.isDebugEnabled()) {
log.debug("Error while parsing date {" + dateString + "}. Using fallback.", e);
}
try {
// We also support date strings which do not include an offset. We apply the system offset in those cases.
Long date = LocalDateTime.parse(dateString).toInstant(zoneOffset).toEpochMilli();
return date;
} catch (DateTimeParseException e2) {
if (log.isDebugEnabled()) {
log.debug("Fallback failed with exception", e);
}
if (failOnFormatError) {
throw error(BAD_REQUEST, "error_date_format_invalid", dateString);
}
}
}
return null;
}
/**
* Check whether the date can be parsed.
*
* @param dateString
* @return
*/
public static boolean isDate(String dateString) {
Long date = fromISO8601(dateString);
return date != null;
}
}
| 1,142 |
413 | <filename>reproc/src/clock.windows.c<gh_stars>100-1000
#define _WIN32_WINNT _WIN32_WINNT_VISTA
#include "clock.h"
#include <windows.h>
int64_t now(void)
{
return (int64_t) GetTickCount64();
}
| 87 |
348 | <gh_stars>100-1000
{"nom":"Laruscade","circ":"11ème circonscription","dpt":"Gironde","inscrits":1879,"abs":1230,"votants":649,"blancs":5,"nuls":51,"exp":593,"res":[{"nuance":"REM","nom":"<NAME>","voix":298},{"nuance":"FN","nom":"<NAME>","voix":295}]} | 101 |
2,337 | <reponame>WSLUser/c2rust
// Unlike struct or union, there are no forward-declared enums in C. However,
// the Enlightenment Foundation Libraries, and possibly other code, contains
// code containing this pattern:
typedef enum _Evas_Filter_Support Evas_Filter_Support;
struct _Evas_Func
{
Evas_Filter_Support (*gfx_filter_supports) (void *engine, void *cmd);
};
// dummy item imported by `test_enums.rs`
int foo(int i) { return i;} | 143 |
31,928 | from localstack.services.generic_proxy import UrlMatchingForwarder
class TestUrlMatchingForwarder:
def test_matches_with_root_path_without_host(self):
forwarder = UrlMatchingForwarder("/", "http://localhost")
assert not forwarder.matches("", "")
assert forwarder.matches("", "/")
assert forwarder.matches("", "/fo")
assert forwarder.matches("", "/foo")
assert forwarder.matches("", "/foo/")
assert forwarder.matches("", "/foo/bar")
assert forwarder.matches("", "/fooo")
assert forwarder.matches("example.com", "/")
assert forwarder.matches("example.com", "/fo")
assert forwarder.matches("example.com", "/foo")
assert forwarder.matches("example.com", "/foo/")
assert forwarder.matches("example.com", "/foo/bar")
assert forwarder.matches("example.com", "/fooo")
assert forwarder.matches("localhost", "/")
assert forwarder.matches("localhost", "/fo")
assert forwarder.matches("localhost", "/foo")
assert forwarder.matches("localhost", "/foo/")
assert forwarder.matches("localhost", "/foo/bar")
assert forwarder.matches("localhost", "/fooo")
assert forwarder.matches("localhost:8080", "/")
assert forwarder.matches("localhost:8080", "/foo")
assert forwarder.matches("localhost:8080", "/foo/bar")
assert forwarder.matches("localhost", "/fooo")
def test_matches_with_path_without_host(self):
forwarder = UrlMatchingForwarder("/foo", "http://localhost")
assert not forwarder.matches("", "")
assert not forwarder.matches("", "/")
assert not forwarder.matches("", "/fo")
assert forwarder.matches("", "/foo")
assert forwarder.matches("", "/foo/")
assert forwarder.matches("", "/foo/bar")
assert not forwarder.matches("", "/fooo")
assert not forwarder.matches("example.com", "/")
assert not forwarder.matches("example.com", "/fo")
assert forwarder.matches("example.com", "/foo")
assert forwarder.matches("example.com", "/foo/")
assert forwarder.matches("example.com", "/foo/bar")
assert not forwarder.matches("example.com", "/fooo")
assert not forwarder.matches("localhost", "/")
assert not forwarder.matches("localhost", "/fo")
assert forwarder.matches("localhost", "/foo")
assert forwarder.matches("localhost", "/foo/")
assert forwarder.matches("localhost", "/foo/bar")
assert not forwarder.matches("localhost", "/fooo")
assert not forwarder.matches("localhost:8080", "/")
assert forwarder.matches("localhost:8080", "/foo")
assert forwarder.matches("localhost:8080", "/foo/bar")
def test_matches_without_path_with_host(self):
forwarder = UrlMatchingForwarder("http://example.com", "http://localhost")
assert not forwarder.matches("", "")
assert not forwarder.matches("", "/")
assert not forwarder.matches("", "/fo")
assert not forwarder.matches("", "/foo")
assert not forwarder.matches("", "/foo/")
assert not forwarder.matches("", "/foo/bar")
assert not forwarder.matches("", "/fooo")
assert forwarder.matches("example.com", "")
assert forwarder.matches("example.com", "/")
assert forwarder.matches("example.com", "/fo")
assert forwarder.matches("example.com", "/foo")
assert forwarder.matches("example.com", "/foo/")
assert forwarder.matches("example.com", "/foo/bar")
assert forwarder.matches("example.com", "/fooo")
assert not forwarder.matches("localhost", "/")
assert not forwarder.matches("localhost", "/fo")
assert not forwarder.matches("localhost", "/foo")
assert not forwarder.matches("localhost", "/foo/")
assert not forwarder.matches("localhost", "/foo/bar")
assert not forwarder.matches("localhost", "/fooo")
assert not forwarder.matches("localhost:8080", "/")
assert not forwarder.matches("localhost:8080", "/foo")
assert not forwarder.matches("localhost:8080", "/foo/bar")
def test_matches_with_path_with_host(self):
forwarder = UrlMatchingForwarder("http://example.com/foo", "http://localhost")
assert not forwarder.matches("", "")
assert not forwarder.matches("", "/")
assert not forwarder.matches("", "/fo")
assert not forwarder.matches("", "/foo")
assert not forwarder.matches("", "/foo/")
assert not forwarder.matches("", "/foo/bar")
assert not forwarder.matches("", "/fooo")
assert not forwarder.matches("example.com", "")
assert not forwarder.matches("example.com", "/")
assert not forwarder.matches("example.com", "/fo")
assert forwarder.matches("example.com", "/foo")
assert forwarder.matches("example.com", "/foo/")
assert forwarder.matches("example.com", "/foo/bar")
assert not forwarder.matches("example.com", "/fooo")
assert not forwarder.matches("localhost", "")
assert not forwarder.matches("localhost", "/")
assert not forwarder.matches("localhost", "/fo")
assert not forwarder.matches("localhost", "/foo")
assert not forwarder.matches("localhost", "/foo/")
assert not forwarder.matches("localhost", "/foo/bar")
assert not forwarder.matches("localhost", "/fooo")
assert not forwarder.matches("localhost:8080", "/")
assert not forwarder.matches("localhost:8080", "")
assert not forwarder.matches("localhost:8080", "/foo")
assert not forwarder.matches("localhost:8080", "/foo/bar")
def test_matches_with_path_with_host_and_port(self):
forwarder = UrlMatchingForwarder("http://localhost:8080/foo", "http://localhost")
assert not forwarder.matches("", "")
assert not forwarder.matches("", "/")
assert not forwarder.matches("", "/fo")
assert not forwarder.matches("", "/foo")
assert not forwarder.matches("", "/foo/")
assert not forwarder.matches("", "/foo/bar")
assert not forwarder.matches("", "/fooo")
assert not forwarder.matches("example.com", "")
assert not forwarder.matches("example.com", "/")
assert not forwarder.matches("example.com", "/fo")
assert not forwarder.matches("example.com", "/foo")
assert not forwarder.matches("example.com", "/foo/")
assert not forwarder.matches("example.com", "/foo/bar")
assert not forwarder.matches("example.com", "/fooo")
assert not forwarder.matches("localhost", "")
assert not forwarder.matches("localhost", "/")
assert not forwarder.matches("localhost", "/fo")
assert not forwarder.matches("localhost", "/foo")
assert not forwarder.matches("localhost", "/foo/")
assert not forwarder.matches("localhost", "/foo/bar")
assert not forwarder.matches("localhost", "/fooo")
assert not forwarder.matches("localhost:8080", "/")
assert not forwarder.matches("localhost:8080", "")
assert forwarder.matches("localhost:8080", "/foo")
assert forwarder.matches("localhost:8080", "/foo/bar")
def test_build_forward_url_with_host(self):
forwarder = UrlMatchingForwarder("/", "http://localhost")
def geturl(host, path):
return forwarder.build_forward_url(host, path).geturl()
assert geturl("", "/") == "http://localhost"
assert geturl("", "/fo") == "http://localhost/fo"
assert geturl("", "/foo") == "http://localhost/foo"
assert geturl("", "/foo/") == "http://localhost/foo/"
assert geturl("", "/foo/bar") == "http://localhost/foo/bar"
assert geturl("", "/fooo") == "http://localhost/fooo"
assert geturl("example.com", "/") == "http://localhost"
assert geturl("example.com", "/fo") == "http://localhost/fo"
assert geturl("example.com", "/foo") == "http://localhost/foo"
assert geturl("example.com", "/foo/") == "http://localhost/foo/"
assert geturl("example.com", "/foo/bar") == "http://localhost/foo/bar"
assert geturl("example.com", "/fooo") == "http://localhost/fooo"
assert geturl("localhost", "/") == "http://localhost"
assert geturl("localhost", "/fo") == "http://localhost/fo"
assert geturl("localhost", "/foo") == "http://localhost/foo"
assert geturl("localhost", "/foo/") == "http://localhost/foo/"
assert geturl("localhost", "/foo/bar") == "http://localhost/foo/bar"
assert geturl("localhost", "/fooo") == "http://localhost/fooo"
assert geturl("localhost:8080", "/") == "http://localhost"
assert geturl("localhost:8080", "/foo") == "http://localhost/foo"
assert geturl("localhost:8080", "/foo/bar") == "http://localhost/foo/bar"
def test_build_forward_url_with_host_and_path(self):
forwarder = UrlMatchingForwarder("/", "http://localhost/p")
def geturl(host, path):
return forwarder.build_forward_url(host, path).geturl()
assert geturl("", "/") == "http://localhost/p"
assert geturl("", "/fo") == "http://localhost/p/fo"
assert geturl("", "/foo") == "http://localhost/p/foo"
assert geturl("", "/foo/") == "http://localhost/p/foo/"
assert geturl("", "/foo/bar") == "http://localhost/p/foo/bar"
assert geturl("", "/fooo") == "http://localhost/p/fooo"
assert geturl("example.com", "/") == "http://localhost/p"
assert geturl("example.com", "/fo") == "http://localhost/p/fo"
assert geturl("example.com", "/foo") == "http://localhost/p/foo"
assert geturl("example.com", "/foo/") == "http://localhost/p/foo/"
assert geturl("example.com", "/foo/bar") == "http://localhost/p/foo/bar"
assert geturl("example.com", "/fooo") == "http://localhost/p/fooo"
assert geturl("localhost", "/") == "http://localhost/p"
assert geturl("localhost", "/fo") == "http://localhost/p/fo"
assert geturl("localhost", "/foo") == "http://localhost/p/foo"
assert geturl("localhost", "/foo/") == "http://localhost/p/foo/"
assert geturl("localhost", "/foo/bar") == "http://localhost/p/foo/bar"
assert geturl("localhost", "/fooo") == "http://localhost/p/fooo"
assert geturl("localhost:8080", "/") == "http://localhost/p"
assert geturl("localhost:8080", "/foo") == "http://localhost/p/foo"
assert geturl("localhost:8080", "/foo/bar") == "http://localhost/p/foo/bar"
def test_build_forward_url_with_host_and_trailing_path(self):
forwarder = UrlMatchingForwarder("/", "http://localhost/p/")
def geturl(host, path):
return forwarder.build_forward_url(host, path).geturl()
assert geturl("", "/") == "http://localhost/p/"
assert geturl("", "/fo") == "http://localhost/p/fo"
assert geturl("localhost", "/") == "http://localhost/p/"
assert geturl("localhost", "/fo") == "http://localhost/p/fo"
def test_build_forward_url_with_host_and_subpath(self):
forwarder = UrlMatchingForwarder("/foo", "http://localhost:1234/oof")
def geturl(host, path):
return forwarder.build_forward_url(host, path).geturl()
assert geturl("", "/foo") == "http://localhost:1234/oof"
assert geturl("", "/foo/") == "http://localhost:1234/oof/"
assert geturl("", "/foo/bar") == "http://localhost:1234/oof/bar"
assert geturl("", "/foo/bar/") == "http://localhost:1234/oof/bar/"
def test_build_forward_url_with_path(self):
forwarder = UrlMatchingForwarder("/", "/p")
def geturl(host, path):
return forwarder.build_forward_url(host, path).geturl()
assert geturl("", "/") == "/p"
assert geturl("", "/fo") == "/p/fo"
assert geturl("", "/foo") == "/p/foo"
assert geturl("", "/foo/") == "/p/foo/"
assert geturl("", "/foo/bar") == "/p/foo/bar"
assert geturl("", "/fooo") == "/p/fooo"
assert geturl("example.com", "/") == "example.com/p"
assert geturl("example.com", "/fo") == "example.com/p/fo"
assert geturl("example.com", "/foo") == "example.com/p/foo"
assert geturl("example.com", "/foo/") == "example.com/p/foo/"
assert geturl("example.com", "/foo/bar") == "example.com/p/foo/bar"
assert geturl("example.com", "/fooo") == "example.com/p/fooo"
assert geturl("localhost", "/") == "localhost/p"
assert geturl("localhost", "/fo") == "localhost/p/fo"
assert geturl("localhost", "/foo") == "localhost/p/foo"
assert geturl("localhost", "/foo/") == "localhost/p/foo/"
assert geturl("localhost", "/foo/bar") == "localhost/p/foo/bar"
assert geturl("localhost", "/fooo") == "localhost/p/fooo"
assert geturl("localhost:8080", "/") == "localhost:8080/p"
assert geturl("localhost:8080", "/foo") == "localhost:8080/p/foo"
assert geturl("localhost:8080", "/foo/bar") == "localhost:8080/p/foo/bar"
def test_forward_request(self, httpserver):
httpserver.expect_request("/baz", method="GET").respond_with_data("baz")
forwarder = UrlMatchingForwarder("/foo", httpserver.url_for("/baz"))
# not matching
response = forwarder.forward_request("GET", "/fooo", "", {})
assert response is True
response = forwarder.forward_request("GET", "/foo", "", {})
assert response is not True
assert response.text == "baz"
httpserver.expect_request("/baz/bar", method="GET").respond_with_data("baz/bar")
response = forwarder.forward_request("GET", "/foo/bar", "", {})
assert response is not True
assert response.text == "baz/bar"
httpserver.check()
| 5,525 |
9,156 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker.service;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.apache.pulsar.common.policies.data.PublishRate;
import org.testng.annotations.Test;
public class PrecisPublishLimiterTest {
@Test
void shouldResetMsgLimitAfterUpdate() {
PrecisPublishLimiter precisPublishLimiter = new PrecisPublishLimiter(new PublishRate(), () -> {
});
precisPublishLimiter.update(new PublishRate(1, 1));
assertFalse(precisPublishLimiter.tryAcquire(99, 99));
precisPublishLimiter.update(new PublishRate(-1, 100));
assertTrue(precisPublishLimiter.tryAcquire(99, 99));
}
@Test
void shouldResetBytesLimitAfterUpdate() {
PrecisPublishLimiter precisPublishLimiter = new PrecisPublishLimiter(new PublishRate(), () -> {
});
precisPublishLimiter.update(new PublishRate(1, 1));
assertFalse(precisPublishLimiter.tryAcquire(99, 99));
precisPublishLimiter.update(new PublishRate(100, -1));
assertTrue(precisPublishLimiter.tryAcquire(99, 99));
}
@Test
void shouldCloseResources() throws Exception {
for (int i = 0; i < 20000; i++) {
PrecisPublishLimiter precisPublishLimiter = new PrecisPublishLimiter(new PublishRate(100, 100), () -> {
});
precisPublishLimiter.tryAcquire(99, 99);
precisPublishLimiter.close();
}
}
} | 803 |
778 | <reponame>262986832/pulsar<gh_stars>100-1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker;
import java.util.UUID;
import org.mockito.Mockito;
/**
* Holds util methods used in test.
*/
public class BrokerTestUtil {
// Generate unique name for different test run.
public static String newUniqueName(String prefix) {
return prefix + "-" + UUID.randomUUID();
}
/**
* Creates a Mockito spy directly without an intermediate instance to spy.
* This is to address flaky test issue where a spy created with a given instance fails with
* {@link org.mockito.exceptions.misusing.WrongTypeOfReturnValue} exception.
*
* @param classToSpy the class to spy
* @param args the constructor arguments to use when creating the spy instance
* @return a spy of the provided class created with given constructor arguments
*/
public static <T> T spyWithClassAndConstructorArgs(Class<T> classToSpy, Object... args) {
return Mockito.mock(classToSpy, Mockito.withSettings()
.useConstructor(args)
.defaultAnswer(Mockito.CALLS_REAL_METHODS));
}
}
| 599 |
575 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/emoji/emoji_ui.h"
#include "ash/public/cpp/tablet_mode.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/views/bubble/bubble_contents_wrapper.h"
#include "chrome/browser/ui/views/bubble/bubble_contents_wrapper_service.h"
#include "chrome/browser/ui/views/bubble/bubble_contents_wrapper_service_factory.h"
#include "chrome/browser/ui/views/bubble/webui_bubble_dialog_view.h"
#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/emoji_picker_resources.h"
#include "chrome/grit/emoji_picker_resources_map.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/emoji/emoji_panel_helper.h"
#include "ui/base/ime/chromeos/ime_bridge.h"
#include "ui/resources/grit/webui_generated_resources.h"
#include <iostream>
namespace {
constexpr gfx::Size kDefaultWindowSize(340, 390);
class EmojiiBubbleDialogView : public WebUIBubbleDialogView {
public:
EmojiiBubbleDialogView(
std::unique_ptr<BubbleContentsWrapper> contents_wrapper)
: WebUIBubbleDialogView(nullptr, contents_wrapper.get()),
contents_wrapper_(std::move(contents_wrapper)) {}
private:
std::unique_ptr<BubbleContentsWrapper> contents_wrapper_;
};
} // namespace
namespace chromeos {
EmojiUI::EmojiUI(content::WebUI* web_ui)
: ui::MojoBubbleWebUIController(web_ui,
true /* Needed for webui browser tests */) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIEmojiPickerHost);
source->UseStringsJs();
// Add required resources.
webui::SetupWebUIDataSource(
source, base::make_span(kEmojiPickerResources, kEmojiPickerResourcesSize),
IDR_EMOJI_PICKER_INDEX_HTML);
content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
source);
}
EmojiUI::~EmojiUI() = default;
void EmojiUI::Show(Profile* profile) {
if (ash::TabletMode::Get()->InTabletMode()) {
ui::ShowTabletModeEmojiPanel();
return;
}
ui::InputMethod* input_method =
ui::IMEBridge::Get()->GetInputContextHandler()->GetInputMethod();
ui::TextInputClient* input_client =
input_method ? input_method->GetTextInputClient() : nullptr;
const bool incognito_mode =
input_client ? !input_client->ShouldDoLearning() : false;
const gfx::Rect caret_bounds =
input_client ? input_client->GetCaretBounds() : gfx::Rect();
// This rect is used for positioning the emoji picker. All that really
// matters is a position, so it has 0 height/width
auto anchor_rect = gfx::Rect(caret_bounds.x() + kDefaultWindowSize.width(),
caret_bounds.bottom(), 0, 0);
// TODO(b/181703133): Refactor so that the webui_bubble_manager can be used
// here to reduce code duplication.
auto contents_wrapper = std::make_unique<BubbleContentsWrapperT<EmojiUI>>(
GURL(chrome::kChromeUIEmojiPickerURL), profile, IDS_ACCNAME_EMOJI_PICKER,
false /*enable_extension_apis*/);
// Need to reload the web contents here because the view isn't visible unless
// ShowUI is called from the JS side. By reloading, we trigger the JS to
// eventually call ShowUI().
contents_wrapper->ReloadWebContents();
contents_wrapper->GetWebUIController()->incognito_mode_ = incognito_mode;
auto bubble_view =
std::make_unique<EmojiiBubbleDialogView>(std::move(contents_wrapper));
auto weak_ptr = bubble_view->GetWeakPtr();
views::BubbleDialogDelegateView::CreateBubble(std::move(bubble_view));
weak_ptr->SetAnchorRect(anchor_rect);
weak_ptr->set_adjust_if_offscreen(true);
}
WEB_UI_CONTROLLER_TYPE_IMPL(EmojiUI)
void EmojiUI::BindInterface(
mojo::PendingReceiver<emoji_picker::mojom::PageHandlerFactory> receiver) {
page_factory_receiver_.reset();
page_factory_receiver_.Bind(std::move(receiver));
}
void EmojiUI::CreatePageHandler(
mojo::PendingReceiver<emoji_picker::mojom::PageHandler> receiver) {
page_handler_ = std::make_unique<EmojiPageHandler>(
std::move(receiver), web_ui(), this, incognito_mode_);
}
} // namespace chromeos
| 1,691 |
1,178 | <reponame>leozz37/makani
#!/usr/bin/python
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate the aio_node_to_ip_address.c file."""
import os
import sys
import textwrap
from makani.avionics.network import network_config
def _WriteIpAddresses(output_dir, script_name, aio_nodes):
"""Write aio_node_to_ip_address.c.
Args:
output_dir: The directory in which to output the files.
script_name: This script's filename.
aio_nodes: The 'aio_nodes' field of the YAML file.
"""
parts = [textwrap.dedent("""
// Generated by {name}; do not edit.
#include "avionics/network/aio_node_to_ip_address.h"
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include "avionics/common/network_config.h"
#include "avionics/network/aio_node.h"
static uint8_t AioNodeToFinalOctet(AioNode node) {{
switch (node) {{
default:
case kAioNodeForceSigned:
case kNumAioNodes:
assert(false);
return 0;"""[1:]).format(name=script_name)]
octet_to_node = {}
for node in aio_nodes:
octet_to_node[node.ip_octet] = node.enum_name
parts.append(' case %s:' % node.enum_name)
parts.append(' return %d;' % node.ip_octet)
parts.append(textwrap.dedent("""
}
}
// Returns the unicast IP address for a given AioNode.
//
// TODO: Renumber all IPs such that each node type gets a range of 20
// addresses.
IpAddress AioNodeToIpAddress(AioNode node) {
bool valid = node > kAioNodeForceSigned && node < kNumAioNodes;
assert(valid);
if (!valid) return (IpAddress) {0, 0, 0, 0};
return (IpAddress) {192, 168, 1, AioNodeToFinalOctet(node)};
}
AioNode FinalOctetToAioNode(uint8_t final_octet) {
switch (final_octet) {"""[1:]))
for i in sorted(list(octet_to_node)):
parts.append(' case %s:' % i)
parts.append(' return %s;' % octet_to_node[i])
parts.append(' default:')
parts.append(' return kAioNodeUnknown;')
parts.append(' }')
parts.append('}\n')
file_name = os.path.join(output_dir, 'aio_node_to_ip_address.c')
with open(file_name, 'w') as f:
f.write('\n'.join(parts))
def main(argv):
flags, argv = network_config.ParseGenerationFlags(argv)
config = network_config.NetworkConfig(flags.network_file)
script_name = os.path.basename(argv[0])
_WriteIpAddresses(flags.output_dir, script_name, config.aio_nodes)
if __name__ == '__main__':
main(sys.argv)
| 1,184 |
339 | <filename>integration/mediation-tests/tests-ui/src/test/java/org/wso2/carbon/esb/ui/test/proxyadmin/ESBJAVA_2841TestCase.java
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.esb.ui.test.proxyadmin;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.extensions.selenium.BrowserManager;
import org.wso2.esb.integration.common.ui.page.LoginPage;
import org.wso2.esb.integration.common.utils.ESBIntegrationUITest;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class ESBJAVA_2841TestCase extends ESBIntegrationUITest {
private WebDriver driver;
@BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
super.init();
loadESBConfigurationFromClasspath("artifacts/ESB/synapseconfig/proxyadmin/log_with_custom_property.xml");
driver = BrowserManager.getWebDriver();
driver.get(getLoginURL());
TimeUnit.SECONDS.sleep(2);
}
@Test(groups = "wso2.esb", description = "verify log mediator can be accessed via mgmt console with custom properties")
public void addLogMediatorCustomProperty() throws Exception {
LoginPage logPage = new LoginPage(driver);
logPage.loginAs(userInfo.getUserName(), userInfo.getPassword());
//Click on API view
driver.findElement(By.linkText("List")).click();
//Reading the table of APIs
WebElement table = driver.findElement(By.id("sgTable"));
//getting all the rows
List<WebElement> allRows = table.findElements(By.tagName("tr"));
outerLoop:
for (WebElement row : allRows) {
List<WebElement> cells = row.findElements(By.tagName("nobr"));
//Selecting the LogMediatorProxy service
for (WebElement proxyService : cells) {
if (proxyService.getText().equals("LogMediatorProxy")) {
//go to Edit -> Design view
row.findElement(By.linkText("Design View")).click();
driver.findElement(By.id("nextBtn")).click();
//clicking the edit button of in sequence
driver.findElement(By.id("inAnonAddEdit")).click();
//look for the log mediator
WebElement logMediator = driver.findElement(By.linkText("Log"));
logMediator.click();
TimeUnit.SECONDS.sleep(1);
// look for the 'Add Property' link
driver.findElement(By.linkText("Add Property")).click();
// specify the name for the custom property
driver.findElement(By.xpath("//*[@id=\"propertyName0\"]")).sendKeys("testProperty");
// specify the value for the custom property
driver.findElement(By.xpath("//*[@id=\"propertyValue0\"]")).sendKeys("testValue");
// add the property
driver.findElement(By.xpath("//*[@id=\"mediator-editor-form\"]/table/tbody/tr/td[1]/input[4]")).click();
TimeUnit.SECONDS.sleep(1);
// check if loading the log mediator editor works now
logMediator.click();
//checking the log mediator editor is successfully loaded
String logMediatorEditorText = driver.findElement(By.xpath("//*[@id=\"mediator-editor-form\"]/div/table/tbody/tr[1]/td/h2")).getText();
Assert.assertEquals(logMediatorEditorText, "Log Mediator", "Log mediator editor did not load properly");
/***
* need to check with error message without the patch
*/
TimeUnit.SECONDS.sleep(1);
break outerLoop;
}
}
}
TimeUnit.SECONDS.sleep(2);
}
@AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
driver.close();
super.cleanup();
}
}
| 2,057 |
995 | <gh_stars>100-1000
/*=============================================================================
Copyright (c) 2015 <NAME>
and.h
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_HOF_GUARD_AND_H
#define BOOST_HOF_GUARD_AND_H
#include <type_traits>
#include <boost/hof/detail/using.hpp>
#include <boost/hof/detail/intrinsics.hpp>
namespace boost { namespace hof { namespace detail {
constexpr bool and_c()
{
return true;
}
template<class... Ts>
constexpr bool and_c(bool b, Ts... bs)
{
return b && and_c(bs...);
}
#ifdef _MSC_VER
template<class... Ts>
struct and_;
template<class T, class... Ts>
struct and_<T, Ts...>
: std::integral_constant<bool, (T::value && and_<Ts...>::value)>
{};
template<>
struct and_<>
: std::true_type
{};
#define BOOST_HOF_AND_UNPACK(Bs) (boost::hof::detail::and_c(Bs...))
#else
template<bool...> struct bool_seq {};
template<class... Ts>
BOOST_HOF_USING(and_, std::is_same<bool_seq<Ts::value...>, bool_seq<(Ts::value, true)...>>);
#define BOOST_HOF_AND_UNPACK(Bs) BOOST_HOF_IS_BASE_OF(boost::hof::detail::bool_seq<Bs...>, boost::hof::detail::bool_seq<(Bs || true)...>)
#endif
}}} // namespace boost::hof
#endif
| 570 |
460 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "list.h"
List* List_push(List **list, void *data) {
List *newnode;
if(!(newnode = malloc(sizeof(newnode)))) {
return NULL;
}
newnode->data = data;
newnode->next = *list;
*list = newnode;
fprintf(stdout, "list item data pointer %p.\n", data);
return newnode;
}
/*
* Note that this function only calls free() for the node, not whatever
* is contained in the data
*/
int List_remove(List **list, List *node){
List *current = *list;
if(current == node) {
// need to delete head item
*list = node->next;
free(node);
return 0;
}
while(current->next && current->next != node) {
current = current->next;
}
if(!current) {
// not found e.g. reached end of list
return -1;
}
// deleting other item
current->next = node->next;
free(node);
return 0;
}
int List_length(List *node) {
int i = 0;
for ( ; node; node = node->next) {
i++;
}
fprintf(stdout, "list length %d.\n", i);
return i;
}
void List_free(List *list) {
List *next;
for( ; list; list = next) {
next = list->next;
free(list);
}
}
int List_map(List *list, int apply(void *item, void *ctxt), void *context) {
int result;
for ( ; list; list = list->next) {
// fprintf(stdout, "apply list item data pointer %p.\n", (void *)list->data);
result = apply(list->data, context);
if(result != 0) {
return result;
}
}
return 0;
}
| 580 |
617 | /*
* Copyright Beijing 58 Information Technology Co.,Ltd.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.bj58.oceanus.result.merger;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.bj58.oceanus.core.jdbc.result.ColumnFinder;
import com.bj58.oceanus.core.jdbc.result.RowSet;
import com.bj58.oceanus.core.jdbc.result.RowSetCreator;
import com.bj58.oceanus.core.jdbc.result.SimpleRowSet;
/**
* DefaultRowSetCreator
*
* @author Service Platform Architecture Team (<EMAIL>)
*/
public class DefaultRowSetCreator implements RowSetCreator {
@Override
public RowSet create(ResultSet resultSet, ColumnFinder columnFinder) throws SQLException {
int count=resultSet.getMetaData().getColumnCount();
Object []values=new Object[count];
for(int i=0;i<values.length;i++){
values[i]=resultSet.getObject(i+1);
}
SimpleRowSet rowSet=new SimpleRowSet(values,columnFinder);
rowSet.setResultSet(resultSet);
return rowSet;
}
}
| 549 |
4,081 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio;
import alluxio.conf.SensitiveConfigMask;
import alluxio.conf.CredentialPropertyKeys;
import alluxio.grpc.MountPOptions;
import alluxio.grpc.MountPRequest;
import alluxio.grpc.UfsInfo;
import alluxio.grpc.GetUfsInfoPResponse;
import alluxio.grpc.UpdateMountPRequest;
import org.slf4j.Logger;
import java.util.Map.Entry;
import java.util.Map;
/**
* RpcSensitiveConfigMask is going to mask the credential RPC messages.
*/
public class RpcSensitiveConfigMask implements SensitiveConfigMask {
public static final RpcSensitiveConfigMask CREDENTIAL_FIELD_MASKER;
static {
CREDENTIAL_FIELD_MASKER = new RpcSensitiveConfigMask();
}
@Override
public Object[] maskObjects(Logger logger, Object... args) {
/**
* This function is to mask MountPOption, and those who are referring to it.
* If something else need be masked, extra code change is required.
* And also if a new proto message referring direct/indirect to MountPOption,
* extra code should be added here.
*/
Object [] objects = new Object[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof MountPOptions) {
MountPOptions.Builder newMP = MountPOptions.newBuilder((MountPOptions) args[i]);
newMP.clearProperties();
copyAndMaskProperties(newMP, ((MountPOptions) args[i]).getPropertiesMap());
objects[i] = newMP.build();
} else if (args[i] instanceof MountPRequest) {
MountPRequest.Builder mpR = MountPRequest.newBuilder((MountPRequest) args[i]);
MountPOptions.Builder newMP = mpR.getOptionsBuilder();
newMP.clearProperties();
copyAndMaskProperties(newMP, ((MountPRequest) args[i]).getOptions().getPropertiesMap());
objects[i] = mpR.build();
} else if (args[i] instanceof UfsInfo) {
UfsInfo.Builder ufsInfo = UfsInfo.newBuilder((UfsInfo) args[i]);
MountPOptions.Builder newMP = ufsInfo.getPropertiesBuilder();
newMP.clearProperties();
copyAndMaskProperties(newMP, ((UfsInfo) args[i]).getProperties().getPropertiesMap());
objects[i] = ufsInfo.build();
} else if (args[i] instanceof GetUfsInfoPResponse) {
GetUfsInfoPResponse.Builder getUfsInfoResponse =
GetUfsInfoPResponse.newBuilder((GetUfsInfoPResponse) args[i]);
MountPOptions.Builder newMP = getUfsInfoResponse.getUfsInfoBuilder().getPropertiesBuilder();
newMP.clearProperties();
copyAndMaskProperties(newMP,
((GetUfsInfoPResponse) args[i]).getUfsInfo().getProperties().getPropertiesMap());
objects[i] = getUfsInfoResponse.build();
} else if (args[i] instanceof UpdateMountPRequest) {
UpdateMountPRequest.Builder updateMountPRequest =
UpdateMountPRequest.newBuilder((UpdateMountPRequest) args[i]);
MountPOptions.Builder newMP = updateMountPRequest.getOptionsBuilder();
newMP.clearProperties();
copyAndMaskProperties(newMP, ((UpdateMountPRequest) args[i])
.getOptions().getPropertiesMap());
objects[i] = updateMountPRequest.build();
} else {
objects[i] = args[i];
}
}
return objects;
}
protected void copyAndMaskProperties(MountPOptions.Builder builder, Map<String, String> rawMap) {
for (Entry entry : rawMap.entrySet()) {
if (!CredentialPropertyKeys.getCredentials().contains(entry.getKey())) {
builder.putProperties((String) entry.getKey(), (String) entry.getValue());
} else {
builder.putProperties((String) entry.getKey(), "Masked");
}
}
}
}
| 1,487 |
649 | {"name":"Adding an extraitem to a list with other items","testSteps":[{"number":1,"description":"Given that Jane has a todo list containing Buy some milk, Walk the dog","duration":7603,"startTime":1479990830673,"screenshots":[{"screenshot":"ebebbb33173ae061c12889e251a2df79.png"}],"result":"SUCCESS","children":[{"number":2,"description":"Jane starts with **a todo list containing Buy some milk, Walk the dog**","duration":7399,"startTime":1479990830675,"screenshots":[{"screenshot":"ebebbb33173ae061c12889e251a2df79.png"}],"result":"SUCCESS","children":[{"number":3,"description":"Jane opens the Application home page","duration":4939,"startTime":1479990830677,"screenshots":[{"screenshot":"7a42c9be4bddb8768d94151590250d92.png"}],"result":"SUCCESS"},{"number":4,"description":"Jane adds the todo items called: [Buy some milk, Walk the dog]","duration":2245,"startTime":1479990835627,"screenshots":[{"screenshot":"970146ee75ba53b15da041551ad0cdfa.png"},{"screenshot":"65130ac3f5dbbce16f04368c8e22e1a3.png"}],"result":"SUCCESS","children":[{"number":5,"description":"Jane adds a todo item called: Buy some milk","duration":968,"startTime":1479990835820,"screenshots":[{"screenshot":"970146ee75ba53b15da041551ad0cdfa.png"},{"screenshot":"d9a8a152a6ab122ce52260a2e5539a87.png"}],"result":"SUCCESS","children":[{"number":6,"description":"Jane enters \u0027Buy some milk\u0027 into \u0027What needs to be done?\u0027 field","duration":568,"startTime":1479990836021,"screenshots":[{"screenshot":"e0c534be3e168b7907811c76923f96b8.png"},{"screenshot":"d9a8a152a6ab122ce52260a2e5539a87.png"}],"result":"SUCCESS"}]},{"number":7,"description":"Jane adds a todo item called: Walk the dog","duration":883,"startTime":1479990836789,"screenshots":[{"screenshot":"d9a8a152a6ab122ce52260a2e5539a87.png"},{"screenshot":"65130ac3f5dbbce16f04368c8e22e1a3.png"}],"result":"SUCCESS","children":[{"number":8,"description":"Jane enters \u0027Walk the dog\u0027 into \u0027What needs to be done?\u0027 field","duration":491,"startTime":1479990836981,"screenshots":[{"screenshot":"a3b52d3879ad7afe1ec1476ac1fc51b9.png"},{"screenshot":"65130ac3f5dbbce16f04368c8e22e1a3.png"}],"result":"SUCCESS"}]}]}]}]},{"number":9,"description":"When she adds \u0027Buy some cereal\u0027 to her list","duration":1370,"startTime":1479990838276,"screenshots":[{"screenshot":"65130ac3f5dbbce16f04368c8e22e1a3.png"},{"screenshot":"1523584aa7c98f8bae3ce4b3ef935849.png"}],"result":"SUCCESS","children":[{"number":10,"description":"Jane adds a todo item called: Buy some cereal","duration":926,"startTime":1479990838481,"screenshots":[{"screenshot":"65130ac3f5dbbce16f04368c8e22e1a3.png"},{"screenshot":"1523584aa7c98f8bae3ce4b3ef935849.png"}],"result":"SUCCESS","children":[{"number":11,"description":"Jane enters \u0027Buy some cereal\u0027 into \u0027What needs to be done?\u0027 field","duration":509,"startTime":1479990838684,"screenshots":[{"screenshot":"65130ac3f5dbbce16f04368c8e22e1a3.png"},{"screenshot":"1523584aa7c98f8bae3ce4b3ef935849.png"}],"result":"SUCCESS"}]}]},{"number":12,"description":"Then her todo list should contain Buy some milk, Walk the dog, Buy some cereal","duration":1079,"startTime":1479990839646,"screenshots":[{"screenshot":"ed47554566468dab97452dadaf7ed29c.png"},{"screenshot":"1523584aa7c98f8bae3ce4b3ef935849.png"}],"result":"SUCCESS","children":[{"number":13,"description":"Then the displayed todo items should be ([Buy some milk, Walk the dog, Buy some cereal])","duration":613,"startTime":1479990839853,"screenshots":[{"screenshot":"ed47554566468dab97452dadaf7ed29c.png"},{"screenshot":"1523584aa7c98f8bae3ce4b3ef935849.png"}],"result":"SUCCESS"}]}],"userStory":{"id":"remember-things-to-do","storyName":"Remember things to do","path":"remembering_things_to_do.feature","narrative":"\nIn order to avoid having to remember things that need doing\nAs a forgetful person\nI want to be able to record what I need to do in a place where I won\u0027t forget about them","type":"feature"},"featureTag":{"name":"Remember things to do","type":"feature"},"title":"Adding an extraitem to a list with other items","description":"","tags":[{"name":"Remembering stuff/Remember things to do","type":"feature"},{"name":"cucumber","type":"tag"},{"name":"Remembering stuff","type":"capability"}],"startTime":1479990830670,"duration":10055,"sessionId":"81e755f77a9d30128671dc1070b715e2","driver":"chrome:jane","manual":false,"testSource":"Cucumber","result":"SUCCESS"} | 1,473 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "precompiled_dbaccess.hxx"
#include "settingsimport.hxx"
/** === begin UNO includes === **/
/** === end UNO includes === **/
#include <tools/diagnose_ex.h>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmluconv.hxx>
//........................................................................
namespace dbaccess
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::UNO_SET_THROW;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::makeAny;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Type;
using ::com::sun::star::xml::sax::XAttributeList;
/** === end UNO using === **/
//====================================================================
//= SettingsImport
//====================================================================
//--------------------------------------------------------------------
SettingsImport::SettingsImport()
:m_refCount( 0 )
{
}
//--------------------------------------------------------------------
SettingsImport::~SettingsImport()
{
}
//--------------------------------------------------------------------
oslInterlockedCount SAL_CALL SettingsImport::acquire()
{
return osl_incrementInterlockedCount( &m_refCount );
}
//--------------------------------------------------------------------
oslInterlockedCount SAL_CALL SettingsImport::release()
{
oslInterlockedCount newCount = osl_decrementInterlockedCount( &m_refCount );
if ( newCount == 0 )
delete this;
return newCount;
}
//--------------------------------------------------------------------
void SettingsImport::startElement( const Reference< XAttributeList >& i_rAttributes )
{
// find the name of the setting
if ( i_rAttributes.is() )
{
m_sItemName = i_rAttributes->getValueByName( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "config:name" ) ) );
m_sItemType = i_rAttributes->getValueByName( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "config:type" ) ) );
}
}
//--------------------------------------------------------------------
void SettingsImport::endElement()
{
}
//--------------------------------------------------------------------
void SettingsImport::characters( const ::rtl::OUString& i_rCharacters )
{
m_aCharacters.append( i_rCharacters );
}
//--------------------------------------------------------------------
void SettingsImport::split( const ::rtl::OUString& i_rElementName, ::rtl::OUString& o_rNamespace, ::rtl::OUString& o_rLocalName )
{
o_rNamespace = ::rtl::OUString();
o_rLocalName = i_rElementName;
const sal_Int32 nSeparatorPos = i_rElementName.indexOf( ':' );
if ( nSeparatorPos > -1 )
{
o_rNamespace = i_rElementName.copy( 0, nSeparatorPos );
o_rLocalName = i_rElementName.copy( nSeparatorPos + 1 );
}
OSL_ENSURE( o_rNamespace.equalsAscii( "config" ), "SettingsImport::split: unexpected namespace!" );
// our recovery file is kind of hand-made, so there shouldn't be anything else than "config".
// If there is, then just ignore it ...
}
//====================================================================
//= IgnoringSettingsImport
//====================================================================
//--------------------------------------------------------------------
::rtl::Reference< SettingsImport > IgnoringSettingsImport::nextState( const ::rtl::OUString& i_rElementName )
{
(void)i_rElementName;
return this;
}
//====================================================================
//= OfficeSettingsImport
//====================================================================
//--------------------------------------------------------------------
OfficeSettingsImport::OfficeSettingsImport( ::comphelper::NamedValueCollection& o_rSettings )
:m_rSettings( o_rSettings )
{
}
//--------------------------------------------------------------------
OfficeSettingsImport::~OfficeSettingsImport()
{
}
//--------------------------------------------------------------------
::rtl::Reference< SettingsImport > OfficeSettingsImport::nextState( const ::rtl::OUString& i_rElementName )
{
// separate the namespace part from the element name
::rtl::OUString sNamespace;
::rtl::OUString sLocalName;
split( i_rElementName, sNamespace, sLocalName );
if ( sLocalName.equalsAscii( "config-item-set" ) )
return new ConfigItemSetImport( m_rSettings );
#if OSL_DEBUG_LEVEL > 0
::rtl::OString sMessage( "unknown (or unsupported at this place) element name '" );
sMessage += ::rtl::OUStringToOString( i_rElementName, RTL_TEXTENCODING_UTF8 );
sMessage += "', ignoring";
OSL_ENSURE( false, sMessage.getStr() );
#endif
return new IgnoringSettingsImport;
}
//====================================================================
//= ConfigItemImport
//====================================================================
//--------------------------------------------------------------------
ConfigItemImport::ConfigItemImport( ::comphelper::NamedValueCollection& o_rSettings )
:m_rSettings( o_rSettings )
{
}
//--------------------------------------------------------------------
ConfigItemImport::~ConfigItemImport()
{
}
//--------------------------------------------------------------------
::rtl::Reference< SettingsImport > ConfigItemImport::nextState( const ::rtl::OUString& i_rElementName )
{
OSL_ENSURE( false, "ConfigItemImport::nextState: unexpected: this class is responsible for child-less items only!" );
(void)i_rElementName;
return new IgnoringSettingsImport;
}
//--------------------------------------------------------------------
void ConfigItemImport::endElement()
{
SettingsImport::endElement();
const ::rtl::OUString sItemName( getItemName() );
ENSURE_OR_RETURN_VOID( sItemName.getLength(), "no item name -> no item value" );
Any aValue;
getItemValue( aValue );
m_rSettings.put( sItemName, aValue );
}
//--------------------------------------------------------------------
void ConfigItemImport::getItemValue( ::com::sun::star::uno::Any& o_rValue ) const
{
o_rValue.clear();
// the characters building up th evalue
::rtl::OUStringBuffer aCharacters( getAccumulatedCharacters() );
const ::rtl::OUString sValue = aCharacters.makeStringAndClear();
const ::rtl::OUString& rItemType( getItemType() );
ENSURE_OR_RETURN_VOID( rItemType.getLength(), "no item type -> no item value" );
if ( ::xmloff::token::IsXMLToken( rItemType, ::xmloff::token::XML_INT ) )
{
sal_Int32 nValue(0);
if ( SvXMLUnitConverter::convertNumber( nValue, sValue ) )
o_rValue <<= nValue;
else
{
OSL_ENSURE( false, "ConfigItemImport::getItemValue: could not convert an int value!" );
}
}
else if ( ::xmloff::token::IsXMLToken( rItemType, ::xmloff::token::XML_BOOLEAN ) )
{
sal_Bool nValue( sal_False );
if ( SvXMLUnitConverter::convertBool( nValue, sValue ) )
o_rValue <<= nValue;
else
{
OSL_ENSURE( false, "ConfigItemImport::getItemValue: could not convert a boolean value!" );
}
}
else if ( ::xmloff::token::IsXMLToken( rItemType, ::xmloff::token::XML_STRING ) )
{
o_rValue <<= sValue;
}
#if OSL_DEBUG_LEVEL > 0
else
{
::rtl::OString sMessage( "ConfigItemImport::getItemValue: unsupported item type '" );
sMessage += ::rtl::OUStringToOString( rItemType, RTL_TEXTENCODING_UTF8 );
sMessage += "', ignoring";
OSL_ENSURE( false, sMessage.getStr() );
}
#endif
}
//====================================================================
//= ConfigItemSetImport
//====================================================================
//--------------------------------------------------------------------
ConfigItemSetImport::ConfigItemSetImport( ::comphelper::NamedValueCollection& o_rSettings )
:ConfigItemImport( o_rSettings )
{
}
//--------------------------------------------------------------------
ConfigItemSetImport::~ConfigItemSetImport()
{
}
//--------------------------------------------------------------------
::rtl::Reference< SettingsImport > ConfigItemSetImport::nextState( const ::rtl::OUString& i_rElementName )
{
// separate the namespace part from the element name
::rtl::OUString sNamespace;
::rtl::OUString sLocalName;
split( i_rElementName, sNamespace, sLocalName );
if ( sLocalName.equalsAscii( "config-item-set" ) )
return new ConfigItemSetImport( m_aChildSettings );
if ( sLocalName.equalsAscii( "config-item" ) )
return new ConfigItemImport( m_aChildSettings );
#if OSL_DEBUG_LEVEL > 0
::rtl::OString sMessage( "unknown element name '" );
sMessage += ::rtl::OUStringToOString( i_rElementName, RTL_TEXTENCODING_UTF8 );
sMessage += "', ignoring";
OSL_ENSURE( false, sMessage.getStr() );
#endif
return new IgnoringSettingsImport;
}
//--------------------------------------------------------------------
void ConfigItemSetImport::getItemValue( Any& o_rValue ) const
{
o_rValue <<= m_aChildSettings.getPropertyValues();
}
//........................................................................
} // namespace dbaccess
//........................................................................
| 3,738 |
23,901 | <filename>etcmodel/models/wikihop/wikihop_eval.py
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Binary for WikiHop eval."""
import json
from typing import Any, Dict, List, Text, Tuple
import numpy as np
import tensorflow.compat.v1 as tf
from etcmodel.models import tokenization
from etcmodel.models.wikihop import data_utils
tf.compat.v1.disable_v2_behavior()
flags = tf.flags
FLAGS = flags.FLAGS
FLAGS = flags.FLAGS
# Populate these constants appropriately at the time of submisssion.
MODEL_PATH = "105/"
SPM_MODEL_VOCAB = "vocab_gpt.model"
class WikiHopInference(object):
"""WikiHop for inference / prediction using SavedModel."""
def __init__(self, model_dir_path: Text, session_target: Text):
"""Loads the WikiHop from an exported `tf.SavedModel`.
Args:
model_dir_path: Path to the exported directory of the model.
session_target: The session target.
"""
self.sess = tf.Session(graph=tf.Graph(), target=session_target)
# Loads the saved model (graph + variables) to the given session.
graph_def = tf.saved_model.load(
self.sess,
tags=[tf.saved_model.tag_constants.SERVING],
export_dir=model_dir_path)
signature = graph_def.signature_def[
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]
self.input_tensor_name = signature.inputs["serialized_tf_example"].name
self.logits_tensor_name = signature.outputs["logits"].name
def predict(self,
serialized_tf_examples: List[Text]) -> List[List[List[float]]]:
"""Retrieves logits for the given list of serialized tf examples.
Args:
serialized_tf_examples: Batched input serialized_tf_examples.
Returns:
A List[List[float]] representing the logits. Each entry i in the list
corresponds to the result i-th serialized_tf_example.
"""
feed_dict = {self.input_tensor_name: serialized_tf_examples}
logits = self.sess.run([self.logits_tensor_name], feed_dict=feed_dict)
return logits
def get_serialized_tf_example(wikihop_example: data_utils.WikiHopExample,
tokenizer: tokenization.FullTokenizer,
long_seq_len: int = 4096,
global_seq_len: int = 430,
max_num_sentences: int = 200) -> Text:
"""Returns serialized TF example from the given json example."""
converter = data_utils.WikiHopTFExampleConverter(
tokenizer=tokenizer,
long_seq_len=long_seq_len,
global_seq_len=global_seq_len,
max_num_sentences=max_num_sentences)
tf_example = converter.convert_single_example(example=wikihop_example)
return tf_example.SerializeToString()
def get_predicted_answer(wikihop_example: data_utils.WikiHopExample,
logits: List[float],
global_seq_len: int = 430) -> Text:
"""Returns prediçted answer for the given example and its logits."""
assert len(logits) == global_seq_len, (
"Mismatch in logits len. Expected: {}, found: {}, logits are: {} ".format(
global_seq_len, len(logits), logits))
logits = logits[0:len(wikihop_example.candidate_answers)]
max_label_index = np.argmax(logits)
assert max_label_index >= 0 and (max_label_index < len(
wikihop_example.candidate_answers))
answer = wikihop_example.candidate_answers[max_label_index]
answer = answer.lower().strip()
return answer
def get_output_single_example(
tokenizer: tokenization.FullTokenizer,
wikihop_inference: WikiHopInference,
json_obj: Dict[Text, Any],
long_seq_len: int = 4096,
global_seq_len: int = 430,
max_num_sentences: int = 200) -> Tuple[Text, Text]:
"""Generates output for a single example."""
wikihop_example = data_utils.WikiHopExample.from_json(single_example=json_obj)
serialized_tf_example = get_serialized_tf_example(
wikihop_example=wikihop_example,
tokenizer=tokenizer,
long_seq_len=long_seq_len,
global_seq_len=global_seq_len,
max_num_sentences=max_num_sentences)
logits = wikihop_inference.predict([serialized_tf_example])[0][0]
assert len(logits) == global_seq_len, (
"Mismatch in0 logits len. Expected: {}, found: {} for example_id: {}. "
"Actual logits are: {}".format(global_seq_len, len(logits),
wikihop_example.example_id, logits))
answer = get_predicted_answer(
wikihop_example=wikihop_example,
logits=logits,
global_seq_len=global_seq_len)
return (wikihop_example.example_id, answer)
def generate_eval_output_bulk(json_examples: List[Dict[Text, Any]],
model_dir_path: Text,
tokenizer: tokenization.FullTokenizer,
long_seq_len: int = 4096,
global_seq_len: int = 430,
max_num_sentences: int = 200,
batch_size: int = 4,
session_target: Text = "") -> Dict[Text, Any]:
"""Bulk mode inference."""
serialized_tf_examples = []
wikihop_examples = []
output = {}
for json_obj in json_examples:
wikihop_example = data_utils.WikiHopExample.from_json(
single_example=json_obj)
wikihop_examples.append(wikihop_example)
serialize_tf_example = get_serialized_tf_example(
wikihop_example=wikihop_example,
tokenizer=tokenizer,
long_seq_len=long_seq_len,
global_seq_len=global_seq_len,
max_num_sentences=max_num_sentences)
serialized_tf_examples.append(serialize_tf_example)
wikihop_inference = WikiHopInference(
model_dir_path=model_dir_path, session_target=session_target)
index = 0
num_examples = len(serialized_tf_examples)
# Note that we getting "all" the serialized examples and then "batching"
# only for prediction. The bottleneck is almost always going to be the
# GPU anyway (for both memory and compute).
while index < num_examples:
predict_batch = serialized_tf_examples[index:min(index +
batch_size, num_examples)]
batch_logits = wikihop_inference.predict(predict_batch)[0]
for (offset, logits) in enumerate(batch_logits):
answer = get_predicted_answer(
wikihop_example=wikihop_examples[index + offset],
logits=logits,
global_seq_len=global_seq_len)
output[wikihop_examples[index + offset].example_id] = answer
index += batch_size
return output
def generate_eval_output(json_examples: List[Dict[Text, Any]],
tokenizer: tokenization.FullTokenizer,
model_dir_path: Text,
long_seq_len: int = 4096,
global_seq_len: int = 430,
max_num_sentences: int = 200,
batch_inference: bool = False,
batch_size: int = 4,
session_target: Text = "") -> Dict[Text, Any]:
"""Generates output for the input json.
Returns the dict output key'ed by the example_id, with the value being the
answer string.
Args:
json_examples: List of examples loaded from json input file.
tokenizer: The BERT or ALBERT tokenizer.
model_dir_path: The path to the directory containing the SavedModel.
long_seq_len: The long input.
global_seq_len: The global input.
max_num_sentences: The max num sentences to be used per example.
batch_inference: If True, we batch together all the examples at once for
faster inference. Given that there are only 1K test examples, we might be
able to fit everything in memeroy (500K per example * 1K).
batch_size: Number of examples to be batched in one to predict. Applicable
only when `batch_inference` is set to True.
session_target: The TF session target.
Returns:
Dict[Text, Text] key'ed by the example_id to the corresponding prediction
answer.
"""
output = {}
if batch_inference:
return generate_eval_output_bulk(
json_examples=json_examples,
model_dir_path=model_dir_path,
tokenizer=tokenizer,
long_seq_len=long_seq_len,
global_seq_len=global_seq_len,
max_num_sentences=max_num_sentences,
batch_size=batch_size,
session_target=session_target)
wikihop_inference = WikiHopInference(
model_dir_path=model_dir_path, session_target=session_target)
for json_obj in json_examples:
(example_id, label) = get_output_single_example(
tokenizer=tokenizer,
wikihop_inference=wikihop_inference,
json_obj=json_obj,
long_seq_len=long_seq_len,
global_seq_len=global_seq_len,
max_num_sentences=max_num_sentences)
output[example_id] = label
return output
def main(argv):
if len(argv) != 3:
raise tf.app.UsageError("Exactly two arguments expected.")
input_json_filepath = argv[1].strip()
output_json_filepath = argv[2].strip()
tokenizer = tokenization.FullTokenizer(
vocab_file=None, do_lower_case=None, spm_model_file=SPM_MODEL_VOCAB)
with tf.gfile.Open(input_json_filepath, "r") as test_data:
json_examples = json.load(test_data)
predictions = generate_eval_output(
tokenizer=tokenizer,
json_examples=json_examples,
model_dir_path=MODEL_PATH)
with tf.gfile.GFile(output_json_filepath, "w") as output_writer:
json.dump(predictions, output_writer)
if __name__ == "__main__":
tf.app.run()
| 4,172 |
1,442 | #include "python_text_area.h"
#include "app.h"
#include <escher/palette.h>
#include <ion/unicode/utf8_helper.h>
#include <python/port/port.h>
/* py/parsenum.h is a C header which uses C keyword restrict.
* It does not exist in C++ so we define it here in order to be able to include
* py/parsenum.h header. */
#ifdef __cplusplus
#define restrict // disable
#endif
extern "C" {
#include "py/nlr.h"
#include "py/lexer.h"
#include "py/parsenum.h"
}
#include <stdlib.h>
#include <algorithm>
using namespace Escher;
namespace Code {
constexpr KDColor CommentColor = KDColor::RGB24(0x999988);
constexpr KDColor NumberColor = KDColor::RGB24(0x009999);
constexpr KDColor KeywordColor = KDColor::RGB24(0xFF000C);
// constexpr KDColor BuiltinColor = KDColor::RGB24(0x0086B3);
constexpr KDColor OperatorColor = KDColor::RGB24(0xd73a49);
constexpr KDColor StringColor = KDColor::RGB24(0x032f62);
constexpr KDColor AutocompleteColor = KDColor::RGB24(0xC6C6C6);
constexpr KDColor BackgroundColor = KDColorWhite;
constexpr KDColor HighlightColor = Palette::Select;
constexpr KDColor DefaultColor = KDColorBlack;
static inline KDColor TokenColor(mp_token_kind_t tokenKind) {
if (tokenKind == MP_TOKEN_STRING) {
return StringColor;
}
if (tokenKind == MP_TOKEN_INTEGER || tokenKind == MP_TOKEN_FLOAT_OR_IMAG) {
return NumberColor;
}
static_assert(MP_TOKEN_ELLIPSIS + 1 == MP_TOKEN_KW_FALSE
&& MP_TOKEN_KW_FALSE + 1 == MP_TOKEN_KW_NONE
&& MP_TOKEN_KW_NONE + 1 == MP_TOKEN_KW_TRUE
&& MP_TOKEN_KW_TRUE + 1 == MP_TOKEN_KW___DEBUG__
&& MP_TOKEN_KW___DEBUG__ + 1 == MP_TOKEN_KW_AND
&& MP_TOKEN_KW_AND + 1 == MP_TOKEN_KW_AS
&& MP_TOKEN_KW_AS + 1 == MP_TOKEN_KW_ASSERT
/* Here there are keywords that depend on MICROPY_PY_ASYNC_AWAIT, we do
* not test them */
&& MP_TOKEN_KW_BREAK + 1 == MP_TOKEN_KW_CLASS
&& MP_TOKEN_KW_CLASS + 1 == MP_TOKEN_KW_CONTINUE
&& MP_TOKEN_KW_CONTINUE + 1 == MP_TOKEN_KW_DEF
&& MP_TOKEN_KW_DEF + 1 == MP_TOKEN_KW_DEL
&& MP_TOKEN_KW_DEL + 1 == MP_TOKEN_KW_ELIF
&& MP_TOKEN_KW_ELIF + 1 == MP_TOKEN_KW_ELSE
&& MP_TOKEN_KW_ELSE + 1 == MP_TOKEN_KW_EXCEPT
&& MP_TOKEN_KW_EXCEPT + 1 == MP_TOKEN_KW_FINALLY
&& MP_TOKEN_KW_FINALLY + 1 == MP_TOKEN_KW_FOR
&& MP_TOKEN_KW_FOR + 1 == MP_TOKEN_KW_FROM
&& MP_TOKEN_KW_FROM + 1 == MP_TOKEN_KW_GLOBAL
&& MP_TOKEN_KW_GLOBAL + 1 == MP_TOKEN_KW_IF
&& MP_TOKEN_KW_IF + 1 == MP_TOKEN_KW_IMPORT
&& MP_TOKEN_KW_IMPORT + 1 == MP_TOKEN_KW_IN
&& MP_TOKEN_KW_IN + 1 == MP_TOKEN_KW_IS
&& MP_TOKEN_KW_IS + 1 == MP_TOKEN_KW_LAMBDA
&& MP_TOKEN_KW_LAMBDA + 1 == MP_TOKEN_KW_NONLOCAL
&& MP_TOKEN_KW_NONLOCAL + 1 == MP_TOKEN_KW_NOT
&& MP_TOKEN_KW_NOT + 1 == MP_TOKEN_KW_OR
&& MP_TOKEN_KW_OR + 1 == MP_TOKEN_KW_PASS
&& MP_TOKEN_KW_PASS + 1 == MP_TOKEN_KW_RAISE
&& MP_TOKEN_KW_RAISE + 1 == MP_TOKEN_KW_RETURN
&& MP_TOKEN_KW_RETURN + 1 == MP_TOKEN_KW_TRY
&& MP_TOKEN_KW_TRY + 1 == MP_TOKEN_KW_WHILE
&& MP_TOKEN_KW_WHILE + 1 == MP_TOKEN_KW_WITH
&& MP_TOKEN_KW_WITH + 1 == MP_TOKEN_KW_YIELD
&& MP_TOKEN_KW_YIELD + 1 == MP_TOKEN_OP_TILDE,
"MP_TOKEN order changed, so Code::PythonTextArea::TokenColor might need to change too.");
if (tokenKind >= MP_TOKEN_KW_FALSE && tokenKind <= MP_TOKEN_KW_YIELD) {
return KeywordColor;
}
static_assert(MP_TOKEN_OP_TILDE + 1 == MP_TOKEN_OP_LESS
&& MP_TOKEN_OP_LESS + 1 == MP_TOKEN_OP_MORE
&& MP_TOKEN_OP_MORE + 1 == MP_TOKEN_OP_DBL_EQUAL
&& MP_TOKEN_OP_DBL_EQUAL + 1 == MP_TOKEN_OP_LESS_EQUAL
&& MP_TOKEN_OP_LESS_EQUAL + 1 == MP_TOKEN_OP_MORE_EQUAL
&& MP_TOKEN_OP_MORE_EQUAL + 1 == MP_TOKEN_OP_NOT_EQUAL
&& MP_TOKEN_OP_NOT_EQUAL + 1 == MP_TOKEN_OP_PIPE
&& MP_TOKEN_OP_PIPE + 1 == MP_TOKEN_OP_CARET
&& MP_TOKEN_OP_CARET + 1 == MP_TOKEN_OP_AMPERSAND
&& MP_TOKEN_OP_AMPERSAND + 1 == MP_TOKEN_OP_DBL_LESS
&& MP_TOKEN_OP_DBL_LESS + 1 == MP_TOKEN_OP_DBL_MORE
&& MP_TOKEN_OP_DBL_MORE + 1 == MP_TOKEN_OP_PLUS
&& MP_TOKEN_OP_PLUS + 1 == MP_TOKEN_OP_MINUS
&& MP_TOKEN_OP_MINUS + 1 == MP_TOKEN_OP_STAR
&& MP_TOKEN_OP_STAR + 1 == MP_TOKEN_OP_AT
&& MP_TOKEN_OP_AT + 1 == MP_TOKEN_OP_DBL_SLASH
&& MP_TOKEN_OP_DBL_SLASH + 1 == MP_TOKEN_OP_SLASH
&& MP_TOKEN_OP_SLASH + 1 == MP_TOKEN_OP_PERCENT
&& MP_TOKEN_OP_PERCENT + 1 == MP_TOKEN_OP_DBL_STAR
&& MP_TOKEN_OP_DBL_STAR + 1 == MP_TOKEN_DEL_PIPE_EQUAL
&& MP_TOKEN_DEL_PIPE_EQUAL + 1 == MP_TOKEN_DEL_CARET_EQUAL
&& MP_TOKEN_DEL_CARET_EQUAL + 1 == MP_TOKEN_DEL_AMPERSAND_EQUAL
&& MP_TOKEN_DEL_AMPERSAND_EQUAL + 1 == MP_TOKEN_DEL_DBL_LESS_EQUAL
&& MP_TOKEN_DEL_DBL_LESS_EQUAL + 1 == MP_TOKEN_DEL_DBL_MORE_EQUAL
&& MP_TOKEN_DEL_DBL_MORE_EQUAL + 1 == MP_TOKEN_DEL_PLUS_EQUAL
&& MP_TOKEN_DEL_PLUS_EQUAL + 1 == MP_TOKEN_DEL_MINUS_EQUAL
&& MP_TOKEN_DEL_MINUS_EQUAL + 1 == MP_TOKEN_DEL_STAR_EQUAL
&& MP_TOKEN_DEL_STAR_EQUAL + 1 == MP_TOKEN_DEL_AT_EQUAL
&& MP_TOKEN_DEL_AT_EQUAL + 1 == MP_TOKEN_DEL_DBL_SLASH_EQUAL
&& MP_TOKEN_DEL_DBL_SLASH_EQUAL + 1 == MP_TOKEN_DEL_SLASH_EQUAL
&& MP_TOKEN_DEL_SLASH_EQUAL + 1 == MP_TOKEN_DEL_PERCENT_EQUAL
&& MP_TOKEN_DEL_PERCENT_EQUAL + 1 == MP_TOKEN_DEL_DBL_STAR_EQUAL
&& MP_TOKEN_DEL_DBL_STAR_EQUAL + 1 == MP_TOKEN_DEL_PAREN_OPEN
&& MP_TOKEN_DEL_PAREN_OPEN + 1 == MP_TOKEN_DEL_PAREN_CLOSE
&& MP_TOKEN_DEL_PAREN_CLOSE + 1 == MP_TOKEN_DEL_BRACKET_OPEN
&& MP_TOKEN_DEL_BRACKET_OPEN + 1 == MP_TOKEN_DEL_BRACKET_CLOSE
&& MP_TOKEN_DEL_BRACKET_CLOSE + 1 == MP_TOKEN_DEL_BRACE_OPEN
&& MP_TOKEN_DEL_BRACE_OPEN + 1 == MP_TOKEN_DEL_BRACE_CLOSE
&& MP_TOKEN_DEL_BRACE_CLOSE + 1 == MP_TOKEN_DEL_COMMA
&& MP_TOKEN_DEL_COMMA + 1 == MP_TOKEN_DEL_COLON
&& MP_TOKEN_DEL_COLON + 1 == MP_TOKEN_DEL_PERIOD
&& MP_TOKEN_DEL_PERIOD + 1 == MP_TOKEN_DEL_SEMICOLON
&& MP_TOKEN_DEL_SEMICOLON + 1 == MP_TOKEN_DEL_EQUAL
&& MP_TOKEN_DEL_EQUAL + 1 == MP_TOKEN_DEL_MINUS_MORE,
"MP_TOKEN order changed, so Code::PythonTextArea::TokenColor might need to change too.");
if ((tokenKind >= MP_TOKEN_OP_TILDE && tokenKind <= MP_TOKEN_DEL_DBL_STAR_EQUAL)
|| tokenKind == MP_TOKEN_DEL_EQUAL
|| tokenKind == MP_TOKEN_DEL_MINUS_MORE)
{
return OperatorColor;
}
return DefaultColor;
}
static inline size_t TokenLength(mp_lexer_t * lex, const char * tokenPosition) {
/* The lexer stores the beginning of the current token and of the next token,
* so we just use that. */
if (lex->line > 1) {
/* The next token is on the next line, so we cannot just make the difference
* of the columns. */
return UTF8Helper::CodePointSearch(tokenPosition, '\n') - tokenPosition;
}
return lex->column - lex->tok_column;
}
PythonTextArea::AutocompletionType PythonTextArea::autocompletionType(const char * autocompletionLocation, const char ** autocompletionLocationBeginning, const char ** autocompletionLocationEnd) const {
const char * location = autocompletionLocation != nullptr ? autocompletionLocation : cursorLocation();
const char * beginningOfToken = nullptr;
/* If there is already autocompleting, the cursor must be at the end of an
* identifier. Trying to compute autocompletionType will fail: because of the
* autocompletion text, the cursor seems to be in the middle of an identifier. */
AutocompletionType autocompleteType = isAutocompleting() ? AutocompletionType::EndOfIdentifier : AutocompletionType::NoIdentifier;
if (autocompletionLocationBeginning == nullptr && autocompletionLocationEnd == nullptr) {
return autocompleteType;
}
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
const char * firstNonSpace = UTF8Helper::BeginningOfWord(m_contentView.editedText(), location);
mp_lexer_t * lex = mp_lexer_new_from_str_len(0, firstNonSpace, UTF8Helper::EndOfWord(location) - firstNonSpace, 0);
const char * tokenStart;
const char * tokenEnd;
_mp_token_kind_t currentTokenKind = lex->tok_kind;
while (currentTokenKind != MP_TOKEN_NEWLINE && currentTokenKind != MP_TOKEN_END) {
tokenStart = firstNonSpace + lex->tok_column - 1;
tokenEnd = tokenStart + TokenLength(lex, tokenStart);
if (location < tokenStart) {
// The location for autocompletion is not in an identifier
assert(autocompleteType == AutocompletionType::NoIdentifier);
break;
}
if (location <= tokenEnd) {
if (currentTokenKind == MP_TOKEN_NAME
|| (currentTokenKind >= MP_TOKEN_KW_FALSE
&& currentTokenKind <= MP_TOKEN_KW_YIELD))
{
/* The location for autocompletion is in the middle or at the end of
* an identifier. */
beginningOfToken = tokenStart;
/* If autocompleteType is already EndOfIdentifier, we are
* autocompleting, so we do not need to update autocompleteType. If we
* recomputed autocompleteType now, we might wrongly think that it is
* MiddleOfIdentifier because of the autocompetion text.
* Example : fin|ally -> the lexer is at the end of "fin", but because
* we are autocompleting with "ally", the lexer thinks the cursor is
* in the middle of an identifier. */
if (autocompleteType != AutocompletionType::EndOfIdentifier) {
autocompleteType = location < tokenEnd ? AutocompletionType::MiddleOfIdentifier : AutocompletionType::EndOfIdentifier;
}
}
break;
}
mp_lexer_to_next(lex);
currentTokenKind = lex->tok_kind;
}
mp_lexer_free(lex);
nlr_pop();
}
if (autocompletionLocationBeginning != nullptr) {
*autocompletionLocationBeginning = beginningOfToken;
}
if (autocompletionLocationEnd != nullptr) {
*autocompletionLocationEnd = location;
}
assert(!isAutocompleting() || autocompleteType == AutocompletionType::EndOfIdentifier);
return autocompleteType;
}
const char * PythonTextArea::ContentView::textToAutocomplete() const {
return UTF8Helper::BeginningOfWord(editedText(), cursorLocation());
}
void PythonTextArea::ContentView::loadSyntaxHighlighter() {
m_pythonDelegate->initPythonWithUser(this);
}
void PythonTextArea::ContentView::unloadSyntaxHighlighter() {
m_pythonDelegate->deinitPython();
}
void PythonTextArea::ContentView::clearRect(KDContext * ctx, KDRect rect) const {
ctx->fillRect(rect, BackgroundColor);
}
#define LOG_DRAWING 0
#if LOG_DRAWING
#include <stdio.h>
#define LOG_DRAW(...) printf(__VA_ARGS__)
#else
#define LOG_DRAW(...)
#endif
void PythonTextArea::ContentView::drawLine(KDContext * ctx, int line, const char * text, size_t byteLength, int fromColumn, int toColumn, const char * selectionStart, const char * selectionEnd) const {
LOG_DRAW("Drawing \"%.*s\"\n", byteLength, text);
assert(m_pythonDelegate->isPythonUser(this));
/* We're using the MicroPython lexer to do syntax highlighting on a per-line
* basis. This can work, however the MicroPython lexer won't accept a line
* starting with a whitespace. So we're discarding leading whitespaces
* beforehand. */
const char * firstNonSpace = UTF8Helper::NotCodePointSearch(text, ' ');
if (firstNonSpace != text) {
// Color the discarded leading whitespaces
const char * spacesStart = UTF8Helper::CodePointAtGlyphOffset(text, fromColumn);
drawStringAt(
ctx,
line,
fromColumn,
spacesStart,
std::min(text + byteLength, firstNonSpace) - spacesStart,
StringColor,
BackgroundColor,
selectionStart,
selectionEnd,
HighlightColor);
}
if (UTF8Helper::CodePointIs(firstNonSpace, UCodePointNull)) {
return;
}
const char * autocompleteStart = m_autocomplete ? m_cursorLocation : nullptr;
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_lexer_t * lex = mp_lexer_new_from_str_len(0, firstNonSpace, byteLength - (firstNonSpace - text), 0);
LOG_DRAW("Pop token %d\n", lex->tok_kind);
const char * tokenFrom = firstNonSpace;
size_t tokenLength = 0;
const char * tokenEnd = firstNonSpace;
while (lex->tok_kind != MP_TOKEN_NEWLINE && lex->tok_kind != MP_TOKEN_END) {
tokenFrom = firstNonSpace + lex->tok_column - 1;
if (tokenFrom != tokenEnd) {
// We passed over white spaces, we need to color them
drawStringAt(
ctx,
line,
UTF8Helper::GlyphOffsetAtCodePoint(text, tokenEnd),
tokenEnd,
std::min(text + byteLength, tokenFrom) - tokenEnd,
StringColor,
BackgroundColor,
selectionStart,
selectionEnd,
HighlightColor);
}
tokenLength = TokenLength(lex, tokenFrom);
tokenEnd = tokenFrom + tokenLength;
// If the token is being autocompleted, use DefaultColor
KDColor color = (tokenFrom <= autocompleteStart && autocompleteStart < tokenEnd) ? DefaultColor : TokenColor(lex->tok_kind);
if (color != DefaultColor && (lex->tok_kind == MP_TOKEN_INTEGER || lex->tok_kind == MP_TOKEN_FLOAT_OR_IMAG)) {
/* Check if the token can actually be parsed because lexer might label
* tokens that cannot be parsed as integer or float */
nlr_buf_t nlrNumberColorParse;
if (nlr_push(&nlrNumberColorParse) == 0) {
/* Use ex->vstr.len instead of tokenLength because it translates
* escaped chars as the interpreter would do. */
if (lex->tok_kind == MP_TOKEN_INTEGER) {
mp_parse_num_integer(tokenFrom, lex->vstr.len, 0, NULL);
} else {
mp_parse_num_decimal(tokenFrom, lex->vstr.len, true, false, NULL);
}
nlr_pop();
} else {
// Parsing raised an exception, use DefaultColor.
color = DefaultColor;
}
}
LOG_DRAW("Draw \"%.*s\" for token %d\n", tokenLength, tokenFrom, lex->tok_kind);
drawStringAt(ctx, line,
UTF8Helper::GlyphOffsetAtCodePoint(text, tokenFrom),
tokenFrom,
tokenLength,
color,
BackgroundColor,
selectionStart,
selectionEnd,
HighlightColor);
mp_lexer_to_next(lex);
LOG_DRAW("Pop token %d\n", lex->tok_kind);
}
tokenFrom += tokenLength;
// Even if the token is being autocompleted, use CommentColor
if (tokenFrom < text + byteLength) {
LOG_DRAW("Draw comment \"%.*s\" from %d\n", byteLength - (tokenFrom - text), firstNonSpace, tokenFrom);
drawStringAt(ctx, line,
UTF8Helper::GlyphOffsetAtCodePoint(text, tokenFrom),
tokenFrom,
text + byteLength - tokenFrom,
CommentColor,
BackgroundColor,
selectionStart,
selectionEnd,
HighlightColor);
}
mp_lexer_free(lex);
nlr_pop();
}
// Redraw the autocompleted word in the right color
if (m_autocomplete && autocompleteStart >= text && autocompleteStart < text + byteLength) {
assert(m_autocompletionEnd != nullptr && m_autocompletionEnd > autocompleteStart);
drawStringAt(
ctx,
line,
UTF8Helper::GlyphOffsetAtCodePoint(text, autocompleteStart),
autocompleteStart,
std::min(text + byteLength, m_autocompletionEnd) - autocompleteStart,
AutocompleteColor,
BackgroundColor,
nullptr,
nullptr,
HighlightColor);
}
}
KDRect PythonTextArea::ContentView::dirtyRectFromPosition(const char * position, bool includeFollowingLines) const {
/* Mark the whole line as dirty.
* TextArea has a very conservative approach and only dirties the surroundings
* of the current character. That works for plain text, but when doing syntax
* highlighting, you may want to redraw the surroundings as well. For example,
* if editing "def foo" into "df foo", you'll want to redraw "df". */
KDRect baseDirtyRect = TextArea::ContentView::dirtyRectFromPosition(position, includeFollowingLines);
return KDRect(
bounds().x(),
baseDirtyRect.y(),
bounds().width(),
baseDirtyRect.height()
);
}
void PythonTextArea::didBecomeFirstResponder() {
/* If we are coming from a Varbox opened while autocompleting, the text was
* removed to preserve the ScriptNodes name pointers. */
if (!m_contentView.isAutocompleting() && m_wasAutocompleting) {
addAutocompletion(m_autocompletionResultIndex);
m_wasAutocompleting = false;
}
}
bool PythonTextArea::handleEvent(Ion::Events::Event event) {
if (m_contentView.isAutocompleting()) {
// Handle event with autocompletion
if (event == Ion::Events::Right
|| event == Ion::Events::ShiftRight
|| event == Ion::Events::OK)
{
m_contentView.reloadRectFromPosition(m_contentView.cursorLocation(), false);
acceptAutocompletion(event != Ion::Events::ShiftRight);
if (event != Ion::Events::ShiftRight) {
// Do not process the event more
scrollToCursor();
return true;
}
} else if (event == Ion::Events::Toolbox
|| event == Ion::Events::Shift
|| event == Ion::Events::Alpha
|| event == Ion::Events::OnOff)
{
} else if(event == Ion::Events::Up
|| event == Ion::Events::Down)
{
cycleAutocompletion(event == Ion::Events::Down);
return true;
} else if (event == Ion::Events::Var) {
/* Remove the autocompletion text so that opening the Varbox does not
* invalidate the ScriptNodes name pointers. */
m_wasAutocompleting = true;
removeAutocompletion();
} else {
removeAutocompletion();
m_contentView.reloadRectFromPosition(m_contentView.cursorLocation(), false);
if (event == Ion::Events::Back) {
// Do not process the event more
return true;
}
}
}
bool result = TextArea::handleEvent(event);
if (event == Ion::Events::Backspace && !m_contentView.isAutocompleting() && selectionIsEmpty()) {
/* We want to add autocompletion when we are editing a word (after adding or
* deleting text). So if nothing is selected, we add the autocompletion if
* the event is backspace, as autocompletion has already been added if the
* event added text, in handleEventWithText. */
addAutocompletion();
} else if (event == Ion::Events::ShiftRight && m_contentView.isAutocompleting()) {
// Prevent further autocompletion after a ShiftRight event
removeAutocompletion();
}
return result;
}
bool PythonTextArea::handleEventWithText(const char * text, bool indentation, bool forceCursorRightOfText) {
if (*text == 0) {
return false;
}
if (m_contentView.isAutocompleting()) {
removeAutocompletion();
}
bool result = TextArea::handleEventWithText(text, indentation, forceCursorRightOfText);
addAutocompletion();
return result;
}
void PythonTextArea::removeAutocompletion() {
assert(m_contentView.isAutocompleting());
removeAutocompletionText();
m_contentView.setAutocompleting(false);
}
void PythonTextArea::removeAutocompletionText() {
assert(m_contentView.isAutocompleting());
assert(m_contentView.autocompletionEnd() != nullptr);
const char * autocompleteStart = m_contentView.cursorLocation();
const char * autocompleteEnd = m_contentView.autocompletionEnd();
assert(autocompleteEnd != nullptr && autocompleteEnd > autocompleteStart);
m_contentView.removeText(autocompleteStart, autocompleteEnd);
}
void PythonTextArea::addAutocompletion(int index) {
assert(!m_contentView.isAutocompleting());
const char * autocompletionTokenBeginning = nullptr;
const char * autocompletionLocation = const_cast<char *>(cursorLocation());
m_autocompletionResultIndex = index;
if (autocompletionType(autocompletionLocation, &autocompletionTokenBeginning) != AutocompletionType::EndOfIdentifier) {
// The cursor is not at the end of an identifier.
return;
}
// First load variables and functions that complete the textToAutocomplete
const int scriptIndex = m_contentView.pythonDelegate()->menuController()->editedScriptIndex();
m_contentView.pythonDelegate()->variableBoxController()->loadFunctionsAndVariables(scriptIndex, autocompletionTokenBeginning, autocompletionLocation - autocompletionTokenBeginning);
addAutocompletionTextAtIndex(index);
}
bool PythonTextArea::addAutocompletionTextAtIndex(int nextIndex, int * currentIndexToUpdate) {
// The variable box should be loaded at this point
const char * autocompletionTokenBeginning = nullptr;
const char * autocompletionLocation = const_cast<char *>(cursorLocation());
AutocompletionType type = autocompletionType(autocompletionLocation, &autocompletionTokenBeginning); // Done to get autocompletionTokenBeginning
assert(type == AutocompletionType::EndOfIdentifier);
(void)type; // Silence warnings
VariableBoxController * varBox = m_contentView.pythonDelegate()->variableBoxController();
int textToInsertLength = 0;
bool addParentheses = false;
const char * textToInsert = varBox->autocompletionAlternativeAtIndex(autocompletionLocation - autocompletionTokenBeginning, &textToInsertLength, &addParentheses, nextIndex, currentIndexToUpdate);
if (textToInsert == nullptr) {
return false;
}
if (textToInsertLength > 0) {
// Try to insert the text (this might fail if the buffer is full)
if (!m_contentView.insertTextAtLocation(textToInsert, const_cast<char *>(autocompletionLocation), textToInsertLength)) {
return false;
}
autocompletionLocation += textToInsertLength;
m_contentView.setAutocompleting(true);
m_contentView.setAutocompletionEnd(autocompletionLocation);
}
// Try to insert the parentheses if needed
const char * parentheses = ScriptNodeCell::k_parentheses;
constexpr int parenthesesLength = 2;
assert(strlen(parentheses) == parenthesesLength);
/* If couldInsertText is false, we should not try to add the parentheses as
* there was already not enough space to add the autocompletion. */
if (addParentheses && m_contentView.insertTextAtLocation(parentheses, const_cast<char *>(autocompletionLocation), parenthesesLength)) {
m_contentView.setAutocompleting(true);
m_contentView.setAutocompletionEnd(autocompletionLocation + parenthesesLength);
return true;
}
return (textToInsertLength > 0);
}
void PythonTextArea::cycleAutocompletion(bool downwards) {
assert(m_contentView.isAutocompleting());
removeAutocompletionText();
addAutocompletionTextAtIndex(m_autocompletionResultIndex + (downwards ? 1 : -1), &m_autocompletionResultIndex);
}
void PythonTextArea::acceptAutocompletion(bool moveCursorToEndOfAutocompletion) {
assert(m_contentView.isAutocompleting());
// Save the cursor location
const char * previousCursorLocation = cursorLocation();
removeAutocompletion();
m_contentView.pythonDelegate()->variableBoxController()->setSender(this);
m_contentView.pythonDelegate()->variableBoxController()->insertAutocompletionResultAtIndex(m_autocompletionResultIndex);
// insertAutocompletionResultAtIndex already added the autocompletion
// If we did not want to move the cursor, restore its position.
if (!moveCursorToEndOfAutocompletion) {
setCursorLocation(previousCursorLocation);
}
}
}
| 9,679 |
879 | <reponame>qianfei11/zstack<filename>test/src/test/java/org/zstack/test/multinodes/MultiNodeTestReply.java
package org.zstack.test.multinodes;
import org.zstack.header.message.MessageReply;
/**
*/
public class MultiNodeTestReply extends MessageReply {
private String managementNodeId;
public String getManagementNodeId() {
return managementNodeId;
}
public void setManagementNodeId(String managementNodeId) {
this.managementNodeId = managementNodeId;
}
}
| 168 |
1,568 | class Stack:
def __init__(self):
self.stack = []
self.top = 0
def is_empty(self):
return (self.top == 0)
def push(self, item):
if self.top < len(self.stack):
self.stack[self.top] = item
else:
self.stack.append(item)
self.top += 1
def pop(self):
if self.is_empty():
return None
else:
self.top -= 1
return self.stack[self.top]
| 214 |
507 | # terrascript/resource/innovationnorway/azure_preview.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:12:49 UTC)
import terrascript
class azurepreview_budget(terrascript.Resource):
pass
class azurepreview_subscription(terrascript.Resource):
pass
__all__ = [
"azurepreview_budget",
"azurepreview_subscription",
]
| 126 |
1,061 | /*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.ai.tests.pfa.tests.tiled.hrchy;
import com.badlogic.gdx.ai.pfa.Connection;
import com.badlogic.gdx.ai.tests.pfa.tests.tiled.TiledNode;
import com.badlogic.gdx.utils.Array;
/** A node for a {@link HierarchicalTiledGraph}.
*
* @author davebaol */
public class HierarchicalTiledNode extends TiledNode<HierarchicalTiledNode> {
/** The index of this tile. */
public final int index;
public HierarchicalTiledNode (int x, int y, int type, int index, int connectionCapacity) {
super(x, y, type, new Array<Connection<HierarchicalTiledNode>>(connectionCapacity));
this.index = index;
}
@Override
public int getIndex () {
return index;
}
public HierarchicalTiledNode getLowerLevelNode() {
return null;
}
}
| 438 |
6,036 | <filename>winml/lib/Api.Experimental/LearningModelOperatorSet.h<gh_stars>1000+
#pragma once
#include "LearningModelOperatorSet.g.h"
namespace WINML_EXPERIMENTALP {
struct LearningModelOperatorSet : LearningModelOperatorSetT<LearningModelOperatorSet>
{
LearningModelOperatorSet(winml_experimental::LearningModelBuilder builder);
winml_experimental::LearningModelBuilder Add(winml_experimental::LearningModelOperator const& op);
private:
winml_experimental::LearningModelBuilder builder_;
wfc::IVector<winml_experimental::LearningModelOperator> operators_;
};
}
| 218 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.hybridcompute.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.hybridcompute.models.OperationValueDisplay;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Describes the properties of a Compute Operation value. */
@Fluent
public final class OperationValueInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(OperationValueInner.class);
/*
* The origin of the compute operation.
*/
@JsonProperty(value = "origin", access = JsonProperty.Access.WRITE_ONLY)
private String origin;
/*
* The name of the compute operation.
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private String name;
/*
* Display properties
*/
@JsonProperty(value = "display")
private OperationValueDisplay display;
/**
* Get the origin property: The origin of the compute operation.
*
* @return the origin value.
*/
public String origin() {
return this.origin;
}
/**
* Get the name property: The name of the compute operation.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Get the display property: Display properties.
*
* @return the display value.
*/
public OperationValueDisplay display() {
return this.display;
}
/**
* Set the display property: Display properties.
*
* @param display the display value to set.
* @return the OperationValueInner object itself.
*/
public OperationValueInner withDisplay(OperationValueDisplay display) {
this.display = display;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (display() != null) {
display().validate();
}
}
}
| 804 |
1,880 | package sample;
import javax.inject.Inject;
/**
* Created by freemanliu on 3/19/18.
*/
public class T62 implements Tank {
@Inject
T62() {}
}
| 60 |
634 | /****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.mpt.imapmailbox.suite;
import java.util.Locale;
import org.apache.james.mpt.api.ImapHostSystem;
import org.apache.james.mpt.imapmailbox.ImapTestConstants;
import org.apache.james.mpt.imapmailbox.suite.base.BasicImapCommands;
import org.apache.james.mpt.script.SimpleScriptedTestProtocol;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public abstract class SelectedState implements ImapTestConstants {
protected abstract ImapHostSystem createImapHostSystem();
private ImapHostSystem system;
private SimpleScriptedTestProtocol simpleScriptedTestProtocol;
@BeforeEach
public void setUp() throws Exception {
system = createImapHostSystem();
simpleScriptedTestProtocol = new SimpleScriptedTestProtocol("/org/apache/james/imap/scripts/", system)
.withUser(USER, PASSWORD)
.withLocale(Locale.US);
BasicImapCommands.welcome(simpleScriptedTestProtocol);
BasicImapCommands.authenticate(simpleScriptedTestProtocol);
BasicImapCommands.prepareMailbox(simpleScriptedTestProtocol);
}
@Test
public void testCheckUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("Check");
}
@Test
public void testExpungeUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("Expunge");
}
@Test
public void testSearchUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("Search");
}
@Test
public void testFetchSingleMessageUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("FetchSingleMessage");
}
@Test
public void testFetchMultipleMessagesUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("FetchMultipleMessages");
}
@Test
public void testFetchPeekUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("FetchPeek");
}
@Test
public void testStoreUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("Store");
}
@Test
public void testCopyUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("Copy");
}
@Test
public void testUidUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("Uid");
}
@Test
public void testCheckITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("Check");
}
@Test
public void testExpungeITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("Expunge");
}
@Test
public void testSearchITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("Search");
}
@Test
public void testFetchSingleMessageITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("FetchSingleMessage");
}
@Test
public void testFetchMultipleMessagesITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("FetchMultipleMessages");
}
@Test
public void testFetchPeekITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("FetchPeek");
}
@Test
public void testStoreITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("Store");
}
@Test
public void testCopyITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("Copy");
}
@Test
public void testUidITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("Uid");
}
@Test
public void testCheckKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("Check");
}
@Test
public void testExpungeKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("Expunge");
}
@Test
public void testSearchKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("Search");
}
@Test
public void testFetchSingleMessageKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("FetchSingleMessage");
}
@Test
public void testFetchMultipleMessagesKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("FetchMultipleMessages");
}
@Test
public void testFetchPeekKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("FetchPeek");
}
@Test
public void testStoreKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("Store");
}
@Test
public void testCopyKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("Copy");
}
@Test
public void testUidKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("Uid");
}
@Test
public void testNamespaceUS() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.US)
.run("Namespace");
}
@Test
public void testNamespaceITALY() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.ITALY)
.run("Namespace");
}
@Test
public void testNamespaceKOREA() throws Exception {
simpleScriptedTestProtocol
.withLocale(Locale.KOREA)
.run("Namespace");
}
}
| 3,331 |
1,091 | <gh_stars>1000+
/*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.drivers.ciena.waveserver.rest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import org.onlab.util.Frequency;
import org.onlab.util.Spectrum;
import org.onosproject.driver.optical.flowrule.CrossConnectCache;
import org.onosproject.alarm.Alarm;
import org.onosproject.alarm.AlarmEntityId;
import org.onosproject.alarm.AlarmId;
import org.onosproject.alarm.DefaultAlarm;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.DeviceId;
import org.onosproject.net.OchSignal;
import org.onosproject.net.OchSignalType;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.net.flow.DefaultFlowEntry;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowId;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criteria;
import org.onosproject.protocol.rest.RestSBController;
import org.slf4j.Logger;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
public class CienaRestDevice {
private static final Frequency CENTER_FREQUENCY = Frequency.ofGHz(195_950);
private static final String ENABLED = "enabled";
private static final String DISABLED = "disabled";
private static final String VALUE = "value";
private static final String STATE = "state";
private static final String ADMIN_STATE = "admin-state";
private static final String WAVELENGTH = "wavelength";
private static final String DATA = "data";
private static final String ACTIVE = "active";
private static final String ACKNOWLEDGE = "acknowledged";
private static final String SEVERITY = "severity";
private static final String DESCRIPTION = "description";
private static final String INSTANCE = "instance";
private static final String PORT = "port";
private static final String PTP = "ptp";
private static final String UTC = "UTC";
private static final String OTHER = "other";
private static final String DATE_TIME_FORMAT = "EEE MMM [ ]d HH:mm:ss yyyy";
//keys
private static final String ALARM_KEY = "ws-alarms";
private static final String ALARM_INSTANCE_ID = "alarm-instance-id";
private static final String ALARM_TABLE_ID = "alarm-table-id";
private static final String ALARM_LOCAL_DATE_TIME = "local-date-time";
private static final String LINE_SYSTEM_CHANNEL_NUMBER = "ciena-ws-ptp-modem:line-system-channel-number";
private static final String FREQUENCY_KEY = "ciena-ws-ptp-modem:frequency";
//URIs
private static final String PORT_URI = "ws-ptps/ptps/%s";
private static final String TRANSMITTER_URI = PORT_URI + "/properties/transmitter";
private static final String PORT_STATE_URI = PORT_URI + "/" + STATE;
private static final String WAVELENGTH_URI = TRANSMITTER_URI + "/" + WAVELENGTH;
private static final String FREQUENCY_URI = TRANSMITTER_URI + "/" + FREQUENCY_KEY;
private static final String CHANNEL_URI = TRANSMITTER_URI + "/" + LINE_SYSTEM_CHANNEL_NUMBER;
private static final String ACTIVE_ALARMS_URL = ALARM_KEY + "/" + ACTIVE;
private static final List<String> LINESIDE_PORT_ID = ImmutableList.of("4", "48");
private static final ChannelSpacing CHANNEL_SPACING = ChannelSpacing.CHL_50GHZ;
private final Logger log = getLogger(getClass());
private DeviceId deviceId;
private RestSBController controller;
private CrossConnectCache crossConnectCache;
private DeviceService deviceService;
public CienaRestDevice(DriverHandler handler) throws NullPointerException {
deviceId = handler.data().deviceId();
controller = checkNotNull(handler.get(RestSBController.class));
crossConnectCache = checkNotNull(handler.get(CrossConnectCache.class));
deviceService = checkNotNull(handler.get(DeviceService.class));
}
/**
* return the Line side ports.
*
* @return List of Line side ports.
*/
public static List<String> getLinesidePortId() {
return LINESIDE_PORT_ID;
}
/**
* add the given flow rules to cross connect-cache.
*
* @param flowRules flow rules that needs to be cached.
*/
public void setCrossConnectCache(Collection<FlowRule> flowRules) {
flowRules.forEach(xc -> crossConnectCache.set(
Objects.hash(deviceId, xc.selector(), xc.treatment()),
xc.id(),
xc.priority()));
}
/**
* remove the given flow rules form the cross-connect cache.
*
* @param flowRules flow rules that needs to be removed from cache.
*/
public void removeCrossConnectCache(Collection<FlowRule> flowRules) {
flowRules.forEach(xc -> crossConnectCache.remove(Objects.hash(deviceId, xc.selector(), xc.treatment())));
}
private final String genPortStateRequest(String state) {
String request = "{\n" +
"\"" + STATE + "\": {\n" +
"\"" + ADMIN_STATE + "\": \"" + state + "\"\n}\n}";
log.debug("generated request: \n{}", request);
return request;
}
private String genWavelengthChangeRequest(String wavelength) {
String request = "{\n" +
"\"" + WAVELENGTH + "\": {\n" +
"\"" + VALUE + "\": " + wavelength + "\n" +
"}\n" +
"}";
log.debug("request:\n{}", request);
return request;
}
private String genFrequencyChangeRequest(double frequency) {
String request = "{\n" +
"\"" + FREQUENCY_KEY + "\": {\n" +
"\"" + VALUE + "\": " + Double.toString(frequency) + "\n" +
"}\n" +
"}";
log.debug("request:\n{}", request);
return request;
}
private String genChannelChangeRequest(int channel) {
String request = "{\n" +
"\"" + LINE_SYSTEM_CHANNEL_NUMBER + "\": " +
Integer.toString(channel) + "\n}";
log.debug("request:\n{}", request);
return request;
}
private final String genUri(String uriFormat, PortNumber port) {
return String.format(uriFormat, port.name());
}
private boolean isPortState(PortNumber number, String state) {
log.debug("checking port {} state is {} or not on device {}", number, state, deviceId);
String uri = genUri(PORT_STATE_URI, number);
JsonNode jsonNode;
try {
jsonNode = get(uri);
} catch (IOException e) {
log.error("unable to get port state on device {}", deviceId);
return false;
}
return jsonNode.get(STATE).get(ADMIN_STATE).asText().equals(state);
}
private boolean confirmPortState(long timePeriodInMillis, int iterations, PortNumber number, String state) {
for (int i = 0; i < iterations; i++) {
log.debug("looping for port state with time period {}ms on device {}. try number {}/{}",
timePeriodInMillis, deviceId, i + 1, iterations);
if (isPortState(number, state)) {
return true;
}
try {
Thread.sleep(timePeriodInMillis);
} catch (InterruptedException e) {
log.error("unable to sleep thread for device {}\n", deviceId, e);
Thread.currentThread().interrupt();
return false;
}
}
return false;
}
private boolean changePortState(PortNumber number, String state) {
log.debug("changing the port {} on device {} state to {}", number, deviceId, state);
String uri = genUri(PORT_STATE_URI, number);
String request = genPortStateRequest(state);
boolean response = putNoReply(uri, request);
if (!response) {
log.error("unable to change port {} on device {} state to {}", number, deviceId, state);
}
// 5 tries with 2 sec delay
long timePeriod = 2000;
int iterations = 5;
return confirmPortState(timePeriod, iterations, number, state);
}
public boolean disablePort(PortNumber number) {
return changePortState(number, DISABLED);
}
public boolean enablePort(PortNumber number) {
return changePortState(number, ENABLED);
}
public final boolean changeFrequency(OchSignal signal, PortNumber outPort) {
String uri = genUri(FREQUENCY_URI, outPort);
double frequency = signal.centralFrequency().asGHz();
String request = genFrequencyChangeRequest(frequency);
boolean response = putNoReply(uri, request);
if (!response) {
log.error("unable to change frequency of port {} on device {}", outPort, deviceId);
}
return response;
}
public final boolean changeChannel(OchSignal signal, PortNumber outPort) {
String uri = genUri(CHANNEL_URI, outPort);
int channel = signal.spacingMultiplier();
log.debug("channel is {} for port {} on device {}", channel, outPort.name(), deviceId);
String request = genChannelChangeRequest(channel);
boolean response = putNoReply(uri, request);
if (!response) {
log.error("unable to change channel to {} for port {} on device {}",
channel, outPort.name(), deviceId);
}
return response;
}
private int getChannel(PortNumber port) {
try {
String uri = genUri(CHANNEL_URI, port);
JsonNode response = get(uri);
return response.get(LINE_SYSTEM_CHANNEL_NUMBER).asInt();
} catch (IOException e) {
// this is expected for client side ports as they don't contain channel data
log.error("unable to get channel for port {} on device {}:\n{}", port, deviceId, e);
return -1;
}
}
private int getChannelFromFrequency(Frequency frequency) {
return (int) frequency.subtract(Spectrum.CENTER_FREQUENCY)
.floorDivision(CHANNEL_SPACING.frequency().asHz()).asHz();
}
private Frequency getFrequency(PortNumber port) {
try {
String uri = genUri(FREQUENCY_URI, port);
JsonNode response = get(uri);
return Frequency.ofGHz(response.get(FREQUENCY_KEY).get(VALUE).asDouble());
} catch (IOException e) {
// this is expected for client side ports as they don't contain frequency data
log.error("unable to get frequency for port {} on device {}:\n{}", port, deviceId, e);
return null;
}
}
private AlarmEntityId getAlarmSource(String instance) {
AlarmEntityId source;
if (instance.contains(PORT)) {
source = AlarmEntityId.alarmEntityId(instance.replace("-", ":"));
} else if (instance.contains(PTP)) {
source = AlarmEntityId.alarmEntityId(instance.replace(PTP + "-", PORT + ":"));
} else {
source = AlarmEntityId.alarmEntityId(OTHER + ":" + instance);
}
return source;
}
private long parseAlarmTime(String time) {
/*
* expecting WaveServer time to be set to UTC.
*/
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
LocalDateTime localDateTime = LocalDateTime.parse(time, formatter);
return localDateTime.atZone(ZoneId.of(UTC)).toInstant().toEpochMilli();
} catch (DateTimeParseException e2) {
log.error("unable to parse time {}, using system time", time);
return System.currentTimeMillis();
}
}
private Alarm newAlarmFromJsonNode(JsonNode jsonNode) {
try {
AlarmId alarmId = AlarmId.alarmId(checkNotNull(jsonNode.get(ALARM_INSTANCE_ID)).asText());
String time = checkNotNull(jsonNode.get(ALARM_LOCAL_DATE_TIME)).asText();
String instance = checkNotNull(jsonNode.get(INSTANCE).asText()).toLowerCase();
String description = checkNotNull(jsonNode.get(DESCRIPTION)).asText() + " - " + instance + " - " + time;
AlarmEntityId source = getAlarmSource(instance);
Alarm.SeverityLevel severity = Alarm.SeverityLevel.valueOf(checkNotNull(
jsonNode.get(SEVERITY)).asText().toUpperCase());
long timeRaised = parseAlarmTime(time);
boolean isAcknowledged = checkNotNull(jsonNode.get(ACKNOWLEDGE)).asBoolean();
return new DefaultAlarm.Builder(alarmId, deviceId, description, severity, timeRaised)
.withAcknowledged(isAcknowledged)
.forSource(source)
.build();
} catch (NullPointerException e) {
log.error("got exception while parsing alarm json node {} for device {}:\n", jsonNode, deviceId, e);
return null;
}
}
private List<Alarm> getActiveAlarms() {
log.debug("getting active alarms for device {}", deviceId);
try {
List<JsonNode> alarms = Lists.newArrayList(get(ACTIVE_ALARMS_URL).get(ACTIVE).elements());
return alarms.stream()
.map(this::newAlarmFromJsonNode)
.filter(Objects::nonNull)
.collect(Collectors.toList());
} catch (IOException e) {
log.error("unable to get active alarms for device {}:\n", deviceId, e);
return null;
}
}
public Collection<FlowEntry> getFlowEntries() {
List<Port> ports = deviceService.getPorts(deviceId);
//driver only handles lineSide ports
//TODO: handle client ports as well
return ports.stream()
.filter(p -> LINESIDE_PORT_ID.contains(p.number().name()))
.map(p -> fetchRule(p.number()))
.filter(Objects::nonNull)
.map(fr -> new DefaultFlowEntry(fr, FlowEntry.FlowEntryState.ADDED, 0, 0, 0))
.collect(Collectors.toList());
}
private FlowRule fetchRule(PortNumber port) {
Frequency frequency = getFrequency(port);
if (frequency == null) {
return null;
}
int channel = getChannelFromFrequency(frequency);
/*
* both inPort and outPort will be same as WaveServer only deal with same port ptp-indexes
* channel and spaceMultiplier are same.
* TODO: find a way to get both inPort and outPort for future when inPort may not be equal to outPort
*/
TrafficSelector selector = DefaultTrafficSelector.builder()
.matchInPort(port)
.add(Criteria.matchOchSignalType(OchSignalType.FIXED_GRID))
.add(Criteria.matchLambda(OchSignal.newDwdmSlot(CHANNEL_SPACING, channel)))
.build();
TrafficTreatment treatment = DefaultTrafficTreatment.builder()
.setOutput(port)
.build();
int hash = Objects.hash(deviceId, selector, treatment);
Pair<FlowId, Integer> lookup = crossConnectCache.get(hash);
if (lookup == null) {
return null;
}
return DefaultFlowRule.builder()
.forDevice(deviceId)
.makePermanent()
.withSelector(selector)
.withTreatment(treatment)
.withPriority(lookup.getRight())
.withCookie(lookup.getLeft().value())
.build();
}
public List<Alarm> getAlarms() {
log.debug("getting alarms for device {}", deviceId);
return getActiveAlarms();
}
private JsonNode get(String uri) throws IOException {
InputStream response = controller.get(deviceId, uri, MediaType.valueOf(MediaType.APPLICATION_JSON));
ObjectMapper om = new ObjectMapper();
final ObjectReader reader = om.reader();
// all waveserver responses contain data node, which contains the requested data
return reader.readTree(response).get(DATA);
}
private int put(String uri, String request) {
InputStream payload = new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8));
int response = controller.put(deviceId, uri, payload, MediaType.valueOf(MediaType.APPLICATION_JSON));
log.debug("response: {}", response);
return response;
}
private boolean putNoReply(String uri, String request) {
return put(uri, request) == Response.Status.NO_CONTENT.getStatusCode();
}
}
| 7,286 |
30,023 | """Tests for the Switch as X Cover platform."""
from homeassistant.components.cover import DOMAIN as COVER_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.switch_as_x.const import CONF_TARGET_DOMAIN, DOMAIN
from homeassistant.const import (
CONF_ENTITY_ID,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COVER,
SERVICE_TOGGLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_CLOSED,
STATE_OFF,
STATE_ON,
STATE_OPEN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
async def test_default_state(hass: HomeAssistant) -> None:
"""Test cover switch default state."""
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
CONF_ENTITY_ID: "switch.test",
CONF_TARGET_DOMAIN: Platform.COVER,
},
title="Garage Door",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("cover.garage_door")
assert state is not None
assert state.state == "unavailable"
assert state.attributes["supported_features"] == 3
async def test_service_calls(hass: HomeAssistant) -> None:
"""Test service calls to cover."""
await async_setup_component(hass, "switch", {"switch": [{"platform": "demo"}]})
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
CONF_ENTITY_ID: "switch.decorative_lights",
CONF_TARGET_DOMAIN: Platform.COVER,
},
title="garage_door",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get("cover.garage_door").state == STATE_OPEN
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_TOGGLE,
{CONF_ENTITY_ID: "cover.garage_door"},
blocking=True,
)
assert hass.states.get("switch.decorative_lights").state == STATE_OFF
assert hass.states.get("cover.garage_door").state == STATE_CLOSED
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{CONF_ENTITY_ID: "cover.garage_door"},
blocking=True,
)
assert hass.states.get("switch.decorative_lights").state == STATE_ON
assert hass.states.get("cover.garage_door").state == STATE_OPEN
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{CONF_ENTITY_ID: "cover.garage_door"},
blocking=True,
)
assert hass.states.get("switch.decorative_lights").state == STATE_OFF
assert hass.states.get("cover.garage_door").state == STATE_CLOSED
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{CONF_ENTITY_ID: "switch.decorative_lights"},
blocking=True,
)
assert hass.states.get("switch.decorative_lights").state == STATE_ON
assert hass.states.get("cover.garage_door").state == STATE_OPEN
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{CONF_ENTITY_ID: "switch.decorative_lights"},
blocking=True,
)
assert hass.states.get("switch.decorative_lights").state == STATE_OFF
assert hass.states.get("cover.garage_door").state == STATE_CLOSED
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{CONF_ENTITY_ID: "switch.decorative_lights"},
blocking=True,
)
assert hass.states.get("switch.decorative_lights").state == STATE_ON
assert hass.states.get("cover.garage_door").state == STATE_OPEN
| 1,596 |
1,648 | /*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2015-2020 Amazon.com, Inc. or its affiliates.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <kernel.h>
#include <lwip.h>
#include <pci.h>
#include "ena_eth_com.h"
static struct ena_eth_io_rx_cdesc_base *ena_com_get_next_rx_cdesc(struct ena_com_io_cq *io_cq)
{
struct ena_eth_io_rx_cdesc_base *cdesc;
u16 expected_phase, head_masked;
u16 desc_phase;
head_masked = io_cq->head & (io_cq->q_depth - 1);
expected_phase = io_cq->phase;
cdesc = (struct ena_eth_io_rx_cdesc_base *)(io_cq->cdesc_addr.virt_addr
+ (head_masked * io_cq->cdesc_entry_size_in_bytes));
desc_phase = (READ_ONCE32(cdesc->status) & ENA_ETH_IO_RX_CDESC_BASE_PHASE_MASK) >>
ENA_ETH_IO_RX_CDESC_BASE_PHASE_SHIFT;
if (desc_phase != expected_phase)
return NULL;
/* Make sure we read the rest of the descriptor after the phase bit
* has been read
*/
dma_rmb();
return cdesc;
}
static void *get_sq_desc_regular_queue(struct ena_com_io_sq *io_sq)
{
u16 tail_masked;
u32 offset;
tail_masked = io_sq->tail & (io_sq->q_depth - 1);
offset = tail_masked * io_sq->desc_entry_size;
return (void *)((uintptr_t)io_sq->desc_addr.virt_addr + offset);
}
static int ena_com_write_bounce_buffer_to_dev(struct ena_com_io_sq *io_sq, u8 *bounce_buffer)
{
struct ena_com_llq_info *llq_info = &io_sq->llq_info;
u16 dst_tail_mask;
u32 dst_offset;
dst_tail_mask = io_sq->tail & (io_sq->q_depth - 1);
dst_offset = dst_tail_mask * llq_info->desc_list_entry_size;
if (is_llq_max_tx_burst_exists(io_sq)) {
if (unlikely(!io_sq->entries_in_tx_burst_left)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq),
"Error: trying to send more packets than tx burst allows\n");
return ENA_COM_NO_SPACE;
}
io_sq->entries_in_tx_burst_left--;
ena_trc_dbg(ena_com_io_sq_to_ena_dev(io_sq),
"Decreasing entries_in_tx_burst_left of queue %d to %d\n", io_sq->qid,
io_sq->entries_in_tx_burst_left);
}
/* Make sure everything was written into the bounce buffer before
* writing the bounce buffer to the device
*/
write_barrier();
/* The line is completed. Copy it to dev */
ENA_MEMCPY_TO_DEVICE_64(io_sq->desc_addr.pbuf_dev_addr + dst_offset, bounce_buffer,
llq_info->desc_list_entry_size);
io_sq->tail++;
/* Switch phase bit in case of wrap around */
if (unlikely((io_sq->tail & (io_sq->q_depth - 1)) == 0))
io_sq->phase ^= 1;
return ENA_COM_OK;
}
static int ena_com_write_header_to_bounce(struct ena_com_io_sq *io_sq, u8 *header_src,
u16 header_len)
{
struct ena_com_llq_pkt_ctrl *pkt_ctrl = &io_sq->llq_buf_ctrl;
struct ena_com_llq_info *llq_info = &io_sq->llq_info;
u8 *bounce_buffer = pkt_ctrl->curr_bounce_buf;
u16 header_offset;
if (unlikely(io_sq->mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_HOST))
return 0;
header_offset = llq_info->descs_num_before_header * io_sq->desc_entry_size;
if (unlikely((header_offset + header_len) > llq_info->desc_list_entry_size)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq),
"Trying to write header larger than llq entry can accommodate\n");
return ENA_COM_FAULT;
}
if (unlikely(!bounce_buffer)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Bounce buffer is NULL\n");
return ENA_COM_FAULT;
}
runtime_memcpy(bounce_buffer + header_offset, header_src, header_len);
return 0;
}
static void *get_sq_desc_llq(struct ena_com_io_sq *io_sq)
{
struct ena_com_llq_pkt_ctrl *pkt_ctrl = &io_sq->llq_buf_ctrl;
u8 *bounce_buffer;
void *sq_desc;
bounce_buffer = pkt_ctrl->curr_bounce_buf;
if (unlikely(!bounce_buffer)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Bounce buffer is NULL\n");
return NULL;
}
sq_desc = bounce_buffer + pkt_ctrl->idx * io_sq->desc_entry_size;
pkt_ctrl->idx++;
pkt_ctrl->descs_left_in_line--;
return sq_desc;
}
static int ena_com_close_bounce_buffer(struct ena_com_io_sq *io_sq)
{
struct ena_com_llq_pkt_ctrl *pkt_ctrl = &io_sq->llq_buf_ctrl;
struct ena_com_llq_info *llq_info = &io_sq->llq_info;
int rc;
if (unlikely(io_sq->mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_HOST))
return ENA_COM_OK;
/* bounce buffer was used, so write it and get a new one */
if (pkt_ctrl->idx) {
rc = ena_com_write_bounce_buffer_to_dev(io_sq, pkt_ctrl->curr_bounce_buf);
if (unlikely(rc)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq),
"Failed to write bounce buffer to device\n");
return rc;
}
pkt_ctrl->curr_bounce_buf = ena_com_get_next_bounce_buffer(&io_sq->bounce_buf_ctrl);
zero(io_sq->llq_buf_ctrl.curr_bounce_buf, llq_info->desc_list_entry_size);
}
pkt_ctrl->idx = 0;
pkt_ctrl->descs_left_in_line = llq_info->descs_num_before_header;
return ENA_COM_OK;
}
static void *get_sq_desc(struct ena_com_io_sq *io_sq)
{
if (io_sq->mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV)
return get_sq_desc_llq(io_sq);
return get_sq_desc_regular_queue(io_sq);
}
static int ena_com_sq_update_llq_tail(struct ena_com_io_sq *io_sq)
{
struct ena_com_llq_pkt_ctrl *pkt_ctrl = &io_sq->llq_buf_ctrl;
struct ena_com_llq_info *llq_info = &io_sq->llq_info;
int rc;
if (!pkt_ctrl->descs_left_in_line) {
rc = ena_com_write_bounce_buffer_to_dev(io_sq, pkt_ctrl->curr_bounce_buf);
if (unlikely(rc)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq),
"Failed to write bounce buffer to device\n");
return rc;
}
pkt_ctrl->curr_bounce_buf = ena_com_get_next_bounce_buffer(&io_sq->bounce_buf_ctrl);
zero(io_sq->llq_buf_ctrl.curr_bounce_buf, llq_info->desc_list_entry_size);
pkt_ctrl->idx = 0;
if (unlikely(llq_info->desc_stride_ctrl == ENA_ADMIN_SINGLE_DESC_PER_ENTRY))
pkt_ctrl->descs_left_in_line = 1;
else
pkt_ctrl->descs_left_in_line = llq_info->desc_list_entry_size / io_sq->desc_entry_size;
}
return ENA_COM_OK;
}
static int ena_com_sq_update_tail(struct ena_com_io_sq *io_sq)
{
if (io_sq->mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV)
return ena_com_sq_update_llq_tail(io_sq);
io_sq->tail++;
/* Switch phase bit in case of wrap around */
if (unlikely((io_sq->tail & (io_sq->q_depth - 1)) == 0))
io_sq->phase ^= 1;
return ENA_COM_OK;
}
static struct ena_eth_io_rx_cdesc_base *
ena_com_rx_cdesc_idx_to_ptr(struct ena_com_io_cq *io_cq, u16 idx)
{
idx &= (io_cq->q_depth - 1);
return (struct ena_eth_io_rx_cdesc_base *)
((uintptr_t)io_cq->cdesc_addr.virt_addr + idx * io_cq->cdesc_entry_size_in_bytes);
}
static u16 ena_com_cdesc_rx_pkt_get(struct ena_com_io_cq *io_cq, u16 *first_cdesc_idx)
{
struct ena_eth_io_rx_cdesc_base *cdesc;
u16 count = 0, head_masked;
u32 last = 0;
do {
cdesc = ena_com_get_next_rx_cdesc(io_cq);
if (!cdesc)
break;
ena_com_cq_inc_head(io_cq);
count++;
last = (READ_ONCE32(cdesc->status) & ENA_ETH_IO_RX_CDESC_BASE_LAST_MASK) >>
ENA_ETH_IO_RX_CDESC_BASE_LAST_SHIFT;
} while (!last);
if (last) {
*first_cdesc_idx = io_cq->cur_rx_pkt_cdesc_start_idx;
count += io_cq->cur_rx_pkt_cdesc_count;
head_masked = io_cq->head & (io_cq->q_depth - 1);
io_cq->cur_rx_pkt_cdesc_count = 0;
io_cq->cur_rx_pkt_cdesc_start_idx = head_masked;
ena_trc_dbg(ena_com_io_cq_to_ena_dev(io_cq),
"ENA q_id: %d packets were completed. first desc idx %d descs# %d\n", io_cq->qid,
*first_cdesc_idx, count);
} else {
io_cq->cur_rx_pkt_cdesc_count += count;
count = 0;
}
return count;
}
static int ena_com_create_meta(struct ena_com_io_sq *io_sq, struct ena_com_tx_meta *ena_meta)
{
struct ena_eth_io_tx_meta_desc *meta_desc = NULL;
meta_desc = get_sq_desc(io_sq);
if (unlikely(!meta_desc))
return ENA_COM_FAULT;
zero(meta_desc, sizeof(struct ena_eth_io_tx_meta_desc));
meta_desc->len_ctrl |= ENA_ETH_IO_TX_META_DESC_META_DESC_MASK;
meta_desc->len_ctrl |= ENA_ETH_IO_TX_META_DESC_EXT_VALID_MASK;
/* bits 0-9 of the mss */
meta_desc->word2 |= ((u32) ena_meta->mss <<
ENA_ETH_IO_TX_META_DESC_MSS_LO_SHIFT) &
ENA_ETH_IO_TX_META_DESC_MSS_LO_MASK;
/* bits 10-13 of the mss */
meta_desc->len_ctrl |= ((ena_meta->mss >> 10) <<
ENA_ETH_IO_TX_META_DESC_MSS_HI_SHIFT) &
ENA_ETH_IO_TX_META_DESC_MSS_HI_MASK;
/* Extended meta desc */
meta_desc->len_ctrl |= ENA_ETH_IO_TX_META_DESC_ETH_META_TYPE_MASK;
meta_desc->len_ctrl |= ((u32) io_sq->phase <<
ENA_ETH_IO_TX_META_DESC_PHASE_SHIFT) &
ENA_ETH_IO_TX_META_DESC_PHASE_MASK;
meta_desc->len_ctrl |= ENA_ETH_IO_TX_META_DESC_FIRST_MASK;
meta_desc->len_ctrl |= ENA_ETH_IO_TX_META_DESC_META_STORE_MASK;
meta_desc->word2 |= ena_meta->l3_hdr_len &
ENA_ETH_IO_TX_META_DESC_L3_HDR_LEN_MASK;
meta_desc->word2 |= (ena_meta->l3_hdr_offset <<
ENA_ETH_IO_TX_META_DESC_L3_HDR_OFF_SHIFT) &
ENA_ETH_IO_TX_META_DESC_L3_HDR_OFF_MASK;
meta_desc->word2 |= ((u32) ena_meta->l4_hdr_len <<
ENA_ETH_IO_TX_META_DESC_L4_HDR_LEN_IN_WORDS_SHIFT) &
ENA_ETH_IO_TX_META_DESC_L4_HDR_LEN_IN_WORDS_MASK;
return ena_com_sq_update_tail(io_sq);
}
static int ena_com_create_and_store_tx_meta_desc(struct ena_com_io_sq *io_sq,
struct ena_com_tx_ctx *ena_tx_ctx, bool *have_meta)
{
struct ena_com_tx_meta *ena_meta = &ena_tx_ctx->ena_meta;
/* When disable meta caching is set, don't bother to save the meta and
* compare it to the stored version, just create the meta
*/
if (io_sq->disable_meta_caching) {
if (unlikely(!ena_tx_ctx->meta_valid))
return ENA_COM_INVAL;
*have_meta = true;
return ena_com_create_meta(io_sq, ena_meta);
}
if (ena_com_meta_desc_changed(io_sq, ena_tx_ctx)) {
*have_meta = true;
/* Cache the meta desc */
runtime_memcpy(&io_sq->cached_tx_meta, ena_meta, sizeof(struct ena_com_tx_meta));
return ena_com_create_meta(io_sq, ena_meta);
}
*have_meta = false;
return ENA_COM_OK;
}
static void ena_com_rx_set_flags(struct ena_com_io_cq *io_cq, struct ena_com_rx_ctx *ena_rx_ctx,
struct ena_eth_io_rx_cdesc_base *cdesc)
{
ena_rx_ctx->l3_proto = cdesc->status &
ENA_ETH_IO_RX_CDESC_BASE_L3_PROTO_IDX_MASK;
ena_rx_ctx->l4_proto = (cdesc->status & ENA_ETH_IO_RX_CDESC_BASE_L4_PROTO_IDX_MASK) >>
ENA_ETH_IO_RX_CDESC_BASE_L4_PROTO_IDX_SHIFT;
ena_rx_ctx->l3_csum_err = !!((cdesc->status & ENA_ETH_IO_RX_CDESC_BASE_L3_CSUM_ERR_MASK) >>
ENA_ETH_IO_RX_CDESC_BASE_L3_CSUM_ERR_SHIFT);
ena_rx_ctx->l4_csum_err = !!((cdesc->status & ENA_ETH_IO_RX_CDESC_BASE_L4_CSUM_ERR_MASK) >>
ENA_ETH_IO_RX_CDESC_BASE_L4_CSUM_ERR_SHIFT);
ena_rx_ctx->l4_csum_checked = !!((cdesc->status & ENA_ETH_IO_RX_CDESC_BASE_L4_CSUM_CHECKED_MASK)
>> ENA_ETH_IO_RX_CDESC_BASE_L4_CSUM_CHECKED_SHIFT);
ena_rx_ctx->hash = cdesc->hash;
ena_rx_ctx->frag = (cdesc->status & ENA_ETH_IO_RX_CDESC_BASE_IPV4_FRAG_MASK) >>
ENA_ETH_IO_RX_CDESC_BASE_IPV4_FRAG_SHIFT;
ena_trc_dbg(ena_com_io_cq_to_ena_dev(io_cq),
"l3_proto %d l4_proto %d l3_csum_err %d l4_csum_err %d hash %d frag %d cdesc_status %x\n",
ena_rx_ctx->l3_proto, ena_rx_ctx->l4_proto, ena_rx_ctx->l3_csum_err,
ena_rx_ctx->l4_csum_err, ena_rx_ctx->hash, ena_rx_ctx->frag, cdesc->status);
}
/*****************************************************************************/
/***************************** API **********************************/
/*****************************************************************************/
int ena_com_prepare_tx(struct ena_com_io_sq *io_sq, struct ena_com_tx_ctx *ena_tx_ctx,
int *nb_hw_desc)
{
struct ena_eth_io_tx_desc *desc = NULL;
struct ena_com_buf *ena_bufs = ena_tx_ctx->ena_bufs;
void *buffer_to_push = ena_tx_ctx->push_header;
u16 header_len = ena_tx_ctx->header_len;
u16 num_bufs = ena_tx_ctx->num_bufs;
u16 start_tail = io_sq->tail;
int i, rc;
bool have_meta;
u64 addr_hi;
ENA_WARN(io_sq->direction != ENA_COM_IO_QUEUE_DIRECTION_TX, ena_com_io_sq_to_ena_dev(io_sq),
"wrong Q type");
/* num_bufs +1 for potential meta desc */
if (unlikely(!ena_com_sq_have_enough_space(io_sq, num_bufs + 1))) {
ena_trc_dbg(ena_com_io_sq_to_ena_dev(io_sq), "Not enough space in the tx queue\n");
return ENA_COM_NO_MEM;
}
if (unlikely(header_len > io_sq->tx_max_header_size)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Header size is too large %d max header: %d\n",
header_len, io_sq->tx_max_header_size);
return ENA_COM_INVAL;
}
if (unlikely(io_sq->mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV && !buffer_to_push)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Push header wasn't provided on LLQ mode\n");
return ENA_COM_INVAL;
}
rc = ena_com_write_header_to_bounce(io_sq, buffer_to_push, header_len);
if (unlikely(rc))
return rc;
rc = ena_com_create_and_store_tx_meta_desc(io_sq, ena_tx_ctx, &have_meta);
if (unlikely(rc)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Failed to create and store tx meta desc\n");
return rc;
}
/* If the caller doesn't want to send packets */
if (unlikely(!num_bufs && !header_len)) {
rc = ena_com_close_bounce_buffer(io_sq);
if (rc)
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Failed to write buffers to LLQ\n");
*nb_hw_desc = io_sq->tail - start_tail;
return rc;
}
desc = get_sq_desc(io_sq);
if (unlikely(!desc))
return ENA_COM_FAULT;
zero(desc, sizeof(struct ena_eth_io_tx_desc));
/* Set first desc when we don't have meta descriptor */
if (!have_meta)
desc->len_ctrl |= ENA_ETH_IO_TX_DESC_FIRST_MASK;
desc->buff_addr_hi_hdr_sz |= ((u32) header_len <<
ENA_ETH_IO_TX_DESC_HEADER_LENGTH_SHIFT) &
ENA_ETH_IO_TX_DESC_HEADER_LENGTH_MASK;
desc->len_ctrl |= ((u32) io_sq->phase << ENA_ETH_IO_TX_DESC_PHASE_SHIFT) &
ENA_ETH_IO_TX_DESC_PHASE_MASK;
desc->len_ctrl |= ENA_ETH_IO_TX_DESC_COMP_REQ_MASK;
/* Bits 0-9 */
desc->meta_ctrl |= ((u32) ena_tx_ctx->req_id <<
ENA_ETH_IO_TX_DESC_REQ_ID_LO_SHIFT) &
ENA_ETH_IO_TX_DESC_REQ_ID_LO_MASK;
desc->meta_ctrl |= (ena_tx_ctx->df <<
ENA_ETH_IO_TX_DESC_DF_SHIFT) &
ENA_ETH_IO_TX_DESC_DF_MASK;
/* Bits 10-15 */
desc->len_ctrl |= ((ena_tx_ctx->req_id >> 10) <<
ENA_ETH_IO_TX_DESC_REQ_ID_HI_SHIFT) &
ENA_ETH_IO_TX_DESC_REQ_ID_HI_MASK;
if (ena_tx_ctx->meta_valid) {
desc->meta_ctrl |= (ena_tx_ctx->tso_enable <<
ENA_ETH_IO_TX_DESC_TSO_EN_SHIFT) &
ENA_ETH_IO_TX_DESC_TSO_EN_MASK;
desc->meta_ctrl |= ena_tx_ctx->l3_proto &
ENA_ETH_IO_TX_DESC_L3_PROTO_IDX_MASK;
desc->meta_ctrl |= (ena_tx_ctx->l4_proto <<
ENA_ETH_IO_TX_DESC_L4_PROTO_IDX_SHIFT) &
ENA_ETH_IO_TX_DESC_L4_PROTO_IDX_MASK;
desc->meta_ctrl |= (ena_tx_ctx->l3_csum_enable <<
ENA_ETH_IO_TX_DESC_L3_CSUM_EN_SHIFT) &
ENA_ETH_IO_TX_DESC_L3_CSUM_EN_MASK;
desc->meta_ctrl |= (ena_tx_ctx->l4_csum_enable <<
ENA_ETH_IO_TX_DESC_L4_CSUM_EN_SHIFT) &
ENA_ETH_IO_TX_DESC_L4_CSUM_EN_MASK;
desc->meta_ctrl |= (ena_tx_ctx->l4_csum_partial <<
ENA_ETH_IO_TX_DESC_L4_CSUM_PARTIAL_SHIFT) &
ENA_ETH_IO_TX_DESC_L4_CSUM_PARTIAL_MASK;
}
for (i = 0; i < num_bufs; i++) {
/* The first desc share the same desc as the header */
if (likely(i != 0)) {
rc = ena_com_sq_update_tail(io_sq);
if (unlikely(rc)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Failed to update sq tail\n");
return rc;
}
desc = get_sq_desc(io_sq);
if (unlikely(!desc))
return ENA_COM_FAULT;
zero(desc, sizeof(struct ena_eth_io_tx_desc));
desc->len_ctrl |= ((u32) io_sq->phase <<
ENA_ETH_IO_TX_DESC_PHASE_SHIFT) &
ENA_ETH_IO_TX_DESC_PHASE_MASK;
}
desc->len_ctrl |= ena_bufs->len &
ENA_ETH_IO_TX_DESC_LENGTH_MASK;
addr_hi = ((ena_bufs->paddr & GENMASK_ULL(io_sq->dma_addr_bits - 1, 32)) >> 32);
desc->buff_addr_lo = (u32) ena_bufs->paddr;
desc->buff_addr_hi_hdr_sz |= addr_hi &
ENA_ETH_IO_TX_DESC_ADDR_HI_MASK;
ena_bufs++;
}
/* set the last desc indicator */
desc->len_ctrl |= ENA_ETH_IO_TX_DESC_LAST_MASK;
rc = ena_com_sq_update_tail(io_sq);
if (unlikely(rc)) {
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq),
"Failed to update sq tail of the last descriptor\n");
return rc;
}
rc = ena_com_close_bounce_buffer(io_sq);
if (rc)
ena_trc_err(ena_com_io_sq_to_ena_dev(io_sq), "Failed when closing bounce buffer\n");
*nb_hw_desc = io_sq->tail - start_tail;
return rc;
}
int ena_com_rx_pkt(struct ena_com_io_cq *io_cq, struct ena_com_io_sq *io_sq,
struct ena_com_rx_ctx *ena_rx_ctx)
{
struct ena_com_rx_buf_info *ena_buf = &ena_rx_ctx->ena_bufs[0];
struct ena_eth_io_rx_cdesc_base *cdesc = NULL;
u16 q_depth = io_cq->q_depth;
u16 cdesc_idx = 0;
u16 nb_hw_desc;
u16 i = 0;
ENA_WARN(io_cq->direction != ENA_COM_IO_QUEUE_DIRECTION_RX, ena_com_io_cq_to_ena_dev(io_cq),
"wrong Q type");
nb_hw_desc = ena_com_cdesc_rx_pkt_get(io_cq, &cdesc_idx);
if (nb_hw_desc == 0) {
ena_rx_ctx->descs = nb_hw_desc;
return 0;
}
ena_trc_dbg(ena_com_io_cq_to_ena_dev(io_cq), "Fetch rx packet: queue %d completed desc: %d\n",
io_cq->qid, nb_hw_desc);
if (unlikely(nb_hw_desc > ena_rx_ctx->max_bufs)) {
ena_trc_err(ena_com_io_cq_to_ena_dev(io_cq), "Too many RX cdescs (%d) > MAX(%d)\n",
nb_hw_desc, ena_rx_ctx->max_bufs);
return ENA_COM_NO_SPACE;
}
cdesc = ena_com_rx_cdesc_idx_to_ptr(io_cq, cdesc_idx);
ena_rx_ctx->pkt_offset = cdesc->offset;
do {
ena_buf[i].len = cdesc->length;
ena_buf[i].req_id = cdesc->req_id;
if (unlikely(ena_buf[i].req_id >= q_depth))
return ENA_COM_EIO;
if (++i >= nb_hw_desc)
break;
cdesc = ena_com_rx_cdesc_idx_to_ptr(io_cq, cdesc_idx + i);
} while (1);
/* Update SQ head ptr */
io_sq->next_to_comp += nb_hw_desc;
ena_trc_dbg(ena_com_io_cq_to_ena_dev(io_cq), "[%s][QID#%d] Updating SQ head to: %d\n", __func__,
io_sq->qid, io_sq->next_to_comp);
/* Get rx flags from the last pkt */
ena_com_rx_set_flags(io_cq, ena_rx_ctx, cdesc);
ena_rx_ctx->descs = nb_hw_desc;
return 0;
}
int ena_com_add_single_rx_desc(struct ena_com_io_sq *io_sq, struct ena_com_buf *ena_buf, u16 req_id)
{
struct ena_eth_io_rx_desc *desc;
ENA_WARN(io_sq->direction != ENA_COM_IO_QUEUE_DIRECTION_RX, ena_com_io_sq_to_ena_dev(io_sq),
"wrong Q type");
if (unlikely(!ena_com_sq_have_enough_space(io_sq, 1)))
return ENA_COM_NO_SPACE;
desc = get_sq_desc(io_sq);
if (unlikely(!desc))
return ENA_COM_FAULT;
zero(desc, sizeof(struct ena_eth_io_rx_desc));
desc->length = ena_buf->len;
desc->ctrl = ENA_ETH_IO_RX_DESC_FIRST_MASK |
ENA_ETH_IO_RX_DESC_LAST_MASK |
ENA_ETH_IO_RX_DESC_COMP_REQ_MASK | (io_sq->phase & ENA_ETH_IO_RX_DESC_PHASE_MASK);
desc->req_id = req_id;
ena_trc_dbg(ena_com_io_sq_to_ena_dev(io_sq),
"[%s] Adding single RX desc, Queue: %d, req_id: %d\n",
__func__, io_sq->qid, req_id);
desc->buff_addr_lo = (u32) ena_buf->paddr;
desc->buff_addr_hi = ((ena_buf->paddr & GENMASK_ULL(io_sq->dma_addr_bits - 1, 32)) >> 32);
return ena_com_sq_update_tail(io_sq);
}
bool ena_com_cq_empty(struct ena_com_io_cq *io_cq)
{
struct ena_eth_io_rx_cdesc_base *cdesc;
cdesc = ena_com_get_next_rx_cdesc(io_cq);
if (cdesc)
return false;
else
return true;
}
| 11,182 |
684 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.workflow.simple.alfresco.conversion.json;
import java.util.ArrayList;
import org.activiti.workflow.simple.alfresco.form.AlfrescoTransitionsPropertyDefinition;
import org.activiti.workflow.simple.alfresco.step.AlfrescoEmailStepDefinition;
import org.activiti.workflow.simple.alfresco.step.AlfrescoReviewStepDefinition;
import org.activiti.workflow.simple.converter.json.SimpleWorkflowJsonConverter;
import org.activiti.workflow.simple.definition.WorkflowDefinition;
/**
* A {@link SimpleWorkflowJsonConverter} that is capable of converting {@link WorkflowDefinition}s using
* custom alfresco definitions.
*
* @author <NAME>
*/
public class AlfrescoSimpleWorkflowJsonConverter extends SimpleWorkflowJsonConverter {
public AlfrescoSimpleWorkflowJsonConverter() {
additionalModelClasses = new ArrayList<Class<?>>();
// Custom form properties
additionalModelClasses.add(AlfrescoTransitionsPropertyDefinition.class);
// Custom step definitions
additionalModelClasses.add(AlfrescoEmailStepDefinition.class);
additionalModelClasses.add(AlfrescoReviewStepDefinition.class);
}
}
| 501 |
5,169 | <filename>Specs/4/1/0/DetectImageColorsFramework/1.0.0/DetectImageColorsFramework.podspec.json<gh_stars>1000+
{
"name": "DetectImageColorsFramework",
"version": "1.0.0",
"summary": "Extracts 4 main colors from an image: primary, secondary, detail and background.",
"description": "Extracts 4 main colors from an image: primary, secondary, detail and background. OS X framework written in Swift 2.2",
"homepage": "https://github.com/ericdke/DetectImageColorsFramework",
"license": {
"type": "MIT",
"file": "LICENSE.md"
},
"authors": {
"<NAME>.": "<EMAIL>"
},
"platforms": {
"osx": "10.9"
},
"requires_arc": true,
"source": {
"git": "https://github.com/ericdke/DetectImageColorsFramework.git",
"tag": "1.0.0",
"submodules": true
},
"source_files": "DetectImageColorsFramework/**/*.{h,swift}",
"deprecated": true
}
| 332 |
5,169 | <reponame>Gantios/Specs
{
"name": "YLCommonKit",
"version": "0.0.4",
"summary": "我的基础库",
"description": "简单的整理,常用的分类",
"homepage": "https://github.com/xyl-private/YLCommonKit",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"村雨灬龑": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/xyl-private/YLCommonKit.git",
"tag": "0.0.4"
},
"subspecs": [
{
"name": "YLMacro",
"source_files": "YLCommonKit/YLMacro/*.{h,m}",
"public_header_files": "YLCommonKit/YLMacro/*.h"
},
{
"name": "YLFoundation",
"source_files": "YLCommonKit/YLCategory/YLFoundation/**/*.{h,m}",
"public_header_files": "YLCommonKit/YLCategory/YLFoundation/**/*.h"
},
{
"name": "YLUIKit",
"source_files": "YLCommonKit/YLCategory/YLUIKit/**/*.{h,m}",
"public_header_files": "YLCommonKit/YLCategory/YLUIKit/**/*.h"
}
]
}
| 512 |
28,899 | from functools import reduce
import numpy as np
from pandas._config import get_option
def ensure_decoded(s):
"""
If we have bytes, decode them to unicode.
"""
if isinstance(s, (np.bytes_, bytes)):
s = s.decode(get_option("display.encoding"))
return s
def result_type_many(*arrays_and_dtypes):
"""
Wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32)
argument limit.
"""
try:
return np.result_type(*arrays_and_dtypes)
except ValueError:
# we have > NPY_MAXARGS terms in our expression
return reduce(np.result_type, arrays_and_dtypes)
| 252 |
1,156 | <gh_stars>1000+
#----------------------------------------------
#--- Author : <NAME>
#--- Mail : <EMAIL>
#--- Date : 14th August 2019
#----------------------------------------------
import numpy as np
import cv2
import backbone
from utils.object_tracking_module import tracking_layer
cap = cv2.VideoCapture("./input_images_and_videos/vehicle_survaillance.mp4")
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fps = int(cap.get(cv2.CAP_PROP_FPS))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('the_output.avi',fourcc, fps, (width, height))
while(True):
ret, img = cap.read()
np.asarray(img)
processed_img = backbone.processor(img)
out.write(processed_img)
print("writing frame...")
print("end of the video!")
| 370 |
1,853 | <reponame>monocilindro/rtabmap
/*
Copyright (c) 2010-2021, <NAME> - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/Memory.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/utilite/UTimer.h>
#include <rtabmap/core/util3d_transforms.h>
using namespace rtabmap;
void showUsage()
{
printf("\n"
"Clear empty space from local occupancy grids and laser scans based on the saved optimized global 2d grid map.\n"
"Advantages:\n"
" * If the map needs to be regenerated in the future (e.g., when \n"
" we re-use the map in SLAM mode), removed obstacles won't reappear.\n"
" * [--scan] The cropped laser scans will be also used for localization,\n"
" so if dynamic obstacles have been removed, localization won't try to\n"
" match them anymore.\n\n"
"Disadvantage:\n"
" * [--scan] Cropping the laser scans cannot be reverted, but grids can.\n"
"\nUsage:\n"
"rtabmap-cleanupLocalGrids [options] database.db\n"
"Options:\n"
" --radius # Radius in cells around empty cell without obstacles to clear\n"
" underlying obstacles. Default is 1.\n"
" --scan Filter also scans, otherwise only local grids are filtered.\n"
"\n");
;
exit(1);
}
int main(int argc, char * argv[])
{
ULogger::setType(ULogger::kTypeConsole);
ULogger::setLevel(ULogger::kInfo);
if(argc < 2)
{
showUsage();
}
int cropRadius = 1;
bool filterScans = false;
for(int i=1; i<argc; ++i)
{
if(std::strcmp(argv[i], "--help") == 0)
{
showUsage();
}
else if(std::strcmp(argv[i], "--scan") == 0)
{
filterScans = true;
}
else if(std::strcmp(argv[i], "--radius") == 0)
{
++i;
if(i<argc-1)
{
cropRadius = uStr2Int(argv[i]);
UASSERT(cropRadius>=0);
}
else
{
showUsage();
}
}
}
std::string dbPath = argv[argc-1];
if(!UFile::exists(dbPath))
{
UERROR("File \"%s\" doesn't exist!", dbPath.c_str());
return -1;
}
// Get parameters
ParametersMap parameters;
Rtabmap rtabmap;
rtabmap.init(ParametersMap(), dbPath, true);
float xMin, yMin, cellSize;
cv::Mat map = rtabmap.getMemory()->load2DMap(xMin, yMin, cellSize);
if(map.empty())
{
UERROR("Database %s doesn't have optimized 2d map saved in it!", dbPath.c_str());
return -1;
}
printf("Options:\n");
printf(" --radius: %d cell(s) (cell size=%.3fm)\n", cropRadius, cellSize);
printf(" --scan: %s\n", filterScans?"true":"false");
std::map<int, Transform> poses = rtabmap.getLocalOptimizedPoses();
if(poses.empty() || poses.lower_bound(1) == poses.end())
{
UERROR("Database %s doesn't have optimized poses saved in it!", dbPath.c_str());
return -1;
}
UTimer timer;
printf("Cleaning grids...\n");
int modifiedCells = rtabmap.cleanupLocalGrids(poses, map, xMin, yMin, cellSize, cropRadius, filterScans);
printf("Cleanup %d cells! (%fs)\n", modifiedCells, timer.ticks());
rtabmap.close();
printf("Done!\n");
return 0;
}
| 1,817 |
558 | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright (C) 2020 Micron Technology, Inc. All rights reserved.
*/
#ifndef HSE_UTIL_COMPRESSION_H
#define HSE_UTIL_COMPRESSION_H
#include <hse_util/hse_err.h>
#include <hse_util/inttypes.h>
typedef uint compress_op_estimate_t(
const void *data,
uint len);
typedef merr_t compress_op_compress_t(
const void *src,
uint src_len,
void *dst,
uint dst_capacity,
uint *dst_len);
typedef merr_t compress_op_decompress_t(
const void *src,
uint src_len,
void *dst,
uint dst_capacity,
uint *dst_len);
struct compress_ops {
compress_op_estimate_t *cop_estimate;
compress_op_compress_t *cop_compress;
compress_op_decompress_t *cop_decompress;
};
#endif
| 393 |
854 | __________________________________________________________________________________________________
sample 4 ms submission
class Solution {
public:
int numMusicPlaylists(int N, int L, int K) {
long dp[N + 1][L + 1], mod = 1e9 + 7;
for (int i = K + 1; i <= N; ++i)
for (int j = i; j <= L; ++j)
if ((i == j) || (i == K + 1))
dp[i][j] = factorial(i);
else
dp[i][j] = (dp[i - 1][j - 1] * i + dp[i][j - 1] * (i - K)) % mod;
return (int) dp[N][L];
}
long factorial(int n) {
return n ? factorial(n - 1) * n % (long)(1e9 + 7) : 1;
}
};
__________________________________________________________________________________________________
sample 8628 kb submission
class Solution {
public:
// dp[4][3] = dp[3][2]*(3-2) + dp[3][3]*(3-1) = 6*1 + 6*2 = 18
// dp[3][2] = [1,2,1],[2,1,2],[2,3,2],[3,2,3],[1,3,1],[3,1,3]
// dp[3][3] = [1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]
int numMusicPlaylists(int N, int L, int K) {
int mod = pow(10, 9) + 7;
long int dp[L+1][N+1];
dp[0][0] = 1;
for(int i=1; i<=L; i++) dp[i][0] = 0;
for(int i=1; i<=N; i++) dp[0][i] = 0;
for (int i = 1; i <= L; i++){
for (int j = 1; j <= N; j++){
dp[i][j] = (dp[i-1][j-1] * (N - (j-1)))%mod;
if (j > K){
dp[i][j] = (dp[i][j] + (dp[i-1][j] * (j-K))%mod)%mod;
}
//cout << i <<" "<<j<< " "<< dp[i][j] << endl;
}
}
return (int)dp[L][N];
}
};
__________________________________________________________________________________________________
| 930 |
1,340 | <reponame>dummylung/MetalPetal<filename>Sources/MetalPetalObjectiveC/include/MTIPixelFormat.h<gh_stars>1000+
//
// MTIPixelFormat.h
// MetalPetal
//
// Created by <NAME> on 11/10/2017.
//
#import <Metal/Metal.h>
NS_ASSUME_NONNULL_BEGIN
FOUNDATION_EXPORT MTLPixelFormat const MTIPixelFormatUnspecified NS_REFINED_FOR_SWIFT; //aliased to MTLPixelFormatInvalid
FOUNDATION_EXPORT MTLPixelFormat const MTIPixelFormatYCBCR8_420_2P NS_REFINED_FOR_SWIFT;
FOUNDATION_EXPORT MTLPixelFormat const MTIPixelFormatYCBCR8_420_2P_sRGB NS_REFINED_FOR_SWIFT;
FOUNDATION_EXPORT MTLPixelFormat const MTIPixelFormatYCBCR10_420_2P NS_REFINED_FOR_SWIFT;
FOUNDATION_EXPORT MTLPixelFormat const MTIPixelFormatYCBCR10_420_2P_sRGB NS_REFINED_FOR_SWIFT;
FOUNDATION_EXPORT BOOL MTIDeviceSupportsYCBCRPixelFormat(id<MTLDevice> device);
NS_ASSUME_NONNULL_END
| 337 |
364 | <filename>src/main/java/rsc/parallel/ParallelOrderedPeek.java
package rsc.parallel;
import java.util.Objects;
import java.util.function.*;
import org.reactivestreams.*;
import rsc.subscriber.SubscriptionHelper;
import rsc.util.*;
/**
* Execute a Consumer in each 'rail' for the current element passing through.
*
* @param <T> the value type
*/
public final class ParallelOrderedPeek<T> extends ParallelOrderedBase<T> {
final ParallelOrderedBase<T> source;
final Consumer<? super T> onNext;
final Consumer<? super T> onAfterNext;
final Consumer<Throwable> onError;
final Runnable onComplete;
final Runnable onAfterTerminated;
final Consumer<? super Subscription> onSubscribe;
final LongConsumer onRequest;
final Runnable onCancel;
public ParallelOrderedPeek(ParallelOrderedBase<T> source,
Consumer<? super T> onNext,
Consumer<? super T> onAfterNext,
Consumer<Throwable> onError,
Runnable onComplete,
Runnable onAfterTerminated,
Consumer<? super Subscription> onSubscribe,
LongConsumer onRequest,
Runnable onCancel
) {
this.source = source;
this.onNext = Objects.requireNonNull(onNext, "onNext");
this.onAfterNext = Objects.requireNonNull(onAfterNext, "onAfterNext");
this.onError = Objects.requireNonNull(onError, "onError");
this.onComplete = Objects.requireNonNull(onComplete, "onComplete");
this.onAfterTerminated = Objects.requireNonNull(onAfterTerminated, "onAfterTerminated");
this.onSubscribe = Objects.requireNonNull(onSubscribe, "onSubscribe");
this.onRequest = Objects.requireNonNull(onRequest, "onRequest");
this.onCancel = Objects.requireNonNull(onCancel, "onCancel");
}
@Override
public void subscribeOrdered(Subscriber<? super OrderedItem<T>>[] subscribers) {
if (!validate(subscribers)) {
return;
}
int n = subscribers.length;
@SuppressWarnings("unchecked")
Subscriber<? super OrderedItem<T>>[] parents = new Subscriber[n];
for (int i = 0; i < n; i++) {
parents[i] = new ParallelPeekSubscriber<>(subscribers[i], this);
}
source.subscribeOrdered(parents);
}
@Override
public int parallelism() {
return source.parallelism();
}
static final class ParallelPeekSubscriber<T, R> implements Subscriber<OrderedItem<T>>, Subscription {
final Subscriber<? super OrderedItem<T>> actual;
final ParallelOrderedPeek<T> parent;
Subscription s;
boolean done;
public ParallelPeekSubscriber(Subscriber<? super OrderedItem<T>> actual, ParallelOrderedPeek<T> parent) {
this.actual = actual;
this.parent = parent;
}
@Override
public void request(long n) {
try {
parent.onRequest.accept(n);
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
UnsignalledExceptions.onErrorDropped(ex);
}
s.request(n);
}
@Override
public void cancel() {
try {
parent.onCancel.run();
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
UnsignalledExceptions.onErrorDropped(ex);
}
s.cancel();
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.s, s)) {
this.s = s;
try {
parent.onSubscribe.accept(s);
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
s.cancel();
actual.onSubscribe(SubscriptionHelper.empty());
onError(ex);
return;
}
actual.onSubscribe(this);
}
}
@Override
public void onNext(OrderedItem<T> t) {
if (done) {
return;
}
try {
parent.onNext.accept(t.get());
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
onError(ex);
return;
}
actual.onNext(t);
try {
parent.onAfterNext.accept(t.get());
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
onError(ex);
return;
}
}
@Override
public void onError(Throwable t) {
if (done) {
UnsignalledExceptions.onErrorDropped(t);
return;
}
done = true;
try {
parent.onError.accept(t);
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
ex.addSuppressed(t);
t = ex;
}
actual.onError(t);
try {
parent.onAfterTerminated.run();
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
UnsignalledExceptions.onErrorDropped(ex);
}
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
try {
parent.onComplete.run();
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
actual.onError(ex);
return;
}
actual.onComplete();
try {
parent.onAfterTerminated.run();
} catch (Throwable ex) {
ExceptionHelper.throwIfFatal(ex);
UnsignalledExceptions.onErrorDropped(ex);
}
}
}
}
| 3,208 |
2,743 | <reponame>eshbeata/open-paperless
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from events.classes import Event
event_document_auto_check_in = Event(
name='checkouts_document_auto_check_in',
label=_('Document automatically checked in')
)
event_document_check_in = Event(
name='checkouts_document_check_in', label=_('Document checked in')
)
event_document_check_out = Event(
name='checkouts_document_check_out', label=_('Document checked out')
)
event_document_forceful_check_in = Event(
name='checkouts_document_forceful_check_in',
label=_('Document forcefully checked in')
)
| 220 |
868 | <reponame>AriCheng/flare
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#ifndef FLARE_TESTING_DETAIL_IMPLICITLY_CASTING_H_
#define FLARE_TESTING_DETAIL_IMPLICITLY_CASTING_H_
#include "flare/base/down_cast.h"
namespace flare::testing::detail {
// This type helps you to implement `ACTION_P` if you need to down-cast
// arguments.
template <class Base>
class ImplicitlyCasting {
public:
explicit ImplicitlyCasting(const Base* ptr) : ptr_(ptr) {}
template <class T> /* implicit */ operator T*() const noexcept {
return flare::down_cast<T>(const_cast<Base*>(ptr_));
}
template <class T> /* implicit */ operator const T*() const noexcept {
return flare::down_cast<T>(ptr_);
}
template <class T> /* implicit */ operator T&() const noexcept {
return *static_cast<T*>(*this);
}
template <class T> /* implicit */ operator const T&() const noexcept {
return *static_cast<const T*>(*this);
}
private:
const Base* ptr_;
};
} // namespace flare::testing::detail
#endif // FLARE_TESTING_DETAIL_IMPLICITLY_CASTING_H_
| 518 |
793 | //=--- CommonBugCategories.h - Provides common issue categories -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_COMMONBUGCATEGORIES_H
#define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_COMMONBUGCATEGORIES_H
// Common strings used for the "category" of many static analyzer issues.
namespace clang {
namespace ento {
namespace categories {
extern const char * const CoreFoundationObjectiveC;
extern const char * const LogicError;
extern const char * const MemoryRefCount;
extern const char * const MemoryError;
extern const char * const UnixAPI;
}
}
}
#endif
| 300 |
2,105 | <gh_stars>1000+
[
{
"name": "Tabbed",
"displayName": "Tabbed",
"summary": "The most common style of navigation in mobile apps.",
"order": "0",
"licenses": "[React Navigation](https://github.com/react-navigation/react-navigation/blob/main/packages/core/LICENSE)",
"platform": "RN",
"languages": ["Any"],
"tags": {
"preview": false
}
}
] | 155 |
30,023 | """The baf integration entities."""
from __future__ import annotations
from aiobafi6 import Device
from homeassistant.core import callback
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.device_registry import format_mac
from homeassistant.helpers.entity import DeviceInfo, Entity
class BAFEntity(Entity):
"""Base class for baf entities."""
_attr_should_poll = False
def __init__(self, device: Device, name: str) -> None:
"""Initialize the entity."""
self._device = device
self._attr_unique_id = format_mac(self._device.mac_address)
self._attr_name = name
self._attr_device_info = DeviceInfo(
connections={(dr.CONNECTION_NETWORK_MAC, self._device.mac_address)},
name=self._device.name,
manufacturer="Big Ass Fans",
model=self._device.model,
sw_version=self._device.firmware_version,
)
self._async_update_attrs()
@callback
def _async_update_attrs(self) -> None:
"""Update attrs from device."""
self._attr_available = self._device.available
@callback
def _async_update_from_device(self, device: Device) -> None:
"""Process an update from the device."""
self._async_update_attrs()
self.async_write_ha_state()
async def async_added_to_hass(self) -> None:
"""Add data updated listener after this object has been initialized."""
self._device.add_callback(self._async_update_from_device)
async def async_will_remove_from_hass(self) -> None:
"""Remove data updated listener after this object has been initialized."""
self._device.remove_callback(self._async_update_from_device)
| 657 |
1,647 | #ifndef PYTHONIC_MATH_GAMMA_HPP
#define PYTHONIC_MATH_GAMMA_HPP
#include "pythonic/include/math/gamma.hpp"
#include "pythonic/utils/functor.hpp"
#include <cmath>
PYTHONIC_NS_BEGIN
namespace math
{
double gamma(double x)
{
return std::tgamma(x);
}
}
PYTHONIC_NS_END
#endif
| 141 |
348 | {"nom":"Ronquerolles","circ":"1ère circonscription","dpt":"Val-d'Oise","inscrits":623,"abs":321,"votants":302,"blancs":32,"nuls":7,"exp":263,"res":[{"nuance":"LR","nom":"<NAME>","voix":137},{"nuance":"REM","nom":"<NAME>","voix":126}]} | 92 |
309 | // Copyright 2020 the deepx authors.
// Author: <NAME> (<EMAIL>)
//
#pragma once
#include <deepx_core/common/any_map.h>
#include <deepx_core/common/stream.h>
#include <deepx_core/tensor/data_type.h>
#include <iostream>
#include <random>
#include <utility>
namespace deepx_core {
/************************************************************************/
/* TensorMap */
/************************************************************************/
class TensorMap : public AnyMap, public DataType {
private:
void _Write(OutputStream& os) const; // NOLINT
void _Read(InputStream& is); // NOLINT
void _ReadView(InputStringStream& is); // NOLINT
void _WriteText(std::ostream& os) const;
friend OutputStream& operator<<(OutputStream& os,
const TensorMap& tensor_map);
friend InputStream& operator>>(InputStream& is, TensorMap& tensor_map);
friend InputStringStream& ReadView(InputStringStream& is, // NOLINT
TensorMap& tensor_map); // NOLINT
friend std::ostream& operator<<(std::ostream& os,
const TensorMap& tensor_map);
public:
// Call 'zeros' for value type 'srm_t', so that its shape is preserved.
void ClearSRMValue() noexcept;
// Call 'clear' for value type 'tsr_t', 'csr_t', 'tsri_t', 'tsrs_t'.
// Call 'zeros' for value type 'srm_t', so that its shape is preserved.
void ClearValue() noexcept;
// Call 'zeros' for value type: 'tsr_t', 'srm_t', 'tsri_t'.
void ZerosValue() noexcept;
void RemoveEmptyValue();
};
/************************************************************************/
/* Instance */
/************************************************************************/
class Instance : public TensorMap {
private:
int batch_ = 0;
public:
void clear_batch() noexcept { batch_ = 0; }
void set_batch(int batch) noexcept { batch_ = batch; }
int batch() const noexcept { return batch_; }
void clear() noexcept {
TensorMap::clear();
clear_batch();
}
void swap(Instance& other) noexcept {
TensorMap::swap(other);
std::swap(batch_, other.batch_);
}
};
std::ostream& operator<<(std::ostream& os, const Instance& inst);
/************************************************************************/
/* Hidden */
/************************************************************************/
class Hidden : public TensorMap {
private:
std::default_random_engine engine_;
float_t* loss_ = nullptr;
Instance inst_;
public:
template <typename Int>
void seed(Int s) {
engine_.seed((std::default_random_engine::result_type)s);
}
std::default_random_engine& engine() noexcept { return engine_; }
void clear_loss() noexcept { loss_ = nullptr; }
void set_loss(float_t* loss) noexcept { loss_ = loss; }
bool has_loss() const noexcept { return loss_ != nullptr; }
float_t loss() const noexcept { return *loss_; }
Instance* mutable_inst() noexcept { return &inst_; }
const Instance& inst() const noexcept { return inst_; }
};
std::ostream& operator<<(std::ostream& os, const Hidden& hidden);
} // namespace deepx_core
| 1,056 |
1,133 | #!/usr/bin/env python3
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Author: <NAME>
# Copyright 2010, by the California Institute of Technology. ALL RIGHTS RESERVED. United States Government Sponsorship acknowledged.
# Any commercial use must be negotiated with the Office of Technology Transfer at the California Institute of Technology.
#
# This software may be subject to U.S. export control laws. By accepting this software, the user agrees to comply with all applicable U.S.
# export laws and regulations. User has the responsibility to obtain export licenses, or other export authority as may be required before
# exporting such information to foreign countries or providing access to foreign persons.
#
# Jet Propulsion Lab
# California Institute of Technology
# (C) 2004-2006 All Rights Reserved
#
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
import sys
import os
from isceobj.RawImage.RawImage import RawImage
def main():
'''
home = os.environ['HOME']
filename = home + "/TEST_DIR/930110/930110.raw"
accessmode = 'read'
endian = 'l'
width = 11812
height = 15
obj = RawImage()
'''
if __name__ == "__main__":
sys.exit(main())
# End of file
| 457 |
343 | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.tim.packet;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-10-22")
public class TimMessageIq implements org.apache.thrift.TBase<TimMessageIq, TimMessageIq._Fields>, java.io.Serializable, Cloneable, Comparable<TimMessageIq> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TimMessageIq");
private static final org.apache.thrift.protocol.TField TIDLIST_FIELD_DESC = new org.apache.thrift.protocol.TField("tidlist", org.apache.thrift.protocol.TType.LIST, (short)1);
private static final org.apache.thrift.protocol.TField TIM_PAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("timPage", org.apache.thrift.protocol.TType.STRUCT, (short)2);
private static final org.apache.thrift.protocol.TField MIDLIST_FIELD_DESC = new org.apache.thrift.protocol.TField("midlist", org.apache.thrift.protocol.TType.LIST, (short)3);
private static final org.apache.thrift.protocol.TField EXTRA_MAP_FIELD_DESC = new org.apache.thrift.protocol.TField("extraMap", org.apache.thrift.protocol.TType.MAP, (short)4);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new TimMessageIqStandardSchemeFactory());
schemes.put(TupleScheme.class, new TimMessageIqTupleSchemeFactory());
}
/**
* tid集合
*/
public List<String> tidlist; // optional
/**
* 分页
*/
public TimPage timPage; // optional
/**
* mid集合
*/
public List<String> midlist; // optional
public Map<String,String> extraMap; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
/**
* tid集合
*/
TIDLIST((short)1, "tidlist"),
/**
* 分页
*/
TIM_PAGE((short)2, "timPage"),
/**
* mid集合
*/
MIDLIST((short)3, "midlist"),
EXTRA_MAP((short)4, "extraMap");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TIDLIST
return TIDLIST;
case 2: // TIM_PAGE
return TIM_PAGE;
case 3: // MIDLIST
return MIDLIST;
case 4: // EXTRA_MAP
return EXTRA_MAP;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final _Fields optionals[] = {_Fields.TIDLIST,_Fields.TIM_PAGE,_Fields.MIDLIST,_Fields.EXTRA_MAP};
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TIDLIST, new org.apache.thrift.meta_data.FieldMetaData("tidlist", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
tmpMap.put(_Fields.TIM_PAGE, new org.apache.thrift.meta_data.FieldMetaData("timPage", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TimPage.class)));
tmpMap.put(_Fields.MIDLIST, new org.apache.thrift.meta_data.FieldMetaData("midlist", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
tmpMap.put(_Fields.EXTRA_MAP, new org.apache.thrift.meta_data.FieldMetaData("extraMap", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.MapMetaData(org.apache.thrift.protocol.TType.MAP,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING),
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TimMessageIq.class, metaDataMap);
}
public TimMessageIq() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TimMessageIq(TimMessageIq other) {
if (other.isSetTidlist()) {
List<String> __this__tidlist = new ArrayList<String>(other.tidlist);
this.tidlist = __this__tidlist;
}
if (other.isSetTimPage()) {
this.timPage = new TimPage(other.timPage);
}
if (other.isSetMidlist()) {
List<String> __this__midlist = new ArrayList<String>(other.midlist);
this.midlist = __this__midlist;
}
if (other.isSetExtraMap()) {
Map<String,String> __this__extraMap = new HashMap<String,String>(other.extraMap);
this.extraMap = __this__extraMap;
}
}
public TimMessageIq deepCopy() {
return new TimMessageIq(this);
}
@Override
public void clear() {
this.tidlist = null;
this.timPage = null;
this.midlist = null;
this.extraMap = null;
}
public int getTidlistSize() {
return (this.tidlist == null) ? 0 : this.tidlist.size();
}
public java.util.Iterator<String> getTidlistIterator() {
return (this.tidlist == null) ? null : this.tidlist.iterator();
}
public void addToTidlist(String elem) {
if (this.tidlist == null) {
this.tidlist = new ArrayList<String>();
}
this.tidlist.add(elem);
}
/**
* tid集合
*/
public List<String> getTidlist() {
return this.tidlist;
}
/**
* tid集合
*/
public TimMessageIq setTidlist(List<String> tidlist) {
this.tidlist = tidlist;
return this;
}
public void unsetTidlist() {
this.tidlist = null;
}
/** Returns true if field tidlist is set (has been assigned a value) and false otherwise */
public boolean isSetTidlist() {
return this.tidlist != null;
}
public void setTidlistIsSet(boolean value) {
if (!value) {
this.tidlist = null;
}
}
/**
* 分页
*/
public TimPage getTimPage() {
return this.timPage;
}
/**
* 分页
*/
public TimMessageIq setTimPage(TimPage timPage) {
this.timPage = timPage;
return this;
}
public void unsetTimPage() {
this.timPage = null;
}
/** Returns true if field timPage is set (has been assigned a value) and false otherwise */
public boolean isSetTimPage() {
return this.timPage != null;
}
public void setTimPageIsSet(boolean value) {
if (!value) {
this.timPage = null;
}
}
public int getMidlistSize() {
return (this.midlist == null) ? 0 : this.midlist.size();
}
public java.util.Iterator<String> getMidlistIterator() {
return (this.midlist == null) ? null : this.midlist.iterator();
}
public void addToMidlist(String elem) {
if (this.midlist == null) {
this.midlist = new ArrayList<String>();
}
this.midlist.add(elem);
}
/**
* mid集合
*/
public List<String> getMidlist() {
return this.midlist;
}
/**
* mid集合
*/
public TimMessageIq setMidlist(List<String> midlist) {
this.midlist = midlist;
return this;
}
public void unsetMidlist() {
this.midlist = null;
}
/** Returns true if field midlist is set (has been assigned a value) and false otherwise */
public boolean isSetMidlist() {
return this.midlist != null;
}
public void setMidlistIsSet(boolean value) {
if (!value) {
this.midlist = null;
}
}
public int getExtraMapSize() {
return (this.extraMap == null) ? 0 : this.extraMap.size();
}
public void putToExtraMap(String key, String val) {
if (this.extraMap == null) {
this.extraMap = new HashMap<String,String>();
}
this.extraMap.put(key, val);
}
public Map<String,String> getExtraMap() {
return this.extraMap;
}
public TimMessageIq setExtraMap(Map<String,String> extraMap) {
this.extraMap = extraMap;
return this;
}
public void unsetExtraMap() {
this.extraMap = null;
}
/** Returns true if field extraMap is set (has been assigned a value) and false otherwise */
public boolean isSetExtraMap() {
return this.extraMap != null;
}
public void setExtraMapIsSet(boolean value) {
if (!value) {
this.extraMap = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TIDLIST:
if (value == null) {
unsetTidlist();
} else {
setTidlist((List<String>)value);
}
break;
case TIM_PAGE:
if (value == null) {
unsetTimPage();
} else {
setTimPage((TimPage)value);
}
break;
case MIDLIST:
if (value == null) {
unsetMidlist();
} else {
setMidlist((List<String>)value);
}
break;
case EXTRA_MAP:
if (value == null) {
unsetExtraMap();
} else {
setExtraMap((Map<String,String>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TIDLIST:
return getTidlist();
case TIM_PAGE:
return getTimPage();
case MIDLIST:
return getMidlist();
case EXTRA_MAP:
return getExtraMap();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TIDLIST:
return isSetTidlist();
case TIM_PAGE:
return isSetTimPage();
case MIDLIST:
return isSetMidlist();
case EXTRA_MAP:
return isSetExtraMap();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof TimMessageIq)
return this.equals((TimMessageIq)that);
return false;
}
public boolean equals(TimMessageIq that) {
if (that == null)
return false;
boolean this_present_tidlist = true && this.isSetTidlist();
boolean that_present_tidlist = true && that.isSetTidlist();
if (this_present_tidlist || that_present_tidlist) {
if (!(this_present_tidlist && that_present_tidlist))
return false;
if (!this.tidlist.equals(that.tidlist))
return false;
}
boolean this_present_timPage = true && this.isSetTimPage();
boolean that_present_timPage = true && that.isSetTimPage();
if (this_present_timPage || that_present_timPage) {
if (!(this_present_timPage && that_present_timPage))
return false;
if (!this.timPage.equals(that.timPage))
return false;
}
boolean this_present_midlist = true && this.isSetMidlist();
boolean that_present_midlist = true && that.isSetMidlist();
if (this_present_midlist || that_present_midlist) {
if (!(this_present_midlist && that_present_midlist))
return false;
if (!this.midlist.equals(that.midlist))
return false;
}
boolean this_present_extraMap = true && this.isSetExtraMap();
boolean that_present_extraMap = true && that.isSetExtraMap();
if (this_present_extraMap || that_present_extraMap) {
if (!(this_present_extraMap && that_present_extraMap))
return false;
if (!this.extraMap.equals(that.extraMap))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_tidlist = true && (isSetTidlist());
list.add(present_tidlist);
if (present_tidlist)
list.add(tidlist);
boolean present_timPage = true && (isSetTimPage());
list.add(present_timPage);
if (present_timPage)
list.add(timPage);
boolean present_midlist = true && (isSetMidlist());
list.add(present_midlist);
if (present_midlist)
list.add(midlist);
boolean present_extraMap = true && (isSetExtraMap());
list.add(present_extraMap);
if (present_extraMap)
list.add(extraMap);
return list.hashCode();
}
@Override
public int compareTo(TimMessageIq other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetTidlist()).compareTo(other.isSetTidlist());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTidlist()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.tidlist, other.tidlist);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetTimPage()).compareTo(other.isSetTimPage());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTimPage()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.timPage, other.timPage);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMidlist()).compareTo(other.isSetMidlist());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMidlist()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.midlist, other.midlist);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetExtraMap()).compareTo(other.isSetExtraMap());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetExtraMap()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.extraMap, other.extraMap);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TimMessageIq(");
boolean first = true;
if (isSetTidlist()) {
sb.append("tidlist:");
if (this.tidlist == null) {
sb.append("null");
} else {
sb.append(this.tidlist);
}
first = false;
}
if (isSetTimPage()) {
if (!first) sb.append(", ");
sb.append("timPage:");
if (this.timPage == null) {
sb.append("null");
} else {
sb.append(this.timPage);
}
first = false;
}
if (isSetMidlist()) {
if (!first) sb.append(", ");
sb.append("midlist:");
if (this.midlist == null) {
sb.append("null");
} else {
sb.append(this.midlist);
}
first = false;
}
if (isSetExtraMap()) {
if (!first) sb.append(", ");
sb.append("extraMap:");
if (this.extraMap == null) {
sb.append("null");
} else {
sb.append(this.extraMap);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (timPage != null) {
timPage.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class TimMessageIqStandardSchemeFactory implements SchemeFactory {
public TimMessageIqStandardScheme getScheme() {
return new TimMessageIqStandardScheme();
}
}
private static class TimMessageIqStandardScheme extends StandardScheme<TimMessageIq> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TimMessageIq struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TIDLIST
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list272 = iprot.readListBegin();
struct.tidlist = new ArrayList<String>(_list272.size);
String _elem273;
for (int _i274 = 0; _i274 < _list272.size; ++_i274)
{
_elem273 = iprot.readString();
struct.tidlist.add(_elem273);
}
iprot.readListEnd();
}
struct.setTidlistIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // TIM_PAGE
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.timPage = new TimPage();
struct.timPage.read(iprot);
struct.setTimPageIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // MIDLIST
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list275 = iprot.readListBegin();
struct.midlist = new ArrayList<String>(_list275.size);
String _elem276;
for (int _i277 = 0; _i277 < _list275.size; ++_i277)
{
_elem276 = iprot.readString();
struct.midlist.add(_elem276);
}
iprot.readListEnd();
}
struct.setMidlistIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // EXTRA_MAP
if (schemeField.type == org.apache.thrift.protocol.TType.MAP) {
{
org.apache.thrift.protocol.TMap _map278 = iprot.readMapBegin();
struct.extraMap = new HashMap<String,String>(2*_map278.size);
String _key279;
String _val280;
for (int _i281 = 0; _i281 < _map278.size; ++_i281)
{
_key279 = iprot.readString();
_val280 = iprot.readString();
struct.extraMap.put(_key279, _val280);
}
iprot.readMapEnd();
}
struct.setExtraMapIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, TimMessageIq struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.tidlist != null) {
if (struct.isSetTidlist()) {
oprot.writeFieldBegin(TIDLIST_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.tidlist.size()));
for (String _iter282 : struct.tidlist)
{
oprot.writeString(_iter282);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
if (struct.timPage != null) {
if (struct.isSetTimPage()) {
oprot.writeFieldBegin(TIM_PAGE_FIELD_DESC);
struct.timPage.write(oprot);
oprot.writeFieldEnd();
}
}
if (struct.midlist != null) {
if (struct.isSetMidlist()) {
oprot.writeFieldBegin(MIDLIST_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.midlist.size()));
for (String _iter283 : struct.midlist)
{
oprot.writeString(_iter283);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
if (struct.extraMap != null) {
if (struct.isSetExtraMap()) {
oprot.writeFieldBegin(EXTRA_MAP_FIELD_DESC);
{
oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING, struct.extraMap.size()));
for (Map.Entry<String, String> _iter284 : struct.extraMap.entrySet())
{
oprot.writeString(_iter284.getKey());
oprot.writeString(_iter284.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class TimMessageIqTupleSchemeFactory implements SchemeFactory {
public TimMessageIqTupleScheme getScheme() {
return new TimMessageIqTupleScheme();
}
}
private static class TimMessageIqTupleScheme extends TupleScheme<TimMessageIq> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TimMessageIq struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetTidlist()) {
optionals.set(0);
}
if (struct.isSetTimPage()) {
optionals.set(1);
}
if (struct.isSetMidlist()) {
optionals.set(2);
}
if (struct.isSetExtraMap()) {
optionals.set(3);
}
oprot.writeBitSet(optionals, 4);
if (struct.isSetTidlist()) {
{
oprot.writeI32(struct.tidlist.size());
for (String _iter285 : struct.tidlist)
{
oprot.writeString(_iter285);
}
}
}
if (struct.isSetTimPage()) {
struct.timPage.write(oprot);
}
if (struct.isSetMidlist()) {
{
oprot.writeI32(struct.midlist.size());
for (String _iter286 : struct.midlist)
{
oprot.writeString(_iter286);
}
}
}
if (struct.isSetExtraMap()) {
{
oprot.writeI32(struct.extraMap.size());
for (Map.Entry<String, String> _iter287 : struct.extraMap.entrySet())
{
oprot.writeString(_iter287.getKey());
oprot.writeString(_iter287.getValue());
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TimMessageIq struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(4);
if (incoming.get(0)) {
{
org.apache.thrift.protocol.TList _list288 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());
struct.tidlist = new ArrayList<String>(_list288.size);
String _elem289;
for (int _i290 = 0; _i290 < _list288.size; ++_i290)
{
_elem289 = iprot.readString();
struct.tidlist.add(_elem289);
}
}
struct.setTidlistIsSet(true);
}
if (incoming.get(1)) {
struct.timPage = new TimPage();
struct.timPage.read(iprot);
struct.setTimPageIsSet(true);
}
if (incoming.get(2)) {
{
org.apache.thrift.protocol.TList _list291 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());
struct.midlist = new ArrayList<String>(_list291.size);
String _elem292;
for (int _i293 = 0; _i293 < _list291.size; ++_i293)
{
_elem292 = iprot.readString();
struct.midlist.add(_elem292);
}
}
struct.setMidlistIsSet(true);
}
if (incoming.get(3)) {
{
org.apache.thrift.protocol.TMap _map294 = new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING, iprot.readI32());
struct.extraMap = new HashMap<String,String>(2*_map294.size);
String _key295;
String _val296;
for (int _i297 = 0; _i297 < _map294.size; ++_i297)
{
_key295 = iprot.readString();
_val296 = iprot.readString();
struct.extraMap.put(_key295, _val296);
}
}
struct.setExtraMapIsSet(true);
}
}
}
}
| 12,353 |
2,406 | # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from common.onnx_layer_test_class import Caffe2OnnxLayerTest
test_data_3D = [
dict(input_shape=[1, 50, 50], output_shapes=[[1, 50, 25], [1, 50, 25]], axis=2),
dict(input_shape=[2, 50, 50], output_shapes=[[2, 20, 50], [2, 15, 50], [2, 15, 50]], axis=1),
dict(input_shape=[4, 50, 50], output_shapes=[[1, 50, 50], [1, 50, 50], [1, 50, 50], [1, 50, 50]], axis=0)]
test_data_4D = [
dict(input_shape=[1, 32, 800, 800], output_shapes=[[1, 16, 800, 800], [1, 16, 800, 800]], axis=1),
dict(input_shape=[4, 32, 80, 80], output_shapes=[[4, 8, 80, 80], [4, 8, 80, 80], [4, 8, 80, 80], [4, 8, 80, 80]],
axis=1),
dict(input_shape=[2, 21, 80, 80], output_shapes=[[2, 7, 80, 80], [2, 7, 80, 80], [2, 7, 80, 80]], axis=1),
dict(input_shape=[3, 21, 80, 80], output_shapes=[[3, 14, 80, 80], [3, 5, 80, 80], [3, 2, 80, 80]], axis=1),
dict(input_shape=[3, 21, 80, 80], output_shapes=[[1, 21, 80, 80], [1, 21, 80, 80], [1, 21, 80, 80]], axis=0),
dict(input_shape=[3, 21, 80, 80], output_shapes=[[3, 21, 20, 80], [3, 21, 35, 80], [3, 21, 25, 80]], axis=2),
dict(input_shape=[3, 21, 80, 80], output_shapes=[[3, 21, 80, 40], [3, 21, 80, 10], [3, 21, 80, 30]], axis=3)]
test_data_5D = [
dict(input_shape=[1, 50, 50, 80, 60],
output_shapes=[[1, 50, 10, 80, 60],
[1, 50, 10, 80, 60],
[1, 50, 10, 80, 60],
[1, 50, 10, 80, 60],
[1, 50, 10, 80, 60]], axis=2),
dict(input_shape=[1, 50, 50, 80, 60], output_shapes=[[1, 25, 50, 80, 60], [1, 25, 50, 80, 60]], axis=1)]
class TestSplitConcat(Caffe2OnnxLayerTest):
# TODO Add test with default values (axis=0)
def create_split_concat_net(self, input_shape, output_shapes, axis, ir_version):
"""
ONNX net IR net
Input->Split->Concat->Output => Input->Split->Concat
"""
#
# Create ONNX model
#
import onnx
from onnx import helper
from onnx import TensorProto
input = helper.make_tensor_value_info('input', TensorProto.FLOAT, input_shape)
outputs, split = [], []
for id, output_shape in enumerate(output_shapes):
helper.make_tensor_value_info('output_{}'.format(id), TensorProto.FLOAT, output_shape)
outputs.append('output_{}'.format(id))
split.append(output_shape[axis])
# Output for concat
output_concat = helper.make_tensor_value_info('output_concat', TensorProto.FLOAT, input_shape)
node_split_def = onnx.helper.make_node(
'Split',
inputs=['input'],
outputs=outputs,
axis=axis,
split=split
)
node_concat_def = onnx.helper.make_node(
'Concat',
inputs=outputs,
outputs=['output_concat'],
axis=axis
)
# Create the graph (GraphProto)
graph_def = helper.make_graph(
[node_split_def, node_concat_def],
'test_split_model',
[input],
[output_concat],
)
# Create the model (ModelProto)
onnx_net = helper.make_model(graph_def, producer_name='test_split_model')
#
# Create reference IR net
# Please, spesify 'type': 'Input' for inpit node
# Moreover, do not forget to validate ALL layer attributes!!!
#
ref_net = None
return onnx_net, ref_net
# TODO Add test with default values (axis=0)
def create_split_concat_net_const(self, input_shape, output_shapes, axis, ir_version):
"""
ONNX net IR net
Input(const)->Split->Concat--->Concat->Output => Input--->Concat
Input-' Const-'
"""
#
# Create ONNX model
#
import onnx
from onnx import helper
from onnx import TensorProto
import numpy as np
concat_axis = 0
concat_output_shape = input_shape.copy()
concat_output_shape[concat_axis] *= 2
const_number = np.prod(input_shape)
constant = np.random.randint(-127, 127, const_number).astype(np.float)
input = helper.make_tensor_value_info('input', TensorProto.FLOAT, input_shape)
outputs, split = [], []
for id, output_shape in enumerate(output_shapes):
helper.make_tensor_value_info('output_{}'.format(id), TensorProto.FLOAT, output_shape)
outputs.append('output_{}'.format(id))
split.append(output_shape[axis])
# Output for concat
output_concat = helper.make_tensor_value_info('output_dyn_concat', TensorProto.FLOAT, concat_output_shape)
node_const_def = onnx.helper.make_node(
'Constant',
inputs=[],
outputs=['const1'],
value=helper.make_tensor(
name='const_tensor',
data_type=TensorProto.FLOAT,
dims=input_shape,
vals=constant,
),
)
node_split_def = onnx.helper.make_node(
'Split',
inputs=['const1'],
outputs=outputs,
axis=axis,
split=split
)
node_concat_def = onnx.helper.make_node(
'Concat',
inputs=outputs,
outputs=['output_concat'],
axis=axis
)
node_dyn_concat_def = onnx.helper.make_node(
'Concat',
inputs=['input', 'output_concat'],
outputs=['output_dyn_concat'],
axis=concat_axis
)
# Create the graph (GraphProto)
graph_def = helper.make_graph(
[node_const_def, node_split_def, node_concat_def, node_dyn_concat_def],
'test_split_model',
[input],
[output_concat],
)
# Create the model (ModelProto)
onnx_net = helper.make_model(graph_def, producer_name='test_split_model')
#
# Create reference IR net
# Please, spesify 'type': 'Input' for inpit node
# Moreover, do not forget to validate ALL layer attributes!!!
#
ref_net = None
return onnx_net, ref_net
@pytest.mark.parametrize("params", test_data_3D)
@pytest.mark.nightly
def test_split_3D(self, params, ie_device, precision, ir_version, temp_dir):
self._test(*self.create_split_concat_net(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
@pytest.mark.parametrize("params", test_data_4D)
@pytest.mark.nightly
def test_split_4D(self, params, ie_device, precision, ir_version, temp_dir):
self._test(*self.create_split_concat_net(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
@pytest.mark.parametrize("params", test_data_5D)
@pytest.mark.nightly
def test_split_5D(self, params, ie_device, precision, ir_version, temp_dir):
self._test(*self.create_split_concat_net(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
@pytest.mark.parametrize("params", test_data_3D)
@pytest.mark.nightly
def test_split_3D_const(self, params, ie_device, precision, ir_version, temp_dir):
self._test(
*self.create_split_concat_net_const(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
@pytest.mark.parametrize("params", test_data_4D)
@pytest.mark.nightly
def test_split_4D_const(self, params, ie_device, precision, ir_version, temp_dir):
self._test(
*self.create_split_concat_net_const(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
@pytest.mark.parametrize("params", test_data_5D)
@pytest.mark.nightly
def test_split_5D_const(self, params, ie_device, precision, ir_version, temp_dir):
self._test(
*self.create_split_concat_net_const(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
class TestSplit(Caffe2OnnxLayerTest):
# TODO Add test with default values (axis=0)
def create_split_net(self, input_shape, output_shapes, axis, ir_version):
"""
ONNX net IR net
Input->Split->Output => Input->Split
"""
#
# Create ONNX model
#
import onnx
from onnx import helper
from onnx import TensorProto
input = helper.make_tensor_value_info('input', TensorProto.FLOAT, input_shape)
outputs, split = [], []
for id, output_shape in enumerate(output_shapes):
out = helper.make_tensor_value_info('output_{}'.format(id), TensorProto.FLOAT, output_shape)
outputs.append((out, 'output_{}'.format(id)))
split.append(output_shape[axis])
node_split_def = onnx.helper.make_node(
'Split',
inputs=['input'],
outputs=['node_{}'.format(x[1]) for x in outputs],
axis=axis,
split=split
)
nodes = [node_split_def]
for x in outputs:
nodes.append(onnx.helper.make_node(
'Elu',
inputs=['node_{}'.format(x[1])],
outputs=[x[1]]
))
# Create the graph (GraphProto)
graph_def = helper.make_graph(
nodes,
'test_split_model',
[input],
[x[0] for x in outputs],
)
# Create the model (ModelProto)
onnx_net = helper.make_model(graph_def, producer_name='test_split_model')
#
# Create reference IR net
# Please, spesify 'type': 'Input' for inpit node
# Moreover, do not forget to validate ALL layer attributes!!!
#
ref_net = None
return onnx_net, ref_net
@pytest.mark.parametrize("params", test_data_3D)
@pytest.mark.nightly
def test_split_3D(self, params, ie_device, precision, ir_version, temp_dir):
self._test(*self.create_split_net(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
@pytest.mark.parametrize("params", test_data_4D)
@pytest.mark.nightly
def test_split_4D(self, params, ie_device, precision, ir_version, temp_dir):
self._test(*self.create_split_net(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
@pytest.mark.parametrize("params", test_data_5D)
@pytest.mark.nightly
def test_split_5D(self, params, ie_device, precision, ir_version, temp_dir):
self._test(*self.create_split_net(**params, ir_version=ir_version), ie_device, precision, ir_version,
temp_dir=temp_dir)
| 5,529 |
6,098 | <filename>h2o-hive/src/main/java/water/hive/ImpersonationUtils.java
package water.hive;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import java.io.IOException;
public class ImpersonationUtils {
public interface Callback { void call(String msg); }
public static void validateImpersonationArgs(
String principal, String keytabPath, String runAsUser,
Callback error, Callback warn
) {
if (principal != null || keytabPath != null) {
if (principal == null) {
error.call("keytab requires a valid principal (use the '-principal' option)");
}
if (keytabPath == null) {
error.call("principal requires a valid keytab path (use the '-keytab' option)");
}
if (runAsUser != null) {
warn.call("will attempt secure impersonation with user from '-run_as_user', " + runAsUser);
}
}
}
public static void impersonate(Configuration conf, String principal, String keytabPath, String runAsUser) throws IOException {
if (principal != null && keytabPath != null) {
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab(principal, keytabPath);
// performs user impersonation (will only work if core-site.xml has hadoop.proxyuser.*.* props set on name node
if (runAsUser != null) {
System.out.println("Attempting to securely impersonate user, " + runAsUser);
UserGroupInformation currentEffUser = UserGroupInformation.getLoginUser();
UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(runAsUser, currentEffUser);
UserGroupInformation.setLoginUser(proxyUser);
}
} else if (runAsUser != null) {
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.setLoginUser(UserGroupInformation.createRemoteUser(runAsUser));
}
}
}
| 822 |
7,018 | <reponame>peterchenlc/Hippy
// Copyright (c) 2020 Tencent Corporation. All rights reserved.
#pragma once
#define TDF_BASE_EMBEDDER_ONLY
#define TDF_BASE_DISALLOW_COPY(TypeName) TypeName(const TypeName&) = delete
#define TDF_BASE_DISALLOW_ASSIGN(TypeName) TypeName& operator=(const TypeName&) = delete
#define TDF_BASE_DISALLOW_MOVE(TypeName) \
TypeName(TypeName&&) = delete; \
TypeName& operator=(TypeName&&) = delete
#define TDF_BASE_DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&) = delete; \
TypeName& operator=(const TypeName&) = delete
#define TDF_BASE_DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName) \
TypeName(const TypeName&) = delete; \
TypeName(TypeName&&) = delete; \
TypeName& operator=(const TypeName&) = delete; \
TypeName& operator=(TypeName&&) = delete
#define TDF_BASE_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
TypeName() = delete; \
TDF_BASE_DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName)
#ifdef NDEBUG
#define assert_fn(fn) ((void)0)
#else
#define assert_fn(fn) \
do { \
auto b = fn(); \
assert(b); \
} while (0)
#endif
#define RETURN_IF(x) \
if (x) { \
return; \
}
| 615 |
448 | # import opencv
import cv2
# Load the Cascade Classifier
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# start web cam
cap = cv2.VideoCapture(0)
while True:
# read image from webcam
respose, color_img = cap.read()
# Convert to grayscale
gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)
# Detect the faces
faces = face_cascade.detectMultiScale(gray_img, 1.4, 7)
# display rectangle
for (x, y, w, h) in faces:
cv2.rectangle(color_img, (x, y), (x + w, y + h), (0, 0, 255), 3)
# display image
cv2.imshow('img', color_img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the VideoCapture object
cap.release()
cv2.destroyAllWindows()
| 313 |
3,189 | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled May 11 2021 09:30:43).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <XCTest/NSObject-Protocol.h>
@class XCTNSPredicateExpectation;
@protocol XCTNSPredicateExpectationObject <NSObject>
@optional
- (_Bool)evaluatePredicateForExpectation:(XCTNSPredicateExpectation *)arg1 debugMessage:(id *)arg2;
@end
| 142 |
777 | <reponame>anuraaga/graphviz-java
/*
* Copyright © 2015 <NAME> (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package guru.nidi.graphviz.attribute;
import org.junit.jupiter.api.Test;
import static guru.nidi.graphviz.attribute.Attributes.attr;
import static guru.nidi.graphviz.attribute.Attributes.attrs;
import static guru.nidi.graphviz.attribute.Rank.RankDir.LEFT_TO_RIGHT;
import static guru.nidi.graphviz.attribute.Rank.RankDir.TOP_TO_BOTTOM;
import static guru.nidi.graphviz.attribute.Rank.RankType.SAME;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RankTest {
@Test
void rank() {
assertEquals(attrs(attr("rank", "same")), attrs(Rank.inSubgraph(SAME)));
}
@Test
void dir() {
assertEquals(attrs(attr("rankdir", "LR")), attrs(Rank.dir(LEFT_TO_RIGHT)));
}
@Test
void sep() {
assertEquals(attrs(attr("ranksep", "2.0")), attrs(Rank.sep(2)));
assertEquals(attrs(attr("ranksep", "2.0 equally")), attrs(Rank.sepEqually(2)));
}
@Test
void newRank() {
assertEquals(attrs(attr("newrank", true)), attrs(Rank.newRank()));
}
@Test
void combine() {
assertEquals(attrs(attr("newrank", true), attr("clusterrank", "global"),
attr("rankdir", "TB"), attr("ranksep", "3.0 equally")),
attrs(Rank.sepEqually(2).newRank(true).noCluster().dir(TOP_TO_BOTTOM).sep(3)));
}
}
| 750 |
575 | <reponame>iridium-browser/iridium-browser
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SHARESHEET_DRIVE_SHARE_ACTION_H_
#define CHROME_BROWSER_SHARESHEET_DRIVE_SHARE_ACTION_H_
#include "chrome/browser/sharesheet/share_action.h"
class DriveShareAction : public sharesheet::ShareAction {
public:
DriveShareAction();
~DriveShareAction() override;
DriveShareAction(const DriveShareAction&) = delete;
DriveShareAction& operator=(const DriveShareAction&) = delete;
// sharesheet::ShareAction:
const std::u16string GetActionName() override;
const gfx::VectorIcon& GetActionIcon() override;
void LaunchAction(sharesheet::SharesheetController* controller,
views::View* root_view,
apps::mojom::IntentPtr intent) override;
void OnClosing(sharesheet::SharesheetController* controller) override;
bool ShouldShowAction(const apps::mojom::IntentPtr& intent,
bool contains_hosted_document) override;
private:
sharesheet::SharesheetController* controller_ = nullptr;
};
#endif // CHROME_BROWSER_SHARESHEET_DRIVE_SHARE_ACTION_H_
| 428 |
2,209 | <reponame>yunnant/kungfu
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
/*! \file rx-map.hpp
\brief For each item from this observable use Selector to produce an item to emit from the new observable that is returned.
\tparam Selector the type of the transforming function
\param s the selector function
\return Observable that emits the items from the source observable, transformed by the specified function.
\sample
\snippet map.cpp map sample
\snippet output.txt map sample
*/
#if !defined(RXCPP_OPERATORS_RX_MAP_HPP)
#define RXCPP_OPERATORS_RX_MAP_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace operators {
namespace detail {
template<class... AN>
struct map_invalid_arguments {};
template<class... AN>
struct map_invalid : public rxo::operator_base<map_invalid_arguments<AN...>> {
using type = observable<map_invalid_arguments<AN...>, map_invalid<AN...>>;
};
template<class... AN>
using map_invalid_t = typename map_invalid<AN...>::type;
template<class T, class Selector>
struct map
{
typedef rxu::decay_t<T> source_value_type;
typedef rxu::decay_t<Selector> select_type;
typedef decltype((*(select_type*)nullptr)(*(source_value_type*)nullptr)) value_type;
select_type selector;
map(select_type s)
: selector(std::move(s))
{
}
template<class Subscriber>
struct map_observer
{
typedef map_observer<Subscriber> this_type;
typedef decltype((*(select_type*)nullptr)(*(source_value_type*)nullptr)) value_type;
typedef rxu::decay_t<Subscriber> dest_type;
typedef observer<source_value_type, this_type> observer_type;
dest_type dest;
mutable select_type selector;
map_observer(dest_type d, select_type s)
: dest(std::move(d))
, selector(std::move(s))
{
}
template<class Value>
void on_next(Value&& v) const {
auto selected = on_exception(
[&](){
return this->selector(std::forward<Value>(v));},
dest);
if (selected.empty()) {
return;
}
dest.on_next(std::move(selected.get()));
}
void on_error(std::exception_ptr e) const {
dest.on_error(e);
}
void on_completed() const {
dest.on_completed();
}
static subscriber<source_value_type, observer_type> make(dest_type d, select_type s) {
auto cs = d.get_subscription();
return make_subscriber<source_value_type>(std::move(cs), observer_type(this_type(std::move(d), std::move(s))));
}
};
template<class Subscriber>
auto operator()(Subscriber dest) const
-> decltype(map_observer<Subscriber>::make(std::move(dest), selector)) {
return map_observer<Subscriber>::make(std::move(dest), selector);
}
};
}
/*! @copydoc rx-map.hpp
*/
template<class... AN>
auto map(AN&&... an)
-> operator_factory<map_tag, AN...> {
return operator_factory<map_tag, AN...>(std::make_tuple(std::forward<AN>(an)...));
}
/*! @copydoc rx-map.hpp
*/
template<class... AN>
auto transform(AN&&... an)
-> operator_factory<map_tag, AN...> {
return operator_factory<map_tag, AN...>(std::make_tuple(std::forward<AN>(an)...));
}
}
template<>
struct member_overload<map_tag>
{
template<class Observable, class Selector,
class Enabled = rxu::enable_if_all_true_type_t<
is_observable<Observable>>,
class ResolvedSelector = rxu::decay_t<Selector>,
class SourceValue = rxu::value_type_t<Observable>,
class Map = rxo::detail::map<SourceValue, ResolvedSelector>,
class Value = rxu::value_type_t<Map>>
static auto member(Observable&& o, Selector&& s)
-> decltype(o.template lift<Value>(Map(std::forward<Selector>(s)))) {
return o.template lift<Value>(Map(std::forward<Selector>(s)));
}
template<class... AN>
static operators::detail::map_invalid_t<AN...> member(const AN...) {
std::terminate();
return {};
static_assert(sizeof...(AN) == 10000, "map takes Selector");
}
};
}
#endif
| 1,831 |
107,386 | {"Action":"run","Test":"TestUnicode"}
{"Action":"output","Test":"TestUnicode","Output":"=== RUN TestUnicode\n"}
{"Action":"output","Test":"TestUnicode","Output":"Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα.\n"}
{"Action":"output","Test":"TestUnicode","Output":"私はガラスを食べられます。それは私を傷つけません。私はガラスを食べられます。それは私を傷つけません。\n"}
{"Action":"output","Test":"TestUnicode","Output":"--- PASS: TestUnicode\n"}
{"Action":"output","Test":"TestUnicode","Output":" ฉันกินกระจกได้ แต่มันไม่ทำให้ฉันเจ็บ ฉันกินกระจกได้ แต่มันไม่ทำให้ฉันเจ็บ\n"}
{"Action":"output","Test":"TestUnicode","Output":" אני יכול לאכול זכוכית וזה לא מזיק לי. אני יכול לאכול זכוכית וזה לא מזיק לי.\n"}
{"Action":"pass","Test":"TestUnicode"}
{"Action":"output","Output":"PASS\n"}
{"Action":"pass"}
| 597 |
852 | <reponame>ckamtsikis/cmssw<filename>L1Trigger/L1TMuonBarrel/test/kalmanTools/validation.py
from __future__ import print_function
import ROOT,itertools,math #
from array import array #
from DataFormats.FWLite import Events, Handle
ROOT.FWLiteEnabler.enable()
#
tag='output'
##A class to keep BMTF data
###Common methods############
def fetchStubsOLD(event,ontime=False,isData=True):
phiSeg = Handle ('L1MuDTChambPhContainer')
if not isData:
event.getByLabel('simTwinMuxDigis',phiSeg)
else:
event.getByLabel('bmtfDigis',phiSeg)
if ontime:
filtered=filter(lambda x: x.bxNum()==0, phiSeg.product().getContainer())
return filtered
else:
return phiSeg.product().getContainer()
def fetchStubs(event,ontime=True):
phiSeg2 = Handle ('std::vector<L1MuKBMTCombinedStub>')
event.getByLabel('simKBmtfStubs',phiSeg2)
if ontime:
filtered=filter(lambda x: x.bxNum()==0, phiSeg2.product())
return filtered
else:
return phiSeg2.product()
def globalBMTFPhi(muon):
temp=muon.processor()*48+muon.hwPhi()
temp=temp*2*math.pi/576.0-math.pi*15.0/180.0;
if temp>math.pi:
temp=temp-2*math.pi;
K=1.0/muon.hwPt()
if muon.hwSign()>0:
K=-1.0/muon.hwPt()
return temp+5.740*K
def fetchKMTF(event,etaMax,collection):
kbmtfH = Handle ('BXVector<l1t::RegionalMuonCand>')
event.getByLabel(collection,kbmtfH)
kbmtf=kbmtfH.product()
kbmtfMuons={}
for bx in [-3,-2,-1,0,1,2,3]:
kbmtfMuons[bx]=[]
for bx in range(kbmtf.getFirstBX(),kbmtf.getLastBX()+1):
for j in range(0,kbmtf.size(bx)):
mu = kbmtf.at(bx,j)
kbmtfMuons[bx].append(mu)
# kbmtfMuons[bx]=sorted(kbmtfMuons[bx],key=lambda x: x.hwPt(),reverse=True)
return kbmtfMuons
def curvResidual(a,b):
return (a.charge()/a.pt()-b.charge()/b.pt())*b.pt()/b.charge()
def ptResidual(a,b):
return (a.pt()-b.pt())/b.pt()
def curvResidualSTA(a,b):
return (a.charge()/a.ptUnconstrained()-b.charge()/b.pt())*b.pt()/b.charge()
def deltaPhi( p1, p2):
'''Computes delta phi, handling periodic limit conditions.'''
res = p1 - p2
while res > math.pi:
res -= 2*math.pi
while res < -math.pi:
res += 2*math.pi
return res
def deltaR( *args ):
return math.sqrt( deltaR2(*args) )
def deltaR2( e1, p1, e2, p2):
de = e1 - e2
dp = deltaPhi(p1, p2)
return de*de + dp*dp
def log(event,counter,mystubs,kmtf,bmtf):
print("--------EVENT"+str(counter)+"------------")
print('RUN={run} LUMI={lumi} EVENT={event}'.format(run=event.eventAuxiliary().id().run(),lumi=event.eventAuxiliary().id().luminosityBlock(),event=event.eventAuxiliary().id().event()))
print("-----------------------------")
print("-----------------------------")
print('Stubs:')
for stub in mystubs:
print('wheel={w} sector={sc} station={st} high/low={ts} phi={phi} phiB={phiB} qual={qual} BX={BX}'.format(w=stub.whNum(),sc=stub.scNum(),st=stub.stNum(),ts=stub.Ts2Tag(),phi=stub.phi(),phiB=stub.phiB(),qual=stub.code(),BX=stub.bxNum()))
print('EMU:')
for g in bmtf :
print("EMU sector={sector} pt={pt} eta={eta} phi={phi} qual={qual} dxy={dxy} pt2={pt2} hasFineEta={HF}".format(sector=g.processor(), pt=g.hwPt(),eta=g.hwEta(),phi=g.hwPhi(),qual=g.hwQual(),dxy=g.hwDXY(),pt2=g.hwPtUnconstrained(),HF=g.hwHF()))
print('DATA:')
for g in kmtf :
print("DATA sector={sector} pt={pt} eta={eta} phi={phi} qual={qual} dxy={dxy} pt2={pt2} hasFineEta={HF}".format(sector=g.processor(),pt=g.hwPt(),eta=g.hwEta(),phi=g.hwPhi(),qual=g.hwQual(),dxy=g.hwDXY(),pt2=g.hwPtUnconstrained(),HF=g.hwHF()))
print("-----------------------------")
print("-----------------------------")
print("c + enter to continue")
import pdb;pdb.set_trace()
###############################
#########Histograms#############
histos={}
histos['fw']={}
histos['fw']['pt1']=ROOT.TH1D("fw_pt1","HW p_{T}",512,0,511)
histos['fw']['eta1']=ROOT.TH1D("fw_eta1","HW #eta",256,-127,128)
histos['fw']['phi1']=ROOT.TH1D("fw_phi1","HW #phi",256,-127,128)
histos['fw']['HF1']=ROOT.TH1D("fw_HF1","HW HF",256,-127,128)
histos['fw']['qual1']=ROOT.TH1D("fw_qual1","HW qual",16,0,16)
histos['fw']['dxy1']=ROOT.TH1D("fw_dxy1","HW DXY",4,0,4)
histos['fw']['ptSTA1']=ROOT.TH1D("fw_ptSTA1","HW STA PT",256,0,255)
histos['fw']['pt2']=ROOT.TH1D("fw_pt2","HW p_{T}",512,0,511)
histos['fw']['eta2']=ROOT.TH1D("fw_eta2","HW #eta",256,-127,128)
histos['fw']['phi2']=ROOT.TH1D("fw_phi2","HW #phi",256,-127,128)
histos['fw']['HF2']=ROOT.TH1D("fw_HF2","HW HF",256,-127,128)
histos['fw']['qual2']=ROOT.TH1D("fw_qual2","HW qual",16,0,16)
histos['fw']['dxy2']=ROOT.TH1D("fw_dxy2","HW DXY",4,0,4)
histos['fw']['ptSTA2']=ROOT.TH1D("fw_ptSTA2","HW STA PT",256,0,255)
histos['fw']['pt3']=ROOT.TH1D("fw_pt3","HW p_{T}",512,0,511)
histos['fw']['eta3']=ROOT.TH1D("fw_eta3","HW #eta",256,-127,128)
histos['fw']['phi3']=ROOT.TH1D("fw_phi3","HW #phi",256,-127,128)
histos['fw']['HF3']=ROOT.TH1D("fw_HF3","HW HF",256,-127,128)
histos['fw']['qual3']=ROOT.TH1D("fw_qual3","HW qual",16,0,16)
histos['fw']['dxy3']=ROOT.TH1D("fw_dxy3","HW DXY",4,0,4)
histos['fw']['ptSTA3']=ROOT.TH1D("fw_ptSTA3","HW STA PT",256,0,255)
histos['emu']={}
histos['emu']['pt1']=ROOT.TH1D("emu_pt1","HW p_{T}",512,0,511)
histos['emu']['eta1']=ROOT.TH1D("emu_eta1","HW #eta",256,-127,128)
histos['emu']['phi1']=ROOT.TH1D("emu_phi1","HW #phi",256,-127,128)
histos['emu']['HF1']=ROOT.TH1D("emu_HF1","HW HF",256,-127,128)
histos['emu']['qual1']=ROOT.TH1D("emu_qual1","HW qual",16,0,16)
histos['emu']['dxy1']=ROOT.TH1D("emu_dxy1","HW DXY",4,0,4)
histos['emu']['ptSTA1']=ROOT.TH1D("emu_ptSTA1","HW STA PT",256,0,255)
histos['emu']['pt2']=ROOT.TH1D("emu_pt2","HW p_{T}",512,0,511)
histos['emu']['eta2']=ROOT.TH1D("emu_eta2","HW #eta",256,-127,128)
histos['emu']['phi2']=ROOT.TH1D("emu_phi2","HW #phi",256,-127,128)
histos['emu']['HF2']=ROOT.TH1D("emu_HF2","HW HF",256,-127,128)
histos['emu']['qual2']=ROOT.TH1D("emu_qual2","HW qual",16,0,16)
histos['emu']['dxy2']=ROOT.TH1D("emu_dxy2","HW DXY",4,0,4)
histos['emu']['ptSTA2']=ROOT.TH1D("emu_ptSTA2","HW STA PT",256,0,255)
histos['emu']['pt3']=ROOT.TH1D("emu_pt3","HW p_{T}",512,0,511)
histos['emu']['eta3']=ROOT.TH1D("emu_eta3","HW #eta",256,-127,128)
histos['emu']['phi3']=ROOT.TH1D("emu_phi3","HW #phi",256,-127,128)
histos['emu']['HF3']=ROOT.TH1D("emu_HF3","HW HF",256,-127,128)
histos['emu']['qual3']=ROOT.TH1D("emu_qual3","HW qual",16,0,16)
histos['emu']['dxy3']=ROOT.TH1D("emu_dxy3","HW DXY",4,0,4)
histos['emu']['ptSTA3']=ROOT.TH1D("emu_ptSTA3","HW STA PT",256,0,255)
for key,histo in histos['fw'].iteritems():
histo.Sumw2()
def fill(info,mu):
if len(mu)>0:
info['pt1'].Fill(mu[0].hwPt())
info['eta1'].Fill(mu[0].hwEta())
info['phi1'].Fill(mu[0].hwPhi())
info['HF1'].Fill(mu[0].hwHF())
info['qual1'].Fill(mu[0].hwQual())
info['dxy1'].Fill(mu[0].hwDXY())
info['ptSTA1'].Fill(mu[0].hwPtUnconstrained())
else:
info['pt1'].Fill(0)
info['eta1'].Fill(0)
info['phi1'].Fill(0)
info['HF1'].Fill(0)
info['qual1'].Fill(0)
info['dxy1'].Fill(0)
info['ptSTA1'].Fill(0)
if len(mu)>1:
info['pt2'].Fill(mu[1].hwPt())
info['eta2'].Fill(mu[1].hwEta())
info['phi2'].Fill(mu[1].hwPhi())
info['HF2'].Fill(mu[1].hwHF())
info['qual2'].Fill(mu[1].hwQual())
info['dxy2'].Fill(mu[1].hwDXY())
info['ptSTA2'].Fill(mu[1].hwPtUnconstrained())
else:
info['pt2'].Fill(0)
info['eta2'].Fill(0)
info['phi2'].Fill(0)
info['HF2'].Fill(0)
info['qual2'].Fill(0)
info['dxy2'].Fill(0)
info['ptSTA2'].Fill(0)
if len(mu)>2:
info['pt3'].Fill(mu[2].hwPt())
info['eta3'].Fill(mu[2].hwEta())
info['phi3'].Fill(mu[2].hwPhi())
info['HF3'].Fill(mu[2].hwHF())
info['qual3'].Fill(mu[2].hwQual())
info['dxy3'].Fill(mu[2].hwDXY())
info['ptSTA3'].Fill(mu[2].hwPtUnconstrained())
else:
info['pt3'].Fill(0)
info['eta3'].Fill(0)
info['phi3'].Fill(0)
info['HF3'].Fill(0)
info['qual3'].Fill(0)
info['dxy3'].Fill(0)
info['ptSTA3'].Fill(0)
##############################
BUNCHES=[0]
events=Events([tag+'.root'])
counter=-1
for event in events:
counter=counter+1
#fetch stubs
stubs=fetchStubsOLD(event,True)
unpacker=fetchKMTF(event,100.0,'bmtfDigis:kBMTF')
emulator=fetchKMTF(event,100.0,'simKBmtfDigis:BMTF')
for processor in range(0,12):
for bx in BUNCHES:
emu=filter(lambda x: x.processor()==processor,emulator[bx])
data=filter(lambda x: x.processor()==processor,unpacker[bx])
if (len(emu)+len(data))>0:
fill(histos['emu'],emu)
fill(histos['fw'],data)
# if len(emu)!=0 and len(data)==0:
# log(event,counter,stubs,data,emu)
# import pdb;pdb.set_trace()
f=ROOT.TFile("validationResults.root","RECREATE")
for key,histo in histos['fw'].iteritems():
histo.SetMarkerStyle(7)
histo.Write()
for key,histo in histos['emu'].iteritems():
histo.SetLineColor(ROOT.kRed)
histo.Write()
#make fancy plots
histonames=['pt1','eta1','phi1','HF1','qual1','dxy1','ptSTA1']
for h in histonames:
c=ROOT.TCanvas(h)
c.cd()
histos['emu'][h].Draw("HIST")
histos['emu'][h].GetXaxis().SetTitle(histos['emu'][h].GetTitle())
histos['emu'][h].GetYaxis().SetTitle("events")
histos['fw'][h].Draw("SAME")
c.SetLogy()
l=ROOT.TLegend(0.6,0.6,0.9,0.8)
l.AddEntry(histos['emu'][h],"emulator","l")
l.AddEntry(histos['fw'][h],"data","p")
l.Draw()
c.Write("plot_"+h)
f.Close()
| 5,178 |
662 | import autopy
autopy.bitmap.capture_screen().save("screenshot.png")
| 24 |
1,346 | package com.ctrip.platform.dal.dao.datasource;
/**
* Created by taochen on 2019/8/7.
*/
public interface DataSourceSwitchListener {
void execute();
}
| 54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.