repo_name
stringlengths 5
100
| ref
stringlengths 12
67
| path
stringlengths 4
244
| copies
stringlengths 1
8
| content
stringlengths 0
1.05M
⌀ |
---|---|---|---|---|
byndcivilization/toy-infrastructure
|
refs/heads/master
|
flask-app/migrations/env.py
|
557
|
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
import logging
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = current_app.extensions['migrate'].db.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.readthedocs.org/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
engine = engine_from_config(config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
nysan/yocto-autobuilder
|
refs/heads/master
|
lib/python2.6/site-packages/SQLAlchemy-0.7.1-py2.6-linux-x86_64.egg/sqlalchemy/sql/operators.py
|
4
|
# sql/operators.py
# Copyright (C) 2005-2011 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
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Defines operators used in SQL expressions."""
from operator import (
and_, or_, inv, add, mul, sub, mod, truediv, lt, le, ne, gt, ge, eq, neg
)
# Py2K
from operator import (div,)
# end Py2K
from sqlalchemy.util import symbol
class Operators(object):
"""Base of comparison and logical operators.
Implements base methods :meth:`operate` and :meth:`reverse_operate`,
as well as :meth:`__and__`, :meth:`__or__`, :meth:`__invert__`.
Usually is used via its most common subclass
:class:`.ColumnOperators`.
"""
def __and__(self, other):
"""Implement the ``&`` operator.
When used with SQL expressions, results in an
AND operation, equivalent to
:func:`~.expression.and_`, that is::
a & b
is equivalent to::
from sqlalchemy import and_
and_(a, b)
Care should be taken when using ``&`` regarding
operator precedence; the ``&`` operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions::
(a == 2) & (b == 4)
"""
return self.operate(and_, other)
def __or__(self, other):
"""Implement the ``|`` operator.
When used with SQL expressions, results in an
OR operation, equivalent to
:func:`~.expression.or_`, that is::
a | b
is equivalent to::
from sqlalchemy import or_
or_(a, b)
Care should be taken when using ``|`` regarding
operator precedence; the ``|`` operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions::
(a == 2) | (b == 4)
"""
return self.operate(or_, other)
def __invert__(self):
"""Implement the ``~`` operator.
When used with SQL expressions, results in a
NOT operation, equivalent to
:func:`~.expression.not_`, that is::
~a
is equivalent to::
from sqlalchemy import not_
not_(a)
"""
return self.operate(inv)
def op(self, opstring):
"""produce a generic operator function.
e.g.::
somecolumn.op("*")(5)
produces::
somecolumn * 5
:param operator: a string which will be output as the infix operator
between this :class:`.ClauseElement` and the expression passed to the
generated function.
This function can also be used to make bitwise operators explicit. For
example::
somecolumn.op('&')(0xff)
is a bitwise AND of the value in somecolumn.
"""
def _op(b):
return self.operate(op, opstring, b)
return _op
def operate(self, op, *other, **kwargs):
"""Operate on an argument.
This is the lowest level of operation, raises
:class:`NotImplementedError` by default.
Overriding this on a subclass can allow common
behavior to be applied to all operations.
For example, overriding :class:`.ColumnOperators`
to apply ``func.lower()`` to the left and right
side::
class MyComparator(ColumnOperators):
def operate(self, op, other):
return op(func.lower(self), func.lower(other))
:param op: Operator callable.
:param \*other: the 'other' side of the operation. Will
be a single scalar for most operations.
:param \**kwargs: modifiers. These may be passed by special
operators such as :meth:`ColumnOperators.contains`.
"""
raise NotImplementedError(str(op))
def reverse_operate(self, op, other, **kwargs):
"""Reverse operate on an argument.
Usage is the same as :meth:`operate`.
"""
raise NotImplementedError(str(op))
class ColumnOperators(Operators):
"""Defines comparison and math operations.
By default all methods call down to
:meth:`Operators.operate` or :meth:`Operators.reverse_operate`
passing in the appropriate operator function from the
Python builtin ``operator`` module or
a SQLAlchemy-specific operator function from
:mod:`sqlalchemy.expression.operators`. For example
the ``__eq__`` function::
def __eq__(self, other):
return self.operate(operators.eq, other)
Where ``operators.eq`` is essentially::
def eq(a, b):
return a == b
A SQLAlchemy construct like :class:`.ColumnElement` ultimately
overrides :meth:`.Operators.operate` and others
to return further :class:`.ClauseElement` constructs,
so that the ``==`` operation above is replaced by a clause
construct.
The docstrings here will describe column-oriented
behavior of each operator. For ORM-based operators
on related objects and collections, see :class:`.RelationshipProperty.Comparator`.
"""
timetuple = None
"""Hack, allows datetime objects to be compared on the LHS."""
def __lt__(self, other):
"""Implement the ``<`` operator.
In a column context, produces the clause ``a < b``.
"""
return self.operate(lt, other)
def __le__(self, other):
"""Implement the ``<=`` operator.
In a column context, produces the clause ``a <= b``.
"""
return self.operate(le, other)
__hash__ = Operators.__hash__
def __eq__(self, other):
"""Implement the ``==`` operator.
In a column context, produces the clause ``a = b``.
If the target is ``None``, produces ``a IS NULL``.
"""
return self.operate(eq, other)
def __ne__(self, other):
"""Implement the ``!=`` operator.
In a column context, produces the clause ``a != b``.
If the target is ``None``, produces ``a IS NOT NULL``.
"""
return self.operate(ne, other)
def __gt__(self, other):
"""Implement the ``>`` operator.
In a column context, produces the clause ``a > b``.
"""
return self.operate(gt, other)
def __ge__(self, other):
"""Implement the ``>=`` operator.
In a column context, produces the clause ``a >= b``.
"""
return self.operate(ge, other)
def __neg__(self):
"""Implement the ``-`` operator.
In a column context, produces the clause ``-a``.
"""
return self.operate(neg)
def concat(self, other):
"""Implement the 'concat' operator.
In a column context, produces the clause ``a || b``,
or uses the ``concat()`` operator on MySQL.
"""
return self.operate(concat_op, other)
def like(self, other, escape=None):
"""Implement the ``like`` operator.
In a column context, produces the clause ``a LIKE other``.
"""
return self.operate(like_op, other, escape=escape)
def ilike(self, other, escape=None):
"""Implement the ``ilike`` operator.
In a column context, produces the clause ``a ILIKE other``.
"""
return self.operate(ilike_op, other, escape=escape)
def in_(self, other):
"""Implement the ``in`` operator.
In a column context, produces the clause ``a IN other``.
"other" may be a tuple/list of column expressions,
or a :func:`~.expression.select` construct.
"""
return self.operate(in_op, other)
def startswith(self, other, **kwargs):
"""Implement the ``startwith`` operator.
In a column context, produces the clause ``LIKE '<other>%'``
"""
return self.operate(startswith_op, other, **kwargs)
def endswith(self, other, **kwargs):
"""Implement the 'endswith' operator.
In a column context, produces the clause ``LIKE '%<other>'``
"""
return self.operate(endswith_op, other, **kwargs)
def contains(self, other, **kwargs):
"""Implement the 'contains' operator.
In a column context, produces the clause ``LIKE '%<other>%'``
"""
return self.operate(contains_op, other, **kwargs)
def match(self, other, **kwargs):
"""Implements the 'match' operator.
In a column context, this produces a MATCH clause, i.e.
``MATCH '<other>'``. The allowed contents of ``other``
are database backend specific.
"""
return self.operate(match_op, other, **kwargs)
def desc(self):
"""Produce a :func:`~.expression.desc` clause against the
parent object."""
return self.operate(desc_op)
def asc(self):
"""Produce a :func:`~.expression.asc` clause against the
parent object."""
return self.operate(asc_op)
def nullsfirst(self):
"""Produce a :func:`~.expression.nullsfirst` clause against the
parent object."""
return self.operate(nullsfirst_op)
def nullslast(self):
"""Produce a :func:`~.expression.nullslast` clause against the
parent object."""
return self.operate(nullslast_op)
def collate(self, collation):
"""Produce a :func:`~.expression.collate` clause against
the parent object, given the collation string."""
return self.operate(collate, collation)
def __radd__(self, other):
"""Implement the ``+`` operator in reverse.
See :meth:`__add__`.
"""
return self.reverse_operate(add, other)
def __rsub__(self, other):
"""Implement the ``-`` operator in reverse.
See :meth:`__sub__`.
"""
return self.reverse_operate(sub, other)
def __rmul__(self, other):
"""Implement the ``*`` operator in reverse.
See :meth:`__mul__`.
"""
return self.reverse_operate(mul, other)
def __rdiv__(self, other):
"""Implement the ``/`` operator in reverse.
See :meth:`__div__`.
"""
return self.reverse_operate(div, other)
def between(self, cleft, cright):
"""Produce a :func:`~.expression.between` clause against
the parent object, given the lower and upper range."""
return self.operate(between_op, cleft, cright)
def distinct(self):
"""Produce a :func:`~.expression.distinct` clause against the parent object."""
return self.operate(distinct_op)
def __add__(self, other):
"""Implement the ``+`` operator.
In a column context, produces the clause ``a + b``
if the parent object has non-string affinity.
If the parent object has a string affinity,
produces the concatenation operator, ``a || b`` -
see :meth:`concat`.
"""
return self.operate(add, other)
def __sub__(self, other):
"""Implement the ``-`` operator.
In a column context, produces the clause ``a - b``.
"""
return self.operate(sub, other)
def __mul__(self, other):
"""Implement the ``*`` operator.
In a column context, produces the clause ``a * b``.
"""
return self.operate(mul, other)
def __div__(self, other):
"""Implement the ``/`` operator.
In a column context, produces the clause ``a / b``.
"""
return self.operate(div, other)
def __mod__(self, other):
"""Implement the ``%`` operator.
In a column context, produces the clause ``a % b``.
"""
return self.operate(mod, other)
def __truediv__(self, other):
"""Implement the ``//`` operator.
In a column context, produces the clause ``a / b``.
"""
return self.operate(truediv, other)
def __rtruediv__(self, other):
"""Implement the ``//`` operator in reverse.
See :meth:`__truediv__`.
"""
return self.reverse_operate(truediv, other)
def from_():
raise NotImplementedError()
def as_():
raise NotImplementedError()
def exists():
raise NotImplementedError()
def is_():
raise NotImplementedError()
def isnot():
raise NotImplementedError()
def collate():
raise NotImplementedError()
def op(a, opstring, b):
return a.op(opstring)(b)
def like_op(a, b, escape=None):
return a.like(b, escape=escape)
def notlike_op(a, b, escape=None):
raise NotImplementedError()
def ilike_op(a, b, escape=None):
return a.ilike(b, escape=escape)
def notilike_op(a, b, escape=None):
raise NotImplementedError()
def between_op(a, b, c):
return a.between(b, c)
def in_op(a, b):
return a.in_(b)
def notin_op(a, b):
raise NotImplementedError()
def distinct_op(a):
return a.distinct()
def startswith_op(a, b, escape=None):
return a.startswith(b, escape=escape)
def endswith_op(a, b, escape=None):
return a.endswith(b, escape=escape)
def contains_op(a, b, escape=None):
return a.contains(b, escape=escape)
def match_op(a, b):
return a.match(b)
def comma_op(a, b):
raise NotImplementedError()
def concat_op(a, b):
return a.concat(b)
def desc_op(a):
return a.desc()
def asc_op(a):
return a.asc()
def nullsfirst_op(a):
return a.nullsfirst()
def nullslast_op(a):
return a.nullslast()
_commutative = set([eq, ne, add, mul])
def is_commutative(op):
return op in _commutative
_associative = _commutative.union([concat_op, and_, or_])
_smallest = symbol('_smallest')
_largest = symbol('_largest')
_PRECEDENCE = {
from_: 15,
mul: 7,
truediv: 7,
# Py2K
div: 7,
# end Py2K
mod: 7,
neg: 7,
add: 6,
sub: 6,
concat_op: 6,
match_op: 6,
ilike_op: 5,
notilike_op: 5,
like_op: 5,
notlike_op: 5,
in_op: 5,
notin_op: 5,
is_: 5,
isnot: 5,
eq: 5,
ne: 5,
gt: 5,
lt: 5,
ge: 5,
le: 5,
between_op: 5,
distinct_op: 5,
inv: 5,
and_: 3,
or_: 2,
comma_op: -1,
collate: 7,
as_: -1,
exists: 0,
_smallest: -1000,
_largest: 1000
}
def is_precedent(operator, against):
if operator is against and operator in _associative:
return False
else:
return (_PRECEDENCE.get(operator, _PRECEDENCE[_smallest]) <=
_PRECEDENCE.get(against, _PRECEDENCE[_largest]))
|
mahak/neutron
|
refs/heads/master
|
neutron/tests/functional/services/logapi/test_logging.py
|
2
|
# Copyright (c) 2017 Fujitsu Limited
# 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.
import re
from unittest import mock
from neutron_lib import constants
from neutron_lib import context as neutron_context
from oslo_config import cfg
from oslo_log import log as logging
import testscenarios
from neutron.objects.logapi import logging_resource as log_object
from neutron.plugins.ml2.drivers.openvswitch.agent import (
ovs_agent_extension_api as ovs_ext_api)
from neutron.plugins.ml2.drivers.openvswitch.agent.common import (
constants as ovs_consts)
from neutron.services.logapi.drivers.openvswitch import (
ovs_firewall_log as ovs_fw_log)
from neutron.tests.functional.agent import test_firewall
LOG = logging.getLogger(__name__)
load_tests = testscenarios.load_tests_apply_scenarios
FAKE_LOG_ID = 'a2d72369-4246-4f19-bd3c-af51ec8d70cd'
FAKE_PROJECT_ID = 'fake_project'
log_object_dict = {
'id': FAKE_LOG_ID,
'resource_type': 'security_group',
'project_id': FAKE_PROJECT_ID,
'event': 'ALL'
}
FAKE_LOG_OBJECT = log_object.Log(**log_object_dict)
class LoggingExtensionTestFramework(test_firewall.BaseFirewallTestCase):
def setUp(self):
super(LoggingExtensionTestFramework, self).setUp()
cfg.CONF.set_override('extensions', ['log'], group='agent')
self.context = neutron_context.get_admin_context_without_session()
self._set_resource_rpc_mock()
if self.firewall_name != 'openvswitch':
self.skipTest("Logging extension doesn't support firewall driver"
" %s at that time " % self.firewall_name)
self.log_driver = self.initialize_ovs_fw_log()
def initialize_ovs_fw_log(self):
self.int_br = ovs_ext_api.OVSCookieBridge(
self.of_helper.br_int_cls(self.tester.bridge.br_name))
self.tun_br = self.of_helper.br_tun_cls('br-tun')
agent_api = ovs_ext_api.OVSAgentExtensionAPI(
self.int_br, self.tun_br,
{'physnet1': self.of_helper.br_phys_cls('br-physnet1')})
log_driver = ovs_fw_log.OVSFirewallLoggingDriver(agent_api)
log_driver.initialize(self.resource_rpc)
return log_driver
def _set_resource_rpc_mock(self):
self.log_info = []
def _get_sg_info_mock(context, **kwargs):
return self.log_info
self.resource_rpc = mock.patch(
'neutron.services.logapi.rpc.agent.LoggingApiStub').start()
self.resource_rpc.get_sg_log_info_for_log_resources.side_effect = (
_get_sg_info_mock)
def _set_ports_log(self, sg_rules):
fake_sg_log_info = [
{
'id': FAKE_LOG_ID,
'ports_log': [
{'port_id': self.src_port_desc['device'],
'security_group_rules': sg_rules}],
'event': 'ALL',
'project_id': FAKE_PROJECT_ID
}]
self.log_info = fake_sg_log_info
class TestLoggingExtension(LoggingExtensionTestFramework):
ip_cidr = '192.168.0.1/24'
def _is_log_flow_set(self, table, actions):
flows = self.log_driver.int_br.br.dump_flows_for_table(table)
pattern = re.compile(
r"^.* table=%s.* actions=%s" % (table, actions)
)
for flow in flows.splitlines():
if pattern.match(flow.strip()):
return True
return False
def _assert_logging_flows_set(self):
self.assertTrue(self._is_log_flow_set(
table=ovs_consts.ACCEPTED_EGRESS_TRAFFIC_TABLE,
actions=r"resubmit\(,%d\),CONTROLLER:65535" % (
ovs_consts.ACCEPTED_EGRESS_TRAFFIC_NORMAL_TABLE)))
self.assertTrue(self._is_log_flow_set(
table=ovs_consts.ACCEPTED_INGRESS_TRAFFIC_TABLE,
actions="CONTROLLER:65535"))
self.assertTrue(self._is_log_flow_set(
table=ovs_consts.DROPPED_TRAFFIC_TABLE,
actions="CONTROLLER:65535"))
def _assert_logging_flows_not_set(self):
self.assertFalse(self._is_log_flow_set(
table=ovs_consts.ACCEPTED_EGRESS_TRAFFIC_TABLE,
actions=r"resubmit\(,%d\),CONTROLLER:65535" % (
ovs_consts.ACCEPTED_EGRESS_TRAFFIC_NORMAL_TABLE)))
self.assertFalse(self._is_log_flow_set(
table=ovs_consts.ACCEPTED_INGRESS_TRAFFIC_TABLE,
actions="CONTROLLER:65535"))
self.assertFalse(self._is_log_flow_set(
table=ovs_consts.DROPPED_TRAFFIC_TABLE,
actions="CONTROLLER:65535"))
def test_log_lifecycle(self):
sg_rules = [{'ethertype': constants.IPv4,
'direction': constants.INGRESS_DIRECTION,
'protocol': constants.PROTO_NAME_ICMP,
'security_group_id': self.FAKE_SECURITY_GROUP_ID},
{'ethertype': constants.IPv4,
'direction': constants.EGRESS_DIRECTION,
'security_group_id': self.FAKE_SECURITY_GROUP_ID},
{'ethertype': constants.IPv6,
'protocol': constants.PROTO_NAME_TCP,
'port_range_min': 22,
'port_range_max': 22,
'remote_group_id': 2,
'direction': constants.EGRESS_DIRECTION,
'security_group_id': self.FAKE_SECURITY_GROUP_ID},
]
self.firewall.update_security_group_rules(
self.FAKE_SECURITY_GROUP_ID, sg_rules)
self.firewall.update_port_filter(self.src_port_desc)
self._set_ports_log(sg_rules)
# start log
self.log_driver.start_logging(
self.context, log_resources=[FAKE_LOG_OBJECT])
self._assert_logging_flows_set()
# stop log
self.log_driver.stop_logging(
self.context, log_resources=[FAKE_LOG_OBJECT])
self._assert_logging_flows_not_set()
|
ldoktor/autotest
|
refs/heads/master
|
tko/migrations/018_add_indexes.py
|
11
|
def migrate_up(manager):
manager.execute_script(CREATE_INDICES)
def migrate_down(manager):
manager.execute_script(DROP_INDICES)
CREATE_INDICES = """
CREATE INDEX job_idx ON tests (job_idx);
CREATE INDEX reason ON tests (reason);
CREATE INDEX test ON tests (test);
CREATE INDEX subdir ON tests (subdir);
CREATE INDEX printable ON kernels (printable);
CREATE INDEX word ON status (word);
CREATE INDEX attribute ON test_attributes (attribute);
CREATE INDEX value ON test_attributes (value);
CREATE INDEX attribute ON iteration_result (attribute);
CREATE INDEX value ON iteration_result (value);
"""
DROP_INDICES = """
DROP INDEX job_idx ON tests;
DROP INDEX reason ON tests;
DROP INDEX test ON tests;
DROP INDEX subdir ON tests;
DROP INDEX printable ON kernels;
DROP INDEX word ON status;
DROP INDEX attribute ON test_attributes;
DROP INDEX value ON test_attributes;
DROP INDEX attribute ON iteration_result;
DROP INDEX value ON iteration_result;
"""
|
LyonsLab/coge
|
refs/heads/master
|
bin/last_wrapper/Bio/pairwise2.py
|
2
|
# Copyright 2002 by Jeffrey Chang. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""This package implements pairwise sequence alignment using a dynamic
programming algorithm.
This provides functions to get global and local alignments between two
sequences. A global alignment finds the best concordance between all
characters in two sequences. A local alignment finds just the
subsequences that align the best.
When doing alignments, you can specify the match score and gap
penalties. The match score indicates the compatibility between an
alignment of two characters in the sequences. Highly compatible
characters should be given positive scores, and incompatible ones
should be given negative scores or 0. The gap penalties should be
negative.
The names of the alignment functions in this module follow the
convention
<alignment type>XX
where <alignment type> is either "global" or "local" and XX is a 2
character code indicating the parameters it takes. The first
character indicates the parameters for matches (and mismatches), and
the second indicates the parameters for gap penalties.
The match parameters are
CODE DESCRIPTION
x No parameters. Identical characters have score of 1, otherwise 0.
m A match score is the score of identical chars, otherwise mismatch score.
d A dictionary returns the score of any pair of characters.
c A callback function returns scores.
The gap penalty parameters are
CODE DESCRIPTION
x No gap penalties.
s Same open and extend gap penalties for both sequences.
d The sequences have different open and extend gap penalties.
c A callback function returns the gap penalties.
All the different alignment functions are contained in an object
"align". For example:
>>> from Bio import pairwise2
>>> alignments = pairwise2.align.globalxx("ACCGT", "ACG")
will return a list of the alignments between the two strings. The
parameters of the alignment function depends on the function called.
Some examples:
>>> pairwise2.align.globalxx("ACCGT", "ACG")
# Find the best global alignment between the two sequences.
# Identical characters are given 1 point. No points are deducted
# for mismatches or gaps.
>>> pairwise2.align.localxx("ACCGT", "ACG")
# Same thing as before, but with a local alignment.
>>> pairwise2.align.globalmx("ACCGT", "ACG", 2, -1)
# Do a global alignment. Identical characters are given 2 points,
# 1 point is deducted for each non-identical character.
>>> pairwise2.align.globalms("ACCGT", "ACG", 2, -1, -.5, -.1)
# Same as above, except now 0.5 points are deducted when opening a
# gap, and 0.1 points are deducted when extending it.
To see a description of the parameters for a function, please look at
the docstring for the function.
>>> print newalign.align.localds.__doc__
localds(sequenceA, sequenceB, match_dict, open, extend) -> alignments
"""
# The alignment functions take some undocumented keyword parameters:
# - penalize_extend_when_opening: boolean
# Whether to count an extension penalty when opening a gap. If
# false, a gap of 1 is only penalize an "open" penalty, otherwise it
# is penalized "open+extend".
# - penalize_end_gaps: boolean
# Whether to count the gaps at the ends of an alignment. By
# default, they are counted for global alignments but not for local
# ones.
# - gap_char: string
# Which character to use as a gap character in the alignment
# returned. By default, uses '-'.
# - force_generic: boolean
# Always use the generic, non-cached, dynamic programming function.
# For debugging.
# - score_only: boolean
# Only get the best score, don't recover any alignments. The return
# value of the function is the score.
# - one_alignment_only: boolean
# Only recover one alignment.
MAX_ALIGNMENTS = 1000 # maximum alignments recovered in traceback
class align(object):
"""This class provides functions that do alignments."""
class alignment_function:
"""This class is callable impersonates an alignment function.
The constructor takes the name of the function. This class
will decode the name of the function to figure out how to
interpret the parameters.
"""
# match code -> tuple of (parameters, docstring)
match2args = {
'x' : ([], ''),
'm' : (['match', 'mismatch'],
"""match is the score to given to identical characters. mismatch is
the score given to non-identical ones."""),
'd' : (['match_dict'],
"""match_dict is a dictionary where the keys are tuples of pairs of
characters and the values are the scores, e.g. ("A", "C") : 2.5."""),
'c' : (['match_fn'],
"""match_fn is a callback function that takes two characters and
returns the score between them."""),
}
# penalty code -> tuple of (parameters, docstring)
penalty2args = {
'x' : ([], ''),
's' : (['open', 'extend'],
"""open and extend are the gap penalties when a gap is opened and
extended. They should be negative."""),
'd' : (['openA', 'extendA', 'openB', 'extendB'],
"""openA and extendA are the gap penalties for sequenceA, and openB
and extendB for sequeneB. The penalties should be negative."""),
'c' : (['gap_A_fn', 'gap_B_fn'],
"""gap_A_fn and gap_B_fn are callback functions that takes 1) the
index where the gap is opened, and 2) the length of the gap. They
should return a gap penalty."""),
}
def __init__(self, name):
# Check to make sure the name of the function is
# reasonable.
if name.startswith("global"):
if len(name) != 8:
raise AttributeError("function should be globalXX")
elif name.startswith("local"):
if len(name) != 7:
raise AttributeError("function should be localXX")
else:
raise AttributeError(name)
align_type, match_type, penalty_type = \
name[:-2], name[-2], name[-1]
try:
match_args, match_doc = self.match2args[match_type]
except KeyError, x:
raise AttributeError("unknown match type %r" % match_type)
try:
penalty_args, penalty_doc = self.penalty2args[penalty_type]
except KeyError, x:
raise AttributeError("unknown penalty type %r" % penalty_type)
# Now get the names of the parameters to this function.
param_names = ['sequenceA', 'sequenceB']
param_names.extend(match_args)
param_names.extend(penalty_args)
self.function_name = name
self.align_type = align_type
self.param_names = param_names
self.__name__ = self.function_name
# Set the doc string.
doc = "%s(%s) -> alignments\n" % (
self.__name__, ', '.join(self.param_names))
if match_doc:
doc += "\n%s\n" % match_doc
if penalty_doc:
doc += "\n%s\n" % penalty_doc
doc += (
"""\nalignments is a list of tuples (seqA, seqB, score, begin, end).
seqA and seqB are strings showing the alignment between the
sequences. score is the score of the alignment. begin and end
are indexes into seqA and seqB that indicate the where the
alignment occurs.
""")
self.__doc__ = doc
def decode(self, *args, **keywds):
# Decode the arguments for the _align function. keywds
# will get passed to it, so translate the arguments to
# this function into forms appropriate for _align.
keywds = keywds.copy()
if len(args) != len(self.param_names):
raise TypeError("%s takes exactly %d argument (%d given)" \
% (self.function_name, len(self.param_names), len(args)))
i = 0
while i < len(self.param_names):
if self.param_names[i] in [
'sequenceA', 'sequenceB',
'gap_A_fn', 'gap_B_fn', 'match_fn']:
keywds[self.param_names[i]] = args[i]
i += 1
elif self.param_names[i] == 'match':
assert self.param_names[i+1] == 'mismatch'
match, mismatch = args[i], args[i+1]
keywds['match_fn'] = identity_match(match, mismatch)
i += 2
elif self.param_names[i] == 'match_dict':
keywds['match_fn'] = dictionary_match(args[i])
i += 1
elif self.param_names[i] == 'open':
assert self.param_names[i+1] == 'extend'
open, extend = args[i], args[i+1]
pe = keywds.get('penalize_extend_when_opening', 0)
keywds['gap_A_fn'] = affine_penalty(open, extend, pe)
keywds['gap_B_fn'] = affine_penalty(open, extend, pe)
i += 2
elif self.param_names[i] == 'openA':
assert self.param_names[i+3] == 'extendB'
openA, extendA, openB, extendB = args[i:i+4]
pe = keywds.get('penalize_extend_when_opening', 0)
keywds['gap_A_fn'] = affine_penalty(openA, extendA, pe)
keywds['gap_B_fn'] = affine_penalty(openB, extendB, pe)
i += 4
else:
raise ValueError("unknown parameter %r" \
% self.param_names[i])
# Here are the default parameters for _align. Assign
# these to keywds, unless already specified.
pe = keywds.get('penalize_extend_when_opening', 0)
default_params = [
('match_fn', identity_match(1, 0)),
('gap_A_fn', affine_penalty(0, 0, pe)),
('gap_B_fn', affine_penalty(0, 0, pe)),
('penalize_extend_when_opening', 0),
('penalize_end_gaps', self.align_type == 'global'),
('align_globally', self.align_type == 'global'),
('gap_char', '-'),
('force_generic', 0),
('score_only', 0),
('one_alignment_only', 0)
]
for name, default in default_params:
keywds[name] = keywds.get(name, default)
return keywds
def __call__(self, *args, **keywds):
keywds = self.decode(*args, **keywds)
return _align(**keywds)
def __getattr__(self, attr):
return self.alignment_function(attr)
align = align()
def _align(sequenceA, sequenceB, match_fn, gap_A_fn, gap_B_fn,
penalize_extend_when_opening, penalize_end_gaps,
align_globally, gap_char, force_generic, score_only,
one_alignment_only):
if not sequenceA or not sequenceB:
return []
if (not force_generic) and isinstance(gap_A_fn, affine_penalty) \
and isinstance(gap_B_fn, affine_penalty):
open_A, extend_A = gap_A_fn.open, gap_A_fn.extend
open_B, extend_B = gap_B_fn.open, gap_B_fn.extend
x = _make_score_matrix_fast(
sequenceA, sequenceB, match_fn, open_A, extend_A, open_B, extend_B,
penalize_extend_when_opening, penalize_end_gaps, align_globally,
score_only)
else:
x = _make_score_matrix_generic(
sequenceA, sequenceB, match_fn, gap_A_fn, gap_B_fn,
penalize_extend_when_opening, penalize_end_gaps, align_globally,
score_only)
score_matrix, trace_matrix = x
#print "SCORE"; print_matrix(score_matrix)
#print "TRACEBACK"; print_matrix(trace_matrix)
# Look for the proper starting point. Get a list of all possible
# starting points.
starts = _find_start(
score_matrix, sequenceA, sequenceB,
gap_A_fn, gap_B_fn, penalize_end_gaps, align_globally)
# Find the highest score.
best_score = max([x[0] for x in starts])
# If they only want the score, then return it.
if score_only:
return best_score
tolerance = 0 # XXX do anything with this?
# Now find all the positions within some tolerance of the best
# score.
i = 0
while i < len(starts):
score, pos = starts[i]
if rint(abs(score-best_score)) > rint(tolerance):
del starts[i]
else:
i += 1
# Recover the alignments and return them.
x = _recover_alignments(
sequenceA, sequenceB, starts, score_matrix, trace_matrix,
align_globally, penalize_end_gaps, gap_char, one_alignment_only)
return x
def _make_score_matrix_generic(
sequenceA, sequenceB, match_fn, gap_A_fn, gap_B_fn,
penalize_extend_when_opening, penalize_end_gaps, align_globally,
score_only):
# This is an implementation of the Needleman-Wunsch dynamic
# programming algorithm for aligning sequences.
# Create the score and traceback matrices. These should be in the
# shape:
# sequenceA (down) x sequenceB (across)
lenA, lenB = len(sequenceA), len(sequenceB)
score_matrix, trace_matrix = [], []
for i in range(lenA):
score_matrix.append([None] * lenB)
trace_matrix.append([[None]] * lenB)
# The top and left borders of the matrices are special cases
# because there are no previously aligned characters. To simplify
# the main loop, handle these separately.
for i in range(lenA):
# Align the first residue in sequenceB to the ith residue in
# sequence A. This is like opening up i gaps at the beginning
# of sequence B.
score = match_fn(sequenceA[i], sequenceB[0])
if penalize_end_gaps:
score += gap_B_fn(0, i)
score_matrix[i][0] = score
for i in range(1, lenB):
score = match_fn(sequenceA[0], sequenceB[i])
if penalize_end_gaps:
score += gap_A_fn(0, i)
score_matrix[0][i] = score
# Fill in the score matrix. Each position in the matrix
# represents an alignment between a character from sequenceA to
# one in sequence B. As I iterate through the matrix, find the
# alignment by choose the best of:
# 1) extending a previous alignment without gaps
# 2) adding a gap in sequenceA
# 3) adding a gap in sequenceB
for row in range(1, lenA):
for col in range(1, lenB):
# First, calculate the score that would occur by extending
# the alignment without gaps.
best_score = score_matrix[row-1][col-1]
best_score_rint = rint(best_score)
best_indexes = [(row-1, col-1)]
# Try to find a better score by opening gaps in sequenceA.
# Do this by checking alignments from each column in the
# previous row. Each column represents a different
# character to align from, and thus a different length
# gap.
for i in range(0, col-1):
score = score_matrix[row-1][i] + gap_A_fn(i, col-1-i)
score_rint = rint(score)
if score_rint == best_score_rint:
best_score, best_score_rint = score, score_rint
best_indexes.append((row-1, i))
elif score_rint > best_score_rint:
best_score, best_score_rint = score, score_rint
best_indexes = [(row-1, i)]
# Try to find a better score by opening gaps in sequenceB.
for i in range(0, row-1):
score = score_matrix[i][col-1] + gap_B_fn(i, row-1-i)
score_rint = rint(score)
if score_rint == best_score_rint:
best_score, best_score_rint = score, score_rint
best_indexes.append((i, col-1))
elif score_rint > best_score_rint:
best_score, best_score_rint = score, score_rint
best_indexes = [(i, col-1)]
score_matrix[row][col] = best_score + \
match_fn(sequenceA[row], sequenceB[col])
if not align_globally and score_matrix[row][col] < 0:
score_matrix[row][col] = 0
trace_matrix[row][col] = best_indexes
return score_matrix, trace_matrix
def _make_score_matrix_fast(
sequenceA, sequenceB, match_fn, open_A, extend_A, open_B, extend_B,
penalize_extend_when_opening, penalize_end_gaps,
align_globally, score_only):
first_A_gap = calc_affine_penalty(1, open_A, extend_A,
penalize_extend_when_opening)
first_B_gap = calc_affine_penalty(1, open_B, extend_B,
penalize_extend_when_opening)
# Create the score and traceback matrices. These should be in the
# shape:
# sequenceA (down) x sequenceB (across)
lenA, lenB = len(sequenceA), len(sequenceB)
score_matrix, trace_matrix = [], []
for i in range(lenA):
score_matrix.append([None] * lenB)
trace_matrix.append([[None]] * lenB)
# The top and left borders of the matrices are special cases
# because there are no previously aligned characters. To simplify
# the main loop, handle these separately.
for i in range(lenA):
# Align the first residue in sequenceB to the ith residue in
# sequence A. This is like opening up i gaps at the beginning
# of sequence B.
score = match_fn(sequenceA[i], sequenceB[0])
if penalize_end_gaps:
score += calc_affine_penalty(
i, open_B, extend_B, penalize_extend_when_opening)
score_matrix[i][0] = score
for i in range(1, lenB):
score = match_fn(sequenceA[0], sequenceB[i])
if penalize_end_gaps:
score += calc_affine_penalty(
i, open_A, extend_A, penalize_extend_when_opening)
score_matrix[0][i] = score
# In the generic algorithm, at each row and column in the score
# matrix, we had to scan all previous rows and columns to see
# whether opening a gap might yield a higher score. Here, since
# we know the penalties are affine, we can cache just the best
# score in the previous rows and columns. Instead of scanning
# through all the previous rows and cols, we can just look at the
# cache for the best one. Whenever the row or col increments, the
# best cached score just decreases by extending the gap longer.
# The best score and indexes for each row (goes down all columns).
# I don't need to store the last row because it's the end of the
# sequence.
row_cache_score, row_cache_index = [None]*(lenA-1), [None]*(lenA-1)
# The best score and indexes for each column (goes across rows).
col_cache_score, col_cache_index = [None]*(lenB-1), [None]*(lenB-1)
for i in range(lenA-1):
# Initialize each row to be the alignment of sequenceA[i] to
# sequenceB[0], plus opening a gap in sequenceA.
row_cache_score[i] = score_matrix[i][0] + first_A_gap
row_cache_index[i] = [(i, 0)]
for i in range(lenB-1):
col_cache_score[i] = score_matrix[0][i] + first_B_gap
col_cache_index[i] = [(0, i)]
# Fill in the score_matrix.
for row in range(1, lenA):
for col in range(1, lenB):
# Calculate the score that would occur by extending the
# alignment without gaps.
nogap_score = score_matrix[row-1][col-1]
# Check the score that would occur if there were a gap in
# sequence A.
if col > 1:
row_score = row_cache_score[row-1]
else:
row_score = nogap_score - 1 # Make sure it's not the best.
# Check the score that would occur if there were a gap in
# sequence B.
if row > 1:
col_score = col_cache_score[col-1]
else:
col_score = nogap_score - 1
best_score = max(nogap_score, row_score, col_score)
best_score_rint = rint(best_score)
best_index = []
if best_score_rint == rint(nogap_score):
best_index.append((row-1, col-1))
if best_score_rint == rint(row_score):
best_index.extend(row_cache_index[row-1])
if best_score_rint == rint(col_score):
best_index.extend(col_cache_index[col-1])
# Set the score and traceback matrices.
score = best_score + match_fn(sequenceA[row], sequenceB[col])
if not align_globally and score < 0:
score_matrix[row][col] = 0
else:
score_matrix[row][col] = score
trace_matrix[row][col] = best_index
# Update the cached column scores. The best score for
# this can come from either extending the gap in the
# previous cached score, or opening a new gap from the
# most previously seen character. Compare the two scores
# and keep the best one.
open_score = score_matrix[row-1][col-1] + first_B_gap
extend_score = col_cache_score[col-1] + extend_B
open_score_rint, extend_score_rint = \
rint(open_score), rint(extend_score)
if open_score_rint > extend_score_rint:
col_cache_score[col-1] = open_score
col_cache_index[col-1] = [(row-1, col-1)]
elif extend_score_rint > open_score_rint:
col_cache_score[col-1] = extend_score
else:
col_cache_score[col-1] = open_score
if (row-1, col-1) not in col_cache_index[col-1]:
col_cache_index[col-1] = col_cache_index[col-1] + \
[(row-1, col-1)]
# Update the cached row scores.
open_score = score_matrix[row-1][col-1] + first_A_gap
extend_score = row_cache_score[row-1] + extend_A
open_score_rint, extend_score_rint = \
rint(open_score), rint(extend_score)
if open_score_rint > extend_score_rint:
row_cache_score[row-1] = open_score
row_cache_index[row-1] = [(row-1, col-1)]
elif extend_score_rint > open_score_rint:
row_cache_score[row-1] = extend_score
else:
row_cache_score[row-1] = open_score
if (row-1, col-1) not in row_cache_index[row-1]:
row_cache_index[row-1] = row_cache_index[row-1] + \
[(row-1, col-1)]
return score_matrix, trace_matrix
def _recover_alignments(sequenceA, sequenceB, starts,
score_matrix, trace_matrix, align_globally,
penalize_end_gaps, gap_char, one_alignment_only):
# Recover the alignments by following the traceback matrix. This
# is a recursive procedure, but it's implemented here iteratively
# with a stack.
lenA, lenB = len(sequenceA), len(sequenceB)
tracebacks = [] # list of (seq1, seq2, score, begin, end)
in_process = [] # list of ([same as tracebacks], prev_pos, next_pos)
# sequenceA and sequenceB may be sequences, including strings,
# lists, or list-like objects. In order to preserve the type of
# the object, we need to use slices on the sequences instead of
# indexes. For example, sequenceA[row] may return a type that's
# not compatible with sequenceA, e.g. if sequenceA is a list and
# sequenceA[row] is a string. Thus, avoid using indexes and use
# slices, e.g. sequenceA[row:row+1]. Assume that client-defined
# sequence classes preserve these semantics.
# Initialize the in_process stack
for score, (row, col) in starts:
if align_globally:
begin, end = None, None
else:
begin, end = None, -max(lenA-row, lenB-col)+1
if not end:
end = None
# Initialize the in_process list with empty sequences of the
# same type as sequenceA. To do this, take empty slices of
# the sequences.
in_process.append(
(sequenceA[0:0], sequenceB[0:0], score, begin, end,
(lenA, lenB), (row, col)))
if one_alignment_only:
break
while in_process and len(tracebacks) < MAX_ALIGNMENTS:
seqA, seqB, score, begin, end, prev_pos, next_pos = in_process.pop()
prevA, prevB = prev_pos
if next_pos is None:
prevlen = len(seqA)
# add the rest of the sequences
seqA = sequenceA[:prevA] + seqA
seqB = sequenceB[:prevB] + seqB
# add the rest of the gaps
seqA, seqB = _lpad_until_equal(seqA, seqB, gap_char)
# Now make sure begin is set.
if begin is None:
if align_globally:
begin = 0
else:
begin = len(seqA) - prevlen
tracebacks.append((seqA, seqB, score, begin, end))
else:
nextA, nextB = next_pos
nseqA, nseqB = prevA-nextA, prevB-nextB
maxseq = max(nseqA, nseqB)
ngapA, ngapB = maxseq-nseqA, maxseq-nseqB
seqA = sequenceA[nextA:nextA+nseqA] + gap_char*ngapA + seqA
seqB = sequenceB[nextB:nextB+nseqB] + gap_char*ngapB + seqB
prev_pos = next_pos
# local alignment stops early if score falls < 0
if not align_globally and score_matrix[nextA][nextB] <= 0:
begin = max(prevA, prevB)
in_process.append(
(seqA, seqB, score, begin, end, prev_pos, None))
else:
for next_pos in trace_matrix[nextA][nextB]:
in_process.append(
(seqA, seqB, score, begin, end, prev_pos, next_pos))
if one_alignment_only:
break
return _clean_alignments(tracebacks)
def _find_start(score_matrix, sequenceA, sequenceB, gap_A_fn, gap_B_fn,
penalize_end_gaps, align_globally):
# Return a list of (score, (row, col)) indicating every possible
# place to start the tracebacks.
if align_globally:
if penalize_end_gaps:
starts = _find_global_start(
sequenceA, sequenceB, score_matrix, gap_A_fn, gap_B_fn, 1)
else:
starts = _find_global_start(
sequenceA, sequenceB, score_matrix, None, None, 0)
else:
starts = _find_local_start(score_matrix)
return starts
def _find_global_start(sequenceA, sequenceB,
score_matrix, gap_A_fn, gap_B_fn, penalize_end_gaps):
# The whole sequence should be aligned, so return the positions at
# the end of either one of the sequences.
nrows, ncols = len(score_matrix), len(score_matrix[0])
positions = []
# Search all rows in the last column.
for row in range(nrows):
# Find the score, penalizing end gaps if necessary.
score = score_matrix[row][ncols-1]
if penalize_end_gaps:
score += gap_B_fn(ncols, nrows-row-1)
positions.append((score, (row, ncols-1)))
# Search all columns in the last row.
for col in range(ncols-1):
score = score_matrix[nrows-1][col]
if penalize_end_gaps:
score += gap_A_fn(nrows, ncols-col-1)
positions.append((score, (nrows-1, col)))
return positions
def _find_local_start(score_matrix):
# Return every position in the matrix.
positions = []
nrows, ncols = len(score_matrix), len(score_matrix[0])
for row in range(nrows):
for col in range(ncols):
score = score_matrix[row][col]
positions.append((score, (row, col)))
return positions
def _clean_alignments(alignments):
# Take a list of alignments and return a cleaned version. Remove
# duplicates, make sure begin and end are set correctly, remove
# empty alignments.
unique_alignments = []
for align in alignments :
if align not in unique_alignments :
unique_alignments.append(align)
i = 0
while i < len(unique_alignments):
seqA, seqB, score, begin, end = unique_alignments[i]
# Make sure end is set reasonably.
if end is None: # global alignment
end = len(seqA)
elif end < 0:
end = end + len(seqA)
# If there's no alignment here, get rid of it.
if begin >= end:
del unique_alignments[i]
continue
unique_alignments[i] = seqA, seqB, score, begin, end
i += 1
return unique_alignments
def _pad_until_equal(s1, s2, char):
# Add char to the end of s1 or s2 until they are equal length.
ls1, ls2 = len(s1), len(s2)
if ls1 < ls2:
s1 = _pad(s1, char, ls2-ls1)
elif ls2 < ls1:
s2 = _pad(s2, char, ls1-ls2)
return s1, s2
def _lpad_until_equal(s1, s2, char):
# Add char to the beginning of s1 or s2 until they are equal
# length.
ls1, ls2 = len(s1), len(s2)
if ls1 < ls2:
s1 = _lpad(s1, char, ls2-ls1)
elif ls2 < ls1:
s2 = _lpad(s2, char, ls1-ls2)
return s1, s2
def _pad(s, char, n):
# Append n chars to the end of s.
return s + char*n
def _lpad(s, char, n):
# Prepend n chars to the beginning of s.
return char*n + s
_PRECISION = 1000
def rint(x, precision=_PRECISION):
return int(x * precision + 0.5)
class identity_match:
"""identity_match([match][, mismatch]) -> match_fn
Create a match function for use in an alignment. match and
mismatch are the scores to give when two residues are equal or
unequal. By default, match is 1 and mismatch is 0.
"""
def __init__(self, match=1, mismatch=0):
self.match = match
self.mismatch = mismatch
def __call__(self, charA, charB):
if charA == charB:
return self.match
return self.mismatch
class dictionary_match:
"""dictionary_match(score_dict[, symmetric]) -> match_fn
Create a match function for use in an alignment. score_dict is a
dictionary where the keys are tuples (residue 1, residue 2) and
the values are the match scores between those residues. symmetric
is a flag that indicates whether the scores are symmetric. If
true, then if (res 1, res 2) doesn't exist, I will use the score
at (res 2, res 1).
"""
def __init__(self, score_dict, symmetric=1):
self.score_dict = score_dict
self.symmetric = symmetric
def __call__(self, charA, charB):
if self.symmetric and (charA, charB) not in self.score_dict:
# If the score dictionary is symmetric, then look up the
# score both ways.
charB, charA = charA, charB
return self.score_dict[(charA, charB)]
class affine_penalty:
"""affine_penalty(open, extend[, penalize_extend_when_opening]) -> gap_fn
Create a gap function for use in an alignment.
"""
def __init__(self, open, extend, penalize_extend_when_opening=0):
if open > 0 or extend > 0:
raise ValueError("Gap penalties should be non-positive.")
self.open, self.extend = open, extend
self.penalize_extend_when_opening = penalize_extend_when_opening
def __call__(self, index, length):
return calc_affine_penalty(
length, self.open, self.extend, self.penalize_extend_when_opening)
def calc_affine_penalty(length, open, extend, penalize_extend_when_opening):
if length <= 0:
return 0
penalty = open + extend * length
if not penalize_extend_when_opening:
penalty -= extend
return penalty
def print_matrix(matrix):
"""print_matrix(matrix)
Print out a matrix. For debugging purposes.
"""
# Transpose the matrix and get the length of the values in each column.
matrixT = [[] for x in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrixT[j].append(len(str(matrix[i][j])))
ndigits = map(max, matrixT)
for i in range(len(matrix)):
#Using string formatting trick to add leading spaces,
print " ".join("%*s " % (ndigits[j], matrix[i][j]) \
for j in range(len(matrix[i])))
def format_alignment(align1, align2, score, begin, end):
"""format_alignment(align1, align2, score, begin, end) -> string
Format the alignment prettily into a string.
"""
s = []
s.append("%s\n" % align1)
s.append("%s%s\n" % (" "*begin, "|"*(end-begin)))
s.append("%s\n" % align2)
s.append(" Score=%g\n" % score)
return ''.join(s)
# Try and load C implementations of functions. If I can't,
# then just ignore and use the pure python implementations.
try:
from cpairwise2 import rint, _make_score_matrix_fast
except ImportError:
pass
|
juliengdt/juliengdt-resources
|
refs/heads/master
|
node_modules/grunt-docker/node_modules/docker/node_modules/pygmentize-bundled/vendor/pygments/build-3.3/pygments/lexers/_clbuiltins.py
|
370
|
# -*- coding: utf-8 -*-
"""
pygments.lexers._clbuiltins
~~~~~~~~~~~~~~~~~~~~~~~~~~~
ANSI Common Lisp builtins.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
BUILTIN_FUNCTIONS = [ # 638 functions
'<', '<=', '=', '>', '>=', '-', '/', '/=', '*', '+', '1-', '1+',
'abort', 'abs', 'acons', 'acos', 'acosh', 'add-method', 'adjoin',
'adjustable-array-p', 'adjust-array', 'allocate-instance',
'alpha-char-p', 'alphanumericp', 'append', 'apply', 'apropos',
'apropos-list', 'aref', 'arithmetic-error-operands',
'arithmetic-error-operation', 'array-dimension', 'array-dimensions',
'array-displacement', 'array-element-type', 'array-has-fill-pointer-p',
'array-in-bounds-p', 'arrayp', 'array-rank', 'array-row-major-index',
'array-total-size', 'ash', 'asin', 'asinh', 'assoc', 'assoc-if',
'assoc-if-not', 'atan', 'atanh', 'atom', 'bit', 'bit-and', 'bit-andc1',
'bit-andc2', 'bit-eqv', 'bit-ior', 'bit-nand', 'bit-nor', 'bit-not',
'bit-orc1', 'bit-orc2', 'bit-vector-p', 'bit-xor', 'boole',
'both-case-p', 'boundp', 'break', 'broadcast-stream-streams',
'butlast', 'byte', 'byte-position', 'byte-size', 'caaaar', 'caaadr',
'caaar', 'caadar', 'caaddr', 'caadr', 'caar', 'cadaar', 'cadadr',
'cadar', 'caddar', 'cadddr', 'caddr', 'cadr', 'call-next-method', 'car',
'cdaaar', 'cdaadr', 'cdaar', 'cdadar', 'cdaddr', 'cdadr', 'cdar',
'cddaar', 'cddadr', 'cddar', 'cdddar', 'cddddr', 'cdddr', 'cddr', 'cdr',
'ceiling', 'cell-error-name', 'cerror', 'change-class', 'char', 'char<',
'char<=', 'char=', 'char>', 'char>=', 'char/=', 'character',
'characterp', 'char-code', 'char-downcase', 'char-equal',
'char-greaterp', 'char-int', 'char-lessp', 'char-name',
'char-not-equal', 'char-not-greaterp', 'char-not-lessp', 'char-upcase',
'cis', 'class-name', 'class-of', 'clear-input', 'clear-output',
'close', 'clrhash', 'code-char', 'coerce', 'compile',
'compiled-function-p', 'compile-file', 'compile-file-pathname',
'compiler-macro-function', 'complement', 'complex', 'complexp',
'compute-applicable-methods', 'compute-restarts', 'concatenate',
'concatenated-stream-streams', 'conjugate', 'cons', 'consp',
'constantly', 'constantp', 'continue', 'copy-alist', 'copy-list',
'copy-pprint-dispatch', 'copy-readtable', 'copy-seq', 'copy-structure',
'copy-symbol', 'copy-tree', 'cos', 'cosh', 'count', 'count-if',
'count-if-not', 'decode-float', 'decode-universal-time', 'delete',
'delete-duplicates', 'delete-file', 'delete-if', 'delete-if-not',
'delete-package', 'denominator', 'deposit-field', 'describe',
'describe-object', 'digit-char', 'digit-char-p', 'directory',
'directory-namestring', 'disassemble', 'documentation', 'dpb',
'dribble', 'echo-stream-input-stream', 'echo-stream-output-stream',
'ed', 'eighth', 'elt', 'encode-universal-time', 'endp',
'enough-namestring', 'ensure-directories-exist',
'ensure-generic-function', 'eq', 'eql', 'equal', 'equalp', 'error',
'eval', 'evenp', 'every', 'exp', 'export', 'expt', 'fboundp',
'fceiling', 'fdefinition', 'ffloor', 'fifth', 'file-author',
'file-error-pathname', 'file-length', 'file-namestring',
'file-position', 'file-string-length', 'file-write-date',
'fill', 'fill-pointer', 'find', 'find-all-symbols', 'find-class',
'find-if', 'find-if-not', 'find-method', 'find-package', 'find-restart',
'find-symbol', 'finish-output', 'first', 'float', 'float-digits',
'floatp', 'float-precision', 'float-radix', 'float-sign', 'floor',
'fmakunbound', 'force-output', 'format', 'fourth', 'fresh-line',
'fround', 'ftruncate', 'funcall', 'function-keywords',
'function-lambda-expression', 'functionp', 'gcd', 'gensym', 'gentemp',
'get', 'get-decoded-time', 'get-dispatch-macro-character', 'getf',
'gethash', 'get-internal-real-time', 'get-internal-run-time',
'get-macro-character', 'get-output-stream-string', 'get-properties',
'get-setf-expansion', 'get-universal-time', 'graphic-char-p',
'hash-table-count', 'hash-table-p', 'hash-table-rehash-size',
'hash-table-rehash-threshold', 'hash-table-size', 'hash-table-test',
'host-namestring', 'identity', 'imagpart', 'import',
'initialize-instance', 'input-stream-p', 'inspect',
'integer-decode-float', 'integer-length', 'integerp',
'interactive-stream-p', 'intern', 'intersection',
'invalid-method-error', 'invoke-debugger', 'invoke-restart',
'invoke-restart-interactively', 'isqrt', 'keywordp', 'last', 'lcm',
'ldb', 'ldb-test', 'ldiff', 'length', 'lisp-implementation-type',
'lisp-implementation-version', 'list', 'list*', 'list-all-packages',
'listen', 'list-length', 'listp', 'load',
'load-logical-pathname-translations', 'log', 'logand', 'logandc1',
'logandc2', 'logbitp', 'logcount', 'logeqv', 'logical-pathname',
'logical-pathname-translations', 'logior', 'lognand', 'lognor',
'lognot', 'logorc1', 'logorc2', 'logtest', 'logxor', 'long-site-name',
'lower-case-p', 'machine-instance', 'machine-type', 'machine-version',
'macroexpand', 'macroexpand-1', 'macro-function', 'make-array',
'make-broadcast-stream', 'make-concatenated-stream', 'make-condition',
'make-dispatch-macro-character', 'make-echo-stream', 'make-hash-table',
'make-instance', 'make-instances-obsolete', 'make-list',
'make-load-form', 'make-load-form-saving-slots', 'make-package',
'make-pathname', 'make-random-state', 'make-sequence', 'make-string',
'make-string-input-stream', 'make-string-output-stream', 'make-symbol',
'make-synonym-stream', 'make-two-way-stream', 'makunbound', 'map',
'mapc', 'mapcan', 'mapcar', 'mapcon', 'maphash', 'map-into', 'mapl',
'maplist', 'mask-field', 'max', 'member', 'member-if', 'member-if-not',
'merge', 'merge-pathnames', 'method-combination-error',
'method-qualifiers', 'min', 'minusp', 'mismatch', 'mod',
'muffle-warning', 'name-char', 'namestring', 'nbutlast', 'nconc',
'next-method-p', 'nintersection', 'ninth', 'no-applicable-method',
'no-next-method', 'not', 'notany', 'notevery', 'nreconc', 'nreverse',
'nset-difference', 'nset-exclusive-or', 'nstring-capitalize',
'nstring-downcase', 'nstring-upcase', 'nsublis', 'nsubst', 'nsubst-if',
'nsubst-if-not', 'nsubstitute', 'nsubstitute-if', 'nsubstitute-if-not',
'nth', 'nthcdr', 'null', 'numberp', 'numerator', 'nunion', 'oddp',
'open', 'open-stream-p', 'output-stream-p', 'package-error-package',
'package-name', 'package-nicknames', 'packagep',
'package-shadowing-symbols', 'package-used-by-list', 'package-use-list',
'pairlis', 'parse-integer', 'parse-namestring', 'pathname',
'pathname-device', 'pathname-directory', 'pathname-host',
'pathname-match-p', 'pathname-name', 'pathnamep', 'pathname-type',
'pathname-version', 'peek-char', 'phase', 'plusp', 'position',
'position-if', 'position-if-not', 'pprint', 'pprint-dispatch',
'pprint-fill', 'pprint-indent', 'pprint-linear', 'pprint-newline',
'pprint-tab', 'pprint-tabular', 'prin1', 'prin1-to-string', 'princ',
'princ-to-string', 'print', 'print-object', 'probe-file', 'proclaim',
'provide', 'random', 'random-state-p', 'rassoc', 'rassoc-if',
'rassoc-if-not', 'rational', 'rationalize', 'rationalp', 'read',
'read-byte', 'read-char', 'read-char-no-hang', 'read-delimited-list',
'read-from-string', 'read-line', 'read-preserving-whitespace',
'read-sequence', 'readtable-case', 'readtablep', 'realp', 'realpart',
'reduce', 'reinitialize-instance', 'rem', 'remhash', 'remove',
'remove-duplicates', 'remove-if', 'remove-if-not', 'remove-method',
'remprop', 'rename-file', 'rename-package', 'replace', 'require',
'rest', 'restart-name', 'revappend', 'reverse', 'room', 'round',
'row-major-aref', 'rplaca', 'rplacd', 'sbit', 'scale-float', 'schar',
'search', 'second', 'set', 'set-difference',
'set-dispatch-macro-character', 'set-exclusive-or',
'set-macro-character', 'set-pprint-dispatch', 'set-syntax-from-char',
'seventh', 'shadow', 'shadowing-import', 'shared-initialize',
'short-site-name', 'signal', 'signum', 'simple-bit-vector-p',
'simple-condition-format-arguments', 'simple-condition-format-control',
'simple-string-p', 'simple-vector-p', 'sin', 'sinh', 'sixth', 'sleep',
'slot-boundp', 'slot-exists-p', 'slot-makunbound', 'slot-missing',
'slot-unbound', 'slot-value', 'software-type', 'software-version',
'some', 'sort', 'special-operator-p', 'sqrt', 'stable-sort',
'standard-char-p', 'store-value', 'stream-element-type',
'stream-error-stream', 'stream-external-format', 'streamp', 'string',
'string<', 'string<=', 'string=', 'string>', 'string>=', 'string/=',
'string-capitalize', 'string-downcase', 'string-equal',
'string-greaterp', 'string-left-trim', 'string-lessp',
'string-not-equal', 'string-not-greaterp', 'string-not-lessp',
'stringp', 'string-right-trim', 'string-trim', 'string-upcase',
'sublis', 'subseq', 'subsetp', 'subst', 'subst-if', 'subst-if-not',
'substitute', 'substitute-if', 'substitute-if-not', 'subtypep','svref',
'sxhash', 'symbol-function', 'symbol-name', 'symbolp', 'symbol-package',
'symbol-plist', 'symbol-value', 'synonym-stream-symbol', 'syntax:',
'tailp', 'tan', 'tanh', 'tenth', 'terpri', 'third',
'translate-logical-pathname', 'translate-pathname', 'tree-equal',
'truename', 'truncate', 'two-way-stream-input-stream',
'two-way-stream-output-stream', 'type-error-datum',
'type-error-expected-type', 'type-of', 'typep', 'unbound-slot-instance',
'unexport', 'unintern', 'union', 'unread-char', 'unuse-package',
'update-instance-for-different-class',
'update-instance-for-redefined-class', 'upgraded-array-element-type',
'upgraded-complex-part-type', 'upper-case-p', 'use-package',
'user-homedir-pathname', 'use-value', 'values', 'values-list', 'vector',
'vectorp', 'vector-pop', 'vector-push', 'vector-push-extend', 'warn',
'wild-pathname-p', 'write', 'write-byte', 'write-char', 'write-line',
'write-sequence', 'write-string', 'write-to-string', 'yes-or-no-p',
'y-or-n-p', 'zerop',
]
SPECIAL_FORMS = [
'block', 'catch', 'declare', 'eval-when', 'flet', 'function', 'go', 'if',
'labels', 'lambda', 'let', 'let*', 'load-time-value', 'locally', 'macrolet',
'multiple-value-call', 'multiple-value-prog1', 'progn', 'progv', 'quote',
'return-from', 'setq', 'symbol-macrolet', 'tagbody', 'the', 'throw',
'unwind-protect',
]
MACROS = [
'and', 'assert', 'call-method', 'case', 'ccase', 'check-type', 'cond',
'ctypecase', 'decf', 'declaim', 'defclass', 'defconstant', 'defgeneric',
'define-compiler-macro', 'define-condition', 'define-method-combination',
'define-modify-macro', 'define-setf-expander', 'define-symbol-macro',
'defmacro', 'defmethod', 'defpackage', 'defparameter', 'defsetf',
'defstruct', 'deftype', 'defun', 'defvar', 'destructuring-bind', 'do',
'do*', 'do-all-symbols', 'do-external-symbols', 'dolist', 'do-symbols',
'dotimes', 'ecase', 'etypecase', 'formatter', 'handler-bind',
'handler-case', 'ignore-errors', 'incf', 'in-package', 'lambda', 'loop',
'loop-finish', 'make-method', 'multiple-value-bind', 'multiple-value-list',
'multiple-value-setq', 'nth-value', 'or', 'pop',
'pprint-exit-if-list-exhausted', 'pprint-logical-block', 'pprint-pop',
'print-unreadable-object', 'prog', 'prog*', 'prog1', 'prog2', 'psetf',
'psetq', 'push', 'pushnew', 'remf', 'restart-bind', 'restart-case',
'return', 'rotatef', 'setf', 'shiftf', 'step', 'time', 'trace', 'typecase',
'unless', 'untrace', 'when', 'with-accessors', 'with-compilation-unit',
'with-condition-restarts', 'with-hash-table-iterator',
'with-input-from-string', 'with-open-file', 'with-open-stream',
'with-output-to-string', 'with-package-iterator', 'with-simple-restart',
'with-slots', 'with-standard-io-syntax',
]
LAMBDA_LIST_KEYWORDS = [
'&allow-other-keys', '&aux', '&body', '&environment', '&key', '&optional',
'&rest', '&whole',
]
DECLARATIONS = [
'dynamic-extent', 'ignore', 'optimize', 'ftype', 'inline', 'special',
'ignorable', 'notinline', 'type',
]
BUILTIN_TYPES = [
'atom', 'boolean', 'base-char', 'base-string', 'bignum', 'bit',
'compiled-function', 'extended-char', 'fixnum', 'keyword', 'nil',
'signed-byte', 'short-float', 'single-float', 'double-float', 'long-float',
'simple-array', 'simple-base-string', 'simple-bit-vector', 'simple-string',
'simple-vector', 'standard-char', 'unsigned-byte',
# Condition Types
'arithmetic-error', 'cell-error', 'condition', 'control-error',
'division-by-zero', 'end-of-file', 'error', 'file-error',
'floating-point-inexact', 'floating-point-overflow',
'floating-point-underflow', 'floating-point-invalid-operation',
'parse-error', 'package-error', 'print-not-readable', 'program-error',
'reader-error', 'serious-condition', 'simple-condition', 'simple-error',
'simple-type-error', 'simple-warning', 'stream-error', 'storage-condition',
'style-warning', 'type-error', 'unbound-variable', 'unbound-slot',
'undefined-function', 'warning',
]
BUILTIN_CLASSES = [
'array', 'broadcast-stream', 'bit-vector', 'built-in-class', 'character',
'class', 'complex', 'concatenated-stream', 'cons', 'echo-stream',
'file-stream', 'float', 'function', 'generic-function', 'hash-table',
'integer', 'list', 'logical-pathname', 'method-combination', 'method',
'null', 'number', 'package', 'pathname', 'ratio', 'rational', 'readtable',
'real', 'random-state', 'restart', 'sequence', 'standard-class',
'standard-generic-function', 'standard-method', 'standard-object',
'string-stream', 'stream', 'string', 'structure-class', 'structure-object',
'symbol', 'synonym-stream', 't', 'two-way-stream', 'vector',
]
|
billonahill/heron
|
refs/heads/master
|
heron/statemgrs/src/python/statemanager.py
|
8
|
# Copyright 2016 Twitter. 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.
''' statemanager.py '''
import abc
import socket
import subprocess
from heron.statemgrs.src.python.log import Log as LOG
HERON_EXECUTION_STATE_PREFIX = "{0}/executionstate/"
HERON_PACKING_PLANS_PREFIX = "{0}/packingplans/"
HERON_PPLANS_PREFIX = "{0}/pplans/"
HERON_SCHEDULER_LOCATION_PREFIX = "{0}/schedulers/"
HERON_TMASTER_PREFIX = "{0}/tmasters/"
HERON_TOPOLOGIES_KEY = "{0}/topologies"
# pylint: disable=too-many-public-methods, attribute-defined-outside-init
class StateManager:
"""
This is the abstract base class for state manager. It provides methods to get/set/delete various
state from the state store. The getters accept an optional callback, which will watch for state
changes of the object and invoke the callback when one occurs.
"""
__metaclass__ = abc.ABCMeta
@property
def name(self):
return self.__name
@name.setter
def name(self, newName):
self.__name = newName
@property
def hostportlist(self):
return self.__hostportlist
@hostportlist.setter
def hostportlist(self, newHostportList):
self.__hostportlist = newHostportList
@property
def rootpath(self):
""" Getter for the path where the heron states are stored. """
return self.__hostport
@rootpath.setter
def rootpath(self, newRootPath):
""" Setter for the path where the heron states are stored. """
self.__hostport = newRootPath
@property
def tunnelhost(self):
""" Getter for the tunnelhost to create the tunnel if host is not accessible """
return self.__tunnelhost
@tunnelhost.setter
def tunnelhost(self, newTunnelHost):
""" Setter for the tunnelhost to create the tunnel if host is not accessible """
self.__tunnelhost = newTunnelHost
def __init__(self):
self.tunnel = []
def is_host_port_reachable(self):
"""
Returns true if the host is reachable. In some cases, it may not be reachable a tunnel
must be used.
"""
for hostport in self.hostportlist:
try:
socket.create_connection(hostport, 2)
return True
except:
LOG.info("StateManager %s Unable to connect to host: %s port %i"
% (self.name, hostport[0], hostport[1]))
continue
return False
# pylint: disable=no-self-use
def pick_unused_port(self):
""" Pick an unused port. There is a slight chance that this wont work. """
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 0))
_, port = s.getsockname()
s.close()
return port
def establish_ssh_tunnel(self):
"""
Establish an ssh tunnel for each local host and port
that can be used to communicate with the state host.
"""
localportlist = []
for (host, port) in self.hostportlist:
localport = self.pick_unused_port()
self.tunnel.append(subprocess.Popen(
('ssh', self.tunnelhost, '-NL127.0.0.1:%d:%s:%d' % (localport, host, port))))
localportlist.append(('127.0.0.1', localport))
return localportlist
def terminate_ssh_tunnel(self):
for tunnel in self.tunnel:
tunnel.terminate()
@abc.abstractmethod
def start(self):
""" If the state manager needs to connect to a remote host. """
pass
@abc.abstractmethod
def stop(self):
""" If the state manager had connected to a remote server, it would need to stop as well. """
pass
def get_topologies_path(self):
return HERON_TOPOLOGIES_KEY.format(self.rootpath)
def get_topology_path(self, topologyName):
return HERON_TOPOLOGIES_KEY.format(self.rootpath) + "/" + topologyName
def get_packing_plan_path(self, topologyName):
return HERON_PACKING_PLANS_PREFIX.format(self.rootpath) + topologyName
def get_pplan_path(self, topologyName):
return HERON_PPLANS_PREFIX.format(self.rootpath) + topologyName
def get_execution_state_path(self, topologyName):
return HERON_EXECUTION_STATE_PREFIX.format(self.rootpath) + topologyName
def get_tmaster_path(self, topologyName):
return HERON_TMASTER_PREFIX.format(self.rootpath) + topologyName
def get_scheduler_location_path(self, topologyName):
return HERON_SCHEDULER_LOCATION_PREFIX.format(self.rootpath) + topologyName
@abc.abstractmethod
def get_topologies(self, callback=None):
pass
@abc.abstractmethod
def get_topology(self, topologyName, callback=None):
pass
@abc.abstractmethod
def create_topology(self, topologyName, topology):
pass
@abc.abstractmethod
def delete_topology(self, topologyName):
pass
@abc.abstractmethod
def get_packing_plan(self, topologyName, callback=None):
"""
Gets the packing_plan for the topology.
If the callback is provided,
sets watch on the path and calls the callback
with the new packing_plan.
"""
pass
@abc.abstractmethod
def get_pplan(self, topologyName, callback=None):
pass
@abc.abstractmethod
def create_pplan(self, topologyName, pplan):
pass
@abc.abstractmethod
def delete_pplan(self, topologyName):
pass
@abc.abstractmethod
def get_execution_state(self, topologyName, callback=None):
pass
@abc.abstractmethod
def create_execution_state(self, topologyName, executionState):
pass
@abc.abstractmethod
def delete_execution_state(self, topologyName):
pass
@abc.abstractmethod
def get_tmaster(self, topologyName, callback=None):
pass
@abc.abstractmethod
def get_scheduler_location(self, topologyName, callback=None):
pass
def delete_topology_from_zk(self, topologyName):
"""
Removes the topology entry from:
1. topologies list,
2. pplan,
3. execution_state, and
"""
self.delete_pplan(topologyName)
self.delete_execution_state(topologyName)
self.delete_topology(topologyName)
|
HighSchoolHacking/GLS
|
refs/heads/master
|
test/integration/Concatenate/three strings.py
|
4
|
#
aaa + bbb + ccc
#
|
GMadorell/Shades
|
refs/heads/master
|
Code/Pieces/Systems/LastStepSystem.py
|
1
|
import larv
from Globals import *
class LastStepSystem(larv.System):
"""
Does the last steps of the game loop:
- Updates physics engine (if physics bool is True)
- Updates pygame display
- Sets the frame clock correctly
"""
def __init__(self, physics = True):
self.physics = physics
def update(self):
# Update the physics engine
if self.physics:
SPACE.step(1/FPS)
# Update the window (paint everything)
pygame.display.flip()
# Wait so FPS get accomplished
FPS_CLOCK.tick(FPS)
|
13xforever/webserver
|
refs/heads/master
|
qa/270-Options-asterisk1.py
|
7
|
from base import *
class Test (TestBase):
def __init__ (self):
TestBase.__init__ (self, __file__)
self.name = "OPTIONS *"
self.request = "OPTIONS * HTTP/1.0\r\n" % (globals())
self.expected_error = 200
self.expected_content = ["Content-Length: 0"]
self.forbidden_content = ["Bad Request"]
|
minghuadev/chromeos-kernel-3-8
|
refs/heads/chromeos-3.8
|
scripts/tracing/draw_functrace.py
|
14679
|
#!/usr/bin/python
"""
Copyright 2008 (c) Frederic Weisbecker <[email protected]>
Licensed under the terms of the GNU GPL License version 2
This script parses a trace provided by the function tracer in
kernel/trace/trace_functions.c
The resulted trace is processed into a tree to produce a more human
view of the call stack by drawing textual but hierarchical tree of
calls. Only the functions's names and the the call time are provided.
Usage:
Be sure that you have CONFIG_FUNCTION_TRACER
# mount -t debugfs nodev /sys/kernel/debug
# echo function > /sys/kernel/debug/tracing/current_tracer
$ cat /sys/kernel/debug/tracing/trace_pipe > ~/raw_trace_func
Wait some times but not too much, the script is a bit slow.
Break the pipe (Ctrl + Z)
$ scripts/draw_functrace.py < raw_trace_func > draw_functrace
Then you have your drawn trace in draw_functrace
"""
import sys, re
class CallTree:
""" This class provides a tree representation of the functions
call stack. If a function has no parent in the kernel (interrupt,
syscall, kernel thread...) then it is attached to a virtual parent
called ROOT.
"""
ROOT = None
def __init__(self, func, time = None, parent = None):
self._func = func
self._time = time
if parent is None:
self._parent = CallTree.ROOT
else:
self._parent = parent
self._children = []
def calls(self, func, calltime):
""" If a function calls another one, call this method to insert it
into the tree at the appropriate place.
@return: A reference to the newly created child node.
"""
child = CallTree(func, calltime, self)
self._children.append(child)
return child
def getParent(self, func):
""" Retrieve the last parent of the current node that
has the name given by func. If this function is not
on a parent, then create it as new child of root
@return: A reference to the parent.
"""
tree = self
while tree != CallTree.ROOT and tree._func != func:
tree = tree._parent
if tree == CallTree.ROOT:
child = CallTree.ROOT.calls(func, None)
return child
return tree
def __repr__(self):
return self.__toString("", True)
def __toString(self, branch, lastChild):
if self._time is not None:
s = "%s----%s (%s)\n" % (branch, self._func, self._time)
else:
s = "%s----%s\n" % (branch, self._func)
i = 0
if lastChild:
branch = branch[:-1] + " "
while i < len(self._children):
if i != len(self._children) - 1:
s += "%s" % self._children[i].__toString(branch +\
" |", False)
else:
s += "%s" % self._children[i].__toString(branch +\
" |", True)
i += 1
return s
class BrokenLineException(Exception):
"""If the last line is not complete because of the pipe breakage,
we want to stop the processing and ignore this line.
"""
pass
class CommentLineException(Exception):
""" If the line is a comment (as in the beginning of the trace file),
just ignore it.
"""
pass
def parseLine(line):
line = line.strip()
if line.startswith("#"):
raise CommentLineException
m = re.match("[^]]+?\\] +([0-9.]+): (\\w+) <-(\\w+)", line)
if m is None:
raise BrokenLineException
return (m.group(1), m.group(2), m.group(3))
def main():
CallTree.ROOT = CallTree("Root (Nowhere)", None, None)
tree = CallTree.ROOT
for line in sys.stdin:
try:
calltime, callee, caller = parseLine(line)
except BrokenLineException:
break
except CommentLineException:
continue
tree = tree.getParent(caller)
tree = tree.calls(callee, calltime)
print CallTree.ROOT
if __name__ == "__main__":
main()
|
ademinn/AdaptiveIPFilter
|
refs/heads/master
|
.ycm_extra_conf.py
|
1
|
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# 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 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.
#
# For more information, please refer to <http://unlicense.org/>
import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
# You 100% do NOT need -DUSE_CLANG_COMPLETER in your flags; only the YCM
# source code needs it.
'-DUSE_CLANG_COMPLETER',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c++11',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
'-isystem',
'../BoostParts',
'-isystem',
# This path will only work on OS X, but extra paths that don't exist are not
# harmful
'/System/Library/Frameworks/Python.framework/Headers',
'-isystem',
'../llvm/include',
'-isystem',
'../llvm/tools/clang/include',
'-I',
'.',
'-I',
'./ClangCompleter',
'-isystem',
'./tests/gmock/gtest',
'-isystem',
'./tests/gmock/gtest/include',
'-isystem',
'./tests/gmock',
'-isystem',
'./tests/gmock/include',
'-isystem',
'/usr/include',
'-isystem',
'/usr/local/include',
'-isystem',
'/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1',
'-isystem',
'/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include',
]
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# You can get CMake to generate this file for you by adding:
# set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''
if os.path.exists( compilation_database_folder ):
database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
database = None
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
if not working_directory:
return list( flags )
new_flags = []
make_next_absolute = False
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
for flag in flags:
new_flag = flag
if make_next_absolute:
make_next_absolute = False
if not flag.startswith( '/' ):
new_flag = os.path.join( working_directory, flag )
for path_flag in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith( path_flag ):
path = flag[ len( path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag:
new_flags.append( new_flag )
return new_flags
def IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def GetCompilationInfoForFile( filename ):
# The compilation_commands.json file generated by CMake does not have entries
# for header files. So we do our best by asking the db for flags for a
# corresponding source file, if any. If one exists, the flags for that file
# should be good enough.
if IsHeaderFile( filename ):
basename = os.path.splitext( filename )[ 0 ]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if os.path.exists( replacement_file ):
compilation_info = database.GetCompilationInfoForFile(
replacement_file )
if compilation_info.compiler_flags_:
return compilation_info
return None
return database.GetCompilationInfoForFile( filename )
def FlagsForFile( filename, **kwargs ):
if database:
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
# python list, but a "list-like" StringVec object
compilation_info = GetCompilationInfoForFile( filename )
if not compilation_info:
return None
final_flags = MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_ )
# NOTE: This is just for YouCompleteMe; it's highly likely that your project
# does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
# ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.
try:
final_flags.remove( '-stdlib=libc++' )
except ValueError:
pass
else:
relative_to = DirectoryOfThisScript()
final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )
return {
'flags': final_flags,
'do_cache': True
}
|
wdv4758h/ZipPy
|
refs/heads/master
|
lib-python/3/encodings/shift_jisx0213.py
|
816
|
#
# shift_jisx0213.py: Python Unicode Codec for SHIFT_JISX0213
#
# Written by Hye-Shik Chang <[email protected]>
#
import _codecs_jp, codecs
import _multibytecodec as mbc
codec = _codecs_jp.getcodec('shift_jisx0213')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.MultibyteIncrementalEncoder,
codecs.IncrementalEncoder):
codec = codec
class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
codecs.IncrementalDecoder):
codec = codec
class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
codec = codec
class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
codec = codec
def getregentry():
return codecs.CodecInfo(
name='shift_jisx0213',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
|
philmui/django-boiler
|
refs/heads/master
|
lists/migrations/0002_item_text.py
|
2
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('lists', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='item',
name='text',
field=models.TextField(default=''),
preserve_default=False,
),
]
|
apagac/cfme_tests
|
refs/heads/master
|
scripts/cleanup_openstack_instance_snapshot.py
|
2
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cleanup unused instance snapshot from glance repository
Usage: scripts/cleanup_openstack_instance_snapshot.py [optional list of provider keys]
If no providers specified, it will cleanup all of them.
"""
import argparse
from datetime import datetime
from datetime import timedelta
import tzlocal
from cfme.utils.log import add_stdout_handler
from cfme.utils.log import logger
from cfme.utils.providers import get_mgmt
from cfme.utils.providers import list_provider_keys
LOCAL_TZ = tzlocal.get_localzone()
GRACE_TIME = timedelta(hours=2)
TIME_LIMIT = datetime.now(tz=LOCAL_TZ) - GRACE_TIME
# log to stdout too
add_stdout_handler(logger)
def parse_cmd_line():
parser = argparse.ArgumentParser(argument_default=None)
parser.add_argument('--name', default='test_snapshot_',
help='Starting pettern of snaphsot name '
'e.g. --name test_ delete all snapshot starting with test_')
parser.add_argument('--providers', default=list_provider_keys("openstack"), nargs='+',
help='List of provider keys e.g. --providers rhos13 rhos12'
)
args = parser.parse_args()
return args
def main(args):
""" Cleanup all snapshots name starting with test_snapshot and created by >= 2 hours before
:param providers: Lists provider keys
:return:
"""
for provider_key in args.providers:
logger.info("Cleaning up {}".format(provider_key))
provider_obj = get_mgmt(provider_key)
try:
images = provider_obj.list_templates()
except Exception:
logger.exception("Unable to get the list of templates")
continue
for img in images:
if img.name.startswith(args.name) and img.creation_time < TIME_LIMIT:
logger.info("Deleting {}".format(img.name))
try:
img.delete()
except Exception:
logger.exception("Snapshot {} Deletion failed".format(img.name))
if __name__ == "__main__":
main(parse_cmd_line())
|
suncycheng/intellij-community
|
refs/heads/master
|
python/testData/docstrings/simpleGoogleDocString.py
|
53
|
def func(x, y, *args, **kwargs):
"""Summary
Parameters:
x (int) : first parameter
y: second parameter
with longer description
Raises:
Exception: if anything bad happens
Returns:
None: always
"""
pass
|
Elandril/SickRage
|
refs/heads/master
|
lib/hachoir_core/language.py
|
95
|
from hachoir_core.iso639 import ISO639_2
class Language:
def __init__(self, code):
code = str(code)
if code not in ISO639_2:
raise ValueError("Invalid language code: %r" % code)
self.code = code
def __cmp__(self, other):
if other.__class__ != Language:
return 1
return cmp(self.code, other.code)
def __unicode__(self):
return ISO639_2[self.code]
def __str__(self):
return self.__unicode__()
def __repr__(self):
return "<Language '%s', code=%r>" % (unicode(self), self.code)
|
AOSP-S4-KK/platform_external_chromium_org
|
refs/heads/kk-4.4
|
build/android/pylib/perf/surface_stats_collector.py
|
26
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import Queue
import datetime
import logging
import re
import threading
# Log marker containing SurfaceTexture timestamps.
_SURFACE_TEXTURE_TIMESTAMPS_MESSAGE = 'SurfaceTexture update timestamps'
_SURFACE_TEXTURE_TIMESTAMP_RE = '\d+'
_MIN_NORMALIZED_FRAME_LENGTH = 0.5
class SurfaceStatsCollector(object):
"""Collects surface stats for a SurfaceView from the output of SurfaceFlinger.
Args:
adb: the adb connection to use.
"""
class Result(object):
def __init__(self, name, value, unit):
self.name = name
self.value = value
self.unit = unit
def __init__(self, adb):
self._adb = adb
self._collector_thread = None
self._use_legacy_method = False
self._surface_before = None
self._get_data_event = None
self._data_queue = None
self._stop_event = None
self._results = []
self._warn_about_empty_data = True
def DisableWarningAboutEmptyData(self):
self._warn_about_empty_data = False
def Start(self):
assert not self._collector_thread
if self._ClearSurfaceFlingerLatencyData():
self._get_data_event = threading.Event()
self._stop_event = threading.Event()
self._data_queue = Queue.Queue()
self._collector_thread = threading.Thread(target=self._CollectorThread)
self._collector_thread.start()
else:
self._use_legacy_method = True
self._surface_before = self._GetSurfaceStatsLegacy()
def Stop(self):
self._StorePerfResults()
if self._collector_thread:
self._stop_event.set()
self._collector_thread.join()
self._collector_thread = None
def SampleResults(self):
self._StorePerfResults()
results = self.GetResults()
self._results = []
return results
def GetResults(self):
return self._results or self._GetEmptyResults()
def _GetEmptyResults(self):
return [
SurfaceStatsCollector.Result('refresh_period', None, 'seconds'),
SurfaceStatsCollector.Result('jank_count', None, 'janks'),
SurfaceStatsCollector.Result('max_frame_delay', None, 'vsyncs'),
SurfaceStatsCollector.Result('frame_lengths', None, 'vsyncs'),
SurfaceStatsCollector.Result('avg_surface_fps', None, 'fps')
]
@staticmethod
def _GetNormalizedDeltas(data, refresh_period, min_normalized_delta=None):
deltas = [t2 - t1 for t1, t2 in zip(data, data[1:])]
if min_normalized_delta != None:
deltas = filter(lambda d: d / refresh_period >= min_normalized_delta,
deltas)
return (deltas, [delta / refresh_period for delta in deltas])
@staticmethod
def _CalculateResults(refresh_period, timestamps, result_suffix):
"""Returns a list of SurfaceStatsCollector.Result."""
frame_count = len(timestamps)
seconds = timestamps[-1] - timestamps[0]
frame_lengths, normalized_frame_lengths = \
SurfaceStatsCollector._GetNormalizedDeltas(
timestamps, refresh_period, _MIN_NORMALIZED_FRAME_LENGTH)
if len(frame_lengths) < frame_count - 1:
logging.warning('Skipping frame lengths that are too short.')
frame_count = len(frame_lengths) + 1
if len(frame_lengths) == 0:
raise Exception('No valid frames lengths found.')
length_changes, normalized_changes = \
SurfaceStatsCollector._GetNormalizedDeltas(
frame_lengths, refresh_period)
jankiness = [max(0, round(change)) for change in normalized_changes]
pause_threshold = 20
jank_count = sum(1 for change in jankiness
if change > 0 and change < pause_threshold)
return [
SurfaceStatsCollector.Result(
'avg_surface_fps' + result_suffix,
int(round((frame_count - 1) / seconds)), 'fps'),
SurfaceStatsCollector.Result(
'jank_count' + result_suffix, jank_count, 'janks'),
SurfaceStatsCollector.Result(
'max_frame_delay' + result_suffix,
round(max(normalized_frame_lengths)),
'vsyncs'),
SurfaceStatsCollector.Result(
'frame_lengths' + result_suffix, normalized_frame_lengths,
'vsyncs'),
]
@staticmethod
def _CalculateBuckets(refresh_period, timestamps):
results = []
for pct in [0.99, 0.5]:
sliced = timestamps[min(int(-pct * len(timestamps)), -3) : ]
results += SurfaceStatsCollector._CalculateResults(
refresh_period, sliced, '_' + str(int(pct * 100)))
return results
def _StorePerfResults(self):
if self._use_legacy_method:
surface_after = self._GetSurfaceStatsLegacy()
td = surface_after['timestamp'] - self._surface_before['timestamp']
seconds = td.seconds + td.microseconds / 1e6
frame_count = (surface_after['page_flip_count'] -
self._surface_before['page_flip_count'])
self._results.append(SurfaceStatsCollector.Result(
'avg_surface_fps', int(round(frame_count / seconds)), 'fps'))
return
# Non-legacy method.
assert self._collector_thread
(refresh_period, timestamps) = self._GetDataFromThread()
if not refresh_period or not len(timestamps) >= 3:
if self._warn_about_empty_data:
logging.warning('Surface stat data is empty')
return
self._results.append(SurfaceStatsCollector.Result(
'refresh_period', refresh_period, 'seconds'))
self._results += self._CalculateResults(refresh_period, timestamps, '')
self._results += self._CalculateBuckets(refresh_period, timestamps)
def _CollectorThread(self):
last_timestamp = 0
timestamps = []
retries = 0
while not self._stop_event.is_set():
self._get_data_event.wait(1)
try:
refresh_period, new_timestamps = self._GetSurfaceFlingerFrameData()
if refresh_period is None or timestamps is None:
retries += 1
if retries < 3:
continue
if last_timestamp:
# Some data has already been collected, but either the app
# was closed or there's no new data. Signal the main thread and
# wait.
self._data_queue.put((None, None))
self._stop_event.wait()
break
raise Exception('Unable to get surface flinger latency data')
timestamps += [timestamp for timestamp in new_timestamps
if timestamp > last_timestamp]
if len(timestamps):
last_timestamp = timestamps[-1]
if self._get_data_event.is_set():
self._get_data_event.clear()
self._data_queue.put((refresh_period, timestamps))
timestamps = []
except Exception as e:
# On any error, before aborting, put the exception into _data_queue to
# prevent the main thread from waiting at _data_queue.get() infinitely.
self._data_queue.put(e)
raise
def _GetDataFromThread(self):
self._get_data_event.set()
ret = self._data_queue.get()
if isinstance(ret, Exception):
raise ret
return ret
def _ClearSurfaceFlingerLatencyData(self):
"""Clears the SurfaceFlinger latency data.
Returns:
True if SurfaceFlinger latency is supported by the device, otherwise
False.
"""
# The command returns nothing if it is supported, otherwise returns many
# lines of result just like 'dumpsys SurfaceFlinger'.
results = self._adb.RunShellCommand(
'dumpsys SurfaceFlinger --latency-clear SurfaceView')
return not len(results)
def _GetSurfaceFlingerFrameData(self):
"""Returns collected SurfaceFlinger frame timing data.
Returns:
A tuple containing:
- The display's nominal refresh period in seconds.
- A list of timestamps signifying frame presentation times in seconds.
The return value may be (None, None) if there was no data collected (for
example, if the app was closed before the collector thread has finished).
"""
# adb shell dumpsys SurfaceFlinger --latency <window name>
# prints some information about the last 128 frames displayed in
# that window.
# The data returned looks like this:
# 16954612
# 7657467895508 7657482691352 7657493499756
# 7657484466553 7657499645964 7657511077881
# 7657500793457 7657516600576 7657527404785
# (...)
#
# The first line is the refresh period (here 16.95 ms), it is followed
# by 128 lines w/ 3 timestamps in nanosecond each:
# A) when the app started to draw
# B) the vsync immediately preceding SF submitting the frame to the h/w
# C) timestamp immediately after SF submitted that frame to the h/w
#
# The difference between the 1st and 3rd timestamp is the frame-latency.
# An interesting data is when the frame latency crosses a refresh period
# boundary, this can be calculated this way:
#
# ceil((C - A) / refresh-period)
#
# (each time the number above changes, we have a "jank").
# If this happens a lot during an animation, the animation appears
# janky, even if it runs at 60 fps in average.
#
# We use the special "SurfaceView" window name because the statistics for
# the activity's main window are not updated when the main web content is
# composited into a SurfaceView.
results = self._adb.RunShellCommand(
'dumpsys SurfaceFlinger --latency SurfaceView',
log_result=logging.getLogger().isEnabledFor(logging.DEBUG))
if not len(results):
return (None, None)
timestamps = []
nanoseconds_per_second = 1e9
refresh_period = long(results[0]) / nanoseconds_per_second
# If a fence associated with a frame is still pending when we query the
# latency data, SurfaceFlinger gives the frame a timestamp of INT64_MAX.
# Since we only care about completed frames, we will ignore any timestamps
# with this value.
pending_fence_timestamp = (1 << 63) - 1
for line in results[1:]:
fields = line.split()
if len(fields) != 3:
continue
timestamp = long(fields[1])
if timestamp == pending_fence_timestamp:
continue
timestamp /= nanoseconds_per_second
timestamps.append(timestamp)
return (refresh_period, timestamps)
def _GetSurfaceStatsLegacy(self):
"""Legacy method (before JellyBean), returns the current Surface index
and timestamp.
Calculate FPS by measuring the difference of Surface index returned by
SurfaceFlinger in a period of time.
Returns:
Dict of {page_flip_count (or 0 if there was an error), timestamp}.
"""
results = self._adb.RunShellCommand('service call SurfaceFlinger 1013')
assert len(results) == 1
match = re.search('^Result: Parcel\((\w+)', results[0])
cur_surface = 0
if match:
try:
cur_surface = int(match.group(1), 16)
except Exception:
logging.error('Failed to parse current surface from ' + match.group(1))
else:
logging.warning('Failed to call SurfaceFlinger surface ' + results[0])
return {
'page_flip_count': cur_surface,
'timestamp': datetime.datetime.now(),
}
|
acsone/server-tools
|
refs/heads/8.0
|
super_calendar/models/super_calendar.py
|
37
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Management Solution
#
# Copyright (c) All rights reserved:
# (c) 2012 Agile Business Group sagl (<http://www.agilebg.com>)
# (c) 2012 Domsense srl (<http://www.domsense.com>)
# (c) 2015 Anubía, soluciones en la nube,SL (http://www.anubia.es)
# Alejandro Santana <[email protected]>
# (c) 2015 Savoir-faire Linux <http://www.savoirfairelinux.com>)
# Agathe Mollé <[email protected]>
#
# 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
#
##############################################################################
from openerp import fields, models
def _models_get(self):
model_obj = self.env['ir.model']
model_list = model_obj.search([])
return [(model.model, model.name) for model in model_list]
class SuperCalendar(models.Model):
_name = 'super.calendar'
name = fields.Char(
string='Description',
required=True,
readonly=True,
)
date_start = fields.Datetime(
string='Start date',
required=True,
readonly=True,
)
duration = fields.Float(
string='Duration',
readonly=True,
)
user_id = fields.Many2one(
comodel_name='res.users',
string='User',
readonly=True,
)
configurator_id = fields.Many2one(
comodel_name='super.calendar.configurator',
string='Configurator',
readonly=True,
)
res_id = fields.Reference(
selection=_models_get,
string='Resource',
readonly=True,
)
model_id = fields.Many2one(
comodel_name='ir.model',
string='Model',
readonly=True,
)
|
ollien/Timpani
|
refs/heads/master
|
timpani/webserver/controllers/admin.py
|
1
|
import flask
import os.path
import datetime
import json
import uuid
import magic
import mimetypes
from sqlalchemy.exc import IntegrityError
from .. import webhelpers
from ... import blog
from ... import auth
from ... import themes
from ... import settings
FILE_LOCATION = os.path.abspath(os.path.dirname(__file__))
CONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../../configs/"))
TEMPLATE_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../../templates"))
UPLOAD_LOCATION = os.path.abspath(os.path.join(FILE_LOCATION, "../../../static/uploads"))
blueprint = flask.Blueprint("admin", __name__, template_folder=TEMPLATE_PATH)
@blueprint.route("/manage")
@webhelpers.checkUserPermissions("/login", saveRedirect=False)
def manage():
return flask.render_template("manage.html",
user=webhelpers.checkForSession().user)
@blueprint.route("/add_post", methods=["GET", "POST"])
@webhelpers.checkUserPermissions("/manage",
requiredPermissions=auth.CAN_POST_PERMISSION)
def addPost():
if flask.request.method == "GET":
return flask.render_template("add_post.html",
user=webhelpers.checkForSession().user)
elif flask.request.method == "POST":
postTitle = flask.request.form["post-title"]
postBody = flask.request.form["post-body"].replace("\t", " ")
postBody = flask.request.form["post-body"].replace(" ", " ")
postTags = flask.request.form["post-tags"]
blog.addPost(
title=postTitle,
body=postBody,
time_posted=datetime.datetime.now(),
author=webhelpers.checkForSession().user,
tags=postTags)
return flask.redirect("/")
@blueprint.route("/manage_posts")
@webhelpers.checkUserPermissions("/manage",
requiredPermissions=auth.CAN_POST_PERMISSION)
def managePosts():
posts = blog.getPosts(tags=False)
return flask.render_template("manage_posts.html",
posts=posts,
user=webhelpers.checkForSession().user)
@blueprint.route("/edit_post/<int:postId>", methods=["GET", "POST"])
@webhelpers.checkUserPermissions("/manage",
requiredPermissions=auth.CAN_POST_PERMISSION)
def editPost(postId):
if flask.request.method == "GET":
post = blog.getPostById(postId)
return flask.render_template("add_post.html",
post=post,
user=webhelpers.checkForSession().user)
elif flask.request.method == "POST":
postTitle = flask.request.form["post-title"]
postBody = flask.request.form["post-body"].replace("\t", " ")
postBody = flask.request.form["post-body"].replace(" ", " ")
postTags = flask.request.form["post-tags"]
blog.editPost(postId, postTitle, postBody, postTags)
return flask.redirect("/")
@blueprint.route("/settings", methods=["GET", "POST"])
@webhelpers.checkUserPermissions("/manage",
requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION)
def settingsPage():
if flask.request.method == "GET":
return flask.render_template("settings.html",
settings=settings.getAllSettings(),
themes=themes.getAvailableThemes(),
user=webhelpers.checkForSession().user)
if flask.request.method == "POST":
invalidSettings = []
for setting in flask.request.form:
value = flask.request.form[setting]
if not settings.validateSetting(setting, value):
invalidSettings.append(setting)
if len(invalidSettings) == 0:
for setting in flask.request.form:
value = flask.request.form[setting]
settings.setSettingValue(setting, value)
flask.flash("Your settings have been successfully saved.", "success")
return flask.redirect("/settings")
else:
flask.flash("Invalid settings. Please make sure the following requirements are met and try again.", "error")
for setting in invalidSettings:
flask.flash(settings.VALIDATION_MESAGES[setting], "error")
storedSettings = settings.getAllSettings()
#Since flask.request.form is an ImmutableMultiDict, we must call to_dict
#flat = True means we will only get the first value in the dict (which should be fine).
storedSettings.update(flask.request.form.to_dict(flat=True))
return flask.render_template("settings.html",
settings=storedSettings,
themes=themes.getAvailableThemes(),
user=webhelpers.checkForSession().user)
@blueprint.route("/manage_users", methods=["GET", "POST"])
@webhelpers.checkUserPermissions("/manage",
requiredPermissions = auth.CAN_CHANGE_SETTINGS_PERMISSION)
def manageUsers():
if flask.request.method == "GET":
return flask.render_template("manage_users.html",
userList = auth.getAllUsers(),
user = webhelpers.checkForSession().user)
#Returns a JSON Object based on whether or not user is logged in and if creation was succuessful.
@blueprint.route("/create_user", methods=["POST"])
@webhelpers.checkUserPermissions(requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,
saveRedirect=False)
def createUser(authed, authMessage):
if authed:
username = flask.request.form["username"]
password = flask.request.form["password"]
fullName = flask.request.form["full_name"]
canChangeSettings = False
canWritePosts = False
if (auth.CAN_POST_PERMISSION in flask.request.form
and flask.request.form[auth.CAN_POST_PERMISSION] == "on"):
canChangeSettings = True
if (auth.CAN_CHANGE_SETTINGS_PERMISSION in flask.request.form
and flask.request.form[auth.CAN_CHANGE_SETTINGS_PERMISSION] == "on"):
canWritePosts = True
user = None
try:
user = auth.createUser(username, fullName, password, canChangeSettings, canWritePosts)
except IntegrityError:
return json.dumps({"error": 2}), 400
return json.dumps({"error": 0, "user_id": user.id})
else:
return json.dumps({"error": 1}), 403
#Returns a JSON object based on whether or not user is logged in and if a user is found.
#Object contains user information
@blueprint.route("/get_user_info/<int:userId>")
@webhelpers.checkUserPermissions(requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION)
def getUserInfo(userId, authed, authMessage):
if authed:
user = auth.getUserById(userId)
if user is None:
return json.dumps({"error": 2})
userPermissions = []
if user.can_change_settings:
userPermissions.append(auth.CAN_CHANGE_SETTINGS_PERMISSION)
if user.can_write_posts:
userPermissions.append(auth.CAN_POST_PERMISSION)
userInfo = {
"username": user.username,
"full_name": user.full_name,
"permissions" : userPermissions
}
return json.dumps({"error": 0, "info": userInfo})
else:
return json.dumps({"error": 1}), 403
#Returns a JSON Object based on whether or not the user is logged in.
@blueprint.route("/delete_post/<int:postId>", methods=["POST"])
@webhelpers.checkUserPermissions(requiredPermissions=auth.CAN_POST_PERMISSION,
saveRedirect=False)
def deletePost(postId, authed, authMessage):
if authed:
blog.deletePost(postId)
return json.dumps({"error": 0})
else:
return json.dumps({"error": 1}), 403
#Returns a JSON Object based on whether or not the user is logged in,
#or if it's an invalid file type.
@blueprint.route("/upload_image", methods=["POST"])
@webhelpers.checkUserPermissions(requiredPermissions=auth.CAN_POST_PERMISSION,
saveRedirect=False)
def uploadImage(authed, authMessage):
ACCEPTED_FORMATS = ["image/jpeg", "image/png", "image/gif"]
if authed:
image = flask.request.files["image"]
mime = magic.from_buffer(image.stream.read(), mime=True)
image.stream.seek(0,0)
if type(mime) == bytes:
mime = mime.decode()
if mime in ACCEPTED_FORMATS:
extension = mimetypes.guess_extension(mime)
fileName = "{}{}".format(uuid.uuid4().hex, extension)
image.save(os.path.join(UPLOAD_LOCATION, fileName))
return json.dumps({
"error": 0,
"url": os.path.join("/static/uploads",
fileName)})
else:
return json.dumps({"error": 2}), 400
else:
return json.dumps({"error": 1}), 403
@blueprint.route("/reset_password", methods=["POST"])
@webhelpers.checkUserPermissions(requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,
saveRedirect=False)
def resetPassword(authed, authMessage):
if authed:
userId = flask.request.form["userId"]
newPassword = flask.request.form["password"]
auth.resetPasswordById(userId, newPassword)
return json.dumps({"error": 0})
else:
return json.dumps({"error": 1}), 403
@blueprint.route("/change_user_permisisons", methods=["POST"])
@webhelpers.checkUserPermissions(requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,
saveRedirect=False)
def changePermissions(authed, authMessage):
if authed:
if (auth.CAN_POST_PERMISSION in flask.request.form
and flask.request.form[auth.CAN_POST_PERMISSION] == "on"):
auth.grantUserPermissionById(flask.request.form["userId"], auth.CAN_POST_PERMISSION)
else:
auth.revokeUserPermissionById(flask.request.form["userId"], auth.CAN_POST_PERMISSION)
if (auth.CAN_CHANGE_SETTINGS_PERMISSION in flask.request.form
and flask.request.form[auth.CAN_CHANGE_SETTINGS_PERMISSION] == "on"):
auth.grantUserPermissionById(flask.request.form["userId"], auth.CAN_CHANGE_SETTINGS_PERMISSION)
else:
auth.revokeUserPermissionById(flask.request.form["userId"], auth.CAN_CHANGE_SETTINGS_PERMISSION)
return json.dumps({"error": 0})
else:
return json.dumps({"error": 1})
@blueprint.route("/delete_user/<int:userId>", methods=["POST"])
@webhelpers.checkUserPermissions(requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,
saveRedirect=False)
def deleteUser(userId, authed, authMessage):
if authed:
# auth.deleteUserById(userId)
return json.dumps({"error": 0})
else:
json.dumps({"error": 1})
|
carmark/vbox
|
refs/heads/master
|
src/VBox/ValidationKit/tests/shutdown/tdGuestOsShutdown1.py
|
1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
VMM Guest OS boot tests.
"""
__copyright__ = \
"""
Copyright (C) 2010-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.
You may elect to license modified versions of this file under the
terms and conditions of either the GPL or the CDDL or both.
"""
__version__ = "$Revision: 56295 $"
# Standard Python imports.
import os
import sys
import time
# Only the main script needs to modify the path.
try: __file__
except: __file__ = sys.argv[0]
g_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(g_ksValidationKitDir)
# Validation Kit imports.
from testdriver import vbox
from testdriver import base
from testdriver import reporter
from testdriver import vboxcon
class tdGuestOsBootTest1(vbox.TestDriver):
"""
VMM Unit Tests Set.
Scenario:
- Create VM that corresponds to Guest OS pre-installed on selected HDD
- Start VM and wait for TXS server connection (which is started after Guest successfully booted)
"""
ksSataController = 'SATA Controller'
ksIdeController = 'IDE Controller'
# VM parameters required to run HDD image.
# Format: { HDD image filename: (sKind, HDD controller type) }
kaoVmParams = {
't-win80.vdi': ( 'Windows 8 (64 bit)', ksSataController ),
}
# List of platforms which are able to suspend and resume host automatically.
# In order to add new platform, self._SuspendResume() should be adapted.
kasSuspendAllowedPlatforms = ( 'darwin' )
kcMsVmStartLimit = 5 * 60000
kcMsVmShutdownLimit = 1 * 60000
def __init__(self):
"""
Reinitialize child class instance.
"""
vbox.TestDriver.__init__(self)
self.sVmName = 'TestVM'
self.sHddName = None
self.sHddPathBase = os.path.join(self.sResourcePath, '4.2', 'nat', 'win80')
self.oVM = None
# TODO: that should be moved to some common place
self.fEnableIOAPIC = True
self.cCpus = 1
self.fEnableNestedPaging = True
self.fEnablePAE = False
self.fSuspendHost = False
self.cSecSuspendTime = 60
self.cShutdownIters = 1
self.fExtraVm = False
self.sExtraVmName = "TestVM-Extra"
self.oExtraVM = None
self.fLocalCatch = False
#
# Overridden methods.
#
def showUsage(self):
"""
Extend usage info
"""
rc = vbox.TestDriver.showUsage(self)
reporter.log(' --boot-hdd <HDD image file name>')
reporter.log(' --cpus <# CPUs>')
reporter.log(' --no-ioapic')
reporter.log(' --no-nested-paging')
reporter.log(' --pae')
reporter.log(' --suspend-host')
reporter.log(' --suspend-time <sec>')
reporter.log(' --shutdown-iters <# iters>')
reporter.log(' --extra-vm')
reporter.log(' --local-catch')
return rc
def parseOption(self, asArgs, iArg):
"""
Extend standard options set
"""
if asArgs[iArg] == '--boot-hdd':
iArg += 1
if iArg >= len(asArgs): raise base.InvalidOption('The "--boot-hdd" option requires an argument')
self.sHddName = asArgs[iArg]
elif asArgs[iArg] == '--cpus':
iArg += 1
if iArg >= len(asArgs): raise base.InvalidOption('The "--cpus" option requires an argument')
self.cCpus = int(asArgs[iArg])
elif asArgs[iArg] == '--no-ioapic':
self.fEnableIOAPIC = False
elif asArgs[iArg] == '--no-nested-paging':
self.fEnableNestedPaging = False
elif asArgs[iArg] == '--pae':
self.fEnablePAE = True
elif asArgs[iArg] == '--suspend-host':
self.fSuspendHost = True
elif asArgs[iArg] == '--suspend-time':
iArg += 1
if iArg >= len(asArgs): raise base.InvalidOption('The "--suspend-time" option requires an argument')
self.cSecSuspendTime = int(asArgs[iArg])
elif asArgs[iArg] == '--shutdown-iters':
iArg += 1
if iArg >= len(asArgs): raise base.InvalidOption('The "--shutdown-iters" option requires an argument')
self.cShutdownIters = int(asArgs[iArg])
elif asArgs[iArg] == '--extra-vm':
self.fExtraVm = True
elif asArgs[iArg] == '--local-catch':
self.fLocalCatch = True
else:
return vbox.TestDriver.parseOption(self, asArgs, iArg)
return iArg + 1
def getResourceSet(self):
"""
Returns a set of file and/or directory names relative to
TESTBOX_PATH_RESOURCES.
"""
return [os.path.join(self.sHddPathBase, sRsrc) for sRsrc in self.kaoVmParams];
def _addVM(self, sVmName, sNicTraceFile=None):
"""
Create VM
"""
# Get VM params specific to HDD image
sKind, sController = self.kaoVmParams[self.sHddName]
# Create VM itself
eNic0AttachType = vboxcon.NetworkAttachmentType_NAT
sHddPath = os.path.join(self.sHddPathBase, self.sHddName)
assert os.path.isfile(sHddPath)
oVM = \
self.createTestVM(sVmName, 1, sKind=sKind, cCpus=self.cCpus,
eNic0AttachType=eNic0AttachType, sDvdImage = self.sVBoxValidationKitIso)
assert oVM is not None
oSession = self.openSession(oVM)
# Attach an HDD
fRc = oSession.attachHd(sHddPath, sController, fImmutable=True)
# Enable HW virt
fRc = fRc and oSession.enableVirtEx(True)
# Enable I/O APIC
fRc = fRc and oSession.enableIoApic(self.fEnableIOAPIC)
# Enable Nested Paging
fRc = fRc and oSession.enableNestedPaging(self.fEnableNestedPaging)
# Enable PAE
fRc = fRc and oSession.enablePae(self.fEnablePAE)
if (sNicTraceFile is not None):
fRc = fRc and oSession.setNicTraceEnabled(True, sNicTraceFile)
# Remote desktop
oSession.setupVrdp(True)
fRc = fRc and oSession.saveSettings()
fRc = fRc and oSession.close()
assert fRc is True
return oVM
def actionConfig(self):
"""
Configure pre-conditions.
"""
if not self.importVBoxApi():
return False
# Save time: do not start VM if there is no way to suspend host
if (self.fSuspendHost is True and sys.platform not in self.kasSuspendAllowedPlatforms):
reporter.log('Platform [%s] is not in the list of supported platforms' % sys.platform)
return False
assert self.sHddName is not None
if self.sHddName not in self.kaoVmParams:
reporter.log('Error: unknown HDD image specified: %s' % self.sHddName)
return False
if (self.fExtraVm is True):
self.oExtraVM = self._addVM(self.sExtraVmName)
self.oVM = self._addVM(self.sVmName)
return vbox.TestDriver.actionConfig(self)
def _SuspendResume(self, cSecTimeout):
"""
Put host into sleep and automatically resume it after specified timeout.
"""
fRc = False
if (sys.platform == 'darwin'):
tsStart = time.time()
fRc = os.system("/usr/bin/pmset relative wake %d" % self.cSecSuspendTime)
fRc |= os.system("/usr/bin/pmset sleepnow")
# Wait for host to wake up
while ((time.time() - tsStart) < self.cSecSuspendTime):
self.sleep(0.1)
return fRc == 0
def _waitKeyboardInterrupt(self):
"""
Idle loop until user press CTRL+C
"""
reporter.log('[LOCAL CATCH]: waiting for keyboard interrupt')
while (True):
try:
self.sleep(1)
except KeyboardInterrupt:
reporter.log('[LOCAL CATCH]: keyboard interrupt occurred')
break
def actionExecute(self):
"""
Execute the testcase itself.
"""
#self.logVmInfo(self.oVM)
reporter.testStart('SHUTDOWN GUEST')
cIter = 0
fRc = True
if (self.fExtraVm is True):
oExtraSession, oExtraTxsSession = self.startVmAndConnectToTxsViaTcp(self.sExtraVmName,
fCdWait=False,
cMsTimeout=self.kcMsVmStartLimit)
if oExtraSession is None or oExtraTxsSession is None:
reporter.error('Unable to start extra VM.')
if (self.fLocalCatch is True):
self._waitKeyboardInterrupt()
reporter.testDone()
return False
while (cIter < self.cShutdownIters):
cIter += 1
reporter.log("Starting iteration #%d." % cIter)
oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(self.sVmName,
fCdWait=False,
cMsTimeout=self.kcMsVmStartLimit)
if oSession is not None and oTxsSession is not None:
# Wait until guest reported success
reporter.log('Guest started. Connection to TXS service established.')
if (self.fSuspendHost is True):
reporter.log("Disconnect form TXS.")
fRc = fRc and self.txsDisconnect(oSession, oTxsSession)
if (fRc is not True):
reporter.log("Disconnect form TXS failed.")
else:
reporter.log('Put host to sleep and resume it automatically after %d seconds.' % self.cSecSuspendTime)
fRc = fRc and self._SuspendResume(self.cSecSuspendTime)
if (fRc is True):
reporter.log("Sleep/resume success.")
else:
reporter.log("Sleep/resume failed.")
reporter.log("Re-connect to TXS in 10 seconds.")
self.sleep(10)
(fRc, oTxsSession) = self.txsDoConnectViaTcp(oSession, 2 * 60 * 10000)
if (fRc is not True):
reporter.log("Re-connect to TXS failed.")
if (fRc is True):
reporter.log('Attempt to shutdown guest.')
fRc = fRc and oTxsSession.syncShutdown(cMsTimeout=(4 * 60 * 1000))
if (fRc is True):
reporter.log('Shutdown request issued successfully.')
self.waitOnDirectSessionClose(self.oVM, self.kcMsVmShutdownLimit)
reporter.log('Shutdown %s.' % ('success' if fRc is True else 'failed'))
else:
reporter.error('Shutdown request failed.')
# Do not terminate failing VM in order to catch it.
if (fRc is not True and self.fLocalCatch is True):
self._waitKeyboardInterrupt()
break
fRc = fRc and self.terminateVmBySession(oSession)
reporter.log('VM terminated.')
else:
reporter.error('Guest did not start (iteration %d of %d)' % (cIter, self.cShutdownIters))
fRc = False
# Stop if fail
if (fRc is not True):
break
# Local catch at the end.
if (self.fLocalCatch is True):
reporter.log("Test completed. Waiting for user to press CTRL+C.")
self._waitKeyboardInterrupt()
if (self.fExtraVm is True):
fRc = fRc and self.terminateVmBySession(oExtraSession)
reporter.testDone()
return fRc is True
if __name__ == '__main__':
sys.exit(tdGuestOsBootTest1().main(sys.argv))
|
mancoast/CPythonPyc_test
|
refs/heads/master
|
fail/342_test_message.py
|
72
|
import unittest
import textwrap
from email import policy, message_from_string
from email.message import EmailMessage, MIMEPart
from test.test_email import TestEmailBase, parameterize
# Helper.
def first(iterable):
return next(filter(lambda x: x is not None, iterable), None)
class Test(TestEmailBase):
policy = policy.default
def test_error_on_setitem_if_max_count_exceeded(self):
m = self._str_msg("")
m['To'] = 'abc@xyz'
with self.assertRaises(ValueError):
m['To'] = 'xyz@abc'
def test_rfc2043_auto_decoded_and_emailmessage_used(self):
m = message_from_string(textwrap.dedent("""\
Subject: Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?=
From: =?utf-8?q?Pep=C3=A9?= Le Pew <[email protected]>
To: "Penelope Pussycat" <"[email protected]">
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
sample text
"""), policy=policy.default)
self.assertEqual(m['subject'], "Ayons asperges pour le déjeuner")
self.assertEqual(m['from'], "Pepé Le Pew <[email protected]>")
self.assertIsInstance(m, EmailMessage)
@parameterize
class TestEmailMessageBase:
policy = policy.default
# The first argument is a triple (related, html, plain) of indices into the
# list returned by 'walk' called on a Message constructed from the third.
# The indices indicate which part should match the corresponding part-type
# when passed to get_body (ie: the "first" part of that type in the
# message). The second argument is a list of indices into the 'walk' list
# of the attachments that should be returned by a call to
# 'iter_attachments'. The third argument is a list of indices into 'walk'
# that should be returned by a call to 'iter_parts'. Note that the first
# item returned by 'walk' is the Message itself.
message_params = {
'empty_message': (
(None, None, 0),
(),
(),
""),
'non_mime_plain': (
(None, None, 0),
(),
(),
textwrap.dedent("""\
To: [email protected]
simple text body
""")),
'mime_non_text': (
(None, None, None),
(),
(),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: image/jpg
bogus body.
""")),
'plain_html_alternative': (
(None, 2, 1),
(),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="==="
preamble
--===
Content-Type: text/plain
simple body
--===
Content-Type: text/html
<p>simple body</p>
--===--
""")),
'plain_html_mixed': (
(None, 2, 1),
(),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
preamble
--===
Content-Type: text/plain
simple body
--===
Content-Type: text/html
<p>simple body</p>
--===--
""")),
'plain_html_attachment_mixed': (
(None, None, 1),
(2,),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
--===
Content-Type: text/plain
simple body
--===
Content-Type: text/html
Content-Disposition: attachment
<p>simple body</p>
--===--
""")),
'html_text_attachment_mixed': (
(None, 2, None),
(1,),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
--===
Content-Type: text/plain
Content-Disposition: AtTaChment
simple body
--===
Content-Type: text/html
<p>simple body</p>
--===--
""")),
'html_text_attachment_inline_mixed': (
(None, 2, 1),
(),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
--===
Content-Type: text/plain
Content-Disposition: InLine
simple body
--===
Content-Type: text/html
Content-Disposition: inline
<p>simple body</p>
--===--
""")),
# RFC 2387
'related': (
(0, 1, None),
(2,),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/related; boundary="==="; type=text/html
--===
Content-Type: text/html
<p>simple body</p>
--===
Content-Type: image/jpg
Content-ID: <image1>
bogus data
--===--
""")),
# This message structure will probably never be seen in the wild, but
# it proves we distinguish between text parts based on 'start'. The
# content would not, of course, actually work :)
'related_with_start': (
(0, 2, None),
(1,),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/related; boundary="==="; type=text/html;
start="<body>"
--===
Content-Type: text/html
Content-ID: <include>
useless text
--===
Content-Type: text/html
Content-ID: <body>
<p>simple body</p>
<!--#include file="<include>"-->
--===--
""")),
'mixed_alternative_plain_related': (
(3, 4, 2),
(6, 7),
(1, 6, 7),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
--===
Content-Type: multipart/alternative; boundary="+++"
--+++
Content-Type: text/plain
simple body
--+++
Content-Type: multipart/related; boundary="___"
--___
Content-Type: text/html
<p>simple body</p>
--___
Content-Type: image/jpg
Content-ID: <image1@cid>
bogus jpg body
--___--
--+++--
--===
Content-Type: image/jpg
Content-Disposition: attachment
bogus jpg body
--===
Content-Type: image/jpg
Content-Disposition: AttacHmenT
another bogus jpg body
--===--
""")),
# This structure suggested by Stephen J. Turnbull...may not exist/be
# supported in the wild, but we want to support it.
'mixed_related_alternative_plain_html': (
(1, 4, 3),
(6, 7),
(1, 6, 7),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
--===
Content-Type: multipart/related; boundary="+++"
--+++
Content-Type: multipart/alternative; boundary="___"
--___
Content-Type: text/plain
simple body
--___
Content-Type: text/html
<p>simple body</p>
--___--
--+++
Content-Type: image/jpg
Content-ID: <image1@cid>
bogus jpg body
--+++--
--===
Content-Type: image/jpg
Content-Disposition: attachment
bogus jpg body
--===
Content-Type: image/jpg
Content-Disposition: attachment
another bogus jpg body
--===--
""")),
# Same thing, but proving we only look at the root part, which is the
# first one if there isn't any start parameter. That is, this is a
# broken related.
'mixed_related_alternative_plain_html_wrong_order': (
(1, None, None),
(6, 7),
(1, 6, 7),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
--===
Content-Type: multipart/related; boundary="+++"
--+++
Content-Type: image/jpg
Content-ID: <image1@cid>
bogus jpg body
--+++
Content-Type: multipart/alternative; boundary="___"
--___
Content-Type: text/plain
simple body
--___
Content-Type: text/html
<p>simple body</p>
--___--
--+++--
--===
Content-Type: image/jpg
Content-Disposition: attachment
bogus jpg body
--===
Content-Type: image/jpg
Content-Disposition: attachment
another bogus jpg body
--===--
""")),
'message_rfc822': (
(None, None, None),
(),
(),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: message/rfc822
To: [email protected]
From: [email protected]
this is a message body.
""")),
'mixed_text_message_rfc822': (
(None, None, 1),
(2,),
(1, 2),
textwrap.dedent("""\
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==="
--===
Content-Type: text/plain
Your message has bounced, ser.
--===
Content-Type: message/rfc822
To: [email protected]
From: [email protected]
this is a message body.
--===--
""")),
}
def message_as_get_body(self, body_parts, attachments, parts, msg):
m = self._str_msg(msg)
allparts = list(m.walk())
expected = [None if n is None else allparts[n] for n in body_parts]
related = 0; html = 1; plain = 2
self.assertEqual(m.get_body(), first(expected))
self.assertEqual(m.get_body(preferencelist=(
'related', 'html', 'plain')),
first(expected))
self.assertEqual(m.get_body(preferencelist=('related', 'html')),
first(expected[related:html+1]))
self.assertEqual(m.get_body(preferencelist=('related', 'plain')),
first([expected[related], expected[plain]]))
self.assertEqual(m.get_body(preferencelist=('html', 'plain')),
first(expected[html:plain+1]))
self.assertEqual(m.get_body(preferencelist=['related']),
expected[related])
self.assertEqual(m.get_body(preferencelist=['html']), expected[html])
self.assertEqual(m.get_body(preferencelist=['plain']), expected[plain])
self.assertEqual(m.get_body(preferencelist=('plain', 'html')),
first(expected[plain:html-1:-1]))
self.assertEqual(m.get_body(preferencelist=('plain', 'related')),
first([expected[plain], expected[related]]))
self.assertEqual(m.get_body(preferencelist=('html', 'related')),
first(expected[html::-1]))
self.assertEqual(m.get_body(preferencelist=('plain', 'html', 'related')),
first(expected[::-1]))
self.assertEqual(m.get_body(preferencelist=('html', 'plain', 'related')),
first([expected[html],
expected[plain],
expected[related]]))
def message_as_iter_attachment(self, body_parts, attachments, parts, msg):
m = self._str_msg(msg)
allparts = list(m.walk())
attachments = [allparts[n] for n in attachments]
self.assertEqual(list(m.iter_attachments()), attachments)
def message_as_iter_parts(self, body_parts, attachments, parts, msg):
m = self._str_msg(msg)
allparts = list(m.walk())
parts = [allparts[n] for n in parts]
self.assertEqual(list(m.iter_parts()), parts)
class _TestContentManager:
def get_content(self, msg, *args, **kw):
return msg, args, kw
def set_content(self, msg, *args, **kw):
self.msg = msg
self.args = args
self.kw = kw
def test_get_content_with_cm(self):
m = self._str_msg('')
cm = self._TestContentManager()
self.assertEqual(m.get_content(content_manager=cm), (m, (), {}))
msg, args, kw = m.get_content('foo', content_manager=cm, bar=1, k=2)
self.assertEqual(msg, m)
self.assertEqual(args, ('foo',))
self.assertEqual(kw, dict(bar=1, k=2))
def test_get_content_default_cm_comes_from_policy(self):
p = policy.default.clone(content_manager=self._TestContentManager())
m = self._str_msg('', policy=p)
self.assertEqual(m.get_content(), (m, (), {}))
msg, args, kw = m.get_content('foo', bar=1, k=2)
self.assertEqual(msg, m)
self.assertEqual(args, ('foo',))
self.assertEqual(kw, dict(bar=1, k=2))
def test_set_content_with_cm(self):
m = self._str_msg('')
cm = self._TestContentManager()
m.set_content(content_manager=cm)
self.assertEqual(cm.msg, m)
self.assertEqual(cm.args, ())
self.assertEqual(cm.kw, {})
m.set_content('foo', content_manager=cm, bar=1, k=2)
self.assertEqual(cm.msg, m)
self.assertEqual(cm.args, ('foo',))
self.assertEqual(cm.kw, dict(bar=1, k=2))
def test_set_content_default_cm_comes_from_policy(self):
cm = self._TestContentManager()
p = policy.default.clone(content_manager=cm)
m = self._str_msg('', policy=p)
m.set_content()
self.assertEqual(cm.msg, m)
self.assertEqual(cm.args, ())
self.assertEqual(cm.kw, {})
m.set_content('foo', bar=1, k=2)
self.assertEqual(cm.msg, m)
self.assertEqual(cm.args, ('foo',))
self.assertEqual(cm.kw, dict(bar=1, k=2))
# outcome is whether xxx_method should raise ValueError error when called
# on multipart/subtype. Blank outcome means it depends on xxx (add
# succeeds, make raises). Note: 'none' means there are content-type
# headers but payload is None...this happening in practice would be very
# unusual, so treating it as if there were content seems reasonable.
# method subtype outcome
subtype_params = (
('related', 'no_content', 'succeeds'),
('related', 'none', 'succeeds'),
('related', 'plain', 'succeeds'),
('related', 'related', ''),
('related', 'alternative', 'raises'),
('related', 'mixed', 'raises'),
('alternative', 'no_content', 'succeeds'),
('alternative', 'none', 'succeeds'),
('alternative', 'plain', 'succeeds'),
('alternative', 'related', 'succeeds'),
('alternative', 'alternative', ''),
('alternative', 'mixed', 'raises'),
('mixed', 'no_content', 'succeeds'),
('mixed', 'none', 'succeeds'),
('mixed', 'plain', 'succeeds'),
('mixed', 'related', 'succeeds'),
('mixed', 'alternative', 'succeeds'),
('mixed', 'mixed', ''),
)
def _make_subtype_test_message(self, subtype):
m = self.message()
payload = None
msg_headers = [
('To', '[email protected]'),
('From', '[email protected]'),
]
if subtype != 'no_content':
('content-shadow', 'Logrus'),
msg_headers.append(('X-Random-Header', 'Corwin'))
if subtype == 'text':
payload = ''
msg_headers.append(('Content-Type', 'text/plain'))
m.set_payload('')
elif subtype != 'no_content':
payload = []
msg_headers.append(('Content-Type', 'multipart/' + subtype))
msg_headers.append(('X-Trump', 'Random'))
m.set_payload(payload)
for name, value in msg_headers:
m[name] = value
return m, msg_headers, payload
def _check_disallowed_subtype_raises(self, m, method_name, subtype, method):
with self.assertRaises(ValueError) as ar:
getattr(m, method)()
exc_text = str(ar.exception)
self.assertIn(subtype, exc_text)
self.assertIn(method_name, exc_text)
def _check_make_multipart(self, m, msg_headers, payload):
count = 0
for name, value in msg_headers:
if not name.lower().startswith('content-'):
self.assertEqual(m[name], value)
count += 1
self.assertEqual(len(m), count+1) # +1 for new Content-Type
part = next(m.iter_parts())
count = 0
for name, value in msg_headers:
if name.lower().startswith('content-'):
self.assertEqual(part[name], value)
count += 1
self.assertEqual(len(part), count)
self.assertEqual(part.get_payload(), payload)
def subtype_as_make(self, method, subtype, outcome):
m, msg_headers, payload = self._make_subtype_test_message(subtype)
make_method = 'make_' + method
if outcome in ('', 'raises'):
self._check_disallowed_subtype_raises(m, method, subtype, make_method)
return
getattr(m, make_method)()
self.assertEqual(m.get_content_maintype(), 'multipart')
self.assertEqual(m.get_content_subtype(), method)
if subtype == 'no_content':
self.assertEqual(len(m.get_payload()), 0)
self.assertEqual(m.items(),
msg_headers + [('Content-Type',
'multipart/'+method)])
else:
self.assertEqual(len(m.get_payload()), 1)
self._check_make_multipart(m, msg_headers, payload)
def subtype_as_make_with_boundary(self, method, subtype, outcome):
# Doing all variation is a bit of overkill...
m = self.message()
if outcome in ('', 'raises'):
m['Content-Type'] = 'multipart/' + subtype
with self.assertRaises(ValueError) as cm:
getattr(m, 'make_' + method)()
return
if subtype == 'plain':
m['Content-Type'] = 'text/plain'
elif subtype != 'no_content':
m['Content-Type'] = 'multipart/' + subtype
getattr(m, 'make_' + method)(boundary="abc")
self.assertTrue(m.is_multipart())
self.assertEqual(m.get_boundary(), 'abc')
def test_policy_on_part_made_by_make_comes_from_message(self):
for method in ('make_related', 'make_alternative', 'make_mixed'):
m = self.message(policy=self.policy.clone(content_manager='foo'))
m['Content-Type'] = 'text/plain'
getattr(m, method)()
self.assertEqual(m.get_payload(0).policy.content_manager, 'foo')
class _TestSetContentManager:
def set_content(self, msg, content, *args, **kw):
msg['Content-Type'] = 'text/plain'
msg.set_payload(content)
def subtype_as_add(self, method, subtype, outcome):
m, msg_headers, payload = self._make_subtype_test_message(subtype)
cm = self._TestSetContentManager()
add_method = 'add_attachment' if method=='mixed' else 'add_' + method
if outcome == 'raises':
self._check_disallowed_subtype_raises(m, method, subtype, add_method)
return
getattr(m, add_method)('test', content_manager=cm)
self.assertEqual(m.get_content_maintype(), 'multipart')
self.assertEqual(m.get_content_subtype(), method)
if method == subtype or subtype == 'no_content':
self.assertEqual(len(m.get_payload()), 1)
for name, value in msg_headers:
self.assertEqual(m[name], value)
part = m.get_payload()[0]
else:
self.assertEqual(len(m.get_payload()), 2)
self._check_make_multipart(m, msg_headers, payload)
part = m.get_payload()[1]
self.assertEqual(part.get_content_type(), 'text/plain')
self.assertEqual(part.get_payload(), 'test')
if method=='mixed':
self.assertEqual(part['Content-Disposition'], 'attachment')
elif method=='related':
self.assertEqual(part['Content-Disposition'], 'inline')
else:
# Otherwise we don't guess.
self.assertIsNone(part['Content-Disposition'])
class _TestSetRaisingContentManager:
def set_content(self, msg, content, *args, **kw):
raise Exception('test')
def test_default_content_manager_for_add_comes_from_policy(self):
cm = self._TestSetRaisingContentManager()
m = self.message(policy=self.policy.clone(content_manager=cm))
for method in ('add_related', 'add_alternative', 'add_attachment'):
with self.assertRaises(Exception) as ar:
getattr(m, method)('')
self.assertEqual(str(ar.exception), 'test')
def message_as_clear(self, body_parts, attachments, parts, msg):
m = self._str_msg(msg)
m.clear()
self.assertEqual(len(m), 0)
self.assertEqual(list(m.items()), [])
self.assertIsNone(m.get_payload())
self.assertEqual(list(m.iter_parts()), [])
def message_as_clear_content(self, body_parts, attachments, parts, msg):
m = self._str_msg(msg)
expected_headers = [h for h in m.keys()
if not h.lower().startswith('content-')]
m.clear_content()
self.assertEqual(list(m.keys()), expected_headers)
self.assertIsNone(m.get_payload())
self.assertEqual(list(m.iter_parts()), [])
def test_is_attachment(self):
m = self._make_message()
self.assertFalse(m.is_attachment())
with self.assertWarns(DeprecationWarning):
self.assertFalse(m.is_attachment)
m['Content-Disposition'] = 'inline'
self.assertFalse(m.is_attachment())
with self.assertWarns(DeprecationWarning):
self.assertFalse(m.is_attachment)
m.replace_header('Content-Disposition', 'attachment')
self.assertTrue(m.is_attachment())
with self.assertWarns(DeprecationWarning):
self.assertTrue(m.is_attachment)
m.replace_header('Content-Disposition', 'AtTachMent')
self.assertTrue(m.is_attachment())
with self.assertWarns(DeprecationWarning):
self.assertTrue(m.is_attachment)
m.set_param('filename', 'abc.png', 'Content-Disposition')
self.assertTrue(m.is_attachment())
with self.assertWarns(DeprecationWarning):
self.assertTrue(m.is_attachment)
class TestEmailMessage(TestEmailMessageBase, TestEmailBase):
message = EmailMessage
def test_set_content_adds_MIME_Version(self):
m = self._str_msg('')
cm = self._TestContentManager()
self.assertNotIn('MIME-Version', m)
m.set_content(content_manager=cm)
self.assertEqual(m['MIME-Version'], '1.0')
class _MIME_Version_adding_CM:
def set_content(self, msg, *args, **kw):
msg['MIME-Version'] = '1.0'
def test_set_content_does_not_duplicate_MIME_Version(self):
m = self._str_msg('')
cm = self._MIME_Version_adding_CM()
self.assertNotIn('MIME-Version', m)
m.set_content(content_manager=cm)
self.assertEqual(m['MIME-Version'], '1.0')
class TestMIMEPart(TestEmailMessageBase, TestEmailBase):
# Doing the full test run here may seem a bit redundant, since the two
# classes are almost identical. But what if they drift apart? So we do
# the full tests so that any future drift doesn't introduce bugs.
message = MIMEPart
def test_set_content_does_not_add_MIME_Version(self):
m = self._str_msg('')
cm = self._TestContentManager()
self.assertNotIn('MIME-Version', m)
m.set_content(content_manager=cm)
self.assertNotIn('MIME-Version', m)
if __name__ == '__main__':
unittest.main()
|
kaleid0scope/SITE-database
|
refs/heads/master
|
DjangoWebProject/DjangoWebProject/users/conf.py
|
3
|
from appconf import AppConf
from django.conf import settings
class UsersAppConf(AppConf):
VERIFY_EMAIL = False
CREATE_SUPERUSER = settings.DEBUG
SUPERUSER_EMAIL = '[email protected]'
SUPERUSER_PASSWORD = 'django'
EMAIL_CONFIRMATION_TIMEOUT_DAYS = 3
SPAM_PROTECTION = True
REGISTRATION_OPEN = True
AUTO_LOGIN_ON_ACTIVATION = True
AUTO_LOGIN_AFTER_REGISTRATION = False
PASSWORD_MIN_LENGTH = 5
PASSWORD_MAX_LENGTH = None
CHECK_PASSWORD_COMPLEXITY = True
PASSWORD_POLICY = {
'UPPER': 0, # Uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'LOWER': 0, # Lowercase 'abcdefghijklmnopqrstuvwxyz'
'DIGITS': 0, # Digits '0123456789'
'PUNCTUATION': 0 # Punctuation """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
}
VALIDATE_EMAIL_DOMAIN = True
EMAIL_DOMAINS_BLACKLIST = []
EMAIL_DOMAINS_WHITELIST = []
class Meta:
prefix = 'users'
|
PriklyGrayp/Noitacude.PY
|
refs/heads/master
|
__init__.py
|
22
|
__author__ = "Prikly Grayp"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "[email protected]"
__status__ = "Development"
|
titze/apparecium
|
refs/heads/master
|
androguard/core/bytecodes/api_permissions.py
|
50
|
DVM_PERMISSIONS_BY_PERMISSION = {
"BIND_DEVICE_ADMIN" : {
"Landroid/app/admin/DeviceAdminReceiver;" : [
("C", "ACTION_DEVICE_ADMIN_ENABLED", "Ljava/lang/String;"),
],
"Landroid/app/admin/DevicePolicyManager;" : [
("F", "getRemoveWarning", "(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)"),
("F", "reportFailedPasswordAttempt", "()"),
("F", "reportSuccessfulPasswordAttempt", "()"),
("F", "setActiveAdmin", "(Landroid/content/ComponentName;)"),
("F", "setActivePasswordState", "(I I)"),
],
"Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;" : [
("F", "getRemoveWarning", "(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)"),
("F", "reportFailedPasswordAttempt", "()"),
("F", "reportSuccessfulPasswordAttempt", "()"),
("F", "setActiveAdmin", "(Landroid/content/ComponentName;)"),
("F", "setActivePasswordState", "(I I)"),
],
},
"READ_SYNC_SETTINGS" : {
"Landroid/app/ContextImpl$ApplicationContentResolver;" : [
("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getMasterSyncAutomatically", "()"),
("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
"Landroid/content/ContentService;" : [
("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getMasterSyncAutomatically", "()"),
("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
"Landroid/content/ContentResolver;" : [
("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getMasterSyncAutomatically", "()"),
("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
"Landroid/content/IContentService$Stub$Proxy;" : [
("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getMasterSyncAutomatically", "()"),
("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
},
"FACTORY_TEST" : {
"Landroid/content/pm/ApplicationInfo;" : [
("C", "FLAG_FACTORY_TEST", "I"),
("C", "flags", "I"),
],
"Landroid/content/Intent;" : [
("C", "IntentResolution", "Ljava/lang/String;"),
("C", "ACTION_FACTORY_TEST", "Ljava/lang/String;"),
],
},
"SET_ALWAYS_FINISH" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "setAlwaysFinish", "(B)"),
],
},
"READ_CALENDAR" : {
"Landroid/provider/Calendar$CalendarAlerts;" : [
("F", "alarmExists", "(Landroid/content/ContentResolver; J J J)"),
("F", "findNextAlarmTime", "(Landroid/content/ContentResolver; J)"),
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)"),
],
"Landroid/provider/Calendar$Calendars;" : [
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/provider/Calendar$Events;" : [
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"),
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)"),
],
"Landroid/provider/Calendar$Instances;" : [
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J Ljava/lang/String; Ljava/lang/String;)"),
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J)"),
],
"Landroid/provider/Calendar$EventDays;" : [
("F", "query", "(Landroid/content/ContentResolver; I I)"),
],
},
"ACCESS_DRM" : {
"Landroid/provider/DrmStore;" : [
("F", "enforceAccessDrmPermission", "(Landroid/content/Context;)"),
],
},
"CHANGE_CONFIGURATION" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "updateConfiguration", "(Landroid/content/res/Configuration;)"),
],
},
"SET_ACTIVITY_WATCHER" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "profileControl", "(Ljava/lang/String; B Ljava/lang/String; Landroid/os/ParcelFileDescriptor;)"),
("F", "setActivityController", "(Landroid/app/IActivityController;)"),
],
},
"GET_PACKAGE_SIZE" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "getPackageSizeInfo", "(Ljava/lang/String; LIPackageStatsObserver;)"),
("F", "getPackageSizeInfo", "(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "getPackageSizeInfo", "(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)"),
],
},
"CONTROL_LOCATION_UPDATES" : {
"Landroid/telephony/TelephonyManager;" : [
("F", "disableLocationUpdates", "()"),
("F", "enableLocationUpdates", "()"),
],
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [
("F", "disableLocationUpdates", "()"),
("F", "enableLocationUpdates", "()"),
],
},
"CLEAR_APP_CACHE" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "freeStorage", "(J LIntentSender;)"),
("F", "freeStorageAndNotify", "(J LIPackageDataObserver;)"),
("F", "freeStorage", "(J Landroid/content/IntentSender;)"),
("F", "freeStorageAndNotify", "(J Landroid/content/pm/IPackageDataObserver;)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "freeStorage", "(J Landroid/content/IntentSender;)"),
("F", "freeStorageAndNotify", "(J Landroid/content/pm/IPackageDataObserver;)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "freeStorage", "(J Landroid/content/IntentSender;)"),
("F", "freeStorageAndNotify", "(J Landroid/content/pm/IPackageDataObserver;)"),
],
},
"BIND_INPUT_METHOD" : {
"Landroid/view/inputmethod/InputMethod;" : [
("C", "SERVICE_INTERFACE", "Ljava/lang/String;"),
],
},
"SIGNAL_PERSISTENT_PROCESSES" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "signalPersistentProcesses", "(I)"),
],
},
"BATTERY_STATS" : {
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;" : [
("F", "getAwakeTimeBattery", "()"),
("F", "getAwakeTimePlugged", "()"),
("F", "getStatistics", "()"),
],
},
"AUTHENTICATE_ACCOUNTS" : {
"Landroid/accounts/AccountManager;" : [
("F", "addAccountExplicitly", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "getPassword", "(Landroid/accounts/Account;)"),
("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
("F", "addAccountExplicitly", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "getPassword", "(Landroid/accounts/Account;)"),
("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/accounts/AccountManagerService;" : [
("F", "addAccount", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "checkAuthenticateAccountsPermission", "(Landroid/accounts/Account;)"),
("F", "getPassword", "(Landroid/accounts/Account;)"),
("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/accounts/IAccountManager$Stub$Proxy;" : [
("F", "addAccount", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "getPassword", "(Landroid/accounts/Account;)"),
("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"),
],
},
"CHANGE_BACKGROUND_DATA_SETTING" : {
"Landroid/net/IConnectivityManager$Stub$Proxy;" : [
("F", "setBackgroundDataSetting", "(B)"),
],
"Landroid/net/ConnectivityManager;" : [
("F", "setBackgroundDataSetting", "(B)"),
],
},
"RESTART_PACKAGES" : {
"Landroid/app/ActivityManagerNative;" : [
("F", "killBackgroundProcesses", "(Ljava/lang/String;)"),
("F", "restartPackage", "(Ljava/lang/String;)"),
],
"Landroid/app/ActivityManager;" : [
("F", "killBackgroundProcesses", "(Ljava/lang/String;)"),
("F", "restartPackage", "(Ljava/lang/String;)"),
],
},
"CALL_PRIVILEGED" : {
"Landroid/telephony/TelephonyManager;" : [
("F", "getCompleteVoiceMailNumber", "()"),
],
"Landroid/telephony/PhoneNumberUtils;" : [
("F", "getNumberFromIntent", "(Landroid/content/Intent; Landroid/content/Context;)"),
],
},
"SET_WALLPAPER_COMPONENT" : {
"Landroid/app/IWallpaperManager$Stub$Proxy;" : [
("F", "setWallpaperComponent", "(Landroid/content/ComponentName;)"),
],
},
"DISABLE_KEYGUARD" : {
"Landroid/view/IWindowManager$Stub$Proxy;" : [
("F", "disableKeyguard", "(Landroid/os/IBinder; Ljava/lang/String;)"),
("F", "exitKeyguardSecurely", "(Landroid/view/IOnKeyguardExitResult;)"),
("F", "reenableKeyguard", "(Landroid/os/IBinder;)"),
],
"Landroid/app/KeyguardManager;" : [
("F", "exitKeyguardSecurely", "(Landroid/app/KeyguardManager$OnKeyguardExitResult;)"),
],
"Landroid/app/KeyguardManager$KeyguardLock;" : [
("F", "disableKeyguard", "()"),
("F", "reenableKeyguard", "()"),
],
},
"DELETE_PACKAGES" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "deletePackage", "(Ljava/lang/String; LIPackageDeleteObserver; I)"),
("F", "deletePackage", "(Ljava/lang/String; LIPackageDeleteObserver; I)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "deletePackage", "(Ljava/lang/String; LIPackageDeleteObserver; I)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "deletePackage", "(Ljava/lang/String; Landroid/content/pm/IPackageDeleteObserver; I)"),
],
},
"CHANGE_COMPONENT_ENABLED_STATE" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"),
("F", "setComponentEnabledSetting", "(LComponentName; I I)"),
("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"),
("F", "setComponentEnabledSetting", "(Landroid/content/ComponentName; I I)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"),
("F", "setComponentEnabledSetting", "(Landroid/content/ComponentName; I I)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"),
("F", "setComponentEnabledSetting", "(Landroid/content/ComponentName; I I)"),
],
},
"ASEC_ACCESS" : {
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "getSecureContainerList", "()"),
("F", "getSecureContainerPath", "(Ljava/lang/String;)"),
("F", "isSecureContainerMounted", "(Ljava/lang/String;)"),
],
},
"UPDATE_DEVICE_STATS " : {
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;" : [
("F", "noteLaunchTime", "(LComponentName;)"),
],
},
"RECORD_AUDIO" : {
"Landroid/net/sip/SipAudioCall;" : [
("F", "startAudio", "()"),
],
"Landroid/media/MediaRecorder;" : [
("F", "setAudioSource", "(I)"),
],
"Landroid/speech/SpeechRecognizer;" : [
("F", "cancel", "()"),
("F", "handleCancelMessage", "()"),
("F", "handleStartListening", "(Landroid/content/Intent;)"),
("F", "handleStopMessage", "()"),
("F", "startListening", "(Landroid/content/Intent;)"),
("F", "stopListening", "()"),
],
"Landroid/media/AudioRecord;" : [
("F", "<init>", "(I I I I I)"),
],
},
"ACCESS_MOCK_LOCATION" : {
"Landroid/location/LocationManager;" : [
("F", "addTestProvider", "(Ljava/lang/String; B B B B B B B I I)"),
("F", "clearTestProviderEnabled", "(Ljava/lang/String;)"),
("F", "clearTestProviderLocation", "(Ljava/lang/String;)"),
("F", "clearTestProviderStatus", "(Ljava/lang/String;)"),
("F", "removeTestProvider", "(Ljava/lang/String;)"),
("F", "setTestProviderEnabled", "(Ljava/lang/String; B)"),
("F", "setTestProviderLocation", "(Ljava/lang/String; Landroid/location/Location;)"),
("F", "setTestProviderStatus", "(Ljava/lang/String; I Landroid/os/Bundle; J)"),
("F", "addTestProvider", "(Ljava/lang/String; B B B B B B B I I)"),
("F", "clearTestProviderEnabled", "(Ljava/lang/String;)"),
("F", "clearTestProviderLocation", "(Ljava/lang/String;)"),
("F", "clearTestProviderStatus", "(Ljava/lang/String;)"),
("F", "removeTestProvider", "(Ljava/lang/String;)"),
("F", "setTestProviderEnabled", "(Ljava/lang/String; B)"),
("F", "setTestProviderLocation", "(Ljava/lang/String; Landroid/location/Location;)"),
("F", "setTestProviderStatus", "(Ljava/lang/String; I Landroid/os/Bundle; J)"),
],
"Landroid/location/ILocationManager$Stub$Proxy;" : [
("F", "addTestProvider", "(Ljava/lang/String; B B B B B B B I I)"),
("F", "clearTestProviderEnabled", "(Ljava/lang/String;)"),
("F", "clearTestProviderLocation", "(Ljava/lang/String;)"),
("F", "clearTestProviderStatus", "(Ljava/lang/String;)"),
("F", "removeTestProvider", "(Ljava/lang/String;)"),
("F", "setTestProviderEnabled", "(Ljava/lang/String; B)"),
("F", "setTestProviderLocation", "(Ljava/lang/String; Landroid/location/Location;)"),
("F", "setTestProviderStatus", "(Ljava/lang/String; I Landroid/os/Bundle; J)"),
],
},
"VIBRATE" : {
"Landroid/media/AudioManager;" : [
("C", "EXTRA_RINGER_MODE", "Ljava/lang/String;"),
("C", "EXTRA_VIBRATE_SETTING", "Ljava/lang/String;"),
("C", "EXTRA_VIBRATE_TYPE", "Ljava/lang/String;"),
("C", "FLAG_REMOVE_SOUND_AND_VIBRATE", "I"),
("C", "FLAG_VIBRATE", "I"),
("C", "RINGER_MODE_VIBRATE", "I"),
("C", "VIBRATE_SETTING_CHANGED_ACTION", "Ljava/lang/String;"),
("C", "VIBRATE_SETTING_OFF", "I"),
("C", "VIBRATE_SETTING_ON", "I"),
("C", "VIBRATE_SETTING_ONLY_SILENT", "I"),
("C", "VIBRATE_TYPE_NOTIFICATION", "I"),
("C", "VIBRATE_TYPE_RINGER", "I"),
("F", "getRingerMode", "()"),
("F", "getVibrateSetting", "(I)"),
("F", "setRingerMode", "(I)"),
("F", "setVibrateSetting", "(I I)"),
("F", "shouldVibrate", "(I)"),
],
"Landroid/os/Vibrator;" : [
("F", "cancel", "()"),
("F", "vibrate", "([L; I)"),
("F", "vibrate", "(J)"),
],
"Landroid/provider/Settings/System;" : [
("C", "VIBRATE_ON", "Ljava/lang/String;"),
],
"Landroid/app/NotificationManager;" : [
("F", "notify", "(I Landroid/app/Notification;)"),
("F", "notify", "(Ljava/lang/String; I Landroid/app/Notification;)"),
],
"Landroid/app/Notification/Builder;" : [
("F", "setDefaults", "(I)"),
],
"Landroid/os/IVibratorService$Stub$Proxy;" : [
("F", "cancelVibrate", "(Landroid/os/IBinder;)"),
("F", "vibrate", "(J Landroid/os/IBinder;)"),
("F", "vibratePattern", "([L; I Landroid/os/IBinder;)"),
],
"Landroid/app/Notification;" : [
("C", "DEFAULT_VIBRATE", "I"),
("C", "defaults", "I"),
],
},
"ASEC_CREATE" : {
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "createSecureContainer", "(Ljava/lang/String; I Ljava/lang/String; Ljava/lang/String; I)"),
("F", "finalizeSecureContainer", "(Ljava/lang/String;)"),
],
},
"WRITE_SECURE_SETTINGS" : {
"Landroid/bluetooth/BluetoothAdapter;" : [
("F", "setScanMode", "(I I)"),
("F", "setScanMode", "(I)"),
],
"Landroid/server/BluetoothService;" : [
("F", "setScanMode", "(I I)"),
],
"Landroid/os/IPowerManager$Stub$Proxy;" : [
("F", "setMaximumScreenOffTimeount", "(I)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "setInstallLocation", "(I)"),
],
"Landroid/bluetooth/IBluetooth$Stub$Proxy;" : [
("F", "setScanMode", "(I I)"),
],
},
"SET_ORIENTATION" : {
"Landroid/view/IWindowManager$Stub$Proxy;" : [
("F", "setRotation", "(I B I)"),
],
},
"PACKAGE_USAGE_STATS" : {
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;" : [
("F", "getAllPkgUsageStats", "()"),
("F", "getPkgUsageStats", "(LComponentName;)"),
],
},
"FLASHLIGHT" : {
"Landroid/os/IHardwareService$Stub$Proxy;" : [
("F", "setFlashlightEnabled", "(B)"),
],
},
"GLOBAL_SEARCH" : {
"Landroid/app/SearchManager;" : [
("C", "EXTRA_SELECT_QUERY", "Ljava/lang/String;"),
("C", "INTENT_ACTION_GLOBAL_SEARCH", "Ljava/lang/String;"),
],
"Landroid/server/search/Searchables;" : [
("F", "buildSearchableList", "()"),
("F", "findGlobalSearchActivity", "()"),
],
},
"CHANGE_WIFI_STATE" : {
"Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [
("F", "addOrUpdateNetwork", "(Landroid/net/wifi/WifiConfiguration;)"),
("F", "disableNetwork", "(I)"),
("F", "disconnect", "()"),
("F", "enableNetwork", "(I B)"),
("F", "pingSupplicant", "()"),
("F", "reassociate", "()"),
("F", "reconnect", "()"),
("F", "removeNetwork", "(I)"),
("F", "saveConfiguration", "()"),
("F", "setNumAllowedChannels", "(I B)"),
("F", "setWifiApEnabled", "(Landroid/net/wifi/WifiConfiguration; B)"),
("F", "setWifiEnabled", "(B)"),
("F", "startScan", "(B)"),
],
"Landroid/net/wifi/WifiManager;" : [
("F", "addNetwork", "(Landroid/net/wifi/WifiConfiguration;)"),
("F", "addOrUpdateNetwork", "(Landroid/net/wifi/WifiConfiguration;)"),
("F", "disableNetwork", "(I)"),
("F", "disconnect", "()"),
("F", "enableNetwork", "(I B)"),
("F", "pingSupplicant", "()"),
("F", "reassociate", "()"),
("F", "reconnect", "()"),
("F", "removeNetwork", "(I)"),
("F", "saveConfiguration", "()"),
("F", "setNumAllowedChannels", "(I B)"),
("F", "setWifiApEnabled", "(Landroid/net/wifi/WifiConfiguration; B)"),
("F", "setWifiEnabled", "(B)"),
("F", "startScan", "()"),
("F", "startScanActive", "()"),
],
},
"BROADCAST_STICKY" : {
"Landroid/app/ExpandableListActivity;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/accessibilityservice/AccessibilityService;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/accounts/GrantCredentialsPermissionActivity;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/backup/BackupAgent;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/service/wallpaper/WallpaperService;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/backup/BackupAgentHelper;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/accounts/AccountAuthenticatorActivity;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "unbroadcastIntent", "(Landroid/app/IApplicationThread; Landroid/content/Intent;)"),
],
"Landroid/app/ActivityGroup;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/content/ContextWrapper;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/Activity;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/ContextImpl;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/AliasActivity;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/content/Context;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/service/urlrenderer/UrlRendererService;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/FullBackupAgent;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/TabActivity;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/view/ContextThemeWrapper;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/speech/RecognitionService;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/IntentService;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/inputmethodservice/AbstractInputMethodService;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/Application;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/ListActivity;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/app/Service;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/content/MutableContextWrapper;" : [
("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"),
("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"),
],
},
"FORCE_STOP_PACKAGES" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "forceStopPackage", "(Ljava/lang/String;)"),
],
"Landroid/app/ActivityManagerNative;" : [
("F", "forceStopPackage", "(Ljava/lang/String;)"),
],
"Landroid/app/ActivityManager;" : [
("F", "forceStopPackage", "(Ljava/lang/String;)"),
],
},
"KILL_BACKGROUND_PROCESSES" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "killBackgroundProcesses", "(Ljava/lang/String;)"),
],
"Landroid/app/ActivityManager;" : [
("F", "killBackgroundProcesses", "(Ljava/lang/String;)"),
],
},
"SET_TIME_ZONE" : {
"Landroid/app/AlarmManager;" : [
("F", "setTimeZone", "(Ljava/lang/String;)"),
("F", "setTimeZone", "(Ljava/lang/String;)"),
],
"Landroid/app/IAlarmManager$Stub$Proxy;" : [
("F", "setTimeZone", "(Ljava/lang/String;)"),
],
},
"BLUETOOTH_ADMIN" : {
"Landroid/server/BluetoothA2dpService;" : [
("F", "connectSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "disconnectSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "resumeSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"),
("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"),
("F", "suspendSink", "(Landroid/bluetooth/BluetoothDevice;)"),
],
"Landroid/bluetooth/BluetoothPbap;" : [
("F", "disconnect", "()"),
],
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;" : [
("F", "connectSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "disconnectSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "resumeSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"),
("F", "suspendSink", "(Landroid/bluetooth/BluetoothDevice;)"),
],
"Landroid/bluetooth/BluetoothAdapter;" : [
("F", "cancelDiscovery", "()"),
("F", "disable", "()"),
("F", "enable", "()"),
("F", "setName", "(Ljava/lang/String;)"),
("F", "startDiscovery", "()"),
("F", "cancelDiscovery", "()"),
("F", "disable", "()"),
("F", "enable", "()"),
("F", "setDiscoverableTimeout", "(I)"),
("F", "setName", "(Ljava/lang/String;)"),
("F", "startDiscovery", "()"),
],
"Landroid/server/BluetoothService;" : [
("F", "cancelBondProcess", "(Ljava/lang/String;)"),
("F", "cancelDiscovery", "()"),
("F", "cancelPairingUserInput", "(Ljava/lang/String;)"),
("F", "createBond", "(Ljava/lang/String;)"),
("F", "disable", "()"),
("F", "disable", "(B)"),
("F", "enable", "()"),
("F", "enable", "(B)"),
("F", "removeBond", "(Ljava/lang/String;)"),
("F", "setDiscoverableTimeout", "(I)"),
("F", "setName", "(Ljava/lang/String;)"),
("F", "setPairingConfirmation", "(Ljava/lang/String; B)"),
("F", "setPasskey", "(Ljava/lang/String; I)"),
("F", "setPin", "(Ljava/lang/String; [L;)"),
("F", "setTrust", "(Ljava/lang/String; B)"),
("F", "startDiscovery", "()"),
],
"Landroid/bluetooth/BluetoothHeadset;" : [
("F", "connectHeadset", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "disconnectHeadset", "()"),
("F", "setPriority", "(Landroid/bluetooth/BluetoothDevice; I)"),
],
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;" : [
("F", "connectHeadset", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "disconnectHeadset", "()"),
("F", "setPriority", "(Landroid/bluetooth/BluetoothDevice; I)"),
],
"Landroid/bluetooth/BluetoothDevice;" : [
("F", "cancelBondProcess", "()"),
("F", "cancelPairingUserInput", "()"),
("F", "createBond", "()"),
("F", "removeBond", "()"),
("F", "setPairingConfirmation", "(B)"),
("F", "setPasskey", "(I)"),
("F", "setPin", "([L;)"),
],
"Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;" : [
("F", "connect", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "disconnect", "()"),
],
"Landroid/bluetooth/BluetoothA2dp;" : [
("F", "connectSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "disconnectSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "resumeSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"),
("F", "suspendSink", "(Landroid/bluetooth/BluetoothDevice;)"),
],
"Landroid/bluetooth/IBluetooth$Stub$Proxy;" : [
("F", "cancelBondProcess", "(Ljava/lang/String;)"),
("F", "cancelDiscovery", "()"),
("F", "cancelPairingUserInput", "(Ljava/lang/String;)"),
("F", "createBond", "(Ljava/lang/String;)"),
("F", "disable", "(B)"),
("F", "enable", "()"),
("F", "removeBond", "(Ljava/lang/String;)"),
("F", "setDiscoverableTimeout", "(I)"),
("F", "setName", "(Ljava/lang/String;)"),
("F", "setPairingConfirmation", "(Ljava/lang/String; B)"),
("F", "setPasskey", "(Ljava/lang/String; I)"),
("F", "setPin", "(Ljava/lang/String; [L;)"),
("F", "setTrust", "(Ljava/lang/String; B)"),
("F", "startDiscovery", "()"),
],
},
"INJECT_EVENTS" : {
"Landroid/view/IWindowManager$Stub$Proxy;" : [
("F", "injectKeyEvent", "(Landroid/view/KeyEvent; B)"),
("F", "injectPointerEvent", "(Landroid/view/MotionEvent; B)"),
("F", "injectTrackballEvent", "(Landroid/view/MotionEvent; B)"),
],
"Landroid/app/Instrumentation;" : [
("F", "invokeContextMenuAction", "(Landroid/app/Activity; I I)"),
("F", "sendCharacterSync", "(I)"),
("F", "sendKeyDownUpSync", "(I)"),
("F", "sendKeySync", "(Landroid/view/KeyEvent;)"),
("F", "sendPointerSync", "(Landroid/view/MotionEvent;)"),
("F", "sendStringSync", "(Ljava/lang/String;)"),
("F", "sendTrackballEventSync", "(Landroid/view/MotionEvent;)"),
],
},
"CAMERA" : {
"Landroid/hardware/Camera/ErrorCallback;" : [
("F", "onError", "(I Landroid/hardware/Camera;)"),
],
"Landroid/media/MediaRecorder;" : [
("F", "setVideoSource", "(I)"),
],
"Landroid/view/KeyEvent;" : [
("C", "KEYCODE_CAMERA", "I"),
],
"Landroid/bluetooth/BluetoothClass/Device;" : [
("C", "AUDIO_VIDEO_VIDEO_CAMERA", "I"),
],
"Landroid/provider/MediaStore;" : [
("C", "INTENT_ACTION_STILL_IMAGE_CAMERA", "Ljava/lang/String;"),
("C", "INTENT_ACTION_VIDEO_CAMERA", "Ljava/lang/String;"),
],
"Landroid/hardware/Camera/CameraInfo;" : [
("C", "CAMERA_FACING_BACK", "I"),
("C", "CAMERA_FACING_FRONT", "I"),
("C", "facing", "I"),
],
"Landroid/provider/ContactsContract/StatusColumns;" : [
("C", "CAPABILITY_HAS_CAMERA", "I"),
],
"Landroid/hardware/Camera/Parameters;" : [
("F", "setRotation", "(I)"),
],
"Landroid/media/MediaRecorder/VideoSource;" : [
("C", "CAMERA", "I"),
],
"Landroid/content/Intent;" : [
("C", "IntentResolution", "Ljava/lang/String;"),
("C", "ACTION_CAMERA_BUTTON", "Ljava/lang/String;"),
],
"Landroid/content/pm/PackageManager;" : [
("C", "FEATURE_CAMERA", "Ljava/lang/String;"),
("C", "FEATURE_CAMERA_AUTOFOCUS", "Ljava/lang/String;"),
("C", "FEATURE_CAMERA_FLASH", "Ljava/lang/String;"),
("C", "FEATURE_CAMERA_FRONT", "Ljava/lang/String;"),
],
"Landroid/hardware/Camera;" : [
("C", "CAMERA_ERROR_SERVER_DIED", "I"),
("C", "CAMERA_ERROR_UNKNOWN", "I"),
("F", "setDisplayOrientation", "(I)"),
("F", "native_setup", "(Ljava/lang/Object;)"),
("F", "open", "()"),
],
},
"SET_WALLPAPER" : {
"Landroid/app/Activity;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/ExpandableListActivity;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/accessibilityservice/AccessibilityService;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/accounts/GrantCredentialsPermissionActivity;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/backup/BackupAgent;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/service/wallpaper/WallpaperService;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/backup/BackupAgentHelper;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/accounts/AccountAuthenticatorActivity;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/IWallpaperManager$Stub$Proxy;" : [
("F", "setWallpaper", "(Ljava/lang/String;)"),
],
"Landroid/app/ActivityGroup;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/content/ContextWrapper;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/WallpaperManager;" : [
("F", "setBitmap", "(Landroid/graphics/Bitmap;)"),
("F", "clear", "()"),
("F", "setBitmap", "(Landroid/graphics/Bitmap;)"),
("F", "setResource", "(I)"),
("F", "setStream", "(Ljava/io/InputStream;)"),
],
"Landroid/app/ContextImpl;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/AliasActivity;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/content/Context;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/service/urlrenderer/UrlRendererService;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/FullBackupAgent;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/TabActivity;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/view/ContextThemeWrapper;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/speech/RecognitionService;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/IntentService;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/inputmethodservice/AbstractInputMethodService;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/Application;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/ListActivity;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/app/Service;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
"Landroid/content/MutableContextWrapper;" : [
("F", "clearWallpaper", "()"),
("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"),
("F", "setWallpaper", "(Ljava/io/InputStream;)"),
],
},
"WAKE_LOCK" : {
"Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [
("F", "acquireWifiLock", "(Landroid/os/IBinder; I Ljava/lang/String;)"),
("F", "releaseWifiLock", "(Landroid/os/IBinder;)"),
],
"Landroid/bluetooth/HeadsetBase;" : [
("F", "acquireWakeLock", "()"),
("F", "finalize", "()"),
("F", "handleInput", "(Ljava/lang/String;)"),
("F", "releaseWakeLock", "()"),
],
"Landroid/os/PowerManager$WakeLock;" : [
("F", "acquire", "()"),
("F", "acquire", "(J)"),
("F", "release", "()"),
("F", "release", "(I)"),
],
"Landroid/media/MediaPlayer;" : [
("F", "setWakeMode", "(Landroid/content/Context; I)"),
("F", "start", "()"),
("F", "stayAwake", "(B)"),
("F", "stop", "()"),
],
"Landroid/bluetooth/ScoSocket;" : [
("F", "acquireWakeLock", "()"),
("F", "close", "()"),
("F", "finalize", "()"),
("F", "releaseWakeLock", "()"),
("F", "releaseWakeLockNow", "()"),
],
"Landroid/media/AsyncPlayer;" : [
("F", "acquireWakeLock", "()"),
("F", "enqueueLocked", "(Landroid/media/AsyncPlayer$Command;)"),
("F", "play", "(Landroid/content/Context; Landroid/net/Uri; B I)"),
("F", "releaseWakeLock", "()"),
("F", "stop", "()"),
],
"Landroid/net/wifi/WifiManager$WifiLock;" : [
("F", "acquire", "()"),
("F", "finalize", "()"),
("F", "release", "()"),
],
"Landroid/os/IPowerManager$Stub$Proxy;" : [
("F", "acquireWakeLock", "(I Landroid/os/IBinder; Ljava/lang/String;)"),
("F", "releaseWakeLock", "(Landroid/os/IBinder; I)"),
],
"Landroid/net/sip/SipAudioCall;" : [
("F", "startAudio", "()"),
],
"Landroid/os/PowerManager;" : [
("C", "ACQUIRE_CAUSES_WAKEUP", "I"),
("C", "FULL_WAKE_LOCK", "I"),
("C", "ON_AFTER_RELEASE", "I"),
("C", "PARTIAL_WAKE_LOCK", "I"),
("C", "SCREEN_BRIGHT_WAKE_LOCK", "I"),
("C", "SCREEN_DIM_WAKE_LOCK", "I"),
("F", "newWakeLock", "(I Ljava/lang/String;)"),
],
},
"MANAGE_ACCOUNTS" : {
"Landroid/accounts/AccountManager;" : [
("F", "addAccount", "(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"),
("F", "clearPassword", "(Landroid/accounts/Account;)"),
("F", "confirmCredentials", "(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"),
("F", "editProperties", "(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"),
("F", "getAuthTokenByFeatures", "(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"),
("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "removeAccount", "(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)"),
("F", "updateCredentials", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"),
("F", "addAccount", "(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
("F", "clearPassword", "(Landroid/accounts/Account;)"),
("F", "confirmCredentials", "(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
("F", "editProperties", "(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "removeAccount", "(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
("F", "updateCredentials", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
],
"Landroid/accounts/AccountManagerService;" : [
("F", "addAcount", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)"),
("F", "checkManageAccountsOrUseCredentialsPermissions", "()"),
("F", "checkManageAccountsPermission", "()"),
("F", "clearPassword", "(Landroid/accounts/Account;)"),
("F", "confirmCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)"),
("F", "editProperties", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)"),
("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "removeAccount", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)"),
("F", "updateCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)"),
],
"Landroid/accounts/IAccountManager$Stub$Proxy;" : [
("F", "addAcount", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)"),
("F", "clearPassword", "(Landroid/accounts/Account;)"),
("F", "confirmCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)"),
("F", "editProperties", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)"),
("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "removeAccount", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)"),
("F", "updateCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)"),
],
},
"WRITE_CALENDAR" : {
"Landroid/provider/Calendar$CalendarAlerts;" : [
("F", "insert", "(Landroid/content/ContentResolver; J J J J I)"),
],
"Landroid/provider/Calendar$Calendars;" : [
("F", "delete", "(Landroid/content/ContentResolver; Ljava/lang/String; [L[Ljava/lang/Strin;)"),
("F", "deleteCalendarsForAccount", "(Landroid/content/ContentResolver; Landroid/accounts/Account;)"),
],
},
"BIND_APPWIDGET" : {
"Landroid/appwidget/AppWidgetManager;" : [
("F", "bindAppWidgetId", "(I Landroid/content/ComponentName;)"),
],
"Lcom/android/internal/appwidget/IAppWidgetService$Stub$Proxy;" : [
("F", "bindAppWidgetId", "(I LComponentName;)"),
],
},
"ASEC_MOUNT_UNMOUNT" : {
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "mountSecureContainer", "(Ljava/lang/String; Ljava/lang/String; I)"),
("F", "unmountSecureContainer", "(Ljava/lang/String; B)"),
],
},
"SET_PREFERRED_APPLICATIONS" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "addPreferredActivity", "(LIntentFilter; I [LComponentName; LComponentName;)"),
("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"),
("F", "replacePreferredActivity", "(LIntentFilter; I [LComponentName; LComponentName;)"),
("F", "addPreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"),
("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"),
("F", "replacePreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "addPreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"),
("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"),
("F", "replacePreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "addPreferredActivity", "(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)"),
("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"),
("F", "replacePreferredActivity", "(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)"),
],
},
"NFC" : {
"Landroid/inputmethodservice/InputMethodService;" : [
("C", "SoftInputView", "I"),
("C", "CandidatesView", "I"),
("C", "FullscreenMode", "I"),
("C", "GeneratingText", "I"),
],
"Landroid/nfc/tech/NfcA;" : [
("F", "close", "()"),
("F", "connect", "()"),
("F", "get", "(Landroid/nfc/Tag;)"),
("F", "transceive", "([B)"),
],
"Landroid/nfc/tech/NfcB;" : [
("F", "close", "()"),
("F", "connect", "()"),
("F", "get", "(Landroid/nfc/Tag;)"),
("F", "transceive", "([B)"),
],
"Landroid/nfc/NfcAdapter;" : [
("C", "ACTION_TECH_DISCOVERED", "Ljava/lang/String;"),
("F", "disableForegroundDispatch", "(Landroid/app/Activity;)"),
("F", "disableForegroundNdefPush", "(Landroid/app/Activity;)"),
("F", "enableForegroundDispatch", "(Landroid/app/Activity; Landroid/app/PendingIntent; [Landroid/content/IntentFilter; [[Ljava/lang/String[];)"),
("F", "enableForegroundNdefPush", "(Landroid/app/Activity; Landroid/nfc/NdefMessage;)"),
("F", "getDefaultAdapter", "()"),
("F", "getDefaultAdapter", "(Landroid/content/Context;)"),
("F", "isEnabled", "()"),
],
"Landroid/nfc/tech/NfcF;" : [
("F", "close", "()"),
("F", "connect", "()"),
("F", "get", "(Landroid/nfc/Tag;)"),
("F", "transceive", "([B)"),
],
"Landroid/nfc/tech/NdefFormatable;" : [
("F", "close", "()"),
("F", "connect", "()"),
("F", "format", "(Landroid/nfc/NdefMessage;)"),
("F", "formatReadOnly", "(Landroid/nfc/NdefMessage;)"),
],
"Landroid/app/Activity;" : [
("C", "Fragments", "I"),
("C", "ActivityLifecycle", "I"),
("C", "ConfigurationChanges", "I"),
("C", "StartingActivities", "I"),
("C", "SavingPersistentState", "I"),
("C", "Permissions", "I"),
("C", "ProcessLifecycle", "I"),
],
"Landroid/nfc/tech/MifareClassic;" : [
("C", "KEY_NFC_FORUM", "[B"),
("F", "authenticateSectorWithKeyA", "(I [B)"),
("F", "authenticateSectorWithKeyB", "(I [B)"),
("F", "close", "()"),
("F", "connect", "()"),
("F", "decrement", "(I I)"),
("F", "increment", "(I I)"),
("F", "readBlock", "(I)"),
("F", "restore", "(I)"),
("F", "transceive", "([B)"),
("F", "transfer", "(I)"),
("F", "writeBlock", "(I [B)"),
],
"Landroid/nfc/Tag;" : [
("F", "getTechList", "()"),
],
"Landroid/app/Service;" : [
("C", "WhatIsAService", "I"),
("C", "ServiceLifecycle", "I"),
("C", "Permissions", "I"),
("C", "ProcessLifecycle", "I"),
("C", "LocalServiceSample", "I"),
("C", "RemoteMessengerServiceSample", "I"),
],
"Landroid/nfc/NfcManager;" : [
("F", "getDefaultAdapter", "()"),
],
"Landroid/nfc/tech/MifareUltralight;" : [
("F", "close", "()"),
("F", "connect", "()"),
("F", "readPages", "(I)"),
("F", "transceive", "([B)"),
("F", "writePage", "(I [B)"),
],
"Landroid/nfc/tech/NfcV;" : [
("F", "close", "()"),
("F", "connect", "()"),
("F", "get", "(Landroid/nfc/Tag;)"),
("F", "transceive", "([B)"),
],
"Landroid/nfc/tech/TagTechnology;" : [
("F", "close", "()"),
("F", "connect", "()"),
],
"Landroid/preference/PreferenceActivity;" : [
("C", "SampleCode", "Ljava/lang/String;"),
],
"Landroid/content/pm/PackageManager;" : [
("C", "FEATURE_NFC", "Ljava/lang/String;"),
],
"Landroid/content/Context;" : [
("C", "NFC_SERVICE", "Ljava/lang/String;"),
],
"Landroid/nfc/tech/Ndef;" : [
("C", "NFC_FORUM_TYPE_1", "Ljava/lang/String;"),
("C", "NFC_FORUM_TYPE_2", "Ljava/lang/String;"),
("C", "NFC_FORUM_TYPE_3", "Ljava/lang/String;"),
("C", "NFC_FORUM_TYPE_4", "Ljava/lang/String;"),
("F", "close", "()"),
("F", "connect", "()"),
("F", "getType", "()"),
("F", "isWritable", "()"),
("F", "makeReadOnly", "()"),
("F", "writeNdefMessage", "(Landroid/nfc/NdefMessage;)"),
],
"Landroid/nfc/tech/IsoDep;" : [
("F", "close", "()"),
("F", "connect", "()"),
("F", "setTimeout", "(I)"),
("F", "transceive", "([B)"),
],
},
"CALL_PHONE" : {
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [
("F", "call", "(Ljava/lang/String;)"),
("F", "endCall", "()"),
],
},
"INTERNET" : {
"Lcom/android/http/multipart/FilePart;" : [
("F", "sendData", "(Ljava/io/OutputStream;)"),
("F", "sendDispositionHeader", "(Ljava/io/OutputStream;)"),
],
"Ljava/net/HttpURLConnection;" : [
("F", "<init>", "(Ljava/net/URL;)"),
("F", "connect", "()"),
],
"Landroid/webkit/WebSettings;" : [
("F", "setBlockNetworkLoads", "(B)"),
("F", "verifyNetworkAccess", "()"),
],
"Lorg/apache/http/impl/client/DefaultHttpClient;" : [
("F", "<init>", "()"),
("F", "<init>", "(Lorg/apache/http/params/HttpParams;)"),
("F", "<init>", "(Lorg/apache/http/conn/ClientConnectionManager; Lorg/apache/http/params/HttpParams;)"),
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)"),
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"),
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"),
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"),
],
"Lorg/apache/http/impl/client/HttpClient;" : [
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)"),
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"),
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"),
("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)"),
("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"),
],
"Lcom/android/http/multipart/Part;" : [
("F", "send", "(Ljava/io/OutputStream;)"),
("F", "sendParts", "(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part;)"),
("F", "sendParts", "(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part; [B)"),
("F", "sendStart", "(Ljava/io/OutputStream;)"),
("F", "sendTransferEncodingHeader", "(Ljava/io/OutputStream;)"),
],
"Landroid/drm/DrmErrorEvent;" : [
("C", "TYPE_NO_INTERNET_CONNECTION", "I"),
],
"Landroid/webkit/WebViewCore;" : [
("F", "<init>", "(Landroid/content/Context; Landroid/webkit/WebView; Landroid/webkit/CallbackProxy; Ljava/util/Map;)"),
],
"Ljava/net/URLConnection;" : [
("F", "connect", "()"),
("F", "getInputStream", "()"),
],
"Landroid/app/Activity;" : [
("F", "setContentView", "(I)"),
],
"Ljava/net/MulticastSocket;" : [
("F", "<init>", "()"),
("F", "<init>", "(I)"),
("F", "<init>", "(Ljava/net/SocketAddress;)"),
],
"Lcom/android/http/multipart/StringPart;" : [
("F", "sendData", "(Ljava/io/OuputStream;)"),
],
"Ljava/net/URL;" : [
("F", "getContent", "([Ljava/lang/Class;)"),
("F", "getContent", "()"),
("F", "openConnection", "(Ljava/net/Proxy;)"),
("F", "openConnection", "()"),
("F", "openStream", "()"),
],
"Ljava/net/DatagramSocket;" : [
("F", "<init>", "()"),
("F", "<init>", "(I)"),
("F", "<init>", "(I Ljava/net/InetAddress;)"),
("F", "<init>", "(Ljava/net/SocketAddress;)"),
],
"Ljava/net/ServerSocket;" : [
("F", "<init>", "()"),
("F", "<init>", "(I)"),
("F", "<init>", "(I I)"),
("F", "<init>", "(I I Ljava/net/InetAddress;)"),
("F", "bind", "(Ljava/net/SocketAddress;)"),
("F", "bind", "(Ljava/net/SocketAddress; I)"),
],
"Ljava/net/Socket;" : [
("F", "<init>", "()"),
("F", "<init>", "(Ljava/lang/String; I)"),
("F", "<init>", "(Ljava/lang/String; I Ljava/net/InetAddress; I)"),
("F", "<init>", "(Ljava/lang/String; I B)"),
("F", "<init>", "(Ljava/net/InetAddress; I)"),
("F", "<init>", "(Ljava/net/InetAddress; I Ljava/net/InetAddress; I)"),
("F", "<init>", "(Ljava/net/InetAddress; I B)"),
],
"Landroid/webkit/WebView;" : [
("F", "<init>", "(Landroid/content/Context; Landroid/util/AttributeSet; I)"),
("F", "<init>", "(Landroid/content/Context; Landroid/util/AttributeSet;)"),
("F", "<init>", "(Landroid/content/Context;)"),
],
"Ljava/net/NetworkInterface;" : [
("F", "<init>", "()"),
("F", "<init>", "(Ljava/lang/String; I Ljava/net/InetAddress;)"),
],
},
"ACCESS_FINE_LOCATION" : {
"Landroid/webkit/WebChromeClient;" : [
("F", "onGeolocationPermissionsShowPrompt", "(Ljava/lang/String; Landroid/webkit/GeolocationPermissions/Callback;)"),
],
"Landroid/location/LocationManager;" : [
("C", "GPS_PROVIDER", "Ljava/lang/String;"),
("C", "NETWORK_PROVIDER", "Ljava/lang/String;"),
("C", "PASSIVE_PROVIDER", "Ljava/lang/String;"),
("F", "addGpsStatusListener", "(Landroid/location/GpsStatus/Listener;)"),
("F", "addNmeaListener", "(Landroid/location/GpsStatus/NmeaListener;)"),
("F", "_requestLocationUpdates", "(Ljava/lang/String; J F Landroid/app/PendingIntent;)"),
("F", "_requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)"),
("F", "addGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)"),
("F", "addNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)"),
("F", "addProximityAlert", "(D D F J Landroid/app/PendingIntent;)"),
("F", "best", "(Ljava/util/List;)"),
("F", "getBestProvider", "(Landroid/location/Criteria; B)"),
("F", "getLastKnownLocation", "(Ljava/lang/String;)"),
("F", "getProvider", "(Ljava/lang/String;)"),
("F", "getProviders", "(Landroid/location/Criteria; B)"),
("F", "getProviders", "(B)"),
("F", "isProviderEnabled", "(Ljava/lang/String;)"),
("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/app/PendingIntent;)"),
("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)"),
("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/LocationListener;)"),
("F", "sendExtraCommand", "(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/webkit/GeolocationService;" : [
("F", "registerForLocationUpdates", "()"),
("F", "setEnableGps", "(B)"),
("F", "start", "()"),
],
"Landroid/telephony/TelephonyManager;" : [
("F", "getCellLocation", "()"),
("F", "getCellLocation", "()"),
("F", "getNeighboringCellInfo", "()"),
],
"Landroid/location/ILocationManager$Stub$Proxy;" : [
("F", "addGpsStatusListener", "(Landroid/location/IGpsStatusListener;)"),
("F", "addProximityAlert", "(D D F J Landroid/app/PendingIntent;)"),
("F", "getLastKnownLocation", "(Ljava/lang/String;)"),
("F", "getProviderInfo", "(Ljava/lang/String;)"),
("F", "getProviders", "(B)"),
("F", "isProviderEnabled", "(Ljava/lang/String;)"),
("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/ILocationListener;)"),
("F", "requestLocationUpdatesPI", "(Ljava/lang/String; J F Landroid/app/PendingIntent;)"),
("F", "sendExtraCommand", "(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [
("F", "getCellLocation", "()"),
("F", "getNeighboringCellInfo", "()"),
],
"Landroid/webkit/GeolocationPermissions$Callback;" : [
("F", "invok", "()"),
],
},
"READ_SMS" : {
"Landroid/provider/Telephony$Sms$Inbox;" : [
("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B)"),
],
"Landroid/provider/Telephony$Threads;" : [
("F", "getOrCreateThreadId", "(Landroid/content/Context; Ljava/lang/String;)"),
("F", "getOrCreateThreadId", "(Landroid/content/Context; Ljava/util/Set;)"),
],
"Landroid/provider/Telephony$Mms;" : [
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"),
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)"),
],
"Landroid/provider/Telephony$Sms$Draft;" : [
("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)"),
],
"Landroid/provider/Telephony$Sms$Sent;" : [
("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)"),
],
"Landroid/provider/Telephony$Sms;" : [
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"),
("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)"),
],
},
"ACCESS_SURFACE_FLINGER" : {
"Landroid/view/SurfaceSession;" : [
("F", "<init>", "()"),
],
"Landroid/view/Surface;" : [
("F", "closeTransaction", "()"),
("F", "freezeDisplay", "(I)"),
("F", "setOrientation", "(I I I)"),
("F", "setOrientation", "(I I)"),
("F", "unfreezeDisplay", "(I)"),
],
},
"REORDER_TASKS" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "moveTaskBackwards", "(I)"),
("F", "moveTaskToBack", "(I)"),
("F", "moveTaskToFront", "(I)"),
],
"Landroid/app/ActivityManager;" : [
("F", "moveTaskToFront", "(I I)"),
],
},
"MODIFY_AUDIO_SETTINGS" : {
"Landroid/net/sip/SipAudioCall;" : [
("F", "setSpeakerMode", "(B)"),
],
"Landroid/server/BluetoothA2dpService;" : [
("F", "checkSinkSuspendState", "(I)"),
("F", "handleSinkStateChange", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "onBluetoothDisable", "()"),
("F", "onBluetoothEnable", "()"),
],
"Landroid/media/IAudioService$Stub$Proxy;" : [
("F", "setBluetoothScoOn", "(B)"),
("F", "setMode", "(I Landroid/os/IBinder;)"),
("F", "setSpeakerphoneOn", "(B)"),
("F", "startBluetoothSco", "(Landroid/os/IBinder;)"),
("F", "stopBluetoothSco", "(Landroid/os/IBinder;)"),
],
"Landroid/media/AudioService;" : [
("F", "setBluetoothScoOn", "(B)"),
("F", "setMode", "(I Landroid/os/IBinder;)"),
("F", "setSpeakerphoneOn", "(B)"),
("F", "startBluetoothSco", "(Landroid/os/IBinder;)"),
("F", "stopBluetoothSco", "(Landroid/os/IBinder;)"),
],
"Landroid/media/AudioManager;" : [
("F", "startBluetoothSco", "()"),
("F", "stopBluetoothSco", "()"),
("F", "isBluetoothA2dpOn", "()"),
("F", "isWiredHeadsetOn", "()"),
("F", "setBluetoothScoOn", "(B)"),
("F", "setMicrophoneMute", "(B)"),
("F", "setMode", "(I)"),
("F", "setParameter", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "setParameters", "(Ljava/lang/String;)"),
("F", "setSpeakerphoneOn", "(B)"),
("F", "startBluetoothSco", "()"),
("F", "stopBluetoothSco", "()"),
],
},
"READ_PHONE_STATE" : {
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;" : [
("F", "getDeviceId", "()"),
("F", "getDeviceSvn", "()"),
("F", "getIccSerialNumber", "()"),
("F", "getLine1AlphaTag", "()"),
("F", "getLine1Number", "()"),
("F", "getSubscriberId", "()"),
("F", "getVoiceMailAlphaTag", "()"),
("F", "getVoiceMailNumber", "()"),
],
"Landroid/telephony/PhoneStateListener;" : [
("C", "LISTEN_CALL_FORWARDING_INDICATOR", "I"),
("C", "LISTEN_CALL_STATE", "I"),
("C", "LISTEN_DATA_ACTIVITY", "I"),
("C", "LISTEN_MESSAGE_WAITING_INDICATOR", "I"),
("C", "LISTEN_SIGNAL_STRENGTH", "I"),
],
"Landroid/accounts/AccountManagerService$SimWatcher;" : [
("F", "onReceive", "(Landroid/content/Context; Landroid/content/Intent;)"),
],
"Lcom/android/internal/telephony/CallerInfo;" : [
("F", "markAsVoiceMail", "()"),
],
"Landroid/os/Build/VERSION_CODES;" : [
("C", "DONUT", "I"),
],
"Landroid/telephony/TelephonyManager;" : [
("C", "ACTION_PHONE_STATE_CHANGED", "Ljava/lang/String;"),
("F", "getDeviceId", "()"),
("F", "getDeviceSoftwareVersion", "()"),
("F", "getLine1Number", "()"),
("F", "getSimSerialNumber", "()"),
("F", "getSubscriberId", "()"),
("F", "getVoiceMailAlphaTag", "()"),
("F", "getVoiceMailNumber", "()"),
("F", "getDeviceId", "()"),
("F", "getDeviceSoftwareVersion", "()"),
("F", "getLine1AlphaTag", "()"),
("F", "getLine1Number", "()"),
("F", "getSimSerialNumber", "()"),
("F", "getSubscriberId", "()"),
("F", "getVoiceMailAlphaTag", "()"),
("F", "getVoiceMailNumber", "()"),
("F", "listen", "(Landroid/telephony/PhoneStateListener; I)"),
],
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;" : [
("F", "listen", "(Ljava/lang/String; Lcom/android/internal/telephony/IPhoneStateListener; I B)"),
],
"Landroid/telephony/PhoneNumberUtils;" : [
("F", "isVoiceMailNumber", "(Ljava/lang/String;)"),
],
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [
("F", "isSimPinEnabled", "()"),
],
},
"WRITE_SETTINGS" : {
"Landroid/media/RingtoneManager;" : [
("F", "setActualDefaultRingtoneUri", "(Landroid/content/Context; I Landroid/net/Uri;)"),
],
"Landroid/os/IPowerManager$Stub$Proxy;" : [
("F", "setStayOnSetting", "(I)"),
],
"Landroid/server/BluetoothService;" : [
("F", "persistBluetoothOnSetting", "(B)"),
],
"Landroid/provider/Settings$Secure;" : [
("F", "putFloat", "(Landroid/content/ContentResolver; Ljava/lang/String; F)"),
("F", "putInt", "(Landroid/content/ContentResolver; Ljava/lang/String; I)"),
("F", "putLong", "(Landroid/content/ContentResolver; Ljava/lang/String; J)"),
("F", "putString", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)"),
("F", "setLocationProviderEnabled", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"),
],
"Landroid/provider/Settings$Bookmarks;" : [
("F", "add", "(Landroid/content/ContentResolver; Landroid/content/Intent; Ljava/lang/String; Ljava/lang/String; C I)"),
("F", "getIntentForShortcut", "(Landroid/content/ContentResolver; C)"),
],
"Landroid/os/IMountService$Stub$Proxy;" : [
("F", "setAutoStartUm", "()"),
("F", "setPlayNotificationSound", "()"),
],
"Landroid/provider/Settings$System;" : [
("F", "putConfiguration", "(Landroid/content/ContentResolver; Landroid/content/res/Configuration;)"),
("F", "putFloat", "(Landroid/content/ContentResolver; Ljava/lang/String; F)"),
("F", "putInt", "(Landroid/content/ContentResolver; Ljava/lang/String; I)"),
("F", "putLong", "(Landroid/content/ContentResolver; Ljava/lang/String; J)"),
("F", "putString", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)"),
("F", "setShowGTalkServiceStatus", "(Landroid/content/ContentResolver; B)"),
],
},
"BIND_WALLPAPER" : {
"Landroid/service/wallpaper/WallpaperService;" : [
("C", "SERVICE_INTERFACE", "Ljava/lang/String;"),
],
"Lcom/android/server/WallpaperManagerService;" : [
("F", "bindWallpaperComponentLocked", "(Landroid/content/ComponentName;)"),
],
},
"DUMP" : {
"Landroid/content/ContentService;" : [
("F", "dump", "(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Strin;)"),
],
"Landroid/view/IWindowManager$Stub$Proxy;" : [
("F", "isViewServerRunning", "()"),
("F", "startViewServer", "(I)"),
("F", "stopViewServer", "()"),
],
"Landroid/os/Debug;" : [
("F", "dumpService", "(Ljava/lang/String; Ljava/io/FileDescriptor; [Ljava/lang/String;)"),
],
"Landroid/os/IBinder;" : [
("C", "DUMP_TRANSACTION", "I"),
],
"Lcom/android/server/WallpaperManagerService;" : [
("F", "dump", "(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Stri;)"),
],
},
"USE_CREDENTIALS" : {
"Landroid/accounts/AccountManager;" : [
("F", "blockingGetAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B)"),
("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"),
("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"),
("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "blockingGetAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B)"),
("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
],
"Landroid/accounts/AccountManagerService;" : [
("F", "getAuthToken", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)"),
],
"Landroid/accounts/IAccountManager$Stub$Proxy;" : [
("F", "getAuthToken", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)"),
],
},
"UPDATE_DEVICE_STATS" : {
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;" : [
("F", "notePauseComponent", "(LComponentName;)"),
("F", "noteResumeComponent", "(LComponentName;)"),
],
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;" : [
("F", "noteFullWifiLockAcquired", "(I)"),
("F", "noteFullWifiLockReleased", "(I)"),
("F", "noteInputEvent", "()"),
("F", "notePhoneDataConnectionState", "(I B)"),
("F", "notePhoneOff", "()"),
("F", "notePhoneOn", "()"),
("F", "notePhoneSignalStrength", "(LSignalStrength;)"),
("F", "notePhoneState", "(I)"),
("F", "noteScanWifiLockAcquired", "(I)"),
("F", "noteScanWifiLockReleased", "(I)"),
("F", "noteScreenBrightness", "(I)"),
("F", "noteScreenOff", "()"),
("F", "noteScreenOn", "()"),
("F", "noteStartGps", "(I)"),
("F", "noteStartSensor", "(I I)"),
("F", "noteStartWakelock", "(I Ljava/lang/String; I)"),
("F", "noteStopGps", "(I)"),
("F", "noteStopSensor", "(I I)"),
("F", "noteStopWakelock", "(I Ljava/lang/String; I)"),
("F", "noteUserActivity", "(I I)"),
("F", "noteWifiMulticastDisabled", "(I)"),
("F", "noteWifiMulticastEnabled", "(I)"),
("F", "noteWifiOff", "(I)"),
("F", "noteWifiOn", "(I)"),
("F", "noteWifiRunning", "()"),
("F", "noteWifiStopped", "()"),
("F", "recordCurrentLevel", "(I)"),
("F", "setOnBattery", "(B I)"),
],
},
"SEND_SMS" : {
"Landroid/telephony/gsm/SmsManager;" : [
("F", "getDefault", "()"),
("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
("F", "sendMultipartTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)"),
("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
],
"Landroid/telephony/SmsManager;" : [
("F", "getDefault", "()"),
("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
("F", "sendMultipartTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)"),
("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
],
"Lcom/android/internal/telephony/ISms$Stub$Proxy;" : [
("F", "sendData", "(Ljava/lang/String; Ljava/lang/String; I [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
("F", "sendMultipartText", "(Ljava/lang/String; Ljava/lang/String; Ljava/util/List; Ljava/util/List; Ljava/util/List;)"),
("F", "sendText", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"),
],
},
"WRITE_USER_DICTIONARY" : {
"Landroid/provider/UserDictionary$Words;" : [
("F", "addWord", "(Landroid/content/Context; Ljava/lang/String; I I)"),
],
},
"ACCESS_COARSE_LOCATION" : {
"Landroid/telephony/TelephonyManager;" : [
("F", "getCellLocation", "()"),
],
"Landroid/telephony/PhoneStateListener;" : [
("C", "LISTEN_CELL_LOCATION", "I"),
],
"Landroid/location/LocationManager;" : [
("C", "NETWORK_PROVIDER", "Ljava/lang/String;"),
],
},
"ASEC_RENAME" : {
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "renameSecureContainer", "(Ljava/lang/String; Ljava/lang/String;)"),
],
},
"SYSTEM_ALERT_WINDOW" : {
"Landroid/view/IWindowSession$Stub$Proxy;" : [
("F", "add", "(Landroid/view/IWindow; Landroid/view/WindowManager$LayoutParams; I Landroid/graphics/Rect;)"),
],
},
"CHANGE_WIFI_MULTICAST_STATE" : {
"Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [
("F", "acquireMulticastLock", "(Landroid/os/IBinder; Ljava/lang/String;)"),
("F", "initializeMulticastFiltering", "()"),
("F", "releaseMulticastLock", "()"),
],
"Landroid/net/wifi/WifiManager$MulticastLock;" : [
("F", "acquire", "()"),
("F", "finalize", "()"),
("F", "release", "()"),
],
"Landroid/net/wifi/WifiManager;" : [
("F", "initializeMulticastFiltering", "()"),
],
},
"RECEIVE_BOOT_COMPLETED" : {
"Landroid/content/Intent;" : [
("C", "ACTION_BOOT_COMPLETED", "Ljava/lang/String;"),
],
},
"SET_ALARM" : {
"Landroid/provider/AlarmClock;" : [
("C", "ACTION_SET_ALARM", "Ljava/lang/String;"),
("C", "EXTRA_HOUR", "Ljava/lang/String;"),
("C", "EXTRA_MESSAGE", "Ljava/lang/String;"),
("C", "EXTRA_MINUTES", "Ljava/lang/String;"),
("C", "EXTRA_SKIP_UI", "Ljava/lang/String;"),
],
},
"WRITE_CONTACTS" : {
"Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;" : [
("F", "updateAdnRecordsInEfByIndex", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
("F", "updateAdnRecordsInEfBySearch", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/provider/Contacts$People;" : [
("F", "addToGroup", "(Landroid/content/ContentResolver; J J)"),
],
"Landroid/provider/ContactsContract$Contacts;" : [
("F", "markAsContacted", "(Landroid/content/ContentResolver; J)"),
],
"Landroid/provider/Contacts$Settings;" : [
("F", "setSetting", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
],
"Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;" : [
("F", "updateAdnRecordsInEfByIndex", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
("F", "updateAdnRecordsInEfBySearch", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/provider/CallLog$Calls;" : [
("F", "removeExpiredEntries", "(Landroid/content/Context;)"),
],
"Landroid/pim/vcard/VCardEntryCommitter;" : [
("F", "onEntryCreated", "(Landroid/pim/vcard/VCardEntry;)"),
],
"Landroid/pim/vcard/VCardEntryHandler;" : [
("F", "onEntryCreated", "(Landroid/pim/vcard/VCardEntry;)"),
],
"Landroid/pim/vcard/VCardEntry;" : [
("F", "pushIntoContentResolver", "(Landroid/content/ContentResolver;)"),
],
},
"PROCESS_OUTGOING_CALLS" : {
"Landroid/content/Intent;" : [
("C", "ACTION_NEW_OUTGOING_CALL", "Ljava/lang/String;"),
],
},
"EXPAND_STATUS_BAR" : {
"Landroid/app/StatusBarManager;" : [
("F", "collapse", "()"),
("F", "expand", "()"),
("F", "toggle", "()"),
],
"Landroid/app/IStatusBar$Stub$Proxy;" : [
("F", "activate", "()"),
("F", "deactivate", "()"),
("F", "toggle", "()"),
],
},
"MODIFY_PHONE_STATE" : {
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [
("F", "answerRingingCall", "()"),
("F", "cancelMissedCallsNotification", "()"),
("F", "disableApnType", "(Ljava/lang/String;)"),
("F", "disableDataConnectivity", "()"),
("F", "enableApnType", "(Ljava/lang/String;)"),
("F", "enableDataConnectivity", "()"),
("F", "handlePinMmi", "(Ljava/lang/String;)"),
("F", "setRadio", "(B)"),
("F", "silenceRinger", "()"),
("F", "supplyPin", "(Ljava/lang/String;)"),
("F", "toggleRadioOnOff", "()"),
],
"Landroid/net/MobileDataStateTracker;" : [
("F", "reconnect", "()"),
("F", "setRadio", "(B)"),
("F", "teardown", "()"),
],
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;" : [
("F", "notifyCallForwardingChanged", "(B)"),
("F", "notifyCallState", "(I Ljava/lang/String;)"),
("F", "notifyCellLocation", "(Landroid/os/Bundle;)"),
("F", "notifyDataActivity", "(I)"),
("F", "notifyDataConnection", "(I B Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Ljava/lang/String; I)"),
("F", "notifyDataConnectionFailed", "(Ljava/lang/String;)"),
("F", "notifyMessageWaitingChanged", "(B)"),
("F", "notifyServiceState", "(Landroid/telephony/ServiceState;)"),
("F", "notifySignalStrength", "(Landroid/telephony/SignalStrength;)"),
],
},
"MOUNT_FORMAT_FILESYSTEMS" : {
"Landroid/os/IMountService$Stub$Proxy;" : [
("F", "formatMedi", "()"),
],
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "formatVolume", "(Ljava/lang/String;)"),
],
},
"ACCESS_DOWNLOAD_MANAGER" : {
"Landroid/net/Downloads$DownloadBase;" : [
("F", "startDownloadByUri", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/net/Downloads$ByUri;" : [
("F", "getCurrentOtaDownloads", "(Landroid/content/Context; Ljava/lang/String;)"),
("F", "getProgressCursor", "(Landroid/content/Context; J)"),
("F", "getStatus", "(Landroid/content/Context; Ljava/lang/String; J)"),
("F", "removeAllDownloadsByPackage", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String;)"),
("F", "startDownloadByUri", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/net/Downloads$ById;" : [
("F", "deleteDownload", "(Landroid/content/Context; J)"),
("F", "getMimeTypeForId", "(Landroid/content/Context; J)"),
("F", "getStatus", "(Landroid/content/Context; J)"),
("F", "openDownload", "(Landroid/content/Context; J Ljava/lang/String;)"),
("F", "openDownloadStream", "(Landroid/content/Context; J)"),
("F", "startDownloadByUri", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
],
},
"READ_INPUT_STATE" : {
"Landroid/view/IWindowManager$Stub$Proxy;" : [
("F", "getDPadKeycodeState", "(I)"),
("F", "getDPadScancodeState", "(I)"),
("F", "getKeycodeState", "(I)"),
("F", "getKeycodeStateForDevice", "(I I)"),
("F", "getScancodeState", "(I)"),
("F", "getScancodeStateForDevice", "(I I)"),
("F", "getSwitchState", "(I)"),
("F", "getSwitchStateForDevice", "(I I)"),
("F", "getTrackballKeycodeState", "(I)"),
("F", "getTrackballScancodeState", "(I)"),
],
},
"READ_SYNC_STATS" : {
"Landroid/app/ContextImpl$ApplicationContentResolver;" : [
("F", "getCurrentSync", "()"),
("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
"Landroid/content/ContentService;" : [
("F", "getCurrentSync", "()"),
("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
"Landroid/content/ContentResolver;" : [
("F", "getCurrentSync", "()"),
("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
"Landroid/content/IContentService$Stub$Proxy;" : [
("F", "getCurrentSync", "()"),
("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"),
("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"),
],
},
"SET_TIME" : {
"Landroid/app/AlarmManager;" : [
("F", "setTime", "(J)"),
("F", "setTimeZone", "(Ljava/lang/String;)"),
("F", "setTime", "(J)"),
],
"Landroid/app/IAlarmManager$Stub$Proxy;" : [
("F", "setTime", "(J)"),
],
},
"CHANGE_WIMAX_STATE" : {
"Lcom/htc/net/wimax/WimaxController$Stub$Proxy;" : [
("F", "setWimaxEnable", "()"),
],
},
"MOUNT_UNMOUNT_FILESYSTEMS" : {
"Landroid/os/IMountService$Stub$Proxy;" : [
("F", "mountMedi", "()"),
("F", "unmountMedi", "()"),
],
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "getStorageUsers", "(Ljava/lang/String;)"),
("F", "mountVolume", "(Ljava/lang/String;)"),
("F", "setUsbMassStorageEnabled", "(B)"),
("F", "unmountVolume", "(Ljava/lang/String; B)"),
],
"Landroid/os/storage/StorageManager;" : [
("F", "disableUsbMassStorage", "()"),
("F", "enableUsbMassStorage", "()"),
],
},
"MOVE_PACKAGE" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "movePackage", "(Ljava/lang/String; LIPackageMoveObserver; I)"),
("F", "movePackage", "(Ljava/lang/String; LIPackageMoveObserver; I)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "movePackage", "(Ljava/lang/String; LIPackageMoveObserver; I)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "movePackage", "(Ljava/lang/String; Landroid/content/pm/IPackageMoveObserver; I)"),
],
},
"ACCESS_WIMAX_STATE" : {
"Lcom/htc/net/wimax/WimaxController$Stub$Proxy;" : [
("F", "getConnectionInf", "()"),
("F", "getWimaxStat", "()"),
("F", "isBackoffStat", "()"),
("F", "isWimaxEnable", "()"),
],
},
"ACCESS_WIFI_STATE" : {
"Landroid/net/sip/SipAudioCall;" : [
("F", "startAudio", "()"),
],
"Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [
("F", "getConfiguredNetworks", "()"),
("F", "getConnectionInfo", "()"),
("F", "getDhcpInfo", "()"),
("F", "getNumAllowedChannels", "()"),
("F", "getScanResults", "()"),
("F", "getValidChannelCounts", "()"),
("F", "getWifiApEnabledState", "()"),
("F", "getWifiEnabledState", "()"),
("F", "isMulticastEnabled", "()"),
],
"Landroid/net/wifi/WifiManager;" : [
("F", "getConfiguredNetworks", "()"),
("F", "getConnectionInfo", "()"),
("F", "getDhcpInfo", "()"),
("F", "getNumAllowedChannels", "()"),
("F", "getScanResults", "()"),
("F", "getValidChannelCounts", "()"),
("F", "getWifiApState", "()"),
("F", "getWifiState", "()"),
("F", "isMulticastEnabled", "()"),
("F", "isWifiApEnabled", "()"),
("F", "isWifiEnabled", "()"),
],
},
"READ_HISTORY_BOOKMARKS" : {
"Landroid/webkit/WebIconDatabase;" : [
("F", "bulkRequestIconForPageUrl", "(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)"),
],
"Landroid/provider/Browser;" : [
("C", "BOOKMARKS_URI", "Landroid/net/Uri;"),
("C", "SEARCHES_URI", "Landroid/net/Uri;"),
("F", "addSearchUrl", "(Landroid/content/ContentResolver; Ljava/lang/String;)"),
("F", "canClearHistory", "(Landroid/content/ContentResolver;)"),
("F", "getAllBookmarks", "(Landroid/content/ContentResolver;)"),
("F", "getAllVisitedUrls", "(Landroid/content/ContentResolver;)"),
("F", "requestAllIcons", "(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase/IconListener;)"),
("F", "truncateHistory", "(Landroid/content/ContentResolver;)"),
("F", "updateVisitedHistory", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"),
("F", "addSearchUrl", "(Landroid/content/ContentResolver; Ljava/lang/String;)"),
("F", "canClearHistory", "(Landroid/content/ContentResolver;)"),
("F", "clearHistory", "(Landroid/content/ContentResolver;)"),
("F", "deleteFromHistory", "(Landroid/content/ContentResolver; Ljava/lang/String;)"),
("F", "deleteHistoryTimeFrame", "(Landroid/content/ContentResolver; J J)"),
("F", "deleteHistoryWhere", "(Landroid/content/ContentResolver; Ljava/lang/String;)"),
("F", "getAllBookmarks", "(Landroid/content/ContentResolver;)"),
("F", "getAllVisitedUrls", "(Landroid/content/ContentResolver;)"),
("F", "getVisitedHistory", "(Landroid/content/ContentResolver;)"),
("F", "getVisitedLike", "(Landroid/content/ContentResolver; Ljava/lang/String;)"),
("F", "requestAllIcons", "(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)"),
("F", "truncateHistory", "(Landroid/content/ContentResolver;)"),
("F", "updateVisitedHistory", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"),
],
},
"ASEC_DESTROY" : {
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "destroySecureContainer", "(Ljava/lang/String; B)"),
],
},
"ACCESS_NETWORK_STATE" : {
"Landroid/net/ThrottleManager;" : [
("F", "getByteCount", "(Ljava/lang/String; I I I)"),
("F", "getCliffLevel", "(Ljava/lang/String; I)"),
("F", "getCliffThreshold", "(Ljava/lang/String; I)"),
("F", "getHelpUri", "()"),
("F", "getPeriodStartTime", "(Ljava/lang/String;)"),
("F", "getResetTime", "(Ljava/lang/String;)"),
],
"Landroid/net/NetworkInfo;" : [
("F", "isConnectedOrConnecting", "()"),
],
"Landroid/os/INetworkManagementService$Stub$Proxy;" : [
("F", "getDnsForwarders", "()"),
("F", "getInterfaceRxCounter", "(Ljava/lang/String;)"),
("F", "getInterfaceRxThrottle", "(Ljava/lang/String;)"),
("F", "getInterfaceTxCounter", "(Ljava/lang/String;)"),
("F", "getInterfaceTxThrottle", "(Ljava/lang/String;)"),
("F", "getIpForwardingEnabled", "()"),
("F", "isTetheringStarted", "()"),
("F", "isUsbRNDISStarted", "()"),
("F", "listInterfaces", "()"),
("F", "listTetheredInterfaces", "()"),
("F", "listTtys", "()"),
],
"Landroid/net/IConnectivityManager$Stub$Proxy;" : [
("F", "getActiveNetworkInfo", "()"),
("F", "getAllNetworkInfo", "()"),
("F", "getLastTetherError", "(Ljava/lang/String;)"),
("F", "getMobileDataEnabled", "()"),
("F", "getNetworkInfo", "(I)"),
("F", "getNetworkPreference", "()"),
("F", "getTetherableIfaces", "()"),
("F", "getTetherableUsbRegexs", "()"),
("F", "getTetherableWifiRegexs", "()"),
("F", "getTetheredIfaces", "()"),
("F", "getTetheringErroredIfaces", "()"),
("F", "isTetheringSupported", "()"),
("F", "startUsingNetworkFeature", "(I Ljava/lang/String; Landroid/os/IBinder;)"),
],
"Landroid/net/IThrottleManager$Stub$Proxy;" : [
("F", "getByteCount", "(Ljava/lang/String; I I I)"),
("F", "getCliffLevel", "(Ljava/lang/String; I)"),
("F", "getCliffThreshold", "(Ljava/lang/String; I)"),
("F", "getHelpUri", "()"),
("F", "getPeriodStartTime", "(Ljava/lang/String;)"),
("F", "getResetTime", "(Ljava/lang/String;)"),
("F", "getThrottle", "(Ljava/lang/String;)"),
],
"Landroid/net/ConnectivityManager;" : [
("F", "getActiveNetworkInfo", "()"),
("F", "getAllNetworkInfo", "()"),
("F", "getLastTetherError", "(Ljava/lang/String;)"),
("F", "getMobileDataEnabled", "()"),
("F", "getNetworkInfo", "(I)"),
("F", "getNetworkPreference", "()"),
("F", "getTetherableIfaces", "()"),
("F", "getTetherableUsbRegexs", "()"),
("F", "getTetherableWifiRegexs", "()"),
("F", "getTetheredIfaces", "()"),
("F", "getTetheringErroredIfaces", "()"),
("F", "isTetheringSupported", "()"),
],
"Landroid/net/http/RequestQueue;" : [
("F", "enablePlatformNotifications", "()"),
("F", "setProxyConfig", "()"),
],
},
"GET_TASKS" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "getRecentTasks", "(I I)"),
("F", "getTasks", "(I I Landroid/app/IThumbnailReceiver;)"),
],
"Landroid/app/ActivityManagerNative;" : [
("F", "getRecentTasks", "(I I)"),
("F", "getRunningTasks", "(I)"),
],
"Landroid/app/ActivityManager;" : [
("F", "getRecentTasks", "(I I)"),
("F", "getRunningTasks", "(I)"),
("F", "getRecentTasks", "(I I)"),
("F", "getRunningTasks", "(I)"),
],
},
"STATUS_BAR" : {
"Landroid/view/View/OnSystemUiVisibilityChangeListener;" : [
("F", "onSystemUiVisibilityChange", "(I)"),
],
"Landroid/view/View;" : [
("C", "STATUS_BAR_HIDDEN", "I"),
("C", "STATUS_BAR_VISIBLE", "I"),
],
"Landroid/app/StatusBarManager;" : [
("F", "addIcon", "(Ljava/lang/String; I I)"),
("F", "disable", "(I)"),
("F", "removeIcon", "(Landroid/os/IBinder;)"),
("F", "updateIcon", "(Landroid/os/IBinder; Ljava/lang/String; I I)"),
],
"Landroid/view/WindowManager/LayoutParams;" : [
("C", "TYPE_STATUS_BAR", "I"),
("C", "TYPE_STATUS_BAR_PANEL", "I"),
("C", "systemUiVisibility", "I"),
("C", "type", "I"),
],
"Landroid/app/IStatusBar$Stub$Proxy;" : [
("F", "addIcon", "(Ljava/lang/String; Ljava/lang/String; I I)"),
("F", "disable", "(I Landroid/os/IBinder; Ljava/lang/String;)"),
("F", "removeIcon", "(Landroid/os/IBinder;)"),
("F", "updateIcon", "(Landroid/os/IBinder; Ljava/lang/String; Ljava/lang/String; I I)"),
],
},
"SHUTDOWN" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "shutdown", "(I)"),
],
"Landroid/os/IMountService$Stub$Proxy;" : [
("F", "shutdow", "()"),
],
"Landroid/os/storage/IMountService$Stub$Proxy;" : [
("F", "shutdown", "(Landroid/os/storage/IMountShutdownObserver;)"),
],
"Landroid/os/INetworkManagementService$Stub$Proxy;" : [
("F", "shutdown", "()"),
],
},
"READ_LOGS" : {
"Landroid/os/DropBoxManager;" : [
("C", "ACTION_DROPBOX_ENTRY_ADDED", "Ljava/lang/String;"),
("F", "getNextEntry", "(Ljava/lang/String; J)"),
("F", "getNextEntry", "(Ljava/lang/String; J)"),
],
"Lcom/android/internal/os/IDropBoxManagerService$Stub$Proxy;" : [
("F", "getNextEntry", "(Ljava/lang/String; J)"),
],
"Ljava/lang/Runtime;" : [
("F", "exec", "(Ljava/lang/String;)"),
("F", "exec", "([Ljava/lang/String;)"),
("F", "exec", "([Ljava/lang/String; [Ljava/lang/String;)"),
("F", "exec", "([Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)"),
("F", "exec", "(Ljava/lang/String; [Ljava/lang/String;)"),
("F", "exec", "(Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)"),
],
},
"BLUETOOTH" : {
"Landroid/os/Process;" : [
("C", "BLUETOOTH_GID", "I"),
],
"Landroid/bluetooth/BluetoothA2dp;" : [
("C", "ACTION_CONNECTION_STATE_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_PLAYING_STATE_CHANGED", "Ljava/lang/String;"),
("F", "getConnectedDevices", "()"),
("F", "getConnectionState", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getDevicesMatchingConnectionStates", "([I)"),
("F", "isA2dpPlaying", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getConnectedSinks", "()"),
("F", "getNonDisconnectedSinks", "()"),
("F", "getSinkPriority", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getSinkState", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "isSinkConnected", "(Landroid/bluetooth/BluetoothDevice;)"),
],
"Landroid/media/AudioManager;" : [
("C", "ROUTE_BLUETOOTH", "I"),
("C", "ROUTE_BLUETOOTH_A2DP", "I"),
("C", "ROUTE_BLUETOOTH_SCO", "I"),
],
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;" : [
("F", "getConnectedSinks", "()"),
("F", "getNonDisconnectedSinks", "()"),
("F", "getSinkPriority", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getSinkState", "(Landroid/bluetooth/BluetoothDevice;)"),
],
"Landroid/bluetooth/BluetoothSocket;" : [
("F", "connect", "()"),
],
"Landroid/bluetooth/BluetoothPbap;" : [
("F", "getClient", "()"),
("F", "getState", "()"),
("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"),
],
"Landroid/provider/Settings/System;" : [
("C", "AIRPLANE_MODE_RADIOS", "Ljava/lang/String;"),
("C", "BLUETOOTH_DISCOVERABILITY", "Ljava/lang/String;"),
("C", "BLUETOOTH_DISCOVERABILITY_TIMEOUT", "Ljava/lang/String;"),
("C", "BLUETOOTH_ON", "Ljava/lang/String;"),
("C", "RADIO_BLUETOOTH", "Ljava/lang/String;"),
("C", "VOLUME_BLUETOOTH_SCO", "Ljava/lang/String;"),
],
"Landroid/provider/Settings;" : [
("C", "ACTION_BLUETOOTH_SETTINGS", "Ljava/lang/String;"),
],
"Landroid/bluetooth/IBluetooth$Stub$Proxy;" : [
("F", "addRfcommServiceRecord", "(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)"),
("F", "fetchRemoteUuids", "(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)"),
("F", "getAddress", "()"),
("F", "getBluetoothState", "()"),
("F", "getBondState", "(Ljava/lang/String;)"),
("F", "getDiscoverableTimeout", "()"),
("F", "getName", "()"),
("F", "getRemoteClass", "(Ljava/lang/String;)"),
("F", "getRemoteName", "(Ljava/lang/String;)"),
("F", "getRemoteServiceChannel", "(Ljava/lang/String; Landroid/os/ParcelUuid;)"),
("F", "getRemoteUuids", "(Ljava/lang/String;)"),
("F", "getScanMode", "()"),
("F", "getTrustState", "(Ljava/lang/String;)"),
("F", "isDiscovering", "()"),
("F", "isEnabled", "()"),
("F", "listBonds", "()"),
("F", "removeServiceRecord", "(I)"),
],
"Landroid/bluetooth/BluetoothAdapter;" : [
("C", "ACTION_CONNECTION_STATE_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_DISCOVERY_FINISHED", "Ljava/lang/String;"),
("C", "ACTION_DISCOVERY_STARTED", "Ljava/lang/String;"),
("C", "ACTION_LOCAL_NAME_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_REQUEST_DISCOVERABLE", "Ljava/lang/String;"),
("C", "ACTION_REQUEST_ENABLE", "Ljava/lang/String;"),
("C", "ACTION_SCAN_MODE_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_STATE_CHANGED", "Ljava/lang/String;"),
("F", "cancelDiscovery", "()"),
("F", "disable", "()"),
("F", "enable", "()"),
("F", "getAddress", "()"),
("F", "getBondedDevices", "()"),
("F", "getName", "()"),
("F", "getScanMode", "()"),
("F", "getState", "()"),
("F", "isDiscovering", "()"),
("F", "isEnabled", "()"),
("F", "listenUsingInsecureRfcommWithServiceRecord", "(Ljava/lang/String; Ljava/util/UUID;)"),
("F", "listenUsingRfcommWithServiceRecord", "(Ljava/lang/String; Ljava/util/UUID;)"),
("F", "setName", "(Ljava/lang/String;)"),
("F", "startDiscovery", "()"),
("F", "getAddress", "()"),
("F", "getBondedDevices", "()"),
("F", "getDiscoverableTimeout", "()"),
("F", "getName", "()"),
("F", "getScanMode", "()"),
("F", "getState", "()"),
("F", "isDiscovering", "()"),
("F", "isEnabled", "()"),
("F", "listenUsingRfcommWithServiceRecord", "(Ljava/lang/String; Ljava/util/UUID;)"),
],
"Landroid/bluetooth/BluetoothProfile;" : [
("F", "getConnectedDevices", "()"),
("F", "getConnectionState", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getDevicesMatchingConnectionStates", "([I)"),
],
"Landroid/bluetooth/BluetoothHeadset;" : [
("C", "ACTION_AUDIO_STATE_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_CONNECTION_STATE_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_VENDOR_SPECIFIC_HEADSET_EVENT", "Ljava/lang/String;"),
("F", "getConnectedDevices", "()"),
("F", "getConnectionState", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getDevicesMatchingConnectionStates", "([I)"),
("F", "isAudioConnected", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "startVoiceRecognition", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "stopVoiceRecognition", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getBatteryUsageHint", "()"),
("F", "getCurrentHeadset", "()"),
("F", "getPriority", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getState", "()"),
("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "startVoiceRecognition", "()"),
("F", "stopVoiceRecognition", "()"),
],
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;" : [
("F", "getBatteryUsageHint", "()"),
("F", "getCurrentHeadset", "()"),
("F", "getPriority", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getState", "()"),
("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "startVoiceRecognition", "()"),
("F", "stopVoiceRecognition", "()"),
],
"Landroid/bluetooth/BluetoothDevice;" : [
("C", "ACTION_ACL_CONNECTED", "Ljava/lang/String;"),
("C", "ACTION_ACL_DISCONNECTED", "Ljava/lang/String;"),
("C", "ACTION_ACL_DISCONNECT_REQUESTED", "Ljava/lang/String;"),
("C", "ACTION_BOND_STATE_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_CLASS_CHANGED", "Ljava/lang/String;"),
("C", "ACTION_FOUND", "Ljava/lang/String;"),
("C", "ACTION_NAME_CHANGED", "Ljava/lang/String;"),
("F", "createInsecureRfcommSocketToServiceRecord", "(Ljava/util/UUID;)"),
("F", "createRfcommSocketToServiceRecord", "(Ljava/util/UUID;)"),
("F", "getBluetoothClass", "()"),
("F", "getBondState", "()"),
("F", "getName", "()"),
("F", "createRfcommSocketToServiceRecord", "(Ljava/util/UUID;)"),
("F", "fetchUuidsWithSdp", "()"),
("F", "getBondState", "()"),
("F", "getName", "()"),
("F", "getServiceChannel", "(Landroid/os/ParcelUuid;)"),
("F", "getUuids", "()"),
],
"Landroid/server/BluetoothA2dpService;" : [
("F", "<init>", "(Landroid/content/Context; Landroid/server/BluetoothService;)"),
("F", "addAudioSink", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getConnectedSinks", "()"),
("F", "getNonDisconnectedSinks", "()"),
("F", "getSinkPriority", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "getSinkState", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "isSinkDevice", "(Landroid/bluetooth/BluetoothDevice;)"),
("F", "lookupSinksMatchingStates", "([I)"),
("F", "onConnectSinkResult", "(Ljava/lang/String; B)"),
("F", "onSinkPropertyChanged", "(Ljava/lang/String; [L[Ljava/lang/Strin;)"),
],
"Landroid/provider/Settings/Secure;" : [
("C", "BLUETOOTH_ON", "Ljava/lang/String;"),
],
"Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;" : [
("F", "getClient", "()"),
("F", "getState", "()"),
("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"),
],
"Landroid/server/BluetoothService;" : [
("F", "addRemoteDeviceProperties", "(Ljava/lang/String; [L[Ljava/lang/Strin;)"),
("F", "addRfcommServiceRecord", "(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)"),
("F", "fetchRemoteUuids", "(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)"),
("F", "getAddress", "()"),
("F", "getAddressFromObjectPath", "(Ljava/lang/String;)"),
("F", "getAllProperties", "()"),
("F", "getBluetoothState", "()"),
("F", "getBondState", "(Ljava/lang/String;)"),
("F", "getDiscoverableTimeout", "()"),
("F", "getName", "()"),
("F", "getObjectPathFromAddress", "(Ljava/lang/String;)"),
("F", "getProperty", "(Ljava/lang/String;)"),
("F", "getPropertyInternal", "(Ljava/lang/String;)"),
("F", "getRemoteClass", "(Ljava/lang/String;)"),
("F", "getRemoteName", "(Ljava/lang/String;)"),
("F", "getRemoteServiceChannel", "(Ljava/lang/String; Landroid/os/ParcelUuid;)"),
("F", "getRemoteUuids", "(Ljava/lang/String;)"),
("F", "getScanMode", "()"),
("F", "getTrustState", "(Ljava/lang/String;)"),
("F", "isDiscovering", "()"),
("F", "isEnabled", "()"),
("F", "listBonds", "()"),
("F", "removeServiceRecord", "(I)"),
("F", "sendUuidIntent", "(Ljava/lang/String;)"),
("F", "setLinkTimeout", "(Ljava/lang/String; I)"),
("F", "setPropertyBoolean", "(Ljava/lang/String; B)"),
("F", "setPropertyInteger", "(Ljava/lang/String; I)"),
("F", "setPropertyString", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "updateDeviceServiceChannelCache", "(Ljava/lang/String;)"),
("F", "updateRemoteDevicePropertiesCache", "(Ljava/lang/String;)"),
],
"Landroid/content/pm/PackageManager;" : [
("C", "FEATURE_BLUETOOTH", "Ljava/lang/String;"),
],
"Landroid/bluetooth/BluetoothAssignedNumbers;" : [
("C", "BLUETOOTH_SIG", "I"),
],
},
"CLEAR_APP_USER_DATA" : {
"Landroid/app/ActivityManagerNative;" : [
("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"),
],
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "clearApplicationUserData", "(Ljava/lang/String; LIPackageDataObserver;)"),
("F", "clearApplicationUserData", "(Ljava/lang/String; LIPackageDataObserver;)"),
],
"Landroid/app/ActivityManager;" : [
("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"),
],
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "clearApplicationUserData", "(Ljava/lang/String; LIPackageDataObserver;)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"),
],
},
"WRITE_SMS" : {
"Landroid/provider/Telephony$Sms;" : [
("F", "addMessageToUri", "(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B J)"),
("F", "addMessageToUri", "(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B)"),
("F", "moveMessageToFolder", "(Landroid/content/Context; Landroid/net/Uri; I I)"),
],
"Landroid/provider/Telephony$Sms$Outbox;" : [
("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B J)"),
],
"Landroid/provider/Telephony$Sms$Draft;" : [
("F", "saveMessage", "(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String;)"),
],
},
"SET_PROCESS_LIMIT" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "setProcessForeground", "(Landroid/os/IBinder; I B)"),
("F", "setProcessLimit", "(I)"),
],
},
"DEVICE_POWER" : {
"Landroid/os/PowerManager;" : [
("F", "goToSleep", "(J)"),
("F", "setBacklightBrightness", "(I)"),
],
"Landroid/os/IPowerManager$Stub$Proxy;" : [
("F", "clearUserActivityTimeout", "(J J)"),
("F", "goToSleep", "(J)"),
("F", "goToSleepWithReason", "(J I)"),
("F", "preventScreenOn", "(B)"),
("F", "setAttentionLight", "(B I)"),
("F", "setBacklightBrightness", "(I)"),
("F", "setPokeLock", "(I Landroid/os/IBinder; Ljava/lang/String;)"),
("F", "userActivityWithForce", "(J B B)"),
],
},
"PERSISTENT_ACTIVITY" : {
"Landroid/app/ExpandableListActivity;" : [
("F", "setPersistent", "(B)"),
],
"Landroid/accounts/GrantCredentialsPermissionActivity;" : [
("F", "setPersistent", "(B)"),
],
"Landroid/app/Activity;" : [
("F", "setPersistent", "(B)"),
],
"Landroid/app/ListActivity;" : [
("F", "setPersistent", "(B)"),
],
"Landroid/app/AliasActivity;" : [
("F", "setPersistent", "(B)"),
],
"Landroid/accounts/AccountAuthenticatorActivity;" : [
("F", "setPersistent", "(B)"),
],
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "setPersistent", "(Landroid/os/IBinder; B)"),
],
"Landroid/app/TabActivity;" : [
("F", "setPersistent", "(B)"),
],
"Landroid/app/ActivityGroup;" : [
("F", "setPersistent", "(B)"),
],
},
"MANAGE_APP_TOKENS" : {
"Landroid/view/IWindowManager$Stub$Proxy;" : [
("F", "addAppToken", "(I Landroid/view/IApplicationToken; I I B)"),
("F", "addWindowToken", "(Landroid/os/IBinder; I)"),
("F", "executeAppTransition", "()"),
("F", "moveAppToken", "(I Landroid/os/IBinder;)"),
("F", "moveAppTokensToBottom", "(Ljava/util/List;)"),
("F", "moveAppTokensToTop", "(Ljava/util/List;)"),
("F", "pauseKeyDispatching", "(Landroid/os/IBinder;)"),
("F", "prepareAppTransition", "(I)"),
("F", "removeAppToken", "(Landroid/os/IBinder;)"),
("F", "removeWindowToken", "(Landroid/os/IBinder;)"),
("F", "resumeKeyDispatching", "(Landroid/os/IBinder;)"),
("F", "setAppGroupId", "(Landroid/os/IBinder; I)"),
("F", "setAppOrientation", "(Landroid/view/IApplicationToken; I)"),
("F", "setAppStartingWindow", "(Landroid/os/IBinder; Ljava/lang/String; I Ljava/lang/CharSequence; I I Landroid/os/IBinder; B)"),
("F", "setAppVisibility", "(Landroid/os/IBinder; B)"),
("F", "setAppWillBeHidden", "(Landroid/os/IBinder;)"),
("F", "setEventDispatching", "(B)"),
("F", "setFocusedApp", "(Landroid/os/IBinder; B)"),
("F", "setNewConfiguration", "(Landroid/content/res/Configuration;)"),
("F", "startAppFreezingScreen", "(Landroid/os/IBinder; I)"),
("F", "stopAppFreezingScreen", "(Landroid/os/IBinder; B)"),
("F", "updateOrientationFromAppTokens", "(Landroid/content/res/Configuration; Landroid/os/IBinder;)"),
],
},
"WRITE_HISTORY_BOOKMARKS" : {
"Landroid/provider/Browser;" : [
("C", "BOOKMARKS_URI", "Landroid/net/Uri;"),
("C", "SEARCHES_URI", "Landroid/net/Uri;"),
("F", "addSearchUrl", "(Landroid/content/ContentResolver; Ljava/lang/String;)"),
("F", "clearHistory", "(Landroid/content/ContentResolver;)"),
("F", "clearSearches", "(Landroid/content/ContentResolver;)"),
("F", "deleteFromHistory", "(Landroid/content/ContentResolver; Ljava/lang/String;)"),
("F", "deleteHistoryTimeFrame", "(Landroid/content/ContentResolver; J J)"),
("F", "truncateHistory", "(Landroid/content/ContentResolver;)"),
("F", "updateVisitedHistory", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"),
("F", "clearSearches", "(Landroid/content/ContentResolver;)"),
],
},
"FORCE_BACK" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "unhandledBack", "(I)"),
],
},
"CHANGE_NETWORK_STATE" : {
"Landroid/net/IConnectivityManager$Stub$Proxy;" : [
("F", "requestRouteToHost", "(I I)"),
("F", "setMobileDataEnabled", "(B)"),
("F", "setNetworkPreference", "(I)"),
("F", "setRadio", "(I B)"),
("F", "setRadios", "(B)"),
("F", "stopUsingNetworkFeature", "(I Ljava/lang/String;)"),
("F", "tether", "(Ljava/lang/String;)"),
("F", "untether", "(Ljava/lang/String;)"),
],
"Landroid/net/ConnectivityManager;" : [
("F", "requestRouteToHost", "(I I)"),
("F", "setMobileDataEnabled", "(B)"),
("F", "setNetworkPreference", "(I)"),
("F", "setRadio", "(I B)"),
("F", "setRadios", "(B)"),
("F", "startUsingNetworkFeature", "(I Ljava/lang/String;)"),
("F", "stopUsingNetworkFeature", "(I Ljava/lang/String;)"),
("F", "tether", "(Ljava/lang/String;)"),
("F", "untether", "(Ljava/lang/String;)"),
],
"Landroid/os/INetworkManagementService$Stub$Proxy;" : [
("F", "attachPppd", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"),
("F", "detachPppd", "(Ljava/lang/String;)"),
("F", "disableNat", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "enableNat", "(Ljava/lang/String; Ljava/lang/String;)"),
("F", "setAccessPoint", "(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)"),
("F", "setInterfaceThrottle", "(Ljava/lang/String; I I)"),
("F", "setIpForwardingEnabled", "(B)"),
("F", "startAccessPoint", "(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)"),
("F", "startUsbRNDIS", "()"),
("F", "stopAccessPoint", "()"),
("F", "stopTethering", "()"),
("F", "stopUsbRNDIS", "()"),
("F", "tetherInterface", "(Ljava/lang/String;)"),
("F", "unregisterObserver", "(Landroid/net/INetworkManagementEventObserver;)"),
("F", "untetherInterface", "(Ljava/lang/String;)"),
],
},
"WRITE_SYNC_SETTINGS" : {
"Landroid/app/ContextImpl$ApplicationContentResolver;" : [
("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"),
("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"),
("F", "setMasterSyncAutomatically", "(B)"),
("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"),
],
"Landroid/content/ContentService;" : [
("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"),
("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"),
("F", "setMasterSyncAutomatically", "(B)"),
("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"),
],
"Landroid/content/ContentResolver;" : [
("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"),
("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"),
("F", "setMasterSyncAutomatically", "(B)"),
("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"),
],
"Landroid/content/IContentService$Stub$Proxy;" : [
("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"),
("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"),
("F", "setMasterSyncAutomatically", "(B)"),
("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"),
],
},
"ACCOUNT_MANAGER" : {
"Landroid/accounts/AccountManager;" : [
("C", "KEY_ACCOUNT_MANAGER_RESPONSE", "Ljava/lang/String;"),
],
"Landroid/accounts/AbstractAccountAuthenticator;" : [
("F", "checkBinderPermission", "()"),
("F", "confirmCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)"),
("F", "editProperties", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"),
("F", "getAccountRemovalAllowed", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)"),
("F", "getAuthToken", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "getAuthTokenLabel", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"),
("F", "hasFeatures", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"),
("F", "updateCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "addAccount", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)"),
],
"Landroid/accounts/AbstractAccountAuthenticator$Transport;" : [
("F", "addAccount", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)"),
("F", "confirmCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)"),
("F", "editProperties", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"),
("F", "getAccountRemovalAllowed", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)"),
("F", "getAuthToken", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "getAuthTokenLabel", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"),
("F", "hasFeatures", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"),
("F", "updateCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
],
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;" : [
("F", "addAccount", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)"),
("F", "confirmCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)"),
("F", "editProperties", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"),
("F", "getAccountRemovalAllowed", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)"),
("F", "getAuthToken", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
("F", "getAuthTokenLabel", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"),
("F", "hasFeatures", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"),
("F", "updateCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"),
],
},
"SET_ANIMATION_SCALE" : {
"Landroid/view/IWindowManager$Stub$Proxy;" : [
("F", "setAnimationScale", "(I F)"),
("F", "setAnimationScales", "([L;)"),
],
},
"GET_ACCOUNTS" : {
"Landroid/accounts/AccountManager;" : [
("F", "getAccounts", "()"),
("F", "getAccountsByType", "(Ljava/lang/String;)"),
("F", "getAccountsByTypeAndFeatures", "(Ljava/lang/String; [Ljava/lang/String; [Landroid/accounts/AccountManagerCallback<android/accounts/Account[; Landroid/os/Handler;)"),
("F", "hasFeatures", "(Landroid/accounts/Account; [Ljava/lang/String; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)"),
("F", "addOnAccountsUpdatedListener", "(Landroid/accounts/OnAccountsUpdateListener; Landroid/os/Handler; B)"),
("F", "getAccounts", "()"),
("F", "getAccountsByType", "(Ljava/lang/String;)"),
("F", "getAccountsByTypeAndFeatures", "(Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
("F", "getAuthTokenByFeatures", "(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
("F", "hasFeatures", "(Landroid/accounts/Account; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"),
],
"Landroid/content/ContentService;" : [
("F", "<init>", "(Landroid/content/Context; B)"),
("F", "main", "(Landroid/content/Context; B)"),
],
"Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;" : [
("F", "doWork", "()"),
("F", "start", "()"),
],
"Landroid/accounts/AccountManager$AmsTask;" : [
("F", "doWork", "()"),
("F", "start", "()"),
],
"Landroid/accounts/IAccountManager$Stub$Proxy;" : [
("F", "getAccounts", "(Ljava/lang/String;)"),
("F", "getAccountsByFeatures", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)"),
("F", "hasFeatures", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"),
],
"Landroid/accounts/AccountManagerService;" : [
("F", "checkReadAccountsPermission", "()"),
("F", "getAccounts", "(Ljava/lang/String;)"),
("F", "getAccountsByFeatures", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)"),
("F", "hasFeatures", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"),
],
},
"RECEIVE_SMS" : {
"Landroid/telephony/gsm/SmsManager;" : [
("F", "copyMessageToSim", "([L; [L; I)"),
("F", "deleteMessageFromSim", "(I)"),
("F", "getAllMessagesFromSim", "()"),
("F", "updateMessageOnSim", "(I I [L;)"),
],
"Landroid/telephony/SmsManager;" : [
("F", "copyMessageToIcc", "([L; [L; I)"),
("F", "deleteMessageFromIcc", "(I)"),
("F", "getAllMessagesFromIcc", "()"),
("F", "updateMessageOnIcc", "(I I [L;)"),
],
"Lcom/android/internal/telephony/ISms$Stub$Proxy;" : [
("F", "copyMessageToIccEf", "(I [B [B)"),
("F", "getAllMessagesFromIccEf", "()"),
("F", "updateMessageOnIccEf", "(I I [B)"),
],
},
"STOP_APP_SWITCHES" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "resumeAppSwitches", "()"),
("F", "stopAppSwitches", "()"),
],
},
"DELETE_CACHE_FILES" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; LIPackageDataObserver;)"),
("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"),
],
},
"WRITE_EXTERNAL_STORAGE" : {
"Landroid/os/Build/VERSION_CODES;" : [
("C", "DONUT", "I"),
],
"Landroid/app/DownloadManager/Request;" : [
("F", "setDestinationUri", "(Landroid/net/Uri;)"),
],
},
"REBOOT" : {
"Landroid/os/RecoverySystem;" : [
("F", "installPackage", "(Landroid/content/Context; Ljava/io/File;)"),
("F", "rebootWipeUserData", "(Landroid/content/Context;)"),
("F", "bootCommand", "(Landroid/content/Context; Ljava/lang/String;)"),
("F", "installPackage", "(Landroid/content/Context; Ljava/io/File;)"),
("F", "rebootWipeUserData", "(Landroid/content/Context;)"),
],
"Landroid/content/Intent;" : [
("C", "IntentResolution", "Ljava/lang/String;"),
("C", "ACTION_REBOOT", "Ljava/lang/String;"),
],
"Landroid/os/PowerManager;" : [
("F", "reboot", "(Ljava/lang/String;)"),
("F", "reboot", "(Ljava/lang/String;)"),
],
"Landroid/os/IPowerManager$Stub$Proxy;" : [
("F", "crash", "(Ljava/lang/String;)"),
("F", "reboot", "(Ljava/lang/String;)"),
],
},
"INSTALL_PACKAGES" : {
"Landroid/app/ContextImpl$ApplicationPackageManager;" : [
("F", "installPackage", "(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)"),
("F", "installPackage", "(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)"),
],
"Landroid/content/pm/PackageManager;" : [
("F", "installPackage", "(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)"),
],
"Landroid/content/pm/IPackageManager$Stub$Proxy;" : [
("F", "installPackage", "(Landroid/net/Uri; Landroid/content/pm/IPackageInstallObserver; I Ljava/lang/String;)"),
],
},
"SET_DEBUG_APP" : {
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "setDebugApp", "(Ljava/lang/String; B B)"),
],
},
"INSTALL_LOCATION_PROVIDER" : {
"Landroid/location/ILocationManager$Stub$Proxy;" : [
("F", "reportLocation", "(Landroid/location/Location; B)"),
],
},
"SET_WALLPAPER_HINTS" : {
"Landroid/app/WallpaperManager;" : [
("F", "suggestDesiredDimensions", "(I I)"),
],
"Landroid/app/IWallpaperManager$Stub$Proxy;" : [
("F", "setDimensionHints", "(I I)"),
],
},
"READ_CONTACTS" : {
"Landroid/app/ContextImpl$ApplicationContentResolver;" : [
("F", "openFileDescriptor", "(Landroid/net/Uri; Ljava/lang/String;)"),
("F", "openInputStream", "(Landroid/net/Uri;)"),
("F", "openOutputStream", "(Landroid/net/Uri;)"),
("F", "query", "(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)"),
],
"Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;" : [
("F", "getAdnRecordsInEf", "(I)"),
],
"Landroid/provider/Contacts$People;" : [
("F", "addToGroup", "(Landroid/content/ContentResolver; J Ljava/lang/String;)"),
("F", "addToMyContactsGroup", "(Landroid/content/ContentResolver; J)"),
("F", "createPersonInMyContactsGroup", "(Landroid/content/ContentResolver; Landroid/content/ContentValues;)"),
("F", "loadContactPhoto", "(Landroid/content/Context; Landroid/net/Uri; I Landroid/graphics/BitmapFactory$Options;)"),
("F", "markAsContacted", "(Landroid/content/ContentResolver; J)"),
("F", "openContactPhotoInputStream", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"),
("F", "queryGroups", "(Landroid/content/ContentResolver; J)"),
("F", "setPhotoData", "(Landroid/content/ContentResolver; Landroid/net/Uri; [L;)"),
("F", "tryGetMyContactsGroupId", "(Landroid/content/ContentResolver;)"),
],
"Landroid/provider/ContactsContract$Data;" : [
("F", "getContactLookupUri", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"),
],
"Landroid/provider/ContactsContract$Contacts;" : [
("F", "getLookupUri", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"),
("F", "lookupContact", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"),
("F", "openContactPhotoInputStream", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"),
],
"Landroid/pim/vcard/VCardComposer;" : [
("F", "createOneEntry", "()"),
("F", "createOneEntry", "(Ljava/lang/reflect/Method;)"),
("F", "createOneEntryInternal", "(Ljava/lang/String; Ljava/lang/reflect/Method;)"),
("F", "init", "()"),
("F", "init", "(Ljava/lang/String; [L[Ljava/lang/Strin;)"),
],
"Landroid/pim/vcard/VCardComposer$OneEntryHandler;" : [
("F", "onInit", "(Landroid/content/Context;)"),
],
"Lcom/android/internal/telephony/CallerInfo;" : [
("F", "getCallerId", "(Landroid/content/Context; Ljava/lang/String;)"),
("F", "getCallerInfo", "(Landroid/content/Context; Ljava/lang/String;)"),
],
"Landroid/provider/Contacts$Settings;" : [
("F", "getSetting", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)"),
],
"Landroid/provider/ContactsContract$RawContacts;" : [
("F", "getContactLookupUri", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"),
],
"Landroid/provider/CallLog$Calls;" : [
("F", "addCall", "(Lcom/android/internal/telephony/CallerInfo; Landroid/content/Context; Ljava/lang/String; I I J I)"),
("F", "getLastOutgoingCall", "(Landroid/content/Context;)"),
],
"Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;" : [
("F", "getAdnRecordsInEf", "(I)"),
],
"Landroid/pim/vcard/VCardComposer$HandlerForOutputStream;" : [
("F", "onInit", "(Landroid/content/Context;)"),
],
"Landroid/provider/ContactsContract$CommonDataKinds$Phone;" : [
("C", "CONTENT_URI", "Landroid/net/Uri;"),
],
"Landroid/widget/QuickContactBadge;" : [
("F", "assignContactFromEmail", "(Ljava/lang/String; B)"),
("F", "assignContactFromPhone", "(Ljava/lang/String; B)"),
("F", "trigger", "(Landroid/net/Uri;)"),
],
"Landroid/content/ContentResolver;" : [
("F", "openFileDescriptor", "(Landroid/net/Uri; Ljava/lang/String;)"),
("F", "openInputStream", "(Landroid/net/Uri;)"),
("F", "openOutputStream", "(Landroid/net/Uri;)"),
("F", "query", "(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)"),
],
},
"BACKUP" : {
"Landroid/app/backup/IBackupManager$Stub$Proxy;" : [
("F", "backupNow", "()"),
("F", "beginRestoreSession", "(Ljava/lang/String;)"),
("F", "clearBackupData", "(Ljava/lang/String;)"),
("F", "dataChanged", "(Ljava/lang/String;)"),
("F", "getCurrentTransport", "()"),
("F", "isBackupEnabled", "()"),
("F", "listAllTransports", "()"),
("F", "selectBackupTransport", "(Ljava/lang/String;)"),
("F", "setAutoRestore", "(B)"),
("F", "setBackupEnabled", "(B)"),
],
"Landroid/app/IActivityManager$Stub$Proxy;" : [
("F", "bindBackupAgent", "(Landroid/content/pm/ApplicationInfo; I)"),
],
"Landroid/app/backup/BackupManager;" : [
("F", "beginRestoreSession", "()"),
("F", "dataChanged", "(Ljava/lang/String;)"),
("F", "requestRestore", "(Landroid/app/backup/RestoreObserver;)"),
],
},
}
DVM_PERMISSIONS_BY_ELEMENT = {
"Landroid/app/admin/DeviceAdminReceiver;-ACTION_DEVICE_ADMIN_ENABLED-Ljava/lang/String;" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/DevicePolicyManager;-getRemoveWarning-(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/DevicePolicyManager;-reportFailedPasswordAttempt-()" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/DevicePolicyManager;-reportSuccessfulPasswordAttempt-()" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/DevicePolicyManager;-setActiveAdmin-(Landroid/content/ComponentName;)" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/DevicePolicyManager;-setActivePasswordState-(I I)" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-getRemoveWarning-(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-reportFailedPasswordAttempt-()" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-reportSuccessfulPasswordAttempt-()" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-setActiveAdmin-(Landroid/content/ComponentName;)" : "BIND_DEVICE_ADMIN",
"Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-setActivePasswordState-(I I)" : "BIND_DEVICE_ADMIN",
"Landroid/app/ContextImpl$ApplicationContentResolver;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentService;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentService;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentService;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentService;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS",
"Landroid/content/pm/ApplicationInfo;-FLAG_FACTORY_TEST-I" : "FACTORY_TEST",
"Landroid/content/pm/ApplicationInfo;-flags-I" : "FACTORY_TEST",
"Landroid/content/Intent;-IntentResolution-Ljava/lang/String;" : "FACTORY_TEST",
"Landroid/content/Intent;-ACTION_FACTORY_TEST-Ljava/lang/String;" : "FACTORY_TEST",
"Landroid/app/IActivityManager$Stub$Proxy;-setAlwaysFinish-(B)" : "SET_ALWAYS_FINISH",
"Landroid/provider/Calendar$CalendarAlerts;-alarmExists-(Landroid/content/ContentResolver; J J J)" : "READ_CALENDAR",
"Landroid/provider/Calendar$CalendarAlerts;-findNextAlarmTime-(Landroid/content/ContentResolver; J)" : "READ_CALENDAR",
"Landroid/provider/Calendar$CalendarAlerts;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)" : "READ_CALENDAR",
"Landroid/provider/Calendar$Calendars;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_CALENDAR",
"Landroid/provider/Calendar$Events;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_CALENDAR",
"Landroid/provider/Calendar$Events;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)" : "READ_CALENDAR",
"Landroid/provider/Calendar$Instances;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J Ljava/lang/String; Ljava/lang/String;)" : "READ_CALENDAR",
"Landroid/provider/Calendar$Instances;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J)" : "READ_CALENDAR",
"Landroid/provider/Calendar$EventDays;-query-(Landroid/content/ContentResolver; I I)" : "READ_CALENDAR",
"Landroid/provider/DrmStore;-enforceAccessDrmPermission-(Landroid/content/Context;)" : "ACCESS_DRM",
"Landroid/app/IActivityManager$Stub$Proxy;-updateConfiguration-(Landroid/content/res/Configuration;)" : "CHANGE_CONFIGURATION",
"Landroid/app/IActivityManager$Stub$Proxy;-profileControl-(Ljava/lang/String; B Ljava/lang/String; Landroid/os/ParcelFileDescriptor;)" : "SET_ACTIVITY_WATCHER",
"Landroid/app/IActivityManager$Stub$Proxy;-setActivityController-(Landroid/app/IActivityController;)" : "SET_ACTIVITY_WATCHER",
"Landroid/app/ContextImpl$ApplicationPackageManager;-getPackageSizeInfo-(Ljava/lang/String; LIPackageStatsObserver;)" : "GET_PACKAGE_SIZE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-getPackageSizeInfo-(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)" : "GET_PACKAGE_SIZE",
"Landroid/content/pm/PackageManager;-getPackageSizeInfo-(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)" : "GET_PACKAGE_SIZE",
"Landroid/telephony/TelephonyManager;-disableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES",
"Landroid/telephony/TelephonyManager;-enableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-disableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-enableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES",
"Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorage-(J LIntentSender;)" : "CLEAR_APP_CACHE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorageAndNotify-(J LIPackageDataObserver;)" : "CLEAR_APP_CACHE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorage-(J Landroid/content/IntentSender;)" : "CLEAR_APP_CACHE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorageAndNotify-(J Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_CACHE",
"Landroid/content/pm/PackageManager;-freeStorage-(J Landroid/content/IntentSender;)" : "CLEAR_APP_CACHE",
"Landroid/content/pm/PackageManager;-freeStorageAndNotify-(J Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_CACHE",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-freeStorage-(J Landroid/content/IntentSender;)" : "CLEAR_APP_CACHE",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-freeStorageAndNotify-(J Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_CACHE",
"Landroid/view/inputmethod/InputMethod;-SERVICE_INTERFACE-Ljava/lang/String;" : "BIND_INPUT_METHOD",
"Landroid/app/IActivityManager$Stub$Proxy;-signalPersistentProcesses-(I)" : "SIGNAL_PERSISTENT_PROCESSES",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-getAwakeTimeBattery-()" : "BATTERY_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-getAwakeTimePlugged-()" : "BATTERY_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-getStatistics-()" : "BATTERY_STATS",
"Landroid/accounts/AccountManager;-addAccountExplicitly-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-addAccountExplicitly-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManager;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-addAccount-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-checkAuthenticateAccountsPermission-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-addAccount-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS",
"Landroid/net/IConnectivityManager$Stub$Proxy;-setBackgroundDataSetting-(B)" : "CHANGE_BACKGROUND_DATA_SETTING",
"Landroid/net/ConnectivityManager;-setBackgroundDataSetting-(B)" : "CHANGE_BACKGROUND_DATA_SETTING",
"Landroid/app/ActivityManagerNative;-killBackgroundProcesses-(Ljava/lang/String;)" : "RESTART_PACKAGES",
"Landroid/app/ActivityManagerNative;-restartPackage-(Ljava/lang/String;)" : "RESTART_PACKAGES",
"Landroid/app/ActivityManager;-killBackgroundProcesses-(Ljava/lang/String;)" : "RESTART_PACKAGES",
"Landroid/app/ActivityManager;-restartPackage-(Ljava/lang/String;)" : "RESTART_PACKAGES",
"Landroid/telephony/TelephonyManager;-getCompleteVoiceMailNumber-()" : "CALL_PRIVILEGED",
"Landroid/telephony/PhoneNumberUtils;-getNumberFromIntent-(Landroid/content/Intent; Landroid/content/Context;)" : "CALL_PRIVILEGED",
"Landroid/app/IWallpaperManager$Stub$Proxy;-setWallpaperComponent-(Landroid/content/ComponentName;)" : "SET_WALLPAPER_COMPONENT",
"Landroid/view/IWindowManager$Stub$Proxy;-disableKeyguard-(Landroid/os/IBinder; Ljava/lang/String;)" : "DISABLE_KEYGUARD",
"Landroid/view/IWindowManager$Stub$Proxy;-exitKeyguardSecurely-(Landroid/view/IOnKeyguardExitResult;)" : "DISABLE_KEYGUARD",
"Landroid/view/IWindowManager$Stub$Proxy;-reenableKeyguard-(Landroid/os/IBinder;)" : "DISABLE_KEYGUARD",
"Landroid/app/KeyguardManager;-exitKeyguardSecurely-(Landroid/app/KeyguardManager$OnKeyguardExitResult;)" : "DISABLE_KEYGUARD",
"Landroid/app/KeyguardManager$KeyguardLock;-disableKeyguard-()" : "DISABLE_KEYGUARD",
"Landroid/app/KeyguardManager$KeyguardLock;-reenableKeyguard-()" : "DISABLE_KEYGUARD",
"Landroid/app/ContextImpl$ApplicationPackageManager;-deletePackage-(Ljava/lang/String; LIPackageDeleteObserver; I)" : "DELETE_PACKAGES",
"Landroid/app/ContextImpl$ApplicationPackageManager;-deletePackage-(Ljava/lang/String; LIPackageDeleteObserver; I)" : "DELETE_PACKAGES",
"Landroid/content/pm/PackageManager;-deletePackage-(Ljava/lang/String; LIPackageDeleteObserver; I)" : "DELETE_PACKAGES",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-deletePackage-(Ljava/lang/String; Landroid/content/pm/IPackageDeleteObserver; I)" : "DELETE_PACKAGES",
"Landroid/app/ContextImpl$ApplicationPackageManager;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-setComponentEnabledSetting-(LComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-setComponentEnabledSetting-(Landroid/content/ComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/content/pm/PackageManager;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/content/pm/PackageManager;-setComponentEnabledSetting-(Landroid/content/ComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-setComponentEnabledSetting-(Landroid/content/ComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE",
"Landroid/os/storage/IMountService$Stub$Proxy;-getSecureContainerList-()" : "ASEC_ACCESS",
"Landroid/os/storage/IMountService$Stub$Proxy;-getSecureContainerPath-(Ljava/lang/String;)" : "ASEC_ACCESS",
"Landroid/os/storage/IMountService$Stub$Proxy;-isSecureContainerMounted-(Ljava/lang/String;)" : "ASEC_ACCESS",
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;-noteLaunchTime-(LComponentName;)" : "UPDATE_DEVICE_STATS ",
"Landroid/net/sip/SipAudioCall;-startAudio-()" : "RECORD_AUDIO",
"Landroid/media/MediaRecorder;-setAudioSource-(I)" : "RECORD_AUDIO",
"Landroid/speech/SpeechRecognizer;-cancel-()" : "RECORD_AUDIO",
"Landroid/speech/SpeechRecognizer;-handleCancelMessage-()" : "RECORD_AUDIO",
"Landroid/speech/SpeechRecognizer;-handleStartListening-(Landroid/content/Intent;)" : "RECORD_AUDIO",
"Landroid/speech/SpeechRecognizer;-handleStopMessage-()" : "RECORD_AUDIO",
"Landroid/speech/SpeechRecognizer;-startListening-(Landroid/content/Intent;)" : "RECORD_AUDIO",
"Landroid/speech/SpeechRecognizer;-stopListening-()" : "RECORD_AUDIO",
"Landroid/media/AudioRecord;-<init>-(I I I I I)" : "RECORD_AUDIO",
"Landroid/location/LocationManager;-addTestProvider-(Ljava/lang/String; B B B B B B B I I)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-clearTestProviderEnabled-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-clearTestProviderLocation-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-clearTestProviderStatus-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-removeTestProvider-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-setTestProviderEnabled-(Ljava/lang/String; B)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-setTestProviderLocation-(Ljava/lang/String; Landroid/location/Location;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-setTestProviderStatus-(Ljava/lang/String; I Landroid/os/Bundle; J)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-addTestProvider-(Ljava/lang/String; B B B B B B B I I)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-clearTestProviderEnabled-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-clearTestProviderLocation-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-clearTestProviderStatus-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-removeTestProvider-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-setTestProviderEnabled-(Ljava/lang/String; B)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-setTestProviderLocation-(Ljava/lang/String; Landroid/location/Location;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/LocationManager;-setTestProviderStatus-(Ljava/lang/String; I Landroid/os/Bundle; J)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-addTestProvider-(Ljava/lang/String; B B B B B B B I I)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-clearTestProviderEnabled-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-clearTestProviderLocation-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-clearTestProviderStatus-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-removeTestProvider-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-setTestProviderEnabled-(Ljava/lang/String; B)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-setTestProviderLocation-(Ljava/lang/String; Landroid/location/Location;)" : "ACCESS_MOCK_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-setTestProviderStatus-(Ljava/lang/String; I Landroid/os/Bundle; J)" : "ACCESS_MOCK_LOCATION",
"Landroid/media/AudioManager;-EXTRA_RINGER_MODE-Ljava/lang/String;" : "VIBRATE",
"Landroid/media/AudioManager;-EXTRA_VIBRATE_SETTING-Ljava/lang/String;" : "VIBRATE",
"Landroid/media/AudioManager;-EXTRA_VIBRATE_TYPE-Ljava/lang/String;" : "VIBRATE",
"Landroid/media/AudioManager;-FLAG_REMOVE_SOUND_AND_VIBRATE-I" : "VIBRATE",
"Landroid/media/AudioManager;-FLAG_VIBRATE-I" : "VIBRATE",
"Landroid/media/AudioManager;-RINGER_MODE_VIBRATE-I" : "VIBRATE",
"Landroid/media/AudioManager;-VIBRATE_SETTING_CHANGED_ACTION-Ljava/lang/String;" : "VIBRATE",
"Landroid/media/AudioManager;-VIBRATE_SETTING_OFF-I" : "VIBRATE",
"Landroid/media/AudioManager;-VIBRATE_SETTING_ON-I" : "VIBRATE",
"Landroid/media/AudioManager;-VIBRATE_SETTING_ONLY_SILENT-I" : "VIBRATE",
"Landroid/media/AudioManager;-VIBRATE_TYPE_NOTIFICATION-I" : "VIBRATE",
"Landroid/media/AudioManager;-VIBRATE_TYPE_RINGER-I" : "VIBRATE",
"Landroid/media/AudioManager;-getRingerMode-()" : "VIBRATE",
"Landroid/media/AudioManager;-getVibrateSetting-(I)" : "VIBRATE",
"Landroid/media/AudioManager;-setRingerMode-(I)" : "VIBRATE",
"Landroid/media/AudioManager;-setVibrateSetting-(I I)" : "VIBRATE",
"Landroid/media/AudioManager;-shouldVibrate-(I)" : "VIBRATE",
"Landroid/os/Vibrator;-cancel-()" : "VIBRATE",
"Landroid/os/Vibrator;-vibrate-([L; I)" : "VIBRATE",
"Landroid/os/Vibrator;-vibrate-(J)" : "VIBRATE",
"Landroid/provider/Settings/System;-VIBRATE_ON-Ljava/lang/String;" : "VIBRATE",
"Landroid/app/NotificationManager;-notify-(I Landroid/app/Notification;)" : "VIBRATE",
"Landroid/app/NotificationManager;-notify-(Ljava/lang/String; I Landroid/app/Notification;)" : "VIBRATE",
"Landroid/app/Notification/Builder;-setDefaults-(I)" : "VIBRATE",
"Landroid/os/IVibratorService$Stub$Proxy;-cancelVibrate-(Landroid/os/IBinder;)" : "VIBRATE",
"Landroid/os/IVibratorService$Stub$Proxy;-vibrate-(J Landroid/os/IBinder;)" : "VIBRATE",
"Landroid/os/IVibratorService$Stub$Proxy;-vibratePattern-([L; I Landroid/os/IBinder;)" : "VIBRATE",
"Landroid/app/Notification;-DEFAULT_VIBRATE-I" : "VIBRATE",
"Landroid/app/Notification;-defaults-I" : "VIBRATE",
"Landroid/os/storage/IMountService$Stub$Proxy;-createSecureContainer-(Ljava/lang/String; I Ljava/lang/String; Ljava/lang/String; I)" : "ASEC_CREATE",
"Landroid/os/storage/IMountService$Stub$Proxy;-finalizeSecureContainer-(Ljava/lang/String;)" : "ASEC_CREATE",
"Landroid/bluetooth/BluetoothAdapter;-setScanMode-(I I)" : "WRITE_SECURE_SETTINGS",
"Landroid/bluetooth/BluetoothAdapter;-setScanMode-(I)" : "WRITE_SECURE_SETTINGS",
"Landroid/server/BluetoothService;-setScanMode-(I I)" : "WRITE_SECURE_SETTINGS",
"Landroid/os/IPowerManager$Stub$Proxy;-setMaximumScreenOffTimeount-(I)" : "WRITE_SECURE_SETTINGS",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-setInstallLocation-(I)" : "WRITE_SECURE_SETTINGS",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-setScanMode-(I I)" : "WRITE_SECURE_SETTINGS",
"Landroid/view/IWindowManager$Stub$Proxy;-setRotation-(I B I)" : "SET_ORIENTATION",
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;-getAllPkgUsageStats-()" : "PACKAGE_USAGE_STATS",
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;-getPkgUsageStats-(LComponentName;)" : "PACKAGE_USAGE_STATS",
"Landroid/os/IHardwareService$Stub$Proxy;-setFlashlightEnabled-(B)" : "FLASHLIGHT",
"Landroid/app/SearchManager;-EXTRA_SELECT_QUERY-Ljava/lang/String;" : "GLOBAL_SEARCH",
"Landroid/app/SearchManager;-INTENT_ACTION_GLOBAL_SEARCH-Ljava/lang/String;" : "GLOBAL_SEARCH",
"Landroid/server/search/Searchables;-buildSearchableList-()" : "GLOBAL_SEARCH",
"Landroid/server/search/Searchables;-findGlobalSearchActivity-()" : "GLOBAL_SEARCH",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-addOrUpdateNetwork-(Landroid/net/wifi/WifiConfiguration;)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-disableNetwork-(I)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-disconnect-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-enableNetwork-(I B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-pingSupplicant-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-reassociate-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-reconnect-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-removeNetwork-(I)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-saveConfiguration-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-setNumAllowedChannels-(I B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-setWifiApEnabled-(Landroid/net/wifi/WifiConfiguration; B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-setWifiEnabled-(B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-startScan-(B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-addNetwork-(Landroid/net/wifi/WifiConfiguration;)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-addOrUpdateNetwork-(Landroid/net/wifi/WifiConfiguration;)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-disableNetwork-(I)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-disconnect-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-enableNetwork-(I B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-pingSupplicant-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-reassociate-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-reconnect-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-removeNetwork-(I)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-saveConfiguration-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-setNumAllowedChannels-(I B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-setWifiApEnabled-(Landroid/net/wifi/WifiConfiguration; B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-setWifiEnabled-(B)" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-startScan-()" : "CHANGE_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-startScanActive-()" : "CHANGE_WIFI_STATE",
"Landroid/app/ExpandableListActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ExpandableListActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ExpandableListActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/accessibilityservice/AccessibilityService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/accessibilityservice/AccessibilityService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/accessibilityservice/AccessibilityService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/accounts/GrantCredentialsPermissionActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/accounts/GrantCredentialsPermissionActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/accounts/GrantCredentialsPermissionActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/backup/BackupAgent;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/backup/BackupAgent;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/backup/BackupAgent;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/service/wallpaper/WallpaperService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/service/wallpaper/WallpaperService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/service/wallpaper/WallpaperService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/backup/BackupAgentHelper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/backup/BackupAgentHelper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/backup/BackupAgentHelper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/accounts/AccountAuthenticatorActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/accounts/AccountAuthenticatorActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/accounts/AccountAuthenticatorActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/IActivityManager$Stub$Proxy;-unbroadcastIntent-(Landroid/app/IApplicationThread; Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ActivityGroup;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ActivityGroup;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ActivityGroup;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/content/ContextWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/ContextWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/ContextWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/ContextWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/ContextWrapper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/Activity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/Activity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/Activity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/ContextImpl;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ContextImpl;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ContextImpl;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/AliasActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/AliasActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/AliasActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/content/Context;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/Context;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/Context;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/Context;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/Context;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/service/urlrenderer/UrlRendererService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/service/urlrenderer/UrlRendererService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/service/urlrenderer/UrlRendererService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/FullBackupAgent;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/FullBackupAgent;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/FullBackupAgent;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/TabActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/TabActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/TabActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/view/ContextThemeWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/view/ContextThemeWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/view/ContextThemeWrapper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/speech/RecognitionService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/speech/RecognitionService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/speech/RecognitionService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/IntentService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/IntentService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/IntentService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/inputmethodservice/AbstractInputMethodService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/inputmethodservice/AbstractInputMethodService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/inputmethodservice/AbstractInputMethodService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/Application;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/Application;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/Application;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/Application;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/ListActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ListActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/ListActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/Service;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/Service;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/app/Service;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/content/MutableContextWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/MutableContextWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY",
"Landroid/content/MutableContextWrapper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY",
"Landroid/app/IActivityManager$Stub$Proxy;-forceStopPackage-(Ljava/lang/String;)" : "FORCE_STOP_PACKAGES",
"Landroid/app/ActivityManagerNative;-forceStopPackage-(Ljava/lang/String;)" : "FORCE_STOP_PACKAGES",
"Landroid/app/ActivityManager;-forceStopPackage-(Ljava/lang/String;)" : "FORCE_STOP_PACKAGES",
"Landroid/app/IActivityManager$Stub$Proxy;-killBackgroundProcesses-(Ljava/lang/String;)" : "KILL_BACKGROUND_PROCESSES",
"Landroid/app/ActivityManager;-killBackgroundProcesses-(Ljava/lang/String;)" : "KILL_BACKGROUND_PROCESSES",
"Landroid/app/AlarmManager;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME_ZONE",
"Landroid/app/AlarmManager;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME_ZONE",
"Landroid/app/IAlarmManager$Stub$Proxy;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME_ZONE",
"Landroid/server/BluetoothA2dpService;-connectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothA2dpService;-disconnectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothA2dpService;-resumeSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothA2dpService;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothA2dpService;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothA2dpService;-suspendSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothPbap;-disconnect-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-connectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-disconnectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-resumeSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-suspendSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-cancelDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-disable-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-enable-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-startDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-cancelDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-disable-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-enable-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-setDiscoverableTimeout-(I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothAdapter;-startDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-cancelBondProcess-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-cancelDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-cancelPairingUserInput-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-createBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-disable-()" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-disable-(B)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-enable-()" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-enable-(B)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-removeBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-setDiscoverableTimeout-(I)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-setPairingConfirmation-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-setPasskey-(Ljava/lang/String; I)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-setPin-(Ljava/lang/String; [L;)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-setTrust-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN",
"Landroid/server/BluetoothService;-startDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothHeadset;-connectHeadset-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothHeadset;-disconnectHeadset-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothHeadset;-setPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-connectHeadset-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-disconnectHeadset-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-setPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothDevice;-cancelBondProcess-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothDevice;-cancelPairingUserInput-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothDevice;-createBond-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothDevice;-removeBond-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothDevice;-setPairingConfirmation-(B)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothDevice;-setPasskey-(I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothDevice;-setPin-([L;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-connect-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-disconnect-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothA2dp;-connectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothA2dp;-disconnectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothA2dp;-resumeSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothA2dp;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/BluetoothA2dp;-suspendSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-cancelBondProcess-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-cancelDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-cancelPairingUserInput-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-createBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-disable-(B)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-enable-()" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-removeBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-setDiscoverableTimeout-(I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-setPairingConfirmation-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-setPasskey-(Ljava/lang/String; I)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-setPin-(Ljava/lang/String; [L;)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-setTrust-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-startDiscovery-()" : "BLUETOOTH_ADMIN",
"Landroid/view/IWindowManager$Stub$Proxy;-injectKeyEvent-(Landroid/view/KeyEvent; B)" : "INJECT_EVENTS",
"Landroid/view/IWindowManager$Stub$Proxy;-injectPointerEvent-(Landroid/view/MotionEvent; B)" : "INJECT_EVENTS",
"Landroid/view/IWindowManager$Stub$Proxy;-injectTrackballEvent-(Landroid/view/MotionEvent; B)" : "INJECT_EVENTS",
"Landroid/app/Instrumentation;-invokeContextMenuAction-(Landroid/app/Activity; I I)" : "INJECT_EVENTS",
"Landroid/app/Instrumentation;-sendCharacterSync-(I)" : "INJECT_EVENTS",
"Landroid/app/Instrumentation;-sendKeyDownUpSync-(I)" : "INJECT_EVENTS",
"Landroid/app/Instrumentation;-sendKeySync-(Landroid/view/KeyEvent;)" : "INJECT_EVENTS",
"Landroid/app/Instrumentation;-sendPointerSync-(Landroid/view/MotionEvent;)" : "INJECT_EVENTS",
"Landroid/app/Instrumentation;-sendStringSync-(Ljava/lang/String;)" : "INJECT_EVENTS",
"Landroid/app/Instrumentation;-sendTrackballEventSync-(Landroid/view/MotionEvent;)" : "INJECT_EVENTS",
"Landroid/hardware/Camera/ErrorCallback;-onError-(I Landroid/hardware/Camera;)" : "CAMERA",
"Landroid/media/MediaRecorder;-setVideoSource-(I)" : "CAMERA",
"Landroid/view/KeyEvent;-KEYCODE_CAMERA-I" : "CAMERA",
"Landroid/bluetooth/BluetoothClass/Device;-AUDIO_VIDEO_VIDEO_CAMERA-I" : "CAMERA",
"Landroid/provider/MediaStore;-INTENT_ACTION_STILL_IMAGE_CAMERA-Ljava/lang/String;" : "CAMERA",
"Landroid/provider/MediaStore;-INTENT_ACTION_VIDEO_CAMERA-Ljava/lang/String;" : "CAMERA",
"Landroid/hardware/Camera/CameraInfo;-CAMERA_FACING_BACK-I" : "CAMERA",
"Landroid/hardware/Camera/CameraInfo;-CAMERA_FACING_FRONT-I" : "CAMERA",
"Landroid/hardware/Camera/CameraInfo;-facing-I" : "CAMERA",
"Landroid/provider/ContactsContract/StatusColumns;-CAPABILITY_HAS_CAMERA-I" : "CAMERA",
"Landroid/hardware/Camera/Parameters;-setRotation-(I)" : "CAMERA",
"Landroid/media/MediaRecorder/VideoSource;-CAMERA-I" : "CAMERA",
"Landroid/content/Intent;-IntentResolution-Ljava/lang/String;" : "CAMERA",
"Landroid/content/Intent;-ACTION_CAMERA_BUTTON-Ljava/lang/String;" : "CAMERA",
"Landroid/content/pm/PackageManager;-FEATURE_CAMERA-Ljava/lang/String;" : "CAMERA",
"Landroid/content/pm/PackageManager;-FEATURE_CAMERA_AUTOFOCUS-Ljava/lang/String;" : "CAMERA",
"Landroid/content/pm/PackageManager;-FEATURE_CAMERA_FLASH-Ljava/lang/String;" : "CAMERA",
"Landroid/content/pm/PackageManager;-FEATURE_CAMERA_FRONT-Ljava/lang/String;" : "CAMERA",
"Landroid/hardware/Camera;-CAMERA_ERROR_SERVER_DIED-I" : "CAMERA",
"Landroid/hardware/Camera;-CAMERA_ERROR_UNKNOWN-I" : "CAMERA",
"Landroid/hardware/Camera;-setDisplayOrientation-(I)" : "CAMERA",
"Landroid/hardware/Camera;-native_setup-(Ljava/lang/Object;)" : "CAMERA",
"Landroid/hardware/Camera;-open-()" : "CAMERA",
"Landroid/app/Activity;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/Activity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/Activity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/ExpandableListActivity;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/ExpandableListActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/ExpandableListActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/accessibilityservice/AccessibilityService;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/accessibilityservice/AccessibilityService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/accessibilityservice/AccessibilityService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/accounts/GrantCredentialsPermissionActivity;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/accounts/GrantCredentialsPermissionActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/accounts/GrantCredentialsPermissionActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/backup/BackupAgent;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/backup/BackupAgent;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/backup/BackupAgent;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/service/wallpaper/WallpaperService;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/service/wallpaper/WallpaperService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/service/wallpaper/WallpaperService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/backup/BackupAgentHelper;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/backup/BackupAgentHelper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/backup/BackupAgentHelper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/accounts/AccountAuthenticatorActivity;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/accounts/AccountAuthenticatorActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/accounts/AccountAuthenticatorActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/IWallpaperManager$Stub$Proxy;-setWallpaper-(Ljava/lang/String;)" : "SET_WALLPAPER",
"Landroid/app/ActivityGroup;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/ActivityGroup;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/ActivityGroup;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/content/ContextWrapper;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/content/ContextWrapper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/content/ContextWrapper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/WallpaperManager;-setBitmap-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/WallpaperManager;-clear-()" : "SET_WALLPAPER",
"Landroid/app/WallpaperManager;-setBitmap-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/WallpaperManager;-setResource-(I)" : "SET_WALLPAPER",
"Landroid/app/WallpaperManager;-setStream-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/ContextImpl;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/ContextImpl;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/ContextImpl;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/AliasActivity;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/AliasActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/AliasActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/content/Context;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/content/Context;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/content/Context;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/service/urlrenderer/UrlRendererService;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/service/urlrenderer/UrlRendererService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/service/urlrenderer/UrlRendererService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/FullBackupAgent;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/FullBackupAgent;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/FullBackupAgent;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/TabActivity;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/TabActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/TabActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/view/ContextThemeWrapper;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/view/ContextThemeWrapper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/view/ContextThemeWrapper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/speech/RecognitionService;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/speech/RecognitionService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/speech/RecognitionService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/IntentService;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/IntentService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/IntentService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/inputmethodservice/AbstractInputMethodService;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/inputmethodservice/AbstractInputMethodService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/inputmethodservice/AbstractInputMethodService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/Application;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/Application;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/Application;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/ListActivity;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/ListActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/ListActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/app/Service;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/app/Service;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/app/Service;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/content/MutableContextWrapper;-clearWallpaper-()" : "SET_WALLPAPER",
"Landroid/content/MutableContextWrapper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER",
"Landroid/content/MutableContextWrapper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-acquireWifiLock-(Landroid/os/IBinder; I Ljava/lang/String;)" : "WAKE_LOCK",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-releaseWifiLock-(Landroid/os/IBinder;)" : "WAKE_LOCK",
"Landroid/bluetooth/HeadsetBase;-acquireWakeLock-()" : "WAKE_LOCK",
"Landroid/bluetooth/HeadsetBase;-finalize-()" : "WAKE_LOCK",
"Landroid/bluetooth/HeadsetBase;-handleInput-(Ljava/lang/String;)" : "WAKE_LOCK",
"Landroid/bluetooth/HeadsetBase;-releaseWakeLock-()" : "WAKE_LOCK",
"Landroid/os/PowerManager$WakeLock;-acquire-()" : "WAKE_LOCK",
"Landroid/os/PowerManager$WakeLock;-acquire-(J)" : "WAKE_LOCK",
"Landroid/os/PowerManager$WakeLock;-release-()" : "WAKE_LOCK",
"Landroid/os/PowerManager$WakeLock;-release-(I)" : "WAKE_LOCK",
"Landroid/media/MediaPlayer;-setWakeMode-(Landroid/content/Context; I)" : "WAKE_LOCK",
"Landroid/media/MediaPlayer;-start-()" : "WAKE_LOCK",
"Landroid/media/MediaPlayer;-stayAwake-(B)" : "WAKE_LOCK",
"Landroid/media/MediaPlayer;-stop-()" : "WAKE_LOCK",
"Landroid/bluetooth/ScoSocket;-acquireWakeLock-()" : "WAKE_LOCK",
"Landroid/bluetooth/ScoSocket;-close-()" : "WAKE_LOCK",
"Landroid/bluetooth/ScoSocket;-finalize-()" : "WAKE_LOCK",
"Landroid/bluetooth/ScoSocket;-releaseWakeLock-()" : "WAKE_LOCK",
"Landroid/bluetooth/ScoSocket;-releaseWakeLockNow-()" : "WAKE_LOCK",
"Landroid/media/AsyncPlayer;-acquireWakeLock-()" : "WAKE_LOCK",
"Landroid/media/AsyncPlayer;-enqueueLocked-(Landroid/media/AsyncPlayer$Command;)" : "WAKE_LOCK",
"Landroid/media/AsyncPlayer;-play-(Landroid/content/Context; Landroid/net/Uri; B I)" : "WAKE_LOCK",
"Landroid/media/AsyncPlayer;-releaseWakeLock-()" : "WAKE_LOCK",
"Landroid/media/AsyncPlayer;-stop-()" : "WAKE_LOCK",
"Landroid/net/wifi/WifiManager$WifiLock;-acquire-()" : "WAKE_LOCK",
"Landroid/net/wifi/WifiManager$WifiLock;-finalize-()" : "WAKE_LOCK",
"Landroid/net/wifi/WifiManager$WifiLock;-release-()" : "WAKE_LOCK",
"Landroid/os/IPowerManager$Stub$Proxy;-acquireWakeLock-(I Landroid/os/IBinder; Ljava/lang/String;)" : "WAKE_LOCK",
"Landroid/os/IPowerManager$Stub$Proxy;-releaseWakeLock-(Landroid/os/IBinder; I)" : "WAKE_LOCK",
"Landroid/net/sip/SipAudioCall;-startAudio-()" : "WAKE_LOCK",
"Landroid/os/PowerManager;-ACQUIRE_CAUSES_WAKEUP-I" : "WAKE_LOCK",
"Landroid/os/PowerManager;-FULL_WAKE_LOCK-I" : "WAKE_LOCK",
"Landroid/os/PowerManager;-ON_AFTER_RELEASE-I" : "WAKE_LOCK",
"Landroid/os/PowerManager;-PARTIAL_WAKE_LOCK-I" : "WAKE_LOCK",
"Landroid/os/PowerManager;-SCREEN_BRIGHT_WAKE_LOCK-I" : "WAKE_LOCK",
"Landroid/os/PowerManager;-SCREEN_DIM_WAKE_LOCK-I" : "WAKE_LOCK",
"Landroid/os/PowerManager;-newWakeLock-(I Ljava/lang/String;)" : "WAKE_LOCK",
"Landroid/accounts/AccountManager;-addAccount-(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-confirmCredentials-(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-editProperties-(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-getAuthTokenByFeatures-(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-removeAccount-(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-updateCredentials-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-addAccount-(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-confirmCredentials-(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-editProperties-(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-removeAccount-(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManager;-updateCredentials-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-addAcount-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-checkManageAccountsOrUseCredentialsPermissions-()" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-checkManageAccountsPermission-()" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-confirmCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-editProperties-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-removeAccount-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-updateCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-addAcount-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-confirmCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-editProperties-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-removeAccount-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-updateCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS",
"Landroid/provider/Calendar$CalendarAlerts;-insert-(Landroid/content/ContentResolver; J J J J I)" : "WRITE_CALENDAR",
"Landroid/provider/Calendar$Calendars;-delete-(Landroid/content/ContentResolver; Ljava/lang/String; [L[Ljava/lang/Strin;)" : "WRITE_CALENDAR",
"Landroid/provider/Calendar$Calendars;-deleteCalendarsForAccount-(Landroid/content/ContentResolver; Landroid/accounts/Account;)" : "WRITE_CALENDAR",
"Landroid/appwidget/AppWidgetManager;-bindAppWidgetId-(I Landroid/content/ComponentName;)" : "BIND_APPWIDGET",
"Lcom/android/internal/appwidget/IAppWidgetService$Stub$Proxy;-bindAppWidgetId-(I LComponentName;)" : "BIND_APPWIDGET",
"Landroid/os/storage/IMountService$Stub$Proxy;-mountSecureContainer-(Ljava/lang/String; Ljava/lang/String; I)" : "ASEC_MOUNT_UNMOUNT",
"Landroid/os/storage/IMountService$Stub$Proxy;-unmountSecureContainer-(Ljava/lang/String; B)" : "ASEC_MOUNT_UNMOUNT",
"Landroid/app/ContextImpl$ApplicationPackageManager;-addPreferredActivity-(LIntentFilter; I [LComponentName; LComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/app/ContextImpl$ApplicationPackageManager;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/app/ContextImpl$ApplicationPackageManager;-replacePreferredActivity-(LIntentFilter; I [LComponentName; LComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/app/ContextImpl$ApplicationPackageManager;-addPreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/app/ContextImpl$ApplicationPackageManager;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/app/ContextImpl$ApplicationPackageManager;-replacePreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/content/pm/PackageManager;-addPreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/content/pm/PackageManager;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/content/pm/PackageManager;-replacePreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-addPreferredActivity-(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-replacePreferredActivity-(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS",
"Landroid/inputmethodservice/InputMethodService;-SoftInputView-I" : "NFC",
"Landroid/inputmethodservice/InputMethodService;-CandidatesView-I" : "NFC",
"Landroid/inputmethodservice/InputMethodService;-FullscreenMode-I" : "NFC",
"Landroid/inputmethodservice/InputMethodService;-GeneratingText-I" : "NFC",
"Landroid/nfc/tech/NfcA;-close-()" : "NFC",
"Landroid/nfc/tech/NfcA;-connect-()" : "NFC",
"Landroid/nfc/tech/NfcA;-get-(Landroid/nfc/Tag;)" : "NFC",
"Landroid/nfc/tech/NfcA;-transceive-([B)" : "NFC",
"Landroid/nfc/tech/NfcB;-close-()" : "NFC",
"Landroid/nfc/tech/NfcB;-connect-()" : "NFC",
"Landroid/nfc/tech/NfcB;-get-(Landroid/nfc/Tag;)" : "NFC",
"Landroid/nfc/tech/NfcB;-transceive-([B)" : "NFC",
"Landroid/nfc/NfcAdapter;-ACTION_TECH_DISCOVERED-Ljava/lang/String;" : "NFC",
"Landroid/nfc/NfcAdapter;-disableForegroundDispatch-(Landroid/app/Activity;)" : "NFC",
"Landroid/nfc/NfcAdapter;-disableForegroundNdefPush-(Landroid/app/Activity;)" : "NFC",
"Landroid/nfc/NfcAdapter;-enableForegroundDispatch-(Landroid/app/Activity; Landroid/app/PendingIntent; [Landroid/content/IntentFilter; [[Ljava/lang/String[];)" : "NFC",
"Landroid/nfc/NfcAdapter;-enableForegroundNdefPush-(Landroid/app/Activity; Landroid/nfc/NdefMessage;)" : "NFC",
"Landroid/nfc/NfcAdapter;-getDefaultAdapter-()" : "NFC",
"Landroid/nfc/NfcAdapter;-getDefaultAdapter-(Landroid/content/Context;)" : "NFC",
"Landroid/nfc/NfcAdapter;-isEnabled-()" : "NFC",
"Landroid/nfc/tech/NfcF;-close-()" : "NFC",
"Landroid/nfc/tech/NfcF;-connect-()" : "NFC",
"Landroid/nfc/tech/NfcF;-get-(Landroid/nfc/Tag;)" : "NFC",
"Landroid/nfc/tech/NfcF;-transceive-([B)" : "NFC",
"Landroid/nfc/tech/NdefFormatable;-close-()" : "NFC",
"Landroid/nfc/tech/NdefFormatable;-connect-()" : "NFC",
"Landroid/nfc/tech/NdefFormatable;-format-(Landroid/nfc/NdefMessage;)" : "NFC",
"Landroid/nfc/tech/NdefFormatable;-formatReadOnly-(Landroid/nfc/NdefMessage;)" : "NFC",
"Landroid/app/Activity;-Fragments-I" : "NFC",
"Landroid/app/Activity;-ActivityLifecycle-I" : "NFC",
"Landroid/app/Activity;-ConfigurationChanges-I" : "NFC",
"Landroid/app/Activity;-StartingActivities-I" : "NFC",
"Landroid/app/Activity;-SavingPersistentState-I" : "NFC",
"Landroid/app/Activity;-Permissions-I" : "NFC",
"Landroid/app/Activity;-ProcessLifecycle-I" : "NFC",
"Landroid/nfc/tech/MifareClassic;-KEY_NFC_FORUM-[B" : "NFC",
"Landroid/nfc/tech/MifareClassic;-authenticateSectorWithKeyA-(I [B)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-authenticateSectorWithKeyB-(I [B)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-close-()" : "NFC",
"Landroid/nfc/tech/MifareClassic;-connect-()" : "NFC",
"Landroid/nfc/tech/MifareClassic;-decrement-(I I)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-increment-(I I)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-readBlock-(I)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-restore-(I)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-transceive-([B)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-transfer-(I)" : "NFC",
"Landroid/nfc/tech/MifareClassic;-writeBlock-(I [B)" : "NFC",
"Landroid/nfc/Tag;-getTechList-()" : "NFC",
"Landroid/app/Service;-WhatIsAService-I" : "NFC",
"Landroid/app/Service;-ServiceLifecycle-I" : "NFC",
"Landroid/app/Service;-Permissions-I" : "NFC",
"Landroid/app/Service;-ProcessLifecycle-I" : "NFC",
"Landroid/app/Service;-LocalServiceSample-I" : "NFC",
"Landroid/app/Service;-RemoteMessengerServiceSample-I" : "NFC",
"Landroid/nfc/NfcManager;-getDefaultAdapter-()" : "NFC",
"Landroid/nfc/tech/MifareUltralight;-close-()" : "NFC",
"Landroid/nfc/tech/MifareUltralight;-connect-()" : "NFC",
"Landroid/nfc/tech/MifareUltralight;-readPages-(I)" : "NFC",
"Landroid/nfc/tech/MifareUltralight;-transceive-([B)" : "NFC",
"Landroid/nfc/tech/MifareUltralight;-writePage-(I [B)" : "NFC",
"Landroid/nfc/tech/NfcV;-close-()" : "NFC",
"Landroid/nfc/tech/NfcV;-connect-()" : "NFC",
"Landroid/nfc/tech/NfcV;-get-(Landroid/nfc/Tag;)" : "NFC",
"Landroid/nfc/tech/NfcV;-transceive-([B)" : "NFC",
"Landroid/nfc/tech/TagTechnology;-close-()" : "NFC",
"Landroid/nfc/tech/TagTechnology;-connect-()" : "NFC",
"Landroid/preference/PreferenceActivity;-SampleCode-Ljava/lang/String;" : "NFC",
"Landroid/content/pm/PackageManager;-FEATURE_NFC-Ljava/lang/String;" : "NFC",
"Landroid/content/Context;-NFC_SERVICE-Ljava/lang/String;" : "NFC",
"Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_1-Ljava/lang/String;" : "NFC",
"Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_2-Ljava/lang/String;" : "NFC",
"Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_3-Ljava/lang/String;" : "NFC",
"Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_4-Ljava/lang/String;" : "NFC",
"Landroid/nfc/tech/Ndef;-close-()" : "NFC",
"Landroid/nfc/tech/Ndef;-connect-()" : "NFC",
"Landroid/nfc/tech/Ndef;-getType-()" : "NFC",
"Landroid/nfc/tech/Ndef;-isWritable-()" : "NFC",
"Landroid/nfc/tech/Ndef;-makeReadOnly-()" : "NFC",
"Landroid/nfc/tech/Ndef;-writeNdefMessage-(Landroid/nfc/NdefMessage;)" : "NFC",
"Landroid/nfc/tech/IsoDep;-close-()" : "NFC",
"Landroid/nfc/tech/IsoDep;-connect-()" : "NFC",
"Landroid/nfc/tech/IsoDep;-setTimeout-(I)" : "NFC",
"Landroid/nfc/tech/IsoDep;-transceive-([B)" : "NFC",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-call-(Ljava/lang/String;)" : "CALL_PHONE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-endCall-()" : "CALL_PHONE",
"Lcom/android/http/multipart/FilePart;-sendData-(Ljava/io/OutputStream;)" : "INTERNET",
"Lcom/android/http/multipart/FilePart;-sendDispositionHeader-(Ljava/io/OutputStream;)" : "INTERNET",
"Ljava/net/HttpURLConnection;-<init>-(Ljava/net/URL;)" : "INTERNET",
"Ljava/net/HttpURLConnection;-connect-()" : "INTERNET",
"Landroid/webkit/WebSettings;-setBlockNetworkLoads-(B)" : "INTERNET",
"Landroid/webkit/WebSettings;-verifyNetworkAccess-()" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-<init>-()" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-<init>-(Lorg/apache/http/params/HttpParams;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-<init>-(Lorg/apache/http/conn/ClientConnectionManager; Lorg/apache/http/params/HttpParams;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET",
"Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET",
"Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET",
"Lcom/android/http/multipart/Part;-send-(Ljava/io/OutputStream;)" : "INTERNET",
"Lcom/android/http/multipart/Part;-sendParts-(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part;)" : "INTERNET",
"Lcom/android/http/multipart/Part;-sendParts-(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part; [B)" : "INTERNET",
"Lcom/android/http/multipart/Part;-sendStart-(Ljava/io/OutputStream;)" : "INTERNET",
"Lcom/android/http/multipart/Part;-sendTransferEncodingHeader-(Ljava/io/OutputStream;)" : "INTERNET",
"Landroid/drm/DrmErrorEvent;-TYPE_NO_INTERNET_CONNECTION-I" : "INTERNET",
"Landroid/webkit/WebViewCore;-<init>-(Landroid/content/Context; Landroid/webkit/WebView; Landroid/webkit/CallbackProxy; Ljava/util/Map;)" : "INTERNET",
"Ljava/net/URLConnection;-connect-()" : "INTERNET",
"Ljava/net/URLConnection;-getInputStream-()" : "INTERNET",
"Landroid/app/Activity;-setContentView-(I)" : "INTERNET",
"Ljava/net/MulticastSocket;-<init>-()" : "INTERNET",
"Ljava/net/MulticastSocket;-<init>-(I)" : "INTERNET",
"Ljava/net/MulticastSocket;-<init>-(Ljava/net/SocketAddress;)" : "INTERNET",
"Lcom/android/http/multipart/StringPart;-sendData-(Ljava/io/OuputStream;)" : "INTERNET",
"Ljava/net/URL;-getContent-([Ljava/lang/Class;)" : "INTERNET",
"Ljava/net/URL;-getContent-()" : "INTERNET",
"Ljava/net/URL;-openConnection-(Ljava/net/Proxy;)" : "INTERNET",
"Ljava/net/URL;-openConnection-()" : "INTERNET",
"Ljava/net/URL;-openStream-()" : "INTERNET",
"Ljava/net/DatagramSocket;-<init>-()" : "INTERNET",
"Ljava/net/DatagramSocket;-<init>-(I)" : "INTERNET",
"Ljava/net/DatagramSocket;-<init>-(I Ljava/net/InetAddress;)" : "INTERNET",
"Ljava/net/DatagramSocket;-<init>-(Ljava/net/SocketAddress;)" : "INTERNET",
"Ljava/net/ServerSocket;-<init>-()" : "INTERNET",
"Ljava/net/ServerSocket;-<init>-(I)" : "INTERNET",
"Ljava/net/ServerSocket;-<init>-(I I)" : "INTERNET",
"Ljava/net/ServerSocket;-<init>-(I I Ljava/net/InetAddress;)" : "INTERNET",
"Ljava/net/ServerSocket;-bind-(Ljava/net/SocketAddress;)" : "INTERNET",
"Ljava/net/ServerSocket;-bind-(Ljava/net/SocketAddress; I)" : "INTERNET",
"Ljava/net/Socket;-<init>-()" : "INTERNET",
"Ljava/net/Socket;-<init>-(Ljava/lang/String; I)" : "INTERNET",
"Ljava/net/Socket;-<init>-(Ljava/lang/String; I Ljava/net/InetAddress; I)" : "INTERNET",
"Ljava/net/Socket;-<init>-(Ljava/lang/String; I B)" : "INTERNET",
"Ljava/net/Socket;-<init>-(Ljava/net/InetAddress; I)" : "INTERNET",
"Ljava/net/Socket;-<init>-(Ljava/net/InetAddress; I Ljava/net/InetAddress; I)" : "INTERNET",
"Ljava/net/Socket;-<init>-(Ljava/net/InetAddress; I B)" : "INTERNET",
"Landroid/webkit/WebView;-<init>-(Landroid/content/Context; Landroid/util/AttributeSet; I)" : "INTERNET",
"Landroid/webkit/WebView;-<init>-(Landroid/content/Context; Landroid/util/AttributeSet;)" : "INTERNET",
"Landroid/webkit/WebView;-<init>-(Landroid/content/Context;)" : "INTERNET",
"Ljava/net/NetworkInterface;-<init>-()" : "INTERNET",
"Ljava/net/NetworkInterface;-<init>-(Ljava/lang/String; I Ljava/net/InetAddress;)" : "INTERNET",
"Landroid/webkit/WebChromeClient;-onGeolocationPermissionsShowPrompt-(Ljava/lang/String; Landroid/webkit/GeolocationPermissions/Callback;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-GPS_PROVIDER-Ljava/lang/String;" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-NETWORK_PROVIDER-Ljava/lang/String;" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-PASSIVE_PROVIDER-Ljava/lang/String;" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-addGpsStatusListener-(Landroid/location/GpsStatus/Listener;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-addNmeaListener-(Landroid/location/GpsStatus/NmeaListener;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-_requestLocationUpdates-(Ljava/lang/String; J F Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-_requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-addGpsStatusListener-(Landroid/location/GpsStatus$Listener;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-addNmeaListener-(Landroid/location/GpsStatus$NmeaListener;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-addProximityAlert-(D D F J Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-best-(Ljava/util/List;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-getBestProvider-(Landroid/location/Criteria; B)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-getLastKnownLocation-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-getProvider-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-getProviders-(Landroid/location/Criteria; B)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-getProviders-(B)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-isProviderEnabled-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/LocationListener;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/LocationManager;-sendExtraCommand-(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCESS_FINE_LOCATION",
"Landroid/webkit/GeolocationService;-registerForLocationUpdates-()" : "ACCESS_FINE_LOCATION",
"Landroid/webkit/GeolocationService;-setEnableGps-(B)" : "ACCESS_FINE_LOCATION",
"Landroid/webkit/GeolocationService;-start-()" : "ACCESS_FINE_LOCATION",
"Landroid/telephony/TelephonyManager;-getCellLocation-()" : "ACCESS_FINE_LOCATION",
"Landroid/telephony/TelephonyManager;-getCellLocation-()" : "ACCESS_FINE_LOCATION",
"Landroid/telephony/TelephonyManager;-getNeighboringCellInfo-()" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-addGpsStatusListener-(Landroid/location/IGpsStatusListener;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-addProximityAlert-(D D F J Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-getLastKnownLocation-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-getProviderInfo-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-getProviders-(B)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-isProviderEnabled-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/ILocationListener;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-requestLocationUpdatesPI-(Ljava/lang/String; J F Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION",
"Landroid/location/ILocationManager$Stub$Proxy;-sendExtraCommand-(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCESS_FINE_LOCATION",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-getCellLocation-()" : "ACCESS_FINE_LOCATION",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-getNeighboringCellInfo-()" : "ACCESS_FINE_LOCATION",
"Landroid/webkit/GeolocationPermissions$Callback;-invok-()" : "ACCESS_FINE_LOCATION",
"Landroid/provider/Telephony$Sms$Inbox;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B)" : "READ_SMS",
"Landroid/provider/Telephony$Threads;-getOrCreateThreadId-(Landroid/content/Context; Ljava/lang/String;)" : "READ_SMS",
"Landroid/provider/Telephony$Threads;-getOrCreateThreadId-(Landroid/content/Context; Ljava/util/Set;)" : "READ_SMS",
"Landroid/provider/Telephony$Mms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_SMS",
"Landroid/provider/Telephony$Mms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)" : "READ_SMS",
"Landroid/provider/Telephony$Sms$Draft;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)" : "READ_SMS",
"Landroid/provider/Telephony$Sms$Sent;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)" : "READ_SMS",
"Landroid/provider/Telephony$Sms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_SMS",
"Landroid/provider/Telephony$Sms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)" : "READ_SMS",
"Landroid/view/SurfaceSession;-<init>-()" : "ACCESS_SURFACE_FLINGER",
"Landroid/view/Surface;-closeTransaction-()" : "ACCESS_SURFACE_FLINGER",
"Landroid/view/Surface;-freezeDisplay-(I)" : "ACCESS_SURFACE_FLINGER",
"Landroid/view/Surface;-setOrientation-(I I I)" : "ACCESS_SURFACE_FLINGER",
"Landroid/view/Surface;-setOrientation-(I I)" : "ACCESS_SURFACE_FLINGER",
"Landroid/view/Surface;-unfreezeDisplay-(I)" : "ACCESS_SURFACE_FLINGER",
"Landroid/app/IActivityManager$Stub$Proxy;-moveTaskBackwards-(I)" : "REORDER_TASKS",
"Landroid/app/IActivityManager$Stub$Proxy;-moveTaskToBack-(I)" : "REORDER_TASKS",
"Landroid/app/IActivityManager$Stub$Proxy;-moveTaskToFront-(I)" : "REORDER_TASKS",
"Landroid/app/ActivityManager;-moveTaskToFront-(I I)" : "REORDER_TASKS",
"Landroid/net/sip/SipAudioCall;-setSpeakerMode-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/server/BluetoothA2dpService;-checkSinkSuspendState-(I)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/server/BluetoothA2dpService;-handleSinkStateChange-(Landroid/bluetooth/BluetoothDevice;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/server/BluetoothA2dpService;-onBluetoothDisable-()" : "MODIFY_AUDIO_SETTINGS",
"Landroid/server/BluetoothA2dpService;-onBluetoothEnable-()" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/IAudioService$Stub$Proxy;-setBluetoothScoOn-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/IAudioService$Stub$Proxy;-setMode-(I Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/IAudioService$Stub$Proxy;-setSpeakerphoneOn-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/IAudioService$Stub$Proxy;-startBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/IAudioService$Stub$Proxy;-stopBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioService;-setBluetoothScoOn-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioService;-setMode-(I Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioService;-setSpeakerphoneOn-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioService;-startBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioService;-stopBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-startBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-stopBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-isBluetoothA2dpOn-()" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-isWiredHeadsetOn-()" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-setBluetoothScoOn-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-setMicrophoneMute-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-setMode-(I)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-setParameter-(Ljava/lang/String; Ljava/lang/String;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-setParameters-(Ljava/lang/String;)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-setSpeakerphoneOn-(B)" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-startBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS",
"Landroid/media/AudioManager;-stopBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getDeviceId-()" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getDeviceSvn-()" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getIccSerialNumber-()" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getLine1AlphaTag-()" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getLine1Number-()" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getSubscriberId-()" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getVoiceMailAlphaTag-()" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getVoiceMailNumber-()" : "READ_PHONE_STATE",
"Landroid/telephony/PhoneStateListener;-LISTEN_CALL_FORWARDING_INDICATOR-I" : "READ_PHONE_STATE",
"Landroid/telephony/PhoneStateListener;-LISTEN_CALL_STATE-I" : "READ_PHONE_STATE",
"Landroid/telephony/PhoneStateListener;-LISTEN_DATA_ACTIVITY-I" : "READ_PHONE_STATE",
"Landroid/telephony/PhoneStateListener;-LISTEN_MESSAGE_WAITING_INDICATOR-I" : "READ_PHONE_STATE",
"Landroid/telephony/PhoneStateListener;-LISTEN_SIGNAL_STRENGTH-I" : "READ_PHONE_STATE",
"Landroid/accounts/AccountManagerService$SimWatcher;-onReceive-(Landroid/content/Context; Landroid/content/Intent;)" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/CallerInfo;-markAsVoiceMail-()" : "READ_PHONE_STATE",
"Landroid/os/Build/VERSION_CODES;-DONUT-I" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-ACTION_PHONE_STATE_CHANGED-Ljava/lang/String;" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getDeviceId-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getDeviceSoftwareVersion-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getLine1Number-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getSimSerialNumber-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getSubscriberId-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getVoiceMailAlphaTag-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getVoiceMailNumber-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getDeviceId-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getDeviceSoftwareVersion-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getLine1AlphaTag-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getLine1Number-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getSimSerialNumber-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getSubscriberId-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getVoiceMailAlphaTag-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-getVoiceMailNumber-()" : "READ_PHONE_STATE",
"Landroid/telephony/TelephonyManager;-listen-(Landroid/telephony/PhoneStateListener; I)" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-listen-(Ljava/lang/String; Lcom/android/internal/telephony/IPhoneStateListener; I B)" : "READ_PHONE_STATE",
"Landroid/telephony/PhoneNumberUtils;-isVoiceMailNumber-(Ljava/lang/String;)" : "READ_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-isSimPinEnabled-()" : "READ_PHONE_STATE",
"Landroid/media/RingtoneManager;-setActualDefaultRingtoneUri-(Landroid/content/Context; I Landroid/net/Uri;)" : "WRITE_SETTINGS",
"Landroid/os/IPowerManager$Stub$Proxy;-setStayOnSetting-(I)" : "WRITE_SETTINGS",
"Landroid/server/BluetoothService;-persistBluetoothOnSetting-(B)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$Secure;-putFloat-(Landroid/content/ContentResolver; Ljava/lang/String; F)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$Secure;-putInt-(Landroid/content/ContentResolver; Ljava/lang/String; I)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$Secure;-putLong-(Landroid/content/ContentResolver; Ljava/lang/String; J)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$Secure;-putString-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$Secure;-setLocationProviderEnabled-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$Bookmarks;-add-(Landroid/content/ContentResolver; Landroid/content/Intent; Ljava/lang/String; Ljava/lang/String; C I)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$Bookmarks;-getIntentForShortcut-(Landroid/content/ContentResolver; C)" : "WRITE_SETTINGS",
"Landroid/os/IMountService$Stub$Proxy;-setAutoStartUm-()" : "WRITE_SETTINGS",
"Landroid/os/IMountService$Stub$Proxy;-setPlayNotificationSound-()" : "WRITE_SETTINGS",
"Landroid/provider/Settings$System;-putConfiguration-(Landroid/content/ContentResolver; Landroid/content/res/Configuration;)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$System;-putFloat-(Landroid/content/ContentResolver; Ljava/lang/String; F)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$System;-putInt-(Landroid/content/ContentResolver; Ljava/lang/String; I)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$System;-putLong-(Landroid/content/ContentResolver; Ljava/lang/String; J)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$System;-putString-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_SETTINGS",
"Landroid/provider/Settings$System;-setShowGTalkServiceStatus-(Landroid/content/ContentResolver; B)" : "WRITE_SETTINGS",
"Landroid/service/wallpaper/WallpaperService;-SERVICE_INTERFACE-Ljava/lang/String;" : "BIND_WALLPAPER",
"Lcom/android/server/WallpaperManagerService;-bindWallpaperComponentLocked-(Landroid/content/ComponentName;)" : "BIND_WALLPAPER",
"Landroid/content/ContentService;-dump-(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Strin;)" : "DUMP",
"Landroid/view/IWindowManager$Stub$Proxy;-isViewServerRunning-()" : "DUMP",
"Landroid/view/IWindowManager$Stub$Proxy;-startViewServer-(I)" : "DUMP",
"Landroid/view/IWindowManager$Stub$Proxy;-stopViewServer-()" : "DUMP",
"Landroid/os/Debug;-dumpService-(Ljava/lang/String; Ljava/io/FileDescriptor; [Ljava/lang/String;)" : "DUMP",
"Landroid/os/IBinder;-DUMP_TRANSACTION-I" : "DUMP",
"Lcom/android/server/WallpaperManagerService;-dump-(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Stri;)" : "DUMP",
"Landroid/accounts/AccountManager;-blockingGetAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B)" : "USE_CREDENTIALS",
"Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "USE_CREDENTIALS",
"Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "USE_CREDENTIALS",
"Landroid/accounts/AccountManager;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "USE_CREDENTIALS",
"Landroid/accounts/AccountManager;-blockingGetAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B)" : "USE_CREDENTIALS",
"Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "USE_CREDENTIALS",
"Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "USE_CREDENTIALS",
"Landroid/accounts/AccountManagerService;-getAuthToken-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)" : "USE_CREDENTIALS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-getAuthToken-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)" : "USE_CREDENTIALS",
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;-notePauseComponent-(LComponentName;)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IUsageStats$Stub$Proxy;-noteResumeComponent-(LComponentName;)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteFullWifiLockAcquired-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteFullWifiLockReleased-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteInputEvent-()" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneDataConnectionState-(I B)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneOff-()" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneOn-()" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneSignalStrength-(LSignalStrength;)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneState-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScanWifiLockAcquired-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScanWifiLockReleased-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScreenBrightness-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScreenOff-()" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScreenOn-()" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStartGps-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStartSensor-(I I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStartWakelock-(I Ljava/lang/String; I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStopGps-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStopSensor-(I I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStopWakelock-(I Ljava/lang/String; I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteUserActivity-(I I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiMulticastDisabled-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiMulticastEnabled-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiOff-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiOn-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiRunning-()" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiStopped-()" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-recordCurrentLevel-(I)" : "UPDATE_DEVICE_STATS",
"Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-setOnBattery-(B I)" : "UPDATE_DEVICE_STATS",
"Landroid/telephony/gsm/SmsManager;-getDefault-()" : "SEND_SMS",
"Landroid/telephony/gsm/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/telephony/gsm/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/telephony/gsm/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/telephony/gsm/SmsManager;-sendMultipartTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)" : "SEND_SMS",
"Landroid/telephony/gsm/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/telephony/SmsManager;-getDefault-()" : "SEND_SMS",
"Landroid/telephony/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/telephony/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/telephony/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/telephony/SmsManager;-sendMultipartTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)" : "SEND_SMS",
"Landroid/telephony/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Lcom/android/internal/telephony/ISms$Stub$Proxy;-sendData-(Ljava/lang/String; Ljava/lang/String; I [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Lcom/android/internal/telephony/ISms$Stub$Proxy;-sendMultipartText-(Ljava/lang/String; Ljava/lang/String; Ljava/util/List; Ljava/util/List; Ljava/util/List;)" : "SEND_SMS",
"Lcom/android/internal/telephony/ISms$Stub$Proxy;-sendText-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS",
"Landroid/provider/UserDictionary$Words;-addWord-(Landroid/content/Context; Ljava/lang/String; I I)" : "WRITE_USER_DICTIONARY",
"Landroid/telephony/TelephonyManager;-getCellLocation-()" : "ACCESS_COARSE_LOCATION",
"Landroid/telephony/PhoneStateListener;-LISTEN_CELL_LOCATION-I" : "ACCESS_COARSE_LOCATION",
"Landroid/location/LocationManager;-NETWORK_PROVIDER-Ljava/lang/String;" : "ACCESS_COARSE_LOCATION",
"Landroid/os/storage/IMountService$Stub$Proxy;-renameSecureContainer-(Ljava/lang/String; Ljava/lang/String;)" : "ASEC_RENAME",
"Landroid/view/IWindowSession$Stub$Proxy;-add-(Landroid/view/IWindow; Landroid/view/WindowManager$LayoutParams; I Landroid/graphics/Rect;)" : "SYSTEM_ALERT_WINDOW",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-acquireMulticastLock-(Landroid/os/IBinder; Ljava/lang/String;)" : "CHANGE_WIFI_MULTICAST_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-initializeMulticastFiltering-()" : "CHANGE_WIFI_MULTICAST_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-releaseMulticastLock-()" : "CHANGE_WIFI_MULTICAST_STATE",
"Landroid/net/wifi/WifiManager$MulticastLock;-acquire-()" : "CHANGE_WIFI_MULTICAST_STATE",
"Landroid/net/wifi/WifiManager$MulticastLock;-finalize-()" : "CHANGE_WIFI_MULTICAST_STATE",
"Landroid/net/wifi/WifiManager$MulticastLock;-release-()" : "CHANGE_WIFI_MULTICAST_STATE",
"Landroid/net/wifi/WifiManager;-initializeMulticastFiltering-()" : "CHANGE_WIFI_MULTICAST_STATE",
"Landroid/content/Intent;-ACTION_BOOT_COMPLETED-Ljava/lang/String;" : "RECEIVE_BOOT_COMPLETED",
"Landroid/provider/AlarmClock;-ACTION_SET_ALARM-Ljava/lang/String;" : "SET_ALARM",
"Landroid/provider/AlarmClock;-EXTRA_HOUR-Ljava/lang/String;" : "SET_ALARM",
"Landroid/provider/AlarmClock;-EXTRA_MESSAGE-Ljava/lang/String;" : "SET_ALARM",
"Landroid/provider/AlarmClock;-EXTRA_MINUTES-Ljava/lang/String;" : "SET_ALARM",
"Landroid/provider/AlarmClock;-EXTRA_SKIP_UI-Ljava/lang/String;" : "SET_ALARM",
"Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;-updateAdnRecordsInEfByIndex-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS",
"Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;-updateAdnRecordsInEfBySearch-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS",
"Landroid/provider/Contacts$People;-addToGroup-(Landroid/content/ContentResolver; J J)" : "WRITE_CONTACTS",
"Landroid/provider/ContactsContract$Contacts;-markAsContacted-(Landroid/content/ContentResolver; J)" : "WRITE_CONTACTS",
"Landroid/provider/Contacts$Settings;-setSetting-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS",
"Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;-updateAdnRecordsInEfByIndex-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS",
"Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;-updateAdnRecordsInEfBySearch-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS",
"Landroid/provider/CallLog$Calls;-removeExpiredEntries-(Landroid/content/Context;)" : "WRITE_CONTACTS",
"Landroid/pim/vcard/VCardEntryCommitter;-onEntryCreated-(Landroid/pim/vcard/VCardEntry;)" : "WRITE_CONTACTS",
"Landroid/pim/vcard/VCardEntryHandler;-onEntryCreated-(Landroid/pim/vcard/VCardEntry;)" : "WRITE_CONTACTS",
"Landroid/pim/vcard/VCardEntry;-pushIntoContentResolver-(Landroid/content/ContentResolver;)" : "WRITE_CONTACTS",
"Landroid/content/Intent;-ACTION_NEW_OUTGOING_CALL-Ljava/lang/String;" : "PROCESS_OUTGOING_CALLS",
"Landroid/app/StatusBarManager;-collapse-()" : "EXPAND_STATUS_BAR",
"Landroid/app/StatusBarManager;-expand-()" : "EXPAND_STATUS_BAR",
"Landroid/app/StatusBarManager;-toggle-()" : "EXPAND_STATUS_BAR",
"Landroid/app/IStatusBar$Stub$Proxy;-activate-()" : "EXPAND_STATUS_BAR",
"Landroid/app/IStatusBar$Stub$Proxy;-deactivate-()" : "EXPAND_STATUS_BAR",
"Landroid/app/IStatusBar$Stub$Proxy;-toggle-()" : "EXPAND_STATUS_BAR",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-answerRingingCall-()" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-cancelMissedCallsNotification-()" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-disableApnType-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-disableDataConnectivity-()" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-enableApnType-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-enableDataConnectivity-()" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-handlePinMmi-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-setRadio-(B)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-silenceRinger-()" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-supplyPin-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-toggleRadioOnOff-()" : "MODIFY_PHONE_STATE",
"Landroid/net/MobileDataStateTracker;-reconnect-()" : "MODIFY_PHONE_STATE",
"Landroid/net/MobileDataStateTracker;-setRadio-(B)" : "MODIFY_PHONE_STATE",
"Landroid/net/MobileDataStateTracker;-teardown-()" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyCallForwardingChanged-(B)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyCallState-(I Ljava/lang/String;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyCellLocation-(Landroid/os/Bundle;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyDataActivity-(I)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyDataConnection-(I B Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Ljava/lang/String; I)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyDataConnectionFailed-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyMessageWaitingChanged-(B)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyServiceState-(Landroid/telephony/ServiceState;)" : "MODIFY_PHONE_STATE",
"Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifySignalStrength-(Landroid/telephony/SignalStrength;)" : "MODIFY_PHONE_STATE",
"Landroid/os/IMountService$Stub$Proxy;-formatMedi-()" : "MOUNT_FORMAT_FILESYSTEMS",
"Landroid/os/storage/IMountService$Stub$Proxy;-formatVolume-(Ljava/lang/String;)" : "MOUNT_FORMAT_FILESYSTEMS",
"Landroid/net/Downloads$DownloadBase;-startDownloadByUri-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ByUri;-getCurrentOtaDownloads-(Landroid/content/Context; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ByUri;-getProgressCursor-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ByUri;-getStatus-(Landroid/content/Context; Ljava/lang/String; J)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ByUri;-removeAllDownloadsByPackage-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ByUri;-startDownloadByUri-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ById;-deleteDownload-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ById;-getMimeTypeForId-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ById;-getStatus-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ById;-openDownload-(Landroid/content/Context; J Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ById;-openDownloadStream-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/net/Downloads$ById;-startDownloadByUri-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER",
"Landroid/view/IWindowManager$Stub$Proxy;-getDPadKeycodeState-(I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getDPadScancodeState-(I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getKeycodeState-(I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getKeycodeStateForDevice-(I I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getScancodeState-(I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getScancodeStateForDevice-(I I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getSwitchState-(I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getSwitchStateForDevice-(I I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getTrackballKeycodeState-(I)" : "READ_INPUT_STATE",
"Landroid/view/IWindowManager$Stub$Proxy;-getTrackballScancodeState-(I)" : "READ_INPUT_STATE",
"Landroid/app/ContextImpl$ApplicationContentResolver;-getCurrentSync-()" : "READ_SYNC_STATS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/ContentService;-getCurrentSync-()" : "READ_SYNC_STATS",
"Landroid/content/ContentService;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/ContentService;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/ContentService;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/ContentResolver;-getCurrentSync-()" : "READ_SYNC_STATS",
"Landroid/content/ContentResolver;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/ContentResolver;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/ContentResolver;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/IContentService$Stub$Proxy;-getCurrentSync-()" : "READ_SYNC_STATS",
"Landroid/content/IContentService$Stub$Proxy;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/IContentService$Stub$Proxy;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/content/IContentService$Stub$Proxy;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS",
"Landroid/app/AlarmManager;-setTime-(J)" : "SET_TIME",
"Landroid/app/AlarmManager;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME",
"Landroid/app/AlarmManager;-setTime-(J)" : "SET_TIME",
"Landroid/app/IAlarmManager$Stub$Proxy;-setTime-(J)" : "SET_TIME",
"Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-setWimaxEnable-()" : "CHANGE_WIMAX_STATE",
"Landroid/os/IMountService$Stub$Proxy;-mountMedi-()" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/os/IMountService$Stub$Proxy;-unmountMedi-()" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/os/storage/IMountService$Stub$Proxy;-getStorageUsers-(Ljava/lang/String;)" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/os/storage/IMountService$Stub$Proxy;-mountVolume-(Ljava/lang/String;)" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/os/storage/IMountService$Stub$Proxy;-setUsbMassStorageEnabled-(B)" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/os/storage/IMountService$Stub$Proxy;-unmountVolume-(Ljava/lang/String; B)" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/os/storage/StorageManager;-disableUsbMassStorage-()" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/os/storage/StorageManager;-enableUsbMassStorage-()" : "MOUNT_UNMOUNT_FILESYSTEMS",
"Landroid/app/ContextImpl$ApplicationPackageManager;-movePackage-(Ljava/lang/String; LIPackageMoveObserver; I)" : "MOVE_PACKAGE",
"Landroid/app/ContextImpl$ApplicationPackageManager;-movePackage-(Ljava/lang/String; LIPackageMoveObserver; I)" : "MOVE_PACKAGE",
"Landroid/content/pm/PackageManager;-movePackage-(Ljava/lang/String; LIPackageMoveObserver; I)" : "MOVE_PACKAGE",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-movePackage-(Ljava/lang/String; Landroid/content/pm/IPackageMoveObserver; I)" : "MOVE_PACKAGE",
"Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-getConnectionInf-()" : "ACCESS_WIMAX_STATE",
"Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-getWimaxStat-()" : "ACCESS_WIMAX_STATE",
"Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-isBackoffStat-()" : "ACCESS_WIMAX_STATE",
"Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-isWimaxEnable-()" : "ACCESS_WIMAX_STATE",
"Landroid/net/sip/SipAudioCall;-startAudio-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getConfiguredNetworks-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getConnectionInfo-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getDhcpInfo-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getNumAllowedChannels-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getScanResults-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getValidChannelCounts-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getWifiApEnabledState-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-getWifiEnabledState-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/IWifiManager$Stub$Proxy;-isMulticastEnabled-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getConfiguredNetworks-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getConnectionInfo-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getDhcpInfo-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getNumAllowedChannels-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getScanResults-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getValidChannelCounts-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getWifiApState-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-getWifiState-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-isMulticastEnabled-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-isWifiApEnabled-()" : "ACCESS_WIFI_STATE",
"Landroid/net/wifi/WifiManager;-isWifiEnabled-()" : "ACCESS_WIFI_STATE",
"Landroid/webkit/WebIconDatabase;-bulkRequestIconForPageUrl-(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-BOOKMARKS_URI-Landroid/net/Uri;" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-SEARCHES_URI-Landroid/net/Uri;" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-addSearchUrl-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-canClearHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-getAllBookmarks-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-getAllVisitedUrls-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-requestAllIcons-(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase/IconListener;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-truncateHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-updateVisitedHistory-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-addSearchUrl-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-canClearHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-clearHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-deleteFromHistory-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-deleteHistoryTimeFrame-(Landroid/content/ContentResolver; J J)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-deleteHistoryWhere-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-getAllBookmarks-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-getAllVisitedUrls-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-getVisitedHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-getVisitedLike-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-requestAllIcons-(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-truncateHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-updateVisitedHistory-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "READ_HISTORY_BOOKMARKS",
"Landroid/os/storage/IMountService$Stub$Proxy;-destroySecureContainer-(Ljava/lang/String; B)" : "ASEC_DESTROY",
"Landroid/net/ThrottleManager;-getByteCount-(Ljava/lang/String; I I I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/ThrottleManager;-getCliffLevel-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/ThrottleManager;-getCliffThreshold-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/ThrottleManager;-getHelpUri-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ThrottleManager;-getPeriodStartTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/ThrottleManager;-getResetTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/NetworkInfo;-isConnectedOrConnecting-()" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-getDnsForwarders-()" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceRxCounter-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceRxThrottle-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceTxCounter-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceTxThrottle-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-getIpForwardingEnabled-()" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-isTetheringStarted-()" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-isUsbRNDISStarted-()" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-listInterfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-listTetheredInterfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-listTtys-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getActiveNetworkInfo-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getAllNetworkInfo-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getLastTetherError-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getMobileDataEnabled-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getNetworkInfo-(I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getNetworkPreference-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getTetherableIfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getTetherableUsbRegexs-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getTetherableWifiRegexs-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getTetheredIfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-getTetheringErroredIfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-isTetheringSupported-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-startUsingNetworkFeature-(I Ljava/lang/String; Landroid/os/IBinder;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IThrottleManager$Stub$Proxy;-getByteCount-(Ljava/lang/String; I I I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IThrottleManager$Stub$Proxy;-getCliffLevel-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IThrottleManager$Stub$Proxy;-getCliffThreshold-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IThrottleManager$Stub$Proxy;-getHelpUri-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/IThrottleManager$Stub$Proxy;-getPeriodStartTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IThrottleManager$Stub$Proxy;-getResetTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/IThrottleManager$Stub$Proxy;-getThrottle-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getActiveNetworkInfo-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getAllNetworkInfo-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getLastTetherError-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getMobileDataEnabled-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getNetworkInfo-(I)" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getNetworkPreference-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getTetherableIfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getTetherableUsbRegexs-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getTetherableWifiRegexs-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getTetheredIfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-getTetheringErroredIfaces-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-isTetheringSupported-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/http/RequestQueue;-enablePlatformNotifications-()" : "ACCESS_NETWORK_STATE",
"Landroid/net/http/RequestQueue;-setProxyConfig-()" : "ACCESS_NETWORK_STATE",
"Landroid/app/IActivityManager$Stub$Proxy;-getRecentTasks-(I I)" : "GET_TASKS",
"Landroid/app/IActivityManager$Stub$Proxy;-getTasks-(I I Landroid/app/IThumbnailReceiver;)" : "GET_TASKS",
"Landroid/app/ActivityManagerNative;-getRecentTasks-(I I)" : "GET_TASKS",
"Landroid/app/ActivityManagerNative;-getRunningTasks-(I)" : "GET_TASKS",
"Landroid/app/ActivityManager;-getRecentTasks-(I I)" : "GET_TASKS",
"Landroid/app/ActivityManager;-getRunningTasks-(I)" : "GET_TASKS",
"Landroid/app/ActivityManager;-getRecentTasks-(I I)" : "GET_TASKS",
"Landroid/app/ActivityManager;-getRunningTasks-(I)" : "GET_TASKS",
"Landroid/view/View/OnSystemUiVisibilityChangeListener;-onSystemUiVisibilityChange-(I)" : "STATUS_BAR",
"Landroid/view/View;-STATUS_BAR_HIDDEN-I" : "STATUS_BAR",
"Landroid/view/View;-STATUS_BAR_VISIBLE-I" : "STATUS_BAR",
"Landroid/app/StatusBarManager;-addIcon-(Ljava/lang/String; I I)" : "STATUS_BAR",
"Landroid/app/StatusBarManager;-disable-(I)" : "STATUS_BAR",
"Landroid/app/StatusBarManager;-removeIcon-(Landroid/os/IBinder;)" : "STATUS_BAR",
"Landroid/app/StatusBarManager;-updateIcon-(Landroid/os/IBinder; Ljava/lang/String; I I)" : "STATUS_BAR",
"Landroid/view/WindowManager/LayoutParams;-TYPE_STATUS_BAR-I" : "STATUS_BAR",
"Landroid/view/WindowManager/LayoutParams;-TYPE_STATUS_BAR_PANEL-I" : "STATUS_BAR",
"Landroid/view/WindowManager/LayoutParams;-systemUiVisibility-I" : "STATUS_BAR",
"Landroid/view/WindowManager/LayoutParams;-type-I" : "STATUS_BAR",
"Landroid/app/IStatusBar$Stub$Proxy;-addIcon-(Ljava/lang/String; Ljava/lang/String; I I)" : "STATUS_BAR",
"Landroid/app/IStatusBar$Stub$Proxy;-disable-(I Landroid/os/IBinder; Ljava/lang/String;)" : "STATUS_BAR",
"Landroid/app/IStatusBar$Stub$Proxy;-removeIcon-(Landroid/os/IBinder;)" : "STATUS_BAR",
"Landroid/app/IStatusBar$Stub$Proxy;-updateIcon-(Landroid/os/IBinder; Ljava/lang/String; Ljava/lang/String; I I)" : "STATUS_BAR",
"Landroid/app/IActivityManager$Stub$Proxy;-shutdown-(I)" : "SHUTDOWN",
"Landroid/os/IMountService$Stub$Proxy;-shutdow-()" : "SHUTDOWN",
"Landroid/os/storage/IMountService$Stub$Proxy;-shutdown-(Landroid/os/storage/IMountShutdownObserver;)" : "SHUTDOWN",
"Landroid/os/INetworkManagementService$Stub$Proxy;-shutdown-()" : "SHUTDOWN",
"Landroid/os/DropBoxManager;-ACTION_DROPBOX_ENTRY_ADDED-Ljava/lang/String;" : "READ_LOGS",
"Landroid/os/DropBoxManager;-getNextEntry-(Ljava/lang/String; J)" : "READ_LOGS",
"Landroid/os/DropBoxManager;-getNextEntry-(Ljava/lang/String; J)" : "READ_LOGS",
"Lcom/android/internal/os/IDropBoxManagerService$Stub$Proxy;-getNextEntry-(Ljava/lang/String; J)" : "READ_LOGS",
"Ljava/lang/Runtime;-exec-(Ljava/lang/String;)" : "READ_LOGS",
"Ljava/lang/Runtime;-exec-([Ljava/lang/String;)" : "READ_LOGS",
"Ljava/lang/Runtime;-exec-([Ljava/lang/String; [Ljava/lang/String;)" : "READ_LOGS",
"Ljava/lang/Runtime;-exec-([Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)" : "READ_LOGS",
"Ljava/lang/Runtime;-exec-(Ljava/lang/String; [Ljava/lang/String;)" : "READ_LOGS",
"Ljava/lang/Runtime;-exec-(Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)" : "READ_LOGS",
"Landroid/os/Process;-BLUETOOTH_GID-I" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-ACTION_CONNECTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-ACTION_PLAYING_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-getConnectedDevices-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-getConnectionState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-getDevicesMatchingConnectionStates-([I)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-isA2dpPlaying-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-getConnectedSinks-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-getNonDisconnectedSinks-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-getSinkPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-getSinkState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothA2dp;-isSinkConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/media/AudioManager;-ROUTE_BLUETOOTH-I" : "BLUETOOTH",
"Landroid/media/AudioManager;-ROUTE_BLUETOOTH_A2DP-I" : "BLUETOOTH",
"Landroid/media/AudioManager;-ROUTE_BLUETOOTH_SCO-I" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getConnectedSinks-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getNonDisconnectedSinks-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getSinkPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getSinkState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothSocket;-connect-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothPbap;-getClient-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothPbap;-getState-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothPbap;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/provider/Settings/System;-AIRPLANE_MODE_RADIOS-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/provider/Settings/System;-BLUETOOTH_DISCOVERABILITY-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/provider/Settings/System;-BLUETOOTH_DISCOVERABILITY_TIMEOUT-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/provider/Settings/System;-BLUETOOTH_ON-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/provider/Settings/System;-RADIO_BLUETOOTH-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/provider/Settings/System;-VOLUME_BLUETOOTH_SCO-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/provider/Settings;-ACTION_BLUETOOTH_SETTINGS-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-addRfcommServiceRecord-(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-fetchRemoteUuids-(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getAddress-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getBluetoothState-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getBondState-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getDiscoverableTimeout-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getName-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteClass-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteName-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteServiceChannel-(Ljava/lang/String; Landroid/os/ParcelUuid;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteUuids-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getScanMode-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-getTrustState-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-isDiscovering-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-isEnabled-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-listBonds-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetooth$Stub$Proxy;-removeServiceRecord-(I)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_CONNECTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_DISCOVERY_FINISHED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_DISCOVERY_STARTED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_LOCAL_NAME_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_REQUEST_DISCOVERABLE-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_REQUEST_ENABLE-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_SCAN_MODE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-ACTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-cancelDiscovery-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-disable-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-enable-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getAddress-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getBondedDevices-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getName-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getScanMode-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getState-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-isDiscovering-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-isEnabled-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-listenUsingInsecureRfcommWithServiceRecord-(Ljava/lang/String; Ljava/util/UUID;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-listenUsingRfcommWithServiceRecord-(Ljava/lang/String; Ljava/util/UUID;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-setName-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-startDiscovery-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getAddress-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getBondedDevices-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getDiscoverableTimeout-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getName-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getScanMode-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-getState-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-isDiscovering-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-isEnabled-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAdapter;-listenUsingRfcommWithServiceRecord-(Ljava/lang/String; Ljava/util/UUID;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothProfile;-getConnectedDevices-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothProfile;-getConnectionState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothProfile;-getDevicesMatchingConnectionStates-([I)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-ACTION_AUDIO_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-ACTION_CONNECTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-ACTION_VENDOR_SPECIFIC_HEADSET_EVENT-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-getConnectedDevices-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-getConnectionState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-getDevicesMatchingConnectionStates-([I)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-isAudioConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-startVoiceRecognition-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-stopVoiceRecognition-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-getBatteryUsageHint-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-getCurrentHeadset-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-getPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-getState-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-startVoiceRecognition-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothHeadset;-stopVoiceRecognition-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getBatteryUsageHint-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getCurrentHeadset-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getState-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-startVoiceRecognition-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-stopVoiceRecognition-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-ACTION_ACL_CONNECTED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-ACTION_ACL_DISCONNECTED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-ACTION_ACL_DISCONNECT_REQUESTED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-ACTION_BOND_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-ACTION_CLASS_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-ACTION_FOUND-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-ACTION_NAME_CHANGED-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-createInsecureRfcommSocketToServiceRecord-(Ljava/util/UUID;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-createRfcommSocketToServiceRecord-(Ljava/util/UUID;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-getBluetoothClass-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-getBondState-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-getName-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-createRfcommSocketToServiceRecord-(Ljava/util/UUID;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-fetchUuidsWithSdp-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-getBondState-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-getName-()" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-getServiceChannel-(Landroid/os/ParcelUuid;)" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothDevice;-getUuids-()" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-<init>-(Landroid/content/Context; Landroid/server/BluetoothService;)" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-addAudioSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-getConnectedSinks-()" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-getNonDisconnectedSinks-()" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-getSinkPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-getSinkState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-isSinkDevice-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-lookupSinksMatchingStates-([I)" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-onConnectSinkResult-(Ljava/lang/String; B)" : "BLUETOOTH",
"Landroid/server/BluetoothA2dpService;-onSinkPropertyChanged-(Ljava/lang/String; [L[Ljava/lang/Strin;)" : "BLUETOOTH",
"Landroid/provider/Settings/Secure;-BLUETOOTH_ON-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-getClient-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-getState-()" : "BLUETOOTH",
"Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-addRemoteDeviceProperties-(Ljava/lang/String; [L[Ljava/lang/Strin;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-addRfcommServiceRecord-(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-fetchRemoteUuids-(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getAddress-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getAddressFromObjectPath-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getAllProperties-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getBluetoothState-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getBondState-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getDiscoverableTimeout-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getName-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getObjectPathFromAddress-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getProperty-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getPropertyInternal-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getRemoteClass-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getRemoteName-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getRemoteServiceChannel-(Ljava/lang/String; Landroid/os/ParcelUuid;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getRemoteUuids-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getScanMode-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-getTrustState-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-isDiscovering-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-isEnabled-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-listBonds-()" : "BLUETOOTH",
"Landroid/server/BluetoothService;-removeServiceRecord-(I)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-sendUuidIntent-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-setLinkTimeout-(Ljava/lang/String; I)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-setPropertyBoolean-(Ljava/lang/String; B)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-setPropertyInteger-(Ljava/lang/String; I)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-setPropertyString-(Ljava/lang/String; Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-updateDeviceServiceChannelCache-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/server/BluetoothService;-updateRemoteDevicePropertiesCache-(Ljava/lang/String;)" : "BLUETOOTH",
"Landroid/content/pm/PackageManager;-FEATURE_BLUETOOTH-Ljava/lang/String;" : "BLUETOOTH",
"Landroid/bluetooth/BluetoothAssignedNumbers;-BLUETOOTH_SIG-I" : "BLUETOOTH",
"Landroid/app/ActivityManagerNative;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA",
"Landroid/app/ContextImpl$ApplicationPackageManager;-clearApplicationUserData-(Ljava/lang/String; LIPackageDataObserver;)" : "CLEAR_APP_USER_DATA",
"Landroid/app/ContextImpl$ApplicationPackageManager;-clearApplicationUserData-(Ljava/lang/String; LIPackageDataObserver;)" : "CLEAR_APP_USER_DATA",
"Landroid/app/ActivityManager;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA",
"Landroid/app/IActivityManager$Stub$Proxy;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA",
"Landroid/content/pm/PackageManager;-clearApplicationUserData-(Ljava/lang/String; LIPackageDataObserver;)" : "CLEAR_APP_USER_DATA",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA",
"Landroid/provider/Telephony$Sms;-addMessageToUri-(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B J)" : "WRITE_SMS",
"Landroid/provider/Telephony$Sms;-addMessageToUri-(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B)" : "WRITE_SMS",
"Landroid/provider/Telephony$Sms;-moveMessageToFolder-(Landroid/content/Context; Landroid/net/Uri; I I)" : "WRITE_SMS",
"Landroid/provider/Telephony$Sms$Outbox;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B J)" : "WRITE_SMS",
"Landroid/provider/Telephony$Sms$Draft;-saveMessage-(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String;)" : "WRITE_SMS",
"Landroid/app/IActivityManager$Stub$Proxy;-setProcessForeground-(Landroid/os/IBinder; I B)" : "SET_PROCESS_LIMIT",
"Landroid/app/IActivityManager$Stub$Proxy;-setProcessLimit-(I)" : "SET_PROCESS_LIMIT",
"Landroid/os/PowerManager;-goToSleep-(J)" : "DEVICE_POWER",
"Landroid/os/PowerManager;-setBacklightBrightness-(I)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-clearUserActivityTimeout-(J J)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-goToSleep-(J)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-goToSleepWithReason-(J I)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-preventScreenOn-(B)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-setAttentionLight-(B I)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-setBacklightBrightness-(I)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-setPokeLock-(I Landroid/os/IBinder; Ljava/lang/String;)" : "DEVICE_POWER",
"Landroid/os/IPowerManager$Stub$Proxy;-userActivityWithForce-(J B B)" : "DEVICE_POWER",
"Landroid/app/ExpandableListActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/accounts/GrantCredentialsPermissionActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/app/Activity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/app/ListActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/app/AliasActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/accounts/AccountAuthenticatorActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/app/IActivityManager$Stub$Proxy;-setPersistent-(Landroid/os/IBinder; B)" : "PERSISTENT_ACTIVITY",
"Landroid/app/TabActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/app/ActivityGroup;-setPersistent-(B)" : "PERSISTENT_ACTIVITY",
"Landroid/view/IWindowManager$Stub$Proxy;-addAppToken-(I Landroid/view/IApplicationToken; I I B)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-addWindowToken-(Landroid/os/IBinder; I)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-executeAppTransition-()" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-moveAppToken-(I Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-moveAppTokensToBottom-(Ljava/util/List;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-moveAppTokensToTop-(Ljava/util/List;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-pauseKeyDispatching-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-prepareAppTransition-(I)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-removeAppToken-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-removeWindowToken-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-resumeKeyDispatching-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setAppGroupId-(Landroid/os/IBinder; I)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setAppOrientation-(Landroid/view/IApplicationToken; I)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setAppStartingWindow-(Landroid/os/IBinder; Ljava/lang/String; I Ljava/lang/CharSequence; I I Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setAppVisibility-(Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setAppWillBeHidden-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setEventDispatching-(B)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setFocusedApp-(Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-setNewConfiguration-(Landroid/content/res/Configuration;)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-startAppFreezingScreen-(Landroid/os/IBinder; I)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-stopAppFreezingScreen-(Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS",
"Landroid/view/IWindowManager$Stub$Proxy;-updateOrientationFromAppTokens-(Landroid/content/res/Configuration; Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS",
"Landroid/provider/Browser;-BOOKMARKS_URI-Landroid/net/Uri;" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-SEARCHES_URI-Landroid/net/Uri;" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-addSearchUrl-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-clearHistory-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-clearSearches-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-deleteFromHistory-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-deleteHistoryTimeFrame-(Landroid/content/ContentResolver; J J)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-truncateHistory-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-updateVisitedHistory-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/provider/Browser;-clearSearches-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS",
"Landroid/app/IActivityManager$Stub$Proxy;-unhandledBack-(I)" : "FORCE_BACK",
"Landroid/net/IConnectivityManager$Stub$Proxy;-requestRouteToHost-(I I)" : "CHANGE_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-setMobileDataEnabled-(B)" : "CHANGE_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-setNetworkPreference-(I)" : "CHANGE_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-setRadio-(I B)" : "CHANGE_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-setRadios-(B)" : "CHANGE_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-stopUsingNetworkFeature-(I Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-tether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/net/IConnectivityManager$Stub$Proxy;-untether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-requestRouteToHost-(I I)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-setMobileDataEnabled-(B)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-setNetworkPreference-(I)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-setRadio-(I B)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-setRadios-(B)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-startUsingNetworkFeature-(I Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-stopUsingNetworkFeature-(I Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-tether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/net/ConnectivityManager;-untether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-attachPppd-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-detachPppd-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-disableNat-(Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-enableNat-(Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-setAccessPoint-(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-setInterfaceThrottle-(Ljava/lang/String; I I)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-setIpForwardingEnabled-(B)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-startAccessPoint-(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-startUsbRNDIS-()" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-stopAccessPoint-()" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-stopTethering-()" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-stopUsbRNDIS-()" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-tetherInterface-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-unregisterObserver-(Landroid/net/INetworkManagementEventObserver;)" : "CHANGE_NETWORK_STATE",
"Landroid/os/INetworkManagementService$Stub$Proxy;-untetherInterface-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE",
"Landroid/app/ContextImpl$ApplicationContentResolver;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentService;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentService;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentService;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentService;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentService;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/ContentResolver;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS",
"Landroid/content/IContentService$Stub$Proxy;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS",
"Landroid/accounts/AccountManager;-KEY_ACCOUNT_MANAGER_RESPONSE-Ljava/lang/String;" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-checkBinderPermission-()" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-confirmCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-editProperties-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-getAccountRemovalAllowed-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-getAuthToken-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-getAuthTokenLabel-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-hasFeatures-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-updateCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator;-addAccount-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-addAccount-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-confirmCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-editProperties-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-getAccountRemovalAllowed-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-getAuthToken-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-getAuthTokenLabel-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-hasFeatures-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/AbstractAccountAuthenticator$Transport;-updateCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-addAccount-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-confirmCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-editProperties-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-getAccountRemovalAllowed-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-getAuthToken-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-getAuthTokenLabel-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-hasFeatures-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "ACCOUNT_MANAGER",
"Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-updateCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER",
"Landroid/view/IWindowManager$Stub$Proxy;-setAnimationScale-(I F)" : "SET_ANIMATION_SCALE",
"Landroid/view/IWindowManager$Stub$Proxy;-setAnimationScales-([L;)" : "SET_ANIMATION_SCALE",
"Landroid/accounts/AccountManager;-getAccounts-()" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-getAccountsByType-(Ljava/lang/String;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-getAccountsByTypeAndFeatures-(Ljava/lang/String; [Ljava/lang/String; [Landroid/accounts/AccountManagerCallback<android/accounts/Account[; Landroid/os/Handler;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-hasFeatures-(Landroid/accounts/Account; [Ljava/lang/String; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-addOnAccountsUpdatedListener-(Landroid/accounts/OnAccountsUpdateListener; Landroid/os/Handler; B)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-getAccounts-()" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-getAccountsByType-(Ljava/lang/String;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-getAccountsByTypeAndFeatures-(Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-getAuthTokenByFeatures-(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager;-hasFeatures-(Landroid/accounts/Account; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "GET_ACCOUNTS",
"Landroid/content/ContentService;-<init>-(Landroid/content/Context; B)" : "GET_ACCOUNTS",
"Landroid/content/ContentService;-main-(Landroid/content/Context; B)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;-doWork-()" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;-start-()" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager$AmsTask;-doWork-()" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManager$AmsTask;-start-()" : "GET_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-getAccounts-(Ljava/lang/String;)" : "GET_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-getAccountsByFeatures-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS",
"Landroid/accounts/IAccountManager$Stub$Proxy;-hasFeatures-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-checkReadAccountsPermission-()" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-getAccounts-(Ljava/lang/String;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-getAccountsByFeatures-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS",
"Landroid/accounts/AccountManagerService;-hasFeatures-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS",
"Landroid/telephony/gsm/SmsManager;-copyMessageToSim-([L; [L; I)" : "RECEIVE_SMS",
"Landroid/telephony/gsm/SmsManager;-deleteMessageFromSim-(I)" : "RECEIVE_SMS",
"Landroid/telephony/gsm/SmsManager;-getAllMessagesFromSim-()" : "RECEIVE_SMS",
"Landroid/telephony/gsm/SmsManager;-updateMessageOnSim-(I I [L;)" : "RECEIVE_SMS",
"Landroid/telephony/SmsManager;-copyMessageToIcc-([L; [L; I)" : "RECEIVE_SMS",
"Landroid/telephony/SmsManager;-deleteMessageFromIcc-(I)" : "RECEIVE_SMS",
"Landroid/telephony/SmsManager;-getAllMessagesFromIcc-()" : "RECEIVE_SMS",
"Landroid/telephony/SmsManager;-updateMessageOnIcc-(I I [L;)" : "RECEIVE_SMS",
"Lcom/android/internal/telephony/ISms$Stub$Proxy;-copyMessageToIccEf-(I [B [B)" : "RECEIVE_SMS",
"Lcom/android/internal/telephony/ISms$Stub$Proxy;-getAllMessagesFromIccEf-()" : "RECEIVE_SMS",
"Lcom/android/internal/telephony/ISms$Stub$Proxy;-updateMessageOnIccEf-(I I [B)" : "RECEIVE_SMS",
"Landroid/app/IActivityManager$Stub$Proxy;-resumeAppSwitches-()" : "STOP_APP_SWITCHES",
"Landroid/app/IActivityManager$Stub$Proxy;-stopAppSwitches-()" : "STOP_APP_SWITCHES",
"Landroid/app/ContextImpl$ApplicationPackageManager;-deleteApplicationCacheFiles-(Ljava/lang/String; LIPackageDataObserver;)" : "DELETE_CACHE_FILES",
"Landroid/app/ContextImpl$ApplicationPackageManager;-deleteApplicationCacheFiles-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "DELETE_CACHE_FILES",
"Landroid/content/pm/PackageManager;-deleteApplicationCacheFiles-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "DELETE_CACHE_FILES",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-deleteApplicationCacheFiles-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "DELETE_CACHE_FILES",
"Landroid/os/Build/VERSION_CODES;-DONUT-I" : "WRITE_EXTERNAL_STORAGE",
"Landroid/app/DownloadManager/Request;-setDestinationUri-(Landroid/net/Uri;)" : "WRITE_EXTERNAL_STORAGE",
"Landroid/os/RecoverySystem;-installPackage-(Landroid/content/Context; Ljava/io/File;)" : "REBOOT",
"Landroid/os/RecoverySystem;-rebootWipeUserData-(Landroid/content/Context;)" : "REBOOT",
"Landroid/os/RecoverySystem;-bootCommand-(Landroid/content/Context; Ljava/lang/String;)" : "REBOOT",
"Landroid/os/RecoverySystem;-installPackage-(Landroid/content/Context; Ljava/io/File;)" : "REBOOT",
"Landroid/os/RecoverySystem;-rebootWipeUserData-(Landroid/content/Context;)" : "REBOOT",
"Landroid/content/Intent;-IntentResolution-Ljava/lang/String;" : "REBOOT",
"Landroid/content/Intent;-ACTION_REBOOT-Ljava/lang/String;" : "REBOOT",
"Landroid/os/PowerManager;-reboot-(Ljava/lang/String;)" : "REBOOT",
"Landroid/os/PowerManager;-reboot-(Ljava/lang/String;)" : "REBOOT",
"Landroid/os/IPowerManager$Stub$Proxy;-crash-(Ljava/lang/String;)" : "REBOOT",
"Landroid/os/IPowerManager$Stub$Proxy;-reboot-(Ljava/lang/String;)" : "REBOOT",
"Landroid/app/ContextImpl$ApplicationPackageManager;-installPackage-(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES",
"Landroid/app/ContextImpl$ApplicationPackageManager;-installPackage-(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES",
"Landroid/content/pm/PackageManager;-installPackage-(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES",
"Landroid/content/pm/IPackageManager$Stub$Proxy;-installPackage-(Landroid/net/Uri; Landroid/content/pm/IPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES",
"Landroid/app/IActivityManager$Stub$Proxy;-setDebugApp-(Ljava/lang/String; B B)" : "SET_DEBUG_APP",
"Landroid/location/ILocationManager$Stub$Proxy;-reportLocation-(Landroid/location/Location; B)" : "INSTALL_LOCATION_PROVIDER",
"Landroid/app/WallpaperManager;-suggestDesiredDimensions-(I I)" : "SET_WALLPAPER_HINTS",
"Landroid/app/IWallpaperManager$Stub$Proxy;-setDimensionHints-(I I)" : "SET_WALLPAPER_HINTS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-openFileDescriptor-(Landroid/net/Uri; Ljava/lang/String;)" : "READ_CONTACTS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-openInputStream-(Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-openOutputStream-(Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/app/ContextImpl$ApplicationContentResolver;-query-(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)" : "READ_CONTACTS",
"Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;-getAdnRecordsInEf-(I)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-addToGroup-(Landroid/content/ContentResolver; J Ljava/lang/String;)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-addToMyContactsGroup-(Landroid/content/ContentResolver; J)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-createPersonInMyContactsGroup-(Landroid/content/ContentResolver; Landroid/content/ContentValues;)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-loadContactPhoto-(Landroid/content/Context; Landroid/net/Uri; I Landroid/graphics/BitmapFactory$Options;)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-markAsContacted-(Landroid/content/ContentResolver; J)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-openContactPhotoInputStream-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-queryGroups-(Landroid/content/ContentResolver; J)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-setPhotoData-(Landroid/content/ContentResolver; Landroid/net/Uri; [L;)" : "READ_CONTACTS",
"Landroid/provider/Contacts$People;-tryGetMyContactsGroupId-(Landroid/content/ContentResolver;)" : "READ_CONTACTS",
"Landroid/provider/ContactsContract$Data;-getContactLookupUri-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/provider/ContactsContract$Contacts;-getLookupUri-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/provider/ContactsContract$Contacts;-lookupContact-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/provider/ContactsContract$Contacts;-openContactPhotoInputStream-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/pim/vcard/VCardComposer;-createOneEntry-()" : "READ_CONTACTS",
"Landroid/pim/vcard/VCardComposer;-createOneEntry-(Ljava/lang/reflect/Method;)" : "READ_CONTACTS",
"Landroid/pim/vcard/VCardComposer;-createOneEntryInternal-(Ljava/lang/String; Ljava/lang/reflect/Method;)" : "READ_CONTACTS",
"Landroid/pim/vcard/VCardComposer;-init-()" : "READ_CONTACTS",
"Landroid/pim/vcard/VCardComposer;-init-(Ljava/lang/String; [L[Ljava/lang/Strin;)" : "READ_CONTACTS",
"Landroid/pim/vcard/VCardComposer$OneEntryHandler;-onInit-(Landroid/content/Context;)" : "READ_CONTACTS",
"Lcom/android/internal/telephony/CallerInfo;-getCallerId-(Landroid/content/Context; Ljava/lang/String;)" : "READ_CONTACTS",
"Lcom/android/internal/telephony/CallerInfo;-getCallerInfo-(Landroid/content/Context; Ljava/lang/String;)" : "READ_CONTACTS",
"Landroid/provider/Contacts$Settings;-getSetting-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)" : "READ_CONTACTS",
"Landroid/provider/ContactsContract$RawContacts;-getContactLookupUri-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/provider/CallLog$Calls;-addCall-(Lcom/android/internal/telephony/CallerInfo; Landroid/content/Context; Ljava/lang/String; I I J I)" : "READ_CONTACTS",
"Landroid/provider/CallLog$Calls;-getLastOutgoingCall-(Landroid/content/Context;)" : "READ_CONTACTS",
"Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;-getAdnRecordsInEf-(I)" : "READ_CONTACTS",
"Landroid/pim/vcard/VCardComposer$HandlerForOutputStream;-onInit-(Landroid/content/Context;)" : "READ_CONTACTS",
"Landroid/provider/ContactsContract$CommonDataKinds$Phone;-CONTENT_URI-Landroid/net/Uri;" : "READ_CONTACTS",
"Landroid/widget/QuickContactBadge;-assignContactFromEmail-(Ljava/lang/String; B)" : "READ_CONTACTS",
"Landroid/widget/QuickContactBadge;-assignContactFromPhone-(Ljava/lang/String; B)" : "READ_CONTACTS",
"Landroid/widget/QuickContactBadge;-trigger-(Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/content/ContentResolver;-openFileDescriptor-(Landroid/net/Uri; Ljava/lang/String;)" : "READ_CONTACTS",
"Landroid/content/ContentResolver;-openInputStream-(Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/content/ContentResolver;-openOutputStream-(Landroid/net/Uri;)" : "READ_CONTACTS",
"Landroid/content/ContentResolver;-query-(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)" : "READ_CONTACTS",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-backupNow-()" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-beginRestoreSession-(Ljava/lang/String;)" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-clearBackupData-(Ljava/lang/String;)" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-dataChanged-(Ljava/lang/String;)" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-getCurrentTransport-()" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-isBackupEnabled-()" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-listAllTransports-()" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-selectBackupTransport-(Ljava/lang/String;)" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-setAutoRestore-(B)" : "BACKUP",
"Landroid/app/backup/IBackupManager$Stub$Proxy;-setBackupEnabled-(B)" : "BACKUP",
"Landroid/app/IActivityManager$Stub$Proxy;-bindBackupAgent-(Landroid/content/pm/ApplicationInfo; I)" : "BACKUP",
"Landroid/app/backup/BackupManager;-beginRestoreSession-()" : "BACKUP",
"Landroid/app/backup/BackupManager;-dataChanged-(Ljava/lang/String;)" : "BACKUP",
"Landroid/app/backup/BackupManager;-requestRestore-(Landroid/app/backup/RestoreObserver;)" : "BACKUP",
}
|
4talesa/rethinkdb
|
refs/heads/next
|
external/re2_20140111/re2/make_unicode_groups.py
|
121
|
#!/usr/bin/python
# Copyright 2008 The RE2 Authors. All Rights Reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Generate C++ tables for Unicode Script and Category groups."""
import sys
import unicode
_header = """
// GENERATED BY make_unicode_groups.py; DO NOT EDIT.
// make_unicode_groups.py >unicode_groups.cc
#include "re2/unicode_groups.h"
namespace re2 {
"""
_trailer = """
} // namespace re2
"""
n16 = 0
n32 = 0
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges
def PrintRanges(type, name, ranges):
"""Print the ranges as an array of type named name."""
print "static const %s %s[] = {" % (type, name,)
for lo, hi in ranges:
print "\t{ %d, %d }," % (lo, hi)
print "};"
# def PrintCodes(type, name, codes):
# """Print the codes as an array of type named name."""
# print "static %s %s[] = {" % (type, name,)
# for c in codes:
# print "\t%d," % (c,)
# print "};"
def PrintGroup(name, codes):
"""Print the data structures for the group of codes.
Return a UGroup literal for the group."""
# See unicode_groups.h for a description of the data structure.
# Split codes into 16-bit ranges and 32-bit ranges.
range16 = MakeRanges([c for c in codes if c < 65536])
range32 = MakeRanges([c for c in codes if c >= 65536])
# Pull singleton ranges out of range16.
# code16 = [lo for lo, hi in range16 if lo == hi]
# range16 = [[lo, hi] for lo, hi in range16 if lo != hi]
global n16
global n32
n16 += len(range16)
n32 += len(range32)
ugroup = "{ \"%s\", +1" % (name,)
# if len(code16) > 0:
# PrintCodes("uint16", name+"_code16", code16)
# ugroup += ", %s_code16, %d" % (name, len(code16))
# else:
# ugroup += ", 0, 0"
if len(range16) > 0:
PrintRanges("URange16", name+"_range16", range16)
ugroup += ", %s_range16, %d" % (name, len(range16))
else:
ugroup += ", 0, 0"
if len(range32) > 0:
PrintRanges("URange32", name+"_range32", range32)
ugroup += ", %s_range32, %d" % (name, len(range32))
else:
ugroup += ", 0, 0"
ugroup += " }"
return ugroup
def main():
print _header
ugroups = []
for name, codes in unicode.Categories().iteritems():
ugroups.append(PrintGroup(name, codes))
for name, codes in unicode.Scripts().iteritems():
ugroups.append(PrintGroup(name, codes))
print "// %d 16-bit ranges, %d 32-bit ranges" % (n16, n32)
print "const UGroup unicode_groups[] = {";
ugroups.sort()
for ug in ugroups:
print "\t%s," % (ug,)
print "};"
print "const int num_unicode_groups = %d;" % (len(ugroups),)
print _trailer
if __name__ == '__main__':
main()
|
qt-haiku/LibreOffice
|
refs/heads/master
|
wizards/com/sun/star/wizards/web/data/CGPublish.py
|
9
|
#
# This file is part of the LibreOffice project.
#
# 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/.
#
# This file incorporates work covered by the following license notice:
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed
# with this work for additional information regarding copyright
# ownership. The ASF licenses this file to you under the Apache
# License, Version 2.0 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0 .
#
from ...common.ConfigGroup import ConfigGroup
'''
A Class which describes the publishing arguments
in a session.
Each session can contain different publishers, which are configured
through such a CGPublish object.
'''
class CGPublish(ConfigGroup):
def __init__(self):
self.cp_Publish = bool()
self.cp_URL = str()
self.cp_Username = str()
self.password = str()
self.overwriteApproved = bool()
self.url = str()
def setURL(self, path):
try:
self.cp_URL = self.root.getFileAccess().getURL(path)
self.overwriteApproved = False
except Exception as ex:
ex.printStackTrace()
def getURL(self):
try:
return self.root.getFileAccess().getPath(self.cp_URL, None)
except Exception as e:
e.printStackTrace()
return ""
|
sourcefabric/Booktype
|
refs/heads/master
|
lib/booki/editor/south_migrations/0021_auto__chg_field_license_url.py
|
8
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'License.url'
db.alter_column(u'editor_license', 'url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True))
def backwards(self, orm):
# Changing field 'License.url'
db.alter_column(u'editor_license', 'url', self.gf('django.db.models.fields.URLField')(default='', max_length=200))
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'editor.attachment': {
'Meta': {'object_name': 'Attachment'},
'attachment': ('django.db.models.fields.files.FileField', [], {'max_length': '2500'}),
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'status': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookStatus']"}),
'version': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookVersion']"})
},
u'editor.attributionexclude': {
'Meta': {'object_name': 'AttributionExclude'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']", 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'editor.book': {
'Meta': {'object_name': 'Book'},
'cover': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'description': ('django.db.models.fields.TextField', [], {'default': "''"}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookiGroup']", 'null': 'True'}),
'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Language']", 'null': 'True'}),
'license': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.License']", 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'permission': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'published': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'status': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'status'", 'null': 'True', 'to': u"orm['editor.BookStatus']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '2500'}),
'url_title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '2500'}),
'version': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'version'", 'null': 'True', 'to': u"orm['editor.BookVersion']"})
},
u'editor.bookcover': {
'Meta': {'object_name': 'BookCover'},
'approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'attachment': ('django.db.models.fields.files.FileField', [], {'max_length': '2500'}),
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']", 'null': 'True'}),
'booksize': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'cid': ('django.db.models.fields.CharField', [], {'default': "''", 'unique': 'True', 'max_length': '40'}),
'cover_type': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {}),
'creator': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
'filename': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '250'}),
'height': ('django.db.models.fields.IntegerField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_book': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_ebook': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_pdf': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'license': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.License']", 'null': 'True'}),
'notes': ('django.db.models.fields.TextField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '250'}),
'unit': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'width': ('django.db.models.fields.IntegerField', [], {'blank': 'True'})
},
u'editor.bookhistory': {
'Meta': {'object_name': 'BookHistory'},
'args': ('django.db.models.fields.CharField', [], {'max_length': '2500'}),
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
'chapter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Chapter']", 'null': 'True'}),
'chapter_history': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.ChapterHistory']", 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'kind': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'version': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookVersion']", 'null': 'True'})
},
u'editor.bookigroup': {
'Meta': {'object_name': 'BookiGroup'},
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'members': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'members'", 'blank': 'True', 'to': u"orm['auth.User']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'url_name': ('django.db.models.fields.CharField', [], {'max_length': '300'})
},
u'editor.bookipermission': {
'Meta': {'object_name': 'BookiPermission'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']", 'null': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookiGroup']", 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permission': ('django.db.models.fields.SmallIntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'editor.booknotes': {
'Meta': {'object_name': 'BookNotes'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notes': ('django.db.models.fields.TextField', [], {})
},
u'editor.bookstatus': {
'Meta': {'object_name': 'BookStatus'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
'weight': ('django.db.models.fields.SmallIntegerField', [], {})
},
u'editor.booktoc': {
'Meta': {'object_name': 'BookToc'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
'chapter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Chapter']", 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '2500', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookToc']", 'null': 'True', 'blank': 'True'}),
'typeof': ('django.db.models.fields.SmallIntegerField', [], {}),
'version': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookVersion']"}),
'weight': ('django.db.models.fields.IntegerField', [], {})
},
u'editor.bookversion': {
'Meta': {'object_name': 'BookVersion'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'major': ('django.db.models.fields.IntegerField', [], {}),
'minor': ('django.db.models.fields.IntegerField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'})
},
u'editor.chapter': {
'Meta': {'object_name': 'Chapter'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
'content': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'revision': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'status': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookStatus']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '2500'}),
'url_title': ('django.db.models.fields.CharField', [], {'max_length': '2500'}),
'version': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.BookVersion']"})
},
u'editor.chapterhistory': {
'Meta': {'object_name': 'ChapterHistory'},
'chapter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Chapter']"}),
'comment': ('django.db.models.fields.CharField', [], {'max_length': '2500', 'blank': 'True'}),
'content': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'revision': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'editor.info': {
'Meta': {'object_name': 'Info'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'kind': ('django.db.models.fields.SmallIntegerField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '2500', 'db_index': 'True'}),
'value_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'value_integer': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'value_string': ('django.db.models.fields.CharField', [], {'max_length': '2500', 'null': 'True'}),
'value_text': ('django.db.models.fields.TextField', [], {'null': 'True'})
},
u'editor.language': {
'Meta': {'object_name': 'Language'},
'abbrevation': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'editor.license': {
'Meta': {'object_name': 'License'},
'abbrevation': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'editor.publishwizzard': {
'Meta': {'unique_together': "(('book', 'user', 'wizz_type'),)", 'object_name': 'PublishWizzard'},
'book': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['editor.Book']", 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'wizz_options': ('django.db.models.fields.TextField', [], {'default': "''"}),
'wizz_type': ('django.db.models.fields.CharField', [], {'max_length': '20'})
}
}
complete_apps = ['editor']
|
liorvh/golismero
|
refs/heads/master
|
doc/plugins/source/conf.py
|
8
|
# -*- coding: utf-8 -*-
#
# golismero documentation build configuration file, created by
# sphinx-quickstart on Mon May 27 16:39:33 2013.
#
# 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, os.path, warnings
# 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(os.path.join('..', '..', '..')))
sys.path.append(os.path.abspath(os.path.join('..', '..', '..', 'thirdparty_libs')))
# Workaround for docutils bug, see:
# http://sourceforge.net/p/docutils/bugs/228/
try:
import standalone
except ImportError:
standalone = None
if standalone is not None:
sentinel = object()
old_standalone = sys.modules.get("standalone", sentinel)
with warnings.catch_warnings(record=True):
from docutils.readers import standalone
sys.modules["standalone"] = standalone
# Autogenerate the rst files on the first run.
if not os.path.exists("index.rst"):
sys.path.append(os.path.abspath("."))
from gen import gen
gen()
# -- 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.coverage', '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'GoLismero'
copyright = u'2013, GoLismero Project'
# 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 = '2.0'
# The full version, including alpha/beta/rc tags.
#release = '2.0.1'
from golismero import __version__ as release
version = release[:3]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = "en"
# 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 = []
# 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 = 'default'
# 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 = []
# 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 = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# 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 = None
# 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 = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# 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 = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# 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 = 'golismerodoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'golismero.tex', u'GoLismero Documentation',
u'golismero-project', '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
# 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', 'golismero', u'GoLismero Documentation',
[u'golismero-project'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'golismero', u'GoLismero Documentation',
u'golismero-project', 'golismero', 'GoLismero project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'GoLismero'
epub_author = u'GoLismero Project'
epub_publisher = u'Golismero Project'
epub_copyright = u'2013, Golismero Project'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
|
wangdeshui/zulip
|
refs/heads/master
|
zerver/lib/mention.py
|
125
|
from __future__ import absolute_import
# Match multi-word string between @** ** or match any one-word
# sequences after @
find_mentions = r'(?<![^\s\'\"\(,:<])@(?:\*\*([^\*]+)\*\*|(\w+))'
wildcards = ['all', 'everyone']
def user_mention_matches_wildcard(mention):
return mention in wildcards
|
gh0std4ncer/thug
|
refs/heads/master
|
src/ActiveX/modules/CABrightStor.py
|
8
|
# CA BrightStor
# CVE-NOMATCH
import logging
log = logging.getLogger("Thug")
def AddColumn(self, arg0, arg1):
if len(arg0) > 100:
log.ThugLogging.log_exploit_event(self._window.url,
"CA BrightStor ActiveX",
"Overflow in AddColumn")
|
praveenaki/zulip
|
refs/heads/master
|
zerver/lib/actions.py
|
114
|
from __future__ import absolute_import
from django.conf import settings
from django.core import validators
from django.contrib.sessions.models import Session
from zerver.lib.cache import flush_user_profile
from zerver.lib.context_managers import lockfile
from zerver.models import Realm, RealmEmoji, Stream, UserProfile, UserActivity, \
Subscription, Recipient, Message, UserMessage, valid_stream_name, \
DefaultStream, UserPresence, Referral, PushDeviceToken, MAX_SUBJECT_LENGTH, \
MAX_MESSAGE_LENGTH, get_client, get_stream, get_recipient, get_huddle, \
get_user_profile_by_id, PreregistrationUser, get_display_recipient, \
to_dict_cache_key, get_realm, stringify_message_dict, bulk_get_recipients, \
resolve_email_to_domain, email_to_username, display_recipient_cache_key, \
get_stream_cache_key, to_dict_cache_key_id, \
UserActivityInterval, get_active_user_dicts_in_realm, get_active_streams, \
realm_filters_for_domain, RealmFilter, receives_offline_notifications, \
ScheduledJob, realm_filters_for_domain, RealmFilter, get_active_bot_dicts_in_realm
from zerver.lib.avatar import get_avatar_url, avatar_url
from guardian.shortcuts import assign_perm, remove_perm
from django.db import transaction, IntegrityError
from django.db.models import F, Q
from django.core.exceptions import ValidationError
from django.utils.importlib import import_module
from django.core.mail import EmailMessage
from django.utils.timezone import now
from confirmation.models import Confirmation
session_engine = import_module(settings.SESSION_ENGINE)
from zerver.lib.create_user import random_api_key
from zerver.lib.initial_password import initial_password
from zerver.lib.timestamp import timestamp_to_datetime, datetime_to_timestamp
from zerver.lib.cache_helpers import cache_save_message
from zerver.lib.queue import queue_json_publish
from django.utils import timezone
from zerver.lib.create_user import create_user
from zerver.lib import bugdown
from zerver.lib.cache import cache_with_key, cache_set, \
user_profile_by_email_cache_key, cache_set_many, \
cache_delete, cache_delete_many, message_cache_key
from zerver.decorator import get_user_profile_by_email, JsonableError, \
statsd_increment
from zerver.lib.event_queue import request_event_queue, get_user_events, send_event
from zerver.lib.utils import log_statsd_event, statsd
from zerver.lib.html_diff import highlight_html_differences
from zerver.lib.alert_words import user_alert_words, add_user_alert_words, \
remove_user_alert_words, set_user_alert_words
from zerver.lib.push_notifications import num_push_devices_for_user, \
send_apple_push_notification, send_android_push_notification
from zerver.lib.notifications import clear_followup_emails_queue
from zerver.lib.narrow import check_supported_events_narrow_filter
from zerver.lib.session_user import get_session_user
import DNS
import ujson
import time
import traceback
import re
import datetime
import os
import platform
import logging
import itertools
from collections import defaultdict
# Store an event in the log for re-importing messages
def log_event(event):
if settings.EVENT_LOG_DIR is None:
return
if "timestamp" not in event:
event["timestamp"] = time.time()
if not os.path.exists(settings.EVENT_LOG_DIR):
os.mkdir(settings.EVENT_LOG_DIR)
template = os.path.join(settings.EVENT_LOG_DIR,
'%s.' + platform.node()
+ datetime.datetime.now().strftime('.%Y-%m-%d'))
with lockfile(template % ('lock',)):
with open(template % ('events',), 'a') as log:
log.write(ujson.dumps(event) + '\n')
def active_user_ids(realm):
return [userdict['id'] for userdict in get_active_user_dicts_in_realm(realm)]
def stream_user_ids(stream):
subscriptions = Subscription.objects.filter(recipient__type=Recipient.STREAM,
recipient__type_id=stream.id)
if stream.invite_only:
subscriptions = subscriptions.filter(active=True)
return [sub['user_profile_id'] for sub in subscriptions.values('user_profile_id')]
def bot_owner_userids(user_profile):
is_private_bot = (
user_profile.default_sending_stream and user_profile.default_sending_stream.invite_only or
user_profile.default_events_register_stream and user_profile.default_events_register_stream.invite_only)
if is_private_bot:
return (user_profile.bot_owner_id,)
else:
return active_user_ids(user_profile.realm)
def notify_created_user(user_profile):
event = dict(type="realm_user", op="add",
person=dict(email=user_profile.email,
is_admin=user_profile.is_admin(),
full_name=user_profile.full_name,
is_bot=user_profile.is_bot))
send_event(event, active_user_ids(user_profile.realm))
def notify_created_bot(user_profile):
def stream_name(stream):
if not stream:
return None
return stream.name
default_sending_stream_name = stream_name(user_profile.default_sending_stream)
default_events_register_stream_name = stream_name(user_profile.default_events_register_stream)
event = dict(type="realm_bot", op="add",
bot=dict(email=user_profile.email,
full_name=user_profile.full_name,
api_key=user_profile.api_key,
default_sending_stream=default_sending_stream_name,
default_events_register_stream=default_events_register_stream_name,
default_all_public_streams=user_profile.default_all_public_streams,
avatar_url=avatar_url(user_profile),
owner=user_profile.bot_owner.email,
))
send_event(event, bot_owner_userids(user_profile))
def do_create_user(email, password, realm, full_name, short_name,
active=True, bot=False, bot_owner=None,
avatar_source=UserProfile.AVATAR_FROM_GRAVATAR,
default_sending_stream=None, default_events_register_stream=None,
default_all_public_streams=None):
event = {'type': 'user_created',
'timestamp': time.time(),
'full_name': full_name,
'short_name': short_name,
'user': email,
'domain': realm.domain,
'bot': bot}
if bot:
event['bot_owner'] = bot_owner.email
log_event(event)
user_profile = create_user(email=email, password=password, realm=realm,
full_name=full_name, short_name=short_name,
active=active, bot=bot, bot_owner=bot_owner,
avatar_source=avatar_source,
default_sending_stream=default_sending_stream,
default_events_register_stream=default_events_register_stream,
default_all_public_streams=default_all_public_streams)
notify_created_user(user_profile)
if bot:
notify_created_bot(user_profile)
return user_profile
def user_sessions(user_profile):
return [s for s in Session.objects.all()
if get_session_user(s) == user_profile.id]
def delete_session(session):
return session_engine.SessionStore(session.session_key).delete()
def delete_user_sessions(user_profile):
for session in Session.objects.all():
if get_session_user(session) == user_profile.id:
delete_session(session)
def delete_realm_user_sessions(realm):
realm_user_ids = [user_profile.id for user_profile in
UserProfile.objects.filter(realm=realm)]
for session in Session.objects.filter(expire_date__gte=datetime.datetime.now()):
if get_session_user(session) in realm_user_ids:
delete_session(session)
def delete_all_user_sessions():
for session in Session.objects.all():
delete_session(session)
def active_humans_in_realm(realm):
return UserProfile.objects.filter(realm=realm, is_active=True, is_bot=False)
def do_set_realm_name(realm, name):
realm.name = name
realm.save(update_fields=['name'])
event = dict(
type="realm",
op="update",
property='name',
value=name,
)
send_event(event, active_user_ids(realm))
return {}
def get_realm_name(domain):
realm = Realm.objects.get(domain=domain)
return realm.name
def do_set_realm_restricted_to_domain(realm, restricted):
realm.restricted_to_domain = restricted
realm.save(update_fields=['restricted_to_domain'])
event = dict(
type="realm",
op="update",
property='restricted_to_domain',
value=restricted,
)
send_event(event, active_user_ids(realm))
return {}
def do_set_realm_invite_required(realm, invite_required):
realm.invite_required = invite_required
realm.save(update_fields=['invite_required'])
event = dict(
type="realm",
op="update",
property='invite_required',
value=invite_required,
)
send_event(event, active_user_ids(realm))
return {}
def do_set_realm_invite_by_admins_only(realm, invite_by_admins_only):
realm.invite_by_admins_only = invite_by_admins_only
realm.save(update_fields=['invite_by_admins_only'])
event = dict(
type="realm",
op="update",
property='invite_by_admins_only',
value=invite_by_admins_only,
)
send_event(event, active_user_ids(realm))
return {}
def do_deactivate_realm(realm):
"""
Deactivate this realm. Do NOT deactivate the users -- we need to be able to
tell the difference between users that were intentionally deactivated,
e.g. by a realm admin, and users who can't currently use Zulip because their
realm has been deactivated.
"""
if realm.deactivated:
return
realm.deactivated = True
realm.save(update_fields=["deactivated"])
for user in active_humans_in_realm(realm):
# Don't deactivate the users, but do delete their sessions so they get
# bumped to the login screen, where they'll get a realm deactivation
# notice when they try to log in.
delete_user_sessions(user)
def do_deactivate_user(user_profile, log=True, _cascade=True):
if not user_profile.is_active:
return
user_profile.is_active = False;
user_profile.save(update_fields=["is_active"])
delete_user_sessions(user_profile)
if log:
log_event({'type': 'user_deactivated',
'timestamp': time.time(),
'user': user_profile.email,
'domain': user_profile.realm.domain})
event = dict(type="realm_user", op="remove",
person=dict(email=user_profile.email,
full_name=user_profile.full_name))
send_event(event, active_user_ids(user_profile.realm))
if user_profile.is_bot:
event = dict(type="realm_bot", op="remove",
bot=dict(email=user_profile.email,
full_name=user_profile.full_name))
send_event(event, bot_owner_userids(user_profile))
if _cascade:
bot_profiles = UserProfile.objects.filter(is_bot=True, is_active=True,
bot_owner=user_profile)
for profile in bot_profiles:
do_deactivate_user(profile, _cascade=False)
def do_deactivate_stream(stream, log=True):
user_profiles = UserProfile.objects.filter(realm=stream.realm)
for user_profile in user_profiles:
do_remove_subscription(user_profile, stream)
was_invite_only = stream.invite_only
stream.deactivated = True
stream.invite_only = True
# Preserve as much as possible the original stream name while giving it a
# special prefix that both indicates that the stream is deactivated and
# frees up the original name for reuse.
old_name = stream.name
new_name = ("!DEACTIVATED:" + old_name)[:Stream.MAX_NAME_LENGTH]
for i in range(20):
existing_deactivated_stream = get_stream(new_name, stream.realm)
if existing_deactivated_stream:
# This stream has alrady been deactivated, keep prepending !s until
# we have a unique stream name or you've hit a rename limit.
new_name = ("!" + new_name)[:Stream.MAX_NAME_LENGTH]
else:
break
# If you don't have a unique name at this point, this will fail later in the
# code path.
stream.name = new_name[:Stream.MAX_NAME_LENGTH]
stream.save()
# Remove the old stream information from memcached.
old_cache_key = get_stream_cache_key(old_name, stream.realm)
cache_delete(old_cache_key)
if not was_invite_only:
stream_dict = stream.to_dict()
stream_dict.update(dict(name=old_name, invite_only=was_invite_only))
event = dict(type="stream", op="delete",
streams=[stream_dict])
send_event(event, active_user_ids(stream.realm))
return
def do_change_user_email(user_profile, new_email):
old_email = user_profile.email
user_profile.email = new_email
user_profile.save(update_fields=["email"])
log_event({'type': 'user_email_changed',
'old_email': old_email,
'new_email': new_email})
def compute_irc_user_fullname(email):
return email.split("@")[0] + " (IRC)"
def compute_jabber_user_fullname(email):
return email.split("@")[0] + " (XMPP)"
def compute_mit_user_fullname(email):
try:
# Input is either e.g. [email protected] or user|[email protected]
match_user = re.match(r'^([a-zA-Z0-9_.-]+)(\|.+)?@mit\.edu$', email.lower())
if match_user and match_user.group(2) is None:
answer = DNS.dnslookup(
"%s.passwd.ns.athena.mit.edu" % (match_user.group(1),),
DNS.Type.TXT)
hesiod_name = answer[0][0].split(':')[4].split(',')[0].strip()
if hesiod_name != "":
return hesiod_name
elif match_user:
return match_user.group(1).lower() + "@" + match_user.group(2).upper()[1:]
except DNS.Base.ServerError:
pass
except:
print ("Error getting fullname for %s:" % (email,))
traceback.print_exc()
return email.lower()
@cache_with_key(lambda realm, email, f: user_profile_by_email_cache_key(email),
timeout=3600*24*7)
def create_mirror_user_if_needed(realm, email, email_to_fullname):
try:
return get_user_profile_by_email(email)
except UserProfile.DoesNotExist:
try:
# Forge a user for this person
return create_user(email, initial_password(email), realm,
email_to_fullname(email), email_to_username(email),
active=False, is_mirror_dummy=True)
except IntegrityError:
return get_user_profile_by_email(email)
def log_message(message):
if not message.sending_client.name.startswith("test:"):
log_event(message.to_log_dict())
def always_push_notify(user):
# robinhood.io asked to get push notifications for **all** notifyable
# messages, regardless of idle status
return user.realm.domain in ['robinhood.io']
# Helper function. Defaults here are overriden by those set in do_send_messages
def do_send_message(message, rendered_content = None, no_log = False, stream = None, local_id = None):
return do_send_messages([{'message': message,
'rendered_content': rendered_content,
'no_log': no_log,
'stream': stream,
'local_id': local_id}])[0]
def do_send_messages(messages):
# Filter out messages which didn't pass internal_prep_message properly
messages = [message for message in messages if message is not None]
# Filter out zephyr mirror anomalies where the message was already sent
already_sent_ids = []
new_messages = []
for message in messages:
if isinstance(message['message'], int):
already_sent_ids.append(message['message'])
else:
new_messages.append(message)
messages = new_messages
# For consistency, changes to the default values for these gets should also be applied
# to the default args in do_send_message
for message in messages:
message['rendered_content'] = message.get('rendered_content', None)
message['no_log'] = message.get('no_log', False)
message['stream'] = message.get('stream', None)
message['local_id'] = message.get('local_id', None)
message['sender_queue_id'] = message.get('sender_queue_id', None)
# Log the message to our message log for populate_db to refill
for message in messages:
if not message['no_log']:
log_message(message['message'])
for message in messages:
if message['message'].recipient.type == Recipient.PERSONAL:
message['recipients'] = list(set([get_user_profile_by_id(message['message'].recipient.type_id),
get_user_profile_by_id(message['message'].sender_id)]))
# For personals, you send out either 1 or 2 copies of the message, for
# personals to yourself or to someone else, respectively.
assert((len(message['recipients']) == 1) or (len(message['recipients']) == 2))
elif (message['message'].recipient.type == Recipient.STREAM or
message['message'].recipient.type == Recipient.HUDDLE):
# We use select_related()/only() here, while the PERSONAL case above uses
# get_user_profile_by_id() to get UserProfile objects from cache. Streams will
# typically have more recipients than PMs, so get_user_profile_by_id() would be
# a bit more expensive here, given that we need to hit the DB anyway and only
# care about the email from the user profile.
fields = [
'user_profile__id',
'user_profile__email',
'user_profile__is_active',
'user_profile__realm__domain'
]
query = Subscription.objects.select_related("user_profile", "user_profile__realm").only(*fields).filter(
recipient=message['message'].recipient, active=True)
message['recipients'] = [s.user_profile for s in query]
else:
raise ValueError('Bad recipient type')
# Only deliver the message to active user recipients
message['active_recipients'] = filter(lambda user_profile: user_profile.is_active,
message['recipients'])
message['message'].maybe_render_content(None)
message['message'].update_calculated_fields()
# Save the message receipts in the database
user_message_flags = defaultdict(dict)
with transaction.atomic():
Message.objects.bulk_create([message['message'] for message in messages])
ums = []
for message in messages:
ums_to_create = [UserMessage(user_profile=user_profile, message=message['message'])
for user_profile in message['active_recipients']]
# These properties on the Message are set via
# Message.render_markdown by code in the bugdown inline patterns
wildcard = message['message'].mentions_wildcard
mentioned_ids = message['message'].mentions_user_ids
ids_with_alert_words = message['message'].user_ids_with_alert_words
is_me_message = message['message'].is_me_message
for um in ums_to_create:
if um.user_profile.id == message['message'].sender.id and \
message['message'].sent_by_human():
um.flags |= UserMessage.flags.read
if wildcard:
um.flags |= UserMessage.flags.wildcard_mentioned
if um.user_profile_id in mentioned_ids:
um.flags |= UserMessage.flags.mentioned
if um.user_profile_id in ids_with_alert_words:
um.flags |= UserMessage.flags.has_alert_word
if is_me_message:
um.flags |= UserMessage.flags.is_me_message
user_message_flags[message['message'].id][um.user_profile_id] = um.flags_list()
ums.extend(ums_to_create)
UserMessage.objects.bulk_create(ums)
for message in messages:
cache_save_message(message['message'])
# Render Markdown etc. here and store (automatically) in
# memcached, so that the single-threaded Tornado server
# doesn't have to.
user_flags = user_message_flags.get(message['message'].id, {})
sender = message['message'].sender
user_presences = get_status_dict(sender)
presences = {}
for user_profile in message['active_recipients']:
if user_profile.email in user_presences:
presences[user_profile.id] = user_presences[user_profile.email]
event = dict(
type = 'message',
message = message['message'].id,
message_dict_markdown = message['message'].to_dict(apply_markdown=True),
message_dict_no_markdown = message['message'].to_dict(apply_markdown=False),
presences = presences)
users = [{'id': user.id,
'flags': user_flags.get(user.id, []),
'always_push_notify': always_push_notify(user)}
for user in message['active_recipients']]
if message['message'].recipient.type == Recipient.STREAM:
# Note: This is where authorization for single-stream
# get_updates happens! We only attach stream data to the
# notify new_message request if it's a public stream,
# ensuring that in the tornado server, non-public stream
# messages are only associated to their subscribed users.
if message['stream'] is None:
message['stream'] = Stream.objects.select_related("realm").get(id=message['message'].recipient.type_id)
if message['stream'].is_public():
event['realm_id'] = message['stream'].realm.id
event['stream_name'] = message['stream'].name
if message['stream'].invite_only:
event['invite_only'] = True
if message['local_id'] is not None:
event['local_id'] = message['local_id']
if message['sender_queue_id'] is not None:
event['sender_queue_id'] = message['sender_queue_id']
send_event(event, users)
if (settings.ENABLE_FEEDBACK and
message['message'].recipient.type == Recipient.PERSONAL and
settings.FEEDBACK_BOT in [up.email for up in message['recipients']]):
queue_json_publish(
'feedback_messages',
message['message'].to_dict(apply_markdown=False),
lambda x: None
)
# Note that this does not preserve the order of message ids
# returned. In practice, this shouldn't matter, as we only
# mirror single zephyr messages at a time and don't otherwise
# intermingle sending zephyr messages with other messages.
return already_sent_ids + [message['message'].id for message in messages]
def do_create_stream(realm, stream_name):
# This is used by a management command now, mostly to facilitate testing. It
# doesn't simulate every single aspect of creating a subscription; for example,
# we don't send Zulips to users to tell them they have been subscribed.
stream = Stream()
stream.realm = realm
stream.name = stream_name
stream.save()
Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
subscribers = UserProfile.objects.filter(realm=realm, is_active=True, is_bot=False)
bulk_add_subscriptions([stream], subscribers)
def create_stream_if_needed(realm, stream_name, invite_only=False):
(stream, created) = Stream.objects.get_or_create(
realm=realm, name__iexact=stream_name,
defaults={'name': stream_name, 'invite_only': invite_only})
if created:
Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
if not invite_only:
event = dict(type="stream", op="create",
streams=[stream.to_dict()])
send_event(event, active_user_ids(realm))
return stream, created
def recipient_for_emails(emails, not_forged_mirror_message,
user_profile, sender):
recipient_profile_ids = set()
normalized_emails = set()
realm_domains = set()
normalized_emails.add(sender.email)
realm_domains.add(sender.realm.domain)
for email in emails:
try:
user_profile = get_user_profile_by_email(email)
except UserProfile.DoesNotExist:
raise ValidationError("Invalid email '%s'" % (email,))
if (not user_profile.is_active and not user_profile.is_mirror_dummy) or \
user_profile.realm.deactivated:
raise ValidationError("'%s' is no longer using Zulip." % (email,))
recipient_profile_ids.add(user_profile.id)
normalized_emails.add(user_profile.email)
realm_domains.add(user_profile.realm.domain)
if not_forged_mirror_message and user_profile.id not in recipient_profile_ids:
raise ValidationError("User not authorized for this query")
# Prevent cross realm private messages unless it is between only two realms
# and one of users is a zuliper
if len(realm_domains) == 2:
# I'm assuming that cross-realm PMs with the "admin realm" are rare, and therefore can be slower
admin_realm = Realm.objects.get(domain=settings.ADMIN_DOMAIN)
admin_realm_admin_emails = {u.email for u in admin_realm.get_admin_users()}
# We allow settings.CROSS_REALM_BOT_EMAILS for the hardcoded emails for the feedback and notification bots
if not (normalized_emails & admin_realm_admin_emails or normalized_emails & settings.CROSS_REALM_BOT_EMAILS):
raise ValidationError("You can't send private messages outside of your organization.")
if len(realm_domains) > 2:
raise ValidationError("You can't send private messages outside of your organization.")
# If the private message is just between the sender and
# another person, force it to be a personal internally
if (len(recipient_profile_ids) == 2
and sender.id in recipient_profile_ids):
recipient_profile_ids.remove(sender.id)
if len(recipient_profile_ids) > 1:
# Make sure the sender is included in huddle messages
recipient_profile_ids.add(sender.id)
huddle = get_huddle(list(recipient_profile_ids))
return get_recipient(Recipient.HUDDLE, huddle.id)
else:
return get_recipient(Recipient.PERSONAL, list(recipient_profile_ids)[0])
def already_sent_mirrored_message_id(message):
if message.recipient.type == Recipient.HUDDLE:
# For huddle messages, we use a 10-second window because the
# timestamps aren't guaranteed to actually match between two
# copies of the same message.
time_window = datetime.timedelta(seconds=10)
else:
time_window = datetime.timedelta(seconds=0)
messages = Message.objects.filter(
sender=message.sender,
recipient=message.recipient,
content=message.content,
subject=message.subject,
sending_client=message.sending_client,
pub_date__gte=message.pub_date - time_window,
pub_date__lte=message.pub_date + time_window)
if messages.exists():
return messages[0].id
return None
def extract_recipients(s):
# We try to accept multiple incoming formats for recipients.
# See test_extract_recipients() for examples of what we allow.
try:
data = ujson.loads(s)
except ValueError:
data = s
if isinstance(data, basestring):
data = data.split(',')
if not isinstance(data, list):
raise ValueError("Invalid data type for recipients")
recipients = data
# Strip recipients, and then remove any duplicates and any that
# are the empty string after being stripped.
recipients = [recipient.strip() for recipient in recipients]
return list(set(recipient for recipient in recipients if recipient))
# check_send_message:
# Returns the id of the sent message. Has same argspec as check_message.
def check_send_message(*args, **kwargs):
message = check_message(*args, **kwargs)
return do_send_messages([message])[0]
def check_stream_name(stream_name):
if stream_name == "":
raise JsonableError("Stream can't be empty")
if len(stream_name) > Stream.MAX_NAME_LENGTH:
raise JsonableError("Stream name too long")
if not valid_stream_name(stream_name):
raise JsonableError("Invalid stream name")
def send_pm_if_empty_stream(sender, stream, stream_name):
if sender.realm.domain == 'mit.edu' or sender.realm.deactivated:
return
if sender.is_bot and sender.bot_owner is not None:
if stream:
num_subscribers = stream.num_subscribers()
if stream is None or num_subscribers == 0:
# Warn a bot's owner if they are sending a message to a stream
# that does not exist, or has no subscribers
# We warn the user once every 5 minutes to avoid a flood of
# PMs on a misconfigured integration, re-using the
# UserProfile.last_reminder field, which is not used for bots.
last_reminder = sender.last_reminder_tzaware()
waitperiod = datetime.timedelta(minutes=UserProfile.BOT_OWNER_STREAM_ALERT_WAITPERIOD)
if not last_reminder or timezone.now() - last_reminder > waitperiod:
if stream is None:
error_msg = "that stream does not yet exist. To create it, "
elif num_subscribers == 0:
error_msg = "there are no subscribers to that stream. To join it, "
content = ("Hi there! We thought you'd like to know that your bot **%s** just "
"tried to send a message to stream `%s`, but %s"
"click the gear in the left-side stream list." %
(sender.full_name, stream_name, error_msg))
message = internal_prep_message(settings.NOTIFICATION_BOT, "private",
sender.bot_owner.email, "", content)
do_send_messages([message])
sender.last_reminder = timezone.now()
sender.save(update_fields=['last_reminder'])
# check_message:
# Returns message ready for sending with do_send_message on success or the error message (string) on error.
def check_message(sender, client, message_type_name, message_to,
subject_name, message_content, realm=None, forged=False,
forged_timestamp=None, forwarder_user_profile=None, local_id=None,
sender_queue_id=None):
stream = None
if not message_to and message_type_name == 'stream' and sender.default_sending_stream:
# Use the users default stream
message_to = [sender.default_sending_stream.name]
elif len(message_to) == 0:
raise JsonableError("Message must have recipients")
if len(message_content.strip()) == 0:
raise JsonableError("Message must not be empty")
message_content = truncate_body(message_content)
if realm is None:
realm = sender.realm
if message_type_name == 'stream':
if len(message_to) > 1:
raise JsonableError("Cannot send to multiple streams")
stream_name = message_to[0].strip()
check_stream_name(stream_name)
if subject_name is None:
raise JsonableError("Missing topic")
subject = subject_name.strip()
if subject == "":
raise JsonableError("Topic can't be empty")
subject = truncate_topic(subject)
## FIXME: Commented out temporarily while we figure out what we want
# if not valid_stream_name(subject):
# return json_error("Invalid subject name")
stream = get_stream(stream_name, realm)
send_pm_if_empty_stream(sender, stream, stream_name)
if stream is None:
raise JsonableError("Stream does not exist")
recipient = get_recipient(Recipient.STREAM, stream.id)
if not stream.invite_only:
# This is a public stream
pass
elif subscribed_to_stream(sender, stream):
# Or it is private, but your are subscribed
pass
elif sender.is_api_super_user() or (forwarder_user_profile is not None and
forwarder_user_profile.is_api_super_user()):
# Or this request is being done on behalf of a super user
pass
elif sender.is_bot and subscribed_to_stream(sender.bot_owner, stream):
# Or you're a bot and your owner is subscribed.
pass
else:
# All other cases are an error.
raise JsonableError("Not authorized to send to stream '%s'" % (stream.name,))
elif message_type_name == 'private':
mirror_message = client and client.name in ["zephyr_mirror", "irc_mirror", "jabber_mirror", "JabberMirror"]
not_forged_mirror_message = mirror_message and not forged
try:
recipient = recipient_for_emails(message_to, not_forged_mirror_message,
forwarder_user_profile, sender)
except ValidationError, e:
assert isinstance(e.messages[0], basestring)
raise JsonableError(e.messages[0])
else:
raise JsonableError("Invalid message type")
message = Message()
message.sender = sender
message.content = message_content
message.recipient = recipient
if message_type_name == 'stream':
message.subject = subject
if forged and forged_timestamp is not None:
# Forged messages come with a timestamp
message.pub_date = timestamp_to_datetime(forged_timestamp)
else:
message.pub_date = timezone.now()
message.sending_client = client
if not message.maybe_render_content(realm.domain):
raise JsonableError("Unable to render message")
if client.name == "zephyr_mirror":
id = already_sent_mirrored_message_id(message)
if id is not None:
return {'message': id}
return {'message': message, 'stream': stream, 'local_id': local_id, 'sender_queue_id': sender_queue_id}
def internal_prep_message(sender_email, recipient_type_name, recipients,
subject, content, realm=None):
"""
Create a message object and checks it, but doesn't send it or save it to the database.
The internal function that calls this can therefore batch send a bunch of created
messages together as one database query.
Call do_send_messages with a list of the return values of this method.
"""
if len(content) > MAX_MESSAGE_LENGTH:
content = content[0:3900] + "\n\n[message was too long and has been truncated]"
sender = get_user_profile_by_email(sender_email)
if realm is None:
realm = sender.realm
parsed_recipients = extract_recipients(recipients)
if recipient_type_name == "stream":
stream, _ = create_stream_if_needed(realm, parsed_recipients[0])
try:
return check_message(sender, get_client("Internal"), recipient_type_name,
parsed_recipients, subject, content, realm)
except JsonableError, e:
logging.error("Error queueing internal message by %s: %s" % (sender_email, str(e)))
return None
def internal_send_message(sender_email, recipient_type_name, recipients,
subject, content, realm=None):
msg = internal_prep_message(sender_email, recipient_type_name, recipients,
subject, content, realm)
# internal_prep_message encountered an error
if msg is None:
return
do_send_messages([msg])
def pick_color(user_profile):
subs = Subscription.objects.filter(user_profile=user_profile,
active=True,
recipient__type=Recipient.STREAM)
return pick_color_helper(user_profile, subs)
def pick_color_helper(user_profile, subs):
# These colors are shared with the palette in subs.js.
stream_assignment_colors = [
"#76ce90", "#fae589", "#a6c7e5", "#e79ab5",
"#bfd56f", "#f4ae55", "#b0a5fd", "#addfe5",
"#f5ce6e", "#c2726a", "#94c849", "#bd86e5",
"#ee7e4a", "#a6dcbf", "#95a5fd", "#53a063",
"#9987e1", "#e4523d", "#c2c2c2", "#4f8de4",
"#c6a8ad", "#e7cc4d", "#c8bebf", "#a47462"]
used_colors = [sub.color for sub in subs if sub.active]
available_colors = filter(lambda x: x not in used_colors,
stream_assignment_colors)
if available_colors:
return available_colors[0]
else:
return stream_assignment_colors[len(used_colors) % len(stream_assignment_colors)]
def get_subscription(stream_name, user_profile):
stream = get_stream(stream_name, user_profile.realm)
recipient = get_recipient(Recipient.STREAM, stream.id)
return Subscription.objects.get(user_profile=user_profile,
recipient=recipient, active=True)
def validate_user_access_to_subscribers(user_profile, stream):
""" Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:
* The user and the stream are in different realms
* The realm is MIT and the stream is not invite only.
* The stream is invite only, requesting_user is passed, and that user
does not subscribe to the stream.
"""
return validate_user_access_to_subscribers_helper(
user_profile,
{"realm__domain": stream.realm.domain,
"realm_id": stream.realm_id,
"invite_only": stream.invite_only},
# We use a lambda here so that we only compute whether the
# user is subscribed if we have to
lambda: subscribed_to_stream(user_profile, stream))
def validate_user_access_to_subscribers_helper(user_profile, stream_dict, check_user_subscribed):
""" Helper for validate_user_access_to_subscribers that doesn't require a full stream object
* check_user_subscribed is a function that when called with no
arguments, will report whether the user is subscribed to the stream
"""
if user_profile is not None and user_profile.realm_id != stream_dict["realm_id"]:
raise ValidationError("Requesting user not on given realm")
if stream_dict["realm__domain"] == "mit.edu" and not stream_dict["invite_only"]:
raise JsonableError("You cannot get subscribers for public streams in this realm")
if (user_profile is not None and stream_dict["invite_only"] and
not check_user_subscribed()):
raise JsonableError("Unable to retrieve subscribers for invite-only stream")
# sub_dict is a dictionary mapping stream_id => whether the user is subscribed to that stream
def bulk_get_subscriber_user_ids(stream_dicts, user_profile, sub_dict):
target_stream_dicts = []
for stream_dict in stream_dicts:
try:
validate_user_access_to_subscribers_helper(user_profile, stream_dict,
lambda: sub_dict[stream_dict["id"]])
except JsonableError:
continue
target_stream_dicts.append(stream_dict)
subscriptions = Subscription.objects.select_related("recipient").filter(
recipient__type=Recipient.STREAM,
recipient__type_id__in=[stream["id"] for stream in target_stream_dicts],
user_profile__is_active=True,
active=True).values("user_profile_id", "recipient__type_id")
result = dict((stream["id"], []) for stream in stream_dicts)
for sub in subscriptions:
result[sub["recipient__type_id"]].append(sub["user_profile_id"])
return result
def get_subscribers_query(stream, requesting_user):
""" Build a query to get the subscribers list for a stream, raising a JsonableError if:
'stream' can either be a string representing a stream name, or a Stream
object. If it's a Stream object, 'realm' is optional.
The caller can refine this query with select_related(), values(), etc. depending
on whether it wants objects or just certain fields
"""
validate_user_access_to_subscribers(requesting_user, stream)
# Note that non-active users may still have "active" subscriptions, because we
# want to be able to easily reactivate them with their old subscriptions. This
# is why the query here has to look at the UserProfile.is_active flag.
subscriptions = Subscription.objects.filter(recipient__type=Recipient.STREAM,
recipient__type_id=stream.id,
user_profile__is_active=True,
active=True)
return subscriptions
def get_subscribers(stream, requesting_user=None):
subscriptions = get_subscribers_query(stream, requesting_user).select_related()
return [subscription.user_profile for subscription in subscriptions]
def get_subscriber_emails(stream, requesting_user=None):
subscriptions = get_subscribers_query(stream, requesting_user)
subscriptions = subscriptions.values('user_profile__email')
return [subscription['user_profile__email'] for subscription in subscriptions]
def get_subscriber_ids(stream):
try:
subscriptions = get_subscribers_query(stream, None)
except JsonableError:
return []
rows = subscriptions.values('user_profile_id')
ids = [row['user_profile_id'] for row in rows]
return ids
def get_other_subscriber_ids(stream, user_profile_id):
ids = get_subscriber_ids(stream)
return filter(lambda id: id != user_profile_id, ids)
def maybe_get_subscriber_emails(stream):
""" Alternate version of get_subscriber_emails that takes a Stream object only
(not a name), and simply returns an empty list if unable to get a real
subscriber list (because we're on the MIT realm). """
try:
subscribers = get_subscriber_emails(stream)
except JsonableError:
subscribers = []
return subscribers
def set_stream_color(user_profile, stream_name, color=None):
subscription = get_subscription(stream_name, user_profile)
if not color:
color = pick_color(user_profile)
subscription.color = color
subscription.save(update_fields=["color"])
return color
def get_subscribers_to_streams(streams):
""" Return a dict where the keys are user profiles, and the values are
arrays of all the streams within 'streams' to which that user is
subscribed.
"""
subscribes_to = {}
for stream in streams:
try:
subscribers = get_subscribers(stream)
except JsonableError:
# We can't get a subscriber list for this stream. Probably MIT.
continue
for subscriber in subscribers:
if subscriber not in subscribes_to:
subscribes_to[subscriber] = []
subscribes_to[subscriber].append(stream)
return subscribes_to
def notify_subscriptions_added(user_profile, sub_pairs, stream_emails, no_log=False):
if not no_log:
log_event({'type': 'subscription_added',
'user': user_profile.email,
'names': [stream.name for sub, stream in sub_pairs],
'domain': stream.realm.domain})
# Send a notification to the user who subscribed.
payload = [dict(name=stream.name,
stream_id=stream.id,
in_home_view=subscription.in_home_view,
invite_only=stream.invite_only,
color=subscription.color,
email_address=encode_email_address(stream),
desktop_notifications=subscription.desktop_notifications,
audible_notifications=subscription.audible_notifications,
description=stream.description,
subscribers=stream_emails(stream))
for (subscription, stream) in sub_pairs]
event = dict(type="subscription", op="add",
subscriptions=payload)
send_event(event, [user_profile.id])
def bulk_add_subscriptions(streams, users):
recipients_map = bulk_get_recipients(Recipient.STREAM, [stream.id for stream in streams])
recipients = [recipient.id for recipient in recipients_map.values()]
stream_map = {}
for stream in streams:
stream_map[recipients_map[stream.id].id] = stream
subs_by_user = defaultdict(list)
all_subs_query = Subscription.objects.select_related("user_profile")
for sub in all_subs_query.filter(user_profile__in=users,
recipient__type=Recipient.STREAM):
subs_by_user[sub.user_profile_id].append(sub)
already_subscribed = []
subs_to_activate = []
new_subs = []
for user_profile in users:
needs_new_sub = set(recipients)
for sub in subs_by_user[user_profile.id]:
if sub.recipient_id in needs_new_sub:
needs_new_sub.remove(sub.recipient_id)
if sub.active:
already_subscribed.append((user_profile, stream_map[sub.recipient_id]))
else:
subs_to_activate.append((sub, stream_map[sub.recipient_id]))
# Mark the sub as active, without saving, so that
# pick_color will consider this to be an active
# subscription when picking colors
sub.active = True
for recipient_id in needs_new_sub:
new_subs.append((user_profile, recipient_id, stream_map[recipient_id]))
subs_to_add = []
for (user_profile, recipient_id, stream) in new_subs:
color = pick_color_helper(user_profile, subs_by_user[user_profile.id])
sub_to_add = Subscription(user_profile=user_profile, active=True,
color=color, recipient_id=recipient_id,
desktop_notifications=user_profile.enable_stream_desktop_notifications,
audible_notifications=user_profile.enable_stream_sounds)
subs_by_user[user_profile.id].append(sub_to_add)
subs_to_add.append((sub_to_add, stream))
# TODO: XXX: This transaction really needs to be done at the serializeable
# transaction isolation level.
with transaction.atomic():
occupied_streams_before = list(get_occupied_streams(user_profile.realm))
Subscription.objects.bulk_create([sub for (sub, stream) in subs_to_add])
Subscription.objects.filter(id__in=[sub.id for (sub, stream_name) in subs_to_activate]).update(active=True)
occupied_streams_after = list(get_occupied_streams(user_profile.realm))
new_occupied_streams = [stream for stream in
set(occupied_streams_after) - set(occupied_streams_before)
if not stream.invite_only]
if new_occupied_streams:
event = dict(type="stream", op="occupy",
streams=[stream.to_dict()
for stream in new_occupied_streams])
send_event(event, active_user_ids(user_profile.realm))
# Notify all existing users on streams that users have joined
# First, get all users subscribed to the streams that we care about
# We fetch all subscription information upfront, as it's used throughout
# the following code and we want to minize DB queries
all_subs = Subscription.objects.filter(recipient__type=Recipient.STREAM,
recipient__type_id__in=[stream.id for stream in streams],
user_profile__is_active=True,
active=True).select_related('recipient', 'user_profile')
all_subs_by_stream = defaultdict(list)
emails_by_stream = defaultdict(list)
for sub in all_subs:
all_subs_by_stream[sub.recipient.type_id].append(sub.user_profile)
emails_by_stream[sub.recipient.type_id].append(sub.user_profile.email)
def fetch_stream_subscriber_emails(stream):
if stream.realm.domain == "mit.edu" and not stream.invite_only:
return []
return emails_by_stream[stream.id]
sub_tuples_by_user = defaultdict(list)
new_streams = set()
for (sub, stream) in subs_to_add + subs_to_activate:
sub_tuples_by_user[sub.user_profile.id].append((sub, stream))
new_streams.add((sub.user_profile.id, stream.id))
for user_profile in users:
if len(sub_tuples_by_user[user_profile.id]) == 0:
continue
sub_pairs = sub_tuples_by_user[user_profile.id]
notify_subscriptions_added(user_profile, sub_pairs, fetch_stream_subscriber_emails)
for stream in streams:
if stream.realm.domain == "mit.edu" and not stream.invite_only:
continue
new_users = [user for user in users if (user.id, stream.id) in new_streams]
new_user_ids = [user.id for user in new_users]
all_subscribed_ids = [user.id for user in all_subs_by_stream[stream.id]]
other_user_ids = set(all_subscribed_ids) - set(new_user_ids)
if other_user_ids:
for user_profile in new_users:
event = dict(type="subscription", op="peer_add",
subscriptions=[stream.name],
user_email=user_profile.email)
send_event(event, other_user_ids)
return ([(user_profile, stream_name) for (user_profile, recipient_id, stream_name) in new_subs] +
[(sub.user_profile, stream_name) for (sub, stream_name) in subs_to_activate],
already_subscribed)
# When changing this, also change bulk_add_subscriptions
def do_add_subscription(user_profile, stream, no_log=False):
recipient = get_recipient(Recipient.STREAM, stream.id)
color = pick_color(user_profile)
# TODO: XXX: This transaction really needs to be done at the serializeable
# transaction isolation level.
with transaction.atomic():
vacant_before = stream.num_subscribers() == 0
(subscription, created) = Subscription.objects.get_or_create(
user_profile=user_profile, recipient=recipient,
defaults={'active': True, 'color': color,
'notifications': user_profile.default_desktop_notifications})
did_subscribe = created
if not subscription.active:
did_subscribe = True
subscription.active = True
subscription.save(update_fields=["active"])
if vacant_before and did_subscribe and not stream.invite_only:
event = dict(type="stream", op="occupy",
streams=[stream.to_dict()])
send_event(event, active_user_ids(user_profile.realm))
if did_subscribe:
emails_by_stream = {stream.id: maybe_get_subscriber_emails(stream)}
notify_subscriptions_added(user_profile, [(subscription, stream)], lambda stream: emails_by_stream[stream.id], no_log)
user_ids = get_other_subscriber_ids(stream, user_profile.id)
event = dict(type="subscription", op="peer_add",
subscriptions=[stream.name],
user_email=user_profile.email)
send_event(event, user_ids)
return did_subscribe
def notify_subscriptions_removed(user_profile, streams, no_log=False):
if not no_log:
log_event({'type': 'subscription_removed',
'user': user_profile.email,
'names': [stream.name for stream in streams],
'domain': stream.realm.domain})
payload = [dict(name=stream.name, stream_id=stream.id) for stream in streams]
event = dict(type="subscription", op="remove",
subscriptions=payload)
send_event(event, [user_profile.id])
# As with a subscription add, send a 'peer subscription' notice to other
# subscribers so they know the user unsubscribed.
# FIXME: This code was mostly a copy-paste from notify_subscriptions_added.
# We have since streamlined how we do notifications for adds, and
# we should do the same for removes.
notifications_for = get_subscribers_to_streams(streams)
for event_recipient, notifications in notifications_for.iteritems():
# Don't send a peer subscription notice to yourself.
if event_recipient == user_profile:
continue
stream_names = [stream.name for stream in notifications]
event = dict(type="subscription", op="peer_remove",
subscriptions=stream_names,
user_email=user_profile.email)
send_event(event, [event_recipient.id])
def bulk_remove_subscriptions(users, streams):
recipients_map = bulk_get_recipients(Recipient.STREAM,
[stream.id for stream in streams])
stream_map = {}
for stream in streams:
stream_map[recipients_map[stream.id].id] = stream
subs_by_user = dict((user_profile.id, []) for user_profile in users)
for sub in Subscription.objects.select_related("user_profile").filter(user_profile__in=users,
recipient__in=recipients_map.values(),
active=True):
subs_by_user[sub.user_profile_id].append(sub)
subs_to_deactivate = []
not_subscribed = []
for user_profile in users:
recipients_to_unsub = set([recipient.id for recipient in recipients_map.values()])
for sub in subs_by_user[user_profile.id]:
recipients_to_unsub.remove(sub.recipient_id)
subs_to_deactivate.append((sub, stream_map[sub.recipient_id]))
for recipient_id in recipients_to_unsub:
not_subscribed.append((user_profile, stream_map[recipient_id]))
# TODO: XXX: This transaction really needs to be done at the serializeable
# transaction isolation level.
with transaction.atomic():
occupied_streams_before = list(get_occupied_streams(user_profile.realm))
Subscription.objects.filter(id__in=[sub.id for (sub, stream_name) in
subs_to_deactivate]).update(active=False)
occupied_streams_after = list(get_occupied_streams(user_profile.realm))
new_vacant_streams = [stream for stream in
set(occupied_streams_before) - set(occupied_streams_after)
if not stream.invite_only]
if new_vacant_streams:
event = dict(type="stream", op="vacate",
streams=[stream.to_dict()
for stream in new_vacant_streams])
send_event(event, active_user_ids(user_profile.realm))
streams_by_user = defaultdict(list)
for (sub, stream) in subs_to_deactivate:
streams_by_user[sub.user_profile_id].append(stream)
for user_profile in users:
if len(streams_by_user[user_profile.id]) == 0:
continue
notify_subscriptions_removed(user_profile, streams_by_user[user_profile.id])
return ([(sub.user_profile, stream) for (sub, stream) in subs_to_deactivate],
not_subscribed)
def do_remove_subscription(user_profile, stream, no_log=False):
recipient = get_recipient(Recipient.STREAM, stream.id)
maybe_sub = Subscription.objects.filter(user_profile=user_profile,
recipient=recipient)
if len(maybe_sub) == 0:
return False
subscription = maybe_sub[0]
did_remove = subscription.active
subscription.active = False
with transaction.atomic():
subscription.save(update_fields=["active"])
vacant_after = stream.num_subscribers() == 0
if vacant_after and did_remove and not stream.invite_only:
event = dict(type="stream", op="vacate",
streams=[stream.to_dict()])
send_event(event, active_user_ids(user_profile.realm))
if did_remove:
notify_subscriptions_removed(user_profile, [stream], no_log)
return did_remove
def log_subscription_property_change(user_email, stream_name, property, value):
event = {'type': 'subscription_property',
'property': property,
'user': user_email,
'stream_name': stream_name,
'value': value}
log_event(event)
def do_change_subscription_property(user_profile, sub, stream_name,
property_name, value):
setattr(sub, property_name, value)
sub.save(update_fields=[property_name])
log_subscription_property_change(user_profile.email, stream_name,
property_name, value)
event = dict(type="subscription",
op="update",
email=user_profile.email,
property=property_name,
value=value,
name=stream_name)
send_event(event, [user_profile.id])
def do_activate_user(user_profile, log=True, join_date=timezone.now()):
user_profile.is_active = True
user_profile.is_mirror_dummy = False
user_profile.set_password(initial_password(user_profile.email))
user_profile.date_joined = join_date
user_profile.save(update_fields=["is_active", "date_joined", "password",
"is_mirror_dummy"])
if log:
domain = user_profile.realm.domain
log_event({'type': 'user_activated',
'user': user_profile.email,
'domain': domain})
notify_created_user(user_profile)
def do_reactivate_user(user_profile):
# Unlike do_activate_user, this is meant for re-activating existing users,
# so it doesn't reset their password, etc.
user_profile.is_active = True
user_profile.save(update_fields=["is_active"])
domain = user_profile.realm.domain
log_event({'type': 'user_reactivated',
'user': user_profile.email,
'domain': domain})
notify_created_user(user_profile)
def do_change_password(user_profile, password, log=True, commit=True,
hashed_password=False):
if hashed_password:
# This is a hashed password, not the password itself.
user_profile.set_password(password)
else:
user_profile.set_password(password)
if commit:
user_profile.save(update_fields=["password"])
if log:
log_event({'type': 'user_change_password',
'user': user_profile.email,
'pwhash': user_profile.password})
def do_change_full_name(user_profile, full_name, log=True):
user_profile.full_name = full_name
user_profile.save(update_fields=["full_name"])
if log:
log_event({'type': 'user_change_full_name',
'user': user_profile.email,
'full_name': full_name})
payload = dict(email=user_profile.email,
full_name=user_profile.full_name)
send_event(dict(type='realm_user', op='update', person=payload),
active_user_ids(user_profile.realm))
if user_profile.is_bot:
send_event(dict(type='realm_bot', op='update', bot=payload),
bot_owner_userids(user_profile))
def do_regenerate_api_key(user_profile, log=True):
user_profile.api_key = random_api_key()
user_profile.save(update_fields=["api_key"])
if log:
log_event({'type': 'user_change_api_key',
'user': user_profile.email})
if user_profile.is_bot:
send_event(dict(type='realm_bot',
op='update',
bot=dict(email=user_profile.email,
api_key=user_profile.api_key,)),
bot_owner_userids(user_profile))
def do_change_avatar_source(user_profile, avatar_source, log=True):
user_profile.avatar_source = avatar_source
user_profile.save(update_fields=["avatar_source"])
if log:
log_event({'type': 'user_change_avatar_source',
'user': user_profile.email,
'avatar_source': avatar_source})
if user_profile.is_bot:
send_event(dict(type='realm_bot',
op='update',
bot=dict(email=user_profile.email,
avatar_url=avatar_url(user_profile),)),
bot_owner_userids(user_profile))
def _default_stream_permision_check(user_profile, stream):
# Any user can have a None default stream
if stream is not None:
if user_profile.is_bot:
user = user_profile.bot_owner
else:
user = user_profile
if stream.invite_only and not subscribed_to_stream(user, stream):
raise JsonableError('Insufficient permission')
def do_change_default_sending_stream(user_profile, stream, log=True):
_default_stream_permision_check(user_profile, stream)
user_profile.default_sending_stream = stream
user_profile.save(update_fields=['default_sending_stream'])
if log:
log_event({'type': 'user_change_default_sending_stream',
'user': user_profile.email,
'stream': str(stream)})
if user_profile.is_bot:
if stream:
stream_name = stream.name
else:
stream_name = None
send_event(dict(type='realm_bot',
op='update',
bot=dict(email=user_profile.email,
default_sending_stream=stream_name,)),
bot_owner_userids(user_profile))
def do_change_default_events_register_stream(user_profile, stream, log=True):
_default_stream_permision_check(user_profile, stream)
user_profile.default_events_register_stream = stream
user_profile.save(update_fields=['default_events_register_stream'])
if log:
log_event({'type': 'user_change_default_events_register_stream',
'user': user_profile.email,
'stream': str(stream)})
if user_profile.is_bot:
if stream:
stream_name = stream.name
else:
stream_name = None
send_event(dict(type='realm_bot',
op='update',
bot=dict(email=user_profile.email,
default_events_register_stream=stream_name,)),
bot_owner_userids(user_profile))
def do_change_default_all_public_streams(user_profile, value, log=True):
user_profile.default_all_public_streams = value
user_profile.save(update_fields=['default_all_public_streams'])
if log:
log_event({'type': 'user_change_default_all_public_streams',
'user': user_profile.email,
'value': str(value)})
if user_profile.is_bot:
send_event(dict(type='realm_bot',
op='update',
bot=dict(email=user_profile.email,
default_all_public_streams=user_profile.default_all_public_streams,)),
bot_owner_userids(user_profile))
def do_change_is_admin(user_profile, is_admin, permission='administer'):
if is_admin:
assign_perm(permission, user_profile, user_profile.realm)
else:
remove_perm(permission, user_profile, user_profile.realm)
if permission == 'administer':
event = dict(type="realm_user", op="update",
person=dict(email=user_profile.email,
is_admin=is_admin))
send_event(event, active_user_ids(user_profile.realm))
def do_make_stream_public(user_profile, realm, stream_name):
stream_name = stream_name.strip()
stream = get_stream(stream_name, realm)
if not stream:
raise JsonableError('Unknown stream "%s"' % (stream_name,))
if not subscribed_to_stream(user_profile, stream):
raise JsonableError('You are not invited to this stream.')
stream.invite_only = False
stream.save(update_fields=['invite_only'])
return {}
def do_make_stream_private(realm, stream_name):
stream_name = stream_name.strip()
stream = get_stream(stream_name, realm)
if not stream:
raise JsonableError('Unknown stream "%s"' % (stream_name,))
stream.invite_only = True
stream.save(update_fields=['invite_only'])
return {}
def do_rename_stream(realm, old_name, new_name, log=True):
old_name = old_name.strip()
new_name = new_name.strip()
stream = get_stream(old_name, realm)
if not stream:
raise JsonableError('Unknown stream "%s"' % (old_name,))
# Will raise if there's an issue.
check_stream_name(new_name)
if get_stream(new_name, realm) and old_name.lower() != new_name.lower():
raise JsonableError('Stream name "%s" is already taken' % (new_name,))
old_name = stream.name
stream.name = new_name
stream.save(update_fields=["name"])
if log:
log_event({'type': 'stream_name_change',
'domain': realm.domain,
'new_name': new_name})
recipient = get_recipient(Recipient.STREAM, stream.id)
messages = Message.objects.filter(recipient=recipient).only("id")
# Update the display recipient and stream, which are easy single
# items to set.
old_cache_key = get_stream_cache_key(old_name, realm)
new_cache_key = get_stream_cache_key(stream.name, realm)
if old_cache_key != new_cache_key:
cache_delete(old_cache_key)
cache_set(new_cache_key, stream)
cache_set(display_recipient_cache_key(recipient.id), stream.name)
# Delete cache entries for everything else, which is cheaper and
# clearer than trying to set them. display_recipient is the out of
# date field in all cases.
cache_delete_many(message_cache_key(message.id) for message in messages)
cache_delete_many(
to_dict_cache_key_id(message.id, True) for message in messages)
cache_delete_many(
to_dict_cache_key_id(message.id, False) for message in messages)
new_email = encode_email_address(stream)
# We will tell our users to essentially
# update stream.name = new_name where name = old_name
# and update stream.email = new_email where name = old_name.
# We could optimize this by trying to send one message, but the
# client code really wants one property update at a time, and
# updating stream names is a pretty infrequent operation.
# More importantly, we want to key these updates by id, not name,
# since id is the immutable primary key, and obviously name is not.
data_updates = [
['email_address', new_email],
['name', new_name],
]
for property, value in data_updates:
event = dict(
op="update",
type="stream",
property=property,
value=value,
name=old_name
)
send_event(event, stream_user_ids(stream))
# Even though the token doesn't change, the web client needs to update the
# email forwarding address to display the correctly-escaped new name.
return {"email_address": new_email}
def do_change_stream_description(realm, stream_name, new_description):
stream = get_stream(stream_name, realm)
stream.description = new_description
stream.save(update_fields=['description'])
event = dict(type='stream', op='update',
property='description', name=stream_name,
value=new_description)
send_event(event, stream_user_ids(stream))
return {}
def do_create_realm(domain, name, restricted_to_domain=True):
realm = get_realm(domain)
created = not realm
if created:
realm = Realm(domain=domain, name=name,
restricted_to_domain=restricted_to_domain)
realm.save()
# Create stream once Realm object has been saved
notifications_stream, _ = create_stream_if_needed(realm, Realm.NOTIFICATION_STREAM_NAME)
realm.notifications_stream = notifications_stream
realm.save(update_fields=['notifications_stream'])
# Include a welcome message in this notifications stream
product_name = "Zulip"
content = """Hello, and welcome to %s!
This is a message on stream `%s` with the topic `welcome`. We'll use this stream for system-generated notifications.""" % (product_name, notifications_stream.name,)
msg = internal_prep_message(settings.WELCOME_BOT, 'stream',
notifications_stream.name, "welcome",
content, realm=realm)
do_send_messages([msg])
# Log the event
log_event({"type": "realm_created",
"domain": domain,
"restricted_to_domain": restricted_to_domain})
if settings.NEW_USER_BOT is not None:
signup_message = "Signups enabled"
if not restricted_to_domain:
signup_message += " (open realm)"
internal_send_message(settings.NEW_USER_BOT, "stream",
"signups", domain, signup_message)
return (realm, created)
def do_change_enable_stream_desktop_notifications(user_profile,
enable_stream_desktop_notifications,
log=True):
user_profile.enable_stream_desktop_notifications = enable_stream_desktop_notifications
user_profile.save(update_fields=["enable_stream_desktop_notifications"])
event = {'type': 'update_global_notifications',
'user': user_profile.email,
'notification_name': 'enable_stream_desktop_notifications',
'setting': enable_stream_desktop_notifications}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_enable_stream_sounds(user_profile, enable_stream_sounds, log=True):
user_profile.enable_stream_sounds = enable_stream_sounds
user_profile.save(update_fields=["enable_stream_sounds"])
event = {'type': 'update_global_notifications',
'user': user_profile.email,
'notification_name': 'enable_stream_sounds',
'setting': enable_stream_sounds}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_enable_desktop_notifications(user_profile, enable_desktop_notifications, log=True):
user_profile.enable_desktop_notifications = enable_desktop_notifications
user_profile.save(update_fields=["enable_desktop_notifications"])
event = {'type': 'update_global_notifications',
'user': user_profile.email,
'notification_name': 'enable_desktop_notifications',
'setting': enable_desktop_notifications}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_enable_sounds(user_profile, enable_sounds, log=True):
user_profile.enable_sounds = enable_sounds
user_profile.save(update_fields=["enable_sounds"])
event = {'type': 'update_global_notifications',
'user': user_profile.email,
'notification_name': 'enable_sounds',
'setting': enable_sounds}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_enable_offline_email_notifications(user_profile, offline_email_notifications, log=True):
user_profile.enable_offline_email_notifications = offline_email_notifications
user_profile.save(update_fields=["enable_offline_email_notifications"])
event = {'type': 'update_global_notifications',
'user': user_profile.email,
'notification_name': 'enable_offline_email_notifications',
'setting': offline_email_notifications}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_enable_offline_push_notifications(user_profile, offline_push_notifications, log=True):
user_profile.enable_offline_push_notifications = offline_push_notifications
user_profile.save(update_fields=["enable_offline_push_notifications"])
event = {'type': 'update_global_notifications',
'user': user_profile.email,
'notification_name': 'enable_offline_push_notifications',
'setting': offline_push_notifications}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_enable_digest_emails(user_profile, enable_digest_emails, log=True):
user_profile.enable_digest_emails = enable_digest_emails
user_profile.save(update_fields=["enable_digest_emails"])
if not enable_digest_emails:
# Remove any digest emails that have been enqueued.
clear_followup_emails_queue(user_profile.email)
event = {'type': 'update_global_notifications',
'user': user_profile.email,
'notification_name': 'enable_digest_emails',
'setting': enable_digest_emails}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_autoscroll_forever(user_profile, autoscroll_forever, log=True):
user_profile.autoscroll_forever = autoscroll_forever
user_profile.save(update_fields=["autoscroll_forever"])
if log:
log_event({'type': 'autoscroll_forever',
'user': user_profile.email,
'autoscroll_forever': autoscroll_forever})
def do_change_enter_sends(user_profile, enter_sends):
user_profile.enter_sends = enter_sends
user_profile.save(update_fields=["enter_sends"])
def do_change_default_desktop_notifications(user_profile, default_desktop_notifications):
user_profile.default_desktop_notifications = default_desktop_notifications
user_profile.save(update_fields=["default_desktop_notifications"])
def do_change_twenty_four_hour_time(user_profile, setting_value, log=True):
user_profile.twenty_four_hour_time = setting_value
user_profile.save(update_fields=["twenty_four_hour_time"])
event = {'type': 'update_display_settings',
'user': user_profile.email,
'setting_name': 'twenty_four_hour_time',
'setting': setting_value}
if log:
log_event(event)
send_event(event, [user_profile.id])
def do_change_left_side_userlist(user_profile, setting_value, log=True):
user_profile.left_side_userlist = setting_value
user_profile.save(update_fields=["left_side_userlist"])
event = {'type': 'update_display_settings',
'user': user_profile.email,
'setting_name':'left_side_userlist',
'setting': setting_value}
if log:
log_event(event)
send_event(event, [user_profile.id])
def set_default_streams(realm, stream_names):
DefaultStream.objects.filter(realm=realm).delete()
for stream_name in stream_names:
stream, _ = create_stream_if_needed(realm, stream_name)
DefaultStream.objects.create(stream=stream, realm=realm)
# All realms get a notifications stream by default
notifications_stream, _ = create_stream_if_needed(realm, Realm.NOTIFICATION_STREAM_NAME)
DefaultStream.objects.create(stream=notifications_stream, realm=realm)
log_event({'type': 'default_streams',
'domain': realm.domain,
'streams': stream_names})
def do_add_default_stream(realm, stream_name):
stream, _ = create_stream_if_needed(realm, stream_name)
if DefaultStream.objects.filter(realm=realm, stream=stream).exists():
return
DefaultStream.objects.create(realm=realm, stream=stream)
return {}
def do_remove_default_stream(realm, stream_name):
DefaultStream.objects.filter(realm=realm, stream__name=stream_name).delete()
return {}
def get_default_streams_for_realm(realm):
return [default.stream for default in
DefaultStream.objects.select_related("stream", "stream__realm").filter(realm=realm)]
def get_default_subs(user_profile):
# Right now default streams are realm-wide. This wrapper gives us flexibility
# to some day further customize how we set up default streams for new users.
return get_default_streams_for_realm(user_profile.realm)
def do_update_user_activity_interval(user_profile, log_time):
effective_end = log_time + datetime.timedelta(minutes=15)
# This code isn't perfect, because with various races we might end
# up creating two overlapping intervals, but that shouldn't happen
# often, and can be corrected for in post-processing
try:
last = UserActivityInterval.objects.filter(user_profile=user_profile).order_by("-end")[0]
# There are two ways our intervals could overlap:
# (1) The start of the new interval could be inside the old interval
# (2) The end of the new interval could be inside the old interval
# In either case, we just extend the old interval to include the new interval.
if ((log_time <= last.end and log_time >= last.start) or
(effective_end <= last.end and effective_end >= last.start)):
last.end = max(last.end, effective_end)
last.start = min(last.start, log_time)
last.save(update_fields=["start", "end"])
return
except IndexError:
pass
# Otherwise, the intervals don't overlap, so we should make a new one
UserActivityInterval.objects.create(user_profile=user_profile, start=log_time,
end=effective_end)
@statsd_increment('user_activity')
def do_update_user_activity(user_profile, client, query, log_time):
(activity, created) = UserActivity.objects.get_or_create(
user_profile = user_profile,
client = client,
query = query,
defaults={'last_visit': log_time, 'count': 0})
activity.count += 1
activity.last_visit = log_time
activity.save(update_fields=["last_visit", "count"])
def send_presence_changed(user_profile, presence):
presence_dict = presence.to_dict()
event = dict(type="presence", email=user_profile.email,
server_timestamp=time.time(),
presence={presence_dict['client']: presence.to_dict()})
send_event(event, active_user_ids(user_profile.realm))
def consolidate_client(client):
# The web app reports a client as 'website'
# The desktop app reports a client as ZulipDesktop
# due to it setting a custom user agent. We want both
# to count as web users
# Alias ZulipDesktop to website
if client.name in ['ZulipDesktop']:
return get_client('website')
else:
return client
@statsd_increment('user_presence')
def do_update_user_presence(user_profile, client, log_time, status):
client = consolidate_client(client)
(presence, created) = UserPresence.objects.get_or_create(
user_profile = user_profile,
client = client,
defaults = {'timestamp': log_time,
'status': status})
stale_status = (log_time - presence.timestamp) > datetime.timedelta(minutes=1, seconds=10)
was_idle = presence.status == UserPresence.IDLE
became_online = (status == UserPresence.ACTIVE) and (stale_status or was_idle)
# If an object was created, it has already been saved.
#
# We suppress changes from ACTIVE to IDLE before stale_status is reached;
# this protects us from the user having two clients open: one active, the
# other idle. Without this check, we would constantly toggle their status
# between the two states.
if not created and stale_status or was_idle or status == presence.status:
# The following block attempts to only update the "status"
# field in the event that it actually changed. This is
# important to avoid flushing the UserPresence cache when the
# data it would return to a client hasn't actually changed
# (see the UserPresence post_save hook for details).
presence.timestamp = log_time
update_fields = ["timestamp"]
if presence.status != status:
presence.status = status
update_fields.append("status")
presence.save(update_fields=update_fields)
if not user_profile.realm.domain == "mit.edu" and (created or became_online):
# Push event to all users in the realm so they see the new user
# appear in the presence list immediately, or the newly online
# user without delay. Note that we won't send an update here for a
# timestamp update, because we rely on the browser to ping us every 50
# seconds for realm-wide status updates, and those updates should have
# recent timestamps, which means the browser won't think active users
# have gone idle. If we were more aggressive in this function about
# sending timestamp updates, we could eliminate the ping responses, but
# that's not a high priority for now, considering that most of our non-MIT
# realms are pretty small.
send_presence_changed(user_profile, presence)
def update_user_activity_interval(user_profile, log_time):
event={'user_profile_id': user_profile.id,
'time': datetime_to_timestamp(log_time)}
queue_json_publish("user_activity_interval", event,
lambda e: do_update_user_activity_interval(user_profile, log_time))
def update_user_presence(user_profile, client, log_time, status,
new_user_input):
event={'user_profile_id': user_profile.id,
'status': status,
'time': datetime_to_timestamp(log_time),
'client': client.name}
queue_json_publish("user_presence", event,
lambda e: do_update_user_presence(user_profile, client,
log_time, status))
if new_user_input:
update_user_activity_interval(user_profile, log_time)
def do_update_pointer(user_profile, pointer, update_flags=False):
prev_pointer = user_profile.pointer
user_profile.pointer = pointer
user_profile.save(update_fields=["pointer"])
if update_flags:
# Until we handle the new read counts in the Android app
# natively, this is a shim that will mark as read any messages
# up until the pointer move
UserMessage.objects.filter(user_profile=user_profile,
message__id__gt=prev_pointer,
message__id__lte=pointer,
flags=~UserMessage.flags.read) \
.update(flags=F('flags').bitor(UserMessage.flags.read))
event = dict(type='pointer', pointer=pointer)
send_event(event, [user_profile.id])
def do_update_message_flags(user_profile, operation, flag, messages, all):
flagattr = getattr(UserMessage.flags, flag)
if all:
log_statsd_event('bankruptcy')
msgs = UserMessage.objects.filter(user_profile=user_profile)
else:
msgs = UserMessage.objects.filter(user_profile=user_profile,
message__id__in=messages)
# Hack to let you star any message
if msgs.count() == 0:
if not len(messages) == 1:
raise JsonableError("Invalid message(s)")
if flag != "starred":
raise JsonableError("Invalid message(s)")
# Check that the user could have read the relevant message
try:
message = Message.objects.get(id=messages[0])
except Message.DoesNotExist:
raise JsonableError("Invalid message(s)")
recipient = Recipient.objects.get(id=message.recipient_id)
if recipient.type != Recipient.STREAM:
raise JsonableError("Invalid message(s)")
stream = Stream.objects.select_related("realm").get(id=recipient.type_id)
if not stream.is_public():
raise JsonableError("Invalid message(s)")
# OK, this is a message that you legitimately have access
# to via narrowing to the stream it is on, even though you
# didn't actually receive it. So we create a historical,
# read UserMessage message row for you to star.
UserMessage.objects.create(user_profile=user_profile,
message=message,
flags=UserMessage.flags.historical | UserMessage.flags.read)
# The filter() statements below prevent postgres from doing a lot of
# unnecessary work, which is a big deal for users updating lots of
# flags (e.g. bankruptcy). This patch arose from seeing slow calls
# to /json/update_message_flags in the logs. The filter() statements
# are kind of magical; they are actually just testing the one bit.
if operation == 'add':
msgs = msgs.filter(flags=~flagattr)
count = msgs.update(flags=F('flags').bitor(flagattr))
elif operation == 'remove':
msgs = msgs.filter(flags=flagattr)
count = msgs.update(flags=F('flags').bitand(~flagattr))
event = {'type': 'update_message_flags',
'operation': operation,
'flag': flag,
'messages': messages,
'all': all}
log_event(event)
send_event(event, [user_profile.id])
statsd.incr("flags.%s.%s" % (flag, operation), count)
def subscribed_to_stream(user_profile, stream):
try:
if Subscription.objects.get(user_profile=user_profile,
active=True,
recipient__type=Recipient.STREAM,
recipient__type_id=stream.id):
return True
return False
except Subscription.DoesNotExist:
return False
def truncate_content(content, max_length, truncation_message):
if len(content) > max_length:
content = content[:max_length - len(truncation_message)] + truncation_message
return content
def truncate_body(body):
return truncate_content(body, MAX_MESSAGE_LENGTH, "...")
def truncate_topic(topic):
return truncate_content(topic, MAX_SUBJECT_LENGTH, "...")
def update_user_message_flags(message, ums):
wildcard = message.mentions_wildcard
mentioned_ids = message.mentions_user_ids
ids_with_alert_words = message.user_ids_with_alert_words
changed_ums = set()
def update_flag(um, should_set, flag):
if should_set:
if not (um.flags & flag):
um.flags |= flag
changed_ums.add(um)
else:
if (um.flags & flag):
um.flags &= ~flag
changed_ums.add(um)
for um in ums:
has_alert_word = um.user_profile_id in ids_with_alert_words
update_flag(um, has_alert_word, UserMessage.flags.has_alert_word)
mentioned = um.user_profile_id in mentioned_ids
update_flag(um, mentioned, UserMessage.flags.mentioned)
update_flag(um, wildcard, UserMessage.flags.wildcard_mentioned)
for um in changed_ums:
um.save(update_fields=['flags'])
def do_update_message(user_profile, message_id, subject, propagate_mode, content):
try:
message = Message.objects.select_related().get(id=message_id)
except Message.DoesNotExist:
raise JsonableError("Unknown message id")
event = {'type': 'update_message',
'sender': user_profile.email,
'message_id': message_id}
edit_history_event = {}
changed_messages = [message]
# You can only edit a message if:
# 1. You sent it, OR:
# 2. This is a topic-only edit for a (no topic) message, OR:
# 3. This is a topic-only edit and you are an admin.
if message.sender == user_profile:
pass
elif (content is None) and ((message.subject == "(no topic)") or
user_profile.is_admin()):
pass
else:
raise JsonableError("You don't have permission to edit this message")
# Set first_rendered_content to be the oldest version of the
# rendered content recorded; which is the current version if the
# content hasn't been edited before. Note that because one could
# have edited just the subject, not every edit history event
# contains a prev_rendered_content element.
first_rendered_content = message.rendered_content
if message.edit_history is not None:
edit_history = ujson.loads(message.edit_history)
for old_edit_history_event in edit_history:
if 'prev_rendered_content' in old_edit_history_event:
first_rendered_content = old_edit_history_event['prev_rendered_content']
ums = UserMessage.objects.filter(message=message_id)
if content is not None:
if len(content.strip()) == 0:
content = "(deleted)"
content = truncate_body(content)
rendered_content = message.render_markdown(content)
if not rendered_content:
raise JsonableError("We were unable to render your updated message")
update_user_message_flags(message, ums)
# We are turning off diff highlighting everywhere until ticket #1532 is addressed.
if False:
# Don't highlight message edit diffs on prod
rendered_content = highlight_html_differences(first_rendered_content, rendered_content)
event['orig_content'] = message.content
event['orig_rendered_content'] = message.rendered_content
edit_history_event["prev_content"] = message.content
edit_history_event["prev_rendered_content"] = message.rendered_content
edit_history_event["prev_rendered_content_version"] = message.rendered_content_version
message.content = content
message.set_rendered_content(rendered_content)
event["content"] = content
event["rendered_content"] = rendered_content
if subject is not None:
orig_subject = message.subject
subject = subject.strip()
if subject == "":
raise JsonableError("Topic can't be empty")
subject = truncate_topic(subject)
event["orig_subject"] = orig_subject
event["propagate_mode"] = propagate_mode
message.subject = subject
event["stream_id"] = message.recipient.type_id
event["subject"] = subject
event['subject_links'] = bugdown.subject_links(message.sender.realm.domain.lower(), subject)
edit_history_event["prev_subject"] = orig_subject
if propagate_mode in ["change_later", "change_all"]:
propagate_query = Q(recipient = message.recipient, subject = orig_subject)
# We only change messages up to 2 days in the past, to avoid hammering our
# DB by changing an unbounded amount of messages
if propagate_mode == 'change_all':
before_bound = now() - datetime.timedelta(days=2)
propagate_query = propagate_query & ~Q(id = message.id) & \
Q(pub_date__range=(before_bound, now()))
if propagate_mode == 'change_later':
propagate_query = propagate_query & Q(id__gt = message.id)
messages = Message.objects.filter(propagate_query).select_related();
# Evaluate the query before running the update
messages_list = list(messages)
messages.update(subject=subject)
for m in messages_list:
# The cached ORM object is not changed by messages.update()
# and the memcached update requires the new value
m.subject = subject
changed_messages += messages_list
message.last_edit_time = timezone.now()
event['edit_timestamp'] = datetime_to_timestamp(message.last_edit_time)
edit_history_event['timestamp'] = event['edit_timestamp']
if message.edit_history is not None:
edit_history.insert(0, edit_history_event)
else:
edit_history = [edit_history_event]
message.edit_history = ujson.dumps(edit_history)
log_event(event)
message.save(update_fields=["subject", "content", "rendered_content",
"rendered_content_version", "last_edit_time",
"edit_history"])
# Update the message as stored in the (deprecated) message
# cache (for shunting the message over to Tornado in the old
# get_messages API) and also the to_dict caches.
items_for_memcached = {}
event['message_ids'] = []
for changed_message in changed_messages:
event['message_ids'].append(changed_message.id)
items_for_memcached[message_cache_key(changed_message.id)] = (changed_message,)
items_for_memcached[to_dict_cache_key(changed_message, True)] = \
(stringify_message_dict(changed_message.to_dict_uncached(apply_markdown=True)),)
items_for_memcached[to_dict_cache_key(changed_message, False)] = \
(stringify_message_dict(changed_message.to_dict_uncached(apply_markdown=False)),)
cache_set_many(items_for_memcached)
def user_info(um):
return {
'id': um.user_profile_id,
'flags': um.flags_list()
}
send_event(event, map(user_info, ums))
def encode_email_address(stream):
return encode_email_address_helper(stream.name, stream.email_token)
def encode_email_address_helper(name, email_token):
# Some deployments may not use the email gateway
if settings.EMAIL_GATEWAY_PATTERN == '':
return ''
# Given the fact that we have almost no restrictions on stream names and
# that what characters are allowed in e-mail addresses is complicated and
# dependent on context in the address, we opt for a very simple scheme:
#
# Only encode the stream name (leave the + and token alone). Encode
# everything that isn't alphanumeric plus _ as the percent-prefixed integer
# ordinal of that character, padded with zeroes to the maximum number of
# bytes of a UTF-8 encoded Unicode character.
encoded_name = re.sub("\W", lambda x: "%" + str(ord(x.group(0))).zfill(4), name)
encoded_token = "%s+%s" % (encoded_name, email_token)
return settings.EMAIL_GATEWAY_PATTERN % (encoded_token,)
def decode_email_address(email):
# Perform the reverse of encode_email_address. Returns a tuple of (streamname, email_token)
pattern_parts = [re.escape(part) for part in settings.EMAIL_GATEWAY_PATTERN.split('%s')]
if settings.ZULIP_COM:
# Accept mails delivered to any Zulip server
pattern_parts[-1] = r'@[\w-]*\.zulip\.net'
match_email_re = re.compile("(.*?)".join(pattern_parts))
match = match_email_re.match(email)
if not match:
return None
full_address = match.group(1)
if '.' in full_address:
# Workaround for Google Groups and other programs that don't accept emails
# that have + signs in them (see Trac #2102)
encoded_stream_name, token = full_address.split('.')
else:
encoded_stream_name, token = full_address.split('+')
stream_name = re.sub("%\d{4}", lambda x: unichr(int(x.group(0)[1:])), encoded_stream_name)
return stream_name, token
# In general, it's better to avoid using .values() because it makes
# the code pretty ugly, but in this case, it has significant
# performance impact for loading / for users with large numbers of
# subscriptions, so it's worth optimizing.
def gather_subscriptions_helper(user_profile):
sub_dicts = Subscription.objects.select_related("recipient").filter(
user_profile = user_profile,
recipient__type = Recipient.STREAM).values(
"recipient__type_id", "in_home_view", "color", "desktop_notifications",
"audible_notifications", "active")
stream_ids = [sub["recipient__type_id"] for sub in sub_dicts]
stream_dicts = get_active_streams(user_profile.realm).select_related(
"realm").filter(id__in=stream_ids).values(
"id", "name", "invite_only", "realm_id", "realm__domain", "email_token", "description")
stream_hash = {}
for stream in stream_dicts:
stream_hash[stream["id"]] = stream
subscribed = []
unsubscribed = []
# Deactivated streams aren't in stream_hash.
streams = [stream_hash[sub["recipient__type_id"]] for sub in sub_dicts \
if sub["recipient__type_id"] in stream_hash]
streams_subscribed_map = dict((sub["recipient__type_id"], sub["active"]) for sub in sub_dicts)
subscriber_map = bulk_get_subscriber_user_ids(streams, user_profile, streams_subscribed_map)
for sub in sub_dicts:
stream = stream_hash.get(sub["recipient__type_id"])
if not stream:
# This stream has been deactivated, don't include it.
continue
subscribers = subscriber_map[stream["id"]]
# Important: don't show the subscribers if the stream is invite only
# and this user isn't on it anymore.
if stream["invite_only"] and not sub["active"]:
subscribers = None
stream_dict = {'name': stream["name"],
'in_home_view': sub["in_home_view"],
'invite_only': stream["invite_only"],
'color': sub["color"],
'desktop_notifications': sub["desktop_notifications"],
'audible_notifications': sub["audible_notifications"],
'stream_id': stream["id"],
'description': stream["description"],
'email_address': encode_email_address_helper(stream["name"], stream["email_token"])}
if subscribers is not None:
stream_dict['subscribers'] = subscribers
if sub["active"]:
subscribed.append(stream_dict)
else:
unsubscribed.append(stream_dict)
user_ids = set()
for subs in [subscribed, unsubscribed]:
for sub in subs:
if 'subscribers' in sub:
for subscriber in sub['subscribers']:
user_ids.add(subscriber)
email_dict = get_emails_from_user_ids(list(user_ids))
return (sorted(subscribed), sorted(unsubscribed), email_dict)
def gather_subscriptions(user_profile):
subscribed, unsubscribed, email_dict = gather_subscriptions_helper(user_profile)
for subs in [subscribed, unsubscribed]:
for sub in subs:
if 'subscribers' in sub:
sub['subscribers'] = [email_dict[user_id] for user_id in sub['subscribers']]
return (subscribed, unsubscribed)
def get_status_dict(requesting_user_profile):
# Return no status info for MIT
if requesting_user_profile.realm.domain == 'mit.edu':
return defaultdict(dict)
return UserPresence.get_status_dict_by_realm(requesting_user_profile.realm_id)
def get_realm_user_dicts(user_profile):
# Due to our permission model, it is advantageous to find the admin users in bulk.
admins = user_profile.realm.get_admin_users()
admin_emails = set(map(lambda up: up.email, admins))
return [{'email' : userdict['email'],
'is_admin' : userdict['email'] in admin_emails,
'is_bot' : userdict['is_bot'],
'full_name' : userdict['full_name']}
for userdict in get_active_user_dicts_in_realm(user_profile.realm)]
def get_realm_bot_dicts(user_profile):
return [{'email' : botdict['email'],
'full_name' : botdict['full_name'],
'api_key' : botdict['api_key'],
'default_sending_stream': botdict['default_sending_stream__name'],
'default_events_register_stream': botdict['default_events_register_stream__name'],
'default_all_public_streams': botdict['default_all_public_streams'],
'owner': botdict['bot_owner__email'],
'avatar_url': get_avatar_url(botdict['avatar_source'], botdict['email']),
}
for botdict in get_active_bot_dicts_in_realm(user_profile.realm)]
# Fetch initial data. When event_types is not specified, clients want
# all event types. Whenever you add new code to this function, you
# should also add corresponding events for changes in the data
# structures and new code to apply_events (and add a test in EventsRegisterTest).
def fetch_initial_state_data(user_profile, event_types, queue_id):
state = {'queue_id': queue_id}
if event_types is None:
want = lambda msg_type: True
else:
want = set(event_types).__contains__
if want('alert_words'):
state['alert_words'] = user_alert_words(user_profile)
if want('message'):
# The client should use get_old_messages() to fetch messages
# starting with the max_message_id. They will get messages
# newer than that ID via get_events()
messages = Message.objects.filter(usermessage__user_profile=user_profile).order_by('-id')[:1]
if messages:
state['max_message_id'] = messages[0].id
else:
state['max_message_id'] = -1
if want('muted_topics'):
state['muted_topics'] = ujson.loads(user_profile.muted_topics)
if want('pointer'):
state['pointer'] = user_profile.pointer
if want('presence'):
state['presences'] = get_status_dict(user_profile)
if want('realm'):
state['realm_name'] = user_profile.realm.name
state['realm_restricted_to_domain'] = user_profile.realm.restricted_to_domain
state['realm_invite_required'] = user_profile.realm.invite_required
state['realm_invite_by_admins_only'] = user_profile.realm.invite_by_admins_only
if want('realm_domain'):
state['realm_domain'] = user_profile.realm.domain
if want('realm_emoji'):
state['realm_emoji'] = user_profile.realm.get_emoji()
if want('realm_filters'):
state['realm_filters'] = realm_filters_for_domain(user_profile.realm.domain)
if want('realm_user'):
state['realm_users'] = get_realm_user_dicts(user_profile)
if want('realm_bot'):
state['realm_bots'] = get_realm_bot_dicts(user_profile)
if want('referral'):
state['referrals'] = {'granted': user_profile.invites_granted,
'used': user_profile.invites_used}
if want('subscription'):
subscriptions, unsubscribed, email_dict = gather_subscriptions_helper(user_profile)
state['subscriptions'] = subscriptions
state['unsubscribed'] = unsubscribed
state['email_dict'] = email_dict
if want('update_message_flags'):
# There's no initial data for message flag updates, client will
# get any updates during a session from get_events()
pass
if want('stream'):
state['streams'] = do_get_streams(user_profile)
if want('update_display_settings'):
state['twenty_four_hour_time'] = user_profile.twenty_four_hour_time
state['left_side_userlist'] = user_profile.left_side_userlist
return state
def apply_events(state, events, user_profile):
for event in events:
if event['type'] == "message":
state['max_message_id'] = max(state['max_message_id'], event['message']['id'])
elif event['type'] == "pointer":
state['pointer'] = max(state['pointer'], event['pointer'])
elif event['type'] == "realm_user":
person = event['person']
def our_person(p):
return p['email'] == person['email']
if event['op'] == "add":
state['realm_users'].append(person)
elif event['op'] == "remove":
state['realm_users'] = itertools.ifilterfalse(our_person, state['realm_users'])
elif event['op'] == 'update':
for p in state['realm_users']:
if our_person(p):
p.update(person)
elif event['type'] == 'realm_bot':
if event['op'] == 'add':
state['realm_bots'].append(event['bot'])
if event['op'] == 'remove':
email = event['bot']['email']
state['realm_bots'] = [b for b in state['realm_bots'] if b['email'] != email]
if event['op'] == 'update':
for bot in state['realm_bots']:
if bot['email'] == event['bot']['email']:
bot.update(event['bot'])
elif event['type'] == 'stream':
if event['op'] == 'update':
# For legacy reasons, we call stream data 'subscriptions' in
# the state var here, for the benefit of the JS code.
for obj in state['subscriptions']:
if obj['name'].lower() == event['name'].lower():
obj[event['property']] = event['value']
# Also update the pure streams data
for stream in state['streams']:
if stream['name'].lower() == event['name'].lower():
prop = event['property']
if prop in stream:
stream[prop] = event['value']
elif event['op'] == "occupy":
state['streams'] += event['streams']
elif event['op'] == "vacate":
stream_ids = [s["stream_id"] for s in event['streams']]
state['streams'] = filter(lambda s: s["stream_id"] not in stream_ids,
state['streams'])
elif event['type'] == 'realm':
field = 'realm_' + event['property']
state[field] = event['value']
elif event['type'] == "subscription":
if event['op'] in ["add"]:
# Convert the user_profile IDs to emails since that's what register() returns
# TODO: Clean up this situation
for item in event["subscriptions"]:
item["subscribers"] = [get_user_profile_by_email(email).id for email in item["subscribers"]]
def name(sub):
return sub['name'].lower()
if event['op'] == "add":
added_names = map(name, event["subscriptions"])
was_added = lambda s: name(s) in added_names
# add the new subscriptions
state['subscriptions'] += event['subscriptions']
# remove them from unsubscribed if they had been there
state['unsubscribed'] = list(itertools.ifilterfalse(was_added, state['unsubscribed']))
elif event['op'] == "remove":
removed_names = map(name, event["subscriptions"])
was_removed = lambda s: name(s) in removed_names
# Find the subs we are affecting.
removed_subs = filter(was_removed, state['subscriptions'])
# Remove our user from the subscribers of the removed subscriptions.
for sub in removed_subs:
sub['subscribers'] = filter(lambda id: id != user_profile.id, sub['subscribers'])
# We must effectively copy the removed subscriptions from subscriptions to
# unsubscribe, since we only have the name in our data structure.
state['unsubscribed'] += removed_subs
# Now filter out the removed subscriptions from subscriptions.
state['subscriptions'] = list(itertools.ifilterfalse(was_removed, state['subscriptions']))
elif event['op'] == 'update':
for sub in state['subscriptions']:
if sub['name'].lower() == event['name'].lower():
sub[event['property']] = event['value']
elif event['op'] == 'peer_add':
user_id = get_user_profile_by_email(event['user_email']).id
for sub in state['subscriptions']:
if (sub['name'] in event['subscriptions'] and
user_id not in sub['subscribers']):
sub['subscribers'].append(user_id)
elif event['op'] == 'peer_remove':
user_id = get_user_profile_by_email(event['user_email']).id
for sub in state['subscriptions']:
if (sub['name'] in event['subscriptions'] and
user_id in sub['subscribers']):
sub['subscribers'].remove(user_id)
elif event['type'] == "presence":
state['presences'][event['email']] = event['presence']
elif event['type'] == "update_message":
# The client will get the updated message directly
pass
elif event['type'] == "referral":
state['referrals'] = event['referrals']
elif event['type'] == "update_message_flags":
# The client will get the message with the updated flags directly
pass
elif event['type'] == "realm_emoji":
state['realm_emoji'] = event['realm_emoji']
elif event['type'] == "alert_words":
state['alert_words'] = event['alert_words']
elif event['type'] == "muted_topics":
state['muted_topics'] = event["muted_topics"]
elif event['type'] == "realm_filters":
state['realm_filters'] = event["realm_filters"]
elif event['type'] == "update_display_settings":
if event['setting_name'] == "twenty_four_hour_time":
state['twenty_four_hour_time'] = event["setting"]
if event['setting_name'] == 'left_side_userlist':
state['left_side_userlist'] = event["setting"]
else:
raise ValueError("Unexpected event type %s" % (event['type'],))
def do_events_register(user_profile, user_client, apply_markdown=True,
event_types=None, queue_lifespan_secs=0, all_public_streams=False,
narrow=[]):
# Technically we don't need to check this here because
# build_narrow_filter will check it, but it's nicer from an error
# handling perspective to do it before contacting Tornado
check_supported_events_narrow_filter(narrow)
queue_id = request_event_queue(user_profile, user_client, apply_markdown,
queue_lifespan_secs, event_types, all_public_streams,
narrow=narrow)
if queue_id is None:
raise JsonableError("Could not allocate event queue")
if event_types is not None:
event_types = set(event_types)
ret = fetch_initial_state_data(user_profile, event_types, queue_id)
# Apply events that came in while we were fetching initial data
events = get_user_events(user_profile, queue_id, -1)
apply_events(ret, events, user_profile)
if events:
ret['last_event_id'] = events[-1]['id']
else:
ret['last_event_id'] = -1
return ret
def do_send_confirmation_email(invitee, referrer):
"""
Send the confirmation/welcome e-mail to an invited user.
`invitee` is a PreregistrationUser.
`referrer` is a UserProfile.
"""
subject_template_path = 'confirmation/invite_email_subject.txt'
body_template_path = 'confirmation/invite_email_body.txt'
context = {'referrer': referrer,
'support_email': settings.ZULIP_ADMINISTRATOR,
'voyager': settings.VOYAGER}
if referrer.realm.domain == 'mit.edu':
subject_template_path = 'confirmation/mituser_invite_email_subject.txt'
body_template_path = 'confirmation/mituser_invite_email_body.txt'
Confirmation.objects.send_confirmation(
invitee, invitee.email, additional_context=context,
subject_template_path=subject_template_path,
body_template_path=body_template_path)
@statsd_increment("push_notifications")
def handle_push_notification(user_profile_id, missed_message):
try:
user_profile = get_user_profile_by_id(user_profile_id)
if not receives_offline_notifications(user_profile):
return
umessage = UserMessage.objects.get(user_profile=user_profile,
message__id=missed_message['message_id'])
message = umessage.message
if umessage.flags.read:
return
sender_str = message.sender.full_name
apple = num_push_devices_for_user(user_profile, kind=PushDeviceToken.APNS)
android = num_push_devices_for_user(user_profile, kind=PushDeviceToken.GCM)
if apple or android:
#TODO: set badge count in a better way
# Determine what alert string to display based on the missed messages
if message.recipient.type == Recipient.HUDDLE:
alert = "New private group message from %s" % (sender_str,)
elif message.recipient.type == Recipient.PERSONAL:
alert = "New private message from %s" % (sender_str,)
elif message.recipient.type == Recipient.STREAM:
alert = "New mention from %s" % (sender_str,)
else:
alert = "New Zulip mentions and private messages from %s" % (sender_str,)
if apple:
apple_extra_data = {'message_ids': [message.id]}
send_apple_push_notification(user_profile, alert, badge=1, zulip=apple_extra_data)
if android:
content = message.content
content_truncated = (len(content) > 200)
if content_truncated:
content = content[:200] + "..."
android_data = {
'user': user_profile.email,
'event': 'message',
'alert': alert,
'zulip_message_id': message.id, # message_id is reserved for CCS
'time': datetime_to_timestamp(message.pub_date),
'content': content,
'content_truncated': content_truncated,
'sender_email': message.sender.email,
'sender_full_name': message.sender.full_name,
'sender_avatar_url': get_avatar_url(message.sender.avatar_source, message.sender.email),
}
if message.recipient.type == Recipient.STREAM:
android_data['recipient_type'] = "stream"
android_data['stream'] = get_display_recipient(message.recipient)
android_data['topic'] = message.subject
elif message.recipient.type in (Recipient.HUDDLE, Recipient.PERSONAL):
android_data['recipient_type'] = "private"
send_android_push_notification(user_profile, android_data)
except UserMessage.DoesNotExist:
logging.error("Could not find UserMessage with message_id %s" %(missed_message['message_id'],))
def is_inactive(value):
try:
if get_user_profile_by_email(value).is_active:
raise ValidationError(u'%s is already active' % value)
except UserProfile.DoesNotExist:
pass
def user_email_is_unique(value):
try:
get_user_profile_by_email(value)
raise ValidationError(u'%s is already registered' % value)
except UserProfile.DoesNotExist:
pass
def do_invite_users(user_profile, invitee_emails, streams):
new_prereg_users = []
errors = []
skipped = []
ret_error = None
ret_error_data = {}
for email in invitee_emails:
if email == '':
continue
try:
validators.validate_email(email)
except ValidationError:
errors.append((email, "Invalid address."))
continue
if user_profile.realm.restricted_to_domain and resolve_email_to_domain(email) != user_profile.realm.domain.lower():
errors.append((email, "Outside your domain."))
continue
try:
existing_user_profile = get_user_profile_by_email(email)
except UserProfile.DoesNotExist:
existing_user_profile = None
try:
if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
# Mirror dummy users to be activated must be inactive
is_inactive(email)
else:
# Other users should not already exist at all.
user_email_is_unique(email)
except ValidationError:
skipped.append((email, "Already has an account."))
continue
# The logged in user is the referrer.
prereg_user = PreregistrationUser(email=email, referred_by=user_profile)
# We save twice because you cannot associate a ManyToMany field
# on an unsaved object.
prereg_user.save()
prereg_user.streams = streams
prereg_user.save()
new_prereg_users.append(prereg_user)
if errors:
ret_error = "Some emails did not validate, so we didn't send any invitations."
ret_error_data = {'errors': errors}
if skipped and len(skipped) == len(invitee_emails):
# All e-mails were skipped, so we didn't actually invite anyone.
ret_error = "We weren't able to invite anyone."
ret_error_data = {'errors': skipped}
return ret_error, ret_error_data
# If we encounter an exception at any point before now, there are no unwanted side-effects,
# since it is totally fine to have duplicate PreregistrationUsers
for user in new_prereg_users:
event = {"email": user.email, "referrer_email": user_profile.email}
queue_json_publish("invites", event,
lambda event: do_send_confirmation_email(user, user_profile))
if skipped:
ret_error = "Some of those addresses are already using Zulip, \
so we didn't send them an invitation. We did send invitations to everyone else!"
ret_error_data = {'errors': skipped}
return ret_error, ret_error_data
def send_referral_event(user_profile):
event = dict(type="referral",
referrals=dict(granted=user_profile.invites_granted,
used=user_profile.invites_used))
send_event(event, [user_profile.id])
def do_refer_friend(user_profile, email):
content = """Referrer: "%s" <%s>
Realm: %s
Referred: %s""" % (user_profile.full_name, user_profile.email, user_profile.realm.domain, email)
subject = "Zulip referral: %s" % (email,)
from_email = '"%s" <%s>' % (user_profile.full_name, '[email protected]')
to_email = '"Zulip Referrals" <[email protected]>'
headers = {'Reply-To' : '"%s" <%s>' % (user_profile.full_name, user_profile.email,)}
msg = EmailMessage(subject, content, from_email, [to_email], headers=headers)
msg.send()
referral = Referral(user_profile=user_profile, email=email)
referral.save()
user_profile.invites_used += 1
user_profile.save(update_fields=['invites_used'])
send_referral_event(user_profile)
def notify_realm_emoji(realm):
event = dict(type="realm_emoji", op="update",
realm_emoji=realm.get_emoji())
user_ids = [userdict['id'] for userdict in get_active_user_dicts_in_realm(realm)]
send_event(event, user_ids)
def do_add_realm_emoji(realm, name, img_url):
RealmEmoji(realm=realm, name=name, img_url=img_url).save()
notify_realm_emoji(realm)
def do_remove_realm_emoji(realm, name):
RealmEmoji.objects.get(realm=realm, name=name).delete()
notify_realm_emoji(realm)
def notify_alert_words(user_profile, words):
event = dict(type="alert_words", alert_words=words)
send_event(event, [user_profile.id])
def do_add_alert_words(user_profile, alert_words):
words = add_user_alert_words(user_profile, alert_words)
notify_alert_words(user_profile, words)
def do_remove_alert_words(user_profile, alert_words):
words = remove_user_alert_words(user_profile, alert_words)
notify_alert_words(user_profile, words)
def do_set_alert_words(user_profile, alert_words):
set_user_alert_words(user_profile, alert_words)
notify_alert_words(user_profile, alert_words)
def do_set_muted_topics(user_profile, muted_topics):
user_profile.muted_topics = ujson.dumps(muted_topics)
user_profile.save(update_fields=['muted_topics'])
event = dict(type="muted_topics", muted_topics=muted_topics)
send_event(event, [user_profile.id])
def notify_realm_filters(realm):
realm_filters = realm_filters_for_domain(realm.domain)
user_ids = [userdict['id'] for userdict in get_active_user_dicts_in_realm(realm)]
event = dict(type="realm_filters", realm_filters=realm_filters)
send_event(event, user_ids)
# NOTE: Regexes must be simple enough that they can be easily translated to JavaScript
# RegExp syntax. In addition to JS-compatible syntax, the following features are available:
# * Named groups will be converted to numbered groups automatically
# * Inline-regex flags will be stripped, and where possible translated to RegExp-wide flags
def do_add_realm_filter(realm, pattern, url_format_string):
RealmFilter(realm=realm, pattern=pattern,
url_format_string=url_format_string).save()
notify_realm_filters(realm)
def do_remove_realm_filter(realm, pattern):
RealmFilter.objects.get(realm=realm, pattern=pattern).delete()
notify_realm_filters(realm)
def get_emails_from_user_ids(user_ids):
# We may eventually use memcached to speed this up, but the DB is fast.
return UserProfile.emails_from_ids(user_ids)
def realm_aliases(realm):
return [alias.domain for alias in realm.realmalias_set.all()]
def get_occupied_streams(realm):
""" Get streams with subscribers """
subs_filter = Subscription.objects.filter(active=True, user_profile__realm=realm,
user_profile__is_active=True).values('recipient_id')
stream_ids = Recipient.objects.filter(
type=Recipient.STREAM, id__in=subs_filter).values('type_id')
return Stream.objects.filter(id__in=stream_ids, realm=realm, deactivated=False)
def do_get_streams(user_profile, include_public=True, include_subscribed=True,
include_all_active=False):
if include_all_active and not user_profile.is_api_super_user():
raise JsonableError("User not authorized for this query")
# Listing public streams are disabled for the mit.edu realm.
include_public = include_public and user_profile.realm.domain != "mit.edu"
# Start out with all streams in the realm with subscribers
query = get_occupied_streams(user_profile.realm)
if not include_all_active:
user_subs = Subscription.objects.select_related("recipient").filter(
active=True, user_profile=user_profile,
recipient__type=Recipient.STREAM)
if include_subscribed:
recipient_check = Q(id__in=[sub.recipient.type_id for sub in user_subs])
if include_public:
invite_only_check = Q(invite_only=False)
if include_subscribed and include_public:
query = query.filter(recipient_check | invite_only_check)
elif include_public:
query = query.filter(invite_only_check)
elif include_subscribed:
query = query.filter(recipient_check)
else:
# We're including nothing, so don't bother hitting the DB.
query = []
def make_dict(row):
return dict(
stream_id = row.id,
name = row.name,
description = row.description,
invite_only = row.invite_only,
)
streams = [make_dict(row) for row in query]
streams.sort(key=lambda elt: elt["name"])
return streams
|
ns950/calibre
|
refs/heads/master
|
src/calibre/gui2/dialogs/comments_dialog.py
|
14
|
#!/usr/bin/env python2
__copyright__ = '2008, Kovid Goyal [email protected]'
__docformat__ = 'restructuredtext en'
__license__ = 'GPL v3'
from PyQt5.Qt import Qt, QDialog, QDialogButtonBox
from calibre.gui2 import gprefs, Application
from calibre.gui2.dialogs.comments_dialog_ui import Ui_CommentsDialog
from calibre.library.comments import comments_to_html
class CommentsDialog(QDialog, Ui_CommentsDialog):
def __init__(self, parent, text, column_name=None):
QDialog.__init__(self, parent)
Ui_CommentsDialog.__init__(self)
self.setupUi(self)
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
self.textbox.html = comments_to_html(text) if text else ''
self.textbox.wyswyg_dirtied()
# self.textbox.setTabChangesFocus(True)
self.buttonBox.button(QDialogButtonBox.Ok).setText(_('O&K'))
self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
if column_name:
self.setWindowTitle(_('Edit "{0}"').format(column_name))
geom = gprefs.get('comments_dialog_geom', None)
if geom is not None:
self.restoreGeometry(geom)
def save_geometry(self):
gprefs.set('comments_dialog_geom', bytearray(self.saveGeometry()))
def accept(self):
self.save_geometry()
QDialog.accept(self)
def reject(self):
self.save_geometry()
QDialog.reject(self)
def closeEvent(self, ev):
self.save_geometry()
return QDialog.closeEvent(self, ev)
if __name__ == '__main__':
app = Application([])
d = CommentsDialog(None, 'testing', 'Comments')
d.exec_()
del d
del app
|
pycontw/pycontw2016
|
refs/heads/master
|
src/users/migrations/0010_cocrecord.py
|
1
|
# Generated by Django 3.0.2 on 2020-02-23 12:28
import core.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0009_auto_20160227_1656'),
]
operations = [
migrations.CreateModel(
name='CocRecord',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('coc_version', models.CharField(max_length=15, verbose_name='latest agreed CoC version')),
('user', core.models.BigForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')),
],
),
]
|
devs1991/test_edx_docmode
|
refs/heads/master
|
venv/lib/python2.7/site-packages/edx_proctoring/callbacks.py
|
1
|
"""
Various callback paths that support callbacks from SoftwareSecure
"""
import logging
from django.template import Context, loader
from django.conf import settings
from django.http import HttpResponse
import pytz
from datetime import datetime
from ipware.ip import get_ip
from django.core.urlresolvers import reverse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.negotiation import BaseContentNegotiation
from edx_proctoring.api import (
get_exam_attempt_by_code,
mark_exam_attempt_as_ready,
update_exam_attempt
)
from edx_proctoring.backends import get_backend_provider
from edx_proctoring.exceptions import ProctoredBaseException
from edx_proctoring.models import ProctoredExamStudentAttemptStatus
log = logging.getLogger(__name__)
def start_exam_callback(request, attempt_code): # pylint: disable=unused-argument
"""
A callback endpoint which is called when SoftwareSecure completes
the proctoring setup and the exam should be started.
NOTE: This returns HTML as it will be displayed in an embedded browser
This is an authenticated endpoint and the attempt_code is passed in
as part of the URL path
IMPORTANT: This is an unauthenticated endpoint, so be VERY CAREFUL about extending
this endpoint
"""
attempt = get_exam_attempt_by_code(attempt_code)
if not attempt:
return HttpResponse(
content='You have entered an exam code that is not valid.',
status=404
)
if attempt['status'] in [ProctoredExamStudentAttemptStatus.created,
ProctoredExamStudentAttemptStatus.download_software_clicked]:
mark_exam_attempt_as_ready(attempt['proctored_exam']['id'], attempt['user']['id'])
template = loader.get_template('proctored_exam/proctoring_launch_callback.html')
poll_url = reverse(
'edx_proctoring.anonymous.proctoring_poll_status',
args=[attempt_code]
)
return HttpResponse(
template.render(
Context({
'exam_attempt_status_url': poll_url,
'platform_name': settings.PLATFORM_NAME,
'link_urls': settings.PROCTORING_SETTINGS.get('LINK_URLS', {})
})
)
)
class IgnoreClientContentNegotiation(BaseContentNegotiation):
"""
This specialized class allows for more tolerance regarding
what the passed in Content-Type is. This is taken directly
from the Django REST Framework:
http://tomchristie.github.io/rest-framework-2-docs/api-guide/content-negotiation
"""
def select_parser(self, request, parsers):
"""
Select the first parser in the `.parser_classes` list.
"""
return parsers[0]
def select_renderer(self, request, renderers, format_suffix): # pylint: disable=signature-differs
"""
Select the first renderer in the `.renderer_classes` list.
"""
return (renderers[0], renderers[0].media_type)
class ExamReviewCallback(APIView):
"""
This endpoint is called by a 3rd party proctoring review service when
there are results available for us to record
IMPORTANT: This is an unauthenticated endpoint, so be VERY CAREFUL about extending
this endpoint
"""
content_negotiation_class = IgnoreClientContentNegotiation
def post(self, request):
"""
Post callback handler
"""
provider = get_backend_provider()
# call down into the underlying provider code
try:
provider.on_review_callback(request.data)
except ProctoredBaseException, ex:
log.exception(ex)
return Response(
data={
'reason': unicode(ex)
},
status=400
)
return Response(
data='OK',
status=200
)
class AttemptStatus(APIView):
"""
This endpoint is called by a 3rd party proctoring review service to determine
status of an exam attempt.
IMPORTANT: This is an unauthenticated endpoint, so be VERY CAREFUL about extending
this endpoint
"""
def get(self, request, attempt_code): # pylint: disable=unused-argument
"""
Returns the status of an exam attempt. Given that this is an unauthenticated
caller, we will only return the status string, no additional information
about the exam
"""
attempt = get_exam_attempt_by_code(attempt_code)
ip_address = get_ip(request)
timestamp = datetime.now(pytz.UTC)
if not attempt:
return HttpResponse(
content='You have entered an exam code that is not valid.',
status=404
)
update_exam_attempt(attempt['id'], last_poll_timestamp=timestamp, last_poll_ipaddr=ip_address)
return Response(
data={
# IMPORTANT: Don't add more information to this as it is an
# unauthenticated endpoint
'status': attempt['status'],
},
status=200
)
|
awemulya/fieldsight-kobocat
|
refs/heads/master
|
kobocat/lib/python3.5/site-packages/wheel/util.py
|
345
|
"""Utility functions."""
import sys
import os
import base64
import json
import hashlib
try:
from collections import OrderedDict
except ImportError:
OrderedDict = dict
__all__ = ['urlsafe_b64encode', 'urlsafe_b64decode', 'utf8',
'to_json', 'from_json', 'matches_requirement']
def urlsafe_b64encode(data):
"""urlsafe_b64encode without padding"""
return base64.urlsafe_b64encode(data).rstrip(binary('='))
def urlsafe_b64decode(data):
"""urlsafe_b64decode without padding"""
pad = b'=' * (4 - (len(data) & 3))
return base64.urlsafe_b64decode(data + pad)
def to_json(o):
'''Convert given data to JSON.'''
return json.dumps(o, sort_keys=True)
def from_json(j):
'''Decode a JSON payload.'''
return json.loads(j)
def open_for_csv(name, mode):
if sys.version_info[0] < 3:
nl = {}
bin = 'b'
else:
nl = { 'newline': '' }
bin = ''
return open(name, mode + bin, **nl)
try:
unicode
def utf8(data):
'''Utf-8 encode data.'''
if isinstance(data, unicode):
return data.encode('utf-8')
return data
except NameError:
def utf8(data):
'''Utf-8 encode data.'''
if isinstance(data, str):
return data.encode('utf-8')
return data
try:
# For encoding ascii back and forth between bytestrings, as is repeatedly
# necessary in JSON-based crypto under Python 3
unicode
def native(s):
return s
def binary(s):
if isinstance(s, unicode):
return s.encode('ascii')
return s
except NameError:
def native(s):
if isinstance(s, bytes):
return s.decode('ascii')
return s
def binary(s):
if isinstance(s, str):
return s.encode('ascii')
class HashingFile(object):
def __init__(self, fd, hashtype='sha256'):
self.fd = fd
self.hashtype = hashtype
self.hash = hashlib.new(hashtype)
self.length = 0
def write(self, data):
self.hash.update(data)
self.length += len(data)
self.fd.write(data)
def close(self):
self.fd.close()
def digest(self):
if self.hashtype == 'md5':
return self.hash.hexdigest()
digest = self.hash.digest()
return self.hashtype + '=' + native(urlsafe_b64encode(digest))
class OrderedDefaultDict(OrderedDict):
def __init__(self, *args, **kwargs):
if not args:
self.default_factory = None
else:
if not (args[0] is None or callable(args[0])):
raise TypeError('first argument must be callable or None')
self.default_factory = args[0]
args = args[1:]
super(OrderedDefaultDict, self).__init__(*args, **kwargs)
def __missing__ (self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = default = self.default_factory()
return default
if sys.platform == 'win32':
import ctypes.wintypes
# CSIDL_APPDATA for reference - not used here for compatibility with
# dirspec, which uses LOCAL_APPDATA and COMMON_APPDATA in that order
csidl = dict(CSIDL_APPDATA=26, CSIDL_LOCAL_APPDATA=28,
CSIDL_COMMON_APPDATA=35)
def get_path(name):
SHGFP_TYPE_CURRENT = 0
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(0, csidl[name], 0, SHGFP_TYPE_CURRENT, buf)
return buf.value
def save_config_path(*resource):
appdata = get_path("CSIDL_LOCAL_APPDATA")
path = os.path.join(appdata, *resource)
if not os.path.isdir(path):
os.makedirs(path)
return path
def load_config_paths(*resource):
ids = ["CSIDL_LOCAL_APPDATA", "CSIDL_COMMON_APPDATA"]
for id in ids:
base = get_path(id)
path = os.path.join(base, *resource)
if os.path.exists(path):
yield path
else:
def save_config_path(*resource):
import xdg.BaseDirectory
return xdg.BaseDirectory.save_config_path(*resource)
def load_config_paths(*resource):
import xdg.BaseDirectory
return xdg.BaseDirectory.load_config_paths(*resource)
def matches_requirement(req, wheels):
"""List of wheels matching a requirement.
:param req: The requirement to satisfy
:param wheels: List of wheels to search.
"""
try:
from pkg_resources import Distribution, Requirement
except ImportError:
raise RuntimeError("Cannot use requirements without pkg_resources")
req = Requirement.parse(req)
selected = []
for wf in wheels:
f = wf.parsed_filename
dist = Distribution(project_name=f.group("name"), version=f.group("ver"))
if dist in req:
selected.append(wf)
return selected
|
Allianzcortex/scrapy
|
refs/heads/master
|
scrapy/http/response/text.py
|
98
|
"""
This module implements the TextResponse class which adds encoding handling and
discovering (through HTTP headers) to base Response class.
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin
from w3lib.encoding import html_to_unicode, resolve_encoding, \
html_body_declared_encoding, http_content_type_encoding
from scrapy.http.response import Response
from scrapy.utils.response import get_base_url
from scrapy.utils.python import memoizemethod_noargs, to_native_str
class TextResponse(Response):
_DEFAULT_ENCODING = 'ascii'
def __init__(self, *args, **kwargs):
self._encoding = kwargs.pop('encoding', None)
self._cached_benc = None
self._cached_ubody = None
self._cached_selector = None
super(TextResponse, self).__init__(*args, **kwargs)
def _set_url(self, url):
if isinstance(url, six.text_type):
if six.PY2 and self.encoding is None:
raise TypeError("Cannot convert unicode url - %s "
"has no encoding" % type(self).__name__)
self._url = to_native_str(url, self.encoding)
else:
super(TextResponse, self)._set_url(url)
def _set_body(self, body):
self._body = b'' # used by encoding detection
if isinstance(body, six.text_type):
if self._encoding is None:
raise TypeError('Cannot convert unicode body - %s has no encoding' %
type(self).__name__)
self._body = body.encode(self._encoding)
else:
super(TextResponse, self)._set_body(body)
def replace(self, *args, **kwargs):
kwargs.setdefault('encoding', self.encoding)
return Response.replace(self, *args, **kwargs)
@property
def encoding(self):
return self._declared_encoding() or self._body_inferred_encoding()
def _declared_encoding(self):
return self._encoding or self._headers_encoding() \
or self._body_declared_encoding()
def body_as_unicode(self):
"""Return body as unicode"""
# check for self.encoding before _cached_ubody just in
# _body_inferred_encoding is called
benc = self.encoding
if self._cached_ubody is None:
charset = 'charset=%s' % benc
self._cached_ubody = html_to_unicode(charset, self.body)[1]
return self._cached_ubody
def urljoin(self, url):
"""Join this Response's url with a possible relative url to form an
absolute interpretation of the latter."""
return urljoin(get_base_url(self), url)
@memoizemethod_noargs
def _headers_encoding(self):
content_type = self.headers.get(b'Content-Type', b'')
return http_content_type_encoding(to_native_str(content_type))
def _body_inferred_encoding(self):
if self._cached_benc is None:
content_type = to_native_str(self.headers.get(b'Content-Type', b''))
benc, ubody = html_to_unicode(content_type, self.body,
auto_detect_fun=self._auto_detect_fun,
default_encoding=self._DEFAULT_ENCODING)
self._cached_benc = benc
self._cached_ubody = ubody
return self._cached_benc
def _auto_detect_fun(self, text):
for enc in (self._DEFAULT_ENCODING, 'utf-8', 'cp1252'):
try:
text.decode(enc)
except UnicodeError:
continue
return resolve_encoding(enc)
@memoizemethod_noargs
def _body_declared_encoding(self):
return html_body_declared_encoding(self.body)
@property
def selector(self):
from scrapy.selector import Selector
if self._cached_selector is None:
self._cached_selector = Selector(self)
return self._cached_selector
def xpath(self, query):
return self.selector.xpath(query)
def css(self, query):
return self.selector.css(query)
|
nss350/magPy
|
refs/heads/master
|
utils/utilsFreq.py
|
1
|
# utility functions for frequency related stuff
import numpy as np
import numpy.fft as fft
import math
def getFrequencyArray(fs, samples):
# frequencies go from to nyquist
nyquist = fs/2
return np.linspace(0, nyquist, samples)
# use this function for all FFT calculations
# then if change FFT later (i.e. FFTW), just replace one function
def forwardFFT(data, **kwargs):
if "norm" in kwargs and not kwargs["norm"]:
return fft.rfft(data, axis=0)
return fft.rfft(data, norm='ortho', axis=0)
def inverseFFT(data, length, **kwargs):
if "norm" in kwargs and not kwargs["norm"]:
return fft.irfft(data, n=length)
return fft.irfft(data, n=length, norm='ortho')
def padNextPower2(size):
next2Power = math.ceil(math.log(size,2))
next2Size = math.pow(2, int(next2Power))
return int(next2Size) - size
|
metacademy/metacademy-application
|
refs/heads/master
|
server/apps/roadmaps/views.py
|
1
|
import difflib
import os
from operator import attrgetter
import bleach
import markdown
import re
import urlparse
import reversion
from lazysignup.templatetags.lazysignup_tags import is_lazy_user
from django.db import transaction
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.utils import safestring
from django.utils.html import escape
from django.views.decorators.csrf import csrf_exempt
from django.core.urlresolvers import reverse
from apps.graph.models import Concept
from utils.roadmap_extension import RoadmapExtension
from utils.mathjax_extension import MathJaxExtension
from forms import RoadmapForm, RoadmapSettingsForm
import models
BLEACH_TAG_WHITELIST = ['a', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul',
'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'pre',
'table', 'tr', 'th', 'tbody', 'thead', 'td', 'img', 'div']
BLEACH_ATTR_WHITELIST = {
'*': ['id', 'class'],
'a': ['href', 'rel'],
'img': ['src', 'alt', 'width', 'height']
}
# TODO what is this used for - Colorado
def metacademy_domains():
return ['']
def is_internal_link(url):
p = urlparse.urlparse(url)
if p.netloc not in metacademy_domains():
return False
return p.path.find('/concepts/') != -1
re_tag = re.compile(r'/concepts/(\w+)')
def parse_tag(url):
m = re_tag.match(url)
if m:
return m.group(1)
else:
return None
def process_link(attrs, new=False):
if is_internal_link(attrs['href']):
if Concept.objects.filter(tag=parse_tag(attrs['href'])).exists():
attrs['class'] = 'internal-link'
else:
attrs['class'] = 'internal-link missing-link'
else:
attrs['class'] = 'external-link'
attrs['target'] = '_blank'
return attrs
def wiki_link_url_builder(label, base, end):
"""
TODO allow tags and titles (how to distinguish?)
"""
res = Concept.objects.filter(title=label)
if len(res):
return base + res[0].tag
else:
return base + label
def markdown_to_html(markdown_text):
"""
converts markdown text to html using the markdown python library
"""
roadmap_ext = RoadmapExtension()
mathjax_ext = MathJaxExtension()
body_html = markdown.markdown(markdown_text,
extensions=[roadmap_ext, mathjax_ext, 'toc', 'sane_lists', 'extra', 'wikilinks(base_url=/concepts/)'],
extension_configs={'wikilinks(base_url=/concepts/)': [('build_url', wiki_link_url_builder)]})
html = bleach.clean(body_html, tags=BLEACH_TAG_WHITELIST, attributes=BLEACH_ATTR_WHITELIST)
return bleach.linkify(html, callbacks=[process_link])
def show(request, in_username, tag, vnum=-1):
try:
rm_dict = get_roadmap_objs(in_username, tag)
except:
return HttpResponse(status=404)
roadmap = rm_dict["roadmap"]
roadmap_settings = rm_dict["settings"]
if not roadmap_settings.viewable_by(request.user):
return HttpResponse(status=404)
vnum = int(vnum)
versions = _get_versions_obj(roadmap)
num_versions = len(versions)
if num_versions > vnum >= 0:
roadmap = versions[vnum].object_version.object
common_rm_dict = get_common_roadmap_dict(roadmap, roadmap_settings, request.user, in_username, tag)
return render(request, 'roadmap.html', dict({
'body_html': markdown_to_html(roadmap.body),
'num_versions': num_versions,
'page_class': "view"
}, **common_rm_dict))
def format_diff_line(line):
line = escape(line)
if line[0] == '+':
return '<ins>' + line + '</ins>'
elif line[0] == '-':
return '<del>' + line + '</del>'
else:
return line
def show_changes(request, in_username, tag, vnum=-1):
try:
rm_dict = get_roadmap_objs(in_username, tag)
except:
return HttpResponse(status=404)
roadmap = rm_dict["roadmap"]
roadmap_settings = rm_dict["settings"]
if not roadmap_settings.viewable_by(request.user):
return HttpResponse(status=404)
vnum = int(vnum)
versions = _get_versions_obj(roadmap)
num_versions = len(versions)
if num_versions > vnum >= 0:
roadmap = versions[vnum].object_version.object
curr_body = roadmap.body
curr_lines = curr_body.splitlines()
if vnum > 0:
prev_roadmap = versions[vnum - 1].object_version.object
prev_body = prev_roadmap.body
else:
prev_body = ''
prev_lines = prev_body.splitlines()
differ = difflib.Differ()
diff_lines = differ.compare(prev_lines, curr_lines)
diff_lines = filter(lambda l: l[0] != '?', diff_lines)
diff = '\n'.join(map(format_diff_line, diff_lines))
common_rm_dict = get_common_roadmap_dict(roadmap, roadmap_settings, request.user, in_username, tag)
return render(request, 'roadmap-diff.html', dict({
'diff': diff,
}, **common_rm_dict))
def show_history(request, in_username, tag):
try:
rm_dict = get_roadmap_objs(in_username, tag)
except:
return HttpResponse(status=404)
roadmap = rm_dict["roadmap"]
roadmap_settings = rm_dict["settings"]
if not roadmap_settings.viewable_by(request.user):
return HttpResponse(status=404)
cur_version_num = roadmap.version_num
revs = _get_versions_obj(roadmap)[::-1]
common_rm_dict = get_common_roadmap_dict(roadmap, roadmap_settings, request.user, in_username, tag)
return render(request, 'roadmap-history.html',
dict({"revs": revs,
'page_class': "history",
'cur_version_num': cur_version_num,
'show_change_button': True,
'show_preview_button': True
}, **common_rm_dict))
@csrf_exempt
def update_to_revision(request, in_username, tag, vnum):
"""
update the given roadmap to the specified reversion number (simply copies over the previous entry)
"""
if not request.method == "PUT":
return HttpResponse(status=403)
try:
rm_dict = get_roadmap_objs(in_username, tag)
except:
return HttpResponse(status=404)
roadmap = rm_dict["roadmap"]
roadmap_settings = rm_dict["settings"]
can_edit = roadmap_settings.editable_by(request.user)
if not can_edit:
return HttpResponse(status=401)
vnum = int(vnum)
versions = _get_versions_obj(roadmap)
num_versions = len(versions)
if 0 > vnum or vnum >= num_versions:
return HttpResponse(status=404)
versions[vnum].revision.revert()
return HttpResponse(status=200)
def _get_versions_obj(obj):
return reversion.get_for_object(obj).order_by("id")
@transaction.atomic
def edit(request, in_username, tag):
try:
rm_dict = get_roadmap_objs(in_username, tag)
except:
return HttpResponse(status=404)
roadmap = rm_dict["roadmap"]
roadmap_settings = rm_dict["settings"]
if not roadmap_settings.viewable_by(request.user):
return HttpResponse(status=404)
common_rm_dict = get_common_roadmap_dict(roadmap, roadmap_settings, request.user, in_username, tag)
can_edit = roadmap_settings.editable_by(request.user)
if request.method == 'POST':
if not (request.user.is_authenticated() and can_edit):
# TODO inform the user that they cannot edit
return HttpResponse(status=401)
form = RoadmapForm(request.POST, instance=roadmap)
if form.is_valid():
versions = _get_versions_obj(roadmap)
cur_vn = len(versions) + 1
smodel = form.save(commit=False)
smodel.version_num = cur_vn
with reversion.create_revision():
smodel.save()
reversion.set_user(request.user)
reversion.set_comment(form.cleaned_data['commit_msg'])
if request.POST["submitbutton"] == "Publish" and common_rm_dict['can_change_settings']:
roadmap_settings.published = True
roadmap_settings.save()
return HttpResponseRedirect('/roadmaps/%s/%s' % (in_username, tag))
elif request.method == 'GET':
form = RoadmapForm(instance=roadmap)
else:
return HttpResponse(status=403)
return render(request, 'roadmap-edit.html', dict({
'form': form,
'page_class': "edit",
}, **common_rm_dict))
def settings(request, in_username, tag):
# check that the user is logged in
if not request.user.is_authenticated() or is_lazy_user(request.user):
return HttpResponseRedirect(reverse("user:login"))
# get the roadmap and settings
try:
rm_dict = get_roadmap_objs(in_username, tag)
except:
return HttpResponse(status=404)
roadmap = rm_dict["roadmap"]
roadmap_settings = rm_dict["settings"]
# make sure the user is capable of changing the settings
if (not roadmap_settings.can_change_settings(request.user)):
return HttpResponse(status=401)
if request.method == 'POST':
form = RoadmapSettingsForm(request.POST, instance=roadmap_settings)
rms_sudo_listed_in_main = roadmap_settings.sudo_listed_in_main
if form.is_valid():
rs = form.save(commit=False)
if not request.user.is_superuser:
rs.sudo_listed_in_main = rms_sudo_listed_in_main
rs.save()
return HttpResponseRedirect('/roadmaps/%s/%s' % (in_username, form.data['url_tag']))
elif request.method == 'GET':
form = RoadmapSettingsForm(instance=roadmap_settings)
else:
return HttpResponse(status=403)
common_rm_dict = get_common_roadmap_dict(roadmap, roadmap_settings, request.user, in_username, tag)
return render(request, 'roadmap-settings.html', dict({
'settings_form': form,
'page_class': "settings",
}, **common_rm_dict))
# TODO refactor with edit
def new(request):
if not request.user.is_authenticated() or is_lazy_user(request.user):
return HttpResponseRedirect(reverse("user:login"))
if request.method == 'POST':
form = RoadmapForm(request.POST)
settings_form = RoadmapSettingsForm(request.POST)
is_publish = request.POST["submitbutton"] == "Publish"
if form.is_valid() and settings_form.is_valid():
with reversion.create_revision():
roadmap = form.save(commit=False)
roadmap.save()
reversion.set_user(request.user)
rms = settings_form.save(commit=False)
if not request.user.is_superuser:
rms.sudo_listed_in_main = models.RoadmapSettings._meta.get_field_by_name('sudo_listed_in_main')[0].default # TODO hack
if is_publish:
rms.published = True
rms.roadmap = roadmap
prof = request.user.profile
rms.creator = prof
rms.save()
rms.owners.add(prof)
rms.save()
return HttpResponseRedirect('/roadmaps/%s/%s'
% (request.user.username,
settings_form.cleaned_data['url_tag']))
else:
try:
initial_txt = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates/roadmap-instructions.txt")).read()
except:
sys.stderr.write("unable to open roadmap instructions txt\n")
initial_txt = ""
form = RoadmapForm(initial={'body': initial_txt})
settings_form = RoadmapSettingsForm()
return render(request, 'roadmap-new.html', {
'form': form,
'settings_form': settings_form,
'can_edit': True
})
@csrf_exempt # this is a POST request because it contains data, but there are no side effects
def preview(request):
if request.method != 'POST':
return HttpResponse(status=404)
roadmap = {
'title': request.POST['title'] if 'title' in request.POST else '',
'author': request.POST['author'] if 'author' in request.POST else '',
'audience': request.POST['audience'] if 'audience' in request.POST else '',
}
body = request.POST['body'] if 'body' in request.POST else ''
body_html = markdown_to_html(body)
return render(request, 'roadmap-content.html', {
'roadmap': roadmap,
'body_html': safestring.mark_safe(body_html),
'show_edit_link': False
})
def list_for_type(request, doc_type, pl_doc_type):
roadmaps = models.Roadmap.objects.all()
roadmaps = filter(lambda r: r.roadmapsettings.is_listed_in_main() and \
r.roadmapsettings.is_published() and \
r.roadmapsettings.doc_type == doc_type, roadmaps)
roadmaps = sorted(roadmaps, key=lambda x: x.title.lower())
return render(request, 'roadmap-list.html', {
'roadmaps': roadmaps,
'include_create': True,
'empty_message': 'Nobody has made any roadmaps yet.',
'doc_type': doc_type,
'pl_doc_type': pl_doc_type,
})
def list(request):
return list_for_type(request, 'Roadmap', 'Roadmaps')
def course_guide_list(request):
return list_for_type(request, 'Course Guide', 'Course Guides')
def list_by_user(request, in_username):
try:
user = User.objects.get(username__exact=in_username)
except User.DoesNotExist:
return HttpResponse(status=404)
roadmaps_setting = models.RoadmapSettings.objects.filter(creator=user.profile)
roadmaps = [rs.roadmap for rs in roadmaps_setting if rs.is_listed_in_main()]
roadmaps.sort(key=attrgetter("title"))
include_create = request.user.is_authenticated() and request.user.username == in_username
return render(request, 'roadmap-list.html', {
'roadmaps': roadmaps,
'include_create': include_create,
'empty_message': 'This user has not made any public roadmaps.'
})
def get_common_roadmap_dict(roadmap, roadmap_settings, user, rm_username, tag):
base_url = '/roadmaps/%s/%s' % (rm_username, tag) # TODO remove hardcoding
return {
'roadmap': roadmap,
'roadmap_settings': roadmap_settings,
'username': rm_username,
'tag': tag,
'edit_url': base_url + "/edit",
'base_url': base_url,
'is_published': roadmap_settings.is_published(),
'history_url': base_url + "/history",
'settings_url': base_url + '/settings',
'can_change_settings': roadmap_settings.can_change_settings(user),
'can_edit': roadmap_settings.editable_by(user),
'base_rev_url': base_url + '/version/'
}
def get_roadmap_objs(username, tag):
roadmap_settings = models.load_roadmap_settings(username, tag)
roadmap = roadmap_settings.roadmap
assert(roadmap is not None)
return {'roadmap': roadmap, 'settings': roadmap_settings}
|
mikemow/youtube-dl
|
refs/heads/master
|
youtube_dl/extractor/cbs.py
|
93
|
from __future__ import unicode_literals
from .common import InfoExtractor
class CBSIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?(?:cbs\.com/shows/[^/]+/(?:video|artist)|colbertlateshow\.com/(?:video|podcasts))/[^/]+/(?P<id>[^/]+)'
_TESTS = [{
'url': 'http://www.cbs.com/shows/garth-brooks/video/_u7W953k6la293J7EPTd9oHkSPs6Xn6_/connect-chat-feat-garth-brooks/',
'info_dict': {
'id': '4JUVEwq3wUT7',
'display_id': 'connect-chat-feat-garth-brooks',
'ext': 'flv',
'title': 'Connect Chat feat. Garth Brooks',
'description': 'Connect with country music singer Garth Brooks, as he chats with fans on Wednesday November 27, 2013. Be sure to tune in to Garth Brooks: Live from Las Vegas, Friday November 29, at 9/8c on CBS!',
'duration': 1495,
},
'params': {
# rtmp download
'skip_download': True,
},
'_skip': 'Blocked outside the US',
}, {
'url': 'http://www.cbs.com/shows/liveonletterman/artist/221752/st-vincent/',
'info_dict': {
'id': 'WWF_5KqY3PK1',
'display_id': 'st-vincent',
'ext': 'flv',
'title': 'Live on Letterman - St. Vincent',
'description': 'Live On Letterman: St. Vincent in concert from New York\'s Ed Sullivan Theater on Tuesday, July 16, 2014.',
'duration': 3221,
},
'params': {
# rtmp download
'skip_download': True,
},
'_skip': 'Blocked outside the US',
}, {
'url': 'http://colbertlateshow.com/video/8GmB0oY0McANFvp2aEffk9jZZZ2YyXxy/the-colbeard/',
'only_matching': True,
}, {
'url': 'http://www.colbertlateshow.com/podcasts/dYSwjqPs_X1tvbV_P2FcPWRa_qT6akTC/in-the-bad-room-with-stephen/',
'only_matching': True,
}]
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
real_id = self._search_regex(
[r"video\.settings\.pid\s*=\s*'([^']+)';", r"cbsplayer\.pid\s*=\s*'([^']+)';"],
webpage, 'real video ID')
return {
'_type': 'url_transparent',
'ie_key': 'ThePlatform',
'url': 'theplatform:%s' % real_id,
'display_id': display_id,
}
|
elibixby/gcloud-python
|
refs/heads/master
|
gcloud/pubsub/connection.py
|
6
|
# 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.
"""Create / interact with gcloud pubsub connections."""
import os
from gcloud import connection as base_connection
from gcloud.environment_vars import PUBSUB_EMULATOR
class Connection(base_connection.JSONConnection):
"""A connection to Google Cloud Pubsub via the JSON REST API.
:type credentials: :class:`oauth2client.client.OAuth2Credentials`
:param credentials: (Optional) The OAuth2 Credentials to use for this
connection.
:type http: :class:`httplib2.Http` or class that defines ``request()``.
:param http: (Optional) HTTP object to make requests.
:type api_base_url: string
:param api_base_url: The base of the API call URL. Defaults to the value
:attr:`Connection.API_BASE_URL`.
"""
API_BASE_URL = 'https://pubsub.googleapis.com'
"""The base of the API call URL."""
API_VERSION = 'v1'
"""The version of the API, used in building the API call's URL."""
API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
"""A template for the URL of a particular API call."""
SCOPE = ('https://www.googleapis.com/auth/pubsub',
'https://www.googleapis.com/auth/cloud-platform')
"""The scopes required for authenticating as a Cloud Pub/Sub consumer."""
def __init__(self, credentials=None, http=None, api_base_url=None):
super(Connection, self).__init__(credentials=credentials, http=http)
if api_base_url is None:
emulator_host = os.getenv(PUBSUB_EMULATOR)
if emulator_host is None:
api_base_url = self.__class__.API_BASE_URL
else:
api_base_url = 'http://' + emulator_host
self.api_base_url = api_base_url
def build_api_url(self, path, query_params=None,
api_base_url=None, api_version=None):
"""Construct an API url given a few components, some optional.
Typically, you shouldn't need to use this method.
:type path: string
:param path: The path to the resource.
:type query_params: dict or list
:param query_params: A dictionary of keys and values (or list of
key-value pairs) to insert into the query
string of the URL.
:type api_base_url: string
:param api_base_url: The base URL for the API endpoint.
Typically you won't have to provide this.
:type api_version: string
:param api_version: The version of the API to call.
Typically you shouldn't provide this and instead
use the default for the library.
:rtype: string
:returns: The URL assembled from the pieces provided.
"""
if api_base_url is None:
api_base_url = self.api_base_url
return super(Connection, self.__class__).build_api_url(
path, query_params=query_params,
api_base_url=api_base_url, api_version=api_version)
class _PublisherAPI(object):
"""Helper mapping publisher-related APIs.
:type connection: :class:`Connection`
:param connection: the connection used to make API requests.
"""
def __init__(self, connection):
self._connection = connection
def list_topics(self, project, page_size=None, page_token=None):
"""API call: list topics for a given project
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/list
:type project: string
:param project: project ID
:type page_size: int
:param page_size: maximum number of topics to return, If not passed,
defaults to a value set by the API.
:type page_token: string
:param page_token: opaque marker for the next "page" of topics. If not
passed, the API will return the first page of
topics.
:rtype: tuple, (list, str)
:returns: list of ``Topic`` resource dicts, plus a
"next page token" string: if not None, indicates that
more topics can be retrieved with another call (pass that
value as ``page_token``).
"""
conn = self._connection
params = {}
if page_size is not None:
params['pageSize'] = page_size
if page_token is not None:
params['pageToken'] = page_token
path = '/projects/%s/topics' % (project,)
resp = conn.api_request(method='GET', path=path, query_params=params)
return resp.get('topics', ()), resp.get('nextPageToken')
def topic_create(self, topic_path):
"""API call: create a topic
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/create
:type topic_path: string
:param topic_path: the fully-qualified path of the new topic, in format
``projects/<PROJECT>/topics/<TOPIC_NAME>``.
:rtype: dict
:returns: ``Topic`` resource returned from the API.
"""
conn = self._connection
return conn.api_request(method='PUT', path='/%s' % (topic_path,))
def topic_get(self, topic_path):
"""API call: retrieve a topic
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/get
:type topic_path: string
:param topic_path: the fully-qualified path of the topic, in format
``projects/<PROJECT>/topics/<TOPIC_NAME>``.
:rtype: dict
:returns: ``Topic`` resource returned from the API.
"""
conn = self._connection
return conn.api_request(method='GET', path='/%s' % (topic_path,))
def topic_delete(self, topic_path):
"""API call: delete a topic
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/delete
:type topic_path: string
:param topic_path: the fully-qualified path of the topic, in format
``projects/<PROJECT>/topics/<TOPIC_NAME>``.
"""
conn = self._connection
conn.api_request(method='DELETE', path='/%s' % (topic_path,))
def topic_publish(self, topic_path, messages):
"""API call: publish one or more messages to a topic
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/publish
:type topic_path: string
:param topic_path: the fully-qualified path of the topic, in format
``projects/<PROJECT>/topics/<TOPIC_NAME>``.
:type messages: list of dict
:param messages: messages to be published.
:rtype: list of string
:returns: list of opaque IDs for published messages.
"""
conn = self._connection
data = {'messages': messages}
response = conn.api_request(
method='POST', path='/%s:publish' % (topic_path,), data=data)
return response['messageIds']
def topic_list_subscriptions(self, topic_path, page_size=None,
page_token=None):
"""API call: list subscriptions bound to a topic
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics.subscriptions/list
:type topic_path: string
:param topic_path: the fully-qualified path of the topic, in format
``projects/<PROJECT>/topics/<TOPIC_NAME>``.
:type page_size: int
:param page_size: maximum number of subscriptions to return, If not
passed, defaults to a value set by the API.
:type page_token: string
:param page_token: opaque marker for the next "page" of topics. If not
passed, the API will return the first page of
topics.
:rtype: list of strings
:returns: fully-qualified names of subscriptions for the supplied
topic.
"""
conn = self._connection
params = {}
if page_size is not None:
params['pageSize'] = page_size
if page_token is not None:
params['pageToken'] = page_token
path = '/%s/subscriptions' % (topic_path,)
resp = conn.api_request(method='GET', path=path, query_params=params)
return resp.get('subscriptions', ()), resp.get('nextPageToken')
class _SubscriberAPI(object):
"""Helper mapping subscriber-related APIs.
:type connection: :class:`Connection`
:param connection: the connection used to make API requests.
"""
def __init__(self, connection):
self._connection = connection
def list_subscriptions(self, project, page_size=None, page_token=None):
"""API call: list subscriptions for a given project
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/list
:type project: string
:param project: project ID
:type page_size: int
:param page_size: maximum number of subscriptions to return, If not
passed, defaults to a value set by the API.
:type page_token: string
:param page_token: opaque marker for the next "page" of subscriptions.
If not passed, the API will return the first page
of subscriptions.
:rtype: tuple, (list, str)
:returns: list of ``Subscription`` resource dicts, plus a
"next page token" string: if not None, indicates that
more subscriptions can be retrieved with another call (pass
that value as ``page_token``).
"""
conn = self._connection
params = {}
if page_size is not None:
params['pageSize'] = page_size
if page_token is not None:
params['pageToken'] = page_token
path = '/projects/%s/subscriptions' % (project,)
resp = conn.api_request(method='GET', path=path, query_params=params)
return resp.get('subscriptions', ()), resp.get('nextPageToken')
def subscription_create(self, subscription_path, topic_path,
ack_deadline=None, push_endpoint=None):
"""API call: create a subscription
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/create
:type subscription_path: string
:param subscription_path: the fully-qualified path of the new
subscription, in format
``projects/<PROJECT>/subscriptions/<SUB_NAME>``.
:type topic_path: string
:param topic_path: the fully-qualified path of the topic being
subscribed, in format
``projects/<PROJECT>/topics/<TOPIC_NAME>``.
:type ack_deadline: int, or ``NoneType``
:param ack_deadline: the deadline (in seconds) by which messages pulled
from the back-end must be acknowledged.
:type push_endpoint: string, or ``NoneType``
:param push_endpoint: URL to which messages will be pushed by the
back-end. If not set, the application must pull
messages.
:rtype: dict
:returns: ``Subscription`` resource returned from the API.
"""
conn = self._connection
path = '/%s' % (subscription_path,)
resource = {'topic': topic_path}
if ack_deadline is not None:
resource['ackDeadlineSeconds'] = ack_deadline
if push_endpoint is not None:
resource['pushConfig'] = {'pushEndpoint': push_endpoint}
return conn.api_request(method='PUT', path=path, data=resource)
def subscription_get(self, subscription_path):
"""API call: retrieve a subscription
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/get
:type subscription_path: string
:param subscription_path: the fully-qualified path of the subscription,
in format
``projects/<PROJECT>/subscriptions/<SUB_NAME>``.
:rtype: dict
:returns: ``Subscription`` resource returned from the API.
"""
conn = self._connection
path = '/%s' % (subscription_path,)
return conn.api_request(method='GET', path=path)
def subscription_delete(self, subscription_path):
"""API call: delete a subscription
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/delete
:type subscription_path: string
:param subscription_path: the fully-qualified path of the subscription,
in format
``projects/<PROJECT>/subscriptions/<SUB_NAME>``.
"""
conn = self._connection
path = '/%s' % (subscription_path,)
conn.api_request(method='DELETE', path=path)
def subscription_modify_push_config(self, subscription_path,
push_endpoint):
"""API call: update push config of a subscription
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/modifyPushConfig
:type subscription_path: string
:param subscription_path: the fully-qualified path of the new
subscription, in format
``projects/<PROJECT>/subscriptions/<SUB_NAME>``.
:type push_endpoint: string, or ``NoneType``
:param push_endpoint: URL to which messages will be pushed by the
back-end. If not set, the application must pull
messages.
"""
conn = self._connection
path = '/%s:modifyPushConfig' % (subscription_path,)
resource = {'pushConfig': {'pushEndpoint': push_endpoint}}
conn.api_request(method='POST', path=path, data=resource)
def subscription_pull(self, subscription_path, return_immediately=False,
max_messages=1):
"""API call: retrieve messages for a subscription
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/modifyPushConfig
:type subscription_path: string
:param subscription_path: the fully-qualified path of the new
subscription, in format
``projects/<PROJECT>/subscriptions/<SUB_NAME>``.
:type return_immediately: boolean
:param return_immediately: if True, the back-end returns even if no
messages are available; if False, the API
call blocks until one or more messages are
available.
:type max_messages: int
:param max_messages: the maximum number of messages to return.
:rtype: list of dict
:returns: the ``receivedMessages`` element of the response.
"""
conn = self._connection
path = '/%s:pull' % (subscription_path,)
data = {
'returnImmediately': return_immediately,
'maxMessages': max_messages,
}
response = conn.api_request(method='POST', path=path, data=data)
return response.get('receivedMessages', ())
def subscription_acknowledge(self, subscription_path, ack_ids):
"""API call: acknowledge retrieved messages
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/modifyPushConfig
:type subscription_path: string
:param subscription_path: the fully-qualified path of the new
subscription, in format
``projects/<PROJECT>/subscriptions/<SUB_NAME>``.
:type ack_ids: list of string
:param ack_ids: ack IDs of messages being acknowledged
"""
conn = self._connection
path = '/%s:acknowledge' % (subscription_path,)
data = {
'ackIds': ack_ids,
}
conn.api_request(method='POST', path=path, data=data)
def subscription_modify_ack_deadline(self, subscription_path, ack_ids,
ack_deadline):
"""API call: update ack deadline for retrieved messages
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/modifyAckDeadline
:type subscription_path: string
:param subscription_path: the fully-qualified path of the new
subscription, in format
``projects/<PROJECT>/subscriptions/<SUB_NAME>``.
:type ack_ids: list of string
:param ack_ids: ack IDs of messages being acknowledged
:type ack_deadline: int
:param ack_deadline: the deadline (in seconds) by which messages pulled
from the back-end must be acknowledged.
"""
conn = self._connection
path = '/%s:modifyAckDeadline' % (subscription_path,)
data = {
'ackIds': ack_ids,
'ackDeadlineSeconds': ack_deadline,
}
conn.api_request(method='POST', path=path, data=data)
class _IAMPolicyAPI(object):
"""Helper mapping IAM policy-related APIs.
:type connection: :class:`Connection`
:param connection: the connection used to make API requests.
"""
def __init__(self, connection):
self._connection = connection
def get_iam_policy(self, target_path):
"""API call: fetch the IAM policy for the target
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/getIamPolicy
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/getIamPolicy
:type target_path: string
:param target_path: the path of the target object.
:rtype: dict
:returns: the resource returned by the ``getIamPolicy`` API request.
"""
conn = self._connection
path = '/%s:getIamPolicy' % (target_path,)
return conn.api_request(method='GET', path=path)
def set_iam_policy(self, target_path, policy):
"""API call: update the IAM policy for the target
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/setIamPolicy
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/setIamPolicy
:type target_path: string
:param target_path: the path of the target object.
:type policy: dict
:param policy: the new policy resource.
:rtype: dict
:returns: the resource returned by the ``setIamPolicy`` API request.
"""
conn = self._connection
wrapped = {'policy': policy}
path = '/%s:setIamPolicy' % (target_path,)
return conn.api_request(method='POST', path=path, data=wrapped)
def test_iam_permissions(self, target_path, permissions):
"""API call: test permissions
See:
https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/testIamPermissions
https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/testIamPermissions
:type target_path: string
:param target_path: the path of the target object.
:type permissions: list of string
:param permissions: the permissions to check
:rtype: dict
:returns: the resource returned by the ``getIamPolicy`` API request.
"""
conn = self._connection
wrapped = {'permissions': permissions}
path = '/%s:testIamPermissions' % (target_path,)
resp = conn.api_request(method='POST', path=path, data=wrapped)
return resp.get('permissions', [])
|
googleapis/python-spanner-django
|
refs/heads/master
|
django_spanner/creation.py
|
1
|
# Copyright 2020 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
import os
import sys
from unittest import skip
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.utils.module_loading import import_string
class DatabaseCreation(BaseDatabaseCreation):
"""
Spanner-specific wrapper for Django class encapsulating methods for
creation and destruction of the underlying test database.
"""
def mark_skips(self):
"""Skip tests that don't work on Spanner."""
for test_name in self.connection.features.skip_tests:
test_case_name, _, method_name = test_name.rpartition(".")
test_app = test_name.split(".")[0]
# Importing a test app that isn't installed raises RuntimeError.
if test_app in settings.INSTALLED_APPS:
test_case = import_string(test_case_name)
method = getattr(test_case, method_name)
setattr(
test_case,
method_name,
skip("unsupported by Spanner")(method),
)
def create_test_db(self, *args, **kwargs):
"""Create a test database.
:rtype: str
:returns: The name of the newly created test Database.
"""
# This environment variable is set by the Travis build script or
# by a developer running the tests locally.
if os.environ.get("RUNNING_SPANNER_BACKEND_TESTS") == "1":
self.mark_skips()
super().create_test_db(*args, **kwargs)
def _create_test_db(self, verbosity, autoclobber, keepdb=False):
"""
Create dummy test tables. This method is mostly copied from the
base class but removes usage of `_nodb_connection` since Spanner doesn't
have or need one.
"""
# Mostly copied from the base class but removes usage of
# _nodb_connection since Spanner doesn't have or need one.
test_database_name = self._get_test_db_name()
# Don't quote the test database name because google.cloud.spanner_v1
# does it.
test_db_params = {"dbname": test_database_name}
# Create the test database.
try:
self._execute_create_test_db(None, test_db_params, keepdb)
except Exception as e:
# If the db should be kept, then no need to do any of the below,
# just return and skip it all.
if keepdb:
return test_database_name
self.log("Got an error creating the test database: %s" % e)
if not autoclobber:
confirm = input(
"Type 'yes' if you would like to try deleting the test "
"database '%s', or 'no' to cancel: " % test_database_name
)
if autoclobber or confirm == "yes":
try:
if verbosity >= 1:
self.log(
"Destroying old test database for alias %s..."
% (
self._get_database_display_str(
verbosity, test_database_name
),
)
)
self._destroy_test_db(test_database_name, verbosity)
self._execute_create_test_db(None, test_db_params, keepdb)
except Exception as e:
self.log(
"Got an error recreating the test database: %s" % e
)
sys.exit(2)
else:
self.log("Tests cancelled.")
sys.exit(1)
return test_database_name
def _execute_create_test_db(self, cursor, parameters, keepdb=False):
self.connection.instance.database(parameters["dbname"]).create()
def _destroy_test_db(self, test_database_name, verbosity):
self.connection.instance.database(test_database_name).drop()
|
addition-it-solutions/project-all
|
refs/heads/master
|
addons/web_tests_demo/__openerp__.py
|
384
|
{
'name': "Demonstration of web/javascript tests",
'category': 'Hidden',
'description': """
OpenERP Web demo of a test suite
================================
Test suite example, same code as that used in the testing documentation.
""",
'depends': ['web'],
'data' : [
'views/web_tests_demo.xml',
],
'qweb': ['static/src/xml/demo.xml'],
}
|
tboyce021/home-assistant
|
refs/heads/dev
|
homeassistant/components/tfiac/climate.py
|
21
|
"""Climate platform that offers a climate device for the TFIAC protocol."""
from concurrent import futures
from datetime import timedelta
import logging
from pytfiac import Tfiac
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
FAN_AUTO,
FAN_HIGH,
FAN_LOW,
FAN_MEDIUM,
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_DRY,
HVAC_MODE_FAN_ONLY,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_SWING_MODE,
SUPPORT_TARGET_TEMPERATURE,
SWING_BOTH,
SWING_HORIZONTAL,
SWING_OFF,
SWING_VERTICAL,
)
from homeassistant.const import ATTR_TEMPERATURE, CONF_HOST, TEMP_FAHRENHEIT
import homeassistant.helpers.config_validation as cv
SCAN_INTERVAL = timedelta(seconds=60)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_HOST): cv.string})
_LOGGER = logging.getLogger(__name__)
MIN_TEMP = 61
MAX_TEMP = 88
HVAC_MAP = {
HVAC_MODE_HEAT: "heat",
HVAC_MODE_AUTO: "selfFeel",
HVAC_MODE_DRY: "dehumi",
HVAC_MODE_FAN_ONLY: "fan",
HVAC_MODE_COOL: "cool",
HVAC_MODE_OFF: "off",
}
HVAC_MAP_REV = {v: k for k, v in HVAC_MAP.items()}
SUPPORT_FAN = [FAN_AUTO, FAN_HIGH, FAN_MEDIUM, FAN_LOW]
SUPPORT_SWING = [SWING_OFF, SWING_HORIZONTAL, SWING_VERTICAL, SWING_BOTH]
SUPPORT_FLAGS = SUPPORT_FAN_MODE | SUPPORT_SWING_MODE | SUPPORT_TARGET_TEMPERATURE
CURR_TEMP = "current_temp"
TARGET_TEMP = "target_temp"
OPERATION_MODE = "operation"
FAN_MODE = "fan_mode"
SWING_MODE = "swing_mode"
ON_MODE = "is_on"
async def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the TFIAC climate device."""
tfiac_client = Tfiac(config[CONF_HOST])
try:
await tfiac_client.update()
except futures.TimeoutError:
_LOGGER.error("Unable to connect to %s", config[CONF_HOST])
return
async_add_devices([TfiacClimate(hass, tfiac_client)])
class TfiacClimate(ClimateEntity):
"""TFIAC class."""
def __init__(self, hass, client):
"""Init class."""
self._client = client
self._available = True
@property
def available(self):
"""Return if the device is available."""
return self._available
async def async_update(self):
"""Update status via socket polling."""
try:
await self._client.update()
self._available = True
except futures.TimeoutError:
self._available = False
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def min_temp(self):
"""Return the minimum temperature."""
return MIN_TEMP
@property
def max_temp(self):
"""Return the maximum temperature."""
return MAX_TEMP
@property
def name(self):
"""Return the name of the climate device."""
return self._client.name
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._client.status["target_temp"]
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_FAHRENHEIT
@property
def current_temperature(self):
"""Return the current temperature."""
return self._client.status["current_temp"]
@property
def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
"""
if self._client.status[ON_MODE] != "on":
return HVAC_MODE_OFF
state = self._client.status["operation"]
return HVAC_MAP_REV.get(state)
@property
def hvac_modes(self):
"""Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
"""
return list(HVAC_MAP)
@property
def fan_mode(self):
"""Return the fan setting."""
return self._client.status["fan_mode"].lower()
@property
def fan_modes(self):
"""Return the list of available fan modes."""
return SUPPORT_FAN
@property
def swing_mode(self):
"""Return the swing setting."""
return self._client.status["swing_mode"].lower()
@property
def swing_modes(self):
"""List of available swing modes."""
return SUPPORT_SWING
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temp = kwargs.get(ATTR_TEMPERATURE)
if temp is not None:
await self._client.set_state(TARGET_TEMP, temp)
async def async_set_hvac_mode(self, hvac_mode):
"""Set new target hvac mode."""
if hvac_mode == HVAC_MODE_OFF:
await self._client.set_state(ON_MODE, "off")
else:
await self._client.set_state(OPERATION_MODE, HVAC_MAP[hvac_mode])
async def async_set_fan_mode(self, fan_mode):
"""Set new fan mode."""
await self._client.set_state(FAN_MODE, fan_mode.capitalize())
async def async_set_swing_mode(self, swing_mode):
"""Set new swing mode."""
await self._client.set_swing(swing_mode.capitalize())
async def async_turn_on(self):
"""Turn device on."""
await self._client.set_state(OPERATION_MODE)
async def async_turn_off(self):
"""Turn device off."""
await self._client.set_state(ON_MODE, "off")
|
MattNolanLab/ei-attractor
|
refs/heads/master
|
grid_cell_model/simulations/simulation_demo/default_params.py
|
2
|
#
# default_params.py
#
# Default neuron and network parameters
#
# Copyright (C) 2012 Lukas Solanka <[email protected]>
#
# 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/>.
#
import numpy as np
__all__ = ['defaultParameters']
_defaultOutputDir = "output/"
y_dim = np.sqrt(3)/2.
defaultParameters = {
"Ne" : 34,
"Ni" : 34,
"delay" : 0.1, # ms
"nthreads" : 1,
"printTime" : 0, # This is boolean
"ratVelFName" : '../../../data/hafting_et_al_2005/rat_trajectory_lowpass.mat',
"gridSep" : 60, # cm
"EI_flat" : 0, # bool
"IE_flat" : 0, # bool
"use_EE" : 0, # bool
"AMPA_gaussian" : 0, # bool
"pEE_sigma" : .05,
"pAMPA_mu" : y_dim/2.0,
"pAMPA_sigma" : 0.5/6,
"pGABA_mu" : y_dim/2.0,
"pGABA_sigma" : 0.5/6,
"prefDirC_e" : 4.0,
"prefDirC_ee" : 0.0,
"prefDirC_i" : 0.0,
"arenaSize" : 180.0, # cm
"NMDA_amount" : 2.0, # %
"C_Mg" : .0, # mM; def is no Vm dependence
"probabilistic_synapses": 0, # bool
"Iext_e_const" : 300.0, # pA
"Iext_i_const" : 200.0, # pA
"Iext_e_theta" : 375.0, # pA
"Iext_i_theta" : 25.0, # pA
"theta_start_t" : 0.5e3, # ms
"theta_freq" : 8, # Hz
"taum_e" : 9.3, # ms
"taum_e_spread" : 0.31, # ms
"EL_e" : -68.5, # mV
"EL_e_spread" : 0.20, # mV
"Vt_e" : -50, # mV
"Vr_e" : -68.5, # mV
"gL_e" : 22.73, # nS
"deltaT_e" : 0.4, # mV
"E_AHP_e" : -80, # mV
"tau_AHP_e" : 20, # ms
"g_AHP_e_max" : 5.0, # nS
"t_ref_e" : 0.1, # ms
"V_peak_e" : -40, # mV
"taum_i" : 10, # ms
"taum_i_spread" : 0, # ms
"EL_i" : -60, # mV
"EL_i_spread" : 0, # mV
"Vt_i" : -45, # mV
"Vr_i" : -60, # mV
"gL_i" : 22.73, # nS
"t_ref_i" : 0.1, # ms
"deltaT_i" : 0.4, # mV
"ad_tau_i_mean" : 7.5, # ms
"ad_tau_i_std" : 0.5, # ms, Unused in the simulation for now
"ad_i_g_inc" : 22.73, # nS
"V_peak_i" : -35, # mV
"tau_AMPA" : 1, # ms
"tau_NMDA_fall" : 100, # ms, only a single exponential used here
"g_AMPA_total" : 1400, # nS
"g_uni_AMPA_total" : 0, # nS
"uni_AMPA_density" : 0.001, # fraction
"tau_GABA_A_rise" : 0.1, # ms
"tau_GABA_A_fall" : 5, # ms
"g_GABA_total" : 2160, # nS
"g_uni_GABA_frac" : 0.013, # fraction of g_GABA_total
"uni_GABA_density" : 0.4,
"g_EI_uni_density" : .1, # Probability
"g_IE_uni_density" : .1, # Probability
"use_II" : 0, # bool
"g_II_total" : 50., # nS
"g_II_uni_density" : .1, # Probability
"E_AMPA" : 0, # mV
"E_GABA_A" : -75, # mV
"N_place_cells" : 30, # sqrt(total PC number)
"pc_max_rate" : 50.0, # Hz
"pc_conn_weight" : 0.5, # nS
"pc_field_std" : 20.0, # cm
"bumpCurrentSlope" : 0.53, # neurons/s/pA, !! this will depend on prefDirC !!
"pc_start_max_rate" : 100.0, # Hz
"pc_start_conn_weight" : 5.0, # nS
"ipc_ON" : 0, # bool
"ipc_N" : 30, # sqrt(total IPC number)
"ipc_nconn" : 10,
"ipc_field_std" : 20.0, # cm
"ipc_max_rate" : 50.0, # Hz
"ipc_weight" : 0.5, # nS
"noise_sigma" : 150.0, # pA
"gammaNSample" : 25, # No. of neurons
"sim_dt" : 0.1, # ms
"Vclamp" : -50, # mV
"ntrials" : 1,
"output_dir" : _defaultOutputDir,
"stateMonDur" : 20e3, # ms
}
|
adwu73/robotframework-selenium2library
|
refs/heads/master
|
test/lib/mockito/spying.py
|
70
|
#!/usr/bin/env python
# coding: utf-8
'''Spying on real objects.'''
from invocation import RememberedProxyInvocation, VerifiableInvocation
from mocking import TestDouble
__author__ = "Serhiy Oplakanets <[email protected]>"
__copyright__ = "Copyright 2009-2010, Mockito Contributors"
__license__ = "MIT"
__maintainer__ = "Mockito Maintainers"
__email__ = "[email protected]"
__all__ = ['spy']
def spy(original_object):
return Spy(original_object)
class Spy(TestDouble):
strict = True # spies always have to check if method exists
def __init__(self, original_object):
self.original_object = original_object
self.invocations = []
self.verification = None
def __getattr__(self, name):
if self.verification:
return VerifiableInvocation(self, name)
else:
return RememberedProxyInvocation(self, name)
def remember(self, invocation):
self.invocations.insert(0, invocation)
def pull_verification(self):
v = self.verification
self.verification = None
return v
|
ahmedbodi/vertcoin
|
refs/heads/master
|
contrib/testgen/base58.py
|
45
|
# Copyright (c) 2012-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Bitcoin base58 encoding and decoding.
Based on https://bitcointalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return bytes( (n,) )
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
__b58base = len(__b58chars)
b58chars = __b58chars
def b58encode(v):
""" encode v, which is a string of bytes, to base58.
"""
long_value = 0
for (i, c) in enumerate(v[::-1]):
if isinstance(c, str):
c = ord(c)
long_value += (256**i) * c
result = ''
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == 0:
nPad += 1
else:
break
return (__b58chars[0]*nPad) + result
def b58decode(v, length = None):
""" decode v into a string of len bytes
"""
long_value = 0
for i, c in enumerate(v[::-1]):
pos = __b58chars.find(c)
assert pos != -1
long_value += pos * (__b58base**i)
result = bytes()
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result
nPad = 0
for c in v:
if c == __b58chars[0]:
nPad += 1
continue
break
result = bytes(nPad) + result
if length is not None and len(result) != length:
return None
return result
def checksum(v):
"""Return 32-bit checksum based on SHA256"""
return SHA256.new(SHA256.new(v).digest()).digest()[0:4]
def b58encode_chk(v):
"""b58encode a string, with 32-bit checksum"""
return b58encode(v + checksum(v))
def b58decode_chk(v):
"""decode a base58 string, check and remove checksum"""
result = b58decode(v)
if result is None:
return None
if result[-4:] == checksum(result[:-4]):
return result[:-4]
else:
return None
def get_bcaddress_version(strAddress):
""" Returns None if strAddress is invalid. Otherwise returns integer version of address. """
addr = b58decode_chk(strAddress)
if addr is None or len(addr)!=21:
return None
version = addr[0]
return ord(version)
if __name__ == '__main__':
# Test case (from http://gitorious.org/bitcoin/python-base58.git)
assert get_bcaddress_version('15VjRaDX9zpbA8LVnbrCAFzrVzN7ixHNsC') is 0
_ohai = 'o hai'.encode('ascii')
_tmp = b58encode(_ohai)
assert _tmp == 'DYB3oMS'
assert b58decode(_tmp, 5) == _ohai
print("Tests passed")
|
vitan/hue
|
refs/heads/master
|
desktop/core/ext-py/tablib-develop/tablib/packages/xlwt/Row.py
|
57
|
# -*- coding: windows-1252 -*-
import BIFFRecords
import Style
from Cell import StrCell, BlankCell, NumberCell, FormulaCell, MulBlankCell, BooleanCell, ErrorCell, \
_get_cells_biff_data_mul
import ExcelFormula
import datetime as dt
try:
from decimal import Decimal
except ImportError:
# Python 2.3: decimal not supported; create dummy Decimal class
class Decimal(object):
pass
class Row(object):
__slots__ = [# private variables
"__idx",
"__parent",
"__parent_wb",
"__cells",
"__min_col_idx",
"__max_col_idx",
"__xf_index",
"__has_default_xf_index",
"__height_in_pixels",
# public variables
"height",
"has_default_height",
"height_mismatch",
"level",
"collapse",
"hidden",
"space_above",
"space_below"]
def __init__(self, rowx, parent_sheet):
if not (isinstance(rowx, int) and 0 <= rowx <= 65535):
raise ValueError("row index (%r) not an int in range(65536)" % rowx)
self.__idx = rowx
self.__parent = parent_sheet
self.__parent_wb = parent_sheet.get_parent()
self.__cells = {}
self.__min_col_idx = 0
self.__max_col_idx = 0
self.__xf_index = 0x0F
self.__has_default_xf_index = 0
self.__height_in_pixels = 0x11
self.height = 0x00FF
self.has_default_height = 0x00
self.height_mismatch = 0
self.level = 0
self.collapse = 0
self.hidden = 0
self.space_above = 0
self.space_below = 0
def __adjust_height(self, style):
twips = style.font.height
points = float(twips)/20.0
# Cell height in pixels can be calcuted by following approx. formula:
# cell height in pixels = font height in points * 83/50 + 2/5
# It works when screen resolution is 96 dpi
pix = int(round(points*83.0/50.0 + 2.0/5.0))
if pix > self.__height_in_pixels:
self.__height_in_pixels = pix
def __adjust_bound_col_idx(self, *args):
for arg in args:
iarg = int(arg)
if not ((0 <= iarg <= 255) and arg == iarg):
raise ValueError("column index (%r) not an int in range(256)" % arg)
sheet = self.__parent
if iarg < self.__min_col_idx:
self.__min_col_idx = iarg
if iarg > self.__max_col_idx:
self.__max_col_idx = iarg
if iarg < sheet.first_used_col:
sheet.first_used_col = iarg
if iarg > sheet.last_used_col:
sheet.last_used_col = iarg
def __excel_date_dt(self, date):
if isinstance(date, dt.date) and (not isinstance(date, dt.datetime)):
epoch = dt.date(1899, 12, 31)
elif isinstance(date, dt.time):
date = dt.datetime.combine(dt.datetime(1900, 1, 1), date)
epoch = dt.datetime(1900, 1, 1, 0, 0, 0)
else:
epoch = dt.datetime(1899, 12, 31, 0, 0, 0)
delta = date - epoch
xldate = delta.days + float(delta.seconds) / (24*60*60)
# Add a day for Excel's missing leap day in 1900
if xldate > 59:
xldate += 1
return xldate
def get_height_in_pixels(self):
return self.__height_in_pixels
def set_style(self, style):
self.__adjust_height(style)
self.__xf_index = self.__parent_wb.add_style(style)
self.__has_default_xf_index = 1
def get_xf_index(self):
return self.__xf_index
def get_cells_count(self):
return len(self.__cells)
def get_min_col(self):
return self.__min_col_idx
def get_max_col(self):
return self.__max_col_idx
def get_row_biff_data(self):
height_options = (self.height & 0x07FFF)
height_options |= (self.has_default_height & 0x01) << 15
options = (self.level & 0x07) << 0
options |= (self.collapse & 0x01) << 4
options |= (self.hidden & 0x01) << 5
options |= (self.height_mismatch & 0x01) << 6
options |= (self.__has_default_xf_index & 0x01) << 7
options |= (0x01 & 0x01) << 8
options |= (self.__xf_index & 0x0FFF) << 16
options |= (self.space_above & 1) << 28
options |= (self.space_below & 1) << 29
return BIFFRecords.RowRecord(self.__idx, self.__min_col_idx,
self.__max_col_idx, height_options, options).get()
def insert_cell(self, col_index, cell_obj):
if col_index in self.__cells:
if not self.__parent._cell_overwrite_ok:
msg = "Attempt to overwrite cell: sheetname=%r rowx=%d colx=%d" \
% (self.__parent.name, self.__idx, col_index)
raise Exception(msg)
prev_cell_obj = self.__cells[col_index]
sst_idx = getattr(prev_cell_obj, 'sst_idx', None)
if sst_idx is not None:
self.__parent_wb.del_str(sst_idx)
self.__cells[col_index] = cell_obj
def insert_mulcells(self, colx1, colx2, cell_obj):
self.insert_cell(colx1, cell_obj)
for col_index in xrange(colx1+1, colx2+1):
self.insert_cell(col_index, None)
def get_cells_biff_data(self):
cell_items = [item for item in self.__cells.iteritems() if item[1] is not None]
cell_items.sort() # in column order
return _get_cells_biff_data_mul(self.__idx, cell_items)
# previously:
# return ''.join([cell.get_biff_data() for colx, cell in cell_items])
def get_index(self):
return self.__idx
def set_cell_text(self, colx, value, style=Style.default_style):
self.__adjust_height(style)
self.__adjust_bound_col_idx(colx)
xf_index = self.__parent_wb.add_style(style)
self.insert_cell(colx, StrCell(self.__idx, colx, xf_index, self.__parent_wb.add_str(value)))
def set_cell_blank(self, colx, style=Style.default_style):
self.__adjust_height(style)
self.__adjust_bound_col_idx(colx)
xf_index = self.__parent_wb.add_style(style)
self.insert_cell(colx, BlankCell(self.__idx, colx, xf_index))
def set_cell_mulblanks(self, first_colx, last_colx, style=Style.default_style):
assert 0 <= first_colx <= last_colx <= 255
self.__adjust_height(style)
self.__adjust_bound_col_idx(first_colx, last_colx)
xf_index = self.__parent_wb.add_style(style)
# ncols = last_colx - first_colx + 1
self.insert_mulcells(first_colx, last_colx, MulBlankCell(self.__idx, first_colx, last_colx, xf_index))
def set_cell_number(self, colx, number, style=Style.default_style):
self.__adjust_height(style)
self.__adjust_bound_col_idx(colx)
xf_index = self.__parent_wb.add_style(style)
self.insert_cell(colx, NumberCell(self.__idx, colx, xf_index, number))
def set_cell_date(self, colx, datetime_obj, style=Style.default_style):
self.__adjust_height(style)
self.__adjust_bound_col_idx(colx)
xf_index = self.__parent_wb.add_style(style)
self.insert_cell(colx,
NumberCell(self.__idx, colx, xf_index, self.__excel_date_dt(datetime_obj)))
def set_cell_formula(self, colx, formula, style=Style.default_style, calc_flags=0):
self.__adjust_height(style)
self.__adjust_bound_col_idx(colx)
xf_index = self.__parent_wb.add_style(style)
self.__parent_wb.add_sheet_reference(formula)
self.insert_cell(colx, FormulaCell(self.__idx, colx, xf_index, formula, calc_flags=0))
def set_cell_boolean(self, colx, value, style=Style.default_style):
self.__adjust_height(style)
self.__adjust_bound_col_idx(colx)
xf_index = self.__parent_wb.add_style(style)
self.insert_cell(colx, BooleanCell(self.__idx, colx, xf_index, bool(value)))
def set_cell_error(self, colx, error_string_or_code, style=Style.default_style):
self.__adjust_height(style)
self.__adjust_bound_col_idx(colx)
xf_index = self.__parent_wb.add_style(style)
self.insert_cell(colx, ErrorCell(self.__idx, colx, xf_index, error_string_or_code))
def write(self, col, label, style=Style.default_style):
self.__adjust_height(style)
self.__adjust_bound_col_idx(col)
style_index = self.__parent_wb.add_style(style)
if isinstance(label, basestring):
if len(label) > 0:
self.insert_cell(col,
StrCell(self.__idx, col, style_index, self.__parent_wb.add_str(label))
)
else:
self.insert_cell(col, BlankCell(self.__idx, col, style_index))
elif isinstance(label, bool): # bool is subclass of int; test bool first
self.insert_cell(col, BooleanCell(self.__idx, col, style_index, label))
elif isinstance(label, (float, int, long, Decimal)):
self.insert_cell(col, NumberCell(self.__idx, col, style_index, label))
elif isinstance(label, (dt.datetime, dt.date, dt.time)):
date_number = self.__excel_date_dt(label)
self.insert_cell(col, NumberCell(self.__idx, col, style_index, date_number))
elif label is None:
self.insert_cell(col, BlankCell(self.__idx, col, style_index))
elif isinstance(label, ExcelFormula.Formula):
self.__parent_wb.add_sheet_reference(label)
self.insert_cell(col, FormulaCell(self.__idx, col, style_index, label))
else:
raise Exception("Unexpected data type %r" % type(label))
write_blanks = set_cell_mulblanks
|
joeythesaint/yocto-autobuilder
|
refs/heads/master
|
lib/python2.7/site-packages/sqlalchemy_migrate-0.6-py2.6.egg/migrate/tests/versioning/test_shell.py
|
5
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import tempfile
try:
from runpy import run_module
except ImportError:
pass #python2.4
from sqlalchemy import MetaData, Table
from nose.plugins.skip import SkipTest
from migrate.versioning.repository import Repository
from migrate.versioning import genmodel, shell, api
from migrate.versioning.exceptions import *
from migrate.tests.fixture import Shell, DB, usedb
from migrate.tests.fixture import models
class TestShellCommands(Shell):
"""Tests migrate.py commands"""
def test_help(self):
"""Displays default help dialog"""
self.assertEqual(self.env.run('migrate -h').returncode, 0)
self.assertEqual(self.env.run('migrate --help').returncode, 0)
self.assertEqual(self.env.run('migrate help').returncode, 0)
def test_help_commands(self):
"""Display help on a specific command"""
# we can only test that we get some output
for cmd in api.__all__:
result = self.env.run('migrate help %s' % cmd)
self.assertTrue(isinstance(result.stdout, basestring))
self.assertTrue(result.stdout)
self.assertFalse(result.stderr)
def test_shutdown_logging(self):
"""Try to shutdown logging output"""
repos = self.tmp_repos()
result = self.env.run('migrate create %s repository_name' % repos)
result = self.env.run('migrate version %s --disable_logging' % repos)
self.assertEqual(result.stdout, '')
result = self.env.run('migrate version %s -q' % repos)
self.assertEqual(result.stdout, '')
# TODO: assert logging messages to 0
shell.main(['version', repos], logging=False)
def test_main_with_runpy(self):
if sys.version_info[:2] == (2, 4):
raise SkipTest("runpy is not part of python2.4")
try:
run_module('migrate.versioning.shell', run_name='__main__')
except:
pass
def test_main(self):
"""Test main() function"""
# TODO: test output?
repos = self.tmp_repos()
shell.main(['help'])
shell.main(['help', 'create'])
shell.main(['create', 'repo_name', '--preview_sql'], repository=repos)
shell.main(['version', '--', '--repository=%s' % repos])
shell.main(['version', '-d', '--repository=%s' % repos, '--version=2'])
try:
shell.main(['foobar'])
except SystemExit, e:
pass
try:
shell.main(['create', 'f', 'o', 'o'])
except SystemExit, e:
pass
try:
shell.main(['create'])
except SystemExit, e:
pass
try:
shell.main(['create', 'repo_name'], repository=repos)
except SystemExit, e:
pass
def test_create(self):
"""Repositories are created successfully"""
repos = self.tmp_repos()
# Creating a file that doesn't exist should succeed
result = self.env.run('migrate create %s repository_name' % repos)
# Files should actually be created
self.assert_(os.path.exists(repos))
# The default table should not be None
repos_ = Repository(repos)
self.assertNotEquals(repos_.config.get('db_settings', 'version_table'), 'None')
# Can't create it again: it already exists
result = self.env.run('migrate create %s repository_name' % repos,
expect_error=True)
self.assertEqual(result.returncode, 2)
def test_script(self):
"""We can create a migration script via the command line"""
repos = self.tmp_repos()
result = self.env.run('migrate create %s repository_name' % repos)
result = self.env.run('migrate script --repository=%s Desc' % repos)
self.assert_(os.path.exists('%s/versions/001_Desc.py' % repos))
result = self.env.run('migrate script More %s' % repos)
self.assert_(os.path.exists('%s/versions/002_More.py' % repos))
result = self.env.run('migrate script "Some Random name" %s' % repos)
self.assert_(os.path.exists('%s/versions/003_Some_Random_name.py' % repos))
def test_script_sql(self):
"""We can create a migration sql script via the command line"""
repos = self.tmp_repos()
result = self.env.run('migrate create %s repository_name' % repos)
result = self.env.run('migrate script_sql mydb %s' % repos)
self.assert_(os.path.exists('%s/versions/001_mydb_upgrade.sql' % repos))
self.assert_(os.path.exists('%s/versions/001_mydb_downgrade.sql' % repos))
# Test creating a second
result = self.env.run('migrate script_sql postgres --repository=%s' % repos)
self.assert_(os.path.exists('%s/versions/002_postgres_upgrade.sql' % repos))
self.assert_(os.path.exists('%s/versions/002_postgres_downgrade.sql' % repos))
# TODO: test --previews
def test_manage(self):
"""Create a project management script"""
script = self.tmp_py()
self.assert_(not os.path.exists(script))
# No attempt is made to verify correctness of the repository path here
result = self.env.run('migrate manage %s --repository=/bla/' % script)
self.assert_(os.path.exists(script))
class TestShellRepository(Shell):
"""Shell commands on an existing repository/python script"""
def setUp(self):
"""Create repository, python change script"""
super(TestShellRepository, self).setUp()
self.path_repos = self.tmp_repos()
result = self.env.run('migrate create %s repository_name' % self.path_repos)
def test_version(self):
"""Correctly detect repository version"""
# Version: 0 (no scripts yet); successful execution
result = self.env.run('migrate version --repository=%s' % self.path_repos)
self.assertEqual(result.stdout.strip(), "0")
# Also works as a positional param
result = self.env.run('migrate version %s' % self.path_repos)
self.assertEqual(result.stdout.strip(), "0")
# Create a script and version should increment
result = self.env.run('migrate script Desc %s' % self.path_repos)
result = self.env.run('migrate version %s' % self.path_repos)
self.assertEqual(result.stdout.strip(), "1")
def test_source(self):
"""Correctly fetch a script's source"""
result = self.env.run('migrate script Desc --repository=%s' % self.path_repos)
filename = '%s/versions/001_Desc.py' % self.path_repos
source = open(filename).read()
self.assert_(source.find('def upgrade') >= 0)
# Version is now 1
result = self.env.run('migrate version %s' % self.path_repos)
self.assertEqual(result.stdout.strip(), "1")
# Output/verify the source of version 1
result = self.env.run('migrate source 1 --repository=%s' % self.path_repos)
self.assertEqual(result.stdout.strip(), source.strip())
# We can also send the source to a file... test that too
result = self.env.run('migrate source 1 %s --repository=%s' %
(filename, self.path_repos))
self.assert_(os.path.exists(filename))
fd = open(filename)
result = fd.read()
self.assert_(result.strip() == source.strip())
class TestShellDatabase(Shell, DB):
"""Commands associated with a particular database"""
# We'll need to clean up after ourself, since the shell creates its own txn;
# we need to connect to the DB to see if things worked
level = DB.CONNECT
@usedb()
def test_version_control(self):
"""Ensure we can set version control on a database"""
path_repos = repos = self.tmp_repos()
url = self.url
result = self.env.run('migrate create %s repository_name' % repos)
result = self.env.run('migrate drop_version_control %(url)s %(repos)s'\
% locals(), expect_error=True)
self.assertEqual(result.returncode, 1)
result = self.env.run('migrate version_control %(url)s %(repos)s' % locals())
# Clean up
result = self.env.run('migrate drop_version_control %(url)s %(repos)s' % locals())
# Attempting to drop vc from a database without it should fail
result = self.env.run('migrate drop_version_control %(url)s %(repos)s'\
% locals(), expect_error=True)
self.assertEqual(result.returncode, 1)
@usedb()
def test_wrapped_kwargs(self):
"""Commands with default arguments set by manage.py"""
path_repos = repos = self.tmp_repos()
url = self.url
result = self.env.run('migrate create --name=repository_name %s' % repos)
result = self.env.run('migrate drop_version_control %(url)s %(repos)s' % locals(), expect_error=True)
self.assertEqual(result.returncode, 1)
result = self.env.run('migrate version_control %(url)s %(repos)s' % locals())
result = self.env.run('migrate drop_version_control %(url)s %(repos)s' % locals())
@usedb()
def test_version_control_specified(self):
"""Ensure we can set version control to a particular version"""
path_repos = self.tmp_repos()
url = self.url
result = self.env.run('migrate create --name=repository_name %s' % path_repos)
result = self.env.run('migrate drop_version_control %(url)s %(path_repos)s' % locals(), expect_error=True)
self.assertEqual(result.returncode, 1)
# Fill the repository
path_script = self.tmp_py()
version = 2
for i in range(version):
result = self.env.run('migrate script Desc --repository=%s' % path_repos)
# Repository version is correct
result = self.env.run('migrate version %s' % path_repos)
self.assertEqual(result.stdout.strip(), str(version))
# Apply versioning to DB
result = self.env.run('migrate version_control %(url)s %(path_repos)s %(version)s' % locals())
# Test db version number (should start at 2)
result = self.env.run('migrate db_version %(url)s %(path_repos)s' % locals())
self.assertEqual(result.stdout.strip(), str(version))
# Clean up
result = self.env.run('migrate drop_version_control %(url)s %(path_repos)s' % locals())
@usedb()
def test_upgrade(self):
"""Can upgrade a versioned database"""
# Create a repository
repos_name = 'repos_name'
repos_path = self.tmp()
result = self.env.run('migrate create %(repos_path)s %(repos_name)s' % locals())
self.assertEquals(self.run_version(repos_path), 0)
# Version the DB
result = self.env.run('migrate drop_version_control %s %s' % (self.url, repos_path), expect_error=True)
result = self.env.run('migrate version_control %s %s' % (self.url, repos_path))
# Upgrades with latest version == 0
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
result = self.env.run('migrate upgrade %s %s' % (self.url, repos_path))
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
result = self.env.run('migrate upgrade %s %s' % (self.url, repos_path))
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
result = self.env.run('migrate upgrade %s %s 1' % (self.url, repos_path), expect_error=True)
self.assertEquals(result.returncode, 1)
result = self.env.run('migrate upgrade %s %s -1' % (self.url, repos_path), expect_error=True)
self.assertEquals(result.returncode, 2)
# Add a script to the repository; upgrade the db
result = self.env.run('migrate script Desc --repository=%s' % (repos_path))
self.assertEquals(self.run_version(repos_path), 1)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
# Test preview
result = self.env.run('migrate upgrade %s %s 0 --preview_sql' % (self.url, repos_path))
result = self.env.run('migrate upgrade %s %s 0 --preview_py' % (self.url, repos_path))
result = self.env.run('migrate upgrade %s %s' % (self.url, repos_path))
self.assertEquals(self.run_db_version(self.url, repos_path), 1)
# Downgrade must have a valid version specified
result = self.env.run('migrate downgrade %s %s' % (self.url, repos_path), expect_error=True)
self.assertEquals(result.returncode, 2)
result = self.env.run('migrate downgrade %s %s -1' % (self.url, repos_path), expect_error=True)
self.assertEquals(result.returncode, 2)
result = self.env.run('migrate downgrade %s %s 2' % (self.url, repos_path), expect_error=True)
self.assertEquals(result.returncode, 2)
self.assertEquals(self.run_db_version(self.url, repos_path), 1)
result = self.env.run('migrate downgrade %s %s 0' % (self.url, repos_path))
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
result = self.env.run('migrate downgrade %s %s 1' % (self.url, repos_path), expect_error=True)
self.assertEquals(result.returncode, 2)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
result = self.env.run('migrate drop_version_control %s %s' % (self.url, repos_path))
def _run_test_sqlfile(self, upgrade_script, downgrade_script):
# TODO: add test script that checks if db really changed
repos_path = self.tmp()
repos_name = 'repos'
result = self.env.run('migrate create %s %s' % (repos_path, repos_name))
result = self.env.run('migrate drop_version_control %s %s' % (self.url, repos_path), expect_error=True)
result = self.env.run('migrate version_control %s %s' % (self.url, repos_path))
self.assertEquals(self.run_version(repos_path), 0)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
beforeCount = len(os.listdir(os.path.join(repos_path, 'versions'))) # hmm, this number changes sometimes based on running from svn
result = self.env.run('migrate script_sql %s --repository=%s' % ('postgres', repos_path))
self.assertEquals(self.run_version(repos_path), 1)
self.assertEquals(len(os.listdir(os.path.join(repos_path, 'versions'))), beforeCount + 2)
open('%s/versions/001_postgres_upgrade.sql' % repos_path, 'a').write(upgrade_script)
open('%s/versions/001_postgres_downgrade.sql' % repos_path, 'a').write(downgrade_script)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
self.assertRaises(Exception, self.engine.text('select * from t_table').execute)
result = self.env.run('migrate upgrade %s %s' % (self.url, repos_path))
self.assertEquals(self.run_db_version(self.url, repos_path), 1)
self.engine.text('select * from t_table').execute()
result = self.env.run('migrate downgrade %s %s 0' % (self.url, repos_path))
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
self.assertRaises(Exception, self.engine.text('select * from t_table').execute)
# The tests below are written with some postgres syntax, but the stuff
# being tested (.sql files) ought to work with any db.
@usedb(supported='postgres')
def test_sqlfile(self):
upgrade_script = """
create table t_table (
id serial,
primary key(id)
);
"""
downgrade_script = """
drop table t_table;
"""
self.meta.drop_all()
self._run_test_sqlfile(upgrade_script, downgrade_script)
@usedb(supported='postgres')
def test_sqlfile_comment(self):
upgrade_script = """
-- Comments in SQL break postgres autocommit
create table t_table (
id serial,
primary key(id)
);
"""
downgrade_script = """
-- Comments in SQL break postgres autocommit
drop table t_table;
"""
self._run_test_sqlfile(upgrade_script, downgrade_script)
@usedb()
def test_command_test(self):
repos_name = 'repos_name'
repos_path = self.tmp()
result = self.env.run('migrate create repository_name --repository=%s' % repos_path)
result = self.env.run('migrate drop_version_control %s %s' % (self.url, repos_path), expect_error=True)
result = self.env.run('migrate version_control %s %s' % (self.url, repos_path))
self.assertEquals(self.run_version(repos_path), 0)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
# Empty script should succeed
result = self.env.run('migrate script Desc %s' % repos_path)
result = self.env.run('migrate test %s %s' % (self.url, repos_path))
self.assertEquals(self.run_version(repos_path), 1)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
# Error script should fail
script_path = self.tmp_py()
script_text='''
from sqlalchemy import *
from migrate import *
def upgrade():
print 'fgsfds'
raise Exception()
def downgrade():
print 'sdfsgf'
raise Exception()
'''.replace("\n ", "\n")
file = open(script_path, 'w')
file.write(script_text)
file.close()
result = self.env.run('migrate test %s %s bla' % (self.url, repos_path), expect_error=True)
self.assertEqual(result.returncode, 2)
self.assertEquals(self.run_version(repos_path), 1)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
# Nonempty script using migrate_engine should succeed
script_path = self.tmp_py()
script_text = '''
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
meta = MetaData(migrate_engine)
account = Table('account', meta,
Column('id', Integer, primary_key=True),
Column('login', Text),
Column('passwd', Text),
)
def upgrade():
# Upgrade operations go here. Don't create your own engine; use the engine
# named 'migrate_engine' imported from migrate.
meta.create_all()
def downgrade():
# Operations to reverse the above upgrade go here.
meta.drop_all()
'''.replace("\n ", "\n")
file = open(script_path, 'w')
file.write(script_text)
file.close()
result = self.env.run('migrate test %s %s' % (self.url, repos_path))
self.assertEquals(self.run_version(repos_path), 1)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
@usedb()
def test_rundiffs_in_shell(self):
# This is a variant of the test_schemadiff tests but run through the shell level.
# These shell tests are hard to debug (since they keep forking processes)
# so they shouldn't replace the lower-level tests.
repos_name = 'repos_name'
repos_path = self.tmp()
script_path = self.tmp_py()
model_module = 'migrate.tests.fixture.models:meta_rundiffs'
old_model_module = 'migrate.tests.fixture.models:meta_old_rundiffs'
# Create empty repository.
self.meta = MetaData(self.engine, reflect=True)
self.meta.reflect()
self.meta.drop_all() # in case junk tables are lying around in the test database
result = self.env.run('migrate create %s %s' % (repos_path, repos_name))
result = self.env.run('migrate drop_version_control %s %s' % (self.url, repos_path), expect_error=True)
result = self.env.run('migrate version_control %s %s' % (self.url, repos_path))
self.assertEquals(self.run_version(repos_path), 0)
self.assertEquals(self.run_db_version(self.url, repos_path), 0)
# Setup helper script.
result = self.env.run('migrate manage %s --repository=%s --url=%s --model=%s'\
% (script_path, repos_path, self.url, model_module))
self.assert_(os.path.exists(script_path))
# Model is defined but database is empty.
result = self.env.run('migrate compare_model_to_db %s %s --model=%s' \
% (self.url, repos_path, model_module))
self.assert_("tables missing in database: tmp_account_rundiffs" in result.stdout)
# Test Deprecation
result = self.env.run('migrate compare_model_to_db %s %s --model=%s' \
% (self.url, repos_path, model_module.replace(":", ".")), expect_error=True)
self.assertEqual(result.returncode, 0)
self.assertTrue("DeprecationWarning" in result.stderr)
self.assert_("tables missing in database: tmp_account_rundiffs" in result.stdout)
# Update db to latest model.
result = self.env.run('migrate update_db_from_model %s %s %s'\
% (self.url, repos_path, model_module))
self.assertEquals(self.run_version(repos_path), 0)
self.assertEquals(self.run_db_version(self.url, repos_path), 0) # version did not get bumped yet because new version not yet created
result = self.env.run('migrate compare_model_to_db %s %s %s'\
% (self.url, repos_path, model_module))
self.assert_("No schema diffs" in result.stdout)
result = self.env.run('migrate drop_version_control %s %s' % (self.url, repos_path), expect_error=True)
result = self.env.run('migrate version_control %s %s' % (self.url, repos_path))
result = self.env.run('migrate create_model %s %s' % (self.url, repos_path))
temp_dict = dict()
exec result.stdout in temp_dict
# TODO: breaks on SA06 and SA05 - in need of total refactor - use different approach
# TODO: compare whole table
self.compare_columns_equal(models.tmp_account_rundiffs.c, temp_dict['tmp_account_rundiffs'].c, ['type'])
##self.assertTrue("""tmp_account_rundiffs = Table('tmp_account_rundiffs', meta,
##Column('id', Integer(), primary_key=True, nullable=False),
##Column('login', String(length=None, convert_unicode=False, assert_unicode=None)),
##Column('passwd', String(length=None, convert_unicode=False, assert_unicode=None))""" in result.stdout)
## We're happy with db changes, make first db upgrade script to go from version 0 -> 1.
#result = self.env.run('migrate make_update_script_for_model', expect_error=True)
#self.assertTrue('Not enough arguments' in result.stderr)
#result_script = self.env.run('migrate make_update_script_for_model %s %s %s %s'\
#% (self.url, repos_path, old_model_module, model_module))
#self.assertEqualsIgnoreWhitespace(result_script.stdout,
#'''from sqlalchemy import *
#from migrate import *
#from migrate.changeset import schema
#meta = MetaData()
#tmp_account_rundiffs = Table('tmp_account_rundiffs', meta,
#Column('id', Integer(), primary_key=True, nullable=False),
#Column('login', Text(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False)),
#Column('passwd', Text(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False)),
#)
#def upgrade(migrate_engine):
## Upgrade operations go here. Don't create your own engine; bind migrate_engine
## to your metadata
#meta.bind = migrate_engine
#tmp_account_rundiffs.create()
#def downgrade(migrate_engine):
## Operations to reverse the above upgrade go here.
#meta.bind = migrate_engine
#tmp_account_rundiffs.drop()''')
## Save the upgrade script.
#result = self.env.run('migrate script Desc %s' % repos_path)
#upgrade_script_path = '%s/versions/001_Desc.py' % repos_path
#open(upgrade_script_path, 'w').write(result_script.stdout)
#result = self.env.run('migrate compare_model_to_db %s %s %s'\
#% (self.url, repos_path, model_module))
#self.assert_("No schema diffs" in result.stdout)
self.meta.drop_all() # in case junk tables are lying around in the test database
|
globality-corp/microcosm
|
refs/heads/develop
|
microcosm/loaders/keys.py
|
1
|
"""
Key expansion.
"""
from typing import (
Any,
Callable,
Dict,
List,
)
def expand_config(
dct: Dict[Any, Any],
separator: str = '.',
skip_to: int = 0,
key_func: Callable[[str], str] = lambda key: key.lower(),
key_parts_filter: Callable[[List[str]], bool] = lambda key_parts: True,
value_func: Callable[[str], str] = lambda value: value
):
"""
Expand a dictionary recursively by splitting keys along the separator.
:param dct: a non-recursive dictionary
:param separator: a separator character for splitting dictionary keys
:param skip_to: index to start splitting keys on; can be used to skip over a key prefix
:param key_func: a key mapping function
:param key_parts_filter: a filter function for excluding keys
:param value_func: a value mapping func
"""
config: Dict[str, Any] = {}
for key, value in dct.items():
key_separator = separator(key) if callable(separator) else separator
key_parts = key.split(key_separator)
if not key_parts_filter(key_parts):
continue
key_config = config
# skip prefix
for key_part in key_parts[skip_to:-1]:
key_config = key_config.setdefault(key_func(key_part), dict())
key_config[key_func(key_parts[-1])] = value_func(value)
return config
|
toshywoshy/ansible
|
refs/heads/devel
|
lib/ansible/modules/cloud/openstack/os_image_info.py
|
20
|
#!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: os_image_info
short_description: Retrieve information about an image within OpenStack.
version_added: "2.0"
author: "Davide Agnello (@dagnello)"
description:
- Retrieve information about a image image from OpenStack.
- This module was called C(os_image_facts) before Ansible 2.9, returning C(ansible_facts).
Note that the M(os_image_info) module no longer returns C(ansible_facts)!
requirements:
- "python >= 2.7"
- "openstacksdk"
options:
image:
description:
- Name or ID of the image
required: false
properties:
description:
- Dict of properties of the images used for query
type: dict
required: false
version_added: '2.9'
availability_zone:
description:
- Ignored. Present for backwards compatibility
required: false
extends_documentation_fragment: openstack
'''
EXAMPLES = '''
- name: Gather information about a previously created image named image1
os_image_info:
auth:
auth_url: https://identity.example.com
username: user
password: password
project_name: someproject
image: image1
register: result
- name: Show openstack information
debug:
msg: "{{ result.openstack_image }}"
# Show all available Openstack images
- name: Retrieve all available Openstack images
os_image_info:
register: result
- name: Show images
debug:
msg: "{{ result.openstack_image }}"
# Show images matching requested properties
- name: Retrieve images having properties with desired values
os_image_facts:
properties:
some_property: some_value
OtherProp: OtherVal
- name: Show images
debug:
msg: "{{ result.openstack_image }}"
'''
RETURN = '''
openstack_image:
description: has all the openstack information about the image
returned: always, but can be null
type: complex
contains:
id:
description: Unique UUID.
returned: success
type: str
name:
description: Name given to the image.
returned: success
type: str
status:
description: Image status.
returned: success
type: str
created_at:
description: Image created at timestamp.
returned: success
type: str
deleted:
description: Image deleted flag.
returned: success
type: bool
container_format:
description: Container format of the image.
returned: success
type: str
min_ram:
description: Min amount of RAM required for this image.
returned: success
type: int
disk_format:
description: Disk format of the image.
returned: success
type: str
updated_at:
description: Image updated at timestamp.
returned: success
type: str
properties:
description: Additional properties associated with the image.
returned: success
type: dict
min_disk:
description: Min amount of disk space required for this image.
returned: success
type: int
protected:
description: Image protected flag.
returned: success
type: bool
checksum:
description: Checksum for the image.
returned: success
type: str
owner:
description: Owner for the image.
returned: success
type: str
is_public:
description: Is public flag of the image.
returned: success
type: bool
deleted_at:
description: Image deleted at timestamp.
returned: success
type: str
size:
description: Size of the image.
returned: success
type: int
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs, openstack_cloud_from_module
def main():
argument_spec = openstack_full_argument_spec(
image=dict(required=False),
properties=dict(default=None, type='dict'),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec, **module_kwargs)
is_old_facts = module._name == 'os_image_facts'
if is_old_facts:
module.deprecate("The 'os_image_facts' module has been renamed to 'os_image_info', "
"and the renamed one no longer returns ansible_facts", version='2.13')
sdk, cloud = openstack_cloud_from_module(module)
try:
if module.params['image']:
image = cloud.get_image(module.params['image'])
if is_old_facts:
module.exit_json(changed=False, ansible_facts=dict(
openstack_image=image))
else:
module.exit_json(changed=False, openstack_image=image)
else:
images = cloud.search_images(filters=module.params['properties'])
if is_old_facts:
module.exit_json(changed=False, ansible_facts=dict(
openstack_image=images))
else:
module.exit_json(changed=False, openstack_image=images)
except sdk.exceptions.OpenStackCloudException as e:
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
|
shinate/phantomjs
|
refs/heads/master
|
src/breakpad/src/tools/gyp/test/sibling/gyptest-all.py
|
151
|
#!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('build/all.gyp', chdir='src')
test.build('build/all.gyp', test.ALL, chdir='src')
chdir = 'src/build'
# The top-level Makefile is in the directory where gyp was run.
# TODO(mmoss) Should the Makefile go in the directory of the passed in .gyp
# file? What about when passing in multiple .gyp files? Would sub-project
# Makefiles (see http://codereview.chromium.org/340008 comments) solve this?
if test.format == 'make':
chdir = 'src'
if test.format == 'xcode':
chdir = 'src/prog1'
test.run_built_executable('prog1',
chdir=chdir,
stdout="Hello from prog1.c\n")
if test.format == 'xcode':
chdir = 'src/prog2'
test.run_built_executable('prog2',
chdir=chdir,
stdout="Hello from prog2.c\n")
test.pass_test()
|
kbidarkar/robottelo
|
refs/heads/master
|
tests/foreman/api/test_subnet.py
|
1
|
"""Tests for the ``subnets`` paths.
An API reference is available here:
http://theforeman.org/api/apidoc/v2/1.15.html
:Requirement: Subnet
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: API
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from robottelo.decorators import (
stubbed,
tier1,
tier2,
tier3,
upgrade
)
from robottelo.test import APITestCase
from robozilla.decorators import skip_if_bug_open
class ParameterizedSubnetTestCase(APITestCase):
"""Implements parametrized subnet tests in API"""
@stubbed
@tier1
def test_positive_add_parameter(self):
"""Parameters can be created in subnet
:id: c1dae6f4-45b1-45db-8529-d7918e41a99b
:steps:
1. Create Subnet with all the details
2. Create subnet parameter with single key and single value
:expectedresults: The parameter should be created in subnet
"""
@stubbed
@tier1
def test_positive_add_parameter_with_multiple_values(self):
"""Subnet parameters can be created with multiple values
:id: b3de6f96-7c39-4c44-b91c-a6d141f5dd6a
:steps:
1. Create Subnet with all the details
2. Create subnet parameter having single key and multiple values
separated with comma
:expectedresults: The parameter with multiple values should be saved
in subnet
"""
@stubbed
@tier1
def test_positive_create_with_parameter_and_valid_separator(self):
"""Subnet parameters can be created with multiple names with valid
separators
:id: d1e2d75a-a1e8-4767-93f1-0bb1b75e10a0
:steps:
1. Create Subnet with all the details
2. Create subnet parameter having key with multiple names separated
by valid separators(e.g fwd slash) and value
:expectedresults: The parameter with multiple names separated by valid
separators should be saved in subnet
"""
@stubbed
@tier1
def test_negative_create_with_parameter_and_invalid_separator(self):
"""Subnet parameters can not be created with multiple names with
invalid separators
:id: 08d10b75-a0db-4a11-a915-965a2a207d16
:steps:
1. Create Subnet with all the details
2. Create subnet parameter having key with multiple names separated
by invalid separators(e.g spaces) and value
:expectedresults:
1. The parameter with multiple names separated by invalid
separators should not be saved in subnet
2. An error for invalid name should be thrown.
"""
@stubbed
@tier1
def test_negative_create_with_duplicated_parameters(self):
"""Attempt to create multiple parameters with same key name for the
same subnet
:id: aa69bdcc-e833-41e4-8f72-7139bdd64daa
:steps:
1. Create Subnet with all the details
2. Create Multiple parameters having duplicate key names
:expectedresults:
1. The subnet parameters should not be created with duplicate
names
2. An error for duplicate parameter should be thrown
"""
@stubbed
@skip_if_bug_open('bugzilla', 1470014)
@tier3
def test_positive_inherit_subnet_parmeters_in_host(self):
"""Host inherits parameters from subnet
:id: e372a594-f758-40ef-95ec-867937e44b63
:steps:
1. Create valid subnet with a valid parameter
2. Create host with above subnet
3. Assign hosts primary interface with subnet
4. List inherited subnet parameters in above host
:expectedresults:
1. The parameters from subnet should be displayed in
host parameters
2. The parameters from subnet should be displayed in
host enc output
CaseLevel: System
"""
@stubbed
@skip_if_bug_open('bugzilla', 1470014)
@tier2
def test_positive_subnet_parameters_override_from_host(self):
"""Subnet parameters values can be overridden from host
:id: b977dbb7-b2e5-41a4-a0e9-2084deec6935
:steps:
1. Create valid subnet with valid parameter
2. Create host with above subnet
3. Assign hosts primary interface with subnet
4. Override subnet parameter value from host with some other value
:expectedresults:
1. The subnet parameters should override from host
2. The new value should be assigned to parameter
3. The parameter and value should be accessible as host parameters
CaseLevel: Integration
"""
@stubbed
@tier3
def test_positive_subnet_parameters_override_impact_on_subnet(self):
"""Override subnet parameter from host impact on subnet parameter
:id: 6fe963ed-93a3-496e-bfd9-599bf91a61f3
:steps:
1. Create valid subnet with valid parameter
2. Create host with above subnet
3. Assign hosts primary interface with subnet
4. Override subnet parameter value from host with some other value
:expectedresults: The override value of subnet parameter from host
should not change actual value in subnet parameter
CaseLevel: System
"""
@stubbed
@tier1
def test_positive_update_parameter(self):
"""Subnet parameter can be updated
:id: 8c389c3f-60ef-4856-b8fc-c5b066c67a2f
:steps:
1. Create valid subnet with valid parameter
2. Update above subnet parameter with new name and
value
:expectedresults: The parameter name and value should be updated
"""
@stubbed
@tier1
def test_negative_update_parameter(self):
"""Subnet parameter can not be updated with invalid names
:id: fcdbad13-ad96-4152-8e20-e023d61a2853
:steps:
1. Create valid subnet with valid parameter
2. Update above subnet parameter with some invalid
name. e.g name with spaces
:expectedresults:
1. The parameter should not be updated with invalid name
2. An error for invalid name should be thrown
"""
@stubbed
@skip_if_bug_open('bugzilla', 1470014)
@tier2
def test_positive_update_subnet_parameter_host_impact(self):
"""Update in parameter name and value from subnet component updates
the parameter in host inheriting that subnet
:id: 64ac7873-ed36-4cad-a8db-5c9a4826868b
:steps:
1. Create valid subnet with valid parameter
2. Create host with the above subnet
3. Update subnet parameter with new name and value
:expectedresults:
1. The inherited subnet parameter in host should have
updated name and value
2. The inherited subnet parameter in host enc should have
updated name and value
CaseLevel: Integration
"""
@stubbed
@tier1
def test_positive_delete_subnet_parameter(self):
"""Subnet parameter can be deleted
:id: 972b66ec-d506-4fcb-9786-c62f2f79ac1a
:steps:
1. Create valid subnet with valid parameter
2. Delete the above subnet parameter
:expectedresults: The parameter should be deleted from subnet
"""
@stubbed
@skip_if_bug_open('bugzilla', 1470014)
@tier2
def test_positive_delete_subnet_parameter_host_impact(self):
"""Deleting parameter from subnet component deletes the parameter in
host inheriting that subnet
:id: f5174e00-33cd-4008-8112-9c8190859244
:steps:
1. Create valid subnet with valid parameter
2. Create host with the above subnet
3. Delete the above parameter from subnet
4. List subnet parameters for above host
:expectedresults:
1. The parameter should be deleted from host
2. The parameter should be deleted from host enc
CaseLevel: Integration
"""
@stubbed
@skip_if_bug_open('bugzilla', 1470014)
@tier2
@upgrade
def test_positive_delete_subnet_overridden_parameter_host_impact(self):
"""Deleting parameter from subnet component doesnt deletes its
overridden parameter in host inheriting that subnet
:id: e8f4a8e8-64ec-4a0f-aee4-14b6e984b470
:steps:
1. Create valid subnet with valid parameter
2. Create host with the above subnet
3. Override subnet parameter value from host
4. Delete the above parameter from subnet
5. List host parameters
:expectedresults:
1. The parameter should not be deleted from host as it becomes
host parameter now
2. The parameter should not be deleted from host enc as well
CaseLevel: Integration
"""
@stubbed
@tier1
def test_positive_list_parameters(self):
"""Satellite lists all the subnet parameters
:id: ce86d531-bf6b-45a9-81e3-67e1b3398f76
:steps:
1. Create subnet with all the details
2. Add two parameters in subnet
3. List parameters of subnet
:expectedresults: The satellite should display all the subnet
parameters
"""
@stubbed
@skip_if_bug_open('bugzilla', 1470014)
@tier3
def test_positive_subnet_parameter_priority(self):
"""Higher priority hosts component parameter overrides subnet parameter
with same name
:id: 75e35bd7-c9bb-4cf9-8b80-018b836f3dbe
:steps:
1. Create valid subnet with valid parameter
2. Create host group with parameter with same name as above
subnet parameter
3. Create host with the above subnet and hostgroup
4. List host parameters
:expectedresults:
1. Host should display the parameter with value inherited from
higher priority component(HostGroup in this case)
2. Host enc should display the parameter with value inherited from
higher priority component(HostGroup in this case)
CaseLevel: System
"""
@stubbed
@skip_if_bug_open('bugzilla', 1470014)
@tier3
def test_negative_component_overrides_subnet_parameter(self):
"""Lower priority hosts component parameter doesnt overrides subnet
parameter with same name
:id: 35d2a5de-07c7-40d6-8d65-a4f3e00ee429
:steps:
1. Create valid subnet with valid parameter
2. Create domain with parameter with same name as above
subnet parameter
3. Create host with the above subnet and domain
4. List host parameters
:expectedresults:
1. Host should not display the parameter with value inherited from
lower priority component(domain in this case)
2. Host enc should not display the parameter with value inherited
from lower priority component(domain in this case)
CaseLevel: System
"""
|
hanlind/nova
|
refs/heads/master
|
nova/wsgi/nova-metadata.py
|
40
|
# 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.
"""WSGI script for Nova metadata
EXPERIMENTAL support script for running Nova metadata under Apache2 etc.
"""
from oslo_config import cfg
from oslo_log import log as logging
from paste import deploy
from nova import config
from nova import objects
from nova import service # noqa
from nova import utils
CONF = cfg.CONF
config_files = ['/etc/nova/api-paste.ini', '/etc/nova/nova.conf']
config.parse_args([], default_config_files=config_files)
logging.setup(CONF, "nova")
utils.monkey_patch()
objects.register_all()
conf = config_files[0]
name = "metadata"
options = deploy.appconfig('config:%s' % conf, name=name)
application = deploy.loadapp('config:%s' % conf, name=name)
|
shanot/imp
|
refs/heads/develop
|
modules/em/test/test_volumes_and_images.py
|
2
|
import IMP.test
import IMP.em
import os
class Tests(IMP.test.TestCase):
def test_em_maps(self):
"""Check volume reading and writing"""
# Read in Xmipp format
rw1 = IMP.em.SpiderMapReaderWriter(
self.get_input_file_name("media_mon_iter3.xmp"),
False, False, True)
rw2 = IMP.em.MRCReaderWriter()
m = IMP.em.read_map(
self.get_input_file_name(
"media_mon_iter3.xmp"),
rw1)
# Compare against known voxel values to make sure we're reading the
# file correctly
self.assertAlmostEqual(m.get_value(m.xyz_ind2voxel(24, 28, 25)),
0.04647, delta=0.001)
self.assertAlmostEqual(m.get_value(m.xyz_ind2voxel(23, 29, 25)),
0.03346, delta=0.001)
IMP.em.write_map(m, "test.mrc", rw2)
IMP.em.write_map(m, "test.xmp", rw1)
m2 = IMP.em.read_map("test.xmp", rw1)
# Check that the two maps have the same values
for k in range(0, m.get_header().get_nz()):
for j in range(0, m.get_header().get_ny()):
for i in range(0, m.get_header().get_nx()):
self.assertEqual(m.get_value(m.xyz_ind2voxel(i, j, k)),
m2.get_value(m.xyz_ind2voxel(i, j, k)))
# Cleanup
os.unlink('test.mrc')
os.unlink('test.xmp')
if __name__ == '__main__':
IMP.test.main()
|
xq262144/hue
|
refs/heads/master
|
desktop/core/ext-py/openpyxl-2.3.0-b2/openpyxl/reader/style.py
|
13
|
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
"""Read shared style definitions"""
# package imports
from openpyxl.compat import OrderedDict, zip
from openpyxl.utils.indexed_list import IndexedList
from openpyxl.styles import (
numbers,
Font,
Fill,
PatternFill,
GradientFill,
Border,
Side,
Protection,
Alignment,
borders,
)
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.styles.colors import COLOR_INDEX, Color
from openpyxl.styles.styleable import StyleArray
from openpyxl.styles.named_styles import NamedStyle
from openpyxl.xml.functions import fromstring, safe_iterator, localname
from openpyxl.xml.constants import SHEET_MAIN_NS, ARC_STYLE
from copy import deepcopy
class SharedStylesParser(object):
def __init__(self, xml_source):
self.root = fromstring(xml_source)
self.cell_styles = IndexedList()
self.differential_styles = []
self.color_index = COLOR_INDEX
self.font_list = IndexedList()
self.fill_list = IndexedList()
self.border_list = IndexedList()
self.alignments = IndexedList([Alignment()])
self.protections = IndexedList([Protection()])
self.custom_number_formats = {}
self.number_formats = IndexedList()
def parse(self):
self.parse_custom_num_formats()
self.parse_color_index()
self.font_list = IndexedList(self.parse_fonts())
self.fill_list = IndexedList(self.parse_fills())
self.border_list = IndexedList(self.parse_borders())
self.parse_dxfs()
self.parse_cell_styles()
self.parse_named_styles()
def parse_custom_num_formats(self):
"""Read in custom numeric formatting rules from the shared style table"""
custom_formats = {}
num_fmts = self.root.findall('{%s}numFmts/{%s}numFmt' % (SHEET_MAIN_NS, SHEET_MAIN_NS))
for node in num_fmts:
idx = int(node.get('numFmtId'))
self.custom_number_formats[idx] = node.get('formatCode')
self.number_formats.append(node.get('formatCode'))
def parse_color_index(self):
"""Read in the list of indexed colors"""
colors =\
self.root.findall('{%s}colors/{%s}indexedColors/{%s}rgbColor' %
(SHEET_MAIN_NS, SHEET_MAIN_NS, SHEET_MAIN_NS))
if not colors:
return
self.color_index = IndexedList([node.get('rgb') for node in colors])
def parse_dxfs(self):
"""Read in the dxfs effects - used by conditional formatting."""
for node in self.root.findall("{%s}dxfs/{%s}dxf" % (SHEET_MAIN_NS, SHEET_MAIN_NS) ):
self.differential_styles.append(DifferentialStyle.from_tree(node))
def parse_fonts(self):
"""Read in the fonts"""
fonts = self.root.findall('{%s}fonts/{%s}font' % (SHEET_MAIN_NS, SHEET_MAIN_NS))
for node in fonts:
yield Font.from_tree(node)
def parse_fills(self):
"""Read in the list of fills"""
fills = self.root.findall('{%s}fills/{%s}fill' % (SHEET_MAIN_NS, SHEET_MAIN_NS))
for fill in fills:
yield Fill.from_tree(fill)
def parse_borders(self):
"""Read in the boarders"""
borders = self.root.findall('{%s}borders/{%s}border' % (SHEET_MAIN_NS, SHEET_MAIN_NS))
for border_node in borders:
yield Border.from_tree(border_node)
def parse_named_styles(self):
"""
Extract named styles
"""
node = self.root.find("{%s}cellStyleXfs" % SHEET_MAIN_NS)
styles = self._parse_xfs(node)
names = self._parse_style_names()
for style in names.values():
_id = styles[style.xfId]
style.border = self.border_list[_id.borderId]
style.fill = self.fill_list[_id.fillId]
style.font = self.font_list[_id.fontId]
if _id.alignmentId:
style.alignment = self.alignments[_id.alignmentId]
if _id.protectionId:
style.protection = self.protections[_id.protectionId]
self.named_styles = names
def _parse_style_names(self):
"""
Extract style names. There can be duplicates in which case last wins
"""
node = self.root.find("{%s}cellStyles" % SHEET_MAIN_NS)
names = {}
for _name in node:
name = _name.get("name")
style = NamedStyle(name=name,
builtinId=_name.get("builtinId"),
hidden=_name.get("hidden")
)
style.xfId = int(_name.get("xfId"))
names[name] = style
return names
def parse_cell_styles(self):
"""
Extract individual cell styles
"""
node = self.root.find('{%s}cellXfs' % SHEET_MAIN_NS)
if node is not None:
self.cell_styles = self._parse_xfs(node)
def _parse_xfs(self, node):
"""Read styles from the shared style table"""
_style_ids = []
xfs = safe_iterator(node, '{%s}xf' % SHEET_MAIN_NS)
for xf in xfs:
style = StyleArray.from_tree(xf)
al = xf.find('{%s}alignment' % SHEET_MAIN_NS)
if al is not None:
alignment = Alignment(**al.attrib)
style.alignmentId = self.alignments.add(alignment)
prot = xf.find('{%s}protection' % SHEET_MAIN_NS)
if prot is not None:
protection = Protection(**prot.attrib)
style.protectionId = self.protections.add(protection)
numFmtId = int(xf.get("numFmtId", 0))
# check for custom formats and normalise indices
if numFmtId in self.custom_number_formats:
format_code = self.custom_number_formats[numFmtId]
style.numFmtId = self.number_formats.add(format_code) + 164
_style_ids.append(style)
return IndexedList(_style_ids)
def read_style_table(archive):
if ARC_STYLE in archive.namelist():
xml_source = archive.read(ARC_STYLE)
p = SharedStylesParser(xml_source)
p.parse()
return p
def bool_attrib(element, attr):
"""
Cast an XML attribute that should be a boolean to a Python equivalent
None, 'f', '0' and 'false' all cast to False, everything else to true
"""
value = element.get(attr)
if not value or value in ("false", "f", "0"):
return False
return True
|
milafrerichs/geonode
|
refs/heads/master
|
geonode/people/migrations/0003_auto_20160824_0245.py
|
5
|
# -*- coding: utf-8 -*-
# flake8: noqa
from __future__ import unicode_literals
from django.db import migrations, models
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('people', '0002_auto_20160821_1919'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='keywords',
field= taggit.managers.TaggableManager(
to='taggit.Tag',
through='taggit.TaggedItem',
blank=True,
help_text='commonly used word(s) or formalised word(s) or phrase(s) used to describe the subject (space or comma-separated',
verbose_name='keywords'),
),
]
|
Apptimize-OSS/github-reviewboard-sync
|
refs/heads/master
|
tests/unit_tests/test_repo.py
|
1
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from hashlib import sha1
from mock import Mock
import unittest2
from github_reviewboard_sync.exceptions import MissingRemoteException, MissingBranchExcpetion
from github_reviewboard_sync.repo import _get_relevant_commit_shas, _get_relevant_commits, \
_construct_summary, _get_messages, _get_remote, _get_branch
class TestGetRelevantCommitShas(unittest2.TestCase):
def test__when_no_matches__returns_empty_list(self):
expected = []
repo = Mock(git=Mock(log=Mock(return_value='a'*1000)))
resp = _get_relevant_commit_shas(repo, 'doesnt', 'matter')
self.assertListEqual(expected, resp)
def test__when_merge__returns_empty_list(self):
expected = []
log_output = 'commit {0}\nMerge'.format(sha1(b'a').hexdigest())
repo = Mock(git=Mock(log=Mock(return_value=log_output)))
resp = _get_relevant_commit_shas(repo, 'doesnt', 'matter')
self.assertListEqual(expected, resp)
def test__when_multiple__returns_all(self):
first = sha1(b'a').hexdigest()
second = sha1(b'b').hexdigest()
expected = [first, second]
log_output = 'commit {0}\n\ncommit {1}\n'.format(first, second)
repo = Mock(git=Mock(log=Mock(return_value=log_output)))
resp = _get_relevant_commit_shas(repo, 'doesnt', 'matter')
self.assertListEqual(expected, resp)
class TestGetRelevantCommits(unittest2.TestCase):
def setUp(self):
self.commit1 = Mock(hexsha=sha1(b'a').hexdigest())
self.commit2 = Mock(hexsha=sha1(b'b').hexdigest())
self.commit3 = Mock(hexsha=sha1(b'c').hexdigest())
self.repo = Mock(iter_commits=Mock(return_value=[self.commit1, self.commit2, self.commit3]))
def test__when_no_shas_match__returns_empty_list(self):
shas = [sha1(b'd').hexdigest()]
resp = _get_relevant_commits(self.repo, shas, 'notrelevant')
self.assertListEqual([], resp)
def test__when_multiple__returns_all_matching(self):
expected = [self.commit1, self.commit3]
shas = [commit.hexsha for commit in expected]
resp = _get_relevant_commits(self.repo, shas, 'notrelevant')
self.assertEqual(expected, resp)
class TestConstructSummary(unittest2.TestCase):
def test__when_empty__returns_generic(self):
expected = 'Autogenerated pull request'
resp = _construct_summary([])
self.assertEqual(expected, resp)
def test__when_not_empty__returns_first_summary(self):
expected = 'blah'
resp = _construct_summary([Mock(summary=expected), Mock(summary='bad')])
self.assertEqual(expected, resp)
class TestGetMessage(unittest2.TestCase):
def test__when_empty__returns_empty_string(self):
resp = _get_messages(None)
self.assertEqual('', resp)
resp = _get_messages([])
self.assertEqual('', resp)
def test__when_not_empty__joins_messages(self):
first = Mock(message='blah')
second = Mock(message='another')
expected = 'blah\n\nanother'
resp = _get_messages([first, second])
self.assertEqual(expected, resp)
class TestGetRemote(unittest2.TestCase):
def test__when_missing_name__raises_missing_remote(self):
# This is strange because the dictionary like object `remotes`
# raises a IndexError instead of a KeyError
repo = Mock(remotes=[])
self.assertRaises(MissingRemoteException, _get_remote, repo, 1)
def test__when_valid_name__returns_remote(self):
repo = Mock(remotes=dict(remote='blah'))
self.assertEquals('blah', _get_remote(repo, 'remote'))
class TestGetBranch(unittest2.TestCase):
def test__when_missing_branch__raises_missing_branch(self):
# This is strange because the dictionary like object `branches`
# raises a IndexError instead of a KeyError
repo = Mock(branches=[])
self.assertRaises(MissingBranchExcpetion, _get_branch, repo, 1)
def test__when_valid_name__returns_remote(self):
repo = Mock(branches=dict(branch='blah'))
self.assertEquals('blah', _get_branch(repo, 'branch'))
|
sarthfrey/sentimizer
|
refs/heads/master
|
lib/flask/testsuite/test_apps/config_module_app.py
|
1257
|
import os
import flask
here = os.path.abspath(os.path.dirname(__file__))
app = flask.Flask(__name__)
|
openhatch/oh-mainline
|
refs/heads/master
|
vendor/packages/zope.interface/src/zope/interface/tests/m2.py
|
83
|
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test module that doesn't declare an interface
"""
|
hchen1202/django-react
|
refs/heads/master
|
virtualenv/lib/python3.6/site-packages/django/db/migrations/operations/base.py
|
127
|
from __future__ import unicode_literals
from django.db import router
class Operation(object):
"""
Base class for migration operations.
It's responsible for both mutating the in-memory model state
(see db/migrations/state.py) to represent what it performs, as well
as actually performing it against a live database.
Note that some operations won't modify memory state at all (e.g. data
copying operations), and some will need their modifications to be
optionally specified by the user (e.g. custom Python code snippets)
Due to the way this class deals with deconstruction, it should be
considered immutable.
"""
# If this migration can be run in reverse.
# Some operations are impossible to reverse, like deleting data.
reversible = True
# Can this migration be represented as SQL? (things like RunPython cannot)
reduces_to_sql = True
# Should this operation be forced as atomic even on backends with no
# DDL transaction support (i.e., does it have no DDL, like RunPython)
atomic = False
# Should this operation be considered safe to elide and optimize across?
elidable = False
serialization_expand_args = []
def __new__(cls, *args, **kwargs):
# We capture the arguments to make returning them trivial
self = object.__new__(cls)
self._constructor_args = (args, kwargs)
return self
def deconstruct(self):
"""
Returns a 3-tuple of class import path (or just name if it lives
under django.db.migrations), positional arguments, and keyword
arguments.
"""
return (
self.__class__.__name__,
self._constructor_args[0],
self._constructor_args[1],
)
def state_forwards(self, app_label, state):
"""
Takes the state from the previous migration, and mutates it
so that it matches what this migration would perform.
"""
raise NotImplementedError('subclasses of Operation must provide a state_forwards() method')
def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""
Performs the mutation on the database schema in the normal
(forwards) direction.
"""
raise NotImplementedError('subclasses of Operation must provide a database_forwards() method')
def database_backwards(self, app_label, schema_editor, from_state, to_state):
"""
Performs the mutation on the database schema in the reverse
direction - e.g. if this were CreateModel, it would in fact
drop the model's table.
"""
raise NotImplementedError('subclasses of Operation must provide a database_backwards() method')
def describe(self):
"""
Outputs a brief summary of what the action does.
"""
return "%s: %s" % (self.__class__.__name__, self._constructor_args)
def references_model(self, name, app_label=None):
"""
Returns True if there is a chance this operation references the given
model name (as a string), with an optional app label for accuracy.
Used for optimization. If in doubt, return True;
returning a false positive will merely make the optimizer a little
less efficient, while returning a false negative may result in an
unusable optimized migration.
"""
return True
def references_field(self, model_name, name, app_label=None):
"""
Returns True if there is a chance this operation references the given
field name, with an optional app label for accuracy.
Used for optimization. If in doubt, return True.
"""
return self.references_model(model_name, app_label)
def allow_migrate_model(self, connection_alias, model):
"""
Returns if we're allowed to migrate the model.
This is a thin wrapper around router.allow_migrate_model() that
preemptively rejects any proxy, swapped out, or unmanaged model.
"""
if not model._meta.can_migrate(connection_alias):
return False
return router.allow_migrate_model(connection_alias, model)
def reduce(self, operation, in_between, app_label=None):
"""
Return either a list of operations the actual operation should be
replaced with or a boolean that indicates whether or not the specified
operation can be optimized across.
"""
if self.elidable:
return [operation]
elif operation.elidable:
return [self]
return False
def __repr__(self):
return "<%s %s%s>" % (
self.__class__.__name__,
", ".join(map(repr, self._constructor_args[0])),
",".join(" %s=%r" % x for x in self._constructor_args[1].items()),
)
|
kustodian/ansible
|
refs/heads/devel
|
test/units/modules/network/f5/test_bigip_profile_dns.py
|
22
|
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from library.modules.bigip_profile_dns import ApiParameters
from library.modules.bigip_profile_dns import ModuleParameters
from library.modules.bigip_profile_dns import ModuleManager
from library.modules.bigip_profile_dns import ArgumentSpec
# In Ansible 2.8, Ansible changed import paths.
from test.units.compat import unittest
from test.units.compat.mock import Mock
from test.units.modules.utils import set_module_args
except ImportError:
from ansible.modules.network.f5.bigip_profile_dns import ApiParameters
from ansible.modules.network.f5.bigip_profile_dns import ModuleParameters
from ansible.modules.network.f5.bigip_profile_dns import ModuleManager
from ansible.modules.network.f5.bigip_profile_dns import ArgumentSpec
# Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.modules.utils import set_module_args
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path in fixture_data:
return fixture_data[path]
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
name='foo',
parent='bar',
enable_dns_express=True,
enable_zone_transfer=True,
enable_dnssec=True,
enable_gtm=True,
process_recursion_desired=True,
use_local_bind=True,
enable_dns_firewall=True,
)
p = ModuleParameters(params=args)
assert p.name == 'foo'
assert p.parent == '/Common/bar'
assert p.enable_dns_express is True
assert p.enable_zone_transfer is True
assert p.enable_dnssec is True
assert p.enable_gtm is True
assert p.process_recursion_desired is True
assert p.use_local_bind is True
assert p.enable_dns_firewall is True
def test_api_parameters(self):
args = load_fixture('load_ltm_profile_dns_1.json')
p = ApiParameters(params=args)
assert p.name == 'foo'
assert p.parent == '/Common/dns'
assert p.enable_dns_express is False
assert p.enable_zone_transfer is True
assert p.enable_dnssec is False
assert p.enable_gtm is False
assert p.process_recursion_desired is True
assert p.use_local_bind is False
assert p.enable_dns_firewall is True
class TestManager(unittest.TestCase):
def setUp(self):
self.spec = ArgumentSpec()
def test_create(self, *args):
# Configure the arguments that would be sent to the Ansible module
set_module_args(dict(
name='foo',
parent='bar',
enable_dns_express=True,
enable_zone_transfer=True,
enable_dnssec=True,
enable_gtm=True,
process_recursion_desired=True,
use_local_bind=True,
enable_dns_firewall=True,
provider=dict(
server='localhost',
password='password',
user='admin'
)
))
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(return_value=False)
mm.create_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert results['enable_dns_express'] == 'yes'
assert results['enable_zone_transfer'] == 'yes'
assert results['enable_dnssec'] == 'yes'
assert results['enable_gtm'] == 'yes'
assert results['process_recursion_desired'] == 'yes'
assert results['use_local_bind'] == 'yes'
assert results['enable_dns_firewall'] == 'yes'
|
jbbskinny/sympy
|
refs/heads/master
|
sympy/solvers/tests/test_constantsimp.py
|
112
|
"""
If the arbitrary constant class from issue 4435 is ever implemented, this
should serve as a set of test cases.
"""
from sympy import (acos, cos, cosh, Eq, exp, Function, I, Integral, log, Pow,
S, sin, sinh, sqrt, Symbol)
from sympy.solvers.ode import constant_renumber, constantsimp
from sympy.utilities.pytest import XFAIL
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
C1 = Symbol('C1')
C2 = Symbol('C2')
C3 = Symbol('C3')
f = Function('f')
def test_constant_mul():
# We want C1 (Constant) below to absorb the y's, but not the x's
assert constant_renumber(constantsimp(y*C1, [C1]), 'C', 1, 1) == C1*y
assert constant_renumber(constantsimp(C1*y, [C1]), 'C', 1, 1) == C1*y
assert constant_renumber(constantsimp(x*C1, [C1]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp(C1*x, [C1]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp(2*C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1*2, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(y*C1*x, [C1, y]), 'C', 1, 1) == C1*x
assert constant_renumber(constantsimp(x*y*C1, [C1, y]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp(y*x*C1, [C1, y]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp(C1*x*y, [C1, y]), 'C', 1, 1) == C1*x
assert constant_renumber(constantsimp(x*C1*y, [C1, y]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp(C1*y*(y + 1), [C1]), 'C', 1, 1) == C1*y*(y+1)
assert constant_renumber(constantsimp(y*C1*(y + 1), [C1]), 'C', 1, 1) == C1*y*(y+1)
assert constant_renumber(constantsimp(x*(y*C1), [C1]), 'C', 1, 1) == x*y*C1
assert constant_renumber(constantsimp(x*(C1*y), [C1]), 'C', 1, 1) == x*y*C1
assert constant_renumber(constantsimp(C1*(x*y), [C1, y]), 'C', 1, 1) == C1*x
assert constant_renumber(constantsimp((x*y)*C1, [C1, y]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp((y*x)*C1, [C1, y]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp(y*(y + 1)*C1, [C1, y]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp((C1*x)*y, [C1, y]), 'C', 1, 1) == C1*x
assert constant_renumber(constantsimp(y*(x*C1), [C1, y]), 'C', 1, 1) == x*C1
assert constant_renumber(constantsimp((x*C1)*y, [C1, y]), 'C', 1, 1) == x*C1
assert constant_renumber(
constantsimp(C1*x*y*x*y*2, [C1, y]), 'C', 1, 1) == C1*x**2
assert constant_renumber(constantsimp(C1*x*y*z, [C1, y, z]), 'C', 1, 1) == C1*x
assert constant_renumber(
constantsimp(C1*x*y**2*sin(z), [C1, y, z]), 'C', 1, 1) == C1*x
assert constant_renumber(constantsimp(C1*C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1*C2, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(C2*C2, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(C1*C1*C2, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(
constantsimp(C1*x*2**x, [C1]), 'C', 1, 1) == C1*x*2**x
def test_constant_add():
assert constant_renumber(constantsimp(C1 + C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1 + 2, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(2 + C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1 + y, [C1, y]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1 + x, [C1]), 'C', 1, 1) == C1 + x
assert constant_renumber(constantsimp(C1 + C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1 + C2, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(C2 + C1, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(C1 + C2 + C1, [C1, C2]), 'C', 1, 2) == C1
def test_constant_power_as_base():
assert constant_renumber(constantsimp(C1**C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(Pow(C1, C1), [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1**C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1**C2, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(C2**C1, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(C2**C2, [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(C1**y, [C1, y]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(C1**x, [C1]), 'C', 1, 1) == C1**x
assert constant_renumber(constantsimp(C1**2, [C1]), 'C', 1, 1) == C1
assert constant_renumber(
constantsimp(C1**(x*y), [C1]), 'C', 1, 1) == C1**(x*y)
def test_constant_power_as_exp():
assert constant_renumber(constantsimp(x**C1, [C1]), 'C', 1, 1) == x**C1
assert constant_renumber(constantsimp(y**C1, [C1, y]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(x**y**C1, [C1, y]), 'C', 1, 1) == x**C1
assert constant_renumber(
constantsimp((x**y)**C1, [C1]), 'C', 1, 1) == (x**y)**C1
assert constant_renumber(
constantsimp(x**(y**C1), [C1, y]), 'C', 1, 1) == x**C1
assert constant_renumber(constantsimp(x**C1**y, [C1, y]), 'C', 1, 1) == x**C1
assert constant_renumber(
constantsimp(x**(C1**y), [C1, y]), 'C', 1, 1) == x**C1
assert constant_renumber(
constantsimp((x**C1)**y, [C1]), 'C', 1, 1) == (x**C1)**y
assert constant_renumber(constantsimp(2**C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(S(2)**C1, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(exp(C1), [C1]), 'C', 1, 1) == C1
assert constant_renumber(
constantsimp(exp(C1 + x), [C1]), 'C', 1, 1) == C1*exp(x)
assert constant_renumber(constantsimp(Pow(2, C1), [C1]), 'C', 1, 1) == C1
def test_constant_function():
assert constant_renumber(constantsimp(sin(C1), [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(f(C1), [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(f(C1, C1), [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(f(C1, C2), [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(f(C2, C1), [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(f(C2, C2), [C1, C2]), 'C', 1, 2) == C1
assert constant_renumber(
constantsimp(f(C1, x), [C1]), 'C', 1, 2) == f(C1, x)
assert constant_renumber(constantsimp(f(C1, y), [C1, y]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(f(y, C1), [C1, y]), 'C', 1, 2) == C1
assert constant_renumber(constantsimp(f(C1, y, C2), [C1, C2, y]), 'C', 1, 2) == C1
def test_constant_function_multiple():
# The rules to not renumber in this case would be too complicated, and
# dsolve is not likely to ever encounter anything remotely like this.
assert constant_renumber(
constantsimp(f(C1, C1, x), [C1]), 'C', 1, 1) == f(C1, C1, x)
def test_constant_multiple():
assert constant_renumber(constantsimp(C1*2 + 2, [C1]), 'C', 1, 1) == C1
assert constant_renumber(constantsimp(x*2/C1, [C1]), 'C', 1, 1) == C1*x
assert constant_renumber(constantsimp(C1**2*2 + 2, [C1]), 'C', 1, 1) == C1
assert constant_renumber(
constantsimp(sin(2*C1) + x + sqrt(2), [C1]), 'C', 1, 1) == C1 + x
assert constant_renumber(constantsimp(2*C1 + C2, [C1, C2]), 'C', 1, 2) == C1
def test_constant_repeated():
assert C1 + C1*x == constant_renumber( C1 + C1*x, 'C', 1, 3)
def test_ode_solutions():
# only a few examples here, the rest will be tested in the actual dsolve tests
assert constant_renumber(constantsimp(C1*exp(2*x) + exp(x)*(C2 + C3), [C1, C2, C3]), 'C', 1, 3) == \
constant_renumber((C1*exp(x) + C2*exp(2*x)), 'C', 1, 2)
assert constant_renumber(
constantsimp(Eq(f(x), I*C1*sinh(x/3) + C2*cosh(x/3)), [C1, C2]),
'C', 1, 2) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3)), 'C', 1, 2)
assert constant_renumber(constantsimp(Eq(f(x), acos((-C1)/cos(x))), [C1]), 'C', 1, 1) == \
Eq(f(x), acos(C1/cos(x)))
assert constant_renumber(
constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), [C1]),
'C', 1, 1) == Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0)
assert constant_renumber(constantsimp(Eq(log(x*sqrt(2)*sqrt(1/x)*sqrt(f(x))
/C1) + x**2/(2*f(x)**2), 0), [C1]), 'C', 1, 1) == \
Eq(log(C1*sqrt(x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
assert constant_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) -
cos(f(x)/x)*exp(-f(x)/x)/2, 0), [C1]), 'C', 1, 1) == \
Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*
exp(-f(x)/x)/2, 0)
u2 = Symbol('u2')
_a = Symbol('_a')
assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2),
(u2, _a, x/f(x))) + log(f(x)/C1), 0), [C1]), 'C', 1, 1) == \
Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) +
log(C1*f(x)), 0)
assert [constantsimp(i, [C1]) for i in [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x + x**2))]] == \
[Eq(f(x), sqrt(x*(C1 + x))), Eq(f(x), -sqrt(x*(C1 + x)))]
@XFAIL
def test_nonlocal_simplification():
assert constantsimp(C1 + C2+x*C2, [C1, C2]) == C1 + C2*x
def test_constant_Eq():
# C1 on the rhs is well-tested, but the lhs is only tested here
assert constantsimp(Eq(C1, 3 + f(x)*x), [C1]) == Eq(x*f(x), C1)
assert constantsimp(Eq(C1, 3 * f(x)*x), [C1]) == Eq(f(x)*x, C1)
|
jakirkham/bokeh
|
refs/heads/master
|
examples/app/gapminder/main.py
|
5
|
# -*- coding: utf-8 -*-
import pandas as pd
from bokeh.core.properties import field
from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.models import (ColumnDataSource, HoverTool, SingleIntervalTicker,
Slider, Button, Label, CategoricalColorMapper)
from bokeh.palettes import Spectral6
from bokeh.plotting import figure
from data import process_data
fertility_df, life_expectancy_df, population_df_size, regions_df, years, regions_list = process_data()
df = pd.concat({'fertility': fertility_df,
'life': life_expectancy_df,
'population': population_df_size},
axis=1)
data = {}
regions_df.rename({'Group':'region'}, axis='columns', inplace=True)
for year in years:
df_year = df.iloc[:,df.columns.get_level_values(1)==year]
df_year.columns = df_year.columns.droplevel(1)
data[year] = df_year.join(regions_df.region).reset_index().to_dict('series')
source = ColumnDataSource(data=data[years[0]])
plot = figure(x_range=(1, 9), y_range=(20, 100), title='Gapminder Data', plot_height=300)
plot.xaxis.ticker = SingleIntervalTicker(interval=1)
plot.xaxis.axis_label = "Children per woman (total fertility)"
plot.yaxis.ticker = SingleIntervalTicker(interval=20)
plot.yaxis.axis_label = "Life expectancy at birth (years)"
label = Label(x=1.1, y=18, text=str(years[0]), text_font_size='70pt', text_color='#eeeeee')
plot.add_layout(label)
color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list)
plot.circle(
x='fertility',
y='life',
size='population',
source=source,
fill_color={'field': 'region', 'transform': color_mapper},
fill_alpha=0.8,
line_color='#7c7e71',
line_width=0.5,
line_alpha=0.5,
legend=field('region'),
)
plot.add_tools(HoverTool(tooltips="@Country", show_arrow=False, point_policy='follow_mouse'))
def animate_update():
year = slider.value + 1
if year > years[-1]:
year = years[0]
slider.value = year
def slider_update(attrname, old, new):
year = slider.value
label.text = str(year)
source.data = data[year]
slider = Slider(start=years[0], end=years[-1], value=years[0], step=1, title="Year")
slider.on_change('value', slider_update)
callback_id = None
def animate():
global callback_id
if button.label == '► Play':
button.label = '❚❚ Pause'
callback_id = curdoc().add_periodic_callback(animate_update, 200)
else:
button.label = '► Play'
curdoc().remove_periodic_callback(callback_id)
button = Button(label='► Play', width=60)
button.on_click(animate)
layout = layout([
[plot],
[slider, button],
], sizing_mode='scale_width')
curdoc().add_root(layout)
curdoc().title = "Gapminder"
|
gogozs/shadowsocks
|
refs/heads/master
|
shadowsocks/eventloop.py
|
949
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013-2015 clowwindy
#
# 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.
# from ssloop
# https://github.com/clowwindy/ssloop
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import time
import socket
import select
import errno
import logging
from collections import defaultdict
from shadowsocks import shell
__all__ = ['EventLoop', 'POLL_NULL', 'POLL_IN', 'POLL_OUT', 'POLL_ERR',
'POLL_HUP', 'POLL_NVAL', 'EVENT_NAMES']
POLL_NULL = 0x00
POLL_IN = 0x01
POLL_OUT = 0x04
POLL_ERR = 0x08
POLL_HUP = 0x10
POLL_NVAL = 0x20
EVENT_NAMES = {
POLL_NULL: 'POLL_NULL',
POLL_IN: 'POLL_IN',
POLL_OUT: 'POLL_OUT',
POLL_ERR: 'POLL_ERR',
POLL_HUP: 'POLL_HUP',
POLL_NVAL: 'POLL_NVAL',
}
# we check timeouts every TIMEOUT_PRECISION seconds
TIMEOUT_PRECISION = 10
class KqueueLoop(object):
MAX_EVENTS = 1024
def __init__(self):
self._kqueue = select.kqueue()
self._fds = {}
def _control(self, fd, mode, flags):
events = []
if mode & POLL_IN:
events.append(select.kevent(fd, select.KQ_FILTER_READ, flags))
if mode & POLL_OUT:
events.append(select.kevent(fd, select.KQ_FILTER_WRITE, flags))
for e in events:
self._kqueue.control([e], 0)
def poll(self, timeout):
if timeout < 0:
timeout = None # kqueue behaviour
events = self._kqueue.control(None, KqueueLoop.MAX_EVENTS, timeout)
results = defaultdict(lambda: POLL_NULL)
for e in events:
fd = e.ident
if e.filter == select.KQ_FILTER_READ:
results[fd] |= POLL_IN
elif e.filter == select.KQ_FILTER_WRITE:
results[fd] |= POLL_OUT
return results.items()
def register(self, fd, mode):
self._fds[fd] = mode
self._control(fd, mode, select.KQ_EV_ADD)
def unregister(self, fd):
self._control(fd, self._fds[fd], select.KQ_EV_DELETE)
del self._fds[fd]
def modify(self, fd, mode):
self.unregister(fd)
self.register(fd, mode)
def close(self):
self._kqueue.close()
class SelectLoop(object):
def __init__(self):
self._r_list = set()
self._w_list = set()
self._x_list = set()
def poll(self, timeout):
r, w, x = select.select(self._r_list, self._w_list, self._x_list,
timeout)
results = defaultdict(lambda: POLL_NULL)
for p in [(r, POLL_IN), (w, POLL_OUT), (x, POLL_ERR)]:
for fd in p[0]:
results[fd] |= p[1]
return results.items()
def register(self, fd, mode):
if mode & POLL_IN:
self._r_list.add(fd)
if mode & POLL_OUT:
self._w_list.add(fd)
if mode & POLL_ERR:
self._x_list.add(fd)
def unregister(self, fd):
if fd in self._r_list:
self._r_list.remove(fd)
if fd in self._w_list:
self._w_list.remove(fd)
if fd in self._x_list:
self._x_list.remove(fd)
def modify(self, fd, mode):
self.unregister(fd)
self.register(fd, mode)
def close(self):
pass
class EventLoop(object):
def __init__(self):
if hasattr(select, 'epoll'):
self._impl = select.epoll()
model = 'epoll'
elif hasattr(select, 'kqueue'):
self._impl = KqueueLoop()
model = 'kqueue'
elif hasattr(select, 'select'):
self._impl = SelectLoop()
model = 'select'
else:
raise Exception('can not find any available functions in select '
'package')
self._fdmap = {} # (f, handler)
self._last_time = time.time()
self._periodic_callbacks = []
self._stopping = False
logging.debug('using event model: %s', model)
def poll(self, timeout=None):
events = self._impl.poll(timeout)
return [(self._fdmap[fd][0], fd, event) for fd, event in events]
def add(self, f, mode, handler):
fd = f.fileno()
self._fdmap[fd] = (f, handler)
self._impl.register(fd, mode)
def remove(self, f):
fd = f.fileno()
del self._fdmap[fd]
self._impl.unregister(fd)
def add_periodic(self, callback):
self._periodic_callbacks.append(callback)
def remove_periodic(self, callback):
self._periodic_callbacks.remove(callback)
def modify(self, f, mode):
fd = f.fileno()
self._impl.modify(fd, mode)
def stop(self):
self._stopping = True
def run(self):
events = []
while not self._stopping:
asap = False
try:
events = self.poll(TIMEOUT_PRECISION)
except (OSError, IOError) as e:
if errno_from_exception(e) in (errno.EPIPE, errno.EINTR):
# EPIPE: Happens when the client closes the connection
# EINTR: Happens when received a signal
# handles them as soon as possible
asap = True
logging.debug('poll:%s', e)
else:
logging.error('poll:%s', e)
import traceback
traceback.print_exc()
continue
for sock, fd, event in events:
handler = self._fdmap.get(fd, None)
if handler is not None:
handler = handler[1]
try:
handler.handle_event(sock, fd, event)
except (OSError, IOError) as e:
shell.print_exception(e)
now = time.time()
if asap or now - self._last_time >= TIMEOUT_PRECISION:
for callback in self._periodic_callbacks:
callback()
self._last_time = now
def __del__(self):
self._impl.close()
# from tornado
def errno_from_exception(e):
"""Provides the errno from an Exception object.
There are cases that the errno attribute was not set so we pull
the errno out of the args but if someone instatiates an Exception
without any args you will get a tuple error. So this function
abstracts all that behavior to give you a safe way to get the
errno.
"""
if hasattr(e, 'errno'):
return e.errno
elif e.args:
return e.args[0]
else:
return None
# from tornado
def get_sock_error(sock):
error_number = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
return socket.error(error_number, os.strerror(error_number))
|
mattclay/ansible-modules-core
|
refs/heads/devel
|
network/nxos/nxos_vxlan_vtep.py
|
13
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: nxos_vxlan_vtep
version_added: "2.2"
short_description: Manages VXLAN Network Virtualization Endpoint (NVE).
description:
- Manages VXLAN Network Virtualization Endpoint (NVE) overlay interface
that terminates VXLAN tunnels.
author: Gabriele Gerbino (@GGabriele)
extends_documentation_fragment: nxos
notes:
- The module is used to manage NVE properties, not to create NVE
interfaces. Use M(nxos_interface) if you wish to do so.
- C(state=absent) removes the interface.
- Default, where supported, restores params default value.
options:
interface:
description:
- Interface name for the VXLAN Network Virtualization Endpoint.
required: true
description:
description:
- Description of the NVE interface.
required: false
default: null
host_reachability:
description:
- Specify mechanism for host reachability advertisement.
required: false
choices: ['true', 'false']
default: null
shutdown:
description:
- Administratively shutdown the NVE interface.
required: false
choices: ['true','false']
default: false
source_interface:
description:
- Specify the loopback interface whose IP address should be
used for the NVE interface.
required: false
default: null
source_interface_hold_down_time:
description:
- Suppresses advertisement of the NVE loopback address until
the overlay has converged.
required: false
default: null
state:
description:
- Determines whether the config should be present or not
on the device.
required: false
default: present
choices: ['present','absent']
'''
EXAMPLES = '''
- nxos_vxlan_vtep:
interface: nve1
description: default
host_reachability: default
source_interface: Loopback0
source_interface_hold_down_time: 30
shutdown: default
username: "{{ un }}"
password: "{{ pwd }}"
host: "{{ inventory_hostname }}"
'''
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: verbose mode
type: dict
sample: {"description": "simple description", "host_reachability": true,
"interface": "nve1", "shutdown": true, "source_interface": "loopback0",
"source_interface_hold_down_time": "30"}
existing:
description: k/v pairs of existing VXLAN VTEP configuration
returned: verbose mode
type: dict
sample: {}
end_state:
description: k/v pairs of VXLAN VTEP configuration after module execution
returned: verbose mode
type: dict
sample: {"description": "simple description", "host_reachability": true,
"interface": "nve1", "shutdown": true, "source_interface": "loopback0",
"source_interface_hold_down_time": "30"}
updates:
description: commands sent to the device
returned: always
type: list
sample: ["interface nve1", "source-interface loopback0",
"source-interface hold-down-time 30", "description simple description",
"shutdown", "host-reachability protocol bgp"]
changed:
description: check to see if a change was made on the device
returned: always
type: boolean
sample: true
'''
# COMMON CODE FOR MIGRATION
import re
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcfg import NetworkConfig, ConfigLine
from ansible.module_utils.shell import ShellError
try:
from ansible.module_utils.nxos import get_module
except ImportError:
from ansible.module_utils.nxos import NetworkModule
def to_list(val):
if isinstance(val, (list, tuple)):
return list(val)
elif val is not None:
return [val]
else:
return list()
class CustomNetworkConfig(NetworkConfig):
def expand_section(self, configobj, S=None):
if S is None:
S = list()
S.append(configobj)
for child in configobj.children:
if child in S:
continue
self.expand_section(child, S)
return S
def get_object(self, path):
for item in self.items:
if item.text == path[-1]:
parents = [p.text for p in item.parents]
if parents == path[:-1]:
return item
def to_block(self, section):
return '\n'.join([item.raw for item in section])
def get_section(self, path):
try:
section = self.get_section_objects(path)
return self.to_block(section)
except ValueError:
return list()
def get_section_objects(self, path):
if not isinstance(path, list):
path = [path]
obj = self.get_object(path)
if not obj:
raise ValueError('path does not exist in config')
return self.expand_section(obj)
def add(self, lines, parents=None):
"""Adds one or lines of configuration
"""
ancestors = list()
offset = 0
obj = None
## global config command
if not parents:
for line in to_list(lines):
item = ConfigLine(line)
item.raw = line
if item not in self.items:
self.items.append(item)
else:
for index, p in enumerate(parents):
try:
i = index + 1
obj = self.get_section_objects(parents[:i])[0]
ancestors.append(obj)
except ValueError:
# add parent to config
offset = index * self.indent
obj = ConfigLine(p)
obj.raw = p.rjust(len(p) + offset)
if ancestors:
obj.parents = list(ancestors)
ancestors[-1].children.append(obj)
self.items.append(obj)
ancestors.append(obj)
# add child objects
for line in to_list(lines):
# check if child already exists
for child in ancestors[-1].children:
if child.text == line:
break
else:
offset = len(parents) * self.indent
item = ConfigLine(line)
item.raw = line.rjust(len(line) + offset)
item.parents = ancestors
ancestors[-1].children.append(item)
self.items.append(item)
def get_network_module(**kwargs):
try:
return get_module(**kwargs)
except NameError:
return NetworkModule(**kwargs)
def get_config(module, include_defaults=False):
config = module.params['config']
if not config:
try:
config = module.get_config()
except AttributeError:
defaults = module.params['include_defaults']
config = module.config.get_config(include_defaults=defaults)
return CustomNetworkConfig(indent=2, contents=config)
def load_config(module, candidate):
config = get_config(module)
commands = candidate.difference(config)
commands = [str(c).strip() for c in commands]
save_config = module.params['save']
result = dict(changed=False)
if commands:
if not module.check_mode:
try:
module.configure(commands)
except AttributeError:
module.config(commands)
if save_config:
try:
module.config.save_config()
except AttributeError:
module.execute(['copy running-config startup-config'])
result['changed'] = True
result['updates'] = commands
return result
# END OF COMMON CODE
BOOL_PARAMS = [
'shutdown',
'host_reachability'
]
PARAM_TO_COMMAND_KEYMAP = {
'description': 'description',
'host_reachability': 'host-reachability protocol bgp',
'interface': 'interface',
'shutdown': 'shutdown',
'source_interface': 'source-interface',
'source_interface_hold_down_time': 'source-interface hold-down-time'
}
PARAM_TO_DEFAULT_KEYMAP = {
'description': False,
'shutdown': True,
}
WARNINGS = []
def invoke(name, *args, **kwargs):
func = globals().get(name)
if func:
return func(*args, **kwargs)
def get_value(arg, config, module):
if arg in BOOL_PARAMS:
REGEX = re.compile(r'\s+{0}\s*$'.format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M)
NO_SHUT_REGEX = re.compile(r'\s+no shutdown\s*$', re.M)
value = False
if arg == 'shutdown':
try:
if NO_SHUT_REGEX.search(config):
value = False
elif REGEX.search(config):
value = True
except TypeError:
value = False
else:
try:
if REGEX.search(config):
value = True
except TypeError:
value = False
else:
REGEX = re.compile(r'(?:{0}\s)(?P<value>.*)$'.format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M)
NO_DESC_REGEX = re.compile(r'\s+{0}\s*$'.format('no description'), re.M)
SOURCE_INTF_REGEX = re.compile(r'(?:{0}\s)(?P<value>\S+)$'.format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M)
value = ''
if arg == 'description':
if NO_DESC_REGEX.search(config):
value = ''
elif PARAM_TO_COMMAND_KEYMAP[arg] in config:
value = REGEX.search(config).group('value').strip()
elif arg == 'source_interface':
for line in config.splitlines():
try:
if PARAM_TO_COMMAND_KEYMAP[arg] in config:
value = SOURCE_INTF_REGEX.search(config).group('value').strip()
break
except AttributeError:
value = ''
else:
if PARAM_TO_COMMAND_KEYMAP[arg] in config:
value = REGEX.search(config).group('value').strip()
return value
def get_existing(module, args):
existing = {}
netcfg = get_config(module)
interface_string = 'interface {0}'.format(module.params['interface'].lower())
parents = [interface_string]
config = netcfg.get_section(parents)
if config:
for arg in args:
existing[arg] = get_value(arg, config, module)
existing['interface'] = module.params['interface'].lower()
else:
if interface_string in str(netcfg):
existing['interface'] = module.params['interface'].lower()
for arg in args:
existing[arg] = ''
return existing
def apply_key_map(key_map, table):
new_dict = {}
for key, value in table.items():
new_key = key_map.get(key)
if new_key:
value = table.get(key)
if value:
new_dict[new_key] = value
else:
new_dict[new_key] = value
return new_dict
def fix_commands(commands, module):
source_interface_command = ''
no_source_interface_command = ''
for command in commands:
if 'no source-interface hold-down-time' in command:
pass
elif 'source-interface hold-down-time' in command:
pass
elif 'no source-interface' in command:
no_source_interface_command = command
elif 'source-interface' in command:
source_interface_command = command
if source_interface_command:
commands.pop(commands.index(source_interface_command))
commands.insert(0, source_interface_command)
if no_source_interface_command:
commands.pop(commands.index(no_source_interface_command))
commands.append(no_source_interface_command)
return commands
def state_present(module, existing, proposed, candidate):
commands = list()
proposed_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, proposed)
existing_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, existing)
for key, value in proposed_commands.iteritems():
if value is True:
commands.append(key)
elif value is False:
commands.append('no {0}'.format(key))
elif value == 'default':
if existing_commands.get(key):
existing_value = existing_commands.get(key)
commands.append('no {0} {1}'.format(key, existing_value))
else:
if key.replace(' ', '_').replace('-', '_') in BOOL_PARAMS:
commands.append('no {0}'.format(key.lower()))
module.exit_json(commands=commands)
else:
command = '{0} {1}'.format(key, value.lower())
commands.append(command)
if commands:
commands = fix_commands(commands, module)
parents = ['interface {0}'.format(module.params['interface'].lower())]
candidate.add(commands, parents=parents)
else:
if not existing and module.params['interface']:
commands = ['interface {0}'.format(module.params['interface'].lower())]
candidate.add(commands, parents=[])
def state_absent(module, existing, proposed, candidate):
commands = ['no interface {0}'.format(module.params['interface'].lower())]
candidate.add(commands, parents=[])
def main():
argument_spec = dict(
interface=dict(required=True, type='str'),
description=dict(required=False, type='str'),
host_reachability=dict(required=False, type='bool'),
shutdown=dict(required=False, type='bool'),
source_interface=dict(required=False, type='str'),
source_interface_hold_down_time=dict(required=False, type='str'),
m_facts=dict(required=False, default=False, type='bool'),
state=dict(choices=['present', 'absent'], default='present',
required=False),
include_defaults=dict(default=True),
config=dict(),
save=dict(type='bool', default=False)
)
module = get_network_module(argument_spec=argument_spec,
supports_check_mode=True)
state = module.params['state']
interface = module.params['interface'].lower()
args = [
'interface',
'description',
'host_reachability',
'shutdown',
'source_interface',
'source_interface_hold_down_time'
]
existing = invoke('get_existing', module, args)
end_state = existing
proposed_args = dict((k, v) for k, v in module.params.iteritems()
if v is not None and k in args)
proposed = {}
for key, value in proposed_args.iteritems():
if key != 'interface':
if str(value).lower() == 'true':
value = True
elif str(value).lower() == 'false':
value = False
elif str(value).lower() == 'default':
value = PARAM_TO_DEFAULT_KEYMAP.get(key)
if value is None:
if key in BOOL_PARAMS:
value = False
else:
value = 'default'
if existing.get(key) or (not existing.get(key) and value):
proposed[key] = value
result = {}
if state == 'present' or (state == 'absent' and existing):
if not existing:
WARNINGS.append("The proposed NVE interface did not exist. "
"It's recommended to use nxos_interface to create "
"all logical interfaces.")
candidate = CustomNetworkConfig(indent=3)
invoke('state_%s' % state, module, existing, proposed, candidate)
try:
response = load_config(module, candidate)
result.update(response)
except ShellError:
exc = get_exception()
module.fail_json(msg=str(exc))
else:
result['updates'] = []
result['connected'] = module.connected
if module._verbosity > 0:
end_state = invoke('get_existing', module, args)
result['end_state'] = end_state
result['existing'] = existing
result['proposed'] = proposed_args
if WARNINGS:
result['warnings'] = WARNINGS
module.exit_json(**result)
if __name__ == '__main__':
main()
|
collinprice/titanium_mobile
|
refs/heads/master
|
support/common/css/csslex.py
|
75
|
# -*- coding: utf-8 -*-
'''
A lexical grammar for CSS.
'''
import re
from ply import lex as _lex
__all__ = ('lex','csslexer')
# re helpers
def r_nongroup(rx):
return ur'(?:' + rx + ur')'
def r_or(*rxs):
return r_nongroup(ur'|'.join([r_nongroup(x) for x in rxs]))
def r_star(rx):
return r_nongroup(rx) + ur'*'
def r_plus(rx):
return r_nongroup(rx) + ur'+'
def r_opt(rx):
return r_nongroup(rx) + ur'?'
# lexer
softsp = r_opt(r_or(ur'\r\n', ur'[ \t\r\n\f]'))
s = r_plus(ur'[ \t\r\n\f]')
w = r_opt(s)
nl = ur'\n|\r\n|\r|\f'
h = ur'[0-9a-fA-F]'
nonascii = ur'[^\0-\177]'
unicode = ur'\\' + h + ur'{1,6}' + softsp
escape = r_or(unicode, ur'\\[^\r\n\f0-9a-fA-F]')
nmstart = r_or(ur'[_a-zA-Z]', nonascii, escape)
nmchar = r_or(ur'[_a-zA-Z0-9-]', nonascii, escape)
string1 = ur'"%s"' % r_star(r_or(ur'[^\n\r\f\\"]',
ur'\\' + nl,
escape))
string2 = r"'%s'" % r_star(r_or(ur"[^\n\r\f\\']",
ur'\\' + nl,
escape))
invalid1 = ur'"%s' % r_star(r_or(ur'[^\n\r\f\\"]',
ur'\\'+nl,
escape))
invalid2 = r"'%s" % r_star(r_or(ur"[^\n\r\f\\']",
ur'\\'+nl,
escape))
comment = ur'\/\*[^*]*\*+(?:[^/][^*]*\*+)*\/'
comment = ur'\/\*' + r_star(ur'[^*]') + r_plus(ur'\*') + \
r_star(ur'[^/]' + r_star(ur'[^*]') + r_plus(ur'\*')) + \
ur'\/'
ident = r_opt(ur'-') + nmstart + r_star(nmchar)
name = r_plus(nmchar)
num = r_or(r_star(ur'[0-9]') + ur'\.' + r_plus(ur'[0-9]'),
r_plus(ur'[0-9]'))
string = r_or(string1, string2)
invalid = r_or(invalid1, invalid2)
url = r_star(r_or(ur'[!#$%&*-~]', nonascii, escape))
def letter(c):
return r_or(c.lower(),
ur'\\0{0,4}' +
r_or(hex(ord(c.upper()))[2:], hex(ord(c.lower()))[2:]) +
softsp)
def normalize(x):
'''Normalizes escaped characters to their literal value.'''
p = ur'\\0{0,4}([0-9]{2})'
r = lambda m: chr(int(m.groups()[0],16))
return re.sub(p,r,x).lower()
A = letter(u'A')
C = letter(u'C')
D = letter(u'D')
E = letter(u'E')
G = letter(u'G')
H = letter(u'H')
I = letter(u'I')
K = letter(u'K')
L = letter(u'L')
M = letter(u'M')
N = letter(u'N')
O = letter(u'O')
P = letter(u'P')
R = letter(u'R')
S = letter(u'S')
T = letter(u'T')
U = letter(u'U')
X = letter(u'X')
Z = letter(u'Z')
# %%
class csslexer(object):
literals = list(ur'*-:;.=/)}[]')
tokens = (
'S',
'CDO', 'CDC', 'INCLUDES', 'DASHMATCH',
'LBRACE', 'PLUS', 'GREATER', 'COMMA',
'STRING', 'INVALID',
'IDENT',
'HASH',
'IMPORT_SYM', 'PAGE_SYM', 'MEDIA_SYM', 'CHARSET_SYM',
'IMPORTANT_SYM',
'EMS', 'EXS', 'LENGTH', 'ANGLE', 'TIME', 'FREQ', 'DIMENSION',
'PERCENTAGE', 'NUMBER',
'URI', 'FUNCTION'
)
# several of the following are defined as functions rather
# than simple rules so that tokenizing precedence works properly,
# i.e. lengths, etc. are not parsed as dimensions
t_S = s
# comments are ignored, but line breaks are counted
@_lex.TOKEN(comment)
def t_COMMENT(self, t):
t.lexer.lineno += len(re.findall(nl,t.value))
return None
t_CDO = ur'\<\!\-\-'
t_CDC = ur'\-\-\>'
t_INCLUDES = ur'\~\='
t_DASHMATCH = ur'\|\='
t_LBRACE = w + ur'\{'
t_PLUS = w + ur'\+'
t_GREATER = w + ur'\>'
t_COMMA = w + ur'\,'
@_lex.TOKEN(string)
def t_STRING(self, t):
t.lexer.lineno += len(re.findall(nl,t.value))
return t
@_lex.TOKEN(invalid)
def t_INVALID(self, t):
t.lexer.lineno += len(re.findall(nl,t.value))
return t
t_IDENT = ident
t_HASH = ur'\#' + name
t_IMPORT_SYM = ur'@' + I + M + P + O + R + T
t_PAGE_SYM = ur'@' + P + A + G + E
t_MEDIA_SYM = ur'@' + M + E + D + I + A
# Per the CSS 2.1 errata, the charset rule must be in lowercase
# and must have a trailing space.
t_CHARSET_SYM = ur'@charset\ '
t_IMPORTANT_SYM = ur'\!' + \
r_star(r_or(w,comment)) + \
I + M + P + O + R + T + A + N + T
@_lex.TOKEN(num + E + M)
def t_EMS(self, t):
return t
@_lex.TOKEN(num + E + X)
def t_EXS(self, t):
return t
@_lex.TOKEN(num + r_or(P + X, r_or(C, M) + M, I + N, P + r_or(T, C)))
def t_LENGTH(self, t):
return t
@_lex.TOKEN(num + r_or(D + E + G, r_opt(G) + R + A + D))
def t_ANGLE(self, t):
return t
@_lex.TOKEN(num + r_opt(M) + S)
def t_TIME(self, t):
return t
@_lex.TOKEN(num + r_opt(K) + H + Z)
def t_FREQ(self, t):
return t
@_lex.TOKEN(num + ident)
def t_DIMENSION(self, t):
return t
@_lex.TOKEN(num + ur'%')
def t_PERCENTAGE(self, t):
return t
t_NUMBER = num
@_lex.TOKEN(U + R + L + ur'\(' + w + r_or(string, url) + w + ur'\)')
def t_URI(self, t):
return t
@_lex.TOKEN(ident + ur'\(')
def t_FUNCTION(self, t):
return t
def t_error(self, t):
print "Illegal token '%s'" % t.value[0]
t.lexer.skip(1)
def lex(**kw):
if 'object' in kw: del kw['object']
kw['module'] = csslexer()
if 'reflags' not in kw:
kw['reflags'] = 0
kw['reflags'] |= re.UNICODE | re.IGNORECASE
return _lex.lex(**kw)
if '__main__' == __name__:
_lex.runmain(lexer=lex())
|
sirex/Misago
|
refs/heads/master
|
misago/threads/views/generic/thread/__init__.py
|
8
|
# flake8: noqa
from misago.threads.views.generic.thread.postsactions import PostsActions
from misago.threads.views.generic.thread.threadactions import ThreadActions
from misago.threads.views.generic.thread.view import ThreadView
|
camptocamp/ngo-addons-backport
|
refs/heads/master
|
addons/mail/tests/test_mail_features.py
|
22
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com>
#
# 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/>.
#
##############################################################################
from openerp.addons.mail.tests.test_mail_base import TestMailBase
from openerp.tools.mail import html_sanitize
class test_mail(TestMailBase):
def test_000_alias_setup(self):
""" Test basic mail.alias setup works, before trying to use them for routing """
cr, uid = self.cr, self.uid
self.user_valentin_id = self.res_users.create(cr, uid,
{'name': 'Valentin Cognito', 'email': '[email protected]', 'login': 'valentin.cognito'})
self.user_valentin = self.res_users.browse(cr, uid, self.user_valentin_id)
self.assertEquals(self.user_valentin.alias_name, self.user_valentin.login, "Login should be used as alias")
self.user_pagan_id = self.res_users.create(cr, uid,
{'name': 'Pagan Le Marchant', 'email': '[email protected]', 'login': '[email protected]'})
self.user_pagan = self.res_users.browse(cr, uid, self.user_pagan_id)
self.assertEquals(self.user_pagan.alias_name, 'plmarchant', "If login is an email, the alias should keep only the local part")
self.user_barty_id = self.res_users.create(cr, uid,
{'name': 'Bartholomew Ironside', 'email': '[email protected]', 'login': 'b4r+_#_R3wl$$'})
self.user_barty = self.res_users.browse(cr, uid, self.user_barty_id)
self.assertEquals(self.user_barty.alias_name, 'b4r+_-_r3wl-', 'Disallowed chars should be replaced by hyphens')
def test_00_followers_function_field(self):
""" Tests designed for the many2many function field 'follower_ids'.
We will test to perform writes using the many2many commands 0, 3, 4,
5 and 6. """
cr, uid, user_admin, partner_bert_id, group_pigs = self.cr, self.uid, self.user_admin, self.partner_bert_id, self.group_pigs
# Data: create 'disturbing' values in mail.followers: same res_id, other res_model; same res_model, other res_id
group_dummy_id = self.mail_group.create(cr, uid,
{'name': 'Dummy group'}, {'mail_create_nolog': True})
self.mail_followers.create(cr, uid,
{'res_model': 'mail.thread', 'res_id': self.group_pigs_id, 'partner_id': partner_bert_id})
self.mail_followers.create(cr, uid,
{'res_model': 'mail.group', 'res_id': group_dummy_id, 'partner_id': partner_bert_id})
# Pigs just created: should be only Admin as follower
follower_ids = set([follower.id for follower in group_pigs.message_follower_ids])
self.assertEqual(follower_ids, set([user_admin.partner_id.id]), 'Admin should be the only Pigs fan')
# Subscribe Bert through a '4' command
group_pigs.write({'message_follower_ids': [(4, partner_bert_id)]})
group_pigs.refresh()
follower_ids = set([follower.id for follower in group_pigs.message_follower_ids])
self.assertEqual(follower_ids, set([partner_bert_id, user_admin.partner_id.id]), 'Bert and Admin should be the only Pigs fans')
# Unsubscribe Bert through a '3' command
group_pigs.write({'message_follower_ids': [(3, partner_bert_id)]})
group_pigs.refresh()
follower_ids = set([follower.id for follower in group_pigs.message_follower_ids])
self.assertEqual(follower_ids, set([user_admin.partner_id.id]), 'Admin should be the only Pigs fan')
# Set followers through a '6' command
group_pigs.write({'message_follower_ids': [(6, 0, [partner_bert_id])]})
group_pigs.refresh()
follower_ids = set([follower.id for follower in group_pigs.message_follower_ids])
self.assertEqual(follower_ids, set([partner_bert_id]), 'Bert should be the only Pigs fan')
# Add a follower created on the fly through a '0' command
group_pigs.write({'message_follower_ids': [(0, 0, {'name': 'Patrick Fiori'})]})
partner_patrick_id = self.res_partner.search(cr, uid, [('name', '=', 'Patrick Fiori')])[0]
group_pigs.refresh()
follower_ids = set([follower.id for follower in group_pigs.message_follower_ids])
self.assertEqual(follower_ids, set([partner_bert_id, partner_patrick_id]), 'Bert and Patrick should be the only Pigs fans')
# Finally, unlink through a '5' command
group_pigs.write({'message_follower_ids': [(5, 0)]})
group_pigs.refresh()
follower_ids = set([follower.id for follower in group_pigs.message_follower_ids])
self.assertFalse(follower_ids, 'Pigs group should not have fans anymore')
# Test dummy data has not been altered
fol_obj_ids = self.mail_followers.search(cr, uid, [('res_model', '=', 'mail.thread'), ('res_id', '=', self.group_pigs_id)])
follower_ids = set([follower.partner_id.id for follower in self.mail_followers.browse(cr, uid, fol_obj_ids)])
self.assertEqual(follower_ids, set([partner_bert_id]), 'Bert should be the follower of dummy mail.thread data')
fol_obj_ids = self.mail_followers.search(cr, uid, [('res_model', '=', 'mail.group'), ('res_id', '=', group_dummy_id)])
follower_ids = set([follower.partner_id.id for follower in self.mail_followers.browse(cr, uid, fol_obj_ids)])
self.assertEqual(follower_ids, set([partner_bert_id, user_admin.partner_id.id]), 'Bert and Admin should be the followers of dummy mail.group data')
def test_05_message_followers_and_subtypes(self):
""" Tests designed for the subscriber API as well as message subtypes """
cr, uid, user_admin, user_raoul, group_pigs = self.cr, self.uid, self.user_admin, self.user_raoul, self.group_pigs
# Data: message subtypes
self.mail_message_subtype.create(cr, uid, {'name': 'mt_mg_def', 'default': True, 'res_model': 'mail.group'})
self.mail_message_subtype.create(cr, uid, {'name': 'mt_other_def', 'default': True, 'res_model': 'crm.lead'})
self.mail_message_subtype.create(cr, uid, {'name': 'mt_all_def', 'default': True, 'res_model': False})
mt_mg_nodef = self.mail_message_subtype.create(cr, uid, {'name': 'mt_mg_nodef', 'default': False, 'res_model': 'mail.group'})
mt_all_nodef = self.mail_message_subtype.create(cr, uid, {'name': 'mt_all_nodef', 'default': False, 'res_model': False})
default_group_subtypes = self.mail_message_subtype.search(cr, uid, [('default', '=', True), '|', ('res_model', '=', 'mail.group'), ('res_model', '=', False)])
# ----------------------------------------
# CASE1: test subscriptions with subtypes
# ----------------------------------------
# Do: subscribe Raoul, should have default subtypes
group_pigs.message_subscribe_users([user_raoul.id])
group_pigs.refresh()
# Test: 2 followers (Admin and Raoul)
follower_ids = [follower.id for follower in group_pigs.message_follower_ids]
self.assertEqual(set(follower_ids), set([user_raoul.partner_id.id, user_admin.partner_id.id]),
'message_subscribe: Admin and Raoul should be the only 2 Pigs fans')
# Raoul follows default subtypes
fol_ids = self.mail_followers.search(cr, uid, [
('res_model', '=', 'mail.group'),
('res_id', '=', self.group_pigs_id),
('partner_id', '=', user_raoul.partner_id.id)
])
fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0]
fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids])
self.assertEqual(set(fol_subtype_ids), set(default_group_subtypes),
'message_subscribe: Raoul subscription subtypes are incorrect, should be all default ones')
# Do: subscribe Raoul with specified new subtypes
group_pigs.message_subscribe_users([user_raoul.id], subtype_ids=[mt_mg_nodef])
# Test: 2 followers (Admin and Raoul)
follower_ids = [follower.id for follower in group_pigs.message_follower_ids]
self.assertEqual(set(follower_ids), set([user_raoul.partner_id.id, user_admin.partner_id.id]),
'message_subscribe: Admin and Raoul should be the only 2 Pigs fans')
# Test: 2 lines in mail.followers (no duplicate for Raoul)
fol_ids = self.mail_followers.search(cr, uid, [
('res_model', '=', 'mail.group'),
('res_id', '=', self.group_pigs_id),
])
self.assertEqual(len(fol_ids), 2,
'message_subscribe: subscribing an already-existing follower should not create new entries in mail.followers')
# Test: Raoul follows only specified subtypes
fol_ids = self.mail_followers.search(cr, uid, [
('res_model', '=', 'mail.group'),
('res_id', '=', self.group_pigs_id),
('partner_id', '=', user_raoul.partner_id.id)
])
fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0]
fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids])
self.assertEqual(set(fol_subtype_ids), set([mt_mg_nodef]),
'message_subscribe: Raoul subscription subtypes are incorrect, should be only specified')
# Do: Subscribe Raoul without specified subtypes: should not erase existing subscription subtypes
group_pigs.message_subscribe_users([user_raoul.id, user_raoul.id])
group_pigs.message_subscribe_users([user_raoul.id])
group_pigs.refresh()
# Test: 2 followers (Admin and Raoul)
follower_ids = [follower.id for follower in group_pigs.message_follower_ids]
self.assertEqual(set(follower_ids), set([user_raoul.partner_id.id, user_admin.partner_id.id]),
'message_subscribe: Admin and Raoul should be the only 2 Pigs fans')
# Test: Raoul follows default subtypes
fol_ids = self.mail_followers.search(cr, uid, [
('res_model', '=', 'mail.group'),
('res_id', '=', self.group_pigs_id),
('partner_id', '=', user_raoul.partner_id.id)
])
fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0]
fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids])
self.assertEqual(set(fol_subtype_ids), set([mt_mg_nodef]),
'message_subscribe: Raoul subscription subtypes are incorrect, should be only specified')
# Do: Unsubscribe Raoul twice through message_unsubscribe_users
group_pigs.message_unsubscribe_users([user_raoul.id, user_raoul.id])
group_pigs.refresh()
# Test: 1 follower (Admin)
follower_ids = [follower.id for follower in group_pigs.message_follower_ids]
self.assertEqual(follower_ids, [user_admin.partner_id.id], 'Admin must be the only Pigs fan')
# Test: 1 lines in mail.followers (no duplicate for Raoul)
fol_ids = self.mail_followers.search(cr, uid, [
('res_model', '=', 'mail.group'),
('res_id', '=', self.group_pigs_id)
])
self.assertEqual(len(fol_ids), 1,
'message_subscribe: group should have only 1 entry in mail.follower for 1 follower')
# Do: subscribe Admin with subtype_ids
group_pigs.message_subscribe_users([uid], [mt_mg_nodef, mt_all_nodef])
fol_ids = self.mail_followers.search(cr, uid, [('res_model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id), ('partner_id', '=', user_admin.partner_id.id)])
fol_obj = self.mail_followers.browse(cr, uid, fol_ids)[0]
fol_subtype_ids = set([subtype.id for subtype in fol_obj.subtype_ids])
self.assertEqual(set(fol_subtype_ids), set([mt_mg_nodef, mt_all_nodef]), 'subscription subtypes are incorrect')
# ----------------------------------------
# CASE2: test mail_thread fields
# ----------------------------------------
subtype_data = group_pigs._get_subscription_data(None, None)[group_pigs.id]['message_subtype_data']
self.assertEqual(set(subtype_data.keys()), set(['Discussions', 'mt_mg_def', 'mt_all_def', 'mt_mg_nodef', 'mt_all_nodef']), 'mail.group available subtypes incorrect')
self.assertFalse(subtype_data['Discussions']['followed'], 'Admin should not follow Discussions in pigs')
self.assertTrue(subtype_data['mt_mg_nodef']['followed'], 'Admin should follow mt_mg_nodef in pigs')
self.assertTrue(subtype_data['mt_all_nodef']['followed'], 'Admin should follow mt_all_nodef in pigs')
def test_10_message_quote_context(self):
""" Tests designed for message_post. """
cr, uid, user_admin, group_pigs = self.cr, self.uid, self.user_admin, self.group_pigs
msg1_id = self.mail_message.create(cr, uid, {'body': 'Thread header about Zap Brannigan', 'subject': 'My subject'})
msg2_id = self.mail_message.create(cr, uid, {'body': 'First answer, should not be displayed', 'subject': 'Re: My subject', 'parent_id': msg1_id})
msg3_id = self.mail_message.create(cr, uid, {'body': 'Second answer', 'subject': 'Re: My subject', 'parent_id': msg1_id})
msg4_id = self.mail_message.create(cr, uid, {'body': 'Third answer', 'subject': 'Re: My subject', 'parent_id': msg1_id})
msg_new_id = self.mail_message.create(cr, uid, {'body': 'My answer I am propagating', 'subject': 'Re: My subject', 'parent_id': msg1_id})
result = self.mail_message.message_quote_context(cr, uid, msg_new_id, limit=3)
self.assertIn('Thread header about Zap Brannigan', result, 'Thread header content should be in quote.')
self.assertIn('Second answer', result, 'Answer should be in quote.')
self.assertIn('Third answer', result, 'Answer should be in quote.')
self.assertIn('expandable', result, 'Expandable should be present.')
self.assertNotIn('First answer, should not be displayed', result, 'Old answer should not be in quote.')
self.assertNotIn('My answer I am propagating', result, 'Thread header content should be in quote.')
def test_20_message_post(self):
""" Tests designed for message_post. """
cr, uid, user_raoul, group_pigs = self.cr, self.uid, self.user_raoul, self.group_pigs
# --------------------------------------------------
# Data creation
# --------------------------------------------------
# 0 - Update existing users-partners
self.res_users.write(cr, uid, [uid], {'email': 'a@a', 'notification_email_send': 'comment'})
self.res_users.write(cr, uid, [self.user_raoul_id], {'email': 'r@r'})
# 1 - Bert Tartopoils, with email, should receive emails for comments and emails
p_b_id = self.res_partner.create(cr, uid, {'name': 'Bert Tartopoils', 'email': 'b@b'})
# 2 - Carine Poilvache, with email, should receive emails for emails
p_c_id = self.res_partner.create(cr, uid, {'name': 'Carine Poilvache', 'email': 'c@c', 'notification_email_send': 'email'})
# 3 - Dédé Grosbedon, without email, to test email verification; should receive emails for every message
p_d_id = self.res_partner.create(cr, uid, {'name': 'Dédé Grosbedon', 'email': 'd@d', 'notification_email_send': 'all'})
# 4 - Attachments
attach1_id = self.ir_attachment.create(cr, user_raoul.id, {
'name': 'Attach1', 'datas_fname': 'Attach1',
'datas': 'bWlncmF0aW9uIHRlc3Q=',
'res_model': 'mail.compose.message', 'res_id': 0})
attach2_id = self.ir_attachment.create(cr, user_raoul.id, {
'name': 'Attach2', 'datas_fname': 'Attach2',
'datas': 'bWlncmF0aW9uIHRlc3Q=',
'res_model': 'mail.compose.message', 'res_id': 0})
attach3_id = self.ir_attachment.create(cr, user_raoul.id, {
'name': 'Attach3', 'datas_fname': 'Attach3',
'datas': 'bWlncmF0aW9uIHRlc3Q=',
'res_model': 'mail.compose.message', 'res_id': 0})
# 5 - Mail data
_subject = 'Pigs'
_mail_subject = 'Re: %s' % (group_pigs.name)
_body1 = '<p>Pigs rules</p>'
_body2 = '<html>Pigs rocks</html>'
_attachments = [
('List1', 'My first attachment'),
('List2', 'My second attachment')
]
# --------------------------------------------------
# CASE1: post comment + partners + attachments
# --------------------------------------------------
# Data: set alias_domain to see emails with alias
self.registry('ir.config_parameter').set_param(self.cr, self.uid, 'mail.catchall.domain', 'schlouby.fr')
# Data: change Pigs name to test reply_to
self.mail_group.write(cr, uid, [self.group_pigs_id], {'name': '"Pigs" !ù $%-'})
# Do: subscribe Raoul
new_follower_ids = [self.partner_raoul_id]
group_pigs.message_subscribe(new_follower_ids)
# Test: group followers = Raoul + uid
group_fids = [follower.id for follower in group_pigs.message_follower_ids]
test_fids = new_follower_ids + [self.partner_admin_id]
self.assertEqual(set(test_fids), set(group_fids),
'message_subscribe: incorrect followers after subscribe')
# Do: Raoul message_post on Pigs
self._init_mock_build_email()
msg1_id = self.mail_group.message_post(cr, user_raoul.id, self.group_pigs_id,
body=_body1, subject=_subject, partner_ids=[p_b_id, p_c_id],
attachment_ids=[attach1_id, attach2_id], attachments=_attachments,
type='comment', subtype='mt_comment')
msg = self.mail_message.browse(cr, uid, msg1_id)
msg_message_id = msg.message_id
msg_pids = [partner.id for partner in msg.notified_partner_ids]
msg_aids = [attach.id for attach in msg.attachment_ids]
sent_emails = self._build_email_kwargs_list
# Test: mail_message: subject and body not modified
self.assertEqual(_subject, msg.subject, 'message_post: mail.message subject incorrect')
self.assertEqual(_body1, msg.body, 'message_post: mail.message body incorrect')
# Test: mail_message: notified_partner_ids = group followers + partner_ids - author
test_pids = set([self.partner_admin_id, p_b_id, p_c_id])
self.assertEqual(test_pids, set(msg_pids), 'message_post: mail.message notified partners incorrect')
# Test: mail_message: attachments (4, attachment_ids + attachments)
test_aids = set([attach1_id, attach2_id])
msg_attach_names = set([attach.name for attach in msg.attachment_ids])
test_attach_names = set(['Attach1', 'Attach2', 'List1', 'List2'])
self.assertEqual(len(msg_aids), 4,
'message_post: mail.message wrong number of attachments')
self.assertEqual(msg_attach_names, test_attach_names,
'message_post: mail.message attachments incorrectly added')
self.assertTrue(test_aids.issubset(set(msg_aids)),
'message_post: mail.message attachments duplicated')
for attach in msg.attachment_ids:
self.assertEqual(attach.res_model, 'mail.group',
'message_post: mail.message attachments were not linked to the document')
self.assertEqual(attach.res_id, group_pigs.id,
'message_post: mail.message attachments were not linked to the document')
if 'List' in attach.name:
self.assertIn((attach.name, attach.datas.decode('base64')), _attachments,
'message_post: mail.message attachment name / data incorrect')
dl_attach = self.mail_message.download_attachment(cr, user_raoul.id, id_message=msg.id, attachment_id=attach.id)
self.assertIn((dl_attach['filename'], dl_attach['base64'].decode('base64')), _attachments,
'message_post: mail.message download_attachment is incorrect')
# Test: followers: same as before (author was already subscribed)
group_pigs.refresh()
group_fids = [follower.id for follower in group_pigs.message_follower_ids]
test_fids = new_follower_ids + [self.partner_admin_id]
self.assertEqual(set(test_fids), set(group_fids),
'message_post: wrong followers after posting')
# Test: mail_mail: notifications have been deleted
self.assertFalse(self.mail_mail.search(cr, uid, [('mail_message_id', '=', msg1_id)]),
'message_post: mail.mail notifications should have been auto-deleted!')
# Test: notifications emails: to a and b, c is email only, r is author
# test_emailto = ['Administrator <a@a>', 'Bert Tartopoils <b@b>']
test_emailto = [u'"Followers of \\"Pigs\\" !\xf9 $%-" <a@a>', u'"Followers of \\"Pigs\\" !\xf9 $%-" <b@b>']
self.assertEqual(len(sent_emails), 2,
'message_post: notification emails wrong number of send emails')
self.assertEqual(set([m['email_to'][0] for m in sent_emails]), set(test_emailto),
'message_post: notification emails wrong recipients (email_to)')
for sent_email in sent_emails:
self.assertEqual(sent_email['email_from'], 'Raoul Grosbedon <[email protected]>',
'message_post: notification email wrong email_from: should use alias of sender')
self.assertEqual(len(sent_email['email_to']), 1,
'message_post: notification email sent to more than one email address instead of a precise partner')
self.assertIn(sent_email['email_to'][0], test_emailto,
'message_post: notification email email_to incorrect')
self.assertEqual(sent_email['reply_to'], u'"Followers of \\"Pigs\\" !\xf9 $%-" <[email protected]>',
'message_post: notification email reply_to incorrect')
self.assertEqual(_subject, sent_email['subject'],
'message_post: notification email subject incorrect')
self.assertIn(_body1, sent_email['body'],
'message_post: notification email body incorrect')
self.assertIn(user_raoul.signature, sent_email['body'],
'message_post: notification email body should contain the sender signature')
self.assertIn('Pigs rules', sent_email['body_alternative'],
'message_post: notification email body alternative should contain the body')
self.assertNotIn('<p>', sent_email['body_alternative'],
'message_post: notification email body alternative still contains html')
self.assertIn(user_raoul.signature, sent_email['body_alternative'],
'message_post: notification email body alternative should contain the sender signature')
self.assertFalse(sent_email['references'],
'message_post: references should be False when sending a message that is not a reply')
# Test: notification linked to this message = group followers = notified_partner_ids
notif_ids = self.mail_notification.search(cr, uid, [('message_id', '=', msg1_id)])
notif_pids = set([notif.partner_id.id for notif in self.mail_notification.browse(cr, uid, notif_ids)])
self.assertEqual(notif_pids, test_pids,
'message_post: mail.message created mail.notification incorrect')
# Data: Pigs name back to normal
self.mail_group.write(cr, uid, [self.group_pigs_id], {'name': 'Pigs'})
# --------------------------------------------------
# CASE2: reply + parent_id + parent notification
# --------------------------------------------------
# Data: remove alias_domain to see emails with alias
param_ids = self.registry('ir.config_parameter').search(cr, uid, [('key', '=', 'mail.catchall.domain')])
self.registry('ir.config_parameter').unlink(cr, uid, param_ids)
# Do: Raoul message_post on Pigs
self._init_mock_build_email()
msg2_id = self.mail_group.message_post(cr, user_raoul.id, self.group_pigs_id,
body=_body2, type='email', subtype='mt_comment',
partner_ids=[p_d_id], parent_id=msg1_id, attachment_ids=[attach3_id],
context={'mail_post_autofollow': True})
msg = self.mail_message.browse(cr, uid, msg2_id)
msg_pids = [partner.id for partner in msg.notified_partner_ids]
msg_aids = [attach.id for attach in msg.attachment_ids]
sent_emails = self._build_email_kwargs_list
# Test: mail_message: subject is False, body, parent_id is msg_id
self.assertEqual(msg.subject, False, 'message_post: mail.message subject incorrect')
self.assertEqual(msg.body, html_sanitize(_body2), 'message_post: mail.message body incorrect')
self.assertEqual(msg.parent_id.id, msg1_id, 'message_post: mail.message parent_id incorrect')
# Test: mail_message: notified_partner_ids = group followers
test_pids = [self.partner_admin_id, p_d_id]
self.assertEqual(set(test_pids), set(msg_pids), 'message_post: mail.message partners incorrect')
# Test: mail_message: notifications linked to this message = group followers = notified_partner_ids
notif_ids = self.mail_notification.search(cr, uid, [('message_id', '=', msg2_id)])
notif_pids = [notif.partner_id.id for notif in self.mail_notification.browse(cr, uid, notif_ids)]
self.assertEqual(set(test_pids), set(notif_pids), 'message_post: mail.message notification partners incorrect')
# Test: mail_mail: notifications deleted
self.assertFalse(self.mail_mail.search(cr, uid, [('mail_message_id', '=', msg2_id)]), 'mail.mail notifications should have been auto-deleted!')
# Test: emails send by server (to a, b, c, d)
# test_emailto = [u'Administrator <a@a>', u'Bert Tartopoils <b@b>', u'Carine Poilvache <c@c>', u'D\xe9d\xe9 Grosbedon <d@d>']
test_emailto = [u'Followers of Pigs <a@a>', u'Followers of Pigs <b@b>', u'Followers of Pigs <c@c>', u'Followers of Pigs <d@d>']
# self.assertEqual(len(sent_emails), 3, 'sent_email number of sent emails incorrect')
for sent_email in sent_emails:
self.assertEqual(sent_email['email_from'], 'Raoul Grosbedon <r@r>',
'message_post: notification email wrong email_from: should use email of sender when no alias domain set')
self.assertEqual(len(sent_email['email_to']), 1,
'message_post: notification email sent to more than one email address instead of a precise partner')
self.assertIn(sent_email['email_to'][0], test_emailto,
'message_post: notification email email_to incorrect')
self.assertEqual(sent_email['reply_to'], 'Followers of Pigs <r@r>',
'message_post: notification email reply_to incorrect: should name Followers of Pigs, and have raoul email')
self.assertEqual(_mail_subject, sent_email['subject'],
'message_post: notification email subject incorrect')
self.assertIn(html_sanitize(_body2), sent_email['body'],
'message_post: notification email does not contain the body')
self.assertIn(user_raoul.signature, sent_email['body'],
'message_post: notification email body should contain the sender signature')
self.assertIn('Pigs rocks', sent_email['body_alternative'],
'message_post: notification email body alternative should contain the body')
self.assertNotIn('<p>', sent_email['body_alternative'],
'message_post: notification email body alternative still contains html')
self.assertIn(user_raoul.signature, sent_email['body_alternative'],
'message_post: notification email body alternative should contain the sender signature')
self.assertIn(msg_message_id, sent_email['references'],
'message_post: notification email references lacks parent message message_id')
# Test: attachments + download
for attach in msg.attachment_ids:
self.assertEqual(attach.res_model, 'mail.group',
'message_post: mail.message attachment res_model incorrect')
self.assertEqual(attach.res_id, self.group_pigs_id,
'message_post: mail.message attachment res_id incorrect')
# Test: Dédé has been notified -> should also have been notified of the parent message
msg = self.mail_message.browse(cr, uid, msg1_id)
msg_pids = set([partner.id for partner in msg.notified_partner_ids])
test_pids = set([self.partner_admin_id, p_b_id, p_c_id, p_d_id])
self.assertEqual(test_pids, msg_pids, 'message_post: mail.message parent notification not created')
# Do: reply to last message
msg3_id = self.mail_group.message_post(cr, user_raoul.id, self.group_pigs_id, body='Test', parent_id=msg2_id)
msg = self.mail_message.browse(cr, uid, msg3_id)
# Test: check that its parent will be the first message
self.assertEqual(msg.parent_id.id, msg1_id, 'message_post did not flatten the thread structure')
def test_25_message_compose_wizard(self):
""" Tests designed for the mail.compose.message wizard. """
cr, uid, user_raoul, group_pigs = self.cr, self.uid, self.user_raoul, self.group_pigs
mail_compose = self.registry('mail.compose.message')
# --------------------------------------------------
# Data creation
# --------------------------------------------------
# 0 - Update existing users-partners
self.res_users.write(cr, uid, [uid], {'email': 'a@a'})
self.res_users.write(cr, uid, [self.user_raoul_id], {'email': 'r@r'})
# 1 - Bert Tartopoils, with email, should receive emails for comments and emails
p_b_id = self.res_partner.create(cr, uid, {'name': 'Bert Tartopoils', 'email': 'b@b'})
# 2 - Carine Poilvache, with email, should receive emails for emails
p_c_id = self.res_partner.create(cr, uid, {'name': 'Carine Poilvache', 'email': 'c@c', 'notification_email_send': 'email'})
# 3 - Dédé Grosbedon, without email, to test email verification; should receive emails for every message
p_d_id = self.res_partner.create(cr, uid, {'name': 'Dédé Grosbedon', 'email': 'd@d', 'notification_email_send': 'all'})
# 4 - Create a Bird mail.group, that will be used to test mass mailing
group_bird_id = self.mail_group.create(cr, uid,
{
'name': 'Bird',
'description': 'Bird resistance',
}, context={'mail_create_nolog': True})
group_bird = self.mail_group.browse(cr, uid, group_bird_id)
# 5 - Mail data
_subject = 'Pigs'
_body = 'Pigs <b>rule</b>'
_reply_subject = 'Re: %s' % _subject
_attachments = [
{'name': 'First', 'datas_fname': 'first.txt', 'datas': 'My first attachment'.encode('base64')},
{'name': 'Second', 'datas_fname': 'second.txt', 'datas': 'My second attachment'.encode('base64')}
]
_attachments_test = [('first.txt', 'My first attachment'), ('second.txt', 'My second attachment')]
# 6 - Subscribe Bert to Pigs
group_pigs.message_subscribe([p_b_id])
# --------------------------------------------------
# CASE1: wizard + partners + context keys
# --------------------------------------------------
# Do: Raoul wizard-composes on Pigs with auto-follow for partners, not for author
compose_id = mail_compose.create(cr, user_raoul.id,
{
'subject': _subject,
'body': _body,
'partner_ids': [(4, p_c_id), (4, p_d_id)],
}, context={
'default_composition_mode': 'comment',
'default_model': 'mail.group',
'default_res_id': self.group_pigs_id,
})
compose = mail_compose.browse(cr, uid, compose_id)
# Test: mail.compose.message: composition_mode, model, res_id
self.assertEqual(compose.composition_mode, 'comment', 'compose wizard: mail.compose.message incorrect composition_mode')
self.assertEqual(compose.model, 'mail.group', 'compose wizard: mail.compose.message incorrect model')
self.assertEqual(compose.res_id, self.group_pigs_id, 'compose wizard: mail.compose.message incorrect res_id')
# Do: Post the comment
mail_compose.send_mail(cr, user_raoul.id, [compose_id], {'mail_post_autofollow': True, 'mail_create_nosubscribe': True})
group_pigs.refresh()
message = group_pigs.message_ids[0]
# Test: mail.group: followers (c and d added by auto follow key; raoul not added by nosubscribe key)
pigs_pids = [p.id for p in group_pigs.message_follower_ids]
test_pids = [self.partner_admin_id, p_b_id, p_c_id, p_d_id]
self.assertEqual(set(pigs_pids), set(test_pids),
'compose wizard: mail_post_autofollow and mail_create_nosubscribe context keys not correctly taken into account')
# Test: mail.message: subject, body inside p
self.assertEqual(message.subject, _subject, 'compose wizard: mail.message incorrect subject')
self.assertEqual(message.body, '<p>%s</p>' % _body, 'compose wizard: mail.message incorrect body')
# Test: mail.message: notified_partner_ids = admin + bert (followers) + c + d (recipients)
msg_pids = [partner.id for partner in message.notified_partner_ids]
test_pids = [self.partner_admin_id, p_b_id, p_c_id, p_d_id]
self.assertEqual(set(msg_pids), set(test_pids),
'compose wizard: mail.message notified_partner_ids incorrect')
# --------------------------------------------------
# CASE2: reply + attachments
# --------------------------------------------------
# Do: Reply with attachments
compose_id = mail_compose.create(cr, user_raoul.id,
{
'attachment_ids': [(0, 0, _attachments[0]), (0, 0, _attachments[1])]
}, context={
'default_composition_mode': 'reply',
'default_model': 'mail.thread',
'default_res_id': self.group_pigs_id,
'default_parent_id': message.id
})
compose = mail_compose.browse(cr, uid, compose_id)
# Test: mail.compose.message: model, res_id, parent_id
self.assertEqual(compose.model, 'mail.group', 'compose wizard: mail.compose.message incorrect model')
self.assertEqual(compose.res_id, self.group_pigs_id, 'compose wizard: mail.compose.message incorrect res_id')
self.assertEqual(compose.parent_id.id, message.id, 'compose wizard: mail.compose.message incorrect parent_id')
# Test: mail.compose.message: subject as Re:.., body, parent_id
self.assertEqual(compose.subject, _reply_subject, 'compose wizard: mail.compose.message incorrect subject')
self.assertFalse(compose.body, 'compose wizard: mail.compose.message body should not contain parent message body')
self.assertEqual(compose.parent_id and compose.parent_id.id, message.id, 'compose wizard: mail.compose.message parent_id incorrect')
# Test: mail.compose.message: attachments
for attach in compose.attachment_ids:
self.assertIn((attach.datas_fname, attach.datas.decode('base64')), _attachments_test,
'compose wizard: mail.message attachment name / data incorrect')
# --------------------------------------------------
# CASE3: mass_mail on Pigs and Bird
# --------------------------------------------------
# Do: Compose in mass_mail_mode on pigs and bird
compose_id = mail_compose.create(cr, user_raoul.id,
{
'subject': _subject,
'body': '${object.description}',
'partner_ids': [(4, p_c_id), (4, p_d_id)],
}, context={
'default_composition_mode': 'mass_mail',
'default_model': 'mail.group',
'default_res_id': False,
'active_ids': [self.group_pigs_id, group_bird_id],
})
compose = mail_compose.browse(cr, uid, compose_id)
# D: Post the comment, get created message for each group
mail_compose.send_mail(cr, user_raoul.id, [compose_id], context={
'default_res_id': -1,
'active_ids': [self.group_pigs_id, group_bird_id]
})
group_pigs.refresh()
group_bird.refresh()
message1 = group_pigs.message_ids[0]
message2 = group_bird.message_ids[0]
# Test: Pigs and Bird did receive their message
test_msg_ids = self.mail_message.search(cr, uid, [], limit=2)
self.assertIn(message1.id, test_msg_ids, 'compose wizard: Pigs did not receive its mass mailing message')
self.assertIn(message2.id, test_msg_ids, 'compose wizard: Bird did not receive its mass mailing message')
# Test: mail.message: subject, body, subtype, notified partners (nobody + specific recipients)
self.assertEqual(message1.subject, _subject,
'compose wizard: message_post: mail.message in mass mail subject incorrect')
self.assertEqual(message1.body, '<p>%s</p>' % group_pigs.description,
'compose wizard: message_post: mail.message in mass mail body incorrect')
self.assertEqual(set([p.id for p in message1.notified_partner_ids]), set([p_c_id, p_d_id]),
'compose wizard: message_post: mail.message in mass mail incorrect notified partners')
self.assertEqual(message2.subject, _subject,
'compose wizard: message_post: mail.message in mass mail subject incorrect')
self.assertEqual(message2.body, '<p>%s</p>' % group_bird.description,
'compose wizard: message_post: mail.message in mass mail body incorrect')
self.assertEqual(set([p.id for p in message2.notified_partner_ids]), set([p_c_id, p_d_id]),
'compose wizard: message_post: mail.message in mass mail incorrect notified partners')
# Test: mail.group followers: author not added as follower in mass mail mode
pigs_pids = [p.id for p in group_pigs.message_follower_ids]
test_pids = [self.partner_admin_id, p_b_id, p_c_id, p_d_id]
self.assertEqual(set(pigs_pids), set(test_pids),
'compose wizard: mail_post_autofollow and mail_create_nosubscribe context keys not correctly taken into account')
bird_pids = [p.id for p in group_bird.message_follower_ids]
test_pids = [self.partner_admin_id]
self.assertEqual(set(bird_pids), set(test_pids),
'compose wizard: mail_post_autofollow and mail_create_nosubscribe context keys not correctly taken into account')
def test_30_needaction(self):
""" Tests for mail.message needaction. """
cr, uid, user_admin, user_raoul, group_pigs = self.cr, self.uid, self.user_admin, self.user_raoul, self.group_pigs
group_pigs_demo = self.mail_group.browse(cr, self.user_raoul_id, self.group_pigs_id)
na_admin_base = self.mail_message._needaction_count(cr, uid, domain=[])
na_demo_base = self.mail_message._needaction_count(cr, user_raoul.id, domain=[])
# Test: number of unread notification = needaction on mail.message
notif_ids = self.mail_notification.search(cr, uid, [
('partner_id', '=', user_admin.partner_id.id),
('read', '=', False)
])
na_count = self.mail_message._needaction_count(cr, uid, domain=[])
self.assertEqual(len(notif_ids), na_count, 'unread notifications count does not match needaction count')
# Do: post 2 message on group_pigs as admin, 3 messages as demo user
for dummy in range(2):
group_pigs.message_post(body='My Body', subtype='mt_comment')
for dummy in range(3):
group_pigs_demo.message_post(body='My Demo Body', subtype='mt_comment')
# Test: admin has 3 new notifications (from demo), and 3 new needaction
notif_ids = self.mail_notification.search(cr, uid, [
('partner_id', '=', user_admin.partner_id.id),
('read', '=', False)
])
self.assertEqual(len(notif_ids), na_admin_base + 3, 'Admin should have 3 new unread notifications')
na_admin = self.mail_message._needaction_count(cr, uid, domain=[])
na_admin_group = self.mail_message._needaction_count(cr, uid, domain=[('model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id)])
self.assertEqual(na_admin, na_admin_base + 3, 'Admin should have 3 new needaction')
self.assertEqual(na_admin_group, 3, 'Admin should have 3 needaction related to Pigs')
# Test: demo has 0 new notifications (not a follower, not receiving its own messages), and 0 new needaction
notif_ids = self.mail_notification.search(cr, uid, [
('partner_id', '=', user_raoul.partner_id.id),
('read', '=', False)
])
self.assertEqual(len(notif_ids), na_demo_base + 0, 'Demo should have 0 new unread notifications')
na_demo = self.mail_message._needaction_count(cr, user_raoul.id, domain=[])
na_demo_group = self.mail_message._needaction_count(cr, user_raoul.id, domain=[('model', '=', 'mail.group'), ('res_id', '=', self.group_pigs_id)])
self.assertEqual(na_demo, na_demo_base + 0, 'Demo should have 0 new needaction')
self.assertEqual(na_demo_group, 0, 'Demo should have 0 needaction related to Pigs')
def test_40_track_field(self):
""" Testing auto tracking of fields. """
def _strip_string_spaces(body):
return body.replace(' ', '').replace('\n', '')
# Data: subscribe Raoul to Pigs, because he will change the public attribute and may loose access to the record
cr, uid = self.cr, self.uid
self.mail_group.message_subscribe_users(cr, uid, [self.group_pigs_id], [self.user_raoul_id])
# Data: res.users.group, to test group_public_id automatic logging
group_system_ref = self.registry('ir.model.data').get_object_reference(cr, uid, 'base', 'group_system')
group_system_id = group_system_ref and group_system_ref[1] or False
# Data: custom subtypes
mt_private_id = self.mail_message_subtype.create(cr, uid, {'name': 'private', 'description': 'Private public'})
self.ir_model_data.create(cr, uid, {'name': 'mt_private', 'model': 'mail.message.subtype', 'module': 'mail', 'res_id': mt_private_id})
mt_name_supername_id = self.mail_message_subtype.create(cr, uid, {'name': 'name_supername', 'description': 'Supername name'})
self.ir_model_data.create(cr, uid, {'name': 'mt_name_supername', 'model': 'mail.message.subtype', 'module': 'mail', 'res_id': mt_name_supername_id})
mt_group_public_id = self.mail_message_subtype.create(cr, uid, {'name': 'group_public', 'description': 'Group changed'})
self.ir_model_data.create(cr, uid, {'name': 'mt_group_public', 'model': 'mail.message.subtype', 'module': 'mail', 'res_id': mt_group_public_id})
# Data: alter mail_group model for testing purposes (test on classic, selection and many2one fields)
self.mail_group._track = {
'public': {
'mail.mt_private': lambda self, cr, uid, obj, ctx=None: obj['public'] == 'private',
},
'name': {
'mail.mt_name_supername': lambda self, cr, uid, obj, ctx=None: obj['name'] == 'supername',
},
'group_public_id': {
'mail.mt_group_public': lambda self, cr, uid, obj, ctx=None: True,
},
}
public_col = self.mail_group._columns.get('public')
name_col = self.mail_group._columns.get('name')
group_public_col = self.mail_group._columns.get('group_public_id')
public_col.track_visibility = 'onchange'
name_col.track_visibility = 'always'
group_public_col.track_visibility = 'onchange'
# Test: change name -> always tracked, not related to a subtype
self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'public': 'public'})
self.group_pigs.refresh()
self.assertEqual(len(self.group_pigs.message_ids), 1, 'tracked: a message should have been produced')
# Test: first produced message: no subtype, name change tracked
last_msg = self.group_pigs.message_ids[-1]
self.assertFalse(last_msg.subtype_id, 'tracked: message should not have been linked to a subtype')
self.assertIn(u'SelectedGroupOnly\u2192Public', _strip_string_spaces(last_msg.body), 'tracked: message body incorrect')
self.assertIn('Pigs', _strip_string_spaces(last_msg.body), 'tracked: message body does not hold always tracked field')
# Test: change name as supername, public as private -> 2 subtypes
self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'name': 'supername', 'public': 'private'})
self.group_pigs.refresh()
self.assertEqual(len(self.group_pigs.message_ids), 3, 'tracked: two messages should have been produced')
# Test: first produced message: mt_name_supername
last_msg = self.group_pigs.message_ids[-2]
self.assertEqual(last_msg.subtype_id.id, mt_private_id, 'tracked: message should be linked to mt_private subtype')
self.assertIn('Private public', last_msg.body, 'tracked: message body does not hold the subtype description')
self.assertIn(u'Pigs\u2192supername', _strip_string_spaces(last_msg.body), 'tracked: message body incorrect')
# Test: second produced message: mt_name_supername
last_msg = self.group_pigs.message_ids[-3]
self.assertEqual(last_msg.subtype_id.id, mt_name_supername_id, 'tracked: message should be linked to mt_name_supername subtype')
self.assertIn('Supername name', last_msg.body, 'tracked: message body does not hold the subtype description')
self.assertIn(u'Public\u2192Private', _strip_string_spaces(last_msg.body), 'tracked: message body incorrect')
self.assertIn(u'Pigs\u2192supername', _strip_string_spaces(last_msg.body), 'tracked feature: message body does not hold always tracked field')
# Test: change public as public, group_public_id -> 1 subtype, name always tracked
self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'public': 'public', 'group_public_id': group_system_id})
self.group_pigs.refresh()
self.assertEqual(len(self.group_pigs.message_ids), 4, 'tracked: one message should have been produced')
# Test: first produced message: mt_group_public_id, with name always tracked, public tracked on change
last_msg = self.group_pigs.message_ids[-4]
self.assertEqual(last_msg.subtype_id.id, mt_group_public_id, 'tracked: message should not be linked to any subtype')
self.assertIn('Group changed', last_msg.body, 'tracked: message body does not hold the subtype description')
self.assertIn(u'Private\u2192Public', _strip_string_spaces(last_msg.body), 'tracked: message body does not hold changed tracked field')
self.assertIn(u'HumanResources/Employee\u2192Administration/Settings', _strip_string_spaces(last_msg.body), 'tracked: message body does not hold always tracked field')
# Test: change not tracked field, no tracking message
self.mail_group.write(cr, self.user_raoul_id, [self.group_pigs_id], {'description': 'Dummy'})
self.group_pigs.refresh()
self.assertEqual(len(self.group_pigs.message_ids), 4, 'tracked: No message should have been produced')
# Data: removed changes
public_col.track_visibility = None
name_col.track_visibility = None
group_public_col.track_visibility = None
self.mail_group._track = {}
|
ASCrookes/django
|
refs/heads/master
|
django/template/engine.py
|
199
|
import warnings
from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache, six
from django.utils.deprecation import RemovedInDjango110Warning
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from .base import Context, Template
from .context import _builtin_context_processors
from .exceptions import TemplateDoesNotExist
from .library import import_library
_context_instance_undefined = object()
_dictionary_undefined = object()
_dirs_undefined = object()
class Engine(object):
default_builtins = [
'django.template.defaulttags',
'django.template.defaultfilters',
'django.template.loader_tags',
]
def __init__(self, dirs=None, app_dirs=False,
allowed_include_roots=None, context_processors=None,
debug=False, loaders=None, string_if_invalid='',
file_charset='utf-8', libraries=None, builtins=None):
if dirs is None:
dirs = []
if allowed_include_roots is None:
allowed_include_roots = []
if context_processors is None:
context_processors = []
if loaders is None:
loaders = ['django.template.loaders.filesystem.Loader']
if app_dirs:
loaders += ['django.template.loaders.app_directories.Loader']
else:
if app_dirs:
raise ImproperlyConfigured(
"app_dirs must not be set when loaders is defined.")
if libraries is None:
libraries = {}
if builtins is None:
builtins = []
if isinstance(allowed_include_roots, six.string_types):
raise ImproperlyConfigured(
"allowed_include_roots must be a tuple, not a string.")
self.dirs = dirs
self.app_dirs = app_dirs
self.allowed_include_roots = allowed_include_roots
self.context_processors = context_processors
self.debug = debug
self.loaders = loaders
self.string_if_invalid = string_if_invalid
self.file_charset = file_charset
self.libraries = libraries
self.template_libraries = self.get_template_libraries(libraries)
self.builtins = self.default_builtins + builtins
self.template_builtins = self.get_template_builtins(self.builtins)
@staticmethod
@lru_cache.lru_cache()
def get_default():
"""
When only one DjangoTemplates backend is configured, returns it.
Raises ImproperlyConfigured otherwise.
This is required for preserving historical APIs that rely on a
globally available, implicitly configured engine such as:
>>> from django.template import Context, Template
>>> template = Template("Hello {{ name }}!")
>>> context = Context({'name': "world"})
>>> template.render(context)
'Hello world!'
"""
# Since Engine is imported in django.template and since
# DjangoTemplates is a wrapper around this Engine class,
# local imports are required to avoid import loops.
from django.template import engines
from django.template.backends.django import DjangoTemplates
django_engines = [engine for engine in engines.all()
if isinstance(engine, DjangoTemplates)]
if len(django_engines) == 1:
# Unwrap the Engine instance inside DjangoTemplates
return django_engines[0].engine
elif len(django_engines) == 0:
raise ImproperlyConfigured(
"No DjangoTemplates backend is configured.")
else:
raise ImproperlyConfigured(
"Several DjangoTemplates backends are configured. "
"You must select one explicitly.")
@cached_property
def template_context_processors(self):
context_processors = _builtin_context_processors
context_processors += tuple(self.context_processors)
return tuple(import_string(path) for path in context_processors)
def get_template_builtins(self, builtins):
return [import_library(x) for x in builtins]
def get_template_libraries(self, libraries):
loaded = {}
for name, path in libraries.items():
loaded[name] = import_library(path)
return loaded
@cached_property
def template_loaders(self):
return self.get_template_loaders(self.loaders)
def get_template_loaders(self, template_loaders):
loaders = []
for template_loader in template_loaders:
loader = self.find_template_loader(template_loader)
if loader is not None:
loaders.append(loader)
return loaders
def find_template_loader(self, loader):
if isinstance(loader, (tuple, list)):
args = list(loader[1:])
loader = loader[0]
else:
args = []
if isinstance(loader, six.string_types):
loader_class = import_string(loader)
if getattr(loader_class, '_accepts_engine_in_init', False):
args.insert(0, self)
else:
warnings.warn(
"%s inherits from django.template.loader.BaseLoader "
"instead of django.template.loaders.base.Loader. " %
loader, RemovedInDjango110Warning, stacklevel=2)
return loader_class(*args)
else:
raise ImproperlyConfigured(
"Invalid value in template loaders configuration: %r" % loader)
def find_template(self, name, dirs=None, skip=None):
tried = []
for loader in self.template_loaders:
if loader.supports_recursion:
try:
template = loader.get_template(
name, template_dirs=dirs, skip=skip,
)
return template, template.origin
except TemplateDoesNotExist as e:
tried.extend(e.tried)
else:
# RemovedInDjango20Warning: Use old api for non-recursive
# loaders.
try:
return loader(name, dirs)
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(name, tried=tried)
def from_string(self, template_code):
"""
Returns a compiled Template object for the given template code,
handling template inheritance recursively.
"""
return Template(template_code, engine=self)
def get_template(self, template_name, dirs=_dirs_undefined):
"""
Returns a compiled Template object for the given template name,
handling template inheritance recursively.
"""
if dirs is _dirs_undefined:
dirs = None
else:
warnings.warn(
"The dirs argument of get_template is deprecated.",
RemovedInDjango110Warning, stacklevel=2)
template, origin = self.find_template(template_name, dirs)
if not hasattr(template, 'render'):
# template needs to be compiled
template = Template(template, origin, template_name, engine=self)
return template
# This method was originally a function defined in django.template.loader.
# It was moved here in Django 1.8 when encapsulating the Django template
# engine in this Engine class. It's still called by deprecated code but it
# will be removed in Django 1.10. It's superseded by a new render_to_string
# function in django.template.loader.
def render_to_string(self, template_name, context=None,
context_instance=_context_instance_undefined,
dirs=_dirs_undefined,
dictionary=_dictionary_undefined):
if context_instance is _context_instance_undefined:
context_instance = None
else:
warnings.warn(
"The context_instance argument of render_to_string is "
"deprecated.", RemovedInDjango110Warning, stacklevel=2)
if dirs is _dirs_undefined:
# Do not set dirs to None here to avoid triggering the deprecation
# warning in select_template or get_template.
pass
else:
warnings.warn(
"The dirs argument of render_to_string is deprecated.",
RemovedInDjango110Warning, stacklevel=2)
if dictionary is _dictionary_undefined:
dictionary = None
else:
warnings.warn(
"The dictionary argument of render_to_string was renamed to "
"context.", RemovedInDjango110Warning, stacklevel=2)
context = dictionary
if isinstance(template_name, (list, tuple)):
t = self.select_template(template_name, dirs)
else:
t = self.get_template(template_name, dirs)
if not context_instance:
# Django < 1.8 accepted a Context in `context` even though that's
# unintended. Preserve this ability but don't rewrap `context`.
if isinstance(context, Context):
return t.render(context)
else:
return t.render(Context(context))
if not context:
return t.render(context_instance)
# Add the context to the context stack, ensuring it gets removed again
# to keep the context_instance in the same state it started in.
with context_instance.push(context):
return t.render(context_instance)
def select_template(self, template_name_list, dirs=_dirs_undefined):
"""
Given a list of template names, returns the first that can be loaded.
"""
if dirs is _dirs_undefined:
# Do not set dirs to None here to avoid triggering the deprecation
# warning in get_template.
pass
else:
warnings.warn(
"The dirs argument of select_template is deprecated.",
RemovedInDjango110Warning, stacklevel=2)
if not template_name_list:
raise TemplateDoesNotExist("No template names provided")
not_found = []
for template_name in template_name_list:
try:
return self.get_template(template_name, dirs)
except TemplateDoesNotExist as exc:
if exc.args[0] not in not_found:
not_found.append(exc.args[0])
continue
# If we get here, none of the templates could be loaded
raise TemplateDoesNotExist(', '.join(not_found))
|
oblalex/django-workflow
|
refs/heads/master
|
src/workflow/admin.py
|
1
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import logging
import datetime
from functools import partial
from django import template
from django import forms
from django.db import models, transaction, router
from django.conf import settings
from django.conf.urls import patterns, url
from django.contrib import admin
from django.contrib.admin import helpers, options
from django.contrib.admin.util import unquote, quote, get_deleted_objects
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericInlineModelAdmin, GenericRelation
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.forms.formsets import all_valid
from django.forms.models import model_to_dict
from django.http import HttpResponseRedirect, HttpResponseNotFound, Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.encoding import force_unicode, force_text
from django.utils.html import mark_safe, escape
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_protect
from workflow.models import Version
from workflow.constants import (
VERSION_STATUS_NEED_ATTENTION, VERSION_STATUS_APPROVED, VERSION_STATUS_REJECTED, VERSION_STATUS_DRAFT,
VERSION_TYPE_ADD, VERSION_TYPE_CHANGE, VERSION_TYPE_DELETE, VERSION_TYPE_RECOVER,
VERSION_BRANCHES_MAX_COUNT)
from workflow.diff import changes_between_models, comment_from_changes
from workflow.security import is_user_content_admin, is_user_content_manager
from workflow.revisions import default_revision_manager, RegistrationError
from workflow.urls import (
version_edit_url, version_view_changes_url, version_history_url, version_approve_url, version_reject_url)
csrf_protect_m = method_decorator(csrf_protect)
LOG = logging.getLogger(__name__)
STATIC_URL = getattr(settings, 'STATIC_URL', settings.MEDIA_URL)
class WorkflowAdmin(admin.ModelAdmin):
# The revision manager instance used to manage revisions.
revision_manager = default_revision_manager
# The serialization format to use when registering models with reversion.
reversion_format = 'json'
# Whether to ignore duplicate revision data.
ignore_duplicate_revisions = False
change_list_template = 'workflow/change_list.html'
change_form_template = 'workflow/change_form.html'
object_history_template = 'workflow/object_history.html'
version_edit_form_template = 'workflow/version_edit_form.html'
view_changes_form_template = 'workflow/view_changes_form.html'
recoverlist_template = 'workflow/recover_list.html'
class Media:
css = {
'all': (STATIC_URL + 'workflow/css/workflow_admin.css', )
}
def _autoregister(self, model, follow=None):
"""Registers a model with reversion, if required."""
if model._meta.proxy:
raise RegistrationError("Proxy models cannot be used with django-reversion, register the parent class instead")
if not self.revision_manager.is_registered(model):
follow = follow or []
for parent_cls, field in model._meta.parents.items():
follow.append(field.name)
self._autoregister(parent_cls)
self.revision_manager.register(model, follow=follow, format=self.reversion_format)
@property
def revision_context_manager(self):
"""The revision context manager for this WorkflowAdmin."""
return self.revision_manager._revision_context_manager
def __init__(self, model, admin_site):
super(WorkflowAdmin, self).__init__(model, admin_site)
self.content_type = ContentType.objects.get_for_model(model)
# Automatically register models if required.
if not self.revision_manager.is_registered(self.model):
inline_fields = []
for inline in self.inlines:
inline_model = inline.model
if issubclass(inline, GenericInlineModelAdmin):
ct_field = inline.ct_field
ct_fk_field = inline.ct_fk_field
for field in self.model._meta.many_to_many:
if (isinstance(field, GenericRelation)
and field.rel.to == inline_model
and field.object_id_field_name == ct_fk_field
and field.content_type_field_name == ct_field):
inline_fields.append(field.name)
self._autoregister(inline_model)
elif issubclass(inline, options.InlineModelAdmin):
fk_name = inline.fk_name
if not fk_name:
for field in inline_model._meta.fields:
if (isinstance(field, (models.ForeignKey, models.OneToOneField))
and issubclass(self.model, field.rel.to)):
fk_name = field.name
self._autoregister(inline_model, follow=[fk_name])
if not inline_model._meta.get_field(fk_name).rel.is_hidden():
accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name()
inline_fields.append(accessor)
self._autoregister(self.model, inline_fields)
# Wrap own methods in manual revision management.
self.add_view = self.revision_context_manager.create_revision(manage_manually=True)(self.add_view)
self.change_view = self.revision_context_manager.create_revision(manage_manually=True)(self.change_view)
self.delete_view = self.revision_context_manager.create_revision(manage_manually=True)(self.delete_view)
self.recover_view = self.revision_context_manager.create_revision(manage_manually=True)(self.recover_view)
self.revision_view = self.revision_context_manager.create_revision(manage_manually=True)(self.version_edit_view)
self.changelist_view = self.revision_context_manager.create_revision(manage_manually=True)(self.changelist_view)
def get_revision_instances(self, request, object):
"""Returns all the instances to be used in the object's revision."""
return [object]
def get_revision_data(self, request, object, flag):
"""Returns all the revision data to be used in the object's revision."""
return dict(
(o, self.revision_manager.get_adapter(o.__class__).get_version_data(o, flag))
for o in self.get_revision_instances(request, object))
def get_revision_form_data(self, request, obj, version):
"""
Returns a dictionary of data to set in the admin form in order to revert
to the given revision.
"""
return version.field_dict
def get_related_versions(self, obj, version, FormSet):
"""Retreives all the related Version objects for the given FormSet."""
object_id = obj.pk
# Get the fk name.
try:
fk_name = FormSet.fk.name
except AttributeError:
# This is a GenericInlineFormset, or similar.
fk_name = FormSet.ct_fk_field.name
# Look up the revision data.
revision_versions = version.revision.version_set.all()
related_versions = dict([(related_version.object_id, related_version)
for related_version in revision_versions
if ContentType.objects.get_for_id(related_version.content_type_id).model_class() == FormSet.model
and force_text(related_version.field_dict[fk_name]) == force_text(object_id)])
return related_versions
def _hack_inline_formset_initial(self, FormSet, formset, obj, version):
"""Hacks the given formset to contain the correct initial data."""
# if the FK this inline formset represents is not being followed, don't process data for it.
# see https://github.com/etianen/django-reversion/issues/222
if formset.rel_name not in self.revision_manager.get_adapter(self.model).follow:
return
# Now we hack it to push in the data from the revision!
initial = []
related_versions = self.get_related_versions(obj, version, FormSet)
formset.related_versions = related_versions
for related_version in related_versions.values():
initial_row = related_version.field_dict
pk_name = ContentType.objects.get_for_id(related_version.content_type_id).model_class()._meta.pk.name
del initial_row[pk_name]
initial.append(initial_row)
for form in formset.forms:
related_obj = form.save(commit=False)
if related_obj.id == None:
initial_data = model_to_dict(related_obj)
pk_name = related_obj._meta.pk.name
del initial_data[pk_name]
if initial_data not in initial:
initial.append(initial_data)
# Reconstruct the forms with the new revision data.
formset.initial = initial
formset.forms = [formset._construct_form(n) for n in range(len(initial))]
# Hack the formset to force a save of everything.
def get_changed_data(form):
return [field.name for field in form.fields]
for form in formset.forms:
form.has_changed = lambda: True
form._get_changed_data = partial(get_changed_data, form=form)
def total_form_count_hack(count):
return lambda: count
formset.total_form_count = total_form_count_hack(len(initial))
@csrf_protect_m
@transaction.commit_on_success
def add_view(self, request, form_url='', extra_context=None):
extra_context = extra_context or {}
# TODO: call content filler to set data about reversion
extra_context['can_be_branched'] = False
self.put_content_permissions(request, extra_context)
return super(WorkflowAdmin, self).add_view(
request, form_url, extra_context=extra_context)
@csrf_protect_m
@transaction.commit_on_success
def change_view(self, request, object_id, form_url='', extra_context=None):
"The 'change' admin view for this model."
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url=reverse('admin:%s_%s_add' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
ModelForm = self.get_form(request, obj)
formsets = []
inline_instances = self.get_inline_instances(request)
version = Version.objects.latest_approved(self.content_type, object_id)
if not version:
version = self.create_initial_version(request, obj)
messages.success(request, _("Initial object version created."))
if request.method == 'POST':
obj_copy = copy.deepcopy(obj)
form = ModelForm(request.POST, request.FILES, instance=obj_copy)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
return self.process_common_post(
request, new_object, request.user, version.revision, form, formsets)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, obj), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
self.get_prepopulated_fields(request, obj),
self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
prepopulated = dict(inline.get_prepopulated_fields(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': "_popup" in request.REQUEST,
'media': media,
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
self.put_can_be_branched(request, object_id, context)
self.put_content_permissions(request, context)
context.update(extra_context or {})
return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
"""Renders the changelist view."""
opts = self.model._meta
context = {
'recoverlist_url': reverse("%s:%s_%s_recoverlist" % (
self.admin_site.name, opts.app_label, opts.module_name)),
'add_url': reverse("%s:%s_%s_add" % (
self.admin_site.name, opts.app_label, opts.module_name)),}
context.update(extra_context or {})
return super(WorkflowAdmin, self).changelist_view(request, context)
def recoverlist_view(self, request, extra_context=None):
"""Displays a list of deleted models to allow recovery."""
# check if user has change or add permissions for model
if not is_user_content_admin(request.user):
raise PermissionDenied
model = self.model
opts = model._meta
deleted = Version.objects.get_deleted(self.content_type)
context = {
'opts': opts,
'app_label': opts.app_label,
'module_name': capfirst(opts.verbose_name),
'title': _("Deleted %(name)s") % {'name': force_text(opts.verbose_name_plural)},
'deleted': deleted,
'changelist_url': reverse("%s:%s_%s_changelist" % (
self.admin_site.name, opts.app_label, opts.module_name)),
}
extra_context = extra_context or {}
context.update(extra_context)
return render_to_response(
self.recoverlist_template, context, template.RequestContext(request))
@transaction.commit_on_success
def recover_view(self, request, version_id, extra_context=None):
"""Displays a form that can recover a deleted model."""
# check if user has change or add permissions for model
if not self.has_change_permission(request) and not self.has_add_permission(request):
raise PermissionDenied
version = get_object_or_404(Version, pk=version_id)
obj = version.object_version.object
context = {
'title': _("Recovering %(name)s") % {'name': version.object_repr},
}
context.update(extra_context or {})
return self.render_version_form(
request, version, self.version_edit_form_template, context, recovering=True)
def history_view(self, request, object_id, extra_context=None):
object_id = unquote(object_id)
opts = self.model._meta
latest_approved_id = Version.objects.latest_approved(self.content_type, object_id).id
action_list = [
{
'revision': version.revision,
'edit_url': version_edit_url(version.object_id, version.id, self.admin_site.name, opts),
'view_url': version_view_changes_url(version.object_id, version.id, self.admin_site.name, opts),
'approve_url': version_approve_url(version.object_id, version.id, self.admin_site.name, opts),
'reject_url': version_reject_url(version.object_id, version.id, self.admin_site.name, opts),
'recover_url': reverse('%s:%s_%s_recover' % (
self.admin_site.name, opts.app_label, opts.module_name
), args=[version.id]),
'is_current': version.id == latest_approved_id,
'children_pks': version.revision.children.all().values_list('id', flat=True),
'pending': version.revision.status == VERSION_STATUS_NEED_ATTENTION,
}
for version in Version.objects.filter(
object_id=object_id,
content_type=self.content_type
).select_related('revision', 'revision__changed_by', 'revision__moderated_by')
]
context = {
'action_list': action_list
, 'is_admin': is_user_content_admin(request.user)
}
context.update(extra_context or {})
return super(WorkflowAdmin, self).history_view(request, object_id, context)
def render_version_form(self, request, version, form_template, extra_context, editing=False, recovering=False):
obj = version.object_version.object
object_id = obj.pk
if (version.revision.deleted and version.revision.children.exists()):
return HttpResponseNotFound(
_(u"<p>Deleted object \"%s\" is already recovered. You cannot recover it again.</p>") % version)
latest_approved = Version.objects.latest_approved(self.content_type, object_id)
if (latest_approved.revision.deleted and not recovering):
return HttpResponseNotFound(_(u"<p>You cannot view versions of deleted object.</p>"))
model = self.model
opts = model._meta
v_opts = Version._meta
ModelForm = self.get_form(request, obj)
formsets = []
is_approved = version.revision.status == VERSION_STATUS_APPROVED
is_rejected = version.revision.status == VERSION_STATUS_REJECTED
is_pending = version.revision.status == VERSION_STATUS_NEED_ATTENTION
if request.method == 'POST':
obj_copy = copy.deepcopy(obj)
# This section is copied directly from the model admin change view
# method. Maybe one day there will be a hook for doing this better.
form = ModelForm(request.POST, request.FILES, instance=obj_copy, initial=self.get_revision_form_data(request, obj_copy, version))
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
# HACK: If the value of a file field is None, remove the file from the model.
for field in new_object._meta.fields:
if isinstance(field, models.FileField) and field.name in form.cleaned_data and form.cleaned_data[field.name] is None:
setattr(new_object, field.name, None)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object),
self.get_inline_instances(request)):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
self._hack_inline_formset_initial(FormSet, formset, obj, version)
# Add this hacked formset to the form.
formsets.append(formset)
if all_valid(formsets) and form_validated:
return self.process_common_post(
request, new_object, request.user, version.revision, form, formsets)
else:
# This is a mutated version of the code in the standard model admin
# change_view. Once again, a hook for this kind of functionality
# would be nice. Unfortunately, it results in doubling the number
# of queries required to construct the formets.
form = ModelForm(instance=obj, initial=self.get_revision_form_data(request, obj, version))
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, obj), self.get_inline_instances(request)):
# This code is standard for creating the formset.
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
self._hack_inline_formset_initial(FormSet, formset, obj, version)
# Add this hacked formset to the form.
formsets.append(formset)
# Generate admin form helper.
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
self.prepopulated_fields, self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
# Generate formset helpers.
inline_admin_formsets = []
for inline, formset in zip(self.get_inline_instances(request), formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
prepopulated = inline.get_prepopulated_fields(request, obj)
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
if not recovering:
if is_approved:
messages.success(request, _("Current object was approved by admin."))
elif is_rejected:
messages.error(request, _("Current object was rejected by admin."))
elif is_pending:
messages.warning(request, _("Current object is waiting for admin approvement."))
if version.revision.get_siblings().exclude(deleted=True).count() and (version.revision.parent is not None):
messages.warning(request, _("Current object has an alternative version."))
# Generate the context.
context = {
'title': _("Edit %(name)s") % {'name': obj},
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': False,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
'add': False,
'change': True,
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
'has_delete_permission': self.has_delete_permission(request, obj),
'has_file_field': True,
'has_absolute_url': False,
'ordered_objects': opts.get_ordered_objects(),
'form_url': mark_safe(request.path),
'opts': opts,
'content_type_id': self.content_type.id,
'save_as': False,
'save_on_top': self.save_on_top,
'changelist_url': reverse("%s:%s_%s_changelist" % (
self.admin_site.name, opts.app_label, opts.module_name)),
'change_url': reverse("%s:%s_%s_change" % (
self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk),)),
'changes_url': version_view_changes_url(obj.pk, version.pk, self.admin_site.name, opts),
'edit_url': version_edit_url(obj.pk, version.pk, self.admin_site.name, opts),
'parent_url': version_edit_url(
obj.pk, version.revision.parent.version(obj.pk, self.content_type).pk, self.admin_site.name, opts
) if version.revision.parent else None,
'history_url': version_history_url(obj.pk, self.admin_site.name, opts),
'delete_url': reverse("%s:%s_%s_delete" % (
self.admin_site.name, v_opts.app_label, v_opts.module_name), args=(quote(version.pk),)),
'working_with_version': True,
'has_children': version.revision.children.exists(),
'is_recovering': recovering,
'is_approved': is_approved,
'is_rejected': is_rejected,
'is_pending': is_pending,
'moderator_old_comment': version.revision.comment,
}
context.update(extra_context or {})
self.put_can_be_branched(request, object_id, context, version)
self.put_content_permissions(request, context)
return render_to_response(form_template, context, template.RequestContext(request))
@csrf_protect_m
@transaction.commit_on_success
def version_edit_view(self, request, object_id, version_id, extra_context=None):
version = get_object_or_404(Version, pk=version_id)
context = {
'title': _("Edit version of %(name)s") % {'name': version.object_repr},
}
context.update(extra_context or {})
return self.render_version_form(
request, version, self.version_edit_form_template, context, editing=True)
@csrf_protect_m
@transaction.commit_on_success
def version_changes_view(self, request, object_id, version_id, extra_context=None):
version = get_object_or_404(Version, pk=version_id)
parent = version.revision.parent
if parent is not None and not parent.deleted:
new_object = version.object_version.object
old_object = parent.version(new_object.id, self.content_type).object_version.object
changes = changes_between_models(
old_object, new_object).values()
else:
changes = {}
context = {
'title': _("Viewing changes of %(name)s") % {'name': version.object_repr},
'change_status_only': True,
'changes': changes,
}
context.update(extra_context or {})
return self.render_version_form(request, version, self.view_changes_form_template, context)
def version_status_change_view(self, request, object_id, version_id, status, extra_context=None):
revision = get_object_or_404(Version, pk=version_id).revision
latest_approved_revision = Version.objects.latest_approved(self.content_type, object_id).revision
if (revision.status == VERSION_STATUS_NEED_ATTENTION):
revision.status = status
revision.update_moderation(request.user)
revision.save()
if status == VERSION_STATUS_APPROVED:
revision.revert(latest_approved_revision)
return HttpResponseRedirect(version_history_url(object_id, self.admin_site.name, self.model._meta))
@transaction.commit_on_success
def version_status_approve_view(self, request, object_id, version_id, extra_context=None):
return self.version_status_change_view(request, object_id, version_id, VERSION_STATUS_APPROVED, extra_context)
@transaction.commit_on_success
def version_status_reject_view(self, request, object_id, version_id, extra_context=None):
return self.version_status_change_view(request, object_id, version_id, VERSION_STATUS_REJECTED, extra_context)
def put_content_permissions(self, request, context):
current_user = request.user
context['has_content_manager_permission'] = is_user_content_manager(current_user)
context['has_content_admin_permission'] = is_user_content_admin(current_user)
def put_can_be_branched(self, request, object_id, context, version=None):
has_children, can_be_branched = Version.objects.children_info(
object_id=object_id,
content_type=self.content_type,
version=version)
if has_children:
if can_be_branched:
messages.warning(
request,
_("Current object has more fresh versions in history."))
else:
messages.error(
request,
_("Current object already has {max_count} unapproved versions"
" and cannot be changed."
).format(max_count=VERSION_BRANCHES_MAX_COUNT))
context['can_be_branched'] = can_be_branched
def create_initial_version(self, request, object):
return self.revision_manager.save_revision(
self.get_revision_data(request, object, VERSION_TYPE_ADD),
user = request.user,
comment = _(u"Initial version."),
status = VERSION_STATUS_APPROVED,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db()
).version(object.pk, self.content_type)
def log_addition(self, request, object):
"""Sets the version meta information."""
super(WorkflowAdmin, self).log_addition(request, object)
self.create_initial_version(request, object);
def delete_model(self, request, obj):
"""
Given a model instance delete it from the database.
"""
self.revision_manager.save_revision(
self.get_revision_data(request, obj, VERSION_TYPE_DELETE),
parent = Version.objects.latest_approved(self.content_type, obj.pk).revision,
user = request.user,
comment = _(u"Object is deleted."),
delete = True,
status = VERSION_STATUS_APPROVED,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db(),
)
obj.delete()
def process_common_post(self, request, obj, moderator, revision, form, formsets):
latest_approved_revision = Version.objects.latest_approved(self.content_type, obj.pk).revision
comment = request.POST.get("moderator_new_comment", "")
changes = False
if formsets:
for formset in formsets:
changes = (hasattr(formset, 'new_objects')
or hasattr(formset, 'changed_objects')
or hasattr(formset, 'deleted_objects'))
if changes:
break
changes = changes or form.has_changed()
status_changed = False
if request.POST.has_key("_reject"):
status_changed = True
revision.status = VERSION_STATUS_REJECTED
if comment:
revision.comment = comment
if request.POST.has_key("_approve"):
status_changed = True
if changes:
if revision.status == VERSION_STATUS_NEED_ATTENTION:
# TODO: can be branged?
revision.status = VERSION_STATUS_DRAFT
revision.update_moderation(moderator)
revision.save()
self.save_with_relations(request, obj, form, formsets)
revision = self.revision_manager.save_revision(
self.get_revision_data(request, obj, VERSION_TYPE_CHANGE),
parent = revision,
user = moderator,
comment = comment,
status = VERSION_STATUS_APPROVED,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db(),)
else:
revision.status = VERSION_STATUS_APPROVED
revision.revert(latest_approved_revision)
if status_changed:
revision.update_moderation(moderator)
revision.save()
return HttpResponseRedirect(
version_history_url(obj.id, self.admin_site.name, self.model._meta))
if request.POST.has_key('_recover'):
self.save_with_relations(request, obj, form, formsets)
revision = self.revision_manager.save_revision(
self.get_revision_data(request, obj, VERSION_TYPE_RECOVER),
parent = revision,
user = moderator,
comment = _(u"Deleted object was recovered."),
status = VERSION_STATUS_APPROVED,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db(),
)
return HttpResponseRedirect(
version_edit_url(
obj.id, revision.version(obj.id, self.content_type).pk, self.admin_site.name, self.model._meta))
if request.POST.has_key('_toapprove'):
if changes or revision.status == VERSION_STATUS_REJECTED:
self.save_with_relations(request, obj, form, formsets)
revision_parent = revision
revision = self.revision_manager.save_revision(
self.get_revision_data(request, obj, VERSION_TYPE_CHANGE),
user = request.user,
comment = comment,
parent = revision_parent,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db(),
)
if (revision_parent.status == VERSION_STATUS_NEED_ATTENTION):
revision_parent.status = VERSION_STATUS_DRAFT
revision_parent.save()
latest_approved_revision.revert(revision)
if revision.status != VERSION_STATUS_APPROVED:
revision.status = VERSION_STATUS_NEED_ATTENTION
revision.save()
return HttpResponseRedirect(
version_edit_url(obj.id, revision.version(obj.id, self.content_type).pk, self.admin_site.name, self.model._meta))
if request.POST.has_key('_tohistory'):
if changes:
self.save_with_relations(request, obj, form, formsets)
revision = self.revision_manager.save_revision(
self.get_revision_data(request, obj, VERSION_TYPE_CHANGE),
user = request.user,
comment = comment,
parent = revision,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db(),
)
latest_approved_revision.revert(revision)
return HttpResponseRedirect(
version_edit_url(
obj.id, revision.version(obj.id, self.content_type).pk, self.admin_site.name, self.model._meta))
else:
return HttpResponseRedirect(".")
if any(i in request.POST.keys() for i in ["_addanother", "_continue", "_save"]):
auto_approve = is_user_content_admin(moderator)
# TODO: improve changes detection for inlines and save only if changes were done
self.save_with_relations(request, obj, form, formsets)
if changes:
# self.save_with_relations(request, obj, form, formsets)
revision = self.revision_manager.save_revision(
self.get_revision_data(request, obj, VERSION_TYPE_CHANGE),
user = request.user,
comment = comment,
parent = revision,
status = VERSION_STATUS_APPROVED if auto_approve else VERSION_STATUS_DRAFT,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db(),
)
if not auto_approve:
latest_approved_revision.revert(revision)
return HttpResponseRedirect(reverse('admin:%s_%s_change' %
(obj._meta.app_label, obj._meta.module_name),
args=(obj.id,),
current_app=self.admin_site.name))
elif auto_approve:
# TODO: improve changes detection for inlines and use this instead of current elif statement:
# elif auto_approve and (revision.children.exists() or revision.status == VERSION_STATUS_REJECTED):
revision = self.revision_manager.save_revision(
self.get_revision_data(request, obj, VERSION_TYPE_CHANGE),
user = request.user,
comment = comment,
parent = revision,
status = VERSION_STATUS_APPROVED,
ignore_duplicates = self.ignore_duplicate_revisions,
db = self.revision_context_manager.get_db(),
)
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (
obj._meta.app_label, obj._meta.module_name),
args=(obj.id,),
current_app=self.admin_site.name))
return HttpResponseRedirect(".")
def save_with_relations(self, request, obj, form, formsets):
self.save_model(request, obj, form, change=True)
form.save_m2m()
for formset in formsets:
# HACK: If the value of a file field is None, remove the file from the model.
related_objects = formset.save(commit=False)
for related_obj, related_form in zip(related_objects, formset.saved_forms):
for field in related_obj._meta.fields:
if (isinstance(field, models.FileField)
and field.name in related_form.cleaned_data
and related_form.cleaned_data[field.name] is None):
setattr(related_obj, field.name, None)
related_obj.save()
formset.save_m2m()
def get_urls(self):
"""Returns the additional urls used by the workflow admin."""
urls = super(WorkflowAdmin, self).get_urls()
admin_site = self.admin_site
opts = self.model._meta
info = opts.app_label, opts.module_name,
reversion_urls = patterns("",
url("^([^/]+)/edit/([^/]+)/$", admin_site.admin_view(self.version_edit_view),
name='%s_%s_edit' % info),
url("^([^/]+)/changes/([^/]+)/$", admin_site.admin_view(self.version_changes_view),
name='%s_%s_changes' % info),
url("^([^/]+)/approve/([^/]+)/$", admin_site.admin_view(self.version_status_approve_view),
name='%s_%s_approve' % info),
url("^([^/]+)/reject/([^/]+)/$", admin_site.admin_view(self.version_status_reject_view),
name='%s_%s_reject' % info),
url("^recover/([^/]+)/$", admin_site.admin_view(self.recover_view),
name='%s_%s_recover' % info),
url("^recover/$", admin_site.admin_view(self.recoverlist_view),
name='%s_%s_recoverlist' % info),
)
return reversion_urls + urls
class VersionAdmin(admin.ModelAdmin):
changelist_view_template = "workflow/version_change_list.html"
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
action_list = []
for version in Version.objects.filter(
revision__status=VERSION_STATUS_NEED_ATTENTION,
).select_related('revision', 'revision__created_by'):
url_params = (version.object_id, version.id, self.admin_site.name, version.object_version.object._meta)
try:
action_list.append({
'version': version,
'edit_url': version_edit_url(*url_params),
'view_url': version_view_changes_url(*url_params),
'approve_url': version_approve_url(*url_params),
'reject_url': version_reject_url(*url_params),
})
except:
pass
context = {
'title': force_unicode(self.model._meta.verbose_name_plural),
'action_list': action_list,
}
context.update(extra_context or {})
return render_to_response(
self.changelist_view_template, context, template.RequestContext(request))
@csrf_protect_m
@transaction.commit_on_success
def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
opts = self.model._meta
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if not self.has_delete_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(deleted_objects, perms_needed, protected) = get_deleted_objects(
[obj], opts, request.user, self.admin_site, using)
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
raw_obj = obj.object_version.object
obj_display = force_unicode(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.')
% {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect(reverse('admin:index',
current_app=self.admin_site.name))
return HttpResponseRedirect(
version_history_url(raw_obj.id, self.admin_site.name, raw_obj._meta))
object_name = force_unicode(opts.verbose_name)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
title = _("Are you sure?")
context = {
"title": title,
"object_name": object_name,
"object": obj,
"deleted_objects": deleted_objects,
"perms_lacking": perms_needed,
"protected": protected,
"opts": opts,
"app_label": app_label,
}
context.update(extra_context or {})
return TemplateResponse(request, self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
"admin/delete_confirmation.html"
], context, current_app=self.admin_site.name)
def delete_model(self, request, obj):
revision = obj.revision
for version in revision.version_set.all():
version.delete()
revision.delete()
admin.site.register(Version, VersionAdmin)
|
DmZ/ajenti
|
refs/heads/dev
|
plugins/power/main.py
|
1
|
from ajenti.ui import *
from ajenti import version
from ajenti.com import implements
from ajenti.api import *
from ajenti.utils import shell
from backend import *
class PowerPlugin(CategoryPlugin):
text = 'Power'
icon = '/dl/power/icon.png'
folder = 'hardware'
def get_ui(self):
ui = self.app.inflate('power:main')
els = ui.find('list')
for ac in get_ac_adapters():
img = 'present' if ac.present else 'none'
st = 'Active' if ac.present else 'Offline'
els.append(UI.ElementBox(UI.HContainer(
UI.Image(file='/dl/power/ac-%s.png'%img),
UI.VContainer(
UI.Label(text='AC Adapter %s' % ac.name, size=2),
UI.Label(text=st)
)
)))
for bat in get_batteries():
if bat.present:
img = str(int((bat.charge+19)/20)*20)
else:
img = '0'
st = 'Active' if bat.present else 'Offline'
if bat.present:
st += ' - %i%%' % bat.charge
els.append(UI.ElementBox(UI.HContainer(
UI.Image(file='/dl/power/battery-%s.png'%img),
UI.VContainer(
UI.Label(text='Battery %s' % bat.name, size=2),
UI.Label(text=st)
)
)))
return ui
@event('button/click')
def on_aclick(self, event, params, vars=None):
if params[0] == 'shutdown':
shell('shuwdown -p now')
if params[0] == 'reboot':
shell('reboot')
|
Johnzero/OE7
|
refs/heads/master
|
openerp/addons-fg/fg_sale/__openerp__.py
|
1
|
# -*- encoding: utf-8 -*-
{
'name': '富光销售模块',
'version': '2.0',
'category' : '富光',
'description': """销售模块""",
'author': '杨振宇',
'website': 'http://www.fuguang.cn',
'depends': ['base', 'board', 'product', 'fg_base'],
'init_xml': [],
'update_xml': [
'fg_sale_data.xml',
'security/group.xml',
'security/ir.model.access.csv',
'fg_sale_view.xml',
],
'demo_xml': [],
'installable': True,
'active': False,
'application':True,
}
|
sunny94/temp
|
refs/heads/iss8501_parsing
|
sympy/printing/gtk.py
|
117
|
from __future__ import print_function, division
from sympy.printing.mathml import mathml
import tempfile
import os
def print_gtk(x, start_viewer=True):
"""Print to Gtkmathview, a gtk widget capable of rendering MathML.
Needs libgtkmathview-bin"""
from sympy.utilities.mathml import c2p
tmp = tempfile.mktemp() # create a temp file to store the result
with open(tmp, 'wb') as file:
file.write( c2p(mathml(x), simple=True) )
if start_viewer:
os.system("mathmlviewer " + tmp)
|
M4rtinK/modrana
|
refs/heads/master
|
tests/voice_tests.py
|
1
|
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Osmo Salomaa
#
# 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/>.
import os
import tempfile
import time
import unittest
from core import voice
from core import threads
threads.initThreading()
class TestVoiceGenerator(unittest.TestCase):
def setUp(self):
self.generator = voice.VoiceGenerator()
def _test_an_engine(self, engine):
"""Test individual voice engines."""
if not engine.supports("en"):
return
handle, fname = tempfile.mkstemp(dir=self.generator._tmpdir)
engine("en").make_wav("just testing", fname)
self.assertTrue(os.path.isfile(fname))
self.assertTrue(os.path.getsize(fname) > 256)
@unittest.skipUnless(voice.VoiceEngineMimic.available(), "Mimic not installed")
def mimic_test(self):
"""Test using the Mimic TTS engine"""
self._test_an_engine(engine=voice.VoiceEngineMimic)
@unittest.skipUnless(voice.VoiceEngineFlite.available(), "Flite not installed")
def flite_test(self):
"""Test using the Flite TTS engine"""
self._test_an_engine(engine=voice.VoiceEngineFlite)
@unittest.skipUnless(voice.VoiceEnginePicoTTS.available(), "PicoTTS not installed")
def picotts_test(self):
"""Test using the PicoTTS engine"""
self._test_an_engine(engine=voice.VoiceEnginePicoTTS)
@unittest.skipUnless(voice.VoiceEngineEspeak.available(), "Espeak not installed")
def espeak_test(self):
"""Test using the Espeak TTS engine"""
self._test_an_engine(engine=voice.VoiceEngineEspeak)
def clean_test(self):
"""Test voice generator cleanup"""
self.generator.set_voice("en")
self.generator.make("just testing")
# this is a little dirty but rather join the
# task queue rather than to introduce an arbitrary
# waiting for the worker thread to finish
self.generator._task_queue.join()
self.generator.clean()
self.assertFalse(os.listdir(self.generator._tmpdir))
def get_test(self):
"""Test getting a voice sample"""
self.generator.set_voice("en")
if not self.generator.active: return
self.generator.make("just testing")
# this is a little dirty but rather join the
# task queue rather than to introduce an arbitrary
# waiting for the worker thread to finish
self.generator._task_queue.join()
fname = self.generator.get("just testing")
self.assertTrue(os.path.isfile(fname))
self.assertTrue(os.path.getsize(fname) > 256)
def make_test(self):
"""Test voice sample creation"""
self.generator.set_voice("en")
self.generator.make("just testing")
# this is a little dirty but rather join the
# task queue rather than to introduce an arbitrary
# waiting for the worker thread to finish
self.generator._task_queue.join()
def quit_test(self):
"""Check voice generator shutdown"""
self.generator.set_voice("en")
self.generator.make("just testing")
# this is a little dirty but rather join the
# task queue rather than to introduce an arbitrary
# waiting for the worker thread to finish
self.generator._task_queue.join()
self.generator.quit()
self.assertFalse(os.path.isdir(self.generator._tmpdir))
def set_voice_test(self):
"""Check setting voice"""
self.generator.set_voice("en")
self.generator.set_voice("en", "male")
self.generator.set_voice("en", "female")
self.generator.set_voice("en_US")
self.generator.set_voice("en_XX")
|
asermax/livestreamer
|
refs/heads/master
|
src/livestreamer/plugins/livestream.py
|
4
|
import re
from collections import defaultdict
from livestreamer.compat import urljoin
from livestreamer.exceptions import PluginError, NoStreamsError
from livestreamer.plugin import Plugin
from livestreamer.stream import AkamaiHDStream, HLSStream
from livestreamer.utils import urlget, verifyjson, res_xml, parse_json
SWF_URL = "http://cdn.livestream.com/swf/hdplayer-2.0.swf"
class Livestream(Plugin):
@classmethod
def default_stream_types(cls, streams):
return ["akamaihd", "hls"]
@classmethod
def can_handle_url(self, url):
return "new.livestream.com" in url
def _get_stream_info(self):
res = urlget(self.url)
match = re.search("window.config = ({.+})", res.text)
if match:
config = match.group(1)
return parse_json(config, "config JSON")
def _parse_smil(self, url, swfurl):
res = urlget(url)
smil = res_xml(res, "SMIL config")
streams = {}
httpbase = smil.find("{http://www.w3.org/2001/SMIL20/Language}head/"
"{http://www.w3.org/2001/SMIL20/Language}meta[@name='httpBase']")
if not (httpbase is not None and httpbase.attrib.get("content")):
raise PluginError("Missing HTTP base in SMIL")
httpbase = httpbase.attrib.get("content")
videos = smil.findall("{http://www.w3.org/2001/SMIL20/Language}body/"
"{http://www.w3.org/2001/SMIL20/Language}switch/"
"{http://www.w3.org/2001/SMIL20/Language}video")
for video in videos:
url = urljoin(httpbase, video.attrib.get("src"))
bitrate = int(video.attrib.get("system-bitrate"))
streams[bitrate] = AkamaiHDStream(self.session, url,
swf=swfurl)
return streams
def _get_streams(self):
self.logger.debug("Fetching stream info")
info = self._get_stream_info()
if not info:
raise NoStreamsError(self.url)
event = verifyjson(info, "event")
streaminfo = verifyjson(event, "stream_info")
if not streaminfo or not streaminfo.get("is_live"):
raise NoStreamsError(self.url)
streams = defaultdict(list)
play_url = streaminfo.get("play_url")
if play_url:
swfurl = info.get("hdPlayerSwfUrl") or SWF_URL
if not swfurl.startswith("http://"):
swfurl = "http://" + swfurl
qualities = streaminfo.get("qualities", [])
smil = self._parse_smil(streaminfo["play_url"], swfurl)
for bitrate, stream in smil.items():
name = "{0}k".format(bitrate/1000)
for quality in qualities:
if quality["bitrate"] == bitrate:
name = "{0}p".format(quality["height"])
streams[name].append(stream)
m3u8_url = streaminfo.get("m3u8_url")
if m3u8_url:
hls_streams = HLSStream.parse_variant_playlist(self.session,
m3u8_url,
namekey="pixels")
for name, stream in hls_streams.items():
streams[name].append(stream)
return streams
__plugin__ = Livestream
|
dbeyer/benchexec
|
refs/heads/master
|
benchexec/tablegenerator/test_util.py
|
3
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
from decimal import Decimal
import sys
import unittest
from benchexec.tablegenerator import util
sys.dont_write_bytecode = True # prevent creation of .pyc files
class TestUnit(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.longMessage = True
cls.maxDiff = None
def assertEqualNumberAndUnit(self, value, number, unit):
self.assertEqual(util.split_number_and_unit(value), (number, unit))
self.assertEqual(util.split_string_at_suffix(value, False), (number, unit))
def assertEqualTextAndNumber(self, value, text, number):
self.assertEqual(util.split_string_at_suffix(value, True), (text, number))
def test_split_number_and_unit(self):
self.assertEqualNumberAndUnit("", "", "")
self.assertEqualNumberAndUnit("1", "1", "")
self.assertEqualNumberAndUnit("1s", "1", "s")
self.assertEqualNumberAndUnit("111s", "111", "s")
self.assertEqualNumberAndUnit("s1", "s1", "")
self.assertEqualNumberAndUnit("s111", "s111", "")
self.assertEqualNumberAndUnit("-1s", "-1", "s")
self.assertEqualNumberAndUnit("1abc", "1", "abc")
self.assertEqualNumberAndUnit("abc", "", "abc")
self.assertEqualNumberAndUnit("abc1abc", "abc1", "abc")
self.assertEqualNumberAndUnit("abc1abc1abc", "abc1abc1", "abc")
def test_split_string_at_suffix(self):
self.assertEqualTextAndNumber("", "", "")
self.assertEqualTextAndNumber("1", "", "1")
self.assertEqualTextAndNumber("1s", "1s", "")
self.assertEqualTextAndNumber("111s", "111s", "")
self.assertEqualTextAndNumber("s1", "s", "1")
self.assertEqualTextAndNumber("s111", "s", "111")
self.assertEqualTextAndNumber("-1s", "-1s", "")
self.assertEqualTextAndNumber("abc1", "abc", "1")
self.assertEqualTextAndNumber("abc", "abc", "")
self.assertEqualTextAndNumber("abc1abc", "abc1abc", "")
self.assertEqualTextAndNumber("abc1abc1", "abc1abc", "1")
def test_print_decimal_roundtrip(self):
# These values should be printed exactly as in the input (with "+" removed)
test_values = [
"NaN",
"Inf",
"-Inf",
"+Inf",
"0",
"-0",
"+0",
"0.0",
"-0.0",
"0.00000000000000000000",
"0.00000000000000000001",
"0.00000000123450000000",
"0.1",
"0.10000000000000000000",
"0.99999999999999999999",
"1",
"-1",
"+1",
"1000000000000000000000",
"10000000000.0000000000",
]
for value in test_values:
expected = value.lstrip("+")
self.assertEqual(expected, util.print_decimal(Decimal(value)))
def test_print_decimal_int(self):
# These values should be printed like Decimal prints them after quantizing
# to remove the exponent.
test_values = ["0e0", "-0e0", "0e20", "1e0", "1e20", "0e10"]
for value in test_values:
value = Decimal(value)
expected = str(value.quantize(1))
assert "e" not in expected
self.assertEqual(expected, util.print_decimal(value))
def test_print_decimal_float(self):
# These values should be printed like str prints floats.
test_values = ["1e-4", "123e-4", "1234e-4", "1234e-5", "1234e-6"]
for value in test_values:
expected = str(float(value))
assert "e" not in expected, expected
self.assertEqual(expected, util.print_decimal(Decimal(value)))
|
canwe/NewsBlur
|
refs/heads/master
|
vendor/seacucumber/management/commands/ses_usage.py
|
20
|
"""
Shows some usage levels and limits for the last and previous 24 hours.
"""
import datetime
from django.core.management.base import BaseCommand
from seacucumber.util import get_boto_ses_connection
class Command(BaseCommand):
"""
This command shows some really vague usage and quota stats from SES.
"""
help = "Shows SES usage and quota limits."
def handle(self, *args, **options):
"""
Renders the output by piecing together a few methods that do the
dirty work.
"""
# AWS SES connection, which can be re-used for each query needed.
conn = get_boto_ses_connection()
self._print_quota(conn)
self._print_daily_stats(conn)
def _print_quota(self, conn):
"""
Prints some basic quota statistics.
"""
quota = conn.get_send_quota()
quota = quota['GetSendQuotaResponse']['GetSendQuotaResult']
print "--- SES Quota ---"
print " 24 Hour Quota: %s" % quota['Max24HourSend']
print " Sent (Last 24 hours): %s" % quota['SentLast24Hours']
print " Max sending rate: %s/sec" % quota['MaxSendRate']
def _print_daily_stats(self, conn):
"""
Prints a Today/Last 24 hour stats section.
"""
stats = conn.get_send_statistics()
stats = stats['GetSendStatisticsResponse']['GetSendStatisticsResult']
stats = stats['SendDataPoints']
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
current_day = {'HeaderName': 'Current Day: %s/%s' % (today.month,
today.day)}
prev_day = {'HeaderName': 'Yesterday: %s/%s' % (yesterday.month,
yesterday.day)}
for data_point in stats:
if self._is_data_from_today(data_point):
day_dict = current_day
else:
day_dict = prev_day
self._update_day_dict(data_point, day_dict)
for day in [current_day, prev_day]:
print "--- %s ---" % day.get('HeaderName', 0)
print " Delivery attempts: %s" % day.get('DeliveryAttempts', 0)
print " Bounces: %s" % day.get('Bounces', 0)
print " Rejects: %s" % day.get('Rejects', 0)
print " Complaints: %s" % day.get('Complaints', 0)
def _is_data_from_today(self, data_point):
"""
Takes a DataPoint from SESConnection.get_send_statistics() and returns
True if it is talking about the current date, False if not.
:param dict data_point: The data point to consider.
:rtype: bool
:returns: True if this data_point is for today, False if not (probably
yesterday).
"""
today = datetime.date.today()
raw_timestr = data_point['Timestamp']
dtime = datetime.datetime.strptime(raw_timestr, '%Y-%m-%dT%H:%M:%SZ')
return today.day == dtime.day
def _update_day_dict(self, data_point, day_dict):
"""
Helper method for :meth:`_print_daily_stats`. Given a data point and
the correct day dict, update attribs on the dict with the contents
of the data point.
:param dict data_point: The data point to add to the day's stats dict.
:param dict day_dict: A stats-tracking dict for a 24 hour period.
"""
for topic in ['Bounces', 'Complaints', 'DeliveryAttempts', 'Rejects']:
day_dict[topic] = day_dict.get(topic, 0) + int(data_point[topic])
|
Bryan792/dotfiles
|
refs/heads/master
|
vim/vim.symlink/eclim/autoload/eclim/python/rope/refactor/extract.py
|
56
|
import re
from rope.base import ast, codeanalyze
from rope.base.change import ChangeSet, ChangeContents
from rope.base.exceptions import RefactoringError
from rope.refactor import (sourceutils, similarfinder,
patchedast, suites, usefunction)
# Extract refactoring has lots of special cases. I tried to split it
# to smaller parts to make it more manageable:
#
# _ExtractInfo: holds information about the refactoring; it is passed
# to the parts that need to have information about the refactoring
#
# _ExtractCollector: merely saves all of the information necessary for
# performing the refactoring.
#
# _DefinitionLocationFinder: finds where to insert the definition.
#
# _ExceptionalConditionChecker: checks for exceptional conditions in
# which the refactoring cannot be applied.
#
# _ExtractMethodParts: generates the pieces of code (like definition)
# needed for performing extract method.
#
# _ExtractVariableParts: like _ExtractMethodParts for variables.
#
# _ExtractPerformer: Uses above classes to collect refactoring
# changes.
#
# There are a few more helper functions and classes used by above
# classes.
class _ExtractRefactoring(object):
def __init__(self, project, resource, start_offset, end_offset,
variable=False):
self.project = project
self.pycore = project.pycore
self.resource = resource
self.start_offset = self._fix_start(resource.read(), start_offset)
self.end_offset = self._fix_end(resource.read(), end_offset)
def _fix_start(self, source, offset):
while offset < len(source) and source[offset].isspace():
offset += 1
return offset
def _fix_end(self, source, offset):
while offset > 0 and source[offset - 1].isspace():
offset -= 1
return offset
def get_changes(self, extracted_name, similar=False, global_=False):
"""Get the changes this refactoring makes
:parameters:
- `similar`: if `True`, similar expressions/statements are also
replaced.
- `global_`: if `True`, the extracted method/variable will
be global.
"""
info = _ExtractInfo(
self.project, self.resource, self.start_offset, self.end_offset,
extracted_name, variable=self.kind == 'variable',
similar=similar, make_global=global_)
new_contents = _ExtractPerformer(info).extract()
changes = ChangeSet('Extract %s <%s>' % (self.kind,
extracted_name))
changes.add_change(ChangeContents(self.resource, new_contents))
return changes
class ExtractMethod(_ExtractRefactoring):
def __init__(self, *args, **kwds):
super(ExtractMethod, self).__init__(*args, **kwds)
kind = 'method'
class ExtractVariable(_ExtractRefactoring):
def __init__(self, *args, **kwds):
kwds = dict(kwds)
kwds['variable'] = True
super(ExtractVariable, self).__init__(*args, **kwds)
kind = 'variable'
class _ExtractInfo(object):
"""Holds information about the extract to be performed"""
def __init__(self, project, resource, start, end, new_name,
variable, similar, make_global):
self.pycore = project.pycore
self.resource = resource
self.pymodule = self.pycore.resource_to_pyobject(resource)
self.global_scope = self.pymodule.get_scope()
self.source = self.pymodule.source_code
self.lines = self.pymodule.lines
self.new_name = new_name
self.variable = variable
self.similar = similar
self._init_parts(start, end)
self._init_scope()
self.make_global = make_global
def _init_parts(self, start, end):
self.region = (self._choose_closest_line_end(start),
self._choose_closest_line_end(end, end=True))
start = self.logical_lines.logical_line_in(
self.lines.get_line_number(self.region[0]))[0]
end = self.logical_lines.logical_line_in(
self.lines.get_line_number(self.region[1]))[1]
self.region_lines = (start, end)
self.lines_region = (self.lines.get_line_start(self.region_lines[0]),
self.lines.get_line_end(self.region_lines[1]))
@property
def logical_lines(self):
return self.pymodule.logical_lines
def _init_scope(self):
start_line = self.region_lines[0]
scope = self.global_scope.get_inner_scope_for_line(start_line)
if scope.get_kind() != 'Module' and scope.get_start() == start_line:
scope = scope.parent
self.scope = scope
self.scope_region = self._get_scope_region(self.scope)
def _get_scope_region(self, scope):
return (self.lines.get_line_start(scope.get_start()),
self.lines.get_line_end(scope.get_end()) + 1)
def _choose_closest_line_end(self, offset, end=False):
lineno = self.lines.get_line_number(offset)
line_start = self.lines.get_line_start(lineno)
line_end = self.lines.get_line_end(lineno)
if self.source[line_start:offset].strip() == '':
if end:
return line_start - 1
else:
return line_start
elif self.source[offset:line_end].strip() == '':
return min(line_end, len(self.source))
return offset
@property
def one_line(self):
return self.region != self.lines_region and \
(self.logical_lines.logical_line_in(self.region_lines[0]) ==
self.logical_lines.logical_line_in(self.region_lines[1]))
@property
def global_(self):
return self.scope.parent is None
@property
def method(self):
return self.scope.parent is not None and \
self.scope.parent.get_kind() == 'Class'
@property
def indents(self):
return sourceutils.get_indents(self.pymodule.lines,
self.region_lines[0])
@property
def scope_indents(self):
if self.global_:
return 0
return sourceutils.get_indents(self.pymodule.lines,
self.scope.get_start())
@property
def extracted(self):
return self.source[self.region[0]:self.region[1]]
_returned = None
@property
def returned(self):
"""Does the extracted piece contain return statement"""
if self._returned is None:
node = _parse_text(self.extracted)
self._returned = usefunction._returns_last(node)
return self._returned
class _ExtractCollector(object):
"""Collects information needed for performing the extract"""
def __init__(self, info):
self.definition = None
self.body_pattern = None
self.checks = {}
self.replacement_pattern = None
self.matches = None
self.replacements = None
self.definition_location = None
class _ExtractPerformer(object):
def __init__(self, info):
self.info = info
_ExceptionalConditionChecker()(self.info)
def extract(self):
extract_info = self._collect_info()
content = codeanalyze.ChangeCollector(self.info.source)
definition = extract_info.definition
lineno, indents = extract_info.definition_location
offset = self.info.lines.get_line_start(lineno)
indented = sourceutils.fix_indentation(definition, indents)
content.add_change(offset, offset, indented)
self._replace_occurrences(content, extract_info)
return content.get_changed()
def _replace_occurrences(self, content, extract_info):
for match in extract_info.matches:
replacement = similarfinder.CodeTemplate(
extract_info.replacement_pattern)
mapping = {}
for name in replacement.get_names():
node = match.get_ast(name)
if node:
start, end = patchedast.node_region(match.get_ast(name))
mapping[name] = self.info.source[start:end]
else:
mapping[name] = name
region = match.get_region()
content.add_change(region[0], region[1],
replacement.substitute(mapping))
def _collect_info(self):
extract_collector = _ExtractCollector(self.info)
self._find_definition(extract_collector)
self._find_matches(extract_collector)
self._find_definition_location(extract_collector)
return extract_collector
def _find_matches(self, collector):
regions = self._where_to_search()
finder = similarfinder.SimilarFinder(self.info.pymodule)
matches = []
for start, end in regions:
matches.extend((finder.get_matches(collector.body_pattern,
collector.checks, start, end)))
collector.matches = matches
def _where_to_search(self):
if self.info.similar:
if self.info.make_global or self.info.global_:
return [(0, len(self.info.pymodule.source_code))]
if self.info.method and not self.info.variable:
class_scope = self.info.scope.parent
regions = []
method_kind = _get_function_kind(self.info.scope)
for scope in class_scope.get_scopes():
if method_kind == 'method' and \
_get_function_kind(scope) != 'method':
continue
start = self.info.lines.get_line_start(scope.get_start())
end = self.info.lines.get_line_end(scope.get_end())
regions.append((start, end))
return regions
else:
if self.info.variable:
return [self.info.scope_region]
else:
return [self.info._get_scope_region(self.info.scope.parent)]
else:
return [self.info.region]
def _find_definition_location(self, collector):
matched_lines = []
for match in collector.matches:
start = self.info.lines.get_line_number(match.get_region()[0])
start_line = self.info.logical_lines.logical_line_in(start)[0]
matched_lines.append(start_line)
location_finder = _DefinitionLocationFinder(self.info, matched_lines)
collector.definition_location = (location_finder.find_lineno(),
location_finder.find_indents())
def _find_definition(self, collector):
if self.info.variable:
parts = _ExtractVariableParts(self.info)
else:
parts = _ExtractMethodParts(self.info)
collector.definition = parts.get_definition()
collector.body_pattern = parts.get_body_pattern()
collector.replacement_pattern = parts.get_replacement_pattern()
collector.checks = parts.get_checks()
class _DefinitionLocationFinder(object):
def __init__(self, info, matched_lines):
self.info = info
self.matched_lines = matched_lines
# This only happens when subexpressions cannot be matched
if not matched_lines:
self.matched_lines.append(self.info.region_lines[0])
def find_lineno(self):
if self.info.variable and not self.info.make_global:
return self._get_before_line()
if self.info.make_global or self.info.global_:
toplevel = self._find_toplevel(self.info.scope)
ast = self.info.pymodule.get_ast()
newlines = sorted(self.matched_lines + [toplevel.get_end() + 1])
return suites.find_visible(ast, newlines)
return self._get_after_scope()
def _find_toplevel(self, scope):
toplevel = scope
if toplevel.parent is not None:
while toplevel.parent.parent is not None:
toplevel = toplevel.parent
return toplevel
def find_indents(self):
if self.info.variable and not self.info.make_global:
return sourceutils.get_indents(self.info.lines,
self._get_before_line())
else:
if self.info.global_ or self.info.make_global:
return 0
return self.info.scope_indents
def _get_before_line(self):
ast = self.info.scope.pyobject.get_ast()
return suites.find_visible(ast, self.matched_lines)
def _get_after_scope(self):
return self.info.scope.get_end() + 1
class _ExceptionalConditionChecker(object):
def __call__(self, info):
self.base_conditions(info)
if info.one_line:
self.one_line_conditions(info)
else:
self.multi_line_conditions(info)
def base_conditions(self, info):
if info.region[1] > info.scope_region[1]:
raise RefactoringError('Bad region selected for extract method')
end_line = info.region_lines[1]
end_scope = info.global_scope.get_inner_scope_for_line(end_line)
if end_scope != info.scope and end_scope.get_end() != end_line:
raise RefactoringError('Bad region selected for extract method')
try:
extracted = info.source[info.region[0]:info.region[1]]
if info.one_line:
extracted = '(%s)' % extracted
if _UnmatchedBreakOrContinueFinder.has_errors(extracted):
raise RefactoringError('A break/continue without having a '
'matching for/while loop.')
except SyntaxError:
raise RefactoringError('Extracted piece should '
'contain complete statements.')
def one_line_conditions(self, info):
if self._is_region_on_a_word(info):
raise RefactoringError('Should extract complete statements.')
if info.variable and not info.one_line:
raise RefactoringError('Extract variable should not '
'span multiple lines.')
def multi_line_conditions(self, info):
node = _parse_text(info.source[info.region[0]:info.region[1]])
count = usefunction._return_count(node)
if count > 1:
raise RefactoringError('Extracted piece can have only one '
'return statement.')
if usefunction._yield_count(node):
raise RefactoringError('Extracted piece cannot '
'have yield statements.')
if count == 1 and not usefunction._returns_last(node):
raise RefactoringError('Return should be the last statement.')
if info.region != info.lines_region:
raise RefactoringError('Extracted piece should '
'contain complete statements.')
def _is_region_on_a_word(self, info):
if info.region[0] > 0 and self._is_on_a_word(info, info.region[0] - 1) or \
self._is_on_a_word(info, info.region[1] - 1):
return True
def _is_on_a_word(self, info, offset):
prev = info.source[offset]
if not (prev.isalnum() or prev == '_') or \
offset + 1 == len(info.source):
return False
next = info.source[offset + 1]
return next.isalnum() or next == '_'
class _ExtractMethodParts(object):
def __init__(self, info):
self.info = info
self.info_collector = self._create_info_collector()
def get_definition(self):
if self.info.global_:
return '\n%s\n' % self._get_function_definition()
else:
return '\n%s' % self._get_function_definition()
def get_replacement_pattern(self):
variables = []
variables.extend(self._find_function_arguments())
variables.extend(self._find_function_returns())
return similarfinder.make_pattern(self._get_call(), variables)
def get_body_pattern(self):
variables = []
variables.extend(self._find_function_arguments())
variables.extend(self._find_function_returns())
variables.extend(self._find_temps())
return similarfinder.make_pattern(self._get_body(), variables)
def _get_body(self):
result = sourceutils.fix_indentation(self.info.extracted, 0)
if self.info.one_line:
result = '(%s)' % result
return result
def _find_temps(self):
return usefunction.find_temps(self.info.pycore.project,
self._get_body())
def get_checks(self):
if self.info.method and not self.info.make_global:
if _get_function_kind(self.info.scope) == 'method':
class_name = similarfinder._pydefined_to_str(
self.info.scope.parent.pyobject)
return {self._get_self_name(): 'type=' + class_name}
return {}
def _create_info_collector(self):
zero = self.info.scope.get_start() - 1
start_line = self.info.region_lines[0] - zero
end_line = self.info.region_lines[1] - zero
info_collector = _FunctionInformationCollector(start_line, end_line,
self.info.global_)
body = self.info.source[self.info.scope_region[0]:
self.info.scope_region[1]]
node = _parse_text(body)
ast.walk(node, info_collector)
return info_collector
def _get_function_definition(self):
args = self._find_function_arguments()
returns = self._find_function_returns()
result = []
if self.info.method and not self.info.make_global and \
_get_function_kind(self.info.scope) != 'method':
result.append('@staticmethod\n')
result.append('def %s:\n' % self._get_function_signature(args))
unindented_body = self._get_unindented_function_body(returns)
indents = sourceutils.get_indent(self.info.pycore)
function_body = sourceutils.indent_lines(unindented_body, indents)
result.append(function_body)
definition = ''.join(result)
return definition + '\n'
def _get_function_signature(self, args):
args = list(args)
prefix = ''
if self._extracting_method():
self_name = self._get_self_name()
if self_name is None:
raise RefactoringError('Extracting a method from a function '
'with no self argument.')
if self_name in args:
args.remove(self_name)
args.insert(0, self_name)
return prefix + self.info.new_name + \
'(%s)' % self._get_comma_form(args)
def _extracting_method(self):
return self.info.method and not self.info.make_global and \
_get_function_kind(self.info.scope) == 'method'
def _get_self_name(self):
param_names = self.info.scope.pyobject.get_param_names()
if param_names:
return param_names[0]
def _get_function_call(self, args):
prefix = ''
if self.info.method and not self.info.make_global:
if _get_function_kind(self.info.scope) == 'method':
self_name = self._get_self_name()
if self_name in args:
args.remove(self_name)
prefix = self_name + '.'
else:
prefix = self.info.scope.parent.pyobject.get_name() + '.'
return prefix + '%s(%s)' % (self.info.new_name,
self._get_comma_form(args))
def _get_comma_form(self, names):
result = ''
if names:
result += names[0]
for name in names[1:]:
result += ', ' + name
return result
def _get_call(self):
if self.info.one_line:
args = self._find_function_arguments()
return self._get_function_call(args)
args = self._find_function_arguments()
returns = self._find_function_returns()
call_prefix = ''
if returns:
call_prefix = self._get_comma_form(returns) + ' = '
if self.info.returned:
call_prefix = 'return '
return call_prefix + self._get_function_call(args)
def _find_function_arguments(self):
# if not make_global, do not pass any global names; they are
# all visible.
if self.info.global_ and not self.info.make_global:
return ()
if not self.info.one_line:
result = (self.info_collector.prewritten &
self.info_collector.read)
result |= (self.info_collector.prewritten &
self.info_collector.postread &
(self.info_collector.maybe_written -
self.info_collector.written))
return list(result)
start = self.info.region[0]
if start == self.info.lines_region[0]:
start = start + re.search('\S', self.info.extracted).start()
function_definition = self.info.source[start:self.info.region[1]]
read = _VariableReadsAndWritesFinder.find_reads_for_one_liners(
function_definition)
return list(self.info_collector.prewritten.intersection(read))
def _find_function_returns(self):
if self.info.one_line or self.info.returned:
return []
written = self.info_collector.written | \
self.info_collector.maybe_written
return list(written & self.info_collector.postread)
def _get_unindented_function_body(self, returns):
if self.info.one_line:
return 'return ' + _join_lines(self.info.extracted)
extracted_body = self.info.extracted
unindented_body = sourceutils.fix_indentation(extracted_body, 0)
if returns:
unindented_body += '\nreturn %s' % self._get_comma_form(returns)
return unindented_body
class _ExtractVariableParts(object):
def __init__(self, info):
self.info = info
def get_definition(self):
result = self.info.new_name + ' = ' + \
_join_lines(self.info.extracted) + '\n'
return result
def get_body_pattern(self):
return '(%s)' % self.info.extracted.strip()
def get_replacement_pattern(self):
return self.info.new_name
def get_checks(self):
return {}
class _FunctionInformationCollector(object):
def __init__(self, start, end, is_global):
self.start = start
self.end = end
self.is_global = is_global
self.prewritten = set()
self.maybe_written = set()
self.written = set()
self.read = set()
self.postread = set()
self.postwritten = set()
self.host_function = True
self.conditional = False
def _read_variable(self, name, lineno):
if self.start <= lineno <= self.end:
if name not in self.written:
self.read.add(name)
if self.end < lineno:
if name not in self.postwritten:
self.postread.add(name)
def _written_variable(self, name, lineno):
if self.start <= lineno <= self.end:
if self.conditional:
self.maybe_written.add(name)
else:
self.written.add(name)
if self.start > lineno:
self.prewritten.add(name)
if self.end < lineno:
self.postwritten.add(name)
def _FunctionDef(self, node):
if not self.is_global and self.host_function:
self.host_function = False
for name in _get_argnames(node.args):
self._written_variable(name, node.lineno)
for child in node.body:
ast.walk(child, self)
else:
self._written_variable(node.name, node.lineno)
visitor = _VariableReadsAndWritesFinder()
for child in node.body:
ast.walk(child, visitor)
for name in visitor.read - visitor.written:
self._read_variable(name, node.lineno)
def _Name(self, node):
if isinstance(node.ctx, (ast.Store, ast.AugStore)):
self._written_variable(node.id, node.lineno)
if not isinstance(node.ctx, ast.Store):
self._read_variable(node.id, node.lineno)
def _Assign(self, node):
ast.walk(node.value, self)
for child in node.targets:
ast.walk(child, self)
def _ClassDef(self, node):
self._written_variable(node.name, node.lineno)
def _handle_conditional_node(self, node):
self.conditional = True
try:
for child in ast.get_child_nodes(node):
ast.walk(child, self)
finally:
self.conditional = False
def _If(self, node):
self._handle_conditional_node(node)
def _While(self, node):
self._handle_conditional_node(node)
def _For(self, node):
self._handle_conditional_node(node)
def _get_argnames(arguments):
result = [node.id for node in arguments.args
if isinstance(node, ast.Name)]
if arguments.vararg:
result.append(arguments.vararg)
if arguments.kwarg:
result.append(arguments.kwarg)
return result
class _VariableReadsAndWritesFinder(object):
def __init__(self):
self.written = set()
self.read = set()
def _Name(self, node):
if isinstance(node.ctx, (ast.Store, ast.AugStore)):
self.written.add(node.id)
if not isinstance(node, ast.Store):
self.read.add(node.id)
def _FunctionDef(self, node):
self.written.add(node.name)
visitor = _VariableReadsAndWritesFinder()
for child in ast.get_child_nodes(node):
ast.walk(child, visitor)
self.read.update(visitor.read - visitor.written)
def _Class(self, node):
self.written.add(node.name)
@staticmethod
def find_reads_and_writes(code):
if code.strip() == '':
return set(), set()
if isinstance(code, unicode):
code = code.encode('utf-8')
node = _parse_text(code)
visitor = _VariableReadsAndWritesFinder()
ast.walk(node, visitor)
return visitor.read, visitor.written
@staticmethod
def find_reads_for_one_liners(code):
if code.strip() == '':
return set(), set()
node = _parse_text(code)
visitor = _VariableReadsAndWritesFinder()
ast.walk(node, visitor)
return visitor.read
class _UnmatchedBreakOrContinueFinder(object):
def __init__(self):
self.error = False
self.loop_count = 0
def _For(self, node):
self.loop_encountered(node)
def _While(self, node):
self.loop_encountered(node)
def loop_encountered(self, node):
self.loop_count += 1
for child in node.body:
ast.walk(child, self)
self.loop_count -= 1
if node.orelse:
ast.walk(node.orelse, self)
def _Break(self, node):
self.check_loop()
def _Continue(self, node):
self.check_loop()
def check_loop(self):
if self.loop_count < 1:
self.error = True
def _FunctionDef(self, node):
pass
def _ClassDef(self, node):
pass
@staticmethod
def has_errors(code):
if code.strip() == '':
return False
node = _parse_text(code)
visitor = _UnmatchedBreakOrContinueFinder()
ast.walk(node, visitor)
return visitor.error
def _get_function_kind(scope):
return scope.pyobject.get_kind()
def _parse_text(body):
body = sourceutils.fix_indentation(body, 0)
node = ast.parse(body)
return node
def _join_lines(code):
lines = []
for line in code.splitlines():
if line.endswith('\\'):
lines.append(line[:-1].strip())
else:
lines.append(line.strip())
return ' '.join(lines)
|
uppi/adventofcode2016
|
refs/heads/master
|
adventofcode/adv_23.py
|
1
|
import re
HEIGHT = 6
WIDTH = 50
PARSER = re.compile("(inc|dec|cpy|jnz|tgl) (-?\d+|[a-d]) ?(-?\d+|[a-d])?$")
def parse_input(input_seq):
for cmd in input_seq:
op, a, b = PARSER.match(cmd).groups()
if not a.isalpha():
a = int(a)
if b is not None:
if not b.isalpha():
b = int(b)
yield(op, (a, b))
else:
yield(op, (a,))
def tgl(code, registers, value):
value = registers.get(value, value)
value = registers["ip"] + value
print("should toggle ", value)
if value >= len(code):
registers["ip"] += 1
return
if value == registers["ip"]:
print("Thats us")
registers["ip"] += 1
return
instr = code[value]
print("Instr is", instr)
if instr[0] == "inc":
instr = tuple(["dec"] + list(instr[1:]))
elif instr[0] == "dec":
instr = tuple(["inc"] + list(instr[1:]))
elif instr[0] == "tgl":
instr = tuple(["inc"] + list(instr[1:]))
elif instr[0] == "jnz":
print(instr)
if instr[1][1] in ("a", "b", "c", "d"):
instr = tuple(["cpy"] + list(instr[1:]))
elif instr[0] == "cpy":
instr = tuple(["jnz"] + list(instr[1:]))
code[value] = instr
registers["ip"] += 1
def inc(code, registers, reg):
# optimize_inc_dec_jnz(code, registers)
registers[reg] += 1
registers["ip"] += 1
def dec(code, registers, reg):
registers[reg] -= 1
registers["ip"] += 1
def cpy(code, registers, value, reg):
registers[reg] = registers.get(value, value)
registers["ip"] += 1
def jnz(code, registers, value, offset):
if registers.get(value, value) != 0:
registers["ip"] += registers.get(offset, offset)
else:
registers["ip"] += 1
OP = {
"jnz": jnz,
"inc": inc,
"dec": dec,
"cpy": cpy,
"tgl": tgl
}
def execute(code, **kwargs):
registers = {"a": 0, "b": 0, "c": 0, "d": 0, "ip": 0}
registers.update(kwargs)
c = 0
while registers["ip"] < len(code):
c += 1
if c % 1000 == 1:
print(registers)
cmd, args = code[registers["ip"]]
OP[cmd](code, registers, *args)
return registers
if __name__ == '__main__':
with open("data/23.txt") as inp:
inp_seq = list(inp)
parsed_input = list(parse_input(inp_seq))
registers = execute(parsed_input, a=12)
print(registers["a"])
|
Mitchkoens/sympy
|
refs/heads/master
|
sympy/solvers/__init__.py
|
22
|
"""A module for solving all kinds of equations.
Examples
========
>>> from sympy.solvers import solve
>>> from sympy.abc import x
>>> solve(x**5+5*x**4+10*x**3+10*x**2+5*x+1,x)
[-1]
"""
from .solvers import solve, solve_linear_system, solve_linear_system_LU, \
solve_undetermined_coeffs, nsolve, solve_linear, checksol, \
det_quick, inv_quick
from .recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
from .ode import checkodesol, classify_ode, dsolve, \
homogeneous_order
from .polysys import solve_poly_system, solve_triangulated
from .pde import pde_separate, pde_separate_add, pde_separate_mul, \
pdsolve, classify_pde, checkpdesol
from .deutils import ode_order
from .inequalities import reduce_inequalities, reduce_abs_inequality, \
reduce_abs_inequalities, solve_poly_inequality, solve_rational_inequalities, solve_univariate_inequality
|
diegocrzt/pmspy
|
refs/heads/master
|
pms/modelo/peticionControlador.py
|
1
|
from entidad import Proyecto, Peticion, Voto, LB_Ver, Miembro, ItemPeticion,LineaBase
from initdb import db_session, init_db, shutdown_session
from pms.modelo.proyectoControlador import getProyectoId
from pms.modelo.usuarioControlador import getUsuarios
from pms.modelo.itemControlador import getVersionId, getVersionItem, getItemVerNum
from pms.modelo.relacionControlador import calcularCyD, crearGrafoProyecto, desBloquearAdelante, desBloquear, setEnCambio
from datetime import datetime
from datetime import timedelta
session = db_session()
def getPeticionesVotacion(idp=None):
"""
Retorna las peticiones en votacion
"""
init_db()
res=session.query(Peticion).filter(Peticion.proyecto_id==idp).filter(Peticion.estado=="Votacion").all()
shutdown_session()
return res
def getPeticion(id=None):
"""
Retorna una peticion, recibe el id de la peticion
"""
init_db()
res=session.query(Peticion).filter(Peticion.id==id).first()
shutdown_session()
return res
#def crearPeticion(numero,proyecto_id,comentario,estado,usuario_id,cantVotos,cantItems,costoT,dificultadT,fechaCreacion,fechaEnvio):
def crearPeticion(proyecto_id=None,comentario=None,usuario_id=None, items=None, acciones=None):
"""
Crea una Peticion, recibe el id del proyecto, el id de la version del item sobre el cual se solicita la peticion, un comentario y el id del usuario que solicita la peticioin
"""
if proyecto_id and comentario and usuario_id and items and acciones:
init_db()
ultimo=session.query(Peticion).filter(Peticion.proyecto_id==proyecto_id).order_by(Peticion.id.desc()).first()
if ultimo:
numero=ultimo.numero+1
else:
numero=1
fechaCreacion=datetime.today()
l=[]
for i in items:
l.append(i.id)
cd=calcularCyD(l)
#calcular costo y dificultad y mete en el crear de peticion!!1
peticion=Peticion(numero,proyecto_id,comentario,"EnEdicion",usuario_id,0,len(items),cd[0],cd[1],fechaCreacion,None,acciones)
##------------
session.add(peticion)
session.commit()
peticion=session.query(Peticion).filter(Peticion.proyecto_id==proyecto_id).filter(Peticion.numero==numero).first()
if peticion:
for i in items:
a=agregarItem(i.id,peticion.id)
shutdown_session()
def editarPeticion(idp=None,comentario=None,items=None,acciones=None):
"""
Permite editar un Peticion existente, recibe el id de la peticion, su comentario, una lista de items y las acciones
"""
p = getPeticion(idp)
if comentario:
p.comentario=comentario
if acciones:
p.acciones=acciones
if items:
for i in items:
if(getItemPeticion(i.id)==None):
agregarItem(i.id,p.id)
for i in p.items:
if not i.item in items:
quitarItem(i.item.id)
print "if not in items"
l=[]
for i in items:
l.append(i.id)
cd=calcularCyD(l)
p.costoT=cd[0]
p.dificultadT=cd[1]
p.cantItems=len(p.items)
init_db()
session.merge(p)
session.commit()
shutdown_session()
def eliminarPeticion(idp=None):
"""Elimina una Peticion, recibe el id de la peticion
"""
init_db()
u=getPeticion(idp)
for l in u.items:
quitarItemDeCualquierSolicitud(l.item.id, u.id)
for l in u.votos:
quitarVoto(l.user_id,l.peticion_id)
session.query(Peticion).filter(Peticion.id==u.id).delete()
session.commit()
shutdown_session()
def quitarItemDeCualquierSolicitud(idv=None, idp=None):
""" Quita un item de una solicitud sin importar el estado de sicha solicitud
"""
if idv and idp:
init_db()
v=session.query(ItemPeticion).filter(ItemPeticion.item_id==idv).filter(ItemPeticion.peticion_id==idp).first()
if v:
session.query(ItemPeticion).filter(ItemPeticion.item_id==v.item_id).filter(ItemPeticion.peticion_id==v.peticion_id).delete()
session.commit()
shutdown_session()
def getItemPeticion(idv=None):
"""Retorna un ItemPeticion de una peticion con estado "EnVotacion" o "Aprobada" de una version de item
"""
init_db()
res=session.query(ItemPeticion).filter(ItemPeticion.item_id==idv).filter(ItemPeticion.actual==True).first()
shutdown_session()
return res
def comprobarItemPeticion(idv=None):
"""Comprueba que el item no se encuentre en una peticion, retornar False si el item ya esta en una peticion
"""
res=getItemPeticion(idv)
if res==None:
return True
else:
return False
def enviarPeticion(idp=None):
"""Envia una Peticion, recibe el id de la peticion, cambia el estado de la peticion a EnVotacion
"""
if idp:
p = getPeticion(idp)
init_db()
p.estado="EnVotacion"
p.fechaEnvio=datetime.today()
session.merge(p)
session.commit()
shutdown_session()
def agregarItem(idv=None,idp=None,):
"""Agrega un Item a una peticion, recibe el id del item y de la peticion
"""
if idv and idp:
ip=ItemPeticion(idp,idv,True)
init_db()
session.add(ip)
session.commit()
shutdown_session()
return True
return False
def quitarItem(idv=None):
"""Quita un Item de una peticion, recibe el id del item
"""
init_db()
v=getItemPeticion(idv)
if v:
session.query(ItemPeticion).filter(ItemPeticion.item_id==v.item_id).filter(ItemPeticion.peticion_id==v.peticion_id).delete()
else:
session.query(ItemPeticion).filter(ItemPeticion.item_id==idv).filter(ItemPeticion.actual==True).first()
session.commit()
shutdown_session()
def getVoto(idu=None,idp=None):
"""Retorna un voto, recibe el id del usuario y el id de la peticion
"""
init_db()
res=session.query(Voto).filter(Voto.user_id==idu).filter(Voto.peticion_id==idp).first()
shutdown_session()
return res
def comprobarVoto(idu=None,idp=None):
"""Comprueba que el usuario no haya votado aun en la solicitud, recibe el id del usuario y el id de la solicitud
"""
res=getVoto(idu,idp)
if res==None:
return True
else:
return False
def agregarVoto(idu=None, idp=None,valor=None):
"""Crea un voto, recibe el id del ususario que vota, el id de la peticion en la que vota y el valor de su voto (True o False)
"""
if comprobarVoto(idu,idp):
soli=getPeticion(idp)
init_db()
soli.cantVotos=soli.cantVotos+1
v=Voto(idp,idu,valor)
session.add(v)
session.merge(soli)
session.commit()
shutdown_session()
return True
else:
return False
def quitarVoto(idu=None,idp=None):
"""Elimina un voto, recibe el id del usuario y el id de la peticion
"""
soli=getPeticion(idp)
soli.cantVotos=soli.cantVotos-1
init_db()
session.query(Voto).filter(Voto.peticion_id==idp).filter(Voto.user_id==idu).delete()
session.merge(soli)
session.commit()
shutdown_session()
def contarVotos(idp=None):
"""Cuentas los votos de una peticion y la rechaza o aprueba, recibe el id de la peticion
"""
soli=getPeticion(idp)
votos=0
for v in soli.votos:
if v.valor==True:
votos=votos+1
init_db()
c=(soli.cantVotos+1)/2 #cantidad necesaria para aprobar
if votos>=c:
soli.estado="Aprobada"
l=[]
for i in soli.items:
l.append(i.item_id)
desBloquearAdelante(l)
actualizarItemsSolicitud(soli.id)
for i in soli.items:
setEnCambio(i.item.id)
else:
soli.estado="Rechazada"
for i in soli.items:
res=getItemPeticion(i.item.id)
res.actual=False
session.merge(res)
session.merge(soli)
session.commit()
shutdown_session()
def cambiarVotos(idp=None):
"""
Cambia a false el campo actual de los votos para que no se tome en cuenta en futuras operaciones
"""
soli=getPeticion(idp)
init_db()
for v in soli.votos:
v.actual=False
session.merge(v)
session.commit()
shutdown_session()
def getMiembros(idp=None):
"""
Devuelve los usuarios que son miembros de el comite de un proyecto, recibe el id del proyecto
"""
init_db()
res= session.query(Miembro).filter(Miembro.proyecto_id==idp).all()
shutdown_session()
return res
def getMiembro(idp=None,idu=None):
"""
Devuelve un usuario que sea miembro de un poryecto, recive el id del usuario y el proyecto
"""
init_db()
res = session.query(Miembro).filter(Miembro.proyecto_id==idp).filter(Miembro.user_id==idu).first()
shutdown_session()
return res
def agregarMiembro(idp=None,idu=None):
"""
Agrega un usuario a el comite de un proyecto, recibe el id del proyecto y del usuario, devuelve false si el usuario ya esta en el comite
"""
if getMiembro(idp,idu)==None:
init_db()
m=Miembro(idp,idu)
session.add(m)
session.commit()
shutdown_session()
return True
else:
return False
def quitarMiembro(idp=None,idu=None):
"""
Elimina un usuario a el comite de un proyecto, recibe el id del proyecto y del usuario, devuelve false si el usuario no esta en el comite
"""
if getMiembro(idp,idu)!=None:
init_db()
session.query(Miembro).filter(Miembro.user_id==idu).filter(Miembro.proyecto_id==idp).delete()
session.commit()
shutdown_session()
return True
else:
return False
def agregarListaMiembros(lista=None,idp=None):
"""
Cambia el conjunto de usuarios que pertenecen al comite de un proyecto a el conjunto de usuarios que pertenecen a la lista pasada como parametro
"""
c=0
for l in lista:
c=c+1
if (c%2)!=0:
usr=getUsuarios()
for u in usr:
quitarMiembro(idp,u.id)
for l in lista:
agregarMiembro(idp,l.id)
return True
else:
return False
def getVersionesItemParaSolicitud(idpro=None):
"""Retorna una lista de items que no se encuentran en una peticion en votacion, en edicion o aprobada y que estan en estado Bloqueado o Conflicto
"""
if idpro:
l=[]
pro=getProyectoId(idpro)
fases=pro.fases
for f in fases:
for t in f.tipos:
for i in t.instancias:
v=getVersionItem(i.id)
aux=[]
if (v.estado=="Bloqueado" or v.estado=="Conflicto"):#controlar si se encuentra en una solicitud
if comprobarItemPeticion(v.id):
aux.append(v)
aux.append(False)
l.append(aux)
return l
def opercionHabilitada(s=None, op=None):
"""Retorna True si la solicitud de id s contiene la operacion que se le pasa en op
"""
if s and op:
if op=="Editar":
return s.acciones%10==1
elif op=="Eliminar":
return s.acciones%100>=10
elif op=="Crear Relacion":
return s.acciones%1000>=100
elif op=="Eliminar Relacion":
return s.acciones%10000>=1000
else:
return False
def actualizarItemsSolicitud(s=None):
"""
Actualiza las versiones de los items que se encuentran en la solicitud de id s, recorre los items de la solicitud(que en relidad son las versiones de los items)
y revisa que la version que se tiene es la actual del item en cuestion
"""
if s :
soli=getPeticion(s)
for i in soli.items:
idi=i.item.item.id
nuevav=getVersionItem(idi)
if nuevav.id!=i.item.id:
quitarItem(i.item.id)
a=agregarItem(nuevav.id, soli.id)
def reiniciarVotacion(ids=None):
"""
Reinicia una votacion, recibe el id de la peticion
"""
peticion=getPeticion(ids)
peticion.cantVotos=0
init_db()
session.query(Voto).filter(Voto.peticion_id==ids).delete()
session.commit()
session.merge(peticion)
session.commit()
shutdown_session()
def compararPeticion(ids=None):
"""
Comprueba que el costo y la dificultad de una peticion no hayan sido alterados
"""
peticion=getPeticion(ids)
aux=peticion.items
l=[]
for a in aux:
l.append(a.item.id)
r=calcularCyD(l)
if r[0]!=peticion.costoT or r[1]!=peticion.dificultadT:
reiniciarVotacion(peticion.id)
return True
else:
return False
def buscarSolicitud(idv=None):
"""
Comprubea que la modificacion de un item no altera una solicitud en estado de votacion
"""
ver=getVersionId(idv)
itm= ver.item
fase=itm.tipoitem.fase
proyecto=fase.proyecto
grafo=crearGrafoProyecto(proyecto.id)
cola=[]
for n in grafo:
if int(n.version)==int(idv):
n.marca=True
cola.append(n)
for c in cola:
for s in c.entrantes:
s.marca=True
cola.append(s)
if not comprobarItemPeticion(s.version):
compararPeticion(getItemPeticion(s.version).peticion_id)
def tSolicitud(ids=None):
"""
Termina una Solicitud, recibe el id de la solicitud
"""
soli=getPeticion(ids)
init_db()
soli.estado="Terminada"
session.merge(soli)
session.commit()
for i in soli.items:
i.actual=False
session.merge(i)
session.commit()
ver=i.item
if ver.estado=="EnCambio":
ver.estado="Aprobado"
session.merge(ver)
session.commit()
elif ver.estado=="Eliminado":
it=ver.item
it.linea_id=None
session.merge(it)
session.commit()
shutdown_session()
def getLBPeticion(ids=None):
"""
Retorna las lineas base que van a ser o estan quebradas como consecuencia de la solicitud, recibe el id de la solicitud
"""
soli=getPeticion(ids)
lineas=[]
if soli.estado=="Terminada" or soli.estado=="Aprobada":
for i in soli.items:
v=i.item
while not v.lalinea:
v=getItemVerNum(v.item.id,v.version-1)
init_db()
l=session.query(LB_Ver).filter(LB_Ver.ver_id==v.id).first()
shutdown_session()
lineas.append(l.linea)
else:
for i in soli.items:
it=i.item.item
lineas.append(it.lineabase)
return lineas
def getItemsAfectados2(ids=None):
"""
Retorna un diccionario con todos los items afectados por la solicitud y los relacionados con estos
"""
soli=getPeticion(ids)
items={}
lineas={}
colaitems=[]
for i in soli.items:
v=i.item
colaitems.append(v)
if soli.estado=="Aprobada" or soli.estado=="Terminada":
for i in soli.items:
v=i.item
while not v.lalinea:
v=getItemVerNum(v.item.id,v.version-1)
init_db()
lv=session.query(LB_Ver).filter(LB_Ver.ver_id==v.id).first()
ll=session.query(LineaBase).filter(LineaBase.id==lv.lb_id).first()
lineas[ll.id]=ll
shutdown_session()
if not(ll.id in lineas):
for vaux in ll.vers:
vn=getVersionId(vaux.ver_id)
colaitems.append(vn)
for i in colaitems:
if not(i.id in items):
items[i.id]=i
itm=i.item
if itm.lineabase:
lb=itm.lineabase
for n in lb.items:
nv=getVersionItem(n.id)
colaitems.append(nv)
for x in i.ante_list:
if x.ante.actual==True:
colaitems.append(x.ante)
for w in i.post_list:
if w.post.actual==True:
colaitems.append(w.post)
return items
def getItemsAfectados(ids=None):
"""
Retorna un diccionario con los items afectados por una solicitud de cambio, recibe el id de la solicitud de cambio
"""
soli=getPeticion(ids)
items={}
lineas={}
colaitems=[]
for i in soli.items:
v=i.item
colaitems.append(v)
if soli.estado=="Aprobada" or soli.estado=="Terminada":
for i in soli.items:
v=i.item
while not v.lalinea:
v=getItemVerNum(v.item.id,v.version-1)
init_db()
lv=session.query(LB_Ver).filter(LB_Ver.ver_id==v.id).first()
ll=session.query(LineaBase).filter(LineaBase.id==lv.lb_id).first()
lineas[ll.id]=ll
shutdown_session()
if not(ll.id in lineas):
for vaux in ll.vers:
vn=getVersionId(vaux.ver_id)
colaitems.append(vn)
for i in colaitems:
if not(i.id in items):
items[i.id]=i
itm=i.item
if itm.lineabase:
lb=itm.lineabase
for n in lb.items:
nv=getVersionItem(n.id)
colaitems.append(nv)
for w in i.post_list:
if w.post.actual==True:
colaitems.append(w.post)
return items
|
mglukhikh/intellij-community
|
refs/heads/master
|
python/testData/refactoring/introduceVariable/py2862.py
|
83
|
response = self._reqXml('PUT', <selection>'/import/' + urllib.quote(projectId) + '/issues?' +
urllib.urlencode({'assigneeGroup': assigneeGroup})</selection>,
xml, 400).toxml().encode('utf-8')
|
mahak/cinder
|
refs/heads/master
|
cinder/policies/snapshot_metadata.py
|
5
|
# Copyright (c) 2017 Huawei Technologies Co., Ltd.
# 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.
from oslo_policy import policy
from cinder.policies import base
GET_POLICY = 'volume:get_snapshot_metadata'
DELETE_POLICY = 'volume:delete_snapshot_metadata'
UPDATE_POLICY = 'volume:update_snapshot_metadata'
snapshot_metadata_policies = [
policy.DocumentedRuleDefault(
name=GET_POLICY,
check_str=base.RULE_ADMIN_OR_OWNER,
description="Show snapshot's metadata or one specified metadata "
"with a given key.",
operations=[
{
'method': 'GET',
'path': '/snapshots/{snapshot_id}/metadata'
},
{
'method': 'GET',
'path': '/snapshots/{snapshot_id}/metadata/{key}'
}
]),
policy.DocumentedRuleDefault(
name=UPDATE_POLICY,
check_str=base.RULE_ADMIN_OR_OWNER,
description="Update snapshot's metadata or one specified "
"metadata with a given key.",
operations=[
{
'method': 'PUT',
'path': '/snapshots/{snapshot_id}/metadata'
},
{
'method': 'PUT',
'path': '/snapshots/{snapshot_id}/metadata/{key}'
}
]),
policy.DocumentedRuleDefault(
name=DELETE_POLICY,
check_str=base.RULE_ADMIN_OR_OWNER,
description="Delete snapshot's specified metadata "
"with a given key.",
operations=[
{
'method': 'DELETE',
'path': '/snapshots/{snapshot_id}/metadata/{key}'
}
]),
]
def list_rules():
return snapshot_metadata_policies
|
adarob/magenta
|
refs/heads/master
|
magenta/models/nsynth/wavenet/fastgen.py
|
2
|
# Copyright 2019 The Magenta 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.
"""Utilities for "fast" wavenet generation with queues.
For more information, see:
Ramachandran, P., Le Paine, T., Khorrami, P., Babaeizadeh, M.,
Chang, S., Zhang, Y., ... Huang, T. (2017).
Fast Generation For Convolutional Autoregressive Models, 1-5.
"""
from magenta.models.nsynth import utils
from magenta.models.nsynth.wavenet.h512_bo16 import Config
from magenta.models.nsynth.wavenet.h512_bo16 import FastGenerationConfig
import numpy as np
from scipy.io import wavfile
import tensorflow as tf
def sample_categorical(probability_mass_function):
"""Sample from a categorical distribution.
Args:
probability_mass_function: Output of a softmax over categories.
Array of shape [batch_size, number of categories]. Rows sum to 1.
Returns:
idxs: Array of size [batch_size, 1]. Integer of category sampled.
"""
if probability_mass_function.ndim == 1:
probability_mass_function = np.expand_dims(probability_mass_function, 0)
batch_size = probability_mass_function.shape[0]
cumulative_density_function = np.cumsum(probability_mass_function, axis=1)
rand_vals = np.random.rand(batch_size)
idxs = np.zeros([batch_size, 1])
for i in range(batch_size):
idxs[i] = cumulative_density_function[i].searchsorted(rand_vals[i])
return idxs
def load_nsynth(batch_size=1, sample_length=64000):
"""Load the NSynth autoencoder network.
Args:
batch_size: Batch size number of observations to process. [1]
sample_length: Number of samples in the input audio. [64000]
Returns:
graph: The network as a dict with input placeholder in {"X"}
"""
config = Config()
with tf.device("/gpu:0"):
x = tf.placeholder(tf.float32, shape=[batch_size, sample_length])
graph = config.build({"wav": x}, is_training=False)
graph.update({"X": x})
return graph
def load_fastgen_nsynth(batch_size=1):
"""Load the NSynth fast generation network.
Args:
batch_size: Batch size number of observations to process. [1]
Returns:
graph: The network as a dict with input placeholder in {"X"}
"""
config = FastGenerationConfig(batch_size=batch_size)
with tf.device("/gpu:0"):
x = tf.placeholder(tf.float32, shape=[batch_size, 1])
graph = config.build({"wav": x})
graph.update({"X": x})
return graph
def encode(wav_data, checkpoint_path, sample_length=64000):
"""Generate an array of encodings from an array of audio.
Args:
wav_data: Numpy array [batch_size, sample_length]
checkpoint_path: Location of the pretrained model.
sample_length: The total length of the final wave file, padded with 0s.
Returns:
encoding: a [mb, 125, 16] encoding (for 64000 sample audio file).
"""
if wav_data.ndim == 1:
wav_data = np.expand_dims(wav_data, 0)
batch_size = wav_data.shape[0]
# Load up the model for encoding and find the encoding of "wav_data"
session_config = tf.ConfigProto(allow_soft_placement=True)
session_config.gpu_options.allow_growth = True
with tf.Graph().as_default(), tf.Session(config=session_config) as sess:
hop_length = Config().ae_hop_length
wav_data, sample_length = utils.trim_for_encoding(wav_data, sample_length,
hop_length)
net = load_nsynth(batch_size=batch_size, sample_length=sample_length)
saver = tf.train.Saver()
saver.restore(sess, checkpoint_path)
encodings = sess.run(net["encoding"], feed_dict={net["X"]: wav_data})
return encodings
def load_batch_audio(files, sample_length=64000):
"""Load a batch of audio from either .wav files.
Args:
files: A list of filepaths to .wav files.
sample_length: Maximum sample length
Returns:
batch: A padded array of audio [n_files, sample_length]
"""
batch = []
# Load the data
for f in files:
data = utils.load_audio(f, sample_length, sr=16000)
length = data.shape[0]
# Add padding if less than sample length
if length < sample_length:
padded = np.zeros([sample_length])
padded[:length] = data
batch.append(padded)
else:
batch.append(data)
# Return as an numpy array
batch = np.array(batch)
return batch
def load_batch_encodings(files, sample_length=125):
"""Load a batch of encodings from .npy files.
Args:
files: A list of filepaths to .npy files
sample_length: Maximum sample length
Raises:
ValueError: .npy array has wrong dimensions.
Returns:
batch: A padded array encodings [batch, length, dims]
"""
batch = []
# Load the data
for f in files:
data = np.load(f)
if data.ndim != 2:
raise ValueError("Encoding file should have 2 dims "
"[time, channels], not {}".format(data.ndim))
length, channels = data.shape
# Add padding or crop if not equal to sample length
if length < sample_length:
padded = np.zeros([sample_length, channels])
padded[:length, :] = data
batch.append(padded)
else:
batch.append(data[:sample_length])
# Return as an numpy array
batch = np.array(batch)
return batch
def save_batch(batch_audio, batch_save_paths):
for audio, name in zip(batch_audio, batch_save_paths):
tf.logging.info("Saving: %s" % name)
wavfile.write(name, 16000, audio)
def generate_audio_sample(sess, net, audio, encoding):
"""Generate a single sample of audio from an encoding.
Args:
sess: tf.Session to use.
net: Loaded wavenet network (dictionary of endpoint tensors).
audio: Previously generated audio [batch_size, 1].
encoding: Encoding at current time index [batch_size, dim].
Returns:
audio_gen: Generated audio [batch_size, 1]
"""
probability_mass_function = sess.run(
[net["predictions"], net["push_ops"]],
feed_dict={net["X"]: audio, net["encoding"]: encoding})[0]
sample_bin = sample_categorical(probability_mass_function)
audio_gen = utils.inv_mu_law_numpy(sample_bin - 128)
return audio_gen
def synthesize(encodings,
save_paths,
checkpoint_path="model.ckpt-200000",
samples_per_save=10000):
"""Synthesize audio from an array of encodings.
Args:
encodings: Numpy array with shape [batch_size, time, dim].
save_paths: Iterable of output file names.
checkpoint_path: Location of the pretrained model. [model.ckpt-200000]
samples_per_save: Save files after every amount of generated samples.
"""
session_config = tf.ConfigProto(allow_soft_placement=True)
session_config.gpu_options.allow_growth = True
with tf.Graph().as_default(), tf.Session(config=session_config) as sess:
net = load_fastgen_nsynth(batch_size=encodings.shape[0])
saver = tf.train.Saver()
saver.restore(sess, checkpoint_path)
# Get lengths
batch_size, encoding_length, _ = encodings.shape
hop_length = Config().ae_hop_length
total_length = encoding_length * hop_length
# initialize queues w/ 0s
sess.run(net["init_ops"])
# Regenerate the audio file sample by sample
audio_batch = np.zeros(
(batch_size, total_length), dtype=np.float32)
audio = np.zeros([batch_size, 1])
for sample_i in range(total_length):
encoding_i = sample_i // hop_length
audio = generate_audio_sample(sess, net,
audio, encodings[:, encoding_i, :])
audio_batch[:, sample_i] = audio[:, 0]
if sample_i % 100 == 0:
tf.logging.info("Sample: %d" % sample_i)
if sample_i % samples_per_save == 0 and save_paths:
save_batch(audio_batch, save_paths)
save_batch(audio_batch, save_paths)
|
JetBrains/intellij-community
|
refs/heads/master
|
python/helpers/py2only/docutils/writers/odf_odt/pygmentsformatter.py
|
244
|
# $Id: pygmentsformatter.py 5853 2009-01-19 21:02:02Z dkuhlman $
# Author: Dave Kuhlman <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
Additional support for Pygments formatter.
"""
import pygments
import pygments.formatter
class OdtPygmentsFormatter(pygments.formatter.Formatter):
def __init__(self, rststyle_function, escape_function):
pygments.formatter.Formatter.__init__(self)
self.rststyle_function = rststyle_function
self.escape_function = escape_function
def rststyle(self, name, parameters=( )):
return self.rststyle_function(name, parameters)
class OdtPygmentsProgFormatter(OdtPygmentsFormatter):
def format(self, tokensource, outfile):
tokenclass = pygments.token.Token
for ttype, value in tokensource:
value = self.escape_function(value)
if ttype == tokenclass.Keyword:
s2 = self.rststyle('codeblock-keyword')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Literal.String:
s2 = self.rststyle('codeblock-string')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype in (
tokenclass.Literal.Number.Integer,
tokenclass.Literal.Number.Integer.Long,
tokenclass.Literal.Number.Float,
tokenclass.Literal.Number.Hex,
tokenclass.Literal.Number.Oct,
tokenclass.Literal.Number,
):
s2 = self.rststyle('codeblock-number')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Operator:
s2 = self.rststyle('codeblock-operator')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Comment:
s2 = self.rststyle('codeblock-comment')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Name.Class:
s2 = self.rststyle('codeblock-classname')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Name.Function:
s2 = self.rststyle('codeblock-functionname')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Name:
s2 = self.rststyle('codeblock-name')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
else:
s1 = value
outfile.write(s1)
class OdtPygmentsLaTeXFormatter(OdtPygmentsFormatter):
def format(self, tokensource, outfile):
tokenclass = pygments.token.Token
for ttype, value in tokensource:
value = self.escape_function(value)
if ttype == tokenclass.Keyword:
s2 = self.rststyle('codeblock-keyword')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype in (tokenclass.Literal.String,
tokenclass.Literal.String.Backtick,
):
s2 = self.rststyle('codeblock-string')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Name.Attribute:
s2 = self.rststyle('codeblock-operator')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Comment:
if value[-1] == '\n':
s2 = self.rststyle('codeblock-comment')
s1 = '<text:span text:style-name="%s">%s</text:span>\n' % \
(s2, value[:-1], )
else:
s2 = self.rststyle('codeblock-comment')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
elif ttype == tokenclass.Name.Builtin:
s2 = self.rststyle('codeblock-name')
s1 = '<text:span text:style-name="%s">%s</text:span>' % \
(s2, value, )
else:
s1 = value
outfile.write(s1)
|
JCBarahona/edX
|
refs/heads/master
|
common/djangoapps/util/tests/test_keyword_sub_utils.py
|
130
|
"""
Tests for keyword_substitution.py
"""
from student.tests.factories import UserFactory
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from ddt import ddt, file_data
from mock import patch
from util.date_utils import get_default_time_display
from util import keyword_substitution as Ks
@ddt
class KeywordSubTest(ModuleStoreTestCase):
""" Tests for the keyword substitution feature """
def setUp(self):
super(KeywordSubTest, self).setUp(create_user=False)
self.user = UserFactory.create(
email="[email protected]",
username="testuser",
profile__name="Test User"
)
self.course = CourseFactory.create(
org='edx',
course='999',
display_name='test_course'
)
self.context = {
'user_id': self.user.id,
'course_title': self.course.display_name,
'name': self.user.profile.name,
'course_end_date': get_default_time_display(self.course.end),
}
@file_data('fixtures/test_keyword_coursename_sub.json')
def test_course_name_sub(self, test_info):
""" Tests subbing course name in various scenarios """
course_name = self.course.display_name
result = Ks.substitute_keywords_with_data(
test_info['test_string'], self.context,
)
self.assertIn(course_name, result)
self.assertEqual(result, test_info['expected'])
def test_anonymous_id_sub(self):
"""
Test that anonymous_id is subbed
"""
test_string = "Turn %%USER_ID%% into anonymous id"
anonymous_id = Ks.anonymous_id_from_user_id(self.user.id)
result = Ks.substitute_keywords_with_data(
test_string, self.context,
)
self.assertNotIn('%%USER_ID%%', result)
self.assertIn(anonymous_id, result)
def test_name_sub(self):
"""
Test that the user's full name is correctly subbed
"""
test_string = "This is the test string. subthis: %%USER_FULLNAME%% into user name"
user_name = self.user.profile.name
result = Ks.substitute_keywords_with_data(
test_string, self.context,
)
self.assertNotIn('%%USER_FULLNAME%%', result)
self.assertIn(user_name, result)
def test_illegal_subtag(self):
"""
Test that sub-ing doesn't ocurr with illegal tags
"""
test_string = "%%user_id%%"
result = Ks.substitute_keywords_with_data(
test_string, self.context,
)
self.assertEquals(test_string, result)
def test_should_not_sub(self):
"""
Test that sub-ing doesn't work without subtags
"""
test_string = "this string has no subtags"
result = Ks.substitute_keywords_with_data(
test_string, self.context,
)
self.assertEquals(test_string, result)
@file_data('fixtures/test_keywordsub_multiple_tags.json')
def test_sub_multiple_tags(self, test_info):
""" Test that subbing works with multiple subtags """
anon_id = '123456789'
with patch('util.keyword_substitution.anonymous_id_from_user_id', lambda user_id: anon_id):
result = Ks.substitute_keywords_with_data(
test_info['test_string'], self.context,
)
self.assertEqual(result, test_info['expected'])
def test_subbing_no_userid_or_courseid(self):
"""
Tests that no subbing occurs if no user_id or no course_id is given.
"""
test_string = 'This string should not be subbed here %%USER_ID%%'
no_course_context = dict(
(key, value) for key, value in self.context.iteritems() if key != 'course_title'
)
result = Ks.substitute_keywords_with_data(test_string, no_course_context)
self.assertEqual(test_string, result)
no_user_id_context = dict(
(key, value) for key, value in self.context.iteritems() if key != 'user_id'
)
result = Ks.substitute_keywords_with_data(test_string, no_user_id_context)
self.assertEqual(test_string, result)
|
ecoal95/servo
|
refs/heads/master
|
components/script/dom/bindings/codegen/parser/tests/test_interface_maplikesetlikeiterable.py
|
53
|
import WebIDL
import traceback
def WebIDLTest(parser, harness):
def shouldPass(prefix, iface, expectedMembers, numProductions=1):
p = parser.reset()
p.parse(iface)
results = p.finish()
harness.check(len(results), numProductions,
"%s - Should have production count %d" % (prefix, numProductions))
harness.ok(isinstance(results[0], WebIDL.IDLInterface),
"%s - Should be an IDLInterface" % (prefix))
# Make a copy, since we plan to modify it
expectedMembers = list(expectedMembers)
for m in results[0].members:
name = m.identifier.name
if (name, type(m)) in expectedMembers:
harness.ok(True, "%s - %s - Should be a %s" % (prefix, name,
type(m)))
expectedMembers.remove((name, type(m)))
else:
harness.ok(False, "%s - %s - Unknown symbol of type %s" %
(prefix, name, type(m)))
# A bit of a hoop because we can't generate the error string if we pass
if len(expectedMembers) == 0:
harness.ok(True, "Found all the members")
else:
harness.ok(False,
"Expected member not found: %s of type %s" %
(expectedMembers[0][0], expectedMembers[0][1]))
return results
def shouldFail(prefix, iface):
try:
p = parser.reset()
p.parse(iface)
p.finish()
harness.ok(False,
prefix + " - Interface passed when should've failed")
except WebIDL.WebIDLError, e:
harness.ok(True,
prefix + " - Interface failed as expected")
except Exception, e:
harness.ok(False,
prefix + " - Interface failed but not as a WebIDLError exception: %s" % e)
iterableMembers = [(x, WebIDL.IDLMethod) for x in ["entries", "keys",
"values", "forEach"]]
setROMembers = ([(x, WebIDL.IDLMethod) for x in ["has"]] +
[("__setlike", WebIDL.IDLMaplikeOrSetlike)] +
iterableMembers)
setROMembers.extend([("size", WebIDL.IDLAttribute)])
setRWMembers = ([(x, WebIDL.IDLMethod) for x in ["add",
"clear",
"delete"]] +
setROMembers)
setROChromeMembers = ([(x, WebIDL.IDLMethod) for x in ["__add",
"__clear",
"__delete"]] +
setROMembers)
setRWChromeMembers = ([(x, WebIDL.IDLMethod) for x in ["__add",
"__clear",
"__delete"]] +
setRWMembers)
mapROMembers = ([(x, WebIDL.IDLMethod) for x in ["get", "has"]] +
[("__maplike", WebIDL.IDLMaplikeOrSetlike)] +
iterableMembers)
mapROMembers.extend([("size", WebIDL.IDLAttribute)])
mapRWMembers = ([(x, WebIDL.IDLMethod) for x in ["set",
"clear",
"delete"]] + mapROMembers)
mapRWChromeMembers = ([(x, WebIDL.IDLMethod) for x in ["__set",
"__clear",
"__delete"]] +
mapRWMembers)
# OK, now that we've used iterableMembers to set up the above, append
# __iterable to it for the iterable<> case.
iterableMembers.append(("__iterable", WebIDL.IDLIterable))
valueIterableMembers = [("__iterable", WebIDL.IDLIterable)]
valueIterableMembers.append(("__indexedgetter", WebIDL.IDLMethod))
valueIterableMembers.append(("length", WebIDL.IDLAttribute))
disallowedIterableNames = ["keys", "entries", "values"]
disallowedMemberNames = ["forEach", "has", "size"] + disallowedIterableNames
mapDisallowedMemberNames = ["get"] + disallowedMemberNames
disallowedNonMethodNames = ["clear", "delete"]
mapDisallowedNonMethodNames = ["set"] + disallowedNonMethodNames
setDisallowedNonMethodNames = ["add"] + disallowedNonMethodNames
unrelatedMembers = [("unrelatedAttribute", WebIDL.IDLAttribute),
("unrelatedMethod", WebIDL.IDLMethod)]
#
# Simple Usage Tests
#
shouldPass("Iterable (key only)",
"""
interface Foo1 {
iterable<long>;
readonly attribute unsigned long length;
getter long(unsigned long index);
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", valueIterableMembers + unrelatedMembers)
shouldPass("Iterable (key only) inheriting from parent",
"""
interface Foo1 : Foo2 {
iterable<long>;
readonly attribute unsigned long length;
getter long(unsigned long index);
};
interface Foo2 {
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", valueIterableMembers, numProductions=2)
shouldPass("Iterable (key and value)",
"""
interface Foo1 {
iterable<long, long>;
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", iterableMembers + unrelatedMembers,
# numProductions == 2 because of the generated iterator iface,
numProductions=2)
shouldPass("Iterable (key and value) inheriting from parent",
"""
interface Foo1 : Foo2 {
iterable<long, long>;
};
interface Foo2 {
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", iterableMembers,
# numProductions == 3 because of the generated iterator iface,
numProductions=3)
shouldPass("Maplike (readwrite)",
"""
interface Foo1 {
maplike<long, long>;
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", mapRWMembers + unrelatedMembers)
shouldPass("Maplike (readwrite) inheriting from parent",
"""
interface Foo1 : Foo2 {
maplike<long, long>;
};
interface Foo2 {
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", mapRWMembers, numProductions=2)
shouldPass("Maplike (readwrite)",
"""
interface Foo1 {
maplike<long, long>;
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", mapRWMembers + unrelatedMembers)
shouldPass("Maplike (readwrite) inheriting from parent",
"""
interface Foo1 : Foo2 {
maplike<long, long>;
};
interface Foo2 {
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", mapRWMembers, numProductions=2)
shouldPass("Maplike (readonly)",
"""
interface Foo1 {
readonly maplike<long, long>;
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", mapROMembers + unrelatedMembers)
shouldPass("Maplike (readonly) inheriting from parent",
"""
interface Foo1 : Foo2 {
readonly maplike<long, long>;
};
interface Foo2 {
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", mapROMembers, numProductions=2)
shouldPass("Setlike (readwrite)",
"""
interface Foo1 {
setlike<long>;
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", setRWMembers + unrelatedMembers)
shouldPass("Setlike (readwrite) inheriting from parent",
"""
interface Foo1 : Foo2 {
setlike<long>;
};
interface Foo2 {
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", setRWMembers, numProductions=2)
shouldPass("Setlike (readonly)",
"""
interface Foo1 {
readonly setlike<long>;
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", setROMembers + unrelatedMembers)
shouldPass("Setlike (readonly) inheriting from parent",
"""
interface Foo1 : Foo2 {
readonly setlike<long>;
};
interface Foo2 {
attribute long unrelatedAttribute;
long unrelatedMethod();
};
""", setROMembers, numProductions=2)
shouldPass("Inheritance of maplike/setlike",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
};
""", mapRWMembers, numProductions=2)
shouldPass("Implements with maplike/setlike",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 {
};
Foo2 implements Foo1;
""", mapRWMembers, numProductions=3)
shouldPass("JS Implemented maplike interface",
"""
[JSImplementation="@mozilla.org/dom/test-interface-js-maplike;1",
Constructor()]
interface Foo1 {
setlike<long>;
};
""", setRWChromeMembers)
shouldPass("JS Implemented maplike interface",
"""
[JSImplementation="@mozilla.org/dom/test-interface-js-maplike;1",
Constructor()]
interface Foo1 {
maplike<long, long>;
};
""", mapRWChromeMembers)
#
# Multiple maplike/setlike tests
#
shouldFail("Two maplike/setlikes on same interface",
"""
interface Foo1 {
setlike<long>;
maplike<long, long>;
};
""")
shouldFail("Two iterable/setlikes on same interface",
"""
interface Foo1 {
iterable<long>;
maplike<long, long>;
};
""")
shouldFail("Two iterables on same interface",
"""
interface Foo1 {
iterable<long>;
iterable<long, long>;
};
""")
shouldFail("Two maplike/setlikes in partials",
"""
interface Foo1 {
maplike<long, long>;
};
partial interface Foo1 {
setlike<long>;
};
""")
shouldFail("Conflicting maplike/setlikes across inheritance",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
setlike<long>;
};
""")
shouldFail("Conflicting maplike/iterable across inheritance",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
iterable<long>;
};
""")
shouldFail("Conflicting maplike/setlikes across multistep inheritance",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
};
interface Foo3 : Foo2 {
setlike<long>;
};
""")
shouldFail("Consequential interface with conflicting maplike/setlike",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 {
setlike<long>;
};
Foo2 implements Foo1;
""")
shouldFail("Consequential interfaces with conflicting maplike/setlike",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 {
setlike<long>;
};
interface Foo3 {
};
Foo3 implements Foo1;
Foo3 implements Foo2;
""")
#
# Member name collision tests
#
def testConflictingMembers(likeMember, conflictName, expectedMembers, methodPasses):
"""
Tests for maplike/setlike member generation against conflicting member
names. If methodPasses is True, this means we expect the interface to
pass in the case of method shadowing, and expectedMembers should be the
list of interface members to check against on the passing interface.
"""
if methodPasses:
shouldPass("Conflicting method: %s and %s" % (likeMember, conflictName),
"""
interface Foo1 {
%s;
[Throws]
void %s(long test1, double test2, double test3);
};
""" % (likeMember, conflictName), expectedMembers)
else:
shouldFail("Conflicting method: %s and %s" % (likeMember, conflictName),
"""
interface Foo1 {
%s;
[Throws]
void %s(long test1, double test2, double test3);
};
""" % (likeMember, conflictName))
# Inherited conflicting methods should ALWAYS fail
shouldFail("Conflicting inherited method: %s and %s" % (likeMember, conflictName),
"""
interface Foo1 {
void %s(long test1, double test2, double test3);
};
interface Foo2 : Foo1 {
%s;
};
""" % (conflictName, likeMember))
shouldFail("Conflicting static method: %s and %s" % (likeMember, conflictName),
"""
interface Foo1 {
%s;
static void %s(long test1, double test2, double test3);
};
""" % (likeMember, conflictName))
shouldFail("Conflicting attribute: %s and %s" % (likeMember, conflictName),
"""
interface Foo1 {
%s
attribute double %s;
};
""" % (likeMember, conflictName))
shouldFail("Conflicting const: %s and %s" % (likeMember, conflictName),
"""
interface Foo1 {
%s;
const double %s = 0;
};
""" % (likeMember, conflictName))
shouldFail("Conflicting static attribute: %s and %s" % (likeMember, conflictName),
"""
interface Foo1 {
%s;
static attribute long %s;
};
""" % (likeMember, conflictName))
for member in disallowedIterableNames:
testConflictingMembers("iterable<long, long>", member, iterableMembers, False)
for member in mapDisallowedMemberNames:
testConflictingMembers("maplike<long, long>", member, mapRWMembers, False)
for member in disallowedMemberNames:
testConflictingMembers("setlike<long>", member, setRWMembers, False)
for member in mapDisallowedNonMethodNames:
testConflictingMembers("maplike<long, long>", member, mapRWMembers, True)
for member in setDisallowedNonMethodNames:
testConflictingMembers("setlike<long>", member, setRWMembers, True)
shouldPass("Inheritance of maplike/setlike with child member collision",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
void entries();
};
""", mapRWMembers, numProductions=2)
shouldPass("Inheritance of multi-level maplike/setlike with child member collision",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
};
interface Foo3 : Foo2 {
void entries();
};
""", mapRWMembers, numProductions=3)
shouldFail("Interface with consequential maplike/setlike interface member collision",
"""
interface Foo1 {
void entries();
};
interface Foo2 {
maplike<long, long>;
};
Foo1 implements Foo2;
""")
shouldFail("Maplike interface with consequential interface member collision",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 {
void entries();
};
Foo1 implements Foo2;
""")
shouldPass("Consequential Maplike interface with inherited interface member collision",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 {
void entries();
};
interface Foo3 : Foo2 {
};
Foo3 implements Foo1;
""", mapRWMembers, numProductions=4)
shouldPass("Inherited Maplike interface with consequential interface member collision",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 {
void entries();
};
interface Foo3 : Foo1 {
};
Foo3 implements Foo2;
""", mapRWMembers, numProductions=4)
shouldFail("Inheritance of name collision with child maplike/setlike",
"""
interface Foo1 {
void entries();
};
interface Foo2 : Foo1 {
maplike<long, long>;
};
""")
shouldFail("Inheritance of multi-level name collision with child maplike/setlike",
"""
interface Foo1 {
void entries();
};
interface Foo2 : Foo1 {
};
interface Foo3 : Foo2 {
maplike<long, long>;
};
""")
shouldPass("Inheritance of attribute collision with parent maplike/setlike",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
attribute double size;
};
""", mapRWMembers, numProductions=2)
shouldPass("Inheritance of multi-level attribute collision with parent maplike/setlike",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
};
interface Foo3 : Foo2 {
attribute double size;
};
""", mapRWMembers, numProductions=3)
shouldFail("Inheritance of attribute collision with child maplike/setlike",
"""
interface Foo1 {
attribute double size;
};
interface Foo2 : Foo1 {
maplike<long, long>;
};
""")
shouldFail("Inheritance of multi-level attribute collision with child maplike/setlike",
"""
interface Foo1 {
attribute double size;
};
interface Foo2 : Foo1 {
};
interface Foo3 : Foo2 {
maplike<long, long>;
};
""")
shouldFail("Inheritance of attribute/rw function collision with child maplike/setlike",
"""
interface Foo1 {
attribute double set;
};
interface Foo2 : Foo1 {
maplike<long, long>;
};
""")
shouldFail("Inheritance of const/rw function collision with child maplike/setlike",
"""
interface Foo1 {
const double set = 0;
};
interface Foo2 : Foo1 {
maplike<long, long>;
};
""")
shouldPass("Inheritance of rw function with same name in child maplike/setlike",
"""
interface Foo1 {
maplike<long, long>;
};
interface Foo2 : Foo1 {
void clear();
};
""", mapRWMembers, numProductions=2)
shouldFail("Inheritance of unforgeable attribute collision with child maplike/setlike",
"""
interface Foo1 {
[Unforgeable]
attribute double size;
};
interface Foo2 : Foo1 {
maplike<long, long>;
};
""")
shouldFail("Inheritance of multi-level unforgeable attribute collision with child maplike/setlike",
"""
interface Foo1 {
[Unforgeable]
attribute double size;
};
interface Foo2 : Foo1 {
};
interface Foo3 : Foo2 {
maplike<long, long>;
};
""")
shouldPass("Implemented interface with readonly allowable overrides",
"""
interface Foo1 {
readonly setlike<long>;
readonly attribute boolean clear;
};
""", setROMembers + [("clear", WebIDL.IDLAttribute)])
shouldPass("JS Implemented read-only interface with readonly allowable overrides",
"""
[JSImplementation="@mozilla.org/dom/test-interface-js-maplike;1",
Constructor()]
interface Foo1 {
readonly setlike<long>;
readonly attribute boolean clear;
};
""", setROChromeMembers + [("clear", WebIDL.IDLAttribute)])
shouldFail("JS Implemented read-write interface with non-readwrite allowable overrides",
"""
[JSImplementation="@mozilla.org/dom/test-interface-js-maplike;1",
Constructor()]
interface Foo1 {
setlike<long>;
readonly attribute boolean clear;
};
""")
r = shouldPass("Check proper override of clear/delete/set",
"""
interface Foo1 {
maplike<long, long>;
long clear(long a, long b, double c, double d);
long set(long a, long b, double c, double d);
long delete(long a, long b, double c, double d);
};
""", mapRWMembers)
for m in r[0].members:
if m.identifier.name in ["clear", "set", "delete"]:
harness.ok(m.isMethod(), "%s should be a method" % m.identifier.name)
harness.check(m.maxArgCount, 4, "%s should have 4 arguments" % m.identifier.name)
harness.ok(not m.isMaplikeOrSetlikeOrIterableMethod(),
"%s should not be a maplike/setlike function" % m.identifier.name)
|
areriff/pythonlearncanvas
|
refs/heads/master
|
Python Script Sample/portscanner.py
|
1
|
# Script Name : portscanner.py
# Author : Craig Richards
# Created : 20 May 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Port Scanner, you just pass the host and the ports
import optparse # Import the module
from socket import * # Import the module
from threading import * # Import the module
screenLock = Semaphore(value=1) # Prevent other threads from preceeding
def connScan(tgtHost, tgtPort): # Start of the function
try:
connSkt = socket(AF_INET, SOCK_STREAM) # Open a socket
connSkt.connect((tgtHost, tgtPort))
connSkt.send('')
results = connSkt.recv(100)
screenLock.acquire() # Acquire the lock
print
'[+] %d/tcp open' % tgtPort
print
'[+] ' + str(results)
except:
screenLock.acquire()
print
'[-] %d/tcp closed ' % tgtPort
finally:
screenLock.release()
connSkt.close()
def portScan(tgtHost, tgtPorts): # Start of the function
try:
tgtIP = gethostbyname(tgtHost) # Get the IP from the hostname
except:
print
"[-] Cannot resolve '%s': Unknown host" % tgtHost
return
try:
tgtName = gethostbyaddr(tgtIP) # Get hostname from IP
print
'\n[+] Scan Results for: ' + tgtName[0]
except:
print
'\n[+] Scan Results for: ' + tgtIP
setdefaulttimeout(1)
for tgtPort in tgtPorts: # Scan host and ports
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
t.start()
def main():
parser = optparse.OptionParser('usage %prog -H' + ' <target host> -p <target port>')
parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] seperated by a comma')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if (tgtHost == None) | (tgtPorts[0] == None):
print
parser.usage
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()
|
chauhanhardik/populo_2
|
refs/heads/master
|
common/lib/xmodule/xmodule/tests/test_bulk_assertions.py
|
173
|
import ddt
import itertools
from xmodule.tests import BulkAssertionTest, BulkAssertionError
STATIC_PASSING_ASSERTIONS = (
('assertTrue', True),
('assertFalse', False),
('assertIs', 1, 1),
('assertEqual', 1, 1),
('assertEquals', 1, 1),
('assertIsNot', 1, 2),
('assertIsNone', None),
('assertIsNotNone', 1),
('assertIn', 1, (1, 2, 3)),
('assertNotIn', 5, (1, 2, 3)),
('assertIsInstance', 1, int),
('assertNotIsInstance', '1', int),
('assertItemsEqual', [1, 2, 3], [3, 2, 1])
)
STATIC_FAILING_ASSERTIONS = (
('assertTrue', False),
('assertFalse', True),
('assertIs', 1, 2),
('assertEqual', 1, 2),
('assertEquals', 1, 2),
('assertIsNot', 1, 1),
('assertIsNone', 1),
('assertIsNotNone', None),
('assertIn', 5, (1, 2, 3)),
('assertNotIn', 1, (1, 2, 3)),
('assertIsInstance', '1', int),
('assertNotIsInstance', 1, int),
('assertItemsEqual', [1, 1, 1], [1, 1])
)
CONTEXT_PASSING_ASSERTIONS = (
('assertRaises', KeyError, {}.__getitem__, '1'),
('assertRaisesRegexp', KeyError, "1", {}.__getitem__, '1'),
)
CONTEXT_FAILING_ASSERTIONS = (
('assertRaises', ValueError, lambda: None),
('assertRaisesRegexp', KeyError, "2", {}.__getitem__, '1'),
)
@ddt.ddt
class TestBulkAssertionTestCase(BulkAssertionTest):
# We have to use assertion methods from the base UnitTest class,
# so we make a number of super calls that skip BulkAssertionTest.
# pylint: disable=bad-super-call
def _run_assertion(self, assertion_tuple):
"""
Run the supplied tuple of (assertion, *args) as a method on this class.
"""
assertion, args = assertion_tuple[0], assertion_tuple[1:]
getattr(self, assertion)(*args)
def _raw_assert(self, assertion_name, *args, **kwargs):
"""
Run an un-modified assertion.
"""
# Use super(BulkAssertionTest) to make sure we get un-adulturated assertions
return getattr(super(BulkAssertionTest, self), 'assert' + assertion_name)(*args, **kwargs)
@ddt.data(*(STATIC_PASSING_ASSERTIONS + CONTEXT_PASSING_ASSERTIONS))
def test_passing_asserts_passthrough(self, assertion_tuple):
self._run_assertion(assertion_tuple)
@ddt.data(*(STATIC_FAILING_ASSERTIONS + CONTEXT_FAILING_ASSERTIONS))
def test_failing_asserts_passthrough(self, assertion_tuple):
with self._raw_assert('Raises', AssertionError) as context:
self._run_assertion(assertion_tuple)
self._raw_assert('NotIsInstance', context.exception, BulkAssertionError)
@ddt.data(*CONTEXT_PASSING_ASSERTIONS)
@ddt.unpack
def test_passing_context_assertion_passthrough(self, assertion, *args):
assertion_args = []
args = list(args)
exception = args.pop(0)
while not callable(args[0]):
assertion_args.append(args.pop(0))
function = args.pop(0)
with getattr(self, assertion)(exception, *assertion_args):
function(*args)
@ddt.data(*CONTEXT_FAILING_ASSERTIONS)
@ddt.unpack
def test_failing_context_assertion_passthrough(self, assertion, *args):
assertion_args = []
args = list(args)
exception = args.pop(0)
while not callable(args[0]):
assertion_args.append(args.pop(0))
function = args.pop(0)
with self._raw_assert('Raises', AssertionError) as context:
with getattr(self, assertion)(exception, *assertion_args):
function(*args)
self._raw_assert('NotIsInstance', context.exception, BulkAssertionError)
@ddt.data(*list(itertools.product(
CONTEXT_PASSING_ASSERTIONS,
CONTEXT_FAILING_ASSERTIONS,
CONTEXT_FAILING_ASSERTIONS
)))
@ddt.unpack
def test_bulk_assert(self, passing_assertion, failing_assertion1, failing_assertion2):
contextmanager = self.bulk_assertions()
contextmanager.__enter__()
self._run_assertion(passing_assertion)
self._run_assertion(failing_assertion1)
self._run_assertion(failing_assertion2)
with self._raw_assert('Raises', BulkAssertionError) as context:
contextmanager.__exit__(None, None, None)
self._raw_assert('Equals', len(context.exception.errors), 2)
@ddt.data(*list(itertools.product(
CONTEXT_FAILING_ASSERTIONS
)))
@ddt.unpack
def test_nested_bulk_asserts(self, failing_assertion):
with self._raw_assert('Raises', BulkAssertionError) as context:
with self.bulk_assertions():
self._run_assertion(failing_assertion)
with self.bulk_assertions():
self._run_assertion(failing_assertion)
self._run_assertion(failing_assertion)
self._raw_assert('Equal', len(context.exception.errors), 3)
@ddt.data(*list(itertools.product(
CONTEXT_PASSING_ASSERTIONS,
CONTEXT_FAILING_ASSERTIONS,
CONTEXT_FAILING_ASSERTIONS
)))
@ddt.unpack
def test_bulk_assert_closed(self, passing_assertion, failing_assertion1, failing_assertion2):
with self._raw_assert('Raises', BulkAssertionError) as context:
with self.bulk_assertions():
self._run_assertion(passing_assertion)
self._run_assertion(failing_assertion1)
self._raw_assert('Equals', len(context.exception.errors), 1)
with self._raw_assert('Raises', AssertionError) as context:
self._run_assertion(failing_assertion2)
self._raw_assert('NotIsInstance', context.exception, BulkAssertionError)
|
procoder317/scikit-learn
|
refs/heads/master
|
sklearn/externals/joblib/_memory_helpers.py
|
303
|
try:
# Available in Python 3
from tokenize import open as open_py_source
except ImportError:
# Copied from python3 tokenize
from codecs import lookup, BOM_UTF8
import re
from io import TextIOWrapper, open
cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c."""
# Only care about the first 12 characters.
enc = orig_enc[:12].lower().replace("_", "-")
if enc == "utf-8" or enc.startswith("utf-8-"):
return "utf-8"
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
return "iso-8859-1"
return orig_enc
def _detect_encoding(readline):
"""
The detect_encoding() function is used to detect the encoding that
should be used to decode a Python source file. It requires one
argment, readline, in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used
(as a string) and a list of any lines (left as bytes) it has read in.
It detects the encoding from the presence of a utf-8 bom or an encoding
cookie as specified in pep-0263. If both a bom and a cookie are
present, but disagree, a SyntaxError will be raised. If the encoding
cookie is an invalid charset, raise a SyntaxError. Note that if a
utf-8 bom is found, 'utf-8-sig' is returned.
If no encoding is specified, then the default of 'utf-8' will be
returned.
"""
bom_found = False
encoding = None
default = 'utf-8'
def read_or_stop():
try:
return readline()
except StopIteration:
return b''
def find_cookie(line):
try:
line_string = line.decode('ascii')
except UnicodeDecodeError:
return None
matches = cookie_re.findall(line_string)
if not matches:
return None
encoding = _get_normal_name(matches[0])
try:
codec = lookup(encoding)
except LookupError:
# This behaviour mimics the Python interpreter
raise SyntaxError("unknown encoding: " + encoding)
if bom_found:
if codec.name != 'utf-8':
# This behaviour mimics the Python interpreter
raise SyntaxError('encoding problem: utf-8')
encoding += '-sig'
return encoding
first = read_or_stop()
if first.startswith(BOM_UTF8):
bom_found = True
first = first[3:]
default = 'utf-8-sig'
if not first:
return default, []
encoding = find_cookie(first)
if encoding:
return encoding, [first]
second = read_or_stop()
if not second:
return default, [first]
encoding = find_cookie(second)
if encoding:
return encoding, [first, second]
return default, [first, second]
def open_py_source(filename):
"""Open a file in read only mode using the encoding detected by
detect_encoding().
"""
buffer = open(filename, 'rb')
encoding, lines = _detect_encoding(buffer.readline)
buffer.seek(0)
text = TextIOWrapper(buffer, encoding, line_buffering=True)
text.mode = 'r'
return text
|
PX4/Firmware
|
refs/heads/master
|
src/lib/parameters/px4params/srcparser.py
|
2
|
import sys
import re
import math
global default_var
default_var = {}
class ParameterGroup(object):
"""
Single parameter group
"""
def __init__(self, name):
self.name = name
self.no_code_generation = False #for injected parameters
self.params = []
def AddParameter(self, param):
"""
Add parameter to the group
"""
self.params.append(param)
def GetName(self):
"""
Get parameter group name
"""
return self.name
def GetParams(self):
"""
Returns the parsed list of parameters. Every parameter is a Parameter
object. Note that returned object is not a copy. Modifications affect
state of the parser.
"""
return sorted(self.params, key=lambda param: param.name)
class Parameter(object):
"""
Single parameter
"""
# Define sorting order of the fields
priority = {
"board": 9,
"short_desc": 8,
"long_desc": 7,
"min": 5,
"max": 4,
"unit": 3,
"decimal": 2,
# all others == 0 (sorted alphabetically)
}
def __init__(self, name, type, default = ""):
self.fields = {}
self.values = {}
self.bitmask = {}
self.name = name
self.type = type
self.default = default
self.volatile = "false"
self.category = ""
self.boolean = False
def GetName(self):
return self.name
def GetType(self):
return self.type
def GetDefault(self):
return self.default
def GetCategory(self):
return self.category.title()
def GetVolatile(self):
return self.volatile
def GetBoolean(self):
return self.boolean
def SetField(self, code, value):
"""
Set named field value
"""
self.fields[code] = value
def SetEnumValue(self, code, value):
"""
Set named enum value
"""
self.values[code] = value
def SetBitmaskBit(self, index, bit):
"""
Set named enum value
"""
self.bitmask[index] = bit
def SetVolatile(self):
"""
Set volatile flag
"""
self.volatile = "true"
def SetBoolean(self):
"""
Set boolean flag
"""
self.boolean = True
def SetCategory(self, category):
"""
Set param category
"""
self.category = category
def GetFieldCodes(self):
"""
Return list of existing field codes in convenient order
"""
keys = self.fields.keys()
keys = sorted(keys)
keys = sorted(keys, key=lambda x: self.priority.get(x, 0), reverse=True)
return keys
def GetFieldValue(self, code):
"""
Return value of the given field code or None if not found.
"""
fv = self.fields.get(code)
if not fv:
# required because python 3 sorted does not accept None
return ""
return fv
def GetEnumCodes(self):
"""
Return list of existing value codes in convenient order
"""
return sorted(self.values.keys(), key=float)
def GetEnumValue(self, code):
"""
Return value of the given enum code or None if not found.
"""
fv = self.values.get(code)
if not fv:
# required because python 3 sorted does not accept None
return ""
return fv
def GetBitmaskList(self):
"""
Return list of existing bitmask codes in convenient order
"""
keys = self.bitmask.keys()
return sorted(keys, key=float)
def GetBitmaskBit(self, index):
"""
Return value of the given bitmask code or None if not found.
"""
fv = self.bitmask.get(index)
if not fv:
# required because python 3 sorted does not accept None
return ""
return fv
class SourceParser(object):
"""
Parses provided data and stores all found parameters internally.
"""
re_split_lines = re.compile(r'[\r\n]+')
re_comment_start = re.compile(r'^\/\*\*')
re_comment_content = re.compile(r'^\*\s*(.*)')
re_comment_tag = re.compile(r'@([a-zA-Z][a-zA-Z0-9_]*)\s*(.*)')
re_comment_end = re.compile(r'(.*?)\s*\*\/')
re_parameter_definition = re.compile(r'PARAM_DEFINE_([A-Z_][A-Z0-9_]*)\s*\(([A-Z_][A-Z0-9_]*)\s*,\s*([^ ,\)]+)\s*\)\s*;')
re_px4_parameter_definition = re.compile(r'PX4_PARAM_DEFINE_([A-Z_][A-Z0-9_]*)\s*\(([A-Z_][A-Z0-9_]*)\s*\)\s*;')
re_px4_param_default_definition = re.compile(r'#define\s*PARAM_([A-Z_][A-Z0-9_]*)\s*([^ ,\)]+)\s*')
re_cut_type_specifier = re.compile(r'[a-z]+$')
re_is_a_number = re.compile(r'^-?[0-9\.]')
re_remove_dots = re.compile(r'\.+$')
re_remove_carriage_return = re.compile('\n+')
valid_tags = set(["group", "board", "min", "max", "unit", "decimal", "increment", "reboot_required", "value", "boolean", "bit", "category", "volatile"])
# Order of parameter groups
priority = {
# All other groups = 0 (sort alphabetically)
"Miscellaneous": -10
}
def __init__(self):
self.param_groups = {}
def Parse(self, contents):
"""
Incrementally parse program contents and append all found parameters
to the list.
"""
# This code is essentially a comment-parsing grammar. "state"
# represents parser state. It contains human-readable state
# names.
state = None
for line in self.re_split_lines.split(contents):
line = line.strip()
# Ignore empty lines
if line == "":
continue
if self.re_comment_start.match(line):
state = "wait-short"
short_desc = None
long_desc = None
tags = {}
def_values = {}
def_bitmask = {}
elif state is not None and state != "comment-processed":
m = self.re_comment_end.search(line)
if m:
line = m.group(1)
last_comment_line = True
else:
last_comment_line = False
m = self.re_comment_content.match(line)
if m:
comment_content = m.group(1)
if comment_content == "":
# When short comment ends with empty comment line,
# start waiting for the next part - long comment.
if state == "wait-short-end":
state = "wait-long"
else:
m = self.re_comment_tag.match(comment_content)
if m:
tag, desc = m.group(1, 2)
if (tag == "value"):
# Take the meta info string and split the code and description
metainfo = desc.split(" ", 1)
def_values[metainfo[0]] = metainfo[1]
elif (tag == "bit"):
# Take the meta info string and split the code and description
metainfo = desc.split(" ", 1)
def_bitmask[metainfo[0]] = metainfo[1]
else:
tags[tag] = desc
current_tag = tag
state = "wait-tag-end"
elif state == "wait-short":
# Store first line of the short description
short_desc = comment_content
state = "wait-short-end"
elif state == "wait-short-end":
# Append comment line to the short description
short_desc += "\n" + comment_content
elif state == "wait-long":
# Store first line of the long description
long_desc = comment_content
state = "wait-long-end"
elif state == "wait-long-end":
# Append comment line to the long description
long_desc += "\n" + comment_content
elif state == "wait-tag-end":
# Append comment line to the tag text
tags[current_tag] += "\n" + comment_content
else:
raise AssertionError(
"Invalid parser state: %s" % state)
elif not last_comment_line:
# Invalid comment line (inside comment, but not starting with
# "*" or "*/". Reset parsed content.
state = None
if last_comment_line:
state = "comment-processed"
else:
tp = None
name = None
defval = ""
# Non-empty line outside the comment
m = self.re_px4_param_default_definition.match(line)
# Default value handling
if m:
name_m, defval_m = m.group(1,2)
default_var[name_m] = defval_m
m = self.re_parameter_definition.match(line)
if m:
tp, name, defval = m.group(1, 2, 3)
else:
m = self.re_px4_parameter_definition.match(line)
if m:
tp, name = m.group(1, 2)
if (name+'_DEFAULT') in default_var:
defval = default_var[name+'_DEFAULT']
if tp is not None:
# Remove trailing type specifier from numbers: 0.1f => 0.1
if defval != "" and self.re_is_a_number.match(defval):
defval = self.re_cut_type_specifier.sub('', defval)
param = Parameter(name, tp, defval)
param.SetField("short_desc", name)
# If comment was found before the parameter declaration,
# inject its data into the newly created parameter.
group = "Miscellaneous"
if state == "comment-processed":
if short_desc is not None:
param.SetField("short_desc", self.re_remove_dots.sub('', short_desc))
if long_desc is not None:
long_desc = self.re_remove_carriage_return.sub(' ', long_desc)
param.SetField("long_desc", long_desc)
for tag in tags:
if tag == "group":
group = tags[tag]
elif tag == "volatile":
param.SetVolatile()
elif tag == "category":
param.SetCategory(tags[tag])
elif tag == "boolean":
param.SetBoolean()
elif tag not in self.valid_tags:
sys.stderr.write("Skipping invalid documentation tag: '%s'\n" % tag)
return False
else:
param.SetField(tag, tags[tag])
for def_value in def_values:
param.SetEnumValue(def_value, def_values[def_value])
for def_bit in def_bitmask:
param.SetBitmaskBit(def_bit, def_bitmask[def_bit])
# Store the parameter
if group not in self.param_groups:
self.param_groups[group] = ParameterGroup(group)
self.param_groups[group].AddParameter(param)
state = None
return True
def IsNumber(self, numberString):
try:
float(numberString)
return True
except ValueError:
return False
def Validate(self):
"""
Validates the parameter meta data.
"""
seenParamNames = []
#allowedUnits should match set defined in /Firmware/validation/module_schema.yaml
allowedUnits = set ([
'%', 'Hz', 'mAh',
'rad', '%/rad', 'rad/s', 'rad/s^2', '%/rad/s', 'rad s^2/m','rad s/m',
'bit/s', 'B/s',
'deg', 'deg*1e7', 'deg/s',
'celcius', 'gauss', 'gauss/s', 'gauss^2',
'hPa', 'kg', 'kg/m^2', 'kg m^2',
'mm', 'm', 'm/s', 'm^2', 'm/s^2', 'm/s^3', 'm/s^2/sqrt(Hz)', 'm/s/rad',
'Ohm', 'V',
'us', 'ms', 's',
'S', 'A/%', '(m/s^2)^2', 'm/m', 'tan(rad)^2', '(m/s)^2', 'm/rad',
'm/s^3/sqrt(Hz)', 'm/s/sqrt(Hz)', 's/(1000*PWM)', '%m/s', 'min', 'us/C',
'N/(m/s)', 'Nm/(rad/s)', 'Nm', 'N',
'normalized_thrust/s', 'normalized_thrust', 'norm', 'SD',''])
for group in self.GetParamGroups():
for param in group.GetParams():
name = param.GetName()
if len(name) > 16:
sys.stderr.write("Parameter Name {0} is too long (Limit is 16)\n".format(name))
return False
board = param.GetFieldValue("board")
# Check for duplicates
name_plus_board = name + "+" + board
for seenParamName in seenParamNames:
if seenParamName == name_plus_board:
sys.stderr.write("Duplicate parameter definition: {0}\n".format(name_plus_board))
return False
seenParamNames.append(name_plus_board)
# Validate values
default = param.GetDefault()
min = param.GetFieldValue("min")
max = param.GetFieldValue("max")
units = param.GetFieldValue("unit")
if units not in allowedUnits:
sys.stderr.write("Invalid unit in {0}: {1}\n".format(name, units))
return False
#sys.stderr.write("{0} default:{1} min:{2} max:{3}\n".format(name, default, min, max))
if default != "" and not self.IsNumber(default):
sys.stderr.write("Default value not number: {0} {1}\n".format(name, default))
return False
# if default != "" and "." not in default:
# sys.stderr.write("Default value does not contain dot (e.g. 10 needs to be written as 10.0): {0} {1}\n".format(name, default))
# return False
if min != "":
if not self.IsNumber(min):
sys.stderr.write("Min value not number: {0} {1}\n".format(name, min))
return False
if default != "" and float(default) < float(min):
sys.stderr.write("Default value is smaller than min: {0} default:{1} min:{2}\n".format(name, default, min))
return False
if max != "":
if not self.IsNumber(max):
sys.stderr.write("Max value not number: {0} {1}\n".format(name, max))
return False
if default != "" and float(default) > float(max):
sys.stderr.write("Default value is larger than max: {0} default:{1} max:{2}\n".format(name, default, max))
return False
for code in param.GetEnumCodes():
if not self.IsNumber(code):
sys.stderr.write("Min value not number: {0} {1}\n".format(name, code))
return False
if param.GetEnumValue(code) == "":
sys.stderr.write("Description for enum value is empty: {0} {1}\n".format(name, code))
return False
for index in param.GetBitmaskList():
if not self.IsNumber(index):
sys.stderr.write("bit value not number: {0} {1}\n".format(name, index))
return False
if not int(min) <= math.pow(2, int(index)) <= int(max):
sys.stderr.write("Bitmask bit must be between {0} and {1}: {2} {3}\n".format(min, max, name, math.pow(2, int(index))))
return False
if param.GetBitmaskBit(index) == "":
sys.stderr.write("Description for bitmask bit is empty: {0} {1}\n".format(name, index))
return False
return True
def GetParamGroups(self):
"""
Returns the parsed list of parameters. Every parameter is a Parameter
object. Note that returned object is not a copy. Modifications affect
state of the parser.
"""
groups = self.param_groups.values()
groups = sorted(groups, key=lambda x: x.GetName())
groups = sorted(groups, key=lambda x: self.priority.get(x.GetName(), 0), reverse=True)
return groups
|
wyom/sympy
|
refs/heads/master
|
sympy/vector/functions.py
|
66
|
from sympy.vector.coordsysrect import CoordSysCartesian
from sympy.vector.dyadic import Dyadic
from sympy.vector.vector import Vector, BaseVector
from sympy.vector.scalar import BaseScalar
from sympy import sympify, diff, integrate, S
def express(expr, system, system2=None, variables=False):
"""
Global function for 'express' functionality.
Re-expresses a Vector, Dyadic or scalar(sympyfiable) in the given
coordinate system.
If 'variables' is True, then the coordinate variables (base scalars)
of other coordinate systems present in the vector/scalar field or
dyadic are also substituted in terms of the base scalars of the
given system.
Parameters
==========
expr : Vector/Dyadic/scalar(sympyfiable)
The expression to re-express in CoordSysCartesian 'system'
system: CoordSysCartesian
The coordinate system the expr is to be expressed in
system2: CoordSysCartesian
The other coordinate system required for re-expression
(only for a Dyadic Expr)
variables : boolean
Specifies whether to substitute the coordinate variables present
in expr, in terms of those of parameter system
Examples
========
>>> from sympy.vector import CoordSysCartesian
>>> from sympy import Symbol, cos, sin
>>> N = CoordSysCartesian('N')
>>> q = Symbol('q')
>>> B = N.orient_new_axis('B', q, N.k)
>>> from sympy.vector import express
>>> express(B.i, N)
(cos(q))*N.i + (sin(q))*N.j
>>> express(N.x, B, variables=True)
B.x*cos(q) - B.y*sin(q)
>>> d = N.i.outer(N.i)
>>> express(d, B, N) == (cos(q))*(B.i|N.i) + (-sin(q))*(B.j|N.i)
True
"""
if expr == 0 or expr == Vector.zero:
return expr
if not isinstance(system, CoordSysCartesian):
raise TypeError("system should be a CoordSysCartesian \
instance")
if isinstance(expr, Vector):
if system2 is not None:
raise ValueError("system2 should not be provided for \
Vectors")
#Given expr is a Vector
if variables:
#If variables attribute is True, substitute
#the coordinate variables in the Vector
system_list = []
for x in expr.atoms():
if (isinstance(x, (BaseScalar, BaseVector))
and x.system != system):
system_list.append(x.system)
system_list = set(system_list)
subs_dict = {}
for f in system_list:
subs_dict.update(f.scalar_map(system))
expr = expr.subs(subs_dict)
#Re-express in this coordinate system
outvec = Vector.zero
parts = expr.separate()
for x in parts:
if x != system:
temp = system.rotation_matrix(x) * parts[x].to_matrix(x)
outvec += matrix_to_vector(temp, system)
else:
outvec += parts[x]
return outvec
elif isinstance(expr, Dyadic):
if system2 is None:
system2 = system
if not isinstance(system2, CoordSysCartesian):
raise TypeError("system2 should be a CoordSysCartesian \
instance")
outdyad = Dyadic.zero
var = variables
for k, v in expr.components.items():
outdyad += (express(v, system, variables=var) *
(express(k.args[0], system, variables=var) |
express(k.args[1], system2, variables=var)))
return outdyad
else:
if system2 is not None:
raise ValueError("system2 should not be provided for \
Vectors")
if variables:
#Given expr is a scalar field
system_set = set([])
expr = sympify(expr)
#Subsitute all the coordinate variables
for x in expr.atoms():
if isinstance(x, BaseScalar)and x.system != system:
system_set.add(x.system)
subs_dict = {}
for f in system_set:
subs_dict.update(f.scalar_map(system))
return expr.subs(subs_dict)
return expr
def curl(vect, coord_sys):
"""
Returns the curl of a vector field computed wrt the base scalars
of the given coordinate system.
Parameters
==========
vect : Vector
The vector operand
coord_sys : CoordSysCartesian
The coordinate system to calculate the curl in
Examples
========
>>> from sympy.vector import CoordSysCartesian, curl
>>> R = CoordSysCartesian('R')
>>> v1 = R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k
>>> curl(v1, R)
0
>>> v2 = R.x*R.y*R.z*R.i
>>> curl(v2, R)
R.x*R.y*R.j + (-R.x*R.z)*R.k
"""
return coord_sys.delop.cross(vect).doit()
def divergence(vect, coord_sys):
"""
Returns the divergence of a vector field computed wrt the base
scalars of the given coordinate system.
Parameters
==========
vect : Vector
The vector operand
coord_sys : CoordSysCartesian
The cooordinate system to calculate the divergence in
Examples
========
>>> from sympy.vector import CoordSysCartesian, divergence
>>> R = CoordSysCartesian('R')
>>> v1 = R.x*R.y*R.z * (R.i+R.j+R.k)
>>> divergence(v1, R)
R.x*R.y + R.x*R.z + R.y*R.z
>>> v2 = 2*R.y*R.z*R.j
>>> divergence(v2, R)
2*R.z
"""
return coord_sys.delop.dot(vect).doit()
def gradient(scalar, coord_sys):
"""
Returns the vector gradient of a scalar field computed wrt the
base scalars of the given coordinate system.
Parameters
==========
scalar : SymPy Expr
The scalar field to compute the gradient of
coord_sys : CoordSysCartesian
The coordinate system to calculate the gradient in
Examples
========
>>> from sympy.vector import CoordSysCartesian, gradient
>>> R = CoordSysCartesian('R')
>>> s1 = R.x*R.y*R.z
>>> gradient(s1, R)
R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k
>>> s2 = 5*R.x**2*R.z
>>> gradient(s2, R)
10*R.x*R.z*R.i + 5*R.x**2*R.k
"""
return coord_sys.delop(scalar).doit()
def is_conservative(field):
"""
Checks if a field is conservative.
Paramaters
==========
field : Vector
The field to check for conservative property
Examples
========
>>> from sympy.vector import CoordSysCartesian
>>> from sympy.vector import is_conservative
>>> R = CoordSysCartesian('R')
>>> is_conservative(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k)
True
>>> is_conservative(R.z*R.j)
False
"""
#Field is conservative irrespective of system
#Take the first coordinate system in the result of the
#separate method of Vector
if not isinstance(field, Vector):
raise TypeError("field should be a Vector")
if field == Vector.zero:
return True
coord_sys = list(field.separate())[0]
return curl(field, coord_sys).simplify() == Vector.zero
def is_solenoidal(field):
"""
Checks if a field is solenoidal.
Paramaters
==========
field : Vector
The field to check for solenoidal property
Examples
========
>>> from sympy.vector import CoordSysCartesian
>>> from sympy.vector import is_solenoidal
>>> R = CoordSysCartesian('R')
>>> is_solenoidal(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k)
True
>>> is_solenoidal(R.y * R.j)
False
"""
#Field is solenoidal irrespective of system
#Take the first coordinate system in the result of the
#separate method in Vector
if not isinstance(field, Vector):
raise TypeError("field should be a Vector")
if field == Vector.zero:
return True
coord_sys = list(field.separate())[0]
return divergence(field, coord_sys).simplify() == S(0)
def scalar_potential(field, coord_sys):
"""
Returns the scalar potential function of a field in a given
coordinate system (without the added integration constant).
Parameters
==========
field : Vector
The vector field whose scalar potential function is to be
calculated
coord_sys : CoordSysCartesian
The coordinate system to do the calculation in
Examples
========
>>> from sympy.vector import CoordSysCartesian
>>> from sympy.vector import scalar_potential, gradient
>>> R = CoordSysCartesian('R')
>>> scalar_potential(R.k, R) == R.z
True
>>> scalar_field = 2*R.x**2*R.y*R.z
>>> grad_field = gradient(scalar_field, R)
>>> scalar_potential(grad_field, R)
2*R.x**2*R.y*R.z
"""
#Check whether field is conservative
if not is_conservative(field):
raise ValueError("Field is not conservative")
if field == Vector.zero:
return S(0)
#Express the field exntirely in coord_sys
#Subsitute coordinate variables also
if not isinstance(coord_sys, CoordSysCartesian):
raise TypeError("coord_sys must be a CoordSysCartesian")
field = express(field, coord_sys, variables=True)
dimensions = coord_sys.base_vectors()
scalars = coord_sys.base_scalars()
#Calculate scalar potential function
temp_function = integrate(field.dot(dimensions[0]), scalars[0])
for i, dim in enumerate(dimensions[1:]):
partial_diff = diff(temp_function, scalars[i + 1])
partial_diff = field.dot(dim) - partial_diff
temp_function += integrate(partial_diff, scalars[i + 1])
return temp_function
def scalar_potential_difference(field, coord_sys, point1, point2):
"""
Returns the scalar potential difference between two points in a
certain coordinate system, wrt a given field.
If a scalar field is provided, its values at the two points are
considered. If a conservative vector field is provided, the values
of its scalar potential function at the two points are used.
Returns (potential at point2) - (potential at point1)
The position vectors of the two Points are calculated wrt the
origin of the coordinate system provided.
Parameters
==========
field : Vector/Expr
The field to calculate wrt
coord_sys : CoordSysCartesian
The coordinate system to do the calculations in
point1 : Point
The initial Point in given coordinate system
position2 : Point
The second Point in the given coordinate system
Examples
========
>>> from sympy.vector import CoordSysCartesian, Point
>>> from sympy.vector import scalar_potential_difference
>>> R = CoordSysCartesian('R')
>>> P = R.origin.locate_new('P', R.x*R.i + R.y*R.j + R.z*R.k)
>>> vectfield = 4*R.x*R.y*R.i + 2*R.x**2*R.j
>>> scalar_potential_difference(vectfield, R, R.origin, P)
2*R.x**2*R.y
>>> Q = R.origin.locate_new('O', 3*R.i + R.j + 2*R.k)
>>> scalar_potential_difference(vectfield, R, P, Q)
-2*R.x**2*R.y + 18
"""
if not isinstance(coord_sys, CoordSysCartesian):
raise TypeError("coord_sys must be a CoordSysCartesian")
if isinstance(field, Vector):
#Get the scalar potential function
scalar_fn = scalar_potential(field, coord_sys)
else:
#Field is a scalar
scalar_fn = field
#Express positions in required coordinate system
origin = coord_sys.origin
position1 = express(point1.position_wrt(origin), coord_sys,
variables=True)
position2 = express(point2.position_wrt(origin), coord_sys,
variables=True)
#Get the two positions as substitution dicts for coordinate variables
subs_dict1 = {}
subs_dict2 = {}
scalars = coord_sys.base_scalars()
for i, x in enumerate(coord_sys.base_vectors()):
subs_dict1[scalars[i]] = x.dot(position1)
subs_dict2[scalars[i]] = x.dot(position2)
return scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1)
def matrix_to_vector(matrix, system):
"""
Converts a vector in matrix form to a Vector instance.
It is assumed that the elements of the Matrix represent the
measure numbers of the components of the vector along basis
vectors of 'system'.
Parameters
==========
matrix : SymPy Matrix, Dimensions: (3, 1)
The matrix to be converted to a vector
system : CoordSysCartesian
The coordinate system the vector is to be defined in
Examples
========
>>> from sympy import ImmutableMatrix as Matrix
>>> m = Matrix([1, 2, 3])
>>> from sympy.vector import CoordSysCartesian, matrix_to_vector
>>> C = CoordSysCartesian('C')
>>> v = matrix_to_vector(m, C)
>>> v
C.i + 2*C.j + 3*C.k
>>> v.to_matrix(C) == m
True
"""
outvec = Vector.zero
vects = system.base_vectors()
for i, x in enumerate(matrix):
outvec += x * vects[i]
return outvec
def _path(from_object, to_object):
"""
Calculates the 'path' of objects starting from 'from_object'
to 'to_object', along with the index of the first common
ancestor in the tree.
Returns (index, list) tuple.
"""
if from_object._root != to_object._root:
raise ValueError("No connecting path found between " +
str(from_object) + " and " + str(to_object))
other_path = []
obj = to_object
while obj._parent is not None:
other_path.append(obj)
obj = obj._parent
other_path.append(obj)
object_set = set(other_path)
from_path = []
obj = from_object
while obj not in object_set:
from_path.append(obj)
obj = obj._parent
index = len(from_path)
i = other_path.index(obj)
while i >= 0:
from_path.append(other_path[i])
i -= 1
return index, from_path
|
bowlofstew/Herd
|
refs/heads/master
|
herd/BitTornado/BT1/__init__.py
|
101
|
# placeholder
|
freedesktop-unofficial-mirror/telepathy__telepathy-mission-control
|
refs/heads/master
|
tests/twisted/account-manager/auto-connect.py
|
1
|
# Copyright (C) 2009 Nokia Corporation
# Copyright (C) 2009 Collabora Ltd.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
import dbus
"""Feature test for automatically signing in and setting presence etc.
"""
import os
import os.path
import dbus
import dbus.service
from servicetest import EventPattern, tp_name_prefix, tp_path_prefix, \
call_async, assertEquals
from mctest import (exec_test, SimulatedConnection,
SimulatedConnectionManager, MC)
import constants as cs
account_id = 'fakecm/fakeprotocol/jc_2edenton_40unatco_2eint'
def preseed(q, bus, fake_accounts_service):
accounts_dir = os.environ['MC_ACCOUNT_DIR']
try:
os.mkdir(accounts_dir, 0700)
except OSError:
pass
fake_accounts_service.update_attributes(account_id, changed={
'manager': 'fakecm',
'protocol': 'fakeprotocol',
'DisplayName': 'Work account',
'NormalizedName': '[email protected]',
'Enabled': True,
'ConnectAutomatically': True,
# These are in the old format. They'll be combined shortly.
'AutomaticPresenceType': dbus.UInt32(2),
'AutomaticPresenceStatus': 'available',
'AutomaticPresenceMessage': 'My vision is augmented',
'Nickname': 'JC',
'AvatarMime': 'image/jpeg',
})
# As a regression test for part of fd.o #28557, the password starts and
# ends with a double backslash, which is represented in the file as a
# quadruple backslash. We use the untyped-parameters dict in order to
# exercise that.
fake_accounts_service.update_parameters(account_id, untyped={
'account': '[email protected]',
'password': r'\\\\ionstorm\\\\',
})
avatar_filename = account_id
avatar_filename = avatar_filename.replace('/', '-') + '.avatar'
avatar_filename = (os.environ['XDG_DATA_HOME'] +
'/telepathy/mission-control/' + avatar_filename)
os.makedirs(os.path.dirname(avatar_filename))
avatar_bin = open(avatar_filename, 'w')
avatar_bin.write('Deus Ex')
avatar_bin.close()
account_connections_file = open(accounts_dir + '/.mc_connections', 'w')
account_connections_file.write("")
account_connections_file.close()
def test(q, bus, unused, **kwargs):
simulated_cm = SimulatedConnectionManager(q, bus)
fake_accounts_service = kwargs['fake_accounts_service']
preseed(q, bus, fake_accounts_service)
expected_params = {
'account': '[email protected]',
'password': r'\\ionstorm\\',
}
mc = MC(q, bus, wait_for_names=False)
mc.wait_for_names(
# Migration step: the three separate attributes get combined
# (before the names are taken, so we need to expect it here)
EventPattern('dbus-method-call',
interface=cs.TEST_DBUS_ACCOUNT_SERVICE_IFACE,
method='UpdateAttributes',
predicate=(lambda e:
e.args[0] == account_id and
e.args[1] == {'AutomaticPresence':
(2, 'available', 'My vision is augmented')} and
e.args[2] == {'AutomaticPresence': 0} and # flags
set(e.args[3]) == set([ # no particular order
'AutomaticPresenceType',
'AutomaticPresenceStatus',
'AutomaticPresenceMessage',
])))
)
request_conn, prop_changed = q.expect_many(
EventPattern('dbus-method-call', method='RequestConnection',
args=['fakeprotocol', expected_params],
destination=cs.tp_name_prefix + '.ConnectionManager.fakecm',
path=cs.tp_path_prefix + '/ConnectionManager/fakecm',
interface=cs.tp_name_prefix + '.ConnectionManager',
handled=False),
EventPattern('dbus-signal', signal='AccountPropertyChanged',
predicate=(lambda e: 'ConnectionStatus' in e.args[0])),
)
conn = SimulatedConnection(q, bus, 'fakecm', 'fakeprotocol', '_',
'myself', has_presence=True, has_aliasing=True, has_avatars=True)
assertEquals('/', prop_changed.args[0].get('Connection'))
assertEquals('', prop_changed.args[0].get('ConnectionError'))
assertEquals({}, prop_changed.args[0].get('ConnectionErrorDetails'))
assertEquals(cs.CONN_STATUS_CONNECTING,
prop_changed.args[0].get('ConnectionStatus'))
assertEquals(cs.CSR_REQUESTED,
prop_changed.args[0].get('ConnectionStatusReason'))
q.dbus_return(request_conn.message, conn.bus_name, conn.object_path,
signature='so')
account_path = (cs.tp_path_prefix + '/Account/' + account_id)
account = bus.get_object(
cs.tp_name_prefix + '.AccountManager',
account_path)
prop_changed, _ = q.expect_many(
EventPattern('dbus-signal', signal='AccountPropertyChanged',
predicate=(lambda e: 'ConnectionStatus' in e.args[0])),
EventPattern('dbus-method-call', method='Connect',
path=conn.object_path, handled=True, interface=cs.CONN),
)
assertEquals(conn.object_path, prop_changed.args[0].get('Connection'))
assertEquals('', prop_changed.args[0].get('ConnectionError'))
assertEquals({}, prop_changed.args[0].get('ConnectionErrorDetails'))
assertEquals(cs.CONN_STATUS_CONNECTING,
prop_changed.args[0].get('ConnectionStatus'))
assertEquals(cs.CSR_REQUESTED,
prop_changed.args[0].get('ConnectionStatusReason'))
props = account.GetAll(cs.ACCOUNT, dbus_interface=cs.PROPERTIES_IFACE)
assert props['Connection'] == conn.object_path
assert props['ConnectionStatus'] == cs.CONN_STATUS_CONNECTING
assert props['ConnectionStatusReason'] == cs.CSR_REQUESTED
print "becoming connected"
conn.StatusChanged(cs.CONN_STATUS_CONNECTED, cs.CSR_NONE_SPECIFIED)
set_aliases, set_presence, set_avatar, prop_changed = q.expect_many(
EventPattern('dbus-method-call',
interface=cs.CONN_IFACE_ALIASING, method='SetAliases',
args=[{ conn.self_handle: 'JC' }],
handled=False),
EventPattern('dbus-method-call', path=conn.object_path,
interface=cs.CONN_IFACE_SIMPLE_PRESENCE, method='SetPresence',
handled=True),
EventPattern('dbus-method-call',
interface=cs.CONN_IFACE_AVATARS, method='SetAvatar',
args=['Deus Ex', 'image/jpeg'],
handled=True),
EventPattern('dbus-signal', signal='AccountPropertyChanged',
path=account_path, interface=cs.ACCOUNT,
predicate=(lambda e:
e.args[0].get('ConnectionStatus') ==
cs.CONN_STATUS_CONNECTED),
),
)
assertEquals(conn.object_path, prop_changed.args[0].get('Connection'))
assertEquals('', prop_changed.args[0].get('ConnectionError'))
assertEquals({}, prop_changed.args[0].get('ConnectionErrorDetails'))
assertEquals(cs.CONN_STATUS_CONNECTED,
prop_changed.args[0].get('ConnectionStatus'))
assertEquals(cs.CSR_REQUESTED,
prop_changed.args[0].get('ConnectionStatusReason'))
assert account.Get(cs.ACCOUNT, 'CurrentPresence',
dbus_interface=cs.PROPERTIES_IFACE) == (cs.PRESENCE_AVAILABLE,
'available', 'My vision is augmented')
q.dbus_return(set_aliases.message, signature='')
if __name__ == '__main__':
exec_test(test, {}, preload_mc=False, use_fake_accounts_service=True,
pass_kwargs=True)
|
carloscrespog/HookTemperature
|
refs/heads/master
|
node_modules/hook.io/node_modules/npm/node_modules/node-gyp/legacy/tools/gyp/pylib/gyp/generator/ninja_test.py
|
39
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Unit tests for the ninja.py file. """
import gyp.generator.ninja as ninja
import unittest
import StringIO
import TestCommon
class TestPrefixesAndSuffixes(unittest.TestCase):
def test_BinaryNamesWindows(self):
writer = ninja.NinjaWriter('wee', '.', '.', 'ninja.build', 'win')
spec = { 'target_name': 'wee' }
self.assertTrue(writer.ComputeOutputFileName(spec, 'executable').
endswith('.exe'))
self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library').
endswith('.dll'))
self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library').
endswith('.lib'))
def test_BinaryNamesLinux(self):
writer = ninja.NinjaWriter('wee', '.', '.', 'ninja.build', 'linux')
spec = {
'target_name': 'wee'
}
self.assertTrue('.' not in writer.ComputeOutputFileName(spec, 'executable'))
self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library').
startswith('lib'))
self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library').
startswith('lib'))
self.assertTrue(writer.ComputeOutputFileName(spec, 'shared_library').
endswith('.so'))
self.assertTrue(writer.ComputeOutputFileName(spec, 'static_library').
endswith('.a'))
if __name__ == '__main__':
unittest.main()
|
ShinyROM/android_external_chromium_org
|
refs/heads/master
|
tools/perf/benchmarks/spaceport.py
|
23
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs spaceport.io's PerfMarks benchmark."""
import logging
import os
import sys
from telemetry import test
from telemetry.core import util
from telemetry.page import page_measurement
from telemetry.page import page_set
class _SpaceportMeasurement(page_measurement.PageMeasurement):
def CustomizeBrowserOptions(self, options):
options.AppendExtraBrowserArgs('--disable-gpu-vsync')
def MeasurePage(self, _, tab, results):
tab.WaitForJavaScriptExpression(
'!document.getElementById("start-performance-tests").disabled', 60)
tab.ExecuteJavaScript("""
window.__results = {};
window.console.log = function(str) {
if (!str) return;
var key_val = str.split(': ');
if (!key_val.length == 2) return;
__results[key_val[0]] = key_val[1];
};
document.getElementById('start-performance-tests').click();
""")
num_results = 0
num_tests_in_spaceport = 24
while num_results < num_tests_in_spaceport:
tab.WaitForJavaScriptExpression(
'Object.keys(window.__results).length > %d' % num_results, 180)
num_results = tab.EvaluateJavaScript(
'Object.keys(window.__results).length')
logging.info('Completed test %d of %d' %
(num_results, num_tests_in_spaceport))
result_dict = eval(tab.EvaluateJavaScript(
'JSON.stringify(window.__results)'))
for key in result_dict:
chart, trace = key.split('.', 1)
results.Add(trace, 'objects (bigger is better)', float(result_dict[key]),
chart_name=chart, data_type='unimportant')
results.Add('Score', 'objects (bigger is better)',
[float(x) for x in result_dict.values()])
class Spaceport(test.Test):
"""spaceport.io's PerfMarks benchmark."""
test = _SpaceportMeasurement
# crbug.com/166703: This test frequently times out on Windows.
enabled = sys.platform != 'darwin' and not sys.platform.startswith('win')
def CreatePageSet(self, options):
spaceport_dir = os.path.join(util.GetChromiumSrcDir(), 'chrome', 'test',
'data', 'third_party', 'spaceport')
return page_set.PageSet.FromDict(
{'pages': [{'url': 'file://index.html'}]},
spaceport_dir)
|
taxido/django-xadmin
|
refs/heads/master
|
xadmin/plugins/relate.py
|
9
|
# coding=UTF-8
from django.core.urlresolvers import reverse
from django.utils.encoding import force_unicode
from django.utils.encoding import smart_str
from django.utils.safestring import mark_safe
from django.db.models.sql.query import LOOKUP_SEP
from django.db.models.related import RelatedObject
from django.utils.translation import ugettext as _
from django.db import models
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ListAdminView, CreateAdminView, UpdateAdminView, DeleteAdminView
RELATE_PREFIX = '_rel_'
class RelateMenuPlugin(BaseAdminPlugin):
related_list = []
use_related_menu = True
def get_related_list(self):
if hasattr(self, '_related_acts'):
return self._related_acts
_related_acts = []
for r in self.opts.get_all_related_objects() + self.opts.get_all_related_many_to_many_objects():
if self.related_list and (r.get_accessor_name() not in self.related_list):
continue
if r.model not in self.admin_site._registry.keys():
continue
has_view_perm = self.has_model_perm(r.model, 'view')
has_add_perm = self.has_model_perm(r.model, 'add')
if not (has_view_perm or has_add_perm):
continue
_related_acts.append((r, has_view_perm, has_add_perm))
self._related_acts = _related_acts
return self._related_acts
def related_link(self, instance):
links = []
for r, view_perm, add_perm in self.get_related_list():
label = r.opts.app_label
model_name = r.opts.model_name
f = r.field
rel_name = f.rel.get_related_field().name
verbose_name = force_unicode(r.opts.verbose_name)
lookup_name = '%s__%s__exact' % (f.name, rel_name)
link = ''.join(('<li class="with_menu_btn">',
'<a href="%s?%s=%s" title="%s"><i class="icon fa fa-th-list"></i> %s</a>' %
(
reverse('%s:%s_%s_changelist' % (
self.admin_site.app_name, label, model_name)),
RELATE_PREFIX + lookup_name, str(instance.pk), verbose_name, verbose_name) if view_perm else
'<a><span class="text-muted"><i class="icon fa fa-blank"></i> %s</span></a>' % verbose_name,
'<a class="add_link dropdown-menu-btn" href="%s?%s=%s"><i class="icon fa fa-plus pull-right"></i></a>' %
(
reverse('%s:%s_%s_add' % (
self.admin_site.app_name, label, model_name)),
RELATE_PREFIX + lookup_name, str(
instance.pk)) if add_perm else "",
'</li>'))
links.append(link)
ul_html = '<ul class="dropdown-menu" role="menu">%s</ul>' % ''.join(
links)
return '<div class="dropdown related_menu pull-right"><a title="%s" class="relate_menu dropdown-toggle" data-toggle="dropdown"><i class="icon fa fa-list"></i></a>%s</div>' % (_('Related Objects'), ul_html)
related_link.short_description = ' '
related_link.allow_tags = True
related_link.allow_export = False
related_link.is_column = False
def get_list_display(self, list_display):
if self.use_related_menu and len(self.get_related_list()):
list_display.append('related_link')
self.admin_view.related_link = self.related_link
return list_display
class RelateObject(object):
def __init__(self, admin_view, lookup, value):
self.admin_view = admin_view
self.org_model = admin_view.model
self.opts = admin_view.opts
self.lookup = lookup
self.value = value
parts = lookup.split(LOOKUP_SEP)
field = self.opts.get_field_by_name(parts[0])[0]
if not hasattr(field, 'rel') and not isinstance(field, RelatedObject):
raise Exception(u'Relate Lookup field must a related field')
if hasattr(field, 'rel'):
self.to_model = field.rel.to
self.rel_name = field.rel.get_related_field().name
self.is_m2m = isinstance(field.rel, models.ManyToManyRel)
else:
self.to_model = field.model
self.rel_name = self.to_model._meta.pk.name
self.is_m2m = False
to_qs = self.to_model._default_manager.get_queryset()
self.to_objs = to_qs.filter(**{self.rel_name: value}).all()
self.field = field
def filter(self, queryset):
return queryset.filter(**{self.lookup: self.value})
def get_brand_name(self):
if len(self.to_objs) == 1:
to_model_name = str(self.to_objs[0])
else:
to_model_name = force_unicode(self.to_model._meta.verbose_name)
return mark_safe(u"<span class='rel-brand'>%s <i class='fa fa-caret-right'></i></span> %s" % (to_model_name, force_unicode(self.opts.verbose_name_plural)))
class BaseRelateDisplayPlugin(BaseAdminPlugin):
def init_request(self, *args, **kwargs):
self.relate_obj = None
for k, v in self.request.REQUEST.items():
if smart_str(k).startswith(RELATE_PREFIX):
self.relate_obj = RelateObject(
self.admin_view, smart_str(k)[len(RELATE_PREFIX):], v)
break
return bool(self.relate_obj)
def _get_relate_params(self):
return RELATE_PREFIX + self.relate_obj.lookup, self.relate_obj.value
def _get_input(self):
return '<input type="hidden" name="%s" value="%s" />' % self._get_relate_params()
def _get_url(self, url):
return url + ('&' if url.find('?') > 0 else '?') + ('%s=%s' % self._get_relate_params())
class ListRelateDisplayPlugin(BaseRelateDisplayPlugin):
def get_list_queryset(self, queryset):
if self.relate_obj:
queryset = self.relate_obj.filter(queryset)
return queryset
def url_for_result(self, url, result):
return self._get_url(url)
def get_context(self, context):
context['brand_name'] = self.relate_obj.get_brand_name()
context['rel_objs'] = self.relate_obj.to_objs
if 'add_url' in context:
context['add_url'] = self._get_url(context['add_url'])
return context
def get_list_display(self, list_display):
if not self.relate_obj.is_m2m:
try:
list_display.remove(self.relate_obj.field.name)
except Exception:
pass
return list_display
class EditRelateDisplayPlugin(BaseRelateDisplayPlugin):
def get_form_datas(self, datas):
if self.admin_view.org_obj is None and self.admin_view.request_method == 'get':
datas['initial'][
self.relate_obj.field.name] = self.relate_obj.value
return datas
def post_response(self, response):
if isinstance(response, basestring) and response != self.get_admin_url('index'):
return self._get_url(response)
return response
def get_context(self, context):
if 'delete_url' in context:
context['delete_url'] = self._get_url(context['delete_url'])
return context
def block_after_fieldsets(self, context, nodes):
return self._get_input()
class DeleteRelateDisplayPlugin(BaseRelateDisplayPlugin):
def post_response(self, response):
if isinstance(response, basestring) and response != self.get_admin_url('index'):
return self._get_url(response)
return response
def block_form_fields(self, context, nodes):
return self._get_input()
site.register_plugin(RelateMenuPlugin, ListAdminView)
site.register_plugin(ListRelateDisplayPlugin, ListAdminView)
site.register_plugin(EditRelateDisplayPlugin, CreateAdminView)
site.register_plugin(EditRelateDisplayPlugin, UpdateAdminView)
site.register_plugin(DeleteRelateDisplayPlugin, DeleteAdminView)
|
pyjs/pyjs
|
refs/heads/master
|
examples/showcase/src/demos_widgets/checkBox.py
|
13
|
"""
The ``ui.CheckBox`` class is used to show a standard checkbox. When the user
clicks on the checkbox, the checkbox's state is toggled.
The ``setChecked(checked)`` method checks or unchecks the checkbox depending on
the value of the parameter. To get the current value of the checkbox, call
``isChecked()``.
You can enable or disable a checkbox using ``setEnabled(enabled)``. You can
also call ``addClickListener()`` to respond when the user clicks on the
checkbox, as shown below. This can be useful when building complicated input
screens where checking a checkbox causes other input fields to be enabled.
"""
from pyjamas.ui.SimplePanel import SimplePanel
from pyjamas.ui.CheckBox import CheckBox
from pyjamas import Window
class CheckBoxDemo(SimplePanel):
def __init__(self):
SimplePanel.__init__(self)
self.box = CheckBox("Print Results?")
self.box.addClickListener(getattr(self, "onClick"))
self.add(self.box)
def onClick(self, sender=None):
Window.alert("checkbox status: " + str(self.box.isChecked()))
|
helenwarren/pied-wagtail
|
refs/heads/master
|
wagtail/wagtailusers/forms.py
|
3
|
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm as BaseUserCreationForm
from django.utils.translation import ugettext_lazy as _
User = get_user_model()
# extend Django's UserCreationForm with an 'is_superuser' field
class UserCreationForm(BaseUserCreationForm):
required_css_class = "required"
is_superuser = forms.BooleanField(
label=_("Administrator"),
required=False,
help_text=_("If ticked, this user has the ability to manage user accounts.")
)
email = forms.EmailField(required=True, label=_("Email"))
first_name = forms.CharField(required=True, label=_("First Name"))
last_name = forms.CharField(required=True, label=_("Last Name"))
class Meta:
model = User
fields = ("username", "email", "first_name", "last_name", "is_superuser", "groups")
widgets = {
'groups': forms.CheckboxSelectMultiple
}
def clean_username(self):
# Method copied from parent
username = self.cleaned_data["username"]
try:
# When called from BaseUserCreationForm, the method fails if using a AUTH_MODEL_MODEL,
# This is because the following line tries to perform a lookup on
# the default "auth_user" table.
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages['duplicate_username'],
code='duplicate_username',
)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
# users can access django-admin iff they are a superuser
user.is_staff = user.is_superuser
if commit:
user.save()
self.save_m2m()
return user
# Largely the same as django.contrib.auth.forms.UserCreationForm, but with enough subtle changes
# (to make password non-required) that it isn't worth inheriting...
class UserEditForm(forms.ModelForm):
required_css_class = "required"
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.RegexField(
label=_("Username"),
max_length=30,
regex=r'^[\w.@+-]+$',
help_text=_("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages={
'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")
})
email = forms.EmailField(required=True, label=_("Email"))
first_name = forms.CharField(required=True, label=_("First Name"))
last_name = forms.CharField(required=True, label=_("Last Name"))
password1 = forms.CharField(
label=_("Password"),
required=False,
widget=forms.PasswordInput,
help_text=_("Leave blank if not changing."))
password2 = forms.CharField(
label=_("Password confirmation"), required=False,
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
is_superuser = forms.BooleanField(
label=_("Administrator"),
required=False,
help_text=_("Administrators have the ability to manage user accounts.")
)
class Meta:
model = User
fields = ("username", "email", "first_name", "last_name", "is_active", "is_superuser", "groups")
widgets = {
'groups': forms.CheckboxSelectMultiple
}
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User._default_manager.exclude(id=self.instance.id).get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(UserEditForm, self).save(commit=False)
# users can access django-admin iff they are a superuser
user.is_staff = user.is_superuser
if self.cleaned_data["password1"]:
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
self.save_m2m()
return user
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.