max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,006 | from .common import EWSAccountService, create_item_ids_element
from ..errors import ResponseMessageError
from ..util import create_element, MNS
class ExportItems(EWSAccountService):
"""MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/exportitems-operation"""
ERRORS_TO_CATCH_IN_RESPONSE = ResponseMessageError
SERVICE_NAME = 'ExportItems'
element_container_name = '{%s}Data' % MNS
def call(self, items):
return self._elems_to_objs(self._chunked_get_elements(self.get_payload, items=items))
def _elems_to_objs(self, elems):
for elem in elems:
if isinstance(elem, Exception):
yield elem
continue
yield elem.text # All we want is the 64bit string in the 'Data' tag
def get_payload(self, items):
exportitems = create_element('m:%s' % self.SERVICE_NAME)
item_ids = create_item_ids_element(items=items, version=self.account.version)
exportitems.append(item_ids)
return exportitems
# We need to override this since ExportItemsResponseMessage is formatted a
# little bit differently. .
@classmethod
def _get_elements_in_container(cls, container):
return [container]
| 487 |
335 | <gh_stars>100-1000
{
"word": "Village",
"definitions": [
"A group of houses and associated buildings, larger than a hamlet and smaller than a town, situated in a rural area.",
"A self-contained district or community within a town or city, regarded as having features characteristic of village life.",
"A small municipality with limited corporate powers.",
"A select suburban shopping centre."
],
"parts-of-speech": "Noun"
} | 149 |
3,073 | <filename>pkg/urbit/jets/e/shax.c
/* j/5/shax.c
**
*/
#include "all.h"
#include <urcrypt.h>
/* functions
*/
static u3_atom
_cqe_shay(u3_atom wid,
u3_atom dat)
{
c3_w len_w;
if ( !u3r_word_fit(&len_w, wid) ) {
return u3m_bail(c3__fail);
}
else {
c3_y out_y[32];
c3_y* dat_y = u3r_bytes_alloc(0, len_w, dat);
urcrypt_shay(dat_y, len_w, out_y);
u3a_free(dat_y);
return u3i_bytes(32, out_y);
}
}
static u3_atom
_cqe_shax(u3_atom a)
{
c3_w len_w;
c3_y out_y[32];
c3_y* dat_y = u3r_bytes_all(&len_w, a);
urcrypt_shay(dat_y, len_w, out_y);
u3a_free(dat_y);
return u3i_bytes(32, out_y);
}
static u3_atom
_cqe_shal(u3_atom wid,
u3_atom dat)
{
c3_w len_w;
if ( !u3r_word_fit(&len_w, wid) ) {
return u3m_bail(c3__fail);
}
else {
c3_y out_y[64];
c3_y* dat_y = u3r_bytes_alloc(0, len_w, dat);
urcrypt_shal(dat_y, len_w, out_y);
u3a_free(dat_y);
return u3i_bytes(64, out_y);
}
}
static u3_atom
_cqe_shas(u3_atom sal,
u3_atom ruz)
{
c3_w sal_w, ruz_w;
c3_y *sal_y, *ruz_y, out_y[32];
sal_y = u3r_bytes_all(&sal_w, sal);
ruz_y = u3r_bytes_all(&ruz_w, ruz);
urcrypt_shas(sal_y, sal_w, ruz_y, ruz_w, out_y);
u3a_free(sal_y);
u3a_free(ruz_y);
return u3i_bytes(32, out_y);
}
u3_noun
u3we_shax(u3_noun cor)
{
u3_noun a;
if ( (u3_none == (a = u3r_at(u3x_sam, cor))) ||
(c3n == u3ud(a)) )
{
return u3m_bail(c3__exit);
} else {
return _cqe_shax(a);
}
}
u3_noun
u3we_shay(u3_noun cor)
{
u3_noun a, b;
if ( (u3_none == (a = u3r_at(u3x_sam_2, cor))) ||
(u3_none == (b = u3r_at(u3x_sam_3, cor))) ||
(c3n == u3ud(a)) ||
(c3n == u3ud(b)) )
{
return u3m_bail(c3__exit);
} else {
return _cqe_shay(a, b);
}
}
u3_noun
u3we_shal(u3_noun cor)
{
u3_noun a, b;
if ( (u3_none == (a = u3r_at(u3x_sam_2, cor))) ||
(u3_none == (b = u3r_at(u3x_sam_3, cor))) ||
(c3n == u3ud(a)) ||
(c3n == u3ud(b)) )
{
return u3m_bail(c3__exit);
} else {
return _cqe_shal(a, b);
}
}
u3_noun
u3we_shas(u3_noun cor)
{
u3_noun sal, ruz;
if ( (u3_none == (sal = u3r_at(u3x_sam_2, cor))) ||
(u3_none == (ruz = u3r_at(u3x_sam_3, cor))) ||
(c3n == u3ud(sal)) ||
(c3n == u3ud(ruz)) )
{
return u3m_bail(c3__exit);
} else {
return _cqe_shas(sal, ruz);
}
}
static u3_noun
_og_list(u3_noun a,
u3_noun b,
u3_noun c)
{
u3_noun l = u3_nul;
if ( !_(u3a_is_cat(b)) ) {
return u3m_bail(c3__fail);
}
while ( 0 != b ) {
u3_noun x = u3qc_mix(a, c);
u3_noun y = u3qc_mix(b, x);
u3_noun d = _cqe_shas(c3_s4('o','g','-','b'), y);
u3_noun m;
u3z(x); u3z(y);
if ( b < 256 ) {
u3_noun e = u3qc_end(0, b, d);
u3z(d);
m = u3nc(b, e);
b = 0;
} else {
m = u3nc(256, d);
c = d;
b -= 256;
}
l = u3nc(m, l);
}
return u3kb_flop(l);
}
u3_noun
u3qeo_raw(u3_atom a,
u3_atom b)
{
u3_noun x = u3qc_mix(b, a);
u3_noun c = _cqe_shas(c3_s4('o','g','-','a'), x);
u3_noun l = _og_list(a, b, c);
u3_noun r = u3qc_can(0, l);
u3z(l);
u3z(c);
u3z(x);
return r;
}
u3_noun
u3weo_raw(u3_noun cor)
{
u3_noun a, b;
if ( c3n == u3r_mean(cor, u3x_sam, &b, u3x_con_sam, &a, 0) ) {
return u3m_bail(c3__exit);
} else {
return u3qeo_raw(a, b);
}
}
| 2,370 |
844 | <gh_stars>100-1000
{
"github-username": "takshch",
"favourite-emoji": "😀",
"favourite-music": "https://soundcloud.com/maroon-5/what-lovers-do-feat-sza",
"favourite-color": "#fff"
} | 93 |
363 | /*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.internal.maps;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.ShouldNotContainKeys.shouldNotContainKeys;
import static org.assertj.core.internal.ErrorMessages.keysToLookForIsNull;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.AssertionsUtil.expectAssertionError;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.assertj.core.util.Sets.set;
import java.util.Map;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Maps;
import org.assertj.core.internal.MapsBaseTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests for <code>{@link Maps#assertDoesNotContainKeys(AssertionInfo, Map, Object[])}</code>.
*
* @author dorzey
*/
@DisplayName("Maps assertDoesNotContainKeys")
class Maps_assertDoesNotContainKeys_Test extends MapsBaseTest {
private static final String ARRAY_OF_KEYS = "array of keys";
@Override
@BeforeEach
protected void setUp() {
super.setUp();
actual.put(null, null);
}
@Test
void should_pass_if_actual_does_not_contain_given_keys() {
maps.assertDoesNotContainKeys(someInfo(), actual, array("age"));
}
@Test
void should_fail_if_actual_is_null() {
// GIVEN
String[] keys = { "name" };
// WHEN
AssertionError error = expectAssertionError(() -> maps.assertDoesNotContainKeys(someInfo(), null, keys));
// THEN
then(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_given_keys_array_is_null() {
// GIVEN
String[] keys = null;
// WHEN
Throwable thrown = catchThrowable(() -> maps.assertDoesNotContainKeys(someInfo(), actual, keys));
// THEN
then(thrown).isInstanceOf(NullPointerException.class).hasMessage(keysToLookForIsNull(ARRAY_OF_KEYS));
}
@ParameterizedTest
@NullSource
@ValueSource(strings = { "name", "color" })
void should_fail_if_actual_contains_key(String key) {
// GIVEN
String[] keys = { key };
// WHEN
AssertionError error = expectAssertionError(() -> maps.assertDoesNotContainKeys(someInfo(), actual, keys));
// THEN
then(error).hasMessage(shouldNotContainKeys(actual, set(key)).create());
}
@Test
void should_fail_if_actual_contains_keys() {
// GIVEN
String[] keys = { "name", "color" };
// WHEN
AssertionError error = expectAssertionError(() -> maps.assertDoesNotContainKeys(someInfo(), actual, keys));
// THEN
then(error).hasMessage(shouldNotContainKeys(actual, set("name", "color")).create());
}
}
| 1,184 |
445 |
import re
import copy
import numpy as np
from astropy import _erfa as erfa
from astropy.utils.compat.misc import override__dir__
from astropy import units as u
from astropy.constants import c as speed_of_light
from astropy.wcs.utils import skycoord_to_pixel, pixel_to_skycoord
from astropy.utils.data_info import MixinInfo
from astropy.utils import ShapedLikeNDArray
from astropy.time import Time
from .distances import Distance
from .angles import Angle
from .baseframe import (BaseCoordinateFrame, frame_transform_graph,
GenericFrame)
from .builtin_frames import ICRS, SkyOffsetFrame
from .representation import (SphericalRepresentation,
UnitSphericalRepresentation, SphericalDifferential)
from .sky_coordinate_parsers import (_get_frame_class, _get_frame_without_data,
_parse_coordinate_data)
__all__ = ['SkyCoord', 'SkyCoordInfo']
class SkyCoordInfo(MixinInfo):
"""
Container for meta information like name, description, format. This is
required when the object is used as a mixin column within a table, but can
be used as a general way to store meta information.
"""
attrs_from_parent = set(['unit']) # Unit is read-only
_supports_indexing = False
@staticmethod
def default_format(val):
repr_data = val.info._repr_data
formats = ['{0.' + compname + '.value:}' for compname
in repr_data.components]
return ','.join(formats).format(repr_data)
@property
def unit(self):
repr_data = self._repr_data
unit = ','.join(str(getattr(repr_data, comp).unit) or 'None'
for comp in repr_data.components)
return unit
@property
def _repr_data(self):
if self._parent is None:
return None
sc = self._parent
if (issubclass(sc.representation_type, SphericalRepresentation)
and isinstance(sc.data, UnitSphericalRepresentation)):
repr_data = sc.represent_as(sc.data.__class__, in_frame_units=True)
else:
repr_data = sc.represent_as(sc.representation_type,
in_frame_units=True)
return repr_data
def _represent_as_dict(self):
obj = self._parent
attrs = (list(obj.representation_component_names) +
list(frame_transform_graph.frame_attributes.keys()))
# Don't output distance if it is all unitless 1.0
if 'distance' in attrs and np.all(obj.distance == 1.0):
attrs.remove('distance')
out = super()._represent_as_dict(attrs)
out['representation_type'] = obj.representation_type.get_name()
out['frame'] = obj.frame.name
# Note that obj.info.unit is a fake composite unit (e.g. 'deg,deg,None'
# or None,None,m) and is not stored. The individual attributes have
# units.
return out
class SkyCoord(ShapedLikeNDArray):
"""High-level object providing a flexible interface for celestial coordinate
representation, manipulation, and transformation between systems.
The `SkyCoord` class accepts a wide variety of inputs for initialization. At
a minimum these must provide one or more celestial coordinate values with
unambiguous units. Inputs may be scalars or lists/tuples/arrays, yielding
scalar or array coordinates (can be checked via ``SkyCoord.isscalar``).
Typically one also specifies the coordinate frame, though this is not
required. The general pattern for spherical representations is::
SkyCoord(COORD, [FRAME], keyword_args ...)
SkyCoord(LON, LAT, [FRAME], keyword_args ...)
SkyCoord(LON, LAT, [DISTANCE], frame=FRAME, unit=UNIT, keyword_args ...)
SkyCoord([FRAME], <lon_attr>=LON, <lat_attr>=LAT, keyword_args ...)
It is also possible to input coordinate values in other representations
such as cartesian or cylindrical. In this case one includes the keyword
argument ``representation_type='cartesian'`` (for example) along with data
in ``x``, ``y``, and ``z``.
See also: http://docs.astropy.org/en/stable/coordinates/
Examples
--------
The examples below illustrate common ways of initializing a `SkyCoord`
object. For a complete description of the allowed syntax see the
full coordinates documentation. First some imports::
>>> from astropy.coordinates import SkyCoord # High-level coordinates
>>> from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames
>>> from astropy.coordinates import Angle, Latitude, Longitude # Angles
>>> import astropy.units as u
The coordinate values and frame specification can now be provided using
positional and keyword arguments::
>>> c = SkyCoord(10, 20, unit="deg") # defaults to ICRS frame
>>> c = SkyCoord([1, 2, 3], [-30, 45, 8], frame="icrs", unit="deg") # 3 coords
>>> coords = ["1:12:43.2 +1:12:43", "1 12 43.2 +1 12 43"]
>>> c = SkyCoord(coords, frame=FK4, unit=(u.deg, u.hourangle), obstime="J1992.21")
>>> c = SkyCoord("1h12m43.2s +1d12m43s", frame=Galactic) # Units from string
>>> c = SkyCoord(frame="galactic", l="1h12m43.2s", b="+1d12m43s")
>>> ra = Longitude([1, 2, 3], unit=u.deg) # Could also use Angle
>>> dec = np.array([4.5, 5.2, 6.3]) * u.deg # Astropy Quantity
>>> c = SkyCoord(ra, dec, frame='icrs')
>>> c = SkyCoord(frame=ICRS, ra=ra, dec=dec, obstime='2001-01-02T12:34:56')
>>> c = FK4(1 * u.deg, 2 * u.deg) # Uses defaults for obstime, equinox
>>> c = SkyCoord(c, obstime='J2010.11', equinox='B1965') # Override defaults
>>> c = SkyCoord(w=0, u=1, v=2, unit='kpc', frame='galactic',
... representation_type='cartesian')
>>> c = SkyCoord([ICRS(ra=1*u.deg, dec=2*u.deg), ICRS(ra=3*u.deg, dec=4*u.deg)])
Velocity components (proper motions or radial velocities) can also be
provided in a similar manner::
>>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, radial_velocity=10*u.km/u.s)
>>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, pm_ra_cosdec=2*u.mas/u.yr, pm_dec=1*u.mas/u.yr)
As shown, the frame can be a `~astropy.coordinates.BaseCoordinateFrame`
class or the corresponding string alias. The frame classes that are built in
to astropy are `ICRS`, `FK5`, `FK4`, `FK4NoETerms`, and `Galactic`.
The string aliases are simply lower-case versions of the class name, and
allow for creating a `SkyCoord` object and transforming frames without
explicitly importing the frame classes.
Parameters
----------
frame : `~astropy.coordinates.BaseCoordinateFrame` class or string, optional
Type of coordinate frame this `SkyCoord` should represent. Defaults to
to ICRS if not given or given as None.
unit : `~astropy.units.Unit`, string, or tuple of :class:`~astropy.units.Unit` or str, optional
Units for supplied ``LON`` and ``LAT`` values, respectively. If
only one unit is supplied then it applies to both ``LON`` and
``LAT``.
obstime : valid `~astropy.time.Time` initializer, optional
Time(s) of observation.
equinox : valid `~astropy.time.Time` initializer, optional
Coordinate frame equinox.
representation_type : str or Representation class
Specifies the representation, e.g. 'spherical', 'cartesian', or
'cylindrical'. This affects the positional args and other keyword args
which must correspond to the given representation.
copy : bool, optional
If `True` (default), a copy of any coordinate data is made. This
argument can only be passed in as a keyword argument.
**keyword_args
Other keyword arguments as applicable for user-defined coordinate frames.
Common options include:
ra, dec : valid `~astropy.coordinates.Angle` initializer, optional
RA and Dec for frames where ``ra`` and ``dec`` are keys in the
frame's ``representation_component_names``, including `ICRS`,
`FK5`, `FK4`, and `FK4NoETerms`.
pm_ra_cosdec, pm_dec : `~astropy.units.Quantity`, optional
Proper motion components, in angle per time units.
l, b : valid `~astropy.coordinates.Angle` initializer, optional
Galactic ``l`` and ``b`` for for frames where ``l`` and ``b`` are
keys in the frame's ``representation_component_names``, including
the `Galactic` frame.
pm_l_cosb, pm_b : `~astropy.units.Quantity`, optional
Proper motion components in the `Galactic` frame, in angle per time
units.
x, y, z : float or `~astropy.units.Quantity`, optional
Cartesian coordinates values
u, v, w : float or `~astropy.units.Quantity`, optional
Cartesian coordinates values for the Galactic frame.
radial_velocity : `~astropy.units.Quantity`, optional
The component of the velocity along the line-of-sight (i.e., the
radial direction), in velocity units.
"""
# Declare that SkyCoord can be used as a Table column by defining the
# info property.
info = SkyCoordInfo()
def __init__(self, *args, copy=True, **kwargs):
# these are frame attributes set on this SkyCoord but *not* a part of
# the frame object this SkyCoord contains
self._extra_frameattr_names = set()
# If all that is passed in is a frame instance that already has data,
# we should bypass all of the parsing and logic below. This is here
# to make this the fastest way to create a SkyCoord instance. Many of
# the classmethods implemented for performance enhancements will use
# this as the initialization path
if (len(args) == 1 and len(kwargs) == 0
and isinstance(args[0], (BaseCoordinateFrame, SkyCoord))):
coords = args[0]
if isinstance(coords, SkyCoord):
self._extra_frameattr_names = coords._extra_frameattr_names
self.info = coords.info
# Copy over any extra frame attributes
for attr_name in self._extra_frameattr_names:
# Setting it will also validate it.
setattr(self, attr_name, getattr(coords, attr_name))
coords = coords.frame
if not coords.has_data:
raise ValueError('Cannot initialize from a coordinate frame '
'instance without coordinate data')
if copy:
self._sky_coord_frame = coords.copy()
else:
self._sky_coord_frame = coords
else:
# Get the frame instance without coordinate data but with all frame
# attributes set - these could either have been passed in with the
# frame as an instance, or passed in as kwargs here
frame_cls, frame_kwargs = _get_frame_without_data(args, kwargs)
# Parse the args and kwargs to assemble a sanitized and validated
# kwargs dict for initializing attributes for this object and for
# creating the internal self._sky_coord_frame object
args = list(args) # Make it mutable
skycoord_kwargs, components, info = _parse_coordinate_data(
frame_cls(**frame_kwargs), args, kwargs)
# In the above two parsing functions, these kwargs were identified
# as valid frame attributes for *some* frame, but not the frame that
# this SkyCoord will have. We keep these attributes as special
# skycoord frame attributes:
for attr in skycoord_kwargs:
# Setting it will also validate it.
setattr(self, attr, skycoord_kwargs[attr])
if info is not None:
self.info = info
# Finally make the internal coordinate object.
frame_kwargs.update(components)
self._sky_coord_frame = frame_cls(copy=copy, **frame_kwargs)
if not self._sky_coord_frame.has_data:
raise ValueError('Cannot create a SkyCoord without data')
@property
def frame(self):
return self._sky_coord_frame
@property
def representation_type(self):
return self.frame.representation_type
@representation_type.setter
def representation_type(self, value):
self.frame.representation_type = value
# TODO: remove these in future
@property
def representation(self):
return self.frame.representation
@representation.setter
def representation(self, value):
self.frame.representation = value
@property
def shape(self):
return self.frame.shape
def _apply(self, method, *args, **kwargs):
"""Create a new instance, applying a method to the underlying data.
In typical usage, the method is any of the shape-changing methods for
`~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those
picking particular elements (``__getitem__``, ``take``, etc.), which
are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be
applied to the underlying arrays in the representation (e.g., ``x``,
``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`),
as well as to any frame attributes that have a shape, with the results
used to create a new instance.
Internally, it is also used to apply functions to the above parts
(in particular, `~numpy.broadcast_to`).
Parameters
----------
method : str or callable
If str, it is the name of a method that is applied to the internal
``components``. If callable, the function is applied.
args : tuple
Any positional arguments for ``method``.
kwargs : dict
Any keyword arguments for ``method``.
"""
def apply_method(value):
if isinstance(value, ShapedLikeNDArray):
return value._apply(method, *args, **kwargs)
else:
if callable(method):
return method(value, *args, **kwargs)
else:
return getattr(value, method)(*args, **kwargs)
# create a new but empty instance, and copy over stuff
new = super().__new__(self.__class__)
new._sky_coord_frame = self._sky_coord_frame._apply(method,
*args, **kwargs)
new._extra_frameattr_names = self._extra_frameattr_names.copy()
for attr in self._extra_frameattr_names:
value = getattr(self, attr)
if getattr(value, 'size', 1) > 1:
value = apply_method(value)
elif method == 'copy' or method == 'flatten':
# flatten should copy also for a single element array, but
# we cannot use it directly for array scalars, since it
# always returns a one-dimensional array. So, just copy.
value = copy.copy(value)
setattr(new, '_' + attr, value)
# Copy other 'info' attr only if it has actually been defined.
# See PR #3898 for further explanation and justification, along
# with Quantity.__array_finalize__
if 'info' in self.__dict__:
new.info = self.info
return new
def transform_to(self, frame, merge_attributes=True):
"""Transform this coordinate to a new frame.
The precise frame transformed to depends on ``merge_attributes``.
If `False`, the destination frame is used exactly as passed in.
But this is often not quite what one wants. E.g., suppose one wants to
transform an ICRS coordinate that has an obstime attribute to FK4; in
this case, one likely would want to use this information. Thus, the
default for ``merge_attributes`` is `True`, in which the precedence is
as follows: (1) explicitly set (i.e., non-default) values in the
destination frame; (2) explicitly set values in the source; (3) default
value in the destination frame.
Note that in either case, any explicitly set attributes on the source
`SkyCoord` that are not part of the destination frame's definition are
kept (stored on the resulting `SkyCoord`), and thus one can round-trip
(e.g., from FK4 to ICRS to FK4 without loosing obstime).
Parameters
----------
frame : str, `BaseCoordinateFrame` class or instance, or `SkyCoord` instance
The frame to transform this coordinate into. If a `SkyCoord`, the
underlying frame is extracted, and all other information ignored.
merge_attributes : bool, optional
Whether the default attributes in the destination frame are allowed
to be overridden by explicitly set attributes in the source
(see note above; default: `True`).
Returns
-------
coord : `SkyCoord`
A new object with this coordinate represented in the `frame` frame.
Raises
------
ValueError
If there is no possible transformation route.
"""
from astropy.coordinates.errors import ConvertError
frame_kwargs = {}
# Frame name (string) or frame class? Coerce into an instance.
try:
frame = _get_frame_class(frame)()
except Exception:
pass
if isinstance(frame, SkyCoord):
frame = frame.frame # Change to underlying coord frame instance
if isinstance(frame, BaseCoordinateFrame):
new_frame_cls = frame.__class__
# Get frame attributes, allowing defaults to be overridden by
# explicitly set attributes of the source if ``merge_attributes``.
for attr in frame_transform_graph.frame_attributes:
self_val = getattr(self, attr, None)
frame_val = getattr(frame, attr, None)
if (frame_val is not None
and not (merge_attributes
and frame.is_frame_attr_default(attr))):
frame_kwargs[attr] = frame_val
elif (self_val is not None
and not self.is_frame_attr_default(attr)):
frame_kwargs[attr] = self_val
elif frame_val is not None:
frame_kwargs[attr] = frame_val
else:
raise ValueError('Transform `frame` must be a frame name, class, or instance')
# Get the composite transform to the new frame
trans = frame_transform_graph.get_transform(self.frame.__class__, new_frame_cls)
if trans is None:
raise ConvertError('Cannot transform from {} to {}'
.format(self.frame.__class__, new_frame_cls))
# Make a generic frame which will accept all the frame kwargs that
# are provided and allow for transforming through intermediate frames
# which may require one or more of those kwargs.
generic_frame = GenericFrame(frame_kwargs)
# Do the transformation, returning a coordinate frame of the desired
# final type (not generic).
new_coord = trans(self.frame, generic_frame)
# Finally make the new SkyCoord object from the `new_coord` and
# remaining frame_kwargs that are not frame_attributes in `new_coord`.
for attr in (set(new_coord.get_frame_attr_names()) &
set(frame_kwargs.keys())):
frame_kwargs.pop(attr)
return self.__class__(new_coord, **frame_kwargs)
def apply_space_motion(self, new_obstime=None, dt=None):
"""
Compute the position of the source represented by this coordinate object
to a new time using the velocities stored in this object and assuming
linear space motion (including relativistic corrections). This is
sometimes referred to as an "epoch transformation."
The initial time before the evolution is taken from the ``obstime``
attribute of this coordinate. Note that this method currently does not
support evolving coordinates where the *frame* has an ``obstime`` frame
attribute, so the ``obstime`` is only used for storing the before and
after times, not actually as an attribute of the frame. Alternatively,
if ``dt`` is given, an ``obstime`` need not be provided at all.
Parameters
----------
new_obstime : `~astropy.time.Time`, optional
The time at which to evolve the position to. Requires that the
``obstime`` attribute be present on this frame.
dt : `~astropy.units.Quantity`, `~astropy.time.TimeDelta`, optional
An amount of time to evolve the position of the source. Cannot be
given at the same time as ``new_obstime``.
Returns
-------
new_coord : `SkyCoord`
A new coordinate object with the evolved location of this coordinate
at the new time. ``obstime`` will be set on this object to the new
time only if ``self`` also has ``obstime``.
"""
if (new_obstime is None and dt is None or
new_obstime is not None and dt is not None):
raise ValueError("You must specify one of `new_obstime` or `dt`, "
"but not both.")
# Validate that we have velocity info
if 's' not in self.frame.data.differentials:
raise ValueError('SkyCoord requires velocity data to evolve the '
'position.')
if 'obstime' in self.frame.frame_attributes:
raise NotImplementedError("Updating the coordinates in a frame "
"with explicit time dependence is "
"currently not supported. If you would "
"like this functionality, please open an "
"issue on github:\n"
"https://github.com/astropy/astropy")
if new_obstime is not None and self.obstime is None:
# If no obstime is already on this object, raise an error if a new
# obstime is passed: we need to know the time / epoch at which the
# the position / velocity were measured initially
raise ValueError('This object has no associated `obstime`. '
'apply_space_motion() must receive a time '
'difference, `dt`, and not a new obstime.')
# Compute t1 and t2, the times used in the starpm call, which *only*
# uses them to compute a delta-time
t1 = self.obstime
if dt is None:
# self.obstime is not None and new_obstime is not None b/c of above
# checks
t2 = new_obstime
else:
# new_obstime is definitely None b/c of the above checks
if t1 is None:
# MAGIC NUMBER: if the current SkyCoord object has no obstime,
# assume J2000 to do the dt offset. This is not actually used
# for anything except a delta-t in starpm, so it's OK that it's
# not necessarily the "real" obstime
t1 = Time('J2000')
new_obstime = None # we don't actually know the inital obstime
t2 = t1 + dt
else:
t2 = t1 + dt
new_obstime = t2
# starpm wants tdb time
t1 = t1.tdb
t2 = t2.tdb
# proper motion in RA should not include the cos(dec) term, see the
# erfa function eraStarpv, comment (4). So we convert to the regular
# spherical differentials.
icrsrep = self.icrs.represent_as(SphericalRepresentation, SphericalDifferential)
icrsvel = icrsrep.differentials['s']
try:
plx = icrsrep.distance.to_value(u.arcsecond, u.parallax())
except u.UnitConversionError: # No distance: set to 0 by convention
plx = 0.
try:
rv = icrsvel.d_distance.to_value(u.km/u.s)
except u.UnitConversionError: # No RV
rv = 0.
starpm = erfa.starpm(icrsrep.lon.radian, icrsrep.lat.radian,
icrsvel.d_lon.to_value(u.radian/u.yr),
icrsvel.d_lat.to_value(u.radian/u.yr),
plx, rv, t1.jd1, t1.jd2, t2.jd1, t2.jd2)
icrs2 = ICRS(ra=u.Quantity(starpm[0], u.radian, copy=False),
dec=u.Quantity(starpm[1], u.radian, copy=False),
pm_ra=u.Quantity(starpm[2], u.radian/u.yr, copy=False),
pm_dec=u.Quantity(starpm[3], u.radian/u.yr, copy=False),
distance=Distance(parallax=starpm[4] * u.arcsec, copy=False),
radial_velocity=u.Quantity(starpm[5], u.km/u.s, copy=False),
differential_type=SphericalDifferential)
# Update the obstime of the returned SkyCoord, and need to carry along
# the frame attributes
frattrs = {attrnm: getattr(self, attrnm)
for attrnm in self._extra_frameattr_names}
frattrs['obstime'] = new_obstime
return self.__class__(icrs2, **frattrs).transform_to(self.frame)
def _is_name(self, string):
"""
Returns whether a string is one of the aliases for the frame.
"""
return (self.frame.name == string or
(isinstance(self.frame.name, list) and string in self.frame.name))
def __getattr__(self, attr):
"""
Overrides getattr to return coordinates that this can be transformed
to, based on the alias attr in the master transform graph.
"""
if '_sky_coord_frame' in self.__dict__:
if self._is_name(attr):
return self # Should this be a deepcopy of self?
# Anything in the set of all possible frame_attr_names is handled
# here. If the attr is relevant for the current frame then delegate
# to self.frame otherwise get it from self._<attr>.
if attr in frame_transform_graph.frame_attributes:
if attr in self.frame.get_frame_attr_names():
return getattr(self.frame, attr)
else:
return getattr(self, '_' + attr, None)
# Some attributes might not fall in the above category but still
# are available through self._sky_coord_frame.
if not attr.startswith('_') and hasattr(self._sky_coord_frame, attr):
return getattr(self._sky_coord_frame, attr)
# Try to interpret as a new frame for transforming.
frame_cls = frame_transform_graph.lookup_name(attr)
if frame_cls is not None and self.frame.is_transformable_to(frame_cls):
return self.transform_to(attr)
# Fail
raise AttributeError("'{}' object has no attribute '{}'"
.format(self.__class__.__name__, attr))
def __setattr__(self, attr, val):
# This is to make anything available through __getattr__ immutable
if '_sky_coord_frame' in self.__dict__:
if self._is_name(attr):
raise AttributeError(f"'{attr}' is immutable")
if not attr.startswith('_') and hasattr(self._sky_coord_frame, attr):
setattr(self._sky_coord_frame, attr, val)
return
frame_cls = frame_transform_graph.lookup_name(attr)
if frame_cls is not None and self.frame.is_transformable_to(frame_cls):
raise AttributeError(f"'{attr}' is immutable")
if attr in frame_transform_graph.frame_attributes:
# All possible frame attributes can be set, but only via a private
# variable. See __getattr__ above.
super().__setattr__('_' + attr, val)
# Validate it
frame_transform_graph.frame_attributes[attr].__get__(self)
# And add to set of extra attributes
self._extra_frameattr_names |= {attr}
else:
# Otherwise, do the standard Python attribute setting
super().__setattr__(attr, val)
def __delattr__(self, attr):
# mirror __setattr__ above
if '_sky_coord_frame' in self.__dict__:
if self._is_name(attr):
raise AttributeError(f"'{attr}' is immutable")
if not attr.startswith('_') and hasattr(self._sky_coord_frame,
attr):
delattr(self._sky_coord_frame, attr)
return
frame_cls = frame_transform_graph.lookup_name(attr)
if frame_cls is not None and self.frame.is_transformable_to(frame_cls):
raise AttributeError(f"'{attr}' is immutable")
if attr in frame_transform_graph.frame_attributes:
# All possible frame attributes can be deleted, but need to remove
# the corresponding private variable. See __getattr__ above.
super().__delattr__('_' + attr)
# Also remove it from the set of extra attributes
self._extra_frameattr_names -= {attr}
else:
# Otherwise, do the standard Python attribute setting
super().__delattr__(attr)
@override__dir__
def __dir__(self):
"""
Override the builtin `dir` behavior to include:
- Transforms available by aliases
- Attribute / methods of the underlying self.frame object
"""
# determine the aliases that this can be transformed to.
dir_values = set()
for name in frame_transform_graph.get_names():
frame_cls = frame_transform_graph.lookup_name(name)
if self.frame.is_transformable_to(frame_cls):
dir_values.add(name)
# Add public attributes of self.frame
dir_values.update(set(attr for attr in dir(self.frame) if not attr.startswith('_')))
# Add all possible frame attributes
dir_values.update(frame_transform_graph.frame_attributes.keys())
return dir_values
def __repr__(self):
clsnm = self.__class__.__name__
coonm = self.frame.__class__.__name__
frameattrs = self.frame._frame_attrs_repr()
if frameattrs:
frameattrs = ': ' + frameattrs
data = self.frame._data_repr()
if data:
data = ': ' + data
return '<{clsnm} ({coonm}{frameattrs}){data}>'.format(**locals())
def to_string(self, style='decimal', **kwargs):
"""
A string representation of the coordinates.
The default styles definitions are::
'decimal': 'lat': {'decimal': True, 'unit': "deg"}
'lon': {'decimal': True, 'unit': "deg"}
'dms': 'lat': {'unit': "deg"}
'lon': {'unit': "deg"}
'hmsdms': 'lat': {'alwayssign': True, 'pad': True, 'unit': "deg"}
'lon': {'pad': True, 'unit': "hour"}
See :meth:`~astropy.coordinates.Angle.to_string` for details and
keyword arguments (the two angles forming the coordinates are are
both :class:`~astropy.coordinates.Angle` instances). Keyword
arguments have precedence over the style defaults and are passed
to :meth:`~astropy.coordinates.Angle.to_string`.
Parameters
----------
style : {'hmsdms', 'dms', 'decimal'}
The formatting specification to use. These encode the three most
common ways to represent coordinates. The default is `decimal`.
kwargs
Keyword args passed to :meth:`~astropy.coordinates.Angle.to_string`.
"""
sph_coord = self.frame.represent_as(SphericalRepresentation)
styles = {'hmsdms': {'lonargs': {'unit': u.hour, 'pad': True},
'latargs': {'unit': u.degree, 'pad': True, 'alwayssign': True}},
'dms': {'lonargs': {'unit': u.degree},
'latargs': {'unit': u.degree}},
'decimal': {'lonargs': {'unit': u.degree, 'decimal': True},
'latargs': {'unit': u.degree, 'decimal': True}}
}
lonargs = {}
latargs = {}
if style in styles:
lonargs.update(styles[style]['lonargs'])
latargs.update(styles[style]['latargs'])
else:
raise ValueError('Invalid style. Valid options are: {}'.format(",".join(styles)))
lonargs.update(kwargs)
latargs.update(kwargs)
if np.isscalar(sph_coord.lon.value):
coord_string = (sph_coord.lon.to_string(**lonargs) +
" " + sph_coord.lat.to_string(**latargs))
else:
coord_string = []
for lonangle, latangle in zip(sph_coord.lon.ravel(), sph_coord.lat.ravel()):
coord_string += [(lonangle.to_string(**lonargs) +
" " + latangle.to_string(**latargs))]
if len(sph_coord.shape) > 1:
coord_string = np.array(coord_string).reshape(sph_coord.shape)
return coord_string
def is_equivalent_frame(self, other):
"""
Checks if this object's frame as the same as that of the ``other``
object.
To be the same frame, two objects must be the same frame class and have
the same frame attributes. For two `SkyCoord` objects, *all* of the
frame attributes have to match, not just those relevant for the object's
frame.
Parameters
----------
other : SkyCoord or BaseCoordinateFrame
The other object to check.
Returns
-------
isequiv : bool
True if the frames are the same, False if not.
Raises
------
TypeError
If ``other`` isn't a `SkyCoord` or a `BaseCoordinateFrame` or subclass.
"""
if isinstance(other, BaseCoordinateFrame):
return self.frame.is_equivalent_frame(other)
elif isinstance(other, SkyCoord):
if other.frame.name != self.frame.name:
return False
for fattrnm in frame_transform_graph.frame_attributes:
if np.any(getattr(self, fattrnm) != getattr(other, fattrnm)):
return False
return True
else:
# not a BaseCoordinateFrame nor a SkyCoord object
raise TypeError("Tried to do is_equivalent_frame on something that "
"isn't frame-like")
# High-level convenience methods
def separation(self, other):
"""
Computes on-sky separation between this coordinate and another.
.. note::
If the ``other`` coordinate object is in a different frame, it is
first transformed to the frame of this object. This can lead to
unintuitive behavior if not accounted for. Particularly of note is
that ``self.separation(other)`` and ``other.separation(self)`` may
not give the same answer in this case.
For more on how to use this (and related) functionality, see the
examples in :doc:`/coordinates/matchsep`.
Parameters
----------
other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`
The coordinate to get the separation to.
Returns
-------
sep : `~astropy.coordinates.Angle`
The on-sky separation between this and the ``other`` coordinate.
Notes
-----
The separation is calculated using the Vincenty formula, which
is stable at all locations, including poles and antipodes [1]_.
.. [1] https://en.wikipedia.org/wiki/Great-circle_distance
"""
from . import Angle
from .angle_utilities import angular_separation
if not self.is_equivalent_frame(other):
try:
other = other.transform_to(self, merge_attributes=False)
except TypeError:
raise TypeError('Can only get separation to another SkyCoord '
'or a coordinate frame with data')
lon1 = self.spherical.lon
lat1 = self.spherical.lat
lon2 = other.spherical.lon
lat2 = other.spherical.lat
# Get the separation as a Quantity, convert to Angle in degrees
sep = angular_separation(lon1, lat1, lon2, lat2)
return Angle(sep, unit=u.degree)
def separation_3d(self, other):
"""
Computes three dimensional separation between this coordinate
and another.
For more on how to use this (and related) functionality, see the
examples in :doc:`/coordinates/matchsep`.
Parameters
----------
other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`
The coordinate to get the separation to.
Returns
-------
sep : `~astropy.coordinates.Distance`
The real-space distance between these two coordinates.
Raises
------
ValueError
If this or the other coordinate do not have distances.
"""
if not self.is_equivalent_frame(other):
try:
other = other.transform_to(self, merge_attributes=False)
except TypeError:
raise TypeError('Can only get separation to another SkyCoord '
'or a coordinate frame with data')
if issubclass(self.data.__class__, UnitSphericalRepresentation):
raise ValueError('This object does not have a distance; cannot '
'compute 3d separation.')
if issubclass(other.data.__class__, UnitSphericalRepresentation):
raise ValueError('The other object does not have a distance; '
'cannot compute 3d separation.')
c1 = self.cartesian.without_differentials()
c2 = other.cartesian.without_differentials()
return Distance((c1 - c2).norm())
def spherical_offsets_to(self, tocoord):
r"""
Computes angular offsets to go *from* this coordinate *to* another.
Parameters
----------
tocoord : `~astropy.coordinates.BaseCoordinateFrame`
The coordinate to find the offset to.
Returns
-------
lon_offset : `~astropy.coordinates.Angle`
The angular offset in the longitude direction (i.e., RA for
equatorial coordinates).
lat_offset : `~astropy.coordinates.Angle`
The angular offset in the latitude direction (i.e., Dec for
equatorial coordinates).
Raises
------
ValueError
If the ``tocoord`` is not in the same frame as this one. This is
different from the behavior of the `separation`/`separation_3d`
methods because the offset components depend critically on the
specific choice of frame.
Notes
-----
This uses the sky offset frame machinery, and hence will produce a new
sky offset frame if one does not already exist for this object's frame
class.
See Also
--------
separation : for the *total* angular offset (not broken out into components).
position_angle : for the direction of the offset.
"""
if not self.is_equivalent_frame(tocoord):
raise ValueError('Tried to use spherical_offsets_to with two non-matching frames!')
aframe = self.skyoffset_frame()
acoord = tocoord.transform_to(aframe)
dlon = acoord.spherical.lon.view(Angle)
dlat = acoord.spherical.lat.view(Angle)
return dlon, dlat
def directional_offset_by(self, position_angle, separation):
"""
Computes coordinates at the given offset from this coordinate.
Parameters
----------
position_angle : `~astropy.coordinates.Angle`
position_angle of offset
separation : `~astropy.coordinates.Angle`
offset angular separation
Returns
-------
newpoints : `~astropy.coordinates.SkyCoord`
The coordinates for the location that corresponds to offsetting by
the given `position_angle` and `separation`.
Notes
-----
Returned SkyCoord frame retains only the frame attributes that are for
the resulting frame type. (e.g. if the input frame is
`~astropy.coordinates.ICRS`, an ``equinox`` value will be retained, but
an ``obstime`` will not.)
For a more complete set of transform offsets, use `~astropy.wcs.WCS`.
`~astropy.coordinates.SkyCoord.skyoffset_frame()` can also be used to
create a spherical frame with (lat=0, lon=0) at a reference point,
approximating an xy cartesian system for small offsets. This method
is distinct in that it is accurate on the sphere.
See Also
--------
position_angle : inverse operation for the ``position_angle`` component
separation : inverse operation for the ``separation`` component
"""
from . import angle_utilities
slat = self.represent_as(UnitSphericalRepresentation).lat
slon = self.represent_as(UnitSphericalRepresentation).lon
newlon, newlat = angle_utilities.offset_by(
lon=slon, lat=slat,
posang=position_angle, distance=separation)
return SkyCoord(newlon, newlat, frame=self.frame)
def match_to_catalog_sky(self, catalogcoord, nthneighbor=1):
"""
Finds the nearest on-sky matches of this coordinate in a set of
catalog coordinates.
For more on how to use this (and related) functionality, see the
examples in :doc:`/coordinates/matchsep`.
Parameters
----------
catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`
The base catalog in which to search for matches. Typically this
will be a coordinate object that is an array (i.e.,
``catalogcoord.isscalar == False``)
nthneighbor : int, optional
Which closest neighbor to search for. Typically ``1`` is
desired here, as that is correct for matching one set of
coordinates to another. The next likely use case is ``2``,
for matching a coordinate catalog against *itself* (``1``
is inappropriate because each point will find itself as the
closest match).
Returns
-------
idx : integer array
Indices into ``catalogcoord`` to get the matched points for
each of this object's coordinates. Shape matches this
object.
sep2d : `~astropy.coordinates.Angle`
The on-sky separation between the closest match for each
element in this object in ``catalogcoord``. Shape matches
this object.
dist3d : `~astropy.units.Quantity`
The 3D distance between the closest match for each element
in this object in ``catalogcoord``. Shape matches this
object. Unless both this and ``catalogcoord`` have associated
distances, this quantity assumes that all sources are at a
distance of 1 (dimensionless).
Notes
-----
This method requires `SciPy <https://www.scipy.org/>`_ to be
installed or it will fail.
See Also
--------
astropy.coordinates.match_coordinates_sky
SkyCoord.match_to_catalog_3d
"""
from .matching import match_coordinates_sky
if (isinstance(catalogcoord, (SkyCoord, BaseCoordinateFrame))
and catalogcoord.has_data):
self_in_catalog_frame = self.transform_to(catalogcoord)
else:
raise TypeError('Can only get separation to another SkyCoord or a '
'coordinate frame with data')
res = match_coordinates_sky(self_in_catalog_frame, catalogcoord,
nthneighbor=nthneighbor,
storekdtree='_kdtree_sky')
return res
def match_to_catalog_3d(self, catalogcoord, nthneighbor=1):
"""
Finds the nearest 3-dimensional matches of this coordinate to a set
of catalog coordinates.
This finds the 3-dimensional closest neighbor, which is only different
from the on-sky distance if ``distance`` is set in this object or the
``catalogcoord`` object.
For more on how to use this (and related) functionality, see the
examples in :doc:`/coordinates/matchsep`.
Parameters
----------
catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`
The base catalog in which to search for matches. Typically this
will be a coordinate object that is an array (i.e.,
``catalogcoord.isscalar == False``)
nthneighbor : int, optional
Which closest neighbor to search for. Typically ``1`` is
desired here, as that is correct for matching one set of
coordinates to another. The next likely use case is
``2``, for matching a coordinate catalog against *itself*
(``1`` is inappropriate because each point will find
itself as the closest match).
Returns
-------
idx : integer array
Indices into ``catalogcoord`` to get the matched points for
each of this object's coordinates. Shape matches this
object.
sep2d : `~astropy.coordinates.Angle`
The on-sky separation between the closest match for each
element in this object in ``catalogcoord``. Shape matches
this object.
dist3d : `~astropy.units.Quantity`
The 3D distance between the closest match for each element
in this object in ``catalogcoord``. Shape matches this
object.
Notes
-----
This method requires `SciPy <https://www.scipy.org/>`_ to be
installed or it will fail.
See Also
--------
astropy.coordinates.match_coordinates_3d
SkyCoord.match_to_catalog_sky
"""
from .matching import match_coordinates_3d
if (isinstance(catalogcoord, (SkyCoord, BaseCoordinateFrame))
and catalogcoord.has_data):
self_in_catalog_frame = self.transform_to(catalogcoord)
else:
raise TypeError('Can only get separation to another SkyCoord or a '
'coordinate frame with data')
res = match_coordinates_3d(self_in_catalog_frame, catalogcoord,
nthneighbor=nthneighbor,
storekdtree='_kdtree_3d')
return res
def search_around_sky(self, searcharoundcoords, seplimit):
"""
Searches for all coordinates in this object around a supplied set of
points within a given on-sky separation.
This is intended for use on `~astropy.coordinates.SkyCoord` objects
with coordinate arrays, rather than a scalar coordinate. For a scalar
coordinate, it is better to use
`~astropy.coordinates.SkyCoord.separation`.
For more on how to use this (and related) functionality, see the
examples in :doc:`/coordinates/matchsep`.
Parameters
----------
searcharoundcoords : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`
The coordinates to search around to try to find matching points in
this `SkyCoord`. This should be an object with array coordinates,
not a scalar coordinate object.
seplimit : `~astropy.units.Quantity` with angle units
The on-sky separation to search within.
Returns
-------
idxsearcharound : integer array
Indices into ``searcharoundcoords`` that match the
corresponding elements of ``idxself``. Shape matches
``idxself``.
idxself : integer array
Indices into ``self`` that match the
corresponding elements of ``idxsearcharound``. Shape matches
``idxsearcharound``.
sep2d : `~astropy.coordinates.Angle`
The on-sky separation between the coordinates. Shape matches
``idxsearcharound`` and ``idxself``.
dist3d : `~astropy.units.Quantity`
The 3D distance between the coordinates. Shape matches
``idxsearcharound`` and ``idxself``.
Notes
-----
This method requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be
installed or it will fail.
In the current implementation, the return values are always sorted in
the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is
in ascending order). This is considered an implementation detail,
though, so it could change in a future release.
See Also
--------
astropy.coordinates.search_around_sky
SkyCoord.search_around_3d
"""
from .matching import search_around_sky
return search_around_sky(searcharoundcoords, self, seplimit,
storekdtree='_kdtree_sky')
def search_around_3d(self, searcharoundcoords, distlimit):
"""
Searches for all coordinates in this object around a supplied set of
points within a given 3D radius.
This is intended for use on `~astropy.coordinates.SkyCoord` objects
with coordinate arrays, rather than a scalar coordinate. For a scalar
coordinate, it is better to use
`~astropy.coordinates.SkyCoord.separation_3d`.
For more on how to use this (and related) functionality, see the
examples in :doc:`/coordinates/matchsep`.
Parameters
----------
searcharoundcoords : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`
The coordinates to search around to try to find matching points in
this `SkyCoord`. This should be an object with array coordinates,
not a scalar coordinate object.
distlimit : `~astropy.units.Quantity` with distance units
The physical radius to search within.
Returns
-------
idxsearcharound : integer array
Indices into ``searcharoundcoords`` that match the
corresponding elements of ``idxself``. Shape matches
``idxself``.
idxself : integer array
Indices into ``self`` that match the
corresponding elements of ``idxsearcharound``. Shape matches
``idxsearcharound``.
sep2d : `~astropy.coordinates.Angle`
The on-sky separation between the coordinates. Shape matches
``idxsearcharound`` and ``idxself``.
dist3d : `~astropy.units.Quantity`
The 3D distance between the coordinates. Shape matches
``idxsearcharound`` and ``idxself``.
Notes
-----
This method requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be
installed or it will fail.
In the current implementation, the return values are always sorted in
the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is
in ascending order). This is considered an implementation detail,
though, so it could change in a future release.
See Also
--------
astropy.coordinates.search_around_3d
SkyCoord.search_around_sky
"""
from .matching import search_around_3d
return search_around_3d(searcharoundcoords, self, distlimit,
storekdtree='_kdtree_3d')
def position_angle(self, other):
"""
Computes the on-sky position angle (East of North) between this
`SkyCoord` and another.
Parameters
----------
other : `SkyCoord`
The other coordinate to compute the position angle to. It is
treated as the "head" of the vector of the position angle.
Returns
-------
pa : `~astropy.coordinates.Angle`
The (positive) position angle of the vector pointing from ``self``
to ``other``. If either ``self`` or ``other`` contain arrays, this
will be an array following the appropriate `numpy` broadcasting
rules.
Examples
--------
>>> c1 = SkyCoord(0*u.deg, 0*u.deg)
>>> c2 = SkyCoord(1*u.deg, 0*u.deg)
>>> c1.position_angle(c2).degree
90.0
>>> c3 = SkyCoord(1*u.deg, 1*u.deg)
>>> c1.position_angle(c3).degree # doctest: +FLOAT_CMP
44.995636455344844
"""
from . import angle_utilities
if not self.is_equivalent_frame(other):
try:
other = other.transform_to(self, merge_attributes=False)
except TypeError:
raise TypeError('Can only get position_angle to another '
'SkyCoord or a coordinate frame with data')
slat = self.represent_as(UnitSphericalRepresentation).lat
slon = self.represent_as(UnitSphericalRepresentation).lon
olat = other.represent_as(UnitSphericalRepresentation).lat
olon = other.represent_as(UnitSphericalRepresentation).lon
return angle_utilities.position_angle(slon, slat, olon, olat)
def skyoffset_frame(self, rotation=None):
"""
Returns the sky offset frame with this `SkyCoord` at the origin.
Returns
-------
astrframe : `~astropy.coordinates.SkyOffsetFrame`
A sky offset frame of the same type as this `SkyCoord` (e.g., if
this object has an ICRS coordinate, the resulting frame is
SkyOffsetICRS, with the origin set to this object)
rotation : `~astropy.coordinates.Angle` or `~astropy.units.Quantity` with angle units
The final rotation of the frame about the ``origin``. The sign of
the rotation is the left-hand rule. That is, an object at a
particular position angle in the un-rotated system will be sent to
the positive latitude (z) direction in the final frame.
"""
return SkyOffsetFrame(origin=self, rotation=rotation)
def get_constellation(self, short_name=False, constellation_list='iau'):
"""
Determines the constellation(s) of the coordinates this `SkyCoord`
contains.
Parameters
----------
short_name : bool
If True, the returned names are the IAU-sanctioned abbreviated
names. Otherwise, full names for the constellations are used.
constellation_list : str
The set of constellations to use. Currently only ``'iau'`` is
supported, meaning the 88 "modern" constellations endorsed by the IAU.
Returns
-------
constellation : str or string array
If this is a scalar coordinate, returns the name of the
constellation. If it is an array `SkyCoord`, it returns an array of
names.
Notes
-----
To determine which constellation a point on the sky is in, this first
precesses to B1875, and then uses the Delporte boundaries of the 88
modern constellations, as tabulated by
`Roman 1987 <http://cdsarc.u-strasbg.fr/viz-bin/Cat?VI/42>`_.
See Also
--------
astropy.coordinates.get_constellation
"""
from .funcs import get_constellation
# because of issue #7028, the conversion to a PrecessedGeocentric
# system fails in some cases. Work around is to drop the velocities.
# they are not needed here since only position infromation is used
extra_frameattrs = {nm: getattr(self, nm)
for nm in self._extra_frameattr_names}
novel = SkyCoord(self.realize_frame(self.data.without_differentials()),
**extra_frameattrs)
return get_constellation(novel, short_name, constellation_list)
# the simpler version below can be used when gh-issue #7028 is resolved
# return get_constellation(self, short_name, constellation_list)
# WCS pixel to/from sky conversions
def to_pixel(self, wcs, origin=0, mode='all'):
"""
Convert this coordinate to pixel coordinates using a `~astropy.wcs.WCS`
object.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The WCS to use for convert
origin : int
Whether to return 0 or 1-based pixel coordinates.
mode : 'all' or 'wcs'
Whether to do the transformation including distortions (``'all'``) or
only including only the core WCS transformation (``'wcs'``).
Returns
-------
xp, yp : `numpy.ndarray`
The pixel coordinates
See Also
--------
astropy.wcs.utils.skycoord_to_pixel : the implementation of this method
"""
return skycoord_to_pixel(self, wcs=wcs, origin=origin, mode=mode)
@classmethod
def from_pixel(cls, xp, yp, wcs, origin=0, mode='all'):
"""
Create a new `SkyCoord` from pixel coordinates using an
`~astropy.wcs.WCS` object.
Parameters
----------
xp, yp : float or `numpy.ndarray`
The coordinates to convert.
wcs : `~astropy.wcs.WCS`
The WCS to use for convert
origin : int
Whether to return 0 or 1-based pixel coordinates.
mode : 'all' or 'wcs'
Whether to do the transformation including distortions (``'all'``) or
only including only the core WCS transformation (``'wcs'``).
Returns
-------
coord : an instance of this class
A new object with sky coordinates corresponding to the input ``xp``
and ``yp``.
See Also
--------
to_pixel : to do the inverse operation
astropy.wcs.utils.pixel_to_skycoord : the implementation of this method
"""
return pixel_to_skycoord(xp, yp, wcs=wcs, origin=origin, mode=mode, cls=cls)
def contained_by(self, wcs, image=None, **kwargs):
"""
Determines if the SkyCoord is contained in the given wcs footprint.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The coordinate to check if it is within the wcs coordinate.
image : array
Optional. The image associated with the wcs object that the cooordinate
is being checked against. If not given the naxis keywords will be used
to determine if the coordinate falls within the wcs footprint.
**kwargs :
Additional arguments to pass to `~astropy.coordinates.SkyCoord.to_pixel`
Returns
-------
response : bool
True means the WCS footprint contains the coordinate, False means it does not.
"""
if image is not None:
ymax, xmax = image.shape
else:
xmax, ymax = wcs._naxis
import warnings
with warnings.catch_warnings():
# Suppress warnings since they just mean we didn't find the coordinate
warnings.simplefilter("ignore")
try:
x, y = self.to_pixel(wcs, **kwargs)
except Exception:
return False
return (x < xmax) & (x > 0) & (y < ymax) & (y > 0)
def radial_velocity_correction(self, kind='barycentric', obstime=None,
location=None):
"""
Compute the correction required to convert a radial velocity at a given
time and place on the Earth's Surface to a barycentric or heliocentric
velocity.
Parameters
----------
kind : str
The kind of velocity correction. Must be 'barycentric' or
'heliocentric'.
obstime : `~astropy.time.Time` or None, optional
The time at which to compute the correction. If `None`, the
``obstime`` frame attribute on the `SkyCoord` will be used.
location : `~astropy.coordinates.EarthLocation` or None, optional
The observer location at which to compute the correction. If
`None`, the ``location`` frame attribute on the passed-in
``obstime`` will be used, and if that is None, the ``location``
frame attribute on the `SkyCoord` will be used.
Raises
------
ValueError
If either ``obstime`` or ``location`` are passed in (not ``None``)
when the frame attribute is already set on this `SkyCoord`.
TypeError
If ``obstime`` or ``location`` aren't provided, either as arguments
or as frame attributes.
Returns
-------
vcorr : `~astropy.units.Quantity` with velocity units
The correction with a positive sign. I.e., *add* this
to an observed radial velocity to get the barycentric (or
heliocentric) velocity. If m/s precision or better is needed,
see the notes below.
Notes
-----
The barycentric correction is calculated to higher precision than the
heliocentric correction and includes additional physics (e.g time dilation).
Use barycentric corrections if m/s precision is required.
The algorithm here is sufficient to perform corrections at the mm/s level, but
care is needed in application. Strictly speaking, the barycentric correction is
multiplicative and should be applied as::
sc = SkyCoord(1*u.deg, 2*u.deg)
vcorr = sc.rv_correction(kind='barycentric', obstime=t, location=loc)
rv = rv + vcorr + rv * vcorr / consts.c
If your target is nearby and/or has finite proper motion you may need to account
for terms arising from this. See Wright & Eastmann (2014) for details.
The default is for this method to use the builtin ephemeris for
computing the sun and earth location. Other ephemerides can be chosen
by setting the `~astropy.coordinates.solar_system_ephemeris` variable,
either directly or via ``with`` statement. For example, to use the JPL
ephemeris, do::
sc = SkyCoord(1*u.deg, 2*u.deg)
with coord.solar_system_ephemeris.set('jpl'):
rv += sc.rv_correction(obstime=t, location=loc)
"""
# has to be here to prevent circular imports
from .solar_system import get_body_barycentric_posvel
# location validation
timeloc = getattr(obstime, 'location', None)
if location is None:
if self.location is not None:
location = self.location
if timeloc is not None:
raise ValueError('`location` cannot be in both the '
'passed-in `obstime` and this `SkyCoord` '
'because it is ambiguous which is meant '
'for the radial_velocity_correction.')
elif timeloc is not None:
location = timeloc
else:
raise TypeError('Must provide a `location` to '
'radial_velocity_correction, either as a '
'SkyCoord frame attribute, as an attribute on '
'the passed in `obstime`, or in the method '
'call.')
elif self.location is not None or timeloc is not None:
raise ValueError('Cannot compute radial velocity correction if '
'`location` argument is passed in and there is '
'also a `location` attribute on this SkyCoord or '
'the passed-in `obstime`.')
# obstime validation
if obstime is None:
obstime = self.obstime
if obstime is None:
raise TypeError('Must provide an `obstime` to '
'radial_velocity_correction, either as a '
'SkyCoord frame attribute or in the method '
'call.')
elif self.obstime is not None:
raise ValueError('Cannot compute radial velocity correction if '
'`obstime` argument is passed in and it is '
'inconsistent with the `obstime` frame '
'attribute on the SkyCoord')
pos_earth, v_earth = get_body_barycentric_posvel('earth', obstime)
if kind == 'barycentric':
v_origin_to_earth = v_earth
elif kind == 'heliocentric':
v_sun = get_body_barycentric_posvel('sun', obstime)[1]
v_origin_to_earth = v_earth - v_sun
else:
raise ValueError("`kind` argument to radial_velocity_correction must "
"be 'barycentric' or 'heliocentric', but got "
"'{}'".format(kind))
gcrs_p, gcrs_v = location.get_gcrs_posvel(obstime)
# transforming to GCRS is not the correct thing to do here, since we don't want to
# include aberration (or light deflection)? Instead, only apply parallax if necessary
if self.data.__class__ is UnitSphericalRepresentation:
targcart = self.icrs.cartesian
else:
# skycoord has distances so apply parallax
obs_icrs_cart = pos_earth + gcrs_p
icrs_cart = self.icrs.cartesian
targcart = icrs_cart - obs_icrs_cart
targcart /= targcart.norm()
if kind == 'barycentric':
beta_obs = (v_origin_to_earth + gcrs_v) / speed_of_light
gamma_obs = 1 / np.sqrt(1 - beta_obs.norm()**2)
gr = location.gravitational_redshift(obstime)
# barycentric redshift according to eq 28 in Wright & Eastmann (2014),
# neglecting Shapiro delay and effects of the star's own motion
zb = gamma_obs * (1 + targcart.dot(beta_obs)) / (1 + gr/speed_of_light) - 1
return zb * speed_of_light
else:
# do a simpler correction ignoring time dilation and gravitational redshift
# this is adequate since Heliocentric corrections shouldn't be used if
# cm/s precision is required.
return targcart.dot(v_origin_to_earth + gcrs_v)
# Table interactions
@classmethod
def guess_from_table(cls, table, **coord_kwargs):
r"""
A convenience method to create and return a new `SkyCoord` from the data
in an astropy Table.
This method matches table columns that start with the case-insensitive
names of the the components of the requested frames, if they are also
followed by a non-alphanumeric character. It will also match columns
that *end* with the component name if a non-alphanumeric character is
*before* it.
For example, the first rule means columns with names like
``'RA[J2000]'`` or ``'ra'`` will be interpreted as ``ra`` attributes for
`~astropy.coordinates.ICRS` frames, but ``'RAJ2000'`` or ``'radius'``
are *not*. Similarly, the second rule applied to the
`~astropy.coordinates.Galactic` frame means that a column named
``'gal_l'`` will be used as the the ``l`` component, but ``gall`` or
``'fill'`` will not.
The definition of alphanumeric here is based on Unicode's definition
of alphanumeric, except without ``_`` (which is normally considered
alphanumeric). So for ASCII, this means the non-alphanumeric characters
are ``<space>_!"#$%&'()*+,-./\:;<=>?@[]^`{|}~``).
Parameters
----------
table : astropy.Table
The table to load data from.
coord_kwargs
Any additional keyword arguments are passed directly to this class's
constructor.
Returns
-------
newsc : same as this class
The new `SkyCoord` (or subclass) object.
"""
_frame_cls, _frame_kwargs = _get_frame_without_data([], coord_kwargs)
frame = _frame_cls(**_frame_kwargs)
coord_kwargs['frame'] = coord_kwargs.get('frame', frame)
comp_kwargs = {}
for comp_name in frame.representation_component_names:
# this matches things like 'ra[...]'' but *not* 'rad'.
# note that the "_" must be in there explicitly, because
# "alphanumeric" usually includes underscores.
starts_with_comp = comp_name + r'(\W|\b|_)'
# this part matches stuff like 'center_ra', but *not*
# 'aura'
ends_with_comp = r'.*(\W|\b|_)' + comp_name + r'\b'
# the final regex ORs together the two patterns
rex = re.compile('(' + starts_with_comp + ')|(' + ends_with_comp + ')',
re.IGNORECASE | re.UNICODE)
for col_name in table.colnames:
if rex.match(col_name):
if comp_name in comp_kwargs:
oldname = comp_kwargs[comp_name].name
msg = ('Found at least two matches for component "{0}"'
': "{1}" and "{2}". Cannot continue with this '
'ambiguity.')
raise ValueError(msg.format(comp_name, oldname, col_name))
comp_kwargs[comp_name] = table[col_name]
for k, v in comp_kwargs.items():
if k in coord_kwargs:
raise ValueError('Found column "{}" in table, but it was '
'already provided as "{}" keyword to '
'guess_from_table function.'.format(v.name, k))
else:
coord_kwargs[k] = v
return cls(**coord_kwargs)
# Name resolve
@classmethod
def from_name(cls, name, frame='icrs', parse=False):
"""
Given a name, query the CDS name resolver to attempt to retrieve
coordinate information for that object. The search database, sesame
url, and query timeout can be set through configuration items in
``astropy.coordinates.name_resolve`` -- see docstring for
`~astropy.coordinates.get_icrs_coordinates` for more
information.
Parameters
----------
name : str
The name of the object to get coordinates for, e.g. ``'M42'``.
frame : str or `BaseCoordinateFrame` class or instance
The frame to transform the object to.
parse: bool
Whether to attempt extracting the coordinates from the name by
parsing with a regex. For objects catalog names that have
J-coordinates embedded in their names eg:
'CRTS SSS100805 J194428-420209', this may be much faster than a
sesame query for the same object name. The coordinates extracted
in this way may differ from the database coordinates by a few
deci-arcseconds, so only use this option if you do not need
sub-arcsecond accuracy for coordinates.
Returns
-------
coord : SkyCoord
Instance of the SkyCoord class.
"""
from .name_resolve import get_icrs_coordinates
icrs_coord = get_icrs_coordinates(name, parse)
icrs_sky_coord = cls(icrs_coord)
if frame in ('icrs', icrs_coord.__class__):
return icrs_sky_coord
else:
return icrs_sky_coord.transform_to(frame)
| 31,157 |
1,405 | <filename>sample4/recompiled_java/sources/org/apache/commons/httpclient/methods/OptionsMethod.java
package org.apache.commons.httpclient.methods;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class OptionsMethod extends HttpMethodBase {
static Class a;
private static final Log c;
private Vector d = new Vector();
static {
Class cls;
if (a == null) {
cls = a("org.apache.commons.httpclient.methods.OptionsMethod");
a = cls;
} else {
cls = a;
}
c = LogFactory.getLog(cls);
}
private static Class a(String x0) {
try {
return Class.forName(x0);
} catch (ClassNotFoundException x1) {
throw new NoClassDefFoundError(x1.getMessage());
}
}
public OptionsMethod() {
}
public OptionsMethod(String uri) {
super(uri);
}
@Override // org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpMethodBase
public String getName() {
return "OPTIONS";
}
public boolean isAllowed(String method) {
checkUsed();
return this.d.contains(method);
}
public Enumeration getAllowedMethods() {
checkUsed();
return this.d.elements();
}
/* access modifiers changed from: protected */
@Override // org.apache.commons.httpclient.HttpMethodBase
public void processResponseHeaders(HttpState state, HttpConnection conn) {
c.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)");
Header allowHeader = getResponseHeader("allow");
if (allowHeader != null) {
StringTokenizer tokenizer = new StringTokenizer(allowHeader.getValue(), ",");
while (tokenizer.hasMoreElements()) {
this.d.addElement(tokenizer.nextToken().trim().toUpperCase());
}
}
}
public boolean needContentLength() {
return false;
}
}
| 919 |
3,215 | import os
import sys
import time
import json
import unittest
import jc.parsers.stat
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
# Set the timezone on POSIX systems. Need to manually set for Windows tests
if not sys.platform.startswith('win32'):
os.environ['TZ'] = 'America/Los_Angeles'
time.tzset()
class MyTests(unittest.TestCase):
def setUp(self):
# input
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/centos-7.7/stat.out'), 'r', encoding='utf-8') as f:
self.centos_7_7_stat = f.read()
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/ubuntu-18.04/stat.out'), 'r', encoding='utf-8') as f:
self.ubuntu_18_4_stat = f.read()
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/osx-10.14.6/stat.out'), 'r', encoding='utf-8') as f:
self.osx_10_14_6_stat = f.read()
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/osx-10.14.6/stat-filename-with-spaces.out'), 'r', encoding='utf-8') as f:
self.osx_10_14_6_stat_filename_with_spaces = f.read()
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/freebsd12/stat.out'), 'r', encoding='utf-8') as f:
self.freebsd12_stat = f.read()
# output
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/centos-7.7/stat.json'), 'r', encoding='utf-8') as f:
self.centos_7_7_stat_json = json.loads(f.read())
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/ubuntu-18.04/stat.json'), 'r', encoding='utf-8') as f:
self.ubuntu_18_4_stat_json = json.loads(f.read())
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/osx-10.14.6/stat.json'), 'r', encoding='utf-8') as f:
self.osx_10_14_6_stat_json = json.loads(f.read())
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/osx-10.14.6/stat-filename-with-spaces.json'), 'r', encoding='utf-8') as f:
self.osx_10_14_6_stat_filename_with_spaces_json = json.loads(f.read())
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/freebsd12/stat.json'), 'r', encoding='utf-8') as f:
self.freebsd12_stat_json = json.loads(f.read())
def test_stat_nodata(self):
"""
Test 'stat' with no data
"""
self.assertEqual(jc.parsers.stat.parse('', quiet=True), [])
def test_stat_centos_7_7(self):
"""
Test 'stat /bin/*' on Centos 7.7
"""
self.assertEqual(jc.parsers.stat.parse(self.centos_7_7_stat, quiet=True), self.centos_7_7_stat_json)
def test_stat_ubuntu_18_4(self):
"""
Test 'stat /bin/*' on Ubuntu 18.4
"""
self.assertEqual(jc.parsers.stat.parse(self.ubuntu_18_4_stat, quiet=True), self.ubuntu_18_4_stat_json)
def test_stat_osx_10_14_6(self):
"""
Test 'stat /foo/*' on OSX 10.14.6
"""
self.assertEqual(jc.parsers.stat.parse(self.osx_10_14_6_stat, quiet=True), self.osx_10_14_6_stat_json)
def test_stat_filename_with_spaces_osx_10_14_6(self):
"""
Test 'stat' filename with spaces on OSX 10.14.6
"""
self.assertEqual(jc.parsers.stat.parse(self.osx_10_14_6_stat_filename_with_spaces, quiet=True), self.osx_10_14_6_stat_filename_with_spaces_json)
def test_stat_freebsd12(self):
"""
Test 'stat /foo/*' on FreeBSD12
"""
self.assertEqual(jc.parsers.stat.parse(self.freebsd12_stat, quiet=True), self.freebsd12_stat_json)
if __name__ == '__main__':
unittest.main()
| 1,712 |
6,098 | <reponame>ahmedengu/h2o-3<gh_stars>1000+
package water.parser;
import org.junit.*;
import java.io.File;
import water.Key;
import water.TestUtil;
import water.fvec.Frame;
import water.util.FileIntegrityChecker;
import water.util.FileUtils;
public class ParseProgressTest extends TestUtil {
// Attempt a multi-jvm parse of covtype.
// Silently exits if it cannot find covtype.
@Test public void testCovtype() {
String[] covtype_locations = new String[]{"../datasets/UCI/UCI-large/covtype/covtype.data", "../../datasets/UCI/UCI-large/covtype/covtype.data", "../datasets/UCI/UCI-large/covtype/covtype.data.gz", "../demo/UCI-large/covtype/covtype.data", };
File f = null;
for( String covtype_location : covtype_locations ) {
f = FileUtils.locateFile(covtype_location);
if( f != null && f.exists() )
break;
}
if( f == null || !f.exists() ) {
System.out.println("Could not find covtype.data, skipping ParseProgressTest.testCovtype()");
return;
}
FileIntegrityChecker c = FileIntegrityChecker.check(f);
Assert.assertEquals(1,c.size()); // Exactly 1 file
Key k = c.syncDirectory(null,null,null,null);
Assert.assertEquals(true,k!=null);
Frame fr = ParseDataset.parse(Key.make(), k);
Assert.assertEquals( 55, fr.numCols() );
Assert.assertEquals( 581012, fr.numRows() );
fr.delete();
}
}
| 559 |
921 | //-*****************************************************************************
//
// Copyright (c) 2013,
// <NAME> Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// 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 Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their 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 <Alembic/AbcCoreOgawa/OrImpl.h>
#include <Alembic/AbcCoreOgawa/StreamManager.h>
namespace Alembic {
namespace AbcCoreOgawa {
namespace ALEMBIC_VERSION_NS {
//-*****************************************************************************
//-*****************************************************************************
// OBJECT READER IMPLEMENTATION
//-*****************************************************************************
//-*****************************************************************************
//-*****************************************************************************
// Reading as a child of a parent.
OrImpl::OrImpl( AbcA::ObjectReaderPtr iParent,
Ogawa::IGroupPtr iParentGroup,
std::size_t iGroupIndex,
ObjectHeaderPtr iHeader )
: m_header( iHeader )
{
m_parent = Alembic::Util::dynamic_pointer_cast< OrImpl,
AbcA::ObjectReader > (iParent);
// Check validity of all inputs.
ABCA_ASSERT( m_parent, "Invalid parent in OrImpl(Object)" );
ABCA_ASSERT( m_header, "Invalid header in OrImpl(Object)" );
m_archive = m_parent->getArchiveImpl();
ABCA_ASSERT( m_archive, "Invalid archive in OrImpl(Object)" );
StreamIDPtr streamId = m_archive->getStreamID();
std::size_t id = streamId->getID();
Ogawa::IGroupPtr group = iParentGroup->getGroup( iGroupIndex, false, id );
m_data.reset( new OrData( group, iHeader->getFullName(), id,
*m_archive, m_archive->getIndexedMetaData() ) );
}
//-*****************************************************************************
OrImpl::OrImpl( Alembic::Util::shared_ptr< ArImpl > iArchive,
OrDataPtr iData,
ObjectHeaderPtr iHeader )
: m_archive( iArchive )
, m_data( iData )
, m_header( iHeader )
{
ABCA_ASSERT( m_archive, "Invalid archive in OrImpl(Archive)" );
ABCA_ASSERT( m_data, "Invalid data in OrImpl(Archive)" );
ABCA_ASSERT( m_header, "Invalid header in OrImpl(Archive)" );
}
//-*****************************************************************************
OrImpl::~OrImpl()
{
// Nothing.
}
//-*****************************************************************************
const AbcA::ObjectHeader & OrImpl::getHeader() const
{
return *m_header;
}
//-*****************************************************************************
AbcA::ArchiveReaderPtr OrImpl::getArchive()
{
return m_archive;
}
//-*****************************************************************************
AbcA::ObjectReaderPtr OrImpl::getParent()
{
return m_parent;
}
//-*****************************************************************************
AbcA::CompoundPropertyReaderPtr OrImpl::getProperties()
{
return m_data->getProperties( asObjectPtr() );
}
//-*****************************************************************************
size_t OrImpl::getNumChildren()
{
return m_data->getNumChildren();
}
//-*****************************************************************************
const AbcA::ObjectHeader & OrImpl::getChildHeader( size_t i )
{
return m_data->getChildHeader( asObjectPtr(), i );
}
//-*****************************************************************************
const AbcA::ObjectHeader * OrImpl::getChildHeader( const std::string &iName )
{
return m_data->getChildHeader( asObjectPtr(), iName );
}
//-*****************************************************************************
AbcA::ObjectReaderPtr OrImpl::getChild( const std::string &iName )
{
return m_data->getChild( asObjectPtr(), iName );
}
AbcA::ObjectReaderPtr OrImpl::getChild( size_t i )
{
return m_data->getChild( asObjectPtr(), i );
}
//-*****************************************************************************
AbcA::ObjectReaderPtr OrImpl::asObjectPtr()
{
return shared_from_this();
}
//-*****************************************************************************
bool OrImpl::getPropertiesHash( Util::Digest & oDigest )
{
StreamIDPtr streamId = m_archive->getStreamID();
std::size_t id = streamId->getID();
m_data->getPropertiesHash( oDigest, id );
return true;
}
//-*****************************************************************************
bool OrImpl::getChildrenHash( Util::Digest & oDigest )
{
StreamIDPtr streamId = m_archive->getStreamID();
std::size_t id = streamId->getID();
m_data->getChildrenHash( oDigest, id );
return true;
}
//-*****************************************************************************
Alembic::Util::shared_ptr< ArImpl > OrImpl::getArchiveImpl() const
{
return m_archive;
}
} // End namespace ALEMBIC_VERSION_NS
} // End namespace AbcCoreOgawa
} // End namespace Alembic
| 1,891 |
417 | <reponame>Parcons/Torque3D<filename>Engine/source/core/util/str.cpp<gh_stars>100-1000
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 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.
//-----------------------------------------------------------------------------
#include <stdarg.h>
#include <stdio.h>
#include "platform/platform.h"
// Sigh... guess what compiler needs this...
namespace DictHash { U32 hash( String::StringData* ); }
namespace KeyCmp
{
template< typename Key > bool equals( const Key&, const Key& );
template<> bool equals<>( String::StringData* const&, String::StringData* const& );
}
#include "core/util/str.h"
#include "core/util/tDictionary.h"
#include "core/strings/stringFunctions.h"
#include "core/strings/unicode.h"
#include "core/util/hashFunction.h"
#include "core/util/autoPtr.h"
#include "core/util/tVector.h"
#include "core/dataChunker.h"
#include "console/console.h"
#include "console/engineAPI.h"
#include "math/mMathFn.h"
#include "platform/platform.h"
#include "platform/profiler.h"
#include "platform/platformIntrinsics.h"
#include "platform/threads/mutex.h"
#ifndef TORQUE_DISABLE_MEMORY_MANAGER
# undef new
#else
# define _new new
#endif
const String::SizeType String::NPos = U32(~0);
const String String::EmptyString;
/// A delete policy for the AutoPtr class
struct DeleteString
{
template<class T>
static void destroy(T *ptr) { dFree(ptr); }
};
//-----------------------------------------------------------------------------
/// Search for a character.
/// Search for the position of the needle in the haystack.
/// Default mode is StrCase | StrLeft, mode also accepts StrNoCase and StrRight.
/// If pos is non-zero, then in mode StrLeft the search starts at (hay + pos) and
/// in mode StrRight the search starts at (hay + pos - 1)
/// @return Returns a pointer to the location of the character in the haystack or 0
static const char* StrFind(const char* hay, char needle, S32 pos, U32 mode)
{
if (mode & String::Right)
{
// Go to the end first, then search backwards
const char *he = hay;
if (pos)
{
he += pos - 1;
}
else
{
while (*he)
he++;
}
if (mode & String::NoCase)
{
needle = dTolower(needle);
for (; he >= hay; he--)
{
if (dTolower(*he) == needle)
return he;
}
}
else
{
for (; he >= hay; he--)
{
if (*he == needle)
return he;
}
}
return 0;
}
else
{
if (mode & String::NoCase)
{
needle = dTolower(needle);
for (hay += pos; *hay && dTolower(*hay) != needle;)
hay++;
}
else
{
for (hay += pos; *hay && *hay != needle;)
hay++;
}
return *hay ? hay : 0;
}
}
/// Search for a StringData.
/// Search for the position of the needle in the haystack.
/// Default mode is StrCase | StrLeft, mode also accepts StrNoCase and StrRight.
/// If pos is non-zero, then in mode StrLeft the search starts at (hay + pos) and
/// in mode StrRight the search starts at (hay + pos - 1)
/// @return Returns a pointer to the StringData in the haystack or 0
static const char* StrFind(const char* hay, const char* needle, S32 pos, U32 mode)
{
if (mode & String::Right)
{
const char *he = hay;
if (pos)
{
he += pos - 1;
}
else
{
while (*he)
he++;
}
if (mode & String::NoCase)
{
AutoPtr<char,DeleteString> ln(dStrlwr(dStrdup(needle)));
for (; he >= hay; he--)
{
if (dTolower(*he) == *ln)
{
U32 i = 0;
while (ln[i] && ln[i] == dTolower(he[i]))
i++;
if (!ln[i])
return he;
if (!hay[i])
return 0;
}
}
}
else
{
for (; he >= hay; he--)
{
if (*he == *needle)
{
U32 i = 0;
while (needle[i] && needle[i] == he[i])
i++;
if (!needle[i])
return he;
if (!hay[i])
return 0;
}
}
}
return 0;
}
else
{
if (mode & String::NoCase)
{
AutoPtr<char,DeleteString> ln(dStrlwr(dStrdup(needle)));
for (hay += pos; *hay; hay++)
{
if (dTolower(*hay) == *ln)
{
U32 i = 0;
while (ln[i] && ln[i] == dTolower(hay[i]))
i++;
if (!ln[i])
return hay;
if (!hay[i])
return 0;
}
}
}
else
{
for (hay += pos; *hay; hay++)
{
if (*hay == *needle)
{
U32 i = 0;
while (needle[i] && needle[i] == hay[i])
i++;
if (!needle[i])
return hay;
if (!hay[i])
return 0;
}
}
}
}
return 0;
}
//-----------------------------------------------------------------------------
/// Struct with String::StringData's field so we can initialize
/// this without a constructor.
struct StringDataImpl
{
#ifdef TORQUE_DEBUG
StringChar* mString; ///< so we can inspect data in a debugger
#endif
U32 mRefCount; ///< String reference count; string is not refcounted if this is U32_MAX (necessary for thread-safety of interned strings and the empty string).
U32 mLength; ///< String length in bytes excluding null.
mutable U32 mNumChars; ///< Character count; varies from byte count for strings with multi-bytes characters.
mutable U32 mHashCase; ///< case-sensitive hash
mutable U32 mHashNoCase; ///< case-insensitive hash
mutable UTF16* mUTF16;
bool mIsInterned; ///< If true, this string is interned in the string table.
StringChar mData[1]; ///< Start of string data
};
///
class String::StringData : protected StringDataImpl
{
public:
///
StringData( const StringChar* data, bool interned = false )
{
mRefCount = 1;
mNumChars = U32_MAX;
mHashCase = U32_MAX;
mHashNoCase = U32_MAX;
mUTF16 = NULL;
mIsInterned = interned;
// mLength is initialized by operator new()
if( data )
{
dMemcpy( mData, data, sizeof( StringChar ) * mLength );
mData[ mLength ] = '\0';
}
#ifdef TORQUE_DEBUG
mString = &mData[0];
#endif
if( mIsInterned )
mRefCount = U32_MAX;
}
~StringData()
{
if( mUTF16 )
delete [] mUTF16;
}
TORQUE_NOINLINE void* operator new(size_t size, U32 len);
TORQUE_NOINLINE void* operator new( size_t size, U32 len, DataChunker& chunker );
void operator delete(void *);
bool isShared() const
{
return ( mRefCount > 1 );
}
void addRef()
{
if( mRefCount != U32_MAX )
mRefCount ++;
}
void release()
{
if( mRefCount != U32_MAX )
{
-- mRefCount;
if( !mRefCount )
delete this;
}
}
U32 getLength() const
{
return mLength;
}
U32 getDataSize() const
{
return ( mLength + 1 );
}
U32 getDataSizeUTF16() const
{
return ( mLength * sizeof( UTF16 ) );
}
UTF8 operator []( U32 index ) const
{
AssertFatal( index < mLength, "String::StringData::operator []() - index out of range" );
return mData[ index ];
}
UTF8* utf8()
{
return mData;
}
const UTF8* utf8() const
{
return mData;
}
UTF16* utf16() const
{
if( !mUTF16 )
{
// Do this atomically to protect interned strings.
UTF16* utf16 = createUTF16string( mData );
if( !dCompareAndSwap( mUTF16,( UTF16* ) NULL, utf16 ) )
delete [] utf16;
}
return mUTF16;
}
U32 getHashCase() const
{
return mHashCase;
}
U32 getOrCreateHashCase() const
{
if( mHashCase == U32_MAX )
{
PROFILE_SCOPE(StringData_getOrCreateHashCase);
mHashCase = Torque::hash((const U8 *)(mData), mLength, 0);
}
return mHashCase;
}
U32 getHashNoCase() const
{
return mHashNoCase;
}
U32 getOrCreateHashNoCase() const
{
if( mHashNoCase == U32_MAX)
{
PROFILE_SCOPE(StringData_getOrCreateHashNoCase);
UTF8 *lower = new UTF8[ mLength + 1 ];
dStrncpy( lower, utf8(), mLength );
lower[ mLength ] = 0;
dStrlwr( lower );
mHashNoCase = Torque::hash( (const U8*)lower, mLength, 0 );
delete [] lower;
}
return mHashNoCase;
}
U32 getNumChars() const
{
if( mNumChars == U32_MAX )
mNumChars = dStrlen( utf16() );
return mNumChars;
}
bool isInterned() const
{
return mIsInterned;
}
static StringData* Empty()
{
static UTF16 emptyUTF16[ 1 ] = { 0 };
static StringDataImpl empty =
{
#ifdef TORQUE_DEBUG
"", // mString
#endif
U32_MAX, // mRefCount
0, // mLength
0, // mNumChars
0, // mHashCase
0, // mHashNoCase
emptyUTF16, // mUTF16
true, // mIsInterned
{ 0 } // mData
};
return ( StringData* ) ∅
}
};
//-----------------------------------------------------------------------------
namespace DictHash
{
inline U32 hash( String::StringData* data )
{
return data->getOrCreateHashCase();
}
}
namespace KeyCmp
{
template<>
inline bool equals<>( String::StringData* const& d1, String::StringData* const& d2 )
{
return ( String::compare( d1->utf8(), d2->utf8() ) == 0 );
}
}
/// Type for the intern string table. We don't want String instances directly
/// on the table so that destructors don't run when the table is destroyed. This
/// is because we really shouldn't depend on dtor ordering within this file and thus
/// we can't tell whether the intern string memory is freed before or after the
/// table is destroyed.
struct StringInternTable : public HashTable< String::StringData*, String::StringData* >
{
Mutex mMutex;
DataChunker mChunker;
};
static StringInternTable* sInternTable;
struct KillInternTable
{
~KillInternTable()
{
if( sInternTable )
delete sInternTable;
}
};
static KillInternTable sKillInternTable;
//-----------------------------------------------------------------------------
#ifdef TORQUE_DEBUG
/// Tracks the number of bytes allocated for strings.
/// @bug This currently does not include UTF16 allocations.
static U32 sgStringMemBytes;
/// Tracks the number of Strings which are currently instantiated.
static U32 sgStringInstances;
#endif
DefineEngineFunction( dumpStringMemStats, void, (), , "()"
"@brief Dumps information about String memory usage\n\n"
"@ingroup Debugging\n"
"@ingroup Strings\n")
{
#ifdef TORQUE_DEBUG
Con::printf( "String Data: %i instances, %i bytes", sgStringInstances, sgStringMemBytes );
#endif
}
//-----------------------------------------------------------------------------
void* String::StringData::operator new( size_t size, U32 len )
{
AssertFatal( len != 0, "String::StringData::operator new() - string must not be empty" );
StringData *str = static_cast<StringData*>( dMalloc( size + len * sizeof(StringChar) ) );
str->mLength = len;
#ifdef TORQUE_DEBUG
dFetchAndAdd( sgStringMemBytes, size + len * sizeof(StringChar) );
dFetchAndAdd( sgStringInstances, 1 );
#endif
return str;
}
void String::StringData::operator delete(void *ptr)
{
StringData* sub = static_cast<StringData *>(ptr);
AssertFatal( sub->mRefCount == 0, "StringData::delete() - invalid refcount" );
#ifdef TORQUE_DEBUG
dFetchAndAdd( sgStringMemBytes, U32( -( S32( sizeof( StringData ) + sub->mLength * sizeof(StringChar) ) ) ) );
dFetchAndAdd( sgStringInstances, U32( -1 ) );
#endif
dFree( ptr );
}
void* String::StringData::operator new( size_t size, U32 len, DataChunker& chunker )
{
AssertFatal( len != 0, "String::StringData::operator new() - string must not be empty" );
StringData *str = static_cast<StringData*>( chunker.alloc( size + len * sizeof(StringChar) ) );
str->mLength = len;
#ifdef TORQUE_DEBUG
dFetchAndAdd( sgStringMemBytes, size + len * sizeof(StringChar) );
dFetchAndAdd( sgStringInstances, 1 );
#endif
return str;
}
//-----------------------------------------------------------------------------
String::String()
{
PROFILE_SCOPE(String_default_constructor);
_string = StringData::Empty();
}
String::String(const String &str)
{
PROFILE_SCOPE(String_String_constructor);
_string = str._string;
_string->addRef();
}
String::String(const StringChar *str)
{
PROFILE_SCOPE(String_char_constructor);
if( str && *str )
{
U32 len = dStrlen(str);
_string = new ( len ) StringData( str );
}
else
_string = StringData::Empty();
}
String::String(const StringChar *str, SizeType len)
{
PROFILE_SCOPE(String_char_len_constructor);
if (str && *str && len!=0)
{
_string = new ( len ) StringData( str );
}
else
_string = StringData::Empty();
}
String::String(const UTF16 *str)
{
PROFILE_SCOPE(String_UTF16_constructor);
if( str && str[ 0 ] )
{
UTF8* utf8 = createUTF8string( str );
U32 len = dStrlen( utf8 );
_string = new ( len ) StringData( utf8 );
delete [] utf8;
}
else
_string = StringData::Empty();
}
String::~String()
{
if (_string && _string != StringData::Empty())
_string->release();
}
//-----------------------------------------------------------------------------
String String::intern() const
{
if( isInterned() )
return *this;
// Create the intern table, if we haven't already.
if( !sInternTable )
sInternTable = new StringInternTable;
// Lock the string table.
MutexHandle mutex;
mutex.lock( &sInternTable->mMutex );
// Lookup.
StringInternTable::Iterator iter = sInternTable->find( _string );
if( iter != sInternTable->end() )
return ( *iter ).value;
// Create new.
StringData* data = new ( length(), sInternTable->mChunker ) StringData( c_str(), true );
iter = sInternTable->insertUnique( data, data );
return ( *iter ).value;
}
//-----------------------------------------------------------------------------
const StringChar* String::c_str() const
{
return _string->utf8();
}
const UTF16 *String::utf16() const
{
return _string->utf16();
}
String::SizeType String::length() const
{
return _string->getLength();
}
String::SizeType String::size() const
{
return _string->getDataSize();
}
String::SizeType String::numChars() const
{
return _string->getNumChars();
}
bool String::isEmpty() const
{
return ( _string == StringData::Empty() );
}
bool String::isEmpty(const char* str)
{
return str == 0 || str[0] == '\0';
}
bool String::isShared() const
{
return _string->isShared();
}
bool String::isSame( const String& str ) const
{
return ( _string == str._string );
}
bool String::isInterned() const
{
return ( _string->isInterned() );
}
U32 String::getHashCaseSensitive() const
{
return _string->getOrCreateHashCase();
}
U32 String::getHashCaseInsensitive() const
{
return _string->getOrCreateHashNoCase();
}
//-----------------------------------------------------------------------------
String::SizeType String::find(const String &str, SizeType pos, U32 mode) const
{
return find(str._string->utf8(), pos, mode);
}
String& String::insert(SizeType pos, const String &str)
{
return insert(pos, str._string->utf8());
}
String& String::replace(SizeType pos, SizeType len, const String &str)
{
return replace(pos, len, str._string->utf8());
}
//-----------------------------------------------------------------------------
String& String::operator=(StringChar c)
{
_string->release();
_string = new ( 2 ) StringData( 0 );
_string->utf8()[ 0 ] = c;
_string->utf8()[ 1 ] = '\0';
return *this;
}
String& String::operator+=(StringChar c)
{
// Append the given string into a new string
U32 len = _string->getLength();
StringData* sub = new ( len + 1 ) StringData( NULL );
copy( sub->utf8(), _string->utf8(), len );
sub->utf8()[len] = c;
sub->utf8()[len+1] = 0;
_string->release();
_string = sub;
return *this;
}
//-----------------------------------------------------------------------------
String& String::operator=(const StringChar *str)
{
// Protect against self assignment which is not only a
// waste of time, but can also lead to the string being
// freed before it can be reassigned.
if ( _string->utf8() == str )
return *this;
_string->release();
if (str && *str)
{
U32 len = dStrlen(str);
_string = new ( len ) StringData( str );
}
else
_string = StringData::Empty();
return *this;
}
String& String::operator=(const String &src)
{
// Inc src first to avoid assignment to self problems.
src._string->addRef();
_string->release();
_string = src._string;
return *this;
}
String& String::operator+=(const StringChar *src)
{
if( src == NULL || !*src )
return *this;
// Append the given string into a new string
U32 lena = _string->getLength();
U32 lenb = dStrlen(src);
U32 newlen = lena + lenb;
StringData* sub;
if( !newlen )
sub = StringData::Empty();
else
{
sub = new ( newlen ) StringData( NULL );
copy(sub->utf8(),_string->utf8(),lena);
copy(sub->utf8() + lena,src,lenb + 1);
}
_string->release();
_string = sub;
return *this;
}
String& String::operator+=(const String &src)
{
if( src.isEmpty() )
return *this;
// Append the given string into a new string
U32 lena = _string->getLength();
U32 lenb = src._string->getLength();
U32 newlen = lena + lenb;
StringData* sub;
if( !newlen )
sub = StringData::Empty();
else
{
sub = new ( newlen ) StringData( NULL );
copy(sub->utf8(),_string->utf8(),lena);
copy(sub->utf8() + lena,src._string->utf8(),lenb + 1);
}
_string->release();
_string = sub;
return *this;
}
//-----------------------------------------------------------------------------
String operator+(const String &a, const String &b)
{
PROFILE_SCOPE( String_String_plus_String );
if( a.isEmpty() )
return b;
else if( b.isEmpty() )
return a;
U32 lena = a.length();
U32 lenb = b.length();
String::StringData *sub = new ( lena + lenb ) String::StringData( NULL );
String::copy(sub->utf8(),a._string->utf8(),lena);
String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
return String(sub);
}
String operator+(const String &a, StringChar c)
{
//PROFILE_SCOPE( String_String_plus_Char );
U32 lena = a.length();
String::StringData *sub = new ( lena + 1 ) String::StringData( NULL );
String::copy(sub->utf8(),a._string->utf8(),lena);
sub->utf8()[lena] = c;
sub->utf8()[lena+1] = 0;
return String(sub);
}
String operator+(StringChar c, const String &a)
{
//PROFILE_SCOPE( String_Char_plus_String );
U32 lena = a.length();
String::StringData *sub = new ( lena + 1 ) String::StringData( NULL );
String::copy(sub->utf8() + 1,a._string->utf8(),lena + 1);
sub->utf8()[0] = c;
return String(sub);
}
String operator+(const String &a, const StringChar *b)
{
//PROFILE_SCOPE( String_String_plus_CString );
AssertFatal(b,"String:: Invalid null ptr argument");
if( a.isEmpty() )
return String( b );
U32 lena = a.length();
U32 lenb = dStrlen(b);
if( !lenb )
return a;
String::StringData *sub = new ( lena + lenb ) String::StringData( NULL );
String::copy(sub->utf8(),a._string->utf8(),lena);
String::copy(sub->utf8() + lena,b,lenb + 1);
return String(sub);
}
String operator+(const StringChar *a, const String &b)
{
//PROFILE_SCOPE( String_CString_plus_String );
AssertFatal(a,"String:: Invalid null ptr argument");
if( b.isEmpty() )
return String( a );
U32 lena = dStrlen(a);
if( !lena )
return b;
U32 lenb = b.length();
String::StringData* sub = new ( lena + lenb ) String::StringData( NULL );
String::copy(sub->utf8(),a,lena);
String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
return String(sub);
}
bool String::operator==(const String &str) const
{
//PROFILE_SCOPE( String_op_equal );
if( str._string == _string )
return true;
else if( str._string->isInterned() && _string->isInterned() )
return false;
else if( str.length() != length() )
return false;
else if( str._string->getHashCase() != U32_MAX
&& _string->getHashCase() != U32_MAX
&& str._string->getHashCase() != _string->getHashCase() )
return false;
else
return ( dMemcmp( str._string->utf8(), _string->utf8(), _string->getLength() ) == 0 );
}
bool String::operator==( StringChar c ) const
{
if( !_string || _string->getLength() != 1 )
return false;
else
return ( _string->utf8()[ 0 ] == c );
}
bool String::operator<(const String &str) const
{
return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) < 0 );
}
bool String::operator>(const String &str) const
{
return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) > 0 );
}
bool String::operator<=(const String &str) const
{
return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) <= 0 );
}
bool String::operator>=(const String &str) const
{
return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) >= 0 );
}
//-----------------------------------------------------------------------------
// Base functions for string comparison
S32 String::compare(const StringChar *str, SizeType len, U32 mode) const
{
PROFILE_SCOPE( String_compare );
AssertFatal(str,"String:: Invalid null ptr argument");
const StringChar *p1 = _string->utf8();
const StringChar *p2 = str;
if (p1 == p2)
return 0;
if( mode & String::Right )
{
U32 n = len;
if( n > length() )
n = length();
p1 += length() - n;
p2 += dStrlen( str ) - n;
}
if (mode & String::NoCase)
{
if (len)
{
for (;--len; p1++,p2++)
{
if (dTolower(*p1) != dTolower(*p2) || !*p1)
break;
}
}
else
{
while (dTolower(*p1) == dTolower(*p2) && *p1)
{
p1++;
p2++;
}
}
return dTolower(*p1) - dTolower(*p2);
}
if (len)
return dMemcmp(p1,p2,len);
while (*p1 == *p2 && *p1)
{
p1++;
p2++;
}
return *p1 - *p2;
}
S32 String::compare(const String &str, SizeType len, U32 mode) const
{
if ( str._string == _string )
return 0;
return compare( str.c_str(), len, mode );
}
S32 String::compare(const char *str1, const char *str2)
{
return strcmp(str1, str2);
}
S32 String::compare(const UTF16 *str1, const UTF16 *str2)
{
#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON)
return wcscmp(reinterpret_cast<const wchar_t *>(str1), reinterpret_cast<const wchar_t *>(str2));
#else
S32 ret;
const UTF16 *a, *b;
a = str1;
b = str2;
while (((ret = *a - *b) == 0) && *a && *b)
a++, b++;
return ret;
#endif
}
bool String::equal(const String &str, U32 mode) const
{
if( !mode )
return ( *this == str );
else
{
if( _string == str._string )
return true;
else if( _string->isInterned() && str._string->isInterned() )
return false;
else if( length() != str.length() )
return false;
else if( _string->getHashNoCase() != U32_MAX
&& str._string->getHashNoCase() != U32_MAX
&& _string->getHashNoCase() != str._string->getHashNoCase() )
return false;
else
return ( compare( str.c_str(), length(), mode ) == 0 );
}
}
//-----------------------------------------------------------------------------
String::SizeType String::find(StringChar c, SizeType pos, U32 mode) const
{
const StringChar* ptr = StrFind(_string->utf8(),c,pos,mode);
return ptr? SizeType(ptr - _string->utf8()): NPos;
}
String::SizeType String::find(const StringChar *str, SizeType pos, U32 mode) const
{
AssertFatal(str,"String:: Invalid null ptr argument");
const StringChar* ptr = StrFind(_string->utf8(),str,pos,mode);
return ptr? SizeType(ptr - _string->utf8()): NPos;
}
//-----------------------------------------------------------------------------
String& String::insert(SizeType pos, const StringChar *str)
{
AssertFatal(str,"String:: Invalid null ptr argument");
return insert(pos,str,dStrlen(str));
}
///@todo review for error checking
String& String::insert(SizeType pos, const StringChar *str, SizeType len)
{
if( !len )
return *this;
AssertFatal( str, "String:: Invalid null ptr argument" );
SizeType lena = length();
AssertFatal((pos <= lena),"Calling String::insert with position greater than length");
U32 newlen = lena + len;
StringData *sub;
if( !newlen )
sub = StringData::Empty();
else
{
sub = new ( newlen ) StringData( NULL );
String::copy(sub->utf8(),_string->utf8(),pos);
String::copy(sub->utf8() + pos,str,len);
String::copy(sub->utf8() + pos + len,_string->utf8() + pos,lena - pos + 1);
}
_string->release();
_string = sub;
return *this;
}
String& String::erase(SizeType pos, SizeType len)
{
AssertFatal( len != 0, "String::erase() - Calling String::erase with 0 length" );
AssertFatal( ( pos + len ) <= length(), "String::erase() - Invalid string region" );
if( !len )
return *this;
SizeType slen = length();
U32 newlen = slen - len;
StringData *sub;
if( !newlen )
sub = StringData::Empty();
else
{
sub = new ( newlen ) StringData( NULL );
if (pos > 0)
String::copy(sub->utf8(),_string->utf8(),pos);
String::copy(sub->utf8() + pos, _string->utf8() + pos + len, slen - (pos + len) + 1);
}
_string->release();
_string = sub;
return *this;
}
///@todo review for error checking
String& String::replace(SizeType pos, SizeType len, const StringChar *str)
{
AssertFatal( str, "String::replace() - Invalid null ptr argument" );
AssertFatal( len != 0, "String::replace() - Zero length" );
AssertFatal( ( pos + len ) <= length(), "String::replace() - Invalid string region" );
SizeType slen = length();
SizeType rlen = dStrlen(str);
U32 newlen = slen - len + rlen;
StringData *sub;
if( !newlen )
sub = StringData::Empty();
else
{
sub = new ( newlen ) StringData( NULL );
String::copy(sub->utf8(),_string->utf8(), pos);
String::copy(sub->utf8() + pos,str,rlen);
String::copy(sub->utf8() + pos + rlen,_string->utf8() + pos + len,slen - pos - len + 1);
}
_string->release();
_string = sub;
return *this;
}
String& String::replace( StringChar c1, StringChar c2 )
{
if( isEmpty() )
return *this;
// Create the new string lazily so that we don't needlessly
// dup strings when there is nothing to replace.
StringData* sub = NULL;
bool foundReplacement = false;
StringChar* c = _string->utf8();
while( *c )
{
if( *c == c1 )
{
if( !foundReplacement )
{
sub = new ( length() ) StringData( _string->utf8() );
c = &sub->utf8()[ c - _string->utf8() ];
foundReplacement = true;
}
*c = c2;
}
c++;
}
if( foundReplacement )
{
_string->release();
_string = sub;
}
return *this;
}
String &String::replace(const String &s1, const String &s2)
{
// Find number of occurrences of s1 and
// Calculate length of the new string...
const U32 &s1len = s1.length();
const U32 &s2len = s2.length();
U32 pos = 0;
Vector<U32> indices;
StringChar *walk = _string->utf8();
while ( walk )
{
// Casting away the const... was there a better way?
walk = (StringChar*)StrFind( _string->utf8(), s1.c_str(), pos, Case|Left );
if ( walk )
{
pos = SizeType(walk - _string->utf8());
indices.push_back( pos );
pos += s1len;
}
}
// Early-out, no StringDatas found.
if ( indices.size() == 0 )
return *this;
U32 newSize = size() - ( indices.size() * s1len ) + ( indices.size() * s2len );
StringData *sub;
if( newSize == 1 )
sub = StringData::Empty();
else
{
sub = new (newSize - 1 ) StringData( NULL );
// Now assemble the new string from the pieces of the old...
// Index into the old string
pos = 0;
// Index into the new string
U32 newPos = 0;
// Used to store a character count to be memcpy'd
U32 copyCharCount = 0;
for ( U32 i = 0; i < indices.size(); i++ )
{
const U32 &index = indices[i];
// Number of chars (if any) before the next indexed StringData
copyCharCount = index - pos;
// Copy chars before the StringData if we have any.
if ( copyCharCount > 0 )
{
dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
newPos += copyCharCount;
}
// Copy over the replacement string.
if ( s2len > 0 )
dMemcpy( sub->utf8() + newPos, s2._string->utf8(), s2len * sizeof(StringChar) );
newPos += s2len;
pos = index + s1len;
}
// There could be characters left in the original string after the last
// StringData occurrence, which we need to copy now - outside the loop.
copyCharCount = length() - indices.last() - s1len;
if ( copyCharCount != 0 )
dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
// Null terminate it!
sub->utf8()[newSize-1] = 0;
}
_string->release();
_string = sub;
return *this;
}
//-----------------------------------------------------------------------------
String String::substr(SizeType pos, SizeType len) const
{
//PROFILE_SCOPE( String_substr );
AssertFatal( pos <= length(), "String::substr - Invalid position!" );
if ( len == -1 )
len = length() - pos;
AssertFatal( len + pos <= length(), "String::substr - Invalid length!" );
StringData* sub;
if( !len )
sub = StringData::Empty();
else
sub = new ( len ) StringData( _string->utf8() + pos );
return sub;
}
//-----------------------------------------------------------------------------
String String::trim() const
{
if( isEmpty() )
return *this;
const StringChar* start = _string->utf8();
while( *start && dIsspace( *start ) )
start ++;
const StringChar* end = _string->utf8() + length() - 1;
while( end > start && dIsspace( *end ) )
end --;
end ++;
const U32 len = end - start;
if( len == length() )
return *this;
StringData* sub;
if( !len )
sub = StringData::Empty();
else
sub = new ( len ) StringData( start );
return sub;
}
//-----------------------------------------------------------------------------
String String::expandEscapes() const
{
char* tmp = ( char* ) dMalloc( length() * 2 + 1 ); // worst-case situation.
expandEscape( tmp, c_str() );
String str( tmp );
dFree( tmp );
return str;
}
//-----------------------------------------------------------------------------
String String::collapseEscapes() const
{
char* tmp = dStrdup( c_str() );
collapseEscape( tmp );
String str( tmp );
dFree( tmp );
return str;
}
//-----------------------------------------------------------------------------
void String::split( const char* delimiter, Vector< String >& outElements ) const
{
const char* ptr = _string->utf8();
const char* start = ptr;
while( *ptr )
{
// Search for start of delimiter.
if( *ptr != delimiter[ 0 ] )
ptr ++;
else
{
// Skip delimiter.
const char* end = ptr;
const char* del = delimiter;
while( *del && *del == *ptr )
{
ptr ++;
del ++;
}
// If we didn't match all of delimiter,
// continue with search.
if( *del != '\0' )
continue;
// Extract component.
outElements.push_back( String( start, end - start ) );
start = ptr;
}
}
// Add rest of string if there is any.
if( start != ptr )
outElements.push_back( start );
}
//-----------------------------------------------------------------------------
bool String::startsWith( const char* text ) const
{
return dStrStartsWith( _string->utf8(), text );
}
//-----------------------------------------------------------------------------
bool String::endsWith( const char* text ) const
{
return dStrEndsWith( _string->utf8(), text );
}
//-----------------------------------------------------------------------------
void String::copy(StringChar* dst, const StringChar *src, U32 len)
{
dMemcpy(dst, src, len * sizeof(StringChar));
}
//-----------------------------------------------------------------------------
#if defined(TORQUE_OS_WIN)
// This standard function is not defined when compiling with VC7...
#define vsnprintf _vsnprintf
#endif
String::StrFormat::~StrFormat()
{
if( _dynamicBuffer )
dFree( _dynamicBuffer );
}
S32 String::StrFormat::format( const char *format, va_list args )
{
_len=0;
return formatAppend(format,args);
}
S32 String::StrFormat::formatAppend( const char *format, va_list args )
{
// Format into the fixed buffer first.
S32 startLen = _len;
if (_dynamicBuffer == NULL)
{
_len += vsnprintf(_fixedBuffer + _len, sizeof(_fixedBuffer) - _len, format, args);
if (_len >= 0 && _len < sizeof(_fixedBuffer))
return _len;
// Start off the dynamic buffer at twice fixed buffer size
_len = startLen;
_dynamicSize = sizeof(_fixedBuffer) * 2;
_dynamicBuffer = (char*)dMalloc(_dynamicSize);
dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
}
// Format into the dynamic buffer, if the buffer is not large enough, then
// keep doubling it's size until it is. The buffer is not reallocated
// using reallocate() to avoid unnecessary buffer copying.
_len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
while (_len < 0 || _len >= _dynamicSize)
{
_len = startLen;
_dynamicBuffer = (char*)dRealloc(_dynamicBuffer, _dynamicSize *= 2);
_len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
}
return _len;
}
S32 String::StrFormat::append(const char * str, S32 len)
{
if (_dynamicBuffer == NULL)
{
if (_len+len >= 0 && _len+len < sizeof(_fixedBuffer))
{
dMemcpy(_fixedBuffer + _len, str, len);
_len += len;
_fixedBuffer[_len] = '\0';
return _len;
}
_dynamicSize = sizeof(_fixedBuffer) * 2;
_dynamicBuffer = (char*)dMalloc(_dynamicSize);
dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
}
S32 newSize = _dynamicSize;
while (newSize < _len+len)
newSize *= 2;
if (newSize != _dynamicSize)
_dynamicBuffer = (char*) dRealloc(_dynamicBuffer, newSize);
_dynamicSize = newSize;
dMemcpy(_dynamicBuffer + _len, str, len);
_len += len;
_dynamicBuffer[_len] = '\0';
return _len;
}
S32 String::StrFormat::append(const char * str)
{
return append(str, dStrlen(str));
}
char* String::StrFormat::copy( char *buffer ) const
{
dMemcpy(buffer, _dynamicBuffer? _dynamicBuffer: _fixedBuffer, _len+1);
return buffer;
}
//-----------------------------------------------------------------------------
String String::ToString( bool value )
{
static String sTrue = "true";
static String sFalse = "false";
if( value )
return sTrue;
return sFalse;
}
String String::ToString(const char *str, ...)
{
AssertFatal(str,"String:: Invalid null ptr argument");
// Use the format object
va_list args;
va_start(args, str);
String ret = VToString(str, args);
va_end(args);
return ret;
}
String String::VToString(const char* str, va_list args)
{
StrFormat format(str,args);
// Copy it into a string
U32 len = format.length();
StringData* sub;
if( !len )
sub = StringData::Empty();
else
{
sub = new ( len ) StringData( NULL );
format.copy( sub->utf8() );
sub->utf8()[ len ] = 0;
}
return sub;
}
String String::SpanToString(const char *start, const char *end)
{
if ( end == start )
return String();
AssertFatal( end > start, "Invalid arguments to String::SpanToString - end is before start" );
U32 len = U32(end - start);
StringData* sub = new ( len ) StringData( start );
return sub;
}
String String::ToLower(const String &string)
{
if ( string.isEmpty() )
return String();
StringData* sub = new ( string.length() ) StringData( string );
dStrlwr( sub->utf8() );
return sub;
}
String String::ToUpper(const String &string)
{
if ( string.isEmpty() )
return String();
StringData* sub = new ( string.length() ) StringData( string );
dStrupr( sub->utf8() );
return sub;
}
String String::GetTrailingNumber(const char* str, S32& number)
{
// Check for trivial strings
if (!str || !str[0])
return String::EmptyString;
// Find the number at the end of the string
String base(str);
const char* p = base.c_str() + base.length() - 1;
// Ignore trailing whitespace
while ((p != base.c_str()) && dIsspace(*p))
p--;
// Need at least one digit!
if (!isdigit(*p))
return base;
// Back up to the first non-digit character
while ((p != base.c_str()) && isdigit(*p))
p--;
// Convert number => allow negative numbers, treat '_' as '-' for Maya
if ((*p == '-') || (*p == '_'))
number = -dAtoi(p + 1);
else
number = (isdigit(*p) ? dAtoi(p) : dAtoi(++p));
// Remove space between the name and the number
while ((p > base.c_str()) && dIsspace(*(p-1)))
p--;
return base.substr(0, p - base.c_str());
}
String String::GetFirstNumber(const char* str, U32& startPos, U32& endPos)
{
// Check for trivial strings
if (!str || !str[0])
return String::EmptyString;
// Find the number at the end of the string
String base(str);
const char* p = base.c_str();
const char* end = base.c_str() + base.length() - 1;
bool dec = false;
startPos = 0;
//Check if we are just a digit
if(p == end && isdigit(*p))
return base;
//Look for the first digit
while ((p != end) && (dIsspace(*p) || !isdigit(*p)))
{
p++;
startPos++;
}
//Handle if we are at the end and found nothing
if(p == end && !isdigit(*p))
return "";
//update our end position at least to the start of our number
endPos = startPos;
//Backup our ptr
const char* backup = p;
//Check for any negative or decimal values
if(startPos > 0)
{
p--;
startPos--;
if(*p == '.')
{
dec = true;
//ignore any duplicate periods
while ((p != base.c_str()) && (*p == '.'))
{
p--;
startPos--;
}
//Found a decimal lets still check for negative sign
if(startPos > 0)
{
p--;
startPos--;
if((*p != '-') && (*p != '_'))
{
startPos++;
p++;
}
}
}
else if((*p != '-') && (*p != '_'))
{
//go back to where we where cause no decimal or negative sign found
startPos++;
p++;
}
}
//Restore where we were
p = backup;
//look for the end of the digits
bool justFoundDec = false;
while (p != end)
{
if(*p == '.')
{
if(dec && !justFoundDec)
break;
else
{
dec = true;
justFoundDec = true;
}
}
else if(!isdigit(*p))
break;
else if(justFoundDec)
justFoundDec = false;
p++;
endPos++;
}
U32 len = (!isdigit(*p)) ? endPos - startPos : (endPos + 1) - startPos;
return base.substr(startPos, len);
}
| 17,756 |
5,766 | //
// Cipher.h
//
// Library: Crypto
// Package: Cipher
// Module: Cipher
//
// Definition of the Cipher class.
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Crypto_Cipher_INCLUDED
#define Crypto_Cipher_INCLUDED
#include "Poco/Crypto/Crypto.h"
#include "Poco/Crypto/CryptoTransform.h"
#include "Poco/RefCountedObject.h"
#include "Poco/AutoPtr.h"
#include <istream>
#include <ostream>
#include <vector>
namespace Poco {
namespace Crypto {
class Crypto_API Cipher: public Poco::RefCountedObject
/// Represents the abstract base class from which all implementations of
/// symmetric/asymmetric encryption algorithms must inherit. Use the CipherFactory
/// class to obtain an instance of this class:
///
/// CipherFactory& factory = CipherFactory::defaultFactory();
/// // Creates a 256-bit AES cipher
/// Cipher* pCipher = factory.createCipher(CipherKey("aes-256"));
/// Cipher* pRSACipher = factory.createCipher(RSAKey(RSAKey::KL_1024, RSAKey::EXP_SMALL));
///
/// Check the different Key constructors on how to initialize/create
/// a key. The above example auto-generates random keys.
///
/// Note that you won't be able to decrypt data encrypted with a random key
/// once the Cipher is destroyed unless you persist the generated key and IV.
/// An example usage for random keys is to encrypt data saved in a temporary
/// file.
///
/// Once your key is set up, you can use the Cipher object to encrypt or
/// decrypt strings or, in conjunction with a CryptoInputStream or a
/// CryptoOutputStream, to encrypt streams of data.
///
/// Since encrypted strings will contain arbitrary binary data that will cause
/// problems in applications that are not binary-safe (eg., when sending
/// encrypted data in e-mails), the encryptString() and decryptString() can
/// encode (or decode, respectively) encrypted data using a "transport encoding".
/// Supported encodings are Base64 and BinHex.
///
/// The following example encrypts and decrypts a string utilizing Base64
/// encoding:
///
/// std::string plainText = "<PASSWORD> is my secret information";
/// std::string encrypted = pCipher->encryptString(plainText, Cipher::ENC_BASE64);
/// std::string decrypted = pCipher->decryptString(encrypted, Cipher::ENC_BASE64);
///
/// In order to encrypt a stream of data (eg. to encrypt files), you can use
/// a CryptoStream:
///
/// // Create an output stream that will encrypt all data going through it
/// // and write pass it to the underlying file stream.
/// Poco::FileOutputStream sink("encrypted.dat");
/// CryptoOutputStream encryptor(sink, pCipher->createEncryptor());
///
/// Poco::FileInputStream source("source.txt");
/// Poco::StreamCopier::copyStream(source, encryptor);
///
/// // Always close output streams to flush all internal buffers
/// encryptor.close();
/// sink.close();
{
public:
using Ptr = Poco::AutoPtr<Cipher>;
using ByteVec = std::vector<unsigned char>;
enum Encoding
/// Transport encoding to use for encryptString() and decryptString().
{
ENC_NONE = 0x00, /// Plain binary output
ENC_BASE64 = 0x01, /// Base64-encoded output
ENC_BINHEX = 0x02, /// BinHex-encoded output
ENC_BASE64_NO_LF = 0x81, /// Base64-encoded output, no linefeeds
ENC_BINHEX_NO_LF = 0x82 /// BinHex-encoded output, no linefeeds
};
virtual ~Cipher();
/// Destroys the Cipher.
virtual const std::string& name() const = 0;
/// Returns the name of the Cipher.
virtual CryptoTransform::Ptr createEncryptor() = 0;
/// Creates an encryptor object to be used with a CryptoStream.
virtual CryptoTransform::Ptr createDecryptor() = 0;
/// Creates a decryptor object to be used with a CryptoStream.
virtual std::string encryptString(const std::string& str, Encoding encoding = ENC_NONE);
/// Directly encrypt a string and encode it using the given encoding.
virtual std::string decryptString(const std::string& str, Encoding encoding = ENC_NONE);
/// Directly decrypt a string that is encoded with the given encoding.
virtual void encrypt(std::istream& source, std::ostream& sink, Encoding encoding = ENC_NONE);
/// Directly encrypts an input stream and encodes it using the given encoding.
virtual void decrypt(std::istream& source, std::ostream& sink, Encoding encoding = ENC_NONE);
/// Directly decrypt an input stream that is encoded with the given encoding.
protected:
Cipher();
/// Creates a new Cipher object.
private:
Cipher(const Cipher&);
Cipher& operator = (const Cipher&);
};
} } // namespace Poco::Crypto
#endif // Crypto_Cipher_INCLUDED
| 1,478 |
852 | <reponame>ckamtsikis/cmssw
#include "RecoEgamma/EgammaTools/interface/EgammaPCAHelper.h"
#include "DataFormats/HGCRecHit/interface/HGCRecHit.h"
#include "DataFormats/Math/interface/deltaPhi.h"
#include "DataFormats/ForwardDetId/interface/HGCalDetId.h"
#include "DataFormats/HcalDetId/interface/HcalDetId.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <algorithm>
#include <iostream>
#include <memory>
using namespace hgcal;
EGammaPCAHelper::EGammaPCAHelper()
: // Thickness correction to dEdx weights
// (100um, 200um, 300um silicon)
// See RecoLocalCalo.HGCalRecProducers.HGCalRecHit_cfi
invThicknessCorrection_({1. / 1.132, 1. / 1.092, 1. / 1.084}),
pca_(new TPrincipal(3, "D")) {
hitMap_ = nullptr;
debug_ = false;
}
void EGammaPCAHelper::setHitMap(const std::unordered_map<DetId, const HGCRecHit*>* hitMap) {
hitMap_ = hitMap;
pcaIteration_ = 0;
}
void EGammaPCAHelper::setRecHitTools(const hgcal::RecHitTools* recHitTools) {
recHitTools_ = recHitTools;
maxlayer_ = recHitTools_->lastLayerBH();
}
void EGammaPCAHelper::storeRecHits(const reco::HGCalMultiCluster& cluster) {
theCluster_ = &cluster;
std::vector<std::pair<DetId, float>> result;
for (reco::HGCalMultiCluster::component_iterator it = cluster.begin(); it != cluster.end(); it++) {
const std::vector<std::pair<DetId, float>>& hf = (*it)->hitsAndFractions();
result.insert(result.end(), hf.begin(), hf.end());
}
storeRecHits(result);
}
void EGammaPCAHelper::storeRecHits(const reco::CaloCluster& cluster) {
theCluster_ = &cluster;
storeRecHits(cluster.hitsAndFractions());
}
void EGammaPCAHelper::storeRecHits(const std::vector<std::pair<DetId, float>>& hf) {
std::vector<double> pcavars;
pcavars.resize(3, 0.);
theSpots_.clear();
pcaIteration_ = 0;
sigu_ = 0.;
sigv_ = 0.;
sigp_ = 0.;
sige_ = 0.;
unsigned hfsize = hf.size();
if (debug_)
std::cout << "The seed cluster constains " << hfsize << " hits " << std::endl;
if (hfsize == 0)
return;
for (unsigned int j = 0; j < hfsize; j++) {
unsigned int layer = recHitTools_->getLayerWithOffset(hf[j].first);
const DetId rh_detid = hf[j].first;
std::unordered_map<DetId, const HGCRecHit*>::const_iterator itcheck = hitMap_->find(rh_detid);
if (itcheck == hitMap_->end()) {
edm::LogWarning("EgammaPCAHelper") << " Big problem, unable to find a hit " << rh_detid.rawId() << " "
<< rh_detid.det() << " " << HGCalDetId(rh_detid) << std::endl;
continue;
}
if (debug_) {
std::cout << "DetId " << rh_detid.rawId() << " " << layer << " " << itcheck->second->energy() << std::endl;
std::cout << " Hit " << itcheck->second << " " << itcheck->second->energy() << std::endl;
}
float fraction = hf[j].second;
int thickIndex = recHitTools_->getSiThickIndex(rh_detid);
double mip = dEdXWeights_[layer] * 0.001; // convert in GeV
if (thickIndex > -1 and thickIndex < 3)
mip *= invThicknessCorrection_[thickIndex];
pcavars[0] = recHitTools_->getPosition(rh_detid).x();
pcavars[1] = recHitTools_->getPosition(rh_detid).y();
pcavars[2] = recHitTools_->getPosition(rh_detid).z();
if (pcavars[2] == 0.)
edm::LogWarning("EgammaPCAHelper") << " Problem, hit with z =0 ";
else {
Spot mySpot(rh_detid, itcheck->second->energy(), pcavars, layer, fraction, mip);
theSpots_.push_back(mySpot);
}
}
if (debug_) {
std::cout << " Stored " << theSpots_.size() << " hits " << std::endl;
}
}
void EGammaPCAHelper::computePCA(float radius, bool withHalo) {
// very important - to reset
pca_ = std::make_unique<TPrincipal>(3, "D");
bool initialCalculation = radius < 0;
if (debug_)
std::cout << " Initial calculation " << initialCalculation << std::endl;
if (initialCalculation && withHalo) {
edm::LogWarning("EGammaPCAHelper") << "Warning - in the first iteration, the halo hits are excluded " << std::endl;
withHalo = false;
}
float radius2 = radius * radius;
if (!initialCalculation) {
math::XYZVector mainAxis(axis_);
mainAxis.unit();
math::XYZVector phiAxis(barycenter_.x(), barycenter_.y(), 0);
math::XYZVector udir(mainAxis.Cross(phiAxis));
udir = udir.unit();
trans_ = Transform3D(Point(barycenter_),
Point(barycenter_ + axis_),
Point(barycenter_ + udir),
Point(0, 0, 0),
Point(0., 0., 1.),
Point(1., 0., 0.));
}
std::set<int> layers;
for (const auto& spot : theSpots_) {
if (spot.layer() > recHitTools_->lastLayerEE())
continue;
if (!withHalo && (!spot.isCore()))
continue;
if (initialCalculation) {
// initial calculation, take only core hits
if (!spot.isCore())
continue;
layers.insert(spot.layer());
for (int i = 0; i < spot.multiplicity(); ++i)
pca_->AddRow(spot.row());
} else {
// use a cylinder, include all hits
math::XYZPoint local = trans_(Point(spot.row()[0], spot.row()[1], spot.row()[2]));
if (local.Perp2() > radius2)
continue;
layers.insert(spot.layer());
for (int i = 0; i < spot.multiplicity(); ++i)
pca_->AddRow(spot.row());
}
}
if (debug_)
std::cout << " Nlayers " << layers.size() << std::endl;
if (layers.size() < 3) {
pcaIteration_ = -1;
return;
}
pca_->MakePrincipals();
++pcaIteration_;
const TVectorD& means = *(pca_->GetMeanValues());
const TMatrixD& eigens = *(pca_->GetEigenVectors());
barycenter_ = math::XYZPoint(means[0], means[1], means[2]);
axis_ = math::XYZVector(eigens(0, 0), eigens(1, 0), eigens(2, 0));
if (axis_.z() * barycenter_.z() < 0.0) {
axis_ = -1. * axis_;
}
}
void EGammaPCAHelper::computeShowerWidth(float radius, bool withHalo) {
sigu_ = 0.;
sigv_ = 0.;
sigp_ = 0.;
sige_ = 0.;
double cyl_ene = 0.;
float radius2 = radius * radius;
for (const auto& spot : theSpots_) {
Point globalPoint(spot.row()[0], spot.row()[1], spot.row()[2]);
math::XYZPoint local = trans_(globalPoint);
if (local.Perp2() > radius2)
continue;
// Select halo hits or not
if (withHalo && spot.fraction() < 0)
continue;
if (!withHalo && !(spot.isCore()))
continue;
sige_ += (globalPoint.eta() - theCluster_->eta()) * (globalPoint.eta() - theCluster_->eta()) * spot.energy();
sigp_ += deltaPhi(globalPoint.phi(), theCluster_->phi()) * deltaPhi(globalPoint.phi(), theCluster_->phi()) *
spot.energy();
sigu_ += local.x() * local.x() * spot.energy();
sigv_ += local.y() * local.y() * spot.energy();
cyl_ene += spot.energy();
}
if (cyl_ene > 0.) {
const double inv_cyl_ene = 1. / cyl_ene;
sigu_ = sigu_ * inv_cyl_ene;
sigv_ = sigv_ * inv_cyl_ene;
sigp_ = sigp_ * inv_cyl_ene;
sige_ = sige_ * inv_cyl_ene;
}
sigu_ = std::sqrt(sigu_);
sigv_ = std::sqrt(sigv_);
sigp_ = std::sqrt(sigp_);
sige_ = std::sqrt(sige_);
}
bool EGammaPCAHelper::checkIteration() const {
if (pcaIteration_ == 0) {
if (debug_)
std::cout << " The PCA has not been run yet " << std::endl;
return false;
} else if (pcaIteration_ == 1) {
if (debug_)
std::cout << " The PCA has been run only once - careful " << std::endl;
return false;
} else if (pcaIteration_ == -1) {
if (debug_)
std::cout << " Not enough layers to perform PCA " << std::endl;
return false;
}
return true;
}
void EGammaPCAHelper::clear() {
theSpots_.clear();
pcaIteration_ = 0;
sigu_ = 0.;
sigv_ = 0.;
sigp_ = 0.;
sige_ = 0.;
}
LongDeps EGammaPCAHelper::energyPerLayer(float radius, bool withHalo) {
if (debug_)
checkIteration();
std::set<int> layers;
float radius2 = radius * radius;
std::vector<float> energyPerLayer(maxlayer_ + 1, 0.f);
math::XYZVector mainAxis(axis_);
mainAxis.unit();
math::XYZVector phiAxis(barycenter_.x(), barycenter_.y(), 0);
math::XYZVector udir(mainAxis.Cross(phiAxis));
udir = udir.unit();
trans_ = Transform3D(Point(barycenter_),
Point(barycenter_ + axis_),
Point(barycenter_ + udir),
Point(0, 0, 0),
Point(0., 0., 1.),
Point(1., 0., 0.));
float energyEE = 0.;
float energyFH = 0.;
float energyBH = 0.;
for (const auto& spot : theSpots_) {
if (!withHalo && !spot.isCore())
continue;
math::XYZPoint local = trans_(Point(spot.row()[0], spot.row()[1], spot.row()[2]));
if (local.Perp2() > radius2)
continue;
energyPerLayer[spot.layer()] += spot.energy();
layers.insert(spot.layer());
if (spot.detId().det() == DetId::HGCalEE or spot.subdet() == HGCEE) {
energyEE += spot.energy();
} else if (spot.detId().det() == DetId::HGCalHSi or spot.subdet() == HGCHEF) {
energyFH += spot.energy();
} else if (spot.detId().det() == DetId::HGCalHSc or spot.subdet() == HGCHEB) {
energyBH += spot.energy();
}
}
return LongDeps(radius, energyPerLayer, energyEE, energyFH, energyBH, layers);
}
void EGammaPCAHelper::printHits(float radius) const {
unsigned nSpots = theSpots_.size();
float radius2 = radius * radius;
for (unsigned i = 0; i < nSpots; ++i) {
Spot spot(theSpots_[i]);
math::XYZPoint local = trans_(Point(spot.row()[0], spot.row()[1], spot.row()[2]));
if (local.Perp2() < radius2) {
std::cout << i << " " << theSpots_[i].detId().rawId() << " " << theSpots_[i].layer() << " "
<< theSpots_[i].energy() << " " << theSpots_[i].isCore();
std::cout << " " << std::sqrt(local.Perp2()) << std::endl;
}
}
}
float EGammaPCAHelper::findZFirstLayer(const LongDeps& ld) const {
unsigned int firstLayer = 0;
for (unsigned il = 1; il <= maxlayer_; ++il) {
if (ld.energyPerLayer()[il] > 0.) {
firstLayer = il;
break;
}
}
// Make dummy DetId to get abs(z) for layer
return recHitTools_->getPositionLayer(firstLayer).z();
}
float EGammaPCAHelper::clusterDepthCompatibility(const LongDeps& ld,
float& measuredDepth,
float& expectedDepth,
float& expectedSigma) {
expectedDepth = -999.;
expectedSigma = -999.;
measuredDepth = -999.;
if (!checkIteration())
return -999.;
float z = findZFirstLayer(ld);
math::XYZVector dir = axis_.unit();
measuredDepth = std::abs((z - std::abs(barycenter_.z())) / dir.z());
return showerDepth_.getClusterDepthCompatibility(measuredDepth, ld.energyEE(), expectedDepth, expectedSigma);
}
| 4,723 |
364 | package ca.uhn.fhir.interceptor.executor;
/*-
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2021 Smile CDR, Inc.
* %%
* 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.
* #L%
*/
import ca.uhn.fhir.interceptor.api.Hook;
import ca.uhn.fhir.interceptor.api.HookParams;
import ca.uhn.fhir.interceptor.api.IAnonymousInterceptor;
import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
import ca.uhn.fhir.interceptor.api.IInterceptorService;
import ca.uhn.fhir.interceptor.api.Interceptor;
import ca.uhn.fhir.interceptor.api.Pointcut;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang3.Validate;
import java.lang.reflect.Method;
import java.util.Optional;
public class InterceptorService extends BaseInterceptorService<Pointcut> implements IInterceptorService, IInterceptorBroadcaster {
/**
* Constructor which uses a default name of "default"
*/
public InterceptorService() {
this("default");
}
/**
* Constructor
*
* @param theName The name for this registry (useful for troubleshooting)
*/
public InterceptorService(String theName) {
super(theName);
}
@Override
protected Optional<HookDescriptor> scanForHook(Method nextMethod) {
return findAnnotation(nextMethod, Hook.class).map(t -> new HookDescriptor(t.value(), t.order()));
}
@Override
@VisibleForTesting
public void registerAnonymousInterceptor(Pointcut thePointcut, IAnonymousInterceptor theInterceptor) {
registerAnonymousInterceptor(thePointcut, Interceptor.DEFAULT_ORDER, theInterceptor);
}
@Override
public void registerAnonymousInterceptor(Pointcut thePointcut, int theOrder, IAnonymousInterceptor theInterceptor) {
Validate.notNull(thePointcut);
Validate.notNull(theInterceptor);
BaseInvoker invoker = new AnonymousLambdaInvoker(thePointcut, theInterceptor, theOrder);
registerAnonymousInterceptor(thePointcut, theInterceptor, invoker);
}
private class AnonymousLambdaInvoker extends BaseInvoker {
private final IAnonymousInterceptor myHook;
private final Pointcut myPointcut;
public AnonymousLambdaInvoker(Pointcut thePointcut, IAnonymousInterceptor theHook, int theOrder) {
super(theHook, theOrder);
myHook = theHook;
myPointcut = thePointcut;
}
@Override
Object invoke(HookParams theParams) {
myHook.invoke(myPointcut, theParams);
return true;
}
}
}
| 920 |
378 | <reponame>xinkang/Super4PCS<filename>src/super4pcs/algorithms/super4pcs.h<gh_stars>100-1000
// Copyright 2014 <NAME>
//
// 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.
//
// -------------------------------------------------------------------------- //
//
// Authors: <NAME>, <NAME>
//
// An implementation of the Super 4-points Congruent Sets (Super 4PCS)
// algorithm presented in:
//
// Super 4PCS: Fast Global Pointcloud Registration via Smart Indexing
// <NAME>, <NAME>, <NAME>
// Symposium on Geometry Processing 2014.
//
// Data acquisition in large-scale scenes regularly involves accumulating
// information across multiple scans. A common approach is to locally align scan
// pairs using Iterative Closest Point (ICP) algorithm (or its variants), but
// requires static scenes and small motion between scan pairs. This prevents
// accumulating data across multiple scan sessions and/or different acquisition
// modalities (e.g., stereo, depth scans). Alternatively, one can use a global
// registration algorithm allowing scans to be in arbitrary initial poses. The
// state-of-the-art global registration algorithm, 4PCS, however has a quadratic
// time complexity in the number of data points. This vastly limits its
// applicability to acquisition of large environments. We present Super 4PCS for
// global pointcloud registration that is optimal, i.e., runs in linear time (in
// the number of data points) and is also output sensitive in the complexity of
// the alignment problem based on the (unknown) overlap across scan pairs.
// Technically, we map the algorithm as an 'instance problem' and solve it
// efficiently using a smart indexing data organization. The algorithm is
// simple, memory-efficient, and fast. We demonstrate that Super 4PCS results in
// significant speedup over alternative approaches and allows unstructured
// efficient acquisition of scenes at scales previously not possible. Complete
// source code and datasets are available for research use at
// http://geometry.cs.ucl.ac.uk/projects/2014/super4PCS/.
#ifndef _SUPER4PCS_ALGO_SUPER4PCS_H_
#define _SUPER4PCS_ALGO_SUPER4PCS_H_
#include "super4pcs/algorithms/match4pcsBase.h"
#include "super4pcs/algorithms/pairCreationFunctor.h"
namespace GlobalRegistration {
/// Class for the computation of the 4PCS algorithm.
class MatchSuper4PCS : public Match4PCSBase {
public:
using Base = Match4PCSBase;
using Scalar = typename Base::Scalar;
using PairsVector = typename Base::PairsVector;
explicit MatchSuper4PCS(const Match4PCSOptions& options,
const Utils::Logger &logger);
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
~MatchSuper4PCS();
private:
/// Private data contains parameters and internal variables that are computed
/// and change during the match computation. All parameters have default
/// values.
/// Internal data members.
mutable PairCreationFunctor<Scalar> pcfunctor_;
protected:
/// Constructs pairs of points in Q, corresponding to a single pair in the
/// in basein P.
/// @param [in] pair_distance The distance between the pairs in P that we have
/// to match in the pairs we select from Q.
/// @param [in] pair_normal_distance The angle between the normals of the pair
/// in P.
/// @param [in] pair_distance_epsilon Tolerance on the pair distance. We allow
/// candidate pair in Q to have distance of
/// pair_distance+-pair_distance_epsilon.
/// @param [in] base_point1 The index of the first point in P.
/// @param [in] base_point2 The index of the second point in P.
/// @param [out] pairs A set of pairs in Q that match the pair in P with
/// respect to distance and normals, up to the given tolerance.
void
ExtractPairs(
Scalar pair_distance,
Scalar pair_normals_angle,
Scalar pair_distance_epsilon,
int base_point1,
int base_point2,
PairsVector* pairs) const override;
/// Finds congruent candidates in the set Q, given the invariants and threshold
/// distances. Returns true if a non empty set can be found, false otherwise.
/// @param invariant1 [in] The first invariant corresponding to the set P_pairs
/// of pairs, previously extracted from Q.
/// @param invariant2 [in] The second invariant corresponding to the set
/// Q_pairs of pairs, previously extracted from Q.
/// @param [in] distance_threshold1 The distance for verification.
/// @param [in] distance_threshold2 The distance for matching middle points due
/// to the invariants (See the paper for e1, e2).
/// @param [in] P_pairs The first set of pairs.
/// @param [in] Q_pairs The second set of pairs.
/// @param [out] quadrilaterals The set of congruent quadrilateral. In fact,
/// it's a super set from which we extract the real congruent set.
bool FindCongruentQuadrilaterals(
Scalar invariant1,
Scalar invariant2,
Scalar distance_threshold1,
Scalar distance_threshold2,
const PairsVector& P_pairs,
const PairsVector& Q_pairs,
std::vector<Quadrilateral>* quadrilaterals) const override;
/// Initializes the data structures and needed values before the match
/// computation.
/// @param [in] point_P First input set.
/// @param [in] point_Q Second input set.
/// expected to be in the inliers.
void Initialize(const std::vector<Point3D>& P,
const std::vector<Point3D>& Q) override;
};
} /// namespace Super4PCS
#endif /// _4PCS_H_
| 1,787 |
301 | <gh_stars>100-1000
"""
Functionality for skorch-based training.
"""
from .losses import CroppedLoss, mixup_criterion, TimeSeriesLoss
from .scoring import (CroppedTrialEpochScoring, PostEpochTrainScoring,
CroppedTimeSeriesEpochScoring, trial_preds_from_window_preds, predict_trials)
| 116 |
25,200 | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "matrix.h"
namespace fasttext {
Matrix::Matrix() : m_(0), n_(0) {}
Matrix::Matrix(int64_t m, int64_t n) : m_(m), n_(n) {}
int64_t Matrix::size(int64_t dim) const {
assert(dim == 0 || dim == 1);
if (dim == 0) {
return m_;
}
return n_;
}
} // namespace fasttext
| 180 |
348 | <gh_stars>100-1000
"""Search implementation using a database of WiFi networks."""
from collections import defaultdict
from ichnaea.api.locate.constants import (
MAX_WIFI_CLUSTER_METERS,
MAX_WIFIS_IN_CLUSTER,
WIFI_MAX_ACCURACY,
WIFI_MIN_ACCURACY,
)
from ichnaea.api.locate.mac import (
aggregate_cluster_position,
cluster_networks,
query_macs,
)
from ichnaea.api.locate.result import (
Position,
PositionResultList,
Region,
RegionResultList,
)
from ichnaea.api.locate.score import station_score
from ichnaea.geocode import GEOCODER
from ichnaea.models import WifiShard
from ichnaea.models.constants import MIN_WIFI_SIGNAL
from ichnaea import util
class WifiPositionMixin(object):
"""
A WifiPositionMixin implements a position search using
the WiFi models and a series of clustering algorithms.
"""
raven_client = None
result_list = PositionResultList
result_type = Position
def should_search_wifi(self, query, results):
return bool(query.wifi)
def search_wifi(self, query):
results = self.result_list()
wifis = query_macs(query, query.wifi, self.raven_client, WifiShard)
for cluster in cluster_networks(
wifis,
query.wifi,
min_radius=WIFI_MIN_ACCURACY,
min_signal=MIN_WIFI_SIGNAL,
max_distance=MAX_WIFI_CLUSTER_METERS,
):
result = aggregate_cluster_position(
cluster,
self.result_type,
"wifi",
max_networks=MAX_WIFIS_IN_CLUSTER,
min_accuracy=WIFI_MIN_ACCURACY,
max_accuracy=WIFI_MAX_ACCURACY,
)
results.add(result)
return results
class WifiRegionMixin(object):
"""
A WifiRegionMixin implements a region search using our wifi data.
"""
raven_client = None
result_list = RegionResultList
result_type = Region
def should_search_wifi(self, query, results):
return bool(query.wifi)
def search_wifi(self, query):
results = self.result_list()
now = util.utcnow()
regions = defaultdict(int)
wifis = query_macs(query, query.wifi, self.raven_client, WifiShard)
for wifi in wifis:
regions[wifi.region] += station_score(wifi, now)
for code, score in regions.items():
region = GEOCODER.region_for_code(code)
if region:
results.add(
self.result_type(
region_code=code,
region_name=region.name,
accuracy=region.radius,
score=score,
)
)
return results
| 1,325 |
2,863 | package spock.lang;
import org.spockframework.runtime.extension.ExtensionAnnotation;
import org.spockframework.runtime.extension.builtin.ResourceLockExtension;
import org.spockframework.runtime.model.parallel.ResourceAccessMode;
import org.spockframework.util.Beta;
import java.lang.annotation.*;
/**
* Allows to control access to a shared resource.
*
* If applied on class-level, the lock will be on the class,
* covering shared fields and {@code setupSpec}/{@code cleanupSpec}.
* This will also cause all features to run on the same thread
* as the Specification.
*
* @see Isolated
* @see Execution
*
* @since 2.0
*/
@Beta
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@ExtensionAnnotation(ResourceLockExtension.class)
@Repeatable(ResourceLock.Container.class)
public @interface ResourceLock {
/**
* The key identifying the resource.
*
* @see org.spockframework.runtime.model.parallel.Resources for a list of standard resources
* @return the key
*/
String value();
/**
* Controls the access mode of the resource.
* @return mode to use
*/
ResourceAccessMode mode() default ResourceAccessMode.READ_WRITE;
@Beta
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface Container {
ResourceLock[] value();
}
}
| 407 |
678 | <filename>WeChat-Headers/MMDumpReportData.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
@class NSMutableArray;
@interface MMDumpReportData : NSObject
{
NSMutableArray *m_uploadFilesArray;
unsigned long long m_dumpType;
}
@property(nonatomic) unsigned long long m_dumpType; // @synthesize m_dumpType;
@property(retain, nonatomic) NSMutableArray *m_uploadFilesArray; // @synthesize m_uploadFilesArray;
- (void).cxx_destruct;
@end
| 207 |
640 | <filename>books_and_notes/professional_courses/computer_organization_and_architecture/sources/hw/自己动手写CPU/tools/Bin2Mem/Bin2Mem.c<gh_stars>100-1000
#include <stdlib.h>
#include <stdio.h>
char *option_invalid = NULL;
char *option_file_in = NULL;
char *option_file_out = NULL;
FILE *file_in_descriptor = NULL;
FILE *file_out_descriptor = NULL;
void exception_handler(int code) {
switch (code) {
case 0:
break;
case 10001:
printf("Error (10001): No option recognized.\n");
printf("Please specify at least one valid option.\n");
break;
case 10002:
printf("Error (10002): Invalid option: %s\n", option_invalid);
break;
case 10003:
printf("Error (10003): No input Binary file specified.\n");
break;
case 10004:
printf("Error (10004): Cannot open file: %s\n", option_file_in);
break;
case 10005:
printf("Error (10005): Cannot create file: %s\n", option_file_out);
break;
default:
break;
}
if (file_in_descriptor != NULL) {
fclose(file_in_descriptor);
}
if (file_out_descriptor != NULL) {
fclose(file_out_descriptor);
}
exit(0);
}
int main(int argc, char **argv) {
int i=0,j=0;
unsigned char temp1,temp2,temp3,temp4;
unsigned int option_flag = 0;
while (argc > 0) {
if (**argv == '-') {
(*argv) ++;
switch (**argv) {
case 'f':
option_flag |= 0x4;
argv ++;
option_file_in = *argv;
argc --;
break;
case 'o':
option_flag |= 0x8;
argv ++;
option_file_out = *argv;
argc --;
break;
default:
option_flag |= 0x1;
(*argv) --;
option_invalid = *argv;
break;
}
}
argv ++;
argc --;
}
file_in_descriptor = fopen(option_file_in, "rb");
if (file_in_descriptor == NULL) {
exception_handler(10004);
}
file_out_descriptor = fopen(option_file_out, "w");
if (file_out_descriptor == NULL) {
exception_handler(10005);
}
while (!feof(file_in_descriptor)) {
fscanf(file_in_descriptor, "%c", &temp1);
fscanf(file_in_descriptor, "%c", &temp2);
fscanf(file_in_descriptor, "%c", &temp3);
fscanf(file_in_descriptor, "%c", &temp4);
if(!feof(file_in_descriptor))
{
fprintf(file_out_descriptor, "%02x", temp1);
fprintf(file_out_descriptor, "%02x", temp2);
fprintf(file_out_descriptor, "%02x", temp3);
fprintf(file_out_descriptor, "%02x", temp4);
fprintf(file_out_descriptor, "\n");
}
}
exception_handler(0);
return 0;
}
| 1,867 |
5,166 | <reponame>iconara/aws-doc-sdk-examples
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.tags;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectTaggingRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.services.s3.model.Tagging;
import software.amazon.awssdk.services.s3.model.Tag;
import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectTaggingRequest;
public class S3Service {
private S3Client getClient() {
Region region = Region.US_WEST_2;
return S3Client.builder()
.region(region)
.build();
}
public byte[] getObjectBytes(String bucketName, String keyName) {
S3Client s3 = getClient();
try {
GetObjectRequest objectRequest = GetObjectRequest
.builder()
.key(keyName)
.bucket(bucketName)
.build();
// Return the byte[] from this object.
ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
return objectBytes.asByteArray();
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
// Returns the names of all images in the given bucket.
public List<String> listBucketObjects(String bucketName) {
S3Client s3 = getClient();
String keyName;
List<String> keys = new ArrayList<>();
try {
ListObjectsRequest listObjects = ListObjectsRequest
.builder()
.bucket(bucketName)
.build();
ListObjectsResponse res = s3.listObjects(listObjects);
List<S3Object> objects = res.contents();
for (S3Object myValue: objects) {
keyName = myValue.key();
keys.add(keyName);
}
return keys;
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
// tag assets with labels in the given list.
public void tagAssets(List myList, String bucketName) {
try {
S3Client s3 = getClient();
int len = myList.size();
String assetName = "";
String labelName = "";
String labelValue = "";
// tag all the assets in the list.
for (Object o : myList) {
//Need to get the WorkItem from each list.
List innerList = (List) o;
for (Object value : innerList) {
WorkItem workItem = (WorkItem) value;
assetName = workItem.getKey();
labelName = workItem.getName();
labelValue = workItem.getConfidence();
tagExistingObject(s3, bucketName, assetName, labelName, labelValue);
}
}
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
// This method tags an existing object.
private void tagExistingObject(S3Client s3, String bucketName, String key, String label, String LabelValue) {
try {
// First need to get existing tag set; otherwise the existing tags are overwritten.
GetObjectTaggingRequest getObjectTaggingRequest = GetObjectTaggingRequest.builder()
.bucket(bucketName)
.key(key)
.build();
GetObjectTaggingResponse response = s3.getObjectTagging(getObjectTaggingRequest);
// Get the existing immutable list - cannot modify this list.
List<Tag> existingList = response.tagSet();
ArrayList<Tag> newTagList = new ArrayList(new ArrayList<>(existingList));
// Create a new tag.
Tag myTag = Tag.builder()
.key(label)
.value(LabelValue)
.build();
// push new tag to list.
newTagList.add(myTag);
Tagging tagging = Tagging.builder()
.tagSet(newTagList)
.build();
PutObjectTaggingRequest taggingRequest = PutObjectTaggingRequest.builder()
.key(key)
.bucket(bucketName)
.tagging(tagging)
.build();
s3.putObjectTagging(taggingRequest);
System.out.println(key + " was tagged with " + label);
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
//Delete tags from the given object.
public void deleteTagFromObject(String bucketName, String key) {
try {
DeleteObjectTaggingRequest deleteObjectTaggingRequest = DeleteObjectTaggingRequest.builder()
.key(key)
.bucket(bucketName)
.build();
S3Client s3 = getClient();
s3.deleteObjectTagging(deleteObjectTaggingRequest);
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
| 3,056 |
372 | <filename>boon/src/main/java/org/boon/sort/UniversalComparator.java
/*
* Copyright 2013-2014 <NAME>
* 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.
*
* __________ _____ __ .__
* \______ \ ____ ____ ____ /\ / \ _____ | | _|__| ____ ____
* | | _// _ \ / _ \ / \ \/ / \ / \\__ \ | |/ / |/ \ / ___\
* | | ( <_> | <_> ) | \ /\ / Y \/ __ \| <| | | \/ /_/ >
* |______ /\____/ \____/|___| / \/ \____|__ (____ /__|_ \__|___| /\___ /
* \/ \/ \/ \/ \/ \//_____/
* ____. ___________ _____ ______________.___.
* | |____ ___ _______ \_ _____/ / _ \ / _____/\__ | |
* | \__ \\ \/ /\__ \ | __)_ / /_\ \ \_____ \ / | |
* /\__| |/ __ \\ / / __ \_ | \/ | \/ \ \____ |
* \________(____ /\_/ (____ / /_______ /\____|__ /_______ / / ______|
* \/ \/ \/ \/ \/ \/
*/
package org.boon.sort;
import org.boon.Exceptions;
import org.boon.Str;
import org.boon.core.reflection.fields.FieldAccess;
import org.boon.primitive.Chr;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import static org.boon.core.reflection.BeanUtils.atIndex;
/**
* Created by Richard on 3/8/14.
*/
public final class UniversalComparator implements Comparator<Object> {
final String sortBy;
final Map<String, FieldAccess> fields;
final SortType sortType;
final List<Comparator> comparators;
private final boolean byPath;
public UniversalComparator(String sortBy, Map<String, FieldAccess> fields,
SortType sortType, List<Comparator> comparators
) {
this.sortBy = sortBy;
this.fields = fields;
this.sortType = sortType;
this.comparators = comparators;
this.byPath = Str.in(Chr.array('.', '[', ']', '/'), sortBy);
}
@Override
final public int compare( Object o1, Object o2 ) {
Object value1;
Object value2;
/** Compare by this. */
if (byPath || o1 instanceof Map) {
/* Grab the values of the sort field. */
if ( sortType == SortType.ASCENDING ) {
value1 = atIndex(o1, sortBy);
value2 = atIndex(o2, sortBy);
} else {
value1 = atIndex(o2, sortBy);
value2 = atIndex(o1, sortBy);
}
}
else if ( sortBy.equals( "this" ) && o1 instanceof Comparable ) {
if ( sortType == SortType.ASCENDING ) {
value1 = o1;
value2 = o2;
} else {
value1 = o2;
value2 = o1;
}
}
else {
/* Compare by sort field. */
FieldAccess field = fields.get( sortBy );
if ( field == null ) {
Exceptions.die(Str.lines(
"The fields was null for sortBy " + sortBy,
String.format("fields = %s", fields),
String.format("Outer object type = %s", o1.getClass().getName()),
String.format("Outer object is %s", o1)
));
}
/* Grab the values of the sort field. */
if ( sortType == SortType.ASCENDING ) {
value1 = field.getValue( o1 );
value2 = field.getValue( o2 );
} else {
value1 = field.getValue( o2 );
value2 = field.getValue( o1 );
}
}
int compare = Sorting.compare(value1, value2);
if ( compare == 0 ) {
for ( Comparator comparator : comparators ) {
compare = comparator.compare( o1, o2 );
if ( compare != 0 ) {
break;
}
}
}
return compare;
}
public static Comparator universalComparator( final String sortBy, final Map<String, FieldAccess> fields,
final SortType sortType, final List<Comparator> comparators ) {
return new UniversalComparator(sortBy, fields, sortType, comparators) ;
}
}
| 2,455 |
5,169 | {
"name": "objrpc",
"version": "1.0.3",
"summary": "the gsrpc object-c injection runtimes",
"description": "A longer description of objrpc in Markdown format.\n\n* Think: Why did you write this? What is the focus? What does it do?\n* CocoaPods will be using this to generate tags, and improve search results.\n* Try to keep it short, snappy and to the point.\n* Finally, don't worry about the indent, CocoaPods strips it!",
"homepage": "http://gsrpc.github.io/",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"yayanyang": "<EMAIL>"
},
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/gsrpc/objrpc.git",
"tag": "v1.0.3"
},
"source_files": "src/**/*.{h,m}",
"public_header_files": "src/**/*.h",
"xcconfig": {
"HEADER_SEARCH_PATHS": "${PODS_ROOT}/**"
}
}
| 353 |
734 | /*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
*/
#pragma once
namespace te = tracktion_engine;
static inline const char* getInternalPluginFormatName() { return "TracktionInternal"; }
//==============================================================================
class PluginTreeBase
{
public:
virtual ~PluginTreeBase() = default;
virtual String getUniqueName() const = 0;
void addSubItem (PluginTreeBase* itm) { subitems.add (itm); }
int getNumSubItems() { return subitems.size(); }
PluginTreeBase* getSubItem (int idx) { return subitems[idx]; }
private:
OwnedArray<PluginTreeBase> subitems;
};
//==============================================================================
class PluginTreeItem : public PluginTreeBase
{
public:
PluginTreeItem (const PluginDescription&);
PluginTreeItem (const String& uniqueId, const String& name, const String& xmlType, bool isSynth, bool isPlugin);
te::Plugin::Ptr create (te::Edit&);
String getUniqueName() const override
{
if (desc.fileOrIdentifier.startsWith (te::RackType::getRackPresetPrefix()))
return desc.fileOrIdentifier;
return desc.createIdentifierString();
}
PluginDescription desc;
String xmlType;
bool isPlugin = true;
JUCE_LEAK_DETECTOR (PluginTreeItem)
};
//==============================================================================
class PluginTreeGroup : public PluginTreeBase
{
public:
PluginTreeGroup (te::Edit&, KnownPluginList::PluginTree&, te::Plugin::Type);
PluginTreeGroup (const String&);
String getUniqueName() const override { return name; }
String name;
private:
void populateFrom (KnownPluginList::PluginTree&);
void createBuiltInItems (int& num, te::Plugin::Type);
JUCE_LEAK_DETECTOR (PluginTreeGroup)
};
//==============================================================================
PluginTreeItem::PluginTreeItem (const PluginDescription& d)
: desc (d), xmlType (te::ExternalPlugin::xmlTypeName), isPlugin (true)
{
jassert (xmlType.isNotEmpty());
}
PluginTreeItem::PluginTreeItem (const String& uniqueId, const String& name,
const String& xmlType_, bool isSynth, bool isPlugin_)
: xmlType (xmlType_), isPlugin (isPlugin_)
{
jassert (xmlType.isNotEmpty());
desc.name = name;
desc.fileOrIdentifier = uniqueId;
desc.pluginFormatName = (uniqueId.endsWith ("_trkbuiltin") || xmlType == te::RackInstance::xmlTypeName)
? getInternalPluginFormatName() : String();
desc.category = xmlType;
desc.isInstrument = isSynth;
}
te::Plugin::Ptr PluginTreeItem::create (te::Edit& ed)
{
return ed.getPluginCache().createNewPlugin (xmlType, desc);
}
//==============================================================================
PluginTreeGroup::PluginTreeGroup (te::Edit& edit, KnownPluginList::PluginTree& tree, te::Plugin::Type types)
: name ("Plugins")
{
{
int num = 1;
auto builtinFolder = new PluginTreeGroup (TRANS("Builtin Plugins"));
addSubItem (builtinFolder);
builtinFolder->createBuiltInItems (num, types);
}
{
auto racksFolder = new PluginTreeGroup (TRANS("Plugin Racks"));
addSubItem (racksFolder);
racksFolder->addSubItem (new PluginTreeItem (String (te::RackType::getRackPresetPrefix()) + "-1",
TRANS("Create New Empty Rack"),
te::RackInstance::xmlTypeName, false, false));
int i = 0;
for (auto rf : edit.getRackList().getTypes())
racksFolder->addSubItem (new PluginTreeItem ("RACK__" + String (i++), rf->rackName,
te::RackInstance::xmlTypeName, false, false));
}
populateFrom (tree);
}
PluginTreeGroup::PluginTreeGroup (const String& s) : name (s)
{
jassert (name.isNotEmpty());
}
void PluginTreeGroup::populateFrom (KnownPluginList::PluginTree& tree)
{
for (auto subTree : tree.subFolders)
{
if (subTree->plugins.size() > 0 || subTree->subFolders.size() > 0)
{
auto fs = new PluginTreeGroup (subTree->folder);
addSubItem (fs);
fs->populateFrom (*subTree);
}
}
for (const auto& pd : tree.plugins)
addSubItem (new PluginTreeItem (pd));
}
template<class FilterClass>
void addInternalPlugin (PluginTreeBase& item, int& num, bool synth = false)
{
item.addSubItem (new PluginTreeItem (String (num++) + "_trkbuiltin",
TRANS (FilterClass::getPluginName()),
FilterClass::xmlTypeName, synth, false));
}
void PluginTreeGroup::createBuiltInItems (int& num, te::Plugin::Type types)
{
addInternalPlugin<te::VolumeAndPanPlugin> (*this, num);
addInternalPlugin<te::LevelMeterPlugin> (*this, num);
addInternalPlugin<te::EqualiserPlugin> (*this, num);
addInternalPlugin<te::ReverbPlugin> (*this, num);
addInternalPlugin<te::DelayPlugin> (*this, num);
addInternalPlugin<te::ChorusPlugin> (*this, num);
addInternalPlugin<te::PhaserPlugin> (*this, num);
addInternalPlugin<te::CompressorPlugin> (*this, num);
addInternalPlugin<te::PitchShiftPlugin> (*this, num);
addInternalPlugin<te::LowPassPlugin> (*this, num);
addInternalPlugin<te::MidiModifierPlugin> (*this, num);
addInternalPlugin<te::MidiPatchBayPlugin> (*this, num);
addInternalPlugin<te::PatchBayPlugin> (*this, num);
addInternalPlugin<te::AuxSendPlugin> (*this, num);
addInternalPlugin<te::AuxReturnPlugin> (*this, num);
addInternalPlugin<te::TextPlugin> (*this, num);
addInternalPlugin<te::FreezePointPlugin> (*this, num);
#if TRACKTION_ENABLE_REWIRE
addInternalPlugin<te::ReWirePlugin> (*this, num, true);
#endif
if (types == te::Plugin::Type::allPlugins)
{
addInternalPlugin<te::SamplerPlugin> (*this, num, true);
addInternalPlugin<te::FourOscPlugin> (*this, num, true);
}
addInternalPlugin<te::InsertPlugin> (*this, num);
#if ENABLE_INTERNAL_PLUGINS
for (auto& d : PluginTypeBase::getAllPluginDescriptions())
if (isPluginAuthorised (d))
addSubItem (new PluginTreeItem (d));
#endif
}
//==============================================================================
class PluginMenu : public PopupMenu
{
public:
PluginMenu() = default;
PluginMenu (PluginTreeGroup& node)
{
for (int i = 0; i < node.getNumSubItems(); ++i)
if (auto subNode = dynamic_cast<PluginTreeGroup*> (node.getSubItem (i)))
addSubMenu (subNode->name, PluginMenu (*subNode), true);
for (int i = 0; i < node.getNumSubItems(); ++i)
if (auto subType = dynamic_cast<PluginTreeItem*> (node.getSubItem (i)))
addItem (subType->getUniqueName().hashCode(), subType->desc.name, true, false);
}
static PluginTreeItem* findType (PluginTreeGroup& node, int hash)
{
for (int i = 0; i < node.getNumSubItems(); ++i)
if (auto subNode = dynamic_cast<PluginTreeGroup*> (node.getSubItem (i)))
if (auto* t = findType (*subNode, hash))
return t;
for (int i = 0; i < node.getNumSubItems(); ++i)
if (auto t = dynamic_cast<PluginTreeItem*> (node.getSubItem (i)))
if (t->getUniqueName().hashCode() == hash)
return t;
return nullptr;
}
PluginTreeItem* runMenu (PluginTreeGroup& node)
{
int res = show();
if (res == 0)
return nullptr;
return findType (node, res);
}
};
//==============================================================================
te::Plugin::Ptr showMenuAndCreatePlugin (te::Edit& edit)
{
if (auto tree = EngineHelpers::createPluginTree (edit.engine))
{
PluginTreeGroup root (edit, *tree, te::Plugin::Type::allPlugins);
PluginMenu m (root);
if (auto type = m.runMenu (root))
return type->create (edit);
}
return {};
}
//==============================================================================
ClipComponent::ClipComponent (EditViewState& evs, te::Clip::Ptr c)
: editViewState (evs), clip (c)
{
}
void ClipComponent::paint (Graphics& g)
{
g.fillAll (clip->getColour().withAlpha (0.5f));
g.setColour (Colours::black);
g.drawRect (getLocalBounds());
if (editViewState.selectionManager.isSelected (clip.get()))
{
g.setColour (Colours::red);
g.drawRect (getLocalBounds(), 2);
}
}
void ClipComponent::mouseDown (const MouseEvent&)
{
editViewState.selectionManager.selectOnly (clip.get());
}
//==============================================================================
AudioClipComponent::AudioClipComponent (EditViewState& evs, te::Clip::Ptr c)
: ClipComponent (evs, c)
{
updateThumbnail();
}
void AudioClipComponent::paint (Graphics& g)
{
ClipComponent::paint (g);
if (editViewState.drawWaveforms && thumbnail != nullptr)
drawWaveform (g, *getWaveAudioClip(), *thumbnail, Colours::black.withAlpha (0.5f),
0, getWidth(), 0, getHeight(), 0);
}
void AudioClipComponent::drawWaveform (Graphics& g, te::AudioClipBase& c, te::SmartThumbnail& thumb, Colour colour,
int left, int right, int y, int h, int xOffset)
{
auto getTimeRangeForDrawing = [this] (const int l, const int r) -> te::EditTimeRange
{
if (auto p = getParentComponent())
{
double t1 = editViewState.xToTime (l, p->getWidth());
double t2 = editViewState.xToTime (r, p->getWidth());
return { t1, t2 };
}
return {};
};
jassert (left <= right);
const auto gain = c.getGain();
const auto pan = thumb.getNumChannels() == 1 ? 0.0f : c.getPan();
const float pv = pan * gain;
const float gainL = (gain - pv);
const float gainR = (gain + pv);
const bool usesTimeStretchedProxy = c.usesTimeStretchedProxy();
const auto clipPos = c.getPosition();
auto offset = clipPos.getOffset();
auto speedRatio = c.getSpeedRatio();
g.setColour (colour);
if (usesTimeStretchedProxy)
{
const Rectangle<int> area (left + xOffset, y, right - left, h);
if (! thumb.isOutOfDate())
{
drawChannels (g, thumb, area, false,
getTimeRangeForDrawing (left, right),
c.isLeftChannelActive(), c.isRightChannelActive(),
gainL, gainR);
}
}
else if (c.getLoopLength() == 0)
{
auto region = getTimeRangeForDrawing (left, right);
auto t1 = (region.getStart() + offset) * speedRatio;
auto t2 = (region.getEnd() + offset) * speedRatio;
drawChannels (g, thumb,
{ left + xOffset, y, right - left, h },
false, { t1, t2 },
c.isLeftChannelActive(), c.isRightChannelActive(),
gainL, gainR);
}
}
void AudioClipComponent::drawChannels (Graphics& g, te::SmartThumbnail& thumb, Rectangle<int> area, bool useHighRes,
te::EditTimeRange time, bool useLeft, bool useRight,
float leftGain, float rightGain)
{
if (useLeft && useRight && thumb.getNumChannels() > 1)
{
thumb.drawChannel (g, area.removeFromTop (area.getHeight() / 2), useHighRes, time, 0, leftGain);
thumb.drawChannel (g, area, useHighRes, time, 1, rightGain);
}
else if (useLeft)
{
thumb.drawChannel (g, area, useHighRes, time, 0, leftGain);
}
else if (useRight)
{
thumb.drawChannel (g, area, useHighRes, time, 1, rightGain);
}
}
void AudioClipComponent::updateThumbnail()
{
if (auto* wac = getWaveAudioClip())
{
te::AudioFile af (wac->getAudioFile());
if (af.getFile().existsAsFile() || (! wac->usesSourceFile()))
{
if (af.isValid())
{
const te::AudioFile proxy ((wac->hasAnyTakes() && wac->isShowingTakes()) ? wac->getAudioFile() : wac->getPlaybackFile());
if (thumbnail == nullptr)
thumbnail = std::make_unique<te::SmartThumbnail> (wac->edit.engine, proxy, *this, &wac->edit);
else
thumbnail->setNewFile (proxy);
}
else
{
thumbnail = nullptr;
}
}
}
}
//==============================================================================
MidiClipComponent::MidiClipComponent (EditViewState& evs, te::Clip::Ptr c)
: ClipComponent (evs, c)
{
}
void MidiClipComponent::paint (Graphics& g)
{
ClipComponent::paint (g);
if (auto mc = getMidiClip())
{
auto& seq = mc->getSequence();
for (auto n : seq.getNotes())
{
double sBeat = mc->getStartBeat() + n->getStartBeat();
double eBeat = mc->getStartBeat() + n->getEndBeat();
auto s = editViewState.beatToTime (sBeat);
auto e = editViewState.beatToTime (eBeat);
if (auto p = getParentComponent())
{
auto t1 = (double) editViewState.timeToX (s, p->getWidth()) - getX();
auto t2 = (double) editViewState.timeToX (e, p->getWidth()) - getX();
double y = (1.0 - double (n->getNoteNumber()) / 127.0) * getHeight();
g.setColour (Colours::white.withAlpha (n->getVelocity() / 127.0f));
g.drawLine (float (t1), float (y), float (t2), float (y));
}
}
}
}
//==============================================================================
RecordingClipComponent::RecordingClipComponent (te::Track::Ptr t, EditViewState& evs)
: track (t), editViewState (evs)
{
startTimerHz (10);
initialiseThumbnailAndPunchTime();
}
void RecordingClipComponent::initialiseThumbnailAndPunchTime()
{
if (auto at = dynamic_cast<te::AudioTrack*> (track.get()))
{
for (auto* idi : at->edit.getEditInputDevices().getDevicesForTargetTrack (*at))
{
punchInTime = idi->getPunchInTime();
if (idi->getRecordingFile().exists())
thumbnail = at->edit.engine.getRecordingThumbnailManager().getThumbnailFor (idi->getRecordingFile());
}
}
}
void RecordingClipComponent::paint (Graphics& g)
{
g.fillAll (Colours::red.withAlpha (0.5f));
g.setColour (Colours::black);
g.drawRect (getLocalBounds());
if (editViewState.drawWaveforms)
drawThumbnail (g, Colours::black.withAlpha (0.5f));
}
void RecordingClipComponent::drawThumbnail (Graphics& g, Colour waveformColour) const
{
if (thumbnail == nullptr)
return;
Rectangle<int> bounds;
Range<double> times;
getBoundsAndTime (bounds, times);
auto w = bounds.getWidth();
if (w > 0 && w < 10000)
{
g.setColour (waveformColour);
thumbnail->thumb.drawChannels (g, bounds, w, times, 1.0f);
}
}
bool RecordingClipComponent::getBoundsAndTime (Rectangle<int>& bounds, Range<double>& times) const
{
auto editTimeToX = [this] (double t)
{
if (auto p = getParentComponent())
return editViewState.timeToX (t, p->getWidth()) - getX();
return 0;
};
auto xToEditTime = [this] (int x)
{
if (auto p = getParentComponent())
return editViewState.xToTime (x + getX(), p->getWidth());
return 0.0;
};
bool hasLooped = false;
auto& edit = track->edit;
if (auto epc = edit.getTransport().getCurrentPlaybackContext())
{
auto localBounds = getLocalBounds();
auto timeStarted = thumbnail->punchInTime;
auto unloopedPos = timeStarted + thumbnail->thumb.getTotalLength();
auto t1 = timeStarted;
auto t2 = unloopedPos;
if (epc->isLooping() && t2 >= epc->getLoopTimes().end)
{
hasLooped = true;
t1 = jmin (t1, epc->getLoopTimes().start);
t2 = epc->getPosition();
t1 = jmax (editViewState.viewX1.get(), t1);
t2 = jmin (editViewState.viewX2.get(), t2);
}
else if (edit.recordingPunchInOut)
{
const double in = thumbnail->punchInTime;
const double out = edit.getTransport().getLoopRange().getEnd();
t1 = jlimit (in, out, t1);
t2 = jlimit (in, out, t2);
}
bounds = localBounds.withX (jmax (localBounds.getX(), editTimeToX (t1)))
.withRight (jmin (localBounds.getRight(), editTimeToX (t2)));
auto loopRange = epc->getLoopTimes();
const double recordedTime = unloopedPos - epc->getLoopTimes().start;
const int numLoops = (int) (recordedTime / loopRange.getLength());
const Range<double> editTimes (xToEditTime (bounds.getX()),
xToEditTime (bounds.getRight()));
times = (editTimes + (numLoops * loopRange.getLength())) - timeStarted;
}
return hasLooped;
}
void RecordingClipComponent::timerCallback()
{
updatePosition();
}
void RecordingClipComponent::updatePosition()
{
auto& edit = track->edit;
if (auto epc = edit.getTransport().getCurrentPlaybackContext())
{
double t1 = punchInTime >= 0 ? punchInTime : edit.getTransport().getTimeWhenStarted();
double t2 = jmax (t1, epc->getUnloopedPosition());
if (epc->isLooping())
{
auto loopTimes = epc->getLoopTimes();
if (t2 >= loopTimes.end)
{
t1 = jmin (t1, loopTimes.start);
t2 = loopTimes.end;
}
}
else if (edit.recordingPunchInOut)
{
auto mr = edit.getTransport().getLoopRange();
auto in = mr.getStart();
auto out = mr.getEnd();
t1 = jlimit (in, out, t1);
t2 = jlimit (in, out, t2);
}
t1 = jmax (t1, editViewState.viewX1.get());
t2 = jmin (t2, editViewState.viewX2.get());
if (auto p = getParentComponent())
{
int x1 = editViewState.timeToX (t1, p->getWidth());
int x2 = editViewState.timeToX (t2, p->getWidth());
setBounds (x1, 0, x2 - x1, p->getHeight());
return;
}
}
setBounds ({});
}
//==============================================================================
TrackHeaderComponent::TrackHeaderComponent (EditViewState& evs, te::Track::Ptr t)
: editViewState (evs), track (t)
{
Helpers::addAndMakeVisible (*this, { &trackName, &armButton, &muteButton, &soloButton, &inputButton });
armButton.setColour (TextButton::buttonOnColourId, Colours::red);
muteButton.setColour (TextButton::buttonOnColourId, Colours::red);
soloButton.setColour (TextButton::buttonOnColourId, Colours::green);
trackName.setText (t->getName(), dontSendNotification);
if (auto at = dynamic_cast<te::AudioTrack*> (track.get()))
{
inputButton.onClick = [this, at]
{
PopupMenu m;
if (EngineHelpers::trackHasInput (*at))
{
bool ticked = EngineHelpers::isInputMonitoringEnabled (*at);
m.addItem (1000, "Input Monitoring", true, ticked);
m.addSeparator();
}
if (editViewState.showWaveDevices)
{
int id = 1;
for (auto instance : at->edit.getAllInputDevices())
{
if (instance->getInputDevice().getDeviceType() == te::InputDevice::waveDevice)
{
bool ticked = instance->getTargetTracks().getFirst() == at;
m.addItem (id++, instance->getInputDevice().getName(), true, ticked);
}
}
}
if (editViewState.showMidiDevices)
{
m.addSeparator();
int id = 100;
for (auto instance : at->edit.getAllInputDevices())
{
if (instance->getInputDevice().getDeviceType() == te::InputDevice::physicalMidiDevice)
{
bool ticked = instance->getTargetTracks().getFirst() == at;
m.addItem (id++, instance->getInputDevice().getName(), true, ticked);
}
}
}
int res = m.show();
if (res == 1000)
{
EngineHelpers::enableInputMonitoring (*at, ! EngineHelpers::isInputMonitoringEnabled (*at));
}
else if (res >= 100)
{
int id = 100;
for (auto instance : at->edit.getAllInputDevices())
{
if (instance->getInputDevice().getDeviceType() == te::InputDevice::physicalMidiDevice)
{
if (id == res)
instance->setTargetTrack (*at, 0, true);
id++;
}
}
}
else if (res >= 1)
{
int id = 1;
for (auto instance : at->edit.getAllInputDevices())
{
if (instance->getInputDevice().getDeviceType() == te::InputDevice::waveDevice)
{
if (id == res)
instance->setTargetTrack (*at, 0, true);
id++;
}
}
}
};
armButton.onClick = [this, at]
{
EngineHelpers::armTrack (*at, ! EngineHelpers::isTrackArmed (*at));
armButton.setToggleState (EngineHelpers::isTrackArmed (*at), dontSendNotification);
};
muteButton.onClick = [at] { at->setMute (! at->isMuted (false)); };
soloButton.onClick = [at] { at->setSolo (! at->isSolo (false)); };
armButton.setToggleState (EngineHelpers::isTrackArmed (*at), dontSendNotification);
}
else
{
armButton.setVisible (false);
muteButton.setVisible (false);
soloButton.setVisible (false);
}
track->state.addListener (this);
inputsState = track->edit.state.getChildWithName (te::IDs::INPUTDEVICES);
inputsState.addListener (this);
valueTreePropertyChanged (track->state, te::IDs::mute);
valueTreePropertyChanged (track->state, te::IDs::solo);
valueTreePropertyChanged (inputsState, te::IDs::targetIndex);
}
TrackHeaderComponent::~TrackHeaderComponent()
{
track->state.removeListener (this);
}
void TrackHeaderComponent::valueTreePropertyChanged (juce::ValueTree& v, const juce::Identifier& i)
{
if (te::TrackList::isTrack (v))
{
if (i == te::IDs::mute)
muteButton.setToggleState ((bool)v[i], dontSendNotification);
else if (i == te::IDs::solo)
soloButton.setToggleState ((bool)v[i], dontSendNotification);
}
else if (v.hasType (te::IDs::INPUTDEVICES)
|| v.hasType (te::IDs::INPUTDEVICE)
|| v.hasType (te::IDs::INPUTDEVICEDESTINATION))
{
if (auto at = dynamic_cast<te::AudioTrack*> (track.get()))
{
armButton.setEnabled (EngineHelpers::trackHasInput (*at));
armButton.setToggleState (EngineHelpers::isTrackArmed (*at), dontSendNotification);
}
}
}
void TrackHeaderComponent::paint (Graphics& g)
{
g.setColour (Colours::grey);
g.fillRect (getLocalBounds().withTrimmedRight (2));
if (editViewState.selectionManager.isSelected (track.get()))
{
g.setColour (Colours::red);
g.drawRect (getLocalBounds().withTrimmedRight (-4), 2);
}
}
void TrackHeaderComponent::mouseDown (const MouseEvent&)
{
editViewState.selectionManager.selectOnly (track.get());
}
void TrackHeaderComponent::resized()
{
auto r = getLocalBounds().reduced (4);
trackName.setBounds (r.removeFromTop (r.getHeight() / 2));
int w = r.getHeight();
inputButton.setBounds (r.removeFromLeft (w));
r.removeFromLeft (2);
armButton.setBounds (r.removeFromLeft (w));
r.removeFromLeft (2);
muteButton.setBounds (r.removeFromLeft (w));
r.removeFromLeft (2);
soloButton.setBounds (r.removeFromLeft (w));
r.removeFromLeft (2);
}
//==============================================================================
PluginComponent::PluginComponent (EditViewState& evs, te::Plugin::Ptr p)
: editViewState (evs), plugin (p)
{
setButtonText (plugin->getName().substring (0, 1));
}
PluginComponent::~PluginComponent()
{
}
void PluginComponent::clicked (const ModifierKeys& modifiers)
{
editViewState.selectionManager.selectOnly (plugin.get());
if (modifiers.isPopupMenu())
{
PopupMenu m;
m.addItem ("Delete", [this] { plugin->deleteFromParent(); });
m.showAt (this);
}
else
{
plugin->showWindowExplicitly();
}
}
//==============================================================================
TrackFooterComponent::TrackFooterComponent (EditViewState& evs, te::Track::Ptr t)
: editViewState (evs), track (t)
{
addAndMakeVisible (addButton);
buildPlugins();
track->state.addListener (this);
addButton.onClick = [this]
{
if (auto plugin = showMenuAndCreatePlugin (track->edit))
track->pluginList.insertPlugin (plugin, 0, &editViewState.selectionManager);
};
}
TrackFooterComponent::~TrackFooterComponent()
{
track->state.removeListener (this);
}
void TrackFooterComponent::valueTreeChildAdded (juce::ValueTree&, juce::ValueTree& c)
{
if (c.hasType (te::IDs::PLUGIN))
markAndUpdate (updatePlugins);
}
void TrackFooterComponent::valueTreeChildRemoved (juce::ValueTree&, juce::ValueTree& c, int)
{
if (c.hasType (te::IDs::PLUGIN))
markAndUpdate (updatePlugins);
}
void TrackFooterComponent::valueTreeChildOrderChanged (juce::ValueTree&, int, int)
{
markAndUpdate (updatePlugins);
}
void TrackFooterComponent::paint (Graphics& g)
{
g.setColour (Colours::grey);
g.fillRect (getLocalBounds().withTrimmedLeft (2));
if (editViewState.selectionManager.isSelected (track.get()))
{
g.setColour (Colours::red);
g.drawRect (getLocalBounds().withTrimmedLeft (-4), 2);
}
}
void TrackFooterComponent::mouseDown (const MouseEvent&)
{
editViewState.selectionManager.selectOnly (track.get());
}
void TrackFooterComponent::resized()
{
auto r = getLocalBounds().reduced (4);
const int cx = 21;
addButton.setBounds (r.removeFromLeft (cx).withSizeKeepingCentre (cx, cx));
r.removeFromLeft (6);
for (auto p : plugins)
{
p->setBounds (r.removeFromLeft (cx).withSizeKeepingCentre (cx, cx));
r.removeFromLeft (2);
}
}
void TrackFooterComponent::handleAsyncUpdate()
{
if (compareAndReset (updatePlugins))
buildPlugins();
}
void TrackFooterComponent::buildPlugins()
{
plugins.clear();
for (auto plugin : track->pluginList)
{
auto p = new PluginComponent (editViewState, plugin);
addAndMakeVisible (p);
plugins.add (p);
}
resized();
}
//==============================================================================
TrackComponent::TrackComponent (EditViewState& evs, te::Track::Ptr t)
: editViewState (evs), track (t)
{
track->state.addListener (this);
track->edit.getTransport().addChangeListener (this);
markAndUpdate (updateClips);
}
TrackComponent::~TrackComponent()
{
track->state.removeListener (this);
track->edit.getTransport().removeChangeListener (this);
}
void TrackComponent::paint (Graphics& g)
{
g.fillAll (Colours::grey);
if (editViewState.selectionManager.isSelected (track.get()))
{
g.setColour (Colours::red);
auto rc = getLocalBounds();
if (editViewState.showHeaders) rc = rc.withTrimmedLeft (-4);
if (editViewState.showFooters) rc = rc.withTrimmedRight (-4);
g.drawRect (rc, 2);
}
}
void TrackComponent::mouseDown (const MouseEvent&)
{
editViewState.selectionManager.selectOnly (track.get());
}
void TrackComponent::changeListenerCallback (ChangeBroadcaster*)
{
markAndUpdate (updateRecordClips);
}
void TrackComponent::valueTreePropertyChanged (juce::ValueTree& v, const juce::Identifier& i)
{
if (te::Clip::isClipState (v))
{
if (i == te::IDs::start
|| i == te::IDs::length)
{
markAndUpdate (updatePositions);
}
}
}
void TrackComponent::valueTreeChildAdded (juce::ValueTree&, juce::ValueTree& c)
{
if (te::Clip::isClipState (c))
markAndUpdate (updateClips);
}
void TrackComponent::valueTreeChildRemoved (juce::ValueTree&, juce::ValueTree& c, int)
{
if (te::Clip::isClipState (c))
markAndUpdate (updateClips);
}
void TrackComponent::valueTreeChildOrderChanged (juce::ValueTree& v, int a, int b)
{
if (te::Clip::isClipState (v.getChild (a)))
markAndUpdate (updatePositions);
else if (te::Clip::isClipState (v.getChild (b)))
markAndUpdate (updatePositions);
}
void TrackComponent::handleAsyncUpdate()
{
if (compareAndReset (updateClips))
buildClips();
if (compareAndReset (updatePositions))
resized();
if (compareAndReset (updateRecordClips))
buildRecordClips();
}
void TrackComponent::resized()
{
for (auto cc : clips)
{
auto& c = cc->getClip();
auto pos = c.getPosition();
int x1 = editViewState.timeToX (pos.getStart(), getWidth());
int x2 = editViewState.timeToX (pos.getEnd(), getWidth());
cc->setBounds (x1, 0, x2 - x1, getHeight());
}
}
void TrackComponent::buildClips()
{
clips.clear();
if (auto ct = dynamic_cast<te::ClipTrack*> (track.get()))
{
for (auto c : ct->getClips())
{
ClipComponent* cc = nullptr;
if (dynamic_cast<te::WaveAudioClip*> (c))
cc = new AudioClipComponent (editViewState, c);
else if (dynamic_cast<te::MidiClip*> (c))
cc = new MidiClipComponent (editViewState, c);
else
cc = new ClipComponent (editViewState, c);
clips.add (cc);
addAndMakeVisible (cc);
}
}
resized();
}
void TrackComponent::buildRecordClips()
{
bool needed = false;
if (track->edit.getTransport().isRecording())
{
for (auto in : track->edit.getAllInputDevices())
{
if (in->isRecordingActive() && track == in->getTargetTracks().getFirst())
{
needed = true;
break;
}
}
}
if (needed)
{
recordingClip = std::make_unique<RecordingClipComponent> (track, editViewState);
addAndMakeVisible (*recordingClip);
}
else
{
recordingClip = nullptr;
}
}
//==============================================================================
PlayheadComponent::PlayheadComponent (te::Edit& e , EditViewState& evs)
: edit (e), editViewState (evs)
{
startTimerHz (30);
}
void PlayheadComponent::paint (Graphics& g)
{
g.setColour (Colours::yellow);
g.drawRect (xPosition, 0, 2, getHeight());
}
bool PlayheadComponent::hitTest (int x, int)
{
if (std::abs (x - xPosition) <= 3)
return true;
return false;
}
void PlayheadComponent::mouseDown (const MouseEvent&)
{
edit.getTransport().setUserDragging (true);
}
void PlayheadComponent::mouseUp (const MouseEvent&)
{
edit.getTransport().setUserDragging (false);
}
void PlayheadComponent::mouseDrag (const MouseEvent& e)
{
double t = editViewState.xToTime (e.x, getWidth());
edit.getTransport().setCurrentPosition (t);
timerCallback();
}
void PlayheadComponent::timerCallback()
{
if (firstTimer)
{
// On Linux, don't set the mouse cursor until after the Component has appeared
firstTimer = false;
setMouseCursor (MouseCursor::LeftRightResizeCursor);
}
int newX = editViewState.timeToX (edit.getTransport().getCurrentPosition(), getWidth());
if (newX != xPosition)
{
repaint (jmin (newX, xPosition) - 1, 0, jmax (newX, xPosition) - jmin (newX, xPosition) + 3, getHeight());
xPosition = newX;
}
}
//==============================================================================
EditComponent::EditComponent (te::Edit& e, te::SelectionManager& sm)
: edit (e), editViewState (e, sm)
{
edit.state.addListener (this);
editViewState.selectionManager.addChangeListener (this);
addAndMakeVisible (playhead);
markAndUpdate (updateTracks);
}
EditComponent::~EditComponent()
{
editViewState.selectionManager.removeChangeListener (this);
edit.state.removeListener (this);
}
void EditComponent::valueTreePropertyChanged (juce::ValueTree& v, const juce::Identifier& i)
{
if (v.hasType (IDs::EDITVIEWSTATE))
{
if (i == IDs::viewX1
|| i == IDs::viewX2
|| i == IDs::viewY)
{
markAndUpdate (updateZoom);
}
else if (i == IDs::showHeaders
|| i == IDs::showFooters)
{
markAndUpdate (updateZoom);
}
else if (i == IDs::drawWaveforms)
{
repaint();
}
}
}
void EditComponent::valueTreeChildAdded (juce::ValueTree&, juce::ValueTree& c)
{
if (te::TrackList::isTrack (c))
markAndUpdate (updateTracks);
}
void EditComponent::valueTreeChildRemoved (juce::ValueTree&, juce::ValueTree& c, int)
{
if (te::TrackList::isTrack (c))
markAndUpdate (updateTracks);
}
void EditComponent::valueTreeChildOrderChanged (juce::ValueTree& v, int a, int b)
{
if (te::TrackList::isTrack (v.getChild (a)))
markAndUpdate (updateTracks);
else if (te::TrackList::isTrack (v.getChild (b)))
markAndUpdate (updateTracks);
}
void EditComponent::handleAsyncUpdate()
{
if (compareAndReset (updateTracks))
buildTracks();
if (compareAndReset (updateZoom))
resized();
}
void EditComponent::resized()
{
jassert (headers.size() == tracks.size());
const int trackHeight = 50, trackGap = 2;
const int headerWidth = editViewState.showHeaders ? 150 : 0;
const int footerWidth = editViewState.showFooters ? 150 : 0;
playhead.setBounds (getLocalBounds().withTrimmedLeft (headerWidth).withTrimmedRight (footerWidth));
int y = roundToInt (editViewState.viewY.get());
for (int i = 0; i < jmin (headers.size(), tracks.size()); i++)
{
auto h = headers[i];
auto t = tracks[i];
auto f = footers[i];
h->setBounds (0, y, headerWidth, trackHeight);
t->setBounds (headerWidth, y, getWidth() - headerWidth - footerWidth, trackHeight);
f->setBounds (getWidth() - footerWidth, y, footerWidth, trackHeight);
y += trackHeight + trackGap;
}
for (auto t : tracks)
t->resized();
}
void EditComponent::buildTracks()
{
tracks.clear();
headers.clear();
footers.clear();
for (auto t : getAllTracks (edit))
{
TrackComponent* c = nullptr;
if (t->isTempoTrack())
{
if (editViewState.showGlobalTrack)
c = new TrackComponent (editViewState, t);
}
else if (t->isMarkerTrack())
{
if (editViewState.showMarkerTrack)
c = new TrackComponent (editViewState, t);
}
else if (t->isChordTrack())
{
if (editViewState.showChordTrack)
c = new TrackComponent (editViewState, t);
}
else if (t->isArrangerTrack())
{
if (editViewState.showArrangerTrack)
c = new TrackComponent (editViewState, t);
}
else
{
c = new TrackComponent (editViewState, t);
}
if (c != nullptr)
{
tracks.add (c);
addAndMakeVisible (c);
auto h = new TrackHeaderComponent (editViewState, t);
headers.add (h);
addAndMakeVisible (h);
auto f = new TrackFooterComponent (editViewState, t);
footers.add (f);
addAndMakeVisible (f);
}
}
playhead.toFront (false);
resized();
}
| 16,791 |
15,337 | <reponame>fairhopeweb/saleor
# Generated by Django 3.2.2 on 2021-06-17 16:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("discount", "0025_auto_20210506_0831"),
]
operations = [
migrations.AddField(
model_name="voucher",
name="only_for_staff",
field=models.BooleanField(default=False),
),
]
| 193 |
1,790 | /*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, 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
*
* This software 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.cloudera.oryx.app.classreg.predict;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.cloudera.oryx.app.classreg.example.FeatureType;
import com.cloudera.oryx.common.OryxTest;
/**
* Tests {@link WeightedPrediction}.
*/
public final class WeightedPredictionTest extends OryxTest {
@Test
public void testNumericVote() {
List<NumericPrediction> predictions = Arrays.asList(
new NumericPrediction(1.0, 1),
new NumericPrediction(3.0, 2),
new NumericPrediction(6.0, 3)
);
double[] weights = {1.0, 1.0, 1.0};
NumericPrediction vote =
(NumericPrediction) WeightedPrediction.voteOnFeature(predictions, weights);
assertEquals(FeatureType.NUMERIC, vote.getFeatureType());
assertEquals(10.0 /3.0, vote.getPrediction());
}
@Test
public void testNumericVoteWeighted() {
List<NumericPrediction> predictions = Arrays.asList(
new NumericPrediction(1.0, 1),
new NumericPrediction(3.0, 2),
new NumericPrediction(6.0, 3)
);
double[] weights = {3.0, 2.0, 1.0};
NumericPrediction vote =
(NumericPrediction) WeightedPrediction.voteOnFeature(predictions, weights);
assertEquals(FeatureType.NUMERIC, vote.getFeatureType());
assertEquals(15.0 / 6.0, vote.getPrediction());
}
@Test
public void testCategoricalVote() {
List<CategoricalPrediction> predictions = Arrays.asList(
new CategoricalPrediction(new int[]{0, 1, 2}),
new CategoricalPrediction(new int[]{6, 2, 0}),
new CategoricalPrediction(new int[]{0, 2, 0})
);
double[] weights = {1.0, 1.0, 1.0};
CategoricalPrediction vote =
(CategoricalPrediction) WeightedPrediction.voteOnFeature(predictions, weights);
assertEquals(FeatureType.CATEGORICAL, vote.getFeatureType());
assertEquals(1, vote.getMostProbableCategoryEncoding());
}
@Test
public void testCategoricalVoteWeighted() {
List<CategoricalPrediction> predictions = Arrays.asList(
new CategoricalPrediction(new int[]{0, 1, 2}),
new CategoricalPrediction(new int[]{6, 2, 0}),
new CategoricalPrediction(new int[]{0, 2, 0})
);
double[] weights = {1.0, 10.0, 1.0};
CategoricalPrediction vote =
(CategoricalPrediction) WeightedPrediction.voteOnFeature(predictions, weights);
assertEquals(FeatureType.CATEGORICAL, vote.getFeatureType());
assertEquals(0, vote.getMostProbableCategoryEncoding());
}
}
| 1,143 |
891 | <gh_stars>100-1000
/*
* Copyright (C) 2008-2010 <NAME>
*
* This file is part of the JNR project.
*
* 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 jnr.ffi;
import java.util.Map;
/**
* Options that apply to a library
*/
public enum LibraryOption {
/**
* Function calls should save the errno/last error after the call.
* This option can be overridden on individual methods by use of the
* {@link jnr.ffi.annotations.IgnoreError} annotation.
*
* @see LibraryLoader#saveError(Map, boolean, boolean)
*/
SaveError,
/**
* Function calls should NOT save the errno/last error after the call.
* This option can be overridden on individual methods by use of the
* {@link jnr.ffi.annotations.SaveError} annotation.
*
* @see LibraryLoader#saveError(Map, boolean, boolean)
*/
IgnoreError,
/**
* A type mapper which maps java types to native types is present.
*/
TypeMapper,
/**
* A function mapper which maps from java function names to native function names.
*/
FunctionMapper,
/**
* The type of calling convention.
*
* @see CallingConvention
*/
CallingConvention,
/**
* Load the library into memory immediately, instead of lazily loading it
*/
LoadNow,
/**
* Relevant for GNU/Linux {@link Platform.Linux} only
*
* Prefer custom paths over system paths when loading a library, even if the custom path has a lower version.
*
* By default JNR-FFI will choose the library of the desired name with the highest version, whether in the custom
* paths or the system default paths.
*
* This can be a problem if you are distributing your own library for example {@code libfoo.so} and the system
* paths <i>happen</i> to have a {@code libfoo.so.4} for example, in which case JNR-FFI will prefer the
* higher version despite your explicit custom paths.
*
* By using this option, JNR-FFI will know to prefer the custom paths, even if they have a lower version, this
* ensures consistent behaviors across environments.
*/
PreferCustomPaths
}
| 872 |
1,673 |
/*
!!DESCRIPTION!! forgetting to emit labels
!!ORIGIN!! Testsuite
!!LICENCE!! Public Domain
*/
/*
http://www.cc65.org/mailarchive/2014-10/11673.html
http://www.cc65.org/mailarchive/2014-10/11675.html
*/
#include <stdlib.h>
#include <stdio.h>
struct udata {
int (*u_sigvec[16])();
int u_argn;
int u_argn1;
};
struct udata udata;
#define sig (int)udata.u_argn
#define func (int (*)())udata.u_argn1
int _signal(void)
{
if (func != 0) {
goto nogood;
}
udata.u_sigvec[sig] = func;
return 0;
nogood:
return (-1);
}
int main(int n,char **args)
{
_signal();
printf("it works\n");
return 0;
}
| 376 |
5,169 | {
"name": "Crex",
"version": "0.1.0",
"summary": "Crex is an library for simple and type safe usage of Notification Center",
"description": "Crex is an library for simple and type safe usage of Notification Center. Posting extra information is so handy due to code completion.",
"homepage": "https://github.com/rogowskimark/Crex",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"rogowskimark": "<EMAIL>"
},
"source": {
"git": "https://github.com/rogowskimark/Crex.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "9.3"
},
"source_files": "Crex/Classes/**/*",
"swift_version": "4.1"
}
| 255 |
2,906 | """Contributed modules for Snorkel."""
| 11 |
763 | <reponame>zabrewer/batfish
package org.batfish.datamodel.vendor_family.f5_bigip;
import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.EqualsTester;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Before;
import org.junit.Test;
/** Test of {@link Pool}. */
public final class PoolTest {
private Pool.Builder _builder;
@Before
public void setup() {
_builder =
Pool.builder()
.setDescription("d")
.addMember(PoolMember.builder().setName("n").setNode("n").setPort(1).build())
.addMonitor("n")
.setName("n");
}
@Test
public void testEquals() {
Pool obj = _builder.build();
new EqualsTester()
.addEqualityGroup(obj, obj, _builder.build())
.addEqualityGroup(_builder.setDescription(null).build())
.addEqualityGroup(_builder.setMembers(ImmutableMap.of()).build())
.addEqualityGroup(_builder.setMonitors(ImmutableList.of()).build())
.addEqualityGroup(_builder.setName("n2").build())
.addEqualityGroup(new Object())
.testEquals();
}
@Test
public void testJavaSerialization() {
Pool obj = _builder.build();
assertEquals(obj, SerializationUtils.clone(obj));
}
}
| 528 |
1,997 | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.tensorrt.engine;
import ai.djl.engine.EngineException;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.nn.AbstractBlock;
import ai.djl.tensorrt.jni.JniUtils;
import ai.djl.training.ParameterStore;
import ai.djl.util.PairList;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** {@code TrtSession} represents the TensorRT's execution context. */
public class TrtSession extends AbstractBlock implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(JniUtils.class);
private long session;
private NDList inputBindings;
private NDList outputBindings;
private Shape[] outputShapes;
TrtSession(TrtNDManager manager, long modelHandle, long session) {
this.session = session;
inputNames = Arrays.asList(JniUtils.getInputNames(modelHandle));
DataType[] inputTypes = JniUtils.getInputDataTypes(modelHandle);
inputShapes = new Shape[inputTypes.length];
inputBindings = new NDList(inputTypes.length);
for (int i = 0; i < inputTypes.length; ++i) {
String inputName = inputNames.get(i);
inputShapes[i] = new Shape(JniUtils.getShape(session, inputName));
int size = Math.toIntExact(inputShapes[i].size() * inputTypes[i].getNumOfBytes());
ByteBuffer bb = manager.allocateDirect(size);
JniUtils.bind(session, inputName, bb);
NDArray array = manager.create(bb, inputShapes[i], inputTypes[i]);
array.setName(inputName);
inputBindings.add(array);
}
String[] outputNames = JniUtils.getOutputNames(modelHandle);
DataType[] outputTypes = JniUtils.getOutputDataTypes(modelHandle);
outputShapes = new Shape[outputNames.length];
outputBindings = new NDList(outputShapes.length);
for (int i = 0; i < outputShapes.length; ++i) {
outputShapes[i] = new Shape(JniUtils.getShape(session, outputNames[i]));
int size = Math.toIntExact(outputShapes[i].size() * outputTypes[i].getNumOfBytes());
ByteBuffer bb = manager.allocateDirect(size);
JniUtils.bind(session, outputNames[i], bb);
NDArray array = manager.create(bb, outputShapes[i], outputTypes[i]);
array.setName(outputNames[i]);
outputBindings.add(array);
}
if (logger.isDebugEnabled()) {
logger.debug("Model information: ");
for (int i = 0; i < inputTypes.length; ++i) {
logger.debug(
"input_{}[{}]: {}, {}",
i,
inputNames.get(i),
inputTypes[i],
inputShapes[i]);
}
for (int i = 0; i < outputTypes.length; ++i) {
logger.debug(
"output_{}[{}]: {}, {}",
i,
outputNames[i],
outputTypes[i],
outputShapes[i]);
}
}
}
/** {@inheritDoc} */
@Override
protected NDList forwardInternal(
ParameterStore parameterStore,
NDList inputs,
boolean training,
PairList<String, Object> params) {
int size = inputs.size();
if (this.inputBindings.size() != size) {
throw new EngineException(
"Unexpected number of inputs: " + size + ", expected: " + inputBindings.size());
}
for (int i = 0; i < size; ++i) {
NDArray array = inputs.get(i);
NDArray bound = inputBindings.get(i);
if (bound != array) {
if (bound.getDataType() != array.getDataType()) {
throw new EngineException(
"Unexpected input_"
+ i
+ '['
+ bound.getName()
+ "] dataType: "
+ array.getDataType()
+ ", expected: "
+ bound.getDataType());
} else if (!bound.getShape().equals(array.getShape())) {
throw new EngineException(
"Unexpected input_"
+ i
+ '['
+ bound.getName()
+ "] shape: "
+ array.getShape()
+ ", expected: "
+ bound.getShape());
}
bound.set(array.toByteBuffer());
}
}
JniUtils.runTrtModel(session);
return outputBindings;
}
/**
* Returns the input {@code NDList} that bound to TensorRT engine.
*
* @return the input {@code NDList} that bound to TensorRT engine
*/
public NDList getInputBindings() {
return inputBindings;
}
/**
* Returns the output {@code NDList} that bound to TensorRT engine.
*
* @return the output {@code NDList} that bound to TensorRT engine
*/
public NDList getOutputBindings() {
return outputBindings;
}
/** {@inheritDoc} */
@Override
public Shape[] getOutputShapes(Shape[] inputShapes) {
return outputShapes;
}
/** {@inheritDoc} */
@Override
public void close() {
JniUtils.deleteSession(session);
}
}
| 3,101 |
526 | <reponame>FreddyZeng/iOSKeyPointExploration<gh_stars>100-1000
//
// HAI_goods_attr_info.h
// haitao
//
// Created by huangchengdu on 15/12/22.
// Copyright © 2015年 上海市配夸网络科技有限公司. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface HAI_goods_attr_info : NSObject
@end
| 146 |
2,151 | <reponame>rcoscali/libcxx
#ifndef TEST_SUPPORT_FILESYSTEM_INCLUDE_HPP
#define TEST_SUPPORT_FILESYSTEM_INCLUDE_HPP
#include <ciso646>
// Test against std::filesystem for STL's other than libc++
#ifndef _LIBCPP_VERSION
#define TEST_INCLUDE_STD_FILESYSTEM
#endif
#ifdef TEST_INCLUDE_STD_FILESYSTEM
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
#endif
| 178 |
761 | /*
Copyright (c) 2016 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef IMPLICITPOINTPRIMITIVE_H
#define IMPLICITPOINTPRIMITIVE_H
#include <stdio.h>
#include <iostream>
#include "vmath.h"
class ImplicitPointPrimitive
{
public:
ImplicitPointPrimitive();
ImplicitPointPrimitive(double x, double y, double z, double r);
ImplicitPointPrimitive(vmath::vec3 p, double r);
~ImplicitPointPrimitive();
void setPosition(double x, double y, double z) { _position = vmath::vec3(x, y, z); }
void setPosition(vmath::vec3 p) { _position = p; }
void setRadius(double r) { _radius = r; _initFieldFunctionCoefficients(); }
void translate(double tx, double ty, double tz) { _position += vmath::vec3(tx, ty, tz); }
void translate(vmath::vec3 t) { _position += t; }
vmath::vec3 getPosition() { return _position; }
void getPosition(double *x, double *y, double *z) { *x = _position.x;
*y = _position.y;
*z = _position.z; }
double getRadius() { return _radius; }
double getFieldValue(double x, double y, double z) { return getFieldValue(vmath::vec3(x, y, z)); };
double getFieldValue(vmath::vec3 p);
private:
void _initFieldFunctionCoefficients();
double _evaluateFieldFunction(double r);
vmath::vec3 _position;
double _radius = 1;
double _coef1;
double _coef2;
double _coef3;
};
#endif
| 806 |
1,382 | <reponame>vankxr/liquid-dsp<filename>sandbox/firpfbch_synthesis_equivalence_test.c
//
// firpfbch_synthesis_equivalence_test.c
//
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include "liquid.internal.h"
#define DEBUG 1
int main() {
// options
unsigned int num_channels=4; // number of channels
unsigned int m=3; // filter delay
unsigned int num_symbols=5; // number of symbols
// derived values
unsigned int num_samples = num_channels * num_symbols;
unsigned int i;
unsigned int j;
// generate filter
// NOTE : these coefficients can be random; the purpose of this
// exercise is to demonstrate mathematical equivalence
unsigned int h_len = 2*m*num_channels;
float h[h_len];
for (i=0; i<h_len; i++) h[i] = randnf();
//for (i=0; i<h_len; i++) h[i] = 0.1f*i;
//for (i=0; i<h_len; i++) h[i] = (i<=m) ? 1.0f : 0.0f;
//for (i=0; i<h_len; i++) h[i] = 1.0f;
// create filterbank manually
dotprod_crcf dp[num_channels]; // vector dot products
windowcf w[num_channels]; // window buffers
#if DEBUG
// print coefficients
printf("h_prototype:\n");
for (i=0; i<h_len; i++)
printf(" h[%3u] = %12.8f\n", i, h[i]);
#endif
// create objects
unsigned int h_sub_len = 2*m;
float h_sub[h_sub_len];
for (i=0; i<num_channels; i++) {
// sub-sample prototype filter, loading coefficients in
// reverse order
#if 0
for (j=0; j<h_sub_len; j++)
h_sub[j] = h[j*num_channels+i];
#else
for (j=0; j<h_sub_len; j++)
h_sub[h_sub_len-j-1] = h[j*num_channels+i];
#endif
// create window buffer and dotprod objects
dp[i] = dotprod_crcf_create(h_sub, h_sub_len);
w[i] = windowcf_create(h_sub_len);
#if DEBUG
printf("h_sub[%u] : \n", i);
for (j=0; j<h_sub_len; j++)
printf(" h[%3u] = %12.8f\n", j, h_sub[j]);
#endif
}
// generate inverse DFT object
float complex x[num_channels]; // time-domain buffer
float complex X[num_channels]; // freq-domain buffer
#if 1
fftplan ifft = fft_create_plan(num_channels, X, x, LIQUID_FFT_BACKWARD, 0);
#else
fftplan ifft = fft_create_plan(num_channels, X, x, LIQUID_FFT_FORWARD, 0);
#endif
// generate filter object
firfilt_crcf f = firfilt_crcf_create(h, h_len);
float complex Y[num_symbols][num_channels]; // channelized input
float complex y0[num_samples]; // time-domain output
float complex y1[num_samples]; // time-domain output
// generate input sequence (complex noise)
for (i=0; i<num_symbols; i++) {
for (j=0; j<num_channels; j++)
Y[i][j] = randnf() * cexpf(_Complex_I*randf()*2*M_PI);
#if 0
for (j=0; j<num_channels; j++)
Y[i][j] = i==0 ? randnf() * cexpf(_Complex_I*randf()*2*M_PI) : 0.0f;
#endif
}
//
// run synthesis filter bank
//
float complex * r; // read pointer
for (i=0; i<num_symbols; i++) {
// load buffers
for (j=0; j<num_channels; j++) {
X[j] = Y[i][j];
}
// execute inverse DFT, store result in buffer 'x'
fft_execute(ifft);
// push samples into filter bank and execute
for (j=0; j<num_channels; j++) {
windowcf_push(w[j], x[j]);
windowcf_read(w[j], &r);
dotprod_crcf_execute(dp[j], r, &y0[i*num_channels+j]);
// normalize by DFT scaling factor
//y0[i*num_channels+j] /= (float) num_channels;
}
}
//
// run traditional up-converter (inefficient)
//
// clear output array
for (i=0; i<num_samples; i++)
y1[i] = 0.0f;
unsigned int n;
float dphi; // carrier frequency
float complex y_hat;
for (i=0; i<num_channels; i++) {
// reset filter
firfilt_crcf_reset(f);
// set center frequency
dphi = 2.0f * M_PI * (float)i / (float)num_channels;
// reset input symbol counter
n=0;
for (j=0; j<num_samples; j++) {
// interpolate sequence
if ( (j%num_channels)==0 ) {
assert(n<num_symbols);
firfilt_crcf_push(f, Y[n][i]);
n++;
} else {
firfilt_crcf_push(f, 0);
}
firfilt_crcf_execute(f, &y_hat);
// accumulate up-converted sample
y1[j] += y_hat * cexpf(_Complex_I*j*dphi);
}
assert(n==num_symbols);
}
// destroy objects
for (i=0; i<num_channels; i++) {
dotprod_crcf_destroy(dp[i]);
windowcf_destroy(w[i]);
}
fft_destroy_plan(ifft);
firfilt_crcf_destroy(f);
//
// print channelizer outputs
//
printf("\n");
printf("output: filterbank: traditional:\n");
for (i=0; i<num_samples; i++) {
printf("%3u: %10.5f+%10.5fj %10.5f+%10.5fj\n",
i,
crealf(y0[i]), cimagf(y0[i]),
crealf(y1[i]), cimagf(y1[i]));
}
//
// compare results
//
float mse = 0.0f;
float complex d;
for (i=0; i<num_samples; i++) {
d = y0[i] - y1[i];
mse += crealf(d*conjf(d));
}
mse /= num_samples;
printf("\n");
printf("rmse: %12.4e\n", sqrtf(mse));
printf("done.\n");
return 0;
}
| 2,784 |
839 | <reponame>AnEmortalKid/cxf
/**
* 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.cxf.binding.soap.interceptor;
import java.io.ByteArrayInputStream;
import java.util.Map;
import javax.xml.stream.XMLStreamReader;
import org.apache.cxf.binding.soap.Soap11;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.staxutils.StaxUtils;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
*
*/
public class ReadHeadersInterceptorTest {
private static final byte[] TEST_SOAP =
("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"
+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
+ " xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:bar='tmp:bar'>"
+ "<soap:Body>"
+ "<ns2:payload xmlns:ns2='urn:tmp:foo'/>"
+ "</soap:Body>"
+ "</soap:Envelope>").getBytes();
private ReadHeadersInterceptor interceptor;
@Before
public void setUp() {
interceptor = new ReadHeadersInterceptor(null);
}
@Test
public void testNotAddNSContext() throws Exception {
SoapMessage message = setUpMessage();
interceptor.handleMessage(message);
Map<String, String> nsc = CastUtils.cast((Map<?, ?>)message.get("soap.body.ns.context"));
assertNull(nsc);
}
@Test
public void testAddNSContext() throws Exception {
SoapMessage message = setUpMessage();
message.put("org.apache.cxf.binding.soap.addNamespaceContext", "true");
interceptor.handleMessage(message);
Map<String, String> nsc = CastUtils.cast((Map<?, ?>)message.get("soap.body.ns.context"));
assertNotNull(nsc);
assertEquals("http://www.w3.org/2001/XMLSchema-instance", nsc.get("xsi"));
assertEquals("http://www.w3.org/2001/XMLSchema", nsc.get("xs"));
assertEquals("tmp:bar", nsc.get("bar"));
}
private SoapMessage setUpMessage() throws Exception {
SoapMessage message = new SoapMessage(Soap11.getInstance());
message.setContent(XMLStreamReader.class, StaxUtils.createXMLStreamReader(new ByteArrayInputStream(TEST_SOAP)));
return message;
}
} | 1,163 |
483 | <reponame>asad-awadia/nitrite-java
/*
* Copyright (c) 2017-2021 Nitrite author or 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.
*
*/
package org.dizitart.no2.spatial;
import org.locationtech.jts.awt.ShapeWriter;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKTReader;
import javax.swing.*;
import java.awt.*;
/**
* @author <NAME>
*/
public class SpatialViewer {
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Paint());
f.setSize(700, 700);
f.setVisible(true);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static class Paint extends JPanel {
public void paint(Graphics g) {
try {
Graphics2D g2d = (Graphics2D) g;
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
WKTReader reader = new WKTReader();
Geometry point = reader.read("POINT(500 505)");
Geometry point2 = reader.read("POINT (490 490)");
Geometry line = reader.read("LINESTRING(550 551, 525 512, 565 566)");
Geometry polygon = reader.read("POLYGON ((550 521, 580 540, 570 564, 512 566, 550 521))");
Geometry search = reader.read("POLYGON ((490 490, 536 490, 536 515, 490 515, 490 490))");
ShapeWriter sw = new ShapeWriter();
Shape pointShape = sw.toShape(point);
Shape pointShape2 = sw.toShape(point2);
Shape lineShape = sw.toShape(line);
Shape polygonShape = sw.toShape(polygon);
Shape searchShape = sw.toShape(search);
g2d.setColor(Color.RED);
g2d.draw(pointShape);
g2d.draw(pointShape2);
g2d.draw(lineShape);
g2d.draw(polygonShape);
g2d.setColor(Color.GREEN);
g2d.draw(searchShape);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 1,314 |
1,172 | // Copyright (C) 2005 Google Inc.
//
// 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.google.caja.lexer;
import com.google.caja.lexer.escaping.UriUtil;
import com.google.caja.util.Pair;
import com.google.caja.util.TestUtil;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
/**
*
* @author <EMAIL>
*/
@SuppressWarnings("static-method")
public final class CharProducerTest extends TestCase {
private static final InputSource STRING_SOURCE = new InputSource(
URI.create("file:///CharProducerTest.java"));
public final void testFromReader() throws Exception {
InputSource src = new InputSource(
TestUtil.getResource(CharProducerTest.class, "testinput1.txt"));
testProducer(
CharProducer.Factory.create(
new StringReader(
TestUtil.readResource(CharProducerTest.class, "testinput1.txt")
),
src),
"The quick brown fox\njumps over\nthe lazy dog\n",
// 0 1 2 3 4
// 01234567890123456789 01234567890 1234567890123 4
ss(0, "testinput1.txt:1+1@1"),
ss(3, "testinput1.txt:1+4@4"),
ss(19, "testinput1.txt:1+20@20"),
ss(20, "testinput1.txt:2+1@21"),
ss(43, "testinput1.txt:3+13@44"),
ss(44, "testinput1.txt:4+1@45")
);
}
public final void testFromString() {
String s =
"but was shocked to learn\n\rthe lazy dog had\r\na fox-seeking missle.";
// 0 1 2 3 4 5 6
// 0123456789012345678901234 5 67890123456789012 3 4567890123456789012345
testProducer(
fromString(s),
s,
ss(0, "CharProducerTest.java:1+1@1"),
ss(24, "CharProducerTest.java:1+25@25"),
ss(25, "CharProducerTest.java:2+1@26"),
ss(26, "CharProducerTest.java:3+1@27"),
ss(42, "CharProducerTest.java:3+17@43"),
ss(43, "CharProducerTest.java:3+18@44"),
ss(44, "CharProducerTest.java:4+1@45"),
ss(65, "CharProducerTest.java:4+22@66")
);
testProducer(fromString(""), "");
}
public final void testChaining() throws Exception {
String input2 =
"but was shocked to learn\n\rthe lazy dog had\r\na fox-seeking missle.";
// 0 1 2 3 4 5 6
// 0123456789012345678901234 5 67890123456789012 3 4567890123456789012345
Reader r = new StringReader(input2);
CharProducer prod1 = TestUtil.getResourceAsProducer(
CharProducerTest.class, "testinput1.txt");
CharProducer prod2 = CharProducer.Factory.create(r, STRING_SOURCE);
String golden1 = "The quick brown fox\njumps over\nthe lazy dog\n",
golden2 = input2;
String chainedGolden = golden1 + golden2;
CharProducer chained = CharProducer.Factory.chain(prod1, prod2);
testProducer(
chained,
chainedGolden,
ss(0, "testinput1.txt:1+1@1"),
ss(3, "testinput1.txt:1+4@4"),
ss(19, "testinput1.txt:1+20@20"),
ss(20, "testinput1.txt:2+1@21"),
ss(43, "testinput1.txt:3+13@44"),
ss(44, "testinput1.txt:4+1@45"),
ss(44 + 24, "CharProducerTest.java:1+25@25"),
ss(44 + 25, "CharProducerTest.java:2+1@26"),
ss(44 + 26, "CharProducerTest.java:3+1@27"),
ss(44 + 42, "CharProducerTest.java:3+17@43"),
ss(44 + 43, "CharProducerTest.java:3+18@44"),
ss(44 + 44, "CharProducerTest.java:4+1@45"),
ss(44 + 65, "CharProducerTest.java:4+22@66")
);
}
public final void testJsUnEscaping() {
String js =
"The quick\\u0020brown fox\\njumps\\40over\\r\\nthe lazy dog\\n";
// 0 1 2 3 4 5
// 0123456789 012345678901234 5678901 2345678 90 12345678901234 56
String golden =
"The quick brown fox\njumps over\r\nthe lazy dog\n";
// 0 1 2 3 4
// 01234567890123456789 01234567890 1 2345678901234 5
testProducer(
CharProducer.Factory.fromJsString(fromString(js)),
golden,
ss(0, "CharProducerTest.java:1+1@1")
);
// test interrupted escapes and escapes at end of file handled gracefully
testProducer(
CharProducer.Factory.fromJsString(fromString("\\\\u000a")),
"\\u000a");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\u00ziggy")),
"u00ziggy");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\u\\u000a")),
"u\n");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\u0\\u000a")),
"u0\n");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\u00\\u000a")),
"u00\n");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\u0")),
"u0");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\u000")),
"u000");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\u")),
"u");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\uffff")),
"\uffff");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\")),
"\\");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\\\x0a")),
"\\x0a");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\x0ziggy")),
"x0ziggy");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\x\\u000a")),
"x\n");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\x0\\u000a")),
"x0\n");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\s0")),
"s0");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\x")),
"x");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\0")),
"\0");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\11")),
"\t");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\011")),
"\t");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\009")),
"\0009");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\09")),
"\0009");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\9")),
"9");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\00")),
"\0");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\000")),
"\0");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\0000")),
"\u0000" + "0");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\37")),
"\037");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\037")),
"\037");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\040")),
" ");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\40")),
" ");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\400")),
" 0");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\380")),
"\003" + "80");
// test the special escapes
testProducer(
CharProducer.Factory.fromJsString(fromString("\\n")),
"\n");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\r")),
"\r");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\r\\n")),
"\r\n");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\t")),
"\t");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\b")),
"\b");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\f")),
"\f");
testProducer(
CharProducer.Factory.fromJsString(fromString("\\v")),
"\013");
}
private static CharProducer fromString(String js) {
return CharProducer.Factory.create(new StringReader(js), STRING_SOURCE);
}
public final void testHtmlUnEscaping() {
String html =
"The quick brown fox
jumps over
 the lazy dog
";
// 1 2 3 4 5 6
// 123456789012345678901234567890123456789012345678901234567890123456789
String golden =
"The quick\u00a0brown fox\njumps over\r\nthe lazy dog\n";
// 0 1 2 3 4
// 0123456789 0123456789 01234567890 1 234567890123
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString(html)),
golden,
ss(0, "CharProducerTest.java:1+1@1"),
ss(10, "CharProducerTest.java:1+16@16"), // The 'b' in "brown"
ss(20, "CharProducerTest.java:1+30@30"), // The 'j' in "jumps"
ss(30, "CharProducerTest.java:1+40@40"), // The CR before "the lazy"
ss(40, "CharProducerTest.java:1+58@58") // The space before "dog"
);
// test interrupted escapes and escapes at end of file handled gracefully
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("\\\\u000a")),
"\\\\u000a");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("𐀀")),
String.valueOf(Character.toChars(0x10000)));
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"
");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("�ziggy")),
"�ziggy");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("਀z;")),
"਀z;");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&#
")),
"&#\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&#x
")),
"&#x\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("

")),
"
\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&#
")),
"&#\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&#x")),
"&#x");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("�")),
"�");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&#")),
"&#");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("\\")),
"\\");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&")),
"&");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("�a;")),
"�a;");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString(" ")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("	")),
"\t");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"
");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("�ziggy")),
"�ziggy");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&#
")),
"&#\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("�
")),
"�\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString(" ")),
"\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&# ")),
"&#\n");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("")),
"");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("
")),
"
");
// test the named escapes
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("<")),
"<");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString(">")),
">");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString(""")),
"\"");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("'")),
"'");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("'")),
"'");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("'")),
"'");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&")),
"&");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&lt;")),
"<");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&")),
"&");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&")),
"&");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&AmP;")),
"&");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("Α")),
"\u0391");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("α")),
"\u03b1");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&;")),
"&;");
testProducer(
CharProducer.Factory.fromHtmlAttribute(fromString("&bogus;")),
"&bogus;");
}
public final void testChainingAndUnescaping() throws Exception {
InputSource src = STRING_SOURCE;
// 12345678
Reader r1 = new StringReader("hiThere(");
// 3333333
// 0123456
Reader r2 = new StringReader(", now);");
CharProducer prod1 = CharProducer.Factory.create(
r1, FilePosition.startOfFile(src)),
prod2 = CharProducer.Factory.create(
r2, FilePosition.instance(src, 2, 30, 1));
String golden = "hiThere(, now);";
CharProducer chained = CharProducer.Factory.fromHtmlAttribute(
CharProducer.Factory.chain(prod1, prod2));
testProducer(
chained,
golden,
ss(0, "CharProducerTest.java:1+1@1"),
ss(1, "CharProducerTest.java:1+2@2"),
ss(2, "CharProducerTest.java:1+3@3"),
ss(3, "CharProducerTest.java:1+4@4"),
ss(4, "CharProducerTest.java:1+5@5"),
ss(5, "CharProducerTest.java:1+6@6"),
ss(6, "CharProducerTest.java:1+7@7"),
ss(7, "CharProducerTest.java:1+8@8"),
ss(8, "CharProducerTest.java:1+9@9"),
ss(9, "CharProducerTest.java:2+2@31"),
ss(10, "CharProducerTest.java:2+3@32"),
ss(11, "CharProducerTest.java:2+4@33"),
ss(12, "CharProducerTest.java:2+5@34"),
ss(13, "CharProducerTest.java:2+6@35"),
ss(14, "CharProducerTest.java:2+7@36"),
ss(15, "CharProducerTest.java:2+8@37")
);
}
/**
* Asserts that the given producer produces the characters in golden, and that
* the character at positions[k].charsRead falls at
* FilePosition positions[k].pos.
*
* @param positions s.t. positions[k+1].charsRead > positions[k].charsRead.
*/
private static void testProducer(
CharProducer p, String golden, StreamState... positions) {
List<Pair<String, FilePosition>> actualPositions
= new ArrayList<Pair<String, FilePosition>>();
StringBuilder sb = new StringBuilder();
char[] buf = p.getBuffer();
for (int k = p.getOffset(); ; p.consume(1)) {
int offset = p.getOffset();
if (k < positions.length && sb.length() == positions[k].charsRead) {
FilePosition pos = p.getSourceBreaks(offset).toFilePosition(
p.getCharInFile(offset));
actualPositions.add(Pair.pair(sb.toString(), pos));
++k;
}
if (offset != p.getLimit()) {
sb.append(buf[p.getOffset()]);
} else {
break;
}
}
String actual = sb.toString();
assertEquals(
"golden:[" + escape(golden) + "]\nactual:[" + escape(actual) + "]",
golden, actual);
for (int k = 0; k < Math.min(positions.length, actualPositions.size()); ++k) {
Pair<String, FilePosition> actualPos = actualPositions.get(k);
String posStr = actualPos.b.toString();
assertEquals(
"Read so far [" + actualPos.a + "] : ["
+ golden.substring(
0, Math.min(actualPos.a.length(), golden.length()))
+ "]",
positions[k].pos, posStr);
}
assertEquals(positions.length, actualPositions.size());
}
private static final String decodeUri(String uriPart) {
return CharProducer.Factory.fromUri(
CharProducer.Factory.fromString(uriPart, InputSource.UNKNOWN))
.toString();
}
public final void testFromUri() {
assertEquals("", decodeUri(""));
assertEquals("foo", decodeUri("foo"));
// Plus (+) character not decoded to space, since + is not an escape
// character in the body of non-hierarchical URLs
// javascript:alert('foo+bar') issues an alert containing a plus character.
assertEquals("foo+bar", decodeUri("foo+bar"));
assertEquals("foo+bar", decodeUri("foo%2bbar"));
assertEquals("foo@bar", decodeUri("foo%40bar"));
assertEquals("\u00A0", decodeUri("%A0")); // A single ASCII char
// Test some well-formed UTF-8 sequences.
assertEquals("foo\u0123bar", decodeUri("foo%C4%a3bar"));
assertEquals("foo\u20ACbar", decodeUri("foo%e2%82%Acbar"));
// There are multiple ways to encode supplementary characters
String supplemental = String.valueOf(Character.toChars(0x1d11e));
assertEquals(
supplemental,
decodeUri("%ed%a0%B4%eD%b4%9E")); // as a surrogate pair
assertEquals(
supplemental,
decodeUri("%F0%9d%84%9E")); // as a 4 byte sequence
assertEquals(
supplemental,
decodeUri("%f0%9D%84%9e")); // as a 4 byte sequence with different case
// Make sure our encoder round trips properly.
assertEquals(supplemental, decodeUri(UriUtil.encode(supplemental)));
// Test boundary conditions.
assertEquals("%", decodeUri("%"));
assertEquals("%2", decodeUri("%2")); // An incomplete sequence
assertEquals("%z", decodeUri("%z")); // A non-hex follower.
assertEquals("%", decodeUri("%25"));
assertEquals("%2", decodeUri("%252"));
assertEquals("%25", decodeUri("%2525")); // Don't over decode.
}
private static final Pattern ESCAPED =
Pattern.compile("[^\\p{javaLetterOrDigit} \\.\\-\\:\\;\\'\\\",/\\?&\\#]");
private static String escape(String s) {
Matcher m = ESCAPED.matcher(s);
if (!m.find()) { return s; }
StringBuffer sb = new StringBuffer(s.length() + 16);
char[] hex = new char[] { 0, 0, 0, 0 };
do {
int ch = m.group().charAt(0);
for (int i = hex.length; --i >= 0;) {
hex[i] = "0123456789abcdef".charAt(ch & 0xf);
ch >>= 4;
}
m.appendReplacement(sb, "<" + new String(hex, 0, 4) + ">");
} while (m.find());
return m.appendTail(sb).toString();
}
private static StreamState ss(int charsRead, String p) {
return new StreamState(charsRead, p);
}
static class StreamState {
final int charsRead;
final String pos;
StreamState(int charsRead, String pos) {
this.charsRead = charsRead;
this.pos = pos;
}
}
}
| 9,431 |
4,391 | # This sample tests the syntax handling for Python 3.11 exception groups
# as described in PEP 654.
def func1():
try:
pass
# This should generate an error if using Python 3.10 or earlier.
except* BaseException:
pass
# This should generate an error if using Python 3.10 or earlier.
except*:
pass
| 117 |
348 | {"nom":"Orgeux","circ":"2ème circonscription","dpt":"Côte-d'Or","inscrits":380,"abs":187,"votants":193,"blancs":4,"nuls":0,"exp":189,"res":[{"nuance":"LR","nom":"<NAME>","voix":99},{"nuance":"REM","nom":"<NAME>","voix":90}]} | 93 |
679 | <filename>main/svx/inc/svx/grafctrl.hxx
/**************************************************************
*
* 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.
*
*************************************************************/
#ifndef _SVX_GRAFCTRL_HXX
#define _SVX_GRAFCTRL_HXX
#include <svl/lstner.hxx>
#include <svl/intitem.hxx>
#include <sfx2/tbxctrl.hxx>
#include "svx/svxdllapi.h"
// ----------------
// - TbxImageItem -
// ----------------
class SVX_DLLPUBLIC TbxImageItem : public SfxUInt16Item
{
public:
TYPEINFO();
TbxImageItem( sal_uInt16 nWhich = 0, sal_uInt16 nImage = 0 );
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual int operator==( const SfxPoolItem& ) const;
};
// -------------------------------
// - SvxGrafFilterToolBoxControl -
// -------------------------------
class SVX_DLLPUBLIC SvxGrafFilterToolBoxControl : public SfxToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafFilterToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
~SvxGrafFilterToolBoxControl();
virtual void StateChanged( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState );
virtual SfxPopupWindowType GetPopupWindowType() const;
virtual SfxPopupWindow* CreatePopupWindow();
};
// -------------------------
// - SvxGrafToolBoxControl -
// -------------------------
class SvxGrafToolBoxControl : public SfxToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
~SvxGrafToolBoxControl();
virtual void StateChanged( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState );
virtual Window* CreateItemWindow( Window *pParent );
};
// ----------------------------
// - SvxGrafRedToolBoxControl -
// ----------------------------
class SVX_DLLPUBLIC SvxGrafRedToolBoxControl : public SvxGrafToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafRedToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
};
// ------------------------------
// - SvxGrafGreenToolBoxControl -
// ------------------------------
class SVX_DLLPUBLIC SvxGrafGreenToolBoxControl : public SvxGrafToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafGreenToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
};
// -----------------------------
// - SvxGrafBlueToolBoxControl -
// -----------------------------
class SVX_DLLPUBLIC SvxGrafBlueToolBoxControl : public SvxGrafToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafBlueToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
};
// ----------------------------------
// - SvxGrafLuminanceToolBoxControl -
// ----------------------------------
class SVX_DLLPUBLIC SvxGrafLuminanceToolBoxControl : public SvxGrafToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafLuminanceToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
};
// ---------------------------------
// - SvxGrafContrastToolBoxControl -
// ---------------------------------
class SVX_DLLPUBLIC SvxGrafContrastToolBoxControl : public SvxGrafToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafContrastToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
};
// ------------------------------
// - SvxGrafGammaToolBoxControl -
// ------------------------------
class SVX_DLLPUBLIC SvxGrafGammaToolBoxControl : public SvxGrafToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafGammaToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
};
// -------------------------------------
// - SvxGrafTransparenceToolBoxControl -
// -------------------------------------
class SVX_DLLPUBLIC SvxGrafTransparenceToolBoxControl : public SvxGrafToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafTransparenceToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
};
// -----------------------------
// - SvxGrafModeToolBoxControl -
// -----------------------------
class SVX_DLLPUBLIC SvxGrafModeToolBoxControl : public SfxToolBoxControl, public SfxListener
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SvxGrafModeToolBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx );
~SvxGrafModeToolBoxControl();
virtual void StateChanged( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState );
virtual Window* CreateItemWindow( Window *pParent );
};
// ---------------------
// - SvxGrafAttrHelper -
// ---------------------
class SdrView;
class SfxRequest;
class SVX_DLLPUBLIC SvxGrafAttrHelper
{
public:
static void ExecuteGrafAttr( SfxRequest& rReq, SdrView& rView );
static void GetGrafAttrState( SfxItemSet& rSet, SdrView& rView );
};
#endif // _SVX_GRAFCTRL_HXX
| 2,021 |
5,871 | <reponame>shrin18/binaryen
#include <emscripten/em_asm.h>
int main() {
EM_ASM({ Module.print("Hello world"); });
int x = EM_ASM_INT({ return $0 + $1; }, 13, 27);
EM_ASM_({ Module.print("Got " + $0); }, x);
return 0;
}
| 99 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Roncourt","circ":"1ère circonscription","dpt":"Moselle","inscrits":718,"abs":464,"votants":254,"blancs":15,"nuls":6,"exp":233,"res":[{"nuance":"FN","nom":"<NAME>","voix":141},{"nuance":"REM","nom":"<NAME>","voix":92}]} | 115 |
778 | package org.aion.zero.impl.types;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.regex.Pattern;
import org.aion.util.bytes.ByteUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* A loader class for the protocol upgrade settings
*
* @author <NAME>
*/
public class ForkPropertyLoader {
private static final Pattern isAlphaNumeric = Pattern.compile("^(0x)?[0-9a-fA-F]+$");
private static final Pattern isNumeric = Pattern.compile("^?[0-9]+$");
/**
* @param filePath the file path to the fork properties JSON file
* @return the ProtocolUpgrade Settings
*/
public static ProtocolUpgradeSettings loadJSON(String filePath)
throws IOException {
File forkPropertyFile = new File(filePath);
if (forkPropertyFile.exists()) {
try (InputStream is = new FileInputStream(forkPropertyFile)) {
String json = new String(ByteStreams.toByteArray(is));
JSONObject mapper = new JSONObject(json);
Properties upgrade = new Properties();
List<byte[]> rollbackTx = null;
if (mapper.has("fork")) {
JSONArray array = mapper.getJSONArray("fork");
for (int i=0 ; i<array.length() ; i++) {
JSONObject object = array.getJSONObject(i);
Objects.requireNonNull(object);
String ver = object.getString("ver");
String block = object.getString("block");
Objects.requireNonNull(ver);
Objects.requireNonNull(block);
if (!isNumeric.matcher(block).matches()) {
throw new IOException("the block number must be numerical");
}
upgrade.put("fork" + ver, block);
if (ver.equals("1.6")) {
rollbackTx = parseRollbackTx(object);
}
}
}
boolean forTest = false;
if (mapper.has("forTest")) {
forTest = mapper.getBoolean("forTest");
}
return new ProtocolUpgradeSettings(upgrade, rollbackTx, forTest);
} catch (IOException | JSONException e) {
throw new IOException(e);
}
} else {
throw new IOException(String.format("fork property file not found at %s", filePath));
}
}
private static List<byte[]> parseRollbackTx(JSONObject object) throws IOException {
JSONArray txArray = object.optJSONArray("rollbackTx");
if (txArray == null) {
return null;
}
List<byte[]> list = new ArrayList<>();
for (int i=0 ; i<txArray.length() ; i++) {
String txHash = txArray.getString(i);
Objects.requireNonNull(txHash);
if (!isAlphaNumeric.matcher(txHash).matches())
throw new IOException("the rollbackTx transaction hash must be hex or numerical");
byte[] hash = ByteUtil.hexStringToBytes(txHash);
if (hash.length != 32) {
throw new IOException("the rollbackTx transaction hash must be 32 bytes");
}
list.add(hash);
}
return list;
}
}
| 1,692 |
10,225 | package io.quarkus.config;
import java.util.Map;
import io.quarkus.runtime.annotations.StaticInitSafe;
import io.smallrye.config.common.MapBackedConfigSource;
@StaticInitSafe
public class StaticInitConfigSource extends MapBackedConfigSource {
public StaticInitConfigSource() {
super("", Map.of("config.static.init.my-prop", "1234"));
}
}
| 123 |
780 | <filename>projects/stage-1/middleware-frameworks/my-interceptor/src/main/java/org/geektimes/interceptor/AnnotatedInterceptor.java<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.geektimes.interceptor;
import org.geektimes.commons.lang.Prioritized;
import org.geektimes.interceptor.util.InterceptorUtils;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.interceptor.*;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.lang.String.format;
import static java.util.ServiceLoader.load;
import static org.geektimes.commons.reflect.util.TypeUtils.resolveTypeArguments;
import static org.geektimes.interceptor.InterceptorManager.getInstance;
import static org.geektimes.interceptor.util.InterceptorUtils.INTERCEPTOR_ANNOTATION_TYPE;
/**
* The abstract annotated {@link javax.interceptor.Interceptor @Interceptor} class
*
* @param <A> the type of {@link Annotation}
* @author <a href="mailto:<EMAIL>">Mercy</a>
* @since 1.0.0
*/
public abstract class AnnotatedInterceptor<A extends Annotation> implements Interceptor, Prioritized {
private final Logger logger = Logger.getLogger(getClass().getName());
private final InterceptorManager interceptorManager;
private final Class<A> interceptorBindingType;
private int priority = Prioritized.NORMAL_PRIORITY;
/**
* @throws IllegalArgumentException If the implementation does not annotate {@link Interceptor @Interceptor} or
* the generic parameter type does not be specified.
*/
public AnnotatedInterceptor() throws IllegalArgumentException {
Class<?> interceptorClass = getClass();
this.interceptorManager = getInstance(interceptorClass.getClassLoader());
this.interceptorManager.registerInterceptorClass(interceptorClass);
this.interceptorBindingType = resolveInterceptorBindingType(interceptorClass);
this.interceptorManager.registerInterceptor(this);
}
@Override
public final int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
@AroundInvoke
public Object intercept(InvocationContext context) throws Throwable {
A interceptorBinding = findInterceptorBinding(context.getMethod());
return interceptorBinding == null ? context.proceed() : intercept(context, interceptorBinding);
}
/**
* Timeout methods are currently specific to Enterprise JavaBeans, although Timer Service functionality
* may be extended to other specifications in the future, and extension specifications may define events
* that may be interposed on by around-timeout methods.
*
* @param context
* @return
* @throws Throwable
*/
@AroundTimeout
public Object interceptTimeout(InvocationContext context) throws Throwable {
A interceptorBinding = findInterceptorBinding(context.getMethod());
return interceptorBinding == null ? context.proceed() : interceptTimeout(context, interceptorBinding);
}
@AroundConstruct
public void interceptConstruct(InvocationContext context) throws Throwable {
A interceptorBinding = findInterceptorBinding(context.getConstructor());
if (interceptorBinding == null) {
context.proceed();
} else {
interceptConstruct(context, interceptorBinding);
}
}
@PostConstruct
public void interceptPostConstruct(InvocationContext context) throws Throwable {
beforePostConstruct(context.getTarget(), context.getMethod());
context.proceed();
afterPostConstruct(context.getTarget(), context.getMethod());
}
@PreDestroy
public void interceptPreDestroy(InvocationContext context) throws Throwable {
beforePreDestroy(context.getTarget(), context.getMethod());
context.proceed();
afterPreDestroy(context.getTarget(), context.getMethod());
}
/**
* Executes {@link AroundInvoke @AroundInvoke} method
*
* @param context {@link InvocationContext}
* @param interceptorBinding the instance of {@link Annotation} annotated by {@link InterceptorBindings}
* @return the result of {@link InvocationContext#proceed()} method
* @throws Throwable any exception if occurs
*/
protected abstract Object intercept(InvocationContext context, A interceptorBinding) throws Throwable;
/**
* Executes {@link AroundTimeout @AroundTimeout} method
*
* @param context {@link InvocationContext}
* @param interceptorBinding the instance of {@link Annotation} annotated by {@link InterceptorBindings}
* @return the result of {@link InvocationContext#proceed()} method
* @throws Throwable any exception if occurs
*/
protected Object interceptTimeout(InvocationContext context, A interceptorBinding) throws Throwable {
return context.proceed();
}
/**
* Executes {@link AroundConstruct @AroundConstruct} method
*
* @param context {@link InvocationContext}
* @param interceptorBinding the instance of {@link Annotation} annotated by {@link InterceptorBindings}
* @throws Throwable any exception if occurs
*/
protected void interceptConstruct(InvocationContext context, A interceptorBinding) throws Throwable {
context.proceed();
}
/**
* Before {@link PostConstruct @PostConstruct} interception
*
* @param target the intercepted target object
* @param method the intercepted {@link Method}
* @throws Throwable any exception if occurs
*/
protected void beforePostConstruct(Object target, Method method) throws Throwable {
}
/**
* After {@link PostConstruct @PostConstruct} interception
*
* @param target the intercepted target object
* @param method the intercepted {@link Method}
* @throws Throwable any exception if occurs
*/
protected void afterPostConstruct(Object target, Method method) throws Throwable {
}
/**
* Before {@link PreDestroy @PreDestroy} interception
*
* @param target the intercepted target object
* @param method the intercepted {@link Method}
* @throws Throwable any exception if occurs
*/
protected void beforePreDestroy(Object target, Method method) throws Throwable {
}
/**
* After {@link PreDestroy @PreDestroy} interception
*
* @param target the intercepted target object
* @param method the intercepted {@link Method}
* @throws Throwable any exception if occurs
*/
protected void afterPreDestroy(Object target, Method method) throws Throwable {
}
/**
* Get the type of {@link Annotation} annotated by {@link InterceptorBindings}
*
* @param interceptorClass
* @return non-null
*/
protected Class<A> resolveInterceptorBindingType(Class<?> interceptorClass) {
Class<A> interceptorBindingType = null;
for (Class<?> typeArgument : resolveTypeArguments(interceptorClass)) {
if (typeArgument.isAnnotation()) {
Class<A> annotationType = (Class<A>) typeArgument;
if (isInterceptorBindingType(annotationType)) {
interceptorBindingType = annotationType;
break;
} else if (shouldRegisterSyntheticInterceptorBindingType()) {
registerSyntheticInterceptorBindingType(annotationType);
interceptorBindingType = annotationType;
break;
} else {
if (logger.isLoggable(Level.SEVERE)) {
logger.severe(format("The annotationType[%s] should annotate %s",
typeArgument.getName(),
InterceptorBindings.class.getName()));
}
}
}
}
validateInterceptorBindingType(interceptorBindingType);
return interceptorBindingType;
}
private boolean isInterceptorBindingType(Class<? extends Annotation> annotationType) {
return interceptorManager.isInterceptorBindingType(annotationType);
}
private void registerSyntheticInterceptorBindingType(Class<A> annotationType) {
interceptorManager.registerInterceptorBindingType(annotationType);
}
protected boolean shouldRegisterSyntheticInterceptorBindingType() {
return false;
}
protected void validateInterceptorBindingType(Class<A> annotationType) {
if (annotationType == null) {
String message = format("The interceptor binding annotation is invalid in the Interceptor class[%s]! " +
"Please check it that should annotate @%s or be registered as a synthetic interceptor " +
"binding type by InterceptorRegistry#registerInterceptorBindingType method!",
getClass().getName(), INTERCEPTOR_ANNOTATION_TYPE.getName());
throw new IllegalArgumentException(message);
}
Target target = annotationType.getAnnotation(Target.class);
ElementType[] elementTypes = target.value();
if (Arrays.stream(elementTypes).anyMatch(ElementType.TYPE::equals)) {
if (!getClass().isAnnotationPresent(annotationType)) {
throw new IllegalArgumentException(format("The @%s must be annotated on the type[%s]!",
annotationType.getName(), getClass().getName()));
}
}
}
protected A findInterceptorBinding(Method method) {
return InterceptorUtils.resolveInterceptorBinding(method, interceptorBindingType);
}
protected A findInterceptorBinding(Constructor<?> constructor) {
return InterceptorUtils.resolveInterceptorBinding(constructor, interceptorBindingType);
}
protected Throwable getFailure(Throwable e) {
Throwable failure = e instanceof InvocationTargetException ? e.getCause() : e;
while (failure instanceof InvocationTargetException) {
failure = getFailure(failure);
}
return failure;
}
public InterceptorManager getInterceptorRegistry() {
return interceptorManager;
}
private boolean excludeInterceptorAnnotation(Annotation annotation) {
return !INTERCEPTOR_ANNOTATION_TYPE.equals(annotation.annotationType());
}
}
| 4,017 |
322 | package com.imooc.lib_audio.mediaplayer.core;
import android.media.MediaPlayer;
import java.io.IOException;
public class CustomMediaPlayer extends MediaPlayer implements MediaPlayer.OnCompletionListener {
private Status mState = Status.IDLE;
private OnCompletionListener mListener;
public enum Status{
IDLE, INITIALIZED, STARTED, PAUSED, STOPPED, COMPLETED, PREPARED
}
CustomMediaPlayer(){
super();
mState = Status.IDLE;
super.setOnCompletionListener(this);
}
@Override
public void onCompletion(MediaPlayer mp) {
mState = Status.COMPLETED;
if(mListener != null){
mListener.onCompletion(mp);
}
}
@Override
public void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException, SecurityException {
super.setDataSource(path);
mState = Status.INITIALIZED;
}
@Override
public void start() throws IllegalStateException {
super.start();
mState = Status.STARTED;
}
@Override
public void pause() throws IllegalStateException {
super.pause();
mState = Status.PAUSED;
}
@Override
public void stop() throws IllegalStateException {
super.stop();
mState = Status.STOPPED;
}
@Override
public void reset() {
super.reset();
mState = Status.IDLE;
}
@Override
public void prepare() throws IOException, IllegalStateException {
super.prepare();
mState = Status.PREPARED;
}
public void setState(Status mState) {
this.mState = mState;
}
public Status getState() {
return mState;
}
public boolean isComplete() {
return mState == Status.COMPLETED;
}
public void setOnCompletionListener(OnCompletionListener listener) {
this.mListener = listener;
}
}
| 555 |
467 | <filename>external/source/armitage/src/ui/ATextField.java
package ui;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
/* A textfield with a popup menu to cut, copy, paste, and clear the textfield */
public class ATextField extends JTextField {
protected JPopupMenu menu = null;
public ATextField(int cols) {
super(cols);
createMenu();
}
public ATextField(Document doc, String text, int cols) {
super(doc, text, cols);
createMenu();
}
public ATextField(String text, int cols) {
super(text, cols);
createMenu();
}
public ATextField() {
super();
createMenu();
}
public void createMenu() {
if (menu != null)
return;
menu = new JPopupMenu();
JMenuItem cut = new JMenuItem("Cut", 'C');
JMenuItem copy = new JMenuItem("Copy", 'o');
JMenuItem paste = new JMenuItem("Paste", 'P');
JMenuItem clear = new JMenuItem("Clear", 'l');
cut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
cut();
}
});
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
copy();
}
});
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
paste();
}
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
setText("");
}
});
menu.add(cut);
menu.add(copy);
menu.add(paste);
menu.add(clear);
addMouseListener(new MouseAdapter() {
public void handle(MouseEvent ev) {
if (ev.isPopupTrigger()) {
menu.show((JComponent)ev.getSource(), ev.getX(), ev.getY());
}
}
public void mousePressed(MouseEvent ev) {
handle(ev);
}
public void mouseClicked(MouseEvent ev) {
handle(ev);
}
public void mouseReleased(MouseEvent ev) {
handle(ev);
}
});
}
}
| 744 |
480 | <reponame>Dennisbonke/mlibc
#ifndef _SOCKET_H
#define _SOCKET_H
#include <abi-bits/gid_t.h>
#include <abi-bits/pid_t.h>
#include <bits/size_t.h>
#include <bits/posix/socklen_t.h>
#include <bits/ssize_t.h>
#include <abi-bits/uid_t.h>
#include <bits/posix/iovec.h>
#include <abi-bits/socket.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
struct sockaddr {
sa_family_t sa_family;
char sa_data[14];
};
struct cmsghdr {
socklen_t cmsg_len;
int cmsg_level;
int cmsg_type;
};
// Control message format:
// The offsets marked with ^ are aligned to alignof(size_t).
//
// |---HEADER---|---DATA---|---PADDING---|---HEADER---|...
// ^ ^ ^
// |---------CMSG_LEN------|
// |---------------CMSG_SPACE------------|
// Auxiliary macro. While there is basically no reason for applications
// to use this, it is exported by glibc.
#define CMSG_ALIGN(s) (((s) + __alignof__(size_t) - 1) & \
~(__alignof__(size_t) - 1))
// Basic macros to return content and padding size of a control message.
#define CMSG_LEN(s) (sizeof(struct cmsghdr) + (s))
#define CMSG_SPACE(s) (sizeof(struct cmsghdr) + CMSG_ALIGN(s))
// Provides access to the data of a control message.
#define CMSG_DATA(c) ((char *)(c) + sizeof(struct cmsghdr))
#define __MLIBC_CMSG_NEXT(c) ((char *)(c) + CMSG_ALIGN((c)->cmsg_len))
#define __MLIBC_MHDR_LIMIT(m) ((char *)(m)->msg_control + (m)->msg_controllen)
// For parsing control messages only.
// Returns a pointer to the first header or nullptr if there is none.
#define CMSG_FIRSTHDR(m) ((size_t)(m)->msg_controllen <= sizeof(struct cmsghdr) \
? (struct cmsghdr *)0 : (struct cmsghdr *) (m)->msg_control)
// For parsing control messages only.
// Returns a pointer to the next header or nullptr if there is none.
#define CMSG_NXTHDR(m, c) \
((c)->cmsg_len < sizeof(struct cmsghdr) || \
(ptrdiff_t)(sizeof(struct cmsghdr) + CMSG_ALIGN((c)->cmsg_len)) \
>= __MLIBC_MHDR_LIMIT(m) - (char *)(c) \
? (struct cmsghdr *)0 : (struct cmsghdr *)__MLIBC_CMSG_NEXT(c))
struct linger{
int l_onoff;
int l_linger;
};
struct ucred {
pid_t pid;
uid_t uid;
gid_t gid;
};
int accept(int, struct sockaddr *__restrict, socklen_t *__restrict);
int bind(int, const struct sockaddr *, socklen_t);
int connect(int, const struct sockaddr *, socklen_t);
int getpeername(int, struct sockaddr *__restrict, socklen_t *__restrict);
int getsockname(int, struct sockaddr *__restrict, socklen_t *__restrict);
int getsockopt(int, int, int, void *__restrict, socklen_t *__restrict);
int listen(int, int);
ssize_t recv(int, void *, size_t, int);
ssize_t recvfrom(int, void *__restrict, size_t, int, struct sockaddr *__restrict, socklen_t *__restrict);
ssize_t recvmsg(int, struct msghdr *, int);
ssize_t send(int, const void *, size_t, int);
ssize_t sendmsg(int, const struct msghdr *, int);
ssize_t sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
int recvmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen, int flags, struct timespec *timeout);
int sendmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen, int flags);
int setsockopt(int, int, int, const void *, socklen_t);
int shutdown(int, int);
int sockatmark(int);
int socket(int, int, int);
int socketpair(int, int, int, int [2]);
#ifdef __cplusplus
}
#endif
#endif // _UNISTD_H
| 1,359 |
774 | //
// BaseConsoleAdapter.java
//
// Lunar Unity Mobile Console
// https://github.com/SpaceMadness/lunar-unity-console
//
// Copyright 2015-2021 <NAME>, SpaceMadness.
//
// 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 spacemadness.com.lunarconsole.console;
import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
abstract class BaseConsoleAdapter<T extends BaseEntry> extends BaseAdapter {
private final DataSource<T> dataSource;
BaseConsoleAdapter(DataSource<T> dataSource) {
if (dataSource == null) {
throw new NullPointerException("Data source is null");
}
this.dataSource = dataSource;
}
@Override
public int getCount() {
return dataSource.getEntryCount();
}
@Override
public Object getItem(int position) {
return dataSource.getEntry(position);
}
@Override
public long getItemId(int position) {
return dataSource.getEntry(position).getItemId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder<T> viewHolder;
if (convertView != null) {
viewHolder = (ViewHolder) convertView.getTag();
} else {
convertView = createConvertView(parent, position);
viewHolder = createViewHolder(convertView, position);
convertView.setTag(viewHolder);
}
T entry = dataSource.getEntry(position);
viewHolder.bindViewHolder(entry, position);
return convertView;
}
//////////////////////////////////////////////////////////////////////////////
// Data Source
protected abstract ViewHolder createViewHolder(View convertView, int position);
//////////////////////////////////////////////////////////////////////////////
// View Holder
protected abstract View createConvertView(ViewGroup parent, int position);
public interface DataSource<E extends BaseEntry> {
E getEntry(int position);
int getEntryCount();
}
public static abstract class ViewHolder<T extends BaseEntry> {
protected final View itemView;
public ViewHolder(View itemView) {
this.itemView = itemView;
}
void bindViewHolder(T entry, int position) {
onBindViewHolder(entry, position);
}
public abstract void onBindViewHolder(T entry, int position);
protected Context getContext() {
return itemView.getContext();
}
protected Resources getResources() {
return getContext().getResources();
}
protected String getString(int id) {
return getResources().getString(id);
}
protected int getColor(int id) {
return getResources().getColor(id);
}
}
} | 1,211 |
622 | <filename>bayespy/inference/vmp/nodes/deterministic.py
################################################################################
# Copyright (C) 2013-2014 <NAME>
#
# This file is licensed under the MIT License.
################################################################################
import functools
import numpy as np
from bayespy.utils import misc
from .node import Node, Moments
class Deterministic(Node):
"""
Base class for deterministic nodes.
Sub-classes must implement:
1. For implementing the deterministic function:
_compute_moments(self, *u)
2. One of the following options:
a) Simple methods:
_compute_message_to_parent(self, index, m, *u)
b) More control with:
_compute_message_and_mask_to_parent(self, index, m, *u)
Sub-classes may need to re-implement:
1. If they manipulate plates:
_compute_weights_to_parent(index, mask)
_compute_plates_to_parent(self, index, plates)
_compute_plates_from_parent(self, index, plates)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, plates=None, notify_parents=False, **kwargs)
def _get_id_list(self):
"""
Returns the stochastic ID list.
This method is used to check that same stochastic nodes are not direct
parents of a node several times. It is only valid if there are
intermediate stochastic nodes.
To put it another way: each ID corresponds to one factor q(..) in the
posterior approximation. Different IDs mean different factors, thus they
mean independence. The parents must have independent factors.
Stochastic nodes should return their unique ID. Deterministic nodes
should return the IDs of their parents. Constant nodes should return
empty list of IDs.
"""
id_list = []
for parent in self.parents:
id_list = id_list + parent._get_id_list()
return id_list
def get_moments(self):
u_parents = self._message_from_parents()
return self._compute_moments(*u_parents)
def _compute_message_and_mask_to_parent(self, index, m_children, *u_parents):
# The following methods should be implemented by sub-classes.
m = self._compute_message_to_parent(index, m_children, *u_parents)
mask = self._compute_weights_to_parent(index, self.mask) != 0
return (m, mask)
def _get_message_and_mask_to_parent(self, index, u_parent=None):
u_parents = self._message_from_parents(exclude=index)
u_parents[index] = u_parent
if u_parent is not None:
u_self = self._compute_moments(*u_parents)
else:
u_self = None
m_children = self._message_from_children(u_self=u_self)
return self._compute_message_and_mask_to_parent(index,
m_children,
*u_parents)
def _compute_moments(self, *u_parents):
"""
Compute the moments given the moments of the parents.
"""
raise NotImplementedError()
def _compute_message_to_parent(self, index, m_children, *u_parents):
"""
Compute the message to a parent.
"""
raise NotImplementedError()
def _add_child(self, child, index):
"""
Add a child node.
Only child nodes that are stochastic (or have stochastic children
recursively) are counted as children because deterministic nodes without
stochastic children do not have any messages to send so the parents do
not need to know about the deterministic node.
A deterministic node does not notify its parents when created, but if it
gets a stochastic child node, then notify parents. This method is called
only if a stochastic child (recursively) node is added, thus there is at
least one stochastic node below this deterministic node.
Parameters
----------
child : node
index : int
The parent index of this node for the child node.
The child node recognizes its parents by their index
number.
"""
super()._add_child(child, index)
# Now that this deterministic node has non-deterministic children,
# notify parents
for (ind,parent) in enumerate(self.parents):
parent._add_child(self, ind)
def _remove_child(self, child, index):
"""
Remove a child node.
Only child nodes that are stochastic (or have stochastic children
recursively) are counted as children because deterministic nodes without
stochastic children do not have any messages to send so the parents do
not need to know about the deterministic node.
So, if the deterministic node does not have any stochastic children left
after removal, remove it from its parents.
"""
super()._remove_child(child, index)
# Check whether there are any children left. If not, remove from parents
if len(self.children) == 0:
for (ind, parent) in enumerate(self.parents):
parent._remove_child(self, ind)
def lower_bound_contribution(self, gradient=False, **kwargs):
# Deterministic functions are delta distributions so the lower bound
# contribuion is zero.
return 0
def random(self):
samples = [parent.random() for parent in self.parents]
return self._compute_function(*samples)
def tile(X, tiles):
"""
Tile the plates of the input node.
x = [a,b,c]
y = tile(x, 2) = [a,b,c,a,b,c]
There should be no need to tile plates that have unit length because they
are handled properly by the broadcasting rules already.
Parameters
----------
X : Node
Input node to be tiled.
tiles : int, tuple
Tiling of the plates (broadcasting rules for plates apply).
See also
--------
numpy.tile
"""
# Make sure `tiles` is tuple (even if an integer is given)
tiles = tuple(np.ravel(tiles))
class _Tile(Deterministic):
_parent_moments = (Moments(),)
def __init__(self, X, **kwargs):
self._moments = X._moments
super().__init__(X, dims=X.dims, **kwargs)
def _compute_plates_to_parent(self, index, plates):
plates = list(plates)
for i in range(-len(tiles), 0):
plates[i] = plates[i] // tiles[i]
return tuple(plates)
def _compute_plates_from_parent(self, index, plates):
return tuple(misc.multiply_shapes(plates, tiles))
def _compute_weights_to_parent(self, index, weights):
# Idea: Reshape the message array such that every other axis
# will be summed and every other kept.
# Make plates equal length
plates = self._plates_to_parent(index)
shape_m = np.shape(weights)
(plates, tiles_m, shape_m) = misc.make_equal_length(
plates,
tiles,
shape_m
)
# Handle broadcasting rules for axes that have unit length in
# the message (although the plate may be non-unit length). Also,
# compute the corresponding broadcasting_multiplier.
plates = list(plates)
tiles_m = list(tiles_m)
for j in range(len(plates)):
if shape_m[j] == 1:
plates[j] = 1
tiles_m[j] = 1
# Combine the tuples by picking every other from tiles_ind and
# every other from shape
shape = functools.reduce(lambda x,y: x+y,
zip(tiles_m, plates))
# ..and reshape the array, that is, every other axis corresponds
# to tiles and every other to plates/dimensions in parents
weights = np.reshape(weights, shape)
# Sum over every other axis
axes = tuple(range(0,len(shape),2))
weights = np.sum(weights, axis=axes)
# Remove extra leading axes
ndim_parent = len(self.parents[index].plates)
weights = misc.squeeze_to_dim(weights, ndim_parent)
return weights
def _compute_message_to_parent(self, index, m, u_X):
m = list(m)
for ind in range(len(m)):
# Idea: Reshape the message array such that every other axis
# will be summed and every other kept.
shape_ind = self._plates_to_parent(index) + self.dims[ind]
# Add variable dimensions to tiles
tiles_ind = tiles + (1,)*len(self.dims[ind])
# Make shape tuples equal length
shape_m = np.shape(m[ind])
(tiles_ind, shape, shape_m) = misc.make_equal_length(tiles_ind,
shape_ind,
shape_m)
# Handle broadcasting rules for axes that have unit length in
# the message (although the plate may be non-unit length). Also,
# compute the corresponding broadcasting multiplier.
r = 1
shape = list(shape)
tiles_ind = list(tiles_ind)
for j in range(len(shape)):
if shape_m[j] == 1:
r *= tiles_ind[j]
shape[j] = 1
tiles_ind[j] = 1
# Combine the tuples by picking every other from tiles_ind and
# every other from shape
shape = functools.reduce(lambda x,y: x+y,
zip(tiles_ind, shape))
# ..and reshape the array, that is, every other axis corresponds
# to tiles and every other to plates/dimensions in parents
m[ind] = np.reshape(m[ind], shape)
# Sum over every other axis
axes = tuple(range(0,len(shape),2))
m[ind] = r * np.sum(m[ind], axis=axes)
# Remove extra leading axes
ndim_parent = len(self.parents[index].get_shape(ind))
m[ind] = misc.squeeze_to_dim(m[ind], ndim_parent)
return m
def _compute_moments(self, u_X):
"""
Tile the plates of the parent's moments.
"""
# Utilize broadcasting: If a tiled axis is unit length in u_X, there
# is no need to tile it.
u = list()
for ind in range(len(u_X)):
ui = u_X[ind]
shape_u = np.shape(ui)
if np.ndim(ui) > 0:
# Add variable dimensions
tiles_ind = tiles + (1,)*len(self.dims[ind])
# Utilize broadcasting: Do not tile leading empty axes
nd = min(len(tiles_ind), np.ndim(ui))
tiles_ind = tiles_ind[(-nd):]
# For simplicity, make tiles and shape equal length
(tiles_ind, shape_u) = misc.make_equal_length(tiles_ind,
shape_u)
# Utilize broadcasting: Use tiling only if the parent's
# moment has non-unit axis length.
tiles_ind = [tile if sh > 1 else 1
for (tile, sh) in zip(tiles_ind, shape_u)]
# Tile
ui = np.tile(ui, tiles_ind)
u.append(ui)
return u
return _Tile(X, name="tile(%s, %s)" % (X.name, tiles))
| 5,576 |
939 | <gh_stars>100-1000
# Copyright 2019 Google 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
#
# https://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.
"""Functions used for Virtual Adversarial Training on dense feature matrices."""
import tensorflow as tf
epsilon = 5
num_power_iterations = 1
xi = 1e-6
scale_r = False
def kl_divergence_with_logit(q_logit, p_logit):
"""Computes KL-divergence between to sets of logits."""
q = tf.nn.softmax(q_logit)
qlogq = -tf.nn.softmax_cross_entropy_with_logits_v2(labels=q, logits=q_logit)
qlogp = -tf.nn.softmax_cross_entropy_with_logits_v2(labels=q, logits=p_logit)
return qlogq - qlogp
def get_normalized_vector(d):
"""Normalizes the provided input vector."""
d /= (1e-12 + tf.reduce_max(tf.abs(d), keep_dims=True))
d /= tf.sqrt(1e-6 + tf.reduce_sum(tf.pow(d, 2.0), keep_dims=True))
return d
def get_normalizing_constant(d):
"""Returns the normalizing constant to scale the VAT perturbation vector."""
c = 1e-12 + tf.reduce_max(tf.abs(d), keep_dims=True)
c *= tf.sqrt(1e-6 + tf.reduce_sum(tf.pow(d, 2.0), keep_dims=True))
return c
def get_loss_vat(inputs, predictions, is_train, model, predictions_var_scope):
"""Computes the virtual adversarial loss for the provided inputs.
Args:
inputs: A batch of input features, where the batch is the first dimension.
predictions: The logits predicted by a model on the provided inputs.
is_train: A boolean placeholder specifying if this is a training or testing
setting.
model: The model that generated the logits.
predictions_var_scope: Variable scope for obtaining the predictions.
Returns:
A float value representing the virtual adversarial loss.
"""
r_vadv = generate_virtual_adversarial_perturbation(
inputs, predictions, model, predictions_var_scope, is_train=is_train)
predictions = tf.stop_gradient(predictions)
logit_p = predictions
new_inputs = tf.add(inputs, r_vadv)
with tf.variable_scope(
predictions_var_scope, auxiliary_name_scope=False, reuse=True):
encoding_m, _, _ = model.get_encoding_and_params(
inputs=new_inputs, is_train=is_train, update_batch_stats=False)
logit_m, _, _ = model.get_predictions_and_params(
encoding=encoding_m, is_train=is_train)
loss = kl_divergence_with_logit(logit_p, logit_m)
return tf.reduce_mean(loss)
def generate_virtual_adversarial_perturbation(inputs,
logits,
model,
predictions_var_scope,
is_train=True):
"""Generates an adversarial perturbation for virtual adversarial training.
Args:
inputs: A batch of input features, where the batch is the first dimension.
logits: The logits predicted by a model on the provided inputs.
model: The model that generated the logits.
predictions_var_scope: Variable scope for obtaining the predictions.
is_train: A boolean placeholder specifying if this is a training or testing
setting.
Returns:
A Tensor of the same shape as the inputs containing the adversarial
perturbation for these inputs.
"""
d = tf.random_normal(shape=tf.shape(inputs))
for _ in range(num_power_iterations):
d = xi * get_normalized_vector(d)
logit_p = logits
with tf.variable_scope(
predictions_var_scope, auxiliary_name_scope=False, reuse=True):
encoding_m, _, _ = model.get_encoding_and_params(
inputs=d + inputs, is_train=is_train, update_batch_stats=False)
logit_m, _, _ = model.get_predictions_and_params(
encoding=encoding_m, is_train=is_train)
dist = kl_divergence_with_logit(logit_p, logit_m)
grad = tf.gradients(dist, [d], aggregation_method=2)[0]
d = tf.stop_gradient(grad)
r_vadv = get_normalized_vector(d)
if scale_r:
r_vadv *= get_normalizing_constant(inputs)
r_vadv *= epsilon
return r_vadv
def entropy_y_x(logits):
"""Entropy term to add to VAT with entropy minimization.
Args:
logits: A Tensor containing the predicted logits for a batch of samples.
Returns:
The entropy minimization loss.
"""
p = tf.nn.softmax(logits)
return tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits_v2(labels=p, logits=logits))
| 1,823 |
988 | /*
* PROGRAM: UTILITIES shared functions prototypes.
* MODULE: util_proto.h
* DESCRIPTION: Prototype header file for util.cpp
*
* The contents of this file are subject to the Interbase Public
* License Version 1.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.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*/
#ifndef UTIL_PROTO_H
#define UTIL_PROTO_H
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
pid_t UTIL_start_process(const char* process, char** argv, const char* prog_name);
int UTIL_wait_for_child(pid_t child_pid, const volatile sig_atomic_t& shutting_down);
int UTIL_shutdown_child(pid_t child_pid, unsigned timeout_term, unsigned timeout_kill);
int UTIL_ex_lock(const char* file);
void UTIL_ex_unlock(int fd_file);
int UTIL_set_handler(int sig, void (*handler) (int), bool restart);
#endif // UTIL_PROTO_H
| 452 |
453 | <filename>ChaseWhisply/src/main/java/fr/tvbarthel/games/chasewhisply/model/bonus/BonusEntryFactory.java
package fr.tvbarthel.games.chasewhisply.model.bonus;
import fr.tvbarthel.games.chasewhisply.R;
import fr.tvbarthel.games.chasewhisply.model.inventory.InventoryItemInformation;
public class BonusEntryFactory {
public static BonusEntry create(int inventoryItemType, long quantity) {
BonusEntry bonusEntry = new BonusEntry(inventoryItemType, quantity);
Bonus bonus = new Bonus.DummyBonus();
int effectResourceId = 0;
switch (inventoryItemType) {
case InventoryItemInformation.TYPE_STEEL_BULLET:
bonus = new BonusDamage(inventoryItemType, 1);
effectResourceId = R.string.bonus_damage_effect;
break;
case InventoryItemInformation.TYPE_GOLD_BULLET:
bonus = new BonusDamage(inventoryItemType, 3);
effectResourceId = R.string.bonus_damage_effect;
break;
case InventoryItemInformation.TYPE_ONE_SHOT_BULLET:
bonus = new BonusDamage(inventoryItemType, 10);
effectResourceId = R.string.bonus_damage_effect;
break;
case InventoryItemInformation.TYPE_SPEED_POTION:
bonus = new BonusSpeed(inventoryItemType, 300);
effectResourceId = R.string.bonus_speed_effect;
break;
}
bonusEntry.setBonus(bonus);
bonusEntry.setEffectResourceId(effectResourceId);
return bonusEntry;
}
}
| 683 |
372 | <reponame>arithmetic1728/google-api-java-client-services
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.content.model;
/**
* The collectionstatus message.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class CollectionStatus extends com.google.api.client.json.GenericJson {
/**
* A list of all issues associated with the collection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CollectionStatusItemLevelIssue> collectionLevelIssuses;
/**
* Date on which the collection has been created in [ISO
* 8601](http://en.wikipedia.org/wiki/ISO_8601) format: Date, time, and offset, e.g.
* "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z"
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationDate;
/**
* The intended destinations for the collection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CollectionStatusDestinationStatus> destinationStatuses;
/**
* Required. The ID of the collection for which status is reported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Date on which the collection has been last updated in [ISO
* 8601](http://en.wikipedia.org/wiki/ISO_8601) format: Date, time, and offset, e.g.
* "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z"
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String lastUpdateDate;
/**
* A list of all issues associated with the collection.
* @return value or {@code null} for none
*/
public java.util.List<CollectionStatusItemLevelIssue> getCollectionLevelIssuses() {
return collectionLevelIssuses;
}
/**
* A list of all issues associated with the collection.
* @param collectionLevelIssuses collectionLevelIssuses or {@code null} for none
*/
public CollectionStatus setCollectionLevelIssuses(java.util.List<CollectionStatusItemLevelIssue> collectionLevelIssuses) {
this.collectionLevelIssuses = collectionLevelIssuses;
return this;
}
/**
* Date on which the collection has been created in [ISO
* 8601](http://en.wikipedia.org/wiki/ISO_8601) format: Date, time, and offset, e.g.
* "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z"
* @return value or {@code null} for none
*/
public java.lang.String getCreationDate() {
return creationDate;
}
/**
* Date on which the collection has been created in [ISO
* 8601](http://en.wikipedia.org/wiki/ISO_8601) format: Date, time, and offset, e.g.
* "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z"
* @param creationDate creationDate or {@code null} for none
*/
public CollectionStatus setCreationDate(java.lang.String creationDate) {
this.creationDate = creationDate;
return this;
}
/**
* The intended destinations for the collection.
* @return value or {@code null} for none
*/
public java.util.List<CollectionStatusDestinationStatus> getDestinationStatuses() {
return destinationStatuses;
}
/**
* The intended destinations for the collection.
* @param destinationStatuses destinationStatuses or {@code null} for none
*/
public CollectionStatus setDestinationStatuses(java.util.List<CollectionStatusDestinationStatus> destinationStatuses) {
this.destinationStatuses = destinationStatuses;
return this;
}
/**
* Required. The ID of the collection for which status is reported.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* Required. The ID of the collection for which status is reported.
* @param id id or {@code null} for none
*/
public CollectionStatus setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Date on which the collection has been last updated in [ISO
* 8601](http://en.wikipedia.org/wiki/ISO_8601) format: Date, time, and offset, e.g.
* "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z"
* @return value or {@code null} for none
*/
public java.lang.String getLastUpdateDate() {
return lastUpdateDate;
}
/**
* Date on which the collection has been last updated in [ISO
* 8601](http://en.wikipedia.org/wiki/ISO_8601) format: Date, time, and offset, e.g.
* "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z"
* @param lastUpdateDate lastUpdateDate or {@code null} for none
*/
public CollectionStatus setLastUpdateDate(java.lang.String lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
return this;
}
@Override
public CollectionStatus set(String fieldName, Object value) {
return (CollectionStatus) super.set(fieldName, value);
}
@Override
public CollectionStatus clone() {
return (CollectionStatus) super.clone();
}
}
| 1,953 |
502 | <reponame>xloya/iceberg<filename>spark/v3.2/spark/src/main/java/org/apache/iceberg/spark/CommitMetadata.java<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.iceberg.spark;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
import org.apache.iceberg.util.ExceptionUtil;
/**
* utility class to accept thread local commit properties
*/
public class CommitMetadata {
private CommitMetadata() {
}
private static final ThreadLocal<Map<String, String>> COMMIT_PROPERTIES = ThreadLocal.withInitial(ImmutableMap::of);
/**
* running the code wrapped as a caller, and any snapshot committed within the callable object will be attached with
* the metadata defined in properties
* @param properties extra commit metadata to attach to the snapshot committed within callable
* @param callable the code to be executed
* @param exClass the expected type of exception which would be thrown from callable
*/
public static <R, E extends Exception> R withCommitProperties(
Map<String, String> properties, Callable<R> callable, Class<E> exClass) throws E {
COMMIT_PROPERTIES.set(properties);
try {
return callable.call();
} catch (Throwable e) {
ExceptionUtil.castAndThrow(e, exClass);
return null;
} finally {
COMMIT_PROPERTIES.set(ImmutableMap.of());
}
}
public static Map<String, String> commitProperties() {
return COMMIT_PROPERTIES.get();
}
}
| 681 |
335 | {
"word": "Hygroscopic",
"definitions": [
"(of a substance) tending to absorb moisture from the air.",
"Relating to humidity or its measurement."
],
"parts-of-speech": "Adjective"
} | 84 |
363 | /*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.error;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.ShouldContainCharSequence.shouldContain;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.Throwables.getStackTrace;
import static org.mockito.internal.util.collections.Sets.newSet;
import java.util.Set;
import org.assertj.core.internal.TestDescription;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Tests for <code>{@link ShouldContainCharSequence#shouldContain(Throwable, CharSequence[], Set)})}</code> and
* <code>{@link ShouldContainCharSequence#shouldContain(Throwable, CharSequence)})}</code>.
*
* @author <NAME>
*/
@DisplayName("ShouldContainThrowable create")
class ShouldContainThrowable_create_Test {
@Test
void should_create_error_message_with_escaping_percent() {
// GIVEN
RuntimeException actual = new RuntimeException("You know nothing %");
// WHEN
String errorMessage = shouldContain(actual, "You know nothing % Jon Snow").create(new TestDescription("TEST"));
// THEN
then(errorMessage).isEqualTo("[TEST] %n" +
"Expecting throwable message:%n" +
" \"You know nothing %%\"%n" +
"to contain:%n" +
" \"You know nothing %% Jon Snow\"%n" +
"but did not.%n" +
"%n" +
"Throwable that failed the check:%n" +
"%n%s", getStackTrace(actual));
}
@Test
void should_create_error_message_with_several_values_not_found() {
// GIVEN
RuntimeException actual = new RuntimeException("You know nothing");
String[] sequence = array("You", "know", "nothing", "Jon", "Snow");
Set<String> notFound = newSet("Jon", "Snow");
// WHEN
String errorMessage = shouldContain(actual, sequence, notFound).create(new TestDescription("TEST"));
// THEN
then(errorMessage).isEqualTo("[TEST] %n" +
"Expecting throwable message:%n" +
" \"You know nothing\"%n" +
"to contain:%n" +
" [\"You\", \"know\", \"nothing\", \"Jon\", \"Snow\"]%n" +
"but could not find:%n" +
" [\"Jon\", \"Snow\"]%n" +
"%n" +
"Throwable that failed the check:%n" +
"%n%s", getStackTrace(actual));
}
}
| 1,449 |
14,668 | <gh_stars>1000+
// Copyright 2017 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 "ash/components/tether/notification_remover.h"
#include <memory>
#include "ash/components/tether/fake_active_host.h"
#include "ash/components/tether/fake_host_scan_cache.h"
#include "ash/components/tether/fake_notification_presenter.h"
#include "ash/components/tether/host_scan_test_util.h"
#include "base/test/task_environment.h"
#include "chromeos/components/multidevice/remote_device_ref.h"
#include "chromeos/components/multidevice/remote_device_test_util.h"
#include "chromeos/network/network_state_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"
namespace ash {
namespace tether {
namespace {
const int kTestSignalStrength = 100;
} // namespace
class NotificationRemoverTest : public testing::Test {
public:
NotificationRemoverTest(const NotificationRemoverTest&) = delete;
NotificationRemoverTest& operator=(const NotificationRemoverTest&) = delete;
protected:
NotificationRemoverTest()
: test_entries_(host_scan_test_util::CreateTestEntries()) {}
void SetUp() override {
notification_presenter_ = std::make_unique<FakeNotificationPresenter>();
host_scan_cache_ = std::make_unique<FakeHostScanCache>();
active_host_ = std::make_unique<FakeActiveHost>();
notification_remover_ = std::make_unique<NotificationRemover>(
helper_.network_state_handler(), notification_presenter_.get(),
host_scan_cache_.get(), active_host_.get());
}
void TearDown() override {
notification_remover_.reset();
}
void NotifyPotentialHotspotNearby() {
notification_presenter_->NotifyPotentialHotspotNearby(
multidevice::CreateRemoteDeviceRefForTest(), 100 /* signal_strength */);
}
void SetAndRemoveHostScanResult() {
host_scan_cache_->SetHostScanResult(
test_entries_.at(host_scan_test_util::kTetherGuid0));
EXPECT_FALSE(host_scan_cache_->empty());
host_scan_cache_->RemoveHostScanResult(host_scan_test_util::kTetherGuid0);
EXPECT_TRUE(host_scan_cache_->empty());
}
void StartConnectingToWifiNetwork() {
std::stringstream ss;
ss << "{"
<< " \"GUID\": \"wifiNetworkGuid\","
<< " \"Type\": \"" << shill::kTypeWifi << "\","
<< " \"State\": \"" << shill::kStateConfiguration << "\""
<< "}";
helper_.ConfigureService(ss.str());
}
base::test::TaskEnvironment task_environment_;
NetworkStateTestHelper helper_{true /* use_default_devices_and_services */};
const std::unordered_map<std::string, HostScanCacheEntry> test_entries_;
std::unique_ptr<FakeNotificationPresenter> notification_presenter_;
std::unique_ptr<FakeHostScanCache> host_scan_cache_;
std::unique_ptr<FakeActiveHost> active_host_;
std::unique_ptr<NotificationRemover> notification_remover_;
};
TEST_F(NotificationRemoverTest, TestCacheBecameEmpty) {
NotifyPotentialHotspotNearby();
SetAndRemoveHostScanResult();
EXPECT_EQ(NotificationPresenter::PotentialHotspotNotificationState::
NO_HOTSPOT_NOTIFICATION_SHOWN,
notification_presenter_->GetPotentialHotspotNotificationState());
notification_presenter_->NotifyMultiplePotentialHotspotsNearby();
SetAndRemoveHostScanResult();
EXPECT_EQ(NotificationPresenter::PotentialHotspotNotificationState::
NO_HOTSPOT_NOTIFICATION_SHOWN,
notification_presenter_->GetPotentialHotspotNotificationState());
}
TEST_F(NotificationRemoverTest, TestStartConnectingToWifiNetwork) {
NotifyPotentialHotspotNearby();
StartConnectingToWifiNetwork();
EXPECT_EQ(NotificationPresenter::PotentialHotspotNotificationState::
NO_HOTSPOT_NOTIFICATION_SHOWN,
notification_presenter_->GetPotentialHotspotNotificationState());
}
TEST_F(NotificationRemoverTest, TestTetherDisabled) {
NotifyPotentialHotspotNearby();
notification_presenter_->NotifySetupRequired("testDevice",
kTestSignalStrength);
notification_presenter_->NotifyConnectionToHostFailed();
notification_remover_.reset();
EXPECT_EQ(NotificationPresenter::PotentialHotspotNotificationState::
NO_HOTSPOT_NOTIFICATION_SHOWN,
notification_presenter_->GetPotentialHotspotNotificationState());
EXPECT_FALSE(notification_presenter_->is_setup_required_notification_shown());
EXPECT_FALSE(
notification_presenter_->is_connection_failed_notification_shown());
}
TEST_F(NotificationRemoverTest, TestActiveHostConnecting) {
NotifyPotentialHotspotNearby();
active_host_->SetActiveHostDisconnected();
EXPECT_EQ(NotificationPresenter::PotentialHotspotNotificationState::
SINGLE_HOTSPOT_NEARBY_SHOWN,
notification_presenter_->GetPotentialHotspotNotificationState());
active_host_->SetActiveHostConnecting("testDeviceId",
host_scan_test_util::kTetherGuid0);
EXPECT_EQ(NotificationPresenter::PotentialHotspotNotificationState::
NO_HOTSPOT_NOTIFICATION_SHOWN,
notification_presenter_->GetPotentialHotspotNotificationState());
}
} // namespace tether
} // namespace ash
| 1,958 |
450 | package java.lang;
public class ArithmeticException extends Exception {
public ArithmeticException(String s) {
super(s);
}
}
| 48 |
435 | {
"copyright_text": "CC BY-NC-SA 4.0",
"description": "The talk will start with a brief introduction into what urllib3 is, what it accomplishes, and why it was created:\r\n\r\n\u201curllib3 is a tool that speaks a special language that lets you download puppy pictures from the Internet\u201d. That language that urllib3 speaks is \u201cHTTP\u201d. HTTP is one of the most important network protocols ever invented, so much so that engineers are rewriting TCP just so cellphones can speak HTTP better and DNS is done over HTTPS because it\u2019s easier to secure HTTP than it is to secure DNS. HTTP is ubiquitous and it\u2019s likely not going away any time soon.\r\n\r\nSo then it matters that Python\u2019s HTTP story is a very good one. In the beginning Python\u2019s included HTTP library had a few key missing features, like supporting HTTPS for security, redirects, connection pooling, thread safety, multipart encoding, retries, and compression. All of these features are necessities of an HTTP library and when urllib3 was first written these things weren\u2019t so easy with the standard library, so Andrey created urllib3 in 2008.\r\n\r\nAround that same time came Python 3, things became even tougher because the HTTP library had changed between Python 2 and 3 along with Python\u2019s handling of binary strings. urllib3 juggles all of these nuances to make HTTP easy for users, especially those who were trying to write libraries that also supported Python 2 and 3 to make the migration between the two major versions smoother.\r\n\r\nNow that 12 years have passed, urllib3 is as ubiquitous within the Python ecosystem as HTTP. The package was downloaded over a billion times in the past 12 months, about 3 millions times per day. And with Python 2 riding off into the sunset our team is looking to solve new challenges coming for Python and HTTP.\n\nAfter three amazing in-person conferences, this time we're moving PyCascades online.\r\n\r\nPyCascades is a regional PyCon in the Pacific Northwest, celebrating the west coast Python developer and user community. Our organizing team includes members of the Vancouver, Seattle, and Portland Python user groups.\r\n\r\nVideos are released as CC BY-NC-SA 4.0.\n\nProduced by Next Day Video Australia: https://nextdayvideo.com.au\n\n#pycascades #pycon #python #conference\n\nSat Feb 20 16:40:00 2021 at Prerecorded Talks",
"duration": 1253,
"language": "eng",
"recorded": "2021-02-20",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://2021.pycascades.com/program/schedule/"
},
{
"label": "https://nextdayvideo.com.au",
"url": "https://nextdayvideo.com.au"
},
{
"label": "https://pretalx.com/pycascades-2021/talk/CCS83U/",
"url": "https://pretalx.com/pycascades-2021/talk/CCS83U/"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"#pycascades#pycon#python#conference",
"pycascades",
"pycascades2021"
],
"thumbnail_url": "https://i.ytimg.com/vi_webp/o9ESKvkuvXM/maxresdefault.webp",
"title": "Shipping Breaking Changes as the Most Downloaded Python Package",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=o9ESKvkuvXM"
}
]
}
| 1,006 |
2,706 | /* Copyright (c) 2013-2015 <NAME>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef GBA_SIO_H
#define GBA_SIO_H
#include <mgba-util/common.h>
CXX_GUARD_START
#include <mgba/gba/interface.h>
#include <mgba/core/log.h>
#define MAX_GBAS 4
extern const int GBASIOCyclesPerTransfer[4][MAX_GBAS];
mLOG_DECLARE_CATEGORY(GBA_SIO);
enum {
RCNT_INITIAL = 0x8000
};
enum {
JOY_CMD_RESET = 0xFF,
JOY_CMD_POLL = 0x00,
JOY_CMD_TRANS = 0x14,
JOY_CMD_RECV = 0x15,
JOYSTAT_TRANS_BIT = 8,
JOYSTAT_RECV_BIT = 2,
};
struct GBASIODriverSet {
struct GBASIODriver* normal;
struct GBASIODriver* multiplayer;
struct GBASIODriver* joybus;
};
struct GBASIO {
struct GBA* p;
enum GBASIOMode mode;
struct GBASIODriverSet drivers;
struct GBASIODriver* activeDriver;
uint16_t rcnt;
// TODO: Convert to bitfields
union {
struct {
unsigned sc : 1;
unsigned internalSc : 1;
unsigned si : 1;
unsigned idleSo : 1;
unsigned : 3;
unsigned start : 1;
unsigned : 4;
unsigned length : 1;
unsigned : 1;
unsigned irq : 1;
unsigned : 1;
} normalControl;
struct {
unsigned baud : 2;
unsigned slave : 1;
unsigned ready : 1;
unsigned id : 2;
unsigned error : 1;
unsigned busy : 1;
unsigned : 6;
unsigned irq : 1;
unsigned : 1;
} multiplayerControl;
uint16_t siocnt;
};
};
void GBASIOInit(struct GBASIO* sio);
void GBASIODeinit(struct GBASIO* sio);
void GBASIOReset(struct GBASIO* sio);
void GBASIOSetDriverSet(struct GBASIO* sio, struct GBASIODriverSet* drivers);
void GBASIOSetDriver(struct GBASIO* sio, struct GBASIODriver* driver, enum GBASIOMode mode);
void GBASIOWriteRCNT(struct GBASIO* sio, uint16_t value);
void GBASIOWriteSIOCNT(struct GBASIO* sio, uint16_t value);
uint16_t GBASIOWriteRegister(struct GBASIO* sio, uint32_t address, uint16_t value);
CXX_GUARD_END
#endif
| 853 |
1,144 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via <EMAIL> or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.apps;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
import com.sun.corba.se.spi.orbutil.threadpool.Work;
import de.metas.workflow.WFNode;
import de.metas.workflow.Workflow;
import de.metas.workflow.WorkflowId;
import lombok.NonNull;
import org.adempiere.ad.element.api.AdWindowId;
import org.adempiere.ad.trx.api.ITrx;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.exceptions.DBException;
import org.adempiere.ui.api.IWindowBL;
import org.compiere.model.I_AD_Menu;
import org.compiere.model.I_AD_WF_Node;
import org.compiere.model.MTask;
import org.compiere.model.MTreeNode;
import org.compiere.model.X_AD_Menu;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.slf4j.Logger;
import de.metas.adempiere.form.IClientUI;
import de.metas.logging.LogManager;
import de.metas.process.ui.ProcessDialog;
import de.metas.util.Check;
import de.metas.util.Services;
/**
* Start application action ( process, workflow, window, form, task etc).
*
* @author <NAME>
*/
public class AMenuStartItem extends SwingWorker<Void, Void>
{
/**
* Start menu item action asynchronously
*
* @param node
* @param menu
*/
public static final void startMenuItem(final MTreeNode node, final AMenu menu)
{
new AMenuStartItem(node, menu).start();
}
/**
* Start menu item action asynchronously
*
* @param adMenuId
* @param name
* @param menu
*/
public static final void startMenuItemById(final int adMenuId, final String name, final AMenu menu)
{
final boolean isMenu = true;
new AMenuStartItem(adMenuId, isMenu, name, menu).start();
}
public static final void startWFNode(
@NonNull final WorkflowId workflowId,
@NonNull final WFNode wfNode,
final AMenu menu)
{
new AMenuStartItem(workflowId, wfNode, menu).start();
}
/**
* Start Menu Item
*
* @param ID ID
* @param isMenu false if Workflow
* @param name Name
* @param menu Menu
*/
private AMenuStartItem(final int ID, final boolean isMenu, final String name, final AMenu menu)
{
super();
m_ID = ID;
m_isMenu = isMenu;
m_name = name;
m_menu = menu == null ? AEnv.getAMenu() : menu;
}
private AMenuStartItem(final MTreeNode node, final AMenu menu)
{
super();
Check.assumeNotNull(node, "node not null");
m_ID = node.getNode_ID();
m_isMenu = true;
m_name = node.getName();
m_menu = menu == null ? AEnv.getAMenu() : menu;
}
private AMenuStartItem(
@NonNull final WorkflowId workflowId,
@NonNull final WFNode wfNode,
final AMenu menu)
{
m_ID = wfNode.getId().getRepoId();
m_isMenu = false;
m_name = wfNode.getName().translate(Env.getADLanguageOrBaseLanguage());
m_menu = menu == null ? AEnv.getAMenu() : menu;
//
// Load
this.action = wfNode.getAction().getCode();
this.adWindowId = wfNode.getAdWindowId();
this.adWorkbenchId = -1;
this.adProcessId = -1; // wfNode.getAD_Process_ID();
this.adFormId = -1; // wfNode.getAD_Form_ID();
this.adTaskId = -1; // wfNode.getAD_Task_ID();
this.adWorkflowId = workflowId;
this.IsSOTrx = true;
this.loaded = true;
}
/** Logger */
private static final transient Logger logger = LogManager.getLogger(AMenuStartItem.class);
/** The ID (AD_Menu_ID or AD_WF_Node_ID) */
private final int m_ID;
/** true if {@link #m_ID} is AD_Menu_ID, false if {@link #m_ID} is AD_WF_Node_ID */
private final boolean m_isMenu;
private final String m_name;
//
private boolean loaded = false;
private String action;
private boolean IsSOTrx = true;
private AdWindowId adWindowId = null;
private int adWorkbenchId = -1;
private int adProcessId = -1;
private WorkflowId adWorkflowId = null;
private int adFormId = -1;
private int adTaskId = -1;
private final AMenu m_menu;
public final void start()
{
lock();
execute();
}
private final void lock()
{
if (m_menu != null)
{
m_menu.setBusy(true);
}
}
private final void unlock()
{
if (m_menu != null)
{
m_menu.setBusy(false);
}
}
@Override
protected Void doInBackground() throws Exception
{
loadIfNeeded();
if (action == null)
{
// shall not happen
throw new AdempiereException("Unknown action");
}
if (X_AD_Menu.ACTION_Window.equals(action))
{
startWindow(0, adWindowId);
}
else if (X_AD_Menu.ACTION_Process.equals(action)
|| X_AD_Menu.ACTION_Report.equals(action))
{
startProcess(adProcessId, IsSOTrx);
}
else if (X_AD_Menu.ACTION_Workbench.equals(action))
{
startWindow(adWorkbenchId, (AdWindowId)null);
}
else if (X_AD_Menu.ACTION_WorkFlow.equals(action))
{
startWorkflow(adWorkflowId);
}
else if (X_AD_Menu.ACTION_Task.equals(action))
{
startTask(adTaskId);
}
else if (X_AD_Menu.ACTION_Form.equals(action))
{
startForm(adFormId);
}
else
{
throw new AdempiereException("Unknown action " + action + " for " + m_ID);
}
return null;
}
private final void loadIfNeeded()
{
if (loaded)
{
return;
}
String sql = "SELECT * FROM AD_Menu WHERE AD_Menu_ID=?";
if (!m_isMenu)
{
sql = "SELECT * FROM AD_WF_Node WHERE AD_WF_Node_ID=?";
}
final Object[] sqlParams = new Object[] { m_ID };
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
if (rs.next()) // should only be one
{
action = rs.getString("Action");
if (m_isMenu)
{
IsSOTrx = DisplayType.toBoolean(rs.getString(I_AD_Menu.COLUMNNAME_IsSOTrx));
}
else
{
IsSOTrx = true;
}
adWindowId = AdWindowId.ofRepoIdOrNull(rs.getInt("AD_Window_ID"));
adProcessId = rs.getInt("AD_Process_ID");
adWorkbenchId = rs.getInt("AD_Workbench_ID");
adWorkflowId = WorkflowId.ofRepoIdOrNull(rs.getInt(m_isMenu ? I_AD_Menu.COLUMNNAME_AD_Workflow_ID : I_AD_WF_Node.COLUMNNAME_Workflow_ID));
adTaskId = rs.getInt("AD_Task_ID");
adFormId = rs.getInt("AD_Form_ID");
loaded = true;
}
}
catch (final SQLException e)
{
throw new DBException(e, sql, sqlParams);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
if (!loaded)
{
throw new AdempiereException("@NotFound@ @" + (m_isMenu ? "AD_Menu_ID" : "AD_WF_Node_ID") + "@=" + m_ID);
}
}
@Override
protected final void done()
{
// Unlock
unlock();
//
// Display errors if any
try
{
get();
}
catch (final InterruptedException e)
{
logger.info("Interrupted", e);
}
catch (final ExecutionException e)
{
final Throwable cause = e.getCause() == null ? e : e.getCause();
Services.get(IClientUI.class).error(Env.WINDOW_MAIN, cause);
}
}
/**
* Start Window
*
* @param AD_Workbench_ID workbench
* @param adWindowId window
*/
private void startWindow(final int AD_Workbench_ID, final AdWindowId adWindowId)
{
// metas-ts: task 05796: moved the code to WindowBL.openWindow() to allow it beeing called on other occasions too
Services.get(IWindowBL.class).openWindow(
m_menu.getWindowManager(),
AD_Workbench_ID,
adWindowId);
} // startWindow
/**
* Start Process. Start/show Process Dialog which calls ProcessCtl
*
* @param AD_Process_ID process
* @param IsSOTrx is SO trx
*/
private void startProcess(final int AD_Process_ID, final boolean IsSOTrx)
{
ProcessDialog.builder()
.setAD_Process_ID(AD_Process_ID)
.setIsSOTrx(IsSOTrx)
.show();
}
private final void startWorkflow(final WorkflowId workflowId)
{
if (m_menu == null)
{
new AdempiereException("Cannot start workflow because no menu")
.throwOrLogWarning(false, logger);
return;
}
m_menu.startWorkFlow(workflowId);
}
/**
* Start OS Task
*
* @param AD_Task_ID task
*/
private void startTask(final int AD_Task_ID)
{
// Get Command
MTask task = null;
if (AD_Task_ID > 0)
{
task = new MTask(Env.getCtx(), AD_Task_ID, ITrx.TRXNAME_None);
}
if (task.getAD_Task_ID() != AD_Task_ID)
{
task = null;
}
if (task == null)
{
return;
}
m_menu.getWindowManager().add(new ATask(m_name, task));
// ATask.start(m_name, task);
} // startTask
/**
* Start Form
*
* @param AD_Form_ID form
*/
private void startForm(final int AD_Form_ID)
{
m_menu.startForm(AD_Form_ID);
} // startForm
}
| 3,904 |
1,915 | // Copyright 2018 The casbin Authors. All Rights Reserved.
//
// 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.casbin.jcasbin.main;
import org.casbin.jcasbin.rbac.RoleManager;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.casbin.jcasbin.main.TestUtil.testDomainEnforce;
import static org.casbin.jcasbin.main.TestUtil.testEnforce;
import static org.casbin.jcasbin.main.TestUtil.testEnforceWithoutUsers;
public class ModelUnitTest {
@Test
public void testBasicModel() {
Enforcer e = new Enforcer("examples/basic_model.conf", "examples/basic_policy.csv");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", false);
testEnforce(e, "alice", "data2", "write", false);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", true);
}
@Test
public void testBasicModelNoPolicy() {
Enforcer e = new Enforcer("examples/basic_model.conf");
testEnforce(e, "alice", "data1", "read", false);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", false);
testEnforce(e, "alice", "data2", "write", false);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", false);
}
@Test
public void testBasicModelWithRoot() {
Enforcer e = new Enforcer("examples/basic_with_root_model.conf", "examples/basic_policy.csv");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", false);
testEnforce(e, "alice", "data2", "write", false);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", true);
testEnforce(e, "root", "data1", "read", true);
testEnforce(e, "root", "data1", "write", true);
testEnforce(e, "root", "data2", "read", true);
testEnforce(e, "root", "data2", "write", true);
}
@Test
public void testBasicModelWithRootNoPolicy() {
Enforcer e = new Enforcer("examples/basic_with_root_model.conf");
testEnforce(e, "alice", "data1", "read", false);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", false);
testEnforce(e, "alice", "data2", "write", false);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", false);
testEnforce(e, "root", "data1", "read", true);
testEnforce(e, "root", "data1", "write", true);
testEnforce(e, "root", "data2", "read", true);
testEnforce(e, "root", "data2", "write", true);
}
@Test
public void testBasicModelWithoutUsers() {
Enforcer e = new Enforcer("examples/basic_without_users_model.conf", "examples/basic_without_users_policy.csv");
testEnforceWithoutUsers(e, "data1", "read", true);
testEnforceWithoutUsers(e, "data1", "write", false);
testEnforceWithoutUsers(e, "data2", "read", false);
testEnforceWithoutUsers(e, "data2", "write", true);
}
@Test
public void testBasicModelWithoutResources() {
Enforcer e = new Enforcer("examples/basic_without_resources_model.conf", "examples/basic_without_resources_policy.csv");
testEnforceWithoutUsers(e, "alice", "read", true);
testEnforceWithoutUsers(e, "alice", "write", false);
testEnforceWithoutUsers(e, "bob", "read", false);
testEnforceWithoutUsers(e, "bob", "write", true);
}
@Test
public void testRBACModel() {
Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", true);
testEnforce(e, "alice", "data2", "write", true);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", true);
}
@Test
public void testRBACModelWithResourceRoles() {
Enforcer e = new Enforcer("examples/rbac_with_resource_roles_model.conf", "examples/rbac_with_resource_roles_policy.csv");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", true);
testEnforce(e, "alice", "data2", "read", false);
testEnforce(e, "alice", "data2", "write", true);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", true);
}
@Test
public void testRBACModelWithDomains() {
Enforcer e = new Enforcer("examples/rbac_with_domains_model.conf", "examples/rbac_with_domains_policy.csv");
testDomainEnforce(e, "alice", "domain1", "data1", "read", true);
testDomainEnforce(e, "alice", "domain1", "data1", "write", true);
testDomainEnforce(e, "alice", "domain1", "data2", "read", false);
testDomainEnforce(e, "alice", "domain1", "data2", "write", false);
testDomainEnforce(e, "bob", "domain2", "data1", "read", false);
testDomainEnforce(e, "bob", "domain2", "data1", "write", false);
testDomainEnforce(e, "bob", "domain2", "data2", "read", true);
testDomainEnforce(e, "bob", "domain2", "data2", "write", true);
}
@Test
public void testRBACModelWithMultiDomains() {
Enforcer e = new Enforcer("examples/rbac_with_multiple_domains_model.conf", "examples/rbac_with_multiple_domains_policy.csv");
testDomainEnforce(e, "alice", "data1", "edit", Arrays.asList("dom1","dom2","dom3"),false);
testDomainEnforce(e, "alice", "data1", "read", Arrays.asList("dom1","dom2","dom3"),true);
testDomainEnforce(e, "alice", "data1", "write", Arrays.asList("dom1","dom2","dom3"),true);
}
@Test
public void testRBACModelWithDomainsAtRuntime() {
Enforcer e = new Enforcer("examples/rbac_with_domains_model.conf");
e.addPolicy("admin", "domain1", "data1", "read");
e.addPolicy("admin", "domain1", "data1", "write");
e.addPolicy("admin", "domain2", "data2", "read");
e.addPolicy("admin", "domain2", "data2", "write");
e.addGroupingPolicy("alice", "admin", "domain1");
e.addGroupingPolicy("bob", "admin", "domain2");
testDomainEnforce(e, "alice", "domain1", "data1", "read", true);
testDomainEnforce(e, "alice", "domain1", "data1", "write", true);
testDomainEnforce(e, "alice", "domain1", "data2", "read", false);
testDomainEnforce(e, "alice", "domain1", "data2", "write", false);
testDomainEnforce(e, "bob", "domain2", "data1", "read", false);
testDomainEnforce(e, "bob", "domain2", "data1", "write", false);
testDomainEnforce(e, "bob", "domain2", "data2", "read", true);
testDomainEnforce(e, "bob", "domain2", "data2", "write", true);
// Remove all policy rules related to domain1 and data1.
e.removeFilteredPolicy(1, "domain1", "data1");
testDomainEnforce(e, "alice", "domain1", "data1", "read", false);
testDomainEnforce(e, "alice", "domain1", "data1", "write", false);
testDomainEnforce(e, "alice", "domain1", "data2", "read", false);
testDomainEnforce(e, "alice", "domain1", "data2", "write", false);
testDomainEnforce(e, "bob", "domain2", "data1", "read", false);
testDomainEnforce(e, "bob", "domain2", "data1", "write", false);
testDomainEnforce(e, "bob", "domain2", "data2", "read", true);
testDomainEnforce(e, "bob", "domain2", "data2", "write", true);
// Remove the specified policy rule.
e.removePolicy("admin", "domain2", "data2", "read");
testDomainEnforce(e, "alice", "domain1", "data1", "read", false);
testDomainEnforce(e, "alice", "domain1", "data1", "write", false);
testDomainEnforce(e, "alice", "domain1", "data2", "read", false);
testDomainEnforce(e, "alice", "domain1", "data2", "write", false);
testDomainEnforce(e, "bob", "domain2", "data1", "read", false);
testDomainEnforce(e, "bob", "domain2", "data1", "write", false);
testDomainEnforce(e, "bob", "domain2", "data2", "read", false);
testDomainEnforce(e, "bob", "domain2", "data2", "write", true);
}
@Test
public void testRBACModelWithDeny() {
Enforcer e = new Enforcer("examples/rbac_with_deny_model.conf", "examples/rbac_with_deny_policy.csv");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", true);
testEnforce(e, "alice", "data2", "write", false);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", true);
}
@Test
public void testRBACModelWithOnlyDeny() {
Enforcer e = new Enforcer("examples/rbac_with_not_deny_model.conf", "examples/rbac_with_deny_policy.csv");
testEnforce(e, "alice", "data2", "write", false);
}
@Test
public void testRBACModelWithCustomData() {
Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
// You can add custom data to a grouping policy, Casbin will ignore it. It is only
// meaningful to the caller.
// This feature can be used to store information like whether "bob" is an end user (so no
// subject will inherit "bob")
// For Casbin, it is equivalent to: e.addGroupingPolicy("bob", "data2_admin")
e.addGroupingPolicy("bob", "data2_admin", "custom_data");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", true);
testEnforce(e, "alice", "data2", "write", true);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", true);
testEnforce(e, "bob", "data2", "write", true);
// You should also take the custom data as a parameter when deleting a grouping policy.
// e.removeGroupingPolicy("bob", "data2_admin") won't work.
// Or you can remove it by using removeFilteredGroupingPolicy().
e.removeGroupingPolicy("bob", "data2_admin", "custom_data");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", true);
testEnforce(e, "alice", "data2", "write", true);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", true);
}
class CustomRoleManager implements RoleManager {
@Override
public void clear() {
}
@Override
public void addLink(String name1, String name2, String... domain) {
}
@Override
public void deleteLink(String name1, String name2, String... domain) {
}
@Override
public boolean hasLink(String name1, String name2, String... domain) {
if (name1.equals("alice") && name2.equals("alice")) {
return true;
} else if (name1.equals("alice") && name2.equals("data2_admin")) {
return true;
} else if (name1.equals("bob") && name2.equals("bob")) {
return true;
}
return false;
}
@Override
public List<String> getRoles(String name, String... domain) {
return null;
}
@Override
public List<String> getUsers(String name, String... domain) {
return null;
}
@Override
public void printRoles() {
}
}
@Test
public void testRBACModelWithCustomRoleManager() {
Enforcer e = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
e.setRoleManager(new CustomRoleManager());
e.loadModel();
e.loadPolicy();
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", true);
testEnforce(e, "alice", "data2", "write", true);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", false);
testEnforce(e, "bob", "data2", "write", true);
}
public static class TestResource {
String name;
String owner;
public TestResource(String name, String owner) {
this.name = name;
this.owner = owner;
}
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
}
@Test
public void testABACModel() {
Enforcer e = new Enforcer("examples/abac_model.conf");
TestResource data1 = new TestResource("data1", "alice");
TestResource data2 = new TestResource("data2", "bob");
testEnforce(e, "alice", data1, "read", true);
testEnforce(e, "alice", data1, "write", true);
testEnforce(e, "alice", data2, "read", false);
testEnforce(e, "alice", data2, "write", false);
testEnforce(e, "bob", data1, "read", false);
testEnforce(e, "bob", data1, "write", false);
testEnforce(e, "bob", data2, "read", true);
testEnforce(e, "bob", data2, "write", true);
}
@Test
public void testKeyMatchModel() {
Enforcer e = new Enforcer("examples/keymatch_model.conf", "examples/keymatch_policy.csv");
testEnforce(e, "alice", "/alice_data/resource1", "GET", true);
testEnforce(e, "alice", "/alice_data/resource1", "POST", true);
testEnforce(e, "alice", "/alice_data/resource2", "GET", true);
testEnforce(e, "alice", "/alice_data/resource2", "POST", false);
testEnforce(e, "alice", "/bob_data/resource1", "GET", false);
testEnforce(e, "alice", "/bob_data/resource1", "POST", false);
testEnforce(e, "alice", "/bob_data/resource2", "GET", false);
testEnforce(e, "alice", "/bob_data/resource2", "POST", false);
testEnforce(e, "bob", "/alice_data/resource1", "GET", false);
testEnforce(e, "bob", "/alice_data/resource1", "POST", false);
testEnforce(e, "bob", "/alice_data/resource2", "GET", true);
testEnforce(e, "bob", "/alice_data/resource2", "POST", false);
testEnforce(e, "bob", "/bob_data/resource1", "GET", false);
testEnforce(e, "bob", "/bob_data/resource1", "POST", true);
testEnforce(e, "bob", "/bob_data/resource2", "GET", false);
testEnforce(e, "bob", "/bob_data/resource2", "POST", true);
testEnforce(e, "cathy", "/cathy_data", "GET", true);
testEnforce(e, "cathy", "/cathy_data", "POST", true);
testEnforce(e, "cathy", "/cathy_data", "DELETE", false);
}
@Test
public void testKeyMatch2Model() {
Enforcer e = new Enforcer("examples/keymatch2_model.conf", "examples/keymatch2_policy.csv");
testEnforce(e, "alice", "/alice_data", "GET", false);
testEnforce(e, "alice", "/alice_data/resource1", "GET", true);
testEnforce(e, "alice", "/alice_data2/myid", "GET", false);
testEnforce(e, "alice", "/alice_data2/myid/using/res_id", "GET", true);
}
@Test
public void testIPMatchModel() {
Enforcer e = new Enforcer("examples/ipmatch_model.conf", "examples/ipmatch_policy.csv");
testEnforce(e, "192.168.2.123", "data1", "read", true);
testEnforce(e, "192.168.2.123", "data1", "write", false);
testEnforce(e, "192.168.2.123", "data2", "read", false);
testEnforce(e, "192.168.2.123", "data2", "write", false);
testEnforce(e, "192.168.0.123", "data1", "read", false);
testEnforce(e, "192.168.0.123", "data1", "write", false);
testEnforce(e, "192.168.0.123", "data2", "read", false);
testEnforce(e, "192.168.0.123", "data2", "write", false);
testEnforce(e, "10.0.0.5", "data1", "read", false);
testEnforce(e, "10.0.0.5", "data1", "write", false);
testEnforce(e, "10.0.0.5", "data2", "read", false);
testEnforce(e, "10.0.0.5", "data2", "write", true);
testEnforce(e, "192.168.0.1", "data1", "read", false);
testEnforce(e, "192.168.0.1", "data1", "write", false);
testEnforce(e, "192.168.0.1", "data2", "read", false);
testEnforce(e, "192.168.0.1", "data2", "write", false);
}
@Test
public void testPriorityModel() {
Enforcer e = new Enforcer("examples/priority_model.conf", "examples/priority_policy.csv");
testEnforce(e, "alice", "data1", "read", true);
testEnforce(e, "alice", "data1", "write", false);
testEnforce(e, "alice", "data2", "read", false);
testEnforce(e, "alice", "data2", "write", false);
testEnforce(e, "bob", "data1", "read", false);
testEnforce(e, "bob", "data1", "write", false);
testEnforce(e, "bob", "data2", "read", true);
testEnforce(e, "bob", "data2", "write", false);
}
@Test
public void testPriorityModelIndeterminate() {
Enforcer e = new Enforcer("examples/priority_model.conf", "examples/priority_indeterminate_policy.csv");
testEnforce(e, "alice", "data1", "read", false);
}
@Test
public void testGlobMatchModel() {
Enforcer e = new Enforcer("examples/glob_model.conf", "examples/glob_policy.csv");
testEnforce(e, "u1", "/foo/", "read", true);
testEnforce(e, "u1", "/foo", "read", false);
testEnforce(e, "u1", "/foo/subprefix", "read", true);
testEnforce(e, "u1", "foo", "read", false);
testEnforce(e, "u2", "/foosubprefix", "read", true);
testEnforce(e, "u2", "/foo/subprefix", "read", false);
testEnforce(e, "u2", "foo", "read", false);
testEnforce(e, "u3", "/prefix/foo/subprefix", "read", true);
testEnforce(e, "u3", "/prefix/foo/", "read", true);
testEnforce(e, "u3", "/prefix/foo", "read", false);
testEnforce(e, "u4", "/foo", "read", false);
testEnforce(e, "u4", "foo", "read", true);
}
}
| 8,766 |
433 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
cherry.api
~~~~~~~~~~~~
This module implements the cherry API.
:copyright: (c) 2018-2019 by <NAME>
:license: MIT License, see LICENSE for more details.
"""
from .base import load_data
from .trainer import Trainer
from .classifyer import Classify
from .performancer import Performance
from .searcher import Search
from .displayer import Display
def classify(model, text):
'''
Return a Classify object which contains *probability* and *word_list*
input: text (list of string): the text to be classified
number of word list (int): how many word should be list in the word list
output: Classify (Classify object)
'''
return Classify(model=model, text=text)
def train(model, language='English', preprocessing=None, categories=None, encoding='utf-8',
vectorizer=None, vectorizer_method='Count', clf=None, clf_method='MNB', x_data=None, y_data=None):
'''
Train the `model` inside data directory
*model (string): model name of the training dataset (e.g. 'harmful')
language (string): The language of the data
vectorizer (BaseEstimator object): feature extraction method, CountVectorizer, TfidfVectorizer, HashingVectorizer etc.
clf (Classifier object): Classifier object, DecisionTreeClassifier, RandomForestClassifier, AdaBoostClassifier etc.
x_data (array): training data
y_data (array): training label
'''
return Trainer(
model, language=language, preprocessing=preprocessing, encoding=encoding,
categories=categories, vectorizer=vectorizer, vectorizer_method=vectorizer_method,
clf=clf, clf_method=clf_method, x_data=x_data, y_data=y_data)
def performance(model, language='English', preprocessing=None, categories=None, encoding='utf-8',
vectorizer=None, vectorizer_method='Count', clf=None, clf_method='MNB', x_data=None,
y_data=None, n_splits=10, output='Stdout'):
'''
Calculate scores from the models
'''
return Performance(
model, language=language, preprocessing=preprocessing, encoding=encoding,
categories=categories, vectorizer=vectorizer, vectorizer_method=vectorizer_method,
clf=clf, clf_method=clf_method, x_data=x_data, y_data=y_data,
n_splits=n_splits, output=output)
def search(model, parameters, language='English', preprocessing=None, categories=None, encoding='utf-8',
vectorizer=None, vectorizer_method='Count', clf=None, clf_method='MNB', x_data=None,
y_data=None, method='RandomizedSearchCV', cv=3, n_jobs=-1):
'''
Search the best parameters
'''
return Search(
model, parameters, language=language, preprocessing=preprocessing, encoding=encoding,
categories=categories, vectorizer=vectorizer,
vectorizer_method=vectorizer_method, clf=clf, clf_method=clf_method,
method=method, x_data=x_data, y_data=y_data, cv=cv, n_jobs=n_jobs)
def display(model, language='English', preprocessing=None, categories=None, encoding='utf-8',
vectorizer=None, vectorizer_method='Count', clf=None, clf_method='MNB', x_data=None, y_data=None):
'''
Display the learning curve
'''
return Display(
model, language=language, preprocessing=preprocessing, encoding=encoding,
categories=categories, vectorizer=vectorizer, vectorizer_method=vectorizer_method,
clf=clf, clf_method=clf_method, x_data=x_data, y_data=y_data)
| 1,293 |
14,425 | /**
* 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.hadoop.yarn.server.resourcemanager.federation;
import java.io.StringWriter;
import javax.xml.bind.JAXBException;
import org.apache.hadoop.yarn.server.federation.store.FederationStateStore;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterHeartbeatRequest;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterId;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterState;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ClusterMetricsInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONMarshaller;
/**
* Periodic heart beat from a <code>ResourceManager</code> participating in
* federation to indicate liveliness. The heart beat publishes the current
* capabilities as represented by {@link ClusterMetricsInfo} of the sub cluster.
*
*/
public class FederationStateStoreHeartbeat implements Runnable {
private static final Logger LOG =
LoggerFactory.getLogger(FederationStateStoreHeartbeat.class);
private SubClusterId subClusterId;
private FederationStateStore stateStoreService;
private final ResourceScheduler rs;
private StringWriter currentClusterState;
private JSONJAXBContext jc;
private JSONMarshaller marshaller;
private String capability;
public FederationStateStoreHeartbeat(SubClusterId subClusterId,
FederationStateStore stateStoreClient, ResourceScheduler scheduler) {
this.stateStoreService = stateStoreClient;
this.subClusterId = subClusterId;
this.rs = scheduler;
// Initialize the JAXB Marshaller
this.currentClusterState = new StringWriter();
try {
this.jc = new JSONJAXBContext(
JSONConfiguration.mapped().rootUnwrapping(false).build(),
ClusterMetricsInfo.class);
marshaller = jc.createJSONMarshaller();
} catch (JAXBException e) {
LOG.warn("Exception while trying to initialize JAXB context.", e);
}
LOG.info("Initialized Federation membership for cluster with timestamp: "
+ ResourceManager.getClusterTimeStamp());
}
/**
* Get the current cluster state as a JSON string representation of the
* {@link ClusterMetricsInfo}.
*/
private void updateClusterState() {
try {
// get the current state
currentClusterState.getBuffer().setLength(0);
ClusterMetricsInfo clusterMetricsInfo = new ClusterMetricsInfo(rs);
marshaller.marshallToJSON(clusterMetricsInfo, currentClusterState);
capability = currentClusterState.toString();
} catch (Exception e) {
LOG.warn("Exception while trying to generate cluster state,"
+ " so reverting to last know state.", e);
}
}
@Override
public synchronized void run() {
try {
updateClusterState();
SubClusterHeartbeatRequest request = SubClusterHeartbeatRequest
.newInstance(subClusterId, SubClusterState.SC_RUNNING, capability);
stateStoreService.subClusterHeartbeat(request);
LOG.debug("Sending the heartbeat with capability: {}", capability);
} catch (Exception e) {
LOG.warn("Exception when trying to heartbeat: ", e);
}
}
} | 1,326 |
388 | package cn.wizzer.iot.mqtt;
import cn.wizzer.iot.model.IotDev;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
/**
* 接收者消息回调
* @author <EMAIL>
*/
@IocBean
public class MqttRecieveCallback implements MqttCallback {
private static final Log log = Logs.get();
@Inject
private Dao dao;
public void connectionLost(Throwable cause) {
log.error(cause);
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Client 接收消息主题 : " + topic);
System.out.println("Client 接收消息Qos : " + message.getQos());
System.out.println("Client 接收消息内容 : " + new String(message.getPayload()));
String devId = topic;
if(topic.contains("/")){
devId=topic.substring(topic.lastIndexOf("/")+1);
System.out.println("设备ID : " + devId);
IotDev iotDev=new IotDev();
iotDev.setDevId(devId);
iotDev.setDevData(new String(message.getPayload()));
insert(iotDev);
}
}
public void deliveryComplete(IMqttDeliveryToken token) {
}
// 异步插入数据库
@Async
public void insert(IotDev iotDev){
dao.fastInsert(iotDev);
}
}
| 742 |
1,584 | /*
* Copyright (c) 1991-2013 Kawahara Lab., Kyoto University
* Copyright (c) 2000-2005 Shikano Lab., Nara Institute of Science and Technology
* Copyright (c) 2005-2013 Julius project team, Nagoya Institute of Technology
* All rights reserved
*/
/* next_word functions */
#include "common.h"
#include "gen_next.h"
extern WORD_INFO *winfo;
extern DFA_INFO *dfa;
NEXTWORD **
nw_malloc()
{
NEXTWORD **nw;
NEXTWORD *nwtmp;
int i;
int maxnw;
maxnw = winfo->num * 2; /* NOISE$B$rHt$P$9J,(B */
/* $BO"B3NN0h$rG[Ns$K3d$jEv$F$k(B */
nw = (NEXTWORD **)malloc(maxnw * sizeof(NEXTWORD *));
nwtmp = (NEXTWORD *)malloc(maxnw * sizeof(NEXTWORD));
nw[0] = nwtmp;
for (i=1;i<maxnw; i++) {
nw[i] = &(nwtmp[i]);
}
return nw;
}
/* $BM=B,<!C18l3JG<NN0h$N2rJ|(B */
void
nw_free(NEXTWORD **nw)
{
free(nw[0]);
free(nw);
}
/* $B=i4|>uBV$+$iA+0\$7$&$kC18l=89g$rJV$9(B */
/* $BJV$jCM(B: $BC18l?t(B*/
/* NOISE: $B$3$3$K$OMh$J$$;EMM(B */
int
dfa_firstwords(NEXTWORD **nw)
{
DFA_ARC *arc;
int i, cate, iw, ns;
int num = 0;
for (i=0;i<dfa->state_num;i++) {
if ((dfa->st[i].status & INITIAL_S) != 0) { /* $B=i4|>uBV$+$i(B */
for (arc = dfa->st[i].arc; arc; arc = arc->next) { /* $BA4$F$NA+0\(B */
cate = arc->label;
ns = arc->to_state;
/* $BA+0\$KBP1~$9$k%+%F%4%jFb$NA4C18l$rE83+(B */
for (iw=0;iw<dfa->term.wnum[cate];iw++) {
nw[num]->id = dfa->term.tw[cate][iw];
nw[num]->next_state = ns;
nw[num]->can_insert_sp = FALSE;
num++;
}
}
}
}
return num;
}
int
dfa_firstterms(NEXTWORD **nw)
{
DFA_ARC *arc;
int i, cate, ns;
int num = 0;
for (i=0;i<dfa->state_num;i++) {
if ((dfa->st[i].status & INITIAL_S) != 0) { /* $B=i4|>uBV$+$i(B */
for (arc = dfa->st[i].arc; arc; arc = arc->next) { /* $BA4$F$NA+0\(B */
cate = arc->label;
ns = arc->to_state;
/* $BA+0\$KBP1~$9$k%+%F%4%jFb$N(B1$BC18l$rE83+(B */
if (dfa->term.wnum[cate] == 0) continue;
nw[num]->id = dfa->term.tw[cate][0];
nw[num]->next_state = ns;
nw[num]->can_insert_sp = FALSE;
num++;
}
}
}
return num;
}
/* $B<!$K@\B3$7F@$kC18l72$rJV$9(B */
/* $BJV$jCM(B:$BC18l?t(B */
/* NOISE: $B@h$^$G8+$F!$(Bcan_insert_sp=TRUE$B$GJV$9(B */
int
dfa_nextwords(NODE *hypo, NEXTWORD **nw)
{
DFA_ARC *arc, *arc2;
int iw,cate,ns,cate2,ns2;
int num = 0;
for (arc = dfa->st[hypo->state].arc; arc; arc = arc->next) {
cate = arc->label;
ns = arc->to_state;
if (dfa->is_sp[cate]) {
/* $B@h$^$G8+$k!#<+J,$OE83+$7$J$$(B */
for (arc2 = dfa->st[ns].arc; arc2; arc2 = arc2->next) {
cate2 = arc2->label;
ns2 = arc2->to_state;
for (iw=0;iw<dfa->term.wnum[cate2];iw++) {
nw[num]->id = dfa->term.tw[cate2][iw];
nw[num]->next_state = ns2;
nw[num]->can_insert_sp = TRUE;
num++;
}
}
} else {
/* $BA+0\$KBP1~$9$k%+%F%4%jFb$NA4C18l$rE83+(B */
for (iw=0;iw<dfa->term.wnum[cate];iw++) {
nw[num]->id = dfa->term.tw[cate][iw];
nw[num]->next_state = ns;
nw[num]->can_insert_sp = FALSE;
num++;
}
}
}
return num;
}
int
dfa_nextterms(NODE *hypo, NEXTWORD **nw)
{
DFA_ARC *arc, *arc2;
int cate,ns,cate2,ns2;
int num = 0;
for (arc = dfa->st[hypo->state].arc; arc; arc = arc->next) {
cate = arc->label;
ns = arc->to_state;
if (dfa->is_sp[cate]) {
/* $B@h$^$G8+$k!#<+J,$OE83+$7$J$$(B */
for (arc2 = dfa->st[ns].arc; arc2; arc2 = arc2->next) {
cate2 = arc2->label;
ns2 = arc2->to_state;
if (dfa->term.wnum[cate2] == 0) continue;
nw[num]->id = dfa->term.tw[cate2][0];
nw[num]->next_state = ns2;
nw[num]->can_insert_sp = TRUE;
num++;
}
} else {
/* $BA+0\$KBP1~$9$k%+%F%4%jFb$NA4C18l$rE83+(B */
if (dfa->term.wnum[cate] == 0) continue;
nw[num]->id = dfa->term.tw[cate][0];
nw[num]->next_state = ns;
nw[num]->can_insert_sp = FALSE;
num++;
}
}
return num;
}
/* $B2>@b$,J8$H$7$F<uM}2DG=$G$"$k$+$I$&$+$rJV$9(B */
/* NOISE: $B$3$3$K$O$3$J$$;EMM(B */
boolean
dfa_acceptable(NODE *hypo)
{
/* $B<uM}>uBV$J$i(B */
if (dfa->st[hypo->state].status & ACCEPT_S) {
return TRUE;
} else {
return FALSE;
}
}
| 2,359 |
343 | // Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.
#include "syzygy/refinery/types/typed_data.h"
#include "base/logging.h"
#include "syzygy/refinery/types/type_repository.h"
namespace refinery {
namespace {
bool IsFieldOf(TypePtr type, FieldPtr field) {
DCHECK(type); DCHECK(field);
UserDefinedTypePtr udt;
if (!type->CastTo(&udt))
return false;
for (FieldPtr f : udt->fields()) {
if (*f == *field)
return true;
}
return false;
}
} // namespace
TypedData::TypedData() : bit_source_(nullptr) {
}
TypedData::TypedData(BitSource* bit_source, TypePtr type, Address addr)
: bit_source_(bit_source),
type_(type),
addr_(addr),
bit_pos_(0),
bit_len_(0) {
DCHECK(bit_source_);
DCHECK(type_);
}
TypedData::TypedData(BitSource* bit_source,
TypePtr type,
Address addr,
uint8_t bit_pos,
uint8_t bit_len)
: bit_source_(bit_source),
type_(type),
addr_(addr),
bit_pos_(bit_pos),
bit_len_(bit_len) {
DCHECK(bit_source_);
DCHECK(type_);
DCHECK(bit_pos >= 0 && bit_pos < type_->size() * 8);
DCHECK(bit_len >= 0 && bit_len < type_->size() * 8);
}
bool TypedData::IsValid() const {
return bit_source_ != nullptr && type_ != nullptr;
}
bool TypedData::IsPrimitiveType() const {
DCHECK(type_);
switch (type_->kind()) {
case Type::BASIC_TYPE_KIND:
case Type::POINTER_TYPE_KIND:
return true;
default:
return false;
}
}
bool TypedData::IsPointerType() const {
DCHECK(type_);
return type_->kind() == Type::POINTER_TYPE_KIND;
}
bool TypedData::IsArrayType() const {
DCHECK(type_);
return type_->kind() == Type::ARRAY_TYPE_KIND;
}
bool TypedData::IsUserDefinedType() const {
DCHECK(type_);
return type_->kind() == Type::USER_DEFINED_TYPE_KIND;
}
bool TypedData::GetNamedField(const base::StringPiece16& name,
TypedData* out) const {
DCHECK(out);
// TODO(siggi): Does it ever make sense to request a nameless field?
DCHECK(!name.empty());
DCHECK(type_);
UserDefinedTypePtr udt;
if (!type_->CastTo(&udt))
return false;
const UserDefinedType::Fields& fields = udt->fields();
for (size_t i = 0; i < fields.size(); ++i) {
FieldPtr field = fields[i];
MemberFieldPtr member;
if (!field->CastTo(&member))
continue;
if (name == member->name())
return GetField(i, out);
}
return false;
}
bool TypedData::GetField(size_t field_no, TypedData* out) const {
DCHECK(type_);
DCHECK(IsUserDefinedType());
DCHECK(out);
FieldPtr field;
if (!GetField(field_no, &field))
return false;
uint8_t bit_pos = 0U;
uint8_t bit_len = 0U;
MemberFieldPtr member;
if (field->CastTo(&member)) {
bit_pos = static_cast<uint8_t>(member->bit_pos());
bit_len = static_cast<uint8_t>(member->bit_len());
}
*out = TypedData(bit_source_, field->GetType(), addr() + field->offset(),
bit_pos, bit_len);
return true;
}
bool TypedData::GetField(size_t field_no, FieldPtr* out) const {
DCHECK(type_);
DCHECK(IsUserDefinedType());
DCHECK(out);
UserDefinedTypePtr udt;
if (!type_->CastTo(&udt))
return false;
if (field_no >= udt->fields().size())
return false;
*out = udt->fields()[field_no];
return true;
}
bool TypedData::GetFieldCount(size_t* count) const {
DCHECK(type_);
DCHECK(IsUserDefinedType());
UserDefinedTypePtr udt;
if (!type_->CastTo(&udt))
return false;
*count = udt->fields().size();
return true;
}
bool TypedData::GetSignedValue(int64_t* value) const {
DCHECK(value);
DCHECK(IsPrimitiveType());
DCHECK(bit_source_);
int64_t ret = 0;
switch (type_->size()) {
case sizeof(int8_t): {
int8_t v8 = 0;
if (!GetData(&v8))
return false;
ret = v8;
break;
}
case sizeof(int16_t): {
int16_t v16 = 0;
if (!GetData(&v16))
return false;
ret = v16;
break;
}
case sizeof(int32_t): {
int32_t v32 = 0;
if (!GetData(&v32))
return false;
ret = v32;
break;
}
case sizeof(int64_t): {
int64_t v64 = 0;
if (!GetData(&v64))
return false;
ret = v64;
break;
}
default:
// Wonky size - no can do this. Maybe this type is a float or such?
return false;
}
// Shift, mask and sign-extend bit fields.
if (bit_len_ != 0) {
// Shift the bits into place.
ret >>= bit_pos_;
// Mask to the used bits.
const uint64_t mask = (1ll << bit_len_) - 1;
ret &= mask;
// Check the sign bit and extend out if set.
if (ret & (mask ^ (mask >> 1)))
ret |= (-1ll & ~mask);
}
*value = ret;
return true;
}
bool TypedData::GetUnsignedValue(uint64_t* value) const {
DCHECK(value);
DCHECK(IsPrimitiveType());
DCHECK(bit_source_);
uint64_t ret = 0;
switch (type_->size()) {
case sizeof(uint8_t): {
uint8_t v8 = 0;
if (!GetData(&v8))
return false;
ret = v8;
break;
}
case sizeof(uint16_t): {
uint16_t v16 = 0;
if (!GetData(&v16))
return false;
ret = v16;
break;
}
case sizeof(uint32_t): {
uint32_t v32 = 0;
if (!GetData(&v32))
return false;
ret = v32;
break;
}
case sizeof(uint64_t): {
uint64_t v64 = 0;
if (!GetData(&v64))
return false;
ret = v64;
break;
}
default:
// Wonky size - no can do this. Maybe this type is a float or such?
return false;
}
// Shift & mask bit fields.
if (bit_len_ != 0) {
// Shift the bits uinto place.
ret >>= bit_pos_;
// Mask to the used bits.
const uint64_t mask = (1ull << bit_len_) - 1;
ret &= mask;
}
*value = ret;
return true;
}
bool TypedData::GetPointerValue(Address* value) const {
DCHECK(value);
DCHECK(IsPointerType());
DCHECK_EQ(0, bit_len_); // Bitfields need not apply for pointer.
DCHECK(bit_source_);
PointerTypePtr ptr_type;
if (!type_->CastTo(&ptr_type))
return false;
// Cater for 32- and 64-bit pointers.
if (ptr_type->size() == sizeof(uint32_t)) {
// The pointer size is 32 bit.
uint32_t addr_32 = 0;
if (GetData(&addr_32)) {
*value = addr_32;
return true;
}
} else if (ptr_type->size() == sizeof(uint64_t)) {
// The pointer size is 64 bit.
if (GetData(value))
return true;
}
// The pointer size is strange or we failed on retrieving the value.
return false;
}
bool TypedData::Dereference(TypedData* referenced_data) const {
DCHECK(referenced_data);
DCHECK(IsPointerType());
DCHECK(bit_source_);
PointerTypePtr ptr_type;
if (!type_->CastTo(&ptr_type))
return false;
TypePtr content_type = ptr_type->GetContentType();
if (!content_type)
return false;
Address addr = 0;
if (!GetPointerValue(&addr))
return false;
*referenced_data = TypedData(bit_source_, content_type, addr);
return true;
}
bool TypedData::GetArrayElement(size_t index, TypedData* element_data) const {
DCHECK(element_data);
DCHECK(IsArrayType());
DCHECK(bit_source_);
ArrayTypePtr array_ptr;
if (!type_->CastTo(&array_ptr))
return false;
if (index >= array_ptr->num_elements())
return false;
TypePtr element_type = array_ptr->GetElementType();
if (!element_type)
return false;
*element_data = TypedData(bit_source_, element_type,
addr() + index * element_type->size());
return true;
}
bool TypedData::OffsetAndCast(ptrdiff_t offs,
TypePtr new_type,
TypedData* output) const {
DCHECK(output);
if (!new_type)
return false;
if (!IsValid())
return false;
return OffsetBytesAndCast(offs * type()->size(), new_type, output);
}
bool TypedData::OffsetBytesAndCast(ptrdiff_t offs,
TypePtr new_type,
TypedData* output) const {
DCHECK(output);
if (!new_type)
return false;
if (!IsValid())
return false;
// TODO(siggi): Validate the new range against the bit source with a new
// interface.
*output = TypedData(bit_source(), new_type, addr() + offs);
return true;
}
AddressRange TypedData::GetRange() const {
return AddressRange(addr(), type()->size());
}
bool TypedData::GetDataImpl(void* data, size_t data_size) const {
DCHECK(data);
DCHECK(IsPrimitiveType());
DCHECK(bit_source_);
if (data_size != type_->size())
return false;
return bit_source_->GetAll(GetRange(), data);
}
} // namespace refinery
| 3,880 |
1,800 | <reponame>anticrisis/go-sdl2
#if defined(__WIN32)
#include <SDL2/SDL_ttf.h>
#include <stdlib.h>
#else
#include <SDL_ttf.h>
#endif
| 69 |
1,100 | package com.xncoding.pos.service;
import com.xncoding.pos.dao.entity.Customer;
import com.xncoding.pos.dao.repository.CustomerRepository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* CustomerService
*
* @author XiongNeng
* @version 1.0
* @since 2018/3/3
*/
@Service
public class CustomerService {
@Resource
private CustomerRepository repository;
/**
* 删除所有的客户
*/
public void deleteAll() {
repository.deleteAll();
}
/**
* 保存客户
* @param customer 客户
*/
public void save(Customer customer) {
repository.save(customer);
}
/**
* 查询所有客户列表
* @return 客户列表
*/
public Iterable<Customer> findAll() {
return repository.findAll();
}
/**
* 通过名查找某个客户
* @param firstName
* @return
*/
public Customer findByFirstName(String firstName) {
return repository.findByFirstName(firstName);
}
/**
* 通过姓查找客户列表
* @param lastName
* @return
*/
public List<Customer> findByLastName(String lastName) {
return repository.findByLastName(lastName);
}
}
| 558 |
1,025 | <filename>nlp/src/main/java/org/ocpsoft/prettytime/nlp/PrettyTimeParser.java
package org.ocpsoft.prettytime.nlp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import org.ocpsoft.prettytime.nlp.parse.DateGroup;
import com.joestelmach.natty.Parser;
/**
* A utility for parsing natural language date and time expressions. (e.g. "Let's get lunch at two pm",
* "I did it 3 days ago")
* <p>
* <b>Usage:</b>
* <p>
* <code>
* PrettyTimeParser p = new PrettyTimeParser();<br/>
* List<Date> parsed = p.parse("I'll be there at two");<br/>
* //result: Date - 2:00PM
* <p>
* </code>
*
* @author <a href="mailto:<EMAIL>><NAME>, III</a>
*/
public class PrettyTimeParser
{
private Parser parser = new Parser();
private Map<String, String> translations = new HashMap<String, String>();
private Set<String> periods = new HashSet<String>();
private final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
/**
* Create a new {@link PrettyTimeParser} with the given {@link TimeZone}.
*/
public PrettyTimeParser(TimeZone timezone)
{
parser = new Parser(timezone);
}
/**
* Create a new {@link PrettyTimeParser} with the current system default {@link TimeZone}.
*/
public PrettyTimeParser()
{
this(TimeZone.getDefault());
for (int hours = 0; hours < 24; hours++)
for (int min = 0; min < 60; min++)
translations.put(provideRepresentation(hours * 100 + min), "" + hours * 100 + min);
translations.put(provideRepresentation(60), "" + 60);
translations.put(provideRepresentation(70), "" + 70);
translations.put(provideRepresentation(80), "" + 80);
translations.put(provideRepresentation(90), "" + 90);
translations.put(provideRepresentation(100), "" + 100);
periods.add("morning");
periods.add("afternoon");
periods.add("evening");
periods.add("night");
periods.add("am");
periods.add("pm");
periods.add("ago");
periods.add("from now");
}
/**
* Provides a string representation for the number passed. This method works for limited set of numbers as parsing
* will only be done at maximum for 2400, which will be used in military time format.
*/
private String provideRepresentation(int number)
{
String key;
if (number == 0)
key = "zero";
else if (number < 20)
key = numNames[number];
else if (number < 100)
{
int unit = number % 10;
key = tensNames[number / 10] + numNames[unit];
}
else
{
int unit = number % 10;
int ten = number % 100 - unit;
int hundred = (number - ten) / 100;
if (hundred < 20)
key = numNames[hundred] + " hundred";
else
key = tensNames[hundred / 10] + numNames[hundred % 10] + " hundred";
if (ten + unit < 20 && ten + unit > 10)
key += numNames[ten + unit];
else
key += tensNames[ten / 10] + numNames[unit];
}
return key.trim();
}
/**
* Parse the given language and return a {@link List} with all discovered {@link Date} instances.
*/
public List<Date> parse(String language)
{
language = words2numbers(language);
List<Date> result = new ArrayList<Date>();
List<com.joestelmach.natty.DateGroup> groups = parser.parse(language);
for (com.joestelmach.natty.DateGroup group : groups) {
result.addAll(group.getDates());
}
return result;
}
/**
* Parse the given language and return a {@link List} with all discovered {@link DateGroup} instances.
*/
public List<DateGroup> parseSyntax(String language)
{
language = words2numbers(language);
List<DateGroup> result = new ArrayList<DateGroup>();
List<com.joestelmach.natty.DateGroup> groups = parser.parse(language);
Date now = new Date();
for (com.joestelmach.natty.DateGroup group : groups) {
result.add(new DateGroupImpl(now, group));
}
return result;
}
private String words2numbers(String language)
{
for (Entry<String, String> entry : translations.entrySet()) {
language = language.replaceAll("\\b" + entry.getKey() + "\\b", entry.getValue());
}
return language;
}
private class DateGroupImpl implements DateGroup
{
private List<Date> dates;
private int line;
private int position;
private Date recursUntil;
private String text;
private boolean recurring;
private Date now;
public DateGroupImpl(Date now, com.joestelmach.natty.DateGroup group)
{
this.now = now;
dates = group.getDates();
line = group.getLine();
position = group.getPosition();
recursUntil = group.getRecursUntil();
text = group.getText();
recurring = group.isRecurring();
}
@Override
public List<Date> getDates()
{
return dates;
}
@Override
public int getLine()
{
return line;
}
@Override
public int getPosition()
{
return position;
}
@Override
public Date getRecursUntil()
{
return recursUntil;
}
@Override
public String getText()
{
return text;
}
@Override
public boolean isRecurring()
{
return recurring;
}
@Override
public long getRecurInterval()
{
if (isRecurring())
return getDates().get(0).getTime() - now.getTime();
else
return -1;
}
}
}
| 2,847 |
1,514 | <reponame>fpmuniz/stepmania
/* LibTomCrypt, modular cryptographic library -- <NAME>
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* Implements ECC over Z/pZ for curve y^2 = x^3 - 3x + b
*
* All curves taken from NIST recommendation paper of July 1999
* Available at http://csrc.nist.gov/cryptval/dss.htm
*/
#include "tomcrypt.h"
/**
@file ecc_ansi_x963_export.c
ECC Crypto, <NAME>
*/
#ifdef LTC_MECC
/** ECC X9.63 (Sec. 4.3.6) uncompressed export
@param key Key to export
@param out [out] destination of export
@param outlen [in/out] Length of destination and final output size
Return CRYPT_OK on success
*/
int ecc_ansi_x963_export(ecc_key *key, unsigned char *out, unsigned long *outlen)
{
unsigned char buf[ECC_BUF_SIZE];
unsigned long numlen, xlen, ylen;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(outlen != NULL);
if (ltc_ecc_is_valid_idx(key->idx) == 0) {
return CRYPT_INVALID_ARG;
}
numlen = key->dp->size;
xlen = mp_unsigned_bin_size(key->pubkey.x);
ylen = mp_unsigned_bin_size(key->pubkey.y);
if (xlen > numlen || ylen > numlen || sizeof(buf) < numlen) {
return CRYPT_BUFFER_OVERFLOW;
}
if (*outlen < (1 + 2*numlen)) {
*outlen = 1 + 2*numlen;
return CRYPT_BUFFER_OVERFLOW;
}
LTC_ARGCHK(out != NULL);
/* store byte 0x04 */
out[0] = 0x04;
/* pad and store x */
zeromem(buf, sizeof(buf));
mp_to_unsigned_bin(key->pubkey.x, buf + (numlen - xlen));
XMEMCPY(out+1, buf, numlen);
/* pad and store y */
zeromem(buf, sizeof(buf));
mp_to_unsigned_bin(key->pubkey.y, buf + (numlen - ylen));
XMEMCPY(out+1+numlen, buf, numlen);
*outlen = 1 + 2*numlen;
return CRYPT_OK;
}
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: <PASSWORD> */
/* commit time: 2018-07-01 22:49:01 +0200 */
| 836 |
708 | <reponame>nairobi222/PopsTabView
package com.ccj.poptabview;
import java.util.HashMap;
import java.util.Map;
/**
* Created by chenchangjun on 17/7/26.
*/
public class PopsTabUtils {
/**
* 获取带逗号的string 例如 1,2,3,4,5,6
*
* @param paramsMap
* @return
*/
public static String mapToString(HashMap<String, String> paramsMap) {
StringBuilder params = new StringBuilder();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
params.append(entry.getValue() + ",");
}
String paramString = params.toString();
if (paramString.endsWith(",")) {
paramString = paramString.substring(0, paramString.length() - 1);
}
return paramString;
}
public static String builderToString(StringBuilder paramsMap) {
String paramString = paramsMap.toString();
if (paramString.endsWith(",")) {
paramString = paramString.substring(0, paramString.length() - 1);
}
return paramString;
}
}
| 454 |
432 | <gh_stars>100-1000
/* $NetBSD: uplcom.c,v 1.21 2001/11/13 06:24:56 lukem Exp $ */
/*-
* Copyright (c) 2001-2003, 2005 <NAME> <<EMAIL>>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
/*-
* Copyright (c) 2001 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by <NAME> (<EMAIL>).
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/*
* This driver supports several USB-to-RS232 serial adapters driven by
* Prolific PL-2303, PL-2303X and probably PL-2303HX USB-to-RS232
* bridge chip. The adapters are sold under many different brand
* names.
*
* Datasheets are available at Prolific www site at
* http://www.prolific.com.tw. The datasheets don't contain full
* programming information for the chip.
*
* PL-2303HX is probably programmed the same as PL-2303X.
*
* There are several differences between PL-2303 and PL-2303(H)X.
* PL-2303(H)X can do higher bitrate in bulk mode, has _probably_
* different command for controlling CRTSCTS and needs special
* sequence of commands for initialization which aren't also
* documented in the datasheet.
*/
#include <sys/stdint.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/types.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/bus.h>
#include <sys/module.h>
#include <sys/lock.h>
#include <sys/condvar.h>
#include <sys/sysctl.h>
#include <sys/unistd.h>
#include <sys/callout.h>
#include <sys/malloc.h>
#include <sys/priv.h>
#include <sys/serial.h>
#include <bus/u4b/usb.h>
#include <bus/u4b/usbdi.h>
#include <bus/u4b/usbdi_util.h>
#include <bus/u4b/usb_cdc.h>
#include "usbdevs.h"
#define USB_DEBUG_VAR uplcom_debug
#include <bus/u4b/usb_debug.h>
#include <bus/u4b/usb_process.h>
#include <bus/u4b/serial/usb_serial.h>
#ifdef USB_DEBUG
static int uplcom_debug = 0;
static SYSCTL_NODE(_hw_usb, OID_AUTO, uplcom, CTLFLAG_RW, 0, "USB uplcom");
SYSCTL_INT(_hw_usb_uplcom, OID_AUTO, debug, CTLFLAG_RW,
&uplcom_debug, 0, "Debug level");
#endif
#define UPLCOM_MODVER 1 /* module version */
#define UPLCOM_CONFIG_INDEX 0
#define UPLCOM_IFACE_INDEX 0
#define UPLCOM_SECOND_IFACE_INDEX 1
#ifndef UPLCOM_INTR_INTERVAL
#define UPLCOM_INTR_INTERVAL 0 /* default */
#endif
#define UPLCOM_BULK_BUF_SIZE 1024 /* bytes */
#define UPLCOM_SET_REQUEST 0x01
#define UPLCOM_SET_CRTSCTS 0x41
#define UPLCOM_SET_CRTSCTS_PL2303X 0x61
#define RSAQ_STATUS_CTS 0x80
#define RSAQ_STATUS_DSR 0x02
#define RSAQ_STATUS_DCD 0x01
#define TYPE_PL2303 0
#define TYPE_PL2303HX 1
enum {
UPLCOM_BULK_DT_WR,
UPLCOM_BULK_DT_RD,
UPLCOM_INTR_DT_RD,
UPLCOM_N_TRANSFER,
};
struct uplcom_softc {
struct ucom_super_softc sc_super_ucom;
struct ucom_softc sc_ucom;
struct usb_xfer *sc_xfer[UPLCOM_N_TRANSFER];
struct usb_device *sc_udev;
struct lock sc_lock;
uint16_t sc_line;
uint8_t sc_lsr; /* local status register */
uint8_t sc_msr; /* uplcom status register */
uint8_t sc_chiptype; /* type of chip */
uint8_t sc_ctrl_iface_no;
uint8_t sc_data_iface_no;
uint8_t sc_iface_index[2];
};
/* prototypes */
static usb_error_t uplcom_reset(struct uplcom_softc *, struct usb_device *);
static usb_error_t uplcom_pl2303_do(struct usb_device *, int8_t, uint8_t,
uint16_t, uint16_t, uint16_t);
static int uplcom_pl2303_init(struct usb_device *, uint8_t);
static void uplcom_cfg_set_dtr(struct ucom_softc *, uint8_t);
static void uplcom_cfg_set_rts(struct ucom_softc *, uint8_t);
static void uplcom_cfg_set_break(struct ucom_softc *, uint8_t);
static int uplcom_pre_param(struct ucom_softc *, struct termios *);
static void uplcom_cfg_param(struct ucom_softc *, struct termios *);
static void uplcom_start_read(struct ucom_softc *);
static void uplcom_stop_read(struct ucom_softc *);
static void uplcom_start_write(struct ucom_softc *);
static void uplcom_stop_write(struct ucom_softc *);
static void uplcom_cfg_get_status(struct ucom_softc *, uint8_t *,
uint8_t *);
static void uplcom_poll(struct ucom_softc *ucom);
static device_probe_t uplcom_probe;
static device_attach_t uplcom_attach;
static device_detach_t uplcom_detach;
static usb_callback_t uplcom_intr_callback;
static usb_callback_t uplcom_write_callback;
static usb_callback_t uplcom_read_callback;
static const struct usb_config uplcom_config_data[UPLCOM_N_TRANSFER] = {
[UPLCOM_BULK_DT_WR] = {
.type = UE_BULK,
.endpoint = UE_ADDR_ANY,
.direction = UE_DIR_OUT,
.bufsize = UPLCOM_BULK_BUF_SIZE,
.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
.callback = &uplcom_write_callback,
.if_index = 0,
},
[UPLCOM_BULK_DT_RD] = {
.type = UE_BULK,
.endpoint = UE_ADDR_ANY,
.direction = UE_DIR_IN,
.bufsize = UPLCOM_BULK_BUF_SIZE,
.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
.callback = &uplcom_read_callback,
.if_index = 0,
},
[UPLCOM_INTR_DT_RD] = {
.type = UE_INTERRUPT,
.endpoint = UE_ADDR_ANY,
.direction = UE_DIR_IN,
.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
.bufsize = 0, /* use wMaxPacketSize */
.callback = &uplcom_intr_callback,
.if_index = 1,
},
};
static struct ucom_callback uplcom_callback = {
.ucom_cfg_get_status = &uplcom_cfg_get_status,
.ucom_cfg_set_dtr = &uplcom_cfg_set_dtr,
.ucom_cfg_set_rts = &uplcom_cfg_set_rts,
.ucom_cfg_set_break = &uplcom_cfg_set_break,
.ucom_cfg_param = &uplcom_cfg_param,
.ucom_pre_param = &uplcom_pre_param,
.ucom_start_read = &uplcom_start_read,
.ucom_stop_read = &uplcom_stop_read,
.ucom_start_write = &uplcom_start_write,
.ucom_stop_write = &uplcom_stop_write,
.ucom_poll = &uplcom_poll,
};
#define UPLCOM_DEV(v,p) \
{ USB_VENDOR(USB_VENDOR_##v), USB_PRODUCT(USB_PRODUCT_##v##_##p) }
static const STRUCT_USB_HOST_ID uplcom_devs[] = {
UPLCOM_DEV(ACERP, S81), /* BenQ S81 phone */
UPLCOM_DEV(ADLINK, ND6530), /* ADLINK ND-6530 USB-Serial */
UPLCOM_DEV(ALCATEL, OT535), /* Alcatel One Touch 535/735 */
UPLCOM_DEV(ALCOR, AU9720), /* Alcor AU9720 USB 2.0-RS232 */
UPLCOM_DEV(ANCHOR, SERIAL), /* Anchor Serial adapter */
UPLCOM_DEV(ATEN, UC232A), /* PLANEX USB-RS232 URS-03 */
UPLCOM_DEV(BELKIN, F5U257), /* Belkin F5U257 USB to Serial */
UPLCOM_DEV(COREGA, CGUSBRS232R), /* Corega CG-USBRS232R */
UPLCOM_DEV(EPSON, CRESSI_EDY), /* Cressi Edy diving computer */
UPLCOM_DEV(EPSON, N2ITION3), /* Zeagle N2iTion3 diving computer */
UPLCOM_DEV(ELECOM, UCSGT), /* ELECOM UC-SGT Serial Adapter */
UPLCOM_DEV(ELECOM, UCSGT0), /* ELECOM UC-SGT Serial Adapter */
UPLCOM_DEV(HAL, IMR001), /* HAL Corporation Crossam2+USB */
UPLCOM_DEV(HP, LD220), /* HP LD220 POS Display */
UPLCOM_DEV(IODATA, USBRSAQ), /* I/O DATA USB-RSAQ */
UPLCOM_DEV(IODATA, USBRSAQ5), /* I/O DATA USB-RSAQ5 */
UPLCOM_DEV(ITEGNO, WM1080A), /* iTegno WM1080A GSM/GFPRS modem */
UPLCOM_DEV(ITEGNO, WM2080A), /* iTegno WM2080A CDMA modem */
UPLCOM_DEV(LEADTEK, 9531), /* Leadtek 9531 GPS */
UPLCOM_DEV(MICROSOFT, 700WX), /* Microsoft Palm 700WX */
UPLCOM_DEV(MOBILEACTION, MA620), /* Mobile Action MA-620 Infrared Adapter */
UPLCOM_DEV(NETINDEX, WS002IN), /* Willcom W-S002IN */
UPLCOM_DEV(NOKIA2, CA42), /* Nokia CA-42 cable */
UPLCOM_DEV(OTI, DKU5), /* OTI DKU-5 cable */
UPLCOM_DEV(PANASONIC, TYTP50P6S), /* Panasonic TY-TP50P6-S flat screen */
UPLCOM_DEV(PLX, CA42), /* PLX CA-42 clone cable */
UPLCOM_DEV(PROLIFIC, ALLTRONIX_GPRS), /* Alltronix ACM003U00 modem */
UPLCOM_DEV(PROLIFIC, ALDIGA_AL11U), /* AlDiga AL-11U modem */
UPLCOM_DEV(PROLIFIC, DCU11), /* DCU-11 Phone Cable */
UPLCOM_DEV(PROLIFIC, HCR331), /* HCR331 Card Reader */
UPLCOM_DEV(PROLIFIC, MICROMAX_610U), /* Micromax 610U modem */
UPLCOM_DEV(PROLIFIC, PHAROS), /* Prolific Pharos */
UPLCOM_DEV(PROLIFIC, PL2303), /* Generic adapter */
UPLCOM_DEV(PROLIFIC, RSAQ2), /* I/O DATA USB-RSAQ2 */
UPLCOM_DEV(PROLIFIC, RSAQ3), /* I/O DATA USB-RSAQ3 */
UPLCOM_DEV(PROLIFIC, UIC_MSR206), /* UIC MSR206 Card Reader */
UPLCOM_DEV(PROLIFIC2, PL2303), /* Prolific adapter */
UPLCOM_DEV(RADIOSHACK, USBCABLE), /* Radio Shack USB Adapter */
UPLCOM_DEV(RATOC, REXUSB60), /* RATOC REX-USB60 */
UPLCOM_DEV(SAGEM, USBSERIAL), /* Sagem USB-Serial Controller */
UPLCOM_DEV(SAMSUNG, I330), /* Samsung I330 phone cradle */
UPLCOM_DEV(SANWA, KB_USB2), /* Sanwa KB-USB2 Multimeter cable */
UPLCOM_DEV(SIEMENS3, EF81), /* Siemens EF81 */
UPLCOM_DEV(SIEMENS3, SX1), /* Siemens SX1 */
UPLCOM_DEV(SIEMENS3, X65), /* Siemens X65 */
UPLCOM_DEV(SIEMENS3, X75), /* Siemens X75 */
UPLCOM_DEV(SITECOM, SERIAL), /* Sitecom USB to Serial */
UPLCOM_DEV(SMART, PL2303), /* SMART Technologies USB to Serial */
UPLCOM_DEV(SONY, QN3), /* Sony QN3 phone cable */
UPLCOM_DEV(SONYERICSSON, DATAPILOT), /* <NAME> Datapilot */
UPLCOM_DEV(SONYERICSSON, DCU10), /* <NAME>sson DCU-10 Cable */
UPLCOM_DEV(SOURCENEXT, KEIKAI8), /* SOURCENEXT KeikaiDenwa 8 */
UPLCOM_DEV(SOURCENEXT, KEIKAI8_CHG), /* SOURCENEXT KeikaiDenwa 8 with charger */
UPLCOM_DEV(SPEEDDRAGON, MS3303H), /* Speed Dragon USB-Serial */
UPLCOM_DEV(SYNTECH, CPT8001C), /* Syntech CPT-8001C Barcode scanner */
UPLCOM_DEV(TDK, UHA6400), /* TDK USB-PHS Adapter UHA6400 */
UPLCOM_DEV(TDK, UPA9664), /* TDK USB-PHS Adapter UPA9664 */
UPLCOM_DEV(TRIPPLITE, U209), /* Tripp-Lite U209-000-R USB to Serial */
UPLCOM_DEV(YCCABLE, PL2303), /* YC Cable USB-Serial */
};
#undef UPLCOM_DEV
static device_method_t uplcom_methods[] = {
DEVMETHOD(device_probe, uplcom_probe),
DEVMETHOD(device_attach, uplcom_attach),
DEVMETHOD(device_detach, uplcom_detach),
DEVMETHOD_END
};
static devclass_t uplcom_devclass;
static driver_t uplcom_driver = {
.name = "uplcom",
.methods = uplcom_methods,
.size = sizeof(struct uplcom_softc),
};
DRIVER_MODULE(uplcom, uhub, uplcom_driver, uplcom_devclass, NULL, NULL);
MODULE_DEPEND(uplcom, ucom, 1, 1, 1);
MODULE_DEPEND(uplcom, usb, 1, 1, 1);
MODULE_VERSION(uplcom, UPLCOM_MODVER);
static int
uplcom_probe(device_t dev)
{
struct usb_attach_arg *uaa = device_get_ivars(dev);
DPRINTFN(11, "\n");
if (uaa->usb_mode != USB_MODE_HOST) {
return (ENXIO);
}
if (uaa->info.bConfigIndex != UPLCOM_CONFIG_INDEX) {
return (ENXIO);
}
if (uaa->info.bIfaceIndex != UPLCOM_IFACE_INDEX) {
return (ENXIO);
}
return (usbd_lookup_id_by_uaa(uplcom_devs, sizeof(uplcom_devs), uaa));
}
static int
uplcom_attach(device_t dev)
{
struct usb_attach_arg *uaa = device_get_ivars(dev);
struct uplcom_softc *sc = device_get_softc(dev);
struct usb_interface *iface;
struct usb_interface_descriptor *id;
struct usb_device_descriptor *dd;
int error;
DPRINTFN(11, "\n");
device_set_usb_desc(dev);
lockinit(&sc->sc_lock, "uplcom", 0, LK_CANRECURSE);
DPRINTF("sc = %p\n", sc);
sc->sc_udev = uaa->device;
/* Determine the chip type. This algorithm is taken from Linux. */
dd = usbd_get_device_descriptor(sc->sc_udev);
if (dd->bDeviceClass == 0x02)
sc->sc_chiptype = TYPE_PL2303;
else if (dd->bMaxPacketSize == 0x40)
sc->sc_chiptype = TYPE_PL2303HX;
else
sc->sc_chiptype = TYPE_PL2303;
DPRINTF("chiptype: %s\n",
(sc->sc_chiptype == TYPE_PL2303HX) ?
"2303X" : "2303");
/*
* USB-RSAQ1 has two interface
*
* USB-RSAQ1 | USB-RSAQ2
* -----------------+-----------------
* Interface 0 |Interface 0
* Interrupt(0x81) | Interrupt(0x81)
* -----------------+ BulkIN(0x02)
* Interface 1 | BulkOUT(0x83)
* BulkIN(0x02) |
* BulkOUT(0x83) |
*/
sc->sc_ctrl_iface_no = uaa->info.bIfaceNum;
sc->sc_iface_index[1] = UPLCOM_IFACE_INDEX;
iface = usbd_get_iface(uaa->device, UPLCOM_SECOND_IFACE_INDEX);
if (iface) {
id = usbd_get_interface_descriptor(iface);
if (id == NULL) {
device_printf(dev, "no interface descriptor (2)\n");
goto detach;
}
sc->sc_data_iface_no = id->bInterfaceNumber;
sc->sc_iface_index[0] = UPLCOM_SECOND_IFACE_INDEX;
usbd_set_parent_iface(uaa->device,
UPLCOM_SECOND_IFACE_INDEX, uaa->info.bIfaceIndex);
} else {
sc->sc_data_iface_no = sc->sc_ctrl_iface_no;
sc->sc_iface_index[0] = UPLCOM_IFACE_INDEX;
}
error = usbd_transfer_setup(uaa->device,
sc->sc_iface_index, sc->sc_xfer, uplcom_config_data,
UPLCOM_N_TRANSFER, sc, &sc->sc_lock);
if (error) {
DPRINTF("one or more missing USB endpoints, "
"error=%s\n", usbd_errstr(error));
goto detach;
}
error = uplcom_reset(sc, uaa->device);
if (error) {
device_printf(dev, "reset failed, error=%s\n",
usbd_errstr(error));
goto detach;
}
/* clear stall at first run */
lockmgr(&sc->sc_lock, LK_EXCLUSIVE);
usbd_xfer_set_stall(sc->sc_xfer[UPLCOM_BULK_DT_WR]);
usbd_xfer_set_stall(sc->sc_xfer[UPLCOM_BULK_DT_RD]);
lockmgr(&sc->sc_lock, LK_RELEASE);
error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc,
&uplcom_callback, &sc->sc_lock);
if (error) {
goto detach;
}
/*
* do the initialization during attach so that the system does not
* sleep during open:
*/
if (uplcom_pl2303_init(uaa->device, sc->sc_chiptype)) {
device_printf(dev, "init failed\n");
goto detach;
}
ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev);
return (0);
detach:
uplcom_detach(dev);
return (ENXIO);
}
static int
uplcom_detach(device_t dev)
{
struct uplcom_softc *sc = device_get_softc(dev);
DPRINTF("sc=%p\n", sc);
ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom);
usbd_transfer_unsetup(sc->sc_xfer, UPLCOM_N_TRANSFER);
lockuninit(&sc->sc_lock);
return (0);
}
static usb_error_t
uplcom_reset(struct uplcom_softc *sc, struct usb_device *udev)
{
struct usb_device_request req;
req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
req.bRequest = UPLCOM_SET_REQUEST;
USETW(req.wValue, 0);
req.wIndex[0] = sc->sc_data_iface_no;
req.wIndex[1] = 0;
USETW(req.wLength, 0);
return (usbd_do_request(udev, NULL, &req, NULL));
}
static usb_error_t
uplcom_pl2303_do(struct usb_device *udev, int8_t req_type, uint8_t request,
uint16_t value, uint16_t index, uint16_t length)
{
struct usb_device_request req;
usb_error_t err;
uint8_t buf[4];
req.bmRequestType = req_type;
req.bRequest = request;
USETW(req.wValue, value);
USETW(req.wIndex, index);
USETW(req.wLength, length);
err = usbd_do_request(udev, NULL, &req, buf);
if (err) {
DPRINTF("error=%s\n", usbd_errstr(err));
return (1);
}
return (0);
}
static int
uplcom_pl2303_init(struct usb_device *udev, uint8_t chiptype)
{
int err;
if (uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
|| uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x0404, 0, 0)
|| uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
|| uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8383, 0, 1)
|| uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
|| uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x0404, 1, 0)
|| uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
|| uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8383, 0, 1)
|| uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0, 1, 0)
|| uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 1, 0, 0))
return (EIO);
if (chiptype == TYPE_PL2303HX)
err = uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 2, 0x44, 0);
else
err = uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 2, 0x24, 0);
if (err)
return (EIO);
if (uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 8, 0, 0)
|| uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 9, 0, 0))
return (EIO);
return (0);
}
static void
uplcom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff)
{
struct uplcom_softc *sc = ucom->sc_parent;
struct usb_device_request req;
DPRINTF("onoff = %d\n", onoff);
if (onoff)
sc->sc_line |= UCDC_LINE_DTR;
else
sc->sc_line &= ~UCDC_LINE_DTR;
req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
req.bRequest = UCDC_SET_CONTROL_LINE_STATE;
USETW(req.wValue, sc->sc_line);
req.wIndex[0] = sc->sc_data_iface_no;
req.wIndex[1] = 0;
USETW(req.wLength, 0);
ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
&req, NULL, 0, 1000);
}
static void
uplcom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff)
{
struct uplcom_softc *sc = ucom->sc_parent;
struct usb_device_request req;
DPRINTF("onoff = %d\n", onoff);
if (onoff)
sc->sc_line |= UCDC_LINE_RTS;
else
sc->sc_line &= ~UCDC_LINE_RTS;
req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
req.bRequest = UCDC_SET_CONTROL_LINE_STATE;
USETW(req.wValue, sc->sc_line);
req.wIndex[0] = sc->sc_data_iface_no;
req.wIndex[1] = 0;
USETW(req.wLength, 0);
ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
&req, NULL, 0, 1000);
}
static void
uplcom_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff)
{
struct uplcom_softc *sc = ucom->sc_parent;
struct usb_device_request req;
uint16_t temp;
DPRINTF("onoff = %d\n", onoff);
temp = (onoff ? UCDC_BREAK_ON : UCDC_BREAK_OFF);
req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
req.bRequest = UCDC_SEND_BREAK;
USETW(req.wValue, temp);
req.wIndex[0] = sc->sc_data_iface_no;
req.wIndex[1] = 0;
USETW(req.wLength, 0);
ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
&req, NULL, 0, 1000);
}
static const int32_t uplcom_rates[] = {
75, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, 14400,
19200, 28800, 38400, 57600, 115200,
/*
* Higher speeds are probably possible. PL2303X supports up to
* 6Mb and can set any rate
*/
230400, 460800, 614400, 921600, 1228800
};
static int
uplcom_pre_param(struct ucom_softc *ucom, struct termios *t)
{
struct uplcom_softc *sc = ucom->sc_parent;
uint8_t i;
DPRINTF("\n");
/**
* Check requested baud rate.
*
* The PL2303 can only set specific baud rates, up to 1228800 baud.
* The PL2303X can set any baud rate up to 6Mb.
* The PL2303HX rev. D can set any baud rate up to 12Mb.
*
* XXX: We currently cannot identify the PL2303HX rev. D, so treat
* it the same as the PL2303X.
*/
if (sc->sc_chiptype != TYPE_PL2303HX) {
for (i = 0; i < NELEM(uplcom_rates); i++) {
if (uplcom_rates[i] == t->c_ospeed)
return (0);
}
} else {
if (t->c_ospeed <= 6000000)
return (0);
}
DPRINTF("uplcom_param: bad baud rate (%d)\n", t->c_ospeed);
return (EIO);
}
static void
uplcom_cfg_param(struct ucom_softc *ucom, struct termios *t)
{
struct uplcom_softc *sc = ucom->sc_parent;
struct usb_cdc_line_state ls;
struct usb_device_request req;
DPRINTF("sc = %p\n", sc);
memset(&ls, 0, sizeof(ls));
USETDW(ls.dwDTERate, t->c_ospeed);
if (t->c_cflag & CSTOPB) {
ls.bCharFormat = UCDC_STOP_BIT_2;
} else {
ls.bCharFormat = UCDC_STOP_BIT_1;
}
if (t->c_cflag & PARENB) {
if (t->c_cflag & PARODD) {
ls.bParityType = UCDC_PARITY_ODD;
} else {
ls.bParityType = UCDC_PARITY_EVEN;
}
} else {
ls.bParityType = UCDC_PARITY_NONE;
}
switch (t->c_cflag & CSIZE) {
case CS5:
ls.bDataBits = 5;
break;
case CS6:
ls.bDataBits = 6;
break;
case CS7:
ls.bDataBits = 7;
break;
case CS8:
ls.bDataBits = 8;
break;
}
DPRINTF("rate=%d fmt=%d parity=%d bits=%d\n",
UGETDW(ls.dwDTERate), ls.bCharFormat,
ls.bParityType, ls.bDataBits);
req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
req.bRequest = UCDC_SET_LINE_CODING;
USETW(req.wValue, 0);
req.wIndex[0] = sc->sc_data_iface_no;
req.wIndex[1] = 0;
USETW(req.wLength, UCDC_LINE_STATE_LENGTH);
ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
&req, &ls, 0, 1000);
if (t->c_cflag & CRTSCTS) {
DPRINTF("crtscts = on\n");
req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
req.bRequest = UPLCOM_SET_REQUEST;
USETW(req.wValue, 0);
if (sc->sc_chiptype == TYPE_PL2303HX)
USETW(req.wIndex, UPLCOM_SET_CRTSCTS_PL2303X);
else
USETW(req.wIndex, UPLCOM_SET_CRTSCTS);
USETW(req.wLength, 0);
ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
&req, NULL, 0, 1000);
} else {
req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
req.bRequest = UPLCOM_SET_REQUEST;
USETW(req.wValue, 0);
USETW(req.wIndex, 0);
USETW(req.wLength, 0);
ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
&req, NULL, 0, 1000);
}
}
static void
uplcom_start_read(struct ucom_softc *ucom)
{
struct uplcom_softc *sc = ucom->sc_parent;
/* start interrupt endpoint */
usbd_transfer_start(sc->sc_xfer[UPLCOM_INTR_DT_RD]);
/* start read endpoint */
usbd_transfer_start(sc->sc_xfer[UPLCOM_BULK_DT_RD]);
}
static void
uplcom_stop_read(struct ucom_softc *ucom)
{
struct uplcom_softc *sc = ucom->sc_parent;
/* stop interrupt endpoint */
usbd_transfer_stop(sc->sc_xfer[UPLCOM_INTR_DT_RD]);
/* stop read endpoint */
usbd_transfer_stop(sc->sc_xfer[UPLCOM_BULK_DT_RD]);
}
static void
uplcom_start_write(struct ucom_softc *ucom)
{
struct uplcom_softc *sc = ucom->sc_parent;
usbd_transfer_start(sc->sc_xfer[UPLCOM_BULK_DT_WR]);
}
static void
uplcom_stop_write(struct ucom_softc *ucom)
{
struct uplcom_softc *sc = ucom->sc_parent;
usbd_transfer_stop(sc->sc_xfer[UPLCOM_BULK_DT_WR]);
}
static void
uplcom_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr)
{
struct uplcom_softc *sc = ucom->sc_parent;
DPRINTF("\n");
*lsr = sc->sc_lsr;
*msr = sc->sc_msr;
}
static void
uplcom_intr_callback(struct usb_xfer *xfer, usb_error_t error)
{
struct uplcom_softc *sc = usbd_xfer_softc(xfer);
struct usb_page_cache *pc;
uint8_t buf[9];
int actlen;
usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
switch (USB_GET_STATE(xfer)) {
case USB_ST_TRANSFERRED:
DPRINTF("actlen = %u\n", actlen);
if (actlen >= 9) {
pc = usbd_xfer_get_frame(xfer, 0);
usbd_copy_out(pc, 0, buf, sizeof(buf));
DPRINTF("status = 0x%02x\n", buf[8]);
sc->sc_lsr = 0;
sc->sc_msr = 0;
if (buf[8] & RSAQ_STATUS_CTS) {
sc->sc_msr |= SER_CTS;
}
if (buf[8] & RSAQ_STATUS_DSR) {
sc->sc_msr |= SER_DSR;
}
if (buf[8] & RSAQ_STATUS_DCD) {
sc->sc_msr |= SER_DCD;
}
ucom_status_change(&sc->sc_ucom);
}
case USB_ST_SETUP:
tr_setup:
usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
usbd_transfer_submit(xfer);
return;
default: /* Error */
if (error != USB_ERR_CANCELLED) {
/* try to clear stall first */
usbd_xfer_set_stall(xfer);
goto tr_setup;
}
return;
}
}
static void
uplcom_write_callback(struct usb_xfer *xfer, usb_error_t error)
{
struct uplcom_softc *sc = usbd_xfer_softc(xfer);
struct usb_page_cache *pc;
uint32_t actlen;
switch (USB_GET_STATE(xfer)) {
case USB_ST_SETUP:
case USB_ST_TRANSFERRED:
tr_setup:
pc = usbd_xfer_get_frame(xfer, 0);
if (ucom_get_data(&sc->sc_ucom, pc, 0,
UPLCOM_BULK_BUF_SIZE, &actlen)) {
DPRINTF("actlen = %d\n", actlen);
usbd_xfer_set_frame_len(xfer, 0, actlen);
usbd_transfer_submit(xfer);
}
return;
default: /* Error */
if (error != USB_ERR_CANCELLED) {
/* try to clear stall first */
usbd_xfer_set_stall(xfer);
goto tr_setup;
}
return;
}
}
static void
uplcom_read_callback(struct usb_xfer *xfer, usb_error_t error)
{
struct uplcom_softc *sc = usbd_xfer_softc(xfer);
struct usb_page_cache *pc;
int actlen;
usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
switch (USB_GET_STATE(xfer)) {
case USB_ST_TRANSFERRED:
pc = usbd_xfer_get_frame(xfer, 0);
ucom_put_data(&sc->sc_ucom, pc, 0, actlen);
case USB_ST_SETUP:
tr_setup:
usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
usbd_transfer_submit(xfer);
return;
default: /* Error */
if (error != USB_ERR_CANCELLED) {
/* try to clear stall first */
usbd_xfer_set_stall(xfer);
goto tr_setup;
}
return;
}
}
static void
uplcom_poll(struct ucom_softc *ucom)
{
struct uplcom_softc *sc = ucom->sc_parent;
usbd_transfer_poll(sc->sc_xfer, UPLCOM_N_TRANSFER);
}
| 11,822 |
2,151 | <filename>ios/chrome/browser/ui/ntp/ntp_util.h<gh_stars>1000+
// Copyright 2018 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 IOS_CHROME_BROWSER_UI_NTP_NTP_UTIL_H_
#define IOS_CHROME_BROWSER_UI_NTP_NTP_UTIL_H_
#import "ios/web/public/web_state/web_state.h"
// Returns whether the |web_state| is currently having the NewTabPage url as
// visible URL.
bool IsVisibleUrlNewTabPage(web::WebState* web_state);
#endif // IOS_CHROME_BROWSER_UI_NTP_NTP_UTIL_H_
| 218 |
1,315 | #include "bamSortByCoordinate.h"
#include "BAMfunctions.h"
#include "BAMbinSortByCoordinate.h"
#include "BAMbinSortUnmapped.h"
#include "ErrorWarning.h"
#include "bam_cat.h"
void bamSortByCoordinate (Parameters &P, ReadAlignChunk **RAchunk, Genome &genome, Solo &solo) {
if (P.outBAMcoord) {//sort BAM if needed
*P.inOut->logStdOut << timeMonthDayTime() << " ..... started sorting BAM\n" <<flush;
P.inOut->logMain << timeMonthDayTime() << " ..... started sorting BAM\n" <<flush;
uint32 nBins=P.outBAMcoordNbins;
//check max size needed for sorting
uint maxMem=0;
for (uint32 ibin=0; ibin<nBins-1; ibin++) {//check all bins
uint binS=0;
for (int it=0; it<P.runThreadN; it++) {//collect sizes from threads
binS += RAchunk[it]->chunkOutBAMcoord->binTotalBytes[ibin]+24*RAchunk[it]->chunkOutBAMcoord->binTotalN[ibin];
};
if (binS>maxMem) maxMem=binS;
};
P.inOut->logMain << "Max memory needed for sorting = "<<maxMem<<endl;
if (maxMem>P.limitBAMsortRAM) {
ostringstream errOut;
errOut <<"EXITING because of fatal ERROR: not enough memory for BAM sorting: \n";
errOut <<"SOLUTION: re-run STAR with at least --limitBAMsortRAM " <<maxMem+1000000000;
exitWithError(errOut.str(), std::cerr, P.inOut->logMain, EXIT_CODE_PARAMETER, P);
} else if(maxMem==0) {
P.inOut->logMain << "WARNING: nothing to sort - no output alignments" <<endl;
BGZF *bgzfOut;
bgzfOut=bgzf_open(P.outBAMfileCoordName.c_str(),("w"+to_string((long long) P.outBAMcompression)).c_str());
if (bgzfOut==NULL) {
ostringstream errOut;
errOut <<"EXITING because of fatal ERROR: could not open output bam file: " << P.outBAMfileCoordName << "\n";
errOut <<"SOLUTION: check that the disk is not full, increase the max number of open files with Linux command ulimit -n before running STAR";
exitWithError(errOut.str(), std::cerr, P.inOut->logMain, EXIT_CODE_PARAMETER, P);
};
outBAMwriteHeader(bgzfOut,P.samHeaderSortedCoord,genome.chrNameAll,genome.chrLengthAll);
bgzf_close(bgzfOut);
} else {//sort
uint totalMem=0;
#pragma omp parallel num_threads(P.outBAMsortingThreadNactual)
#pragma omp for schedule (dynamic,1)
for (uint32 ibin1=0; ibin1<nBins; ibin1++) {
uint32 ibin=nBins-1-ibin1;//reverse order to start with the last bin - unmapped reads
uint binN=0, binS=0;
for (int it=0; it<P.runThreadN; it++) {//collect sizes from threads
binN += RAchunk[it]->chunkOutBAMcoord->binTotalN[ibin];
binS += RAchunk[it]->chunkOutBAMcoord->binTotalBytes[ibin];
};
if (binS==0) continue; //empty bin
if (ibin == nBins-1) {//last bin for unmapped reads
BAMbinSortUnmapped(ibin,P.runThreadN,P.outBAMsortTmpDir, P, genome, solo);
} else {
uint newMem=binS+binN*24;
bool boolWait=true;
while (boolWait) {
#pragma omp critical
if (totalMem+newMem < P.limitBAMsortRAM) {
boolWait=false;
totalMem+=newMem;
};
sleep(0.1);
};
BAMbinSortByCoordinate(ibin,binN,binS,P.runThreadN,P.outBAMsortTmpDir, P, genome, solo);
#pragma omp critical
totalMem-=newMem;//"release" RAM
};
};
//concatenate all BAM files, using bam_cat
char **bamBinNames = new char* [nBins];
vector <string> bamBinNamesV;
for (uint32 ibin=0; ibin<nBins; ibin++) {
bamBinNamesV.push_back(P.outBAMsortTmpDir+"/b"+std::to_string((uint) ibin));
struct stat buffer;
if (stat (bamBinNamesV.back().c_str(), &buffer) != 0) {//check if file exists
bamBinNamesV.pop_back();
};
};
for (uint32 ibin=0; ibin<bamBinNamesV.size(); ibin++) {
bamBinNames[ibin] = (char*) bamBinNamesV.at(ibin).c_str();
};
bam_cat(bamBinNamesV.size(), bamBinNames, 0, P.outBAMfileCoordName.c_str());
};
};
};
| 2,442 |
2,728 | <gh_stars>1000+
# coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import json
import os
import tempfile
import unittest
import pytest
try:
from unittest import mock
except ImportError:
import mock
from io import open
from msrestazure.azure_cloud import AZURE_PUBLIC_CLOUD
# https://github.com/Azure/azure-cli/blob/4e1ff0ec626ea46d74793ad92a1b5eddc2b6e45b/src/azure-cli-core/azure/cli/core/cloud.py#L310
AZURE_PUBLIC_CLOUD.endpoints.app_insights_resource_id='https://api.applicationinsights.io'
from azure.common.client_factory import *
class TestCommon(unittest.TestCase):
@mock.patch('azure.common.client_factory.get_cli_active_cloud')
@mock.patch('azure.common.client_factory.get_azure_cli_credentials')
def test_get_client_from_cli_profile(self, get_azure_cli_credentials, get_cli_active_cloud):
class FakeClient(object):
def __init__(self, credentials, subscription_id, base_url):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
if not isinstance(subscription_id, str):
raise TypeError("Parameter 'subscription_id' must be str.")
if not base_url:
base_url = 'should not be used'
self.credentials = credentials
self.subscription_id = subscription_id
self.base_url = base_url
class FakeSubscriptionClient(object):
def __init__(self, credentials, base_url):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if not base_url:
base_url = 'should not be used'
self.credentials = credentials
self.base_url = base_url
class GraphRbacManagementClient(object):
def __init__(self, credentials, tenant_id, base_url):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if tenant_id is None:
raise ValueError("Parameter 'tenant_id' must not be None.")
if not base_url:
base_url = 'should not be used'
self.credentials = credentials
self.tenant_id = tenant_id
self.base_url = base_url
class ApplicationInsightsDataClient(object):
def __init__(self, credentials, base_url):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if not base_url:
base_url = 'should not be used'
self.credentials = credentials
self.base_url = base_url
class KeyVaultClient(object):
def __init__(self, credentials):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
self.credentials = credentials
get_cli_active_cloud.return_value = AZURE_PUBLIC_CLOUD
get_azure_cli_credentials.return_value = 'credentials', 'subscription_id', 'tenant_id'
client = get_client_from_cli_profile(FakeClient)
get_azure_cli_credentials.assert_called_with(resource=None, with_tenant=True)
assert client.credentials == 'credentials'
assert client.subscription_id == 'subscription_id'
assert client.base_url == "https://management.azure.com/"
client = get_client_from_cli_profile(FakeSubscriptionClient)
get_azure_cli_credentials.assert_called_with(resource=None, with_tenant=True)
assert client.credentials == 'credentials'
assert client.base_url == "https://management.azure.com/"
client = get_client_from_cli_profile(GraphRbacManagementClient)
get_azure_cli_credentials.assert_called_with(resource="https://graph.windows.net/", with_tenant=True)
assert client.credentials == 'credentials'
assert client.tenant_id == 'tenant_id'
assert client.base_url == "https://graph.windows.net/"
client = get_client_from_cli_profile(ApplicationInsightsDataClient)
get_azure_cli_credentials.assert_called_with(resource="https://api.applicationinsights.io", with_tenant=True)
assert client.credentials == 'credentials'
assert client.base_url == "https://api.applicationinsights.io/v1"
client = get_client_from_cli_profile(KeyVaultClient)
get_azure_cli_credentials.assert_called_with(resource="https://vault.azure.net", with_tenant=True)
assert client.credentials == 'credentials'
@mock.patch('azure.common.client_factory.get_cli_active_cloud')
@mock.patch('azure.common.client_factory.get_azure_cli_credentials')
def test_get_client_from_cli_profile_core(self, get_azure_cli_credentials, get_cli_active_cloud):
class KeyVaultClientBase(object):
def __init__(self, vault_url, credential):
if not credential:
raise ValueError(
"credential should be an object supporting the TokenCredential protocol, "
"such as a credential from azure-identity"
)
if not vault_url:
raise ValueError("vault_url must be the URL of an Azure Key Vault")
self.credential = credential
self.vault_url = vault_url
class NewKeyVaultClient(KeyVaultClientBase):
pass
class StorageAccountHostsMixin(object):
def __init__(
self, account_url, # type: str
credential=None, # type: Optional[Any]
**kwargs # type: Any
):
try:
if not account_url.lower().startswith('http'):
account_url = "https://" + account_url
except AttributeError:
raise ValueError("Account URL must be a string.")
self.credential = credential
self.account_url = account_url
class BlobServiceClient(StorageAccountHostsMixin):
pass
get_cli_active_cloud.return_value = AZURE_PUBLIC_CLOUD
get_azure_cli_credentials.return_value = 'credential', 'subscription_id', 'tenant_id'
client = get_client_from_cli_profile(NewKeyVaultClient, vault_url="foo")
assert client.credential == 'credential'
assert client.vault_url == "foo"
client = get_client_from_cli_profile(BlobServiceClient, account_url="foo")
assert client.credential == 'credential'
assert client.account_url == "https://foo"
client = get_client_from_cli_profile(BlobServiceClient, account_url="foo", credential=None)
assert client.credential == None
assert client.account_url == "https://foo"
def test_get_client_from_auth_file(self):
configuration = {
"clientId": "a2ab11af-01aa-4759-8345-7803287dbd39",
"clientSecret": "password",
"subscriptionId": "15dbcfa8-4b93-4c9a-881c-6189d39f04d4",
"tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}
class FakeClient(object):
def __init__(self, credentials, subscription_id, base_url):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
if not isinstance(subscription_id, str):
raise TypeError("Parameter 'subscription_id' must be str.")
if not base_url:
base_url = 'should not be used'
self.credentials = credentials
self.subscription_id = subscription_id
self.base_url = base_url
class FakeSubscriptionClient(object):
def __init__(self, credentials, base_url):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if not base_url:
base_url = 'should not be used'
self.credentials = credentials
self.base_url = base_url
class GraphRbacManagementClient(object):
def __init__(self, credentials, tenant_id, base_url):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
if tenant_id is None:
raise ValueError("Parameter 'tenant_id' must not be None.")
if not base_url:
base_url = 'should not be used'
self.credentials = credentials
self.tenant_id = tenant_id
self.base_url = base_url
class KeyVaultClient(object):
def __init__(self, credentials):
if credentials is None:
raise ValueError("Parameter 'credentials' must not be None.")
self.credentials = credentials
class KeyVaultClientTrack2(object):
def __init__(self, credential):
if credential is None:
raise ValueError("Parameter 'credentials' must not be None.")
self.credential = credential
for encoding in ['utf-8', 'utf-8-sig', 'ascii']:
temp_auth_file = tempfile.NamedTemporaryFile(delete=False)
temp_auth_file.write(json.dumps(configuration).encode(encoding))
temp_auth_file.close()
client = get_client_from_auth_file(FakeClient, temp_auth_file.name)
self.assertEqual('15dbcfa8-4b93-4c9a-881c-6189d39f04d4', client.subscription_id)
self.assertEqual('https://management.azure.com/', client.base_url)
self.assertTupleEqual(client.credentials._args, (
'https://management.azure.com/',
'a2ab11af-01aa-4759-8345-7803287dbd39',
'password'
))
client = get_client_from_auth_file(FakeClient, temp_auth_file.name, subscription_id='fakesubid')
self.assertEqual('fakesubid', client.subscription_id)
self.assertEqual('https://management.azure.com/', client.base_url)
self.assertTupleEqual(client.credentials._args, (
'https://management.azure.com/',
'a2ab11af-01aa-4759-8345-7803287dbd39',
'password'
))
credentials_instance = "Fake credentials class as a string"
client = get_client_from_auth_file(FakeClient, temp_auth_file.name, credentials=credentials_instance)
self.assertEqual('15dbcfa8-4b93-4c9a-881c-6189d39f04d4', client.subscription_id)
self.assertEqual('https://management.azure.com/', client.base_url)
self.assertEqual(credentials_instance, client.credentials)
client = get_client_from_auth_file(FakeSubscriptionClient, temp_auth_file.name)
self.assertEqual('https://management.azure.com/', client.base_url)
self.assertTupleEqual(client.credentials._args, (
'https://management.azure.com/',
'a2ab11af-01aa-4759-8345-<PASSWORD>',
'password'
))
client = get_client_from_auth_file(GraphRbacManagementClient, temp_auth_file.name)
assert client.base_url == 'https://graph.windows.net/'
assert client.tenant_id == "c81da1d8-65ca-11e7-b1d1-ecb1d756380e"
assert client.credentials._args == (
"https://graph.windows.net/",
'a2ab11af-01aa-4759-8345-7803287dbd39',
'password'
)
client = get_client_from_auth_file(KeyVaultClient, temp_auth_file.name)
assert client.credentials._args == (
"https://vault.azure.net",
'a2ab11af-01<PASSWORD>',
'password'
)
with pytest.raises(ValueError) as excinfo:
get_client_from_auth_file(KeyVaultClientTrack2, temp_auth_file.name)
assert "https://aka.ms/azsdk/python/azidmigration" in str(excinfo.value)
os.unlink(temp_auth_file.name)
#------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
| 6,179 |
1,170 | <filename>VHGithubNotifier/View/VHPopUpButtonCell.h
//
// VHPopUpButtonCell.h
// VHGithubNotifier
//
// Created by viktorhuang on 2017/3/7.
// Copyright © 2017年 黄伟平. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface VHPopUpButtonCell : NSPopUpButtonCell
@end
| 120 |
450 | <filename>src/bin/gpoptutils/gpoptutils.c
/*
* 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.
* ---------------------------------------------------------------------
*
* The dynamically linked library created from this source can be reference by
* creating a function in psql that references it. For example,
*
* CREATE FUNCTION gp_dump_query_oids(text)
* RETURNS text
* AS '$libdir/gpoptutils', 'gp_dump_query_oids'
* LANGUAGE C STRICT;
*/
#include "postgres_fe.h"
#include "postgres.h"
#include "funcapi.h"
#include "utils/builtins.h"
#include "rewrite/rewriteHandler.h"
#include "tcop/tcopprot.h"
#define atooid(x) ((Oid) strtoul((x), NULL, 10))
Datum gp_dump_query_oids(PG_FUNCTION_ARGS);
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(gp_dump_query_oids);
static void
traverseQueryOids
(
Query *pquery,
HTAB *relhtab,
StringInfoData *relbuf,
HTAB *funchtab,
StringInfoData *funcbuf
)
{
bool found;
const char *whitespace = " \t\n\r";
char *query = nodeToString(pquery);
char *token = strtok(query, whitespace);
while (token)
{
if (pg_strcasecmp(token, ":relid") == 0)
{
token = strtok(NULL, whitespace);
if (token)
{
Oid relid = atooid(token);
hash_search(relhtab, (void *)&relid, HASH_ENTER, &found);
if (!found)
{
if (relbuf->len != 0)
appendStringInfo(relbuf, "%s", ",");
appendStringInfo(relbuf, "%u", relid);
}
}
}
else if (pg_strcasecmp(token, ":funcid") == 0)
{
token = strtok(NULL, whitespace);
if (token)
{
Oid funcid = atooid(token);
hash_search(funchtab, (void *)&funcid, HASH_ENTER, &found);
if (!found)
{
if (funcbuf->len != 0)
appendStringInfo(funcbuf, "%s", ",");
appendStringInfo(funcbuf, "%u", funcid);
}
}
}
token = strtok(NULL, whitespace);
}
}
/*
* Function dumping dependent relation & function oids for a given SQL text
*/
Datum
gp_dump_query_oids(PG_FUNCTION_ARGS)
{
char *sqlText = text_to_cstring(PG_GETARG_TEXT_P(0));
List *queryList = pg_parse_and_rewrite(sqlText, NULL, 0);
ListCell *plc;
StringInfoData relbuf, funcbuf;
initStringInfo(&relbuf);
initStringInfo(&funcbuf);
typedef struct OidHashEntry
{
Oid key;
bool value;
} OidHashEntry;
HASHCTL ctl;
ctl.keysize = sizeof(Oid);
ctl.entrysize = sizeof(OidHashEntry);
ctl.hash = oid_hash;
HTAB *relhtab = hash_create("relid hash table", 100, &ctl, HASH_ELEM | HASH_FUNCTION);
HTAB *funchtab = hash_create("funcid hash table", 100, &ctl, HASH_ELEM | HASH_FUNCTION);
foreach(plc, queryList)
{
Query *query = (Query *) lfirst(plc);
if (CMD_UTILITY == query->commandType && T_ExplainStmt == query->utilityStmt->type)
{
Query *queryExplain = ((ExplainStmt *)query->utilityStmt)->query;
List *queryTree = QueryRewrite(queryExplain);
Assert(1 == list_length(queryTree));
query = (Query *) lfirst(list_head(queryTree));
}
traverseQueryOids(query, relhtab, &relbuf, funchtab, &funcbuf);
}
hash_destroy(relhtab);
hash_destroy(funchtab);
StringInfoData str;
initStringInfo(&str);
appendStringInfo(&str, "{\"relids\": \"%s\", \"funcids\": \"%s\"}", relbuf.data, funcbuf.data);
text *result = cstring_to_text(str.data);
pfree(relbuf.data);
pfree(funcbuf.data);
pfree(str.data);
PG_RETURN_TEXT_P(result);
}
| 1,596 |
883 | <reponame>jerrywham/bludit
{
"plugin-data":
{
"name": "Compteur de visites",
"description": "Affichez le nombre de visites ou de visiteurs uniques dans la barre latérale de votre site."
},
"show-unique-visitors": "Afficher les visiteurs uniques"
} | 104 |
854 | <reponame>timxor/leetcode-journal
__________________________________________________________________________________________________
sample 52 ms submission
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num+1,0);
for(int i=1;i<=num;i++){
res[i]=res[i>>1]+(i&1);
}
return res;
}
};
__________________________________________________________________________________________________
sample 9340 kb submission
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num + 1);
ret[0] = 0;
for (int i = 1; i <= num; ++i) {
ret[i] = ret[i/2] + i%2;
}
return ret;
}
};
__________________________________________________________________________________________________
| 332 |
3,353 | <filename>jetty-util/src/main/java/org/eclipse/jetty/util/InetAddressSet.java<gh_stars>1000+
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.util;
import java.net.InetAddress;
import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/**
* A set of InetAddress patterns.
* <p>This is a {@link Set} of String patterns that are used to match
* a {@link Predicate} over InetAddress for containment semantics.
* The patterns that may be set are defined in {@link InetAddressPattern}.
* </p>
* <p>This class is designed to work with {@link IncludeExcludeSet}</p>
*
* @see IncludeExcludeSet
*/
public class InetAddressSet extends AbstractSet<String> implements Set<String>, Predicate<InetAddress>
{
private Map<String, InetAddressPattern> _patterns = new HashMap<>();
@Override
public boolean add(String pattern)
{
return _patterns.put(pattern, InetAddressPattern.from(pattern)) == null;
}
@Override
public boolean remove(Object pattern)
{
return _patterns.remove(pattern) != null;
}
@Override
public Iterator<String> iterator()
{
return _patterns.keySet().iterator();
}
@Override
public int size()
{
return _patterns.size();
}
@Override
public boolean test(InetAddress address)
{
if (address == null)
return false;
for (InetAddressPattern pattern : _patterns.values())
{
if (pattern.test(address))
return true;
}
return false;
}
}
| 757 |
318 | #include <stdlib.h>
#include <vector>
#include <set>
#include <functional>
#include <iostream>
#ifdef WITH_MAXFLOW_IBFS
# include <opengm/inference/auxiliary/minstcutibfs.hxx>
#endif
int main() {
#ifdef WITH_MAXFLOW_IBFS
typedef opengm::external::MinSTCutIBFS<int, int> MinStCutType;
MinStCutType g(5,2+3*2);
g.addEdge(0,2,1000);
g.addEdge(0,3,1);
g.addEdge(0,4,1);
g.addEdge(2,1,5);
g.addEdge(3,1,5);
g.addEdge(4,1,5);
g.addEdge(2,3,1);
g.addEdge(3,4,1);
std::vector<bool> x(5);
g.calculateCut(x);
for(size_t i=0; i<x.size(); ++i)
std::cout <<x[i]<< " ";
std::cout << std::endl;
#endif
return 0;
}
| 344 |
1,747 | <gh_stars>1000+
/*-
* -\-\-
* Helios Services
* --
* Copyright (C) 2016 Spotify AB
* --
* 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.spotify.helios.agent;
import com.codahale.metrics.health.HealthCheck;
import com.spotify.docker.client.DockerClient;
/**
* Checks if helios-agent can talk to Docker daemon.
*/
class DockerDaemonHealthChecker extends HealthCheck {
private final DockerClient dockerClient;
DockerDaemonHealthChecker(final DockerClient dockerClient) {
this.dockerClient = dockerClient;
}
@Override
protected Result check() throws Exception {
try {
dockerClient.ping();
return Result.healthy();
} catch (final Exception ex) {
return Result.unhealthy(ex);
}
}
}
| 379 |
548 | # Copyright 2019 ZTE corporation. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from . import repository
from .. import utilities
from ..models.irs.keras_model import KerasModel
from ..models.irs.tf_model import Input, TensorFlowModel
from ..keras_util import Config, get_inputs, get_outputs
@repository.REPOSITORY.register(source_type=KerasModel, target_type=TensorFlowModel, config_type=Config)
def compile_source(source: KerasModel, config: Config) -> TensorFlowModel:
inputs = [Input(tensor=tensor, data_format=data_format)
for tensor, data_format in get_inputs(source.model, config.input_nodes)]
outputs = get_outputs(source.model, config.output_nodes)
utilities.judge_batch_size([model_input.tensor.shape for model_input in inputs],
[model_output.shape for model_output in outputs])
return TensorFlowModel(inputs=inputs, outputs=outputs, session=source.session)
| 331 |
415 | //-----------------------------------------------------------------------------
// File: text.h
// Desc: class to enable drawing of text
// Copyright (C) 2005, <NAME>, <NAME>, UFRGS-Brasil
//-----------------------------------------------------------------------------
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//-----------------------------------------------------------------------------
#ifndef TEXT_H
#define TEXT_H
#include <tchar.h>
#include <D3D9.h>
//-----------------------------------------------------------------------------
// Name: class CText
// Desc: Texture-based font class for doing text in a 3D scene.
//-----------------------------------------------------------------------------
class CText {
char m_aszFontFilename[MAX_PATH];
IDirect3DDevice9 *m_pD3DDevice;
IDirect3DTexture9 *m_pTexture;
IDirect3DVertexBuffer9 *m_pVB;
int m_nTexWidth, m_nTexHeight;
float m_aafTexCoords[136][4];
//stateblocks for setting and restoring render states
IDirect3DStateBlock9 *m_pStateBlockSaved;
IDirect3DStateBlock9 *m_pStateBlockDrawText;
public:
//text drawing function
bool DrawText(float fSX, float fSY, DWORD wwColor, const char* aszText);
//initializing and destroying device-dependent objects
bool InitDeviceObjects(IDirect3DDevice9 *pd3dDevice);
bool RestoreDeviceObjects();
bool InvalidateDeviceObjects();
bool DeleteDeviceObjects();
//constructor / destructor
CText(const char* pszFontFilename);
~CText();
};
#endif //TEXT_H
| 647 |
323 | /*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jshell.execution;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import jdk.jshell.spi.ExecutionControl;
import jdk.jshell.spi.ExecutionControl.ClassBytecodes;
import jdk.jshell.spi.ExecutionControl.ClassInstallException;
import jdk.jshell.spi.ExecutionControl.EngineTerminationException;
import jdk.jshell.spi.ExecutionControl.InternalException;
import jdk.jshell.spi.ExecutionControl.NotImplementedException;
import jdk.jshell.spi.ExecutionControl.ResolutionException;
import jdk.jshell.spi.ExecutionControl.StoppedException;
import jdk.jshell.spi.ExecutionControl.UserException;
import static jdk.jshell.execution.RemoteCodes.*;
/**
* Forwards commands from the input to the specified {@link ExecutionControl}
* instance, then responses back on the output.
*/
class ExecutionControlForwarder {
/**
* Represent null in a streamed UTF string. Vanishingly improbable string to
* occur in a user string.
*/
static final String NULL_MARKER = "\u0002*\u03C0*NULL*\u03C0*\u0003";
/**
* Maximum number of characters for writeUTF(). Byte maximum is 65535, at
* maximum three bytes per character that is 65535 / 3 == 21845. Minus one
* for safety.
*/
private static final int MAX_UTF_CHARS = 21844;
private final ExecutionControl ec;
private final ObjectInput in;
private final ObjectOutput out;
ExecutionControlForwarder(ExecutionControl ec, ObjectInput in, ObjectOutput out) {
this.ec = ec;
this.in = in;
this.out = out;
}
private boolean writeSuccess() throws IOException {
writeStatus(RESULT_SUCCESS);
flush();
return true;
}
private boolean writeSuccessAndResult(String result) throws IOException {
writeStatus(RESULT_SUCCESS);
writeUTF(result);
flush();
return true;
}
private boolean writeSuccessAndResult(Object result) throws IOException {
writeStatus(RESULT_SUCCESS);
writeObject(result);
flush();
return true;
}
private void writeStatus(int status) throws IOException {
out.writeInt(status);
}
private void writeObject(Object o) throws IOException {
out.writeObject(o);
}
private void writeInt(int i) throws IOException {
out.writeInt(i);
}
private void writeNullOrUTF(String s) throws IOException {
writeUTF(s == null ? NULL_MARKER : s);
}
private void writeUTF(String s) throws IOException {
if (s == null) {
s = "";
} else if (s.length() > MAX_UTF_CHARS) {
// Truncate extremely long strings to prevent writeUTF from crashing the VM
s = s.substring(0, MAX_UTF_CHARS);
}
out.writeUTF(s);
}
private void flush() throws IOException {
out.flush();
}
private boolean processCommand() throws IOException {
try {
int prefix = in.readInt();
if (prefix != COMMAND_PREFIX) {
throw new EngineTerminationException("Invalid command prefix: " + prefix);
}
String cmd = in.readUTF();
switch (cmd) {
case CMD_LOAD: {
// Load a generated class file over the wire
ClassBytecodes[] cbcs = (ClassBytecodes[]) in.readObject();
ec.load(cbcs);
return writeSuccess();
}
case CMD_REDEFINE: {
// Load a generated class file over the wire
ClassBytecodes[] cbcs = (ClassBytecodes[]) in.readObject();
ec.redefine(cbcs);
return writeSuccess();
}
case CMD_INVOKE: {
// Invoke executable entry point in loaded code
String className = in.readUTF();
String methodName = in.readUTF();
String res = ec.invoke(className, methodName);
return writeSuccessAndResult(res);
}
case CMD_VAR_VALUE: {
// Retrieve a variable value
String className = in.readUTF();
String varName = in.readUTF();
String res = ec.varValue(className, varName);
return writeSuccessAndResult(res);
}
case CMD_ADD_CLASSPATH: {
// Append to the claspath
String cp = in.readUTF();
ec.addToClasspath(cp);
return writeSuccess();
}
case CMD_STOP: {
// Stop the current execution
try {
ec.stop();
} catch (Throwable ex) {
// JShell-core not waiting for a result, ignore
}
return true;
}
case CMD_CLOSE: {
// Terminate this process
try {
ec.close();
} catch (Throwable ex) {
// JShell-core not waiting for a result, ignore
}
return true;
}
default: {
Object arg = in.readObject();
Object res = ec.extensionCommand(cmd, arg);
return writeSuccessAndResult(res);
}
}
} catch (IOException ex) {
// handled by the outer level
throw ex;
} catch (EngineTerminationException ex) {
writeStatus(RESULT_TERMINATED);
writeUTF(ex.getMessage());
flush();
return false;
} catch (NotImplementedException ex) {
writeStatus(RESULT_NOT_IMPLEMENTED);
writeUTF(ex.getMessage());
flush();
return true;
} catch (InternalException ex) {
writeInternalException(ex);
flush();
return true;
} catch (ClassInstallException ex) {
writeStatus(RESULT_CLASS_INSTALL_EXCEPTION);
writeUTF(ex.getMessage());
writeObject(ex.installed());
flush();
return true;
} catch (UserException ex) {
writeStatus(RESULT_USER_EXCEPTION_CHAINED);
for (Throwable e = ex; e != null; ) {
if (e instanceof UserException) {
writeUserException((UserException) e);
e = e.getCause();
} else if (e instanceof ResolutionException) {
writeResolutionException((ResolutionException) e);
e = null;
} else {
writeInternalException(e);
e = null;
}
}
writeStatus(RESULT_SUCCESS);
flush();
return true;
} catch (ResolutionException ex) {
writeResolutionException(ex);
flush();
return true;
} catch (StoppedException ex) {
writeStatus(RESULT_STOPPED);
flush();
return true;
} catch (Throwable ex) {
// Unexpected exception, have something in the message
writeStatus(RESULT_TERMINATED);
String msg = ex.getMessage();
writeUTF(msg == null? ex.toString() : msg);
flush();
return false;
}
}
void writeInternalException(Throwable ex) throws IOException {
writeStatus(RESULT_INTERNAL_PROBLEM);
writeUTF(ex.getMessage());
}
void writeUserException(UserException ex) throws IOException {
writeStatus(RESULT_USER_EXCEPTION);
writeNullOrUTF(ex.getMessage());
writeUTF(ex.causeExceptionClass());
writeObject(ex.getStackTrace());
}
void writeResolutionException(ResolutionException ex) throws IOException {
writeStatus(RESULT_CORRALLED);
writeInt(ex.id());
writeObject(ex.getStackTrace());
}
void commandLoop() {
try {
while (processCommand()) {
// condition is loop action
}
} catch (IOException ex) {
// drop out of loop
}
}
}
| 4,398 |
530 | package com.bladecoder.engineeditor.undo;
import com.bladecoder.engine.model.BaseActor;
import com.bladecoder.engine.model.Scene;
import com.bladecoder.engineeditor.Ctx;
import com.bladecoder.engineeditor.model.Project;
public class UndoDeleteActor implements UndoOp {
private BaseActor a;
private Scene s;
public UndoDeleteActor(Scene s, BaseActor a) {
this.s = s;
this.a = a;
}
@Override
public void undo() {
s.addActor(a);
Ctx.project.setModified(this, Project.NOTIFY_ELEMENT_CREATED, null, a);
}
}
| 196 |
11,902 | <filename>chia/wallet/key_val_store.py
from typing import Any
import aiosqlite
from chia.util.byte_types import hexstr_to_bytes
from chia.util.db_wrapper import DBWrapper
from chia.util.streamable import Streamable
class KeyValStore:
"""
Multipurpose persistent key-value store
"""
db_connection: aiosqlite.Connection
db_wrapper: DBWrapper
@classmethod
async def create(cls, db_wrapper: DBWrapper):
self = cls()
self.db_wrapper = db_wrapper
self.db_connection = db_wrapper.db
await self.db_connection.execute(
("CREATE TABLE IF NOT EXISTS key_val_store(" " key text PRIMARY KEY," " value text)")
)
await self.db_connection.execute("CREATE INDEX IF NOT EXISTS name on key_val_store(key)")
await self.db_connection.commit()
return self
async def _clear_database(self):
cursor = await self.db_connection.execute("DELETE FROM key_val_store")
await cursor.close()
await self.db_connection.commit()
async def get_object(self, key: str, type: Any) -> Any:
"""
Return bytes representation of stored object
"""
cursor = await self.db_connection.execute("SELECT * from key_val_store WHERE key=?", (key,))
row = await cursor.fetchone()
await cursor.close()
if row is None:
return None
return type.from_bytes(hexstr_to_bytes(row[1]))
async def set_object(self, key: str, obj: Streamable):
"""
Adds object to key val store
"""
async with self.db_wrapper.lock:
cursor = await self.db_connection.execute(
"INSERT OR REPLACE INTO key_val_store VALUES(?, ?)",
(key, bytes(obj).hex()),
)
await cursor.close()
await self.db_connection.commit()
| 783 |
328 | <filename>app/src/main/java/com/stx/xhb/dmgameapp/data/entity/GameBean.java
package com.stx.xhb.dmgameapp.data.entity;
/**
* @author: xiaohaibin.
* @time: 2018/9/11
* @mail:<EMAIL>
* @github:https://github.com/xiaohaibin
* @describe: GameBean
*/
public class GameBean {
/**
* aid : 3712501
* arcurl : https://www.3dmgame.com/games/snkhttf/
* title : SNK女格斗家大乱斗
* litpic : https://img.3dmgame.com/uploads/images/thumbkwdfirst/20180907/1536289976_982297.jpg
* pubdate_at : 1536249600
* showtype : 3
*/
private String aid;
private String arcurl;
private String title;
private String litpic;
private int pubdate_at;
private int showtype;
private double score;
public double getScore() {
return score;
}
public String getAid() {
return aid;
}
public String getArcurl() {
return arcurl;
}
public String getTitle() {
return title;
}
public String getLitpic() {
return litpic;
}
public int getPubdate_at() {
return pubdate_at;
}
public int getShowtype() {
return showtype;
}
}
| 521 |
7,789 | <filename>resilience4j-core/src/test/java/io/github/resilience4j/core/functions/OnceConsumerTest.java
package io.github.resilience4j.core.functions;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.*;
/**
* Class OnceConsumer test.
*/
public class OnceConsumerTest {
@Test
public void shouldApplyOnlyOnce() {
final List<String> lst = new ArrayList<>();
OnceConsumer<List<String>> once = OnceConsumer.of(lst);
once.applyOnce((l) -> l.add("Hello World"));
once.applyOnce((l) -> l.add("Hello World"));
assertThat(lst).hasSize(1).contains("Hello World");
}
@Test
public void shouldRunOnlyOnceWithException() {
final List<String> lst = new ArrayList<>();
OnceConsumer<List<String>> once = OnceConsumer.of(lst);
Consumer<List<String>> blowUp = (l) -> {
throw new RuntimeException("BAM!");
};
Throwable cause = catchThrowable(() -> once.applyOnce(blowUp));
assertThat(cause).isInstanceOf(RuntimeException.class).hasMessage("BAM!");
assertThatCode(() -> once.applyOnce(blowUp)).doesNotThrowAnyException();
}
} | 481 |
2,144 | /**
* 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.pinot.common.metadata.instance;
import java.util.HashMap;
import java.util.Map;
import org.apache.helix.ZNRecord;
import org.apache.pinot.common.metadata.ZKMetadata;
import org.apache.pinot.spi.utils.StringUtil;
import org.apache.pinot.spi.utils.builder.TableNameBuilder;
import static org.apache.pinot.spi.utils.EqualityUtils.hashCodeOf;
import static org.apache.pinot.spi.utils.EqualityUtils.isEqual;
import static org.apache.pinot.spi.utils.EqualityUtils.isNullOrNotSameClass;
import static org.apache.pinot.spi.utils.EqualityUtils.isSameReference;
public final class InstanceZKMetadata implements ZKMetadata {
private static final String KAFKA_HIGH_LEVEL_CONSUMER_GROUP_MAP = "KAFKA_HLC_GROUP_MAP";
private static final String KAFKA_HIGH_LEVEL_CONSUMER_PARTITION_MAP = "KAFKA_HLC_PARTITION_MAP";
private String _id = null;
private String _instanceName = null;
private int _instancePort;
private String _instanceType = null;
// Only care about realtime resources for now
private Map<String, String> _groupIdMap = new HashMap<String, String>();
private Map<String, String> _partitionMap = new HashMap<String, String>();
public InstanceZKMetadata() {
}
public InstanceZKMetadata(ZNRecord record) {
_id = record.getId();
setInstanceConfigFromId(_id);
_groupIdMap.putAll(record.getMapField(KAFKA_HIGH_LEVEL_CONSUMER_GROUP_MAP));
_partitionMap.putAll(record.getMapField(KAFKA_HIGH_LEVEL_CONSUMER_PARTITION_MAP));
}
private void setInstanceConfigFromId(String id) {
String[] instanceConfigs = id.split("_");
assert instanceConfigs.length == 3;
setInstanceType(instanceConfigs[0]);
setInstanceName(instanceConfigs[1]);
setInstancePort(Integer.parseInt(instanceConfigs[2]));
}
public int getInstancePort() {
return _instancePort;
}
public void setInstancePort(int instancePort) {
_instancePort = instancePort;
}
public String getInstanceType() {
return _instanceType;
}
public void setInstanceType(String instanceType) {
_instanceType = instanceType;
}
public String getId() {
if (_id == null) {
_id = buildIdFromInstanceConfig();
}
return _id;
}
public void setId(String id) {
_id = id;
}
public String getInstanceName() {
return _instanceName;
}
public void setInstanceName(String instanceName) {
_instanceName = instanceName;
}
public String getGroupId(String resourceName) {
return _groupIdMap.get(TableNameBuilder.REALTIME.tableNameWithType(resourceName));
}
public void setGroupId(String resourceName, String groupId) {
_groupIdMap.put(TableNameBuilder.REALTIME.tableNameWithType(resourceName), groupId);
}
public String getPartition(String resourceName) {
return _partitionMap.get(TableNameBuilder.REALTIME.tableNameWithType(resourceName));
}
public void setPartition(String resourceName, String partition) {
_partitionMap.put(TableNameBuilder.REALTIME.tableNameWithType(resourceName), partition);
}
public void removeResource(String resourceName) {
_groupIdMap.remove(resourceName);
_partitionMap.remove(resourceName);
}
@Override
public ZNRecord toZNRecord() {
ZNRecord znRecord = new ZNRecord(getId());
znRecord.setMapField(KAFKA_HIGH_LEVEL_CONSUMER_GROUP_MAP, _groupIdMap);
znRecord.setMapField(KAFKA_HIGH_LEVEL_CONSUMER_PARTITION_MAP, _partitionMap);
return znRecord;
}
private String buildIdFromInstanceConfig() {
return StringUtil.join("_", _instanceType, _instanceName, _instancePort + "");
}
@Override
public boolean equals(Object instanceMetadata) {
if (isSameReference(this, instanceMetadata)) {
return true;
}
if (isNullOrNotSameClass(this, instanceMetadata)) {
return false;
}
InstanceZKMetadata metadata = (InstanceZKMetadata) instanceMetadata;
return isEqual(_id, metadata._id) && isEqual(_instanceName, metadata._instanceName) && isEqual(_instanceType,
metadata._instanceType) && isEqual(_instancePort, metadata._instancePort) && isEqual(_groupIdMap,
metadata._groupIdMap) && isEqual(_partitionMap, metadata._partitionMap);
}
@Override
public int hashCode() {
int result = hashCodeOf(_id);
result = hashCodeOf(result, _instanceName);
result = hashCodeOf(result, _instancePort);
result = hashCodeOf(result, _instanceType);
result = hashCodeOf(result, _groupIdMap);
result = hashCodeOf(result, _partitionMap);
return result;
}
}
| 1,744 |
3,459 | <filename>Real-Time Corruptor/BizHawk_RTC/libmupen64plus/mupen64plus-video-glide64mk2/src/Glide64/TexMod.h
/*
* Glide64 - Glide video plugin for Nintendo 64 emulators.
* Copyright (c) 2002 Dave2001
* Copyright (c) 2003-2009 Sergey 'Gonetz' Lipski
*
* 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
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//****************************************************************
//
// Glide64 - Glide Plugin for Nintendo 64 emulators
// Project started on December 29th, 2001
//
// Authors:
// Dave2001, original author, founded the project in 2001, left it in 2002
// Gugaman, joined the project in 2002, left it in 2002
// Sergey 'Gonetz' Lipski, joined the project in 2002, main author since fall of 2002
// Hiroshi 'KoolSmoky' Morii, joined the project in 2007
//
//****************************************************************
//
// To modify Glide64:
// * Write your name and (optional)email, commented by your work, so I know who did it, and so that you can find which parts you modified when it comes time to send it to me.
// * Do NOT send me the whole project or file that you modified. Take out your modified code sections, and tell me where to put them. If people sent the whole thing, I would have many different versions, but no idea how to combine them all.
//
//****************************************************************
static void mod_tex_inter_color_using_factor (wxUint16 *dst, int size, wxUint32 color, wxUint32 factor)
{
float percent = factor / 255.0f;
float percent_i = 1 - percent;
wxUint32 cr, cg, cb;
wxUint16 col, a;
wxUint8 r, g, b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
r = (wxUint8)(percent_i * ((col >> 8) & 0xF) + percent * cr);
g = (wxUint8)(percent_i * ((col >> 4) & 0xF) + percent * cg);
b = (wxUint8)(percent_i * (col & 0xF) + percent * cb);
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_inter_col_using_col1 (wxUint16 *dst, int size, wxUint32 color0, wxUint32 color1)
{
wxUint32 cr, cg, cb;
wxUint16 col, a;
wxUint8 r, g, b;
float percent_r = ((color1 >> 12) & 0xF) / 15.0f;
float percent_g = ((color1 >> 8) & 0xF) / 15.0f;
float percent_b = ((color1 >> 4) & 0xF) / 15.0f;
float percent_r_i = 1.0f - percent_r;
float percent_g_i = 1.0f - percent_g;
float percent_b_i = 1.0f - percent_b;
cr = (color0 >> 12) & 0xF;
cg = (color0 >> 8) & 0xF;
cb = (color0 >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
r = (wxUint8)(percent_r_i * ((col >> 8) & 0xF) + percent_r * cr);
g = (wxUint8)(percent_g_i * ((col >> 4) & 0xF) + percent_g * cg);
b = (wxUint8)(percent_b_i * (col & 0xF) + percent_b * cb);
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_full_color_sub_tex (wxUint16 *dst, int size, wxUint32 color)
{
wxUint32 cr, cg, cb, ca;
wxUint16 col;
wxUint8 a, r, g, b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
ca = color & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = (wxUint8)(ca - ((col >> 12) & 0xF));
r = (wxUint8)(cr - ((col >> 8) & 0xF));
g = (wxUint8)(cg - ((col >> 4) & 0xF));
b = (wxUint8)(cb - (col & 0xF));
*(dst++) = (a << 12) | (r << 8) | (g << 4) | b;
}
}
static void mod_col_inter_col1_using_tex (wxUint16 *dst, int size, wxUint32 color0, wxUint32 color1)
{
wxUint32 cr0, cg0, cb0, cr1, cg1, cb1;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent_r, percent_g, percent_b;
cr0 = (color0 >> 12) & 0xF;
cg0 = (color0 >> 8) & 0xF;
cb0 = (color0 >> 4) & 0xF;
cr1 = (color1 >> 12) & 0xF;
cg1 = (color1 >> 8) & 0xF;
cb1 = (color1 >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent_r = ((col >> 8) & 0xF) / 15.0f;
percent_g = ((col >> 4) & 0xF) / 15.0f;
percent_b = (col & 0xF) / 15.0f;
r = min(15, (wxUint8)((1.0f-percent_r) * cr0 + percent_r * cr1 + 0.0001f));
g = min(15, (wxUint8)((1.0f-percent_g) * cg0 + percent_g * cg1 + 0.0001f));
b = min(15, (wxUint8)((1.0f-percent_b) * cb0 + percent_b * cb1 + 0.0001f));
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_col_inter_col1_using_texa (wxUint16 *dst, int size, wxUint32 color0, wxUint32 color1)
{
wxUint32 cr0, cg0, cb0, cr1, cg1, cb1;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent, percent_i;
cr0 = (color0 >> 12) & 0xF;
cg0 = (color0 >> 8) & 0xF;
cb0 = (color0 >> 4) & 0xF;
cr1 = (color1 >> 12) & 0xF;
cg1 = (color1 >> 8) & 0xF;
cb1 = (color1 >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent = (a >> 12) / 15.0f;
percent_i = 1.0f - percent;
r = (wxUint8)(percent_i * cr0 + percent * cr1);
g = (wxUint8)(percent_i * cg0 + percent * cg1);
b = (wxUint8)(percent_i * cb0 + percent * cb1);
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_col_inter_col1_using_texa__mul_tex (wxUint16 *dst, int size, wxUint32 color0, wxUint32 color1)
{
wxUint32 cr0, cg0, cb0, cr1, cg1, cb1;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent, percent_i;
cr0 = (color0 >> 12) & 0xF;
cg0 = (color0 >> 8) & 0xF;
cb0 = (color0 >> 4) & 0xF;
cr1 = (color1 >> 12) & 0xF;
cg1 = (color1 >> 8) & 0xF;
cb1 = (color1 >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent = (a >> 12) / 15.0f;
percent_i = 1.0f - percent;
r = (wxUint8)(((percent_i * cr0 + percent * cr1) / 15.0f) * (((col & 0x0F00) >> 8) / 15.0f) * 15.0f);
g = (wxUint8)(((percent_i * cg0 + percent * cg1) / 15.0f) * (((col & 0x00F0) >> 4) / 15.0f) * 15.0f);
b = (wxUint8)(((percent_i * cb0 + percent * cb1) / 15.0f) * ((col & 0x000F) / 15.0f) * 15.0f);
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_col_inter_tex_using_tex (wxUint16 *dst, int size, wxUint32 color)
{
wxUint32 cr, cg, cb;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent_r, percent_g, percent_b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent_r = ((col >> 8) & 0xF) / 15.0f;
percent_g = ((col >> 4) & 0xF) / 15.0f;
percent_b = (col & 0xF) / 15.0f;
r = (wxUint8)((1.0f-percent_r) * cr + percent_r * ((col & 0x0F00) >> 8));
g = (wxUint8)((1.0f-percent_g) * cg + percent_g * ((col & 0x00F0) >> 4));
b = (wxUint8)((1.0f-percent_b) * cb + percent_b * (col & 0x000F));
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_col_inter_tex_using_texa (wxUint16 *dst, int size, wxUint32 color)
{
wxUint32 cr, cg, cb;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent, percent_i;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent = (a >> 12) / 15.0f;
percent_i = 1.0f - percent;
r = (wxUint8)(percent_i * cr + percent * ((col & 0x0F00) >> 8));
g = (wxUint8)(percent_i * cg + percent * ((col & 0x00F0) >> 4));
b = (wxUint8)(percent_i * cb + percent * (col & 0x000F));
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_col2_inter__col_inter_col1_using_tex__using_texa (wxUint16 *dst, int size,
wxUint32 color0, wxUint32 color1,
wxUint32 color2)
{
wxUint32 cr0, cg0, cb0, cr1, cg1, cb1, cr2, cg2, cb2;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent_r, percent_g, percent_b, percent_a;
cr0 = (color0 >> 12) & 0xF;
cg0 = (color0 >> 8) & 0xF;
cb0 = (color0 >> 4) & 0xF;
cr1 = (color1 >> 12) & 0xF;
cg1 = (color1 >> 8) & 0xF;
cb1 = (color1 >> 4) & 0xF;
cr2 = (color2 >> 12) & 0xF;
cg2 = (color2 >> 8) & 0xF;
cb2 = (color2 >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent_a = (a >> 12) / 15.0f;
percent_r = ((col >> 8) & 0xF) / 15.0f;
percent_g = ((col >> 4) & 0xF) / 15.0f;
percent_b = (col & 0xF) / 15.0f;
r = (wxUint8)(((1.0f-percent_r) * cr0 + percent_r * cr1) * percent_a + cr2 * (1.0f-percent_a));
g = (wxUint8)(((1.0f-percent_g) * cg0 + percent_g * cg1) * percent_a + cg2 * (1.0f-percent_a));
b = (wxUint8)(((1.0f-percent_b) * cb0 + percent_b * cb1) * percent_a + cb2 * (1.0f-percent_a));
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_scale_fac_add_fac (wxUint16 *dst, int size, wxUint32 factor)
{
float percent = factor / 255.0f;
wxUint16 col;
wxUint8 a;
float base_a = (1.0f - percent) * 15.0f;
for (int i=0; i<size; i++)
{
col = *dst;
a = (wxUint8)(base_a + percent * (col>>12));
*(dst++) = (a<<12) | (col & 0x0FFF);
}
}
static void mod_tex_sub_col_mul_fac_add_tex (wxUint16 *dst, int size, wxUint32 color, wxUint32 factor)
{
float percent = factor / 255.0f;
wxUint32 cr, cg, cb;
wxUint16 col, a;
float r, g, b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
r = (float)((col >> 8) & 0xF);
r = /*max(*/(r - cr) * percent/*, 0.0f)*/ + r;
if (r > 15.0f) r = 15.0f;
if (r < 0.0f) r = 0.0f;
g = (float)((col >> 4) & 0xF);
g = /*max(*/(g - cg) * percent/*, 0.0f)*/ + g;
if (g > 15.0f) g = 15.0f;
if (g < 0.0f) g = 0.0f;
b = (float)(col & 0xF);
b = /*max(*/(b - cb) * percent/*, 0.0f)*/ + b;
if (b > 15.0f) b = 15.0f;
if (b < 0.0f) b = 0.0f;
*(dst++) = a | ((wxUint16)r << 8) | ((wxUint16)g << 4) | (wxUint16)b;
}
}
static void mod_tex_scale_col_add_col (wxUint16 *dst, int size, wxUint32 color0, wxUint32 color1)
{
wxUint32 cr0, cg0, cb0, cr1, cg1, cb1;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent_r, percent_g, percent_b;
cr0 = (color0 >> 12) & 0xF;
cg0 = (color0 >> 8) & 0xF;
cb0 = (color0 >> 4) & 0xF;
cr1 = (color1 >> 12) & 0xF;
cg1 = (color1 >> 8) & 0xF;
cb1 = (color1 >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent_r = ((col >> 8) & 0xF) / 15.0f;
percent_g = ((col >> 4) & 0xF) / 15.0f;
percent_b = (col & 0xF) / 15.0f;
r = min(15, (wxUint8)(percent_r * cr0 + cr1 + 0.0001f));
g = min(15, (wxUint8)(percent_g * cg0 + cg1 + 0.0001f));
b = min(15, (wxUint8)(percent_b * cb0 + cb1 + 0.0001f));
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_add_col (wxUint16 *dst, int size, wxUint32 color)
{
wxUint32 cr, cg, cb;
wxUint16 col;
wxUint8 a, r, g, b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = (wxUint8)((col >> 12) & 0xF);
// a = col & 0xF000;
r = (wxUint8)(cr + ((col >> 8) & 0xF))&0xF;
g = (wxUint8)(cg + ((col >> 4) & 0xF))&0xF;
b = (wxUint8)(cb + (col & 0xF))&0xF;
*(dst++) = (a << 12) | (r << 8) | (g << 4) | b;
}
}
static void mod_col_mul_texa_add_tex (wxUint16 *dst, int size, wxUint32 color)
{
wxUint32 cr, cg, cb;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float factor;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
factor = (a >> 12) / 15.0f;
r = (wxUint8)(cr*factor + ((col >> 8) & 0xF))&0xF;
g = (wxUint8)(cg*factor + ((col >> 4) & 0xF))&0xF;
b = (wxUint8)(cb*factor + (col & 0xF))&0xF;
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_sub_col (wxUint16 *dst, int size, wxUint32 color)
{
int cr, cg, cb;
wxUint16 col;
wxUint8 a, r, g, b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = (wxUint8)(col & 0xF000);
r = (wxUint8)max((((col >> 8) & 0xF) - cr), 0);
g = (wxUint8)max((((col >> 4) & 0xF) - cg), 0);
b = (wxUint8)max(((col & 0xF) - cb), 0);
*(dst++) = (a << 12) | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_sub_col_mul_fac (wxUint16 *dst, int size, wxUint32 color, wxUint32 factor)
{
float percent = factor / 255.0f;
wxUint32 cr, cg, cb;
wxUint16 col, a;
float r, g, b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = (wxUint8)((col >> 12) & 0xF);
r = (float)((col >> 8) & 0xF);
r = (r - cr) * percent;
if (r > 15.0f) r = 15.0f;
if (r < 0.0f) r = 0.0f;
g = (float)((col >> 4) & 0xF);
g = (g - cg) * percent;
if (g > 15.0f) g = 15.0f;
if (g < 0.0f) g = 0.0f;
b = (float)(col & 0xF);
b = (b - cb) * percent;
if (b > 15.0f) b = 15.0f;
if (b < 0.0f) b = 0.0f;
*(dst++) = (a << 12) | ((wxUint16)r << 8) | ((wxUint16)g << 4) | (wxUint16)b;
}
}
static void mod_col_inter_tex_using_col1 (wxUint16 *dst, int size, wxUint32 color0, wxUint32 color1)
{
wxUint32 cr, cg, cb;
wxUint16 col, a;
wxUint8 r, g, b;
float percent_r = ((color1 >> 12) & 0xF) / 15.0f;
float percent_g = ((color1 >> 8) & 0xF) / 15.0f;
float percent_b = ((color1 >> 4) & 0xF) / 15.0f;
float percent_r_i = 1.0f - percent_r;
float percent_g_i = 1.0f - percent_g;
float percent_b_i = 1.0f - percent_b;
cr = (color0 >> 12) & 0xF;
cg = (color0 >> 8) & 0xF;
cb = (color0 >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = (wxUint8)((col >> 12) & 0xF);
r = (wxUint8)(percent_r * ((col >> 8) & 0xF) + percent_r_i * cr);
g = (wxUint8)(percent_g * ((col >> 4) & 0xF) + percent_g_i * cg);
b = (wxUint8)(percent_b * (col & 0xF) + percent_b_i * cb);
*(dst++) = (a << 12) | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_inter_noise_using_col (wxUint16 *dst, int size, wxUint32 color)
{
wxUint16 col, a;
wxUint8 r, g, b, noise;
float percent_r = ((color >> 12) & 0xF) / 15.0f;
float percent_g = ((color >> 8) & 0xF) / 15.0f;
float percent_b = ((color >> 4) & 0xF) / 15.0f;
float percent_r_i = 1.0f - percent_r;
float percent_g_i = 1.0f - percent_g;
float percent_b_i = 1.0f - percent_b;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
noise = rand()%16;
r = (wxUint8)(percent_r_i * ((col >> 8) & 0xF) + percent_r * noise);
g = (wxUint8)(percent_g_i * ((col >> 4) & 0xF) + percent_g * noise);
b = (wxUint8)(percent_b_i * (col & 0xF) + percent_b * noise);
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_inter_col_using_texa (wxUint16 *dst, int size, wxUint32 color)
{
wxUint32 cr, cg, cb;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
float percent, percent_i;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
percent = (a >> 12) / 15.0f;
percent_i = 1.0f - percent;
r = (wxUint8)(percent * cr + percent_i * ((col & 0x0F00) >> 8));
g = (wxUint8)(percent * cg + percent_i * ((col & 0x00F0) >> 4));
b = (wxUint8)(percent * cb + percent_i * (col & 0x000F));
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_mul_col (wxUint16 *dst, int size, wxUint32 color)
{
float cr, cg, cb;
wxUint16 col;
wxUint8 r, g, b;
wxUint16 a;
cr = (float)((color >> 12) & 0xF)/16.0f;
cg = (float)((color >> 8) & 0xF)/16.0f;
cb = (float)((color >> 4) & 0xF)/16.0f;
for (int i=0; i<size; i++)
{
col = *dst;
a = col & 0xF000;
r = (wxUint8)(cr * ((col & 0x0F00) >> 8));
g = (wxUint8)(cg * ((col & 0x00F0) >> 4));
b = (wxUint8)(cb * (col & 0x000F));
*(dst++) = a | (r << 8) | (g << 4) | b;
}
}
static void mod_tex_scale_fac_add_col (wxUint16 *dst, int size, wxUint32 color, wxUint32 factor)
{
float percent = factor / 255.0f;
wxUint32 cr, cg, cb;
wxUint16 col;
float r, g, b;
cr = (color >> 12) & 0xF;
cg = (color >> 8) & 0xF;
cb = (color >> 4) & 0xF;
for (int i=0; i<size; i++)
{
col = *dst;
r = cr + percent * (float)((col>>8)&0xF);
g = cg + percent * (float)((col>>4)&0xF);
b = cb + percent * (float)(col&0xF);
*(dst++) = (col&0xF000) | ((wxUint8)r << 8) | ((wxUint8)g << 4) | (wxUint8)b;
}
}
| 8,251 |
759 | <filename>Line/line_base.py
import pyecharts.options as opts
from pyecharts.charts import Line
from pyecharts.faker import Faker
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values())
.add_yaxis("商家B", Faker.values())
.set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
.render("line_base.html")
)
| 168 |
2,707 | package org.jetlinks.community.notify.manager.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.hswebframework.web.dict.EnumDict;
@Getter
@AllArgsConstructor
public enum NotifyState implements EnumDict<String> {
success("成功"),
error("失败");
private final String text;
@Override
public String getValue() {
return name();
}
}
| 147 |
14,965 | <filename>app/wails.json
{
"name": "xbar",
"outputfilename": "xbar",
"html": "frontend/public/index.html",
"js": "frontend/public/bundle.js",
"css": "frontend/public/bundle.css",
"frontend:build": "npm run build",
"frontend:install": "npm install"
}
| 121 |
2,223 | <filename>iPERCore/tools/human_digitalizer/smplx/body_models.py
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is authorized to grant you that right.
# Any use of the computer program without a valid license is prohibited and
# liable to prosecution.
#
# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
# for Intelligent Systems. All rights reserved.
#
# Contact: <EMAIL>
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import os.path as osp
try:
import cPickle as pickle
except ImportError:
import pickle
import numpy as np
from collections import namedtuple
import torch
import torch.nn as nn
from .lbs import (
lbs, vertices2landmarks, find_dynamic_lmk_idx_and_bcoords)
from .vertex_ids import vertex_ids as VERTEX_IDS
from .utils import Struct, to_np, to_tensor
from .vertex_joint_selector import VertexJointSelector
ModelOutput = namedtuple('ModelOutput',
['vertices', 'joints', 'full_pose', 'betas',
'global_orient',
'body_pose', 'expression',
'left_hand_pose', 'right_hand_pose',
'jaw_pose'])
ModelOutput.__new__.__defaults__ = (None,) * len(ModelOutput._fields)
def create(model_path, model_type='smpl',
**kwargs):
""" Method for creating a model from a path and a model type
Parameters
----------
model_path: str
Either the path to the model you wish to load or a folder,
where each subfolder contains the differents types, i.e.:
model_path:
|
|-- smpl
|-- SMPL_FEMALE
|-- SMPL_NEUTRAL
|-- SMPL_MALE
|-- smplh
|-- SMPLH_FEMALE
|-- SMPLH_MALE
|-- smplx
|-- SMPLX_FEMALE
|-- SMPLX_NEUTRAL
|-- SMPLX_MALE
model_type: str, optional
When model_path is a folder, then this parameter specifies the
type of model to be loaded
**kwargs: dict
Keyword arguments
Returns
-------
body_model: nn.Module
The PyTorch module that implements the corresponding body model
Raises
------
ValueError: In case the model type is not one of SMPL, SMPLH or
SMPLX
"""
# If it's a folder, assume
if osp.isdir(model_path):
model_path = os.path.join(model_path, model_type)
if model_type.lower() == 'smpl':
return SMPL(model_path, **kwargs)
elif model_type.lower() == 'smplh':
return SMPLH(model_path, **kwargs)
elif model_type.lower() == 'smplx':
return SMPLX(model_path, **kwargs)
else:
raise ValueError('Unknown model type {}, exiting!'.format(model_type))
class SMPL(nn.Module):
NUM_JOINTS = 23
NUM_BODY_JOINTS = 23
NUM_BETAS = 10
def __init__(self, model_path, data_struct=None,
create_betas=True,
betas=None,
create_global_orient=True,
global_orient=None,
create_body_pose=True,
body_pose=None,
create_transl=True,
transl=None,
dtype=torch.float32,
batch_size=1,
joint_mapper=None, gender='neutral',
vertex_ids=None,
**kwargs):
""" SMPL model constructor
Parameters
----------
model_path: str
The path to the folder or to the file where the model
parameters are stored
data_struct: Strct
A struct object. If given, then the parameters of the model are
read from the object. Otherwise, the model tries to read the
parameters from the given `model_path`. (default = None)
create_global_orient: bool, optional
Flag for creating a member variable for the global orientation
of the body. (default = True)
global_orient: torch.tensor, optional, Bx3
The default value for the global orientation variable.
(default = None)
create_body_pose: bool, optional
Flag for creating a member variable for the pose of the body.
(default = True)
body_pose: torch.tensor, optional, Bx(Body Joints * 3)
The default value for the body pose variable.
(default = None)
create_betas: bool, optional
Flag for creating a member variable for the shape space
(default = True).
betas: torch.tensor, optional, Bx10
The default value for the shape member variable.
(default = None)
create_transl: bool, optional
Flag for creating a member variable for the translation
of the body. (default = True)
transl: torch.tensor, optional, Bx3
The default value for the transl variable.
(default = None)
dtype: torch.dtype, optional
The data type for the created variables
batch_size: int, optional
The batch size used for creating the member variables
joint_mapper: object, optional
An object that re-maps the joints. Useful if one wants to
re-order the SMPL joints to some other convention (e.g. MSCOCO)
(default = None)
gender: str, optional
Which gender to load
vertex_ids: dict, optional
A dictionary containing the indices of the extra vertices that
will be selected
"""
self.gender = gender
if data_struct is None:
if osp.isdir(model_path):
model_fn = 'SMPL_{}.{ext}'.format(gender.upper(), ext='pkl')
smpl_path = os.path.join(model_path, model_fn)
else:
smpl_path = model_path
assert osp.exists(smpl_path), 'Path {} does not exist!'.format(
smpl_path)
with open(smpl_path, 'rb') as smpl_file:
data_struct = Struct(**pickle.load(smpl_file,
encoding='latin1'))
super(SMPL, self).__init__()
self.batch_size = batch_size
if vertex_ids is None:
# SMPL and SMPL-H share the same topology, so any extra joints can
# be drawn from the same place
vertex_ids = VERTEX_IDS['smplh']
self.dtype = dtype
self.joint_mapper = joint_mapper
self.vertex_joint_selector = VertexJointSelector(
vertex_ids=vertex_ids, **kwargs)
self.faces = data_struct.f
self.register_buffer('faces_tensor',
to_tensor(to_np(self.faces, dtype=np.int64),
dtype=torch.long))
if create_betas:
if betas is None:
default_betas = torch.zeros([batch_size, self.NUM_BETAS],
dtype=dtype)
else:
if 'torch.Tensor' in str(type(betas)):
default_betas = betas.clone().detach()
else:
default_betas = torch.tensor(betas,
dtype=dtype)
self.register_parameter('betas', nn.Parameter(default_betas,
requires_grad=True))
# The tensor that contains the global rotation of the model
# It is separated from the pose of the joints in case we wish to
# optimize only over one of them
if create_global_orient:
if global_orient is None:
default_global_orient = torch.zeros([batch_size, 3],
dtype=dtype)
else:
if 'torch.Tensor' in str(type(global_orient)):
default_global_orient = global_orient.clone().detach()
else:
default_global_orient = torch.tensor(global_orient,
dtype=dtype)
global_orient = nn.Parameter(default_global_orient,
requires_grad=True)
self.register_parameter('global_orient', global_orient)
if create_body_pose:
if body_pose is None:
default_body_pose = torch.zeros(
[batch_size, self.NUM_BODY_JOINTS * 3], dtype=dtype)
else:
if 'torch.Tensor' in str(type(body_pose)):
default_body_pose = body_pose.clone().detach()
else:
default_body_pose = torch.tensor(body_pose,
dtype=dtype)
self.register_parameter(
'body_pose',
nn.Parameter(default_body_pose, requires_grad=True))
if create_transl:
if transl is None:
default_transl = torch.zeros([batch_size, 3],
dtype=dtype,
requires_grad=True)
else:
default_transl = torch.tensor(transl, dtype=dtype)
self.register_parameter(
'transl',
nn.Parameter(default_transl, requires_grad=True))
# The vertices of the template model
self.register_buffer('v_template',
to_tensor(to_np(data_struct.v_template),
dtype=dtype))
# The shape components
shapedirs = data_struct.shapedirs
# The shape components
self.register_buffer(
'shapedirs',
to_tensor(to_np(shapedirs), dtype=dtype))
j_regressor = to_tensor(to_np(
data_struct.J_regressor), dtype=dtype)
self.register_buffer('J_regressor', j_regressor)
# Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*3 x 207
num_pose_basis = data_struct.posedirs.shape[-1]
# 207 x 20670
posedirs = np.reshape(data_struct.posedirs, [-1, num_pose_basis]).T
self.register_buffer('posedirs',
to_tensor(to_np(posedirs), dtype=dtype))
# indices of parents for each joints
parents = to_tensor(to_np(data_struct.kintree_table[0])).long()
parents[0] = -1
self.register_buffer('parents', parents)
self.register_buffer('lbs_weights',
to_tensor(to_np(data_struct.weights), dtype=dtype))
def create_mean_pose(self, data_struct):
pass
@torch.no_grad()
def reset_params(self, **params_dict):
for param_name, param in self.named_parameters():
if param_name in params_dict:
param[:] = torch.tensor(params_dict[param_name])
else:
param.fill_(0)
def get_num_verts(self):
return self.v_template.shape[0]
def get_num_faces(self):
return self.faces.shape[0]
def extra_repr(self):
return 'Number of betas: {}'.format(self.NUM_BETAS)
def forward(self, betas=None, body_pose=None, global_orient=None,
transl=None, return_verts=True, return_full_pose=False, pose2rot=True,
**kwargs):
""" Forward pass for the SMPL model
Parameters
----------
global_orient: torch.tensor, optional, shape Bx3
If given, ignore the member variable and use it as the global
rotation of the body. Useful if someone wishes to predicts this
with an external model. (default=None)
betas: torch.tensor, optional, shape Bx10
If given, ignore the member variable `betas` and use it
instead. For example, it can used if shape parameters
`betas` are predicted from some external model.
(default=None)
body_pose: torch.tensor, optional, shape Bx(J*3)
If given, ignore the member variable `body_pose` and use it
instead. For example, it can used if someone predicts the
pose of the body joints are predicted from some external model.
It should be a tensor that contains joint rotations in
axis-angle format. (default=None)
transl: torch.tensor, optional, shape Bx3
If given, ignore the member variable `transl` and use it
instead. For example, it can used if the translation
`transl` is predicted from some external model.
(default=None)
return_verts: bool, optional
Return the vertices. (default=True)
return_full_pose: bool, optional
Returns the full axis-angle pose vector (default=False)
Returns
-------
"""
# If no shape and pose parameters are passed along, then use the
# ones from the module
global_orient = (global_orient if global_orient is not None else
self.global_orient)
body_pose = body_pose if body_pose is not None else self.body_pose
betas = betas if betas is not None else self.betas
apply_trans = transl is not None or hasattr(self, 'transl')
if transl is None and hasattr(self, 'transl'):
transl = self.transl
full_pose = torch.cat([global_orient, body_pose], dim=1)
batch_size = max(betas.shape[0], global_orient.shape[0],
body_pose.shape[0])
if betas.shape[0] != batch_size:
num_repeats = int(batch_size / betas.shape[0])
betas = betas.expand(num_repeats, -1)
vertices, joints = lbs(betas, full_pose, self.v_template,
self.shapedirs, self.posedirs,
self.J_regressor, self.parents,
self.lbs_weights, pose2rot=pose2rot, dtype=self.dtype)
joints = self.vertex_joint_selector(vertices, joints)
# Map the joints to the current dataset
if self.joint_mapper is not None:
joints = self.joint_mapper(joints)
if apply_trans:
joints += transl.unsqueeze(dim=1)
vertices += transl.unsqueeze(dim=1)
output = ModelOutput(vertices=vertices if return_verts else None,
global_orient=global_orient,
body_pose=body_pose,
joints=joints,
betas=betas,
full_pose=full_pose if return_full_pose else None)
return output
class SMPLH(SMPL):
# The hand joints are replaced by MANO
NUM_BODY_JOINTS = SMPL.NUM_JOINTS - 2
NUM_HAND_JOINTS = 15
NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS
def __init__(self, model_path,
data_struct=None,
create_left_hand_pose=True,
left_hand_pose=None,
create_right_hand_pose=True,
right_hand_pose=None,
use_pca=True,
num_pca_comps=6,
flat_hand_mean=False,
batch_size=1,
gender='neutral',
dtype=torch.float32,
vertex_ids=None,
use_compressed=True,
ext='pkl',
**kwargs):
""" SMPLH model constructor
Parameters
----------
model_path: str
The path to the folder or to the file where the model
parameters are stored
data_struct: Strct
A struct object. If given, then the parameters of the model are
read from the object. Otherwise, the model tries to read the
parameters from the given `model_path`. (default = None)
create_left_hand_pose: bool, optional
Flag for creating a member variable for the pose of the left
hand. (default = True)
left_hand_pose: torch.tensor, optional, BxP
The default value for the left hand pose member variable.
(default = None)
create_right_hand_pose: bool, optional
Flag for creating a member variable for the pose of the right
hand. (default = True)
right_hand_pose: torch.tensor, optional, BxP
The default value for the right hand pose member variable.
(default = None)
num_pca_comps: int, optional
The number of PCA components to use for each hand.
(default = 6)
flat_hand_mean: bool, optional
If False, then the pose of the hand is initialized to False.
batch_size: int, optional
The batch size used for creating the member variables
gender: str, optional
Which gender to load
dtype: torch.dtype, optional
The data type for the created variables
vertex_ids: dict, optional
A dictionary containing the indices of the extra vertices that
will be selected
"""
self.num_pca_comps = num_pca_comps
# If no data structure is passed, then load the data from the given
# model folder
if data_struct is None:
# Load the model
if osp.isdir(model_path):
model_fn = 'SMPLH_{}.{ext}'.format(gender.upper(), ext=ext)
smplh_path = os.path.join(model_path, model_fn)
else:
smplh_path = model_path
assert osp.exists(smplh_path), 'Path {} does not exist!'.format(
smplh_path)
if ext == 'pkl':
with open(smplh_path, 'rb') as smplh_file:
model_data = pickle.load(smplh_file, encoding='latin1')
elif ext == 'npz':
model_data = np.load(smplh_path, allow_pickle=True)
else:
raise ValueError('Unknown extension: {}'.format(ext))
data_struct = Struct(**model_data)
if vertex_ids is None:
vertex_ids = VERTEX_IDS['smplh']
super(SMPLH, self).__init__(
model_path=model_path, data_struct=data_struct,
batch_size=batch_size, vertex_ids=vertex_ids, gender=gender,
use_compressed=use_compressed, dtype=dtype, ext=ext, **kwargs)
self.use_pca = use_pca
self.num_pca_comps = num_pca_comps
self.flat_hand_mean = flat_hand_mean
left_hand_components = data_struct.hands_componentsl[:num_pca_comps]
right_hand_components = data_struct.hands_componentsr[:num_pca_comps]
self.np_left_hand_components = left_hand_components
self.np_right_hand_components = right_hand_components
if self.use_pca:
self.register_buffer(
'left_hand_components',
torch.tensor(left_hand_components, dtype=dtype))
self.register_buffer(
'right_hand_components',
torch.tensor(right_hand_components, dtype=dtype))
if self.flat_hand_mean:
left_hand_mean = np.zeros_like(data_struct.hands_meanl)
else:
left_hand_mean = data_struct.hands_meanl
if self.flat_hand_mean:
right_hand_mean = np.zeros_like(data_struct.hands_meanr)
else:
right_hand_mean = data_struct.hands_meanr
self.register_buffer('left_hand_mean',
to_tensor(left_hand_mean, dtype=self.dtype))
self.register_buffer('right_hand_mean',
to_tensor(right_hand_mean, dtype=self.dtype))
# Create the buffers for the pose of the left hand
hand_pose_dim = num_pca_comps if use_pca else 3 * self.NUM_HAND_JOINTS
if create_left_hand_pose:
if left_hand_pose is None:
default_lhand_pose = torch.zeros([batch_size, hand_pose_dim],
dtype=dtype)
else:
default_lhand_pose = torch.tensor(left_hand_pose, dtype=dtype)
left_hand_pose_param = nn.Parameter(default_lhand_pose,
requires_grad=True)
self.register_parameter('left_hand_pose',
left_hand_pose_param)
if create_right_hand_pose:
if right_hand_pose is None:
default_rhand_pose = torch.zeros([batch_size, hand_pose_dim],
dtype=dtype)
else:
default_rhand_pose = torch.tensor(right_hand_pose, dtype=dtype)
right_hand_pose_param = nn.Parameter(default_rhand_pose,
requires_grad=True)
self.register_parameter('right_hand_pose',
right_hand_pose_param)
# Create the buffer for the mean pose.
pose_mean = self.create_mean_pose(data_struct,
flat_hand_mean=flat_hand_mean)
# pose_mean_tensor = torch.tensor(pose_mean, dtype=dtype)
pose_mean_tensor = pose_mean.type(dtype=dtype)
self.register_buffer('pose_mean', pose_mean_tensor)
def create_mean_pose(self, data_struct, flat_hand_mean=False):
# Create the array for the mean pose. If flat_hand is false, then use
# the mean that is given by the data, rather than the flat open hand
global_orient_mean = torch.zeros([3], dtype=self.dtype)
body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3],
dtype=self.dtype)
pose_mean = torch.cat([global_orient_mean, body_pose_mean,
self.left_hand_mean,
self.right_hand_mean], dim=0)
return pose_mean
def extra_repr(self):
msg = super(SMPLH, self).extra_repr()
if self.use_pca:
msg += '\nNumber of PCA components: {}'.format(self.num_pca_comps)
msg += '\nFlat hand mean: {}'.format(self.flat_hand_mean)
return msg
def forward(self, betas=None, global_orient=None, body_pose=None,
left_hand_pose=None, right_hand_pose=None, transl=None,
return_verts=True, return_full_pose=False, pose2rot=True,
**kwargs):
"""
Args:
betas:
global_orient:
body_pose:
left_hand_pose:
right_hand_pose:
transl:
return_verts:
return_full_pose:
pose2rot:
**kwargs:
Returns:
"""
# If no shape and pose parameters are passed along, then use the
# ones from the module
global_orient = (global_orient if global_orient is not None else
self.global_orient)
body_pose = body_pose if body_pose is not None else self.body_pose
betas = betas if betas is not None else self.betas
left_hand_pose = (left_hand_pose if left_hand_pose is not None else
self.left_hand_pose)
right_hand_pose = (right_hand_pose if right_hand_pose is not None else
self.right_hand_pose)
apply_trans = transl is not None or hasattr(self, 'transl')
if transl is None:
if hasattr(self, 'transl'):
transl = self.transl
if self.use_pca:
left_hand_pose = torch.einsum(
'bi,ij->bj', [left_hand_pose, self.left_hand_components])
right_hand_pose = torch.einsum(
'bi,ij->bj', [right_hand_pose, self.right_hand_components])
full_pose = torch.cat([global_orient, body_pose,
left_hand_pose,
right_hand_pose], dim=1)
full_pose += self.pose_mean
vertices, joints = lbs(self.betas, full_pose, self.v_template,
self.shapedirs, self.posedirs,
self.J_regressor, self.parents,
self.lbs_weights, pose2rot=pose2rot,
dtype=self.dtype)
# Add any extra joints that might be needed, (batch_size, 52 + 5 + 6 + 10 = 73, 3)
joints = self.vertex_joint_selector(vertices, joints)
if self.joint_mapper is not None:
joints = self.joint_mapper(joints)
if apply_trans:
joints += transl.unsqueeze(dim=1)
vertices += transl.unsqueeze(dim=1)
output = ModelOutput(vertices=vertices if return_verts else None,
joints=joints,
betas=betas,
global_orient=global_orient,
body_pose=body_pose,
left_hand_pose=left_hand_pose,
right_hand_pose=right_hand_pose,
full_pose=full_pose if return_full_pose else None)
return output
class SMPLX(SMPLH):
"""
SMPL-X (SMPL eXpressive) is a unified body model, with shape parameters
trained jointly for the face, hands and body.
SMPL-X uses standard vertex based linear blend skinning with learned
corrective blend shapes, has N=10475 vertices and K=54 joints,
which includes joints for the neck, jaw, eyeballs and fingers.
"""
NUM_BODY_JOINTS = SMPLH.NUM_BODY_JOINTS
NUM_HAND_JOINTS = 15
NUM_FACE_JOINTS = 3
NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS + NUM_FACE_JOINTS
NUM_EXPR_COEFFS = 10
NECK_IDX = 12
def __init__(self, model_path,
create_expression=True, expression=None,
create_jaw_pose=True, jaw_pose=None,
create_leye_pose=True, leye_pose=None,
create_reye_pose=True, reye_pose=None,
use_face_contour=False,
batch_size=1, gender='neutral',
dtype=torch.float32,
ext='npz',
**kwargs):
''' SMPLX model constructor
Parameters
----------
model_path: str
The path to the folder or to the file where the model
parameters are stored
create_expression: bool, optional
Flag for creating a member variable for the expression space
(default = True).
expression: torch.tensor, optional, Bx10
The default value for the expression member variable.
(default = None)
create_jaw_pose: bool, optional
Flag for creating a member variable for the jaw pose.
(default = False)
jaw_pose: torch.tensor, optional, Bx3
The default value for the jaw pose variable.
(default = None)
create_leye_pose: bool, optional
Flag for creating a member variable for the left eye pose.
(default = False)
leye_pose: torch.tensor, optional, Bx10
The default value for the left eye pose variable.
(default = None)
create_reye_pose: bool, optional
Flag for creating a member variable for the right eye pose.
(default = False)
reye_pose: torch.tensor, optional, Bx10
The default value for the right eye pose variable.
(default = None)
use_face_contour: bool, optional
Whether to compute the keypoints that form the facial contour
batch_size: int, optional
The batch size used for creating the member variables
gender: str, optional
Which gender to load
dtype: torch.dtype
The data type for the created variables
'''
# Load the model
if osp.isdir(model_path):
model_fn = 'SMPLX_{}.{ext}'.format(gender.upper(), ext=ext)
smplx_path = os.path.join(model_path, model_fn)
else:
smplx_path = model_path
assert osp.exists(smplx_path), 'Path {} does not exist!'.format(
smplx_path)
if ext == 'pkl':
with open(smplx_path, 'rb') as smplx_file:
model_data = pickle.load(smplx_file, encoding='latin1')
elif ext == 'npz':
model_data = np.load(smplx_path, allow_pickle=True)
else:
raise ValueError('Unknown extension: {}'.format(ext))
data_struct = Struct(**model_data)
super(SMPLX, self).__init__(
model_path=model_path,
data_struct=data_struct,
dtype=dtype,
batch_size=batch_size,
vertex_ids=VERTEX_IDS['smplx'],
gender=gender, ext=ext,
**kwargs)
lmk_faces_idx = data_struct.lmk_faces_idx
self.register_buffer('lmk_faces_idx',
torch.tensor(lmk_faces_idx, dtype=torch.long))
lmk_bary_coords = data_struct.lmk_bary_coords
self.register_buffer('lmk_bary_coords',
torch.tensor(lmk_bary_coords, dtype=dtype))
self.use_face_contour = use_face_contour
if self.use_face_contour:
dynamic_lmk_faces_idx = data_struct.dynamic_lmk_faces_idx
dynamic_lmk_faces_idx = torch.tensor(
dynamic_lmk_faces_idx,
dtype=torch.long)
self.register_buffer('dynamic_lmk_faces_idx',
dynamic_lmk_faces_idx)
dynamic_lmk_bary_coords = data_struct.dynamic_lmk_bary_coords
dynamic_lmk_bary_coords = torch.tensor(
dynamic_lmk_bary_coords, dtype=dtype)
self.register_buffer('dynamic_lmk_bary_coords',
dynamic_lmk_bary_coords)
neck_kin_chain = []
curr_idx = torch.tensor(self.NECK_IDX, dtype=torch.long)
while curr_idx != -1:
neck_kin_chain.append(curr_idx)
curr_idx = self.parents[curr_idx]
self.register_buffer('neck_kin_chain',
torch.stack(neck_kin_chain))
if create_jaw_pose:
if jaw_pose is None:
default_jaw_pose = torch.zeros([batch_size, 3], dtype=dtype)
else:
default_jaw_pose = torch.tensor(jaw_pose, dtype=dtype)
jaw_pose_param = nn.Parameter(default_jaw_pose,
requires_grad=True)
self.register_parameter('jaw_pose', jaw_pose_param)
if create_leye_pose:
if leye_pose is None:
default_leye_pose = torch.zeros([batch_size, 3], dtype=dtype)
else:
default_leye_pose = torch.tensor(leye_pose, dtype=dtype)
leye_pose_param = nn.Parameter(default_leye_pose,
requires_grad=True)
self.register_parameter('leye_pose', leye_pose_param)
if create_reye_pose:
if reye_pose is None:
default_reye_pose = torch.zeros([batch_size, 3], dtype=dtype)
else:
default_reye_pose = torch.tensor(reye_pose, dtype=dtype)
reye_pose_param = nn.Parameter(default_reye_pose,
requires_grad=True)
self.register_parameter('reye_pose', reye_pose_param)
if create_expression:
if expression is None:
default_expression = torch.zeros(
[batch_size, self.NUM_EXPR_COEFFS], dtype=dtype)
else:
default_expression = torch.tensor(expression, dtype=dtype)
expression_param = nn.Parameter(default_expression,
requires_grad=True)
self.register_parameter('expression', expression_param)
def create_mean_pose(self, data_struct, flat_hand_mean=False):
# Create the array for the mean pose. If flat_hand is false, then use
# the mean that is given by the data, rather than the flat open hand
global_orient_mean = torch.zeros([3], dtype=self.dtype)
body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3],
dtype=self.dtype)
jaw_pose_mean = torch.zeros([3], dtype=self.dtype)
leye_pose_mean = torch.zeros([3], dtype=self.dtype)
reye_pose_mean = torch.zeros([3], dtype=self.dtype)
pose_mean = np.concatenate([global_orient_mean, body_pose_mean,
jaw_pose_mean,
leye_pose_mean, reye_pose_mean,
self.left_hand_mean, self.right_hand_mean],
axis=0)
return pose_mean
def extra_repr(self):
msg = super(SMPLX, self).extra_repr()
msg += '\nGender: {}'.format(self.gender.title())
msg += '\nExpression Coefficients: {}'.format(
self.NUM_EXPR_COEFFS)
msg += '\nUse face contour: {}'.format(self.use_face_contour)
return msg
def forward(self, betas=None, global_orient=None, body_pose=None,
left_hand_pose=None, right_hand_pose=None, transl=None,
expression=None, jaw_pose=None, leye_pose=None, reye_pose=None,
return_verts=True, return_full_pose=False, pose2rot=True, **kwargs):
'''
Forward pass for the SMPLX model
Parameters
----------
global_orient: torch.tensor, optional, shape Bx3
If given, ignore the member variable and use it as the global
rotation of the body. Useful if someone wishes to predicts this
with an external model. (default=None)
betas: torch.tensor, optional, shape Bx10
If given, ignore the member variable `betas` and use it
instead. For example, it can used if shape parameters
`betas` are predicted from some external model.
(default=None)
expression: torch.tensor, optional, shape Bx10
If given, ignore the member variable `expression` and use it
instead. For example, it can used if expression parameters
`expression` are predicted from some external model.
body_pose: torch.tensor, optional, shape Bx(J*3)
If given, ignore the member variable `body_pose` and use it
instead. For example, it can used if someone predicts the
pose of the body joints are predicted from some external model.
It should be a tensor that contains joint rotations in
axis-angle format. (default=None)
left_hand_pose: torch.tensor, optional, shape BxP
If given, ignore the member variable `left_hand_pose` and
use this instead. It should either contain PCA coefficients or
joint rotations in axis-angle format.
right_hand_pose: torch.tensor, optional, shape BxP
If given, ignore the member variable `right_hand_pose` and
use this instead. It should either contain PCA coefficients or
joint rotations in axis-angle format.
jaw_pose: torch.tensor, optional, shape Bx3
If given, ignore the member variable `jaw_pose` and
use this instead. It should either joint rotations in
axis-angle format.
transl: torch.tensor, optional, shape Bx3
If given, ignore the member variable `transl` and use it
instead. For example, it can used if the translation
`transl` is predicted from some external model.
(default=None)
return_verts: bool, optional
Return the vertices. (default=True)
return_full_pose: bool, optional
Returns the full axis-angle pose vector (default=False)
Returns
-------
output: ModelOutput
A named tuple of type `ModelOutput`
'''
# If no shape and pose parameters are passed along, then use the
# ones from the module
global_orient = (global_orient if global_orient is not None else
self.global_orient)
body_pose = body_pose if body_pose is not None else self.body_pose
betas = betas if betas is not None else self.betas
left_hand_pose = (left_hand_pose if left_hand_pose is not None else
self.left_hand_pose)
right_hand_pose = (right_hand_pose if right_hand_pose is not None else
self.right_hand_pose)
jaw_pose = jaw_pose if jaw_pose is not None else self.jaw_pose
leye_pose = leye_pose if leye_pose is not None else self.leye_pose
reye_pose = reye_pose if reye_pose is not None else self.reye_pose
expression = expression if expression is not None else self.expression
apply_trans = transl is not None or hasattr(self, 'transl')
if transl is None:
if hasattr(self, 'transl'):
transl = self.transl
if self.use_pca:
left_hand_pose = torch.einsum(
'bi,ij->bj', [left_hand_pose, self.left_hand_components])
right_hand_pose = torch.einsum(
'bi,ij->bj', [right_hand_pose, self.right_hand_components])
full_pose = torch.cat([global_orient, body_pose,
jaw_pose, leye_pose, reye_pose,
left_hand_pose,
right_hand_pose], dim=1)
# Add the mean pose of the model. Does not affect the body, only the
# hands when flat_hand_mean == False
full_pose += self.pose_mean
batch_size = max(betas.shape[0], global_orient.shape[0],
body_pose.shape[0])
# Concatenate the shape and expression coefficients
scale = int(batch_size / betas.shape[0])
if scale > 1:
betas = betas.expand(scale, -1)
shape_components = torch.cat([betas, expression], dim=-1)
vertices, joints = lbs(shape_components, full_pose, self.v_template,
self.shapedirs, self.posedirs,
self.J_regressor, self.parents,
self.lbs_weights, pose2rot=pose2rot,
dtype=self.dtype)
lmk_faces_idx = self.lmk_faces_idx.unsqueeze(
dim=0).expand(batch_size, -1).contiguous()
lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat(
self.batch_size, 1, 1)
if self.use_face_contour:
dyn_lmk_faces_idx, dyn_lmk_bary_coords = find_dynamic_lmk_idx_and_bcoords(
vertices, full_pose, self.dynamic_lmk_faces_idx,
self.dynamic_lmk_bary_coords,
self.neck_kin_chain, dtype=self.dtype)
lmk_faces_idx = torch.cat([lmk_faces_idx,
dyn_lmk_faces_idx], 1)
lmk_bary_coords = torch.cat(
[lmk_bary_coords.expand(batch_size, -1, -1),
dyn_lmk_bary_coords], 1)
landmarks = vertices2landmarks(vertices, self.faces_tensor,
lmk_faces_idx,
lmk_bary_coords)
# Add any extra joints that might be needed
joints = self.vertex_joint_selector(vertices, joints)
# Add the landmarks to the joints
joints = torch.cat([joints, landmarks], dim=1)
# Map the joints to the current dataset
if self.joint_mapper is not None:
joints = self.joint_mapper(joints=joints, vertices=vertices)
if apply_trans:
joints += transl.unsqueeze(dim=1)
vertices += transl.unsqueeze(dim=1)
output = ModelOutput(vertices=vertices if return_verts else None,
joints=joints,
betas=betas,
expression=expression,
global_orient=global_orient,
body_pose=body_pose,
left_hand_pose=left_hand_pose,
right_hand_pose=right_hand_pose,
jaw_pose=jaw_pose,
full_pose=full_pose if return_full_pose else None)
return output
| 21,303 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.