prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># Borrowed and modified from xbmcswift
import logging
import xbmc
from pulsar.addon import ADDON_ID
class XBMCHandler(logging.StreamHandler):
xbmc_levels = {
'DEBUG': 0,
'INFO': 2,
'WARNING': 3,
'ERROR': 4,
'LOGCRITICAL': 5,
}
def emit(self, record):
xbmc_level = self.xbmc_levels.get(record.levelname)
xbmc.log(self.format(record), xbmc_level)
<|fim▁hole|> handler = XBMCHandler()
handler.setFormatter(logging.Formatter('[%(name)s] %(message)s'))
logger.addHandler(handler)
return logger
log = _get_logger()<|fim▁end|> | def _get_logger():
logger = logging.getLogger(ADDON_ID)
logger.setLevel(logging.DEBUG) |
<|file_name|>type_api.py<|end_file_name|><|fim▁begin|># sql/types_api.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Base types API.
"""
from .. import exc, util
from . import operators
from .visitors import Visitable, VisitableType
from .base import SchemaEventTarget
# these are back-assigned by sqltypes.
BOOLEANTYPE = None
INTEGERTYPE = None
NULLTYPE = None
STRINGTYPE = None
MATCHTYPE = None
INDEXABLE = None
_resolve_value_to_type = None
class TypeEngine(Visitable):
"""The ultimate base class for all SQL datatypes.
Common subclasses of :class:`.TypeEngine` include
:class:`.String`, :class:`.Integer`, and :class:`.Boolean`.
For an overview of the SQLAlchemy typing system, see
:ref:`types_toplevel`.
.. seealso::
:ref:`types_toplevel`
"""
_sqla_type = True
_isnull = False
class Comparator(operators.ColumnOperators):
"""Base class for custom comparison operations defined at the
type level. See :attr:`.TypeEngine.comparator_factory`.
"""
__slots__ = 'expr', 'type'
default_comparator = None
def __init__(self, expr):
self.expr = expr
self.type = expr.type
@util.dependencies('sqlalchemy.sql.default_comparator')
def operate(self, default_comparator, op, *other, **kwargs):
o = default_comparator.operator_lookup[op.__name__]
return o[0](self.expr, op, *(other + o[1:]), **kwargs)
@util.dependencies('sqlalchemy.sql.default_comparator')
def reverse_operate(self, default_comparator, op, other, **kwargs):
o = default_comparator.operator_lookup[op.__name__]
return o[0](self.expr, op, other,
reverse=True, *o[1:], **kwargs)
def _adapt_expression(self, op, other_comparator):
"""evaluate the return type of <self> <op> <othertype>,
and apply any adaptations to the given operator.
This method determines the type of a resulting binary expression
given two source types and an operator. For example, two
:class:`.Column` objects, both of the type :class:`.Integer`, will
produce a :class:`.BinaryExpression` that also has the type
:class:`.Integer` when compared via the addition (``+``) operator.
However, using the addition operator with an :class:`.Integer`
and a :class:`.Date` object will produce a :class:`.Date`, assuming
"days delta" behavior by the database (in reality, most databases
other than PostgreSQL don't accept this particular operation).
The method returns a tuple of the form <operator>, <type>.
The resulting operator and type will be those applied to the
resulting :class:`.BinaryExpression` as the final operator and the
right-hand side of the expression.
Note that only a subset of operators make usage of
:meth:`._adapt_expression`,
including math operators and user-defined operators, but not
boolean comparison or special SQL keywords like MATCH or BETWEEN.
"""
return op, self.type
def __reduce__(self):
return _reconstitute_comparator, (self.expr, )
hashable = True
"""Flag, if False, means values from this type aren't hashable.
Used by the ORM when uniquing result lists.
"""
comparator_factory = Comparator
"""A :class:`.TypeEngine.Comparator` class which will apply
to operations performed by owning :class:`.ColumnElement` objects.
The :attr:`.comparator_factory` attribute is a hook consulted by
the core expression system when column and SQL expression operations
are performed. When a :class:`.TypeEngine.Comparator` class is
associated with this attribute, it allows custom re-definition of
all existing operators, as well as definition of new operators.
Existing operators include those provided by Python operator overloading
such as :meth:`.operators.ColumnOperators.__add__` and
:meth:`.operators.ColumnOperators.__eq__`,
those provided as standard
attributes of :class:`.operators.ColumnOperators` such as
:meth:`.operators.ColumnOperators.like`
and :meth:`.operators.ColumnOperators.in_`.
Rudimentary usage of this hook is allowed through simple subclassing
of existing types, or alternatively by using :class:`.TypeDecorator`.
See the documentation section :ref:`types_operators` for examples.
.. versionadded:: 0.8 The expression system was enhanced to support
customization of operators on a per-type level.
"""
should_evaluate_none = False
"""If True, the Python constant ``None`` is considered to be handled
explicitly by this type.
The ORM uses this flag to indicate that a positive value of ``None``
is passed to the column in an INSERT statement, rather than omitting
the column from the INSERT statement which has the effect of firing
off column-level defaults. It also allows types which have special
behavior for Python None, such as a JSON type, to indicate that
they'd like to handle the None value explicitly.
To set this flag on an existing type, use the
:meth:`.TypeEngine.evaluates_none` method.
.. seealso::
:meth:`.TypeEngine.evaluates_none`
.. versionadded:: 1.1
"""
def evaluates_none(self):
"""Return a copy of this type which has the :attr:`.should_evaluate_none`
flag set to True.
E.g.::
Table(
'some_table', metadata,
Column(
String(50).evaluates_none(),
nullable=True,
server_default='no value')
)
The ORM uses this flag to indicate that a positive value of ``None``
is passed to the column in an INSERT statement, rather than omitting
the column from the INSERT statement which has the effect of firing
off column-level defaults. It also allows for types which have
special behavior associated with the Python None value to indicate
that the value doesn't necessarily translate into SQL NULL; a
prime example of this is a JSON type which may wish to persist the
JSON value ``'null'``.
In all cases, the actual NULL SQL value can be always be
persisted in any column by using
the :obj:`~.expression.null` SQL construct in an INSERT statement
or associated with an ORM-mapped attribute.
.. note::
The "evaulates none" flag does **not** apply to a value
of ``None`` passed to :paramref:`.Column.default` or
:paramref:`.Column.server_default`; in these cases, ``None``
still means "no default".
.. versionadded:: 1.1
.. seealso::
:ref:`session_forcing_null` - in the ORM documentation
:paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON
interaction with this flag.
:attr:`.TypeEngine.should_evaluate_none` - class-level flag
"""
typ = self.copy()
typ.should_evaluate_none = True
return typ
def copy(self, **kw):
return self.adapt(self.__class__)
def compare_against_backend(self, dialect, conn_type):
"""Compare this type against the given backend type.
This function is currently not implemented for SQLAlchemy
types, and for all built in types will return ``None``. However,
it can be implemented by a user-defined type
where it can be consumed by schema comparison tools such as
Alembic autogenerate.
A future release of SQLAlchemy will potentially impement this method
for builtin types as well.
The function should return True if this type is equivalent to the
given type; the type is typically reflected from the database
so should be database specific. The dialect in use is also
passed. It can also return False to assert that the type is
not equivalent.
:param dialect: a :class:`.Dialect` that is involved in the comparison.
:param conn_type: the type object reflected from the backend.
.. versionadded:: 1.0.3
"""
return None
def copy_value(self, value):
return value
def literal_processor(self, dialect):
"""Return a conversion function for processing literal values that are
to be rendered directly without using binds.
This function is used when the compiler makes use of the
"literal_binds" flag, typically used in DDL generation as well
as in certain scenarios where backends don't accept bound parameters.
.. versionadded:: 0.9.0
"""
return None
def bind_processor(self, dialect):
"""Return a conversion function for processing bind values.
Returns a callable which will receive a bind parameter value
as the sole positional argument and will return a value to
send to the DB-API.
If processing is not necessary, the method should return ``None``.
:param dialect: Dialect instance in use.
"""
return None
def result_processor(self, dialect, coltype):
"""Return a conversion function for processing result row values.
Returns a callable which will receive a result row column
value as the sole positional argument and will return a value
to return to the user.
If processing is not necessary, the method should return ``None``.
:param dialect: Dialect instance in use.
:param coltype: DBAPI coltype argument received in cursor.description.
"""
return None
def column_expression(self, colexpr):
"""Given a SELECT column expression, return a wrapping SQL expression.
This is typically a SQL function that wraps a column expression
as rendered in the columns clause of a SELECT statement.
It is used for special data types that require
columns to be wrapped in some special database function in order
to coerce the value before being sent back to the application.
It is the SQL analogue of the :meth:`.TypeEngine.result_processor`
method.
The method is evaluated at statement compile time, as opposed
to statement construction time.
See also:
:ref:`types_sql_value_processing`
"""
return None
@util.memoized_property
def _has_column_expression(self):
"""memoized boolean, check if column_expression is implemented.
Allows the method to be skipped for the vast majority of expression
types that don't use this feature.
"""
return self.__class__.column_expression.__code__ \
is not TypeEngine.column_expression.__code__
def bind_expression(self, bindvalue):
""""Given a bind value (i.e. a :class:`.BindParameter` instance),
return a SQL expression in its place.
This is typically a SQL function that wraps the existing bound
parameter within the statement. It is used for special data types
that require literals being wrapped in some special database function
in order to coerce an application-level value into a database-specific
format. It is the SQL analogue of the
:meth:`.TypeEngine.bind_processor` method.
The method is evaluated at statement compile time, as opposed
to statement construction time.
Note that this method, when implemented, should always return
the exact same structure, without any conditional logic, as it
may be used in an executemany() call against an arbitrary number
of bound parameter sets.
See also:
:ref:`types_sql_value_processing`
"""
return None
@util.memoized_property
def _has_bind_expression(self):
"""memoized boolean, check if bind_expression is implemented.
Allows the method to be skipped for the vast majority of expression
types that don't use this feature.
"""
return self.__class__.bind_expression.__code__ \
is not TypeEngine.bind_expression.__code__
def compare_values(self, x, y):
"""Compare two values for equality."""<|fim▁hole|> def get_dbapi_type(self, dbapi):
"""Return the corresponding type object from the underlying DB-API, if
any.
This can be useful for calling ``setinputsizes()``, for example.
"""
return None
@property
def python_type(self):
"""Return the Python type object expected to be returned
by instances of this type, if known.
Basically, for those types which enforce a return type,
or are known across the board to do such for all common
DBAPIs (like ``int`` for example), will return that type.
If a return type is not defined, raises
``NotImplementedError``.
Note that any type also accommodates NULL in SQL which
means you can also get back ``None`` from any type
in practice.
"""
raise NotImplementedError()
def with_variant(self, type_, dialect_name):
"""Produce a new type object that will utilize the given
type when applied to the dialect of the given name.
e.g.::
from sqlalchemy.types import String
from sqlalchemy.dialects import mysql
s = String()
s = s.with_variant(mysql.VARCHAR(collation='foo'), 'mysql')
The construction of :meth:`.TypeEngine.with_variant` is always
from the "fallback" type to that which is dialect specific.
The returned type is an instance of :class:`.Variant`, which
itself provides a :meth:`.Variant.with_variant`
that can be called repeatedly.
:param type_: a :class:`.TypeEngine` that will be selected
as a variant from the originating type, when a dialect
of the given name is in use.
:param dialect_name: base name of the dialect which uses
this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
.. versionadded:: 0.7.2
"""
return Variant(self, {dialect_name: to_instance(type_)})
@util.memoized_property
def _type_affinity(self):
"""Return a rudimental 'affinity' value expressing the general class
of type."""
typ = None
for t in self.__class__.__mro__:
if t in (TypeEngine, UserDefinedType):
return typ
elif issubclass(t, (TypeEngine, UserDefinedType)):
typ = t
else:
return self.__class__
def dialect_impl(self, dialect):
"""Return a dialect-specific implementation for this
:class:`.TypeEngine`.
"""
try:
return dialect._type_memos[self]['impl']
except KeyError:
return self._dialect_info(dialect)['impl']
def _cached_literal_processor(self, dialect):
"""Return a dialect-specific literal processor for this type."""
try:
return dialect._type_memos[self]['literal']
except KeyError:
d = self._dialect_info(dialect)
d['literal'] = lp = d['impl'].literal_processor(dialect)
return lp
def _cached_bind_processor(self, dialect):
"""Return a dialect-specific bind processor for this type."""
try:
return dialect._type_memos[self]['bind']
except KeyError:
d = self._dialect_info(dialect)
d['bind'] = bp = d['impl'].bind_processor(dialect)
return bp
def _cached_result_processor(self, dialect, coltype):
"""Return a dialect-specific result processor for this type."""
try:
return dialect._type_memos[self][coltype]
except KeyError:
d = self._dialect_info(dialect)
# key assumption: DBAPI type codes are
# constants. Else this dictionary would
# grow unbounded.
d[coltype] = rp = d['impl'].result_processor(dialect, coltype)
return rp
def _dialect_info(self, dialect):
"""Return a dialect-specific registry which
caches a dialect-specific implementation, bind processing
function, and one or more result processing functions."""
if self in dialect._type_memos:
return dialect._type_memos[self]
else:
impl = self._gen_dialect_impl(dialect)
if impl is self:
impl = self.adapt(type(self))
# this can't be self, else we create a cycle
assert impl is not self
dialect._type_memos[self] = d = {'impl': impl}
return d
def _gen_dialect_impl(self, dialect):
return dialect.type_descriptor(self)
def adapt(self, cls, **kw):
"""Produce an "adapted" form of this type, given an "impl" class
to work with.
This method is used internally to associate generic
types with "implementation" types that are specific to a particular
dialect.
"""
return util.constructor_copy(self, cls, **kw)
def coerce_compared_value(self, op, value):
"""Suggest a type for a 'coerced' Python value in an expression.
Given an operator and value, gives the type a chance
to return a type which the value should be coerced into.
The default behavior here is conservative; if the right-hand
side is already coerced into a SQL type based on its
Python type, it is usually left alone.
End-user functionality extension here should generally be via
:class:`.TypeDecorator`, which provides more liberal behavior in that
it defaults to coercing the other side of the expression into this
type, thus applying special Python conversions above and beyond those
needed by the DBAPI to both ides. It also provides the public method
:meth:`.TypeDecorator.coerce_compared_value` which is intended for
end-user customization of this behavior.
"""
_coerced_type = _resolve_value_to_type(value)
if _coerced_type is NULLTYPE or _coerced_type._type_affinity \
is self._type_affinity:
return self
else:
return _coerced_type
def _compare_type_affinity(self, other):
return self._type_affinity is other._type_affinity
def compile(self, dialect=None):
"""Produce a string-compiled form of this :class:`.TypeEngine`.
When called with no arguments, uses a "default" dialect
to produce a string result.
:param dialect: a :class:`.Dialect` instance.
"""
# arg, return value is inconsistent with
# ClauseElement.compile()....this is a mistake.
if not dialect:
dialect = self._default_dialect()
return dialect.type_compiler.process(self)
@util.dependencies("sqlalchemy.engine.default")
def _default_dialect(self, default):
if self.__class__.__module__.startswith("sqlalchemy.dialects"):
tokens = self.__class__.__module__.split(".")[0:3]
mod = ".".join(tokens)
return getattr(__import__(mod).dialects, tokens[-1]).dialect()
else:
return default.DefaultDialect()
def __str__(self):
if util.py2k:
return unicode(self.compile()).\
encode('ascii', 'backslashreplace')
else:
return str(self.compile())
def __repr__(self):
return util.generic_repr(self)
class VisitableCheckKWArg(util.EnsureKWArgType, VisitableType):
pass
class UserDefinedType(util.with_metaclass(VisitableCheckKWArg, TypeEngine)):
"""Base for user defined types.
This should be the base of new types. Note that
for most cases, :class:`.TypeDecorator` is probably
more appropriate::
import sqlalchemy.types as types
class MyType(types.UserDefinedType):
def __init__(self, precision = 8):
self.precision = precision
def get_col_spec(self, **kw):
return "MYTYPE(%s)" % self.precision
def bind_processor(self, dialect):
def process(value):
return value
return process
def result_processor(self, dialect, coltype):
def process(value):
return value
return process
Once the type is made, it's immediately usable::
table = Table('foo', meta,
Column('id', Integer, primary_key=True),
Column('data', MyType(16))
)
The ``get_col_spec()`` method will in most cases receive a keyword
argument ``type_expression`` which refers to the owning expression
of the type as being compiled, such as a :class:`.Column` or
:func:`.cast` construct. This keyword is only sent if the method
accepts keyword arguments (e.g. ``**kw``) in its argument signature;
introspection is used to check for this in order to support legacy
forms of this function.
.. versionadded:: 1.0.0 the owning expression is passed to
the ``get_col_spec()`` method via the keyword argument
``type_expression``, if it receives ``**kw`` in its signature.
"""
__visit_name__ = "user_defined"
ensure_kwarg = 'get_col_spec'
class Comparator(TypeEngine.Comparator):
__slots__ = ()
def _adapt_expression(self, op, other_comparator):
if hasattr(self.type, 'adapt_operator'):
util.warn_deprecated(
"UserDefinedType.adapt_operator is deprecated. Create "
"a UserDefinedType.Comparator subclass instead which "
"generates the desired expression constructs, given a "
"particular operator."
)
return self.type.adapt_operator(op), self.type
else:
return op, self.type
comparator_factory = Comparator
def coerce_compared_value(self, op, value):
"""Suggest a type for a 'coerced' Python value in an expression.
Default behavior for :class:`.UserDefinedType` is the
same as that of :class:`.TypeDecorator`; by default it returns
``self``, assuming the compared value should be coerced into
the same type as this one. See
:meth:`.TypeDecorator.coerce_compared_value` for more detail.
.. versionchanged:: 0.8 :meth:`.UserDefinedType.coerce_compared_value`
now returns ``self`` by default, rather than falling onto the
more fundamental behavior of
:meth:`.TypeEngine.coerce_compared_value`.
"""
return self
class TypeDecorator(SchemaEventTarget, TypeEngine):
"""Allows the creation of types which add additional functionality
to an existing type.
This method is preferred to direct subclassing of SQLAlchemy's
built-in types as it ensures that all required functionality of
the underlying type is kept in place.
Typical usage::
import sqlalchemy.types as types
class MyType(types.TypeDecorator):
'''Prefixes Unicode values with "PREFIX:" on the way in and
strips it off on the way out.
'''
impl = types.Unicode
def process_bind_param(self, value, dialect):
return "PREFIX:" + value
def process_result_value(self, value, dialect):
return value[7:]
def copy(self, **kw):
return MyType(self.impl.length)
The class-level "impl" attribute is required, and can reference any
TypeEngine class. Alternatively, the load_dialect_impl() method
can be used to provide different type classes based on the dialect
given; in this case, the "impl" variable can reference
``TypeEngine`` as a placeholder.
Types that receive a Python type that isn't similar to the ultimate type
used may want to define the :meth:`TypeDecorator.coerce_compared_value`
method. This is used to give the expression system a hint when coercing
Python objects into bind parameters within expressions. Consider this
expression::
mytable.c.somecol + datetime.date(2009, 5, 15)
Above, if "somecol" is an ``Integer`` variant, it makes sense that
we're doing date arithmetic, where above is usually interpreted
by databases as adding a number of days to the given date.
The expression system does the right thing by not attempting to
coerce the "date()" value into an integer-oriented bind parameter.
However, in the case of ``TypeDecorator``, we are usually changing an
incoming Python type to something new - ``TypeDecorator`` by default will
"coerce" the non-typed side to be the same type as itself. Such as below,
we define an "epoch" type that stores a date value as an integer::
class MyEpochType(types.TypeDecorator):
impl = types.Integer
epoch = datetime.date(1970, 1, 1)
def process_bind_param(self, value, dialect):
return (value - self.epoch).days
def process_result_value(self, value, dialect):
return self.epoch + timedelta(days=value)
Our expression of ``somecol + date`` with the above type will coerce the
"date" on the right side to also be treated as ``MyEpochType``.
This behavior can be overridden via the
:meth:`~TypeDecorator.coerce_compared_value` method, which returns a type
that should be used for the value of the expression. Below we set it such
that an integer value will be treated as an ``Integer``, and any other
value is assumed to be a date and will be treated as a ``MyEpochType``::
def coerce_compared_value(self, op, value):
if isinstance(value, int):
return Integer()
else:
return self
.. warning::
Note that the **behavior of coerce_compared_value is not inherited
by default from that of the base type**.
If the :class:`.TypeDecorator` is augmenting a
type that requires special logic for certain types of operators,
this method **must** be overridden. A key example is when decorating
the :class:`.postgresql.JSON` and :class:`.postgresql.JSONB` types;
the default rules of :meth:`.TypeEngine.coerce_compared_value` should
be used in order to deal with operators like index operations::
class MyJsonType(TypeDecorator):
impl = postgresql.JSON
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
Without the above step, index operations such as ``mycol['foo']``
will cause the index value ``'foo'`` to be JSON encoded.
"""
__visit_name__ = "type_decorator"
def __init__(self, *args, **kwargs):
"""Construct a :class:`.TypeDecorator`.
Arguments sent here are passed to the constructor
of the class assigned to the ``impl`` class level attribute,
assuming the ``impl`` is a callable, and the resulting
object is assigned to the ``self.impl`` instance attribute
(thus overriding the class attribute of the same name).
If the class level ``impl`` is not a callable (the unusual case),
it will be assigned to the same instance attribute 'as-is',
ignoring those arguments passed to the constructor.
Subclasses can override this to customize the generation
of ``self.impl`` entirely.
"""
if not hasattr(self.__class__, 'impl'):
raise AssertionError("TypeDecorator implementations "
"require a class-level variable "
"'impl' which refers to the class of "
"type being decorated")
self.impl = to_instance(self.__class__.impl, *args, **kwargs)
coerce_to_is_types = (util.NoneType, )
"""Specify those Python types which should be coerced at the expression
level to "IS <constant>" when compared using ``==`` (and same for
``IS NOT`` in conjunction with ``!=``.
For most SQLAlchemy types, this includes ``NoneType``, as well as
``bool``.
:class:`.TypeDecorator` modifies this list to only include ``NoneType``,
as typedecorator implementations that deal with boolean types are common.
Custom :class:`.TypeDecorator` classes can override this attribute to
return an empty tuple, in which case no values will be coerced to
constants.
.. versionadded:: 0.8.2
Added :attr:`.TypeDecorator.coerce_to_is_types` to allow for easier
control of ``__eq__()`` ``__ne__()`` operations.
"""
class Comparator(TypeEngine.Comparator):
__slots__ = ()
def operate(self, op, *other, **kwargs):
kwargs['_python_is_types'] = self.expr.type.coerce_to_is_types
return super(TypeDecorator.Comparator, self).operate(
op, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs):
kwargs['_python_is_types'] = self.expr.type.coerce_to_is_types
return super(TypeDecorator.Comparator, self).reverse_operate(
op, other, **kwargs)
@property
def comparator_factory(self):
if TypeDecorator.Comparator in self.impl.comparator_factory.__mro__:
return self.impl.comparator_factory
else:
return type("TDComparator",
(TypeDecorator.Comparator,
self.impl.comparator_factory),
{})
def _gen_dialect_impl(self, dialect):
"""
#todo
"""
adapted = dialect.type_descriptor(self)
if adapted is not self:
return adapted
# otherwise adapt the impl type, link
# to a copy of this TypeDecorator and return
# that.
typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect)
tt = self.copy()
if not isinstance(tt, self.__class__):
raise AssertionError('Type object %s does not properly '
'implement the copy() method, it must '
'return an object of type %s' %
(self, self.__class__))
tt.impl = typedesc
return tt
@property
def _type_affinity(self):
"""
#todo
"""
return self.impl._type_affinity
def _set_parent(self, column):
"""Support SchemaEentTarget"""
super(TypeDecorator, self)._set_parent(column)
if isinstance(self.impl, SchemaEventTarget):
self.impl._set_parent(column)
def _set_parent_with_dispatch(self, parent):
"""Support SchemaEentTarget"""
super(TypeDecorator, self)._set_parent_with_dispatch(parent)
if isinstance(self.impl, SchemaEventTarget):
self.impl._set_parent_with_dispatch(parent)
def type_engine(self, dialect):
"""Return a dialect-specific :class:`.TypeEngine` instance
for this :class:`.TypeDecorator`.
In most cases this returns a dialect-adapted form of
the :class:`.TypeEngine` type represented by ``self.impl``.
Makes usage of :meth:`dialect_impl` but also traverses
into wrapped :class:`.TypeDecorator` instances.
Behavior can be customized here by overriding
:meth:`load_dialect_impl`.
"""
adapted = dialect.type_descriptor(self)
if not isinstance(adapted, type(self)):
return adapted
elif isinstance(self.impl, TypeDecorator):
return self.impl.type_engine(dialect)
else:
return self.load_dialect_impl(dialect)
def load_dialect_impl(self, dialect):
"""Return a :class:`.TypeEngine` object corresponding to a dialect.
This is an end-user override hook that can be used to provide
differing types depending on the given dialect. It is used
by the :class:`.TypeDecorator` implementation of :meth:`type_engine`
to help determine what type should ultimately be returned
for a given :class:`.TypeDecorator`.
By default returns ``self.impl``.
"""
return self.impl
def __getattr__(self, key):
"""Proxy all other undefined accessors to the underlying
implementation."""
return getattr(self.impl, key)
def process_literal_param(self, value, dialect):
"""Receive a literal parameter value to be rendered inline within
a statement.
This method is used when the compiler renders a
literal value without using binds, typically within DDL
such as in the "server default" of a column or an expression
within a CHECK constraint.
The returned string will be rendered into the output string.
.. versionadded:: 0.9.0
"""
raise NotImplementedError()
def process_bind_param(self, value, dialect):
"""Receive a bound parameter value to be converted.
Subclasses override this method to return the
value that should be passed along to the underlying
:class:`.TypeEngine` object, and from there to the
DBAPI ``execute()`` method.
The operation could be anything desired to perform custom
behavior, such as transforming or serializing data.
This could also be used as a hook for validating logic.
This operation should be designed with the reverse operation
in mind, which would be the process_result_value method of
this class.
:param value: Data to operate upon, of any type expected by
this method in the subclass. Can be ``None``.
:param dialect: the :class:`.Dialect` in use.
"""
raise NotImplementedError()
def process_result_value(self, value, dialect):
"""Receive a result-row column value to be converted.
Subclasses should implement this method to operate on data
fetched from the database.
Subclasses override this method to return the
value that should be passed back to the application,
given a value that is already processed by
the underlying :class:`.TypeEngine` object, originally
from the DBAPI cursor method ``fetchone()`` or similar.
The operation could be anything desired to perform custom
behavior, such as transforming or serializing data.
This could also be used as a hook for validating logic.
:param value: Data to operate upon, of any type expected by
this method in the subclass. Can be ``None``.
:param dialect: the :class:`.Dialect` in use.
This operation should be designed to be reversible by
the "process_bind_param" method of this class.
"""
raise NotImplementedError()
@util.memoized_property
def _has_bind_processor(self):
"""memoized boolean, check if process_bind_param is implemented.
Allows the base process_bind_param to raise
NotImplementedError without needing to test an expensive
exception throw.
"""
return self.__class__.process_bind_param.__code__ \
is not TypeDecorator.process_bind_param.__code__
@util.memoized_property
def _has_literal_processor(self):
"""memoized boolean, check if process_literal_param is implemented.
"""
return self.__class__.process_literal_param.__code__ \
is not TypeDecorator.process_literal_param.__code__
def literal_processor(self, dialect):
"""Provide a literal processing function for the given
:class:`.Dialect`.
Subclasses here will typically override
:meth:`.TypeDecorator.process_literal_param` instead of this method
directly.
By default, this method makes use of
:meth:`.TypeDecorator.process_bind_param` if that method is
implemented, where :meth:`.TypeDecorator.process_literal_param` is
not. The rationale here is that :class:`.TypeDecorator` typically
deals with Python conversions of data that are above the layer of
database presentation. With the value converted by
:meth:`.TypeDecorator.process_bind_param`, the underlying type will
then handle whether it needs to be presented to the DBAPI as a bound
parameter or to the database as an inline SQL value.
.. versionadded:: 0.9.0
"""
if self._has_literal_processor:
process_param = self.process_literal_param
elif self._has_bind_processor:
# the bind processor should normally be OK
# for TypeDecorator since it isn't doing DB-level
# handling, the handling here won't be different for bound vs.
# literals.
process_param = self.process_bind_param
else:
process_param = None
if process_param:
impl_processor = self.impl.literal_processor(dialect)
if impl_processor:
def process(value):
return impl_processor(process_param(value, dialect))
else:
def process(value):
return process_param(value, dialect)
return process
else:
return self.impl.literal_processor(dialect)
def bind_processor(self, dialect):
"""Provide a bound value processing function for the
given :class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for bound value conversion. :class:`.TypeDecorator`
will wrap a user-defined implementation of
:meth:`process_bind_param` here.
User-defined code can override this method directly,
though its likely best to use :meth:`process_bind_param` so that
the processing provided by ``self.impl`` is maintained.
:param dialect: Dialect instance in use.
This method is the reverse counterpart to the
:meth:`result_processor` method of this class.
"""
if self._has_bind_processor:
process_param = self.process_bind_param
impl_processor = self.impl.bind_processor(dialect)
if impl_processor:
def process(value):
return impl_processor(process_param(value, dialect))
else:
def process(value):
return process_param(value, dialect)
return process
else:
return self.impl.bind_processor(dialect)
@util.memoized_property
def _has_result_processor(self):
"""memoized boolean, check if process_result_value is implemented.
Allows the base process_result_value to raise
NotImplementedError without needing to test an expensive
exception throw.
"""
return self.__class__.process_result_value.__code__ \
is not TypeDecorator.process_result_value.__code__
def result_processor(self, dialect, coltype):
"""Provide a result value processing function for the given
:class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for result value conversion. :class:`.TypeDecorator`
will wrap a user-defined implementation of
:meth:`process_result_value` here.
User-defined code can override this method directly,
though its likely best to use :meth:`process_result_value` so that
the processing provided by ``self.impl`` is maintained.
:param dialect: Dialect instance in use.
:param coltype: A SQLAlchemy data type
This method is the reverse counterpart to the
:meth:`bind_processor` method of this class.
"""
if self._has_result_processor:
process_value = self.process_result_value
impl_processor = self.impl.result_processor(dialect,
coltype)
if impl_processor:
def process(value):
return process_value(impl_processor(value), dialect)
else:
def process(value):
return process_value(value, dialect)
return process
else:
return self.impl.result_processor(dialect, coltype)
def coerce_compared_value(self, op, value):
"""Suggest a type for a 'coerced' Python value in an expression.
By default, returns self. This method is called by
the expression system when an object using this type is
on the left or right side of an expression against a plain Python
object which does not yet have a SQLAlchemy type assigned::
expr = table.c.somecolumn + 35
Where above, if ``somecolumn`` uses this type, this method will
be called with the value ``operator.add``
and ``35``. The return value is whatever SQLAlchemy type should
be used for ``35`` for this particular operation.
"""
return self
def copy(self, **kw):
"""Produce a copy of this :class:`.TypeDecorator` instance.
This is a shallow copy and is provided to fulfill part of
the :class:`.TypeEngine` contract. It usually does not
need to be overridden unless the user-defined :class:`.TypeDecorator`
has local state that should be deep-copied.
"""
instance = self.__class__.__new__(self.__class__)
instance.__dict__.update(self.__dict__)
return instance
def get_dbapi_type(self, dbapi):
"""Return the DBAPI type object represented by this
:class:`.TypeDecorator`.
By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the
underlying "impl".
"""
return self.impl.get_dbapi_type(dbapi)
def compare_values(self, x, y):
"""Given two values, compare them for equality.
By default this calls upon :meth:`.TypeEngine.compare_values`
of the underlying "impl", which in turn usually
uses the Python equals operator ``==``.
This function is used by the ORM to compare
an original-loaded value with an intercepted
"changed" value, to determine if a net change
has occurred.
"""
return self.impl.compare_values(x, y)
def __repr__(self):
return util.generic_repr(self, to_inspect=self.impl)
class Variant(TypeDecorator):
"""A wrapping type that selects among a variety of
implementations based on dialect in use.
The :class:`.Variant` type is typically constructed
using the :meth:`.TypeEngine.with_variant` method.
.. versionadded:: 0.7.2
.. seealso:: :meth:`.TypeEngine.with_variant` for an example of use.
"""
def __init__(self, base, mapping):
"""Construct a new :class:`.Variant`.
:param base: the base 'fallback' type
:param mapping: dictionary of string dialect names to
:class:`.TypeEngine` instances.
"""
self.impl = base
self.mapping = mapping
def load_dialect_impl(self, dialect):
if dialect.name in self.mapping:
return self.mapping[dialect.name]
else:
return self.impl
def with_variant(self, type_, dialect_name):
"""Return a new :class:`.Variant` which adds the given
type + dialect name to the mapping, in addition to the
mapping present in this :class:`.Variant`.
:param type_: a :class:`.TypeEngine` that will be selected
as a variant from the originating type, when a dialect
of the given name is in use.
:param dialect_name: base name of the dialect which uses
this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
"""
if dialect_name in self.mapping:
raise exc.ArgumentError(
"Dialect '%s' is already present in "
"the mapping for this Variant" % dialect_name)
mapping = self.mapping.copy()
mapping[dialect_name] = type_
return Variant(self.impl, mapping)
@property
def comparator_factory(self):
"""express comparison behavior in terms of the base type"""
return self.impl.comparator_factory
def _reconstitute_comparator(expression):
return expression.comparator
def to_instance(typeobj, *arg, **kw):
if typeobj is None:
return NULLTYPE
if util.callable(typeobj):
return typeobj(*arg, **kw)
else:
return typeobj
def adapt_type(typeobj, colspecs):
if isinstance(typeobj, type):
typeobj = typeobj()
for t in typeobj.__class__.__mro__[0:-1]:
try:
impltype = colspecs[t]
break
except KeyError:
pass
else:
# couldn't adapt - so just return the type itself
# (it may be a user-defined type)
return typeobj
# if we adapted the given generic type to a database-specific type,
# but it turns out the originally given "generic" type
# is actually a subclass of our resulting type, then we were already
# given a more specific type than that required; so use that.
if (issubclass(typeobj.__class__, impltype)):
return typeobj
return typeobj.adapt(impltype)<|fim▁end|> |
return x == y
|
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright (c) 2008, 2010 Xuggle Inc. All rights reserved.
*
* This file is part of Xuggle-Utils.
*
* Xuggle-Utils 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 3 of the License, or
* (at your option) any later version.
*
* Xuggle-Utils 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 Xuggle-Utils. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
/**
* Provides convenience methods for registering, and
* special implementations of,
* {@link com.xuggle.utils.event.IEventHandler}.
* <p>
* There are certain types of {@link com.xuggle.utils.event.IEventHandler}
* implementations that are very common. For example, sometimes
* you want to forward an event from one
* {@link com.xuggle.utils.event.IEventDispatcher}
* to another.<|fim▁hole|> * a {@link com.xuggle.utils.event.IEventHandler} to execute if the
* {@link com.xuggle.utils.event.IEvent#getSource()} is equal to
* a given source.
* Sometimes you only
* want to handler to execute a maximum number of times.
* </p>
* <p>
* This class tries to provide some of those implementations for you.
* </p>
* <p>
* Use the {@link com.xuggle.utils.event.handler.Handler} class to find
* Factory methods for the special handlers you want.
* </p>
* @see com.xuggle.utils.event.handler.Handler
*
*/
package com.xuggle.utils.event.handler;<|fim▁end|> | * Sometimes you only want |
<|file_name|>invite.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-Today OpenERP SA (<http://www.openerp.com>)
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
from openerp import tools
from openerp.osv import osv
from openerp.osv import fields
from openerp.tools.translate import _
class invite_wizard(osv.osv_memory):
""" Wizard to invite partners and make them followers. """
_name = 'mail.wizard.invite'
_description = 'Invite wizard'
def default_get(self, cr, uid, fields, context=None):
result = super(invite_wizard, self).default_get(cr, uid, fields, context=context)
if 'message' in fields and result.get('res_model') and result.get('res_id'):
document_name = self.pool.get(result.get('res_model')).name_get(cr, uid, [result.get('res_id')], context=context)[0][1]
message = _('<div>You have been invited to follow %s.</div>') % document_name
result['message'] = message
elif 'message' in fields:
result['message'] = _('<div>You have been invited to follow a new document.</div>')
return result
_columns = {
'res_model': fields.char('Related Document Model', size=128,
required=True, select=1,
help='Model of the followed resource'),
'res_id': fields.integer('Related Document ID', select=1,
help='Id of the followed resource'),
'partner_ids': fields.many2many('res.partner', string='Partners'),
'message': fields.html('Message'),
}
def add_followers(self, cr, uid, ids, context=None):
for wizard in self.browse(cr, uid, ids, context=context):
model_obj = self.pool.get(wizard.res_model)
document = model_obj.browse(cr, uid, wizard.res_id, context=context)
# filter partner_ids to get the new followers, to avoid sending email to already following partners
new_follower_ids = [p.id for p in wizard.partner_ids if p.id not in document.message_follower_ids]
model_obj.message_subscribe(cr, uid, [wizard.res_id], new_follower_ids, context=context)
# send an email only if a personal message exists
if wizard.message and not wizard.message == '<br>': # when deleting the message, cleditor keeps a <br>
# add signature
user_id = self.pool.get("res.users").read(cr, uid, [uid], fields=["signature"], context=context)[0]
signature = user_id and user_id["signature"] or ''
if signature:
wizard.message = tools.append_content_to_html(wizard.message, signature, plaintext=True, container_tag='div')
# FIXME 8.0: use notification_email_send, send a wall message and let mail handle email notification + message box
for follower_id in new_follower_ids:
mail_mail = self.pool.get('mail.mail')
# the invite wizard should create a private message not related to any object -> no model, no res_id
mail_id = mail_mail.create(cr, uid, {
'model': wizard.res_model,
'res_id': wizard.res_id,
'subject': _('Invitation to follow %s') % document.name_get()[0][1],
'body_html': '%s' % wizard.message,
'auto_delete': True,
}, context=context)<|fim▁hole|><|fim▁end|> | mail_mail.send(cr, uid, [mail_id], recipient_ids=[follower_id], context=context)
return {'type': 'ir.actions.act_window_close'} |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import {RouteConfig} from "aurelia-router";
import {autoinject} from "aurelia-dependency-injection";
import {FrameworkConfiguration} from "aurelia-framework";
import {BaseAureliaModule, module} from "../aurelia-modules/index";<|fim▁hole|> name: "home",
title: "home",
route: "/",
nav: true,
moduleId: "./pages/home"
}];
@autoinject()
@module("main-app", routes, )
export class MainApplication extends BaseAureliaModule {
public getModuleName(): string {
return "main-app";
}
}
export function configure(config: FrameworkConfiguration) {
config.globalResources('./resources/iterable-value-converter');
}<|fim▁end|> |
const routes: RouteConfig[] = [{ |
<|file_name|>bench_test.go<|end_file_name|><|fim▁begin|>/*
*
* k6 - a next-generation load testing tool
* Copyright (C) 2019 Load Impact
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package influxdb
import (
"io"
"io/ioutil"
"net/http"
"testing"
"time"
"go.k6.io/k6/stats"
)
func benchmarkInfluxdb(b *testing.B, t time.Duration) {
testOutputCycle(b, func(rw http.ResponseWriter, r *http.Request) {
for {
time.Sleep(t)
m, _ := io.CopyN(ioutil.Discard, r.Body, 1<<18) // read 1/4 mb a time
if m == 0 {
break
}
}
rw.WriteHeader(204)
}, func(tb testing.TB, c *Output) {
b = tb.(*testing.B)
b.ResetTimer()
samples := make(stats.Samples, 10)
for i := 0; i < len(samples); i++ {
samples[i] = stats.Sample{
Metric: stats.New("testGauge", stats.Gauge),
Time: time.Now(),
Tags: stats.NewSampleTags(map[string]string{
"something": "else",
"VU": "21",
"else": "something",
}),
Value: 2.0,
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
c.AddMetricSamples([]stats.SampleContainer{samples})<|fim▁hole|> }
})
}
func BenchmarkInfluxdb1Second(b *testing.B) {
benchmarkInfluxdb(b, time.Second)
}
func BenchmarkInfluxdb2Second(b *testing.B) {
benchmarkInfluxdb(b, 2*time.Second)
}
func BenchmarkInfluxdb100Milliseconds(b *testing.B) {
benchmarkInfluxdb(b, 100*time.Millisecond)
}<|fim▁end|> | time.Sleep(time.Nanosecond * 20) |
<|file_name|>openssh_key_pair.go<|end_file_name|><|fim▁begin|>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See the LICENSE file in builder/azure for license information.
package arm
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ssh"<|fim▁hole|>
const (
KeySize = 2048
)
type OpenSshKeyPair struct {
privateKey *rsa.PrivateKey
publicKey ssh.PublicKey
}
func NewOpenSshKeyPair() (*OpenSshKeyPair, error) {
return NewOpenSshKeyPairWithSize(KeySize)
}
func NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, keySize)
if err != nil {
return nil, err
}
publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, err
}
return &OpenSshKeyPair{
privateKey: privateKey,
publicKey: publicKey,
}, nil
}
func (s *OpenSshKeyPair) AuthorizedKey() string {
return fmt.Sprintf("%s %s packer Azure Deployment%s",
s.publicKey.Type(),
base64.StdEncoding.EncodeToString(s.publicKey.Marshal()),
time.Now().Format(time.RFC3339))
}
func (s *OpenSshKeyPair) PrivateKey() string {
privateKey := string(pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(s.privateKey),
}))
return privateKey
}<|fim▁end|> | "time"
) |
<|file_name|>issue-24081.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//<|fim▁hole|>// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::ops::Add; //~ ERROR import `Add` conflicts with type in this module
use std::ops::Sub; //~ ERROR import `Sub` conflicts with type in this module
use std::ops::Mul; //~ ERROR import `Mul` conflicts with type in this module
use std::ops::Div; //~ ERROR import `Div` conflicts with existing submodule
use std::ops::Rem; //~ ERROR import `Rem` conflicts with trait in this module
type Add = bool;
struct Sub { x: f32 }
enum Mul { A, B }
mod Div { }
trait Rem { }
fn main() {}<|fim▁end|> | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import inspect
import operator
import types as pytypes
import typing as pt
from collections import OrderedDict
from collections.abc import Sequence
from llvmlite import ir as llvmir
from numba import njit
from numba.core import cgutils, errors, imputils, types, utils
from numba.core.datamodel import default_manager, models
from numba.core.registry import cpu_target
from numba.core.typing import templates
from numba.core.typing.asnumbatype import as_numba_type
from numba.core.serialize import disable_pickling
from numba.experimental.jitclass import _box
##############################################################################
# Data model
class InstanceModel(models.StructModel):
def __init__(self, dmm, fe_typ):
cls_data_ty = types.ClassDataType(fe_typ)
# MemInfoPointer uses the `dtype` attribute to traverse for nested
# NRT MemInfo. Since we handle nested NRT MemInfo ourselves,
# we will replace provide MemInfoPointer with an opaque type
# so that it does not raise exception for nested meminfo.
dtype = types.Opaque('Opaque.' + str(cls_data_ty))
members = [
('meminfo', types.MemInfoPointer(dtype)),
('data', types.CPointer(cls_data_ty)),
]
super(InstanceModel, self).__init__(dmm, fe_typ, members)
class InstanceDataModel(models.StructModel):
def __init__(self, dmm, fe_typ):
clsty = fe_typ.class_type
members = [(_mangle_attr(k), v) for k, v in clsty.struct.items()]
super(InstanceDataModel, self).__init__(dmm, fe_typ, members)
default_manager.register(types.ClassInstanceType, InstanceModel)
default_manager.register(types.ClassDataType, InstanceDataModel)
default_manager.register(types.ClassType, models.OpaqueModel)
def _mangle_attr(name):
"""
Mangle attributes.
The resulting name does not startswith an underscore '_'.
"""
return 'm_' + name
##############################################################################
# Class object
_ctor_template = """
def ctor({args}):
return __numba_cls_({args})
"""
def _getargs(fn_sig):
"""
Returns list of positional and keyword argument names in order.
"""
params = fn_sig.parameters
args = []
for k, v in params.items():
if (v.kind & v.POSITIONAL_OR_KEYWORD) == v.POSITIONAL_OR_KEYWORD:
args.append(k)
else:
msg = "%s argument type unsupported in jitclass" % v.kind
raise errors.UnsupportedError(msg)
return args
@disable_pickling
class JitClassType(type):
"""
The type of any jitclass.
"""
def __new__(cls, name, bases, dct):
if len(bases) != 1:
raise TypeError("must have exactly one base class")
[base] = bases
if isinstance(base, JitClassType):
raise TypeError("cannot subclass from a jitclass")
assert 'class_type' in dct, 'missing "class_type" attr'
outcls = type.__new__(cls, name, bases, dct)
outcls._set_init()
return outcls
def _set_init(cls):
"""
Generate a wrapper for calling the constructor from pure Python.
Note the wrapper will only accept positional arguments.
"""
init = cls.class_type.instance_type.methods['__init__']
init_sig = utils.pysignature(init)
# get postitional and keyword arguments
# offset by one to exclude the `self` arg
args = _getargs(init_sig)[1:]
cls._ctor_sig = init_sig
ctor_source = _ctor_template.format(args=', '.join(args))
glbls = {"__numba_cls_": cls}
exec(ctor_source, glbls)
ctor = glbls['ctor']
cls._ctor = njit(ctor)
def __instancecheck__(cls, instance):
if isinstance(instance, _box.Box):
return instance._numba_type_.class_type is cls.class_type
return False
def __call__(cls, *args, **kwargs):
# The first argument of _ctor_sig is `cls`, which here
# is bound to None and then skipped when invoking the constructor.
bind = cls._ctor_sig.bind(None, *args, **kwargs)
bind.apply_defaults()
return cls._ctor(*bind.args[1:], **bind.kwargs)
##############################################################################
# Registration utils
def _validate_spec(spec):
for k, v in spec.items():
if not isinstance(k, str):
raise TypeError("spec keys should be strings, got %r" % (k,))
if not isinstance(v, types.Type):
raise TypeError("spec values should be Numba type instances, got %r"
% (v,))
def _fix_up_private_attr(clsname, spec):
"""
Apply the same changes to dunder names as CPython would.
"""
out = OrderedDict()
for k, v in spec.items():
if k.startswith('__') and not k.endswith('__'):
k = '_' + clsname + k
out[k] = v
return out
def _add_linking_libs(context, call):
"""
Add the required libs for the callable to allow inlining.
"""
libs = getattr(call, "libs", ())
if libs:
context.add_linking_libs(libs)
def register_class_type(cls, spec, class_ctor, builder):
"""
Internal function to create a jitclass.
Args
----
cls: the original class object (used as the prototype)
spec: the structural specification contains the field types.
class_ctor: the numba type to represent the jitclass
builder: the internal jitclass builder
"""
# Normalize spec
if spec is None:
spec = OrderedDict()
elif isinstance(spec, Sequence):
spec = OrderedDict(spec)
# Extend spec with class annotations.
for attr, py_type in pt.get_type_hints(cls).items():
if attr not in spec:
spec[attr] = as_numba_type(py_type)
_validate_spec(spec)
# Fix up private attribute names
spec = _fix_up_private_attr(cls.__name__, spec)
# Copy methods from base classes
clsdct = {}
for basecls in reversed(inspect.getmro(cls)):
clsdct.update(basecls.__dict__)
methods, props, static_methods, others = {}, {}, {}, {}
for k, v in clsdct.items():
if isinstance(v, pytypes.FunctionType):
methods[k] = v
elif isinstance(v, property):
props[k] = v
elif isinstance(v, staticmethod):
static_methods[k] = v
else:
others[k] = v
# Check for name shadowing
shadowed = (set(methods) | set(props) | set(static_methods)) & set(spec)
if shadowed:
raise NameError("name shadowing: {0}".format(', '.join(shadowed)))
docstring = others.pop('__doc__', "")
_drop_ignored_attrs(others)
if others:
msg = "class members are not yet supported: {0}"
members = ', '.join(others.keys())
raise TypeError(msg.format(members))
for k, v in props.items():
if v.fdel is not None:
raise TypeError("deleter is not supported: {0}".format(k))
jit_methods = {k: njit(v) for k, v in methods.items()}
jit_props = {}
for k, v in props.items():
dct = {}
if v.fget:
dct['get'] = njit(v.fget)
if v.fset:
dct['set'] = njit(v.fset)
jit_props[k] = dct
jit_static_methods = {
k: njit(v.__func__) for k, v in static_methods.items()}
# Instantiate class type
class_type = class_ctor(
cls,
ConstructorTemplate,
spec,
jit_methods,
jit_props,
jit_static_methods)
jit_class_dct = dict(class_type=class_type, __doc__=docstring)
jit_class_dct.update(jit_static_methods)
cls = JitClassType(cls.__name__, (cls,), jit_class_dct)
# Register resolution of the class object
typingctx = cpu_target.typing_context
typingctx.insert_global(cls, class_type)
# Register class
targetctx = cpu_target.target_context
builder(class_type, typingctx, targetctx).register()
as_numba_type.register(cls, class_type.instance_type)
return cls
class ConstructorTemplate(templates.AbstractTemplate):
"""
Base class for jitclass constructor templates.
"""
def generic(self, args, kws):
# Redirect resolution to __init__
instance_type = self.key.instance_type
ctor = instance_type.jit_methods['__init__']
boundargs = (instance_type.get_reference_type(),) + args
disp_type = types.Dispatcher(ctor)
sig = disp_type.get_call_type(self.context, boundargs, kws)
if not isinstance(sig.return_type, types.NoneType):
raise TypeError(
f"__init__() should return None, not '{sig.return_type}'")
# Actual constructor returns an instance value (not None)
out = templates.signature(instance_type, *sig.args[1:])
return out
def _drop_ignored_attrs(dct):
# ignore anything defined by object
drop = set(['__weakref__',
'__module__',
'__dict__'])<|fim▁hole|>
if '__annotations__' in dct:
drop.add('__annotations__')
for k, v in dct.items():
if isinstance(v, (pytypes.BuiltinFunctionType,
pytypes.BuiltinMethodType)):
drop.add(k)
elif getattr(v, '__objclass__', None) is object:
drop.add(k)
for k in drop:
del dct[k]
class ClassBuilder(object):
"""
A jitclass builder for a mutable jitclass. This will register
typing and implementation hooks to the given typing and target contexts.
"""
class_impl_registry = imputils.Registry('jitclass builder')
implemented_methods = set()
def __init__(self, class_type, typingctx, targetctx):
self.class_type = class_type
self.typingctx = typingctx
self.targetctx = targetctx
def register(self):
"""
Register to the frontend and backend.
"""
# Register generic implementations for all jitclasses
self._register_methods(self.class_impl_registry,
self.class_type.instance_type)
# NOTE other registrations are done at the top-level
# (see ctor_impl and attr_impl below)
self.targetctx.install_registry(self.class_impl_registry)
def _register_methods(self, registry, instance_type):
"""
Register method implementations.
This simply registers that the method names are valid methods. Inside
of imp() below we retrieve the actual method to run from the type of
the reciever argument (i.e. self).
"""
to_register = list(instance_type.jit_methods) + \
list(instance_type.jit_static_methods)
for meth in to_register:
# There's no way to retrieve the particular method name
# inside the implementation function, so we have to register a
# specific closure for each different name
if meth not in self.implemented_methods:
self._implement_method(registry, meth)
self.implemented_methods.add(meth)
def _implement_method(self, registry, attr):
# create a separate instance of imp method to avoid closure clashing
def get_imp():
def imp(context, builder, sig, args):
instance_type = sig.args[0]
if attr in instance_type.jit_methods:
method = instance_type.jit_methods[attr]
elif attr in instance_type.jit_static_methods:
method = instance_type.jit_static_methods[attr]
# imp gets called as a method, where the first argument is
# self. We drop this for a static method.
sig = sig.replace(args=sig.args[1:])
args = args[1:]
disp_type = types.Dispatcher(method)
call = context.get_function(disp_type, sig)
out = call(builder, args)
_add_linking_libs(context, call)
return imputils.impl_ret_new_ref(context, builder,
sig.return_type, out)
return imp
def _getsetitem_gen(getset):
_dunder_meth = "__%s__" % getset
op = getattr(operator, getset)
@templates.infer_global(op)
class GetSetItem(templates.AbstractTemplate):
def generic(self, args, kws):
instance = args[0]
if isinstance(instance, types.ClassInstanceType) and \
_dunder_meth in instance.jit_methods:
meth = instance.jit_methods[_dunder_meth]
disp_type = types.Dispatcher(meth)
sig = disp_type.get_call_type(self.context, args, kws)
return sig
# lower both {g,s}etitem and __{g,s}etitem__ to catch the calls
# from python and numba
imputils.lower_builtin((types.ClassInstanceType, _dunder_meth),
types.ClassInstanceType,
types.VarArg(types.Any))(get_imp())
imputils.lower_builtin(op,
types.ClassInstanceType,
types.VarArg(types.Any))(get_imp())
dunder_stripped = attr.strip('_')
if dunder_stripped in ("getitem", "setitem"):
_getsetitem_gen(dunder_stripped)
else:
registry.lower((types.ClassInstanceType, attr),
types.ClassInstanceType,
types.VarArg(types.Any))(get_imp())
@templates.infer_getattr
class ClassAttribute(templates.AttributeTemplate):
key = types.ClassInstanceType
def generic_resolve(self, instance, attr):
if attr in instance.struct:
# It's a struct field => the type is well-known
return instance.struct[attr]
elif attr in instance.jit_methods:
# It's a jitted method => typeinfer it
meth = instance.jit_methods[attr]
disp_type = types.Dispatcher(meth)
class MethodTemplate(templates.AbstractTemplate):
key = (self.key, attr)
def generic(self, args, kws):
args = (instance,) + tuple(args)
sig = disp_type.get_call_type(self.context, args, kws)
return sig.as_method()
return types.BoundFunction(MethodTemplate, instance)
elif attr in instance.jit_static_methods:
# It's a jitted method => typeinfer it
meth = instance.jit_static_methods[attr]
disp_type = types.Dispatcher(meth)
class StaticMethodTemplate(templates.AbstractTemplate):
key = (self.key, attr)
def generic(self, args, kws):
# Don't add instance as the first argument for a static
# method.
sig = disp_type.get_call_type(self.context, args, kws)
# sig itself does not include ClassInstanceType as it's
# first argument, so instead of calling sig.as_method()
# we insert the recvr. This is equivalent to
# sig.replace(args=(instance,) + sig.args).as_method().
return sig.replace(recvr=instance)
return types.BoundFunction(StaticMethodTemplate, instance)
elif attr in instance.jit_props:
# It's a jitted property => typeinfer its getter
impdct = instance.jit_props[attr]
getter = impdct['get']
disp_type = types.Dispatcher(getter)
sig = disp_type.get_call_type(self.context, (instance,), {})
return sig.return_type
@ClassBuilder.class_impl_registry.lower_getattr_generic(types.ClassInstanceType)
def get_attr_impl(context, builder, typ, value, attr):
"""
Generic getattr() for @jitclass instances.
"""
if attr in typ.struct:
# It's a struct field
inst = context.make_helper(builder, typ, value=value)
data_pointer = inst.data
data = context.make_data_helper(builder, typ.get_data_type(),
ref=data_pointer)
return imputils.impl_ret_borrowed(context, builder,
typ.struct[attr],
getattr(data, _mangle_attr(attr)))
elif attr in typ.jit_props:
# It's a jitted property
getter = typ.jit_props[attr]['get']
sig = templates.signature(None, typ)
dispatcher = types.Dispatcher(getter)
sig = dispatcher.get_call_type(context.typing_context, [typ], {})
call = context.get_function(dispatcher, sig)
out = call(builder, [value])
_add_linking_libs(context, call)
return imputils.impl_ret_new_ref(context, builder, sig.return_type, out)
raise NotImplementedError('attribute {0!r} not implemented'.format(attr))
@ClassBuilder.class_impl_registry.lower_setattr_generic(types.ClassInstanceType)
def set_attr_impl(context, builder, sig, args, attr):
"""
Generic setattr() for @jitclass instances.
"""
typ, valty = sig.args
target, val = args
if attr in typ.struct:
# It's a struct member
inst = context.make_helper(builder, typ, value=target)
data_ptr = inst.data
data = context.make_data_helper(builder, typ.get_data_type(),
ref=data_ptr)
# Get old value
attr_type = typ.struct[attr]
oldvalue = getattr(data, _mangle_attr(attr))
# Store n
setattr(data, _mangle_attr(attr), val)
context.nrt.incref(builder, attr_type, val)
# Delete old value
context.nrt.decref(builder, attr_type, oldvalue)
elif attr in typ.jit_props:
# It's a jitted property
setter = typ.jit_props[attr]['set']
disp_type = types.Dispatcher(setter)
sig = disp_type.get_call_type(context.typing_context,
(typ, valty), {})
call = context.get_function(disp_type, sig)
call(builder, (target, val))
_add_linking_libs(context, call)
else:
raise NotImplementedError(
'attribute {0!r} not implemented'.format(attr))
def imp_dtor(context, module, instance_type):
llvoidptr = context.get_value_type(types.voidptr)
llsize = context.get_value_type(types.uintp)
dtor_ftype = llvmir.FunctionType(llvmir.VoidType(),
[llvoidptr, llsize, llvoidptr])
fname = "_Dtor.{0}".format(instance_type.name)
dtor_fn = cgutils.get_or_insert_function(module, dtor_ftype, fname)
if dtor_fn.is_declaration:
# Define
builder = llvmir.IRBuilder(dtor_fn.append_basic_block())
alloc_fe_type = instance_type.get_data_type()
alloc_type = context.get_value_type(alloc_fe_type)
ptr = builder.bitcast(dtor_fn.args[0], alloc_type.as_pointer())
data = context.make_helper(builder, alloc_fe_type, ref=ptr)
context.nrt.decref(builder, alloc_fe_type, data._getvalue())
builder.ret_void()
return dtor_fn
@ClassBuilder.class_impl_registry.lower(types.ClassType,
types.VarArg(types.Any))
def ctor_impl(context, builder, sig, args):
"""
Generic constructor (__new__) for jitclasses.
"""
# Allocate the instance
inst_typ = sig.return_type
alloc_type = context.get_data_type(inst_typ.get_data_type())
alloc_size = context.get_abi_sizeof(alloc_type)
meminfo = context.nrt.meminfo_alloc_dtor(
builder,
context.get_constant(types.uintp, alloc_size),
imp_dtor(context, builder.module, inst_typ),
)
data_pointer = context.nrt.meminfo_data(builder, meminfo)
data_pointer = builder.bitcast(data_pointer,
alloc_type.as_pointer())
# Nullify all data
builder.store(cgutils.get_null_value(alloc_type),
data_pointer)
inst_struct = context.make_helper(builder, inst_typ)
inst_struct.meminfo = meminfo
inst_struct.data = data_pointer
# Call the jitted __init__
# TODO: extract the following into a common util
init_sig = (sig.return_type,) + sig.args
init = inst_typ.jit_methods['__init__']
disp_type = types.Dispatcher(init)
call = context.get_function(disp_type, types.void(*init_sig))
_add_linking_libs(context, call)
realargs = [inst_struct._getvalue()] + list(args)
call(builder, realargs)
# Prepare return value
ret = inst_struct._getvalue()
return imputils.impl_ret_new_ref(context, builder, inst_typ, ret)<|fim▁end|> | |
<|file_name|>0013_module_list_widget.py<|end_file_name|><|fim▁begin|># encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('infrastructure', '0012_auto_20140209_0400'),
]
operations = [
migrations.AddField(
model_name='module_list',
name='widget',<|fim▁hole|> ]<|fim▁end|> | field=models.TextField(null=True, blank=True),
preserve_default=True,
), |
<|file_name|>print_bot_id.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os<|fim▁hole|>
BOT_NAME = 'chopbot3000'
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
if __name__ == "__main__":
api_call = slack_client.api_call("users.list")
if api_call.get('ok'):
# retrieve all users so we can find our bot
users = api_call.get('members')
for user in users:
if 'name' in user and user.get('name') == BOT_NAME:
print("Bot ID for '" + user['name'] + "' is " + user.get('id'))
else:
print("could not find bot user with the name " + BOT_NAME)<|fim▁end|> | from slackclient import SlackClient
|
<|file_name|>cgol.rs<|end_file_name|><|fim▁begin|>use std::os;
use std::rand;
use std::rand::Rng;
use std::io::Timer;
use std::time::Duration;
use std::clone::Clone;
#[deriving(Clone)]
struct Field {
x: uint,
y: uint,
active: bool
}
fn next_round(field: &mut Vec<Vec<Field>>) {
let old_field = field.clone();
for row in field.iter_mut() {
for c in row.iter_mut() {
c.active = next_vitality(&old_field, c.x, c.y);
}
}
}
fn next_vitality(old_field: &Vec<Vec<Field>>, x: uint, y: uint) -> bool {
let height = old_field.len();
let width = old_field[0].len();
let mut allowed_x: Vec<uint> = vec![x];
let mut allowed_y: Vec<uint> = vec![y];
if x > 0 {
allowed_x.push(x-1);
}
if x < width-1 {
allowed_x.push(x+1);
}
if y > 0 {
allowed_y.push(y-1);
}
if y < height-1 {
allowed_y.push(y+1);
}
let mut total: int = 0;
for i in allowed_x.iter() {
for j in allowed_y.iter() {
if *i == x && *j == y {
continue;
}
if old_field[*j][*i].active == true {
total += 1;
}
}
}
match total {
2 => old_field[y][x].active,
3 => true,
_ => false
}
}
fn print_field(field: &Vec<Vec<Field>>) {
for row in field.iter() {
for c in row.iter() {
print!("{}", match c.active {false => " ", true => "#"});
}
print!("\n");
}
print!("\n");
}
fn generate_first_round() -> Vec<Vec<Field>> {
let mut field: Vec<Vec<Field>> = Vec::new();
let args = os::args();
let mut width: uint = 50;
let mut height: uint = 50;
if args.len() > 1 {
match from_str::<uint>(args[1].as_slice()){
Some(x) => width = x,
None => fail!("Argument supplied is not a positive number")
};
} else {
print!("Use default value 50 as width")
}
if args.len() > 2 {
match from_str::<uint>(args[2].as_slice()){
Some(x) => height = x,
None => fail!("Argument supplied is not a positive number")
};
} else {
print!("Use default value 50 as height")
}
for y in range(0u, height) {
let mut row: Vec<Field> = Vec::new();
for x in range(0u, width) {
let mut v = false;
let mut rng = rand::task_rng();
if rng.gen::<u8>() < 32 {
v = true;
} else {
v = false;
}
row.push(Field{x:x, y:y, active:v});
}
field.push(row);
}
return field;
}
fn main() {<|fim▁hole|> let mut field = generate_first_round();
let mut timer = Timer::new().unwrap();
loop {
timer.sleep(Duration::milliseconds(150));
print_field(&field);
next_round(&mut field);
}
}<|fim▁end|> | |
<|file_name|>format.go<|end_file_name|><|fim▁begin|><|fim▁hole|>package format
import (
"errors"
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/katbyte/terrafmt/lib/common"
)
func Block(content, path string) (string, error) {
b := []byte(content)
common.Log.Debugf("format terraform config... ")
_, syntaxDiags := hclsyntax.ParseConfig(b, path, hcl.Pos{Line: 1, Column: 1})
if syntaxDiags.HasErrors() {
return "", fmt.Errorf("failed to parse hcl: %w", errors.New(syntaxDiags.Error()))
}
return string(hclwrite.Format(b)), nil
}<|fim▁end|> | |
<|file_name|>application.js<|end_file_name|><|fim▁begin|>import Route from '@ember/routing/route';
export default Route.extend({
redirect() {
this._super(...arguments);
this.transitionTo('examples.single-date-picker');<|fim▁hole|><|fim▁end|> | }
}); |
<|file_name|>cluster_handler.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web-UI helpful to run brain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http://www.thevirtualbrain.org
#
# (c) 2012-2013, Baycrest Centre for Geriatric Care ("Baycrest")<|fim▁hole|># the terms of the GNU General Public License version 2 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, you can download it here
# http://www.gnu.org/licenses/old-licenses/gpl-2.0
#
#
# CITATION:
# When using The Virtual Brain for scientific publications, please cite it as follows:
#
# Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide,
# Jochen Mersmann, Anthony R. McIntosh, Viktor Jirsa (2013)
# The Virtual Brain: a simulator of primate brain network dynamics.
# Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010)
#
#
"""
.. moduleauthor:: Calin Pavel <[email protected]>
"""
import os
import logging
from logging.handlers import MemoryHandler
from tvb.basic.profile import TvbProfile
from tvb.basic.logger.simple_handler import SimpleTimedRotatingFileHandler
class ClusterTimedRotatingFileHandler(MemoryHandler):
"""
This is a custom rotating file handler which computes the name of the file depending on the
execution environment (web node or cluster node)
"""
# Name of the log file where code from Web application will be stored
WEB_LOG_FILE = "web_application.log"
# Name of the file where to write logs from the code executed on cluster nodes
CLUSTER_NODES_LOG_FILE = "operations_executions.log"
# Size of the buffer which store log entries in memory
# in number of lines
BUFFER_CAPACITY = 20
def __init__(self, when='h', interval=1, backupCount=0):
"""
Constructor for logging formatter.
"""
# Formatting string
format_str = '%(asctime)s - %(levelname)s'
if TvbProfile.current.cluster.IN_OPERATION_EXECUTION_PROCESS:
log_file = self.CLUSTER_NODES_LOG_FILE
if TvbProfile.current.cluster.IS_RUNNING_ON_CLUSTER_NODE:
node_name = TvbProfile.current.cluster.CLUSTER_NODE_NAME
if node_name is not None:
format_str += ' [node:' + str(node_name) + '] '
else:
format_str += ' [proc:' + str(os.getpid()) + '] '
else:
log_file = self.WEB_LOG_FILE
format_str += ' - %(name)s - %(message)s'
rotating_file_handler = SimpleTimedRotatingFileHandler(log_file, when, interval, backupCount)
rotating_file_handler.setFormatter(logging.Formatter(format_str))
MemoryHandler.__init__(self, capacity=self.BUFFER_CAPACITY, target=rotating_file_handler)<|fim▁end|> | #
# This program is free software; you can redistribute it and/or modify it under |
<|file_name|>post.py<|end_file_name|><|fim▁begin|>import __settings__
from __settings__ import INSTALLED_APPS
assert hasattr(__settings__, 'BASE_DIR'), 'BASE_DIR required'
<|fim▁hole|>)<|fim▁end|> |
INSTALLED_APPS += (
'post', |
<|file_name|>pokemon_hunter.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
from geopy.distance import great_circle
from s2sphere import Cell, CellId, LatLng
from pokemongo_bot import inventory
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.item_list import Item
from pokemongo_bot.walkers.polyline_walker import PolylineWalker
from pokemongo_bot.walkers.step_walker import StepWalker
from pokemongo_bot.worker_result import WorkerResult
class PokemonHunter(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
def __init__(self, bot, config):
super(PokemonHunter, self).__init__(bot, config)
def initialize(self):
self.destination = None
self.walker = None
self.search_cell_id = None
self.search_points = []
self.lost_counter = 0
self.no_log_until = 0
self.config_max_distance = self.config.get("max_distance", 2000)
self.config_hunt_all = self.config.get("hunt_all", False)
self.config_hunt_vip = self.config.get("hunt_vip", True)
self.config_hunt_pokedex = self.config.get("hunt_pokedex", True)
def work(self):
if not self.enabled:
return WorkerResult.SUCCESS
if self.get_pokeball_count() <= 0:
self.destination = None
self.last_cell_id = None
return WorkerResult.SUCCESS
now = time.time()
pokemons = self.get_nearby_pokemons()
if self.destination is None:
worth_pokemons = self.get_worth_pokemons(pokemons)
if len(worth_pokemons) > 0:
self.destination = worth_pokemons[0]
self.lost_counter = 0
self.logger.info("New destination at %(distance).2f meters: %(name)s", self.destination)
self.no_log_until = now + 60
if self.destination["s2_cell_id"] != self.search_cell_id:
self.search_points = self.get_search_points(self.destination["s2_cell_id"])
self.walker = PolylineWalker(self.bot, self.search_points[0][0], self.search_points[0][1])
self.search_cell_id = self.destination["s2_cell_id"]
self.search_points = self.search_points[1:] + self.search_points[:1]
else:
if self.no_log_until < now:
self.logger.info("There is no nearby pokemon worth hunting down [%s]", ", ".join(p["name"] for p in pokemons))
self.no_log_until = now + 120
self.last_cell_id = None
return WorkerResult.SUCCESS<|fim▁hole|> if any(self.destination["encounter_id"] == p["encounter_id"] for p in self.bot.cell["catchable_pokemons"] + self.bot.cell["wild_pokemons"]):
self.destination = None
elif self.walker.step():
if not any(self.destination["encounter_id"] == p["encounter_id"] for p in pokemons):
self.lost_counter += 1
else:
self.lost_counter = 0
if self.lost_counter >= 3:
self.destination = None
else:
self.logger.info("Now searching for %(name)s", self.destination)
self.walker = StepWalker(self.bot, self.search_points[0][0], self.search_points[0][1])
self.search_points = self.search_points[1:] + self.search_points[:1]
elif self.no_log_until < now:
distance = great_circle(self.bot.position, (self.walker.dest_lat, self.walker.dest_lng)).meters
self.logger.info("Moving to destination at %s meters: %s", round(distance, 2), self.destination["name"])
self.no_log_until = now + 30
return WorkerResult.RUNNING
def get_pokeball_count(self):
return sum([inventory.items().get(ball.value).count for ball in [Item.ITEM_POKE_BALL, Item.ITEM_GREAT_BALL, Item.ITEM_ULTRA_BALL]])
def get_nearby_pokemons(self):
radius = self.config_max_distance
pokemons = [p for p in self.bot.cell["nearby_pokemons"] if self.get_distance(self.bot.start_position, p) <= radius]
for pokemon in pokemons:
pokemon["distance"] = self.get_distance(self.bot.position, p)
pokemon["name"] = inventory.pokemons().name_for(pokemon["pokemon_id"])
pokemons.sort(key=lambda p: p["distance"])
return pokemons
def get_worth_pokemons(self, pokemons):
if self.config_hunt_all:
worth_pokemons = pokemons
else:
worth_pokemons = []
if self.config_hunt_vip:
worth_pokemons += [p for p in pokemons if p["name"] in self.bot.config.vips]
if self.config_hunt_pokedex:
worth_pokemons += [p for p in pokemons if (p not in worth_pokemons) and any(not inventory.pokedex().seen(fid) for fid in self.get_family_ids(p))]
worth_pokemons.sort(key=lambda p: inventory.candies().get(p["pokemon_id"]).quantity)
return worth_pokemons
def get_family_ids(self, pokemon):
family_id = inventory.pokemons().data_for(pokemon["pokemon_id"]).first_evolution_id
ids = [family_id]
ids += inventory.pokemons().data_for(family_id).next_evolutions_all[:]
return ids
def get_distance(self, location, pokemon):
return great_circle(location, (pokemon["latitude"], pokemon["longitude"])).meters
def get_search_points(self, cell_id):
points = []
# For cell level 15
for c in Cell(CellId(cell_id)).subdivide():
for cc in c.subdivide():
latlng = LatLng.from_point(cc.get_center())
point = (latlng.lat().degrees, latlng.lng().degrees)
points.append(point)
points[0], points[1] = points[1], points[0]
points[14], points[15] = points[15], points[14]
point = points.pop(2)
points.insert(7, point)
point = points.pop(13)
points.insert(8, point)
closest = min(points, key=lambda p: great_circle(self.bot.position, p).meters)
index = points.index(closest)
return points[index:] + points[:index]<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_slug
from django.db import models
from django.utils import simplejson as json
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from philo.forms.fields import JSONFormField
from philo.utils.registry import RegistryIterator
from philo.validators import TemplateValidator, json_validator
#from philo.models.fields.entities import *
class TemplateField(models.TextField):
"""A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction."""
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs):
super(TemplateField, self).__init__(*args, **kwargs)
self.validators.append(TemplateValidator(allow, disallow, secure))
class JSONDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, instance, owner):
if instance is None:
raise AttributeError # ?
if self.field.name not in instance.__dict__:
json_string = getattr(instance, self.field.attname)
instance.__dict__[self.field.name] = json.loads(json_string)
return instance.__dict__[self.field.name]
def __set__(self, instance, value):
instance.__dict__[self.field.name] = value
setattr(instance, self.field.attname, json.dumps(value))
def __delete__(self, instance):
del(instance.__dict__[self.field.name])
setattr(instance, self.field.attname, json.dumps(None))
class JSONField(models.TextField):
"""A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`."""
default_validators = [json_validator]
def get_attname(self):
return "%s_json" % self.name
def contribute_to_class(self, cls, name):
super(JSONField, self).contribute_to_class(cls, name)
setattr(cls, name, JSONDescriptor(self))
models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs):
# Anything passed in as self.name is assumed to come from a serializer and
# will be treated as a json string.
if self.name in kwargs:
value = kwargs.pop(self.name)
# Hack to handle the xml serializer's handling of "null"
if value is None:
value = 'null'
kwargs[self.attname] = value
def formfield(self, *args, **kwargs):
kwargs["form_class"] = JSONFormField
return super(JSONField, self).formfield(*args, **kwargs)
class SlugMultipleChoiceField(models.Field):
"""Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices."""
__metaclass__ = models.SubfieldBase
description = _("Comma-separated slug field")
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if not value:
return []
if isinstance(value, list):
return value
return value.split(',')
def get_prep_value(self, value):
return ','.join(value)
def formfield(self, **kwargs):
# This is necessary because django hard-codes TypedChoiceField for things with choices.
defaults = {
'widget': forms.CheckboxSelectMultiple,
'choices': self.get_choices(include_blank=False),
'label': capfirst(self.verbose_name),
'required': not self.blank,
'help_text': self.help_text
}
if self.has_default():<|fim▁hole|> if callable(self.default):
defaults['initial'] = self.default
defaults['show_hidden_initial'] = True
else:
defaults['initial'] = self.get_default()
for k in kwargs.keys():
if k not in ('coerce', 'empty_value', 'choices', 'required',
'widget', 'label', 'initial', 'help_text',
'error_messages', 'show_hidden_initial'):
del kwargs[k]
defaults.update(kwargs)
form_class = forms.TypedMultipleChoiceField
return form_class(**defaults)
def validate(self, value, model_instance):
invalid_values = []
for val in value:
try:
validate_slug(val)
except ValidationError:
invalid_values.append(val)
if invalid_values:
# should really make a custom message.
raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
def _get_choices(self):
if isinstance(self._choices, RegistryIterator):
return self._choices.copy()
elif hasattr(self._choices, 'next'):
choices, self._choices = itertools.tee(self._choices)
return choices
else:
return self._choices
choices = property(_get_choices)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"])
add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|> | |
<|file_name|>baseRequiredField.validator.ts<|end_file_name|><|fim▁begin|>import { get, has, upperFirst } from 'lodash';
import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain';
import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator';
export interface IRequiredField {
fieldName: string;
fieldLabel?: string;
}
export interface IBaseRequiredFieldValidationConfig extends IValidatorConfig {
message?: string;
}
export abstract class BaseRequiredFieldValidator implements IStageOrTriggerValidator {
public validate(
pipeline: IPipeline,
stage: IStage | ITrigger,
validationConfig: IBaseRequiredFieldValidationConfig,
config: IStageOrTriggerTypeConfig,
): string {
if (!this.passesValidation(pipeline, stage, validationConfig)) {
return this.validationMessage(validationConfig, config);
}
return null;
}
protected abstract passesValidation(
pipeline: IPipeline,
stage: IStage | ITrigger,
validationConfig: IBaseRequiredFieldValidationConfig,
): boolean;
protected abstract validationMessage(
validationConfig: IBaseRequiredFieldValidationConfig,
config: IStageOrTriggerTypeConfig,
): string;
protected printableFieldLabel(field: IRequiredField): string {
const fieldLabel: string = field.fieldLabel || field.fieldName;
return upperFirst(fieldLabel);
}
protected fieldIsValid(pipeline: IPipeline, stage: IStage | ITrigger, fieldName: string): boolean {
if (pipeline.strategy === true && ['cluster', 'regions', 'zones', 'credentials'].includes(fieldName)) {
return true;
}
const fieldExists = has(stage, fieldName);
const field: any = get(stage, fieldName);
<|fim▁hole|><|fim▁end|> | return fieldExists && (field || field === 0) && !(Array.isArray(field) && field.length === 0);
}
} |
<|file_name|>vrframedata.rs<|end_file_name|><|fim▁begin|>/* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::VRFrameDataBinding;
use crate::dom::bindings::codegen::Bindings::VRFrameDataBinding::VRFrameDataMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::globalscope::GlobalScope;
use crate::dom::vrpose::VRPose;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject};
use js::typedarray::{CreateWith, Float32Array};
use std::cell::Cell;
use std::ptr;
use std::ptr::NonNull;
use webvr_traits::WebVRFrameData;
#[dom_struct]
pub struct VRFrameData {
reflector_: Reflector,
left_proj: Heap<*mut JSObject>,
left_view: Heap<*mut JSObject>,
right_proj: Heap<*mut JSObject>,
right_view: Heap<*mut JSObject>,
pose: Dom<VRPose>,
timestamp: Cell<f64>,
first_timestamp: Cell<f64>,
}
impl VRFrameData {
fn new_inherited(pose: &VRPose) -> VRFrameData {
VRFrameData {
reflector_: Reflector::new(),
left_proj: Heap::default(),
left_view: Heap::default(),
right_proj: Heap::default(),
right_view: Heap::default(),
pose: Dom::from_ref(&*pose),
timestamp: Cell::new(0.0),
first_timestamp: Cell::new(0.0),
}
}
#[allow(unsafe_code)]
fn new(global: &GlobalScope) -> DomRoot<VRFrameData> {
let matrix = [
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0f32,
];
let pose = VRPose::new(&global, &Default::default());
let root = reflect_dom_object(
Box::new(VRFrameData::new_inherited(&pose)),
global,
VRFrameDataBinding::Wrap,
);
let cx = global.get_cx();
create_typed_array(cx, &matrix, &root.left_proj);
create_typed_array(cx, &matrix, &root.left_view);
create_typed_array(cx, &matrix, &root.right_proj);
create_typed_array(cx, &matrix, &root.right_view);
root
}
pub fn Constructor(window: &Window) -> Fallible<DomRoot<VRFrameData>> {
Ok(VRFrameData::new(&window.global()))
}
}
#[allow(unsafe_code)]
fn create_typed_array(cx: *mut JSContext, src: &[f32], dst: &Heap<*mut JSObject>) {
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>());
unsafe {
let _ = Float32Array::create(cx, CreateWith::Slice(src), array.handle_mut());
}
(*dst).set(array.get());
}
impl VRFrameData {
#[allow(unsafe_code)]
pub fn update(&self, data: &WebVRFrameData) {
unsafe {
let cx = self.global().get_cx();
typedarray!(in(cx) let left_proj_array: Float32Array = self.left_proj.get());
if let Ok(mut array) = left_proj_array {
array.update(&data.left_projection_matrix);
}
typedarray!(in(cx) let left_view_array: Float32Array = self.left_view.get());
if let Ok(mut array) = left_view_array {
array.update(&data.left_view_matrix);
}
typedarray!(in(cx) let right_proj_array: Float32Array = self.right_proj.get());
if let Ok(mut array) = right_proj_array {
array.update(&data.right_projection_matrix);
}
typedarray!(in(cx) let right_view_array: Float32Array = self.right_view.get());
if let Ok(mut array) = right_view_array {
array.update(&data.right_view_matrix);
}
}
self.pose.update(&data.pose);
self.timestamp.set(data.timestamp);
if self.first_timestamp.get() == 0.0 {
self.first_timestamp.set(data.timestamp);
}
}
}
impl VRFrameDataMethods for VRFrameData {
// https://w3c.github.io/webvr/#dom-vrframedata-timestamp
fn Timestamp(&self) -> Finite<f64> {
Finite::wrap(self.timestamp.get() - self.first_timestamp.get())
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix<|fim▁hole|> unsafe fn LeftProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.left_proj.get())
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftviewmatrix
unsafe fn LeftViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.left_view.get())
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-rightprojectionmatrix
unsafe fn RightProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.right_proj.get())
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-rightviewmatrix
unsafe fn RightViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.right_view.get())
}
// https://w3c.github.io/webvr/#dom-vrframedata-pose
fn Pose(&self) -> DomRoot<VRPose> {
DomRoot::from_ref(&*self.pose)
}
}<|fim▁end|> | |
<|file_name|>triangulation.rs<|end_file_name|><|fim▁begin|>//! Methods for converting shapes into triangles.
use ImageSize;
use interpolation::lerp;
use types::{
Line,
SourceRectangle,
Polygon,
Polygons,
Radius,
Rectangle,
Resolution,
};
use math::{
multiply,
orient,
translate,
Matrix2d,
Scalar,
Vec2d,
};
use radians::Radians;
/// Transformed x coordinate as f32.
#[inline(always)]
pub fn tx(m: Matrix2d, x: Scalar, y: Scalar) -> f32 {
(m[0][0] * x + m[0][1] * y + m[0][2]) as f32
}
/// Transformed y coordinate as f32.
#[inline(always)]
pub fn ty(m: Matrix2d, x: Scalar, y: Scalar) -> f32 {
(m[1][0] * x + m[1][1] * y + m[1][2]) as f32
}
/// Streams tweened polygons using linear interpolation.
#[inline(always)]
pub fn with_lerp_polygons_tri_list<F>(
m: Matrix2d,
polygons: Polygons,
tween_factor: Scalar,
f: F
)
where
F: FnMut(&[f32])
{
let poly_len = polygons.len() as Scalar;
// Map to interval between 0 and 1.
let tw = tween_factor % 1.0;
// Map negative values to positive.
let tw = if tw < 0.0 { tw + 1.0 } else { tw };
// Map to frame.
let tw = tw * poly_len;
// Get the current frame.
let frame = tw as usize;
// Get the next frame.
let next_frame = (frame + 1) % polygons.len();
let p0 = polygons[frame];
let p1 = polygons[next_frame];
// Get factor between frames.
let tw = tw - frame as Scalar;
let n = polygons[0].len();
let mut i: usize = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let j = i;
i += 1;
Some(lerp(&p0[j], &p1[j], &tw))
}, f);
}
/// Streams an ellipse specified by a resolution.
#[inline(always)]
pub fn with_ellipse_tri_list<F>(
resolution: Resolution,
m: Matrix2d,
rect: Rectangle,
f: F
)
where
F: FnMut(&[f32])
{
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (cw, ch) = (0.5 * w, 0.5 * h);
let (cx, cy) = (x + cw, y + ch);
let n = resolution;
let mut i = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let angle = i as Scalar / n as Scalar * <f64 as Radians>::_360();
i += 1;
Some([cx + angle.cos() * cw, cy + angle.sin() * ch])
}, f);
}
/// Streams a round border line.
#[inline(always)]
pub fn with_round_border_line_tri_list<F>(
resolution_cap: Resolution,
m: Matrix2d,
line: Line,
round_border_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
let radius = round_border_radius;
let (x1, y1, x2, y2) = (line[0], line[1], line[2], line[3]);
let (dx, dy) = (x2 - x1, y2 - y1);
let w = (dx * dx + dy * dy).sqrt();
let m = multiply(m, translate([x1, y1]));
let m = multiply(m, orient(dx, dy));
let n = resolution_cap * 2;
let mut i = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let j = i;
i += 1;
// Detect the half circle from index.
// There is one half circle at each end of the line.
// Together they form a full circle if
// the length of the line is zero.
match j {
j if j >= resolution_cap => {
// Compute the angle to match start and end
// point of half circle.
// This requires an angle offset since
// the other end of line is the first half circle.
let angle = (j - resolution_cap) as Scalar
/ (resolution_cap - 1) as Scalar * <f64 as Radians>::_180()
+ <f64 as Radians>::_180();
// Rotate 90 degrees since the line is horizontal.
let angle = angle + <f64 as Radians>::_90();
Some([w + angle.cos() * radius, angle.sin() * radius])
},
j => {
// Compute the angle to match start and end
// point of half circle.
let angle = j as Scalar
/ (resolution_cap - 1) as Scalar * <f64 as Radians>::_180();
// Rotate 90 degrees since the line is horizontal.
let angle = angle + <f64 as Radians>::_90();
Some([angle.cos() * radius, angle.sin() * radius])
},
}
}, f);
}
/// Streams a round rectangle.
#[inline(always)]
pub fn with_round_rectangle_tri_list<F>(
resolution_corner: Resolution,
m: Matrix2d,
rect: Rectangle,
round_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let radius = round_radius;
let n = resolution_corner * 4;
let mut i = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let j = i;
i += 1;
// Detect quarter circle from index.
// There is one quarter circle at each corner.
// Together they form a full circle if
// each side of rectangle is 2 times the radius.
match j {
j if j >= resolution_corner * 3 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since this
// is the last quarter.
let angle = (j - resolution_corner * 3) as Scalar
/ (resolution_corner - 1) as Scalar * <f64 as Radians>::_90()
+ 3.0 * <f64 as Radians>::_90();
// Set center of the circle to the last corner.
let (cx, cy) = (x + w - radius, y + radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
j if j >= resolution_corner * 2 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second last quarter.
let angle = (j - resolution_corner * 2) as Scalar
/ (resolution_corner - 1) as Scalar * <f64 as Radians>::_90()
+ <f64 as Radians>::_180();
// Set center of the circle to the second last corner.
let (cx, cy) = (x + radius, y + radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
j if j >= resolution_corner * 1 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second quarter.
let angle = (j - resolution_corner) as Scalar
/ (resolution_corner - 1) as Scalar * <f64 as Radians>::_90()
+ <f64 as Radians>::_90();
// Set center of the circle to the second corner.
let (cx, cy) = (x + radius, y + h - radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
j => {
// Compute the angle to match start and end
// point of quarter circle.
let angle = j as Scalar
/ (resolution_corner - 1) as Scalar
* <f64 as Radians>::_90();
// Set center of the circle to the first corner.
let (cx, cy) = (x + w - radius, y + h - radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
}
}, f);
}
/// Streams a polygon into tri list.<|fim▁hole|>pub fn stream_polygon_tri_list<E, F>(
m: Matrix2d,
mut polygon: E,
mut f: F
)
where
E: FnMut() -> Option<Vec2d>,
F: FnMut(&[f32])
{
let mut vertices: [f32; 720] = [0.0; 720];
// Get the first point which will be used a lot.
let fp = match polygon() { None => return, Some(val) => val };
let (fx, fy) = (tx(m, fp[0], fp[1]), ty(m, fp[0], fp[1]));
let gp = match polygon() { None => return, Some(val) => val };
let (gx, gy) = (tx(m, gp[0], gp[1]), ty(m, gp[0], gp[1]));
let mut gx = gx;
let mut gy = gy;
let mut i = 0;
let vertices_per_triangle = 3;
let position_components_per_vertex = 2;
let align_vertices =
vertices_per_triangle
* position_components_per_vertex;
'read_vertices: loop {
let ind_out = i * align_vertices;
vertices[ind_out + 0] = fx;
vertices[ind_out + 1] = fy;
// Copy vertex.
let ind_out = i * align_vertices + 2;
let p =
match polygon() {
None => break 'read_vertices,
Some(val) => val,
};
let x = tx(m, p[0], p[1]);
let y = ty(m, p[0], p[1]);
vertices[ind_out + 0] = gx;
vertices[ind_out + 1] = gy;
vertices[ind_out + 2] = x;
vertices[ind_out + 3] = y;
gx = x;
gy = y;
i += 1;
// Buffer is full.
if i * align_vertices + 2 >= vertices.len() {
// Send chunk and start over.
f(&vertices[0..i * align_vertices]);
i = 0;
}
}
if i > 0 {
f(&vertices[0..i * align_vertices]);
}
}
/// Streams an ellipse border specified by a resolution.
#[inline(always)]
pub fn with_ellipse_border_tri_list<F>(
resolution: Resolution,
m: Matrix2d,
rect: Rectangle,
border_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (cw, ch) = (0.5 * w, 0.5 * h);
let (cw1, ch1) = (cw + border_radius, ch + border_radius);
let (cw2, ch2) = (cw - border_radius, ch - border_radius);
let (cx, cy) = (x + cw, y + ch);
let n = resolution;
let mut i = 0;
stream_quad_tri_list(m, || {
if i > n { return None; }
let angle = i as Scalar / n as Scalar * <f64 as Radians>::_360();
let cos = angle.cos();
let sin = angle.sin();
i += 1;
Some(([cx + cos * cw1, cy + sin * ch1],
[cx + cos * cw2, cy + sin * ch2]))
}, f);
}
/// Streams a round rectangle border.
#[inline(always)]
pub fn with_round_rectangle_border_tri_list<F>(
resolution_corner: Resolution,
m: Matrix2d,
rect: Rectangle,
round_radius: Radius,
border_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let radius = round_radius;
let radius1 = round_radius + border_radius;
let radius2 = round_radius - border_radius;
let n = resolution_corner * 4;
let mut i = 0;
stream_quad_tri_list(m, || {
if i > n { return None; }
let j = i;
i += 1;
// Detect quarter circle from index.
// There is one quarter circle at each corner.
// Together they form a full circle if
// each side of rectangle is 2 times the radius.
match j {
j if j == n => {
let (cx, cy) = (x + w - radius, y + h - radius);
Some(([cx + radius1, cy],
[cx + radius2, cy]))
},
j if j >= resolution_corner * 3 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since this
// is the last quarter.
let angle = (j - resolution_corner * 3) as Scalar
/ (resolution_corner - 1) as Scalar * <f64 as Radians>::_90()
+ 3.0 * <f64 as Radians>::_90();
// Set center of the circle to the last corner.
let (cx, cy) = (x + w - radius, y + radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
j if j >= resolution_corner * 2 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second last quarter.
let angle = (j - resolution_corner * 2) as Scalar
/ (resolution_corner - 1) as Scalar * <f64 as Radians>::_90()
+ <f64 as Radians>::_180();
// Set center of the circle to the second last corner.
let (cx, cy) = (x + radius, y + radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
j if j >= resolution_corner * 1 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second quarter.
let angle = (j - resolution_corner) as Scalar
/ (resolution_corner - 1) as Scalar * <f64 as Radians>::_90()
+ <f64 as Radians>::_90();
// Set center of the circle to the second corner.
let (cx, cy) = (x + radius, y + h - radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
j => {
// Compute the angle to match start and end
// point of quarter circle.
let angle = j as Scalar
/ (resolution_corner - 1) as Scalar
* <f64 as Radians>::_90();
// Set center of the circle to the first corner.
let (cx, cy) = (x + w - radius, y + h - radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
}
}, f);
}
/// Streams a quad into tri list.
///
/// Uses buffers that fit inside L1 cache.
/// The 'quad_edge' stream returns two points
/// defining the next edge.
pub fn stream_quad_tri_list<E, F>(
m: Matrix2d,
mut quad_edge: E,
mut f: F
)
where
E: FnMut() -> Option<(Vec2d, Vec2d)>,
F: FnMut(&[f32])
{
let mut vertices: [f32; 720] = [0.0; 720];
// Get the two points .
let (fp1, fp2) = match quad_edge() {
None => return,
Some((val1, val2)) => (val1, val2)
};
// Transform the points using the matrix.
let (mut fx1, mut fy1) = (
tx(m, fp1[0], fp1[1]),
ty(m, fp1[0], fp1[1])
);
let (mut fx2, mut fy2) = (
tx(m, fp2[0], fp2[1]),
ty(m, fp2[0], fp2[1])
);
// Counts the quads.
let mut i = 0;
let triangles_per_quad = 2;
let vertices_per_triangle = 3;
let position_components_per_vertex = 2;
let align_vertices =
triangles_per_quad
* vertices_per_triangle
* position_components_per_vertex;
loop {
// Read two more points.
let (gp1, gp2) = match quad_edge() {
None => break,
Some((val1, val2)) => (val1, val2)
};
// Transform the points using the matrix.
let (gx1, gy1) = (
tx(m, gp1[0], gp1[1]),
ty(m, gp1[0], gp1[1])
);
let (gx2, gy2) = (
tx(m, gp2[0], gp2[1]),
ty(m, gp2[0], gp2[1])
);
let ind_out = i * align_vertices;
// First triangle.
vertices[ind_out + 0] = fx1;
vertices[ind_out + 1] = fy1;
vertices[ind_out + 2] = fx2;
vertices[ind_out + 3] = fy2;
vertices[ind_out + 4] = gx1;
vertices[ind_out + 5] = gy1;
// Second triangle.
vertices[ind_out + 6] = fx2;
vertices[ind_out + 7] = fy2;
vertices[ind_out + 8] = gx1;
vertices[ind_out + 9] = gy1;
vertices[ind_out + 10] = gx2;
vertices[ind_out + 11] = gy2;
// Next quad.
i += 1;
// Set next current edge.
fx1 = gx1;
fy1 = gy1;
fx2 = gx2;
fy2 = gy2;
// Buffer is full.
if i * align_vertices >= vertices.len() {
// Send chunk and start over.
f(&vertices[0..i * align_vertices]);
i = 0;
}
}
if i > 0 {
f(&vertices[0..i * align_vertices]);
}
}
/// Splits polygon into convex segments.
/// Create a buffer that fits into L1 cache with 1KB overhead.
pub fn with_polygon_tri_list<F>(
m: Matrix2d,
polygon: Polygon,
f: F
)
where
F: FnMut(&[f32])
{
let n = polygon.len();
let mut i = 0;
stream_polygon_tri_list(
m, || {
if i >= n { return None; }
let j = i;
i += 1;
Some(polygon[j])
}, f
);
}
/// Creates triangle list vertices from rectangle.
#[inline(always)]
pub fn rect_tri_list_xy(
m: Matrix2d,
rect: Rectangle
) -> [f32; 12] {
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (x2, y2) = (x + w, y + h);
[
tx(m,x,y), ty(m,x,y),
tx(m,x2,y), ty(m,x2,y),
tx(m,x,y2), ty(m,x,y2),
tx(m,x2,y), ty(m,x2,y),
tx(m,x2,y2), ty(m,x2,y2),
tx(m,x,y2), ty(m,x,y2)
]
}
/// Creates triangle list vertices from rectangle.
#[inline(always)]
pub fn rect_border_tri_list_xy(
m: Matrix2d,
rect: Rectangle,
border_radius: Radius,
) -> [f32; 48] {
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (w1, h1) = (w + border_radius, h + border_radius);
let (w2, h2) = (w - border_radius, h - border_radius);
let (x11, y11) = (x - border_radius, y - border_radius);
let (x21, y21) = (x + border_radius, y + border_radius);
let (x12, y12) = (x + w1, y + h1);
let (x22, y22) = (x + w2, y + h2);
[
tx(m, x11, y11), ty(m, x11, y11),
tx(m, x12, y11), ty(m, x12, y11),
tx(m, x21, y21), ty(m, x21, y21),
tx(m, x21, y21), ty(m, x21, y21),
tx(m, x12, y11), ty(m, x12, y11),
tx(m, x22, y21), ty(m, x22, y21),
tx(m, x22, y21), ty(m, x22, y21),
tx(m, x12, y11), ty(m, x12, y11),
tx(m, x12, y12), ty(m, x12, y12),
tx(m, x22, y21), ty(m, x22, y21),
tx(m, x12, y12), ty(m, x12, y12),
tx(m, x22, y22), ty(m, x22, y22),
tx(m, x12, y12), ty(m, x12, y12),
tx(m, x22, y22), ty(m, x22, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x22, y22), ty(m, x22, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x21, y22), ty(m, x21, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x21, y21), ty(m, x21, y21),
tx(m, x21, y22), ty(m, x21, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x11, y11), ty(m, x11, y11),
tx(m, x21, y21), ty(m, x21, y21),
]
}
/// Creates triangle list texture coords from image.
#[inline(always)]
pub fn rect_tri_list_uv<I: ImageSize>(
image: &I, source_rect: SourceRectangle
) -> [f32; 12] {
let (w, h) = image.get_size();
let (src_x, src_y, src_w, src_h) =
(source_rect[0], source_rect[1], source_rect[2], source_rect[3]);
let x1 = src_x as f32 / w as f32;
let y1 = src_y as f32 / h as f32;
let x2 = (src_w + src_x) as f32 / w as f32;
let y2 = (src_h + src_y) as f32 / h as f32;
[
x1, y1, x2, y1, x1, y2,
x2, y1, x2, y2, x1, y2
]
}<|fim▁end|> | /// Uses buffers that fit inside L1 cache. |
<|file_name|>test_slack_base_object_children.py<|end_file_name|><|fim▁begin|>import unittest
from charlesbot.slack.slack_channel_joined import SlackChannelJoined<|fim▁hole|>from charlesbot.slack.slack_group_left import SlackGroupLeft
from charlesbot.slack.slack_message import SlackMessage
class TestSlackBaseObjectChildren(unittest.TestCase):
def test_slack_channel_joined_compatibility(self):
sc = SlackChannelJoined()
object_dict = {"type": "channel_joined"}
self.assertTrue(sc.is_compatible(object_dict))
def test_slack_channel_left_compatibility(self):
sc = SlackChannelLeft()
object_dict = {"type": "channel_left"}
self.assertTrue(sc.is_compatible(object_dict))
def test_slack_group_joined_compatibility(self):
sc = SlackGroupJoined()
object_dict = {"type": "group_joined"}
self.assertTrue(sc.is_compatible(object_dict))
def test_slack_group_left_compatibility(self):
sc = SlackGroupLeft()
object_dict = {"type": "group_left"}
self.assertTrue(sc.is_compatible(object_dict))
def test_slack_message_compatibility(self):
sc = SlackMessage()
object_dict = {"type": "message"}
self.assertTrue(sc.is_compatible(object_dict))<|fim▁end|> | from charlesbot.slack.slack_channel_left import SlackChannelLeft
from charlesbot.slack.slack_group_joined import SlackGroupJoined |
<|file_name|>avatar.js<|end_file_name|><|fim▁begin|>avatar = function(x){
this.x = x;
this.y = 0;
this.prevY = 0;
this.velocity_x = 0;
this.velocity_y = 0;
this.img = loadImage("stickman.png");
this.crouch = loadImage("crouch.png");
this.width = 16;
this.standingHeight=64;
this.crouchHeight=44;
this.height = this.standingHeight;
this.collisionCheck = [];
};
avatar.prototype.addCollisionCheck = function(item){
this.collisionCheck.push(item);
//console.log("add "+item);
}
avatar.prototype.removeCollisionCheck = function(item){
this.collisionCheck.splice(
this.collisionCheck.indexOf(item), 1);
//console.log("remove mushroom");
}
avatar.prototype.platformCheck = function(){
this.talajon=false;
if(this.y<=0){
this.y=0; this.velocity_y=0; this.talajon=true;
}
for(var i in elements.es){
if(elements.es[i] instanceof platform){
var p=elements.es[i];
if(p.x<this.x +this.width && p.x+p.width > this.x){
if(this.prevY>=p.y && this.y<=p.y){
this.y=p.y;
this.velocity_y=0;
this.talajon=true;
}
}
}
}
}
avatar.prototype.death = function(){
new Audio(explosionSound.src).play();
life--;
lifeText.text = "Life: "+life;
if(life <= 0)
gameOver();
this.x = 0;
this.y = 0;
}
avatar.prototype.spikeCheck = function(){
for(var i in elements.es){
if(elements.es[i] instanceof spike){
var p=elements.es[i];
if(p.x<this.x +this.width && p.x+p.width > this.x){
/*console.log("player.y = "+this.y);
console.log("spike.y = "+p.y);
console.log("spike.height = "+p.height);
console.log("player.height = "+this.height);*/
if(p.y<this.y+this.height && p.y+p.height-3 > this.y){
this.death();
}
}
}
}
}
avatar.prototype.mushroomCheck = function(){
for(var i in elements.es){
if(elements.es[i] instanceof mushroom){
var p=elements.es[i];
if(p.x<=this.x +this.width && p.x+p.width >= this.x){
/*console.log("player.y = "+this.y);
console.log("spike.y = "+p.y);
console.log("spike.height = "+p.height);
console.log("player.height = "+this.height);*/
if(p.y<=this.y+this.height && p.y+p.height >= this.y){
if(this.prevY>p.y+p.height) {
p.death();
}else {
this.death();
}
}
}
}
}
}
avatar.prototype.logic = function(){
var speedX = 5;
if(keys[KEY_RIGHT]){
this.x += speedX;
}if(keys[KEY_LEFT]){
this.x -= speedX;
}
this.prevY = this.y;
this.y += this.velocity_y;
if(keys[KEY_UP] && this.talajon){
this.velocity_y = 14;
this.y += 0.001;
}<|fim▁hole|> //this.spikeCheck();
//this.mushroomCheck();
//collision Test
for(var i in this.collisionCheck){
var p = this.collisionCheck[i];
if(p.x<this.x +this.width &&
p.x+p.width > this.x){
if(p.y<this.y+this.height &&
p.y+p.height > this.y){
p.collide(this);
}
}
}
if(!this.talajon){
this.velocity_y-=1;
}
if(keys[KEY_DOWN]){
this.currentImg=this.crouch;
this.height=this.crouchHeight;
}else{
this.currentImg=this.img;
this.height=this.standingHeight;
}
};
avatar.prototype.draw=function(context, t){
context.drawImage(this.currentImg, t.tX(this.x), t.tY(this.y)-this.standingHeight);
};<|fim▁end|> |
this.platformCheck();
|
<|file_name|>instr_vpackssdw.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vpackssdw_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM1)), operand3: Some(Direct(XMM4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 241, 107, 236], OperandSize::Dword)
}
#[test]
fn vpackssdw_2() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM6)), operand3: Some(Indirect(EBX, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 201, 107, 27], OperandSize::Dword)
}
#[test]
fn vpackssdw_3() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM6)), operand3: Some(Direct(XMM7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 201, 107, 231], OperandSize::Qword)
}
#[test]
fn vpackssdw_4() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM1)), operand3: Some(IndirectDisplaced(RDX, 574201896, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 241, 107, 162, 40, 160, 57, 34], OperandSize::Qword)
}
#[test]
fn vpackssdw_5() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM3)), operand3: Some(Direct(YMM2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 229, 107, 218], OperandSize::Dword)
}
#[test]
fn vpackssdw_6() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(YMM2)), operand2: Some(Direct(YMM1)), operand3: Some(IndirectScaledDisplaced(EDX, Two, 1765361270, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 245, 107, 20, 85, 118, 70, 57, 105], OperandSize::Dword)
}
#[test]
fn vpackssdw_7() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(YMM3)), operand2: Some(Direct(YMM1)), operand3: Some(Direct(YMM2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 245, 107, 218], OperandSize::Qword)
}
#[test]<|fim▁hole|>#[test]
fn vpackssdw_9() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM3)), operand3: Some(Direct(XMM2)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 241, 101, 143, 107, 242], OperandSize::Dword)
}
#[test]
fn vpackssdw_10() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM1)), operand3: Some(IndirectScaledDisplaced(EBX, Four, 693519999, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 241, 117, 143, 107, 52, 157, 127, 70, 86, 41], OperandSize::Dword)
}
#[test]
fn vpackssdw_11() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM7)), operand3: Some(IndirectScaledIndexed(EDI, EAX, Two, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: Some(BroadcastMode::Broadcast1To4) }, &[98, 241, 69, 156, 107, 60, 71], OperandSize::Dword)
}
#[test]
fn vpackssdw_12() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM15)), operand3: Some(Direct(XMM18)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 177, 5, 138, 107, 218], OperandSize::Qword)
}
#[test]
fn vpackssdw_13() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM20)), operand3: Some(IndirectScaledDisplaced(RCX, Eight, 870052923, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 241, 93, 131, 107, 28, 205, 59, 244, 219, 51], OperandSize::Qword)
}
#[test]
fn vpackssdw_14() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(XMM15)), operand2: Some(Direct(XMM29)), operand3: Some(IndirectDisplaced(RBX, 281710896, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: Some(BroadcastMode::Broadcast1To4) }, &[98, 113, 21, 148, 107, 187, 48, 145, 202, 16], OperandSize::Qword)
}<|fim▁end|> | fn vpackssdw_8() {
run_test(&Instruction { mnemonic: Mnemonic::VPACKSSDW, operand1: Some(Direct(YMM1)), operand2: Some(Direct(YMM0)), operand3: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 918132910, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 253, 107, 140, 202, 174, 152, 185, 54], OperandSize::Qword)
}
|
<|file_name|>startRust.rs<|end_file_name|><|fim▁begin|>use std::thread;
fn main() {
let han: Vec<_> = (0..10).into_iter()
.map( |t| { thread::spawn(move || { println!("Hello world from {}", t);
thread::sleep_ms(5000)}) })
.collect();
<|fim▁hole|>
}<|fim▁end|> | for h in han {
h.join().unwrap();
} |
<|file_name|>steps124.go<|end_file_name|><|fim▁begin|>// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package upgrades
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/juju/juju/state"
)
// stateStepsFor124 returns upgrade steps for Juju 1.24 that manipulate state directly.
func stateStepsFor124() []Step {
return []Step{
&upgradeStep{
description: "add block device documents for existing machines",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return state.AddDefaultBlockDevicesDocs(context.State())
}},
&upgradeStep{
description: "move service.UnitSeq to sequence collection",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return state.MoveServiceUnitSeqToSequence(context.State())
}},
&upgradeStep{
description: "add instance id field to IP addresses",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return state.AddInstanceIdFieldOfIPAddresses(context.State())
}},
&upgradeStep{
description: "add UUID field to IP addresses",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return state.AddUUIDToIPAddresses(context.State())
},
},
&upgradeStep{
description: "migrate charm archives into environment storage",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return migrateCharmStorage(context.State(), context.AgentConfig())
},
},
&upgradeStep{
description: "change entityid field on status history to globalkey",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return state.ChangeStatusHistoryEntityId(context.State())
},
},
&upgradeStep{
description: "change updated field on statushistory from time to int",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return state.ChangeStatusHistoryUpdatedType(context.State())
},
},
&upgradeStep{<|fim▁hole|> return state.ChangeStatusUpdatedType(context.State())
},
},
}
}
// stepsFor124 returns upgrade steps for Juju 1.24 that only need the API.
func stepsFor124() []Step {
return []Step{
&upgradeStep{
description: "move syslog config from LogDir to DataDir",
targets: []Target{AllMachines},
run: moveSyslogConfig,
},
}
}
// stateStepsFor1244 returns upgrade steps for Juju 1.24.4 that manipulate state directly.
func stateStepsFor1244() []Step {
return []Step{
&upgradeStep{
description: "add missing service statuses",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return state.AddMissingServiceStatuses(context.State())
},
},
}
}
func moveSyslogConfig(context Context) error {
config := context.AgentConfig()
logdir := config.LogDir()
datadir := config.DataDir()
// these values were copied from
// github.com/juju/juju/utils/syslog/config.go
// Yes this is bad, but it is only needed once every for an
// upgrade, so it didn't seem worth exporting those values.
files := []string{
"ca-cert.pem",
"rsyslog-cert.pem",
"rsyslog-key.pem",
"logrotate.conf",
"logrotate.run",
}
var errs []string
for _, f := range files {
oldpath := filepath.Join(logdir, f)
newpath := filepath.Join(datadir, f)
if err := copyFile(newpath, oldpath); err != nil {
errs = append(errs, err.Error())
continue
}
if err := osRemove(oldpath); err != nil {
// Don't fail the step if we can't get rid of the old files.
// We don't actually care if they still exist or not.
logger.Warningf("Can't delete old config file %q: %s", oldpath, err)
}
}
if len(errs) > 0 {
return fmt.Errorf("error(s) while moving old syslog config files: %s", strings.Join(errs, "\n"))
}
return nil
}
// for testing... of course.
var osRemove = os.Remove
// copyFile copies a file from one location to another. It won't overwrite
// existing files and will return nil in this case. This is used instead of
// os.Rename because os.Rename won't work across partitions.
func copyFile(to, from string) error {
logger.Debugf("Copying %q to %q", from, to)
orig, err := os.Open(from)
if os.IsNotExist(err) {
logger.Debugf("Old file %q does not exist, skipping.", from)
// original doesn't exist, that's fine.
return nil
}
if err != nil {
return err
}
defer orig.Close()
info, err := orig.Stat()
if err != nil {
return err
}
target, err := os.OpenFile(to, os.O_CREATE|os.O_WRONLY|os.O_EXCL, info.Mode())
if os.IsExist(err) {
return nil
}
defer target.Close()
if _, err := io.Copy(target, orig); err != nil {
return err
}
return nil
}<|fim▁end|> | description: "change updated field on status from time to int",
targets: []Target{DatabaseMaster},
run: func(context Context) error { |
<|file_name|>article-min.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | /*! fabrik */
var FbListArticle=new Class({Extends:FbListPlugin}); |
<|file_name|>layout_image.rs<|end_file_name|><|fim▁begin|>/* 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/. */
//! Infrastructure to initiate network requests for images needed by the layout
//! thread. The script thread needs to be responsible for them because there's
//! no guarantee that the responsible nodes will still exist in the future if the
//! layout thread holds on to them during asynchronous operations.
use dom::bindings::reflector::DomObject;
use dom::node::{Node, document_from_node};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::{FetchResponseMsg, FetchResponseListener, FetchMetadata, NetworkError};
use net_traits::image_cache::{ImageCache, PendingImageId};
use net_traits::request::{Destination, RequestInit as FetchRequestInit};
use network_listener::{NetworkListener, PreInvoke};
use servo_url::ServoUrl;
use std::sync::{Arc, Mutex};
use task_source::TaskSourceName;
struct LayoutImageContext {
id: PendingImageId,
cache: Arc<ImageCache>,
}
impl FetchResponseListener for LayoutImageContext {
fn process_request_body(&mut self) {}
fn process_request_eof(&mut self) {}
fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) {
self.cache
.notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata));
}
fn process_response_chunk(&mut self, payload: Vec<u8>) {
self.cache
.notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload));
}
fn process_response_eof(&mut self, response: Result<(), NetworkError>) {
self.cache
.notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response));
}
}
impl PreInvoke for LayoutImageContext {}
pub fn fetch_image_for_layout(
url: ServoUrl,
node: &Node,
id: PendingImageId,
cache: Arc<ImageCache>,
) {
let context = Arc::new(Mutex::new(LayoutImageContext {
id: id,
cache: cache,
}));
let document = document_from_node(node);
let window = document.window();
<|fim▁hole|> context: context,
task_source: window.networking_task_source(),
canceller: Some(window.task_canceller(TaskSourceName::Networking)),
};
ROUTER.add_route(
action_receiver.to_opaque(),
Box::new(move |message| {
listener.notify_fetch(message.to().unwrap());
}),
);
let request = FetchRequestInit {
url: url,
origin: document.origin().immutable().clone(),
destination: Destination::Image,
pipeline_id: Some(document.global().pipeline_id()),
..FetchRequestInit::default()
};
// Layout image loads do not delay the document load event.
document
.loader_mut()
.fetch_async_background(request, action_sender);
}<|fim▁end|> | let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener { |
<|file_name|>pages.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright(C) 2014 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import re
from decimal import Decimal
from datetime import datetime
from weboob.browser.filters.json import Dict
from weboob.browser.elements import ItemElement, ListElement, method
from weboob.browser.pages import JsonPage, HTMLPage, pagination
from weboob.browser.filters.standard import CleanText, CleanDecimal, Regexp, Env, BrowserURL, Filter, Format
from weboob.browser.filters.html import CleanHTML, XPath
from weboob.capabilities.base import NotAvailable, NotLoaded
from weboob.capabilities.housing import Housing, HousingPhoto, City
class DictElement(ListElement):
def find_elements(self):
for el in self.el[0].get(self.item_xpath):
yield el
class CitiesPage(JsonPage):
@method
class get_cities(DictElement):
item_xpath = 'locations'
class item(ItemElement):
klass = City
obj_id = Dict('label')
obj_name = Dict('label')
class SearchPage(HTMLPage):
@pagination
@method
class iter_housings(ListElement):
item_xpath = '//div[starts-with(@id, "bloc-vue-")]'
def next_page(self):
js_datas = CleanText('//div[@id="js-data"]/@data-rest-search-request')(self)
total_page = self.page.browser.get_total_page(js_datas.split('?')[-1])
m = re.match(".*page=(\d?)(?:&.*)?", self.page.url)
if m:
current_page = int(m.group(1))
next_page = current_page + 1
if next_page <= total_page:
return self.page.url.replace('page=%d' % current_page, 'page=%d' % next_page)
class item(ItemElement):
klass = Housing
obj_id = CleanText('./@data-classified-id')
obj_title = CleanText('./div/h2[@itemprop="name"]/a')
obj_location = CleanText('./div/h2[@itemprop="name"]/span[class="item-localisation"]')
obj_cost = CleanDecimal('./div/div/span[@class="price-label"]')
obj_currency = Regexp(CleanText('./div/div/span[@class="price-label"]'),
'.*([%s%s%s])' % (u'€', u'$', u'£'), default=u'€')
obj_text = CleanText('./div/div/div[@itemprop="description"]')
obj_area = CleanDecimal(Regexp(CleanText('./div/h2[@itemprop="name"]/a'),
'(.*?)(\d*) m2(.*?)', '\\2', default=None),
default=NotAvailable)
def obj_phone(self):
phone = CleanText('./div/div/ul/li/span[@class="js-clickphone"]',
replace=[(u'Téléphoner : ', u'')],
default=NotAvailable)(self)
if '...' in phone:
return NotLoaded
return phone
def obj_photos(self):
url = CleanText('./div/div/a/img[@itemprop="image"]/@src')(self)
return [HousingPhoto(url)]
class TypeDecimal(Filter):
def filter(self, el):
return Decimal(el)
class FromTimestamp(Filter):
def filter(self, el):
return datetime.fromtimestamp(el / 1000.0)
class PhonePage(JsonPage):
def get_phone(self):
return self.doc.get('phoneNumber')
class HousingPage2(JsonPage):
@method
class get_housing(ItemElement):
klass = Housing
obj_id = Env('_id')
obj_title = Dict('characteristics/titleWithTransaction')
obj_location = Format('%s %s %s', Dict('location/address'),
Dict('location/postalCode'), Dict('location/cityLabel'))
obj_cost = TypeDecimal(Dict('characteristics/price'))
obj_currency = u'€'
obj_text = CleanHTML(Dict('characteristics/description'))
obj_url = BrowserURL('housing_html', _id=Env('_id'))
obj_area = TypeDecimal(Dict('characteristics/area'))<|fim▁hole|>
def obj_photos(self):
photos = []
for img in Dict('characteristics/images')(self):
m = re.search('http://thbr\.figarocms\.net.*(http://.*)', img)
if m:
photos.append(HousingPhoto(m.group(1)))
return photos
def obj_details(self):
details = {}
details['fees'] = Dict('characteristics/fees')(self)
details['bedrooms'] = Dict('characteristics/bedroomCount')(self)
details['energy'] = Dict('characteristics/energyConsumptionCategory')(self)
rooms = Dict('characteristics/roomCount')(self)
if len(rooms):
details['rooms'] = rooms[0]
details['available'] = Dict('characteristics/available')(self)
return details
def get_total_page(self):
return self.doc.get('pagination').get('total')
class HousingPage(HTMLPage):
@method
class get_housing(ItemElement):
klass = Housing
obj_id = Env('_id')
obj_title = CleanText('//h1[@itemprop="name"]')
obj_location = CleanText('//span[@class="informations-localisation"]')
obj_cost = CleanDecimal('//span[@itemprop="price"]')
obj_currency = Regexp(CleanText('//span[@itemprop="price"]'),
'.*([%s%s%s])' % (u'€', u'$', u'£'), default=u'€')
obj_text = CleanHTML('//div[@itemprop="description"]')
obj_url = BrowserURL('housing', _id=Env('_id'))
obj_area = CleanDecimal(Regexp(CleanText('//h1[@itemprop="name"]'),
'(.*?)(\d*) m2(.*?)', '\\2'), default=NotAvailable)
def obj_photos(self):
photos = []
for img in XPath('//a[@class="thumbnail-link"]/img[@itemprop="image"]')(self):
url = Regexp(CleanText('./@src'), 'http://thbr\.figarocms\.net.*(http://.*)')(img)
photos.append(HousingPhoto(url))
return photos
def obj_details(self):
details = dict()
for item in XPath('//div[@class="features clearfix"]/ul/li')(self):
key = CleanText('./span[@class="name"]')(item)
value = CleanText('./span[@class="value"]')(item)
if value and key:
details[key] = value
key = CleanText('//div[@class="title-dpe clearfix"]')(self)
value = CleanText('//div[@class="energy-consumption"]')(self)
if value and key:
details[key] = value
return details<|fim▁end|> | obj_date = FromTimestamp(Dict('characteristics/date')) |
<|file_name|>grunt.py<|end_file_name|><|fim▁begin|>import socket
import poormanslogging as log
LISTENPORT = 6666
class Grunt(object):
def __init__(self):
try:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind(('', LISTENPORT))
self.s.listen(1)
log.info('Waiting for orders on port {}'.format(LISTENPORT))
(c, a) = self.s.accept()
self._receive_orders(c)
finally:
log.info('Shutting down')
self.s.close()
def _receive_orders(self, sock):
chunks = []
while 1:
try:
chunks.append(self.s.recv(1024))<|fim▁hole|> print("Message:")
print(msg)<|fim▁end|> | except OSError:
break
msg = b''.join(chunks) |
<|file_name|>asm-out-read-uninit.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-fast #[feature] doesn't work with check-fast
#![feature(asm)]
fn foo(x: int) { println!("{}", x); }
<|fim▁hole|>#[cfg(target_arch = "arm")]
pub fn main() {
let x: int;
unsafe {
asm!("mov $1, $0" : "=r"(x) : "r"(x)); //~ ERROR use of possibly uninitialized variable: `x`
}
foo(x);
}
#[cfg(not(target_arch = "x86"), not(target_arch = "x86_64"), not(target_arch = "arm"))]
pub fn main() {}<|fim▁end|> | #[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86_64")] |
<|file_name|>operations.py<|end_file_name|><|fim▁begin|>def rewrite_keywords(journal_like):<|fim▁hole|> return journal_like<|fim▁end|> | bib = journal_like.bibjson()
kwords = [k.lower() for k in bib.keywords]
bib.set_keywords(kwords) |
<|file_name|>test_aggregate.py<|end_file_name|><|fim▁begin|># Copyright 2013 IBM Corp.
#
# 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.
import mock
from oslo_utils import timeutils
from nova import db
from nova import exception
from nova.objects import aggregate
from nova.tests.unit import fake_notifier
from nova.tests.unit.objects import test_objects
from nova.tests import uuidsentinel
NOW = timeutils.utcnow().replace(microsecond=0)
fake_aggregate = {
'created_at': NOW,
'updated_at': None,
'deleted_at': None,
'deleted': False,
'id': 123,
'uuid': uuidsentinel.fake_aggregate,
'name': 'fake-aggregate',
'hosts': ['foo', 'bar'],
'metadetails': {'this': 'that'},
}
SUBS = {'metadata': 'metadetails'}
class _TestAggregateObject(object):
def test_get_by_id(self):
self.mox.StubOutWithMock(db, 'aggregate_get')
db.aggregate_get(self.context, 123).AndReturn(fake_aggregate)
self.mox.ReplayAll()
agg = aggregate.Aggregate.get_by_id(self.context, 123)
self.compare_obj(agg, fake_aggregate, subs=SUBS)
@mock.patch('nova.objects.Aggregate.save')
@mock.patch('nova.db.aggregate_get')
def test_load_allocates_uuid(self, mock_get, mock_save):
fake_agg = dict(fake_aggregate)
del fake_agg['uuid']
mock_get.return_value = fake_agg
uuid = uuidsentinel.aggregate
with mock.patch('oslo_utils.uuidutils.generate_uuid') as mock_g:
mock_g.return_value = uuid
obj = aggregate.Aggregate.get_by_id(self.context, 123)
mock_g.assert_called_once_with()
self.assertEqual(uuid, obj.uuid)
mock_save.assert_called_once_with()
def test_create(self):
self.mox.StubOutWithMock(db, 'aggregate_create')
db.aggregate_create(self.context, {'name': 'foo',
'uuid': uuidsentinel.fake_agg},
metadata={'one': 'two'}).AndReturn(fake_aggregate)
self.mox.ReplayAll()
agg = aggregate.Aggregate(context=self.context)
agg.name = 'foo'
agg.metadata = {'one': 'two'}
agg.uuid = uuidsentinel.fake_agg
agg.create()
self.compare_obj(agg, fake_aggregate, subs=SUBS)
def test_recreate_fails(self):
self.mox.StubOutWithMock(db, 'aggregate_create')
db.aggregate_create(self.context, {'name': 'foo',
'uuid': uuidsentinel.fake_agg},
metadata={'one': 'two'}).AndReturn(fake_aggregate)
self.mox.ReplayAll()
agg = aggregate.Aggregate(context=self.context)
agg.name = 'foo'
agg.metadata = {'one': 'two'}
agg.uuid = uuidsentinel.fake_agg
agg.create()
self.assertRaises(exception.ObjectActionError, agg.create)
def test_save(self):
self.mox.StubOutWithMock(db, 'aggregate_update')
db.aggregate_update(self.context, 123, {'name': 'baz'}).AndReturn(
fake_aggregate)
self.mox.ReplayAll()
agg = aggregate.Aggregate(context=self.context)
agg.id = 123
agg.name = 'baz'
agg.save()
self.compare_obj(agg, fake_aggregate, subs=SUBS)
def test_save_and_create_no_hosts(self):
agg = aggregate.Aggregate(context=self.context)
agg.id = 123
agg.hosts = ['foo', 'bar']
self.assertRaises(exception.ObjectActionError,
agg.create)
self.assertRaises(exception.ObjectActionError,
agg.save)
def test_update_metadata(self):
self.mox.StubOutWithMock(db, 'aggregate_metadata_delete')
self.mox.StubOutWithMock(db, 'aggregate_metadata_add')
db.aggregate_metadata_delete(self.context, 123, 'todelete')
db.aggregate_metadata_add(self.context, 123, {'toadd': 'myval'})
self.mox.ReplayAll()
fake_notifier.NOTIFICATIONS = []
agg = aggregate.Aggregate()
agg._context = self.context
agg.id = 123
agg.metadata = {'foo': 'bar'}
agg.obj_reset_changes()
agg.update_metadata({'todelete': None, 'toadd': 'myval'})
self.assertEqual(2, len(fake_notifier.NOTIFICATIONS))
msg = fake_notifier.NOTIFICATIONS[0]
self.assertEqual('aggregate.updatemetadata.start', msg.event_type)
self.assertEqual({'todelete': None, 'toadd': 'myval'},
msg.payload['meta_data'])
msg = fake_notifier.NOTIFICATIONS[1]
self.assertEqual('aggregate.updatemetadata.end', msg.event_type)
self.assertEqual({'todelete': None, 'toadd': 'myval'},
msg.payload['meta_data'])
self.assertEqual({'foo': 'bar', 'toadd': 'myval'}, agg.metadata)
def test_destroy(self):
self.mox.StubOutWithMock(db, 'aggregate_delete')
db.aggregate_delete(self.context, 123)
self.mox.ReplayAll()
agg = aggregate.Aggregate(context=self.context)
agg.id = 123
agg.destroy()
def test_add_host(self):
self.mox.StubOutWithMock(db, 'aggregate_host_add')
db.aggregate_host_add(self.context, 123, 'bar'
).AndReturn({'host': 'bar'})
self.mox.ReplayAll()
agg = aggregate.Aggregate()
agg.id = 123
agg.hosts = ['foo']
agg._context = self.context
agg.add_host('bar')
self.assertEqual(agg.hosts, ['foo', 'bar'])
def test_delete_host(self):
self.mox.StubOutWithMock(db, 'aggregate_host_delete')
db.aggregate_host_delete(self.context, 123, 'foo')
self.mox.ReplayAll()
agg = aggregate.Aggregate()
agg.id = 123
agg.hosts = ['foo', 'bar']
agg._context = self.context
agg.delete_host('foo')
self.assertEqual(agg.hosts, ['bar'])<|fim▁hole|>
def test_availability_zone(self):
agg = aggregate.Aggregate()
agg.metadata = {'availability_zone': 'foo'}
self.assertEqual('foo', agg.availability_zone)
def test_get_all(self):
self.mox.StubOutWithMock(db, 'aggregate_get_all')
db.aggregate_get_all(self.context).AndReturn([fake_aggregate])
self.mox.ReplayAll()
aggs = aggregate.AggregateList.get_all(self.context)
self.assertEqual(1, len(aggs))
self.compare_obj(aggs[0], fake_aggregate, subs=SUBS)
def test_by_host(self):
self.mox.StubOutWithMock(db, 'aggregate_get_by_host')
db.aggregate_get_by_host(self.context, 'fake-host', key=None,
).AndReturn([fake_aggregate])
self.mox.ReplayAll()
aggs = aggregate.AggregateList.get_by_host(self.context, 'fake-host')
self.assertEqual(1, len(aggs))
self.compare_obj(aggs[0], fake_aggregate, subs=SUBS)
@mock.patch('nova.db.aggregate_get_by_metadata_key')
def test_get_by_metadata_key(self, get_by_metadata_key):
get_by_metadata_key.return_value = [fake_aggregate]
aggs = aggregate.AggregateList.get_by_metadata_key(
self.context, 'this')
self.assertEqual(1, len(aggs))
self.compare_obj(aggs[0], fake_aggregate, subs=SUBS)
@mock.patch('nova.db.aggregate_get_by_metadata_key')
def test_get_by_metadata_key_and_hosts_no_match(self, get_by_metadata_key):
get_by_metadata_key.return_value = [fake_aggregate]
aggs = aggregate.AggregateList.get_by_metadata_key(
self.context, 'this', hosts=['baz'])
self.assertEqual(0, len(aggs))
@mock.patch('nova.db.aggregate_get_by_metadata_key')
def test_get_by_metadata_key_and_hosts_match(self, get_by_metadata_key):
get_by_metadata_key.return_value = [fake_aggregate]
aggs = aggregate.AggregateList.get_by_metadata_key(
self.context, 'this', hosts=['foo', 'bar'])
self.assertEqual(1, len(aggs))
self.compare_obj(aggs[0], fake_aggregate, subs=SUBS)
class TestAggregateObject(test_objects._LocalTest,
_TestAggregateObject):
pass
class TestRemoteAggregateObject(test_objects._RemoteTest,
_TestAggregateObject):
pass<|fim▁end|> | |
<|file_name|>route.js<|end_file_name|><|fim▁begin|>import { inject as service } from '@ember/service';
import Route from '@ember/routing/route';
import { get } from '@ember/object';
export default Route.extend({
access: service(),
catalog: service(),<|fim▁hole|>
beforeModel() {
this._super(...arguments);
return get(this, 'catalog').fetchUnScopedCatalogs().then((hash) => {
this.set('catalogs', hash);
});
},
model(params) {
return get(this, 'catalog').fetchTemplates(params)
.then((res) => {
res.catalogs = get(this, 'catalogs');
return res;
});
},
resetController(controller, isExiting/* , transition*/) {
if (isExiting) {
controller.setProperties({
category: '',
catalogId: '',
projectCatalogId: '',
clusterCatalogId: '',
})
}
},
deactivate() {
// Clear the cache when leaving the route so that it will be reloaded when you come back.
this.set('cache', null);
},
actions: {
refresh() {
// Clear the cache so it has to ask the server again
this.set('cache', null);
this.refresh();
},
},
queryParams: {
category: { refreshModel: true },
catalogId: { refreshModel: true },
clusterCatalogId: { refreshModel: true },
projectCatalogId: { refreshModel: true },
},
});<|fim▁end|> | scope: service(), |
<|file_name|>speech.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 One Laptop Per Child
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import os
import logging
from gi.repository import GConf
from gi.repository import Gst
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
DEFAULT_PITCH = 0
DEFAULT_RATE = 0
_speech_manager = None
class SpeechManager(GObject.GObject):
__gtype_name__ = 'SpeechManager'
__gsignals__ = {
'play': (GObject.SignalFlags.RUN_FIRST, None, []),
'pause': (GObject.SignalFlags.RUN_FIRST, None, []),
'stop': (GObject.SignalFlags.RUN_FIRST, None, [])
}
MIN_PITCH = -100
MAX_PITCH = 100
MIN_RATE = -100
MAX_RATE = 100
def __init__(self, **kwargs):
GObject.GObject.__init__(self, **kwargs)
self._player = _GstSpeechPlayer()
self._player.connect('play', self._update_state, 'play')
self._player.connect('stop', self._update_state, 'stop')
self._player.connect('pause', self._update_state, 'pause')
self._voice_name = self._player.get_default_voice()
self._pitch = DEFAULT_PITCH
self._rate = DEFAULT_RATE
self._is_playing = False
self._is_paused = False
self.restore()
def _update_state(self, player, signal):
self._is_playing = (signal == 'play')
self._is_paused = (signal == 'pause')
self.emit(signal)
def get_is_playing(self):
return self._is_playing
is_playing = GObject.property(type=bool, getter=get_is_playing,
setter=None, default=False)
def get_is_paused(self):
return self._is_paused
is_paused = GObject.property(type=bool, getter=get_is_paused,
setter=None, default=False)
def get_pitch(self):
return self._pitch
def get_rate(self):
return self._rate
def set_pitch(self, pitch):
self._pitch = pitch
self.save()
def set_rate(self, rate):<|fim▁hole|> if text:
self._player.speak(self._pitch, self._rate, self._voice_name, text)
def say_selected_text(self):
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY)
clipboard.request_text(self.__primary_selection_cb, None)
def pause(self):
self._player.pause_sound_device()
def restart(self):
self._player.restart_sound_device()
def stop(self):
self._player.stop_sound_device()
def __primary_selection_cb(self, clipboard, text, user_data):
self.say_text(text)
def save(self):
client = GConf.Client.get_default()
client.set_int('/desktop/sugar/speech/pitch', self._pitch)
client.set_int('/desktop/sugar/speech/rate', self._rate)
logging.debug('saving speech configuration pitch %s rate %s',
self._pitch, self._rate)
def restore(self):
client = GConf.Client.get_default()
self._pitch = client.get_int('/desktop/sugar/speech/pitch')
self._rate = client.get_int('/desktop/sugar/speech/rate')
logging.debug('loading speech configuration pitch %s rate %s',
self._pitch, self._rate)
class _GstSpeechPlayer(GObject.GObject):
__gsignals__ = {
'play': (GObject.SignalFlags.RUN_FIRST, None, []),
'pause': (GObject.SignalFlags.RUN_FIRST, None, []),
'stop': (GObject.SignalFlags.RUN_FIRST, None, [])
}
def __init__(self):
GObject.GObject.__init__(self)
self._pipeline = None
def restart_sound_device(self):
if self._pipeline is None:
logging.debug('Trying to restart not initialized sound device')
return
self._pipeline.set_state(Gst.State.PLAYING)
self.emit('play')
def pause_sound_device(self):
if self._pipeline is None:
return
self._pipeline.set_state(Gst.State.PAUSED)
self.emit('pause')
def stop_sound_device(self):
if self._pipeline is None:
return
self._pipeline.set_state(Gst.State.NULL)
self.emit('stop')
def make_pipeline(self, command):
if self._pipeline is not None:
self.stop_sound_device()
del self._pipeline
self._pipeline = Gst.parse_launch(command)
bus = self._pipeline.get_bus()
bus.add_signal_watch()
bus.connect('message', self.__pipe_message_cb)
def __pipe_message_cb(self, bus, message):
if message.type == Gst.MessageType.EOS:
self._pipeline.set_state(Gst.State.NULL)
self.emit('stop')
elif message.type == Gst.MessageType.ERROR:
self._pipeline.set_state(Gst.State.NULL)
self.emit('stop')
def speak(self, pitch, rate, voice_name, text):
# TODO workaround for http://bugs.sugarlabs.org/ticket/1801
if not [i for i in text if i.isalnum()]:
return
self.make_pipeline('espeak name=espeak ! autoaudiosink')
src = self._pipeline.get_by_name('espeak')
src.props.text = text
src.props.pitch = pitch
src.props.rate = rate
src.props.voice = voice_name
src.props.track = 2 # track for marks
self.restart_sound_device()
def get_all_voices(self):
all_voices = {}
for voice in Gst.ElementFactory.make('espeak', None).props.voices:
name, language, dialect = voice
if dialect != 'none':
all_voices[language + '_' + dialect] = name
else:
all_voices[language] = name
return all_voices
def get_default_voice(self):
"""Try to figure out the default voice, from the current locale ($LANG)
Fall back to espeak's voice called Default."""
voices = self.get_all_voices()
locale = os.environ.get('LANG', '')
language_location = locale.split('.', 1)[0].lower()
language = language_location.split('_')[0]
# if the language is es but not es_es default to es_la (latin voice)
if language == 'es' and language_location != 'es_es':
language_location = 'es_la'
best = voices.get(language_location) or voices.get(language) \
or 'default'
logging.debug('Best voice for LANG %s seems to be %s',
locale, best)
return best
def get_speech_manager():
global _speech_manager
if _speech_manager is None:
_speech_manager = SpeechManager()
return _speech_manager<|fim▁end|> | self._rate = rate
self.save()
def say_text(self, text): |
<|file_name|>interpolate.py<|end_file_name|><|fim▁begin|>import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from scipy.interpolate import interp1d,splev,splrep
def extractSpectrum(filename):
"""
NAME:
extractSpectrum
PURPOSE:
To open an input fits file from SDSS and extract the relevant
components, namely the flux and corresponding wavelength.
INPUTS:
filename The path and filename (including the extension) to the
file to be read in.
OUTPUTS:
lam The wavelengths, in angstrom, of the flux values
flux The actual flux, in arbitrary units
EXAMPLE:
flux, lam = extractSpectra('path/to/file/filename.fits')
"""
hdu = fits.open(filename) #Open the file using astropy
data = hdu[1].data #Data is in 2nd component of HDU
flux = data['flux'] #Get flux from read in dict
lam = 10**(data['loglam']) #Get wavelength, make it not log10
hdu.close() #Close the file, we're done with it
return lam, flux #Return the values as numpy arrays
def interpolate(points, lam, flux, method):
"""
NAME:
interpolate
PURPOSE:
General purpose function that can call and use various scipy.interpolate
methods. Defined for convienience.
INPUTS:
points Set of new points to get interpolated values for.
lam The wavelengths of the data points
flux The fluxes of the data points
method The method of interpolation to use. Valide values include
'interp1d:linear', 'interp1d:quadratic', and 'splrep'.
OUTPUTS:
Interpolated set of values for each corresponding input point.
EXAMPLE:
interpFlux = interpolate(interpLam, lam, flux)
"""
if method == 'interp1d:linear':
f = interp1d(lam, flux, assume_sorted = True)
return f(points)
if method == 'interp1d:quadratic':
f = interp1d(lam, flux, kind = 'quadratic', assume_sorted = True)
return f(points)
if method == 'splrep':
return splev(points, splrep(lam, flux))
raise Exception("You didn't choose a proper interpolating method")
#First extract the flux and corresponding wavelength
<|fim▁hole|>#Now let's plot it, without any processing
plt.figure(1)
plt.plot(lam, flux, '-o', lw = 1.5, c = (0.694,0.906,0.561),
mec = 'none', ms = 4, label = 'Original data')
plt.xlabel('Wavelength', fontsize = 16)
plt.ylabel('Flux', fontsize = 16)
plt.ylim(0,1.1*max(flux))
#Now let's interpolate and plot that up
interpLam = np.arange(4000,10000,1)
interpFlux = interpolate(interpLam, lam, flux, 'splrep') #This is my own method
plt.plot(interpLam, interpFlux, '-k', label = 'Interpolated')
plt.legend(loc = 0)
plt.show(block = False)
print('Done...')<|fim▁end|> | fileName = 'spec-4053-55591-0938.fits'
lam, flux = extractSpectrum(fileName)
|
<|file_name|>PostShowPage.xaml.cpp<|end_file_name|><|fim▁begin|>//
// PostShowPage.xaml.cpp
// Implementation of the PostShowPage class
//
#include "pch.h"
#include "PostShowPage.xaml.h"
#include "PostPage.xaml.h"
#include "LoginPage.xaml.h"
#include "define.h"
using namespace GhostBlogClient;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Popups;
using namespace concurrency;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556
PostShowPage::PostShowPage()
{
InitializeComponent();
SetValue(_defaultViewModelProperty, ref new Platform::Collections::Map<String^, Object^>(std::less<String^>()));
auto navigationHelper = ref new Common::NavigationHelper(this);
SetValue(_navigationHelperProperty, navigationHelper);
navigationHelper->LoadState += ref new Common::LoadStateEventHandler(this, &PostShowPage::LoadState);
navigationHelper->SaveState += ref new Common::SaveStateEventHandler(this, &PostShowPage::SaveState);
}
DependencyProperty^ PostShowPage::_defaultViewModelProperty =
DependencyProperty::Register("DefaultViewModel",
TypeName(IObservableMap<String^, Object^>::typeid), TypeName(PostShowPage::typeid), nullptr);
/// <summary>
/// Used as a trivial view model.
/// </summary>
IObservableMap<String^, Object^>^ PostShowPage::DefaultViewModel::get()
{
return safe_cast<IObservableMap<String^, Object^>^>(GetValue(_defaultViewModelProperty));
}
DependencyProperty^ PostShowPage::_navigationHelperProperty =
DependencyProperty::Register("NavigationHelper",
TypeName(Common::NavigationHelper::typeid), TypeName(PostShowPage::typeid), nullptr);
/// <summary>
/// Gets an implementation of <see cref="NavigationHelper"/> designed to be
/// used as a trivial view model.
/// </summary>
Common::NavigationHelper^ PostShowPage::NavigationHelper::get()
{
return safe_cast<Common::NavigationHelper^>(GetValue(_navigationHelperProperty));
}
#pragma region Navigation support
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="NavigationHelper::LoadState"/>
/// and <see cref="NavigationHelper::SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
void PostShowPage::OnNavigatedTo(NavigationEventArgs^ e)
{
NavigationHelper->OnNavigatedTo(e);
}
void PostShowPage::OnNavigatedFrom(NavigationEventArgs^ e)
{
NavigationHelper->OnNavigatedFrom(e);
}
#pragma endregion
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
void PostShowPage::LoadState(Object^ sender, Common::LoadStateEventArgs^ e)
{
(void) sender; // Unused parameter
(void) e; // Unused parameter
if (e != nullptr && e->NavigationParameter != nullptr) {
blogAll = safe_cast<BlogAll^>(e->NavigationParameter);
ghostClient = blogAll->GhostClient;
currentPost = blogAll->ShowPost;
StartWaiting();
create_task(blogAll->FormatPostToHtml(currentPost))
.then([this](String^ html)
{
PostShowWebView->NavigateToString(html);
FinishWaiting();
});
}
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager::SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
void PostShowPage::SaveState(Object^ sender, Common::SaveStateEventArgs^ e){
(void) sender; // Unused parameter
(void) e; // Unused parameter
}
void PostShowPage::StartWaiting()
{
PostShowCommandBar->IsEnabled = false;
}
void PostShowPage::FinishWaiting()
{
PostShowCommandBar->IsEnabled = true;
}
void PostShowPage::PostShowDeleteButtonClick(Object^ sender, RoutedEventArgs^ e)
{
SubmitDeleteRequest(false, currentPost->Id);
}
void PostShowPage::SubmitDeleteRequest(bool needRefresh, int postId)
{
StartWaiting();
IAsyncOperation<Boolean>^ bOpe;
if (needRefresh) {
bOpe = ghostClient->RefreshAuthToken();
}
else {
bOpe = blogAll->GetBooleanAsyncOperation();
}
create_task(bOpe)
.then([=](Boolean resp)
{
return ghostClient->DeletePost(postId);
}).then([this](PostInfo^ p)
{
blogAll->DeletePost(currentPost);
auto dialog = ref new MessageDialog("删除成功");
return dialog->ShowAsync();
}).then([=](IUICommand^ resp) {
this->FinishWaiting();
NavigationHelper->GoBack();
}).then([=](task<void> prevTask) {
try
{
prevTask.get();
}
catch (Exception ^ex)
{
if (ghostClient->ErrorMsg->ErrorKind == GHOST_AUTH_ERROR)
{
if (!needRefresh) {
this->SubmitDeleteRequest(true, postId);
return;
}
else {
// 需要重新登录
this->FinishWaiting();
this->NeedReLogin();
return;
}
}
this->FinishWaiting();
String^ errMsg = ghostClient->ErrorMsg->GetErrorMessge(ex);
auto dialog = ref new MessageDialog(errMsg, "删除失败");
dialog->ShowAsync();
}
});<|fim▁hole|> if (blogAll->EditPost == nullptr) {
blogAll->EditPost = ref new PostInfo;
}
blogAll->EditPost->SetData(blogAll->ShowPost);
this->Frame->Navigate(TypeName(PostPage::typeid), blogAll);
}
void PostShowPage::SubmitRefreshRequest(bool needRefresh, int postId)
{
IAsyncOperation<Boolean>^ bOpe;
if (!needRefresh) {
StartWaiting();
bOpe = blogAll->GetBooleanAsyncOperation();
}
else {
bOpe = ghostClient->RefreshAuthToken();
}
create_task(bOpe)
.then([=](Boolean resp)
{
return ghostClient->GetPost(postId);
}).then([this](PostInfo^ p)
{
blogAll->AddPost(p, false);
blogAll->ShowPost = p;
currentPost = p;
return blogAll->FormatPostToHtml(p);
}).then([this](String^ html)
{
PostShowWebView->NavigateToString(html);
FinishWaiting();
}).then([=](task<void> prevTask) {
try
{
prevTask.get();
}
catch (Exception ^ex)
{
if (ghostClient->ErrorMsg->ErrorKind == GHOST_AUTH_ERROR)
{
if (!needRefresh) {
this->SubmitDeleteRequest(true, postId);
return;
}
else {
// 需要重新登录
this->FinishWaiting();
this->NeedReLogin();
return;
}
}
this->FinishWaiting();
String^ errMsg = ghostClient->ErrorMsg->GetErrorMessge(ex);
auto dialog = ref new MessageDialog(errMsg, "刷新失败");
dialog->ShowAsync();
}
});
}
void PostShowPage::PostShowRefreshButtonClick(Object^ sender, RoutedEventArgs^ e)
{
SubmitRefreshRequest(false, currentPost->Id);
}
void PostShowPage::NeedReLogin()
{
auto dialog = ref new MessageDialog("操作失败,Token 过时,需要重新登陆");
create_task(dialog->ShowAsync())
.then([this](IUICommand^ resp)
{
blogAll->OnlyLogin = true;
if (this->Frame != nullptr)
{
this->Frame->Navigate(TypeName(LoginPage::typeid), blogAll);
}
}).then([=](task<void> prevTask) {
try
{
prevTask.get();
}
catch (Exception ^ex)
{
}
});
}<|fim▁end|> | }
void PostShowPage::PostShowEditButtonClick(Object^ sender, RoutedEventArgs^ e)
{ |
<|file_name|>len_zero.rs<|end_file_name|><|fim▁begin|>use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::{get_item_name, get_parent_as_impl, is_lint_allowed};
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
use rustc_hir::def_id::DefIdSet;
use rustc_hir::{
def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
ItemKind, Mutability, Node, TraitItemRef, TyKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, AssocKind, FnSig, Ty, TyS};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{
source_map::{Span, Spanned, Symbol},
symbol::sym,
};
declare_clippy_lint! {
/// ### What it does
/// Checks for getting the length of something via `.len()`
/// just to compare to zero, and suggests using `.is_empty()` where applicable.
///
/// ### Why is this bad?
/// Some structures can answer `.is_empty()` much faster
/// than calculating their length. So it is good to get into the habit of using
/// `.is_empty()`, and having it is cheap.
/// Besides, it makes the intent clearer than a manual comparison in some contexts.
///
/// ### Example
/// ```ignore
/// if x.len() == 0 {
/// ..
/// }
/// if y.len() != 0 {
/// ..
/// }
/// ```
/// instead use
/// ```ignore
/// if x.is_empty() {
/// ..
/// }
/// if !y.is_empty() {
/// ..
/// }
/// ```
pub LEN_ZERO,
style,
"checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for items that implement `.len()` but not
/// `.is_empty()`.
///
/// ### Why is this bad?
/// It is good custom to have both methods, because for
/// some data structures, asking about the length will be a costly operation,
/// whereas `.is_empty()` can usually answer in constant time. Also it used to
/// lead to false positives on the [`len_zero`](#len_zero) lint – currently that
/// lint will ignore such entities.
///
/// ### Example
/// ```ignore
/// impl X {
/// pub fn len(&self) -> usize {
/// ..
/// }
/// }
/// ```
pub LEN_WITHOUT_IS_EMPTY,
style,
"traits or impls with a public `len` method but no corresponding `is_empty` method"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for comparing to an empty slice such as `""` or `[]`,
/// and suggests using `.is_empty()` where applicable.
///
/// ### Why is this bad?
/// Some structures can answer `.is_empty()` much faster
/// than checking for equality. So it is good to get into the habit of using
/// `.is_empty()`, and having it is cheap.
/// Besides, it makes the intent clearer than a manual comparison in some contexts.
///
/// ### Example
///
/// ```ignore
/// if s == "" {
/// ..
/// }
///
/// if arr == [] {
/// ..
/// }
/// ```
/// Use instead:
/// ```ignore
/// if s.is_empty() {
/// ..
/// }
///
/// if arr.is_empty() {
/// ..
/// }
/// ```
pub COMPARISON_TO_EMPTY,
style,
"checking `x == \"\"` or `x == []` (or similar) when `.is_empty()` could be used instead"
}
declare_lint_pass!(LenZero => [LEN_ZERO, LEN_WITHOUT_IS_EMPTY, COMPARISON_TO_EMPTY]);
impl<'tcx> LateLintPass<'tcx> for LenZero {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
if item.span.from_expansion() {
return;
}
if let ItemKind::Trait(_, _, _, _, trait_items) = item.kind {
check_trait_items(cx, item, trait_items);
}
}
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
if_chain! {
if item.ident.name == sym::len;
if let ImplItemKind::Fn(sig, _) = &item.kind;
if sig.decl.implicit_self.has_implicit_self();
if cx.access_levels.is_exported(item.def_id);
if matches!(sig.decl.output, FnRetTy::Return(_));
if let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id());
if imp.of_trait.is_none();
if let TyKind::Path(ty_path) = &imp.self_ty.kind;
if let Some(ty_id) = cx.qpath_res(ty_path, imp.self_ty.hir_id).opt_def_id();
if let Some(local_id) = ty_id.as_local();
let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id);
if !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id);
if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.def_id).skip_binder());
then {
let (name, kind) = match cx.tcx.hir().find(ty_hir_id) {
Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"),
Some(Node::Item(x)) => match x.kind {
ItemKind::Struct(..) => (x.ident.name, "struct"),
ItemKind::Enum(..) => (x.ident.name, "enum"),
ItemKind::Union(..) => (x.ident.name, "union"),
_ => (x.ident.name, "type"),
}
_ => return,
};
check_for_is_empty(cx, sig.span, sig.decl.implicit_self, output, ty_id, name, kind)
}
}
}
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if expr.span.from_expansion() {
return;
}
if let ExprKind::Binary(Spanned { node: cmp, .. }, left, right) = expr.kind {
match cmp {
BinOpKind::Eq => {
check_cmp(cx, expr.span, left, right, "", 0); // len == 0
check_cmp(cx, expr.span, right, left, "", 0); // 0 == len
},
BinOpKind::Ne => {
check_cmp(cx, expr.span, left, right, "!", 0); // len != 0
check_cmp(cx, expr.span, right, left, "!", 0); // 0 != len
},
BinOpKind::Gt => {
check_cmp(cx, expr.span, left, right, "!", 0); // len > 0
check_cmp(cx, expr.span, right, left, "", 1); // 1 > len
},
BinOpKind::Lt => {
check_cmp(cx, expr.span, left, right, "", 1); // len < 1
check_cmp(cx, expr.span, right, left, "!", 0); // 0 < len
},
BinOpKind::Ge => check_cmp(cx, expr.span, left, right, "!", 1), // len >= 1
BinOpKind::Le => check_cmp(cx, expr.span, right, left, "!", 1), // 1 <= len
_ => (),
}
}
}
}
fn check_trait_items(cx: &LateContext<'_>, visited_trait: &Item<'_>, trait_items: &[TraitItemRef]) {
fn is_named_self(cx: &LateContext<'_>, item: &TraitItemRef, name: Symbol) -> bool {
item.ident.name == name
&& if let AssocItemKind::Fn { has_self } = item.kind {
has_self && { cx.tcx.fn_sig(item.id.def_id).inputs().skip_binder().len() == 1 }
} else {
false
}
}
// fill the set with current and super traits
fn fill_trait_set(traitt: DefId, set: &mut DefIdSet, cx: &LateContext<'_>) {
if set.insert(traitt) {
for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
fill_trait_set(supertrait, set, cx);
}
}
}
if cx.access_levels.is_exported(visited_trait.def_id) && trait_items.iter().any(|i| is_named_self(cx, i, sym::len))
{
let mut current_and_super_traits = DefIdSet::default();
fill_trait_set(visited_trait.def_id.to_def_id(), &mut current_and_super_traits, cx);
let is_empty_method_found = current_and_super_traits
.iter()
.flat_map(|&i| cx.tcx.associated_items(i).in_definition_order())
.any(|i| {
i.kind == ty::AssocKind::Fn
&& i.fn_has_self_parameter
&& i.ident.name == sym!(is_empty)
&& cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
});
if !is_empty_method_found {
span_lint(
cx,
LEN_WITHOUT_IS_EMPTY,
visited_trait.span,
&format!(
"trait `{}` has a `len` method but no (possibly inherited) `is_empty` method",
visited_trait.ident.name
),
);
}
}
}
#[derive(Debug, Clone, Copy)]
enum LenOutput<'tcx> {
Integral,
Option(DefId),
Result(DefId, Ty<'tcx>),
}
fn parse_len_output(cx: &LateContext<'_>, sig: FnSig<'tcx>) -> Option<LenOutput<'tcx>> {
match *sig.output().kind() {
ty::Int(_) | ty::Uint(_) => Some(LenOutput::Integral),
ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::option_type, adt.did) => {
subs.type_at(0).is_integral().then(|| LenOutput::Option(adt.did))
},
ty::Adt(adt, subs) if cx.tcx.is_diagnostic_item(sym::result_type, adt.did) => subs
.type_at(0)
.is_integral()
.then(|| LenOutput::Result(adt.did, subs.type_at(1))),
_ => None,
}
}
impl LenOutput<'_> {
fn matches_is_empty_output(self, ty: Ty<'_>) -> bool {
match (self, ty.kind()) {
(_, &ty::Bool) => true,
(Self::Option(id), &ty::Adt(adt, subs)) if id == adt.did => subs.type_at(0).is_bool(),
(Self::Result(id, err_ty), &ty::Adt(adt, subs)) if id == adt.did => {
subs.type_at(0).is_bool() && TyS::same_type(subs.type_at(1), err_ty)
},
_ => false,
}
}
fn expected_sig(self, self_kind: ImplicitSelfKind) -> String {
let self_ref = match self_kind {
ImplicitSelfKind::ImmRef => "&",
ImplicitSelfKind::MutRef => "&mut ",
_ => "",
};
match self {
Self::Integral => format!("expected signature: `({}self) -> bool`", self_ref),
Self::Option(_) => format!(
"expected signature: `({}self) -> bool` or `({}self) -> Option<bool>",
self_ref, self_ref
),
Self::Result(..) => format!(
"expected signature: `({}self) -> bool` or `({}self) -> Result<bool>",
self_ref, self_ref
),
}
}
}
/// Checks if the given signature matches the expectations for `is_empty`
fn check_is_empty_sig(sig: FnSig<'_>, self_kind: ImplicitSelfKind, len_output: LenOutput<'_>) -> bool {
match &**sig.inputs_and_output {
[arg, res] if len_output.matches_is_empty_output(res) => {
matches!(
(arg.kind(), self_kind),
(ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::ImmRef)
| (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::MutRef)
) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut))
},
_ => false,
}
}
/// Checks if the given type has an `is_empty` method with the appropriate signature.
fn check_for_is_empty(
cx: &LateContext<'_>,
span: Span,
self_kind: ImplicitSelfKind,
output: LenOutput<'_>,
impl_ty: DefId,
item_name: Symbol,
item_kind: &str,
) {
let is_empty = Symbol::intern("is_empty");
let is_empty = cx
.tcx
.inherent_impls(impl_ty)
.iter()
.flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
.find(|item| item.kind == AssocKind::Fn);
let (msg, is_empty_span, self_kind) = match is_empty {
None => (
format!(
"{} `{}` has a public `len` method, but no `is_empty` method",
item_kind,
item_name.as_str(),
),
None,
None,
),
Some(is_empty) if !cx.access_levels.is_exported(is_empty.def_id.expect_local()) => (
format!(
"{} `{}` has a public `len` method, but a private `is_empty` method",
item_kind,
item_name.as_str(),
),
Some(cx.tcx.def_span(is_empty.def_id)),
None,
),
Some(is_empty)
if !(is_empty.fn_has_self_parameter
&& check_is_empty_sig(cx.tcx.fn_sig(is_empty.def_id).skip_binder(), self_kind, output)) =>
{
(
format!(
"{} `{}` has a public `len` method, but the `is_empty` method has an unexpected signature",
item_kind,
item_name.as_str(),
),
Some(cx.tcx.def_span(is_empty.def_id)),
Some(self_kind),
)
},
Some(_) => return,
};
span_lint_and_then(cx, LEN_WITHOUT_IS_EMPTY, span, &msg, |db| {
if let Some(span) = is_empty_span {
db.span_note(span, "`is_empty` defined here");
}
if let Some(self_kind) = self_kind {
db.note(&output.expected_sig(self_kind));
}
});
}
fn check_cmp(cx: &LateContext<'_>, span: Span, method: &Expr<'_>, lit: &Expr<'_>, op: &str, compare_to: u32) {
if let (&ExprKind::MethodCall(method_path, _, args, _), &ExprKind::Lit(ref lit)) = (&method.kind, &lit.kind) {
// check if we are in an is_empty() method
if let Some(name) = get_item_name(cx, method) {
if name.as_str() == "is_empty" {
return;
}
}
check_len(cx, span, method_path.ident.name, args, &lit.node, op, compare_to);
} else {
check_empty_expr(cx, span, method, lit, op);
}
}
fn check_len(
cx: &LateContext<'_>,
span: Span,
method_name: Symbol,
args: &[Expr<'_>],
lit: &LitKind,
op: &str,
compare_to: u32,
) {
if let LitKind::Int(lit, _) = *lit {
// check if length is compared to the specified number
if lit != u128::from(compare_to) {
return;
}
if method_name == sym::len && args.len() == 1 && has_is_empty(cx, &args[0]) {
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
LEN_ZERO,
span,
&format!("length comparison to {}", if compare_to == 0 { "zero" } else { "one" }),
&format!("using `{}is_empty` is clearer and more explicit", op),
format!(
"{}{}.is_empty()",
op,
snippet_with_applicability(cx, args[0].span, "_", &mut applicability)
),
applicability,
);<|fim▁hole|> }
}
fn check_empty_expr(cx: &LateContext<'_>, span: Span, lit1: &Expr<'_>, lit2: &Expr<'_>, op: &str) {
if (is_empty_array(lit2) || is_empty_string(lit2)) && has_is_empty(cx, lit1) {
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
COMPARISON_TO_EMPTY,
span,
"comparison to empty slice",
&format!("using `{}is_empty` is clearer and more explicit", op),
format!(
"{}{}.is_empty()",
op,
snippet_with_applicability(cx, lit1.span, "_", &mut applicability)
),
applicability,
);
}
}
fn is_empty_string(expr: &Expr<'_>) -> bool {
if let ExprKind::Lit(ref lit) = expr.kind {
if let LitKind::Str(lit, _) = lit.node {
let lit = lit.as_str();
return lit == "";
}
}
false
}
fn is_empty_array(expr: &Expr<'_>) -> bool {
if let ExprKind::Array(arr) = expr.kind {
return arr.is_empty();
}
false
}
/// Checks if this type has an `is_empty` method.
fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
/// Gets an `AssocItem` and return true if it matches `is_empty(self)`.
fn is_is_empty(cx: &LateContext<'_>, item: &ty::AssocItem) -> bool {
if let ty::AssocKind::Fn = item.kind {
if item.ident.name.as_str() == "is_empty" {
let sig = cx.tcx.fn_sig(item.def_id);
let ty = sig.skip_binder();
ty.inputs().len() == 1
} else {
false
}
} else {
false
}
}
/// Checks the inherent impl's items for an `is_empty(self)` method.
fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
cx.tcx.inherent_impls(id).iter().any(|imp| {
cx.tcx
.associated_items(*imp)
.in_definition_order()
.any(|item| is_is_empty(cx, item))
})
}
let ty = &cx.typeck_results().expr_ty(expr).peel_refs();
match ty.kind() {
ty::Dynamic(tt, ..) => tt.principal().map_or(false, |principal| {
cx.tcx
.associated_items(principal.def_id())
.in_definition_order()
.any(|item| is_is_empty(cx, item))
}),
ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
ty::Adt(id, _) => has_is_empty_impl(cx, id.did),
ty::Array(..) | ty::Slice(..) | ty::Str => true,
_ => false,
}
}<|fim▁end|> | } |
<|file_name|>Comment.py<|end_file_name|><|fim▁begin|>from .User import User
class Comment(object):
def __init__(self, commentData):
self.status = None
self.username_id = None
self.created_at_utc = None
self.created_at = None
self.bit_flags = None
self.user = None
self.comment = None
self.pk = None
self.type = None
self.media_id = None
self.status = commentData['status']
if 'user_id' in commentData and commentData['user_id']:
self.username_id = commentData['user_id']
self.created_at_utc = commentData['created_at_utc']
self.created_at = commentData['created_at']
if 'bit_flags' in commentData and commentData['bit_flags']:
self.bit_flags = commentData['bit_flags']
self.user = User(commentData['user'])
self.comment = commentData['text']
self.pk = commentData['pk']
if 'type' in commentData and commentData['type']:
self.type = commentData['type']
if 'media_id' in commentData and commentData['media_id']:
self.media_id = commentData['media_id']<|fim▁hole|> return self.status
def getUsernameId(self):
return self.username_id
def getCreatedAtUtc(self):
return self.created_at_utc
def created_at(self):
return self.created_at
def getBitFlags(self):
return self.bit_flags
def getUser(self):
return self.user
def getComment(self):
return self.comment
def getCommentId(self):
return self.pk
def getType(self):
return self.type
def getMediaId(self):
return self.media_id<|fim▁end|> |
def getStatus(self): |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#
# Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
#
# This file is part of Outer Space.
#
# Outer Space is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Outer Space 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 Outer Space; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
import math
import ige.ospace.Const as Const
from ige.IDataHolder import makeIDataHolder
from Techs import noop as techDefaultHandler
def init(configDir):
global techs, Tech
import Techs
Techs.init(configDir)
from Techs import techs, Tech
## General
turnsPerDay = 24
galaxyStartDelay = turnsPerDay * 2
playerTimeout = 60 * 60 * 24 * 28 # 28 days
novicePlayerTimeout = 60 * 60 * 24 * 14 # 14 days
messageTimeout = 60 * 60 * 24 * 14 # 14 days
## New player
startingPopulation = 9000
startingBio = 1000
startingMin = 1000
startingEn = 1000
startingScannerPwr = 100
## Production
maxProdQueueLen = 10
buildOnSamePlanetMod = 1
buildOnAnotherPlanetMod = 2
unusedProdMod = 0.75
# structure economy revamp constants
basePlanetProdProd = 5 # prevents deadlocked planets, makes small planets more competitive
structDefaultHpRatio = 0.1 # structures are build with this percentage of HPs
structDefaultCpCosts = 0.2 # structures costs this amount of what is in XMLs
structFromShipHpRatio = 1.0 # structures from ships are build with this percentage of HPs
structNewPlayerHpRatio = 1.0 # structures from ships are build with this percentage of HPs
structTransferWaste = 0.5 # when replacing building, how much CP of old building is transfered to new one
structTransferMaxRatio = 0.5 # when replacing building, what is maximum effect of transfered CPs
# as we now build structures damaged, repair and decay are part of economy revamp
# repair ratio is dynamic on cost of building. it's full of magic constants
# goal is to have 480 CP building to repair in ~2 days (which is twice the legacy repair
# ratio), and the most expansive ones (adv. stargate) ~ 6 days.
# We are using log10() as it's quicker than log()
_magicBase = 1.0 / (turnsPerDay * 2)
_repairMagicBase = math.log10(480 * structDefaultCpCosts) ** 2 * _magicBase
repairRatioFunc = lambda x: _repairMagicBase / math.log10(x) ** 2
# building decay ratio bigger or equivalent of 480 CP repair
decayRatioFunc = lambda x: min( _magicBase, repairRatioFunc(x))
decayProdQueue = 0.02
## Environment
envInterval = 1000
envAutoMod = 10.0
envMax = 200<|fim▁hole|>envSelfUpgradeChance = {"H": 5, "C": 1, "B": 500, "m": 100, "r": 100, "p": 100, "e": 100} # in ten thousandths (10 000)
planetSpec = {}
planetSpec[u'A'] = makeIDataHolder(
minBio = 0,
maxBio = 0,
upgradeTo = None,
downgradeTo = None,
)
planetSpec[u'G'] = makeIDataHolder(
minBio = 0,
maxBio = 0,
upgradeTo = None,
downgradeTo = None,
)
planetSpec[u'C'] = makeIDataHolder(
minBio = 0,
maxBio = 6,
upgradeTo = u'D',
upgradeEnReqs = (5, 180),
downgradeTo = None,
)
planetSpec[u'R'] = makeIDataHolder(
minBio = 0,
maxBio = 6,
upgradeTo = u'D',
upgradeEnReqs = (5, 180),
downgradeTo = None,
)
planetSpec[u'D'] = makeIDataHolder(
minBio = 6,
maxBio = 12,
upgradeTo = u'H',
upgradeEnReqs = (25, 150),
downgradeTo = u'R',
)
planetSpec[u'H'] = makeIDataHolder(
minBio = 12,
maxBio = 25,
upgradeTo = u'M',
upgradeEnReqs = (50, 125),
downgradeTo = u'D',
)
planetSpec[u'M'] = makeIDataHolder(
minBio = 25,
maxBio = 75,
upgradeTo = u'E',
upgradeEnReqs = (50, 100),
downgradeTo = u'H',
)
planetSpec[u'E'] = makeIDataHolder(
minBio = 75,
maxBio = 125,
upgradeTo = u"I",
upgradeEnReqs = (50, 100),
downgradeTo = u'M',
)
planetSpec[u"I"] = makeIDataHolder( # gaia
minBio = 125,
maxBio = 200,
upgradeTo = None,
downgradeTo = u"E",
)
## New colony settings
colonyMinBio = 600
colonyMinMin = 600
colonyMinEn = 600
## Storage
popPerSlot = 0
bioPerSlot = 0
minPerSlot = 0
enPerSlot = 0
popBaseStor = 4800
bioBaseStor = 4800
minBaseStor = 4800
enBaseStor = 4800
autoMinStorTurns = 2
tlPopReserve = 100
## Resources
stratResRate = turnsPerDay * 6
stratResAmountBig = 10
stratResAmountSmall = 1
## Population
popGrowthRate = 0.02
popMinGrowthRate = int(5000 * popGrowthRate) # Increase the Minimum Population Growth from 20 to 100 per turn
popDieRate = 0.1
popMinDieRate = 100
popKillMod = 0.25
popSlotKillMod = 5 # how many people per 1 DMG get killed when slot is hit
popSlotHP = 100 # HP of habitable structures on slot (where people live)
## Research
maxRsrchQueueLen = 10
techBaseImprovement = 1
techMaxImprovement = 5
techImprCostMod = {1:480, 2:480, 3:720, 4:960, 5:1200, 6: 1440, 7: 1680} #per level
sciPtsPerCitizen = {1: 0, 2: 0.00075, 3: 0.00150, 4: 0.00175, 5: 0.00200, 6: 0.002125, 7: 0.00225, 99: 0} #per level
techImprEff = {1:0.750, 2:0.875, 3:1.000, 4:1.125, 5:1.250} #per sublevel
#maxSciPtsTL = {1:100, 2:200, 3:300, 4:400, 5:500, 6:600, 7:700}
#sciPtsStepFraction = 0.25
## Scanner
maxSignature = 100
scannerMinPwr = 1
scannerMaxPwr = 150
level1InfoScanPwr = 1000
level2InfoScanPwr = 1200
level3InfoScanPwr = 1400
level4InfoScanPwr = 1600
maxScanPwr = 200000
mapForgetScanPwr = 0.94
partnerScanPwr = 300000
## Fleets
maxCmdQueueLen = 10
signatureBase = 1.10
operProdRatio = 0.001
combatRetreatWait = 3
starGateDamage = 0.2 # damage for 100% speed boost (double for 200%, etc...)
shipDecayRatio = 0.04
maxDamageAbsorb = 5 # max absorbed damage for tech "damageAbsorb" property.
# max seq_mod equipments of equipType; anything not in list is unlimited
maxEquipType = {
'ECM' : 1, # +Missile DEF
'Combat Bonuses' : 1, # +%ATT, +%DEF
'Combat Modifiers' : 1, # +ATT, +DEF
'Shields' : 1, # not hardshields
'Stealth' : 1,
'Auto Repair' : 1,
}
## Buildings
plShieldRegen = 0.05 #regen rate of planetary shield
## Diplomacy
baseRelationChange = -5
relLostWhenAttacked = -1000000
defaultRelation = Const.REL_NEUTRAL
contactTimeout = 6 * turnsPerDay
voteForImpAnnounceOffset = 2 * turnsPerDay
voteForImpPeriod = 6 * turnsPerDay
ratioNeededForImp = 0.6666
pactDescrs = {}
pactDescrs[Const.PACT_ALLOW_CIVILIAN_SHIPS] = makeIDataHolder(
targetRel = 500,
relChng = 10,
validityInterval = (0, 10000),
)
pactDescrs[Const.PACT_ALLOW_MILITARY_SHIPS] = makeIDataHolder(
targetRel = 750,
relChng = 8,
validityInterval = (0, 10000),
)
pactDescrs[Const.PACT_ALLOW_TANKING] = makeIDataHolder(
targetRel = 750,
relChng = 7,
validityInterval = (0, 10000),
)
pactDescrs[Const.PACT_MINOR_CP_COOP] = makeIDataHolder(
targetRel = 1000,
relChng = 6,
effectivity = 0.05,
validityInterval = (625, 10000),
)
pactDescrs[Const.PACT_MAJOR_CP_COOP] = makeIDataHolder(
targetRel = 1000,
relChng = 1,
effectivity = 0.05,
validityInterval = (875, 10000),
)
pactDescrs[Const.PACT_SHARE_SCANNER] = makeIDataHolder(
targetRel = 1000,
relChng = 1,
validityInterval = (625, 10000),
)
pactDescrs[Const.PACT_MINOR_SCI_COOP] = makeIDataHolder(
targetRel = 750,
relChng = 1,
effectivity = 0.05,
validityInterval = (625, 10000),
)
pactDescrs[Const.PACT_MAJOR_SCI_COOP] = makeIDataHolder(
targetRel = 1000,
relChng = 1,
effectivity = 0.05,
validityInterval = (875, 10000),
)
## Morale
baseGovPwr = 50000
maxMorale = 100.0
minMoraleTrgt = 30.0
revoltThr = 25.0
moraleChngPerc = 0.03
moraleHighPopPenalty = 2.0
moraleBasePop = 10000
moraleLowPop = 5000
moraleLowPopBonus = 40.0
moraleLostWhenSurrender = 0.0
moraleLostNoFood = 1.0
moraleModPlHit = 96.0 # how many morale point per 1 per cent of damage
moralePerPointChance = 5.0 # for every point below revoltThr % chance for revolt
moraleProdStep = 10
moraleProdBonus = [-0.875, -0.75, -0.625, -0.50, -0.375, -0.25, -0.125, 0.0, 0.0, 0.125, 0.25]
# we expect pop reserve from TL to get into unemployed
# tlPopReserve * TL1
# if we get no reserve, there is a hit, if we get at least
# the reserve, it's a bonus, linear in between
unemployedMoraleLow = -20
unemployedMoraleHigh = 10
## Revolt
revoltDestrBio = 0.05
revoltDestrMin = 0.05
revoltDestrEn = 0.05
revoltPenalty = 0.75
## Messages
messageMaxAge = turnsPerDay * 3
## Projects
projECOINIT3PlBio = 1
## Ships
shipImprovementMod = 1.05
shipMaxImprovements = 5
shipMaxDesigns = 40
shipExpToLevel = {0:1, 1:2, 2:2, 3:3, 4:3, 5:3, 6:3, 7:4, 8:4, 9:4, 10:4, 11:4,
12:4, 13:4, 15:5}
shipDefLevel = 5
shipLevelEff = {1:0.50, 2:0.75, 3:1.00, 4:1.25, 5:1.50}
shipBaseExpMod = 20
shipBaseExp = {0:10, 1:20, 2:40, 3:80, 4:160}
shipTargetPerc = [25, 50, 90, 100]
shipMinUpgrade = 120
shipUpgradeMod = 1.375
shipUpgradePts = [1, 3, 10]
weaponDmgDegrade = [1.0, 0.5, 0.25, 0.125]
## EMR
emrMinDuration = 36
emrMaxDuration = 60
emrPeriod = 576
emrSeasons = [None, None, None, None]
emrSeasons[0] = makeIDataHolder(
name = "spring",
startTime = 0,
endTime = 143,
emrLevelMin = 0.75,
emrLevelMax = 1.25,
)
emrSeasons[1] = makeIDataHolder(
name = "summer",
startTime = 144,
endTime = 287,
emrLevelMin = 0.50,
emrLevelMax = 1.00,
)
emrSeasons[2] = makeIDataHolder(
name = "fall",
startTime = 287,
endTime = 431,
emrLevelMin = 0.50,
emrLevelMax = 1.50,
)
emrSeasons[3] = makeIDataHolder(
name = "winter",
startTime = 432,
endTime = 575,
emrLevelMin = 1.00,
emrLevelMax = 1.50,
)
## Pirates
## General
pirateInfluenceRange = 7.5 # in parsecs
pirateGovPwr = int(500000 * 1.25)
## Fame
pirateGainFamePropability = lambda d: 2 - d * 0.2
pirateLoseFameProbability = lambda d: 1 - (15 - d) * 0.2
pirateCaptureInRangeFame = 1
pirateSurvivalFame = 1
pirateCaptureOutOfRangeFame = -1
## Colonization
pirateColonyCostMod = 1.5 # base multiplier - all other multipliers are multiplied by this
pirateTL3StratResColonyCostMod = 0.25
piratePlayerZoneCostMod = 1.25
pirateColonyFameZoneCost = lambda d: min(d * 0.1 + pirateTL3StratResColonyCostMod,1)
pirateColonyPlayerZoneCost = lambda d: piratePlayerZoneCostMod + (d - 15) * 0.01 * piratePlayerZoneCostMod
## Techs
pirateCanStealImprovements = 3
pirateGrantHSE = 60*24*3600 #60 days; AI only
pirateGrantASSEM = 105*24*3600 #105 days; AI only
pirateGrantCOND = 105*24*3600 #105 days; AI only
## Timed events (not implemented)
pirateTimerMod = 3*24*3600 # +/- up to 3 days for each grant
pirateTimerRum = 20*24*3600 #20 days; grant Brewery, Rum strategic resource, and Drunken Factory (110% Pirate Prison; requires Rum)
pirateTimerEnslavement = 60*24*3600 #60 days; grant Prison
pirateTimerEDENStructure = 120*24*3600 #120 days; grant EDEN Factory (you have discovered a prototype factory...; 135% Pirate Prison; requires Rum)
pirateTimerBerserk = 150*24*3600 #150 days; grant "Berserk" ship module (major defense penalty; major ATT bonus; requires Rum)
pirateTimerSlaveMine = 180*24*3600 #180 days; grant Slave Mine (mining facility with hamster wheel for power; 160% Pirate Prison; requires Rum)
## Bonuses
galLeaderBonus = 0.05
galImperatorBonus = 0.10
## Combat
combatStructureHitMod = 0.75
combatShipHitMod = 0.75
combatHitXferMod = 3.00
combatStructDefense = 1<|fim▁end|> | |
<|file_name|>osyczka2.py<|end_file_name|><|fim▁begin|>from model import Model
from helpers.candidate import Candidate
from helpers.decision import Decision
class Osyczka2(Model):
def __init__(self):
Model.__init__(self)
self.initialize_decs()
def initialize_decs(self):
dec = Decision('x1', 0, 10)
self.decs.append(dec)
dec = Decision('x2', 0, 10)
self.decs.append(dec)
dec = Decision('x3', 1, 5)
self.decs.append(dec)
dec = Decision('x4', 0, 6)
self.decs.append(dec)
dec = Decision('x5', 1, 5)
self.decs.append(dec)
dec = Decision('x6', 0, 10)
self.decs.append(dec)
def f1(self, candidate):
vec = candidate.dec_vals
part1 = 25 * ((vec[0] - 2) ** 2)
part2 = (vec[1] - 2) ** 2
part3 = (((vec[2] - 1) ** 2) * ((vec[3] - 4) ** 2))
part4 = (vec[4] - 1) ** 2
return (-(part1 + part2 + part3 + part4))
def f2(self, candidate):
vec = candidate.dec_vals
val = 0
for x in vec:
val += x ** 2
return val
def objectives(self):
return [self.f1, self.f2]<|fim▁hole|> aggr = 0
self.eval(candidate)
for score in candidate.scores:
aggr += score
return aggr
def gen_candidate(self):
for i in range(0, self.patience):
decs = [dec.generate_valid_val() for dec in self.decs]
can = Candidate(dec_vals=list(decs))
if self.ok(can):
return can
def ok(self, candidate, debug=False):
if len(candidate.dec_vals) != 6:
return False
x1 = candidate.dec_vals[0]
x2 = candidate.dec_vals[1]
x3 = candidate.dec_vals[2]
x4 = candidate.dec_vals[3]
x5 = candidate.dec_vals[4]
x6 = candidate.dec_vals[5]
if not ((x1 + x2) >= 2):
if debug:
print "Failed 1"
return False
if not ((x1 + x2) <= 6):
if debug:
print "Failed 2"
return False
if not ((x2 - x1) <= 2):
if debug:
print "Failed 3"
return False
if not ((x1 - (3 * x2)) <= 2):
if debug:
print "Failed 4"
return False
if not ((((x3 - 3) ** 2) + x4) <= 4):
if debug:
print "Failed 5"
return False
if not ((((x5 - 3) ** 3) + x6) >= 4):
if debug:
print "Failed 6"
return False
return True<|fim▁end|> |
def aggregate(self, candidate): |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
from django.http import Http404
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from snisi_core.permissions import provider_allowed_or_denied
from snisi_core.models.Projects import Cluster
from snisi_core.models.Periods import MonthPeriod, Period
from snisi_core.models.Entities import Entity
from snisi_trachoma.models import TTBacklogMissionR
from snisi_web.utils import (entity_browser_context, get_base_url_for_period,
get_base_url_for_periods,
ensure_entity_in_cluster,
ensure_entity_at_least)
logger = logging.getLogger(__name__)
@login_required
def trachoma_mission_browser(request,
entity_slug=None,
period_str=None,
**kwargs):
context = {}
root = request.user.location
cluster = Cluster.get_or_none('trachoma_backlog')
entity = Entity.get_or_none(entity_slug)
if entity is None:
entity = root
if entity is None:
raise Http404("Aucune entité pour le code {}".format(entity_slug))
# make sure requested entity is in cluster
ensure_entity_in_cluster(cluster, entity)
# check permissions on this entity and raise 403
provider_allowed_or_denied(request.user, 'access_trachoma', entity)
# mission browser is reserved to district-level and above
ensure_entity_at_least(entity, 'health_district')
def period_from_strid(period_str, reportcls=None):
period = None
if period_str:
try:
period = Period.from_url_str(period_str).casted()
except:
pass
return period
period = period_from_strid(period_str)
if period is None:
period = MonthPeriod.current()
try:
first_period = MonthPeriod.find_create_by_date(
TTBacklogMissionR.objects.all()
.order_by('period__start_on')[0].period.middle())
except IndexError:
first_period = MonthPeriod.current()
all_periods = MonthPeriod.all_from(first_period)
context.update({
'all_periods': [(p.strid(), p) for p in reversed(all_periods)],
'period': period,
'base_url': get_base_url_for_period(
view_name='trachoma_missions', entity=entity,
period_str=period_str or period.strid())
})
context.update(entity_browser_context(
root=root, selected_entity=entity,
full_lineage=['country', 'health_region', 'health_district'],
cluster=cluster))
# retrieve list of missions for that period
missions = TTBacklogMissionR.objects.filter(
period=period,
entity__slug__in=[e.slug for e in entity.get_health_districts()])
context.update({'missions': missions})
return render(request,
kwargs.get('template_name', 'trachoma/missions_list.html'),
context)
@login_required
def trachoma_mission_viewer(request, report_receipt, **kwargs):
context = {}
mission = TTBacklogMissionR.get_or_none(report_receipt)
if mission is None:
return Http404("Nº de reçu incorrect : {}".format(report_receipt))
context.update({'mission': mission})
<|fim▁hole|> context)
@login_required
def trachoma_dashboard(request,
entity_slug=None,
perioda_str=None,
periodb_str=None,
**kwargs):
context = {}
root = request.user.location
cluster = Cluster.get_or_none('trachoma_backlog')
entity = Entity.get_or_none(entity_slug)
if entity is None:
entity = root
if entity is None:
raise Http404("Aucune entité pour le code {}".format(entity_slug))
# make sure requested entity is in cluster
ensure_entity_in_cluster(cluster, entity)
# check permissions on this entity and raise 403
provider_allowed_or_denied(request.user, 'access_trachoma', entity)
# mission browser is reserved to district-level and above
ensure_entity_at_least(entity, 'health_district')
def period_from_strid(period_str, reportcls=None):
period = None
if period_str:
try:
period = Period.from_url_str(period_str).casted()
except:
pass
return period
perioda = period_from_strid(perioda_str)
periodb = period_from_strid(periodb_str)
if periodb is None:
periodb = MonthPeriod.current()
if perioda is None:
perioda = periodb
if perioda is None or periodb is None:
raise Http404("Période incorrecte.")
if perioda > periodb:
t = perioda
perioda = periodb
periodb = t
del(t)
try:
first_period = MonthPeriod.find_create_by_date(
TTBacklogMissionR.objects.all().order_by(
'period__start_on')[0].period.middle())
except IndexError:
first_period = MonthPeriod.current()
all_periods = MonthPeriod.all_from(first_period)
periods = MonthPeriod.all_from(perioda, periodb)
context.update({
'all_periods': [(p.strid(), p) for p in reversed(all_periods)],
'periods': periods,
'perioda': perioda,
'periodb': periodb,
'base_url': get_base_url_for_periods(
view_name='trachoma_dashboard',
entity=entity,
perioda_str=perioda_str or perioda.strid(),
periodb_str=periodb_str or periodb.strid())
})
context.update(entity_browser_context(
root=root, selected_entity=entity,
full_lineage=['country', 'health_region', 'health_district'],
cluster=cluster))
# retrieve Indicator Table
from snisi_trachoma.indicators import (MissionDataSummary,
CumulativeBacklogData)
missions_followup = MissionDataSummary(entity=entity,
periods=periods)
cumulative_backlog = CumulativeBacklogData(entity=entity,
periods=periods)
context.update({
'missions_followup': missions_followup,
'cumulative_backlog': cumulative_backlog,
})
return render(request,
kwargs.get('template_name', 'trachoma/dashboard.html'),
context)<|fim▁end|> | return render(request,
kwargs.get('template_name', 'trachoma/mission_detail.html'), |
<|file_name|>chef_linux.go<|end_file_name|><|fim▁begin|>package collectors
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/leapar/bosun/metadata"<|fim▁hole|> StartTime string `json:"start_time"`
EndTime string `json:"end_time"`
ElapsedTime float32 `json:"elapsed_time"`
Status string `json:"status"`
}
func init() {
collectors = append(collectors, &IntervalCollector{F: c_chef_linux, Enable: chefEnable})
}
const (
chefRunLog = "/var/chef/reports/run_status_json.log"
)
func chefEnable() bool {
_, err := os.Stat(chefRunLog)
return err == nil
}
func c_chef_linux() (opentsdb.MultiDataPoint, error) {
md, err := chef_linux(chefRunLog)
if err != nil {
return nil, err
}
return md, nil
}
func chef_linux(logfile string) (opentsdb.MultiDataPoint, error) {
var md opentsdb.MultiDataPoint
var cr crSummary
// Gather stats from the run summary
s, err := readLastLine(chefRunLog, 4096)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(s), &cr)
if err != nil {
return nil, err
}
endTime, err := time.Parse("2006-01-02 15:04:05 -0700", cr.EndTime)
if err != nil {
return nil, err
}
switch cr.Status {
case "success":
AddTS(&md, "chef.run_status", endTime.Unix(), 0, nil, metadata.Gauge, metadata.Bool, descChefRunStatus)
case "failed":
AddTS(&md, "chef.run_status", endTime.Unix(), 1, nil, metadata.Gauge, metadata.Bool, descChefRunStatus)
default:
err := fmt.Errorf("bad chef run status: %s", cr.Status)
return nil, err
}
AddTS(&md, "chef.run_time", endTime.Unix(), cr.ElapsedTime, nil, metadata.Gauge, metadata.Second, descChefRunTime)
lastrun_delay := time.Now().Sub(endTime).Seconds()
Add(&md, "chef.lastrun_delay", lastrun_delay, nil, metadata.Gauge, metadata.Second, descChefLastRunDelay)
return md, nil
}
const (
descChefRunStatus = "Status of Chef run."
descChefRunTime = "Time which Chef took to run."
descChefLastRunDelay = "Time passed after last Chef run."
)
func readLastLines(filepath string, count int, offset int64) ([]string, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return nil, err
}
size := stat.Size()
if size < offset {
offset = size
}
buf := make([]byte, offset)
if _, err := f.ReadAt(buf, size-offset); err != nil && err != io.EOF {
return nil, err
}
scanner := bufio.NewScanner(strings.NewReader(string(buf[:])))
scanner.Split(bufio.ScanLines)
lines := []string{}
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
to := len(lines)
from := len(lines) - count
if from < 0 {
from = 0
}
return lines[from:to], nil
}
func readLastLine(filepath string, offset int64) (string, error) {
res, err := readLastLines(filepath, 1, offset)
if err != nil {
return "", err
}
if len(res) != 1 {
err := fmt.Errorf("wrong slice size")
return "", err
}
return res[0], nil
}<|fim▁end|> | "github.com/leapar/bosun/opentsdb"
)
type crSummary struct { |
<|file_name|>iptables_test.go<|end_file_name|><|fim▁begin|>package iptables
import (
"net"
"os/exec"
"strconv"
"strings"
"sync"
"testing"
_ "github.com/docker/libnetwork/testutils"
)
const chainName = "DOCKEREST"
var natChain *ChainInfo
var filterChain *ChainInfo
var bridgeName string
func TestNewChain(t *testing.T) {
var err error
bridgeName = "lo"
iptable := GetIptable(IPv4)
natChain, err = iptable.NewChain(chainName, Nat, false)
if err != nil {
t.Fatal(err)
}
err = iptable.ProgramChain(natChain, bridgeName, false, true)
if err != nil {
t.Fatal(err)
}
filterChain, err = iptable.NewChain(chainName, Filter, false)
if err != nil {
t.Fatal(err)
}
err = iptable.ProgramChain(filterChain, bridgeName, false, true)
if err != nil {
t.Fatal(err)
}
}
func TestForward(t *testing.T) {
ip := net.ParseIP("192.168.1.1")
port := 1234
dstAddr := "172.17.0.1"
dstPort := 4321
proto := "tcp"
bridgeName := "lo"
iptable := GetIptable(IPv4)
err := natChain.Forward(Insert, ip, port, proto, dstAddr, dstPort, bridgeName)
if err != nil {
t.Fatal(err)
}
dnatRule := []string{
"-d", ip.String(),
"-p", proto,
"--dport", strconv.Itoa(port),
"-j", "DNAT",
"--to-destination", dstAddr + ":" + strconv.Itoa(dstPort),
"!", "-i", bridgeName,
}
if !iptable.Exists(natChain.Table, natChain.Name, dnatRule...) {
t.Fatal("DNAT rule does not exist")
}
filterRule := []string{
"!", "-i", bridgeName,
"-o", bridgeName,
"-d", dstAddr,
"-p", proto,
"--dport", strconv.Itoa(dstPort),
"-j", "ACCEPT",
}
if !iptable.Exists(filterChain.Table, filterChain.Name, filterRule...) {
t.Fatal("filter rule does not exist")
}
<|fim▁hole|> masqRule := []string{
"-d", dstAddr,
"-s", dstAddr,
"-p", proto,
"--dport", strconv.Itoa(dstPort),
"-j", "MASQUERADE",
}
if !iptable.Exists(natChain.Table, "POSTROUTING", masqRule...) {
t.Fatal("MASQUERADE rule does not exist")
}
}
func TestLink(t *testing.T) {
var err error
bridgeName := "lo"
iptable := GetIptable(IPv4)
ip1 := net.ParseIP("192.168.1.1")
ip2 := net.ParseIP("192.168.1.2")
port := 1234
proto := "tcp"
err = filterChain.Link(Append, ip1, ip2, port, proto, bridgeName)
if err != nil {
t.Fatal(err)
}
rule1 := []string{
"-i", bridgeName,
"-o", bridgeName,
"-p", proto,
"-s", ip1.String(),
"-d", ip2.String(),
"--dport", strconv.Itoa(port),
"-j", "ACCEPT"}
if !iptable.Exists(filterChain.Table, filterChain.Name, rule1...) {
t.Fatal("rule1 does not exist")
}
rule2 := []string{
"-i", bridgeName,
"-o", bridgeName,
"-p", proto,
"-s", ip2.String(),
"-d", ip1.String(),
"--sport", strconv.Itoa(port),
"-j", "ACCEPT"}
if !iptable.Exists(filterChain.Table, filterChain.Name, rule2...) {
t.Fatal("rule2 does not exist")
}
}
func TestPrerouting(t *testing.T) {
args := []string{
"-i", "lo",
"-d", "192.168.1.1"}
iptable := GetIptable(IPv4)
err := natChain.Prerouting(Insert, args...)
if err != nil {
t.Fatal(err)
}
if !iptable.Exists(natChain.Table, "PREROUTING", args...) {
t.Fatal("rule does not exist")
}
delRule := append([]string{"-D", "PREROUTING", "-t", string(Nat)}, args...)
if _, err = iptable.Raw(delRule...); err != nil {
t.Fatal(err)
}
}
func TestOutput(t *testing.T) {
args := []string{
"-o", "lo",
"-d", "192.168.1.1"}
iptable := GetIptable(IPv4)
err := natChain.Output(Insert, args...)
if err != nil {
t.Fatal(err)
}
if !iptable.Exists(natChain.Table, "OUTPUT", args...) {
t.Fatal("rule does not exist")
}
delRule := append([]string{"-D", "OUTPUT", "-t",
string(natChain.Table)}, args...)
if _, err = iptable.Raw(delRule...); err != nil {
t.Fatal(err)
}
}
func TestConcurrencyWithWait(t *testing.T) {
RunConcurrencyTest(t, true)
}
func TestConcurrencyNoWait(t *testing.T) {
RunConcurrencyTest(t, false)
}
// Runs 10 concurrent rule additions. This will fail if iptables
// is actually invoked simultaneously without --wait.
// Note that if iptables does not support the xtable lock on this
// system, then allowXlock has no effect -- it will always be off.
func RunConcurrencyTest(t *testing.T, allowXlock bool) {
var wg sync.WaitGroup
if !allowXlock && supportsXlock {
supportsXlock = false
defer func() { supportsXlock = true }()
}
ip := net.ParseIP("192.168.1.1")
port := 1234
dstAddr := "172.17.0.1"
dstPort := 4321
proto := "tcp"
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
err := natChain.Forward(Append, ip, port, proto, dstAddr, dstPort, "lo")
if err != nil {
t.Fatal(err)
}
}()
}
wg.Wait()
}
func TestCleanup(t *testing.T) {
var err error
var rules []byte
// Cleanup filter/FORWARD first otherwise output of iptables-save is dirty
link := []string{"-t", string(filterChain.Table),
string(Delete), "FORWARD",
"-o", bridgeName,
"-j", filterChain.Name}
iptable := GetIptable(IPv4)
if _, err = iptable.Raw(link...); err != nil {
t.Fatal(err)
}
filterChain.Remove()
err = iptable.RemoveExistingChain(chainName, Nat)
if err != nil {
t.Fatal(err)
}
rules, err = exec.Command("iptables-save").Output()
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(rules), chainName) {
t.Fatalf("Removing chain failed. %s found in iptables-save", chainName)
}
}
func TestExistsRaw(t *testing.T) {
testChain1 := "ABCD"
testChain2 := "EFGH"
iptable := GetIptable(IPv4)
_, err := iptable.NewChain(testChain1, Filter, false)
if err != nil {
t.Fatal(err)
}
defer func() {
iptable.RemoveExistingChain(testChain1, Filter)
}()
_, err = iptable.NewChain(testChain2, Filter, false)
if err != nil {
t.Fatal(err)
}
defer func() {
iptable.RemoveExistingChain(testChain2, Filter)
}()
// Test detection over full and truncated rule string
input := []struct{ rule []string }{
{[]string{"-s", "172.8.9.9/32", "-j", "ACCEPT"}},
{[]string{"-d", "172.8.9.0/24", "-j", "DROP"}},
{[]string{"-s", "172.0.3.0/24", "-d", "172.17.0.0/24", "-p", "tcp", "-m", "tcp", "--dport", "80", "-j", testChain2}},
{[]string{"-j", "RETURN"}},
}
for i, r := range input {
ruleAdd := append([]string{"-t", string(Filter), "-A", testChain1}, r.rule...)
err = iptable.RawCombinedOutput(ruleAdd...)
if err != nil {
t.Fatalf("i=%d, err: %v", i, err)
}
if !iptable.existsRaw(Filter, testChain1, r.rule...) {
t.Fatalf("Failed to detect rule. i=%d", i)
}
// Truncate the rule
trg := r.rule[len(r.rule)-1]
trg = trg[:len(trg)-2]
r.rule[len(r.rule)-1] = trg
if iptable.existsRaw(Filter, testChain1, r.rule...) {
t.Fatalf("Invalid detection. i=%d", i)
}
}
}
func TestGetVersion(t *testing.T) {
mj, mn, mc := parseVersionNumbers("iptables v1.4.19.1-alpha")
if mj != 1 || mn != 4 || mc != 19 {
t.Fatal("Failed to parse version numbers")
}
}
func TestSupportsCOption(t *testing.T) {
input := []struct {
mj int
mn int
mc int
ok bool
}{
{1, 4, 11, true},
{1, 4, 12, true},
{1, 5, 0, true},
{0, 4, 11, false},
{0, 5, 12, false},
{1, 3, 12, false},
{1, 4, 10, false},
}
for ind, inp := range input {
if inp.ok != supportsCOption(inp.mj, inp.mn, inp.mc) {
t.Fatalf("Incorrect check: %d", ind)
}
}
}<|fim▁end|> | |
<|file_name|>hrpd_advanced_config.py<|end_file_name|><|fim▁begin|>from __future__ import (absolute_import, division, print_function)
from isis_powder.hrpd_routines.hrpd_enums import HRPD_TOF_WINDOWS
absorption_correction_params = {
"cylinder_sample_height": 2.0,
"cylinder_sample_radius": 0.3,
"cylinder_position": [0., 0., 0.],
"chemical_formula": "V"
}
# Default cropping values are 5% off each end
window_10_110_params = {
"vanadium_tof_cropping": (1e4, 1.2e5),
"focused_cropping_values": [
(1.5e4, 1.08e5), # Bank 1
(1.5e4, 1.12e5), # Bank 2
(1.5e4, 1e5) # Bank 3
]
}
window_30_130_params = {
"vanadium_tof_cropping": (3e4, 1.4e5),
"focused_cropping_values": [
(3.5e4, 1.3e5), # Bank 1
(3.4e4, 1.4e5), # Bank 2
(3.3e4, 1.3e5) # Bank 3
]
}
window_100_200_params = {
"vanadium_tof_cropping": (1e5, 2.15e5),
"focused_cropping_values": [
(1e5, 2e5), # Bank 1
(8.7e4, 2.1e5), # Bank 2
(9.9e4, 2.1e5) # Bank 3
]
}
file_names = {
"grouping_file_name": "hrpd_new_072_01_corr.cal"
}
general_params = {
"spline_coefficient": 70,
"focused_bin_widths": [
-0.0005, # Bank 1
-0.0005, # Bank 2
-0.001 # Bank 3
],
"mode": "coupled"
}
def get_all_adv_variables(tof_window=HRPD_TOF_WINDOWS.window_10_110):
advanced_config_dict = {}
advanced_config_dict.update(file_names)
advanced_config_dict.update(general_params)
advanced_config_dict.update(get_tof_window_dict(tof_window=tof_window))
return advanced_config_dict
def get_tof_window_dict(tof_window):
if tof_window == HRPD_TOF_WINDOWS.window_10_110:<|fim▁hole|> if tof_window == HRPD_TOF_WINDOWS.window_100_200:
return window_100_200_params
raise RuntimeError("Invalid time-of-flight window: {}".format(tof_window))<|fim▁end|> | return window_10_110_params
if tof_window == HRPD_TOF_WINDOWS.window_30_130:
return window_30_130_params |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate nalgebra;
use nalgebra::{DMat};
/// This trait must be implemented for the single values of a summed area table source.
/// This library contains implementations for all numeric primitive types.
pub trait SourceValue : Copy {
fn as_f64(self) -> f64;
}
impl SourceValue for u8 { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for i8 { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for u32 { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for i32 { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for u64 { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for i64 { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for usize { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for isize { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for f32 { fn as_f64(self) -> f64 { self as f64 } }
impl SourceValue for f64 { fn as_f64(self) -> f64 { self } }
impl <'a>SourceValue for &'a u8 { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a i8 { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a u32 { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a i32 { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a u64 { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a i64 { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a usize { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a isize { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a f32 { fn as_f64(self) -> f64 { *self as f64 } }
impl <'a>SourceValue for &'a f64 { fn as_f64(self) -> f64 { *self } }
/// Structs implementing this trait can calculate a summed area table for themselves.
/// This library contains implementations for vec slices and nalgebra::DMat.
pub trait SummedAreaTableSource<T: SourceValue>{
/// This method will be used to access the source data at given coordinates.
/// e.g. luminosity of pixel at (x,y) or value in matrix where x=column and y=row
fn at(&self, x:usize, y:usize) -> &T;
/// The width of the data source
/// e.g.: image height or number of matrix rows
fn height(&self) -> usize;
/// The width of the data source
/// e.g.: image width or number of matrix columns
fn width(&self) -> usize;
/// Calculates and returns the actual summed area table for a given rect.
/// The arguments 'from' and 'to' represent the rects top-left (inclusive) and bottom-right (inclusive) point.
fn calculate_summed_area_table(&self, from: (usize, usize), to: (usize, usize)) -> SummedAreaTable{
let mut table:DMat<f64> = DMat::new_zeros(self.height(),self.width());
let (from_x, from_y) = from;
let (to_x, to_y) = to;
for row in from_y .. to_y+1 {
for col in from_x .. to_x+1 {
let mut sum = self.at(col, row).as_f64();
if row>0 {
sum = sum + table[(row-1, col)];
}
if col>0 {
sum = sum+ table[(row, col-1)];
}
if row>0 && col>0 {
sum = sum - table[(row-1, col-1)];
}
table[(row,col)] = sum;
}
}
SummedAreaTable{table: table}
}
/// Calculates and returns the actual summed area table for the whole source matrix.
fn calculate_full_summed_area_table(&self) -> SummedAreaTable{
let ncols= self.width();
let nrows= self.height();
self.calculate_summed_area_table((0,0),(ncols-1, nrows-1))
}
}
/// This struct represents a calculated summed area table.
pub struct SummedAreaTable {
pub table: DMat<f64>,
}
impl SummedAreaTable {
/// Returns the sum for a given area,
/// that is described by its upper left and lower right point.
/// It will panic in debug mode if the given points are not within the tables bounds.
/// It will panic in debug mode if `from` is right of or below `to`.
/// `from` is a x/y coordinate tuple for the upper left point (inclusive)
/// `to` is a x/y coordinate tuple for the lower right point (inclusive)
pub fn get_sum(&self, from: (usize,usize), to: (usize,usize)) -> f64{
let (col1, row1) = from;
let (col2, row2) = to;
debug_assert!(row1 <= row2 && col1 <= col2, "`from` ({}/{}) must not be right of or below `to`({}/{})", col1, row1, col2, row2);
debug_assert!( {
let ncols = self.table.ncols();
let nrows = self.table.nrows();
col1 < ncols && col2 < ncols && row1 < nrows && row2 < nrows
},"`from` ({}/{}) or `to` ({}/{}) not within table bounds [(0/0)..({}/{})]", col1, row1, col2, row2, self.table.ncols()-1, self.table.nrows()-1);
let mut sum = self.table[(row2,col2)];
if col1 > 0 && row1 > 0 {
sum = sum + self.table[(row1-1,col1-1)];
}
if col1 > 0 {
let temp = self.table[(row2,col1-1)];
debug_assert!(temp<=sum, "Overlow-Alarm 1: p1({}/{}) p2({}/{}) temp({}) sum({})",
col1, row1, col2, row2, temp, sum);
sum = sum - temp;
}
if row1 > 0 {
let temp = self.table[(row1-1,col2)];
debug_assert!(temp<=sum, "Overlow-Alarm 2: p1({}/{}) p2({}/{}) temp({}) sum({}) ",
col1, row1, col2, row2, temp, sum);
sum = sum - temp;
}
sum
}
/// Returns the average for a given area,
/// that is described by its upper left and lower right point.
/// It will panic in debug mode if the given points are not within the tables bounds.
/// It will panic in debug mode if `from` is right of or below `to`.
/// `from` is a x/y coordinate tuple for the upper left point (inclusive)
/// `to` is a x/y coordinate tuple for the lower right point (inclusive)
pub fn get_average(&self, from: (usize,usize), to: (usize,usize))-> f64{
let sum = self.get_sum(from,to);
let data_count = self.get_data_count(from, to);
sum/data_count as f64
}
/// Returns the number of data points at the given area.
pub fn get_data_count(&self, from: (usize,usize), to: (usize,usize))-> usize{
let (from_x, from_y) = from;
let (to_x, to_y) = to;
(to_x-from_x+1)*(to_y-from_y+1)
}
/// Returns the average for the whole area.
/// that is described by its upper left and lower right point.
/// It will panic in debug mode if the given points are not within the tables bounds.
/// It will panic in debug mode if `from` is right of or below `to`.
/// `from` is a x/y coordinate tuple for the upper left point (inclusive)
/// `to` is a x/y coordinate tuple for the lower right point (inclusive)<|fim▁hole|> /// Returns the sum for the whole area.
/// that is described by its upper left and lower right point.
/// It will panic in debug mode if the given points are not within the tables bounds.
/// It will panic in debug mode if `from` is right of or below `to`.
/// `from` is a x/y coordinate tuple for the upper left point (inclusive)
/// `to` is a x/y coordinate tuple for the lower right point (inclusive)
pub fn get_overall_sum(&self) -> f64{
self.get_sum((0,0),(self.table.ncols()-1,self.table.nrows()-1))
}
/// Returns the number of data points at the whole area.
pub fn get_overall_data_count(&self) -> usize{
self.table.ncols()*self.table.nrows()
}
}
impl <T: SourceValue>SummedAreaTableSource<T> for DMat<T>{
fn at(&self, x: usize, y: usize) -> &T {
&self[(y,x)]
}
fn height(&self) -> usize {
self.nrows()
}
fn width(&self) -> usize {
self.ncols()
}
}
pub struct VecSource<'a,T:'a>{
vec: &'a [T],
height: usize,
width: usize
}
impl <'a, T: SourceValue>VecSource<'a, T>{
pub fn new(vec: &'a [T], width: usize, height: usize) -> VecSource<'a, T> {
VecSource{vec: vec, width: width, height: height}
}
}
impl <'a, T: SourceValue>SummedAreaTableSource<T> for VecSource<'a, T>{
fn at(&self, x: usize, y: usize) -> &T {
&self.vec[util::map_2d_to_1d(x, y, self.width)]
}
fn height(&self) -> usize {
self.height
}
fn width(&self) -> usize {
self.width
}
}
pub mod util {
use nalgebra::{DMat};
pub fn vec_to_dmat(vec: &Vec<usize>) -> DMat<usize> {
DMat::from_col_vec(vec.len(), 1, &vec[..])
}
pub fn map_2d_to_1d(x: usize, y: usize, width: usize)->usize{
y * width + x
}
}
#[test]
fn zeros() {
let src: DMat<usize> = DMat::new_zeros(100,100);
let table = src.calculate_full_summed_area_table();
assert_eq!(0.0, table.get_sum((0,0),(99,99)));
}
#[test]
fn ones() {
let src: DMat<usize> = DMat::from_elem(100,100,1);
let table = src.calculate_full_summed_area_table();
assert_eq!(10000.0, table.get_sum((0,0),(99,99)));
}
#[test]
fn ones_without_first_col_row() {
let src: DMat<usize> = DMat::from_elem(100,100,1);
let table = src.calculate_full_summed_area_table();
assert_eq!(10000.0-199.0, table.get_sum((1,1),(99,99)));
}
#[test]
fn twos() {
let src: DMat<usize> = DMat::from_elem(100,100,2);
let table = src.calculate_full_summed_area_table();
assert_eq!(20000.0, table.get_sum((0,0),(99,99)));
}
#[test]
fn twos_average() {
let src: DMat<usize> = DMat::from_elem(3,3,2);
let table = src.calculate_full_summed_area_table();
assert_eq!(2.0, table.get_average((0,0),(2,2)));
}
#[test]
fn data_count() {
let src: DMat<usize> = DMat::from_elem(123,321,2);
let table = src.calculate_full_summed_area_table();
assert_eq!(123*321, table.get_data_count((0,0),(122,320)));
}
#[test]
fn overall_data_count() {
let src: DMat<usize> = DMat::from_elem(123,321,2);
let table = src.calculate_full_summed_area_table();
assert_eq!(123*321, table.get_overall_data_count());
}
#[test]
fn overall_sum() {
let src: DMat<usize> = DMat::from_elem(100,100,2);
let table = src.calculate_full_summed_area_table();
assert_eq!(20000.0, table.get_overall_sum());
}
#[test]
fn overall_average() {
let src: DMat<usize> = DMat::from_elem(3,3,2);
let table = src.calculate_full_summed_area_table();
assert_eq!(2.0, table.get_overall_average());
}
#[test]
fn ones_quartered() {
let src: DMat<usize> = DMat::from_elem(100,100,1);
let table = src.calculate_full_summed_area_table();
assert_eq!(2500.0, table.get_sum((0,0),(49,49)));
assert_eq!(2500.0, table.get_sum((50,50),(99,99)));
assert_eq!(2500.0, table.get_sum((50,0),(99,49)));
assert_eq!(2500.0, table.get_sum((0,50),(49,99)));
}
#[test]
fn ones_quartered_vec() {
let mat = DMat::from_elem(100,100,1);
let src = VecSource::new(mat.as_vec(), 100,100);
let table = src.calculate_full_summed_area_table();
assert_eq!(2500.0, table.get_sum((0,0),(49,49)));
assert_eq!(2500.0, table.get_sum((50,50),(99,99)));
assert_eq!(2500.0, table.get_sum((50,0),(99,49)));
assert_eq!(2500.0, table.get_sum((0,50),(49,99)));
}
#[test]
fn twos_quartered() {
let src: DMat<usize> = DMat::from_elem(100,100,2);
let table = src.calculate_full_summed_area_table();
assert_eq!(5000.0, table.get_sum((0,0),(49,49)));
assert_eq!(5000.0, table.get_sum((50,50),(99,99)));
assert_eq!(5000.0, table.get_sum((50,0),(99,49)));
assert_eq!(5000.0, table.get_sum((0,50),(49,99)));
}
#[test]
fn first_row() {
let src: DMat<usize> = DMat::from_elem(10,20,1);
let table = src.calculate_full_summed_area_table();
assert_eq!(20.0, table.get_sum((0,0),(19,0)));
}
#[test]
fn first_col() {
let src: DMat<usize> = DMat::from_elem(50,100,1);
let table = src.calculate_full_summed_area_table();
assert_eq!(50.0, table.get_sum((0,0),(0,49)));
}
#[test]
fn from_to_equal() {
let src: DMat<usize> = DMat::from_elem(100,100,1);
let table = src.calculate_full_summed_area_table();
assert_eq!(1.0, table.get_sum((0,0),(0,0)));
assert_eq!(1.0, table.get_sum((50,50),(50,50)));
assert_eq!(1.0, table.get_sum((99,99),(99,99)));
}
#[test]
fn custom() {
let src: DMat<f64> = DMat::from_row_vec(5,5, &[
5.0,2.0,3.0,4.0,1.0,
1.0,5.0,4.0,2.0,3.0,
2.0,2.0,1.0,3.0,4.0,
3.0,5.0,6.0,4.0,5.0,
4.0,1.0,3.0,2.0,6.0
]);
let expected_table: DMat<f64> = DMat::from_row_vec(5,5, &[
5.0,7.0,10.0,14.0,15.0,
6.0,13.0,20.0,26.0,30.0,
8.0,17.0,25.0,34.0,42.0,
11.0,25.0,39.0,52.0,65.0,
15.0,30.0,47.0,62.0,81.0
]);
let table = src.calculate_full_summed_area_table();
for row in 0 .. 5 {
for col in 0 .. 5 {
assert_eq!(expected_table[(row,col)], table.table[(row,col)]);
}
};
for x in 0 .. 5 {
for y in 0 .. 5 {
assert_eq!(expected_table[(y,x)].as_f64(), table.get_sum((0,0), (x,y)));
}
}
}
#[test]
fn vec_to_dmat() {
let src = util::vec_to_dmat(&vec![0,1,2,3,4,5]);
assert_eq!(1, src.ncols());
assert_eq!(6, src.nrows());
let table = src.calculate_full_summed_area_table();
assert_eq!(6, table.get_overall_data_count());
assert_eq!(15.0, table.get_overall_sum());
}
#[test]
fn src_and_sat_same_size() {
let src: DMat<usize> = DMat::new_zeros(100,100);
let table = src.calculate_full_summed_area_table();
assert_eq!(src.nrows(), table.table.nrows());
assert_eq!(src.ncols(), table.table.ncols());
}
#[test]
#[should_panic]
fn bound_check_x() {
let src: DMat<usize> = DMat::new_zeros(50,100);
let table = src.calculate_full_summed_area_table();
table.get_sum((0,0),(50,99));
}
#[test]
#[should_panic]
fn bound_check_y() {
let src: DMat<usize> = DMat::new_zeros(50,100);
let table = src.calculate_full_summed_area_table();
table.get_sum((0,0),(49,100));
}
#[test]
#[should_panic]
fn point_order_check1() {
let src: DMat<usize> = DMat::new_zeros(50,100);
let table = src.calculate_full_summed_area_table();
table.get_sum((49,99),(48,98));
}
#[test]
#[should_panic]
fn point_order_check2() {
let src: DMat<usize> = DMat::new_zeros(50,100);
let table = src.calculate_full_summed_area_table();
table.get_sum((49,99),(48,99));
}
#[test]
#[should_panic]
fn point_order_check3() {
let src: DMat<usize> = DMat::new_zeros(50,100);
let table = src.calculate_full_summed_area_table();
table.get_sum((49,99),(49,98));
}<|fim▁end|> | pub fn get_overall_average(&self) -> f64{
self.get_average((0,0),(self.table.ncols()-1,self.table.nrows()-1))
}
|
<|file_name|>test_multithreading.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2013 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import time
try:
from unittest import mock
except ImportError:
import mock
import testtools
import threading
import six
from six.moves.queue import Queue, Empty
from swiftclient import multithreading as mt
from swiftclient.exceptions import ClientException
class ThreadTestCase(testtools.TestCase):
def setUp(self):
super(ThreadTestCase, self).setUp()
self.got_args_kwargs = Queue()
self.starting_thread_count = threading.active_count()
def _func(self, q_item, *args, **kwargs):
self.got_items.put(q_item)
self.got_args_kwargs.put((args, kwargs))
if q_item == 'go boom':
raise Exception('I went boom!')
if q_item == 'c boom':
raise ClientException(
'Client Boom', http_scheme='http', http_host='192.168.22.1',
http_port=80, http_path='/booze', http_status=404,
http_reason='to much', http_response_content='no sir!')
return 'best result EVAR!'
def assertQueueContains(self, queue, expected_contents):
got_contents = []
try:
while True:
got_contents.append(queue.get(timeout=0.1))
except Empty:
pass
if isinstance(expected_contents, set):
got_contents = set(got_contents)
self.assertEqual(expected_contents, got_contents)
class TestQueueFunctionThread(ThreadTestCase):
def setUp(self):
super(TestQueueFunctionThread, self).setUp()
self.input_queue = Queue()
self.got_items = Queue()
self.stored_results = []
self.qft = mt.QueueFunctionThread(self.input_queue, self._func,
'one_arg', 'two_arg',
red_fish='blue_arg',
store_results=self.stored_results)
self.qft.start()
def tearDown(self):
if self.qft.is_alive():
self.finish_up_thread()
super(TestQueueFunctionThread, self).tearDown()
def finish_up_thread(self):
self.input_queue.put(mt.StopWorkerThreadSignal())
while self.qft.is_alive():
time.sleep(0.05)
def test_plumbing_and_store_results(self):
self.input_queue.put('abc')
self.input_queue.put(123)
self.finish_up_thread()
self.assertQueueContains(self.got_items, ['abc', 123])
self.assertQueueContains(self.got_args_kwargs, [
(('one_arg', 'two_arg'), {'red_fish': 'blue_arg'}),
(('one_arg', 'two_arg'), {'red_fish': 'blue_arg'})])
self.assertEqual(self.stored_results,
['best result EVAR!', 'best result EVAR!'])
def test_exception_handling(self):
self.input_queue.put('go boom')
self.input_queue.put('ok')
self.input_queue.put('go boom')
self.finish_up_thread()
self.assertQueueContains(self.got_items,
['go boom', 'ok', 'go boom'])
self.assertEqual(len(self.qft.exc_infos), 2)
self.assertEqual(Exception, self.qft.exc_infos[0][0])
self.assertEqual(Exception, self.qft.exc_infos[1][0])
self.assertEqual(('I went boom!',), self.qft.exc_infos[0][1].args)
self.assertEqual(('I went boom!',), self.qft.exc_infos[1][1].args)
class TestQueueFunctionManager(ThreadTestCase):
def setUp(self):
super(TestQueueFunctionManager, self).setUp()
self.thread_manager = mock.create_autospec(
mt.MultiThreadingManager, spec_set=True, instance=True)
self.thread_count = 4
self.error_counter = [0]
self.got_items = Queue()
self.stored_results = []
self.qfq = mt.QueueFunctionManager(
self._func, self.thread_count, self.thread_manager,
thread_args=('1arg', '2arg'),
thread_kwargs={'a': 'b', 'store_results': self.stored_results},
error_counter=self.error_counter,
connection_maker=self.connection_maker)
def connection_maker(self):
return 'yup, I made a connection'
def test_context_manager_without_error_counter(self):
self.qfq = mt.QueueFunctionManager(
self._func, self.thread_count, self.thread_manager,
thread_args=('1arg', '2arg'),
thread_kwargs={'a': 'b', 'store_results': self.stored_results},
connection_maker=self.connection_maker)
with self.qfq as input_queue:
self.assertEqual(self.starting_thread_count + self.thread_count,
threading.active_count())
input_queue.put('go boom')
self.assertEqual(self.starting_thread_count, threading.active_count())
error_strs = list(map(str, self.thread_manager.error.call_args_list))
self.assertEqual(1, len(error_strs))
self.assertTrue('Exception: I went boom!' in error_strs[0])
def test_context_manager_without_conn_maker_or_error_counter(self):
self.qfq = mt.QueueFunctionManager(
self._func, self.thread_count, self.thread_manager,
thread_args=('1arg', '2arg'), thread_kwargs={'a': 'b'})
with self.qfq as input_queue:
self.assertEqual(self.starting_thread_count + self.thread_count,
threading.active_count())
for i in range(20):
input_queue.put('slap%d' % i)
self.assertEqual(self.starting_thread_count, threading.active_count())
self.assertEqual([], self.thread_manager.error.call_args_list)
self.assertEqual(0, self.error_counter[0])
self.assertQueueContains(self.got_items,
set(['slap%d' % i for i in range(20)]))
self.assertQueueContains(
self.got_args_kwargs,
[(('1arg', '2arg'), {'a': 'b'})] * 20)
self.assertEqual(self.stored_results, [])
def test_context_manager_with_exceptions(self):
with self.qfq as input_queue:
self.assertEqual(self.starting_thread_count + self.thread_count,
threading.active_count())
for i in range(20):
input_queue.put('item%d' % i if i % 2 == 0 else 'go boom')
self.assertEqual(self.starting_thread_count, threading.active_count())
error_strs = list(map(str, self.thread_manager.error.call_args_list))
self.assertEqual(10, len(error_strs))
self.assertTrue(all(['Exception: I went boom!' in s for s in
error_strs]))
self.assertEqual(10, self.error_counter[0])
expected_items = set(['go boom'] +
['item%d' % i for i in range(20)
if i % 2 == 0])
self.assertQueueContains(self.got_items, expected_items)
self.assertQueueContains(
self.got_args_kwargs,
[(('yup, I made a connection', '1arg', '2arg'), {'a': 'b'})] * 20)
self.assertEqual(self.stored_results, ['best result EVAR!'] * 10)
def test_context_manager_with_client_exceptions(self):
with self.qfq as input_queue:
self.assertEqual(self.starting_thread_count + self.thread_count,
threading.active_count())
for i in range(20):
input_queue.put('item%d' % i if i % 2 == 0 else 'c boom')
self.assertEqual(self.starting_thread_count, threading.active_count())
error_strs = list(map(str, self.thread_manager.error.call_args_list))
self.assertEqual(10, len(error_strs))
stringification = 'Client Boom: ' \
'http://192.168.22.1:80/booze 404 to much no sir!'
self.assertTrue(all([stringification in s for s in error_strs]))
self.assertEqual(10, self.error_counter[0])
expected_items = set(['c boom'] +
['item%d' % i for i in range(20)
if i % 2 == 0])
self.assertQueueContains(self.got_items, expected_items)
self.assertQueueContains(
self.got_args_kwargs,
[(('yup, I made a connection', '1arg', '2arg'), {'a': 'b'})] * 20)
self.assertEqual(self.stored_results, ['best result EVAR!'] * 10)
def test_context_manager_with_connection_maker(self):
with self.qfq as input_queue:
self.assertEqual(self.starting_thread_count + self.thread_count,
threading.active_count())
for i in range(20):
input_queue.put('item%d' % i)
self.assertEqual(self.starting_thread_count, threading.active_count())
self.assertEqual([], self.thread_manager.error.call_args_list)<|fim▁hole|> self.got_args_kwargs,
[(('yup, I made a connection', '1arg', '2arg'), {'a': 'b'})] * 20)
self.assertEqual(self.stored_results, ['best result EVAR!'] * 20)
class TestMultiThreadingManager(ThreadTestCase):
@mock.patch('swiftclient.multithreading.QueueFunctionManager')
def test_instantiation(self, mock_qfq):
thread_manager = mt.MultiThreadingManager()
self.assertEqual([
mock.call(thread_manager._print, 1, thread_manager),
mock.call(thread_manager._print_error, 1, thread_manager),
], mock_qfq.call_args_list)
# These contexts don't get entered into until the
# MultiThreadingManager's context is entered.
self.assertEqual([], thread_manager.printer.__enter__.call_args_list)
self.assertEqual([],
thread_manager.error_printer.__enter__.call_args_list)
# Test default values for the streams.
self.assertEqual(sys.stdout, thread_manager.print_stream)
self.assertEqual(sys.stderr, thread_manager.error_stream)
@mock.patch('swiftclient.multithreading.QueueFunctionManager')
def test_queue_manager_no_args(self, mock_qfq):
thread_manager = mt.MultiThreadingManager()
mock_qfq.reset_mock()
mock_qfq.return_value = 'slap happy!'
self.assertEqual(
'slap happy!',
thread_manager.queue_manager(self._func, 88))
self.assertEqual([
mock.call(self._func, 88, thread_manager, thread_args=(),
thread_kwargs={}, connection_maker=None,
error_counter=None)
], mock_qfq.call_args_list)
@mock.patch('swiftclient.multithreading.QueueFunctionManager')
def test_queue_manager_with_args(self, mock_qfq):
thread_manager = mt.MultiThreadingManager()
mock_qfq.reset_mock()
mock_qfq.return_value = 'do run run'
self.assertEqual(
'do run run',
thread_manager.queue_manager(self._func, 88, 'fun', times='are',
connection_maker='abc', to='be had',
error_counter='def'))
self.assertEqual([
mock.call(self._func, 88, thread_manager, thread_args=('fun',),
thread_kwargs={'times': 'are', 'to': 'be had'},
connection_maker='abc', error_counter='def')
], mock_qfq.call_args_list)
def test_printers(self):
out_stream = six.StringIO()
err_stream = six.StringIO()
with mt.MultiThreadingManager(
print_stream=out_stream,
error_stream=err_stream) as thread_manager:
# Sanity-checking these gives power to the previous test which
# looked at the default values of thread_manager.print/error_stream
self.assertEqual(out_stream, thread_manager.print_stream)
self.assertEqual(err_stream, thread_manager.error_stream)
self.assertEqual(self.starting_thread_count + 2,
threading.active_count())
thread_manager.print_msg('one-argument')
thread_manager.print_msg('one %s, %d fish', 'fish', 88)
thread_manager.error('I have %d problems, but a %s is not one',
99, u'\u062A\u062A')
thread_manager.print_msg('some\n%s\nover the %r', 'where',
u'\u062A\u062A')
thread_manager.error('one-error-argument')
thread_manager.error('Sometimes\n%.1f%% just\ndoes not\nwork!',
3.14159)
self.assertEqual(self.starting_thread_count, threading.active_count())
out_stream.seek(0)
if six.PY3:
over_the = "over the '\u062a\u062a'\n"
else:
over_the = "over the u'\\u062a\\u062a'\n"
self.assertEqual([
'one-argument\n',
'one fish, 88 fish\n',
'some\n', 'where\n', over_the,
], list(out_stream.readlines()))
err_stream.seek(0)
first_item = u'I have 99 problems, but a \u062A\u062A is not one\n'
if six.PY2:
first_item = first_item.encode('utf8')
self.assertEqual([
first_item,
'one-error-argument\n',
'Sometimes\n', '3.1% just\n', 'does not\n', 'work!\n',
], list(err_stream.readlines()))
self.assertEqual(3, thread_manager.error_count)
if __name__ == '__main__':
testtools.main()<|fim▁end|> | self.assertEqual(0, self.error_counter[0])
self.assertQueueContains(self.got_items,
set(['item%d' % i for i in range(20)]))
self.assertQueueContains( |
<|file_name|>GymEvent.py<|end_file_name|><|fim▁begin|><|fim▁hole|># Local Imports
from PokeAlarm.Utils import get_gmaps_link, get_applemaps_link, \
get_waze_link, get_dist_as_str, get_team_emoji, get_ex_eligible_emoji
from . import BaseEvent
from PokeAlarm import Unknown
class GymEvent(BaseEvent):
""" Event representing the change occurred in a Gym. """
def __init__(self, data):
""" Creates a new Gym Event based on the given dict. """
super(GymEvent, self).__init__('gym')
check_for_none = BaseEvent.check_for_none
# Identification
self.gym_id = data.get('gym_id', data.get('id'))
# Location
self.lat = float(data['latitude'])
self.lng = float(data['longitude'])
self.distance = Unknown.SMALL # Completed by Manager
self.direction = Unknown.TINY # Completed by Manager
# Team Info
self.old_team_id = Unknown.TINY
self.new_team_id = int(data.get('team_id', data.get('team')))
# Gym Details
self.gym_name = check_for_none(
str, data.get('name'), Unknown.REGULAR).strip()
self.gym_description = check_for_none(
str, data.get('description'), Unknown.REGULAR).strip()
self.gym_image = check_for_none(
str, data.get('url'), Unknown.REGULAR)
self.ex_eligible = check_for_none(
int, data.get('is_ex_raid_eligible'), Unknown.REGULAR)
# Gym Guards
self.slots_available = check_for_none(
int, data.get('slots_available'), Unknown.TINY)
self.guard_count = (
(6 - self.slots_available)
if Unknown.is_not(self.slots_available)
else Unknown.TINY)
self.name = self.gym_id
self.geofence = Unknown.REGULAR
self.custom_dts = {}
def generate_dts(self, locale, timezone, units):
""" Return a dict with all the DTS for this event. """
dts = self.custom_dts.copy()
dts.update({
# Identification
'gym_id': self.gym_id,
# Location
'lat': self.lat,
'lng': self.lng,
'lat_5': "{:.5f}".format(self.lat),
'lng_5': "{:.5f}".format(self.lng),
'distance': (
get_dist_as_str(self.distance, units)
if Unknown.is_not(self.distance) else Unknown.SMALL),
'direction': self.direction,
'gmaps': get_gmaps_link(self.lat, self.lng),
'applemaps': get_applemaps_link(self.lat, self.lng),
'waze': get_waze_link(self.lat, self.lng),
'geofence': self.geofence,
# Team Info
'old_team': locale.get_team_name(self.old_team_id),
'old_team_id': self.old_team_id,
'old_team_emoji': get_team_emoji(self.old_team_id),
'old_team_color': locale.get_team_color(self.old_team_id),
'old_team_leader': locale.get_leader_name(self.old_team_id),
'new_team': locale.get_team_name(self.new_team_id),
'new_team_id': self.new_team_id,
'new_team_emoji': get_team_emoji(self.new_team_id),
'new_team_color': locale.get_team_color(self.new_team_id),
'new_team_leader': locale.get_leader_name(self.new_team_id),
# Details
'gym_name': self.gym_name,
'gym_description': self.gym_description,
'gym_image': self.gym_image,
'ex_eligible':
self.ex_eligible > 0 if Unknown.is_not(self.ex_eligible)
else Unknown.REGULAR,
'ex_eligible_emoji': get_ex_eligible_emoji(self.ex_eligible),
# Guards
'slots_available': self.slots_available,
'guard_count': self.guard_count,
})
return dts<|fim▁end|> | # Standard Library Imports
# 3rd Party Imports |
<|file_name|>c3.js<|end_file_name|><|fim▁begin|>(function (window) {
'use strict';
/*global define, module, exports, require */
var c3 = { version: "0.4.11" };
var c3_chart_fn,
c3_chart_internal_fn,
c3_chart_internal_axis_fn;
function API(owner) {
this.owner = owner;
}
function inherit(base, derived) {
if (Object.create) {
derived.prototype = Object.create(base.prototype);
} else {
var f = function f() {};
f.prototype = base.prototype;
derived.prototype = new f();
}
derived.prototype.constructor = derived;
return derived;
}
function Chart(config) {
var $$ = this.internal = new ChartInternal(this);
$$.loadConfig(config);
$$.beforeInit(config);
$$.init();
$$.afterInit(config);
// bind "this" to nested API
(function bindThis(fn, target, argThis) {
Object.keys(fn).forEach(function (key) {
target[key] = fn[key].bind(argThis);
if (Object.keys(fn[key]).length > 0) {
bindThis(fn[key], target[key], argThis);
}
});
})(c3_chart_fn, this, this);
}
function ChartInternal(api) {
var $$ = this;
$$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
$$.api = api;
$$.config = $$.getDefaultConfig();
$$.data = {};
$$.cache = {};
$$.axes = {};
}
c3.generate = function (config) {
return new Chart(config);
};
c3.chart = {
fn: Chart.prototype,
internal: {
fn: ChartInternal.prototype,
axis: {
fn: Axis.prototype
}
}
};
c3_chart_fn = c3.chart.fn;
c3_chart_internal_fn = c3.chart.internal.fn;
c3_chart_internal_axis_fn = c3.chart.internal.axis.fn;
c3_chart_internal_fn.beforeInit = function () {
// can do something
};
c3_chart_internal_fn.afterInit = function () {
// can do something
};
c3_chart_internal_fn.init = function () {
var $$ = this, config = $$.config;
$$.initParams();
if (config.data_url) {
$$.convertUrlToData(config.data_url, config.data_mimeType, config.data_headers, config.data_keys, $$.initWithData);
}
else if (config.data_json) {
$$.initWithData($$.convertJsonToData(config.data_json, config.data_keys));
}
else if (config.data_rows) {
$$.initWithData($$.convertRowsToData(config.data_rows));
}
else if (config.data_columns) {
$$.initWithData($$.convertColumnsToData(config.data_columns));
}
else {
throw Error('url or json or rows or columns is required.');
}
};
c3_chart_internal_fn.initParams = function () {
var $$ = this, d3 = $$.d3, config = $$.config;
// MEMO: clipId needs to be unique because it conflicts when multiple charts exist
$$.clipId = "c3-" + (+new Date()) + '-clip',
$$.clipIdForXAxis = $$.clipId + '-xaxis',
$$.clipIdForYAxis = $$.clipId + '-yaxis',
$$.clipIdForGrid = $$.clipId + '-grid',
$$.clipIdForSubchart = $$.clipId + '-subchart',
$$.clipPath = $$.getClipPath($$.clipId),
$$.clipPathForXAxis = $$.getClipPath($$.clipIdForXAxis),
$$.clipPathForYAxis = $$.getClipPath($$.clipIdForYAxis);
$$.clipPathForGrid = $$.getClipPath($$.clipIdForGrid),
$$.clipPathForSubchart = $$.getClipPath($$.clipIdForSubchart),
$$.dragStart = null;
$$.dragging = false;
$$.flowing = false;
$$.cancelClick = false;
$$.mouseover = false;
$$.transiting = false;
$$.color = $$.generateColor();
$$.levelColor = $$.generateLevelColor();
$$.dataTimeFormat = config.data_xLocaltime ? d3.time.format : d3.time.format.utc;
$$.axisTimeFormat = config.axis_x_localtime ? d3.time.format : d3.time.format.utc;
$$.defaultAxisTimeFormat = $$.axisTimeFormat.multi([
[".%L", function (d) { return d.getMilliseconds(); }],
[":%S", function (d) { return d.getSeconds(); }],
["%I:%M", function (d) { return d.getMinutes(); }],
["%I %p", function (d) { return d.getHours(); }],
["%-m/%-d", function (d) { return d.getDay() && d.getDate() !== 1; }],
["%-m/%-d", function (d) { return d.getDate() !== 1; }],
["%-m/%-d", function (d) { return d.getMonth(); }],
["%Y/%-m/%-d", function () { return true; }]
]);
$$.hiddenTargetIds = [];
$$.hiddenLegendIds = [];
$$.focusedTargetIds = [];
$$.defocusedTargetIds = [];
$$.xOrient = config.axis_rotated ? "left" : "bottom";
$$.yOrient = config.axis_rotated ? (config.axis_y_inner ? "top" : "bottom") : (config.axis_y_inner ? "right" : "left");
$$.y2Orient = config.axis_rotated ? (config.axis_y2_inner ? "bottom" : "top") : (config.axis_y2_inner ? "left" : "right");
$$.subXOrient = config.axis_rotated ? "left" : "bottom";
$$.isLegendRight = config.legend_position === 'right';
$$.isLegendInset = config.legend_position === 'inset';
$$.isLegendTop = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'top-right';
$$.isLegendLeft = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'bottom-left';
$$.legendStep = 0;
$$.legendItemWidth = 0;
$$.legendItemHeight = 0;
$$.currentMaxTickWidths = {
x: 0,
y: 0,
y2: 0
};
$$.rotated_padding_left = 30;
$$.rotated_padding_right = config.axis_rotated && !config.axis_x_show ? 0 : 30;
$$.rotated_padding_top = 5;
$$.withoutFadeIn = {};
$$.intervalForObserveInserted = undefined;
$$.axes.subx = d3.selectAll([]); // needs when excluding subchart.js
};
c3_chart_internal_fn.initChartElements = function () {
if (this.initBar) { this.initBar(); }
if (this.initLine) { this.initLine(); }
if (this.initArc) { this.initArc(); }
if (this.initGauge) { this.initGauge(); }
if (this.initText) { this.initText(); }
};
c3_chart_internal_fn.initWithData = function (data) {
var $$ = this, d3 = $$.d3, config = $$.config;
var defs, main, binding = true;
$$.axis = new Axis($$);
if ($$.initPie) { $$.initPie(); }
if ($$.initBrush) { $$.initBrush(); }
if ($$.initZoom) { $$.initZoom(); }
if (!config.bindto) {
$$.selectChart = d3.selectAll([]);
}
else if (typeof config.bindto.node === 'function') {
$$.selectChart = config.bindto;
}
else {
$$.selectChart = d3.select(config.bindto);
}
if ($$.selectChart.empty()) {
$$.selectChart = d3.select(document.createElement('div')).style('opacity', 0);
$$.observeInserted($$.selectChart);
binding = false;
}
$$.selectChart.html("").classed("c3", true);
// Init data as targets
$$.data.xs = {};
$$.data.targets = $$.convertDataToTargets(data);
if (config.data_filter) {
$$.data.targets = $$.data.targets.filter(config.data_filter);
}
// Set targets to hide if needed
if (config.data_hide) {
$$.addHiddenTargetIds(config.data_hide === true ? $$.mapToIds($$.data.targets) : config.data_hide);
}
if (config.legend_hide) {
$$.addHiddenLegendIds(config.legend_hide === true ? $$.mapToIds($$.data.targets) : config.legend_hide);
}
// when gauge, hide legend // TODO: fix
if ($$.hasType('gauge')) {
config.legend_show = false;
}
// Init sizes and scales
$$.updateSizes();
$$.updateScales();
// Set domains for each scale
$$.x.domain(d3.extent($$.getXDomain($$.data.targets)));
$$.y.domain($$.getYDomain($$.data.targets, 'y'));
$$.y2.domain($$.getYDomain($$.data.targets, 'y2'));
$$.subX.domain($$.x.domain());
$$.subY.domain($$.y.domain());
$$.subY2.domain($$.y2.domain());
// Save original x domain for zoom update
$$.orgXDomain = $$.x.domain();
// Set initialized scales to brush and zoom
if ($$.brush) { $$.brush.scale($$.subX); }
if (config.zoom_enabled) { $$.zoom.scale($$.x); }
/*-- Basic Elements --*/
// Define svgs
$$.svg = $$.selectChart.append("svg")
.style("overflow", "hidden")
.on('mouseenter', function () { return config.onmouseover.call($$); })
.on('mouseleave', function () { return config.onmouseout.call($$); });
if ($$.config.svg_classname) {
$$.svg.attr('class', $$.config.svg_classname);
}
// Define defs
defs = $$.svg.append("defs");
$$.clipChart = $$.appendClip(defs, $$.clipId);
$$.clipXAxis = $$.appendClip(defs, $$.clipIdForXAxis);
$$.clipYAxis = $$.appendClip(defs, $$.clipIdForYAxis);
$$.clipGrid = $$.appendClip(defs, $$.clipIdForGrid);
$$.clipSubchart = $$.appendClip(defs, $$.clipIdForSubchart);
$$.updateSvgSize();
// Define regions
main = $$.main = $$.svg.append("g").attr("transform", $$.getTranslate('main'));
if ($$.initSubchart) { $$.initSubchart(); }
if ($$.initTooltip) { $$.initTooltip(); }
if ($$.initLegend) { $$.initLegend(); }
if ($$.initTitle) { $$.initTitle(); }
/*-- Main Region --*/
// text when empty
main.append("text")
.attr("class", CLASS.text + ' ' + CLASS.empty)
.attr("text-anchor", "middle") // horizontal centering of text at x position in all browsers.
.attr("dominant-baseline", "middle"); // vertical centering of text at y position in all browsers, except IE.
// Regions
$$.initRegion();
// Grids
$$.initGrid();
// Define g for chart area
main.append('g')
.attr("clip-path", $$.clipPath)
.attr('class', CLASS.chart);
// Grid lines
if (config.grid_lines_front) { $$.initGridLines(); }
// Cover whole with rects for events
$$.initEventRect();
// Define g for chart
$$.initChartElements();
// if zoom privileged, insert rect to forefront
// TODO: is this needed?
main.insert('rect', config.zoom_privileged ? null : 'g.' + CLASS.regions)
.attr('class', CLASS.zoomRect)
.attr('width', $$.width)
.attr('height', $$.height)
.style('opacity', 0)
.on("dblclick.zoom", null);
// Set default extent if defined
if (config.axis_x_extent) { $$.brush.extent($$.getDefaultExtent()); }
// Add Axis
$$.axis.init();
// Set targets
$$.updateTargets($$.data.targets);
// Draw with targets
if (binding) {
$$.updateDimension();
$$.config.oninit.call($$);
$$.redraw({
withTransition: false,
withTransform: true,
withUpdateXDomain: true,
withUpdateOrgXDomain: true,
withTransitionForAxis: false
});
}
// Bind resize event
$$.bindResize();
// export element of the chart
$$.api.element = $$.selectChart.node();
};
c3_chart_internal_fn.smoothLines = function (el, type) {
var $$ = this;
if (type === 'grid') {
el.each(function () {
var g = $$.d3.select(this),
x1 = g.attr('x1'),
x2 = g.attr('x2'),
y1 = g.attr('y1'),
y2 = g.attr('y2');
g.attr({
'x1': Math.ceil(x1),
'x2': Math.ceil(x2),
'y1': Math.ceil(y1),
'y2': Math.ceil(y2)
});
});
}
};
c3_chart_internal_fn.updateSizes = function () {
var $$ = this, config = $$.config;
var legendHeight = $$.legend ? $$.getLegendHeight() : 0,
legendWidth = $$.legend ? $$.getLegendWidth() : 0,
legendHeightForBottom = $$.isLegendRight || $$.isLegendInset ? 0 : legendHeight,
hasArc = $$.hasArcType(),
xAxisHeight = config.axis_rotated || hasArc ? 0 : $$.getHorizontalAxisHeight('x'),
subchartHeight = config.subchart_show && !hasArc ? (config.subchart_size_height + xAxisHeight) : 0;
$$.currentWidth = $$.getCurrentWidth();
$$.currentHeight = $$.getCurrentHeight();
// for main
$$.margin = config.axis_rotated ? {
top: $$.getHorizontalAxisHeight('y2') + $$.getCurrentPaddingTop(),
right: hasArc ? 0 : $$.getCurrentPaddingRight(),
bottom: $$.getHorizontalAxisHeight('y') + legendHeightForBottom + $$.getCurrentPaddingBottom(),
left: subchartHeight + (hasArc ? 0 : $$.getCurrentPaddingLeft())
} : {
top: 4 + $$.getCurrentPaddingTop(), // for top tick text
right: hasArc ? 0 : $$.getCurrentPaddingRight(),
bottom: xAxisHeight + subchartHeight + legendHeightForBottom + $$.getCurrentPaddingBottom(),
left: hasArc ? 0 : $$.getCurrentPaddingLeft()
};
// for subchart
$$.margin2 = config.axis_rotated ? {
top: $$.margin.top,
right: NaN,
bottom: 20 + legendHeightForBottom,
left: $$.rotated_padding_left
} : {
top: $$.currentHeight - subchartHeight - legendHeightForBottom,
right: NaN,
bottom: xAxisHeight + legendHeightForBottom,
left: $$.margin.left
};
// for legend
$$.margin3 = {
top: 0,
right: NaN,
bottom: 0,
left: 0
};
if ($$.updateSizeForLegend) { $$.updateSizeForLegend(legendHeight, legendWidth); }
$$.width = $$.currentWidth - $$.margin.left - $$.margin.right;
$$.height = $$.currentHeight - $$.margin.top - $$.margin.bottom;
if ($$.width < 0) { $$.width = 0; }
if ($$.height < 0) { $$.height = 0; }
$$.width2 = config.axis_rotated ? $$.margin.left - $$.rotated_padding_left - $$.rotated_padding_right : $$.width;
$$.height2 = config.axis_rotated ? $$.height : $$.currentHeight - $$.margin2.top - $$.margin2.bottom;
if ($$.width2 < 0) { $$.width2 = 0; }
if ($$.height2 < 0) { $$.height2 = 0; }
// for arc
$$.arcWidth = $$.width - ($$.isLegendRight ? legendWidth + 10 : 0);
$$.arcHeight = $$.height - ($$.isLegendRight ? 0 : 10);
if ($$.hasType('gauge') && !config.gauge_fullCircle) {
$$.arcHeight += $$.height - $$.getGaugeLabelHeight();
}
if ($$.updateRadius) { $$.updateRadius(); }
if ($$.isLegendRight && hasArc) {
$$.margin3.left = $$.arcWidth / 2 + $$.radiusExpanded * 1.1;
}
};
c3_chart_internal_fn.updateTargets = function (targets) {
var $$ = this;
/*-- Main --*/
//-- Text --//
$$.updateTargetsForText(targets);
//-- Bar --//
$$.updateTargetsForBar(targets);
//-- Line --//
$$.updateTargetsForLine(targets);
//-- Arc --//
if ($$.hasArcType() && $$.updateTargetsForArc) { $$.updateTargetsForArc(targets); }
/*-- Sub --*/
if ($$.updateTargetsForSubchart) { $$.updateTargetsForSubchart(targets); }
// Fade-in each chart
$$.showTargets();
};
c3_chart_internal_fn.showTargets = function () {
var $$ = this;
$$.svg.selectAll('.' + CLASS.target).filter(function (d) { return $$.isTargetToShow(d.id); })
.transition().duration($$.config.transition_duration)
.style("opacity", 1);
};
c3_chart_internal_fn.redraw = function (options, transitions) {
var $$ = this, main = $$.main, d3 = $$.d3, config = $$.config;
var areaIndices = $$.getShapeIndices($$.isAreaType), barIndices = $$.getShapeIndices($$.isBarType), lineIndices = $$.getShapeIndices($$.isLineType);
var withY, withSubchart, withTransition, withTransitionForExit, withTransitionForAxis,
withTransform, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain, withLegend,
withEventRect, withDimension, withUpdateXAxis;
var hideAxis = $$.hasArcType();
var drawArea, drawBar, drawLine, xForText, yForText;
var duration, durationForExit, durationForAxis;
var waitForDraw, flow;
var targetsToShow = $$.filterTargetsToShow($$.data.targets), tickValues, i, intervalForCulling, xDomainForZoom;
var xv = $$.xv.bind($$), cx, cy;
options = options || {};
withY = getOption(options, "withY", true);
withSubchart = getOption(options, "withSubchart", true);
withTransition = getOption(options, "withTransition", true);
withTransform = getOption(options, "withTransform", false);
withUpdateXDomain = getOption(options, "withUpdateXDomain", false);
withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", false);
withTrimXDomain = getOption(options, "withTrimXDomain", true);
withUpdateXAxis = getOption(options, "withUpdateXAxis", withUpdateXDomain);
withLegend = getOption(options, "withLegend", false);
withEventRect = getOption(options, "withEventRect", true);
withDimension = getOption(options, "withDimension", true);
withTransitionForExit = getOption(options, "withTransitionForExit", withTransition);
withTransitionForAxis = getOption(options, "withTransitionForAxis", withTransition);
duration = withTransition ? config.transition_duration : 0;
durationForExit = withTransitionForExit ? duration : 0;
durationForAxis = withTransitionForAxis ? duration : 0;
transitions = transitions || $$.axis.generateTransitions(durationForAxis);
// update legend and transform each g
if (withLegend && config.legend_show) {
$$.updateLegend($$.mapToIds($$.data.targets), options, transitions);
} else if (withDimension) {
// need to update dimension (e.g. axis.y.tick.values) because y tick values should change
// no need to update axis in it because they will be updated in redraw()
$$.updateDimension(true);
}
// MEMO: needed for grids calculation
if ($$.isCategorized() && targetsToShow.length === 0) {
$$.x.domain([0, $$.axes.x.selectAll('.tick').size()]);
}
if (targetsToShow.length) {
$$.updateXDomain(targetsToShow, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain);
if (!config.axis_x_tick_values) {
tickValues = $$.axis.updateXAxisTickValues(targetsToShow);
}
} else {
$$.xAxis.tickValues([]);
$$.subXAxis.tickValues([]);
}
if (config.zoom_rescale && !options.flow) {
xDomainForZoom = $$.x.orgDomain();
}
$$.y.domain($$.getYDomain(targetsToShow, 'y', xDomainForZoom));
$$.y2.domain($$.getYDomain(targetsToShow, 'y2', xDomainForZoom));
if (!config.axis_y_tick_values && config.axis_y_tick_count) {
$$.yAxis.tickValues($$.axis.generateTickValues($$.y.domain(), config.axis_y_tick_count));
}
if (!config.axis_y2_tick_values && config.axis_y2_tick_count) {
$$.y2Axis.tickValues($$.axis.generateTickValues($$.y2.domain(), config.axis_y2_tick_count));
}
// axes
$$.axis.redraw(transitions, hideAxis);
// Update axis label
$$.axis.updateLabels(withTransition);
// show/hide if manual culling needed
if ((withUpdateXDomain || withUpdateXAxis) && targetsToShow.length) {
if (config.axis_x_tick_culling && tickValues) {
for (i = 1; i < tickValues.length; i++) {
if (tickValues.length / i < config.axis_x_tick_culling_max) {
intervalForCulling = i;
break;
}
}
$$.svg.selectAll('.' + CLASS.axisX + ' .tick text').each(function (e) {
var index = tickValues.indexOf(e);
if (index >= 0) {
d3.select(this).style('display', index % intervalForCulling ? 'none' : 'block');
}
});
} else {
$$.svg.selectAll('.' + CLASS.axisX + ' .tick text').style('display', 'block');
}
}
// setup drawer - MEMO: these must be called after axis updated
drawArea = $$.generateDrawArea ? $$.generateDrawArea(areaIndices, false) : undefined;
drawBar = $$.generateDrawBar ? $$.generateDrawBar(barIndices) : undefined;
drawLine = $$.generateDrawLine ? $$.generateDrawLine(lineIndices, false) : undefined;
xForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, true);
yForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, false);
// Update sub domain
if (withY) {
$$.subY.domain($$.getYDomain(targetsToShow, 'y'));
$$.subY2.domain($$.getYDomain(targetsToShow, 'y2'));
}
// xgrid focus
$$.updateXgridFocus();
// Data empty label positioning and text.
main.select("text." + CLASS.text + '.' + CLASS.empty)
.attr("x", $$.width / 2)
.attr("y", $$.height / 2)
.text(config.data_empty_label_text)
.transition()
.style('opacity', targetsToShow.length ? 0 : 1);
// grid
$$.updateGrid(duration);
// rect for regions
$$.updateRegion(duration);
// bars
$$.updateBar(durationForExit);
// lines, areas and cricles
$$.updateLine(durationForExit);
$$.updateArea(durationForExit);
$$.updateCircle();
// text
if ($$.hasDataLabel()) {
$$.updateText(durationForExit);
}
// title
if ($$.redrawTitle) { $$.redrawTitle(); }
// arc
if ($$.redrawArc) { $$.redrawArc(duration, durationForExit, withTransform); }
// subchart
if ($$.redrawSubchart) {
$$.redrawSubchart(withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices);
}
// circles for select
main.selectAll('.' + CLASS.selectedCircles)
.filter($$.isBarType.bind($$))
.selectAll('circle')
.remove();
// event rects will redrawn when flow called
if (config.interaction_enabled && !options.flow && withEventRect) {
$$.redrawEventRect();
if ($$.updateZoom) { $$.updateZoom(); }
}
// update circleY based on updated parameters
$$.updateCircleY();
// generate circle x/y functions depending on updated params
cx = ($$.config.axis_rotated ? $$.circleY : $$.circleX).bind($$);
cy = ($$.config.axis_rotated ? $$.circleX : $$.circleY).bind($$);
if (options.flow) {
flow = $$.generateFlow({
targets: targetsToShow,
flow: options.flow,
duration: options.flow.duration,
drawBar: drawBar,
drawLine: drawLine,
drawArea: drawArea,
cx: cx,
cy: cy,
xv: xv,
xForText: xForText,
yForText: yForText
});
}
if ((duration || flow) && $$.isTabVisible()) { // Only use transition if tab visible. See #938.
// transition should be derived from one transition
d3.transition().duration(duration).each(function () {
var transitionsToWait = [];
// redraw and gather transitions
[
$$.redrawBar(drawBar, true),
$$.redrawLine(drawLine, true),
$$.redrawArea(drawArea, true),
$$.redrawCircle(cx, cy, true),
$$.redrawText(xForText, yForText, options.flow, true),
$$.redrawRegion(true),
$$.redrawGrid(true),
].forEach(function (transitions) {
transitions.forEach(function (transition) {
transitionsToWait.push(transition);
});
});
// Wait for end of transitions to call flow and onrendered callback
waitForDraw = $$.generateWait();
transitionsToWait.forEach(function (t) {
waitForDraw.add(t);
});
})
.call(waitForDraw, function () {
if (flow) {
flow();
}
if (config.onrendered) {
config.onrendered.call($$);
}
});
}
else {
$$.redrawBar(drawBar);
$$.redrawLine(drawLine);
$$.redrawArea(drawArea);
$$.redrawCircle(cx, cy);
$$.redrawText(xForText, yForText, options.flow);
$$.redrawRegion();
$$.redrawGrid();
if (config.onrendered) {
config.onrendered.call($$);
}
}
// update fadein condition
$$.mapToIds($$.data.targets).forEach(function (id) {
$$.withoutFadeIn[id] = true;
});
};
c3_chart_internal_fn.updateAndRedraw = function (options) {
var $$ = this, config = $$.config, transitions;
options = options || {};
// same with redraw
options.withTransition = getOption(options, "withTransition", true);
options.withTransform = getOption(options, "withTransform", false);
options.withLegend = getOption(options, "withLegend", false);
// NOT same with redraw
options.withUpdateXDomain = true;
options.withUpdateOrgXDomain = true;
options.withTransitionForExit = false;
options.withTransitionForTransform = getOption(options, "withTransitionForTransform", options.withTransition);
// MEMO: this needs to be called before updateLegend and it means this ALWAYS needs to be called)
$$.updateSizes();
// MEMO: called in updateLegend in redraw if withLegend
if (!(options.withLegend && config.legend_show)) {
transitions = $$.axis.generateTransitions(options.withTransitionForAxis ? config.transition_duration : 0);
// Update scales
$$.updateScales();
$$.updateSvgSize();
// Update g positions
$$.transformAll(options.withTransitionForTransform, transitions);
}
// Draw with new sizes & scales
$$.redraw(options, transitions);
};
c3_chart_internal_fn.redrawWithoutRescale = function () {
this.redraw({
withY: false,
withSubchart: false,
withEventRect: false,
withTransitionForAxis: false
});
};
c3_chart_internal_fn.isTimeSeries = function () {
return this.config.axis_x_type === 'timeseries';
};
c3_chart_internal_fn.isCategorized = function () {
return this.config.axis_x_type.indexOf('categor') >= 0;
};
c3_chart_internal_fn.isCustomX = function () {
var $$ = this, config = $$.config;
return !$$.isTimeSeries() && (config.data_x || notEmpty(config.data_xs));
};
c3_chart_internal_fn.isTimeSeriesY = function () {
return this.config.axis_y_type === 'timeseries';
};
c3_chart_internal_fn.getTranslate = function (target) {
var $$ = this, config = $$.config, x, y;
if (target === 'main') {
x = asHalfPixel($$.margin.left);
y = asHalfPixel($$.margin.top);
} else if (target === 'context') {
x = asHalfPixel($$.margin2.left);
y = asHalfPixel($$.margin2.top);
} else if (target === 'legend') {
x = $$.margin3.left;
y = $$.margin3.top;
} else if (target === 'x') {
x = 0;
y = config.axis_rotated ? 0 : $$.height;
} else if (target === 'y') {
x = 0;
y = config.axis_rotated ? $$.height : 0;
} else if (target === 'y2') {
x = config.axis_rotated ? 0 : $$.width;
y = config.axis_rotated ? 1 : 0;
} else if (target === 'subx') {
x = 0;
y = config.axis_rotated ? 0 : $$.height2;
} else if (target === 'arc') {
x = $$.arcWidth / 2;
y = $$.arcHeight / 2;
}
return "translate(" + x + "," + y + ")";
};
c3_chart_internal_fn.initialOpacity = function (d) {
return d.value !== null && this.withoutFadeIn[d.id] ? 1 : 0;
};
c3_chart_internal_fn.initialOpacityForCircle = function (d) {
return d.value !== null && this.withoutFadeIn[d.id] ? this.opacityForCircle(d) : 0;
};
c3_chart_internal_fn.opacityForCircle = function (d) {
var opacity = this.config.point_show ? 1 : 0;
return isValue(d.value) ? (this.isScatterType(d) ? 0.5 : opacity) : 0;
};
c3_chart_internal_fn.opacityForText = function () {
return this.hasDataLabel() ? 1 : 0;
};
c3_chart_internal_fn.xx = function (d) {
return d ? this.x(d.x) : null;
};
c3_chart_internal_fn.xv = function (d) {
var $$ = this, value = d.value;
if ($$.isTimeSeries()) {
value = $$.parseDate(d.value);
}
else if ($$.isCategorized() && typeof d.value === 'string') {
value = $$.config.axis_x_categories.indexOf(d.value);
}
return Math.ceil($$.x(value));
};
c3_chart_internal_fn.yv = function (d) {
var $$ = this,
yScale = d.axis && d.axis === 'y2' ? $$.y2 : $$.y;
return Math.ceil(yScale(d.value));
};
c3_chart_internal_fn.subxx = function (d) {
return d ? this.subX(d.x) : null;
};
c3_chart_internal_fn.transformMain = function (withTransition, transitions) {
var $$ = this,
xAxis, yAxis, y2Axis;
if (transitions && transitions.axisX) {
xAxis = transitions.axisX;
} else {
xAxis = $$.main.select('.' + CLASS.axisX);
if (withTransition) { xAxis = xAxis.transition(); }
}
if (transitions && transitions.axisY) {
yAxis = transitions.axisY;
} else {
yAxis = $$.main.select('.' + CLASS.axisY);
if (withTransition) { yAxis = yAxis.transition(); }
}
if (transitions && transitions.axisY2) {
y2Axis = transitions.axisY2;
} else {
y2Axis = $$.main.select('.' + CLASS.axisY2);
if (withTransition) { y2Axis = y2Axis.transition(); }
}
(withTransition ? $$.main.transition() : $$.main).attr("transform", $$.getTranslate('main'));
xAxis.attr("transform", $$.getTranslate('x'));
yAxis.attr("transform", $$.getTranslate('y'));
y2Axis.attr("transform", $$.getTranslate('y2'));
$$.main.select('.' + CLASS.chartArcs).attr("transform", $$.getTranslate('arc'));
};
c3_chart_internal_fn.transformAll = function (withTransition, transitions) {
var $$ = this;
$$.transformMain(withTransition, transitions);
if ($$.config.subchart_show) { $$.transformContext(withTransition, transitions); }
if ($$.legend) { $$.transformLegend(withTransition); }
};
c3_chart_internal_fn.updateSvgSize = function () {
var $$ = this,
brush = $$.svg.select(".c3-brush .background");
$$.svg.attr('width', $$.currentWidth).attr('height', $$.currentHeight);
$$.svg.selectAll(['#' + $$.clipId, '#' + $$.clipIdForGrid]).select('rect')
.attr('width', $$.width)
.attr('height', $$.height);
$$.svg.select('#' + $$.clipIdForXAxis).select('rect')
.attr('x', $$.getXAxisClipX.bind($$))
.attr('y', $$.getXAxisClipY.bind($$))
.attr('width', $$.getXAxisClipWidth.bind($$))
.attr('height', $$.getXAxisClipHeight.bind($$));
$$.svg.select('#' + $$.clipIdForYAxis).select('rect')
.attr('x', $$.getYAxisClipX.bind($$))
.attr('y', $$.getYAxisClipY.bind($$))
.attr('width', $$.getYAxisClipWidth.bind($$))
.attr('height', $$.getYAxisClipHeight.bind($$));
$$.svg.select('#' + $$.clipIdForSubchart).select('rect')
.attr('width', $$.width)
.attr('height', brush.size() ? brush.attr('height') : 0);
$$.svg.select('.' + CLASS.zoomRect)
.attr('width', $$.width)
.attr('height', $$.height);
// MEMO: parent div's height will be bigger than svg when <!DOCTYPE html>
$$.selectChart.style('max-height', $$.currentHeight + "px");
};
c3_chart_internal_fn.updateDimension = function (withoutAxis) {
var $$ = this;
if (!withoutAxis) {
if ($$.config.axis_rotated) {
$$.axes.x.call($$.xAxis);
$$.axes.subx.call($$.subXAxis);
} else {
$$.axes.y.call($$.yAxis);
$$.axes.y2.call($$.y2Axis);
}
}
$$.updateSizes();
$$.updateScales();
$$.updateSvgSize();
$$.transformAll(false);
};
c3_chart_internal_fn.observeInserted = function (selection) {
var $$ = this, observer;
if (typeof MutationObserver === 'undefined') {
window.console.error("MutationObserver not defined.");
return;
}
observer= new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList' && mutation.previousSibling) {
observer.disconnect();
// need to wait for completion of load because size calculation requires the actual sizes determined after that completion
$$.intervalForObserveInserted = window.setInterval(function () {
// parentNode will NOT be null when completed
if (selection.node().parentNode) {
window.clearInterval($$.intervalForObserveInserted);
$$.updateDimension();
if ($$.brush) { $$.brush.update(); }
$$.config.oninit.call($$);
$$.redraw({
withTransform: true,
withUpdateXDomain: true,
withUpdateOrgXDomain: true,
withTransition: false,
withTransitionForTransform: false,
withLegend: true
});
selection.transition().style('opacity', 1);
}
}, 10);
}
});
});
observer.observe(selection.node(), {attributes: true, childList: true, characterData: true});
};
c3_chart_internal_fn.bindResize = function () {
var $$ = this, config = $$.config;
$$.resizeFunction = $$.generateResize();
$$.resizeFunction.add(function () {
config.onresize.call($$);
});
if (config.resize_auto) {
$$.resizeFunction.add(function () {
if ($$.resizeTimeout !== undefined) {
window.clearTimeout($$.resizeTimeout);
}
$$.resizeTimeout = window.setTimeout(function () {
delete $$.resizeTimeout;
$$.api.flush();
}, 100);
});
}
$$.resizeFunction.add(function () {
config.onresized.call($$);
});
if (window.attachEvent) {
window.attachEvent('onresize', $$.resizeFunction);
} else if (window.addEventListener) {
window.addEventListener('resize', $$.resizeFunction, false);
} else {
// fallback to this, if this is a very old browser
var wrapper = window.onresize;
if (!wrapper) {
// create a wrapper that will call all charts
wrapper = $$.generateResize();
} else if (!wrapper.add || !wrapper.remove) {
// there is already a handler registered, make sure we call it too
wrapper = $$.generateResize();
wrapper.add(window.onresize);
}
// add this graph to the wrapper, we will be removed if the user calls destroy
wrapper.add($$.resizeFunction);
window.onresize = wrapper;
}
};
c3_chart_internal_fn.generateResize = function () {
var resizeFunctions = [];
function callResizeFunctions() {
resizeFunctions.forEach(function (f) {
f();
});
}
callResizeFunctions.add = function (f) {
resizeFunctions.push(f);
};
callResizeFunctions.remove = function (f) {
for (var i = 0; i < resizeFunctions.length; i++) {
if (resizeFunctions[i] === f) {
resizeFunctions.splice(i, 1);
break;
}
}
};
return callResizeFunctions;
};
c3_chart_internal_fn.endall = function (transition, callback) {
var n = 0;
transition
.each(function () { ++n; })
.each("end", function () {
if (!--n) { callback.apply(this, arguments); }
});
};
c3_chart_internal_fn.generateWait = function () {
var transitionsToWait = [],
f = function (transition, callback) {
var timer = setInterval(function () {
var done = 0;
transitionsToWait.forEach(function (t) {
if (t.empty()) {
done += 1;
return;
}
try {
t.transition();
} catch (e) {
done += 1;
}
});
if (done === transitionsToWait.length) {
clearInterval(timer);
if (callback) { callback(); }
}
}, 10);
};
f.add = function (transition) {
transitionsToWait.push(transition);
};
return f;
};
c3_chart_internal_fn.parseDate = function (date) {
var $$ = this, parsedDate;
if (date instanceof Date) {
parsedDate = date;
} else if (typeof date === 'string') {
parsedDate = $$.dataTimeFormat($$.config.data_xFormat).parse(date);
} else if (typeof date === 'number' && !isNaN(date)) {
parsedDate = new Date(+date);
}
if (!parsedDate || isNaN(+parsedDate)) {
window.console.error("Failed to parse x '" + date + "' to Date object");
}
return parsedDate;
};
c3_chart_internal_fn.isTabVisible = function () {
var hidden;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
}
return document[hidden] ? false : true;
};
c3_chart_internal_fn.getDefaultConfig = function () {
var config = {
bindto: '#chart',
svg_classname: undefined,
size_width: undefined,
size_height: undefined,
padding_left: undefined,
padding_right: undefined,
padding_top: undefined,
padding_bottom: undefined,
resize_auto: true,
zoom_enabled: false,
zoom_extent: undefined,
zoom_privileged: false,
zoom_rescale: false,
zoom_onzoom: function () {},
zoom_onzoomstart: function () {},
zoom_onzoomend: function () {},
zoom_x_min: undefined,
zoom_x_max: undefined,
interaction_brighten: true,
interaction_enabled: true,
onmouseover: function () {},
onmouseout: function () {},
onresize: function () {},
onresized: function () {},
oninit: function () {},
onrendered: function () {},
transition_duration: 350,
data_x: undefined,
data_xs: {},
data_xFormat: '%Y-%m-%d',
data_xLocaltime: true,
data_xSort: true,
data_idConverter: function (id) { return id; },
data_names: {},
data_classes: {},
data_groups: [],
data_axes: {},
data_type: undefined,
data_types: {},
data_labels: {},
data_order: 'desc',
data_regions: {},
data_color: undefined,
data_colors: {},
data_hide: false,
data_filter: undefined,
data_selection_enabled: false,
data_selection_grouped: false,
data_selection_isselectable: function () { return true; },
data_selection_multiple: true,
data_selection_draggable: false,
data_onclick: function () {},
data_onmouseover: function () {},
data_onmouseout: function () {},
data_onselected: function () {},
data_onunselected: function () {},
data_url: undefined,
data_headers: undefined,
data_json: undefined,
data_rows: undefined,
data_columns: undefined,
data_mimeType: undefined,
data_keys: undefined,
// configuration for no plot-able data supplied.
data_empty_label_text: "",
// subchart
subchart_show: false,
subchart_size_height: 60,
subchart_axis_x_show: true,
subchart_onbrush: function () {},
// color
color_pattern: [],
color_threshold: {},
// legend
legend_show: true,
legend_hide: false,
legend_position: 'bottom',
legend_inset_anchor: 'top-left',
legend_inset_x: 10,
legend_inset_y: 0,
legend_inset_step: undefined,
legend_item_onclick: undefined,
legend_item_onmouseover: undefined,
legend_item_onmouseout: undefined,
legend_equally: false,
legend_padding: 0,
legend_item_tile_width: 10,
legend_item_tile_height: 10,
// axis
axis_rotated: false,
axis_x_show: true,
axis_x_type: 'indexed',
axis_x_localtime: true,
axis_x_categories: [],
axis_x_tick_centered: false,
axis_x_tick_format: undefined,
axis_x_tick_culling: {},
axis_x_tick_culling_max: 10,
axis_x_tick_count: undefined,
axis_x_tick_fit: true,
axis_x_tick_values: null,
axis_x_tick_rotate: 0,
axis_x_tick_outer: true,
axis_x_tick_multiline: true,
axis_x_tick_width: null,
axis_x_max: undefined,
axis_x_min: undefined,
axis_x_padding: {},
axis_x_height: undefined,
axis_x_extent: undefined,
axis_x_label: {},
axis_y_show: true,
axis_y_type: undefined,
axis_y_max: undefined,
axis_y_min: undefined,
axis_y_inverted: false,
axis_y_center: undefined,
axis_y_inner: undefined,
axis_y_label: {},
axis_y_tick_format: undefined,
axis_y_tick_outer: true,
axis_y_tick_values: null,
axis_y_tick_rotate: 0,
axis_y_tick_count: undefined,
axis_y_tick_time_value: undefined,
axis_y_tick_time_interval: undefined,
axis_y_padding: {},
axis_y_default: undefined,
axis_y2_show: false,
axis_y2_max: undefined,
axis_y2_min: undefined,
axis_y2_inverted: false,
axis_y2_center: undefined,
axis_y2_inner: undefined,
axis_y2_label: {},
axis_y2_tick_format: undefined,
axis_y2_tick_outer: true,
axis_y2_tick_values: null,
axis_y2_tick_count: undefined,
axis_y2_padding: {},
axis_y2_default: undefined,
// grid
grid_x_show: false,
grid_x_type: 'tick',
grid_x_lines: [],
grid_y_show: false,
// not used
// grid_y_type: 'tick',
grid_y_lines: [],
grid_y_ticks: 10,
grid_focus_show: true,
grid_lines_front: true,
// point - point of each data
point_show: true,
point_r: 2.5,
point_sensitivity: 10,
point_focus_expand_enabled: true,
point_focus_expand_r: undefined,
point_select_r: undefined,
// line
line_connectNull: false,
line_step_type: 'step',
// bar
bar_width: undefined,
bar_width_ratio: 0.6,
bar_width_max: undefined,
bar_zerobased: true,
// area
area_zerobased: true,
area_above: false,
// pie
pie_label_show: true,
pie_label_format: undefined,
pie_label_threshold: 0.05,
pie_label_ratio: undefined,
pie_expand: {},
pie_expand_duration: 50,
// gauge
gauge_fullCircle: false,
gauge_label_show: true,
gauge_label_format: undefined,
gauge_min: 0,
gauge_max: 100,
gauge_startingAngle: -1 * Math.PI/2,
gauge_units: undefined,
gauge_width: undefined,
gauge_expand: {},
gauge_expand_duration: 50,
// donut
donut_label_show: true,
donut_label_format: undefined,
donut_label_threshold: 0.05,
donut_label_ratio: undefined,
donut_width: undefined,
donut_title: "",
donut_expand: {},
donut_expand_duration: 50,
// spline
spline_interpolation_type: 'cardinal',
// region - region to change style
regions: [],
// tooltip - show when mouseover on each data
tooltip_show: true,
tooltip_grouped: true,
tooltip_format_title: undefined,
tooltip_format_name: undefined,
tooltip_format_value: undefined,
tooltip_position: undefined,
tooltip_contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
return this.getTooltipContent ? this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color) : '';
},
tooltip_init_show: false,
tooltip_init_x: 0,
tooltip_init_position: {top: '0px', left: '50px'},
tooltip_onshow: function () {},
tooltip_onhide: function () {},
// title
title_text: undefined,
title_padding: {
top: 0,
right: 0,
bottom: 0,
left: 0
},
title_position: 'top-center',
};
Object.keys(this.additionalConfig).forEach(function (key) {
config[key] = this.additionalConfig[key];
}, this);
return config;
};
c3_chart_internal_fn.additionalConfig = {};
c3_chart_internal_fn.loadConfig = function (config) {
var this_config = this.config, target, keys, read;
function find() {
var key = keys.shift();
// console.log("key =>", key, ", target =>", target);
if (key && target && typeof target === 'object' && key in target) {
target = target[key];
return find();
}
else if (!key) {
return target;
}
else {
return undefined;
}
}
Object.keys(this_config).forEach(function (key) {
target = config;
keys = key.split('_');
read = find();
// console.log("CONFIG : ", key, read);
if (isDefined(read)) {
this_config[key] = read;
}
});
};
c3_chart_internal_fn.getScale = function (min, max, forTimeseries) {
return (forTimeseries ? this.d3.time.scale() : this.d3.scale.linear()).range([min, max]);
};
c3_chart_internal_fn.getX = function (min, max, domain, offset) {
var $$ = this,
scale = $$.getScale(min, max, $$.isTimeSeries()),
_scale = domain ? scale.domain(domain) : scale, key;
// Define customized scale if categorized axis
if ($$.isCategorized()) {
offset = offset || function () { return 0; };
scale = function (d, raw) {
var v = _scale(d) + offset(d);
return raw ? v : Math.ceil(v);
};
} else {
scale = function (d, raw) {
var v = _scale(d);
return raw ? v : Math.ceil(v);
};
}
// define functions
for (key in _scale) {
scale[key] = _scale[key];
}
scale.orgDomain = function () {
return _scale.domain();
};
// define custom domain() for categorized axis
if ($$.isCategorized()) {
scale.domain = function (domain) {
if (!arguments.length) {
domain = this.orgDomain();
return [domain[0], domain[1] + 1];
}
_scale.domain(domain);
return scale;
};
}
return scale;
};
c3_chart_internal_fn.getY = function (min, max, domain) {
var scale = this.getScale(min, max, this.isTimeSeriesY());
if (domain) { scale.domain(domain); }
return scale;
};
c3_chart_internal_fn.getYScale = function (id) {
return this.axis.getId(id) === 'y2' ? this.y2 : this.y;
};
c3_chart_internal_fn.getSubYScale = function (id) {
return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY;
};
c3_chart_internal_fn.updateScales = function () {
var $$ = this, config = $$.config,
forInit = !$$.x;
// update edges
$$.xMin = config.axis_rotated ? 1 : 0;
$$.xMax = config.axis_rotated ? $$.height : $$.width;
$$.yMin = config.axis_rotated ? 0 : $$.height;
$$.yMax = config.axis_rotated ? $$.width : 1;
$$.subXMin = $$.xMin;
$$.subXMax = $$.xMax;
$$.subYMin = config.axis_rotated ? 0 : $$.height2;
$$.subYMax = config.axis_rotated ? $$.width2 : 1;
// update scales
$$.x = $$.getX($$.xMin, $$.xMax, forInit ? undefined : $$.x.orgDomain(), function () { return $$.xAxis.tickOffset(); });
$$.y = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y_default : $$.y.domain());
$$.y2 = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y2_default : $$.y2.domain());
$$.subX = $$.getX($$.xMin, $$.xMax, $$.orgXDomain, function (d) { return d % 1 ? 0 : $$.subXAxis.tickOffset(); });
$$.subY = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y_default : $$.subY.domain());
$$.subY2 = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y2_default : $$.subY2.domain());
// update axes
$$.xAxisTickFormat = $$.axis.getXAxisTickFormat();
$$.xAxisTickValues = $$.axis.getXAxisTickValues();
$$.yAxisTickValues = $$.axis.getYAxisTickValues();
$$.y2AxisTickValues = $$.axis.getY2AxisTickValues();
$$.xAxis = $$.axis.getXAxis($$.x, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
$$.subXAxis = $$.axis.getXAxis($$.subX, $$.subXOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
$$.yAxis = $$.axis.getYAxis($$.y, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, config.axis_y_tick_outer);
$$.y2Axis = $$.axis.getYAxis($$.y2, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, config.axis_y2_tick_outer);
// Set initialized scales to brush and zoom
if (!forInit) {
if ($$.brush) { $$.brush.scale($$.subX); }
if (config.zoom_enabled) { $$.zoom.scale($$.x); }
}
// update for arc
if ($$.updateArc) { $$.updateArc(); }
};
c3_chart_internal_fn.getYDomainMin = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasNegativeValue;
if (config.data_groups.length > 0) {
hasNegativeValue = $$.hasNegativeValueInTargets(targets);
for (j = 0; j < config.data_groups.length; j++) {
// Determine baseId
idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
if (idsInGroup.length === 0) { continue; }
baseId = idsInGroup[0];
// Consider negative values
if (hasNegativeValue && ys[baseId]) {
ys[baseId].forEach(function (v, i) {
ys[baseId][i] = v < 0 ? v : 0;
});
}
// Compute min
for (k = 1; k < idsInGroup.length; k++) {
id = idsInGroup[k];
if (! ys[id]) { continue; }
ys[id].forEach(function (v, i) {
if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) {
ys[baseId][i] += +v;
}
});
}
}
}
return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); }));
};
c3_chart_internal_fn.getYDomainMax = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasPositiveValue;
if (config.data_groups.length > 0) {
hasPositiveValue = $$.hasPositiveValueInTargets(targets);
for (j = 0; j < config.data_groups.length; j++) {
// Determine baseId
idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
if (idsInGroup.length === 0) { continue; }
baseId = idsInGroup[0];
// Consider positive values
if (hasPositiveValue && ys[baseId]) {
ys[baseId].forEach(function (v, i) {
ys[baseId][i] = v > 0 ? v : 0;
});
}
// Compute max
for (k = 1; k < idsInGroup.length; k++) {
id = idsInGroup[k];
if (! ys[id]) { continue; }
ys[id].forEach(function (v, i) {
if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) {
ys[baseId][i] += +v;
}
});
}
}
}
return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); }));
};
c3_chart_internal_fn.getYDomain = function (targets, axisId, xDomain) {
var $$ = this, config = $$.config,
targetsByAxisId = targets.filter(function (t) { return $$.axis.getId(t.id) === axisId; }),
yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId,
yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min,
yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max,
yDomainMin = $$.getYDomainMin(yTargets),
yDomainMax = $$.getYDomainMax(yTargets),
domain, domainLength, padding, padding_top, padding_bottom,
center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center,
yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative,
isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased),
isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted,
showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated,
showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated;
// MEMO: avoid inverting domain unexpectedly
yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? (yDomainMin < yMax ? yDomainMin : yMax - 10) : yDomainMin;
yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? (yMin < yDomainMax ? yDomainMax : yMin + 10) : yDomainMax;
if (yTargets.length === 0) { // use current domain if target of axisId is none
return axisId === 'y2' ? $$.y2.domain() : $$.y.domain();
}
if (isNaN(yDomainMin)) { // set minimum to zero when not number
yDomainMin = 0;
}
if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin
yDomainMax = yDomainMin;
}
if (yDomainMin === yDomainMax) {
yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0;
}
isAllPositive = yDomainMin >= 0 && yDomainMax >= 0;
isAllNegative = yDomainMin <= 0 && yDomainMax <= 0;
// Cancel zerobased if axis_*_min / axis_*_max specified
if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) {
isZeroBased = false;
}
// Bar/Area chart should be 0-based if all positive|negative
if (isZeroBased) {
if (isAllPositive) { yDomainMin = 0; }
if (isAllNegative) { yDomainMax = 0; }
}
domainLength = Math.abs(yDomainMax - yDomainMin);
padding = padding_top = padding_bottom = domainLength * 0.1;
if (typeof center !== 'undefined') {
yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax));
yDomainMax = center + yDomainAbs;
yDomainMin = center - yDomainAbs;
}
// add padding for data label
if (showHorizontalDataLabel) {
lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width');
diff = diffDomain($$.y.range());
ratio = [lengths[0] / diff, lengths[1] / diff];
padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1]));
padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1]));
} else if (showVerticalDataLabel) {
lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height');
padding_top += $$.axis.convertPixelsToAxisPadding(lengths[1], domainLength);
padding_bottom += $$.axis.convertPixelsToAxisPadding(lengths[0], domainLength);
}
if (axisId === 'y' && notEmpty(config.axis_y_padding)) {
padding_top = $$.axis.getPadding(config.axis_y_padding, 'top', padding_top, domainLength);
padding_bottom = $$.axis.getPadding(config.axis_y_padding, 'bottom', padding_bottom, domainLength);
}
if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) {
padding_top = $$.axis.getPadding(config.axis_y2_padding, 'top', padding_top, domainLength);
padding_bottom = $$.axis.getPadding(config.axis_y2_padding, 'bottom', padding_bottom, domainLength);
}
// Bar/Area chart should be 0-based if all positive|negative
if (isZeroBased) {
if (isAllPositive) { padding_bottom = yDomainMin; }
if (isAllNegative) { padding_top = -yDomainMax; }
}
domain = [yDomainMin - padding_bottom, yDomainMax + padding_top];
return isInverted ? domain.reverse() : domain;
};
c3_chart_internal_fn.getXDomainMin = function (targets) {
var $$ = this, config = $$.config;
return isDefined(config.axis_x_min) ?
($$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min) :
$$.d3.min(targets, function (t) { return $$.d3.min(t.values, function (v) { return v.x; }); });
};
c3_chart_internal_fn.getXDomainMax = function (targets) {
var $$ = this, config = $$.config;
return isDefined(config.axis_x_max) ?
($$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max) :
$$.d3.max(targets, function (t) { return $$.d3.max(t.values, function (v) { return v.x; }); });
};
c3_chart_internal_fn.getXDomainPadding = function (domain) {
var $$ = this, config = $$.config,
diff = domain[1] - domain[0],
maxDataCount, padding, paddingLeft, paddingRight;
if ($$.isCategorized()) {
padding = 0;
} else if ($$.hasType('bar')) {
maxDataCount = $$.getMaxDataCount();
padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5;
} else {
padding = diff * 0.01;
}
if (typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding)) {
paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding;
paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding;
} else if (typeof config.axis_x_padding === 'number') {
paddingLeft = paddingRight = config.axis_x_padding;
} else {
paddingLeft = paddingRight = padding;
}
return {left: paddingLeft, right: paddingRight};
};
c3_chart_internal_fn.getXDomain = function (targets) {
var $$ = this,
xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)],
firstX = xDomain[0], lastX = xDomain[1],
padding = $$.getXDomainPadding(xDomain),
min = 0, max = 0;
// show center of x domain if min and max are the same
if ((firstX - lastX) === 0 && !$$.isCategorized()) {
if ($$.isTimeSeries()) {
firstX = new Date(firstX.getTime() * 0.5);
lastX = new Date(lastX.getTime() * 1.5);
} else {
firstX = firstX === 0 ? 1 : (firstX * 0.5);
lastX = lastX === 0 ? -1 : (lastX * 1.5);
}
}
if (firstX || firstX === 0) {
min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left;
}
if (lastX || lastX === 0) {
max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right;
}
return [min, max];
};
c3_chart_internal_fn.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
var $$ = this, config = $$.config;
if (withUpdateOrgXDomain) {
$$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets)));
$$.orgXDomain = $$.x.domain();
if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); }
$$.subX.domain($$.x.domain());
if ($$.brush) { $$.brush.scale($$.subX); }
}
if (withUpdateXDomain) {
$$.x.domain(domain ? domain : (!$$.brush || $$.brush.empty()) ? $$.orgXDomain : $$.brush.extent());
if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); }
}
// Trim domain when too big by zoom mousemove event
if (withTrim) { $$.x.domain($$.trimXDomain($$.x.orgDomain())); }
return $$.x.domain();
};
c3_chart_internal_fn.trimXDomain = function (domain) {
var zoomDomain = this.getZoomDomain(),
min = zoomDomain[0], max = zoomDomain[1];
if (domain[0] <= min) {
domain[1] = +domain[1] + (min - domain[0]);
domain[0] = min;
}
if (max <= domain[1]) {
domain[0] = +domain[0] - (domain[1] - max);
domain[1] = max;
}
return domain;
};
c3_chart_internal_fn.isX = function (key) {
var $$ = this, config = $$.config;
return (config.data_x && key === config.data_x) || (notEmpty(config.data_xs) && hasValue(config.data_xs, key));
};
c3_chart_internal_fn.isNotX = function (key) {
return !this.isX(key);
};
c3_chart_internal_fn.getXKey = function (id) {
var $$ = this, config = $$.config;
return config.data_x ? config.data_x : notEmpty(config.data_xs) ? config.data_xs[id] : null;
};
c3_chart_internal_fn.getXValuesOfXKey = function (key, targets) {
var $$ = this,
xValues, ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : [];
ids.forEach(function (id) {
if ($$.getXKey(id) === key) {
xValues = $$.data.xs[id];
}
});
return xValues;
};
c3_chart_internal_fn.getIndexByX = function (x) {
var $$ = this,
data = $$.filterByX($$.data.targets, x);
return data.length ? data[0].index : null;
};
c3_chart_internal_fn.getXValue = function (id, i) {
var $$ = this;
return id in $$.data.xs && $$.data.xs[id] && isValue($$.data.xs[id][i]) ? $$.data.xs[id][i] : i;
};
c3_chart_internal_fn.getOtherTargetXs = function () {
var $$ = this,
idsForX = Object.keys($$.data.xs);
return idsForX.length ? $$.data.xs[idsForX[0]] : null;
};
<|fim▁hole|> };
c3_chart_internal_fn.addXs = function (xs) {
var $$ = this;
Object.keys(xs).forEach(function (id) {
$$.config.data_xs[id] = xs[id];
});
};
c3_chart_internal_fn.hasMultipleX = function (xs) {
return this.d3.set(Object.keys(xs).map(function (id) { return xs[id]; })).size() > 1;
};
c3_chart_internal_fn.isMultipleX = function () {
return notEmpty(this.config.data_xs) || !this.config.data_xSort || this.hasType('scatter');
};
c3_chart_internal_fn.addName = function (data) {
var $$ = this, name;
if (data) {
name = $$.config.data_names[data.id];
data.name = name !== undefined ? name : data.id;
}
return data;
};
c3_chart_internal_fn.getValueOnIndex = function (values, index) {
var valueOnIndex = values.filter(function (v) { return v.index === index; });
return valueOnIndex.length ? valueOnIndex[0] : null;
};
c3_chart_internal_fn.updateTargetX = function (targets, x) {
var $$ = this;
targets.forEach(function (t) {
t.values.forEach(function (v, i) {
v.x = $$.generateTargetX(x[i], t.id, i);
});
$$.data.xs[t.id] = x;
});
};
c3_chart_internal_fn.updateTargetXs = function (targets, xs) {
var $$ = this;
targets.forEach(function (t) {
if (xs[t.id]) {
$$.updateTargetX([t], xs[t.id]);
}
});
};
c3_chart_internal_fn.generateTargetX = function (rawX, id, index) {
var $$ = this, x;
if ($$.isTimeSeries()) {
x = rawX ? $$.parseDate(rawX) : $$.parseDate($$.getXValue(id, index));
}
else if ($$.isCustomX() && !$$.isCategorized()) {
x = isValue(rawX) ? +rawX : $$.getXValue(id, index);
}
else {
x = index;
}
return x;
};
c3_chart_internal_fn.cloneTarget = function (target) {
return {
id : target.id,
id_org : target.id_org,
values : target.values.map(function (d) {
return {x: d.x, value: d.value, id: d.id};
})
};
};
c3_chart_internal_fn.updateXs = function () {
var $$ = this;
if ($$.data.targets.length) {
$$.xs = [];
$$.data.targets[0].values.forEach(function (v) {
$$.xs[v.index] = v.x;
});
}
};
c3_chart_internal_fn.getPrevX = function (i) {
var x = this.xs[i - 1];
return typeof x !== 'undefined' ? x : null;
};
c3_chart_internal_fn.getNextX = function (i) {
var x = this.xs[i + 1];
return typeof x !== 'undefined' ? x : null;
};
c3_chart_internal_fn.getMaxDataCount = function () {
var $$ = this;
return $$.d3.max($$.data.targets, function (t) { return t.values.length; });
};
c3_chart_internal_fn.getMaxDataCountTarget = function (targets) {
var length = targets.length, max = 0, maxTarget;
if (length > 1) {
targets.forEach(function (t) {
if (t.values.length > max) {
maxTarget = t;
max = t.values.length;
}
});
} else {
maxTarget = length ? targets[0] : null;
}
return maxTarget;
};
c3_chart_internal_fn.getEdgeX = function (targets) {
var $$ = this;
return !targets.length ? [0, 0] : [
$$.d3.min(targets, function (t) { return t.values[0].x; }),
$$.d3.max(targets, function (t) { return t.values[t.values.length - 1].x; })
];
};
c3_chart_internal_fn.mapToIds = function (targets) {
return targets.map(function (d) { return d.id; });
};
c3_chart_internal_fn.mapToTargetIds = function (ids) {
var $$ = this;
return ids ? [].concat(ids) : $$.mapToIds($$.data.targets);
};
c3_chart_internal_fn.hasTarget = function (targets, id) {
var ids = this.mapToIds(targets), i;
for (i = 0; i < ids.length; i++) {
if (ids[i] === id) {
return true;
}
}
return false;
};
c3_chart_internal_fn.isTargetToShow = function (targetId) {
return this.hiddenTargetIds.indexOf(targetId) < 0;
};
c3_chart_internal_fn.isLegendToShow = function (targetId) {
return this.hiddenLegendIds.indexOf(targetId) < 0;
};
c3_chart_internal_fn.filterTargetsToShow = function (targets) {
var $$ = this;
return targets.filter(function (t) { return $$.isTargetToShow(t.id); });
};
c3_chart_internal_fn.mapTargetsToUniqueXs = function (targets) {
var $$ = this;
var xs = $$.d3.set($$.d3.merge(targets.map(function (t) { return t.values.map(function (v) { return +v.x; }); }))).values();
xs = $$.isTimeSeries() ? xs.map(function (x) { return new Date(+x); }) : xs.map(function (x) { return +x; });
return xs.sort(function (a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; });
};
c3_chart_internal_fn.addHiddenTargetIds = function (targetIds) {
this.hiddenTargetIds = this.hiddenTargetIds.concat(targetIds);
};
c3_chart_internal_fn.removeHiddenTargetIds = function (targetIds) {
this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
};
c3_chart_internal_fn.addHiddenLegendIds = function (targetIds) {
this.hiddenLegendIds = this.hiddenLegendIds.concat(targetIds);
};
c3_chart_internal_fn.removeHiddenLegendIds = function (targetIds) {
this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
};
c3_chart_internal_fn.getValuesAsIdKeyed = function (targets) {
var ys = {};
targets.forEach(function (t) {
ys[t.id] = [];
t.values.forEach(function (v) {
ys[t.id].push(v.value);
});
});
return ys;
};
c3_chart_internal_fn.checkValueInTargets = function (targets, checker) {
var ids = Object.keys(targets), i, j, values;
for (i = 0; i < ids.length; i++) {
values = targets[ids[i]].values;
for (j = 0; j < values.length; j++) {
if (checker(values[j].value)) {
return true;
}
}
}
return false;
};
c3_chart_internal_fn.hasNegativeValueInTargets = function (targets) {
return this.checkValueInTargets(targets, function (v) { return v < 0; });
};
c3_chart_internal_fn.hasPositiveValueInTargets = function (targets) {
return this.checkValueInTargets(targets, function (v) { return v > 0; });
};
c3_chart_internal_fn.isOrderDesc = function () {
var config = this.config;
return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'desc';
};
c3_chart_internal_fn.isOrderAsc = function () {
var config = this.config;
return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'asc';
};
c3_chart_internal_fn.orderTargets = function (targets) {
var $$ = this, config = $$.config, orderAsc = $$.isOrderAsc(), orderDesc = $$.isOrderDesc();
if (orderAsc || orderDesc) {
targets.sort(function (t1, t2) {
var reducer = function (p, c) { return p + Math.abs(c.value); };
var t1Sum = t1.values.reduce(reducer, 0),
t2Sum = t2.values.reduce(reducer, 0);
return orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum;
});
} else if (isFunction(config.data_order)) {
targets.sort(config.data_order);
} // TODO: accept name array for order
return targets;
};
c3_chart_internal_fn.filterByX = function (targets, x) {
return this.d3.merge(targets.map(function (t) { return t.values; })).filter(function (v) { return v.x - x === 0; });
};
c3_chart_internal_fn.filterRemoveNull = function (data) {
return data.filter(function (d) { return isValue(d.value); });
};
c3_chart_internal_fn.filterByXDomain = function (targets, xDomain) {
return targets.map(function (t) {
return {
id: t.id,
id_org: t.id_org,
values: t.values.filter(function (v) {
return xDomain[0] <= v.x && v.x <= xDomain[1];
})
};
});
};
c3_chart_internal_fn.hasDataLabel = function () {
var config = this.config;
if (typeof config.data_labels === 'boolean' && config.data_labels) {
return true;
} else if (typeof config.data_labels === 'object' && notEmpty(config.data_labels)) {
return true;
}
return false;
};
c3_chart_internal_fn.getDataLabelLength = function (min, max, key) {
var $$ = this,
lengths = [0, 0], paddingCoef = 1.3;
$$.selectChart.select('svg').selectAll('.dummy')
.data([min, max])
.enter().append('text')
.text(function (d) { return $$.dataLabelFormat(d.id)(d); })
.each(function (d, i) {
lengths[i] = this.getBoundingClientRect()[key] * paddingCoef;
})
.remove();
return lengths;
};
c3_chart_internal_fn.isNoneArc = function (d) {
return this.hasTarget(this.data.targets, d.id);
},
c3_chart_internal_fn.isArc = function (d) {
return 'data' in d && this.hasTarget(this.data.targets, d.data.id);
};
c3_chart_internal_fn.findSameXOfValues = function (values, index) {
var i, targetX = values[index].x, sames = [];
for (i = index - 1; i >= 0; i--) {
if (targetX !== values[i].x) { break; }
sames.push(values[i]);
}
for (i = index; i < values.length; i++) {
if (targetX !== values[i].x) { break; }
sames.push(values[i]);
}
return sames;
};
c3_chart_internal_fn.findClosestFromTargets = function (targets, pos) {
var $$ = this, candidates;
// map to array of closest points of each target
candidates = targets.map(function (target) {
return $$.findClosest(target.values, pos);
});
// decide closest point and return
return $$.findClosest(candidates, pos);
};
c3_chart_internal_fn.findClosest = function (values, pos) {
var $$ = this, minDist = $$.config.point_sensitivity, closest;
// find mouseovering bar
values.filter(function (v) { return v && $$.isBarType(v.id); }).forEach(function (v) {
var shape = $$.main.select('.' + CLASS.bars + $$.getTargetSelectorSuffix(v.id) + ' .' + CLASS.bar + '-' + v.index).node();
if (!closest && $$.isWithinBar(shape)) {
closest = v;
}
});
// find closest point from non-bar
values.filter(function (v) { return v && !$$.isBarType(v.id); }).forEach(function (v) {
var d = $$.dist(v, pos);
if (d < minDist) {
minDist = d;
closest = v;
}
});
return closest;
};
c3_chart_internal_fn.dist = function (data, pos) {
var $$ = this, config = $$.config,
xIndex = config.axis_rotated ? 1 : 0,
yIndex = config.axis_rotated ? 0 : 1,
y = $$.circleY(data, data.index),
x = $$.x(data.x);
return Math.sqrt(Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2));
};
c3_chart_internal_fn.convertValuesToStep = function (values) {
var converted = [].concat(values), i;
if (!this.isCategorized()) {
return values;
}
for (i = values.length + 1; 0 < i; i--) {
converted[i] = converted[i - 1];
}
converted[0] = {
x: converted[0].x - 1,
value: converted[0].value,
id: converted[0].id
};
converted[values.length + 1] = {
x: converted[values.length].x + 1,
value: converted[values.length].value,
id: converted[values.length].id
};
return converted;
};
c3_chart_internal_fn.updateDataAttributes = function (name, attrs) {
var $$ = this, config = $$.config, current = config['data_' + name];
if (typeof attrs === 'undefined') { return current; }
Object.keys(attrs).forEach(function (id) {
current[id] = attrs[id];
});
$$.redraw({withLegend: true});
return current;
};
c3_chart_internal_fn.convertUrlToData = function (url, mimeType, headers, keys, done) {
var $$ = this, type = mimeType ? mimeType : 'csv';
var req = $$.d3.xhr(url);
if (headers) {
Object.keys(headers).forEach(function (header) {
req.header(header, headers[header]);
});
}
req.get(function (error, data) {
var d;
if (!data) {
throw new Error(error.responseURL + ' ' + error.status + ' (' + error.statusText + ')');
}
if (type === 'json') {
d = $$.convertJsonToData(JSON.parse(data.response), keys);
} else if (type === 'tsv') {
d = $$.convertTsvToData(data.response);
} else {
d = $$.convertCsvToData(data.response);
}
done.call($$, d);
});
};
c3_chart_internal_fn.convertXsvToData = function (xsv, parser) {
var rows = parser.parseRows(xsv), d;
if (rows.length === 1) {
d = [{}];
rows[0].forEach(function (id) {
d[0][id] = null;
});
} else {
d = parser.parse(xsv);
}
return d;
};
c3_chart_internal_fn.convertCsvToData = function (csv) {
return this.convertXsvToData(csv, this.d3.csv);
};
c3_chart_internal_fn.convertTsvToData = function (tsv) {
return this.convertXsvToData(tsv, this.d3.tsv);
};
c3_chart_internal_fn.convertJsonToData = function (json, keys) {
var $$ = this,
new_rows = [], targetKeys, data;
if (keys) { // when keys specified, json would be an array that includes objects
if (keys.x) {
targetKeys = keys.value.concat(keys.x);
$$.config.data_x = keys.x;
} else {
targetKeys = keys.value;
}
new_rows.push(targetKeys);
json.forEach(function (o) {
var new_row = [];
targetKeys.forEach(function (key) {
// convert undefined to null because undefined data will be removed in convertDataToTargets()
var v = $$.findValueInJson(o, key);
if (isUndefined(v)) {
v = null;
}
new_row.push(v);
});
new_rows.push(new_row);
});
data = $$.convertRowsToData(new_rows);
} else {
Object.keys(json).forEach(function (key) {
new_rows.push([key].concat(json[key]));
});
data = $$.convertColumnsToData(new_rows);
}
return data;
};
c3_chart_internal_fn.findValueInJson = function (object, path) {
path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties (replace [] with .)
path = path.replace(/^\./, ''); // strip a leading dot
var pathArray = path.split('.');
for (var i = 0; i < pathArray.length; ++i) {
var k = pathArray[i];
if (k in object) {
object = object[k];
} else {
return;
}
}
return object;
};
c3_chart_internal_fn.convertRowsToData = function (rows) {
var keys = rows[0], new_row = {}, new_rows = [], i, j;
for (i = 1; i < rows.length; i++) {
new_row = {};
for (j = 0; j < rows[i].length; j++) {
if (isUndefined(rows[i][j])) {
throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
}
new_row[keys[j]] = rows[i][j];
}
new_rows.push(new_row);
}
return new_rows;
};
c3_chart_internal_fn.convertColumnsToData = function (columns) {
var new_rows = [], i, j, key;
for (i = 0; i < columns.length; i++) {
key = columns[i][0];
for (j = 1; j < columns[i].length; j++) {
if (isUndefined(new_rows[j - 1])) {
new_rows[j - 1] = {};
}
if (isUndefined(columns[i][j])) {
throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
}
new_rows[j - 1][key] = columns[i][j];
}
}
return new_rows;
};
c3_chart_internal_fn.convertDataToTargets = function (data, appendXs) {
var $$ = this, config = $$.config,
ids = $$.d3.keys(data[0]).filter($$.isNotX, $$),
xs = $$.d3.keys(data[0]).filter($$.isX, $$),
targets;
// save x for update data by load when custom x and c3.x API
ids.forEach(function (id) {
var xKey = $$.getXKey(id);
if ($$.isCustomX() || $$.isTimeSeries()) {
// if included in input data
if (xs.indexOf(xKey) >= 0) {
$$.data.xs[id] = (appendXs && $$.data.xs[id] ? $$.data.xs[id] : []).concat(
data.map(function (d) { return d[xKey]; })
.filter(isValue)
.map(function (rawX, i) { return $$.generateTargetX(rawX, id, i); })
);
}
// if not included in input data, find from preloaded data of other id's x
else if (config.data_x) {
$$.data.xs[id] = $$.getOtherTargetXs();
}
// if not included in input data, find from preloaded data
else if (notEmpty(config.data_xs)) {
$$.data.xs[id] = $$.getXValuesOfXKey(xKey, $$.data.targets);
}
// MEMO: if no x included, use same x of current will be used
} else {
$$.data.xs[id] = data.map(function (d, i) { return i; });
}
});
// check x is defined
ids.forEach(function (id) {
if (!$$.data.xs[id]) {
throw new Error('x is not defined for id = "' + id + '".');
}
});
// convert to target
targets = ids.map(function (id, index) {
var convertedId = config.data_idConverter(id);
return {
id: convertedId,
id_org: id,
values: data.map(function (d, i) {
var xKey = $$.getXKey(id), rawX = d[xKey],
value = d[id] !== null && !isNaN(d[id]) ? +d[id] : null, x;
// use x as categories if custom x and categorized
if ($$.isCustomX() && $$.isCategorized() && index === 0 && !isUndefined(rawX)) {
if (index === 0 && i === 0) {
config.axis_x_categories = [];
}
x = config.axis_x_categories.indexOf(rawX);
if (x === -1) {
x = config.axis_x_categories.length;
config.axis_x_categories.push(rawX);
}
} else {
x = $$.generateTargetX(rawX, id, i);
}
// mark as x = undefined if value is undefined and filter to remove after mapped
if (isUndefined(d[id]) || $$.data.xs[id].length <= i) {
x = undefined;
}
return {x: x, value: value, id: convertedId};
}).filter(function (v) { return isDefined(v.x); })
};
});
// finish targets
targets.forEach(function (t) {
var i;
// sort values by its x
if (config.data_xSort) {
t.values = t.values.sort(function (v1, v2) {
var x1 = v1.x || v1.x === 0 ? v1.x : Infinity,
x2 = v2.x || v2.x === 0 ? v2.x : Infinity;
return x1 - x2;
});
}
// indexing each value
i = 0;
t.values.forEach(function (v) {
v.index = i++;
});
// this needs to be sorted because its index and value.index is identical
$$.data.xs[t.id].sort(function (v1, v2) {
return v1 - v2;
});
});
// cache information about values
$$.hasNegativeValue = $$.hasNegativeValueInTargets(targets);
$$.hasPositiveValue = $$.hasPositiveValueInTargets(targets);
// set target types
if (config.data_type) {
$$.setTargetType($$.mapToIds(targets).filter(function (id) { return ! (id in config.data_types); }), config.data_type);
}
// cache as original id keyed
targets.forEach(function (d) {
$$.addCache(d.id_org, d);
});
return targets;
};
c3_chart_internal_fn.load = function (targets, args) {
var $$ = this;
if (targets) {
// filter loading targets if needed
if (args.filter) {
targets = targets.filter(args.filter);
}
// set type if args.types || args.type specified
if (args.type || args.types) {
targets.forEach(function (t) {
var type = args.types && args.types[t.id] ? args.types[t.id] : args.type;
$$.setTargetType(t.id, type);
});
}
// Update/Add data
$$.data.targets.forEach(function (d) {
for (var i = 0; i < targets.length; i++) {
if (d.id === targets[i].id) {
d.values = targets[i].values;
targets.splice(i, 1);
break;
}
}
});
$$.data.targets = $$.data.targets.concat(targets); // add remained
}
// Set targets
$$.updateTargets($$.data.targets);
// Redraw with new targets
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
if (args.done) { args.done(); }
};
c3_chart_internal_fn.loadFromArgs = function (args) {
var $$ = this;
if (args.data) {
$$.load($$.convertDataToTargets(args.data), args);
}
else if (args.url) {
$$.convertUrlToData(args.url, args.mimeType, args.headers, args.keys, function (data) {
$$.load($$.convertDataToTargets(data), args);
});
}
else if (args.json) {
$$.load($$.convertDataToTargets($$.convertJsonToData(args.json, args.keys)), args);
}
else if (args.rows) {
$$.load($$.convertDataToTargets($$.convertRowsToData(args.rows)), args);
}
else if (args.columns) {
$$.load($$.convertDataToTargets($$.convertColumnsToData(args.columns)), args);
}
else {
$$.load(null, args);
}
};
c3_chart_internal_fn.unload = function (targetIds, done) {
var $$ = this;
if (!done) {
done = function () {};
}
// filter existing target
targetIds = targetIds.filter(function (id) { return $$.hasTarget($$.data.targets, id); });
// If no target, call done and return
if (!targetIds || targetIds.length === 0) {
done();
return;
}
$$.svg.selectAll(targetIds.map(function (id) { return $$.selectorTarget(id); }))
.transition()
.style('opacity', 0)
.remove()
.call($$.endall, done);
targetIds.forEach(function (id) {
// Reset fadein for future load
$$.withoutFadeIn[id] = false;
// Remove target's elements
if ($$.legend) {
$$.legend.selectAll('.' + CLASS.legendItem + $$.getTargetSelectorSuffix(id)).remove();
}
// Remove target
$$.data.targets = $$.data.targets.filter(function (t) {
return t.id !== id;
});
});
};
c3_chart_internal_fn.categoryName = function (i) {
var config = this.config;
return i < config.axis_x_categories.length ? config.axis_x_categories[i] : i;
};
c3_chart_internal_fn.initEventRect = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.eventRects)
.style('fill-opacity', 0);
};
c3_chart_internal_fn.redrawEventRect = function () {
var $$ = this, config = $$.config,
eventRectUpdate, maxDataCountTarget,
isMultipleX = $$.isMultipleX();
// rects for mouseover
var eventRects = $$.main.select('.' + CLASS.eventRects)
.style('cursor', config.zoom_enabled ? config.axis_rotated ? 'ns-resize' : 'ew-resize' : null)
.classed(CLASS.eventRectsMultiple, isMultipleX)
.classed(CLASS.eventRectsSingle, !isMultipleX);
// clear old rects
eventRects.selectAll('.' + CLASS.eventRect).remove();
// open as public variable
$$.eventRect = eventRects.selectAll('.' + CLASS.eventRect);
if (isMultipleX) {
eventRectUpdate = $$.eventRect.data([0]);
// enter : only one rect will be added
$$.generateEventRectsForMultipleXs(eventRectUpdate.enter());
// update
$$.updateEventRect(eventRectUpdate);
// exit : not needed because always only one rect exists
}
else {
// Set data and update $$.eventRect
maxDataCountTarget = $$.getMaxDataCountTarget($$.data.targets);
eventRects.datum(maxDataCountTarget ? maxDataCountTarget.values : []);
$$.eventRect = eventRects.selectAll('.' + CLASS.eventRect);
eventRectUpdate = $$.eventRect.data(function (d) { return d; });
// enter
$$.generateEventRectsForSingleX(eventRectUpdate.enter());
// update
$$.updateEventRect(eventRectUpdate);
// exit
eventRectUpdate.exit().remove();
}
};
c3_chart_internal_fn.updateEventRect = function (eventRectUpdate) {
var $$ = this, config = $$.config,
x, y, w, h, rectW, rectX;
// set update selection if null
eventRectUpdate = eventRectUpdate || $$.eventRect.data(function (d) { return d; });
if ($$.isMultipleX()) {
// TODO: rotated not supported yet
x = 0;
y = 0;
w = $$.width;
h = $$.height;
}
else {
if (($$.isCustomX() || $$.isTimeSeries()) && !$$.isCategorized()) {
// update index for x that is used by prevX and nextX
$$.updateXs();
rectW = function (d) {
var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index);
// if there this is a single data point make the eventRect full width (or height)
if (prevX === null && nextX === null) {
return config.axis_rotated ? $$.height : $$.width;
}
if (prevX === null) { prevX = $$.x.domain()[0]; }
if (nextX === null) { nextX = $$.x.domain()[1]; }
return Math.max(0, ($$.x(nextX) - $$.x(prevX)) / 2);
};
rectX = function (d) {
var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index),
thisX = $$.data.xs[d.id][d.index];
// if there this is a single data point position the eventRect at 0
if (prevX === null && nextX === null) {
return 0;
}
if (prevX === null) { prevX = $$.x.domain()[0]; }
return ($$.x(thisX) + $$.x(prevX)) / 2;
};
} else {
rectW = $$.getEventRectWidth();
rectX = function (d) {
return $$.x(d.x) - (rectW / 2);
};
}
x = config.axis_rotated ? 0 : rectX;
y = config.axis_rotated ? rectX : 0;
w = config.axis_rotated ? $$.width : rectW;
h = config.axis_rotated ? rectW : $$.height;
}
eventRectUpdate
.attr('class', $$.classEvent.bind($$))
.attr("x", x)
.attr("y", y)
.attr("width", w)
.attr("height", h);
};
c3_chart_internal_fn.generateEventRectsForSingleX = function (eventRectEnter) {
var $$ = this, d3 = $$.d3, config = $$.config;
eventRectEnter.append("rect")
.attr("class", $$.classEvent.bind($$))
.style("cursor", config.data_selection_enabled && config.data_selection_grouped ? "pointer" : null)
.on('mouseover', function (d) {
var index = d.index;
if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing
if ($$.hasArcType()) { return; }
// Expand shapes for selection
if (config.point_focus_expand_enabled) { $$.expandCircles(index, null, true); }
$$.expandBars(index, null, true);
// Call event handler
$$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
config.data_onmouseover.call($$.api, d);
});
})
.on('mouseout', function (d) {
var index = d.index;
if (!$$.config) { return; } // chart is destroyed
if ($$.hasArcType()) { return; }
$$.hideXGridFocus();
$$.hideTooltip();
// Undo expanded shapes
$$.unexpandCircles();
$$.unexpandBars();
// Call event handler
$$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
config.data_onmouseout.call($$.api, d);
});
})
.on('mousemove', function (d) {
var selectedData, index = d.index,
eventRect = $$.svg.select('.' + CLASS.eventRect + '-' + index);
if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing
if ($$.hasArcType()) { return; }
if ($$.isStepType(d) && $$.config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) {
index -= 1;
}
// Show tooltip
selectedData = $$.filterTargetsToShow($$.data.targets).map(function (t) {
return $$.addName($$.getValueOnIndex(t.values, index));
});
if (config.tooltip_grouped) {
$$.showTooltip(selectedData, this);
$$.showXGridFocus(selectedData);
}
if (config.tooltip_grouped && (!config.data_selection_enabled || config.data_selection_grouped)) {
return;
}
$$.main.selectAll('.' + CLASS.shape + '-' + index)
.each(function () {
d3.select(this).classed(CLASS.EXPANDED, true);
if (config.data_selection_enabled) {
eventRect.style('cursor', config.data_selection_grouped ? 'pointer' : null);
}
if (!config.tooltip_grouped) {
$$.hideXGridFocus();
$$.hideTooltip();
if (!config.data_selection_grouped) {
$$.unexpandCircles(index);
$$.unexpandBars(index);
}
}
})
.filter(function (d) {
return $$.isWithinShape(this, d);
})
.each(function (d) {
if (config.data_selection_enabled && (config.data_selection_grouped || config.data_selection_isselectable(d))) {
eventRect.style('cursor', 'pointer');
}
if (!config.tooltip_grouped) {
$$.showTooltip([d], this);
$$.showXGridFocus([d]);
if (config.point_focus_expand_enabled) { $$.expandCircles(index, d.id, true); }
$$.expandBars(index, d.id, true);
}
});
})
.on('click', function (d) {
var index = d.index;
if ($$.hasArcType() || !$$.toggleShape) { return; }
if ($$.cancelClick) {
$$.cancelClick = false;
return;
}
if ($$.isStepType(d) && config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) {
index -= 1;
}
$$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
if (config.data_selection_grouped || $$.isWithinShape(this, d)) {
$$.toggleShape(this, d, index);
$$.config.data_onclick.call($$.api, d, this);
}
});
})
.call(
config.data_selection_draggable && $$.drag ? (
d3.behavior.drag().origin(Object)
.on('drag', function () { $$.drag(d3.mouse(this)); })
.on('dragstart', function () { $$.dragstart(d3.mouse(this)); })
.on('dragend', function () { $$.dragend(); })
) : function () {}
);
};
c3_chart_internal_fn.generateEventRectsForMultipleXs = function (eventRectEnter) {
var $$ = this, d3 = $$.d3, config = $$.config;
function mouseout() {
$$.svg.select('.' + CLASS.eventRect).style('cursor', null);
$$.hideXGridFocus();
$$.hideTooltip();
$$.unexpandCircles();
$$.unexpandBars();
}
eventRectEnter.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', $$.width)
.attr('height', $$.height)
.attr('class', CLASS.eventRect)
.on('mouseout', function () {
if (!$$.config) { return; } // chart is destroyed
if ($$.hasArcType()) { return; }
mouseout();
})
.on('mousemove', function () {
var targetsToShow = $$.filterTargetsToShow($$.data.targets);
var mouse, closest, sameXData, selectedData;
if ($$.dragging) { return; } // do nothing when dragging
if ($$.hasArcType(targetsToShow)) { return; }
mouse = d3.mouse(this);
closest = $$.findClosestFromTargets(targetsToShow, mouse);
if ($$.mouseover && (!closest || closest.id !== $$.mouseover.id)) {
config.data_onmouseout.call($$.api, $$.mouseover);
$$.mouseover = undefined;
}
if (! closest) {
mouseout();
return;
}
if ($$.isScatterType(closest) || !config.tooltip_grouped) {
sameXData = [closest];
} else {
sameXData = $$.filterByX(targetsToShow, closest.x);
}
// show tooltip when cursor is close to some point
selectedData = sameXData.map(function (d) {
return $$.addName(d);
});
$$.showTooltip(selectedData, this);
// expand points
if (config.point_focus_expand_enabled) {
$$.expandCircles(closest.index, closest.id, true);
}
$$.expandBars(closest.index, closest.id, true);
// Show xgrid focus line
$$.showXGridFocus(selectedData);
// Show cursor as pointer if point is close to mouse position
if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
$$.svg.select('.' + CLASS.eventRect).style('cursor', 'pointer');
if (!$$.mouseover) {
config.data_onmouseover.call($$.api, closest);
$$.mouseover = closest;
}
}
})
.on('click', function () {
var targetsToShow = $$.filterTargetsToShow($$.data.targets);
var mouse, closest;
if ($$.hasArcType(targetsToShow)) { return; }
mouse = d3.mouse(this);
closest = $$.findClosestFromTargets(targetsToShow, mouse);
if (! closest) { return; }
// select if selection enabled
if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
$$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(closest.id)).selectAll('.' + CLASS.shape + '-' + closest.index).each(function () {
if (config.data_selection_grouped || $$.isWithinShape(this, closest)) {
$$.toggleShape(this, closest, closest.index);
$$.config.data_onclick.call($$.api, closest, this);
}
});
}
})
.call(
config.data_selection_draggable && $$.drag ? (
d3.behavior.drag().origin(Object)
.on('drag', function () { $$.drag(d3.mouse(this)); })
.on('dragstart', function () { $$.dragstart(d3.mouse(this)); })
.on('dragend', function () { $$.dragend(); })
) : function () {}
);
};
c3_chart_internal_fn.dispatchEvent = function (type, index, mouse) {
var $$ = this,
selector = '.' + CLASS.eventRect + (!$$.isMultipleX() ? '-' + index : ''),
eventRect = $$.main.select(selector).node(),
box = eventRect.getBoundingClientRect(),
x = box.left + (mouse ? mouse[0] : 0),
y = box.top + (mouse ? mouse[1] : 0),
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, window, 0, x, y, x, y,
false, false, false, false, 0, null);
eventRect.dispatchEvent(event);
};
c3_chart_internal_fn.getCurrentWidth = function () {
var $$ = this, config = $$.config;
return config.size_width ? config.size_width : $$.getParentWidth();
};
c3_chart_internal_fn.getCurrentHeight = function () {
var $$ = this, config = $$.config,
h = config.size_height ? config.size_height : $$.getParentHeight();
return h > 0 ? h : 320 / ($$.hasType('gauge') && !config.gauge_fullCircle ? 2 : 1);
};
c3_chart_internal_fn.getCurrentPaddingTop = function () {
var $$ = this,
config = $$.config,
padding = isValue(config.padding_top) ? config.padding_top : 0;
if ($$.title && $$.title.node()) {
padding += $$.getTitlePadding();
}
return padding;
};
c3_chart_internal_fn.getCurrentPaddingBottom = function () {
var config = this.config;
return isValue(config.padding_bottom) ? config.padding_bottom : 0;
};
c3_chart_internal_fn.getCurrentPaddingLeft = function (withoutRecompute) {
var $$ = this, config = $$.config;
if (isValue(config.padding_left)) {
return config.padding_left;
} else if (config.axis_rotated) {
return !config.axis_x_show ? 1 : Math.max(ceil10($$.getAxisWidthByAxisId('x', withoutRecompute)), 40);
} else if (!config.axis_y_show || config.axis_y_inner) { // && !config.axis_rotated
return $$.axis.getYAxisLabelPosition().isOuter ? 30 : 1;
} else {
return ceil10($$.getAxisWidthByAxisId('y', withoutRecompute));
}
};
c3_chart_internal_fn.getCurrentPaddingRight = function () {
var $$ = this, config = $$.config,
defaultPadding = 10, legendWidthOnRight = $$.isLegendRight ? $$.getLegendWidth() + 20 : 0;
if (isValue(config.padding_right)) {
return config.padding_right + 1; // 1 is needed not to hide tick line
} else if (config.axis_rotated) {
return defaultPadding + legendWidthOnRight;
} else if (!config.axis_y2_show || config.axis_y2_inner) { // && !config.axis_rotated
return 2 + legendWidthOnRight + ($$.axis.getY2AxisLabelPosition().isOuter ? 20 : 0);
} else {
return ceil10($$.getAxisWidthByAxisId('y2')) + legendWidthOnRight;
}
};
c3_chart_internal_fn.getParentRectValue = function (key) {
var parent = this.selectChart.node(), v;
while (parent && parent.tagName !== 'BODY') {
try {
v = parent.getBoundingClientRect()[key];
} catch(e) {
if (key === 'width') {
// In IE in certain cases getBoundingClientRect
// will cause an "unspecified error"
v = parent.offsetWidth;
}
}
if (v) {
break;
}
parent = parent.parentNode;
}
return v;
};
c3_chart_internal_fn.getParentWidth = function () {
return this.getParentRectValue('width');
};
c3_chart_internal_fn.getParentHeight = function () {
var h = this.selectChart.style('height');
return h.indexOf('px') > 0 ? +h.replace('px', '') : 0;
};
c3_chart_internal_fn.getSvgLeft = function (withoutRecompute) {
var $$ = this, config = $$.config,
hasLeftAxisRect = config.axis_rotated || (!config.axis_rotated && !config.axis_y_inner),
leftAxisClass = config.axis_rotated ? CLASS.axisX : CLASS.axisY,
leftAxis = $$.main.select('.' + leftAxisClass).node(),
svgRect = leftAxis && hasLeftAxisRect ? leftAxis.getBoundingClientRect() : {right: 0},
chartRect = $$.selectChart.node().getBoundingClientRect(),
hasArc = $$.hasArcType(),
svgLeft = svgRect.right - chartRect.left - (hasArc ? 0 : $$.getCurrentPaddingLeft(withoutRecompute));
return svgLeft > 0 ? svgLeft : 0;
};
c3_chart_internal_fn.getAxisWidthByAxisId = function (id, withoutRecompute) {
var $$ = this, position = $$.axis.getLabelPositionById(id);
return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40);
};
c3_chart_internal_fn.getHorizontalAxisHeight = function (axisId) {
var $$ = this, config = $$.config, h = 30;
if (axisId === 'x' && !config.axis_x_show) { return 8; }
if (axisId === 'x' && config.axis_x_height) { return config.axis_x_height; }
if (axisId === 'y' && !config.axis_y_show) {
return config.legend_show && !$$.isLegendRight && !$$.isLegendInset ? 10 : 1;
}
if (axisId === 'y2' && !config.axis_y2_show) { return $$.rotated_padding_top; }
// Calculate x axis height when tick rotated
if (axisId === 'x' && !config.axis_rotated && config.axis_x_tick_rotate) {
h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - config.axis_x_tick_rotate) / 180);
}
// Calculate y axis height when tick rotated
if (axisId === 'y' && config.axis_rotated && config.axis_y_tick_rotate) {
h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - config.axis_y_tick_rotate) / 180);
}
return h + ($$.axis.getLabelPositionById(axisId).isInner ? 0 : 10) + (axisId === 'y2' ? -10 : 0);
};
c3_chart_internal_fn.getEventRectWidth = function () {
return Math.max(0, this.xAxis.tickInterval());
};
c3_chart_internal_fn.getShapeIndices = function (typeFilter) {
var $$ = this, config = $$.config,
indices = {}, i = 0, j, k;
$$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) {
for (j = 0; j < config.data_groups.length; j++) {
if (config.data_groups[j].indexOf(d.id) < 0) { continue; }
for (k = 0; k < config.data_groups[j].length; k++) {
if (config.data_groups[j][k] in indices) {
indices[d.id] = indices[config.data_groups[j][k]];
break;
}
}
}
if (isUndefined(indices[d.id])) { indices[d.id] = i++; }
});
indices.__max__ = i - 1;
return indices;
};
c3_chart_internal_fn.getShapeX = function (offset, targetsNum, indices, isSub) {
var $$ = this, scale = isSub ? $$.subX : $$.x;
return function (d) {
var index = d.id in indices ? indices[d.id] : 0;
return d.x || d.x === 0 ? scale(d.x) - offset * (targetsNum / 2 - index) : 0;
};
};
c3_chart_internal_fn.getShapeY = function (isSub) {
var $$ = this;
return function (d) {
var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id);
return scale(d.value);
};
};
c3_chart_internal_fn.getShapeOffset = function (typeFilter, indices, isSub) {
var $$ = this,
targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))),
targetIds = targets.map(function (t) { return t.id; });
return function (d, i) {
var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id),
y0 = scale(0), offset = y0;
targets.forEach(function (t) {
var values = $$.isStepType(d) ? $$.convertValuesToStep(t.values) : t.values;
if (t.id === d.id || indices[t.id] !== indices[d.id]) { return; }
if (targetIds.indexOf(t.id) < targetIds.indexOf(d.id)) {
// check if the x values line up
if (typeof values[i] === 'undefined' || +values[i].x !== +d.x) { // "+" for timeseries
// if not, try to find the value that does line up
i = -1;
values.forEach(function (v, j) {
if (v.x === d.x) {
i = j;
}
});
}
if (i in values && values[i].value * d.value >= 0) {
offset += scale(values[i].value) - y0;
}
}
});
return offset;
};
};
c3_chart_internal_fn.isWithinShape = function (that, d) {
var $$ = this,
shape = $$.d3.select(that), isWithin;
if (!$$.isTargetToShow(d.id)) {
isWithin = false;
}
else if (that.nodeName === 'circle') {
isWithin = $$.isStepType(d) ? $$.isWithinStep(that, $$.getYScale(d.id)(d.value)) : $$.isWithinCircle(that, $$.pointSelectR(d) * 1.5);
}
else if (that.nodeName === 'path') {
isWithin = shape.classed(CLASS.bar) ? $$.isWithinBar(that) : true;
}
return isWithin;
};
c3_chart_internal_fn.getInterpolate = function (d) {
var $$ = this,
interpolation = $$.isInterpolationType($$.config.spline_interpolation_type) ? $$.config.spline_interpolation_type : 'cardinal';
return $$.isSplineType(d) ? interpolation : $$.isStepType(d) ? $$.config.line_step_type : "linear";
};
c3_chart_internal_fn.initLine = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartLines);
};
c3_chart_internal_fn.updateTargetsForLine = function (targets) {
var $$ = this, config = $$.config,
mainLineUpdate, mainLineEnter,
classChartLine = $$.classChartLine.bind($$),
classLines = $$.classLines.bind($$),
classAreas = $$.classAreas.bind($$),
classCircles = $$.classCircles.bind($$),
classFocus = $$.classFocus.bind($$);
mainLineUpdate = $$.main.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
.data(targets)
.attr('class', function (d) { return classChartLine(d) + classFocus(d); });
mainLineEnter = mainLineUpdate.enter().append('g')
.attr('class', classChartLine)
.style('opacity', 0)
.style("pointer-events", "none");
// Lines for each data
mainLineEnter.append('g')
.attr("class", classLines);
// Areas
mainLineEnter.append('g')
.attr('class', classAreas);
// Circles for each data point on lines
mainLineEnter.append('g')
.attr("class", function (d) { return $$.generateClass(CLASS.selectedCircles, d.id); });
mainLineEnter.append('g')
.attr("class", classCircles)
.style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
// Update date for selected circles
targets.forEach(function (t) {
$$.main.selectAll('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(t.id)).selectAll('.' + CLASS.selectedCircle).each(function (d) {
d.value = t.values[d.index].value;
});
});
// MEMO: can not keep same color...
//mainLineUpdate.exit().remove();
};
c3_chart_internal_fn.updateLine = function (durationForExit) {
var $$ = this;
$$.mainLine = $$.main.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
.data($$.lineData.bind($$));
$$.mainLine.enter().append('path')
.attr('class', $$.classLine.bind($$))
.style("stroke", $$.color);
$$.mainLine
.style("opacity", $$.initialOpacity.bind($$))
.style('shape-rendering', function (d) { return $$.isStepType(d) ? 'crispEdges' : ''; })
.attr('transform', null);
$$.mainLine.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawLine = function (drawLine, withTransition) {
return [
(withTransition ? this.mainLine.transition(Math.random().toString()) : this.mainLine)
.attr("d", drawLine)
.style("stroke", this.color)
.style("opacity", 1)
];
};
c3_chart_internal_fn.generateDrawLine = function (lineIndices, isSub) {
var $$ = this, config = $$.config,
line = $$.d3.svg.line(),
getPoints = $$.generateGetLinePoints(lineIndices, isSub),
yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
yValue = function (d, i) {
return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)(d.value);
};
line = config.axis_rotated ? line.x(yValue).y(xValue) : line.x(xValue).y(yValue);
if (!config.line_connectNull) { line = line.defined(function (d) { return d.value != null; }); }
return function (d) {
var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
x = isSub ? $$.x : $$.subX, y = yScaleGetter.call($$, d.id), x0 = 0, y0 = 0, path;
if ($$.isLineType(d)) {
if (config.data_regions[d.id]) {
path = $$.lineWithRegions(values, x, y, config.data_regions[d.id]);
} else {
if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
path = line.interpolate($$.getInterpolate(d))(values);
}
} else {
if (values[0]) {
x0 = x(values[0].x);
y0 = y(values[0].value);
}
path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
}
return path ? path : "M 0 0";
};
};
c3_chart_internal_fn.generateGetLinePoints = function (lineIndices, isSub) { // partial duplication of generateGetBarPoints
var $$ = this, config = $$.config,
lineTargetsNum = lineIndices.__max__ + 1,
x = $$.getShapeX(0, lineTargetsNum, lineIndices, !!isSub),
y = $$.getShapeY(!!isSub),
lineOffset = $$.getShapeOffset($$.isLineType, lineIndices, !!isSub),
yScale = isSub ? $$.getSubYScale : $$.getYScale;
return function (d, i) {
var y0 = yScale.call($$, d.id)(0),
offset = lineOffset(d, i) || y0, // offset is for stacked area chart
posX = x(d), posY = y(d);
// fix posY not to overflow opposite quadrant
if (config.axis_rotated) {
if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
}
// 1 point that marks the line position
return [
[posX, posY - (y0 - offset)],
[posX, posY - (y0 - offset)], // needed for compatibility
[posX, posY - (y0 - offset)], // needed for compatibility
[posX, posY - (y0 - offset)] // needed for compatibility
];
};
};
c3_chart_internal_fn.lineWithRegions = function (d, x, y, _regions) {
var $$ = this, config = $$.config,
prev = -1, i, j,
s = "M", sWithRegion,
xp, yp, dx, dy, dd, diff, diffx2,
xOffset = $$.isCategorized() ? 0.5 : 0,
xValue, yValue,
regions = [];
function isWithinRegions(x, regions) {
var i;
for (i = 0; i < regions.length; i++) {
if (regions[i].start < x && x <= regions[i].end) { return true; }
}
return false;
}
// Check start/end of regions
if (isDefined(_regions)) {
for (i = 0; i < _regions.length; i++) {
regions[i] = {};
if (isUndefined(_regions[i].start)) {
regions[i].start = d[0].x;
} else {
regions[i].start = $$.isTimeSeries() ? $$.parseDate(_regions[i].start) : _regions[i].start;
}
if (isUndefined(_regions[i].end)) {
regions[i].end = d[d.length - 1].x;
} else {
regions[i].end = $$.isTimeSeries() ? $$.parseDate(_regions[i].end) : _regions[i].end;
}
}
}
// Set scales
xValue = config.axis_rotated ? function (d) { return y(d.value); } : function (d) { return x(d.x); };
yValue = config.axis_rotated ? function (d) { return x(d.x); } : function (d) { return y(d.value); };
// Define svg generator function for region
function generateM(points) {
return 'M' + points[0][0] + ' ' + points[0][1] + ' ' + points[1][0] + ' ' + points[1][1];
}
if ($$.isTimeSeries()) {
sWithRegion = function (d0, d1, j, diff) {
var x0 = d0.x.getTime(), x_diff = d1.x - d0.x,
xv0 = new Date(x0 + x_diff * j),
xv1 = new Date(x0 + x_diff * (j + diff)),
points;
if (config.axis_rotated) {
points = [[y(yp(j)), x(xv0)], [y(yp(j + diff)), x(xv1)]];
} else {
points = [[x(xv0), y(yp(j))], [x(xv1), y(yp(j + diff))]];
}
return generateM(points);
};
} else {
sWithRegion = function (d0, d1, j, diff) {
var points;
if (config.axis_rotated) {
points = [[y(yp(j), true), x(xp(j))], [y(yp(j + diff), true), x(xp(j + diff))]];
} else {
points = [[x(xp(j), true), y(yp(j))], [x(xp(j + diff), true), y(yp(j + diff))]];
}
return generateM(points);
};
}
// Generate
for (i = 0; i < d.length; i++) {
// Draw as normal
if (isUndefined(regions) || ! isWithinRegions(d[i].x, regions)) {
s += " " + xValue(d[i]) + " " + yValue(d[i]);
}
// Draw with region // TODO: Fix for horizotal charts
else {
xp = $$.getScale(d[i - 1].x + xOffset, d[i].x + xOffset, $$.isTimeSeries());
yp = $$.getScale(d[i - 1].value, d[i].value);
dx = x(d[i].x) - x(d[i - 1].x);
dy = y(d[i].value) - y(d[i - 1].value);
dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
diff = 2 / dd;
diffx2 = diff * 2;
for (j = diff; j <= 1; j += diffx2) {
s += sWithRegion(d[i - 1], d[i], j, diff);
}
}
prev = d[i].x;
}
return s;
};
c3_chart_internal_fn.updateArea = function (durationForExit) {
var $$ = this, d3 = $$.d3;
$$.mainArea = $$.main.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
.data($$.lineData.bind($$));
$$.mainArea.enter().append('path')
.attr("class", $$.classArea.bind($$))
.style("fill", $$.color)
.style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
$$.mainArea
.style("opacity", $$.orgAreaOpacity);
$$.mainArea.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawArea = function (drawArea, withTransition) {
return [
(withTransition ? this.mainArea.transition(Math.random().toString()) : this.mainArea)
.attr("d", drawArea)
.style("fill", this.color)
.style("opacity", this.orgAreaOpacity)
];
};
c3_chart_internal_fn.generateDrawArea = function (areaIndices, isSub) {
var $$ = this, config = $$.config, area = $$.d3.svg.area(),
getPoints = $$.generateGetAreaPoints(areaIndices, isSub),
yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
value0 = function (d, i) {
return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)($$.getAreaBaseValue(d.id));
},
value1 = function (d, i) {
return config.data_groups.length > 0 ? getPoints(d, i)[1][1] : yScaleGetter.call($$, d.id)(d.value);
};
area = config.axis_rotated ? area.x0(value0).x1(value1).y(xValue) : area.x(xValue).y0(config.area_above ? 0 : value0).y1(value1);
if (!config.line_connectNull) {
area = area.defined(function (d) { return d.value !== null; });
}
return function (d) {
var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
x0 = 0, y0 = 0, path;
if ($$.isAreaType(d)) {
if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
path = area.interpolate($$.getInterpolate(d))(values);
} else {
if (values[0]) {
x0 = $$.x(values[0].x);
y0 = $$.getYScale(d.id)(values[0].value);
}
path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
}
return path ? path : "M 0 0";
};
};
c3_chart_internal_fn.getAreaBaseValue = function () {
return 0;
};
c3_chart_internal_fn.generateGetAreaPoints = function (areaIndices, isSub) { // partial duplication of generateGetBarPoints
var $$ = this, config = $$.config,
areaTargetsNum = areaIndices.__max__ + 1,
x = $$.getShapeX(0, areaTargetsNum, areaIndices, !!isSub),
y = $$.getShapeY(!!isSub),
areaOffset = $$.getShapeOffset($$.isAreaType, areaIndices, !!isSub),
yScale = isSub ? $$.getSubYScale : $$.getYScale;
return function (d, i) {
var y0 = yScale.call($$, d.id)(0),
offset = areaOffset(d, i) || y0, // offset is for stacked area chart
posX = x(d), posY = y(d);
// fix posY not to overflow opposite quadrant
if (config.axis_rotated) {
if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
}
// 1 point that marks the area position
return [
[posX, offset],
[posX, posY - (y0 - offset)],
[posX, posY - (y0 - offset)], // needed for compatibility
[posX, offset] // needed for compatibility
];
};
};
c3_chart_internal_fn.updateCircle = function () {
var $$ = this;
$$.mainCircle = $$.main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle)
.data($$.lineOrScatterData.bind($$));
$$.mainCircle.enter().append("circle")
.attr("class", $$.classCircle.bind($$))
.attr("r", $$.pointR.bind($$))
.style("fill", $$.color);
$$.mainCircle
.style("opacity", $$.initialOpacityForCircle.bind($$));
$$.mainCircle.exit().remove();
};
c3_chart_internal_fn.redrawCircle = function (cx, cy, withTransition) {
var selectedCircles = this.main.selectAll('.' + CLASS.selectedCircle);
return [
(withTransition ? this.mainCircle.transition(Math.random().toString()) : this.mainCircle)
.style('opacity', this.opacityForCircle.bind(this))
.style("fill", this.color)
.attr("cx", cx)
.attr("cy", cy),
(withTransition ? selectedCircles.transition(Math.random().toString()) : selectedCircles)
.attr("cx", cx)
.attr("cy", cy)
];
};
c3_chart_internal_fn.circleX = function (d) {
return d.x || d.x === 0 ? this.x(d.x) : null;
};
c3_chart_internal_fn.updateCircleY = function () {
var $$ = this, lineIndices, getPoints;
if ($$.config.data_groups.length > 0) {
lineIndices = $$.getShapeIndices($$.isLineType),
getPoints = $$.generateGetLinePoints(lineIndices);
$$.circleY = function (d, i) {
return getPoints(d, i)[0][1];
};
} else {
$$.circleY = function (d) {
return $$.getYScale(d.id)(d.value);
};
}
};
c3_chart_internal_fn.getCircles = function (i, id) {
var $$ = this;
return (id ? $$.main.selectAll('.' + CLASS.circles + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : ''));
};
c3_chart_internal_fn.expandCircles = function (i, id, reset) {
var $$ = this,
r = $$.pointExpandedR.bind($$);
if (reset) { $$.unexpandCircles(); }
$$.getCircles(i, id)
.classed(CLASS.EXPANDED, true)
.attr('r', r);
};
c3_chart_internal_fn.unexpandCircles = function (i) {
var $$ = this,
r = $$.pointR.bind($$);
$$.getCircles(i)
.filter(function () { return $$.d3.select(this).classed(CLASS.EXPANDED); })
.classed(CLASS.EXPANDED, false)
.attr('r', r);
};
c3_chart_internal_fn.pointR = function (d) {
var $$ = this, config = $$.config;
return $$.isStepType(d) ? 0 : (isFunction(config.point_r) ? config.point_r(d) : config.point_r);
};
c3_chart_internal_fn.pointExpandedR = function (d) {
var $$ = this, config = $$.config;
return config.point_focus_expand_enabled ? (config.point_focus_expand_r ? config.point_focus_expand_r : $$.pointR(d) * 1.75) : $$.pointR(d);
};
c3_chart_internal_fn.pointSelectR = function (d) {
var $$ = this, config = $$.config;
return isFunction(config.point_select_r) ? config.point_select_r(d) : ((config.point_select_r) ? config.point_select_r : $$.pointR(d) * 4);
};
c3_chart_internal_fn.isWithinCircle = function (that, r) {
var d3 = this.d3,
mouse = d3.mouse(that), d3_this = d3.select(that),
cx = +d3_this.attr("cx"), cy = +d3_this.attr("cy");
return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < r;
};
c3_chart_internal_fn.isWithinStep = function (that, y) {
return Math.abs(y - this.d3.mouse(that)[1]) < 30;
};
c3_chart_internal_fn.initBar = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartBars);
};
c3_chart_internal_fn.updateTargetsForBar = function (targets) {
var $$ = this, config = $$.config,
mainBarUpdate, mainBarEnter,
classChartBar = $$.classChartBar.bind($$),
classBars = $$.classBars.bind($$),
classFocus = $$.classFocus.bind($$);
mainBarUpdate = $$.main.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
.data(targets)
.attr('class', function (d) { return classChartBar(d) + classFocus(d); });
mainBarEnter = mainBarUpdate.enter().append('g')
.attr('class', classChartBar)
.style('opacity', 0)
.style("pointer-events", "none");
// Bars for each data
mainBarEnter.append('g')
.attr("class", classBars)
.style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
};
c3_chart_internal_fn.updateBar = function (durationForExit) {
var $$ = this,
barData = $$.barData.bind($$),
classBar = $$.classBar.bind($$),
initialOpacity = $$.initialOpacity.bind($$),
color = function (d) { return $$.color(d.id); };
$$.mainBar = $$.main.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
.data(barData);
$$.mainBar.enter().append('path')
.attr("class", classBar)
.style("stroke", color)
.style("fill", color);
$$.mainBar
.style("opacity", initialOpacity);
$$.mainBar.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawBar = function (drawBar, withTransition) {
return [
(withTransition ? this.mainBar.transition(Math.random().toString()) : this.mainBar)
.attr('d', drawBar)
.style("fill", this.color)
.style("opacity", 1)
];
};
c3_chart_internal_fn.getBarW = function (axis, barTargetsNum) {
var $$ = this, config = $$.config,
w = typeof config.bar_width === 'number' ? config.bar_width : barTargetsNum ? (axis.tickInterval() * config.bar_width_ratio) / barTargetsNum : 0;
return config.bar_width_max && w > config.bar_width_max ? config.bar_width_max : w;
};
c3_chart_internal_fn.getBars = function (i, id) {
var $$ = this;
return (id ? $$.main.selectAll('.' + CLASS.bars + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : ''));
};
c3_chart_internal_fn.expandBars = function (i, id, reset) {
var $$ = this;
if (reset) { $$.unexpandBars(); }
$$.getBars(i, id).classed(CLASS.EXPANDED, true);
};
c3_chart_internal_fn.unexpandBars = function (i) {
var $$ = this;
$$.getBars(i).classed(CLASS.EXPANDED, false);
};
c3_chart_internal_fn.generateDrawBar = function (barIndices, isSub) {
var $$ = this, config = $$.config,
getPoints = $$.generateGetBarPoints(barIndices, isSub);
return function (d, i) {
// 4 points that make a bar
var points = getPoints(d, i);
// switch points if axis is rotated, not applicable for sub chart
var indexX = config.axis_rotated ? 1 : 0;
var indexY = config.axis_rotated ? 0 : 1;
var path = 'M ' + points[0][indexX] + ',' + points[0][indexY] + ' ' +
'L' + points[1][indexX] + ',' + points[1][indexY] + ' ' +
'L' + points[2][indexX] + ',' + points[2][indexY] + ' ' +
'L' + points[3][indexX] + ',' + points[3][indexY] + ' ' +
'z';
return path;
};
};
c3_chart_internal_fn.generateGetBarPoints = function (barIndices, isSub) {
var $$ = this,
axis = isSub ? $$.subXAxis : $$.xAxis,
barTargetsNum = barIndices.__max__ + 1,
barW = $$.getBarW(axis, barTargetsNum),
barX = $$.getShapeX(barW, barTargetsNum, barIndices, !!isSub),
barY = $$.getShapeY(!!isSub),
barOffset = $$.getShapeOffset($$.isBarType, barIndices, !!isSub),
yScale = isSub ? $$.getSubYScale : $$.getYScale;
return function (d, i) {
var y0 = yScale.call($$, d.id)(0),
offset = barOffset(d, i) || y0, // offset is for stacked bar chart
posX = barX(d), posY = barY(d);
// fix posY not to overflow opposite quadrant
if ($$.config.axis_rotated) {
if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
}
// 4 points that make a bar
return [
[posX, offset],
[posX, posY - (y0 - offset)],
[posX + barW, posY - (y0 - offset)],
[posX + barW, offset]
];
};
};
c3_chart_internal_fn.isWithinBar = function (that) {
var mouse = this.d3.mouse(that), box = that.getBoundingClientRect(),
seg0 = that.pathSegList.getItem(0), seg1 = that.pathSegList.getItem(1),
x = Math.min(seg0.x, seg1.x), y = Math.min(seg0.y, seg1.y),
w = box.width, h = box.height, offset = 2,
sx = x - offset, ex = x + w + offset, sy = y + h + offset, ey = y - offset;
return sx < mouse[0] && mouse[0] < ex && ey < mouse[1] && mouse[1] < sy;
};
c3_chart_internal_fn.initText = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartTexts);
$$.mainText = $$.d3.selectAll([]);
};
c3_chart_internal_fn.updateTargetsForText = function (targets) {
var $$ = this, mainTextUpdate, mainTextEnter,
classChartText = $$.classChartText.bind($$),
classTexts = $$.classTexts.bind($$),
classFocus = $$.classFocus.bind($$);
mainTextUpdate = $$.main.select('.' + CLASS.chartTexts).selectAll('.' + CLASS.chartText)
.data(targets)
.attr('class', function (d) { return classChartText(d) + classFocus(d); });
mainTextEnter = mainTextUpdate.enter().append('g')
.attr('class', classChartText)
.style('opacity', 0)
.style("pointer-events", "none");
mainTextEnter.append('g')
.attr('class', classTexts);
};
c3_chart_internal_fn.updateText = function (durationForExit) {
var $$ = this, config = $$.config,
barOrLineData = $$.barOrLineData.bind($$),
classText = $$.classText.bind($$);
$$.mainText = $$.main.selectAll('.' + CLASS.texts).selectAll('.' + CLASS.text)
.data(barOrLineData);
$$.mainText.enter().append('text')
.attr("class", classText)
.attr('text-anchor', function (d) { return config.axis_rotated ? (d.value < 0 ? 'end' : 'start') : 'middle'; })
.style("stroke", 'none')
.style("fill", function (d) { return $$.color(d); })
.style("fill-opacity", 0);
$$.mainText
.text(function (d, i, j) { return $$.dataLabelFormat(d.id)(d.value, d.id, i, j); });
$$.mainText.exit()
.transition().duration(durationForExit)
.style('fill-opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawText = function (xForText, yForText, forFlow, withTransition) {
return [
(withTransition ? this.mainText.transition() : this.mainText)
.attr('x', xForText)
.attr('y', yForText)
.style("fill", this.color)
.style("fill-opacity", forFlow ? 0 : this.opacityForText.bind(this))
];
};
c3_chart_internal_fn.getTextRect = function (text, cls, element) {
var dummy = this.d3.select('body').append('div').classed('c3', true),
svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
font = this.d3.select(element).style('font'),
rect;
svg.selectAll('.dummy')
.data([text])
.enter().append('text')
.classed(cls ? cls : "", true)
.style('font', font)
.text(text)
.each(function () { rect = this.getBoundingClientRect(); });
dummy.remove();
return rect;
};
c3_chart_internal_fn.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) {
var $$ = this,
getAreaPoints = $$.generateGetAreaPoints(areaIndices, false),
getBarPoints = $$.generateGetBarPoints(barIndices, false),
getLinePoints = $$.generateGetLinePoints(lineIndices, false),
getter = forX ? $$.getXForText : $$.getYForText;
return function (d, i) {
var getPoints = $$.isAreaType(d) ? getAreaPoints : $$.isBarType(d) ? getBarPoints : getLinePoints;
return getter.call($$, getPoints(d, i), d, this);
};
};
c3_chart_internal_fn.getXForText = function (points, d, textElement) {
var $$ = this,
box = textElement.getBoundingClientRect(), xPos, padding;
if ($$.config.axis_rotated) {
padding = $$.isBarType(d) ? 4 : 6;
xPos = points[2][1] + padding * (d.value < 0 ? -1 : 1);
} else {
xPos = $$.hasType('bar') ? (points[2][0] + points[0][0]) / 2 : points[0][0];
}
// show labels regardless of the domain if value is null
if (d.value === null) {
if (xPos > $$.width) {
xPos = $$.width - box.width;
} else if (xPos < 0) {
xPos = 4;
}
}
return xPos;
};
c3_chart_internal_fn.getYForText = function (points, d, textElement) {
var $$ = this,
box = textElement.getBoundingClientRect(),
yPos;
if ($$.config.axis_rotated) {
yPos = (points[0][0] + points[2][0] + box.height * 0.6) / 2;
} else {
yPos = points[2][1];
if (d.value < 0 || (d.value === 0 && !$$.hasPositiveValue)) {
yPos += box.height;
if ($$.isBarType(d) && $$.isSafari()) {
yPos -= 3;
}
else if (!$$.isBarType(d) && $$.isChrome()) {
yPos += 3;
}
} else {
yPos += $$.isBarType(d) ? -3 : -6;
}
}
// show labels regardless of the domain if value is null
if (d.value === null && !$$.config.axis_rotated) {
if (yPos < box.height) {
yPos = box.height;
} else if (yPos > this.height) {
yPos = this.height - 4;
}
}
return yPos;
};
c3_chart_internal_fn.setTargetType = function (targetIds, type) {
var $$ = this, config = $$.config;
$$.mapToTargetIds(targetIds).forEach(function (id) {
$$.withoutFadeIn[id] = (type === config.data_types[id]);
config.data_types[id] = type;
});
if (!targetIds) {
config.data_type = type;
}
};
c3_chart_internal_fn.hasType = function (type, targets) {
var $$ = this, types = $$.config.data_types, has = false;
targets = targets || $$.data.targets;
if (targets && targets.length) {
targets.forEach(function (target) {
var t = types[target.id];
if ((t && t.indexOf(type) >= 0) || (!t && type === 'line')) {
has = true;
}
});
} else if (Object.keys(types).length) {
Object.keys(types).forEach(function (id) {
if (types[id] === type) { has = true; }
});
} else {
has = $$.config.data_type === type;
}
return has;
};
c3_chart_internal_fn.hasArcType = function (targets) {
return this.hasType('pie', targets) || this.hasType('donut', targets) || this.hasType('gauge', targets);
};
c3_chart_internal_fn.isLineType = function (d) {
var config = this.config, id = isString(d) ? d : d.id;
return !config.data_types[id] || ['line', 'spline', 'area', 'area-spline', 'step', 'area-step'].indexOf(config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isStepType = function (d) {
var id = isString(d) ? d : d.id;
return ['step', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isSplineType = function (d) {
var id = isString(d) ? d : d.id;
return ['spline', 'area-spline'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isAreaType = function (d) {
var id = isString(d) ? d : d.id;
return ['area', 'area-spline', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isBarType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'bar';
};
c3_chart_internal_fn.isScatterType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'scatter';
};
c3_chart_internal_fn.isPieType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'pie';
};
c3_chart_internal_fn.isGaugeType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'gauge';
};
c3_chart_internal_fn.isDonutType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'donut';
};
c3_chart_internal_fn.isArcType = function (d) {
return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d);
};
c3_chart_internal_fn.lineData = function (d) {
return this.isLineType(d) ? [d] : [];
};
c3_chart_internal_fn.arcData = function (d) {
return this.isArcType(d.data) ? [d] : [];
};
/* not used
function scatterData(d) {
return isScatterType(d) ? d.values : [];
}
*/
c3_chart_internal_fn.barData = function (d) {
return this.isBarType(d) ? d.values : [];
};
c3_chart_internal_fn.lineOrScatterData = function (d) {
return this.isLineType(d) || this.isScatterType(d) ? d.values : [];
};
c3_chart_internal_fn.barOrLineData = function (d) {
return this.isBarType(d) || this.isLineType(d) ? d.values : [];
};
c3_chart_internal_fn.isInterpolationType = function (type) {
return ['linear', 'linear-closed', 'basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', 'cardinal-closed', 'monotone'].indexOf(type) >= 0;
};
c3_chart_internal_fn.initGrid = function () {
var $$ = this, config = $$.config, d3 = $$.d3;
$$.grid = $$.main.append('g')
.attr("clip-path", $$.clipPathForGrid)
.attr('class', CLASS.grid);
if (config.grid_x_show) {
$$.grid.append("g").attr("class", CLASS.xgrids);
}
if (config.grid_y_show) {
$$.grid.append('g').attr('class', CLASS.ygrids);
}
if (config.grid_focus_show) {
$$.grid.append('g')
.attr("class", CLASS.xgridFocus)
.append('line')
.attr('class', CLASS.xgridFocus);
}
$$.xgrid = d3.selectAll([]);
if (!config.grid_lines_front) { $$.initGridLines(); }
};
c3_chart_internal_fn.initGridLines = function () {
var $$ = this, d3 = $$.d3;
$$.gridLines = $$.main.append('g')
.attr("clip-path", $$.clipPathForGrid)
.attr('class', CLASS.grid + ' ' + CLASS.gridLines);
$$.gridLines.append('g').attr("class", CLASS.xgridLines);
$$.gridLines.append('g').attr('class', CLASS.ygridLines);
$$.xgridLines = d3.selectAll([]);
};
c3_chart_internal_fn.updateXGrid = function (withoutUpdate) {
var $$ = this, config = $$.config, d3 = $$.d3,
xgridData = $$.generateGridData(config.grid_x_type, $$.x),
tickOffset = $$.isCategorized() ? $$.xAxis.tickOffset() : 0;
$$.xgridAttr = config.axis_rotated ? {
'x1': 0,
'x2': $$.width,
'y1': function (d) { return $$.x(d) - tickOffset; },
'y2': function (d) { return $$.x(d) - tickOffset; }
} : {
'x1': function (d) { return $$.x(d) + tickOffset; },
'x2': function (d) { return $$.x(d) + tickOffset; },
'y1': 0,
'y2': $$.height
};
$$.xgrid = $$.main.select('.' + CLASS.xgrids).selectAll('.' + CLASS.xgrid)
.data(xgridData);
$$.xgrid.enter().append('line').attr("class", CLASS.xgrid);
if (!withoutUpdate) {
$$.xgrid.attr($$.xgridAttr)
.style("opacity", function () { return +d3.select(this).attr(config.axis_rotated ? 'y1' : 'x1') === (config.axis_rotated ? $$.height : 0) ? 0 : 1; });
}
$$.xgrid.exit().remove();
};
c3_chart_internal_fn.updateYGrid = function () {
var $$ = this, config = $$.config,
gridValues = $$.yAxis.tickValues() || $$.y.ticks(config.grid_y_ticks);
$$.ygrid = $$.main.select('.' + CLASS.ygrids).selectAll('.' + CLASS.ygrid)
.data(gridValues);
$$.ygrid.enter().append('line')
.attr('class', CLASS.ygrid);
$$.ygrid.attr("x1", config.axis_rotated ? $$.y : 0)
.attr("x2", config.axis_rotated ? $$.y : $$.width)
.attr("y1", config.axis_rotated ? 0 : $$.y)
.attr("y2", config.axis_rotated ? $$.height : $$.y);
$$.ygrid.exit().remove();
$$.smoothLines($$.ygrid, 'grid');
};
c3_chart_internal_fn.gridTextAnchor = function (d) {
return d.position ? d.position : "end";
};
c3_chart_internal_fn.gridTextDx = function (d) {
return d.position === 'start' ? 4 : d.position === 'middle' ? 0 : -4;
};
c3_chart_internal_fn.xGridTextX = function (d) {
return d.position === 'start' ? -this.height : d.position === 'middle' ? -this.height / 2 : 0;
};
c3_chart_internal_fn.yGridTextX = function (d) {
return d.position === 'start' ? 0 : d.position === 'middle' ? this.width / 2 : this.width;
};
c3_chart_internal_fn.updateGrid = function (duration) {
var $$ = this, main = $$.main, config = $$.config,
xgridLine, ygridLine, yv;
// hide if arc type
$$.grid.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
if (config.grid_x_show) {
$$.updateXGrid();
}
$$.xgridLines = main.select('.' + CLASS.xgridLines).selectAll('.' + CLASS.xgridLine)
.data(config.grid_x_lines);
// enter
xgridLine = $$.xgridLines.enter().append('g')
.attr("class", function (d) { return CLASS.xgridLine + (d['class'] ? ' ' + d['class'] : ''); });
xgridLine.append('line')
.style("opacity", 0);
xgridLine.append('text')
.attr("text-anchor", $$.gridTextAnchor)
.attr("transform", config.axis_rotated ? "" : "rotate(-90)")
.attr('dx', $$.gridTextDx)
.attr('dy', -5)
.style("opacity", 0);
// udpate
// done in d3.transition() of the end of this function
// exit
$$.xgridLines.exit().transition().duration(duration)
.style("opacity", 0)
.remove();
// Y-Grid
if (config.grid_y_show) {
$$.updateYGrid();
}
$$.ygridLines = main.select('.' + CLASS.ygridLines).selectAll('.' + CLASS.ygridLine)
.data(config.grid_y_lines);
// enter
ygridLine = $$.ygridLines.enter().append('g')
.attr("class", function (d) { return CLASS.ygridLine + (d['class'] ? ' ' + d['class'] : ''); });
ygridLine.append('line')
.style("opacity", 0);
ygridLine.append('text')
.attr("text-anchor", $$.gridTextAnchor)
.attr("transform", config.axis_rotated ? "rotate(-90)" : "")
.attr('dx', $$.gridTextDx)
.attr('dy', -5)
.style("opacity", 0);
// update
yv = $$.yv.bind($$);
$$.ygridLines.select('line')
.transition().duration(duration)
.attr("x1", config.axis_rotated ? yv : 0)
.attr("x2", config.axis_rotated ? yv : $$.width)
.attr("y1", config.axis_rotated ? 0 : yv)
.attr("y2", config.axis_rotated ? $$.height : yv)
.style("opacity", 1);
$$.ygridLines.select('text')
.transition().duration(duration)
.attr("x", config.axis_rotated ? $$.xGridTextX.bind($$) : $$.yGridTextX.bind($$))
.attr("y", yv)
.text(function (d) { return d.text; })
.style("opacity", 1);
// exit
$$.ygridLines.exit().transition().duration(duration)
.style("opacity", 0)
.remove();
};
c3_chart_internal_fn.redrawGrid = function (withTransition) {
var $$ = this, config = $$.config, xv = $$.xv.bind($$),
lines = $$.xgridLines.select('line'),
texts = $$.xgridLines.select('text');
return [
(withTransition ? lines.transition() : lines)
.attr("x1", config.axis_rotated ? 0 : xv)
.attr("x2", config.axis_rotated ? $$.width : xv)
.attr("y1", config.axis_rotated ? xv : 0)
.attr("y2", config.axis_rotated ? xv : $$.height)
.style("opacity", 1),
(withTransition ? texts.transition() : texts)
.attr("x", config.axis_rotated ? $$.yGridTextX.bind($$) : $$.xGridTextX.bind($$))
.attr("y", xv)
.text(function (d) { return d.text; })
.style("opacity", 1)
];
};
c3_chart_internal_fn.showXGridFocus = function (selectedData) {
var $$ = this, config = $$.config,
dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }),
focusEl = $$.main.selectAll('line.' + CLASS.xgridFocus),
xx = $$.xx.bind($$);
if (! config.tooltip_show) { return; }
// Hide when scatter plot exists
if ($$.hasType('scatter') || $$.hasArcType()) { return; }
focusEl
.style("visibility", "visible")
.data([dataToShow[0]])
.attr(config.axis_rotated ? 'y1' : 'x1', xx)
.attr(config.axis_rotated ? 'y2' : 'x2', xx);
$$.smoothLines(focusEl, 'grid');
};
c3_chart_internal_fn.hideXGridFocus = function () {
this.main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
};
c3_chart_internal_fn.updateXgridFocus = function () {
var $$ = this, config = $$.config;
$$.main.select('line.' + CLASS.xgridFocus)
.attr("x1", config.axis_rotated ? 0 : -10)
.attr("x2", config.axis_rotated ? $$.width : -10)
.attr("y1", config.axis_rotated ? -10 : 0)
.attr("y2", config.axis_rotated ? -10 : $$.height);
};
c3_chart_internal_fn.generateGridData = function (type, scale) {
var $$ = this,
gridData = [], xDomain, firstYear, lastYear, i,
tickNum = $$.main.select("." + CLASS.axisX).selectAll('.tick').size();
if (type === 'year') {
xDomain = $$.getXDomain();
firstYear = xDomain[0].getFullYear();
lastYear = xDomain[1].getFullYear();
for (i = firstYear; i <= lastYear; i++) {
gridData.push(new Date(i + '-01-01 00:00:00'));
}
} else {
gridData = scale.ticks(10);
if (gridData.length > tickNum) { // use only int
gridData = gridData.filter(function (d) { return ("" + d).indexOf('.') < 0; });
}
}
return gridData;
};
c3_chart_internal_fn.getGridFilterToRemove = function (params) {
return params ? function (line) {
var found = false;
[].concat(params).forEach(function (param) {
if ((('value' in param && line.value === param.value) || ('class' in param && line['class'] === param['class']))) {
found = true;
}
});
return found;
} : function () { return true; };
};
c3_chart_internal_fn.removeGridLines = function (params, forX) {
var $$ = this, config = $$.config,
toRemove = $$.getGridFilterToRemove(params),
toShow = function (line) { return !toRemove(line); },
classLines = forX ? CLASS.xgridLines : CLASS.ygridLines,
classLine = forX ? CLASS.xgridLine : CLASS.ygridLine;
$$.main.select('.' + classLines).selectAll('.' + classLine).filter(toRemove)
.transition().duration(config.transition_duration)
.style('opacity', 0).remove();
if (forX) {
config.grid_x_lines = config.grid_x_lines.filter(toShow);
} else {
config.grid_y_lines = config.grid_y_lines.filter(toShow);
}
};
c3_chart_internal_fn.initTooltip = function () {
var $$ = this, config = $$.config, i;
$$.tooltip = $$.selectChart
.style("position", "relative")
.append("div")
.attr('class', CLASS.tooltipContainer)
.style("position", "absolute")
.style("pointer-events", "none")
.style("display", "none");
// Show tooltip if needed
if (config.tooltip_init_show) {
if ($$.isTimeSeries() && isString(config.tooltip_init_x)) {
config.tooltip_init_x = $$.parseDate(config.tooltip_init_x);
for (i = 0; i < $$.data.targets[0].values.length; i++) {
if (($$.data.targets[0].values[i].x - config.tooltip_init_x) === 0) { break; }
}
config.tooltip_init_x = i;
}
$$.tooltip.html(config.tooltip_contents.call($$, $$.data.targets.map(function (d) {
return $$.addName(d.values[config.tooltip_init_x]);
}), $$.axis.getXAxisTickFormat(), $$.getYFormat($$.hasArcType()), $$.color));
$$.tooltip.style("top", config.tooltip_init_position.top)
.style("left", config.tooltip_init_position.left)
.style("display", "block");
}
};
c3_chart_internal_fn.getTooltipContent = function (d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor,
orderAsc = $$.isOrderAsc();
if (config.data_groups.length === 0) {
d.sort(function(a, b){
var v1 = a ? a.value : null, v2 = b ? b.value : null;
return orderAsc ? v1 - v2 : v2 - v1;
});
} else {
var ids = $$.orderTargets($$.data.targets).map(function (i) {
return i.id;
});
d.sort(function(a, b) {
var v1 = a ? a.value : null, v2 = b ? b.value : null;
if (v1 > 0 && v2 > 0) {
v1 = a ? ids.indexOf(a.id) : null;
v2 = b ? ids.indexOf(b.id) : null;
}
return orderAsc ? v1 - v2 : v2 - v1;
});
}
for (i = 0; i < d.length; i++) {
if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
if (! text) {
title = sanitise(titleFormat ? titleFormat(d[i].x) : d[i].x);
text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
value = sanitise(valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index, d));
if (value !== undefined) {
// Skip elements when their name is set to null
if (d[i].name === null) { continue; }
name = sanitise(nameFormat(d[i].name, d[i].ratio, d[i].id, d[i].index));
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + $$.CLASS.tooltipName + "-" + $$.getTargetSelectorSuffix(d[i].id) + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
}
return text + "</table>";
};
c3_chart_internal_fn.tooltipPosition = function (dataToShow, tWidth, tHeight, element) {
var $$ = this, config = $$.config, d3 = $$.d3;
var svgLeft, tooltipLeft, tooltipRight, tooltipTop, chartRight;
var forArc = $$.hasArcType(),
mouse = d3.mouse(element);
// Determin tooltip position
if (forArc) {
tooltipLeft = (($$.width - ($$.isLegendRight ? $$.getLegendWidth() : 0)) / 2) + mouse[0];
tooltipTop = ($$.height / 2) + mouse[1] + 20;
} else {
svgLeft = $$.getSvgLeft(true);
if (config.axis_rotated) {
tooltipLeft = svgLeft + mouse[0] + 100;
tooltipRight = tooltipLeft + tWidth;
chartRight = $$.currentWidth - $$.getCurrentPaddingRight();
tooltipTop = $$.x(dataToShow[0].x) + 20;
} else {
tooltipLeft = svgLeft + $$.getCurrentPaddingLeft(true) + $$.x(dataToShow[0].x) + 20;
tooltipRight = tooltipLeft + tWidth;
chartRight = svgLeft + $$.currentWidth - $$.getCurrentPaddingRight();
tooltipTop = mouse[1] + 15;
}
if (tooltipRight > chartRight) {
// 20 is needed for Firefox to keep tooltip width
tooltipLeft -= tooltipRight - chartRight + 20;
}
if (tooltipTop + tHeight > $$.currentHeight) {
tooltipTop -= tHeight + 30;
}
}
if (tooltipTop < 0) {
tooltipTop = 0;
}
return {top: tooltipTop, left: tooltipLeft};
};
c3_chart_internal_fn.showTooltip = function (selectedData, element) {
var $$ = this, config = $$.config;
var tWidth, tHeight, position;
var forArc = $$.hasArcType(),
dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }),
positionFunction = config.tooltip_position || c3_chart_internal_fn.tooltipPosition;
if (dataToShow.length === 0 || !config.tooltip_show) {
return;
}
$$.tooltip.html(config.tooltip_contents.call($$, selectedData, $$.axis.getXAxisTickFormat(), $$.getYFormat(forArc), $$.color)).style("display", "block");
// Get tooltip dimensions
tWidth = $$.tooltip.property('offsetWidth');
tHeight = $$.tooltip.property('offsetHeight');
position = positionFunction.call(this, dataToShow, tWidth, tHeight, element);
// Set tooltip
$$.tooltip
.style("top", position.top + "px")
.style("left", position.left + 'px');
};
c3_chart_internal_fn.hideTooltip = function () {
this.tooltip.style("display", "none");
};
c3_chart_internal_fn.initLegend = function () {
var $$ = this;
$$.legendItemTextBox = {};
$$.legendHasRendered = false;
$$.legend = $$.svg.append("g").attr("transform", $$.getTranslate('legend'));
if (!$$.config.legend_show) {
$$.legend.style('visibility', 'hidden');
$$.hiddenLegendIds = $$.mapToIds($$.data.targets);
return;
}
// MEMO: call here to update legend box and tranlate for all
// MEMO: translate will be upated by this, so transform not needed in updateLegend()
$$.updateLegendWithDefaults();
};
c3_chart_internal_fn.updateLegendWithDefaults = function () {
var $$ = this;
$$.updateLegend($$.mapToIds($$.data.targets), {withTransform: false, withTransitionForTransform: false, withTransition: false});
};
c3_chart_internal_fn.updateSizeForLegend = function (legendHeight, legendWidth) {
var $$ = this, config = $$.config, insetLegendPosition = {
top: $$.isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : $$.currentHeight - legendHeight - $$.getCurrentPaddingBottom() - config.legend_inset_y,
left: $$.isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 : $$.currentWidth - legendWidth - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5
};
$$.margin3 = {
top: $$.isLegendRight ? 0 : $$.isLegendInset ? insetLegendPosition.top : $$.currentHeight - legendHeight,
right: NaN,
bottom: 0,
left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0
};
};
c3_chart_internal_fn.transformLegend = function (withTransition) {
var $$ = this;
(withTransition ? $$.legend.transition() : $$.legend).attr("transform", $$.getTranslate('legend'));
};
c3_chart_internal_fn.updateLegendStep = function (step) {
this.legendStep = step;
};
c3_chart_internal_fn.updateLegendItemWidth = function (w) {
this.legendItemWidth = w;
};
c3_chart_internal_fn.updateLegendItemHeight = function (h) {
this.legendItemHeight = h;
};
c3_chart_internal_fn.getLegendWidth = function () {
var $$ = this;
return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0;
};
c3_chart_internal_fn.getLegendHeight = function () {
var $$ = this, h = 0;
if ($$.config.legend_show) {
if ($$.isLegendRight) {
h = $$.currentHeight;
} else {
h = Math.max(20, $$.legendItemHeight) * ($$.legendStep + 1);
}
}
return h;
};
c3_chart_internal_fn.opacityForLegend = function (legendItem) {
return legendItem.classed(CLASS.legendItemHidden) ? null : 1;
};
c3_chart_internal_fn.opacityForUnfocusedLegend = function (legendItem) {
return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3;
};
c3_chart_internal_fn.toggleFocusLegend = function (targetIds, focus) {
var $$ = this;
targetIds = $$.mapToTargetIds(targetIds);
$$.legend.selectAll('.' + CLASS.legendItem)
.filter(function (id) { return targetIds.indexOf(id) >= 0; })
.classed(CLASS.legendItemFocused, focus)
.transition().duration(100)
.style('opacity', function () {
var opacity = focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend;
return opacity.call($$, $$.d3.select(this));
});
};
c3_chart_internal_fn.revertLegend = function () {
var $$ = this, d3 = $$.d3;
$$.legend.selectAll('.' + CLASS.legendItem)
.classed(CLASS.legendItemFocused, false)
.transition().duration(100)
.style('opacity', function () { return $$.opacityForLegend(d3.select(this)); });
};
c3_chart_internal_fn.showLegend = function (targetIds) {
var $$ = this, config = $$.config;
if (!config.legend_show) {
config.legend_show = true;
$$.legend.style('visibility', 'visible');
if (!$$.legendHasRendered) {
$$.updateLegendWithDefaults();
}
}
$$.removeHiddenLegendIds(targetIds);
$$.legend.selectAll($$.selectorLegends(targetIds))
.style('visibility', 'visible')
.transition()
.style('opacity', function () { return $$.opacityForLegend($$.d3.select(this)); });
};
c3_chart_internal_fn.hideLegend = function (targetIds) {
var $$ = this, config = $$.config;
if (config.legend_show && isEmpty(targetIds)) {
config.legend_show = false;
$$.legend.style('visibility', 'hidden');
}
$$.addHiddenLegendIds(targetIds);
$$.legend.selectAll($$.selectorLegends(targetIds))
.style('opacity', 0)
.style('visibility', 'hidden');
};
c3_chart_internal_fn.clearLegendItemTextBoxCache = function () {
this.legendItemTextBox = {};
};
c3_chart_internal_fn.updateLegend = function (targetIds, options, transitions) {
var $$ = this, config = $$.config;
var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect, x1ForLegendTile, x2ForLegendTile, yForLegendTile;
var paddingTop = 4, paddingRight = 10, maxWidth = 0, maxHeight = 0, posMin = 10, tileWidth = config.legend_item_tile_width + 5;
var l, totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = [0], steps = {}, step = 0;
var withTransition, withTransitionForTransform;
var texts, rects, tiles, background;
// Skip elements when their name is set to null
targetIds = targetIds.filter(function(id) {
return !isDefined(config.data_names[id]) || config.data_names[id] !== null;
});
options = options || {};
withTransition = getOption(options, "withTransition", true);
withTransitionForTransform = getOption(options, "withTransitionForTransform", true);
function getTextBox(textElement, id) {
if (!$$.legendItemTextBox[id]) {
$$.legendItemTextBox[id] = $$.getTextRect(textElement.textContent, CLASS.legendItem, textElement);
}
return $$.legendItemTextBox[id];
}
function updatePositions(textElement, id, index) {
var reset = index === 0, isLast = index === targetIds.length - 1,
box = getTextBox(textElement, id),
itemWidth = box.width + tileWidth + (isLast && !($$.isLegendRight || $$.isLegendInset) ? 0 : paddingRight) + config.legend_padding,
itemHeight = box.height + paddingTop,
itemLength = $$.isLegendRight || $$.isLegendInset ? itemHeight : itemWidth,
areaLength = $$.isLegendRight || $$.isLegendInset ? $$.getLegendHeight() : $$.getLegendWidth(),
margin, maxLength;
// MEMO: care about condifion of step, totalLength
function updateValues(id, withoutStep) {
if (!withoutStep) {
margin = (areaLength - totalLength - itemLength) / 2;
if (margin < posMin) {
margin = (areaLength - itemLength) / 2;
totalLength = 0;
step++;
}
}
steps[id] = step;
margins[step] = $$.isLegendInset ? 10 : margin;
offsets[id] = totalLength;
totalLength += itemLength;
}
if (reset) {
totalLength = 0;
step = 0;
maxWidth = 0;
maxHeight = 0;
}
if (config.legend_show && !$$.isLegendToShow(id)) {
widths[id] = heights[id] = steps[id] = offsets[id] = 0;
return;
}
widths[id] = itemWidth;
heights[id] = itemHeight;
if (!maxWidth || itemWidth >= maxWidth) { maxWidth = itemWidth; }
if (!maxHeight || itemHeight >= maxHeight) { maxHeight = itemHeight; }
maxLength = $$.isLegendRight || $$.isLegendInset ? maxHeight : maxWidth;
if (config.legend_equally) {
Object.keys(widths).forEach(function (id) { widths[id] = maxWidth; });
Object.keys(heights).forEach(function (id) { heights[id] = maxHeight; });
margin = (areaLength - maxLength * targetIds.length) / 2;
if (margin < posMin) {
totalLength = 0;
step = 0;
targetIds.forEach(function (id) { updateValues(id); });
}
else {
updateValues(id, true);
}
} else {
updateValues(id);
}
}
if ($$.isLegendInset) {
step = config.legend_inset_step ? config.legend_inset_step : targetIds.length;
$$.updateLegendStep(step);
}
if ($$.isLegendRight) {
xForLegend = function (id) { return maxWidth * steps[id]; };
yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
} else if ($$.isLegendInset) {
xForLegend = function (id) { return maxWidth * steps[id] + 10; };
yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
} else {
xForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
yForLegend = function (id) { return maxHeight * steps[id]; };
}
xForLegendText = function (id, i) { return xForLegend(id, i) + 4 + config.legend_item_tile_width; };
yForLegendText = function (id, i) { return yForLegend(id, i) + 9; };
xForLegendRect = function (id, i) { return xForLegend(id, i); };
yForLegendRect = function (id, i) { return yForLegend(id, i) - 5; };
x1ForLegendTile = function (id, i) { return xForLegend(id, i) - 2; };
x2ForLegendTile = function (id, i) { return xForLegend(id, i) - 2 + config.legend_item_tile_width; };
yForLegendTile = function (id, i) { return yForLegend(id, i) + 4; };
// Define g for legend area
l = $$.legend.selectAll('.' + CLASS.legendItem)
.data(targetIds)
.enter().append('g')
.attr('class', function (id) { return $$.generateClass(CLASS.legendItem, id); })
.style('visibility', function (id) { return $$.isLegendToShow(id) ? 'visible' : 'hidden'; })
.style('cursor', 'pointer')
.on('click', function (id) {
if (config.legend_item_onclick) {
config.legend_item_onclick.call($$, id);
} else {
if ($$.d3.event.altKey) {
$$.api.hide();
$$.api.show(id);
} else {
$$.api.toggle(id);
$$.isTargetToShow(id) ? $$.api.focus(id) : $$.api.revert();
}
}
})
.on('mouseover', function (id) {
if (config.legend_item_onmouseover) {
config.legend_item_onmouseover.call($$, id);
}
else {
$$.d3.select(this).classed(CLASS.legendItemFocused, true);
if (!$$.transiting && $$.isTargetToShow(id)) {
$$.api.focus(id);
}
}
})
.on('mouseout', function (id) {
if (config.legend_item_onmouseout) {
config.legend_item_onmouseout.call($$, id);
}
else {
$$.d3.select(this).classed(CLASS.legendItemFocused, false);
$$.api.revert();
}
});
l.append('text')
.text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; })
.each(function (id, i) { updatePositions(this, id, i); })
.style("pointer-events", "none")
.attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200)
.attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendText);
l.append('rect')
.attr("class", CLASS.legendItemEvent)
.style('fill-opacity', 0)
.attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendRect : -200)
.attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendRect);
l.append('line')
.attr('class', CLASS.legendItemTile)
.style('stroke', $$.color)
.style("pointer-events", "none")
.attr('x1', $$.isLegendRight || $$.isLegendInset ? x1ForLegendTile : -200)
.attr('y1', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile)
.attr('x2', $$.isLegendRight || $$.isLegendInset ? x2ForLegendTile : -200)
.attr('y2', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile)
.attr('stroke-width', config.legend_item_tile_height);
// Set background for inset legend
background = $$.legend.select('.' + CLASS.legendBackground + ' rect');
if ($$.isLegendInset && maxWidth > 0 && background.size() === 0) {
background = $$.legend.insert('g', '.' + CLASS.legendItem)
.attr("class", CLASS.legendBackground)
.append('rect');
}
texts = $$.legend.selectAll('text')
.data(targetIds)
.text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }) // MEMO: needed for update
.each(function (id, i) { updatePositions(this, id, i); });
(withTransition ? texts.transition() : texts)
.attr('x', xForLegendText)
.attr('y', yForLegendText);
rects = $$.legend.selectAll('rect.' + CLASS.legendItemEvent)
.data(targetIds);
(withTransition ? rects.transition() : rects)
.attr('width', function (id) { return widths[id]; })
.attr('height', function (id) { return heights[id]; })
.attr('x', xForLegendRect)
.attr('y', yForLegendRect);
tiles = $$.legend.selectAll('line.' + CLASS.legendItemTile)
.data(targetIds);
(withTransition ? tiles.transition() : tiles)
.style('stroke', $$.color)
.attr('x1', x1ForLegendTile)
.attr('y1', yForLegendTile)
.attr('x2', x2ForLegendTile)
.attr('y2', yForLegendTile);
if (background) {
(withTransition ? background.transition() : background)
.attr('height', $$.getLegendHeight() - 12)
.attr('width', maxWidth * (step + 1) + 10);
}
// toggle legend state
$$.legend.selectAll('.' + CLASS.legendItem)
.classed(CLASS.legendItemHidden, function (id) { return !$$.isTargetToShow(id); });
// Update all to reflect change of legend
$$.updateLegendItemWidth(maxWidth);
$$.updateLegendItemHeight(maxHeight);
$$.updateLegendStep(step);
// Update size and scale
$$.updateSizes();
$$.updateScales();
$$.updateSvgSize();
// Update g positions
$$.transformAll(withTransitionForTransform, transitions);
$$.legendHasRendered = true;
};
c3_chart_internal_fn.initTitle = function () {
var $$ = this;
$$.title = $$.svg.append("text")
.text($$.config.title_text)
.attr("class", $$.CLASS.title);
};
c3_chart_internal_fn.redrawTitle = function () {
var $$ = this;
$$.title
.attr("x", $$.xForTitle.bind($$))
.attr("y", $$.yForTitle.bind($$));
};
c3_chart_internal_fn.xForTitle = function () {
var $$ = this, config = $$.config, position = config.title_position || 'left', x;
if (position.indexOf('right') >= 0) {
x = $$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width - config.title_padding.right;
} else if (position.indexOf('center') >= 0) {
x = ($$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width) / 2;
} else { // left
x = config.title_padding.left;
}
return x;
};
c3_chart_internal_fn.yForTitle = function () {
var $$ = this;
return $$.config.title_padding.top + $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).height;
};
c3_chart_internal_fn.getTitlePadding = function() {
var $$ = this;
return $$.yForTitle() + $$.config.title_padding.bottom;
};
function Axis(owner) {
API.call(this, owner);
}
inherit(API, Axis);
Axis.prototype.init = function init() {
var $$ = this.owner, config = $$.config, main = $$.main;
$$.axes.x = main.append("g")
.attr("class", CLASS.axis + ' ' + CLASS.axisX)
.attr("clip-path", $$.clipPathForXAxis)
.attr("transform", $$.getTranslate('x'))
.style("visibility", config.axis_x_show ? 'visible' : 'hidden');
$$.axes.x.append("text")
.attr("class", CLASS.axisXLabel)
.attr("transform", config.axis_rotated ? "rotate(-90)" : "")
.style("text-anchor", this.textAnchorForXAxisLabel.bind(this));
$$.axes.y = main.append("g")
.attr("class", CLASS.axis + ' ' + CLASS.axisY)
.attr("clip-path", config.axis_y_inner ? "" : $$.clipPathForYAxis)
.attr("transform", $$.getTranslate('y'))
.style("visibility", config.axis_y_show ? 'visible' : 'hidden');
$$.axes.y.append("text")
.attr("class", CLASS.axisYLabel)
.attr("transform", config.axis_rotated ? "" : "rotate(-90)")
.style("text-anchor", this.textAnchorForYAxisLabel.bind(this));
$$.axes.y2 = main.append("g")
.attr("class", CLASS.axis + ' ' + CLASS.axisY2)
// clip-path?
.attr("transform", $$.getTranslate('y2'))
.style("visibility", config.axis_y2_show ? 'visible' : 'hidden');
$$.axes.y2.append("text")
.attr("class", CLASS.axisY2Label)
.attr("transform", config.axis_rotated ? "" : "rotate(-90)")
.style("text-anchor", this.textAnchorForY2AxisLabel.bind(this));
};
Axis.prototype.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
var $$ = this.owner, config = $$.config,
axisParams = {
isCategory: $$.isCategorized(),
withOuterTick: withOuterTick,
tickMultiline: config.axis_x_tick_multiline,
tickWidth: config.axis_x_tick_width,
tickTextRotate: withoutRotateTickText ? 0 : config.axis_x_tick_rotate,
withoutTransition: withoutTransition,
},
axis = c3_axis($$.d3, axisParams).scale(scale).orient(orient);
if ($$.isTimeSeries() && tickValues && typeof tickValues !== "function") {
tickValues = tickValues.map(function (v) { return $$.parseDate(v); });
}
// Set tick
axis.tickFormat(tickFormat).tickValues(tickValues);
if ($$.isCategorized()) {
axis.tickCentered(config.axis_x_tick_centered);
if (isEmpty(config.axis_x_tick_culling)) {
config.axis_x_tick_culling = false;
}
}
return axis;
};
Axis.prototype.updateXAxisTickValues = function updateXAxisTickValues(targets, axis) {
var $$ = this.owner, config = $$.config, tickValues;
if (config.axis_x_tick_fit || config.axis_x_tick_count) {
tickValues = this.generateTickValues($$.mapTargetsToUniqueXs(targets), config.axis_x_tick_count, $$.isTimeSeries());
}
if (axis) {
axis.tickValues(tickValues);
} else {
$$.xAxis.tickValues(tickValues);
$$.subXAxis.tickValues(tickValues);
}
return tickValues;
};
Axis.prototype.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
var $$ = this.owner, config = $$.config,
axisParams = {
withOuterTick: withOuterTick,
withoutTransition: withoutTransition,
tickTextRotate: withoutRotateTickText ? 0 : config.axis_y_tick_rotate
},
axis = c3_axis($$.d3, axisParams).scale(scale).orient(orient).tickFormat(tickFormat);
if ($$.isTimeSeriesY()) {
axis.ticks($$.d3.time[config.axis_y_tick_time_value], config.axis_y_tick_time_interval);
} else {
axis.tickValues(tickValues);
}
return axis;
};
Axis.prototype.getId = function getId(id) {
var config = this.owner.config;
return id in config.data_axes ? config.data_axes[id] : 'y';
};
Axis.prototype.getXAxisTickFormat = function getXAxisTickFormat() {
var $$ = this.owner, config = $$.config,
format = $$.isTimeSeries() ? $$.defaultAxisTimeFormat : $$.isCategorized() ? $$.categoryName : function (v) { return v < 0 ? v.toFixed(0) : v; };
if (config.axis_x_tick_format) {
if (isFunction(config.axis_x_tick_format)) {
format = config.axis_x_tick_format;
} else if ($$.isTimeSeries()) {
format = function (date) {
return date ? $$.axisTimeFormat(config.axis_x_tick_format)(date) : "";
};
}
}
return isFunction(format) ? function (v) { return format.call($$, v); } : format;
};
Axis.prototype.getTickValues = function getTickValues(tickValues, axis) {
return tickValues ? tickValues : axis ? axis.tickValues() : undefined;
};
Axis.prototype.getXAxisTickValues = function getXAxisTickValues() {
return this.getTickValues(this.owner.config.axis_x_tick_values, this.owner.xAxis);
};
Axis.prototype.getYAxisTickValues = function getYAxisTickValues() {
return this.getTickValues(this.owner.config.axis_y_tick_values, this.owner.yAxis);
};
Axis.prototype.getY2AxisTickValues = function getY2AxisTickValues() {
return this.getTickValues(this.owner.config.axis_y2_tick_values, this.owner.y2Axis);
};
Axis.prototype.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) {
var $$ = this.owner, config = $$.config, option;
if (axisId === 'y') {
option = config.axis_y_label;
} else if (axisId === 'y2') {
option = config.axis_y2_label;
} else if (axisId === 'x') {
option = config.axis_x_label;
}
return option;
};
Axis.prototype.getLabelText = function getLabelText(axisId) {
var option = this.getLabelOptionByAxisId(axisId);
return isString(option) ? option : option ? option.text : null;
};
Axis.prototype.setLabelText = function setLabelText(axisId, text) {
var $$ = this.owner, config = $$.config,
option = this.getLabelOptionByAxisId(axisId);
if (isString(option)) {
if (axisId === 'y') {
config.axis_y_label = text;
} else if (axisId === 'y2') {
config.axis_y2_label = text;
} else if (axisId === 'x') {
config.axis_x_label = text;
}
} else if (option) {
option.text = text;
}
};
Axis.prototype.getLabelPosition = function getLabelPosition(axisId, defaultPosition) {
var option = this.getLabelOptionByAxisId(axisId),
position = (option && typeof option === 'object' && option.position) ? option.position : defaultPosition;
return {
isInner: position.indexOf('inner') >= 0,
isOuter: position.indexOf('outer') >= 0,
isLeft: position.indexOf('left') >= 0,
isCenter: position.indexOf('center') >= 0,
isRight: position.indexOf('right') >= 0,
isTop: position.indexOf('top') >= 0,
isMiddle: position.indexOf('middle') >= 0,
isBottom: position.indexOf('bottom') >= 0
};
};
Axis.prototype.getXAxisLabelPosition = function getXAxisLabelPosition() {
return this.getLabelPosition('x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right');
};
Axis.prototype.getYAxisLabelPosition = function getYAxisLabelPosition() {
return this.getLabelPosition('y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
};
Axis.prototype.getY2AxisLabelPosition = function getY2AxisLabelPosition() {
return this.getLabelPosition('y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
};
Axis.prototype.getLabelPositionById = function getLabelPositionById(id) {
return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition();
};
Axis.prototype.textForXAxisLabel = function textForXAxisLabel() {
return this.getLabelText('x');
};
Axis.prototype.textForYAxisLabel = function textForYAxisLabel() {
return this.getLabelText('y');
};
Axis.prototype.textForY2AxisLabel = function textForY2AxisLabel() {
return this.getLabelText('y2');
};
Axis.prototype.xForAxisLabel = function xForAxisLabel(forHorizontal, position) {
var $$ = this.owner;
if (forHorizontal) {
return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width;
} else {
return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0;
}
};
Axis.prototype.dxForAxisLabel = function dxForAxisLabel(forHorizontal, position) {
if (forHorizontal) {
return position.isLeft ? "0.5em" : position.isRight ? "-0.5em" : "0";
} else {
return position.isTop ? "-0.5em" : position.isBottom ? "0.5em" : "0";
}
};
Axis.prototype.textAnchorForAxisLabel = function textAnchorForAxisLabel(forHorizontal, position) {
if (forHorizontal) {
return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end';
} else {
return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end';
}
};
Axis.prototype.xForXAxisLabel = function xForXAxisLabel() {
return this.xForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
};
Axis.prototype.xForYAxisLabel = function xForYAxisLabel() {
return this.xForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
};
Axis.prototype.xForY2AxisLabel = function xForY2AxisLabel() {
return this.xForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
};
Axis.prototype.dxForXAxisLabel = function dxForXAxisLabel() {
return this.dxForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
};
Axis.prototype.dxForYAxisLabel = function dxForYAxisLabel() {
return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
};
Axis.prototype.dxForY2AxisLabel = function dxForY2AxisLabel() {
return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
};
Axis.prototype.dyForXAxisLabel = function dyForXAxisLabel() {
var $$ = this.owner, config = $$.config,
position = this.getXAxisLabelPosition();
if (config.axis_rotated) {
return position.isInner ? "1.2em" : -25 - this.getMaxTickWidth('x');
} else {
return position.isInner ? "-0.5em" : config.axis_x_height ? config.axis_x_height - 10 : "3em";
}
};
Axis.prototype.dyForYAxisLabel = function dyForYAxisLabel() {
var $$ = this.owner,
position = this.getYAxisLabelPosition();
if ($$.config.axis_rotated) {
return position.isInner ? "-0.5em" : "3em";
} else {
return position.isInner ? "1.2em" : -10 - ($$.config.axis_y_inner ? 0 : (this.getMaxTickWidth('y') + 10));
}
};
Axis.prototype.dyForY2AxisLabel = function dyForY2AxisLabel() {
var $$ = this.owner,
position = this.getY2AxisLabelPosition();
if ($$.config.axis_rotated) {
return position.isInner ? "1.2em" : "-2.2em";
} else {
return position.isInner ? "-0.5em" : 15 + ($$.config.axis_y2_inner ? 0 : (this.getMaxTickWidth('y2') + 15));
}
};
Axis.prototype.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel(!$$.config.axis_rotated, this.getXAxisLabelPosition());
};
Axis.prototype.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getYAxisLabelPosition());
};
Axis.prototype.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getY2AxisLabelPosition());
};
Axis.prototype.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) {
var $$ = this.owner, config = $$.config,
maxWidth = 0, targetsToShow, scale, axis, dummy, svg;
if (withoutRecompute && $$.currentMaxTickWidths[id]) {
return $$.currentMaxTickWidths[id];
}
if ($$.svg) {
targetsToShow = $$.filterTargetsToShow($$.data.targets);
if (id === 'y') {
scale = $$.y.copy().domain($$.getYDomain(targetsToShow, 'y'));
axis = this.getYAxis(scale, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, false, true, true);
} else if (id === 'y2') {
scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2'));
axis = this.getYAxis(scale, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, false, true, true);
} else {
scale = $$.x.copy().domain($$.getXDomain(targetsToShow));
axis = this.getXAxis(scale, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, false, true, true);
this.updateXAxisTickValues(targetsToShow, axis);
}
dummy = $$.d3.select('body').append('div').classed('c3', true);
svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
svg.append('g').call(axis).each(function () {
$$.d3.select(this).selectAll('text').each(function () {
var box = this.getBoundingClientRect();
if (maxWidth < box.width) { maxWidth = box.width; }
});
dummy.remove();
});
}
$$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth;
return $$.currentMaxTickWidths[id];
};
Axis.prototype.updateLabels = function updateLabels(withTransition) {
var $$ = this.owner;
var axisXLabel = $$.main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel),
axisYLabel = $$.main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel),
axisY2Label = $$.main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label);
(withTransition ? axisXLabel.transition() : axisXLabel)
.attr("x", this.xForXAxisLabel.bind(this))
.attr("dx", this.dxForXAxisLabel.bind(this))
.attr("dy", this.dyForXAxisLabel.bind(this))
.text(this.textForXAxisLabel.bind(this));
(withTransition ? axisYLabel.transition() : axisYLabel)
.attr("x", this.xForYAxisLabel.bind(this))
.attr("dx", this.dxForYAxisLabel.bind(this))
.attr("dy", this.dyForYAxisLabel.bind(this))
.text(this.textForYAxisLabel.bind(this));
(withTransition ? axisY2Label.transition() : axisY2Label)
.attr("x", this.xForY2AxisLabel.bind(this))
.attr("dx", this.dxForY2AxisLabel.bind(this))
.attr("dy", this.dyForY2AxisLabel.bind(this))
.text(this.textForY2AxisLabel.bind(this));
};
Axis.prototype.getPadding = function getPadding(padding, key, defaultValue, domainLength) {
var p = typeof padding === 'number' ? padding : padding[key];
if (!isValue(p)) {
return defaultValue;
}
if (padding.unit === 'ratio') {
return padding[key] * domainLength;
}
// assume padding is pixels if unit is not specified
return this.convertPixelsToAxisPadding(p, domainLength);
};
Axis.prototype.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) {
var $$ = this.owner,
length = $$.config.axis_rotated ? $$.width : $$.height;
return domainLength * (pixels / length);
};
Axis.prototype.generateTickValues = function generateTickValues(values, tickCount, forTimeSeries) {
var tickValues = values, targetCount, start, end, count, interval, i, tickValue;
if (tickCount) {
targetCount = isFunction(tickCount) ? tickCount() : tickCount;
// compute ticks according to tickCount
if (targetCount === 1) {
tickValues = [values[0]];
} else if (targetCount === 2) {
tickValues = [values[0], values[values.length - 1]];
} else if (targetCount > 2) {
count = targetCount - 2;
start = values[0];
end = values[values.length - 1];
interval = (end - start) / (count + 1);
// re-construct unique values
tickValues = [start];
for (i = 0; i < count; i++) {
tickValue = +start + interval * (i + 1);
tickValues.push(forTimeSeries ? new Date(tickValue) : tickValue);
}
tickValues.push(end);
}
}
if (!forTimeSeries) { tickValues = tickValues.sort(function (a, b) { return a - b; }); }
return tickValues;
};
Axis.prototype.generateTransitions = function generateTransitions(duration) {
var $$ = this.owner, axes = $$.axes;
return {
axisX: duration ? axes.x.transition().duration(duration) : axes.x,
axisY: duration ? axes.y.transition().duration(duration) : axes.y,
axisY2: duration ? axes.y2.transition().duration(duration) : axes.y2,
axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx
};
};
Axis.prototype.redraw = function redraw(transitions, isHidden) {
var $$ = this.owner;
$$.axes.x.style("opacity", isHidden ? 0 : 1);
$$.axes.y.style("opacity", isHidden ? 0 : 1);
$$.axes.y2.style("opacity", isHidden ? 0 : 1);
$$.axes.subx.style("opacity", isHidden ? 0 : 1);
transitions.axisX.call($$.xAxis);
transitions.axisY.call($$.yAxis);
transitions.axisY2.call($$.y2Axis);
transitions.axisSubX.call($$.subXAxis);
};
c3_chart_internal_fn.getClipPath = function (id) {
var isIE9 = window.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0;
return "url(" + (isIE9 ? "" : document.URL.split('#')[0]) + "#" + id + ")";
};
c3_chart_internal_fn.appendClip = function (parent, id) {
return parent.append("clipPath").attr("id", id).append("rect");
};
c3_chart_internal_fn.getAxisClipX = function (forHorizontal) {
// axis line width + padding for left
var left = Math.max(30, this.margin.left);
return forHorizontal ? -(1 + left) : -(left - 1);
};
c3_chart_internal_fn.getAxisClipY = function (forHorizontal) {
return forHorizontal ? -20 : -this.margin.top;
};
c3_chart_internal_fn.getXAxisClipX = function () {
var $$ = this;
return $$.getAxisClipX(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getXAxisClipY = function () {
var $$ = this;
return $$.getAxisClipY(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipX = function () {
var $$ = this;
return $$.config.axis_y_inner ? -1 : $$.getAxisClipX($$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipY = function () {
var $$ = this;
return $$.getAxisClipY($$.config.axis_rotated);
};
c3_chart_internal_fn.getAxisClipWidth = function (forHorizontal) {
var $$ = this,
left = Math.max(30, $$.margin.left),
right = Math.max(30, $$.margin.right);
// width + axis line width + padding for left/right
return forHorizontal ? $$.width + 2 + left + right : $$.margin.left + 20;
};
c3_chart_internal_fn.getAxisClipHeight = function (forHorizontal) {
// less than 20 is not enough to show the axis label 'outer' without legend
return (forHorizontal ? this.margin.bottom : (this.margin.top + this.height)) + 20;
};
c3_chart_internal_fn.getXAxisClipWidth = function () {
var $$ = this;
return $$.getAxisClipWidth(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getXAxisClipHeight = function () {
var $$ = this;
return $$.getAxisClipHeight(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipWidth = function () {
var $$ = this;
return $$.getAxisClipWidth($$.config.axis_rotated) + ($$.config.axis_y_inner ? 20 : 0);
};
c3_chart_internal_fn.getYAxisClipHeight = function () {
var $$ = this;
return $$.getAxisClipHeight($$.config.axis_rotated);
};
c3_chart_internal_fn.initPie = function () {
var $$ = this, d3 = $$.d3, config = $$.config;
$$.pie = d3.layout.pie().value(function (d) {
return d.values.reduce(function (a, b) { return a + b.value; }, 0);
});
if (!config.data_order) {
$$.pie.sort(null);
}
};
c3_chart_internal_fn.updateRadius = function () {
var $$ = this, config = $$.config,
w = config.gauge_width || config.donut_width;
$$.radiusExpanded = Math.min($$.arcWidth, $$.arcHeight) / 2;
$$.radius = $$.radiusExpanded * 0.95;
$$.innerRadiusRatio = w ? ($$.radius - w) / $$.radius : 0.6;
$$.innerRadius = $$.hasType('donut') || $$.hasType('gauge') ? $$.radius * $$.innerRadiusRatio : 0;
};
c3_chart_internal_fn.updateArc = function () {
var $$ = this;
$$.svgArc = $$.getSvgArc();
$$.svgArcExpanded = $$.getSvgArcExpanded();
$$.svgArcExpandedSub = $$.getSvgArcExpanded(0.98);
};
c3_chart_internal_fn.updateAngle = function (d) {
var $$ = this, config = $$.config,
found = false, index = 0,
gMin, gMax, gTic, gValue;
if (!config) {
return null;
}
$$.pie($$.filterTargetsToShow($$.data.targets)).forEach(function (t) {
if (! found && t.data.id === d.data.id) {
found = true;
d = t;
d.index = index;
}
index++;
});
if (isNaN(d.startAngle)) {
d.startAngle = 0;
}
if (isNaN(d.endAngle)) {
d.endAngle = d.startAngle;
}
if ($$.isGaugeType(d.data)) {
gMin = config.gauge_min;
gMax = config.gauge_max;
gTic = (Math.PI * (config.gauge_fullCircle ? 2 : 1)) / (gMax - gMin);
gValue = d.value < gMin ? 0 : d.value < gMax ? d.value - gMin : (gMax - gMin);
d.startAngle = config.gauge_startingAngle;
d.endAngle = d.startAngle + gTic * gValue;
}
return found ? d : null;
};
c3_chart_internal_fn.getSvgArc = function () {
var $$ = this,
arc = $$.d3.svg.arc().outerRadius($$.radius).innerRadius($$.innerRadius),
newArc = function (d, withoutUpdate) {
var updated;
if (withoutUpdate) { return arc(d); } // for interpolate
updated = $$.updateAngle(d);
return updated ? arc(updated) : "M 0 0";
};
// TODO: extends all function
newArc.centroid = arc.centroid;
return newArc;
};
c3_chart_internal_fn.getSvgArcExpanded = function (rate) {
var $$ = this,
arc = $$.d3.svg.arc().outerRadius($$.radiusExpanded * (rate ? rate : 1)).innerRadius($$.innerRadius);
return function (d) {
var updated = $$.updateAngle(d);
return updated ? arc(updated) : "M 0 0";
};
};
c3_chart_internal_fn.getArc = function (d, withoutUpdate, force) {
return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0";
};
c3_chart_internal_fn.transformForArcLabel = function (d) {
var $$ = this, config = $$.config,
updated = $$.updateAngle(d), c, x, y, h, ratio, translate = "";
if (updated && !$$.hasType('gauge')) {
c = this.svgArc.centroid(updated);
x = isNaN(c[0]) ? 0 : c[0];
y = isNaN(c[1]) ? 0 : c[1];
h = Math.sqrt(x * x + y * y);
if ($$.hasType('donut') && config.donut_label_ratio) {
ratio = isFunction(config.donut_label_ratio) ? config.donut_label_ratio(d, $$.radius, h) : config.donut_label_ratio;
} else if ($$.hasType('pie') && config.pie_label_ratio) {
ratio = isFunction(config.pie_label_ratio) ? config.pie_label_ratio(d, $$.radius, h) : config.pie_label_ratio;
} else {
ratio = $$.radius && h ? (36 / $$.radius > 0.375 ? 1.175 - 36 / $$.radius : 0.8) * $$.radius / h : 0;
}
translate = "translate(" + (x * ratio) + ',' + (y * ratio) + ")";
}
return translate;
};
c3_chart_internal_fn.getArcRatio = function (d) {
var $$ = this,
config = $$.config,
whole = Math.PI * ($$.hasType('gauge') && !config.gauge_fullCircle ? 1 : 2);
return d ? (d.endAngle - d.startAngle) / whole : null;
};
c3_chart_internal_fn.convertToArcData = function (d) {
return this.addName({
id: d.data.id,
value: d.value,
ratio: this.getArcRatio(d),
index: d.index
});
};
c3_chart_internal_fn.textForArcLabel = function (d) {
var $$ = this,
updated, value, ratio, id, format;
if (! $$.shouldShowArcLabel()) { return ""; }
updated = $$.updateAngle(d);
value = updated ? updated.value : null;
ratio = $$.getArcRatio(updated);
id = d.data.id;
if (! $$.hasType('gauge') && ! $$.meetsArcLabelThreshold(ratio)) { return ""; }
format = $$.getArcLabelFormat();
return format ? format(value, ratio, id) : $$.defaultArcValueFormat(value, ratio);
};
c3_chart_internal_fn.expandArc = function (targetIds) {
var $$ = this, interval;
// MEMO: avoid to cancel transition
if ($$.transiting) {
interval = window.setInterval(function () {
if (!$$.transiting) {
window.clearInterval(interval);
if ($$.legend.selectAll('.c3-legend-item-focused').size() > 0) {
$$.expandArc(targetIds);
}
}
}, 10);
return;
}
targetIds = $$.mapToTargetIds(targetIds);
$$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).each(function (d) {
if (! $$.shouldExpand(d.data.id)) { return; }
$$.d3.select(this).selectAll('path')
.transition().duration($$.expandDuration(d.data.id))
.attr("d", $$.svgArcExpanded)
.transition().duration($$.expandDuration(d.data.id) * 2)
.attr("d", $$.svgArcExpandedSub)
.each(function (d) {
if ($$.isDonutType(d.data)) {
// callback here
}
});
});
};
c3_chart_internal_fn.unexpandArc = function (targetIds) {
var $$ = this;
if ($$.transiting) { return; }
targetIds = $$.mapToTargetIds(targetIds);
$$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).selectAll('path')
.transition().duration(function(d) {
return $$.expandDuration(d.data.id);
})
.attr("d", $$.svgArc);
$$.svg.selectAll('.' + CLASS.arc)
.style("opacity", 1);
};
c3_chart_internal_fn.expandDuration = function (id) {
var $$ = this, config = $$.config;
if ($$.isDonutType(id)) {
return config.donut_expand_duration;
} else if ($$.isGaugeType(id)) {
return config.gauge_expand_duration;
} else if ($$.isPieType(id)) {
return config.pie_expand_duration;
} else {
return 50;
}
};
c3_chart_internal_fn.shouldExpand = function (id) {
var $$ = this, config = $$.config;
return ($$.isDonutType(id) && config.donut_expand) ||
($$.isGaugeType(id) && config.gauge_expand) ||
($$.isPieType(id) && config.pie_expand);
};
c3_chart_internal_fn.shouldShowArcLabel = function () {
var $$ = this, config = $$.config, shouldShow = true;
if ($$.hasType('donut')) {
shouldShow = config.donut_label_show;
} else if ($$.hasType('pie')) {
shouldShow = config.pie_label_show;
}
// when gauge, always true
return shouldShow;
};
c3_chart_internal_fn.meetsArcLabelThreshold = function (ratio) {
var $$ = this, config = $$.config,
threshold = $$.hasType('donut') ? config.donut_label_threshold : config.pie_label_threshold;
return ratio >= threshold;
};
c3_chart_internal_fn.getArcLabelFormat = function () {
var $$ = this, config = $$.config,
format = config.pie_label_format;
if ($$.hasType('gauge')) {
format = config.gauge_label_format;
} else if ($$.hasType('donut')) {
format = config.donut_label_format;
}
return format;
};
c3_chart_internal_fn.getArcTitle = function () {
var $$ = this;
return $$.hasType('donut') ? $$.config.donut_title : "";
};
c3_chart_internal_fn.updateTargetsForArc = function (targets) {
var $$ = this, main = $$.main,
mainPieUpdate, mainPieEnter,
classChartArc = $$.classChartArc.bind($$),
classArcs = $$.classArcs.bind($$),
classFocus = $$.classFocus.bind($$);
mainPieUpdate = main.select('.' + CLASS.chartArcs).selectAll('.' + CLASS.chartArc)
.data($$.pie(targets))
.attr("class", function (d) { return classChartArc(d) + classFocus(d.data); });
mainPieEnter = mainPieUpdate.enter().append("g")
.attr("class", classChartArc);
mainPieEnter.append('g')
.attr('class', classArcs);
mainPieEnter.append("text")
.attr("dy", $$.hasType('gauge') ? "-.1em" : ".35em")
.style("opacity", 0)
.style("text-anchor", "middle")
.style("pointer-events", "none");
// MEMO: can not keep same color..., but not bad to update color in redraw
//mainPieUpdate.exit().remove();
};
c3_chart_internal_fn.initArc = function () {
var $$ = this;
$$.arcs = $$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartArcs)
.attr("transform", $$.getTranslate('arc'));
$$.arcs.append('text')
.attr('class', CLASS.chartArcsTitle)
.style("text-anchor", "middle")
.text($$.getArcTitle());
};
c3_chart_internal_fn.redrawArc = function (duration, durationForExit, withTransform) {
var $$ = this, d3 = $$.d3, config = $$.config, main = $$.main,
mainArc;
mainArc = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arc)
.data($$.arcData.bind($$));
mainArc.enter().append('path')
.attr("class", $$.classArc.bind($$))
.style("fill", function (d) { return $$.color(d.data); })
.style("cursor", function (d) { return config.interaction_enabled && config.data_selection_isselectable(d) ? "pointer" : null; })
.style("opacity", 0)
.each(function (d) {
if ($$.isGaugeType(d.data)) {
d.startAngle = d.endAngle = config.gauge_startingAngle;
}
this._current = d;
});
mainArc
.attr("transform", function (d) { return !$$.isGaugeType(d.data) && withTransform ? "scale(0)" : ""; })
.style("opacity", function (d) { return d === this._current ? 0 : 1; })
.on('mouseover', config.interaction_enabled ? function (d) {
var updated, arcData;
if ($$.transiting) { // skip while transiting
return;
}
updated = $$.updateAngle(d);
if (updated) {
arcData = $$.convertToArcData(updated);
// transitions
$$.expandArc(updated.data.id);
$$.api.focus(updated.data.id);
$$.toggleFocusLegend(updated.data.id, true);
$$.config.data_onmouseover(arcData, this);
}
} : null)
.on('mousemove', config.interaction_enabled ? function (d) {
var updated = $$.updateAngle(d), arcData, selectedData;
if (updated) {
arcData = $$.convertToArcData(updated),
selectedData = [arcData];
$$.showTooltip(selectedData, this);
}
} : null)
.on('mouseout', config.interaction_enabled ? function (d) {
var updated, arcData;
if ($$.transiting) { // skip while transiting
return;
}
updated = $$.updateAngle(d);
if (updated) {
arcData = $$.convertToArcData(updated);
// transitions
$$.unexpandArc(updated.data.id);
$$.api.revert();
$$.revertLegend();
$$.hideTooltip();
$$.config.data_onmouseout(arcData, this);
}
} : null)
.on('click', config.interaction_enabled ? function (d, i) {
var updated = $$.updateAngle(d), arcData;
if (updated) {
arcData = $$.convertToArcData(updated);
if ($$.toggleShape) {
$$.toggleShape(this, arcData, i);
}
$$.config.data_onclick.call($$.api, arcData, this);
}
} : null)
.each(function () { $$.transiting = true; })
.transition().duration(duration)
.attrTween("d", function (d) {
var updated = $$.updateAngle(d), interpolate;
if (! updated) {
return function () { return "M 0 0"; };
}
// if (this._current === d) {
// this._current = {
// startAngle: Math.PI*2,
// endAngle: Math.PI*2,
// };
// }
if (isNaN(this._current.startAngle)) {
this._current.startAngle = 0;
}
if (isNaN(this._current.endAngle)) {
this._current.endAngle = this._current.startAngle;
}
interpolate = d3.interpolate(this._current, updated);
this._current = interpolate(0);
return function (t) {
var interpolated = interpolate(t);
interpolated.data = d.data; // data.id will be updated by interporator
return $$.getArc(interpolated, true);
};
})
.attr("transform", withTransform ? "scale(1)" : "")
.style("fill", function (d) {
return $$.levelColor ? $$.levelColor(d.data.values[0].value) : $$.color(d.data.id);
}) // Where gauge reading color would receive customization.
.style("opacity", 1)
.call($$.endall, function () {
$$.transiting = false;
});
mainArc.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
main.selectAll('.' + CLASS.chartArc).select('text')
.style("opacity", 0)
.attr('class', function (d) { return $$.isGaugeType(d.data) ? CLASS.gaugeValue : ''; })
.text($$.textForArcLabel.bind($$))
.attr("transform", $$.transformForArcLabel.bind($$))
.style('font-size', function (d) { return $$.isGaugeType(d.data) ? Math.round($$.radius / 5) + 'px' : ''; })
.transition().duration(duration)
.style("opacity", function (d) { return $$.isTargetToShow(d.data.id) && $$.isArcType(d.data) ? 1 : 0; });
main.select('.' + CLASS.chartArcsTitle)
.style("opacity", $$.hasType('donut') || $$.hasType('gauge') ? 1 : 0);
if ($$.hasType('gauge')) {
$$.arcs.select('.' + CLASS.chartArcsBackground)
.attr("d", function () {
var d = {
data: [{value: config.gauge_max}],
startAngle: config.gauge_startingAngle,
endAngle: -1 * config.gauge_startingAngle
};
return $$.getArc(d, true, true);
});
$$.arcs.select('.' + CLASS.chartArcsGaugeUnit)
.attr("dy", ".75em")
.text(config.gauge_label_show ? config.gauge_units : '');
$$.arcs.select('.' + CLASS.chartArcsGaugeMin)
.attr("dx", -1 * ($$.innerRadius + (($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2))) + "px")
.attr("dy", "1.2em")
.text(config.gauge_label_show ? config.gauge_min : '');
$$.arcs.select('.' + CLASS.chartArcsGaugeMax)
.attr("dx", $$.innerRadius + (($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2)) + "px")
.attr("dy", "1.2em")
.text(config.gauge_label_show ? config.gauge_max : '');
}
};
c3_chart_internal_fn.initGauge = function () {
var arcs = this.arcs;
if (this.hasType('gauge')) {
arcs.append('path')
.attr("class", CLASS.chartArcsBackground);
arcs.append("text")
.attr("class", CLASS.chartArcsGaugeUnit)
.style("text-anchor", "middle")
.style("pointer-events", "none");
arcs.append("text")
.attr("class", CLASS.chartArcsGaugeMin)
.style("text-anchor", "middle")
.style("pointer-events", "none");
arcs.append("text")
.attr("class", CLASS.chartArcsGaugeMax)
.style("text-anchor", "middle")
.style("pointer-events", "none");
}
};
c3_chart_internal_fn.getGaugeLabelHeight = function () {
return this.config.gauge_label_show ? 20 : 0;
};
c3_chart_internal_fn.initRegion = function () {
var $$ = this;
$$.region = $$.main.append('g')
.attr("clip-path", $$.clipPath)
.attr("class", CLASS.regions);
};
c3_chart_internal_fn.updateRegion = function (duration) {
var $$ = this, config = $$.config;
// hide if arc type
$$.region.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
$$.mainRegion = $$.main.select('.' + CLASS.regions).selectAll('.' + CLASS.region)
.data(config.regions);
$$.mainRegion.enter().append('g')
.append('rect')
.style("fill-opacity", 0);
$$.mainRegion
.attr('class', $$.classRegion.bind($$));
$$.mainRegion.exit().transition().duration(duration)
.style("opacity", 0)
.remove();
};
c3_chart_internal_fn.redrawRegion = function (withTransition) {
var $$ = this,
regions = $$.mainRegion.selectAll('rect').each(function () {
// data is binded to g and it's not transferred to rect (child node) automatically,
// then data of each rect has to be updated manually.
// TODO: there should be more efficient way to solve this?
var parentData = $$.d3.select(this.parentNode).datum();
$$.d3.select(this).datum(parentData);
}),
x = $$.regionX.bind($$),
y = $$.regionY.bind($$),
w = $$.regionWidth.bind($$),
h = $$.regionHeight.bind($$);
return [
(withTransition ? regions.transition() : regions)
.attr("x", x)
.attr("y", y)
.attr("width", w)
.attr("height", h)
.style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : 0.1; })
];
};
c3_chart_internal_fn.regionX = function (d) {
var $$ = this, config = $$.config,
xPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
xPos = config.axis_rotated ? ('start' in d ? yScale(d.start) : 0) : 0;
} else {
xPos = config.axis_rotated ? 0 : ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0);
}
return xPos;
};
c3_chart_internal_fn.regionY = function (d) {
var $$ = this, config = $$.config,
yPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
yPos = config.axis_rotated ? 0 : ('end' in d ? yScale(d.end) : 0);
} else {
yPos = config.axis_rotated ? ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0) : 0;
}
return yPos;
};
c3_chart_internal_fn.regionWidth = function (d) {
var $$ = this, config = $$.config,
start = $$.regionX(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
end = config.axis_rotated ? ('end' in d ? yScale(d.end) : $$.width) : $$.width;
} else {
end = config.axis_rotated ? $$.width : ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.width);
}
return end < start ? 0 : end - start;
};
c3_chart_internal_fn.regionHeight = function (d) {
var $$ = this, config = $$.config,
start = this.regionY(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
end = config.axis_rotated ? $$.height : ('start' in d ? yScale(d.start) : $$.height);
} else {
end = config.axis_rotated ? ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.height) : $$.height;
}
return end < start ? 0 : end - start;
};
c3_chart_internal_fn.isRegionOnX = function (d) {
return !d.axis || d.axis === 'x';
};
c3_chart_internal_fn.drag = function (mouse) {
var $$ = this, config = $$.config, main = $$.main, d3 = $$.d3;
var sx, sy, mx, my, minX, maxX, minY, maxY;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable
if (config.zoom_enabled && ! $$.zoom.altDomain) { return; } // skip if zoomable because of conflict drag dehavior
if (!config.data_selection_multiple) { return; } // skip when single selection because drag is used for multiple selection
sx = $$.dragStart[0];
sy = $$.dragStart[1];
mx = mouse[0];
my = mouse[1];
minX = Math.min(sx, mx);
maxX = Math.max(sx, mx);
minY = (config.data_selection_grouped) ? $$.margin.top : Math.min(sy, my);
maxY = (config.data_selection_grouped) ? $$.height : Math.max(sy, my);
main.select('.' + CLASS.dragarea)
.attr('x', minX)
.attr('y', minY)
.attr('width', maxX - minX)
.attr('height', maxY - minY);
// TODO: binary search when multiple xs
main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape)
.filter(function (d) { return config.data_selection_isselectable(d); })
.each(function (d, i) {
var shape = d3.select(this),
isSelected = shape.classed(CLASS.SELECTED),
isIncluded = shape.classed(CLASS.INCLUDED),
_x, _y, _w, _h, toggle, isWithin = false, box;
if (shape.classed(CLASS.circle)) {
_x = shape.attr("cx") * 1;
_y = shape.attr("cy") * 1;
toggle = $$.togglePoint;
isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY;
}
else if (shape.classed(CLASS.bar)) {
box = getPathBox(this);
_x = box.x;
_y = box.y;
_w = box.width;
_h = box.height;
toggle = $$.togglePath;
isWithin = !(maxX < _x || _x + _w < minX) && !(maxY < _y || _y + _h < minY);
} else {
// line/area selection not supported yet
return;
}
if (isWithin ^ isIncluded) {
shape.classed(CLASS.INCLUDED, !isIncluded);
// TODO: included/unincluded callback here
shape.classed(CLASS.SELECTED, !isSelected);
toggle.call($$, !isSelected, shape, d, i);
}
});
};
c3_chart_internal_fn.dragstart = function (mouse) {
var $$ = this, config = $$.config;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable
$$.dragStart = mouse;
$$.main.select('.' + CLASS.chart).append('rect')
.attr('class', CLASS.dragarea)
.style('opacity', 0.1);
$$.dragging = true;
};
c3_chart_internal_fn.dragend = function () {
var $$ = this, config = $$.config;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable
$$.main.select('.' + CLASS.dragarea)
.transition().duration(100)
.style('opacity', 0)
.remove();
$$.main.selectAll('.' + CLASS.shape)
.classed(CLASS.INCLUDED, false);
$$.dragging = false;
};
c3_chart_internal_fn.selectPoint = function (target, d, i) {
var $$ = this, config = $$.config,
cx = (config.axis_rotated ? $$.circleY : $$.circleX).bind($$),
cy = (config.axis_rotated ? $$.circleX : $$.circleY).bind($$),
r = $$.pointSelectR.bind($$);
config.data_onselected.call($$.api, d, target.node());
// add selected-circle on low layer g
$$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
.data([d])
.enter().append('circle')
.attr("class", function () { return $$.generateClass(CLASS.selectedCircle, i); })
.attr("cx", cx)
.attr("cy", cy)
.attr("stroke", function () { return $$.color(d); })
.attr("r", function (d) { return $$.pointSelectR(d) * 1.4; })
.transition().duration(100)
.attr("r", r);
};
c3_chart_internal_fn.unselectPoint = function (target, d, i) {
var $$ = this;
$$.config.data_onunselected.call($$.api, d, target.node());
// remove selected-circle from low layer g
$$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
.transition().duration(100).attr('r', 0)
.remove();
};
c3_chart_internal_fn.togglePoint = function (selected, target, d, i) {
selected ? this.selectPoint(target, d, i) : this.unselectPoint(target, d, i);
};
c3_chart_internal_fn.selectPath = function (target, d) {
var $$ = this;
$$.config.data_onselected.call($$, d, target.node());
if ($$.config.interaction_brighten) {
target.transition().duration(100)
.style("fill", function () { return $$.d3.rgb($$.color(d)).brighter(0.75); });
}
};
c3_chart_internal_fn.unselectPath = function (target, d) {
var $$ = this;
$$.config.data_onunselected.call($$, d, target.node());
if ($$.config.interaction_brighten) {
target.transition().duration(100)
.style("fill", function () { return $$.color(d); });
}
};
c3_chart_internal_fn.togglePath = function (selected, target, d, i) {
selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i);
};
c3_chart_internal_fn.getToggle = function (that, d) {
var $$ = this, toggle;
if (that.nodeName === 'circle') {
if ($$.isStepType(d)) {
// circle is hidden in step chart, so treat as within the click area
toggle = function () {}; // TODO: how to select step chart?
} else {
toggle = $$.togglePoint;
}
}
else if (that.nodeName === 'path') {
toggle = $$.togglePath;
}
return toggle;
};
c3_chart_internal_fn.toggleShape = function (that, d, i) {
var $$ = this, d3 = $$.d3, config = $$.config,
shape = d3.select(that), isSelected = shape.classed(CLASS.SELECTED),
toggle = $$.getToggle(that, d).bind($$);
if (config.data_selection_enabled && config.data_selection_isselectable(d)) {
if (!config.data_selection_multiple) {
$$.main.selectAll('.' + CLASS.shapes + (config.data_selection_grouped ? $$.getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) {
var shape = d3.select(this);
if (shape.classed(CLASS.SELECTED)) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); }
});
}
shape.classed(CLASS.SELECTED, !isSelected);
toggle(!isSelected, shape, d, i);
}
};
c3_chart_internal_fn.initBrush = function () {
var $$ = this, d3 = $$.d3;
$$.brush = d3.svg.brush().on("brush", function () { $$.redrawForBrush(); });
$$.brush.update = function () {
if ($$.context) { $$.context.select('.' + CLASS.brush).call(this); }
return this;
};
$$.brush.scale = function (scale) {
return $$.config.axis_rotated ? this.y(scale) : this.x(scale);
};
};
c3_chart_internal_fn.initSubchart = function () {
var $$ = this, config = $$.config,
context = $$.context = $$.svg.append("g").attr("transform", $$.getTranslate('context')),
visibility = config.subchart_show ? 'visible' : 'hidden';
context.style('visibility', visibility);
// Define g for chart area
context.append('g')
.attr("clip-path", $$.clipPathForSubchart)
.attr('class', CLASS.chart);
// Define g for bar chart area
context.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartBars);
// Define g for line chart area
context.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartLines);
// Add extent rect for Brush
context.append("g")
.attr("clip-path", $$.clipPath)
.attr("class", CLASS.brush)
.call($$.brush);
// ATTENTION: This must be called AFTER chart added
// Add Axis
$$.axes.subx = context.append("g")
.attr("class", CLASS.axisX)
.attr("transform", $$.getTranslate('subx'))
.attr("clip-path", config.axis_rotated ? "" : $$.clipPathForXAxis)
.style("visibility", config.subchart_axis_x_show ? visibility : 'hidden');
};
c3_chart_internal_fn.updateTargetsForSubchart = function (targets) {
var $$ = this, context = $$.context, config = $$.config,
contextLineEnter, contextLineUpdate, contextBarEnter, contextBarUpdate,
classChartBar = $$.classChartBar.bind($$),
classBars = $$.classBars.bind($$),
classChartLine = $$.classChartLine.bind($$),
classLines = $$.classLines.bind($$),
classAreas = $$.classAreas.bind($$);
if (config.subchart_show) {
//-- Bar --//
contextBarUpdate = context.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
.data(targets)
.attr('class', classChartBar);
contextBarEnter = contextBarUpdate.enter().append('g')
.style('opacity', 0)
.attr('class', classChartBar);
// Bars for each data
contextBarEnter.append('g')
.attr("class", classBars);
//-- Line --//
contextLineUpdate = context.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
.data(targets)
.attr('class', classChartLine);
contextLineEnter = contextLineUpdate.enter().append('g')
.style('opacity', 0)
.attr('class', classChartLine);
// Lines for each data
contextLineEnter.append("g")
.attr("class", classLines);
// Area
contextLineEnter.append("g")
.attr("class", classAreas);
//-- Brush --//
context.selectAll('.' + CLASS.brush + ' rect')
.attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? $$.width2 : $$.height2);
}
};
c3_chart_internal_fn.updateBarForSubchart = function (durationForExit) {
var $$ = this;
$$.contextBar = $$.context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
.data($$.barData.bind($$));
$$.contextBar.enter().append('path')
.attr("class", $$.classBar.bind($$))
.style("stroke", 'none')
.style("fill", $$.color);
$$.contextBar
.style("opacity", $$.initialOpacity.bind($$));
$$.contextBar.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) {
(withTransition ? this.contextBar.transition(Math.random().toString()).duration(duration) : this.contextBar)
.attr('d', drawBarOnSub)
.style('opacity', 1);
};
c3_chart_internal_fn.updateLineForSubchart = function (durationForExit) {
var $$ = this;
$$.contextLine = $$.context.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
.data($$.lineData.bind($$));
$$.contextLine.enter().append('path')
.attr('class', $$.classLine.bind($$))
.style('stroke', $$.color);
$$.contextLine
.style("opacity", $$.initialOpacity.bind($$));
$$.contextLine.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) {
(withTransition ? this.contextLine.transition(Math.random().toString()).duration(duration) : this.contextLine)
.attr("d", drawLineOnSub)
.style('opacity', 1);
};
c3_chart_internal_fn.updateAreaForSubchart = function (durationForExit) {
var $$ = this, d3 = $$.d3;
$$.contextArea = $$.context.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
.data($$.lineData.bind($$));
$$.contextArea.enter().append('path')
.attr("class", $$.classArea.bind($$))
.style("fill", $$.color)
.style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
$$.contextArea
.style("opacity", 0);
$$.contextArea.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawAreaForSubchart = function (drawAreaOnSub, withTransition, duration) {
(withTransition ? this.contextArea.transition(Math.random().toString()).duration(duration) : this.contextArea)
.attr("d", drawAreaOnSub)
.style("fill", this.color)
.style("opacity", this.orgAreaOpacity);
};
c3_chart_internal_fn.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) {
var $$ = this, d3 = $$.d3, config = $$.config,
drawAreaOnSub, drawBarOnSub, drawLineOnSub;
$$.context.style('visibility', config.subchart_show ? 'visible' : 'hidden');
// subchart
if (config.subchart_show) {
// reflect main chart to extent on subchart if zoomed
if (d3.event && d3.event.type === 'zoom') {
$$.brush.extent($$.x.orgDomain()).update();
}
// update subchart elements if needed
if (withSubchart) {
// extent rect
if (!$$.brush.empty()) {
$$.brush.extent($$.x.orgDomain()).update();
}
// setup drawer - MEMO: this must be called after axis updated
drawAreaOnSub = $$.generateDrawArea(areaIndices, true);
drawBarOnSub = $$.generateDrawBar(barIndices, true);
drawLineOnSub = $$.generateDrawLine(lineIndices, true);
$$.updateBarForSubchart(duration);
$$.updateLineForSubchart(duration);
$$.updateAreaForSubchart(duration);
$$.redrawBarForSubchart(drawBarOnSub, duration, duration);
$$.redrawLineForSubchart(drawLineOnSub, duration, duration);
$$.redrawAreaForSubchart(drawAreaOnSub, duration, duration);
}
}
};
c3_chart_internal_fn.redrawForBrush = function () {
var $$ = this, x = $$.x;
$$.redraw({
withTransition: false,
withY: $$.config.zoom_rescale,
withSubchart: false,
withUpdateXDomain: true,
withDimension: false
});
$$.config.subchart_onbrush.call($$.api, x.orgDomain());
};
c3_chart_internal_fn.transformContext = function (withTransition, transitions) {
var $$ = this, subXAxis;
if (transitions && transitions.axisSubX) {
subXAxis = transitions.axisSubX;
} else {
subXAxis = $$.context.select('.' + CLASS.axisX);
if (withTransition) { subXAxis = subXAxis.transition(); }
}
$$.context.attr("transform", $$.getTranslate('context'));
subXAxis.attr("transform", $$.getTranslate('subx'));
};
c3_chart_internal_fn.getDefaultExtent = function () {
var $$ = this, config = $$.config,
extent = isFunction(config.axis_x_extent) ? config.axis_x_extent($$.getXDomain($$.data.targets)) : config.axis_x_extent;
if ($$.isTimeSeries()) {
extent = [$$.parseDate(extent[0]), $$.parseDate(extent[1])];
}
return extent;
};
c3_chart_internal_fn.initZoom = function () {
var $$ = this, d3 = $$.d3, config = $$.config, startEvent;
$$.zoom = d3.behavior.zoom()
.on("zoomstart", function () {
startEvent = d3.event.sourceEvent;
$$.zoom.altDomain = d3.event.sourceEvent.altKey ? $$.x.orgDomain() : null;
config.zoom_onzoomstart.call($$.api, d3.event.sourceEvent);
})
.on("zoom", function () {
$$.redrawForZoom.call($$);
})
.on('zoomend', function () {
var event = d3.event.sourceEvent;
// if click, do nothing. otherwise, click interaction will be canceled.
if (event && startEvent.clientX === event.clientX && startEvent.clientY === event.clientY) {
return;
}
$$.redrawEventRect();
$$.updateZoom();
config.zoom_onzoomend.call($$.api, $$.x.orgDomain());
});
$$.zoom.scale = function (scale) {
return config.axis_rotated ? this.y(scale) : this.x(scale);
};
$$.zoom.orgScaleExtent = function () {
var extent = config.zoom_extent ? config.zoom_extent : [1, 10];
return [extent[0], Math.max($$.getMaxDataCount() / extent[1], extent[1])];
};
$$.zoom.updateScaleExtent = function () {
var ratio = diffDomain($$.x.orgDomain()) / diffDomain($$.getZoomDomain()),
extent = this.orgScaleExtent();
this.scaleExtent([extent[0] * ratio, extent[1] * ratio]);
return this;
};
};
c3_chart_internal_fn.getZoomDomain = function () {
var $$ = this, config = $$.config, d3 = $$.d3,
min = d3.min([$$.orgXDomain[0], config.zoom_x_min]),
max = d3.max([$$.orgXDomain[1], config.zoom_x_max]);
return [min, max];
};
c3_chart_internal_fn.updateZoom = function () {
var $$ = this, z = $$.config.zoom_enabled ? $$.zoom : function () {};
$$.main.select('.' + CLASS.zoomRect).call(z).on("dblclick.zoom", null);
$$.main.selectAll('.' + CLASS.eventRect).call(z).on("dblclick.zoom", null);
};
c3_chart_internal_fn.redrawForZoom = function () {
var $$ = this, d3 = $$.d3, config = $$.config, zoom = $$.zoom, x = $$.x;
if (!config.zoom_enabled) {
return;
}
if ($$.filterTargetsToShow($$.data.targets).length === 0) {
return;
}
if (d3.event.sourceEvent.type === 'mousemove' && zoom.altDomain) {
x.domain(zoom.altDomain);
zoom.scale(x).updateScaleExtent();
return;
}
if ($$.isCategorized() && x.orgDomain()[0] === $$.orgXDomain[0]) {
x.domain([$$.orgXDomain[0] - 1e-10, x.orgDomain()[1]]);
}
$$.redraw({
withTransition: false,
withY: config.zoom_rescale,
withSubchart: false,
withEventRect: false,
withDimension: false
});
if (d3.event.sourceEvent.type === 'mousemove') {
$$.cancelClick = true;
}
config.zoom_onzoom.call($$.api, x.orgDomain());
};
c3_chart_internal_fn.generateColor = function () {
var $$ = this, config = $$.config, d3 = $$.d3,
colors = config.data_colors,
pattern = notEmpty(config.color_pattern) ? config.color_pattern : d3.scale.category10().range(),
callback = config.data_color,
ids = [];
return function (d) {
var id = d.id || (d.data && d.data.id) || d, color;
// if callback function is provided
if (colors[id] instanceof Function) {
color = colors[id](d);
}
// if specified, choose that color
else if (colors[id]) {
color = colors[id];
}
// if not specified, choose from pattern
else {
if (ids.indexOf(id) < 0) { ids.push(id); }
color = pattern[ids.indexOf(id) % pattern.length];
colors[id] = color;
}
return callback instanceof Function ? callback(color, d) : color;
};
};
c3_chart_internal_fn.generateLevelColor = function () {
var $$ = this, config = $$.config,
colors = config.color_pattern,
threshold = config.color_threshold,
asValue = threshold.unit === 'value',
values = threshold.values && threshold.values.length ? threshold.values : [],
max = threshold.max || 100;
return notEmpty(config.color_threshold) ? function (value) {
var i, v, color = colors[colors.length - 1];
for (i = 0; i < values.length; i++) {
v = asValue ? value : (value * 100 / max);
if (v < values[i]) {
color = colors[i];
break;
}
}
return color;
} : null;
};
c3_chart_internal_fn.getYFormat = function (forArc) {
var $$ = this,
formatForY = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.yFormat,
formatForY2 = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.y2Format;
return function (v, ratio, id) {
var format = $$.axis.getId(id) === 'y2' ? formatForY2 : formatForY;
return format.call($$, v, ratio);
};
};
c3_chart_internal_fn.yFormat = function (v) {
var $$ = this, config = $$.config,
format = config.axis_y_tick_format ? config.axis_y_tick_format : $$.defaultValueFormat;
return format(v);
};
c3_chart_internal_fn.y2Format = function (v) {
var $$ = this, config = $$.config,
format = config.axis_y2_tick_format ? config.axis_y2_tick_format : $$.defaultValueFormat;
return format(v);
};
c3_chart_internal_fn.defaultValueFormat = function (v) {
return isValue(v) ? +v : "";
};
c3_chart_internal_fn.defaultArcValueFormat = function (v, ratio) {
return (ratio * 100).toFixed(1) + '%';
};
c3_chart_internal_fn.dataLabelFormat = function (targetId) {
var $$ = this, data_labels = $$.config.data_labels,
format, defaultFormat = function (v) { return isValue(v) ? +v : ""; };
// find format according to axis id
if (typeof data_labels.format === 'function') {
format = data_labels.format;
} else if (typeof data_labels.format === 'object') {
if (data_labels.format[targetId]) {
format = data_labels.format[targetId] === true ? defaultFormat : data_labels.format[targetId];
} else {
format = function () { return ''; };
}
} else {
format = defaultFormat;
}
return format;
};
c3_chart_internal_fn.hasCaches = function (ids) {
for (var i = 0; i < ids.length; i++) {
if (! (ids[i] in this.cache)) { return false; }
}
return true;
};
c3_chart_internal_fn.addCache = function (id, target) {
this.cache[id] = this.cloneTarget(target);
};
c3_chart_internal_fn.getCaches = function (ids) {
var targets = [], i;
for (i = 0; i < ids.length; i++) {
if (ids[i] in this.cache) { targets.push(this.cloneTarget(this.cache[ids[i]])); }
}
return targets;
};
var CLASS = c3_chart_internal_fn.CLASS = {
target: 'c3-target',
chart: 'c3-chart',
chartLine: 'c3-chart-line',
chartLines: 'c3-chart-lines',
chartBar: 'c3-chart-bar',
chartBars: 'c3-chart-bars',
chartText: 'c3-chart-text',
chartTexts: 'c3-chart-texts',
chartArc: 'c3-chart-arc',
chartArcs: 'c3-chart-arcs',
chartArcsTitle: 'c3-chart-arcs-title',
chartArcsBackground: 'c3-chart-arcs-background',
chartArcsGaugeUnit: 'c3-chart-arcs-gauge-unit',
chartArcsGaugeMax: 'c3-chart-arcs-gauge-max',
chartArcsGaugeMin: 'c3-chart-arcs-gauge-min',
selectedCircle: 'c3-selected-circle',
selectedCircles: 'c3-selected-circles',
eventRect: 'c3-event-rect',
eventRects: 'c3-event-rects',
eventRectsSingle: 'c3-event-rects-single',
eventRectsMultiple: 'c3-event-rects-multiple',
zoomRect: 'c3-zoom-rect',
brush: 'c3-brush',
focused: 'c3-focused',
defocused: 'c3-defocused',
region: 'c3-region',
regions: 'c3-regions',
title: 'c3-title',
tooltipContainer: 'c3-tooltip-container',
tooltip: 'c3-tooltip',
tooltipName: 'c3-tooltip-name',
shape: 'c3-shape',
shapes: 'c3-shapes',
line: 'c3-line',
lines: 'c3-lines',
bar: 'c3-bar',
bars: 'c3-bars',
circle: 'c3-circle',
circles: 'c3-circles',
arc: 'c3-arc',
arcs: 'c3-arcs',
area: 'c3-area',
areas: 'c3-areas',
empty: 'c3-empty',
text: 'c3-text',
texts: 'c3-texts',
gaugeValue: 'c3-gauge-value',
grid: 'c3-grid',
gridLines: 'c3-grid-lines',
xgrid: 'c3-xgrid',
xgrids: 'c3-xgrids',
xgridLine: 'c3-xgrid-line',
xgridLines: 'c3-xgrid-lines',
xgridFocus: 'c3-xgrid-focus',
ygrid: 'c3-ygrid',
ygrids: 'c3-ygrids',
ygridLine: 'c3-ygrid-line',
ygridLines: 'c3-ygrid-lines',
axis: 'c3-axis',
axisX: 'c3-axis-x',
axisXLabel: 'c3-axis-x-label',
axisY: 'c3-axis-y',
axisYLabel: 'c3-axis-y-label',
axisY2: 'c3-axis-y2',
axisY2Label: 'c3-axis-y2-label',
legendBackground: 'c3-legend-background',
legendItem: 'c3-legend-item',
legendItemEvent: 'c3-legend-item-event',
legendItemTile: 'c3-legend-item-tile',
legendItemHidden: 'c3-legend-item-hidden',
legendItemFocused: 'c3-legend-item-focused',
dragarea: 'c3-dragarea',
EXPANDED: '_expanded_',
SELECTED: '_selected_',
INCLUDED: '_included_'
};
c3_chart_internal_fn.generateClass = function (prefix, targetId) {
return " " + prefix + " " + prefix + this.getTargetSelectorSuffix(targetId);
};
c3_chart_internal_fn.classText = function (d) {
return this.generateClass(CLASS.text, d.index);
};
c3_chart_internal_fn.classTexts = function (d) {
return this.generateClass(CLASS.texts, d.id);
};
c3_chart_internal_fn.classShape = function (d) {
return this.generateClass(CLASS.shape, d.index);
};
c3_chart_internal_fn.classShapes = function (d) {
return this.generateClass(CLASS.shapes, d.id);
};
c3_chart_internal_fn.classLine = function (d) {
return this.classShape(d) + this.generateClass(CLASS.line, d.id);
};
c3_chart_internal_fn.classLines = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.lines, d.id);
};
c3_chart_internal_fn.classCircle = function (d) {
return this.classShape(d) + this.generateClass(CLASS.circle, d.index);
};
c3_chart_internal_fn.classCircles = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.circles, d.id);
};
c3_chart_internal_fn.classBar = function (d) {
return this.classShape(d) + this.generateClass(CLASS.bar, d.index);
};
c3_chart_internal_fn.classBars = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.bars, d.id);
};
c3_chart_internal_fn.classArc = function (d) {
return this.classShape(d.data) + this.generateClass(CLASS.arc, d.data.id);
};
c3_chart_internal_fn.classArcs = function (d) {
return this.classShapes(d.data) + this.generateClass(CLASS.arcs, d.data.id);
};
c3_chart_internal_fn.classArea = function (d) {
return this.classShape(d) + this.generateClass(CLASS.area, d.id);
};
c3_chart_internal_fn.classAreas = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.areas, d.id);
};
c3_chart_internal_fn.classRegion = function (d, i) {
return this.generateClass(CLASS.region, i) + ' ' + ('class' in d ? d['class'] : '');
};
c3_chart_internal_fn.classEvent = function (d) {
return this.generateClass(CLASS.eventRect, d.index);
};
c3_chart_internal_fn.classTarget = function (id) {
var $$ = this;
var additionalClassSuffix = $$.config.data_classes[id], additionalClass = '';
if (additionalClassSuffix) {
additionalClass = ' ' + CLASS.target + '-' + additionalClassSuffix;
}
return $$.generateClass(CLASS.target, id) + additionalClass;
};
c3_chart_internal_fn.classFocus = function (d) {
return this.classFocused(d) + this.classDefocused(d);
};
c3_chart_internal_fn.classFocused = function (d) {
return ' ' + (this.focusedTargetIds.indexOf(d.id) >= 0 ? CLASS.focused : '');
};
c3_chart_internal_fn.classDefocused = function (d) {
return ' ' + (this.defocusedTargetIds.indexOf(d.id) >= 0 ? CLASS.defocused : '');
};
c3_chart_internal_fn.classChartText = function (d) {
return CLASS.chartText + this.classTarget(d.id);
};
c3_chart_internal_fn.classChartLine = function (d) {
return CLASS.chartLine + this.classTarget(d.id);
};
c3_chart_internal_fn.classChartBar = function (d) {
return CLASS.chartBar + this.classTarget(d.id);
};
c3_chart_internal_fn.classChartArc = function (d) {
return CLASS.chartArc + this.classTarget(d.data.id);
};
c3_chart_internal_fn.getTargetSelectorSuffix = function (targetId) {
return targetId || targetId === 0 ? ('-' + targetId).replace(/[\s?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\]/g, '-') : '';
};
c3_chart_internal_fn.selectorTarget = function (id, prefix) {
return (prefix || '') + '.' + CLASS.target + this.getTargetSelectorSuffix(id);
};
c3_chart_internal_fn.selectorTargets = function (ids, prefix) {
var $$ = this;
ids = ids || [];
return ids.length ? ids.map(function (id) { return $$.selectorTarget(id, prefix); }) : null;
};
c3_chart_internal_fn.selectorLegend = function (id) {
return '.' + CLASS.legendItem + this.getTargetSelectorSuffix(id);
};
c3_chart_internal_fn.selectorLegends = function (ids) {
var $$ = this;
return ids && ids.length ? ids.map(function (id) { return $$.selectorLegend(id); }) : null;
};
var isValue = c3_chart_internal_fn.isValue = function (v) {
return v || v === 0;
},
isFunction = c3_chart_internal_fn.isFunction = function (o) {
return typeof o === 'function';
},
isString = c3_chart_internal_fn.isString = function (o) {
return typeof o === 'string';
},
isUndefined = c3_chart_internal_fn.isUndefined = function (v) {
return typeof v === 'undefined';
},
isDefined = c3_chart_internal_fn.isDefined = function (v) {
return typeof v !== 'undefined';
},
ceil10 = c3_chart_internal_fn.ceil10 = function (v) {
return Math.ceil(v / 10) * 10;
},
asHalfPixel = c3_chart_internal_fn.asHalfPixel = function (n) {
return Math.ceil(n) + 0.5;
},
diffDomain = c3_chart_internal_fn.diffDomain = function (d) {
return d[1] - d[0];
},
isEmpty = c3_chart_internal_fn.isEmpty = function (o) {
return typeof o === 'undefined' || o === null || (isString(o) && o.length === 0) || (typeof o === 'object' && Object.keys(o).length === 0);
},
notEmpty = c3_chart_internal_fn.notEmpty = function (o) {
return !c3_chart_internal_fn.isEmpty(o);
},
getOption = c3_chart_internal_fn.getOption = function (options, key, defaultValue) {
return isDefined(options[key]) ? options[key] : defaultValue;
},
hasValue = c3_chart_internal_fn.hasValue = function (dict, value) {
var found = false;
Object.keys(dict).forEach(function (key) {
if (dict[key] === value) { found = true; }
});
return found;
},
sanitise = c3_chart_internal_fn.sanitise = function (str) {
return typeof str === 'string' ? str.replace(/</g, '<').replace(/>/g, '>') : str;
},
getPathBox = c3_chart_internal_fn.getPathBox = function (path) {
var box = path.getBoundingClientRect(),
items = [path.pathSegList.getItem(0), path.pathSegList.getItem(1)],
minX = items[0].x, minY = Math.min(items[0].y, items[1].y);
return {x: minX, y: minY, width: box.width, height: box.height};
};
c3_chart_fn.focus = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),
this.revert();
this.defocus();
candidates.classed(CLASS.focused, true).classed(CLASS.defocused, false);
if ($$.hasArcType()) {
$$.expandArc(targetIds);
}
$$.toggleFocusLegend(targetIds, true);
$$.focusedTargetIds = targetIds;
$$.defocusedTargetIds = $$.defocusedTargetIds.filter(function (id) {
return targetIds.indexOf(id) < 0;
});
};
c3_chart_fn.defocus = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),
candidates.classed(CLASS.focused, false).classed(CLASS.defocused, true);
if ($$.hasArcType()) {
$$.unexpandArc(targetIds);
}
$$.toggleFocusLegend(targetIds, false);
$$.focusedTargetIds = $$.focusedTargetIds.filter(function (id) {
return targetIds.indexOf(id) < 0;
});
$$.defocusedTargetIds = targetIds;
};
c3_chart_fn.revert = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
candidates = $$.svg.selectAll($$.selectorTargets(targetIds)); // should be for all targets
candidates.classed(CLASS.focused, false).classed(CLASS.defocused, false);
if ($$.hasArcType()) {
$$.unexpandArc(targetIds);
}
if ($$.config.legend_show) {
$$.showLegend(targetIds.filter($$.isLegendToShow.bind($$)));
$$.legend.selectAll($$.selectorLegends(targetIds))
.filter(function () {
return $$.d3.select(this).classed(CLASS.legendItemFocused);
})
.classed(CLASS.legendItemFocused, false);
}
$$.focusedTargetIds = [];
$$.defocusedTargetIds = [];
};
c3_chart_fn.show = function (targetIds, options) {
var $$ = this.internal, targets;
targetIds = $$.mapToTargetIds(targetIds);
options = options || {};
$$.removeHiddenTargetIds(targetIds);
targets = $$.svg.selectAll($$.selectorTargets(targetIds));
targets.transition()
.style('opacity', 1, 'important')
.call($$.endall, function () {
targets.style('opacity', null).style('opacity', 1);
});
if (options.withLegend) {
$$.showLegend(targetIds);
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};
c3_chart_fn.hide = function (targetIds, options) {
var $$ = this.internal, targets;
targetIds = $$.mapToTargetIds(targetIds);
options = options || {};
$$.addHiddenTargetIds(targetIds);
targets = $$.svg.selectAll($$.selectorTargets(targetIds));
targets.transition()
.style('opacity', 0, 'important')
.call($$.endall, function () {
targets.style('opacity', null).style('opacity', 0);
});
if (options.withLegend) {
$$.hideLegend(targetIds);
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};
c3_chart_fn.toggle = function (targetIds, options) {
var that = this, $$ = this.internal;
$$.mapToTargetIds(targetIds).forEach(function (targetId) {
$$.isTargetToShow(targetId) ? that.hide(targetId, options) : that.show(targetId, options);
});
};
c3_chart_fn.zoom = function (domain) {
var $$ = this.internal;
if (domain) {
if ($$.isTimeSeries()) {
domain = domain.map(function (x) { return $$.parseDate(x); });
}
$$.brush.extent(domain);
$$.redraw({withUpdateXDomain: true, withY: $$.config.zoom_rescale});
$$.config.zoom_onzoom.call(this, $$.x.orgDomain());
}
return $$.brush.extent();
};
c3_chart_fn.zoom.enable = function (enabled) {
var $$ = this.internal;
$$.config.zoom_enabled = enabled;
$$.updateAndRedraw();
};
c3_chart_fn.unzoom = function () {
var $$ = this.internal;
$$.brush.clear().update();
$$.redraw({withUpdateXDomain: true});
};
c3_chart_fn.zoom.max = function (max) {
var $$ = this.internal, config = $$.config, d3 = $$.d3;
if (max === 0 || max) {
config.zoom_x_max = d3.max([$$.orgXDomain[1], max]);
}
else {
return config.zoom_x_max;
}
};
c3_chart_fn.zoom.min = function (min) {
var $$ = this.internal, config = $$.config, d3 = $$.d3;
if (min === 0 || min) {
config.zoom_x_min = d3.min([$$.orgXDomain[0], min]);
}
else {
return config.zoom_x_min;
}
};
c3_chart_fn.zoom.range = function (range) {
if (arguments.length) {
if (isDefined(range.max)) { this.domain.max(range.max); }
if (isDefined(range.min)) { this.domain.min(range.min); }
} else {
return {
max: this.domain.max(),
min: this.domain.min()
};
}
};
c3_chart_fn.load = function (args) {
var $$ = this.internal, config = $$.config;
// update xs if specified
if (args.xs) {
$$.addXs(args.xs);
}
// update names if exists
if ('names' in args) {
c3_chart_fn.data.names.bind(this)(args.names);
}
// update classes if exists
if ('classes' in args) {
Object.keys(args.classes).forEach(function (id) {
config.data_classes[id] = args.classes[id];
});
}
// update categories if exists
if ('categories' in args && $$.isCategorized()) {
config.axis_x_categories = args.categories;
}
// update axes if exists
if ('axes' in args) {
Object.keys(args.axes).forEach(function (id) {
config.data_axes[id] = args.axes[id];
});
}
// update colors if exists
if ('colors' in args) {
Object.keys(args.colors).forEach(function (id) {
config.data_colors[id] = args.colors[id];
});
}
// use cache if exists
if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) {
$$.load($$.getCaches(args.cacheIds), args.done);
return;
}
// unload if needed
if ('unload' in args) {
// TODO: do not unload if target will load (included in url/rows/columns)
$$.unload($$.mapToTargetIds((typeof args.unload === 'boolean' && args.unload) ? null : args.unload), function () {
$$.loadFromArgs(args);
});
} else {
$$.loadFromArgs(args);
}
};
c3_chart_fn.unload = function (args) {
var $$ = this.internal;
args = args || {};
if (args instanceof Array) {
args = {ids: args};
} else if (typeof args === 'string') {
args = {ids: [args]};
}
$$.unload($$.mapToTargetIds(args.ids), function () {
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
if (args.done) { args.done(); }
});
};
c3_chart_fn.flow = function (args) {
var $$ = this.internal,
targets, data, notfoundIds = [], orgDataCount = $$.getMaxDataCount(),
dataCount, domain, baseTarget, baseValue, length = 0, tail = 0, diff, to;
if (args.json) {
data = $$.convertJsonToData(args.json, args.keys);
}
else if (args.rows) {
data = $$.convertRowsToData(args.rows);
}
else if (args.columns) {
data = $$.convertColumnsToData(args.columns);
}
else {
return;
}
targets = $$.convertDataToTargets(data, true);
// Update/Add data
$$.data.targets.forEach(function (t) {
var found = false, i, j;
for (i = 0; i < targets.length; i++) {
if (t.id === targets[i].id) {
found = true;
if (t.values[t.values.length - 1]) {
tail = t.values[t.values.length - 1].index + 1;
}
length = targets[i].values.length;
for (j = 0; j < length; j++) {
targets[i].values[j].index = tail + j;
if (!$$.isTimeSeries()) {
targets[i].values[j].x = tail + j;
}
}
t.values = t.values.concat(targets[i].values);
targets.splice(i, 1);
break;
}
}
if (!found) { notfoundIds.push(t.id); }
});
// Append null for not found targets
$$.data.targets.forEach(function (t) {
var i, j;
for (i = 0; i < notfoundIds.length; i++) {
if (t.id === notfoundIds[i]) {
tail = t.values[t.values.length - 1].index + 1;
for (j = 0; j < length; j++) {
t.values.push({
id: t.id,
index: tail + j,
x: $$.isTimeSeries() ? $$.getOtherTargetX(tail + j) : tail + j,
value: null
});
}
}
}
});
// Generate null values for new target
if ($$.data.targets.length) {
targets.forEach(function (t) {
var i, missing = [];
for (i = $$.data.targets[0].values[0].index; i < tail; i++) {
missing.push({
id: t.id,
index: i,
x: $$.isTimeSeries() ? $$.getOtherTargetX(i) : i,
value: null
});
}
t.values.forEach(function (v) {
v.index += tail;
if (!$$.isTimeSeries()) {
v.x += tail;
}
});
t.values = missing.concat(t.values);
});
}
$$.data.targets = $$.data.targets.concat(targets); // add remained
// check data count because behavior needs to change when it's only one
dataCount = $$.getMaxDataCount();
baseTarget = $$.data.targets[0];
baseValue = baseTarget.values[0];
// Update length to flow if needed
if (isDefined(args.to)) {
length = 0;
to = $$.isTimeSeries() ? $$.parseDate(args.to) : args.to;
baseTarget.values.forEach(function (v) {
if (v.x < to) { length++; }
});
} else if (isDefined(args.length)) {
length = args.length;
}
// If only one data, update the domain to flow from left edge of the chart
if (!orgDataCount) {
if ($$.isTimeSeries()) {
if (baseTarget.values.length > 1) {
diff = baseTarget.values[baseTarget.values.length - 1].x - baseValue.x;
} else {
diff = baseValue.x - $$.getXDomain($$.data.targets)[0];
}
} else {
diff = 1;
}
domain = [baseValue.x - diff, baseValue.x];
$$.updateXDomain(null, true, true, false, domain);
} else if (orgDataCount === 1) {
if ($$.isTimeSeries()) {
diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2;
domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)];
$$.updateXDomain(null, true, true, false, domain);
}
}
// Set targets
$$.updateTargets($$.data.targets);
// Redraw with new targets
$$.redraw({
flow: {
index: baseValue.index,
length: length,
duration: isValue(args.duration) ? args.duration : $$.config.transition_duration,
done: args.done,
orgDataCount: orgDataCount,
},
withLegend: true,
withTransition: orgDataCount > 1,
withTrimXDomain: false,
withUpdateXAxis: true,
});
};
c3_chart_internal_fn.generateFlow = function (args) {
var $$ = this, config = $$.config, d3 = $$.d3;
return function () {
var targets = args.targets,
flow = args.flow,
drawBar = args.drawBar,
drawLine = args.drawLine,
drawArea = args.drawArea,
cx = args.cx,
cy = args.cy,
xv = args.xv,
xForText = args.xForText,
yForText = args.yForText,
duration = args.duration;
var translateX, scaleX = 1, transform,
flowIndex = flow.index,
flowLength = flow.length,
flowStart = $$.getValueOnIndex($$.data.targets[0].values, flowIndex),
flowEnd = $$.getValueOnIndex($$.data.targets[0].values, flowIndex + flowLength),
orgDomain = $$.x.domain(), domain,
durationForFlow = flow.duration || duration,
done = flow.done || function () {},
wait = $$.generateWait();
var xgrid = $$.xgrid || d3.selectAll([]),
xgridLines = $$.xgridLines || d3.selectAll([]),
mainRegion = $$.mainRegion || d3.selectAll([]),
mainText = $$.mainText || d3.selectAll([]),
mainBar = $$.mainBar || d3.selectAll([]),
mainLine = $$.mainLine || d3.selectAll([]),
mainArea = $$.mainArea || d3.selectAll([]),
mainCircle = $$.mainCircle || d3.selectAll([]);
// set flag
$$.flowing = true;
// remove head data after rendered
$$.data.targets.forEach(function (d) {
d.values.splice(0, flowLength);
});
// update x domain to generate axis elements for flow
domain = $$.updateXDomain(targets, true, true);
// update elements related to x scale
if ($$.updateXGrid) { $$.updateXGrid(true); }
// generate transform to flow
if (!flow.orgDataCount) { // if empty
if ($$.data.targets[0].values.length !== 1) {
translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
} else {
if ($$.isTimeSeries()) {
flowStart = $$.getValueOnIndex($$.data.targets[0].values, 0);
flowEnd = $$.getValueOnIndex($$.data.targets[0].values, $$.data.targets[0].values.length - 1);
translateX = $$.x(flowStart.x) - $$.x(flowEnd.x);
} else {
translateX = diffDomain(domain) / 2;
}
}
} else if (flow.orgDataCount === 1 || (flowStart && flowStart.x) === (flowEnd && flowEnd.x)) {
translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
} else {
if ($$.isTimeSeries()) {
translateX = ($$.x(orgDomain[0]) - $$.x(domain[0]));
} else {
translateX = ($$.x(flowStart.x) - $$.x(flowEnd.x));
}
}
scaleX = (diffDomain(orgDomain) / diffDomain(domain));
transform = 'translate(' + translateX + ',0) scale(' + scaleX + ',1)';
$$.hideXGridFocus();
d3.transition().ease('linear').duration(durationForFlow).each(function () {
wait.add($$.axes.x.transition().call($$.xAxis));
wait.add(mainBar.transition().attr('transform', transform));
wait.add(mainLine.transition().attr('transform', transform));
wait.add(mainArea.transition().attr('transform', transform));
wait.add(mainCircle.transition().attr('transform', transform));
wait.add(mainText.transition().attr('transform', transform));
wait.add(mainRegion.filter($$.isRegionOnX).transition().attr('transform', transform));
wait.add(xgrid.transition().attr('transform', transform));
wait.add(xgridLines.transition().attr('transform', transform));
})
.call(wait, function () {
var i, shapes = [], texts = [], eventRects = [];
// remove flowed elements
if (flowLength) {
for (i = 0; i < flowLength; i++) {
shapes.push('.' + CLASS.shape + '-' + (flowIndex + i));
texts.push('.' + CLASS.text + '-' + (flowIndex + i));
eventRects.push('.' + CLASS.eventRect + '-' + (flowIndex + i));
}
$$.svg.selectAll('.' + CLASS.shapes).selectAll(shapes).remove();
$$.svg.selectAll('.' + CLASS.texts).selectAll(texts).remove();
$$.svg.selectAll('.' + CLASS.eventRects).selectAll(eventRects).remove();
$$.svg.select('.' + CLASS.xgrid).remove();
}
// draw again for removing flowed elements and reverting attr
xgrid
.attr('transform', null)
.attr($$.xgridAttr);
xgridLines
.attr('transform', null);
xgridLines.select('line')
.attr("x1", config.axis_rotated ? 0 : xv)
.attr("x2", config.axis_rotated ? $$.width : xv);
xgridLines.select('text')
.attr("x", config.axis_rotated ? $$.width : 0)
.attr("y", xv);
mainBar
.attr('transform', null)
.attr("d", drawBar);
mainLine
.attr('transform', null)
.attr("d", drawLine);
mainArea
.attr('transform', null)
.attr("d", drawArea);
mainCircle
.attr('transform', null)
.attr("cx", cx)
.attr("cy", cy);
mainText
.attr('transform', null)
.attr('x', xForText)
.attr('y', yForText)
.style('fill-opacity', $$.opacityForText.bind($$));
mainRegion
.attr('transform', null);
mainRegion.select('rect').filter($$.isRegionOnX)
.attr("x", $$.regionX.bind($$))
.attr("width", $$.regionWidth.bind($$));
if (config.interaction_enabled) {
$$.redrawEventRect();
}
// callback for end of flow
done();
$$.flowing = false;
});
};
};
c3_chart_fn.selected = function (targetId) {
var $$ = this.internal, d3 = $$.d3;
return d3.merge(
$$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape)
.filter(function () { return d3.select(this).classed(CLASS.SELECTED); })
.map(function (d) { return d.map(function (d) { var data = d.__data__; return data.data ? data.data : data; }); })
);
};
c3_chart_fn.select = function (ids, indices, resetOther) {
var $$ = this.internal, d3 = $$.d3, config = $$.config;
if (! config.data_selection_enabled) { return; }
$$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
var shape = d3.select(this), id = d.data ? d.data.id : d.id,
toggle = $$.getToggle(this, d).bind($$),
isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
isTargetIndex = !indices || indices.indexOf(i) >= 0,
isSelected = shape.classed(CLASS.SELECTED);
// line/area selection not supported yet
if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
return;
}
if (isTargetId && isTargetIndex) {
if (config.data_selection_isselectable(d) && !isSelected) {
toggle(true, shape.classed(CLASS.SELECTED, true), d, i);
}
} else if (isDefined(resetOther) && resetOther) {
if (isSelected) {
toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
}
}
});
};
c3_chart_fn.unselect = function (ids, indices) {
var $$ = this.internal, d3 = $$.d3, config = $$.config;
if (! config.data_selection_enabled) { return; }
$$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
var shape = d3.select(this), id = d.data ? d.data.id : d.id,
toggle = $$.getToggle(this, d).bind($$),
isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
isTargetIndex = !indices || indices.indexOf(i) >= 0,
isSelected = shape.classed(CLASS.SELECTED);
// line/area selection not supported yet
if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
return;
}
if (isTargetId && isTargetIndex) {
if (config.data_selection_isselectable(d)) {
if (isSelected) {
toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
}
}
}
});
};
c3_chart_fn.transform = function (type, targetIds) {
var $$ = this.internal,
options = ['pie', 'donut'].indexOf(type) >= 0 ? {withTransform: true} : null;
$$.transformTo(targetIds, type, options);
};
c3_chart_internal_fn.transformTo = function (targetIds, type, optionsForRedraw) {
var $$ = this,
withTransitionForAxis = !$$.hasArcType(),
options = optionsForRedraw || {withTransitionForAxis: withTransitionForAxis};
options.withTransitionForTransform = false;
$$.transiting = false;
$$.setTargetType(targetIds, type);
$$.updateTargets($$.data.targets); // this is needed when transforming to arc
$$.updateAndRedraw(options);
};
c3_chart_fn.groups = function (groups) {
var $$ = this.internal, config = $$.config;
if (isUndefined(groups)) { return config.data_groups; }
config.data_groups = groups;
$$.redraw();
return config.data_groups;
};
c3_chart_fn.xgrids = function (grids) {
var $$ = this.internal, config = $$.config;
if (! grids) { return config.grid_x_lines; }
config.grid_x_lines = grids;
$$.redrawWithoutRescale();
return config.grid_x_lines;
};
c3_chart_fn.xgrids.add = function (grids) {
var $$ = this.internal;
return this.xgrids($$.config.grid_x_lines.concat(grids ? grids : []));
};
c3_chart_fn.xgrids.remove = function (params) { // TODO: multiple
var $$ = this.internal;
$$.removeGridLines(params, true);
};
c3_chart_fn.ygrids = function (grids) {
var $$ = this.internal, config = $$.config;
if (! grids) { return config.grid_y_lines; }
config.grid_y_lines = grids;
$$.redrawWithoutRescale();
return config.grid_y_lines;
};
c3_chart_fn.ygrids.add = function (grids) {
var $$ = this.internal;
return this.ygrids($$.config.grid_y_lines.concat(grids ? grids : []));
};
c3_chart_fn.ygrids.remove = function (params) { // TODO: multiple
var $$ = this.internal;
$$.removeGridLines(params, false);
};
c3_chart_fn.regions = function (regions) {
var $$ = this.internal, config = $$.config;
if (!regions) { return config.regions; }
config.regions = regions;
$$.redrawWithoutRescale();
return config.regions;
};
c3_chart_fn.regions.add = function (regions) {
var $$ = this.internal, config = $$.config;
if (!regions) { return config.regions; }
config.regions = config.regions.concat(regions);
$$.redrawWithoutRescale();
return config.regions;
};
c3_chart_fn.regions.remove = function (options) {
var $$ = this.internal, config = $$.config,
duration, classes, regions;
options = options || {};
duration = $$.getOption(options, "duration", config.transition_duration);
classes = $$.getOption(options, "classes", [CLASS.region]);
regions = $$.main.select('.' + CLASS.regions).selectAll(classes.map(function (c) { return '.' + c; }));
(duration ? regions.transition().duration(duration) : regions)
.style('opacity', 0)
.remove();
config.regions = config.regions.filter(function (region) {
var found = false;
if (!region['class']) {
return true;
}
region['class'].split(' ').forEach(function (c) {
if (classes.indexOf(c) >= 0) { found = true; }
});
return !found;
});
return config.regions;
};
c3_chart_fn.data = function (targetIds) {
var targets = this.internal.data.targets;
return typeof targetIds === 'undefined' ? targets : targets.filter(function (t) {
return [].concat(targetIds).indexOf(t.id) >= 0;
});
};
c3_chart_fn.data.shown = function (targetIds) {
return this.internal.filterTargetsToShow(this.data(targetIds));
};
c3_chart_fn.data.values = function (targetId) {
var targets, values = null;
if (targetId) {
targets = this.data(targetId);
values = targets[0] ? targets[0].values.map(function (d) { return d.value; }) : null;
}
return values;
};
c3_chart_fn.data.names = function (names) {
this.internal.clearLegendItemTextBoxCache();
return this.internal.updateDataAttributes('names', names);
};
c3_chart_fn.data.colors = function (colors) {
return this.internal.updateDataAttributes('colors', colors);
};
c3_chart_fn.data.axes = function (axes) {
return this.internal.updateDataAttributes('axes', axes);
};
c3_chart_fn.category = function (i, category) {
var $$ = this.internal, config = $$.config;
if (arguments.length > 1) {
config.axis_x_categories[i] = category;
$$.redraw();
}
return config.axis_x_categories[i];
};
c3_chart_fn.categories = function (categories) {
var $$ = this.internal, config = $$.config;
if (!arguments.length) { return config.axis_x_categories; }
config.axis_x_categories = categories;
$$.redraw();
return config.axis_x_categories;
};
// TODO: fix
c3_chart_fn.color = function (id) {
var $$ = this.internal;
return $$.color(id); // more patterns
};
c3_chart_fn.x = function (x) {
var $$ = this.internal;
if (arguments.length) {
$$.updateTargetX($$.data.targets, x);
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
}
return $$.data.xs;
};
c3_chart_fn.xs = function (xs) {
var $$ = this.internal;
if (arguments.length) {
$$.updateTargetXs($$.data.targets, xs);
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
}
return $$.data.xs;
};
c3_chart_fn.axis = function () {};
c3_chart_fn.axis.labels = function (labels) {
var $$ = this.internal;
if (arguments.length) {
Object.keys(labels).forEach(function (axisId) {
$$.axis.setLabelText(axisId, labels[axisId]);
});
$$.axis.updateLabels();
}
// TODO: return some values?
};
c3_chart_fn.axis.max = function (max) {
var $$ = this.internal, config = $$.config;
if (arguments.length) {
if (typeof max === 'object') {
if (isValue(max.x)) { config.axis_x_max = max.x; }
if (isValue(max.y)) { config.axis_y_max = max.y; }
if (isValue(max.y2)) { config.axis_y2_max = max.y2; }
} else {
config.axis_y_max = config.axis_y2_max = max;
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
} else {
return {
x: config.axis_x_max,
y: config.axis_y_max,
y2: config.axis_y2_max
};
}
};
c3_chart_fn.axis.min = function (min) {
var $$ = this.internal, config = $$.config;
if (arguments.length) {
if (typeof min === 'object') {
if (isValue(min.x)) { config.axis_x_min = min.x; }
if (isValue(min.y)) { config.axis_y_min = min.y; }
if (isValue(min.y2)) { config.axis_y2_min = min.y2; }
} else {
config.axis_y_min = config.axis_y2_min = min;
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
} else {
return {
x: config.axis_x_min,
y: config.axis_y_min,
y2: config.axis_y2_min
};
}
};
c3_chart_fn.axis.range = function (range) {
if (arguments.length) {
if (isDefined(range.max)) { this.axis.max(range.max); }
if (isDefined(range.min)) { this.axis.min(range.min); }
} else {
return {
max: this.axis.max(),
min: this.axis.min()
};
}
};
c3_chart_fn.legend = function () {};
c3_chart_fn.legend.show = function (targetIds) {
var $$ = this.internal;
$$.showLegend($$.mapToTargetIds(targetIds));
$$.updateAndRedraw({withLegend: true});
};
c3_chart_fn.legend.hide = function (targetIds) {
var $$ = this.internal;
$$.hideLegend($$.mapToTargetIds(targetIds));
$$.updateAndRedraw({withLegend: true});
};
c3_chart_fn.resize = function (size) {
var $$ = this.internal, config = $$.config;
config.size_width = size ? size.width : null;
config.size_height = size ? size.height : null;
this.flush();
};
c3_chart_fn.flush = function () {
var $$ = this.internal;
$$.updateAndRedraw({withLegend: true, withTransition: false, withTransitionForTransform: false});
};
c3_chart_fn.destroy = function () {
var $$ = this.internal;
window.clearInterval($$.intervalForObserveInserted);
if ($$.resizeTimeout !== undefined) {
window.clearTimeout($$.resizeTimeout);
}
if (window.detachEvent) {
window.detachEvent('onresize', $$.resizeFunction);
} else if (window.removeEventListener) {
window.removeEventListener('resize', $$.resizeFunction);
} else {
var wrapper = window.onresize;
// check if no one else removed our wrapper and remove our resizeFunction from it
if (wrapper && wrapper.add && wrapper.remove) {
wrapper.remove($$.resizeFunction);
}
}
$$.selectChart.classed('c3', false).html("");
// MEMO: this is needed because the reference of some elements will not be released, then memory leak will happen.
Object.keys($$).forEach(function (key) {
$$[key] = null;
});
return null;
};
c3_chart_fn.tooltip = function () {};
c3_chart_fn.tooltip.show = function (args) {
var $$ = this.internal, index, mouse;
// determine mouse position on the chart
if (args.mouse) {
mouse = args.mouse;
}
// determine focus data
if (args.data) {
if ($$.isMultipleX()) {
// if multiple xs, target point will be determined by mouse
mouse = [$$.x(args.data.x), $$.getYScale(args.data.id)(args.data.value)];
index = null;
} else {
// TODO: when tooltip_grouped = false
index = isValue(args.data.index) ? args.data.index : $$.getIndexByX(args.data.x);
}
}
else if (typeof args.x !== 'undefined') {
index = $$.getIndexByX(args.x);
}
else if (typeof args.index !== 'undefined') {
index = args.index;
}
// emulate mouse events to show
$$.dispatchEvent('mouseover', index, mouse);
$$.dispatchEvent('mousemove', index, mouse);
$$.config.tooltip_onshow.call($$, args.data);
};
c3_chart_fn.tooltip.hide = function () {
// TODO: get target data by checking the state of focus
this.internal.dispatchEvent('mouseout', 0);
this.internal.config.tooltip_onhide.call(this);
};
// Features:
// 1. category axis
// 2. ceil values of translate/x/y to int for half pixel antialiasing
// 3. multiline tick text
var tickTextCharSize;
function c3_axis(d3, params) {
var scale = d3.scale.linear(), orient = "bottom", innerTickSize = 6, outerTickSize, tickPadding = 3, tickValues = null, tickFormat, tickArguments;
var tickOffset = 0, tickCulling = true, tickCentered;
params = params || {};
outerTickSize = params.withOuterTick ? 6 : 0;
function axisX(selection, x) {
selection.attr("transform", function (d) {
return "translate(" + Math.ceil(x(d) + tickOffset) + ", 0)";
});
}
function axisY(selection, y) {
selection.attr("transform", function (d) {
return "translate(0," + Math.ceil(y(d)) + ")";
});
}
function scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
}
function generateTicks(scale) {
var i, domain, ticks = [];
if (scale.ticks) {
return scale.ticks.apply(scale, tickArguments);
}
domain = scale.domain();
for (i = Math.ceil(domain[0]); i < domain[1]; i++) {
ticks.push(i);
}
if (ticks.length > 0 && ticks[0] > 0) {
ticks.unshift(ticks[0] - (ticks[1] - ticks[0]));
}
return ticks;
}
function copyScale() {
var newScale = scale.copy(), domain;
if (params.isCategory) {
domain = scale.domain();
newScale.domain([domain[0], domain[1] - 1]);
}
return newScale;
}
function textFormatted(v) {
var formatted = tickFormat ? tickFormat(v) : v;
return typeof formatted !== 'undefined' ? formatted : '';
}
function getSizeFor1Char(tick) {
if (tickTextCharSize) {
return tickTextCharSize;
}
var size = {
h: 11.5,
w: 5.5
};
tick.select('text').text(textFormatted).each(function (d) {
var box = this.getBoundingClientRect(),
text = textFormatted(d),
h = box.height,
w = text ? (box.width / text.length) : undefined;
if (h && w) {
size.h = h;
size.w = w;
}
}).text('');
tickTextCharSize = size;
return size;
}
function transitionise(selection) {
return params.withoutTransition ? selection : d3.transition(selection);
}
function axis(g) {
g.each(function () {
var g = axis.g = d3.select(this);
var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = copyScale();
var ticks = tickValues ? tickValues : generateTicks(scale1),
tick = g.selectAll(".tick").data(ticks, scale1),
tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", 1e-6),
// MEMO: No exit transition. The reason is this transition affects max tick width calculation because old tick will be included in the ticks.
tickExit = tick.exit().remove(),
tickUpdate = transitionise(tick).style("opacity", 1),
tickTransform, tickX, tickY;
var range = scale.rangeExtent ? scale.rangeExtent() : scaleExtent(scale.range()),
path = g.selectAll(".domain").data([ 0 ]),
pathUpdate = (path.enter().append("path").attr("class", "domain"), transitionise(path));
tickEnter.append("line");
tickEnter.append("text");
var lineEnter = tickEnter.select("line"),
lineUpdate = tickUpdate.select("line"),
textEnter = tickEnter.select("text"),
textUpdate = tickUpdate.select("text");
if (params.isCategory) {
tickOffset = Math.ceil((scale1(1) - scale1(0)) / 2);
tickX = tickCentered ? 0 : tickOffset;
tickY = tickCentered ? tickOffset : 0;
} else {
tickOffset = tickX = 0;
}
var text, tspan, sizeFor1Char = getSizeFor1Char(g.select('.tick')), counts = [];
var tickLength = Math.max(innerTickSize, 0) + tickPadding,
isVertical = orient === 'left' || orient === 'right';
// this should be called only when category axis
function splitTickText(d, maxWidth) {
var tickText = textFormatted(d),
subtext, spaceIndex, textWidth, splitted = [];
if (Object.prototype.toString.call(tickText) === "[object Array]") {
return tickText;
}
if (!maxWidth || maxWidth <= 0) {
maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110;
}
function split(splitted, text) {
spaceIndex = undefined;
for (var i = 1; i < text.length; i++) {
if (text.charAt(i) === ' ') {
spaceIndex = i;
}
subtext = text.substr(0, i + 1);
textWidth = sizeFor1Char.w * subtext.length;
// if text width gets over tick width, split by space index or crrent index
if (maxWidth < textWidth) {
return split(
splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)),
text.slice(spaceIndex ? spaceIndex + 1 : i)
);
}
}
return splitted.concat(text);
}
return split(splitted, tickText + "");
}
function tspanDy(d, i) {
var dy = sizeFor1Char.h;
if (i === 0) {
if (orient === 'left' || orient === 'right') {
dy = -((counts[d.index] - 1) * (sizeFor1Char.h / 2) - 3);
} else {
dy = ".71em";
}
}
return dy;
}
function tickSize(d) {
var tickPosition = scale(d) + (tickCentered ? 0 : tickOffset);
return range[0] < tickPosition && tickPosition < range[1] ? innerTickSize : 0;
}
text = tick.select("text");
tspan = text.selectAll('tspan')
.data(function (d, i) {
var splitted = params.tickMultiline ? splitTickText(d, params.tickWidth) : [].concat(textFormatted(d));
counts[i] = splitted.length;
return splitted.map(function (s) {
return { index: i, splitted: s };
});
});
tspan.enter().append('tspan');
tspan.exit().remove();
tspan.text(function (d) { return d.splitted; });
var rotate = params.tickTextRotate;
function textAnchorForText(rotate) {
if (!rotate) {
return 'middle';
}
return rotate > 0 ? "start" : "end";
}
function textTransform(rotate) {
if (!rotate) {
return '';
}
return "rotate(" + rotate + ")";
}
function dxForText(rotate) {
if (!rotate) {
return 0;
}
return 8 * Math.sin(Math.PI * (rotate / 180));
}
function yForText(rotate) {
if (!rotate) {
return tickLength;
}
return 11.5 - 2.5 * (rotate / 15) * (rotate > 0 ? 1 : -1);
}
switch (orient) {
case "bottom":
{
tickTransform = axisX;
lineEnter.attr("y2", innerTickSize);
textEnter.attr("y", tickLength);
lineUpdate.attr("x1", tickX).attr("x2", tickX).attr("y2", tickSize);
textUpdate.attr("x", 0).attr("y", yForText(rotate))
.style("text-anchor", textAnchorForText(rotate))
.attr("transform", textTransform(rotate));
tspan.attr('x', 0).attr("dy", tspanDy).attr('dx', dxForText(rotate));
pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize);
break;
}
case "top":
{
// TODO: rotated tick text
tickTransform = axisX;
lineEnter.attr("y2", -innerTickSize);
textEnter.attr("y", -tickLength);
lineUpdate.attr("x2", 0).attr("y2", -innerTickSize);
textUpdate.attr("x", 0).attr("y", -tickLength);
text.style("text-anchor", "middle");
tspan.attr('x', 0).attr("dy", "0em");
pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize);
break;
}
case "left":
{
tickTransform = axisY;
lineEnter.attr("x2", -innerTickSize);
textEnter.attr("x", -tickLength);
lineUpdate.attr("x2", -innerTickSize).attr("y1", tickY).attr("y2", tickY);
textUpdate.attr("x", -tickLength).attr("y", tickOffset);
text.style("text-anchor", "end");
tspan.attr('x', -tickLength).attr("dy", tspanDy);
pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize);
break;
}
case "right":
{
tickTransform = axisY;
lineEnter.attr("x2", innerTickSize);
textEnter.attr("x", tickLength);
lineUpdate.attr("x2", innerTickSize).attr("y2", 0);
textUpdate.attr("x", tickLength).attr("y", 0);
text.style("text-anchor", "start");
tspan.attr('x', tickLength).attr("dy", tspanDy);
pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize);
break;
}
}
if (scale1.rangeBand) {
var x = scale1, dx = x.rangeBand() / 2;
scale0 = scale1 = function (d) {
return x(d) + dx;
};
} else if (scale0.rangeBand) {
scale0 = scale1;
} else {
tickExit.call(tickTransform, scale1);
}
tickEnter.call(tickTransform, scale0);
tickUpdate.call(tickTransform, scale1);
});
}
axis.scale = function (x) {
if (!arguments.length) { return scale; }
scale = x;
return axis;
};
axis.orient = function (x) {
if (!arguments.length) { return orient; }
orient = x in {top: 1, right: 1, bottom: 1, left: 1} ? x + "" : "bottom";
return axis;
};
axis.tickFormat = function (format) {
if (!arguments.length) { return tickFormat; }
tickFormat = format;
return axis;
};
axis.tickCentered = function (isCentered) {
if (!arguments.length) { return tickCentered; }
tickCentered = isCentered;
return axis;
};
axis.tickOffset = function () {
return tickOffset;
};
axis.tickInterval = function () {
var interval, length;
if (params.isCategory) {
interval = tickOffset * 2;
}
else {
length = axis.g.select('path.domain').node().getTotalLength() - outerTickSize * 2;
interval = length / axis.g.selectAll('line').size();
}
return interval === Infinity ? 0 : interval;
};
axis.ticks = function () {
if (!arguments.length) { return tickArguments; }
tickArguments = arguments;
return axis;
};
axis.tickCulling = function (culling) {
if (!arguments.length) { return tickCulling; }
tickCulling = culling;
return axis;
};
axis.tickValues = function (x) {
if (typeof x === 'function') {
tickValues = function () {
return x(scale.domain());
};
}
else {
if (!arguments.length) { return tickValues; }
tickValues = x;
}
return axis;
};
return axis;
}
c3_chart_internal_fn.isSafari = function () {
var ua = window.navigator.userAgent;
return ua.indexOf('Safari') >= 0 && ua.indexOf('Chrome') < 0;
};
c3_chart_internal_fn.isChrome = function () {
var ua = window.navigator.userAgent;
return ua.indexOf('Chrome') >= 0;
};
/* jshint ignore:start */
// PhantomJS doesn't have support for Function.prototype.bind, which has caused confusion. Use
// this polyfill to avoid the confusion.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
//SVGPathSeg API polyfill
//https://github.com/progers/pathseg
//
//This is a drop-in replacement for the SVGPathSeg and SVGPathSegList APIs that were removed from
//SVG2 (https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html), including the latest spec
//changes which were implemented in Firefox 43 and Chrome 46.
//Chrome 48 removes these APIs, so this polyfill is required.
(function() { "use strict";
if (!("SVGPathSeg" in window)) {
// Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg
window.SVGPathSeg = function(type, typeAsLetter, owningPathSegList) {
this.pathSegType = type;
this.pathSegTypeAsLetter = typeAsLetter;
this._owningPathSegList = owningPathSegList;
}
SVGPathSeg.PATHSEG_UNKNOWN = 0;
SVGPathSeg.PATHSEG_CLOSEPATH = 1;
SVGPathSeg.PATHSEG_MOVETO_ABS = 2;
SVGPathSeg.PATHSEG_MOVETO_REL = 3;
SVGPathSeg.PATHSEG_LINETO_ABS = 4;
SVGPathSeg.PATHSEG_LINETO_REL = 5;
SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6;
SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7;
SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8;
SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9;
SVGPathSeg.PATHSEG_ARC_ABS = 10;
SVGPathSeg.PATHSEG_ARC_REL = 11;
SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12;
SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13;
SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14;
SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15;
SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16;
SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17;
SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18;
SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19;
// Notify owning PathSegList on any changes so they can be synchronized back to the path element.
SVGPathSeg.prototype._segmentChanged = function() {
if (this._owningPathSegList)
this._owningPathSegList.segmentChanged(this);
}
window.SVGPathSegClosePath = function(owningPathSegList) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CLOSEPATH, "z", owningPathSegList);
}
SVGPathSegClosePath.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegClosePath.prototype.toString = function() { return "[object SVGPathSegClosePath]"; }
SVGPathSegClosePath.prototype._asPathString = function() { return this.pathSegTypeAsLetter; }
SVGPathSegClosePath.prototype.clone = function() { return new SVGPathSegClosePath(undefined); }
window.SVGPathSegMovetoAbs = function(owningPathSegList, x, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_MOVETO_ABS, "M", owningPathSegList);
this._x = x;
this._y = y;
}
SVGPathSegMovetoAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegMovetoAbs.prototype.toString = function() { return "[object SVGPathSegMovetoAbs]"; }
SVGPathSegMovetoAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; }
SVGPathSegMovetoAbs.prototype.clone = function() { return new SVGPathSegMovetoAbs(undefined, this._x, this._y); }
Object.defineProperty(SVGPathSegMovetoAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegMovetoAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegMovetoRel = function(owningPathSegList, x, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_MOVETO_REL, "m", owningPathSegList);
this._x = x;
this._y = y;
}
SVGPathSegMovetoRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegMovetoRel.prototype.toString = function() { return "[object SVGPathSegMovetoRel]"; }
SVGPathSegMovetoRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; }
SVGPathSegMovetoRel.prototype.clone = function() { return new SVGPathSegMovetoRel(undefined, this._x, this._y); }
Object.defineProperty(SVGPathSegMovetoRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegMovetoRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegLinetoAbs = function(owningPathSegList, x, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_ABS, "L", owningPathSegList);
this._x = x;
this._y = y;
}
SVGPathSegLinetoAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegLinetoAbs.prototype.toString = function() { return "[object SVGPathSegLinetoAbs]"; }
SVGPathSegLinetoAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; }
SVGPathSegLinetoAbs.prototype.clone = function() { return new SVGPathSegLinetoAbs(undefined, this._x, this._y); }
Object.defineProperty(SVGPathSegLinetoAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegLinetoAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegLinetoRel = function(owningPathSegList, x, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_REL, "l", owningPathSegList);
this._x = x;
this._y = y;
}
SVGPathSegLinetoRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegLinetoRel.prototype.toString = function() { return "[object SVGPathSegLinetoRel]"; }
SVGPathSegLinetoRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; }
SVGPathSegLinetoRel.prototype.clone = function() { return new SVGPathSegLinetoRel(undefined, this._x, this._y); }
Object.defineProperty(SVGPathSegLinetoRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegLinetoRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoCubicAbs = function(owningPathSegList, x, y, x1, y1, x2, y2) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, "C", owningPathSegList);
this._x = x;
this._y = y;
this._x1 = x1;
this._y1 = y1;
this._x2 = x2;
this._y2 = y2;
}
SVGPathSegCurvetoCubicAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoCubicAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicAbs]"; }
SVGPathSegCurvetoCubicAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; }
SVGPathSegCurvetoCubicAbs.prototype.clone = function() { return new SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); }
Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoCubicRel = function(owningPathSegList, x, y, x1, y1, x2, y2) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, "c", owningPathSegList);
this._x = x;
this._y = y;
this._x1 = x1;
this._y1 = y1;
this._x2 = x2;
this._y2 = y2;
}
SVGPathSegCurvetoCubicRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoCubicRel.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicRel]"; }
SVGPathSegCurvetoCubicRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; }
SVGPathSegCurvetoCubicRel.prototype.clone = function() { return new SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); }
Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoQuadraticAbs = function(owningPathSegList, x, y, x1, y1) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, "Q", owningPathSegList);
this._x = x;
this._y = y;
this._x1 = x1;
this._y1 = y1;
}
SVGPathSegCurvetoQuadraticAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoQuadraticAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticAbs]"; }
SVGPathSegCurvetoQuadraticAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y; }
SVGPathSegCurvetoQuadraticAbs.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1); }
Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoQuadraticRel = function(owningPathSegList, x, y, x1, y1) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, "q", owningPathSegList);
this._x = x;
this._y = y;
this._x1 = x1;
this._y1 = y1;
}
SVGPathSegCurvetoQuadraticRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoQuadraticRel.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticRel]"; }
SVGPathSegCurvetoQuadraticRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y; }
SVGPathSegCurvetoQuadraticRel.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1); }
Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegArcAbs = function(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_ARC_ABS, "A", owningPathSegList);
this._x = x;
this._y = y;
this._r1 = r1;
this._r2 = r2;
this._angle = angle;
this._largeArcFlag = largeArcFlag;
this._sweepFlag = sweepFlag;
}
SVGPathSegArcAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegArcAbs.prototype.toString = function() { return "[object SVGPathSegArcAbs]"; }
SVGPathSegArcAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " + this._x + " " + this._y; }
SVGPathSegArcAbs.prototype.clone = function() { return new SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); }
Object.defineProperty(SVGPathSegArcAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcAbs.prototype, "r1", { get: function() { return this._r1; }, set: function(r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcAbs.prototype, "r2", { get: function() { return this._r2; }, set: function(r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcAbs.prototype, "angle", { get: function() { return this._angle; }, set: function(angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcAbs.prototype, "largeArcFlag", { get: function() { return this._largeArcFlag; }, set: function(largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcAbs.prototype, "sweepFlag", { get: function() { return this._sweepFlag; }, set: function(sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegArcRel = function(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_ARC_REL, "a", owningPathSegList);
this._x = x;
this._y = y;
this._r1 = r1;
this._r2 = r2;
this._angle = angle;
this._largeArcFlag = largeArcFlag;
this._sweepFlag = sweepFlag;
}
SVGPathSegArcRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegArcRel.prototype.toString = function() { return "[object SVGPathSegArcRel]"; }
SVGPathSegArcRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " + this._x + " " + this._y; }
SVGPathSegArcRel.prototype.clone = function() { return new SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); }
Object.defineProperty(SVGPathSegArcRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcRel.prototype, "r1", { get: function() { return this._r1; }, set: function(r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcRel.prototype, "r2", { get: function() { return this._r2; }, set: function(r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcRel.prototype, "angle", { get: function() { return this._angle; }, set: function(angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcRel.prototype, "largeArcFlag", { get: function() { return this._largeArcFlag; }, set: function(largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegArcRel.prototype, "sweepFlag", { get: function() { return this._sweepFlag; }, set: function(sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegLinetoHorizontalAbs = function(owningPathSegList, x) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, "H", owningPathSegList);
this._x = x;
}
SVGPathSegLinetoHorizontalAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegLinetoHorizontalAbs.prototype.toString = function() { return "[object SVGPathSegLinetoHorizontalAbs]"; }
SVGPathSegLinetoHorizontalAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x; }
SVGPathSegLinetoHorizontalAbs.prototype.clone = function() { return new SVGPathSegLinetoHorizontalAbs(undefined, this._x); }
Object.defineProperty(SVGPathSegLinetoHorizontalAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegLinetoHorizontalRel = function(owningPathSegList, x) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, "h", owningPathSegList);
this._x = x;
}
SVGPathSegLinetoHorizontalRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegLinetoHorizontalRel.prototype.toString = function() { return "[object SVGPathSegLinetoHorizontalRel]"; }
SVGPathSegLinetoHorizontalRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x; }
SVGPathSegLinetoHorizontalRel.prototype.clone = function() { return new SVGPathSegLinetoHorizontalRel(undefined, this._x); }
Object.defineProperty(SVGPathSegLinetoHorizontalRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegLinetoVerticalAbs = function(owningPathSegList, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, "V", owningPathSegList);
this._y = y;
}
SVGPathSegLinetoVerticalAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegLinetoVerticalAbs.prototype.toString = function() { return "[object SVGPathSegLinetoVerticalAbs]"; }
SVGPathSegLinetoVerticalAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._y; }
SVGPathSegLinetoVerticalAbs.prototype.clone = function() { return new SVGPathSegLinetoVerticalAbs(undefined, this._y); }
Object.defineProperty(SVGPathSegLinetoVerticalAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegLinetoVerticalRel = function(owningPathSegList, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, "v", owningPathSegList);
this._y = y;
}
SVGPathSegLinetoVerticalRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegLinetoVerticalRel.prototype.toString = function() { return "[object SVGPathSegLinetoVerticalRel]"; }
SVGPathSegLinetoVerticalRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._y; }
SVGPathSegLinetoVerticalRel.prototype.clone = function() { return new SVGPathSegLinetoVerticalRel(undefined, this._y); }
Object.defineProperty(SVGPathSegLinetoVerticalRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoCubicSmoothAbs = function(owningPathSegList, x, y, x2, y2) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, "S", owningPathSegList);
this._x = x;
this._y = y;
this._x2 = x2;
this._y2 = y2;
}
SVGPathSegCurvetoCubicSmoothAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoCubicSmoothAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicSmoothAbs]"; }
SVGPathSegCurvetoCubicSmoothAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; }
SVGPathSegCurvetoCubicSmoothAbs.prototype.clone = function() { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2); }
Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoCubicSmoothRel = function(owningPathSegList, x, y, x2, y2) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, "s", owningPathSegList);
this._x = x;
this._y = y;
this._x2 = x2;
this._y2 = y2;
}
SVGPathSegCurvetoCubicSmoothRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoCubicSmoothRel.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicSmoothRel]"; }
SVGPathSegCurvetoCubicSmoothRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; }
SVGPathSegCurvetoCubicSmoothRel.prototype.clone = function() { return new SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2); }
Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoQuadraticSmoothAbs = function(owningPathSegList, x, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, "T", owningPathSegList);
this._x = x;
this._y = y;
}
SVGPathSegCurvetoQuadraticSmoothAbs.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoQuadraticSmoothAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticSmoothAbs]"; }
SVGPathSegCurvetoQuadraticSmoothAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; }
SVGPathSegCurvetoQuadraticSmoothAbs.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y); }
Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
window.SVGPathSegCurvetoQuadraticSmoothRel = function(owningPathSegList, x, y) {
SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, "t", owningPathSegList);
this._x = x;
this._y = y;
}
SVGPathSegCurvetoQuadraticSmoothRel.prototype = Object.create(SVGPathSeg.prototype);
SVGPathSegCurvetoQuadraticSmoothRel.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticSmoothRel]"; }
SVGPathSegCurvetoQuadraticSmoothRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; }
SVGPathSegCurvetoQuadraticSmoothRel.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y); }
Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true });
Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true });
// Add createSVGPathSeg* functions to SVGPathElement.
// Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathElement.
SVGPathElement.prototype.createSVGPathSegClosePath = function() { return new SVGPathSegClosePath(undefined); }
SVGPathElement.prototype.createSVGPathSegMovetoAbs = function(x, y) { return new SVGPathSegMovetoAbs(undefined, x, y); }
SVGPathElement.prototype.createSVGPathSegMovetoRel = function(x, y) { return new SVGPathSegMovetoRel(undefined, x, y); }
SVGPathElement.prototype.createSVGPathSegLinetoAbs = function(x, y) { return new SVGPathSegLinetoAbs(undefined, x, y); }
SVGPathElement.prototype.createSVGPathSegLinetoRel = function(x, y) { return new SVGPathSegLinetoRel(undefined, x, y); }
SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function(x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2); }
SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function(x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2); }
SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function(x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1); }
SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function(x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1); }
SVGPathElement.prototype.createSVGPathSegArcAbs = function(x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); }
SVGPathElement.prototype.createSVGPathSegArcRel = function(x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); }
SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function(x) { return new SVGPathSegLinetoHorizontalAbs(undefined, x); }
SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function(x) { return new SVGPathSegLinetoHorizontalRel(undefined, x); }
SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function(y) { return new SVGPathSegLinetoVerticalAbs(undefined, y); }
SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function(y) { return new SVGPathSegLinetoVerticalRel(undefined, y); }
SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function(x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2); }
SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function(x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2); }
SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function(x, y) { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y); }
SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function(x, y) { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y); }
}
if (!("SVGPathSegList" in window)) {
// Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList
window.SVGPathSegList = function(pathElement) {
this._pathElement = pathElement;
this._list = this._parsePath(this._pathElement.getAttribute("d"));
// Use a MutationObserver to catch changes to the path's "d" attribute.
this._mutationObserverConfig = { "attributes": true, "attributeFilter": ["d"] };
this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this));
this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);
}
Object.defineProperty(SVGPathSegList.prototype, "numberOfItems", {
get: function() {
this._checkPathSynchronizedToList();
return this._list.length;
},
enumerable: true
});
// Add the pathSegList accessors to SVGPathElement.
// Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData
Object.defineProperty(SVGPathElement.prototype, "pathSegList", {
get: function() {
if (!this._pathSegList)
this._pathSegList = new SVGPathSegList(this);
return this._pathSegList;
},
enumerable: true
});
// FIXME: The following are not implemented and simply return SVGPathElement.pathSegList.
Object.defineProperty(SVGPathElement.prototype, "normalizedPathSegList", { get: function() { return this.pathSegList; }, enumerable: true });
Object.defineProperty(SVGPathElement.prototype, "animatedPathSegList", { get: function() { return this.pathSegList; }, enumerable: true });
Object.defineProperty(SVGPathElement.prototype, "animatedNormalizedPathSegList", { get: function() { return this.pathSegList; }, enumerable: true });
// Process any pending mutations to the path element and update the list as needed.
// This should be the first call of all public functions and is needed because
// MutationObservers are not synchronous so we can have pending asynchronous mutations.
SVGPathSegList.prototype._checkPathSynchronizedToList = function() {
this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords());
}
SVGPathSegList.prototype._updateListFromPathMutations = function(mutationRecords) {
if (!this._pathElement)
return;
var hasPathMutations = false;
mutationRecords.forEach(function(record) {
if (record.attributeName == "d")
hasPathMutations = true;
});
if (hasPathMutations)
this._list = this._parsePath(this._pathElement.getAttribute("d"));
}
// Serialize the list and update the path's 'd' attribute.
SVGPathSegList.prototype._writeListToPath = function() {
this._pathElementMutationObserver.disconnect();
this._pathElement.setAttribute("d", SVGPathSegList._pathSegArrayAsString(this._list));
this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);
}
// When a path segment changes the list needs to be synchronized back to the path element.
SVGPathSegList.prototype.segmentChanged = function(pathSeg) {
this._writeListToPath();
}
SVGPathSegList.prototype.clear = function() {
this._checkPathSynchronizedToList();
this._list.forEach(function(pathSeg) {
pathSeg._owningPathSegList = null;
});
this._list = [];
this._writeListToPath();
}
SVGPathSegList.prototype.initialize = function(newItem) {
this._checkPathSynchronizedToList();
this._list = [newItem];
newItem._owningPathSegList = this;
this._writeListToPath();
return newItem;
}
SVGPathSegList.prototype._checkValidIndex = function(index) {
if (isNaN(index) || index < 0 || index >= this.numberOfItems)
throw "INDEX_SIZE_ERR";
}
SVGPathSegList.prototype.getItem = function(index) {
this._checkPathSynchronizedToList();
this._checkValidIndex(index);
return this._list[index];
}
SVGPathSegList.prototype.insertItemBefore = function(newItem, index) {
this._checkPathSynchronizedToList();
// Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.
if (index > this.numberOfItems)
index = this.numberOfItems;
if (newItem._owningPathSegList) {
// SVG2 spec says to make a copy.
newItem = newItem.clone();
}
this._list.splice(index, 0, newItem);
newItem._owningPathSegList = this;
this._writeListToPath();
return newItem;
}
SVGPathSegList.prototype.replaceItem = function(newItem, index) {
this._checkPathSynchronizedToList();
if (newItem._owningPathSegList) {
// SVG2 spec says to make a copy.
newItem = newItem.clone();
}
this._checkValidIndex(index);
this._list[index] = newItem;
newItem._owningPathSegList = this;
this._writeListToPath();
return newItem;
}
SVGPathSegList.prototype.removeItem = function(index) {
this._checkPathSynchronizedToList();
this._checkValidIndex(index);
var item = this._list[index];
this._list.splice(index, 1);
this._writeListToPath();
return item;
}
SVGPathSegList.prototype.appendItem = function(newItem) {
this._checkPathSynchronizedToList();
if (newItem._owningPathSegList) {
// SVG2 spec says to make a copy.
newItem = newItem.clone();
}
this._list.push(newItem);
newItem._owningPathSegList = this;
// TODO: Optimize this to just append to the existing attribute.
this._writeListToPath();
return newItem;
}
SVGPathSegList._pathSegArrayAsString = function(pathSegArray) {
var string = "";
var first = true;
pathSegArray.forEach(function(pathSeg) {
if (first) {
first = false;
string += pathSeg._asPathString();
} else {
string += " " + pathSeg._asPathString();
}
});
return string;
}
// This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp.
SVGPathSegList.prototype._parsePath = function(string) {
if (!string || string.length == 0)
return [];
var owningPathSegList = this;
var Builder = function() {
this.pathSegList = [];
}
Builder.prototype.appendSegment = function(pathSeg) {
this.pathSegList.push(pathSeg);
}
var Source = function(string) {
this._string = string;
this._currentIndex = 0;
this._endIndex = this._string.length;
this._previousCommand = SVGPathSeg.PATHSEG_UNKNOWN;
this._skipOptionalSpaces();
}
Source.prototype._isCurrentSpace = function() {
var character = this._string[this._currentIndex];
return character <= " " && (character == " " || character == "\n" || character == "\t" || character == "\r" || character == "\f");
}
Source.prototype._skipOptionalSpaces = function() {
while (this._currentIndex < this._endIndex && this._isCurrentSpace())
this._currentIndex++;
return this._currentIndex < this._endIndex;
}
Source.prototype._skipOptionalSpacesOrDelimiter = function() {
if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) != ",")
return false;
if (this._skipOptionalSpaces()) {
if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ",") {
this._currentIndex++;
this._skipOptionalSpaces();
}
}
return this._currentIndex < this._endIndex;
}
Source.prototype.hasMoreData = function() {
return this._currentIndex < this._endIndex;
}
Source.prototype.peekSegmentType = function() {
var lookahead = this._string[this._currentIndex];
return this._pathSegTypeFromChar(lookahead);
}
Source.prototype._pathSegTypeFromChar = function(lookahead) {
switch (lookahead) {
case "Z":
case "z":
return SVGPathSeg.PATHSEG_CLOSEPATH;
case "M":
return SVGPathSeg.PATHSEG_MOVETO_ABS;
case "m":
return SVGPathSeg.PATHSEG_MOVETO_REL;
case "L":
return SVGPathSeg.PATHSEG_LINETO_ABS;
case "l":
return SVGPathSeg.PATHSEG_LINETO_REL;
case "C":
return SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS;
case "c":
return SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL;
case "Q":
return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS;
case "q":
return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL;
case "A":
return SVGPathSeg.PATHSEG_ARC_ABS;
case "a":
return SVGPathSeg.PATHSEG_ARC_REL;
case "H":
return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS;
case "h":
return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL;
case "V":
return SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS;
case "v":
return SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL;
case "S":
return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS;
case "s":
return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL;
case "T":
return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS;
case "t":
return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL;
default:
return SVGPathSeg.PATHSEG_UNKNOWN;
}
}
Source.prototype._nextCommandHelper = function(lookahead, previousCommand) {
// Check for remaining coordinates in the current command.
if ((lookahead == "+" || lookahead == "-" || lookahead == "." || (lookahead >= "0" && lookahead <= "9")) && previousCommand != SVGPathSeg.PATHSEG_CLOSEPATH) {
if (previousCommand == SVGPathSeg.PATHSEG_MOVETO_ABS)
return SVGPathSeg.PATHSEG_LINETO_ABS;
if (previousCommand == SVGPathSeg.PATHSEG_MOVETO_REL)
return SVGPathSeg.PATHSEG_LINETO_REL;
return previousCommand;
}
return SVGPathSeg.PATHSEG_UNKNOWN;
}
Source.prototype.initialCommandIsMoveTo = function() {
// If the path is empty it is still valid, so return true.
if (!this.hasMoreData())
return true;
var command = this.peekSegmentType();
// Path must start with moveTo.
return command == SVGPathSeg.PATHSEG_MOVETO_ABS || command == SVGPathSeg.PATHSEG_MOVETO_REL;
}
// Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp.
// Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF
Source.prototype._parseNumber = function() {
var exponent = 0;
var integer = 0;
var frac = 1;
var decimal = 0;
var sign = 1;
var expsign = 1;
var startIndex = this._currentIndex;
this._skipOptionalSpaces();
// Read the sign.
if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "+")
this._currentIndex++;
else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "-") {
this._currentIndex++;
sign = -1;
}
if (this._currentIndex == this._endIndex || ((this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") && this._string.charAt(this._currentIndex) != "."))
// The first character of a number must be one of [0-9+-.].
return undefined;
// Read the integer part, build right-to-left.
var startIntPartIndex = this._currentIndex;
while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9")
this._currentIndex++; // Advance to first non-digit.
if (this._currentIndex != startIntPartIndex) {
var scanIntPartIndex = this._currentIndex - 1;
var multiplier = 1;
while (scanIntPartIndex >= startIntPartIndex) {
integer += multiplier * (this._string.charAt(scanIntPartIndex--) - "0");
multiplier *= 10;
}
}
// Read the decimals.
if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ".") {
this._currentIndex++;
// There must be a least one digit following the .
if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9")
return undefined;
while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9")
decimal += (this._string.charAt(this._currentIndex++) - "0") * (frac *= 0.1);
}
// Read the exponent part.
if (this._currentIndex != startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) == "e" || this._string.charAt(this._currentIndex) == "E") && (this._string.charAt(this._currentIndex + 1) != "x" && this._string.charAt(this._currentIndex + 1) != "m")) {
this._currentIndex++;
// Read the sign of the exponent.
if (this._string.charAt(this._currentIndex) == "+") {
this._currentIndex++;
} else if (this._string.charAt(this._currentIndex) == "-") {
this._currentIndex++;
expsign = -1;
}
// There must be an exponent.
if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9")
return undefined;
while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") {
exponent *= 10;
exponent += (this._string.charAt(this._currentIndex) - "0");
this._currentIndex++;
}
}
var number = integer + decimal;
number *= sign;
if (exponent)
number *= Math.pow(10, expsign * exponent);
if (startIndex == this._currentIndex)
return undefined;
this._skipOptionalSpacesOrDelimiter();
return number;
}
Source.prototype._parseArcFlag = function() {
if (this._currentIndex >= this._endIndex)
return undefined;
var flag = false;
var flagChar = this._string.charAt(this._currentIndex++);
if (flagChar == "0")
flag = false;
else if (flagChar == "1")
flag = true;
else
return undefined;
this._skipOptionalSpacesOrDelimiter();
return flag;
}
Source.prototype.parseSegment = function() {
var lookahead = this._string[this._currentIndex];
var command = this._pathSegTypeFromChar(lookahead);
if (command == SVGPathSeg.PATHSEG_UNKNOWN) {
// Possibly an implicit command. Not allowed if this is the first command.
if (this._previousCommand == SVGPathSeg.PATHSEG_UNKNOWN)
return null;
command = this._nextCommandHelper(lookahead, this._previousCommand);
if (command == SVGPathSeg.PATHSEG_UNKNOWN)
return null;
} else {
this._currentIndex++;
}
this._previousCommand = command;
switch (command) {
case SVGPathSeg.PATHSEG_MOVETO_REL:
return new SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());
case SVGPathSeg.PATHSEG_MOVETO_ABS:
return new SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());
case SVGPathSeg.PATHSEG_LINETO_REL:
return new SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());
case SVGPathSeg.PATHSEG_LINETO_ABS:
return new SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());
case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:
return new SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber());
case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:
return new SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber());
case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:
return new SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber());
case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:
return new SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber());
case SVGPathSeg.PATHSEG_CLOSEPATH:
this._skipOptionalSpaces();
return new SVGPathSegClosePath(owningPathSegList);
case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL:
var points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);
case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS:
var points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegCurvetoCubicAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);
case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:
var points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, points.x, points.y, points.x2, points.y2);
case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:
var points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, points.x, points.y, points.x2, points.y2);
case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:
var points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegCurvetoQuadraticRel(owningPathSegList, points.x, points.y, points.x1, points.y1);
case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:
var points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegCurvetoQuadraticAbs(owningPathSegList, points.x, points.y, points.x1, points.y1);
case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:
return new SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber());
case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:
return new SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber());
case SVGPathSeg.PATHSEG_ARC_REL:
var points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegArcRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);
case SVGPathSeg.PATHSEG_ARC_ABS:
var points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()};
return new SVGPathSegArcAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);
default:
throw "Unknown path seg type."
}
}
var builder = new Builder();
var source = new Source(string);
if (!source.initialCommandIsMoveTo())
return [];
while (source.hasMoreData()) {
var pathSeg = source.parseSegment();
if (!pathSeg)
return [];
builder.appendSegment(pathSeg);
}
return builder.pathSegList;
}
}
}());
/* jshint ignore:end */
if (typeof define === 'function' && define.amd) {
define("c3", ["d3"], function () { return c3; });
} else if ('undefined' !== typeof exports && 'undefined' !== typeof module) {
module.exports = c3;
} else {
window.c3 = c3;
}
})(window);<|fim▁end|> | c3_chart_internal_fn.getOtherTargetX = function (index) {
var xs = this.getOtherTargetXs();
return xs && index < xs.length ? xs[index] : null;
|
<|file_name|>rclxls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# Extractor for Excel files.
# Mso-dumper is not compatible with Python3. We use sys.executable to
# start the actual extractor, so we need to use python2 too.
import rclexecm
import rclexec1
import xlsxmltocsv
import re
import sys
import os
import xml.sax
class XLSProcessData:
def __init__(self, em, ishtml = False):
self.em = em
self.out = ""
self.gotdata = 0
self.xmldata = ""
self.ishtml = ishtml
def takeLine(self, line):
if self.ishtml:
self.out += line + "\n"
return
if not self.gotdata:
self.out += '''<html><head>''' + \
'''<meta http-equiv="Content-Type" ''' + \
'''content="text/html;charset=UTF-8">''' + \
'''</head><body><pre>'''
self.gotdata = True
self.xmldata += line
def wrapData(self):
if self.ishtml:
return self.out
handler = xlsxmltocsv.XlsXmlHandler()
data = xml.sax.parseString(self.xmldata, handler)
self.out += self.em.htmlescape(handler.output)
return self.out + '''</pre></body></html>'''
class XLSFilter:
def __init__(self, em):
self.em = em
self.ntry = 0
def reset(self):
self.ntry = 0
pass
def getCmd(self, fn):
if self.ntry:
return ([], None)<|fim▁hole|> # Some HTML files masquerade as XLS
try:
data = open(fn, 'rb').read(512)
if data.find('html') != -1 or data.find('HTML') != -1:
return ("cat", XLSProcessData(self.em, True))
except Exception as err:
self.em.rclog("Error reading %s:%s" % (fn, str(err)))
pass
cmd = rclexecm.which("xls-dump.py")
if cmd:
# xls-dump.py often exits 1 with valid data. Ignore exit value
return ([sys.executable, cmd, "--dump-mode=canonical-xml", \
"--utf-8", "--catch"],
XLSProcessData(self.em), rclexec1.Executor.opt_ignxval)
else:
return ([], None)
if __name__ == '__main__':
if not rclexecm.which("xls-dump.py"):
print("RECFILTERROR HELPERNOTFOUND ppt-dump.py")
sys.exit(1)
proto = rclexecm.RclExecM()
filter = XLSFilter(proto)
extract = rclexec1.Executor(proto, filter)
rclexecm.main(proto, extract)<|fim▁end|> | self.ntry = 1 |
<|file_name|>optimize.py<|end_file_name|><|fim▁begin|>import sys
import typing
import click
import glotaran as gta
from . import util
@click.option('--dataformat', '-dfmt', default=None,
type=click.Choice(gta.io.reader.known_reading_formats.keys()),
help='The input format of the data. Will be infered from extension if not set.')
@click.option('--data', '-d', multiple=True,
type=(str, click.Path(exists=True, dir_okay=False)),
help="Path to a dataset in the form '--data DATASET_LABEL PATH_TO_DATA'")
@click.option('--out', '-o', default=None, type=click.Path(file_okay=False),
help='Path to an output directory.', show_default=True)
@click.option('--nfev', '-n', default=None, type=click.IntRange(min=1),
help='Maximum number of function evaluations.', show_default=True)
@click.option('--nnls', is_flag=True,
help='Use non-negative least squares.')
@click.option('--yes', '-y', is_flag=True,
help="Don't ask for confirmation.")
@util.signature_analysis
def optimize_cmd(dataformat: str, data: typing.List[str], out: str, nfev: int, nnls: bool,
yes: bool, parameter: str, model: str, scheme: str):
"""Optimizes a model.<|fim▁hole|> if scheme is not None:
scheme = util.load_scheme_file(scheme, verbose=True)
if nfev is not None:
scheme.nfev = nfev
else:
if model is None:
click.echo('Error: Neither scheme nor model specified', err=True)
sys.exit(1)
model = util.load_model_file(model, verbose=True)
if parameter is None:
click.echo('Error: Neither scheme nor parameter specified', err=True)
sys.exit(1)
parameter = util.load_parameter_file(parameter, verbose=True)
if len(data) == 0:
click.echo('Error: Neither scheme nor data specified', err=True)
sys.exit(1)
dataset_files = {arg[0]: arg[1] for arg in data}
datasets = {}
for label in model.dataset:
if label not in dataset_files:
click.echo(f"Missing dataset for '{label}'", err=True)
sys.exit(1)
path = dataset_files[label]
datasets[label] = util.load_dataset_file(path, fmt=dataformat, verbose=True)
scheme = gta.analysis.scheme.Scheme(model=model, parameter=parameter, data=datasets,
nnls=nnls, nfev=nfev)
click.echo(scheme.validate())
click.echo(f"Use NNLS: {scheme.nnls}")
click.echo(f"Max Nr Function Evaluations: {scheme.nfev}")
click.echo(f"Saving directory: is '{out if out is not None else 'None'}'")
if yes or click.confirm('Do you want to start optimization?', abort=True, default=True):
# try:
# click.echo('Preparing optimization...', nl=False)
# optimizer = gta.analysis.optimizer.Optimizer(scheme)
# click.echo(' Success')
# except Exception as e:
# click.echo(" Error")
# click.echo(e, err=True)
# sys.exit(1)
try:
click.echo('Optimizing...')
result = gta.analysis.optimize.optimize(scheme)
click.echo('Optimization done.')
click.echo(result.markdown(with_model=False))
click.echo('Optimized Parameter:')
click.echo(result.optimized_parameter.markdown())
except Exception as e:
click.echo(f"An error occured during optimization: \n\n{e}", err=True)
sys.exit(1)
if out is not None:
try:
click.echo(f"Saving directory is '{out}'")
if yes or click.confirm('Do you want to save the data?', default=True):
paths = result.save(out)
click.echo(f"File saving successfull, the follwing files have been written:\n")
for p in paths:
click.echo(f"* {p}")
except Exception as e:
click.echo(f"An error occured during optimization: \n\n{e}", err=True)
sys.exit(1)
click.echo('All done, have a nice day!')<|fim▁end|> | e.g.:
glotaran optimize --
""" |
<|file_name|>framework_lib.py<|end_file_name|><|fim▁begin|># 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.
# ==============================================================================
# pylint: disable=unused-import,g-bad-import-order
"""Classes and functions for building TensorFlow graphs.
## Core graph data structures
@@Graph
@@Operation
@@Tensor
## Tensor types
@@DType
@@as_dtype
## Utility functions
@@device
@@name_scope
@@control_dependencies
@@convert_to_tensor
@@convert_to_tensor_or_indexed_slices
@@get_default_graph
@@reset_default_graph
@@import_graph_def
@@load_file_system_library
@@load_op_library
## Graph collections
@@add_to_collection
@@get_collection
@@get_collection_ref
@@GraphKeys
## Defining new operations
@@RegisterGradient
@@NoGradient
@@RegisterShape
@@TensorShape
@@Dimension
@@op_scope
@@get_seed
## For libraries building on TensorFlow
@@register_tensor_conversion_function
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Classes used when building a Graph.
from tensorflow.python.framework.device import DeviceSpec
from tensorflow.python.framework.ops import Graph
from tensorflow.python.framework.ops import Operation
from tensorflow.python.framework.ops import Tensor
from tensorflow.python.framework.ops import SparseTensor
from tensorflow.python.framework.ops import SparseTensorValue
from tensorflow.python.framework.ops import IndexedSlices
# Utilities used when building a Graph.
from tensorflow.python.framework.ops import device
from tensorflow.python.framework.ops import name_scope
from tensorflow.python.framework.ops import op_scope
from tensorflow.python.framework.ops import control_dependencies
from tensorflow.python.framework.ops import get_default_graph
from tensorflow.python.framework.ops import reset_default_graph
from tensorflow.python.framework.ops import GraphKeys
from tensorflow.python.framework.ops import add_to_collection
from tensorflow.python.framework.ops import get_collection
from tensorflow.python.framework.ops import get_collection_ref
from tensorflow.python.framework.ops import convert_to_tensor
from tensorflow.python.framework.ops import convert_to_tensor_or_indexed_slices
from tensorflow.python.framework.random_seed import get_seed
from tensorflow.python.framework.random_seed import set_random_seed
from tensorflow.python.framework.importer import import_graph_def
# Needed when you defined a new Op in C++.
from tensorflow.python.framework.ops import RegisterGradient
from tensorflow.python.framework.ops import NoGradient
from tensorflow.python.framework.ops import RegisterShape
from tensorflow.python.framework.tensor_shape import Dimension
from tensorflow.python.framework.tensor_shape import TensorShape
# Needed when interfacing tensorflow to new array libraries
from tensorflow.python.framework.ops import register_tensor_conversion_function
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.framework.dtypes import *<|fim▁hole|># pylint: enable=wildcard-import<|fim▁end|> |
# Load a TensorFlow plugin
from tensorflow.python.framework.load_library import * |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 Google Inc. All rights reserved.
//
// 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.
//! Command line tool to exercise pulldown-cmark.
extern crate getopts;
extern crate pulldown_cmark;
use pulldown_cmark::Parser;
use pulldown_cmark::{Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES};
use pulldown_cmark::html;
use std::env;
use std::io;
use std::io::{Read, Write};
use std::path::Path;
use std::fs::File;
fn render_html(text: &str, opts: Options) -> String {
let mut s = String::with_capacity(text.len() * 3 / 2);
let p = Parser::new_ext(&text, opts);
html::push_html(&mut s, p);
s
}
fn dry_run(text:&str, opts: Options) {
let p = Parser::new_ext(&text, opts);
/*
let events = p.collect::<Vec<_>>();
let count = events.len();
*/
let count = p.count();
println!("{} events", count);
}
fn print_events(text: &str, opts: Options) {
let mut p = Parser::new_ext(&text, opts);
loop {
print!("{}: ", p.get_offset());
if let Some(event) = p.next() {
println!("{:?}", event);
} else {
break;
}
}
println!("EOF");
}
fn read_file(filename: &str) -> String {
let path = Path::new(filename);
let mut file = match File::open(&path) {
Err(why) => panic!("couldn't open {}: {}", path.display(), why),
Ok(file) => file
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("couldn't open {}: {}", path.display(), why),
Ok(_) => s
}
}
fn find_test_delim(text: &str) -> Option<usize> {
if text.starts_with(".\n") { Some(0) }<|fim▁hole|>
fn run_spec(spec_text: &str, args: &[String], opts: Options) {
//println!("spec length={}, args={:?}", spec_text.len(), args);
let (first, last) = if args.is_empty() {
(None, None)
} else {
let mut iter = args[0].split("..");
let first = iter.next().and_then(|s| s.parse().ok());
let last = match iter.next() {
Some(s) => s.parse().ok(),
None => first
};
(first, last)
};
let mut test_number = 1;
let mut tests_failed = 0;
let mut tests_run = 0;
let mut line_count = 0;
let mut tail = spec_text;
loop {
let rest = match find_test_delim(tail) {
Some(pos) => &tail[pos + 2 ..],
None => break
};
let (source, rest) = match find_test_delim(rest) {
Some(pos) => (&rest[..pos], &rest[pos + 2 ..]),
None => break
};
let (html, rest) = match find_test_delim(rest) {
Some(pos) => (&rest[.. pos], &rest[pos + 2 ..]),
None => break
};
if first.map(|fst| fst <= test_number).unwrap_or(true) &&
last.map(|lst| test_number <= lst).unwrap_or(true) {
if tests_run == 0 || line_count == 0 || (test_number % 10 == 0) {
if line_count > 30 {
println!("");
line_count = 0;
} else if line_count > 0 {
print!(" ");
}
print!("[{}]", test_number);
} else if line_count > 0 && (test_number % 10) == 5 {
print!(" ");
}
let our_html = render_html(&source.replace("→", "\t").replace("\n", "\r\n"), opts);
if our_html == html {
print!(".");
} else {
if tests_failed == 0 {
print!("FAIL {}:\n---input---\n{}\n---wanted---\n{}\n---got---\n{}",
test_number, source, html, our_html);
} else {
print!("X");
}
tests_failed += 1;
}
let _ = io::stdout().flush();
tests_run += 1;
line_count += 1;
}
tail = rest;
test_number += 1;
}
println!("\n{}/{} tests passed", tests_run - tests_failed, tests_run)
}
pub fn main() {
let args: Vec<_> = env::args().collect();
let mut opts = getopts::Options::new();
opts.optflag("d", "dry-run", "dry run, produce no output");
opts.optflag("e", "events", "print event sequence instead of rendering");
opts.optflag("T", "enable-tables", "enable GitHub-style tables");
opts.optflag("F", "enable-footnotes", "enable Hoedown-style footnotes");
opts.optopt("s", "spec", "run tests from spec file", "FILE");
opts.optopt("b", "bench", "run benchmark", "FILE");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string())
};
let mut opts = Options::empty();
if matches.opt_present("enable-tables") {
opts.insert(OPTION_ENABLE_TABLES);
}
if matches.opt_present("enable-footnotes") {
opts.insert(OPTION_ENABLE_FOOTNOTES);
}
if let Some(filename) = matches.opt_str("spec") {
run_spec(&read_file(&filename), &matches.free, opts);
} else if let Some(filename) = matches.opt_str("bench") {
let inp = read_file(&filename);
for _ in 0..1000 {
let _ = render_html(&inp, opts);
}
} else {
let mut input = String::new();
match io::stdin().read_to_string(&mut input) {
Err(why) => panic!("couldn't read from stdin: {}", why),
Ok(_) => ()
}
if matches.opt_present("events") {
print_events(&input, opts);
} else if matches.opt_present("dry-run") {
dry_run(&input, opts);
} else {
print!("{}", render_html(&input, opts));
}
}
}<|fim▁end|> | else { text.find("\n.\n").map(|pos| pos + 1) }
} |
<|file_name|>test_artificial_32_Quantization_MovingAverage_5_12_100.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 5, transform = "Quantization", sigma = 0.0, exog_count = 100, ar_order = 12);<|fim▁end|> | |
<|file_name|>0022_auto_20161208_2216.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-08 21:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0021_auto_20161208_1214'),
]
<|fim▁hole|> field=models.CharField(max_length=255, verbose_name='holdnavn'),
),
migrations.AlterField(
model_name='tournamentteam',
name='profiles',
field=models.ManyToManyField(to='main.Profile', verbose_name='medlemmer'),
),
]<|fim▁end|> | operations = [
migrations.AlterField(
model_name='tournamentteam',
name='name', |
<|file_name|>PlotCursor.ts<|end_file_name|><|fim▁begin|>/*
* Copyright 2018 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import PlotStyleUtils from "beakerx_shared/lib/utils/PlotStyleUtils";
import PlotUtils from "./utils/PlotUtils";
export default class PlotCursor {
scope: any;
constructor(scope) {
this.scope = scope;
this.render = this.render.bind(this);
}
render(event) {
const x = event.offsetX;
const y = event.offsetY;
const width = PlotStyleUtils.safeWidth(this.scope.jqsvg);
const height = PlotStyleUtils.safeHeight(this.scope.jqsvg);
const leftMargin = this.scope.layout.leftLayoutMargin;
const bottomMargin = this.scope.layout.bottomLayoutMargin;
const rightMargin = this.scope.layout.rightLayoutMargin;
const topMargin = this.scope.layout.topLayoutMargin;
const model = this.scope.stdmodel;
if (
x < leftMargin
|| model.yAxisR != null && x > width - rightMargin
|| y > height - bottomMargin
|| y < topMargin
) {
this.scope.svg.selectAll(".plot-cursor").remove();
this.scope.jqcontainer.find(".plot-cursorlabel").remove();
return;
}
this.renderCursorX(x, height, topMargin, bottomMargin);
this.renderCursorY(y, width, leftMargin, rightMargin);
}
renderCursorX(x, height, topMargin, bottomMargin) {
if (this.scope.stdmodel.xCursor == null) {
return;
}
<|fim▁hole|>
this.scope.svg.selectAll("#cursor_x")
.data([{}])
.enter()
.append("line")
.attr("id", "cursor_x")
.attr("class", "plot-cursor")
.style("stroke", opt.color)
.style("stroke-opacity", opt.color_opacity)
.style("stroke-width", opt.width)
.style("stroke-dasharray", opt.stroke_dasharray);
this.scope.svg.select("#cursor_x")
.attr("x1", x)
.attr("y1", topMargin)
.attr("x2", x)
.attr("y2", height - bottomMargin);
this.scope.jqcontainer.find("#cursor_xlabel").remove();
const label = $(`<div id="cursor_xlabel" class="plot-cursorlabel"></div>`)
.appendTo(this.scope.jqcontainer)
.text(PlotUtils.getTipStringPercent(mapX(x), model.xAxis));
const width = label.outerWidth();
const labelHeight = label.outerHeight();
const point = {
x: x - width / 2,
y: height - bottomMargin - this.scope.labelPadding.y - labelHeight
};
label.css({
"left" : point.x ,
"top" : point.y ,
"background-color" : opt.color != null ? opt.color : "black"
});
}
renderCursorY(y, width, leftMargin, rightMargin) {
if (this.scope.stdmodel.yCursor == null) {
return;
}
const model = this.scope.stdmodel;
const opt = model.yCursor;
this.scope.svg.selectAll("#cursor_y").data([{}]).enter().append("line")
.attr("id", "cursor_y")
.attr("class", "plot-cursor")
.style("stroke", opt.color)
.style("stroke-opacity", opt.color_opacity)
.style("stroke-width", opt.width)
.style("stroke-dasharray", opt.stroke_dasharray);
this.scope.svg.select("#cursor_y")
.attr("x1", leftMargin)
.attr("y1", y)
.attr("x2", width - rightMargin)
.attr("y2", y);
this.renderCursorLabel(model.yAxis, "cursor_ylabel", y, false);
if (model.yAxisR) {
this.renderCursorLabel(model.yAxisR, "cursor_yrlabel", y, true);
}
}
renderCursorLabel(axis, id, y, alignRight) {
if (axis == null) {
return;
}
const model = this.scope.stdmodel;
const opt = model.yCursor;
const lMargin = this.scope.layout.leftLayoutMargin;
const rMargin = this.scope.layout.rightLayoutMargin;
const mapY = this.scope.plotRange.scr2dataY;
this.scope.jqcontainer.find("#" + id).remove();
const label = $(`<div id="${id}" class='plot-cursorlabel'></div>`)
.appendTo(this.scope.jqcontainer)
.text(PlotUtils.getTipStringPercent(mapY(y), axis));
const height = label.outerHeight();
const point = { x: (alignRight ? rMargin : lMargin) + this.scope.labelPadding.x, y: y - height / 2 };
label.css({
"top" : point.y ,
"background-color" : opt.color != null ? opt.color : "black",
[alignRight ? "right" : "left"]: point.x
});
}
clear() {
this.scope.svg.selectAll(".plot-cursor").remove();
this.scope.jqcontainer.find(".plot-cursorlabel").remove();
}
}<|fim▁end|> | const model = this.scope.stdmodel;
const opt = model.xCursor;
const mapX = this.scope.plotRange.scr2dataX; |
<|file_name|>metric.py<|end_file_name|><|fim▁begin|># coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Classes to track metrics about cache line evictions."""
import abc
import numpy as np
from scipy import stats
from cache_replacement.policy_learning.cache_model import utils
class CacheEvictionMetric(abc.ABC):
"""Tracks the value of a metric about predictions on cache lines."""
@abc.abstractmethod
def update(self, prediction_probs, eviction_mask, oracle_scores):
"""Updates the value of the metric based on a batch of data.
Args:
prediction_probs (torch.FloatTensor): batch of probability distributions
over cache lines of shape (batch_size, num_cache_lines), each
corresponding to a cache access. In each distribution, the lines are
ordered from top-1 to top-num_cache_lines.
eviction_mask (torch.ByteTensor): of shape (batch_size), where
eviction_mask[i] = True if the i-th cache access results in an eviction.
The metric value is tracked for two populations: (i) all cache accesses
and (ii) for evictions.
oracle_scores (list[list[float]]): the oracle scores of the cache lines,
of shape (batch_size, num_cache_lines).
"""
raise NotImplementedError()
@abc.abstractmethod
def write_to_tensorboard(self, tb_writer, tb_tag, step):
"""Writes the value of the tracked metric(s) to tensorboard.
Args:<|fim▁hole|> tb_tag (str): metrics are written to tb_tag/metric_name(s).
step (int): the step to use when writing to tensorboard.
"""
raise NotImplementedError()
class SuccessRateMetric(CacheEvictionMetric):
"""Tracks the success rate of predicting the top-1 to top-k elements.
Writes the following metrics to tensorboard:
tb_tag/eviction_top_i for i = 1, ..., k
tb_tag/total_top_i for i = 1, ..., k
"""
def __init__(self, k):
"""Sets the value of k to track up to.
Args:
k (int): metric tracks top-1 to top-k.
"""
self._k = k
self._num_top_i_successes = {"total": [0] * k, "eviction": [0] * k}
self._num_accesses = {"total": 0, "eviction": 0}
def update(self, prediction_probs, eviction_mask, oracle_scores):
del oracle_scores
sorted_probs, _ = prediction_probs.sort(descending=True)
num_elems = sorted_probs.shape[-1]
for i in range(self._k):
top_i_successes = (
prediction_probs[:, 0] >= sorted_probs[:, min(i, num_elems - 1)])
self._num_top_i_successes["total"][i] += top_i_successes.sum().item()
self._num_top_i_successes["eviction"][i] += (
eviction_mask * top_i_successes).sum().item()
self._num_accesses["total"] += prediction_probs.shape[0]
self._num_accesses["eviction"] += eviction_mask.sum().item()
def write_to_tensorboard(self, tb_writer, tb_tag, step):
for key in self._num_top_i_successes:
for i in range(self._k):
top_i_success_rate = (self._num_top_i_successes[key][i] /
(self._num_accesses[key] + 1e-8))
utils.log_scalar(
tb_writer, "{}/{}_top_{}".format(tb_tag, key, i + 1),
top_i_success_rate, step)
class KendallWeightedTau(CacheEvictionMetric):
"""Tracks value of Kendall's weighted tau w.r.t. labeled ordering."""
def __init__(self):
self._weighted_taus = []
self._masks = []
def update(self, prediction_probs, eviction_mask, oracle_scores):
del oracle_scores
_, predicted_order = prediction_probs.sort(descending=True)
for unbatched_order in predicted_order.cpu().data.numpy():
# Need to negate arguments for rank: see weightedtau docs
# NOTE: This is incorporating potentially masked & padded probs
weighted_tau, _ = stats.weightedtau(
-unbatched_order, -np.array(range(len(unbatched_order))), rank=False)
self._weighted_taus.append(weighted_tau)
self._masks.extend(eviction_mask.cpu().data.numpy())
def write_to_tensorboard(self, tb_writer, tb_tag, step):
weighted_taus = np.array(self._weighted_taus)
eviction_masks = np.array(self._masks)
eviction_mean_weighted_tau = np.sum(
weighted_taus * eviction_masks) / (np.sum(eviction_masks) + 1e-8)
utils.log_scalar(
tb_writer, "{}/eviction_weighted_tau".format(tb_tag),
eviction_mean_weighted_tau, step)
utils.log_scalar(
tb_writer, "{}/total_weighted_tau".format(tb_tag),
np.mean(weighted_taus), step)
class OracleScoreGap(CacheEvictionMetric):
"""Tracks the gap between the oracle score of evicted vs. optimal line.
Given lines l_1, ..., l_N with model probabilities p_1, ..., p_N and oracle
scores s_1, ..., s_N, computes two gaps:
- the optimal line is l_1 with score s_1
- the evicted line is l_i, where i = argmax_j p_j
- the quotient gap is computed as log(s_1 / s_i)
- the difference gap is computed as log(s_i - s_1 + 1) [+1 to avoid log(0)]
- scores are typically negative reuse distances.
"""
def __init__(self):
self._optimal_scores = []
self._evicted_scores = []
self._masks = []
def update(self, prediction_probs, eviction_mask, oracle_scores):
chosen_indices = prediction_probs.argmax(-1).cpu().data.numpy()
# Default to optimal score = evicted score = 1, if no scores
# Simpler than just excluding the scores, because of the masks.
# Need to do explicit len check for numpy array
# pylint: disable=g-explicit-length-test
self._optimal_scores.append(
[scores[0] if len(scores) > 0 else 1 for scores in oracle_scores])
self._evicted_scores.append(
[scores[index] if len(scores) > 0 else 1
for (index, scores) in zip(chosen_indices, oracle_scores)])
self._masks.append(eviction_mask.cpu().data.numpy())
def write_to_tensorboard(self, tb_writer, tb_tag, step):
eviction_masks = np.array(self._masks)
difference_gap = np.log10(
np.array(self._evicted_scores) - np.array(self._optimal_scores) + 1)
quotient_gap = np.log10(
np.array(self._optimal_scores) / np.array(self._evicted_scores))
gaps = {
"difference": difference_gap,
"quotient": quotient_gap,
}
for gap_type, gap in gaps.items():
eviction_mean_gap = np.sum(
gap * eviction_masks) / (np.sum(eviction_masks) + 1e-8)
utils.log_scalar(
tb_writer, "{}/eviction_oracle_score_{}_gap".format(tb_tag, gap_type),
eviction_mean_gap, step)
utils.log_scalar(
tb_writer, "{}/oracle_score_{}_gap".format(tb_tag, gap_type),
np.mean(gap), step)<|fim▁end|> | tb_writer (tf.Writer): tensorboard writer to write to. |
<|file_name|>core-tls-store-pointer.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Testing that we can't store a reference in task-local storage
local_data_key!(key: Box<&int>)
//~^ ERROR missing lifetime specifier
fn main() {}<|fim▁end|> | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. |
<|file_name|>fermentator-status.ts<|end_file_name|><|fim▁begin|>export const FERMENTATORS_STATUS: any[] = [
{ id: 0, name: 'Vacío', buttonClass: 'btn-outline-danger'},<|fim▁hole|><|fim▁end|> | { id: 1, name: 'Fermentando', buttonClass: 'btn-outline-primary'},
{ id: 2, name: 'Enfriando', buttonClass: 'btn-outline-secondary'}
]; |
<|file_name|>editLambdaArgToTypeParameter1.ts<|end_file_name|><|fim▁begin|>/// <reference path='fourslash.ts'/>
////class C<T> {
//// foo(x: T) {
//// return (a: number/*1*/) => x;
//// }
////}
/////*2*/
goTo.marker('1');
edit.backspace(6);
edit.insert('T');
verify.numberOfErrorsInCurrentFile(0);
goTo.marker('2');<|fim▁hole|><|fim▁end|> | edit.insertLine('');
verify.numberOfErrorsInCurrentFile(0); |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>"""
Django settings for dts_test_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TENANT_APPS_DIR = os.path.join(BASE_DIR, os.pardir)
sys.path.insert(0, TENANT_APPS_DIR)
sys.path.insert(0, BASE_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'cl1)b#c&xmm36z3e(quna-vb@ab#&gpjtdjtpyzh!qn%bc^xxn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
SHARED_APPS = (
'django_tenants', # mandatory
'customers', # you must list the app where your tenant model resides in
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
TENANT_APPS = (
'dts_test_app',
)
TENANT_MODEL = "customers.Client" # app.Model
TENANT_DOMAIN_MODEL = "customers.Domain" # app.Model
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]
ROOT_URLCONF = 'dts_test_project.urls'
WSGI_APPLICATION = 'dts_test_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django_tenants.postgresql_backend',
'NAME': 'dts_test_project',
'USER': 'postgres',
'PASSWORD': os.environ.get('DATABASE_PASSWORD', 'root'),
'HOST': os.environ.get('DATABASE_HOST', 'localhost'),
'PORT': '',
}
}
DATABASE_ROUTERS = (
'django_tenants.routers.TenantSyncRouter',
)
MIDDLEWARE = (
'tenant_tutorial.middleware.TenantTutorialMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
)
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/<|fim▁hole|>
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'<|fim▁end|> |
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC' |
<|file_name|>invalidEnumAssignments.ts<|end_file_name|><|fim▁begin|>enum E {
A,
B
}
enum E2 {
A,
B
}
var e: E;
var e2: E2;
<|fim▁hole|>e = E2.A;
e2 = E.A;
e = <void>null;
e = {};
e = '';
function f<T>(a: T) {
e = a;
}<|fim▁end|> | |
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md><|fim▁hole|>}<|fim▁end|> | extern crate build;
fn main() {
build::link("mstask", true) |
<|file_name|>pluginconf_d.py<|end_file_name|><|fim▁begin|>"""
pluginconf.d configuration file - Files
=======================================
Shared mappers for parsing and extracting data from
``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained
in this module are:
PluginConfD - files ``/etc/yum/pluginconf.d/*.conf``
---------------------------------------------------
PluginConfDIni - files ``/etc/yum/pluginconf.d/*.conf``
-------------------------------------------------------
"""
from insights.core import IniConfigFile, LegacyItemAccess, Parser
from insights.core.plugins import parser
from insights.parsers import get_active_lines
from insights.specs import Specs
from insights.util import deprecated
@parser(Specs.pluginconf_d)
class PluginConfD(LegacyItemAccess, Parser):
"""
.. warning::
This parser is deprecated, please use
:py:class:`insights.parsers.pluginconf_d.PluginConfDIni` instead
Class to parse configuration file under ``pluginconf.d``
Sample configuration::<|fim▁hole|>
[main]
enabled = 0
gpgcheck = 1
timeout = 120
# You can specify options per channel, e.g.:
#
#[rhel-i386-server-5]
#enabled = 1
#
#[some-unsigned-custom-channel]
#gpgcheck = 0
"""
def parse_content(self, content):
deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.")
plugin_dict = {}
section_dict = {}
key = None
for line in get_active_lines(content):
if line.startswith('['):
section_dict = {}
plugin_dict[line[1:-1]] = section_dict
elif '=' in line:
key, _, value = line.partition("=")
key = key.strip()
section_dict[key] = value.strip()
else:
if key:
section_dict[key] = ','.join([section_dict[key], line])
self.data = plugin_dict
def __iter__(self):
for sec in self.data:
yield sec
@parser(Specs.pluginconf_d)
class PluginConfDIni(IniConfigFile):
"""
Read yum plugin config files, in INI format, using the standard INI file
parser class.
Sample configuration::
[main]
enabled = 0
gpgcheck = 1
timeout = 120
# You can specify options per channel, e.g.:
#
#[rhel-i386-server-5]
#enabled = 1
#
#[some-unsigned-custom-channel]
#gpgcheck = 0
[test]
test_multiline_config = http://example.com/repos/test/
http://mirror_example.com/repos/test/
Examples:
>>> type(conf)
<class 'insights.parsers.pluginconf_d.PluginConfDIni'>
>>> conf.sections()
['main', 'test']
>>> conf.has_option('main', 'gpgcheck')
True
>>> conf.get("main", "enabled")
'0'
>>> conf.getint("main", "timeout")
120
>>> conf.getboolean("main", "enabled")
False
>>> conf.get("test", "test_multiline_config")
'http://example.com/repos/test/ http://mirror_example.com/repos/test/'
"""
pass<|fim▁end|> | |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Setup script for the WDmodel package
"""
import sys<|fim▁hole|>import glob
from setuptools import find_packages, setup
dep_file = 'dependencies_py36.txt'
with open(dep_file,'r') as f:
required = f.read().splitlines()
dir_path = os.path.dirname(os.path.realpath(__file__))
init_string = open(os.path.join(dir_path, 'WDmodel', '__init__.py')).read()
VERS = r"^__version__\s+=\s+[\'\"]([0-9\.]*)[\'\"]$"
mo = re.search(VERS, init_string, re.M)
__version__ = mo.group(1)
AUTH = r"^__author__\s+=\s+[\'\"]([A-za-z\s]*)[\'\"]$"
mo = re.search(AUTH, init_string, re.M)
__author__ = mo.group(1)
LICE = r"^__license__ \s+=\s+[\'\"]([A-za-z\s0-9]*)[\'\"]$"
mo = re.search(LICE, init_string, re.M)
__license__ = mo.group(1)
long_description = open('README.rst').read()
scripts = glob.glob('bin/*')
print(scripts)
setup(
name='WDmodel',
packages=find_packages(),
entry_points={'console_scripts': [
'WDmodel = WDmodel.main:main'
]},
include_package_data=True,
version=__version__, # noqa
description=('Bayesian inference of '
'faint DA white dwarf spectral energy distributions'
'from ground-based spectroscopy and HST photometry'
'to establish faint CALSPEC spectrophotometric standards.'),
scripts = scripts,
license=__license__, # noqa
author=__author__, # noqa
author_email='[email protected]',
install_requires=required,
url='https://github.com/gnarayan/WDmodel',
keywords=['astronomy', 'fitting', 'monte carlo', 'modeling', 'calibration'],
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Astronomy',
'Topic :: Scientific/Engineering :: Physics'
])<|fim▁end|> | import os
import re |
<|file_name|>libvirt.py<|end_file_name|><|fim▁begin|>#
# Copyright 2015 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
import json
import libvirt
import netaddr
import os
import os.path
import subprocess
from lxml import etree
from ..driverbase import VirtDeployDriverBase
from ..errors import InstanceNotFound
from ..errors import VirtDeployException
from ..utils import execute
from ..utils import random_password
DEFAULT_NET = 'default'
DEFAULT_POOL = 'default'
BASE_FORMAT = 'qcow2'
BASE_SIZE = '20G'
INSTANCE_DEFAULTS = {
'cpus': 2,
'memory': 1024,
'arch': 'x86_64',
'network': DEFAULT_NET,
'pool': DEFAULT_POOL,
'password': None,
}
_NET_ADD_LAST = libvirt.VIR_NETWORK_UPDATE_COMMAND_ADD_LAST
_NET_MODIFY = libvirt.VIR_NETWORK_UPDATE_COMMAND_MODIFY
_NET_DELETE = libvirt.VIR_NETWORK_UPDATE_COMMAND_DELETE
_NET_DNS_HOST = libvirt.VIR_NETWORK_SECTION_DNS_HOST
_NET_DHCP_HOST = libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST
_NET_UPDATE_FLAGS = (
libvirt.VIR_NETWORK_UPDATE_AFFECT_CONFIG |
libvirt.VIR_NETWORK_UPDATE_AFFECT_LIVE
)
_IMAGE_OS_TABLE = {
'centos-6': 'centos6.5', # TODO: fix versions
'centos-7.1': 'centos7.0', # TODO: fix versions
'centos-7.2': 'centos7.0', # TODO: fix versions
'rhel-6.7': 'rhel6', # TODO: fix versions
'rhel-7.2': 'rhel7', # TODO: fix versions
}
class VirtDeployLibvirtDriver(VirtDeployDriverBase):
def __init__(self, uri='qemu:///system'):
self._uri = uri
def _libvirt_open(self):
def libvirt_callback(ctx, err):
pass # add logging only when required
libvirt.registerErrorHandler(libvirt_callback, ctx=None)
return libvirt.open(self._uri)
def template_list(self):
templates = _get_virt_templates()
if templates['version'] != 1:
raise VirtDeployException('Unsupported template list version')
return [{'id': x['os-version'], 'name': x['full-name']}
for x in templates['templates']]
def instance_create(self, vmid, template, **kwargs):
kwargs = dict(INSTANCE_DEFAULTS.items() + kwargs.items())
name = '{0}-{1}-{2}'.format(vmid, template, kwargs['arch'])
image = '{0}.qcow2'.format(name)
conn = self._libvirt_open()
pool = conn.storagePoolLookupByName(kwargs['pool'])
net = conn.networkLookupByName(kwargs['network'])
repository = _get_pool_path(pool)
path = os.path.join(repository, image)
if os.path.exists(path):
raise OSError(os.errno.EEXIST, "Image already exists")
base = _create_base(template, kwargs['arch'], repository)
execute(('qemu-img', 'create', '-f', 'qcow2', '-b', base, image),
cwd=repository)
hostname = 'vm-{0}'.format(vmid)
domainname = _get_network_domainname(net)
if domainname is None:
fqdn = hostname
else:
fqdn = '{0}.{1}'.format(hostname, domainname)
if kwargs['password'] is None:
kwargs['password'] = random_password()
password_string = 'password:{0}'.format(kwargs['password'])
execute(('virt-customize',
'-a', path,
'--hostname', fqdn,
'--root-password', password_string))
network = 'network={0}'.format(kwargs['network'])
try:
conn.nwfilterLookupByName('clean-traffic')<|fim▁hole|> else:
network += ',filterref=clean-traffic'
disk = 'path={0},format=qcow2,bus=scsi,discard=unmap'.format(path)
channel = 'unix,name=org.qemu.guest_agent.0'
execute(('virt-install',
'--quiet',
'--connect={0}'.format(self._uri),
'--name', name,
'--cpu', 'host-model-only,+vmx',
'--vcpus', str(kwargs['cpus']),
'--memory', str(kwargs['memory']),
'--controller', 'scsi,model=virtio-scsi',
'--disk', disk,
'--network', network,
'--graphics', 'spice',
'--channel', channel,
'--os-variant', _get_image_os(template),
'--import',
'--noautoconsole',
'--noreboot'))
netmac = _get_domain_mac_addresses(_get_domain(conn, name)).next()
ipaddress = _new_network_ipaddress(net)
# TODO: fix race between _new_network_ipaddress and ip reservation
_add_network_host(net, hostname, ipaddress)
_add_network_dhcp_host(net, hostname, netmac['mac'], ipaddress)
return {
'name': name,
'password': kwargs['password'],
'mac': netmac['mac'],
'hostname': fqdn,
'ipaddress': ipaddress,
}
def instance_address(self, vmid, network=None):
conn = self._libvirt_open()
dom = _get_domain(conn, vmid)
netmacs = _get_domain_macs_by_network(dom)
if network:
netmacs = {k: v for k, v in netmacs.iteritems()}
addresses = set()
for name, macs in netmacs.iteritems():
net = conn.networkLookupByName(name)
for lease in _get_network_dhcp_leases(net):
if lease['mac'] in macs:
addresses.add(lease['ip'])
return list(addresses)
def instance_start(self, vmid):
dom = _get_domain(self._libvirt_open(), vmid)
try:
dom.create()
except libvirt.libvirtError as e:
if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID:
raise
def instance_stop(self, vmid):
dom = _get_domain(self._libvirt_open(), vmid)
try:
dom.shutdownFlags(
libvirt.VIR_DOMAIN_SHUTDOWN_GUEST_AGENT |
libvirt.VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN
)
except libvirt.libvirtError as e:
if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID:
raise
def instance_delete(self, vmid):
conn = self._libvirt_open()
dom = _get_domain(conn, vmid)
try:
dom.destroy()
except libvirt.libvirtError as e:
if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID:
raise
xmldesc = etree.fromstring(dom.XMLDesc())
for disk in xmldesc.iterfind('./devices/disk/source'):
try:
os.remove(disk.get('file'))
except OSError as e:
if e.errno != os.errno.ENOENT:
raise
netmacs = _get_domain_macs_by_network(dom)
for network, macs in netmacs.iteritems():
net = conn.networkLookupByName(network)
for x in _get_network_dhcp_hosts(net):
if x['mac'] in macs:
_del_network_host(net, x['name'])
_del_network_dhcp_host(net, x['name'])
dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)
def _get_image_os(image):
try:
return _IMAGE_OS_TABLE[image]
except KeyError:
return image.replace('-', '')
def _create_base(template, arch, repository):
name = '_{0}-{1}.{2}'.format(template, arch, BASE_FORMAT)
path = os.path.join(repository, name)
if not os.path.exists(path):
execute(('virt-builder', template,
'-o', path,
'--size', BASE_SIZE,
'--format', BASE_FORMAT,
'--arch', arch,
'--root-password', 'locked:disabled'))
# As mentioned in the virt-builder man in section "CLONES" the
# resulting image should be cleaned before bsing used as template.
# TODO: handle half-backed templates
execute(('virt-sysprep', '-a', path))
return name
def _get_virt_templates():
stdout, _ = execute(('virt-builder', '-l', '--list-format', 'json'),
stdout=subprocess.PIPE)
return json.loads(stdout)
def _get_domain(conn, name):
try:
return conn.lookupByName(name)
except libvirt.libvirtError as e:
if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
raise InstanceNotFound(name)
raise
def _get_domain_mac_addresses(dom):
xmldesc = etree.fromstring(dom.XMLDesc())
netxpath = './devices/interface[@type="network"]'
for iface in xmldesc.iterfind(netxpath):
network = iface.find('./source').get('network')
mac = iface.find('./mac').get('address')
yield {'mac': mac, 'network': network}
def _get_domain_macs_by_network(dom):
netmacs = {}
for x in _get_domain_mac_addresses(dom):
netmacs.setdefault(x['network'], []).append(x['mac'])
return netmacs
def _get_pool_path(pool):
xmldesc = etree.fromstring(pool.XMLDesc())
for x in xmldesc.iterfind('.[@type="dir"]/target/path'):
return x.text
raise OSError(os.errno.ENOENT, 'Path not found for pool')
def _get_network_domainname(net):
xmldesc = etree.fromstring(net.XMLDesc())
for domain in xmldesc.iterfind('./domain'):
return domain.get('name')
def _add_network_host(net, hostname, ipaddress):
xmlhost = etree.Element('host')
xmlhost.set('ip', ipaddress)
etree.SubElement(xmlhost, 'hostname').text = hostname
# Attempt to delete if present
_del_network_host(net, hostname)
net.update(_NET_ADD_LAST, _NET_DNS_HOST, 0, etree.tostring(xmlhost),
_NET_UPDATE_FLAGS)
def _del_network_host(net, hostname):
xmlhost = etree.Element('host')
etree.SubElement(xmlhost, 'hostname').text = hostname
try:
net.update(_NET_DELETE, _NET_DNS_HOST, 0, etree.tostring(xmlhost),
_NET_UPDATE_FLAGS)
except libvirt.libvirtError as e:
if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID:
raise
def _add_network_dhcp_host(net, hostname, mac, ipaddress):
xmlhost = etree.Element('host')
xmlhost.set('mac', mac)
xmlhost.set('name', hostname)
xmlhost.set('ip', ipaddress)
# Attempt to delete if present
_del_network_dhcp_host(net, hostname)
net.update(_NET_ADD_LAST, _NET_DHCP_HOST, 0, etree.tostring(xmlhost),
_NET_UPDATE_FLAGS)
def _del_network_dhcp_host(net, hostname):
xmlhost = etree.Element('host')
xmlhost.set('name', hostname)
try:
net.update(_NET_DELETE, _NET_DHCP_HOST, 0, etree.tostring(xmlhost),
_NET_UPDATE_FLAGS)
except libvirt.libvirtError as e:
if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID:
raise
def _get_network_dhcp_hosts(net):
xmldesc = etree.fromstring(net.XMLDesc())
for x in xmldesc.iterfind('./ip/dhcp/host'):
yield {'name': x.get('name'), 'mac': x.get('mac'),
'ip': x.get('ip')}
def _get_network_dhcp_leases(net):
for x in _get_network_dhcp_hosts(net):
yield x
for x in net.DHCPLeases():
yield {'name': x['hostname'], 'mac': x['mac'],
'ip': x['ipaddr']}
def _new_network_ipaddress(net):
xmldesc = etree.fromstring(net.XMLDesc())
hosts = _get_network_dhcp_leases(net)
addresses = set(netaddr.IPAddress(x['ip']) for x in hosts)
localip = xmldesc.find('./ip').get('address')
netmask = xmldesc.find('./ip').get('netmask')
addresses.add(netaddr.IPAddress(localip))
for ip in netaddr.IPNetwork(localip, netmask)[1:-1]:
if ip not in addresses:
return str(ip)<|fim▁end|> | except libvirt.libvirtError as e:
if e.get_error_code() != libvirt.VIR_ERR_NO_NWFILTER:
raise |
<|file_name|>jquery.topUniversityFloatBox.js<|end_file_name|><|fim▁begin|>jQuery(function($){
var window_height = $(window).height();
var element_height = $("#top_university_float_box").height();
var window_scrollTop = $(window).scrollTop();
var ep = window_scrollTop + ( window_height - element_height) /2;
$("#top_university_float_box").stop().animate({
top: ep,
}, 1000, function() {
// Animation complete.
});
$(window).scroll(function(){
//alert("window scrolled");
var window_height = $(window).height();
var element_height = $("#top_university_float_box").height();
var window_scrollTop = $(window).scrollTop();
var ep = window_scrollTop + ( window_height - element_height) /2;
//alert(window_scrollTop);
$("#top_university_float_box").stop().animate({
top: ep,
}, 1000, function() {
// Animation complete.
});
});
//$("#top_university_float_box").
/*$(".has_menu").mouseover(function(){
if (!$(this).hasClass("menu_active")){
//$(".menu_body").slideUp();
$(".menu_body").hide();
$(".menu_title").css("background","transparent").removeClass("menu_active");
$(".menu_title").css("color","#000");
}
$(this).addClass("menu_active");
var id = $(this).attr('id');
var bd = id.replace("_title", "_body");
//$(this).css("background-color","#ff0");
if( id == "courses_title" )
$(this).css('background-color','#09f');
if( id == "students_title" )
$(this).css('background-color','#f90');
if( id == "useful_title" )
$(this).css('background-color','#c0f');
if( id == "about_title" )
$(this).css('background-color','#060');
if( id == "social_title" )
$(this).css('background-color','#c00');
//$(this).css('background-image','url(../img/menu_tab.jpg)');
//$(this).css('background-image','url(../img/menu_tab_gradient.jpg)');
//$(this).addClass("menu_title_over");
$(this).css("color","#fff");
//$(this).css("border-left","solid 1px #ff0");
$("#"+bd).show();<|fim▁hole|> $("#header, .info_block, #footer, #home_title,#top_banner").mouseover(function(){
$("#mask").hide();
$(".menu_title").css("background","transparent").removeClass("menu_active");
$(".menu_title").css("color","#000");
//$(".menu_body").slideUp(300);
$(".menu_body").hide();
});*/
});<|fim▁end|> | }); |
<|file_name|>test_sqlite_util.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from aq.sqlite_util import connect, create_table, insert_all
class TestSqliteUtil(TestCase):
def test_dict_adapter(self):
with connect(':memory:') as conn:
conn.execute('CREATE TABLE foo (foo)')
conn.execute('INSERT INTO foo (foo) VALUES (?)', ({'bar': 'blah'},))
values = conn.execute('SELECT * FROM foo').fetchone()
self.assertEqual(len(values), 1)
self.assertEqual(values[0], '{"bar": "blah"}')
def test_create_table(self):
with connect(':memory:') as conn:
create_table(conn, None, 'foo', ('col1', 'col2'))
tables = conn.execute("PRAGMA table_info(\'foo\')").fetchall()
self.assertEqual(len(tables), 2)
self.assertEqual(tables[0][1], 'col1')
self.assertEqual(tables[1][1], 'col2')
def test_insert_all(self):
class Foo(object):
def __init__(self, c1, c2):
self.c1 = c1
self.c2 = c2
columns = ('c1', 'c2')
values = (Foo(1, 2), Foo(3, 4))
with connect(':memory:') as conn:
create_table(conn, None, 'foo', columns)
insert_all(conn, None, 'foo', columns, values)
rows = conn.execute('SELECT * FROM foo').fetchall()
self.assertTrue((1, 2) in rows, '(1, 2) in rows')
self.assertTrue((3, 4) in rows, '(3, 4) in rows')
def test_json_get_field(self):
with connect(':memory:') as conn:<|fim▁hole|> def test_json_get_index(self):
with connect(':memory:') as conn:
json_obj = '[1, 2, 3]'
query = "select json_get('{0}', 1)".format(json_obj)
self.assertEqual(conn.execute(query).fetchone()[0], 2)
def test_json_get_field_nested(self):
with connect(':memory:') as conn:
json_obj = '{"foo": {"bar": "blah"}}'
query = "select json_get('{0}', 'foo')".format(json_obj)
self.assertEqual(conn.execute(query).fetchone()[0], '{"bar": "blah"}')
query = "select json_get(json_get('{0}', 'foo'), 'bar')".format(json_obj)
self.assertEqual(conn.execute(query).fetchone()[0], 'blah')
def test_json_get_field_of_null(self):
with connect(':memory:') as conn:
query = "select json_get(NULL, 'foo')"
self.assertEqual(conn.execute(query).fetchone()[0], None)
def test_json_get_field_of_serialized_null(self):
with connect(':memory:') as conn:
json_obj = 'null'
query = "select json_get('{0}', 'foo')".format(json_obj)
self.assertEqual(conn.execute(query).fetchone()[0], None)<|fim▁end|> | json_obj = '{"foo": "bar"}'
query = "select json_get('{0}', 'foo')".format(json_obj)
self.assertEqual(conn.execute(query).fetchone()[0], 'bar')
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import ipdb
# Print log messages only from the root process in parallel
parameters["std_out_all_processes"] = False;
# Load mesh from file
mesh = Mesh()
domain_vertices = [Point(1.0, -1.0),
Point(6.0, -1.0),
Point(6.0, 1.0),
Point(1.0, 1.0),
Point(1.0, 6.0),
Point(-1.0, 6.0),
Point(-1.0, 1.0),
Point(-6.0, 1.0),
Point(-6.0, -1.0),
Point(-1.0, -1.0),
Point(-1.0, -6.0),
Point(1.0, -6.0),
Point(1.0,-1.0),
Point(1.0, -1.0)]
# Generate mesh and plot
PolygonalMeshGenerator.generate(mesh, domain_vertices, 0.75);
cell_markers = CellFunction("bool", mesh)
cell_markers.set_all(False)
origin = Point(0.0, 0.0)
for cell in cells(mesh):
p = cell.midpoint()
# print p
if p.distance(origin) < 2:
cell_markers[cell] = True
mesh = refine(mesh, cell_markers)
cell_markers = CellFunction("bool", mesh)
cell_markers.set_all(False)
origin = Point(0.0, 0.0)
for cell in cells(mesh):
p = cell.midpoint()
# print p
if p.distance(origin) < 1:
cell_markers[cell] = True
mesh = refine(mesh, cell_markers)
class noflow1(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (-6.0,-1.0)) and near(x[0],1.0)
class noflow4(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (1.0, 6.0)) and near(x[0],1.0)
class noflow5(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (-6.0,-1.0)) and near(x[0],-1.0)
class noflow8(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (1.0, 6.0)) and near(x[0],-1.0)
class noflow2(SubDomain):
def inside(self, x, on_boundary):
return between(x[0], (1.0,6.0)) and near(x[1],-1.0)
class noflow3(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (1.0,6.0)) and near(x[1],1.0)
class noflow6(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (-6.0,-1.0)) and near(x[1],-1.0)
class noflow7(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (-6.0,-1.0)) and near(x[1],1.0)
Noflow1 = noflow1()
Noflow2 = noflow2()
Noflow3 = noflow3()
Noflow4 = noflow4()
Noflow5 = noflow5()
Noflow6 = noflow6()
Noflow7 = noflow7()
Noflow8 = noflow8()
class inflow1(SubDomain):
def inside(self, x, on_boundary):
return between(x[0], (-1.0,1.0)) and near(x[1],-6.0)
class inflow2(SubDomain):
def inside(self, x, on_boundary):
return between(x[0], (-1.0,1.0)) and near(x[1],6.0)
class outflow1(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (-1.0,1.0)) and near(x[0],6.0)
class outflow2(SubDomain):
def inside(self, x, on_boundary):
return between(x[1], (-1.0,1.0)) and near(x[0],-6.0)
boundaries = FacetFunction("size_t", mesh)
boundaries.set_all(0)
Noflow1.mark(boundaries, 1)
Noflow2.mark(boundaries, 1)
Noflow3.mark(boundaries, 1)
Noflow4.mark(boundaries, 1)
Noflow5.mark(boundaries, 1)
Noflow6.mark(boundaries, 1)
Noflow7.mark(boundaries, 1)
Noflow8.mark(boundaries, 1)
Inflow1 = inflow1()
Inflow2 = inflow2()
Outlow1 = outflow1()
Outlow2 = outflow2()
Inflow1.mark(boundaries, 2)
Inflow2.mark(boundaries, 2)
Outlow1.mark(boundaries, 3)
Outlow2.mark(boundaries, 3)
# Define function spaces (P2-P1)
V = VectorFunctionSpace(mesh, "CG", 2)
Q = FunctionSpace(mesh, "CG", 1)
# Define trial and test functions
u = TrialFunction(V)
p = TrialFunction(Q)
v = TestFunction(V)
q = TestFunction(Q)
# Set parameter values
dt = 0.01
T = 3
nu = 0.01
# Define time-dependent pressure boundary condition
p_in = Expression("-sin(3.0*t)", t=0.0)
p_in2 = Expression("sin(3.0*t)", t=0.0)
# Define boundary conditions
noslip = DirichletBC(V, (0, 0),boundaries,1)
inflow = DirichletBC(Q, p_in, boundaries,2)
outflow = DirichletBC(Q, p_in2, boundaries,3)
bcu = [noslip]
bcp = [inflow, outflow]
# Create functions
u0 = Function(V)
u1 = Function(V)
p1 = Function(Q)
# Define coefficients
k = Constant(dt)
f = Constant((0, 0))
# Tentative velocity step
F1 = (1/k)*inner(u - u0, v)*dx + inner(grad(u0)*u0, v)*dx + \
nu*inner(grad(u), grad(v))*dx - inner(f, v)*dx
a1 = lhs(F1)
L1 = rhs(F1)
# Pressure update
a2 = inner(grad(p), grad(q))*dx
L2 = -(1/k)*div(u1)*q*dx
# Velocity update
a3 = inner(u, v)*dx
L3 = inner(u1, v)*dx - k*inner(grad(p1), v)*dx
# Assemble matrices
A1 = assemble(a1)
A2 = assemble(a2)
A3 = assemble(a3)
# Use amg preconditioner if available
prec = "amg" if has_krylov_solver_preconditioner("amg") else "default"
# Create files for storing solution
ufile = File("results/velocity.pvd")
pfile = File("results/pressure.pvd")
# Time-stepping
t = dt
while t < T + DOLFIN_EPS:
# Update pressure boundary condition
p_in.t = t
# Compute tentative velocity step
begin("Computing tentative velocity")
b1 = assemble(L1)
[bc.apply(A1, b1) for bc in bcu]
solve(A1, u1.vector(), b1, "gmres", "default")
end()
# Pressure correction
begin("Computing pressure correction")
b2 = assemble(L2)
[bc.apply(A2, b2) for bc in bcp]
solve(A2, p1.vector(), b2, "gmres", prec)
end()
# Velocity correction
begin("Computing velocity correction")
b3 = assemble(L3)
[bc.apply(A3, b3) for bc in bcu]
solve(A3, u1.vector(), b3, "gmres", "default")
end()
# Plot solution
plot(p1, title="Pressure", rescale=True)
plot(u1, title="Velocity", scalarbar=True)
# Save to file
ufile << u1
pfile << p1
# Move to next time step
u0.assign(u1)
t += dt
print "t =", t
# Hold plot
interactive()<|fim▁end|> | from dolfin import * |
<|file_name|>fdt_test.py<|end_file_name|><|fim▁begin|># SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <[email protected]>
#
# Test for the fdt modules
import os
import sys
import tempfile
import unittest
from dtoc import fdt
from dtoc import fdt_util
from dtoc.fdt import FdtScan
from patman import tools
class TestFdt(unittest.TestCase):
@classmethod
def setUpClass(self):
self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
self._indir = tempfile.mkdtemp(prefix='binmant.')
tools.PrepareOutputDir(self._indir, True)
@classmethod
def tearDownClass(self):
tools._FinaliseForTest()
def TestFile(self, fname):
return os.path.join(self._binman_dir, 'test', fname)
def GetCompiled(self, fname):
return fdt_util.EnsureCompiled(self.TestFile(fname))
def _DeleteProp(self, dt):
node = dt.GetNode('/microcode/update@0')
node.DeleteProp('data')
def testFdtNormal(self):
fname = self.GetCompiled('034_x86_ucode.dts')
dt = FdtScan(fname)
self._DeleteProp(dt)
def testFdtNormalProp(self):
fname = self.GetCompiled('045_prop_test.dts')
dt = FdtScan(fname)
node = dt.GetNode('/binman/intel-me')
self.assertEquals('intel-me', node.name)
val = fdt_util.GetString(node, 'filename')
self.assertEquals(str, type(val))
self.assertEquals('me.bin', val)
prop = node.props['intval']
self.assertEquals(fdt.TYPE_INT, prop.type)
self.assertEquals(3, fdt_util.GetInt(node, 'intval'))
prop = node.props['intarray']
self.assertEquals(fdt.TYPE_INT, prop.type)
self.assertEquals(list, type(prop.value))
self.assertEquals(2, len(prop.value))
self.assertEquals([5, 6],
[fdt_util.fdt32_to_cpu(val) for val in prop.value])
prop = node.props['byteval']
self.assertEquals(fdt.TYPE_BYTE, prop.type)
self.assertEquals(chr(8), prop.value)
prop = node.props['bytearray']
self.assertEquals(fdt.TYPE_BYTE, prop.type)
self.assertEquals(list, type(prop.value))
self.assertEquals(str, type(prop.value[0]))
self.assertEquals(3, len(prop.value))
self.assertEquals([chr(1), '#', '4'], prop.value)
prop = node.props['longbytearray']
self.assertEquals(fdt.TYPE_INT, prop.type)
self.assertEquals(0x090a0b0c, fdt_util.GetInt(node, 'longbytearray'))
prop = node.props['stringval']
self.assertEquals(fdt.TYPE_STRING, prop.type)
self.assertEquals('message2', fdt_util.GetString(node, 'stringval'))
prop = node.props['stringarray']
self.assertEquals(fdt.TYPE_STRING, prop.type)
self.assertEquals(list, type(prop.value))
self.assertEquals(3, len(prop.value))<|fim▁hole|><|fim▁end|> | self.assertEquals(['another', 'multi-word', 'message'], prop.value) |
<|file_name|>URE_Model.java<|end_file_name|><|fim▁begin|>package jat.coreNOSA.gps;
/* JAT: Java Astrodynamics Toolkit
*
* Copyright (c) 2003 National Aeronautics and Space Administration. All rights reserved.
*
* This file is part of JAT. JAT is free software; you can
* redistribute it and/or modify it under the terms of the
* NASA Open Source Agreement
*
*
* 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
* NASA Open Source Agreement for more details.
*
* You should have received a copy of the NASA Open Source Agreement
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*
* File Created on Jun 20, 2003
*/
//import jat.gps.*;
import jat.coreNOSA.cm.Constants;
import jat.coreNOSA.cm.TwoBody;
import jat.coreNOSA.math.MatrixVector.data.Matrix;
import jat.coreNOSA.math.MatrixVector.data.RandomNumber;
import jat.coreNOSA.math.MatrixVector.data.VectorN;
/**
* <P>
* The URE_Model Class provides a model of the errors in the GPS system
* due to GPS SV ephemeris and clock errors. For this simulation, they
* are modeled as random constants with sigmas from:
*
* Reference: J. F. Zumberge and W. I. Bertiger, "Ephemeris and Clock
* Navigation Message Accuracy", Global Positioning System: Theory and
* Applications, Volume 1, edited by Parkinson and Spilker.
*
* @author
* @version 1.0
*/
public class URE_Model {
/** Radial ephemeris error sigma in meters */
private static final double sigma_r = 1.2;
/** Cross-track ephemeris error sigma in meters */
private static final double sigma_c = 3.2;
/** Along-track ephemeris error sigma in meters */
private static final double sigma_a = 4.5;
/** SV Clock error sigma in meters */
private static final double sigma_t = 1.12E-08 * Constants.c;
private static final double sigma_ure
= Math.sqrt(sigma_r*sigma_r + sigma_c*sigma_c + sigma_a*sigma_a + sigma_t*sigma_t);
public static final double correlationTime = 7200.0;
private double qbias;
private double q;
/** Radial ephemeris error vector, one entry per GPS SV */
private VectorN dr;
/** Crosstrack ephemeris error vector, one entry per GPS SV */
private VectorN dc;
/** Alongtrack ephemeris error vector, one entry per GPS SV */
private VectorN da;
/** SV Clock error vector, one entry per GPS SV */
private VectorN dtc;
/** Size of the GPS Constellation */
private int size;
/** Constructor
* @param n size of the GPS Constellation
*/
public URE_Model(int n) {
this.size = n;
dr = new VectorN(n);
dc = new VectorN(n);
da = new VectorN(n);
dtc = new VectorN(n);
RandomNumber rn = new RandomNumber();
for (int i = 0; i < n; i++) {
double radial = rn.normal(0.0, sigma_r);
dr.set(i, radial);
double crosstrack = rn.normal(0.0, sigma_c);
dc.set(i, crosstrack);
double alongtrack = rn.normal(0.0, sigma_a);
da.set(i, alongtrack);
double clock = rn.normal(0.0, sigma_t);
dtc.set(i, clock);
}
double dt = 1.0;
double exponent = -2.0*dt/correlationTime;
this.qbias = sigma_ure*sigma_ure*(1.0 - Math.exp(exponent)); // in (rad/sec)^2/Hz
this.q = 2.0 * sigma_ure*sigma_ure / correlationTime;
}
/** Constructor
* @param n size of the GPS Constellation
* @param seed long containing random number seed to be used
*/
public URE_Model(int n, long seed) {
this.size = n;
dr = new VectorN(n);
dc = new VectorN(n);
da = new VectorN(n);
dtc = new VectorN(n);
RandomNumber rn = new RandomNumber(seed);
for (int i = 0; i < n; i++) {
double radial = rn.normal(0.0, sigma_r);
dr.set(i, radial);
double crosstrack = rn.normal(0.0, sigma_c);
dc.set(i, crosstrack);
double alongtrack = rn.normal(0.0, sigma_a);
da.set(i, alongtrack);
double clock = rn.normal(0.0, sigma_t);
dtc.set(i, clock);
}
double dt = 1.0;
double exponent = -2.0*dt/correlationTime;
this.qbias = sigma_ure*sigma_ure*(1.0 - Math.exp(exponent)); // in (rad/sec)^2/Hz
this.q = 2.0 * sigma_ure*sigma_ure / correlationTime;
<|fim▁hole|> * @param los GPS line of sight vector
* @param rGPS GPS SV position vector
* @param vGPS GPS SV velocity vector
* @return the user range error in meters
*/
public double ure (int i, VectorN los, VectorN rGPS, VectorN vGPS) {
// get the transformation from RIC to ECI
TwoBody orbit = new TwoBody(Constants.GM_Earth, rGPS, vGPS);
Matrix rot = orbit.RSW2ECI();
// form the ephemeris error vector for the ith GPS SV
VectorN error = new VectorN(this.dr.x[i], this.da.x[i], this.dc.x[i]);
// rotate the ephemeris error to the ECI frame
VectorN errECI = rot.times(error);
// find the magnitude of the projection of the error vector onto the LOS vector
double drho = errECI.projectionMag(los);
// add the SV clock error
double out = drho + this.dtc.x[i];
return out;
}
/**
* Compute the derivatives for the URE state.
* The URE is modeled as a first order Gauss-Markov process.
* Used by GPS_INS Process Model.
* @param ure URE state vector
* @return the time derivative of the URE
*/
public VectorN ureProcess(VectorN ure) {
double coef = -1.0/correlationTime;
VectorN out = ure.times(coef);
return out;
}
/**
* Return the URE noise strength to be used in
* the process noise matrix Q.
* @return URE noise strength
*/
public double biasQ() {
return this.qbias;
}
/**
* Return the URE noise strength to be used in
* the process noise matrix Q.
* @return URE noise strength
*/
public double Q() {
return this.q;
}
/**
* Return the URE sigma
* @return URE sigma
*/
public double sigma() {
return sigma_ure;
}
}<|fim▁end|> | }
/** Compute the User range error due to SV clock and ephemeris errors.
* @param i GPS SV index |
<|file_name|>bitcoin_bs.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="bs" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About nopoolcoin</source>
<translation>About nopoolcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>nopoolcoin</b> version</source>
<translation><b>nopoolcoin</b> version</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The nopoolcoin developers</source>
<translation>The nopoolcoin developers</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Address Book</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Double-click to edit address or label</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Create a new address</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copy the currently selected address to the system clipboard</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&New Address</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your nopoolcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>These are your nopoolcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copy Address</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Show &QR Code</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a nopoolcoin address</source>
<translation>Sign a message to prove you own a nopoolcoin address</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Sign &Message</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Delete the currently selected address from the list</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Export the data in the current tab to a file</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified nopoolcoin address</source>
<translation>Verify a message to ensure it was signed with a specified nopoolcoin address</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Delete</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your nopoolcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>These are your nopoolcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copy &Label</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Edit</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Send &Coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Export Address Book Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(no label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Passphrase Dialog</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Enter passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>New passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repeat new passphrase</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>This operation needs your wallet passphrase to unlock the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Unlock wallet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>This operation needs your wallet passphrase to decrypt the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Change passphrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Enter the old and new passphrase to the wallet.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirm wallet encryption</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Are you sure you wish to encrypt your wallet?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Warning: The Caps Lock key is on!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Wallet encrypted</translation>
</message>
<message>
<location line="-56"/>
<source>nopoolcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your nopoolcoins from being stolen by malware infecting your computer.</source>
<translation>nopoolcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your nopoolcoins from being stolen by malware infecting your computer.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Wallet encryption failed</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>The supplied passphrases do not match.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Wallet unlock failed</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>The passphrase entered for the wallet decryption was incorrect.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Wallet decryption failed</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Wallet passphrase was successfully changed.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Sign &message...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronizing with network...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Overview</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Show general overview of wallet</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transactions</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Browse transaction history</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edit the list of stored addresses and labels</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Show the list of addresses for receiving payments</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>E&xit</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Quit application</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about nopoolcoin</source>
<translation>Show information about nopoolcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>About &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Show information about Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Options...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Encrypt Wallet...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup Wallet...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Change Passphrase...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importing blocks from disk...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Reindexing blocks on disk...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a nopoolcoin address</source>
<translation>Send coins to a nopoolcoin address</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for nopoolcoin</source>
<translation>Modify configuration options for nopoolcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Backup wallet to another location</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Change the passphrase used for wallet encryption</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debug window</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Open debugging and diagnostic console</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verify message...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>nopoolcoin</source>
<translation>nopoolcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Send</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Receive</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Addresses</translation>
</message>
<message>
<location line="+22"/>
<source>&About nopoolcoin</source>
<translation>&About nopoolcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Show / Hide</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Show or hide the main Window</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Encrypt the private keys that belong to your wallet</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your nopoolcoin addresses to prove you own them</source>
<translation>Sign messages with your nopoolcoin addresses to prove you own them</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified nopoolcoin addresses</source>
<translation>Verify messages to ensure they were signed with specified nopoolcoin addresses</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&File</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Settings</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Help</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Tabs toolbar</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>nopoolcoin client</source>
<translation>nopoolcoin client</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to nopoolcoin network</source>
<translation>
<numerusform>%n active connection to nopoolcoin network</numerusform>
<numerusform>%n active connections to nopoolcoin network</numerusform>
</translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>No block source available...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Processed %1 of %2 (estimated) blocks of transaction history.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Processed %1 blocks of transaction history.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation>
<numerusform>%n hour</numerusform>
<numerusform>%n hours</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation>
<numerusform>%n day</numerusform>
<numerusform>%n days</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation>
<numerusform>%n week</numerusform>
<numerusform>%n weeks</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 behind</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Last received block was generated %1 ago.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transactions after this will not yet be visible.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Up to date</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Catching up...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirm transaction fee</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sent transaction</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Incoming transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Date: %1
Amount: %2
Type: %3
Address: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI handling</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid nopoolcoin address or malformed URI parameters.</source>
<translation>URI can not be parsed! This can be caused by an invalid nopoolcoin address or malformed URI parameters.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>unlocked</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>locked</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. nopoolcoin can no longer continue safely and will quit.</source>
<translation>A fatal error occurred. nopoolcoin can no longer continue safely and will quit.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Network Alert</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Edit Address</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>The label associated with this address book entry</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Address</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>The address associated with this address book entry. This can only be modified for sending addresses.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>New receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>New sending address</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Edit receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Edit sending address</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>The entered address "%1" is already in the address book.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid nopoolcoin address.</source>
<translation>The entered address "%1" is not a valid nopoolcoin address.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Could not unlock wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>New key generation failed.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>nopoolcoin-Qt</source>
<translation>nopoolcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>command-line options</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI options</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Set language, for example "de_DE" (default: system locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start minimized</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Show splash screen on startup (default: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Options</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Main</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Pay transaction &fee</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start nopoolcoin after logging in to the system.</source>
<translation>Automatically start nopoolcoin after logging in to the system.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start nopoolcoin on system login</source>
<translation>&Start nopoolcoin on system login</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Reset all client options to default.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Reset Options</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Network</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the nopoolcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatically open the nopoolcoin client port on the router. This only works when your router supports UPnP and it is enabled.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Map port using &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the nopoolcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Connect to the nopoolcoin network through a SOCKS proxy (e.g. when connecting through Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Connect through SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP address of the proxy (e.g. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port of the proxy (e.g. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Version:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS version of the proxy (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Window</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Show only a tray icon after minimizing the window.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimize to the tray instead of the taskbar</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimize on close</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Display</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>User Interface &language:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting nopoolcoin.</source>
<translation>The user interface language can be set here. This setting will take effect after restarting nopoolcoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unit to show amounts in:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Choose the default subdivision unit to show in the interface and when sending coins.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show nopoolcoin addresses in the transaction list or not.</source>
<translation>Whether to show nopoolcoin addresses in the transaction list or not.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Display addresses in transaction list</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancel</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Apply</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>default</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirm options reset</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Some settings may require a client restart to take effect.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Do you want to proceed?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting nopoolcoin.</source>
<translation>This setting will take effect after restarting nopoolcoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>The supplied proxy address is invalid.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the nopoolcoin network after a connection is established, but this process has not completed yet.</source>
<translation>The displayed information may be out of date. Your wallet automatically synchronizes with the nopoolcoin network after a connection is established, but this process has not completed yet.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Unconfirmed:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Immature:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Mined balance that has not yet matured</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Recent transactions</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Your current balance</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>out of sync</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start nopoolcoin: click-to-pay handler</source>
<translation>Cannot start nopoolcoin: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Code Dialog</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Request Payment</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Amount:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Message:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Save As...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Error encoding URI into QR Code.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>The entered amount is invalid, please check.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulting URI too long, try to reduce the text for label / message.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Save QR Code</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Images (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Client name</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Client version</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Information</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Using OpenSSL version</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Startup time</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Network</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Number of connections</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>On testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Block chain</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Current number of blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Estimated total blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Last block time</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Command-line options</translation>
</message>
<message>
<location line="+7"/>
<source>Show the nopoolcoin-Qt help message to get a list with possible nopoolcoin command-line options.</source>
<translation>Show the nopoolcoin-Qt help message to get a list with possible nopoolcoin command-line options.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Show</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Build date</translation>
</message>
<message>
<location line="-104"/>
<source>nopoolcoin - Debug window</source>
<translation>nopoolcoin - Debug window</translation>
</message>
<message>
<location line="+25"/>
<source>nopoolcoin Core</source>
<translation>nopoolcoin Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug log file</translation>
</message>
<message>
<location line="+7"/>
<source>Open the nopoolcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Open the nopoolcoin debug log file from the current data directory. This can take a few seconds for large log files.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Clear console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the nopoolcoin RPC console.</source>
<translation>Welcome to the nopoolcoin RPC console.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Type <b>help</b> for an overview of available commands.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Send to multiple recipients at once</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Add &Recipient</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remove all transaction fields</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirm the send action</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirm send coins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Are you sure you want to send %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> and </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>The recipient address is not valid, please recheck.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>The amount to pay must be larger than 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>The amount exceeds your balance.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>The total exceeds your balance when the %1 transaction fee is included.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplicate address found, can only send to each address once per send operation.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Error: Transaction creation failed!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>A&mount:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Pay &To:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</source>
<translation>The address to send the payment to (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Enter a label for this address to add it to your address book</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Choose address from address book</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Remove this recipient</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a nopoolcoin address (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</source>
<translation>Enter a nopoolcoin address (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Sign / Verify a Message</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Sign Message</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</source>
<translation>The address to sign the message with (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Choose an address from the address book</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Enter the message you want to sign here</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Signature</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copy the current signature to the system clipboard</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this nopoolcoin address</source>
<translation>Sign the message to prove you own this nopoolcoin address</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Sign &Message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Reset all sign message fields</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</source>
<translation>The address the message was signed with (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified nopoolcoin address</source>
<translation>Verify the message to ensure it was signed with the specified nopoolcoin address</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verify &Message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Reset all verify message fields</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a nopoolcoin address (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</source>
<translation>Enter a nopoolcoin address (e.g. N7pJrLp6TVSs628wNL1qDE8gT7K9q23Kxe)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click "Sign Message" to generate signature</translation>
</message>
<message>
<location line="+3"/>
<source>Enter nopoolcoin signature</source>
<translation>Enter nopoolcoin signature</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>The entered address is invalid.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Please check the address and try again.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>The entered address does not refer to a key.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Wallet unlock was cancelled.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Private key for the entered address is not available.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Message signing failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Message signed.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>The signature could not be decoded.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Please check the signature and try again.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>The signature did not match the message digest.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Message verification failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Message verified.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The nopoolcoin developers</source>
<translation>The nopoolcoin developers</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/unconfirmed</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation>
<numerusform>, broadcast through %n node</numerusform>
<numerusform>, broadcast through %n nodes</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generated</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>From</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>To</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>own address</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>label</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation>
<numerusform>matures in %n more block</numerusform>
<numerusform>matures in %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>not accepted</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaction fee</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net amount</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comment</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaction ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug information</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>true</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>false</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, has not been successfully broadcast yet</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>unknown</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaction details</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>This pane shows a detailed description of the transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+3"/><|fim▁hole|> <source>Offline (%1 confirmations)</source>
<translation>Offline (%1 confirmations)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Unconfirmed (%1 of %2 confirmations)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmed (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation>
<numerusform>Mined balance will be available when it matures in %n more block</numerusform>
<numerusform>Mined balance will be available when it matures in %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>This block was not received by any other nodes and will probably not be accepted!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generated but not accepted</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Received from</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Payment to yourself</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaction status. Hover over this field to show number of confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date and time that the transaction was received.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Destination address of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Amount removed from or added to balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>All</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Today</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>This week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>This month</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Last month</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>This year</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Range...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>To yourself</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Other</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Enter address or label to search</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min amount</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copy address</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copy label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copy amount</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copy transaction ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edit label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Show transaction details</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Export Transaction Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmed</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Range:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>to</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Export the data in the current tab to a file</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Backup Wallet</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Wallet Data (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Backup Failed</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>There was an error trying to save the wallet data to the new location.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Backup Successful</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>The wallet data was successfully saved to the new location.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>nopoolcoin version</source>
<translation>nopoolcoin version</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or nopoolcoind</source>
<translation>Send command to -server or nopoolcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>List commands</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Get help for a command</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Options:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: nopoolcoin.conf)</source>
<translation>Specify configuration file (default: nopoolcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: nopoolcoind.pid)</source>
<translation>Specify pid file (default: nopoolcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Specify data directory</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Set database cache size in megabytes (default: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Listen for connections on <port> (default: 8333 or testnet: 18333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Maintain at most <n> connections to peers (default: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Connect to a node to retrieve peer addresses, and disconnect</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Specify your own public address</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Threshold for disconnecting misbehaving peers (default: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>An error occurred while setting up the RPC port %u for listening on IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accept command line and JSON-RPC commands</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Run in the background as a daemon and accept commands</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Use the test network</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accept connections from outside (default: 1 if no -proxy or -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=nopoolcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "nopoolcoin Alert" [email protected]
</source>
<translation>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=nopoolcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "nopoolcoin Alert" [email protected]
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Bind to given address and always listen on it. Use [host]:port notation for IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. nopoolcoin is probably already running.</source>
<translation>Cannot obtain a lock on data directory %s. nopoolcoin is probably already running.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Execute command when a relevant alert is received (%s in cmd is replaced by message)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong nopoolcoin will not work properly.</source>
<translation>Warning: Please check that your computer's date and time are correct! If your clock is wrong nopoolcoin will not work properly.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Attempt to recover private keys from a corrupt wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Block creation options:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Connect only to the specified node(s)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Corrupted block database detected</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Discover own IP address (default: 1 when listening and no -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Do you want to rebuild the block database now?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Error initializing block database</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Error initializing wallet database environment %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Error loading block database</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Error opening block database</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Error: Disk space is low!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Error: Wallet locked, unable to create transaction!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Error: system error: </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Failed to listen on any port. Use -listen=0 if you want this.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Failed to read block info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Failed to read block</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Failed to sync block index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Failed to write block index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Failed to write block info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Failed to write block</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Failed to write file info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Failed to write to coin database</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Failed to write transaction index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Failed to write undo data</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Find peers using DNS lookup (default: 1 unless -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Generate coins (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>How many blocks to check at startup (default: 288, 0 = all)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>How thorough the block verification is (0-4, default: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Not enough file descriptors available.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Rebuild block chain index from current blk000??.dat files</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Set the number of threads to service RPC calls (default: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verifying blocks...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifying wallet...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Imports blocks from external blk000??.dat file</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Invalid -tor address: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Invalid amount for -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Invalid amount for -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Maintain a full transaction index (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Only accept block chain matching built-in checkpoints (default: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Output extra debugging information. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Output extra network debugging information</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Prepend debug output with timestamp</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the nopoolcoin Wiki for SSL setup instructions)</source>
<translation>SSL options: (see the nopoolcoin Wiki for SSL setup instructions)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Select the version of socks proxy to use (4-5, default: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send trace/debug info to console instead of debug.log file</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Send trace/debug info to debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Set maximum block size in bytes (default: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Set minimum block size in bytes (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Shrink debug.log file on client startup (default: 1 when no -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Signing transaction failed</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specify connection timeout in milliseconds (default: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>System error: </translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Transaction amount too small</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Transaction amounts must be positive</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transaction too large</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Use UPnP to map the listening port (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Use UPnP to map the listening port (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Use proxy to reach tor hidden services (default: same as -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Username for JSON-RPC connections</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Warning: This version is obsolete, upgrade required!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>You need to rebuild the databases using -reindex to change -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupt, salvage failed</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Password for JSON-RPC connections</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Allow JSON-RPC connections from specified IP address</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send commands to node running on <ip> (default: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Execute command when the best block changes (%s in cmd is replaced by block hash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Upgrade wallet to latest format</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Set key pool size to <n> (default: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescan the block chain for missing wallet transactions</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Use OpenSSL (https) for JSON-RPC connections</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Server certificate file (default: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Server private key (default: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>This help message</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Unable to bind to %s on this computer (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Connect through socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Allow DNS lookups for -addnode, -seednode and -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Loading addresses...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error loading wallet.dat: Wallet corrupted</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of nopoolcoin</source>
<translation>Error loading wallet.dat: Wallet requires newer version of nopoolcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart nopoolcoin to complete</source>
<translation>Wallet needed to be rewritten: restart nopoolcoin to complete</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error loading wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Invalid -proxy address: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Unknown network specified in -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Unknown -socks proxy version requested: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Cannot resolve -bind address: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Cannot resolve -externalip address: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Invalid amount for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Invalid amount</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Insufficient funds</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Loading block index...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Add a node to connect to and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. nopoolcoin is probably already running.</source>
<translation>Unable to bind to %s on this computer. nopoolcoin is probably already running.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Fee per KB to add to transactions you send</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Loading wallet...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Cannot downgrade wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Cannot write default address</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Rescanning...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Done loading</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>To use the %s option</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>base.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
from collections import OrderedDict
from django.core.management.base import BaseCommand, CommandParser
from django.core.management.color import no_style<|fim▁hole|> parser.add_argument(
'--noinput',
action='store_false',
dest='interactive',
default=True,
help='Tells Django CMS to NOT prompt the user for input of any kind.'
)
# These are taking "as-is" from Django's management base
# management command.
parser.add_argument('-v', '--verbosity', action='store', dest='verbosity', default='1',
type=int, choices=[0, 1, 2, 3],
help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output')
parser.add_argument('--settings',
help=(
'The Python path to a settings module, e.g. '
'"myproject.settings.main". If this isn\'t provided, the '
'DJANGO_SETTINGS_MODULE environment variable will be used.'
),
)
parser.add_argument('--pythonpath',
help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".')
parser.add_argument('--traceback', action='store_true',
help='Raise on CommandError exceptions')
parser.add_argument('--no-color', action='store_true', dest='no_color', default=False,
help="Don't colorize the command output.")
class SubcommandsCommand(BaseCommand):
subcommands = OrderedDict()
instances = {}
help_string = ''
command_name = ''
subcommand_dest = 'subcmd'
def create_parser(self, prog_name, subcommand):
parser = CommandParser(
self,
prog="%s %s" % (os.path.basename(prog_name), subcommand),
description=self.help or None
)
self.add_arguments(parser)
return parser
def add_arguments(self, parser):
self.instances = {}
if self.subcommands:
subparsers = parser.add_subparsers(dest=self.subcommand_dest)
for command, cls in self.subcommands.items():
instance = cls(self.stdout._out, self.stderr._out)
instance.style = self.style
parser_sub = subparsers.add_parser(
cmd=self, name=instance.command_name, help=instance.help_string,
description=instance.help_string
)
add_builtin_arguments(parser=parser_sub)
instance.add_arguments(parser_sub)
self.instances[command] = instance
def handle(self, *args, **options):
if options[self.subcommand_dest] in self.instances:
command = self.instances[options[self.subcommand_dest]]
if options.get('no_color'):
command.style = no_style()
command.stderr.style_func = None
if options.get('stdout'):
command.stdout._out = options.get('stdout')
if options.get('stderr'):
command.stderr._out = options.get('stderr')
command.handle(*args, **options)
else:
self.print_help('manage.py', 'cms')<|fim▁end|> |
def add_builtin_arguments(parser): |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../'))
import pyrotrfid
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyrotrfid'
copyright = u'GLP3'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = pyrotrfid.__version__
# The full version, including alpha/beta/rc tags.
release = pyrotrfid.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'rtd'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["themes"]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = project + " v" + release
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = 'logo.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'logo.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {'**': 'links.html'}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
<|fim▁hole|># If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = False
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pyrotrfiddoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [('index', 'pyrotrfid.tex', u'pyrotrfid Documentation', u'', 'manual')]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [('index', 'pyrotrfid', u'pyrotrfid Documentation', [u''], 1)]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('http://docs.python.org/', None)}<|fim▁end|> | # If false, no module index is generated.
#html_domain_indices = True
|
<|file_name|>AssetRegistry.js<|end_file_name|><|fim▁begin|>sap.ui.define(['exports', './asset-registries/i18n', './asset-registries/LocaleData', './asset-registries/Themes', './asset-registries/Icons'], function (exports, i18n, LocaleData, Themes, Icons) { 'use strict';<|fim▁hole|>
exports.registerI18nLoader = i18n.registerI18nLoader;
exports.registerLocaleDataLoader = LocaleData.registerLocaleDataLoader;
exports.registerThemePropertiesLoader = Themes.registerThemePropertiesLoader;
exports.registerIconLoader = Icons.registerIconLoader;
Object.defineProperty(exports, '__esModule', { value: true });
});<|fim▁end|> | |
<|file_name|>HTMLElement.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>
try:
from io import StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import bs4 as BeautifulSoup
import logging
from thug.DOM.W3C.Element import Element
from thug.DOM.W3C.Style.CSS.ElementCSSInlineStyle import ElementCSSInlineStyle
from .attr_property import attr_property
log = logging.getLogger("Thug")
class HTMLElement(Element, ElementCSSInlineStyle):
id = attr_property("id")
title = attr_property("title")
lang = attr_property("lang")
dir = attr_property("dir")
className = attr_property("class", default = "")
def __init__(self, doc, tag):
Element.__init__(self, doc, tag)
ElementCSSInlineStyle.__init__(self, doc, tag)
def getInnerHTML(self):
if not self.hasChildNodes():
return ""
html = StringIO()
for tag in self.tag.contents:
html.write(unicode(tag))
return html.getvalue()
def setInnerHTML(self, html):
self.tag.clear()
soup = BeautifulSoup.BeautifulSoup(html, "html5lib")
for node in list(soup.head.descendants):
self.tag.append(node)
name = getattr(node, 'name', None)
if name is None:
continue
handler = getattr(log.DFT, 'handle_%s' % (name, ), None)
if handler:
handler(node)
for node in list(soup.body.children):
self.tag.append(node)
name = getattr(node, 'name', None)
if name is None:
continue
handler = getattr(log.DFT, 'handle_%s' % (name, ), None)
if handler:
handler(node)
# soup.head.unwrap()
# soup.body.unwrap()
# soup.html.wrap(self.tag)
# self.tag.html.unwrap()
for node in self.tag.descendants:
name = getattr(node, 'name', None)
if not name:
continue
p = getattr(self.doc.window.doc.DFT, 'handle_%s' % (name, ), None)
if p is None:
p = getattr(log.DFT, 'handle_%s' % (name, ), None)
if p:
p(node)
innerHTML = property(getInnerHTML, setInnerHTML)
# WARNING: NOT DEFINED IN W3C SPECS!
def focus(self):
pass
@property
def sourceIndex(self):
return None<|fim▁end|> | |
<|file_name|>ApplicationCustomizersService.ts<|end_file_name|><|fim▁begin|>import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/user-custom-actions";
import { ISearchQuery } from "@pnp/sp/search";
import { Web } from "@pnp/sp/webs";
export default class ApplicationCustomizersService {
/**
* fetchAllApplictionCustomizers
*/
public fetchAllApplictionCustomizers = async (webURL: string) => {
let web = Web(webURL);
let response;
try {
response = await web.userCustomActions();
console.log(response);
//let temp = await sp.site.userCustomActions();
//console.log(temp);
} catch (error) {
console.log(error);
response = error;
}
return response;
}
/**
* getAllSiteCollection
*/
public getAllSiteCollection = async () => {
let response;
try {
response = await sp.search(<ISearchQuery>{
Querytext: "contentclass:STS_Site",
SelectProperties: ["Title", "SPSiteUrl", "WebTemplate"],
RowLimit: 1000,
TrimDuplicates: true
});
console.log(response.PrimarySearchResults);
} catch (error) {
console.log(error);
response = error;
}
return response;
}
/**
* updateApplicationCustomizer
*/
public updateApplicationCustomizer = async (webURL: string | number, selectedID: string, updateJSON: any) => {
let web = Web(webURL as string);
let response;
try {
response = await web.userCustomActions.getById(selectedID).update(updateJSON);<|fim▁hole|> console.log(error);
}
}
}<|fim▁end|> | } catch (error) { |
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {<|fim▁hole|> }
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if not first_name.isalpha():
raise forms.ValidationError("Introdu un prenume valid")
return first_name
def clean_email(self):
email = self.cleaned_data['email']
if validate_email(email):
raise forms.ValidationError("Adresa de email nu e valida")
return email
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if not last_name.isalpha():
raise forms.ValidationError("Introdu un nume corect")
return last_name
def clean_message(self):
message = self.cleaned_data['message']
if len(message) < 50:
raise forms.ValidationError(
"Mesajul tau e prea scurt!"
"Trebuie sa contina minim 50 de caractere")
return message<|fim▁end|> | 'email': forms.EmailInput({'required': 'required',
'placeholder': 'Email'}),
'message': forms.Textarea(attrs={'required': 'required',
'placeholder': 'Message'}) |
<|file_name|>index.events.js<|end_file_name|><|fim▁begin|><|fim▁hole|>
bus.registerEvent([
{
kind: 'event',
type: 'connector.telegram.started',
toString: (ev) => `${ev.service}: bots webhooks: ${Object.entries(ev.bots).map(([botName, bot]) => `\n\t${botName} (${bot.ref}): ${bot.webhook}`)}`,
},
]);
})<|fim▁end|> | import {VType, validateEventFactory, BaseEvent} from '../../common/events'
import oncePerServices from '../../common/services/oncePerServices'
export default oncePerServices(function defineEvents({bus = missingService('bus')}) { |
<|file_name|>200-ensure-low-loadavg.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
# Exits with exit code 0 (i.e., allows sleep) if all load averages
# (1, 5, 15 minutes) are below ``MAX_IDLE_LOAD``.
from os import getloadavg
MAX_IDLE_LOAD = .09
def check_load(time_span, load):
if load > MAX_IDLE_LOAD:
print(
" Won't sleep because %i minute load average" % time_span,
"of %.2f is above threshold of %.2f." % (load, MAX_IDLE_LOAD)
)
exit(1)
loads = getloadavg()
check_load(1, loads[0])
check_load(5, loads[1])
check_load(15, loads[2])<|fim▁end|> | #!/usr/bin/env python3 |
<|file_name|>vec.rs<|end_file_name|><|fim▁begin|>//! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// double-drop.
struct NoDropVec<T> {
inner: Vec<T>,
}
impl<T> Drop for NoDropVec<T> {
fn drop(&mut self) {
unsafe { self.inner.set_len(0) }
}
}
// required by Arc. VecSplit/Iter never actually uses the data in the vector
// except to move out of it, and it never aliases.
unsafe impl<T: Send> Sync for NoDropVec<T> {}
/// The iterator which `VecSplit<T>` will turn when done splitting.
pub struct Iter<T> {
_items: Arc<NoDropVec<T>>,
cur: *mut T,<|fim▁hole|> type Item = T;
fn next(&mut self) -> Option<T> {
if self.cur == self.end {
None
} else {
let item = unsafe { ptr::read(self.cur) };
self.cur = unsafe { self.cur.offset(1) };
Some(item)
}
}
}
// drop all the remaining items, just to be nice.
impl<T> Drop for Iter<T> {
fn drop(&mut self) {
while let Some(_) = self.next() {}
}
}
/// A `Spliterator` for vectors.
pub struct VecSplit<T> {
// keeps the data alive until it is consumed.
items: Arc<NoDropVec<T>>,
start: usize,
len: usize,
}
impl<T> IntoIterator for VecSplit<T> {
type IntoIter = Iter<T>;
type Item = T;
fn into_iter(self) -> Self::IntoIter {
let cur_ptr = unsafe { self.items.inner.as_ptr().offset(self.start as isize) };
let end_ptr = unsafe { cur_ptr.offset(self.len as isize) };
Iter {
_items: self.items,
cur: cur_ptr as *mut T,
end: end_ptr as *mut T,
}
}
}
impl<T: Send> Split for VecSplit<T> {
fn should_split(&self, mul: f32) -> Option<usize> {
if self.len > 1 && (self.len as f32 *mul) > 4096.0 { Some(self.len / 2) }
else { None }
}
fn split(self, mut idx: usize) -> (Self, Self) {
if idx > self.len { idx = self.len }
(
VecSplit { items: self.items.clone(), start: self.start, len: idx},
VecSplit { items: self.items, start: self.start + idx, len: self.len - idx }
)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<T: Send> ExactSizeSpliterator for VecSplit<T> {
fn size(&self) -> usize {
self.len
}
}
impl<T: Send> IntoSpliterator for Vec<T> {
type Item = T;
type SplitIter = VecSplit<T>;
fn into_split_iter(self) -> VecSplit<T> {
let len = self.len();
VecSplit {
items: Arc::new(NoDropVec { inner: self }),
start: 0,
len: len,
}
}
}
#[cfg(test)]
mod tests {
use ::{IntoSpliterator, Spliterator, make_pool};
#[test]
fn it_works() {
let mut pool = make_pool(4).unwrap();
let v: Vec<_> = (0..10000).collect();
let doubled: Vec<_> = v.into_split_iter().map(|x| x * 2).collect(&pool.spawner());
assert_eq!(doubled, (0..10000).map(|x| x*2).collect::<Vec<_>>());
}
}<|fim▁end|> | end: *mut T,
}
impl<T> Iterator for Iter<T> { |
<|file_name|>a_very_big_sum_test.go<|end_file_name|><|fim▁begin|>package averybigsum
import (
"testing"
)
func TestExample(t *testing.T) {
ar := []int32{1000000001, 1000000002, 1000000003, 1000000004, 1000000005}
result := AVeryBigSum(ar)
if result != 5000000015 {<|fim▁hole|><|fim▁end|> | t.Errorf("AVeryBigSum failed the example test")
}
} |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
responses
=========
A utility library for mocking out the `requests` Python library.
:copyright: (c) 2013 Dropbox, Inc.
"""
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
setup_requires = []
if 'test' in sys.argv:
setup_requires.append('pytest')
install_requires = [
'requests',
'mock',
'six',
]
tests_require = [
'pytest',
'pytest-cov',
'flake8',
]
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['test_responses.py']
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
<|fim▁hole|> description=(
'A utility library for mocking out the `requests` Python library.'
),
long_description=open('README.rst').read(),
py_modules=['responses'],
zip_safe=False,
install_requires=install_requires,
extras_require={
'tests': tests_require,
},
tests_require=tests_require,
setup_requires=setup_requires,
cmdclass={'test': PyTest},
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)<|fim▁end|> | setup(
name='responses',
version='0.2.2',
author='David Cramer', |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(
template_name='pages/home.html'), name="home"),
url(r'^about/$',
TemplateView.as_view(template_name='pages/about.html'), name="about"),
# Django Admin
#url(r'^admin/', include(admin.site.urls)),
# User management
url(r'^users/', include("TestYourProject.users.urls", namespace="users")),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
url(r'^api-auth/', include(
'rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include('core.api', namespace='api')),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration', include('rest_auth.registration.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', 'django.views.defaults.bad_request'),<|fim▁hole|> url(r'^404/$', 'django.views.defaults.page_not_found'),
url(r'^500/$', 'django.views.defaults.server_error'),
]<|fim▁end|> | url(r'^403/$', 'django.views.defaults.permission_denied'), |
<|file_name|>oneshot.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: uint = 0; // initial state: no data, no blocked receiver
const DATA: uint = 1; // data ready for receiver to take
const DISCONNECTED: uint = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send + 'static> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED => {
Err(self.data.take().unwrap())
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_uint() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst) != EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_uint(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),<|fim▁hole|>
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_uint(ptr) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_uint(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_uint(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send + 'static> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}<|fim▁end|> | None => unreachable!(),
}
} |
<|file_name|>build.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna 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 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
fn main() {
let target = std::env::var("TARGET").unwrap();
if target.ends_with("-apple-darwin") {
println!("cargo:rustc-link-search=framework=/Library/Frameworks");
}
}<|fim▁end|> | |
<|file_name|>old_serialize.py<|end_file_name|><|fim▁begin|># Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, 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. 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.
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict # Python 2.6
import json
class Serializer(object):
DEFAULT_ENCODING = 'utf-8'
def serialize_to_request(self, parameters, operation_model):
# Don't serialize any parameter with a None value.
filtered_parameters = OrderedDict(
(k, v) for k, v in parameters.items() if v is not None)
serialized = {}
# serialized['method'] = operation_model.http['method']
# serialized['headers'] = {'Content-Type': 'application/json'}
# serialized['url_path'] = operation_model.http['requestUri']
serialized_body = OrderedDict()
if len(filtered_parameters) != 0:
self._serialize(serialized_body, filtered_parameters, None)
serialized['body'] = json.dumps(serialized_body).encode(self.DEFAULT_ENCODING)
return serialized
def _serialize(self, serialized, value, shape, key=None):
# serialize_method_name = '_serialize_type_%s' % shape.type_name
# method = getattr(self, serialize_method_name, self._default_serialize)
self._default_serialize(serialized, value, shape, key)
def _serialize_type_object(self, serialized, value, shape, key):
if key is not None:
# If a key is provided, this is a result of a recursive call, so we
# need to add a new child dict as the value of the passed in dict.
# Below we will add all the structure members to the new serialized
# dictionary we just created.
serialized[key] = OrderedDict()
serialized = serialized[key]
for member_key, member_value in value.items():
member_shape = shape.members[member_key]
self._serialize(serialized, member_value, member_shape, member_key)
def _serialize_type_array(self, serialized, value, shape, key):
array_obj = []
serialized[key] = array_obj
for array_item in value:<|fim▁hole|> # wrapper dict to serialize each list item before appending it to
# the serialized list.
self._serialize(wrapper, array_item, shape.member, "__current__")
array_obj.append(wrapper["__current__"])
def _default_serialize(self, serialized, value, shape, key):
if key:
serialized[key] = value
else:
for member_key, member_value in value.items():
serialized[member_key] = member_value<|fim▁end|> | wrapper = {}
# JSON list serialization is the only case where we aren't setting
# a key on a dict. We handle this by using a __current__ key on a |
<|file_name|>gateway.py<|end_file_name|><|fim▁begin|>import twe_lite
import json
import queue
import sys
import time
import traceback
import yaml
from threading import Thread
from datetime import datetime
from pytz import timezone
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult, IoTHubClientStatus
from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError, DeviceMethodReturnValue
SECRETS_FILE_NAME = "secrets.yml"
DEFAULT_PORT_NAME = '/dev/ttyUSB0'
TIME_ZONE = timezone('Asia/Tokyo')
def print_usage():
print('Usage: python gateway.py DEVICE_ID [SERIAL_PORT_NAME]')
print("if SERIAL_PORT_NAME is omitted, port name is '/dev/ttyUSB0' by default")
secrets = None
with open(SECRETS_FILE_NAME, 'r') as f:
secrets = yaml.load(f)
device_id = None
port_name = DEFAULT_PORT_NAME
if len(sys.argv) == 2:
device_id = sys.argv[1]
elif len(sys.argv) == 3:
device_id = sys.argv[1]
port_name = sys.argv[2]
else:
print_usage()
sys.exit(1)
print("Device ID: " + device_id)
print("Port name: " + port_name)
continues = True
class MonoStickTread(Thread):
def __init__(self, mono_stick, parser, queue):
super().__init__()
self.__mono_stick = mono_stick
self.__parser = parser
self.__queue = queue
def run(self):
print("Start reading data from monostick.")
while continues:
try:
data = mono_stick.read_line()
if len(data) == 0:
continue
print('Data: {0}'.format(data))
received_message = self.__parser.parse(data)
self.__queue.put(received_message, timeout=0.1)
except queue.Full as _:
print('Message queue is full')
except twe_lite.InvalidMessageFormatError as e:
print(traceback.format_exc())
class SendMessageThread(Thread):
def __init__(self, iothub_client, queue):
super().__init__()
self.__iothub_client = iothub_client
self.__queue = queue
def run(self):
print("Start sending data to Azure IoT Hub.")
while continues:
try:
try:
status_notification_message = self.__queue.get(timeout=0.1)
except queue.Empty as _:
continue
self.__queue.task_done()
print(str(status_notification_message))
if not status_notification_message.di1.changed:
continue
if status_notification_message.di1.state == twe_lite.DigitalPinState.HIGH:
continue
self.__send_message()
except IoTHubError as iothub_error:
print("Unexpected error %s from IoTHub" % iothub_error)
time.sleep(1)
except Exception as e:
print(traceback.format_exc())
def __send_message(self):
detected_json = self.__make_detected_json()
sending_message = IoTHubMessage(bytearray(detected_json, 'utf8'))
self.__iothub_client.send_event_async(sending_message, self.__event_confirmation_callback, None)
while True:
<|fim▁hole|>
def __event_confirmation_callback(self, message, result, _):
print("Confirmation received for message with result = %s" % (result))
def __make_detected_json(self):
now = datetime.now(TIME_ZONE)
return json.dumps({
'MessageType': 'DeviceEvent',
'DeviceId': device_id,
'EventType': 'HumanDetected',
'EventTime': now.isoformat()
})
def iothub_client_init():
connection_string = secrets['iothub']['connection_string']
client = IoTHubClient(connection_string, IoTHubTransportProvider.MQTT)
client.set_option("messageTimeout", 10000)
client.set_option("logtrace", 0)
client.set_option("product_info", "TweLiteGateway")
return client
with twe_lite.MonoStick(port_name, 0.1, 0.1) as mono_stick:
client = iothub_client_init()
parser = twe_lite.Parser()
message_queue = queue.Queue()
threads = []
try:
threads.append(MonoStickTread(mono_stick, parser, message_queue))
threads.append(SendMessageThread(client, message_queue))
for thread in threads:
thread.start()
while continues:
print("Quit if 'q is entered.")
c = input()
if c == 'q':
continues = False
break
finally:
for thread in threads:
thread.join()
sys.exit(0)<|fim▁end|> | status = self.__iothub_client.get_send_status()
if status == IoTHubClientStatus.IDLE:
break
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import locale
from collections import OrderedDict
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from pootle.core.cache import make_method_key
from pootle.core.mixins import TreeItem
from pootle.core.url_helpers import get_editor_filter
from pootle.i18n.gettext import tr_lang, language_dir
class LanguageManager(models.Manager):
def get_queryset(self):
"""Mimics `select_related(depth=1)` behavior. Pending review."""
return (
super(LanguageManager, self).get_queryset().select_related(
'directory',
)
)
class LiveLanguageManager(models.Manager):
"""Manager that only considers `live` languages.
A live language is any language containing at least a project with
translatable files.
"""
def get_queryset(self):
return super(LiveLanguageManager, self).get_queryset().filter(
translationproject__isnull=False,
project__isnull=True,
).distinct()
def cached_dict(self, locale_code='en-us'):
"""Retrieves a sorted list of live language codes and names.
:param locale_code: the UI locale for which language full names need to
be localized.
:return: an `OrderedDict`
"""
key = make_method_key(self, 'cached_dict', locale_code)
languages = cache.get(key, None)
if languages is None:
languages = OrderedDict(
sorted([(lang[0], tr_lang(lang[1]))
for lang in self.values_list('code', 'fullname')],
cmp=locale.strcoll,
key=lambda x: x[1])
)
cache.set(key, languages, settings.POOTLE_CACHE_TIMEOUT)
return languages
class Language(models.Model, TreeItem):
code_help_text = _('ISO 639 language code for the language, possibly '
'followed by an underscore (_) and an ISO 3166 country code. '
'<a href="http://www.w3.org/International/articles/language-tags/">'
'More information</a>')
code = models.CharField(max_length=50, null=False, unique=True,
db_index=True, verbose_name=_("Code"), help_text=code_help_text)
fullname = models.CharField(max_length=255, null=False,
verbose_name=_("Full Name"))
specialchars_help_text = _('Enter any special characters that users '
'might find difficult to type')
specialchars = models.CharField(max_length=255, blank=True,
verbose_name=_("Special Characters"),
help_text=specialchars_help_text)
plurals_help_text = _('For more information, visit '
'<a href="http://docs.translatehouse.org/projects/'
'localization-guide/en/latest/l10n/pluralforms.html">'
'our page</a> on plural forms.')
nplural_choices = (
(0, _('Unknown')), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)
)
nplurals = models.SmallIntegerField(default=0, choices=nplural_choices,
verbose_name=_("Number of Plurals"), help_text=plurals_help_text)
pluralequation = models.CharField(max_length=255, blank=True,
verbose_name=_("Plural Equation"), help_text=plurals_help_text)
directory = models.OneToOneField('pootle_app.Directory', db_index=True,
editable=False)
objects = LanguageManager()
live = LiveLanguageManager()
class Meta:
ordering = ['code']
db_table = 'pootle_app_language'
############################ Properties ###################################
@property
def pootle_path(self):
return '/%s/' % self.code
@property
def name(self):
"""Localized fullname for the language."""
return tr_lang(self.fullname)
############################ Methods ######################################
@property
def direction(self):
"""Return the language direction."""
return language_dir(self.code)
def __unicode__(self):
return u"%s - %s" % (self.name, self.code)
def __init__(self, *args, **kwargs):
super(Language, self).__init__(*args, **kwargs)
def __repr__(self):
return u'<%s: %s>' % (self.__class__.__name__, self.fullname)
def save(self, *args, **kwargs):
# create corresponding directory object
from pootle_app.models.directory import Directory
self.directory = Directory.objects.root.get_or_make_subdir(self.code)
super(Language, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
directory = self.directory
super(Language, self).delete(*args, **kwargs)
directory.delete()
def get_absolute_url(self):
return reverse('pootle-language-browse', args=[self.code])
def get_translate_url(self, **kwargs):
return u''.join([
reverse('pootle-language-translate', args=[self.code]),
get_editor_filter(**kwargs),
])<|fim▁hole|> super(Language, self).clean()
if self.fullname:
self.fullname = self.fullname.strip()
### TreeItem
def get_children(self):
return self.translationproject_set.live()
def get_cachekey(self):
return self.directory.pootle_path
### /TreeItem
@receiver([post_delete, post_save])
def invalidate_language_list_cache(sender, instance, **kwargs):
# XXX: maybe use custom signals or simple function calls?
if instance.__class__.__name__ not in ['Language', 'TranslationProject']:
return
key = make_method_key('LiveLanguageManager', 'cached_dict', '*')
cache.delete_pattern(key)<|fim▁end|> |
def clean(self): |
<|file_name|>gregorian.js<|end_file_name|><|fim▁begin|>define(
"dojo/cldr/nls/en-ie/gregorian", //begin v1.x content
{
"dateFormatItem-Md": "d/M",
"dateFormatItem-yMEd": "EEE, d/M/yyyy",
"timeFormat-full": "HH:mm:ss zzzz",<|fim▁hole|> "dateFormat-medium": "d MMM y",
"dateFormatItem-MMdd": "dd/MM",
"dateFormatItem-yyyyMM": "MM/yyyy",
"dateFormat-full": "EEEE d MMMM y",
"timeFormat-long": "HH:mm:ss z",
"dayPeriods-format-wide-am": "a.m.",
"timeFormat-short": "HH:mm",
"dateFormat-short": "dd/MM/yyyy",
"dateFormatItem-MMMMd": "d MMMM",
"dayPeriods-format-wide-pm": "p.m.",
"dateFormat-long": "d MMMM y"
}
//end v1.x content
);<|fim▁end|> | "timeFormat-medium": "HH:mm:ss",
"dateFormatItem-yyyyMMMM": "MMMM y",
"dateFormatItem-MEd": "E, d/M", |
<|file_name|>pager.rs<|end_file_name|><|fim▁begin|>// SPDX-License-Identifier: Unlicense
//! Interface for paging functions.
use crate::pager::{
Attributes, FixedOffset, FrameAllocator, PhysAddr, PhysAddrRange, Translate, VirtAddr,
VirtAddrRange,
};
use crate::util::locked::Locked;
use crate::Result;<|fim▁hole|>
use core::any::Any;
/// Each architecture must supply the following entry points for paging..
pub trait PagerTrait {
/// Physical address range of ram
fn ram_range() -> PhysAddrRange;
/// Base virtual address of kernel address space
fn kernel_base() -> VirtAddr;
/// Kernel offset on boot
fn kernel_offset() -> FixedOffset;
/// Kernel boot image
fn boot_image() -> PhysAddrRange;
/// Kernel code
fn text_image() -> PhysAddrRange;
/// Kernel read-only data
fn static_image() -> PhysAddrRange;
/// Kernel zero-initialised
fn bss_image() -> PhysAddrRange;
/// Kernel dynamic data (includes bss)
fn data_image() -> PhysAddrRange;
/// Kernel reset stack
fn stack_range() -> PhysAddrRange;
/// Initialise virtual memory management.
fn pager_init() -> Result<()>;
/// Enable virtual memory management.
fn enable_paging(page_directory: &impl PageDirectory) -> Result<()>;
/// Move the stack pointer and branch
fn move_stack(stack_pointer: VirtAddr, next: fn() -> !) -> !;
}
/// Methods to maintain a directory of virtual to physical addresses.
pub trait PageDirectory {
/// Enable downshift to arch-specific concrete page directories.
fn as_any(&self) -> &dyn Any;
/// Map physical address range at offset.
fn map_translation(
&mut self,
virt_addr_range: VirtAddrRange,
translation: impl Translate + core::fmt::Debug,
attributes: Attributes,
allocator: &Locked<impl FrameAllocator>,
mem_access_translation: &impl Translate,
) -> Result<VirtAddrRange>;
/// Return the current physical address for a virtual address
fn maps_to(
&self,
virt_addr: VirtAddr,
mem_access_translation: &FixedOffset,
) -> Result<PhysAddr>;
/// Unmap a previously mapped range, and return any memory to the allocator.
fn unmap(
&mut self,
virt_addr_range: VirtAddrRange,
allocator: &'static Locked<impl FrameAllocator>,
mem_access_translation: &FixedOffset,
) -> Result<()>;
/// Log the state of the page directory at debug.
fn dump(&self, mem_access_translation: &impl Translate);
}
/// Construct an empty page directory.
/// TODO: Should this be in Arch trait? limitation of generics in traits right now.
pub fn new_page_directory() -> impl PageDirectory {
super::arch::new_page_directory()
}<|fim▁end|> | |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
import sqlite3
import os, sys, time, datetime, random, string
import urllib.request, urllib.error
import configparser
from flask import Flask, request, session, redirect
from flask import render_template, g, flash, url_for
from contextlib import closing
from .modules import Pagi
from pxeat import app
from config import *
def prt_help():
print("To start the service:\n\n\t" + sys.argv[0] + " server\n")
print("Listen to \"localhost:5000\" by default, \nDeploy on production (Apache, Nginx...) with \"pxeat.wsgi\"")
def chk_args():
if len(sys.argv) == 2:
if sys.argv[1] == 'server':
if not os.path.isfile(DATABASE):
print("Database is not available!\nCreate with --initdb")
sys.exit()
if not os.path.isfile(PXE_FILE):
print("PXE file is not available!\nPlease check the configuration")
sys.exit()
if not os.path.isfile("./config.py"):
print("PXEAT Config file is missing!")
sys.exit()
elif sys.argv[1] == '--initdb':
init_db()
else:
prt_help()
sys.exit()
else:
prt_help()
sys.exit()
# Defaults
items_num = int(ITEMS_NUM)
form_default = ["", \
"http://", \
REPO_KERNEL_DEFAULT, \
REPO_INITRD_DEFAULT, \
"def", \
""]
loader_dir = TFTP_ROOT + LOADER_PATH
postfix_kernelfn = '-0'
postfix_initrdfn = '-1'
items = {}
def chk_input(chk_string, chk_type):
if chk_type == 'pxe_title':
if chk_string == '':
raise ValueError("The title can not be empty!")
return
elif chk_type == 'file_path':
if chk_string[0] != '/' or chk_string[-1] == '/':
raise ValueError("Path format is invalid!")
return
elif chk_type == 'repo_url':
chk_elements = chk_string.split('//')
if chk_elements[1] == '':
raise ValueError("The repository can not be empty!")
return
elif chk_elements[0] not in ['http:','https:']:
raise ValueError("Invalid format!"+\
" (Only support http:// or https://)")
return
else:
sys.exit("chk_type error!")
def grab_file(base_url, file_path, saved_file):
errmsg0 = "<br />Something wrong, please contact the administrator."
errmsg1 = "<br />Something wrong, please check the repository link \
and kernel/initrd file path."
dbginfo_local = "Debug info: Configuration error! \
Failed to open/write local kernel&initrd file. \
Check your \'LOADER_PATH\' setting in config file. \
Make sure the path exist and you have permission to write.\n\
Current path: " + saved_file
file_url = base_url + file_path
try:
f = urllib.request.urlopen(file_url)
except urllib.error.HTTPError as e:
return str(e.code) + " " + str(e.reason) + str(errmsg1)
except:
return str(errmsg0)
try:
local_file = open(saved_file, "wb")
local_file.write(f.read())
except:
print(dbginfo_local)
return str(errmsg0)
local_file.close()
def boot_opts_gen(opt_flag):
if opt_flag == "vnc":
return(DEFAULT_BOOT_OPTS + \
" console=ttyS0 vnc=1 vncpassword=" + \
VNC_PASSWD)
elif opt_flag == "ssh":
return(DEFAULT_BOOT_OPTS + \
" console=ttyS0 usessh=1 sshpassword=" + \
SSH_PASSWD)
else:
return(DEFAULT_BOOT_OPTS)
def connect_db():
return sqlite3.connect(DATABASE)
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
@app.route('/')
def form():
default_val = {}
for i,k in enumerate(['title', \
'repo_url', \
'repo_kernel', \
'repo_initrd', \
'inst_method', \
'comment']):
default_val[k] = form_default[i]
return render_template('form.html', default_val=default_val)
@app.route('/history/', defaults={'page': 1})
@app.route('/history/page/<int:page>')
def history(page):
count = g.db.execute('select count(*) from pxeitems').fetchone()[0]
per_page = 10
pagination = Pagi(page, per_page, count)
try:
cur = g.db.execute('select id,\
pxe_title,\
repo_url,\
repo_kernel,\
repo_initrd,\
pxe_comment,\
unix_time,\
inst_flag from pxeitems order by id desc')
except sqlite3.Error as e:
return render_template('failed.html', \
failed_msg = "Database error: "+str(e))
history_entries = [ dict(pxe_id=row[0], \
pxe_title=row[1], \
repo_url=row[2], \
repo_kernel=row[3], \
repo_initrd=row[4], \
pxe_comment=row[5], \
unix_time=datetime.datetime.fromtimestamp(int(row[6])), \
inst_flag=row[7]) \
for row in cur.fetchall()[(page-1)*per_page:page*per_page]\
]
if not history_entries and page != 1:
#Shoud do something here other than pass or abort(404)
pass
return render_template('history.html',\
pagination=pagination,\
history_entries=history_entries)
@app.route('/clone/<int:clone_id>')
def clone(clone_id):
row = g.db.execute('select pxe_title,\
repo_url,\
repo_kernel,\
repo_initrd,\
inst_flag,\
pxe_comment from pxeitems where id=?',[clone_id]).fetchone()
default_val = {}
for i,k in enumerate(['title', \
'repo_url', \
'repo_kernel', \
'repo_initrd', \
'inst_method', \
'comment']):
default_val[k] = row[i]
flash(u'Cloned Entry!','green')
return render_template('form.html', default_val=default_val)
@app.route('/about')
@app.route('/about/')
def about():
return render_template('about.html')
# For the pagination
def url_for_other_page(page):
args = request.view_args.copy()
args['page'] = page
return url_for(request.endpoint, **args)
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
@app.route('/confirm', methods=['POST'])
def confirm_entry():
#Input checking
try:
for x,y in [[request.form['pxe_title'],'pxe_title'], \
[request.form['repo_url'], 'repo_url'], \
[request.form['repo_kernel'], 'file_path'], \
[request.form['repo_initrd'], 'file_path']]:
chk_input(x,y)
except ValueError as e:
flash(e.args[0],'error')
return redirect(url_for('form'))
# Assign to the dictionary
items['repo_kernel'] = request.form['repo_kernel']
items['repo_url'] = request.form['repo_url']
items['repo_initrd'] = request.form['repo_initrd']
items['pxe_title'] = request.form['pxe_title']
items['pxe_comment'] = request.form['pxe_comment']
items['inst_flag'] = request.form['inst_method']
# Generate a random string
items['random_str'] = ''.join(random.choice(string.ascii_lowercase) for _ in range(4))
items['unix_time'] = ''
# Show the entry which will be generated on the confirm page
gen_format = ["menu label ^a - " + items['pxe_title'], \
"kernel " + LOADER_PATH + "[random]" + postfix_kernelfn, \
"append initrd=" + LOADER_PATH + "[random]" + postfix_initrdfn + " " + \
boot_opts_gen(items['inst_flag']) + " " + \
"install=" + items['repo_url']]
return render_template('confirm.html', cfm_entries=items, cfm_fmt=gen_format)
@app.route('/add', methods=['POST'])
def add_entry():
items['unix_time'] = str(int(time.time()))
id_random = items['unix_time'] + items['random_str']
# Get kernel and initrd file
for f_name,i in [[items['repo_kernel'], postfix_kernelfn],\
[items['repo_initrd'], postfix_initrdfn]]:
ret = grab_file(items['repo_url'],\
f_name,\
loader_dir + id_random + i)
if ret:
return render_template('failed.html',\
failed_msg = f_name + ": " + str(ret))
else:
pass
# Add new entry to database
try:
g.db.execute('INSERT INTO pxeitems (\
pxe_title, \
repo_url, \
repo_kernel, \
repo_initrd, \
pxe_comment, \
unix_time, \
random_str, \
inst_flag) values (?, ?, ?, ?, ?, ?, ?, ?)', \
[items['pxe_title'], \
items['repo_url'], \
items['repo_kernel'], \
items['repo_initrd'], \
items['pxe_comment'], \
items['unix_time'], \
items['random_str'], \
items['inst_flag']\
])
except sqlite3.Error as e:
#Remove downloaded files here
for i in (postfix_kernelfn, postfix_initrdfn):
os.remove(TFTP_ROOT + LOADER_PATH + id_random + i)
return render_template('failed.html', \
failed_msg = "Database error: " + str(e))
g.db.commit()
# Fetch first items_num of entires from the database
cur = g.db.execute('SELECT pxe_title,\
repo_url,\
repo_kernel,\
repo_initrd,\
inst_flag FROM pxeitems order by id desc')
pxe_entries = [ dict(pxe_title=row[0], \
repo_url=row[1], \
repo_kernel=row[2], \
repo_initrd=row[3], \
inst_flag=row[4]) for row in cur.fetchall()[:items_num]\
]
# Write the entries to PXE configure file
try:
fpxe = open(PXE_FILE,'w')
except IOError as e:
for i in ("0","1"):
os.remove(TFTP_ROOT + LOADER_PATH + id_random + "-" + i)<|fim▁hole|>
pxe_index = 'a'
for pxe_entry in pxe_entries:
fpxe.write('label {0}\n menu label ^{0} - {1}\n menu indent 2\n kernel {2}\n append initrd={3} {4} install={5}\n\n'.format(\
pxe_index,\
pxe_entry['pxe_title'],\
LOADER_PATH + items['unix_time'] + items['random_str'] + postfix_kernelfn, \
LOADER_PATH + items['unix_time'] + items['random_str'] + postfix_initrdfn, \
boot_opts_gen(pxe_entry['inst_flag']),items['repo_url']))
pxe_index = chr(ord(pxe_index)+1)
fpxe.write(PXE_FOOTER + '\n')
fpxe.close
# Remove the out of service kernel&initrd files
for root, dirs, files in os.walk(loader_dir, topdown=False):
names=sorted(files,reverse=True)
for i in names[items_num*2:]:
os.remove(os.path.join(root,i))
flash(u'New entry was successfully posted','green')
return redirect(url_for('form'))<|fim▁end|> | g.db.execute('DELETE FROM pxeitems WHERE id = (SELECT max(id) FROM pxeitems)')
return render_template('failed.html', failed_msg = e)
fpxe.write(PXE_HEADER + '\n') |
<|file_name|>thing.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Thing } from './thing';
@Component({
selector: 'app-thing',
templateUrl: './thing.component.html',
styleUrls: ['./thing.component.css']
})
export class ThingComponent implements OnInit {
private thing1: Thing;
private thing2: Thing;
private thing3: Thing;
private things: Thing[];
public paramId;
constructor(private _route: ActivatedRoute, private _router: Router) {
this.thing1 = new Thing(1, 'Thing 1', 'A');
this.thing2 = new Thing(2, 'Thing 2', 'B');
this.thing3 = new Thing(3, 'Thing 3', 'A');
this.things = [this.thing1, this.thing2, this.thing3];
}
ngOnInit() {
this._route.params.forEach((params: Params) => {
console.log(params);
this.paramId = Number(params['id']);
});
}
<|fim▁hole|> }
}<|fim▁end|> | redirect(id: number) {
this._router.navigate(['/thing', id]); |
<|file_name|>securitygroup.py<|end_file_name|><|fim▁begin|>""" -*- coding: utf-8 -*- """
from python2awscli import bin_aws
from python2awscli.error import AWSNotFound, ParseError, AWSDuplicate
from python2awscli import must
class BaseSecurityGroup(object):
def __init__(self, name, region, vpc, description, inbound=None, outbound=None):
"""
:param name: String, name of SG
:param region: String, AWS region
:param vpc: String, IP of the VPC this SG belongs to
:param description: String
:param inbound: List of dicts, IP Permissions that should exist
:param outbound: List of dicts, IP Permissions that should exist
"""
self.id = None
self.name = name
self.region = region
self.vpc = vpc
self.description = description
self.IpPermissions = []
self.IpPermissionsEgress = []
self.owner = None
self.changed = False
try:
self._get()
except AWSNotFound:
self._create()
self._merge_rules(must.be_list(inbound), self.IpPermissions)
self._merge_rules(must.be_list(outbound), self.IpPermissionsEgress, egress=True)
if self.changed:
self._get()
def _break_out(self, existing):
"""
Undo AWS's rule flattening so we can do simple 'if rule in existing' logic later.
:param existing: List of SG rules as dicts.
:return: List of SG rules as dicts.
"""
spool = list()
for rule in existing:
for ip in rule['IpRanges']:
copy_of_rule = rule.copy()
copy_of_rule['IpRanges'] = [ip]
copy_of_rule['UserIdGroupPairs'] = []
spool.append(copy_of_rule)
for group in rule['UserIdGroupPairs']:
copy_of_rule = rule.copy()
copy_of_rule['IpRanges'] = []
copy_of_rule['UserIdGroupPairs'] = [group]
spool.append(copy_of_rule)
return spool
def _merge_rules(self, requested, active, egress=False):
"""
:param requested: List of dicts, IP Permissions that should exist
:param active: List of dicts, IP Permissions that already exist
:param egress: Bool, addressing outbound rules or not?
:return: Bool
"""
if not isinstance(requested, list):
raise ParseError(
'SecurityGroup {0}, need a list of dicts, instead got "{1}"'.format(self.name, requested))
for rule in requested:
if rule not in active:
self._add_rule(rule, egress)
for active_rule in active:
if active_rule not in requested:
self._rm_rule(active_rule, egress)
return True
def _add_rule(self, ip_permissions, egress):
"""
:param ip_permissions: Dict of IP Permissions
:param egress: Bool
:return: Bool
"""
direction = 'authorize-security-group-ingress'
if egress:
direction = 'authorize-security-group-egress'
command = ['ec2', direction,
'--region', self.region,
'--group-id', self.id,
'--ip-permissions', str(ip_permissions).replace("'", '"')
]
bin_aws(command)
print('Authorized: {0}'.format(ip_permissions)) # TODO: Log(...)
self.changed = True
return True
def _rm_rule(self, ip_permissions, egress):
"""
:param ip_permissions: Dict of IP Permissions
:param egress: Bool
:return: Bool
"""
direction = 'revoke-security-group-ingress'
if egress:
direction = 'revoke-security-group-egress'
command = ['ec2', direction,
'--region', self.region,
'--group-id', self.id,
'--ip-permissions', str(ip_permissions).replace("'", '"')
]
bin_aws(command)
print('Revoked: {0}'.format(ip_permissions)) # TODO: Log(...)
self.changed = True
return True
def _create(self):
"""
Create a Security Group
:return:
"""
# AWS grants all new SGs this default outbound rule "This is pro-human & anti-machine behavior."
default_egress = {
'Ipv6Ranges': [],
'PrefixListIds': [],
'IpRanges': [{'CidrIp': '0.0.0.0/0'}],
'UserIdGroupPairs': [], 'IpProtocol': '-1'
}
command = [
'ec2', 'create-security-group',
'--region', self.region,
'--group-name', self.name,<|fim▁hole|> try:
self.id = bin_aws(command, key='GroupId')
except AWSDuplicate:
return False # OK if it already exists.
print('Created {0}'.format(command)) # TODO: Log(...)
self.IpPermissions = []
self.IpPermissionsEgress = [default_egress]
self.changed = True
return True
def _get(self):
"""
Get information about Security Group from AWS and update self
:return: Bool
"""
command = ['ec2', 'describe-security-groups', '--region', self.region, '--group-names', self.name]
result = bin_aws(command, key='SecurityGroups', max=1) # will raise NotFound if empty
me = result[0]
self.id = me['GroupId']
self.owner = me['OwnerId']
self.IpPermissions = self._break_out(me['IpPermissions'])
self.IpPermissionsEgress = self._break_out(me['IpPermissionsEgress'])
print('Got {0}'.format(command)) # TODO: Log(...)
return True
def _delete(self):
"""
Delete myself by my own id.
As of 20170114 no other methods call me. You must do `foo._delete()`
:return:
"""
command = ['ec2', 'delete-security-group', '--region', self.region,
# '--dry-run',
'--group-id', self.id
]
bin_aws(command, decode_output=False)
print('Deleted {0}'.format(command)) # TODO: Log(...)
return True<|fim▁end|> | '--description', self.description,
'--vpc-id', self.vpc
] |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os
from setuptools import setup, find_packages
CURRENT_DIR = os.path.dirname(__file__)
setup(name='datapot',
description='Library for automatic feature extraction from JSON-datasets',
long_description=open(os.path.join(CURRENT_DIR, 'README.rst')).read(),
version='0.1.3',
url='https://github.com/bashalex/datapot',<|fim▁hole|> maintainer='Nikita Savelyev',
maintainer_email='[email protected]',
install_requires=[
'numpy >= 1.6.1',
'scipy >= 0.17.0',
'pandas >= 0.17.1',
'scikit-learn >= 0.17.1',
'iso-639 >= 0.4.5',
'langdetect >= 1.0.7',
'gensim >= 2.1.0',
'nltk >= 3.2.4',
'tsfresh >= 0.7.1',
'python-dateutil >= 2.6.0',
'fastnumbers >= 2.0.1',
'pystemmer >= 1.3.0',
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering',
'Topic :: Software Development',
],
packages=find_packages())<|fim▁end|> | author='Alex Bash, Yuriy Mokriy, Nikita Saveyev, Michal Rozenwald, Peter Romov',
author_email='[email protected], [email protected], [email protected], [email protected], [email protected]',
license='GNU v3.0', |
<|file_name|>ServerProxy.java<|end_file_name|><|fim▁begin|>package com.rockoutwill.letsmodreboot.proxy;<|fim▁hole|>public class ServerProxy extends CommonProxy {
}<|fim▁end|> | |
<|file_name|>projection-one-region-closure.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test cases where we constrain `<T as Anything<'b>>::AssocType` to
// outlive `'a` and there are no bounds in the trait definition of
// `Anything`. This means that the constraint can only be satisfied in two
// ways:
//
// - by ensuring that `T: 'a` and `'b: 'a`, or
// - by something in the where clauses.
//
// As of this writing, the where clause option does not work because
// of limitations in our region inferencing system (this is true both
// with and without NLL). See `projection_outlives`.
//
// Ensuring that both `T: 'a` and `'b: 'a` holds does work (`elements_outlive`).
// compile-flags:-Zborrowck=mir -Zverbose
#![allow(warnings)]
#![feature(rustc_attrs)]
use std::cell::Cell;
trait Anything<'a> {
type AssocType;
}
fn with_signature<'a, T, F>(cell: Cell<&'a ()>, t: T, op: F)
where
F: FnOnce(Cell<&'a ()>, T),
{
op(cell, t)
}
fn require<'a, 'b, T>(_cell: Cell<&'a ()>, _t: T)
where
T: Anything<'b>,
T::AssocType: 'a,
{<|fim▁hole|>where
T: Anything<'b>,
{
with_signature(cell, t, |cell, t| require(cell, t));
//~^ ERROR the parameter type `T` may not live long enough
//~| ERROR
}
#[rustc_regions]
fn no_relationships_early<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
where
T: Anything<'b>,
'a: 'a,
{
with_signature(cell, t, |cell, t| require(cell, t));
//~^ ERROR the parameter type `T` may not live long enough
//~| ERROR
}
#[rustc_regions]
fn projection_outlives<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
where
T: Anything<'b>,
T::AssocType: 'a,
{
// We are projecting `<T as Anything<'b>>::AssocType`, and we know
// that this outlives `'a` because of the where-clause.
with_signature(cell, t, |cell, t| require(cell, t));
}
#[rustc_regions]
fn elements_outlive<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
where
T: Anything<'b>,
T: 'a,
'b: 'a,
{
with_signature(cell, t, |cell, t| require(cell, t));
}
fn main() {}<|fim▁end|> | }
#[rustc_regions]
fn no_relationships_late<'a, 'b, T>(cell: Cell<&'a ()>, t: T) |
<|file_name|>webpack.config.js<|end_file_name|><|fim▁begin|>'use strict';
import path from 'path';
import webpack, { optimize, HotModuleReplacementPlugin, NoErrorsPlugin } from 'webpack';
export default {
devtool: 'eval-cheap-module-source-map',
entry: [
'webpack-hot-middleware/client',
'./app/js/bootstrap'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new optimize.OccurenceOrderPlugin(),
new HotModuleReplacementPlugin(),
new NoErrorsPlugin()
],
module: {
loaders: [
{<|fim▁hole|> include: [
path.resolve(__dirname)
]
}
]
}
};<|fim▁end|> | test: /\.js$/,
loaders: ['babel'],
exclude: path.resolve(__dirname, 'node_modules'), |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>fn main() {
println!("hello, world");<|fim▁hole|>}<|fim▁end|> | |
<|file_name|>sudoku_descr.py<|end_file_name|><|fim▁begin|>import json
import math
from common.matrix import Matrix
class SudokuDescr(object):
def __init__(self, matrix=None):
self.matrix = Matrix(matrix=matrix)
y_size = int(math.sqrt(self.matrix.shape[0]))
x_size = int(math.sqrt(self.matrix.shape[1]))
self._box_shape = (x_size, y_size)
self._values = set([i + 1 for i in xrange(x_size*y_size)])
def __eq__(self, other):
return other is not None \
and self.matrix == other.matrix
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
return SudokuDescrPrinter.pretty_string(self)
def values(self):
return self._values
def box_shape(self):
return self._box_shape
def save(self):
return {"matrix", self.matrix}
def save_to_file(self, filepath):
with open(filepath, 'w') as outfile:
json.dump(self.save(), outfile, indent=4, sort_keys=False)
@staticmethod
def load(data):
return SudokuDescr(**data)
@staticmethod
def load_from_file(filepath):
with open(filepath, "r") as inputfile:
return SudokuDescr.load(json.load(inputfile))<|fim▁hole|> @staticmethod
def pretty_string(descr):
s = ""
x_box_size, y_box_size = descr.box_shape()
x_size, y_size = descr.matrix.shape
for y in xrange(y_size):
if y % y_box_size == 0 and y > 0:
s += '-'*(y_size + y_size/x_box_size) + '\n'
for x in xrange(x_size):
v = descr.matrix.value(x, y)
if v != 0:
s += str(v)
else:
s += "."
if (x + 1) % x_box_size == 0:
s += '|'
s += '\n'
return s<|fim▁end|> |
class SudokuDescrPrinter(): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.