{"input": "import logging\nimport operator\nimport pytest\nfrom bloop.conditions import ConditionRenderer\nfrom bloop.exceptions import InvalidModel, InvalidStream\nfrom bloop.models import (\n BaseModel,\n Column,\n GlobalSecondaryIndex,\n IMeta,\n Index,\n LocalSecondaryIndex,\n bind_column,\n bind_index,\n model_created,\n object_modified,\n unbind,\n unpack_from_dynamodb,\n)\nfrom bloop.types import (\n UUID,\n Boolean,\n DateTime,\n Integer,\n String,\n Timestamp,\n Type,\n)\nfrom ..helpers.models import User, VectorModel\n\n\n\n\n\noperations = [\n (operator.ne, \"!=\"),\n (operator.eq, \"==\"),\n (operator.lt, \"<\"),\n (operator.le, \"<=\"),\n (operator.gt, \">\"),\n (operator.ge, \">=\")\n]\n\n\n@pytest.fixture\ndef unpack_kwargs(engine):\n return {\n \"attrs\": {\"name\": {\"S\": \"numberoverzero\"}},\n \"expected\": {User.name, User.joined},\n \"model\": User,\n \"engine\": engine,\n \"context\": {\"engine\": engine, \"extra\": \"foo\"},\n }\n\n\n# BASE MODEL =============================================================================================== BASE MODEL\n\n\ndef test_default_model_init():\n \"\"\"Missing attributes are set to `None`\"\"\"\n user = User(id=\"user_id\", email=\"user@domain.com\")\n assert user.id == \"user_id\"\n assert user.email == \"user@domain.com\"\n assert not hasattr(user, \"name\")\n\n\ndef test_load_default_init(engine):\n \"\"\"The default model loader uses cls.__new__(cls) method\"\"\"\n init_called = False\n\n", "context": "bloop/types.py\nclass Boolean(Type):\n python_type = bool\n backing_type = BOOLEAN\n\n def dynamo_load(self, value, *, context, **kwargs):\n if value is None:\n return None\n return bool(value)\n\n def dynamo_dump(self, value, *, context, **kwargs):\n if value is None:\n return None\n return bool(value)\nbloop/models.py\nclass IMeta:\nclass BaseModel:\n class Meta(IMeta):\nclass Index:\nclass GlobalSecondaryIndex(Index):\nclass LocalSecondaryIndex(Index):\nclass Column(ComparisonMixin):\n class UNBOUND:\n class Meta(IMeta):\n def __init__(self, **attrs):\n def __init_subclass__(cls: type, **kwargs):\n def __repr__(self):\n def __init__(self, *, projection, hash_key=None, range_key=None, dynamo_name=None, **kwargs):\n def __copy__(self):\n def __set_name__(self, owner, name):\n def __repr__(self):\n def name(self):\n def dynamo_name(self):\n def hash_key(self):\n def range_key(self):\n def keys(self):\n def __set__(self, obj, value):\n def __get__(self, obj, type=None):\n def __delete__(self, obj):\n def __init__(\n self, *, projection,\n hash_key, range_key=None,\n read_units=None, write_units=None,\n dynamo_name=None, **kwargs):\n def __init__(self, *, projection, range_key, dynamo_name=None, strict=True, **kwargs):\n def hash_key(self):\n def read_units(self):\n def read_units(self, value):\n def write_units(self):\n def write_units(self, value):\n def __init__(self, typedef, hash_key=False, range_key=False, dynamo_name=None, default=missing):\n def __copy__(self):\n def __set_name__(self, owner, name):\n def __set__(self, obj, value):\n def __get__(self, obj, type=None):\n def __delete__(self, obj):\n def __repr__(self):\n def name(self):\n def dynamo_name(self):\ndef subclassof(obj, classinfo):\ndef instanceof(obj, classinfo):\ndef loaded_columns(obj: BaseModel):\ndef unpack_from_dynamodb(*, attrs, expected, model=None, obj=None, engine=None, context=None, **kwargs):\ndef validate_projection(projection):\ndef validate_stream(meta):\ndef validate_encryption(meta):\ndef validate_backups(meta):\ndef validate_billing(meta):\ndef validate_ttl(meta):\ndef unbound_repr(obj):\ndef setdefault(obj, field, default):\ndef ensure_hash(cls) -> None:\ndef initialize_meta(cls: type):\ndef bind_column(model, name, column, force=False, recursive=False, copy=False) -> Column:\ndef bind_index(model, name, index, force=False, recursive=True, copy=False) -> Index:\ndef refresh_index(meta, index) -> None:\ndef unbind(meta, name=None, dynamo_name=None) -> None:\nbloop/types.py\nclass Integer(Number):\n \"\"\"Truncates values when loading or dumping.\n\n For example, ``3.14`` in DynamoDB is loaded as ``3``. If a value is ``7.5``\n locally, it's stored in DynamoDB as ``7``.\n \"\"\"\n python_type = int\n\n def dynamo_load(self, value, *, context, **kwargs):\n if value is None:\n return None\n number = super().dynamo_load(value, context=context, **kwargs)\n return int(number)\n\n def dynamo_dump(self, value, *, context, **kwargs):\n if value is None:\n return None\n value = int(value)\n return super().dynamo_dump(value, context=context, **kwargs)\nbloop/exceptions.py\nclass InvalidModel(BloopException, ValueError):\n \"\"\"This is not a valid Model.\"\"\"\nbloop/types.py\nclass DateTime(String):\n \"\"\"Always stored in DynamoDB using the :data:`~bloop.types.FIXED_ISO8601_FORMAT` format.\n\n Naive datetimes (``tzinfo is None``) are not supported, and trying to use one will raise ``ValueError``.\n\n .. code-block:: python\n\n from datetime import datetime, timedelta, timezone\n\n class Model(Base):\n id = Column(Integer, hash_key=True)\n date = Column(DateTime)\n engine.bind()\n\n obj = Model(id=1, date=datetime.now(timezone.utc))\n engine.save(obj)\n\n one_day_ago = datetime.now(timezone.utc) - timedelta(days=1)\n\n query = engine.query(\n Model,\n key=Model.id==1,\n filter=Model.date >= one_day_ago)\n\n query.first().date\n\n .. note::\n\n To use common datetime libraries such as `arrow`_, `delorean`_, or `pendulum`_,\n see :ref:`DateTime and Timestamp Extensions ` in the user guide. These\n are drop-in replacements and support non-utc timezones:\n\n .. code-block:: python\n\n from bloop import DateTime # becomes:\n from bloop.ext.pendulum import DateTime\n\n .. _arrow: http://crsmithdev.com/arrow\n .. _delorean: https://delorean.readthedocs.io/en/latest/\n .. _pendulum: https://pendulum.eustace.io\n \"\"\"\n python_type = datetime.datetime\n\n def dynamo_load(self, value, *, context, **kwargs):\n if value is None:\n return None\n dt = datetime.datetime.strptime(value, FIXED_ISO8601_FORMAT)\n # we assume all stored values are utc, so we simply force timezone to utc\n # without changing the day/time values\n return dt.replace(tzinfo=datetime.timezone.utc)\n\n def dynamo_dump(self, value, *, context, **kwargs):\n if value is None:\n return None\n if value.tzinfo is None:\n raise ValueError(\n \"naive datetime instances are not supported. You can set a timezone with either \"\n \"your_dt.replace(tzinfo=) or your_dt.astimezone(tz=). WARNING: calling astimezone on a naive \"\n \"datetime will assume the naive datetime is in the system's timezone, even though \"\n \"datetime.utcnow() creates a naive object! You almost certainly don't want to do that.\"\n )\n dt = value.astimezone(tz=datetime.timezone.utc)\n return dt.strftime(FIXED_ISO8601_FORMAT)\nbloop/exceptions.py\nclass InvalidStream(BloopException, ValueError):\n \"\"\"This is not a valid stream definition.\"\"\"\nbloop/types.py\nclass UUID(String):\n python_type = uuid.UUID\n\n def dynamo_load(self, value, *, context, **kwargs):\n if value is None:\n return None\n return uuid.UUID(value)\n\n def dynamo_dump(self, value, *, context, **kwargs):\n if value is None:\n return None\n return str(value)\ntests/helpers/models.py\nclass VectorModel(BaseModel):\n name = Column(String, hash_key=True)\n list_str = Column(List(String))\n set_str = Column(Set(String))\n map_nested = Column(Map(**{\n \"bytes\": Binary,\n \"str\": String,\n \"map\": Map(**{\n \"int\": Integer,\n \"str\": String\n })\n }))\n some_int = Column(Integer)\n some_bytes = Column(Binary)\nbloop/types.py\nclass Type:\n \"\"\"Abstract base type.\"\"\"\n\n python_type = None\n backing_type = None\n\n def supports_operation(self, operation: str) -> bool:\n \"\"\"\n Used to ensure a conditional operation is supported by this type.\n\n By default, uses a hardcoded table of operations that maps to each backing DynamoDB type.\n\n You can override this method to implement your own conditional operators, or to dynamically\n adjust which operations your type supports.\n \"\"\"\n return operation in OPERATION_SUPPORT_BY_TYPE[self.backing_type]\n\n def __init__(self):\n if not hasattr(self, \"inner_typedef\"):\n self.inner_typedef = self\n super().__init__()\n\n def __getitem__(self, key):\n raise RuntimeError(f\"{self!r} does not support document paths\")\n\n def dynamo_dump(self, value, *, context, **kwargs):\n \"\"\"Converts a local value into a DynamoDB value.\n\n For example, to store a string enum as an integer:\n\n .. code-block:: python\n\n def dynamo_dump(self, value, *, context, **kwargs):\n colors = [\"red\", \"blue\", \"green\"]\n return colors.index(value.lower())\n \"\"\"\n raise NotImplementedError\n\n def dynamo_load(self, value, *, context, **kwargs):\n \"\"\"Converts a DynamoDB value into a local value.\n\n For example, to load a string enum from an integer:\n\n .. code-block:: python\n\n def dynamo_dump(self, value, *, context, **kwargs):\n colors = [\"red\", \"blue\", \"green\"]\n return colors[value]\n \"\"\"\n raise NotImplementedError\n\n def _dump(self, value, **kwargs):\n \"\"\"Entry point for serializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_dump`.\n\n This wraps the return value of :func:`~bloop.types.Type.dynamo_dump` in DynamoDB's wire format.\n For example, serializing a string enum to an int:\n\n .. code-block:: python\n\n value = \"green\"\n # dynamo_dump(\"green\") = 2\n _dump(value) == {\"N\": 2}\n\n If a complex type calls this function with ``None``, it will forward ``None`` to\n :func:`~bloop.types.Type.dynamo_dump`. This can happen when dumping eg. a sparse\n :class:`~.bloop.types.Map`, or a missing (not set) value.\n \"\"\"\n wrapped = actions.wrap(value)\n value = self.dynamo_dump(wrapped.value, **kwargs)\n if value is None:\n return actions.wrap(None)\n else:\n value = {self.backing_type: value}\n return wrapped.type.new_action(value)\n\n def _load(self, value, **kwargs):\n \"\"\"Entry point for deserializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_load`.\n\n This unpacks DynamoDB's wire format and calls :func:`~bloop.types.Type.dynamo_load` on the inner value.\n For example, deserializing an int to a string enum:\n\n .. code-block:: python\n\n value = {\"N\": 2}\n # dynamo_load(2) = \"green\"\n _load(value) == \"green\"\n\n If a complex type calls this function with ``None``, it will forward ``None`` to\n :func:`~bloop.types.Type.dynamo_load`. This can happen when loading eg. a sparse :class:`~bloop.types.Map`.\n \"\"\"\n if value is not None:\n value = next(iter(value.values()))\n return self.dynamo_load(value, **kwargs)\n\n def __repr__(self):\n # Render class python types by name\n python_type = self.python_type\n if isinstance(python_type, type):\n python_type = python_type.__name__\n\n return \"<{}[{}:{}]>\".format(\n self.__class__.__name__,\n self.backing_type, python_type\n )\ntests/helpers/models.py\nclass User(BaseModel):\n id = Column(String, hash_key=True)\n age = Column(Integer)\n name = Column(String)\n email = Column(String)\n joined = Column(DateTime, dynamo_name=\"j\")\n by_email = GlobalSecondaryIndex(hash_key=\"email\", projection=\"all\")\nbloop/types.py\nclass Timestamp(Integer):\n \"\"\"Stores the unix (epoch) time in seconds. Milliseconds are truncated to 0 on load and save.\n\n Naive datetimes (``tzinfo is None``) are not supported, and trying to use one will raise ``ValueError``.\n\n .. code-block:: python\n\n from datetime import datetime, timedelta, timezone\n\n class Model(Base):\n id = Column(Integer, hash_key=True)\n date = Column(Timestamp)\n engine.bind()\n\n obj = Model(id=1, date=datetime.now(timezone.utc))\n engine.save(obj)\n\n one_day_ago = datetime.now(timezone.utc) - timedelta(days=1)\n\n query = engine.query(\n Model,\n key=Model.id==1,\n filter=Model.date >= one_day_ago)\n\n query.first().date\n\n .. note::\n\n To use common datetime libraries such as `arrow`_, `delorean`_, or `pendulum`_,\n see :ref:`DateTime and Timestamp Extensions ` in the user guide. These\n are drop-in replacements and support non-utc timezones:\n\n .. code-block:: python\n\n from bloop import Timestamp # becomes:\n from bloop.ext.pendulum import Timestamp\n\n .. _arrow: http://crsmithdev.com/arrow\n .. _delorean: https://delorean.readthedocs.io/en/latest/\n .. _pendulum: https://pendulum.eustace.io\n \"\"\"\n python_type = datetime.datetime\n\n def dynamo_load(self, value, *, context, **kwargs):\n if value is None:\n return None\n value = super().dynamo_load(value, context=context, **kwargs)\n # we assume all stored values are utc, so we simply force timezone to utc\n # without changing the day/time values\n return datetime.datetime.fromtimestamp(value, tz=datetime.timezone.utc)\n\n def dynamo_dump(self, value, *, context, **kwargs):\n if value is None:\n return None\n if value.tzinfo is None:\n raise ValueError(\n \"naive datetime instances are not supported. You can set a timezone with either \"\n \"your_dt.replace(tzinfo=) or your_dt.astimezone(tz=). WARNING: calling astimezone on a naive \"\n \"datetime will assume the naive datetime is in the system's timezone, even though \"\n \"datetime.utcnow() creates a naive object! You almost certainly don't want to do that.\"\n )\n value = value.timestamp()\n return super().dynamo_dump(value, context=context, **kwargs)\nbloop/conditions.py\nclass ConditionRenderer:\n # noinspection PyUnresolvedReferences\n \"\"\"Renders collections of :class:`~bloop.conditions.BaseCondition` into DynamoDB's wire format for expressions,\n including:\n\n * ``\"ConditionExpression\"`` -- used in conditional operations\n * ``\"FilterExpression\"`` -- used in queries and scans to ignore results that don't match the filter\n * ``\"KeyConditionExpressions\"`` -- used to describe a query's hash (and range) key(s)\n * ``\"ProjectionExpression\"`` -- used to include a subset of possible columns in the results of a query or scan\n * ``\"UpdateExpression\"`` -- used to save objects\n\n Normally, you will only need to call :func:`~bloop.conditions.ConditionRenderer.render` to handle any combination\n of conditions. You can also call each individual ``render_*`` function to control how multiple conditions of\n each type are applied.\n\n You can collect the rendered condition at any time through :attr:`~bloop.conditions.ConditionRenderer.rendered`.\n\n .. code-block:: python\n\n >>> renderer.render(obj=user, atomic=True)\n >>> renderer.output\n {'ConditionExpression': '((#n0 = :v1) AND (attribute_not_exists(#n2)) AND (#n4 = :v5))',\n 'ExpressionAttributeNames': {'#n0': 'age', '#n2': 'email', '#n4': 'id'},\n 'ExpressionAttributeValues': {':v1': {'N': '3'}, ':v5': {'S': 'some-user-id'}}}\n\n\n :param engine: Used to dump values in conditions into the appropriate wire format.\n :type engine: :class:`~bloop.engine.Engine`\n \"\"\"\n def __init__(self, engine):\n self.refs = ReferenceTracker(engine)\n self.engine = engine\n self.expressions = {}\n\n def render(self, obj=None, condition=None, update=False, filter=None, projection=None, key=None):\n \"\"\"Main entry point for rendering multiple expressions. All parameters are optional, except obj when\n atomic or update are True.\n\n :param obj: *(Optional)* An object to render an atomic condition or update expression for. Required if\n update or atomic are true. Default is False.\n :param condition: *(Optional)* Rendered as a \"ConditionExpression\" for a conditional operation.\n If atomic is True, the two are rendered in an AND condition. Default is None.\n :type condition: :class:`~bloop.conditions.BaseCondition`\n :param bool update: *(Optional)* True if an \"UpdateExpression\" should be rendered for ``obj``.\n Default is False.\n :param filter: *(Optional)* A filter condition for a query or scan, rendered as a \"FilterExpression\".\n Default is None.\n :type filter: :class:`~bloop.conditions.BaseCondition`\n :param projection: *(Optional)* A set of Columns to include in a query or scan, rendered as a\n \"ProjectionExpression\". Default is None.\n :type projection: set :class:`~bloop.models.Column`\n :param key: *(Optional)* A key condition for queries, rendered as a \"KeyConditionExpression\". Default is None.\n :type key: :class:`~bloop.conditions.BaseCondition`\n \"\"\"\n if update and not obj:\n raise InvalidCondition(\"An object is required to render updates.\")\n\n if filter:\n self.filter_expression(filter)\n\n if projection:\n self.projection_expression(projection)\n\n if key:\n self.key_expression(key)\n\n # Condition requires a bit of work, because either one can be empty/false\n if condition:\n self.condition_expression(condition)\n\n if update:\n self.update_expression(obj)\n\n def condition_expression(self, condition):\n self.expressions[\"ConditionExpression\"] = condition.render(self)\n\n def filter_expression(self, condition):\n self.expressions[\"FilterExpression\"] = condition.render(self)\n\n def key_expression(self, condition):\n self.expressions[\"KeyConditionExpression\"] = condition.render(self)\n\n def projection_expression(self, columns):\n included = set()\n ref_names = []\n for column in columns:\n if column in included:\n continue\n included.add(column)\n ref = self.refs.any_ref(column=column)\n ref_names.append(ref.name)\n self.expressions[\"ProjectionExpression\"] = \", \".join(ref_names)\n\n def update_expression(self, obj):\n updates = {\n ActionType.Add: [],\n ActionType.Delete: [],\n ActionType.Remove: [],\n ActionType.Set: [],\n }\n for column in sorted(\n # Don't include key columns in an UpdateExpression\n filter(lambda c: c not in obj.Meta.keys, global_tracking[obj]),\n key=lambda c: c.dynamo_name):\n name_ref = self.refs.any_ref(column=column)\n value_ref = self.refs.any_ref(column=column, value=getattr(obj, column.name, None))\n update_type = value_ref.action.type\n # Can't set to an empty value, force to a Remove\n if is_empty(value_ref) or update_type is ActionType.Remove:\n self.refs.pop_refs(value_ref)\n update_type = ActionType.Remove\n value_ref = None\n updates[update_type].append((name_ref, value_ref))\n\n expressions = []\n for update_type, refs in updates.items():\n if not refs:\n continue\n k = update_type.wire_key.upper()\n r = update_type.render\n expressions.append(f\"{k} \" + \", \".join(r(*ref) for ref in refs))\n if expressions:\n self.expressions[\"UpdateExpression\"] = \" \".join(e.strip() for e in expressions)\n\n @property\n def output(self):\n \"\"\"The wire format for all conditions that have been rendered.\n A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation.\"\"\"\n expressions = {k: v for (k, v) in self.expressions.items() if v is not None}\n if self.refs.attr_names:\n expressions[\"ExpressionAttributeNames\"] = self.refs.attr_names\n if self.refs.attr_values:\n expressions[\"ExpressionAttributeValues\"] = self.refs.attr_values\n return expressions\nbloop/types.py\nclass String(Type):\n python_type = str\n backing_type = STRING\n\n def dynamo_load(self, value, *, context, **kwargs):\n if not value:\n return \"\"\n return value\n\n def dynamo_dump(self, value, *, context, **kwargs):\n if not value:\n return None\n return value\n", "answers": [" class Blob(BaseModel):"], "length": 2045, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "8857338affe2d9fe32dc189b478b4aa891b3905618953f5b"} {"input": "package de.fau.cs.mad.yasme.android.ui.fragments;\nimport android.app.Fragment;\nimport android.content.Context;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.Spinner;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.List;\nimport de.fau.cs.mad.yasme.android.R;\nimport de.fau.cs.mad.yasme.android.asyncTasks.server.GetImageWithoutSavingTask;\nimport de.fau.cs.mad.yasme.android.asyncTasks.server.SearchUserTask;\nimport de.fau.cs.mad.yasme.android.controller.FragmentObservable;\nimport de.fau.cs.mad.yasme.android.controller.Log;\nimport de.fau.cs.mad.yasme.android.controller.NotifiableFragment;\nimport de.fau.cs.mad.yasme.android.controller.ObservableRegistry;\nimport de.fau.cs.mad.yasme.android.controller.Toaster;\nimport de.fau.cs.mad.yasme.android.entities.User;\nimport de.fau.cs.mad.yasme.android.storage.DatabaseManager;\nimport de.fau.cs.mad.yasme.android.storage.PictureManager;\nimport de.fau.cs.mad.yasme.android.ui.UserAdapter;\n\n\n\n\n/**\n * Created by Stefan Ettl \n */\n\npublic class SearchContactFragment\n extends Fragment\n implements View.OnClickListener,\n AdapterView.OnItemClickListener,\n NotifiableFragment {\n\n private List users;\n private Spinner searchSpinner;\n private Button searchButton;\n private ListView searchResultView;\n private TextView searchText;\n\n //private AtomicInteger bgTasksRunning = new AtomicInteger(0);\n private UserAdapter mAdapter;\n private OnSearchFragmentInteractionListener mListener;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\n\n @Override\n public void onStart() {\n super.onStart();", "context": "yasme/src/main/java/de/fau/cs/mad/yasme/android/storage/DatabaseManager.java\npublic enum DatabaseManager {\n INSTANCE;\n\n private boolean mInitialized = false;\n private boolean mDBInitialized = false;\n private DatabaseHelper mHelper;\n private Context mContext;\n private long mUserId = -1;\n private long mDeviceId = -1;\n private String mAccessToken = null;\n private long serverInfoUpdateTime = -1;\n private ServerInfo serverInfo = null;\n private SharedPreferences mSharedPreferences, mSettings;\n private String mUserEmail;\n private NewMessageNotificationManager notifier = null;\n\n private UserDAO userDAO;\n private ChatDAO chatDAO;\n private MessageDAO messageDAO;\n private MessageKeyDAO messageKeyDAO;\n private DeviceDAO deviceDAO;\n\n\n public void init(Context context, SharedPreferences sharedPreferences,\n SharedPreferences settings, long userId) {\n mContext = context;\n mSharedPreferences = sharedPreferences;\n mSettings = settings;\n mUserId = userId;\n initDB(context, userId);\n initializeDAOs();\n mInitialized = true;\n }\n\n public void initDB(Context context, long userId) {\n mHelper = new DatabaseHelper(context, userId);\n mDBInitialized = true;\n }\n\n public boolean isInitialized() {\n return mInitialized;\n }\n\n public boolean isDBInitialized() {\n return mDBInitialized;\n }\n\n private DatabaseHelper getHelper() {\n return mHelper;\n }\n\n public SharedPreferences getSharedPreferences() {\n return mSharedPreferences;\n }\n\n public SharedPreferences getSettings() {\n return mSettings;\n }\n\n public Context getContext() {\n return mContext;\n }\n\n private void initializeDAOs() {\n UserDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n userDAO = UserDAOImpl.INSTANCE;\n\n ChatDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n chatDAO = ChatDAOImpl.INSTANCE;\n\n MessageDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n messageDAO = MessageDAOImpl.INSTANCE;\n\n MessageKeyDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n messageKeyDAO = MessageKeyDAOImpl.INSTANCE;\n\n DeviceDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n deviceDAO = DeviceDAOImpl.INSTANCE;\n }\n\n public UserDAO getUserDAO() {\n return userDAO;\n }\n\n public ChatDAO getChatDAO() {\n return chatDAO;\n }\n\n public MessageDAO getMessageDAO() {\n return messageDAO;\n }\n\n public MessageKeyDAO getMessageKeyDAO() {\n return messageKeyDAO;\n }\n\n public DeviceDAO getDeviceDAO() {\n return deviceDAO;\n }\n\n public long getUserId() {\n if (-1 == mUserId) {\n mUserId = getSharedPreferences().getLong(AbstractYasmeActivity.USER_ID, -1);\n }\n return mUserId;\n }\n\n public void setUserId(long mUserId) {\n this.mUserId = mUserId;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putLong(AbstractYasmeActivity.USER_ID, mUserId);\n editor.apply();\n }\n\n public long getDeviceId() {\n if (-1 == mDeviceId) {\n mDeviceId = getSharedPreferences().getLong(AbstractYasmeActivity.DEVICE_ID, -1);\n }\n return mDeviceId;\n }\n\n public void setDeviceId(long mDeviceId) {\n this.mDeviceId = mDeviceId;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putLong(AbstractYasmeActivity.DEVICE_ID, mDeviceId);\n editor.apply();\n }\n\n public String getAccessToken() {\n if (null == mAccessToken) {\n mAccessToken = getSharedPreferences().getString(AbstractYasmeActivity.ACCESSTOKEN, null);\n }\n return mAccessToken;\n }\n\n public void setAccessToken(String accessToken) {\n this.mAccessToken = accessToken;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(AbstractYasmeActivity.ACCESSTOKEN, mAccessToken);\n editor.commit();\n }\n\n public long getServerInfoUpdateTime() {\n if (-1 == serverInfoUpdateTime) {\n serverInfoUpdateTime = getSharedPreferences().getLong(AbstractYasmeActivity.SERVERINFOUPDATETIME, -1);\n }\n return serverInfoUpdateTime;\n }\n\n public void setServerInfoUpdateTime() {\n this.serverInfoUpdateTime = System.currentTimeMillis();\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putLong(AbstractYasmeActivity.SERVERINFOUPDATETIME, serverInfoUpdateTime);\n editor.commit();\n }\n\n public ServerInfo getServerInfo() {\n return serverInfo;\n }\n\n public void setServerInfo(ServerInfo serverInfo) {\n this.serverInfo = serverInfo;\n }\n\n public String getUserEmail() {\n if (null == mUserEmail || \"\" == mUserEmail) {\n mUserEmail = getSharedPreferences().getString(AbstractYasmeActivity.USER_MAIL, null);\n }\n return mUserEmail;\n }\n\n public void setUserEmail(String mUserEmail) {\n this.mUserEmail = mUserEmail;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(AbstractYasmeActivity.USER_MAIL, mUserEmail);\n editor.commit();\n }\n\n public NewMessageNotificationManager getNotifier() {\n if (notifier == null) {\n notifier = new NewMessageNotificationManager();\n }\n return notifier;\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/storage/PictureManager.java\npublic enum PictureManager {\n INSTANCE;\n\n private Context mContext = DatabaseManager.INSTANCE.getContext();\n\n private Bitmap scaleBitmap(Bitmap bigBitmap, int newMaxSize) {\n float picScale = ((float) newMaxSize)\n / ((float) Math.max(bigBitmap.getHeight(), bigBitmap.getWidth()));\n int newHeight = (int) (bigBitmap.getHeight() * picScale);\n int newWidth = (int) (bigBitmap.getWidth() * picScale);\n Bitmap bitmap = Bitmap.createScaledBitmap(bigBitmap, newWidth, newHeight, false);\n return bitmap;\n }\n\n public byte[] scaledBitmapToByteArray(Bitmap bitmap, int newMaxSize) {\n float picScale = ((float) newMaxSize)\n / ((float) Math.max(bitmap.getHeight(), bitmap.getWidth()));\n int newHeight = (int) (bitmap.getHeight() * picScale);\n int newWidth = (int) (bitmap.getWidth() * picScale);\n Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);\n\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);\n return stream.toByteArray();\n }\n\n /**\n * Stores a given bitmap on internal storage\n *\n * @param user for generating the filename\n * @param bitmap bitmap to be stored\n * @return path of the stored picture\n */\n public String storePicture(User user, Bitmap bitmap) throws IOException {\n // TODO Remove old picture\n // I think it will be replaced automatically\n\n // Create directory userPictures\n ContextWrapper cw = new ContextWrapper(mContext);\n File directory = cw.getDir(\"userPictures\", Context.MODE_PRIVATE);\n\n // Generate file name\n String filename = user.getId() + \"_profilePicture.jpg\";\n\n // Concatenate directory and filename to path\n File path = new File(directory, filename);\n\n FileOutputStream fileOutputStream = new FileOutputStream(path);\n BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);\n\n // scale down bitmap\n Bitmap scaledBitmap = scaleBitmap(bitmap, 300);\n\n // Use the compress method on the BitMap object to write image to the OutputStream\n scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);\n\n bos.flush();\n bos.close();\n fileOutputStream.close();\n\n Log.d(this.getClass().getSimpleName(), \"Picture stored under: \" + path.getAbsolutePath());\n return path.getAbsolutePath();\n }\n\n\n public static int calculateInSampleSize(\n BitmapFactory.Options options, int reqWidth, int reqHeight) {\n // Raw height and width of image\n final int height = options.outHeight;\n final int width = options.outWidth;\n int inSampleSize = 1;\n\n if (height > reqHeight || width > reqWidth) {\n\n final int halfHeight = height / 2;\n final int halfWidth = width / 2;\n\n // Calculate the largest inSampleSize value that is a power of 2 and keeps both\n // height and width larger than the requested height and width.\n while ((halfHeight / inSampleSize) > reqHeight\n && (halfWidth / inSampleSize) > reqWidth) {\n inSampleSize *= 2;\n }\n }\n return inSampleSize;\n }\n\n /**\n * Fetches the profilePicture from the storage sampled to a smaller size\n *\n * @param user User\n * @param reqHeight int\n * @param reqWidth int\n * @return profilePicture as a bitmap\n */\n public Bitmap getPicture(User user, int reqHeight, int reqWidth) {\n String path = user.getProfilePicture();\n if (path == null || path.isEmpty()) {\n return null;\n }\n File file = new File(path);\n if (!file.exists()) {\n return null;\n }\n\n // First decode with inJustDecodeBounds=true to check dimensions\n final BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeFile(path, options);\n\n // Calculate inSampleSize\n options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);\n\n // Decode bitmap with inSampleSize set\n options.inJustDecodeBounds = false;\n return BitmapFactory.decodeFile(path, options);\n }\n\n public boolean deletePicture(User user) {\n String path = user.getProfilePicture();\n if (path == null || path.isEmpty()) {\n return false;\n }\n File file = new File(path);\n if (!file.exists()) {\n return false;\n }\n return file.delete();\n }\n\n /**\n * @param bitmap\n * @return converting bitmap and return a string\n */\n public String bitMapToString(Bitmap bitmap) {\n Bitmap btmp = scaleBitmap(bitmap, 512);\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n btmp.compress(Bitmap.CompressFormat.PNG, 100, baos);\n byte[] b = baos.toByteArray();\n String temp = Base64.encodeToString(b, Base64.DEFAULT);\n return temp;\n }\n\n /**\n * @param encodedString\n * @return bitmap (from given string)\n */\n public Bitmap stringToBitMap(String encodedString) {\n try {\n byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);\n Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);\n return bitmap;\n } catch (Exception e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return null;\n }\n }\n\n /**\n * Create a file Uri for saving an image or video\n */\n public static File getOutputMediaFilePath() throws IOException {\n File mediaStorageDir = new File(\n Environment.getExternalStorageDirectory(),\n \"Yasme Pictures\");\n\n // Create the storage directory if it does not exist\n if (!mediaStorageDir.exists()) {\n if (!mediaStorageDir.mkdirs()) {\n Log.d(\"MyCameraApp\", \"failed to create directory\");\n return null;\n }\n }\n\n // Create a media file name\n String timeStamp = new SimpleDateFormat(\"yyyyMMdd_HHmmss\").format(new Date());\n File mediaFile = new File(mediaStorageDir.getPath() + File.separator +\n \"IMG_\" + timeStamp + \".jpg\");\n\n return mediaFile;\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/entities/User.java\n@JsonIgnoreProperties(ignoreUnknown = true)\n@DatabaseTable(tableName = DatabaseConstants.USER_TABLE)\npublic class User implements Serializable {\n\n @DatabaseField(columnName = DatabaseConstants.USER_ID, id = true)\n private long id;\n\n @DatabaseField(columnName = DatabaseConstants.USER_NAME)\n private String name;\n\n //@DatabaseField(columnName = DatabaseConstants.USER_EMAIL)\n private String email;\n\n private String pw;\n\n @JsonIgnore\n private List devices; // Just for convenience\n\n @DatabaseField(columnName = DatabaseConstants.USER_LAST_MODIFIED)\n private Date lastModified;\n\n @DatabaseField(columnName = DatabaseConstants.USER_CREATED)\n private Date created;\n\n @JsonIgnore\n @DatabaseField(columnName = DatabaseConstants.USER_PICTURE)\n private String profilePicture;\n\n\n @JsonIgnore\n @DatabaseField(columnName = DatabaseConstants.CONTACT)\n private int contactFlag = 0;\n\n\n public User(String pw, String name, String email) {\n this.pw = pw;\n this.name = name;\n this.email = email;\n }\n\n public User(String email, String pw) {\n this.email = email;\n this.pw = pw;\n }\n\n public User(String name, long id) {\n this.name = name;\n this.id = id;\n }\n\n public User(long id) {\n this.id = id;\n }\n\n public User(String name, String email, long id) {\n this.name = name;\n this.email = email;\n this.id = id;\n }\n\n public User() {\n // ORMLite needs a no-arg constructor\n }\n\n /*\n * Getters\n */\n\n @JsonIgnoreProperties({\"id\", \"user\", \"publicKey\", \"product\", \"lastModified\"})\n public List getDevices() {\n return devices;\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getName() {\n return name;\n }\n\n public String getPw() {\n return pw;\n }\n\n public long getId() {\n return id;\n }\n\n public Date getLastModified() {\n return lastModified;\n }\n\n public Date getCreated() {\n return created;\n }\n\n public String getProfilePicture() {\n return profilePicture;\n }\n\n /*\n * Setters\n */\n\n public void setDevices(List devices) {\n this.devices = devices;\n }\n\n public void setPw(String pw) {\n this.pw = pw;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public void setLastModified(Date lastModified) {\n this.lastModified = lastModified;\n }\n\n public void setCreated(Date created) {\n this.created = created;\n }\n\n public void setProfilePicture(String profilePicture) {\n this.profilePicture = profilePicture;\n }\n\n @JsonIgnore\n public void addToContacts() {\n contactFlag = 1;\n }\n\n @JsonIgnore\n public void removeFromContacts() {\n contactFlag = 0;\n }\n\n @JsonIgnore\n public boolean isContact() {\n return contactFlag == 1;\n }\n\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/asyncTasks/server/SearchUserTask.java\npublic class SearchUserTask extends AsyncTask> {\n\n\n private SearchBy searchBy;\n private String searchText;\n private Class classToNotify;\n\n public SearchUserTask(SearchBy searchBy, String searchText, Class classToNotify) {\n this.searchBy = searchBy;\n this.searchText = searchText;\n this.classToNotify = classToNotify;\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n SpinnerObservable.getInstance().registerBackgroundTask(this);\n }\n\n @Override\n protected List doInBackground(String... params) {\n SearchTask searchTask = SearchTask.getInstance();\n List uList = new ArrayList();\n\n try {\n switch (searchBy) {\n case LIKE:\n uList = searchTask.userByLike(String.valueOf(searchText));\n return uList;\n case MAIL:\n uList.add(searchTask.userByMail(String.valueOf(searchText)));\n return uList;\n case NUMBER:\n uList.add(searchTask.userByNumber(String.valueOf(searchText)));\n return uList;\n case ID:\n uList.add(searchTask.userById(String.valueOf(searchText)));\n return uList;\n default:\n return uList;\n }\n } catch (RestServiceException rse) {\n Log.e(this.getClass().getSimpleName(), rse.getMessage());\n }\n\n return null;\n }\n\n\n protected void onPostExecute(List userList) {\n SpinnerObservable.getInstance().removeBackgroundTask(this);\n if (classToNotify == SearchContactFragment.class) {\n ObservableRegistry.getObservable(SearchContactFragment.class)\n .notifyFragments(new SearchContactFragment.UsersClass(userList));\n }\n if (classToNotify == QRCodeFragment.class) {\n ObservableRegistry.getObservable(QRCodeFragment.class).notifyFragments(userList);\n }\n }\n\n public enum SearchBy {\n LIKE,\n MAIL,\n NUMBER,\n UNKNOWN,\n ID;\n\n public static SearchBy getSearchBy(int searchBy) {\n switch (searchBy) {\n case 0:\n return LIKE;\n case 1:\n return MAIL;\n case 2:\n return ID;\n }\n return UNKNOWN;\n }\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/Log.java\npublic class Log {\r\n static final boolean LOG_I = BuildConfig.DEBUG;\r\n static final boolean LOG_E = BuildConfig.DEBUG;\r\n static final boolean LOG_D = BuildConfig.DEBUG;\r\n static final boolean LOG_V = BuildConfig.DEBUG;\r\n static final boolean LOG_W = BuildConfig.DEBUG;\r\n\r\n public static void i(String tag, String string) {\r\n if (LOG_I) android.util.Log.i(tag, string);\r\n }\r\n public static void e(String tag, String string) {\r\n if (LOG_E) android.util.Log.e(tag, string);\r\n }\r\n public static void d(String tag, String string) {\r\n if (LOG_D) android.util.Log.d(tag, string);\r\n }\r\n public static void v(String tag, String string) {\r\n if (LOG_V) android.util.Log.v(tag, string);\r\n }\r\n public static void w(String tag, String string) {\r\n if (LOG_W) android.util.Log.w(tag, string);\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/Toaster.java\npublic class Toaster {\r\n private static Toaster instance;\r\n private Context context;\r\n private Set toastables = new HashSet<>();\r\n\r\n private Toaster() {\r\n context = DatabaseManager.INSTANCE.getContext();\r\n }\r\n\r\n public static Toaster getInstance() {\r\n if (instance == null) {\r\n instance = new Toaster();\r\n }\r\n return instance;\r\n }\r\n\r\n public void register(Toastable toast) {\r\n toastables.add(toast);\r\n }\r\n\r\n public void remove(Toastable toast) {\r\n toastables.remove(toast);\r\n }\r\n\r\n public void toast(int id, int duration) {\r\n for (Toastable toast : toastables) {\r\n toast.toast(id,duration);\r\n }\r\n }\r\n\r\n public void toast(String text, int duration) {\r\n for (Toastable toast : toastables) {\r\n toast.toast(text, duration);\r\n }\r\n }\r\n\r\n public void toast(String text, int duration, int gravity) {\r\n for (Toastable toast : toastables) {\r\n toast.toast(text, duration, gravity);\r\n }\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/ObservableRegistry.java\npublic class ObservableRegistry {\n\n private static ArrayList entries = new ArrayList();\n\n public static , P> FragmentObservable getObservable(Class fragmentClass) {\n for (ObservableRegistryEntry entry : entries) {\n if (entry.check(fragmentClass)) {\n Log.d(\"ObserverRegistry\",\"Returned existing observable\");\n return (FragmentObservable) entry.getObs(); // no idea how to solve this... \n }\n }\n\n FragmentObservable res = new FragmentObservable();\n Log.d(\"ObserverRegistry\",\"Created new observable\");\n entries.add(new ObservableRegistryEntry

(res,fragmentClass));\n return res;\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/ui/UserAdapter.java\npublic class UserAdapter extends ArrayAdapter {\n private List users;\n private final Context context;\n private SparseBooleanArray selectedContacts = new SparseBooleanArray();\n private int layout = R.layout.user_item;\n\n public SparseBooleanArray getSelectedContacts() {\n return selectedContacts;\n }\n\n /**\n * @see Color palette used\n * from K9 Mail\n */\n public final static int CONTACT_DUMMY_COLORS_ARGB[] = {\n 0xff33B5E5,\n 0xffAA66CC,\n 0xff99CC00,\n 0xffFFBB33,\n 0xffFF4444,\n 0xff0099CC,\n 0xff9933CC,\n 0xff669900,\n 0xffFF8800,\n 0xffCC0000\n };\n\n public UserAdapter(Context context, int resource, List users) {\n super(context, resource, users);\n this.users = users;\n this.context = context;\n this.layout = resource;\n }\n\n @Override\n public void notifyDataSetChanged() {\n selectedContacts = new SparseBooleanArray();\n super.notifyDataSetChanged();\n }\n\n @Override\n public View getView(final int position, View convertView, ViewGroup parent) {\n User user = DatabaseManager.INSTANCE.getUserDAO().get(users.get(position).getId());\n if (user == null) {\n Log.w(this.getClass().getSimpleName(), \"User not found in DB\");\n user = users.get(position);\n }\n\n LayoutInflater inflater = ((Activity) context).getLayoutInflater();\n\n View rowView = inflater.inflate(layout, parent, false);\n\n ImageView profileImage = (ImageView) rowView.findViewById(R.id.user_picture);\n TextView initial = (TextView) rowView.findViewById(R.id.user_picture_text);\n TextView profileName = (TextView) rowView.findViewById(R.id.user_name);\n TextView profileId = (TextView) rowView.findViewById(R.id.user_id);\n CheckBox checkBox;\n if (layout == R.layout.user_item_checkbox) {\n checkBox = (CheckBox) rowView.findViewById(R.id.checkBox);\n } else {\n checkBox = null;\n }\n\n boolean isSelf = (user.getId() == DatabaseManager.INSTANCE.getUserId());\n if (isSelf) {\n SharedPreferences storage = context\n .getSharedPreferences(AbstractYasmeActivity.STORAGE_PREFS, Context.MODE_PRIVATE);\n user.setProfilePicture(storage.getString(AbstractYasmeActivity.PROFILE_PICTURE, null));\n }\n\n if (user.getProfilePicture() != null && !user.getProfilePicture().isEmpty()) {\n // load picture from local storage\n initial.setVisibility(View.GONE);\n profileImage.setBackgroundColor(Color.TRANSPARENT);\n profileImage.setImageBitmap(PictureManager.INSTANCE.getPicture(user, 50, 50));\n } else {\n // no local picture found. Set default pic\n profileImage.setBackgroundColor(CONTACT_DUMMY_COLORS_ARGB\n [(int) user.getId() % CONTACT_DUMMY_COLORS_ARGB.length]);\n initial.setText(user.getName().substring(0, 1).toUpperCase());\n }\n\n profileName.setText(user.getName());\n profileId.setText(\"YD \" + user.getId());\n if (checkBox != null) {\n checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton compoundButton, boolean b) {\n selectedContacts.append(position, b);\n }\n });\n }\n\n rowView.requestFocus();\n return rowView;\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/NotifiableFragment.java\npublic interface NotifiableFragment {\n\n void notifyFragment(T value);\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/FragmentObservable.java\npublic class FragmentObservable, P> {\r\n private Set fragments;\r\n private P buffer;\r\n\r\n public FragmentObservable() {\r\n fragments = new HashSet();\r\n }\r\n\r\n public void register(T fragment) {\r\n fragments.add(fragment);\r\n if (buffer != null) {\r\n notifyFragments(buffer);\r\n }\r\n }\r\n\r\n public void remove(T fragment) {\r\n fragments.remove(fragment);\r\n }\r\n\r\n //addIfNotExists\r\n public void notifyFragments(P parameter) {\r\n buffer = parameter;\r\n for (T fragment : fragments) {\r\n try {\r\n Log.d(this.getClass().getSimpleName(), \"Notify fragment: \" + fragment.getClass().getSimpleName());\r\n fragment.notifyFragment(parameter);\r\n buffer = null;\r\n } catch (Exception e) {\r\n Log.e(this.getClass().getSimpleName(), \"Notify fragment failed: \" + fragment.getClass().getSimpleName());\r\n }\r\n }\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/asyncTasks/server/GetImageWithoutSavingTask.java\npublic class GetImageWithoutSavingTask extends AsyncTask {\n\n private BitmapDrawable profilePicture;\n private Class classToNotify;\n private boolean isSelf;\n private User user;\n\n public GetImageWithoutSavingTask(Class classToNotify, User user) {\n this.classToNotify = classToNotify;\n this.user = user;\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n SpinnerObservable.getInstance().registerBackgroundTask(this);\n }\n\n /**\n * @return true on success, false on error\n */\n @Override\n protected Boolean doInBackground(Long... params) {\n long userId = user.getId();\n\n try {\n profilePicture = UserTask.getInstance().getProfilePicture(userId);\n } catch (RestServiceException e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return false;\n }\n if (profilePicture == null) {\n Log.d(this.getClass().getSimpleName(), \"profilePicture was null\");\n user.setProfilePicture(null);\n return true;\n }\n\n isSelf = (userId == DatabaseManager.INSTANCE.getUserId());\n\n String path;\n try {\n path = PictureManager.INSTANCE.storePicture(user, profilePicture.getBitmap());\n } catch (IOException e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return false;\n }\n if (path != null && !path.isEmpty()) {\n user.setProfilePicture(path);\n } else {\n return false;\n }\n\n return true;\n }\n\n @Override\n protected void onPostExecute(Boolean success) {\n SpinnerObservable.getInstance().removeBackgroundTask(this);\n if (success) {\n if (classToNotify == null) {\n //No one to notify\n return;\n }\n // Notify registered fragments\n FragmentObservable obs =\n ObservableRegistry.getObservable(classToNotify);\n obs.notifyFragments(new SearchContactFragment.ImageClass(profilePicture, user));\n }\n }\n}\n", "answers": [" FragmentObservable obs"], "length": 2473, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "9b3cf05beccb404c5889b37c9c94f311cd351532699c046f"} {"input": "import android.animation.Animator;\nimport android.animation.AnimatorListenerAdapter;\nimport android.annotation.TargetApi;\nimport android.app.AlertDialog;\nimport android.app.Fragment;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.text.InputType;\nimport android.text.TextUtils;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.regex.Pattern;\nimport de.fau.cs.mad.yasme.android.BuildConfig;\nimport de.fau.cs.mad.yasme.android.EditTextWithX;\nimport de.fau.cs.mad.yasme.android.R;\nimport de.fau.cs.mad.yasme.android.asyncTasks.server.ChangePasswordTask;\nimport de.fau.cs.mad.yasme.android.asyncTasks.server.DeviceRegistrationTask;\nimport de.fau.cs.mad.yasme.android.asyncTasks.server.UserLoginTask;\nimport de.fau.cs.mad.yasme.android.controller.FragmentObservable;\nimport de.fau.cs.mad.yasme.android.controller.Log;\nimport de.fau.cs.mad.yasme.android.controller.NotifiableFragment;\nimport de.fau.cs.mad.yasme.android.controller.ObservableRegistry;\nimport de.fau.cs.mad.yasme.android.controller.Toaster;\nimport de.fau.cs.mad.yasme.android.encryption.PasswordEncryption;\nimport de.fau.cs.mad.yasme.android.entities.ServerInfo;\nimport de.fau.cs.mad.yasme.android.entities.User;\nimport de.fau.cs.mad.yasme.android.storage.DatabaseManager;\nimport de.fau.cs.mad.yasme.android.storage.DebugManager;\nimport de.fau.cs.mad.yasme.android.ui.AbstractYasmeActivity;\nimport de.fau.cs.mad.yasme.android.ui.activities.ChatListActivity;\n obs.remove(this);\n }\n\n private void registerDialog() {\n getFragmentManager().beginTransaction()\n .add(R.id.singleFragmentContainer, new RegisterFragment()).commit();\n }\n\n /**\n * Attempts to sign in or register the account specified by the login form.\n * If there are form errors (missing fields, etc.), the errors are presented\n * and no actual login attempt is made.\n */\n public void attemptLogin() {\n if (authTask == null) {\n authTask = new UserLoginTask(true, this.getClass());\n Log.d(this.getClass().getSimpleName(), \"AuthTask is null\");\n }\n\n // Reset errors.\n emailView.setError(null);\n passwordView.setError(null);\n\n // Store values at the time of the login attempt.\n emailTmp = emailView.getText().toString();\n passwordTmp = passwordView.getText().toString();\n\n boolean cancel = false;\n\n // Check for a valid password.\n if (TextUtils.isEmpty(passwordTmp)) {\n passwordView.setError(getString(R.string.error_field_required));\n focusView = passwordView;\n cancel = true;\n } else if (passwordTmp.length() < 8) {\n passwordView.setError(getString(R.string.error_invalid_password));\n focusView = passwordView;\n cancel = true;\n }\n\n // Check for a valid mail.\n if (TextUtils.isEmpty(emailTmp)) {\n emailView.setError(getString(R.string.error_field_required));\n focusView = emailView;\n cancel = true;\n }\n\n if (cancel) {\n // There was an error; don't attempt login and focus the first\n // form field with an error.\n focusView.requestFocus();\n } else {\n // Show a progress spinner, and kick off a background task to\n // perform the user login attempt.\n loginStatusMessageView.setText(R.string.login_progress_signing_in);\n showProgress(true);\n\n // Hide the virtual keyboard\n AbstractYasmeActivity activity = (AbstractYasmeActivity) getActivity();\n View focus = activity.getCurrentFocus();\n if (null == focus) {\n focus = focusView;\n }\n if (null == focus) {\n focus = passwordView;\n }\n if (null == focus) {\n focus = emailView;\n }\n InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);\n if (null != imm && null != focus)\n imm.hideSoftInputFromWindow(focus.getWindowToken(), 0);\n\n // Start the asynctask\n authTask.execute(emailTmp, passwordTmp);\n authTask = null;\n }\n }\n\n public void onPostLoginExecute(Boolean success, long userId) {\n AbstractYasmeActivity activity = (AbstractYasmeActivity) getActivity();\n\n activity.getSelfUser().setId(userId);\n\n if (success) {\n //Initialize database (once in application)\n if (!DatabaseManager.INSTANCE.isInitialized()) {\n Log.e(getClass().getSimpleName(), \"DB-Manger hasn't been initialized\");\n }\n DatabaseManager.INSTANCE.setUserId(userId);\n\n // check if there is a device in the Database\n if (yasmeDeviceCheck()) {\n Log.d(this.getClass().getSimpleName(), \"Device exists in Database\");\n\n long deviceId = DatabaseManager.INSTANCE.getSharedPreferences().getLong(AbstractYasmeActivity.DEVICE_ID, -1);\n if (deviceId < 0) {\n // Error ocurred\n Log.e(this.getClass().getSimpleName(), \"Could not load registered device's id from shared prefs\");\n showProgress(false);\n return;\n }\n\n DatabaseManager.INSTANCE.setDeviceId(deviceId);\n\n showProgress(false);\n Intent intent = new Intent(activity, ChatListActivity.class);\n startActivity(intent);\n getActivity().finish();\n } else {\n // register device\n Log.d(this.getClass().getSimpleName(), \"Device does not exist in Database\");\n Log.d(this.getClass().getSimpleName(), \"Starting task to register device at yasme server\");\n\n new DeviceRegistrationTask(activity, this.getClass())\n .execute(Long.toString(userId), this.deviceProduct, this.getClass().getName());\n\n }\n } else {\n Log.d(getClass().getSimpleName(), \"Login failed\");", "context": "yasme/src/main/java/de/fau/cs/mad/yasme/android/encryption/PasswordEncryption.java\npublic class PasswordEncryption{\r\n\r\n private static final String SALT = \"Y45M3\";\r\n private User user;\r\n\r\n public PasswordEncryption(User user) {\r\n this.user = user;\r\n }\r\n\r\n /**\r\n * get a secure password (hashed and salted)\r\n *\r\n * @return user-object containing the secure password\r\n */\r\n public User securePassword(){\r\n String secure = getSecurePassword();\r\n user.setPw(secure);\r\n return user;\r\n }\r\n\r\n\r\n /**\r\n * get a secure password (hashed and salted)\r\n *\r\n * @return hashed and salted password as String\r\n */\r\n public String getSecurePassword(){\r\n return SHA512(salt(SALT,user.getPw()));\r\n }\r\n\r\n\r\n /**\r\n * hash the password using SHA-512\r\n *\r\n * @param password password that should be hashed\r\n * @return hashed String\r\n */\r\n private String SHA512(String password){\r\n try {\r\n MessageDigest md = MessageDigest.getInstance(\"SHA-512\");\r\n md.update(password.getBytes(\"UTF-8\"));\r\n byte[] hash = md.digest();\r\n Base64 base64 = new Base64();\r\n return new String(base64.base64Encode(hash));\r\n }\r\n catch (Exception e){\r\n Log.d(this.getClass().getSimpleName(), \"Hashing Password failed\");\r\n Log.d(this.getClass().getSimpleName(), \"Error: \" + e.getMessage());\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * salt the password\r\n *\r\n * @param salt salt-value that should be used\r\n * @param password password that should be secured\r\n * @return salted password\r\n */\r\n private String salt(String salt, String password){\r\n String passwordSalted = salt+password;\r\n return passwordSalted;\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/ui/activities/ChatListActivity.java\npublic class ChatListActivity extends AbstractYasmeActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n //progress bar in actionbar\n requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);\n\n setContentView(R.layout.activity_with_single_fragment);\n\n if (HttpClient.context == null) {\n HttpClient.context = this.getApplicationContext();\n }\n\n SharedPreferences devicePrefs = getSharedPreferences(DEVICE_PREFS, MODE_PRIVATE);\n\n // Make sure that the device has been registered. Otherwise several other tasks will fail\n long deviceId = DatabaseManager.INSTANCE.getDeviceId();\n if (deviceId <= 0) {\n Log.e(this.getClass().getSimpleName(), \"Device id should not be <= 0 after login. \" +\n \"Looks like the device registration failed but no one was notified about that\");\n }\n\n if (savedInstanceState == null) {\n getFragmentManager().beginTransaction()\n .add(R.id.singleFragmentContainer, new ChatListFragment()).commit();\n }\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.chatlist, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if (id == R.id.action_add_chat) {\n Intent intent = new Intent(this, InviteToChatActivity.class);\n startActivity(intent);\n return true;\n }\n if (id == R.id.sign_out) {\n new LogoutTask().execute();\n }\n return super.onOptionsItemSelected(item);\n }\n\n protected void startLoginActivity() {\n //setSignedInFlag(false);\n DatabaseManager.INSTANCE.setAccessToken(null);\n Intent intent = new Intent(this, LoginActivity.class);\n startActivity(intent);\n finish();\n }\n\n private class LogoutTask extends AsyncTask {\n @Override\n protected Boolean doInBackground(Void... voids) {\n try {\n AuthorizationTask.getInstance().logoutUser();\n } catch (RestServiceException e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n Log.i(this.getClass().getSimpleName(), \"Sign out not succesfull\");\n return false;\n }\n return true;\n }\n\n protected void onPostExecute(Boolean success) {\n if (!success) {\n return;\n }\n startLoginActivity();\n }\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/entities/ServerInfo.java\npublic class ServerInfo {\r\n String message;\r\n boolean loginAllowed = true;\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n\r\n public void setMessage(String message) {\r\n this.message = message;\r\n }\r\n\r\n public boolean getLoginAllowed() {\r\n return loginAllowed;\r\n }\r\n\r\n public void setLoginAllowed(boolean loginAllowed) {\r\n this.loginAllowed = loginAllowed;\r\n }\r\n\r\n public boolean hasMessage() {\r\n return message != null && message.length() > 0;\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/ui/AbstractYasmeActivity.java\npublic abstract class AbstractYasmeActivity extends Activity implements Toastable {\n public final static String USER_ID = \"de.fau.cs.mad.yasme.android.USER_ID\";\n public final static String USER_NAME = \"de.fau.cs.mad.yasme.android.USER_NAME\";\n public final static String USER_MAIL = \"de.fau.cs.mad.yasme.android.USER_MAIL\";\n public final static String USER_PW = \"de.fau.cs.mad.yasme.android.USER_PW\";\n public final static String DEVICE_ID = \"de.fau.cs.mad.yasme.android.DEVICE_ID\";\n public final static String PROFILE_PICTURE = \"de.fau.cs.mad.yasme.android.PROFILE_PICTURE\";\n\n public final static String CHAT_ID = \"de.fau.cs.mad.yasme.android.CHAT_ID\";\n public final static String LAST_MESSAGE_ID = \"de.fau.cs.mad.yasme.android.LAST_MESSAGE_ID\";\n\n public final static String ACCESSTOKEN = \"de.fau.cs.mad.yasme.android.ACCESSTOKEN\";\n public final static String SIGN_IN = \"de.fau.cs.mad.yasme.android.SIGN_IN\";\n\n public final static String SERVERINFOUPDATETIME = \"de.fau.cs.mad.yasme.android.SERVERINFOUPDATETIME\";\n public final static String SERVERMESSAGE = \"de.fau.cs.mad.yasme.android.SERVERMESSAGE\";\n\n public final static String STORAGE_PREFS = \"de.fau.cs.mad.yasme.android.STORAGE_PREFS\";\n public final static String SETTINGS_PREFS = \"de.fau.cs.mad.yasme.android.SETTINGS_PREFS\";\n public final static String DEVICE_PREFS = \"de.fau.cs.mad.yasme.android.DEVICE_PREFS\";\n public final static String PUSH_PREFS = \"de.fau.cs.mad.yasme.android.PUSH_PREFS\";\n\n public final static String NOTIFICATION_VIBRATE = \"de.fau.cs.mad.yasme.android.NOTIFICATION_VIBRATE\";\n public final static String NOTIFICATION_SOUND = \"de.fau.cs.mad.yasme.android.NOTIFICATION_SOUND\";\n\n\n //GCM Properties\n public static final String PROPERTY_REG_ID = \"registration_id\";\n public static final String PROPERTY_APP_VERSION = \"appVersion\";\n public static final String SENDER_ID = \"688782154540\"; //\"104759172131\";\n public static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;\n public static final String TAG = \"YasmeGCM\";\n\n protected User selfUser;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (!ConnectionTask.isInitialized()) {\n String server = getResources().getString(R.string.server_host);\n if (BuildConfig.DEBUG) {\n server = getResources().getString(R.string.server_host_debug);\n }\n Log.d(getClass().getSimpleName(), \"YASME-Server: \" + server);\n ConnectionTask.initParams(getResources().getString(R.string.server_scheme),\n server,\n getResources().getString(R.string.server_port), getResources().getString(R.string.language), getVersion());\n }\n\n SharedPreferences storage = getSharedPreferences(STORAGE_PREFS, MODE_PRIVATE);\n SharedPreferences settings = getSharedPreferences(SETTINGS_PREFS, MODE_PRIVATE);\n Long userId = storage.getLong(USER_ID, 0);\n String userName = storage.getString(USER_NAME, \"\");\n String userMail = storage.getString(USER_MAIL, \"\");\n String userPw = storage.getString(USER_PW, \"password\");\n\n if(selfUser==null) {\n selfUser = new User();\n }\n selfUser.setId(userId);\n selfUser.setName(userName);\n selfUser.setEmail(userMail);\n selfUser.setPw(userPw);\n\n\n //Initialize databaseManager (once in application)\n if (!DatabaseManager.INSTANCE.isInitialized()) {\n DatabaseManager.INSTANCE.init(this, storage, settings, userId);\n }\n //Init QR-Code\n QR.init(false);\n\n String accessToken = DatabaseManager.INSTANCE.getAccessToken();\n if ((accessToken == null || accessToken.length() <= 0) && !this.getClass().equals(LoginActivity.class)) {\n Log.i(this.getClass().getSimpleName(), \"Not logged in, starting login activity\");\n Intent intent = new Intent(this, LoginActivity.class);\n startActivity(intent);\n finish();\n return;\n }\n }\n\n @Override\n public void onStart() {\n super.onStart();\n Toaster.getInstance().register(this);\n stopSpinning();\n SpinnerObservable.getInstance().registerActivity(this);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n String accessToken = DatabaseManager.INSTANCE.getAccessToken();\n if ((accessToken == null || accessToken.length() <= 0) && !this.getClass().equals(LoginActivity.class)) {\n Log.i(this.getClass().getSimpleName(), \"Not logged in, starting login activity\");\n Intent intent = new Intent(this, LoginActivity.class);\n startActivity(intent);\n finish();\n return;\n }\n }\n\n @Override\n public void onStop() {\n super.onStop();\n Toaster.getInstance().remove(this);\n SpinnerObservable.getInstance().removeActivity(this);\n }\n\n public void setActionBarTitle(String title) {\n getActionBar().setTitle(title);\n }\n\n public void setActionBarTitle(String title, String subtitle) {\n getActionBar().setTitle(title);\n getActionBar().setSubtitle(subtitle);\n }\n\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n Intent intent;\n int itemId = item.getItemId();\n switch (itemId) {\n case android.R.id.home:\n if (NavUtils.getParentActivityName(this) != null) {\n NavUtils.navigateUpFromSameTask(this);\n }\n return true;\n case R.id.action_settings:\n intent = new Intent(this, SettingsActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n startActivity(intent);\n return true;\n case R.id.action_chats:\n intent = new Intent(this, ChatListActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n startActivity(intent);\n return true;\n case R.id.action_add_chat:\n intent = new Intent(this, InviteToChatActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);\n startActivity(intent);\n return true;\n case R.id.action_contacts:\n intent = new Intent(this, ContactActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);\n startActivity(intent);\n return true;\n default:\n return super.onOptionsItemSelected(item);\n\n }\n }\n\n public String getSelfName() {\n\n if(selfUser==null) {\n SharedPreferences storage = getSharedPreferences(STORAGE_PREFS, MODE_PRIVATE);\n Long userId = storage.getLong(USER_ID, 0);\n String userName = storage.getString(USER_NAME, \"\");\n String userMail = storage.getString(USER_MAIL, \"\");\n String userPw = storage.getString(USER_PW, \"password\");\n\n selfUser = new User();\n selfUser.setId(userId);\n selfUser.setName(userName);\n selfUser.setEmail(userMail);\n selfUser.setPw(userPw);\n }\n if (selfUser.getName().isEmpty()) {\n String name = getSharedPreferences(STORAGE_PREFS, MODE_PRIVATE).getString(USER_NAME, \"\");\n selfUser.setName(name);\n }\n return selfUser.getName();\n }\n\n public User getSelfUser() {\n return selfUser;\n }\n\n public String getUserMail() {\n if (selfUser == null || selfUser.getEmail().isEmpty()) {\n String mail = getSharedPreferences(STORAGE_PREFS, MODE_PRIVATE).getString(USER_MAIL, \"\");\n selfUser.setEmail(mail);\n }\n return selfUser.getEmail();\n }\n\n public long getUserId() {\n return selfUser.getId();\n }\n\n public String getOwnProfilePicture() {\n String path = selfUser.getProfilePicture();\n if (path == null || path.isEmpty()) {\n path = getSharedPreferences(STORAGE_PREFS, MODE_PRIVATE).getString(PROFILE_PICTURE, null);\n }\n return path;\n }\n\n public void setOwnProfilePicture(String ownProfilePicture) {\n selfUser.setProfilePicture(ownProfilePicture);\n SharedPreferences.Editor editor = getSharedPreferences(STORAGE_PREFS, MODE_PRIVATE).edit();\n editor.putString(AbstractYasmeActivity.PROFILE_PICTURE, ownProfilePicture);\n editor.commit();\n }\n\n public String getAccessToken() {\n return DatabaseManager.INSTANCE.getAccessToken();\n }\n\n public void toast(final int messageId, final int duration) {\n String text = getApplicationContext().getResources().getString(messageId);\n toast(text, duration, -1);\n }\n\n public void toast(final String text, final int duration) {\n toast(text, duration, -1);\n }\n\n public void toast(final String text, final int duration, final int gravity) {\n runOnUiThread(new Runnable() {\n public void run() {\n Toast toast = Toast.makeText(getApplicationContext(), text, duration);\n if (-1 != gravity) {\n toast.setGravity(gravity, 0, 0);\n }\n // otherwise use default position\n Log.d(getClass().getSimpleName(), \"Toast: \" + text);\n toast.show();\n }\n });\n }\n\n public void startSpinning() {\n runOnUiThread(new Runnable() {\n public void run() {\n setProgressBarIndeterminateVisibility(true);\n }\n });\n }\n\n public void stopSpinning() {\n runOnUiThread(new Runnable() {\n public void run() {\n setProgressBarIndeterminateVisibility(false);\n }\n });\n }\n\n public int getVersion() {\n try {\n return getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;\n } catch (Exception e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return 0;\n }\n }\n\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/asyncTasks/server/ChangePasswordTask.java\npublic class ChangePasswordTask extends AsyncTask {\n private User user;\n private String task;\n\n public ChangePasswordTask(User user) {\n this.user = user;\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n SpinnerObservable.getInstance().registerBackgroundTask(this);\n }\n\n /**\n * @param params 0 is flag for preparation to change password\n * 1 is mailToken\n * @return Returns true if it was successful, otherwise false\n */\n @Override\n protected Boolean doInBackground(String... params) {\n if (user.getEmail() == null || user.getEmail().isEmpty()) {\n return false;\n }\n task = params[0];\n if (task.equals(\"1\")) {\n try {\n UserTask.getInstance().requirePasswordToken(user);\n } catch (RestServiceException e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return false;\n }\n } else {\n try {\n UserTask.getInstance().changePassword(user, params[1]);\n } catch (RestServiceException e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return false;\n }\n }\n return true;\n }\n\n @Override\n protected void onPostExecute(final Boolean success) {\n SpinnerObservable.getInstance().removeBackgroundTask(this);\n if (success) {\n if (task.equals(\"1\")) {\n Toaster.getInstance().toast(\n DatabaseManager.INSTANCE.getContext().getString(R.string.sent_token_mail)\n + \" \" + user.getEmail(),\n Toast.LENGTH_SHORT);\n } else {\n Toaster.getInstance().toast(R.string.successful_changed_password, Toast.LENGTH_LONG);\n }\n } else {\n Toaster.getInstance().toast(R.string.error_change_password, Toast.LENGTH_LONG);\n }\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/ObservableRegistry.java\npublic class ObservableRegistry {\n\n private static ArrayList entries = new ArrayList();\n\n public static , P> FragmentObservable getObservable(Class fragmentClass) {\n for (ObservableRegistryEntry entry : entries) {\n if (entry.check(fragmentClass)) {\n Log.d(\"ObserverRegistry\",\"Returned existing observable\");\n return (FragmentObservable) entry.getObs(); // no idea how to solve this... \n }\n }\n\n FragmentObservable res = new FragmentObservable();\n Log.d(\"ObserverRegistry\",\"Created new observable\");\n entries.add(new ObservableRegistryEntry

(res,fragmentClass));\n return res;\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/asyncTasks/server/DeviceRegistrationTask.java\npublic class DeviceRegistrationTask extends AsyncTask {\n\n private long deviceId;\n private Activity activity;\n private String regId;\n private Class classToNotify;\n\n public DeviceRegistrationTask(Activity activity, Class classToNotify) {\n this.activity = activity;\n this.classToNotify = classToNotify;\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n SpinnerObservable.getInstance().registerBackgroundTask(this);\n }\n\n /**\n * @params params[0] is userId\n * @params params[1] is product\n */\n @Override\n protected Boolean doInBackground(String... params) {\n long userId = Long.parseLong(params[0]);\n\n // the product : e.g Google Nexus\n String product = params[1];\n\n // Register for Google Cloud Messaging at Google Server\n if (!registerGCM()) {\n return false;\n }\n\n // Register at YASME server\n return registerDeviceAtYASME(userId, product, regId);\n }\n\n\n private boolean registerGCM() {\n CloudMessaging cloudMessaging = CloudMessaging.getInstance(this.activity);\n\n if (cloudMessaging.checkPlayServices()) {\n String regid = cloudMessaging.getRegistrationId();\n Log.d(this.getClass().getSimpleName(), \"Google reg id is empty? \" + regid.isEmpty());\n if (regid.isEmpty()) {\n regId = cloudMessaging.registerInBackground();\n if (null == regId || regId.isEmpty()) {\n Log.e(this.getClass().getSimpleName(), \"reg id for GCM is empty\");\n return false;\n }\n }\n } else {\n Log.i(AbstractYasmeActivity.TAG, \"No valid Google Play Services APK found.\");\n }\n\n return true;\n }\n\n\n private boolean registerDeviceAtYASME(long userId, String product, String regId) {\n long deviceIdFromServer;\n\n //register device through REST-Call\n // create a new device to be registered\n\n // user which want to register the device\n // ignore the name user, the server will set the right values according to the userId\n User user = new User(\"user\", userId);\n\n // indicates if its a smartphone or a tablet\n // currently unused\n String type = \"device\";\n\n // phone number, currently unused\n String number = null;\n\n KeyEncryption rsa = new KeyEncryption();\n //generate private and public Key\n rsa.generateRSAKeys();\n String pubKeyInBase64 = rsa.getGeneratedPubKeyInBase64();\n\n OwnDevice deviceToBeRegistered = new OwnDevice(user, OwnDevice.Platform.ANDROID, pubKeyInBase64, type, number, product, regId);\n\n // make the REST-Call\n try {\n deviceIdFromServer = DeviceTask.getInstance().registerDevice(deviceToBeRegistered);\n deviceId = deviceIdFromServer;\n //save private and public Key to storage\n rsa.saveRSAKeys(deviceId);\n } catch (RestServiceException e) {\n // if error occurs return false\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return false;\n }\n\n Log.d(this.getClass().getSimpleName(), \"Device registered at yasme server\");\n QR.init(true);\n // For Developer-Devices only\n if (DebugManager.INSTANCE.isDebugMode()) {\n Log.d(getClass().getSimpleName(), \"Store keys to external storage\");\n DebugManager.INSTANCE.storeDeviceId(deviceId);\n }\n\n return true;\n }\n\n @Override\n protected void onPostExecute(final Boolean success) {\n SpinnerObservable.getInstance().removeBackgroundTask(this);\n // after device registration\n ObservableRegistry.getObservable(classToNotify)\n .notifyFragments(new LoginFragment.DeviceRegistrationParam(success));\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/asyncTasks/server/UserLoginTask.java\npublic class UserLoginTask extends AsyncTask {\n private Boolean plainPassword = false;\n private String email;\n private String password;\n private Class classToNotify;\n\n public UserLoginTask(Boolean plainPassword, Class classToNotify) {\n this.plainPassword = plainPassword;\n this.classToNotify = classToNotify;\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n SpinnerObservable.getInstance().registerBackgroundTask(this);\n }\n\n /**\n * @param params 0 is email\n * 1 is password\n * @return\n */\n protected Boolean doInBackground(String... params) {\n GetInfoTask getInfoTask = new GetInfoTask(0);\n getInfoTask.execute();\n\n email = params[0].toLowerCase();\n password = params[1];\n try {\n // DEBUG:\n //Log.d(this.getClass().getSimpleName(), \"email: \" + email + \" \" + \"password: \" + password);\n\n if (plainPassword) {\n PasswordEncryption pwEnc = new PasswordEncryption(new User(email, password));\n password = pwEnc.getSecurePassword();\n }\n\n String loginReturn[] = AuthorizationTask.getInstance().loginUser(new User(email, password));\n } catch (RestServiceException e) {\n Log.e(this.getClass().getSimpleName(), e.getMessage());\n return false;\n }\n\n return true;\n }\n\n @Override\n protected void onPostExecute(final Boolean success) {\n SpinnerObservable.getInstance().removeBackgroundTask(this);\n if (success) {\n // Store email address for later use\n DatabaseManager.INSTANCE.setUserEmail(email);\n }\n ObservableRegistry.getObservable(classToNotify).notifyFragments(\n new LoginFragment.LoginProcessParam(success));\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/FragmentObservable.java\npublic class FragmentObservable, P> {\r\n private Set fragments;\r\n private P buffer;\r\n\r\n public FragmentObservable() {\r\n fragments = new HashSet();\r\n }\r\n\r\n public void register(T fragment) {\r\n fragments.add(fragment);\r\n if (buffer != null) {\r\n notifyFragments(buffer);\r\n }\r\n }\r\n\r\n public void remove(T fragment) {\r\n fragments.remove(fragment);\r\n }\r\n\r\n //addIfNotExists\r\n public void notifyFragments(P parameter) {\r\n buffer = parameter;\r\n for (T fragment : fragments) {\r\n try {\r\n Log.d(this.getClass().getSimpleName(), \"Notify fragment: \" + fragment.getClass().getSimpleName());\r\n fragment.notifyFragment(parameter);\r\n buffer = null;\r\n } catch (Exception e) {\r\n Log.e(this.getClass().getSimpleName(), \"Notify fragment failed: \" + fragment.getClass().getSimpleName());\r\n }\r\n }\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/Log.java\npublic class Log {\r\n static final boolean LOG_I = BuildConfig.DEBUG;\r\n static final boolean LOG_E = BuildConfig.DEBUG;\r\n static final boolean LOG_D = BuildConfig.DEBUG;\r\n static final boolean LOG_V = BuildConfig.DEBUG;\r\n static final boolean LOG_W = BuildConfig.DEBUG;\r\n\r\n public static void i(String tag, String string) {\r\n if (LOG_I) android.util.Log.i(tag, string);\r\n }\r\n public static void e(String tag, String string) {\r\n if (LOG_E) android.util.Log.e(tag, string);\r\n }\r\n public static void d(String tag, String string) {\r\n if (LOG_D) android.util.Log.d(tag, string);\r\n }\r\n public static void v(String tag, String string) {\r\n if (LOG_V) android.util.Log.v(tag, string);\r\n }\r\n public static void w(String tag, String string) {\r\n if (LOG_W) android.util.Log.w(tag, string);\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/NotifiableFragment.java\npublic interface NotifiableFragment {\n\n void notifyFragment(T value);\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/controller/Toaster.java\npublic class Toaster {\r\n private static Toaster instance;\r\n private Context context;\r\n private Set toastables = new HashSet<>();\r\n\r\n private Toaster() {\r\n context = DatabaseManager.INSTANCE.getContext();\r\n }\r\n\r\n public static Toaster getInstance() {\r\n if (instance == null) {\r\n instance = new Toaster();\r\n }\r\n return instance;\r\n }\r\n\r\n public void register(Toastable toast) {\r\n toastables.add(toast);\r\n }\r\n\r\n public void remove(Toastable toast) {\r\n toastables.remove(toast);\r\n }\r\n\r\n public void toast(int id, int duration) {\r\n for (Toastable toast : toastables) {\r\n toast.toast(id,duration);\r\n }\r\n }\r\n\r\n public void toast(String text, int duration) {\r\n for (Toastable toast : toastables) {\r\n toast.toast(text, duration);\r\n }\r\n }\r\n\r\n public void toast(String text, int duration, int gravity) {\r\n for (Toastable toast : toastables) {\r\n toast.toast(text, duration, gravity);\r\n }\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/storage/DebugManager.java\npublic enum DebugManager {\r\n INSTANCE;\r\n\r\n private final String OWNDEVICE = \"owndevice\";\r\n private final String MESSAGEKEYS = \"messagekeys\";\r\n\r\n private boolean debugMode = false;\r\n private OwnDevice ownDevice = new OwnDevice();\r\n\r\n public boolean isDebugMode() {\r\n return debugMode;\r\n }\r\n\r\n public boolean storeDeviceId(long deviceId) {\r\n ownDevice.setId(deviceId);\r\n return storeOwnDeviceToExternalStorage();\r\n }\r\n\r\n\r\n public boolean storePrivatePublicKeyToExternalStorage(String privateKey, String publicKey) {\r\n ownDevice.setPrivateKey(privateKey);\r\n ownDevice.setPublicKey(publicKey);\r\n return storeOwnDeviceToExternalStorage();\r\n }\r\n\r\n public boolean storePushId(String pushId) {\r\n ownDevice.setPushId(pushId);\r\n return storeOwnDeviceToExternalStorage();\r\n }\r\n\r\n private boolean storeOwnDeviceToExternalStorage() {\r\n return storeToExternalStorage(OWNDEVICE, ownDevice, false);\r\n }\r\n\r\n public boolean storeMessageKeyToExternalStorage(MessageKey data) {\r\n return storeToExternalStorage(MESSAGEKEYS, data, true);\r\n }\r\n\r\n private boolean storeToExternalStorage(String name, Object data, boolean append) {\r\n try {\r\n String state = Environment.getExternalStorageState();\r\n Log.d(getClass().getSimpleName(), \"Check state\");\r\n if (!Environment.MEDIA_MOUNTED.equals(state)) {\r\n return false;\r\n }\r\n Log.d(getClass().getSimpleName(), \"Open dir\");\r\n File dir = getDir();\r\n Log.d(getClass().getSimpleName(), \"Mkdir\");\r\n if (!dir.exists() && !dir.mkdirs()) {\r\n Log.d(getClass().getSimpleName(), \"... failed\");\r\n return false;\r\n }\r\n Log.d(getClass().getSimpleName(), \"Open file\");\r\n File file = new File(dir,name + \".txt\");\r\n Log.d(getClass().getSimpleName(), \"Write file\");\r\n\r\n ObjectWriter objectWriter = new ObjectMapper().writer();\r\n String json = objectWriter.writeValueAsString(data);\r\n Log.d(getClass().getSimpleName(),\"Generated JSON: \" + json);\r\n\r\n FileOutputStream f = new FileOutputStream(file,append);\r\n PrintWriter pw = new PrintWriter(f);\r\n if (append) {\r\n pw.println(json + \",\");\r\n } else {\r\n pw.println(json);\r\n }\r\n pw.flush();\r\n pw.close();\r\n f.close();\r\n } catch (Exception e) {\r\n Log.e(this.getClass().getSimpleName(),e.getMessage());\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n public boolean restoreData() {\r\n Log.d(getClass().getSimpleName(),\"Restoring data\");\r\n if (!restoreOwnDeviceFromExternalStorage()) {\r\n Log.d(getClass().getSimpleName(), \"Restoring OwnDevice failed\");\r\n return false;\r\n }\r\n if (!restoreMessageKeysFromExternalStorage()) {\r\n Log.d(getClass().getSimpleName(), \"Restoring MessageKeys failed\");\r\n return false;\r\n }\r\n Log.d(getClass().getSimpleName(), \"Restoring successful\");\r\n Toaster.getInstance().toast(\"Restoring Debug-Data successful\", Toast.LENGTH_LONG);\r\n return true;\r\n }\r\n\r\n\r\n private boolean restoreOwnDeviceFromExternalStorage() {\r\n final String RSAKEY_STORAGE = \"rsaKeyStorage\"; //Storage for Private and Public Keys from user\r\n final String PRIVATEKEY = \"privateKey\";\r\n final String PUBLICKEY = \"publicKey\";\r\n\r\n try {\r\n OwnDevice device = getOwnDeviceFromExternalStorage();\r\n if (device == null) {\r\n Log.d(getClass().getSimpleName(), \"Device is null\");\r\n return false;\r\n }\r\n\r\n // Restore devId\r\n Log.d(getClass().getSimpleName(), \"Restore devId\");\r\n SharedPreferences.Editor editor1 = DatabaseManager.INSTANCE.getSharedPreferences().edit();\r\n editor1.putLong(AbstractYasmeActivity.DEVICE_ID, ownDevice.getId());\r\n editor1.commit();\r\n\r\n // Restore pushId and app version\r\n Log.d(getClass().getSimpleName(), \"Restore pushId\");\r\n SharedPreferences prefs = DatabaseManager.INSTANCE.getContext().getSharedPreferences(LoginActivity.class.getSimpleName(), Context.MODE_PRIVATE);\r\n SharedPreferences.Editor editor2 = prefs.edit();\r\n editor2.putString(AbstractYasmeActivity.PROPERTY_REG_ID, ownDevice.getPushId());\r\n editor2.commit();\r\n\r\n // Restore PrivatePublicKey\r\n Log.d(getClass().getSimpleName(), \"Restore PrivPubKeys\");\r\n String RSAKEY_STORAGE_USER = RSAKEY_STORAGE + \"_\" + ownDevice.getId();\r\n Context context = DatabaseManager.INSTANCE.getContext();\r\n SharedPreferences privKeyStorage = context.getSharedPreferences(RSAKEY_STORAGE_USER, Context.MODE_PRIVATE);\r\n SharedPreferences.Editor keyeditor = privKeyStorage.edit();\r\n\r\n keyeditor.putString(PRIVATEKEY, device.getPrivateKey());\r\n keyeditor.putString(PUBLICKEY,device.getPublicKey());\r\n keyeditor.commit();\r\n } catch (Exception e) {\r\n Log.e(this.getClass().getSimpleName(),e.getMessage());\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n private OwnDevice getOwnDeviceFromExternalStorage() {\r\n String text = readText(OWNDEVICE);\r\n if (text == null || text == \"\") {\r\n return null;\r\n }\r\n Log.d(getClass().getSimpleName(), \"Device-Text: \" + text);\r\n try {\r\n OwnDevice device = new ObjectMapper().readValue(text, OwnDevice.class);\r\n Log.d(getClass().getSimpleName(), \"PubKey: \" + device.getPublicKey());\r\n return device;\r\n } catch (Exception e) {\r\n Log.e(this.getClass().getSimpleName(),e.getMessage());\r\n return null;\r\n }\r\n }\r\n\r\n private boolean restoreMessageKeysFromExternalStorage() {\r\n String text = readText(MESSAGEKEYS);\r\n if (text == null) {\r\n return false;\r\n }\r\n if (text == \"\") {\r\n // No messageKey stored yet\r\n return true;\r\n }\r\n String json = \"[\" + text + \"{}]\";\r\n Log.d(getClass().getSimpleName(), \"MessageKeys-Text: \" + text);\r\n try {\r\n Log.d(getClass().getSimpleName(), \"JSON: \" + json);\r\n JSONArray jsonArray = new JSONArray(json);\r\n\r\n for (int i = 0; i < jsonArray.length() - 1; i++) {\r\n MessageKey messageKey = new ObjectMapper().readValue((jsonArray.getJSONObject(i)).\r\n toString(), MessageKey.class);\r\n messageKey.setAuthenticity(true);\r\n DatabaseManager.INSTANCE.getMessageKeyDAO().addOrUpdate(messageKey);\r\n }\r\n\r\n return true;\r\n } catch (Exception e) {\r\n Log.e(this.getClass().getSimpleName(),e.getMessage());\r\n return false;\r\n }\r\n }\r\n\r\n private String readText(String name) {\r\n String filename = \"\";\r\n try {\r\n Log.d(getClass().getSimpleName(), \"Open dir\");\r\n File dir = getDir();\r\n if (!dir.exists()) {\r\n return null;\r\n }\r\n Log.d(getClass().getSimpleName(), \"Open file\");\r\n filename = dir.getAbsolutePath() + \"/\" + name + \".txt\";\r\n\r\n\r\n BufferedReader br = new BufferedReader(new FileReader(filename));\r\n StringBuilder sb = new StringBuilder();\r\n String line = br.readLine();\r\n\r\n while (line != null) {\r\n sb.append(line);\r\n line = br.readLine();\r\n }\r\n br.close();\r\n return sb.toString();\r\n } catch (FileNotFoundException e) {\r\n Log.e(getClass().getSimpleName(), \"File \" + filename + \" not found.\");\r\n return \"\";\r\n }\r\n catch (Exception e) {\r\n Log.e(this.getClass().getSimpleName(),e.getMessage());\r\n return null;\r\n }\r\n }\r\n\r\n private File getDir() {\r\n return new File(Environment.getExternalStoragePublicDirectory(\"yasme\"), String.valueOf(DatabaseManager.INSTANCE.getUserId()));\r\n }\r\n}\r\nyasme/src/main/java/de/fau/cs/mad/yasme/android/storage/DatabaseManager.java\npublic enum DatabaseManager {\n INSTANCE;\n\n private boolean mInitialized = false;\n private boolean mDBInitialized = false;\n private DatabaseHelper mHelper;\n private Context mContext;\n private long mUserId = -1;\n private long mDeviceId = -1;\n private String mAccessToken = null;\n private long serverInfoUpdateTime = -1;\n private ServerInfo serverInfo = null;\n private SharedPreferences mSharedPreferences, mSettings;\n private String mUserEmail;\n private NewMessageNotificationManager notifier = null;\n\n private UserDAO userDAO;\n private ChatDAO chatDAO;\n private MessageDAO messageDAO;\n private MessageKeyDAO messageKeyDAO;\n private DeviceDAO deviceDAO;\n\n\n public void init(Context context, SharedPreferences sharedPreferences,\n SharedPreferences settings, long userId) {\n mContext = context;\n mSharedPreferences = sharedPreferences;\n mSettings = settings;\n mUserId = userId;\n initDB(context, userId);\n initializeDAOs();\n mInitialized = true;\n }\n\n public void initDB(Context context, long userId) {\n mHelper = new DatabaseHelper(context, userId);\n mDBInitialized = true;\n }\n\n public boolean isInitialized() {\n return mInitialized;\n }\n\n public boolean isDBInitialized() {\n return mDBInitialized;\n }\n\n private DatabaseHelper getHelper() {\n return mHelper;\n }\n\n public SharedPreferences getSharedPreferences() {\n return mSharedPreferences;\n }\n\n public SharedPreferences getSettings() {\n return mSettings;\n }\n\n public Context getContext() {\n return mContext;\n }\n\n private void initializeDAOs() {\n UserDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n userDAO = UserDAOImpl.INSTANCE;\n\n ChatDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n chatDAO = ChatDAOImpl.INSTANCE;\n\n MessageDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n messageDAO = MessageDAOImpl.INSTANCE;\n\n MessageKeyDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n messageKeyDAO = MessageKeyDAOImpl.INSTANCE;\n\n DeviceDAOImpl.INSTANCE.setDatabaseHelper(mHelper);\n deviceDAO = DeviceDAOImpl.INSTANCE;\n }\n\n public UserDAO getUserDAO() {\n return userDAO;\n }\n\n public ChatDAO getChatDAO() {\n return chatDAO;\n }\n\n public MessageDAO getMessageDAO() {\n return messageDAO;\n }\n\n public MessageKeyDAO getMessageKeyDAO() {\n return messageKeyDAO;\n }\n\n public DeviceDAO getDeviceDAO() {\n return deviceDAO;\n }\n\n public long getUserId() {\n if (-1 == mUserId) {\n mUserId = getSharedPreferences().getLong(AbstractYasmeActivity.USER_ID, -1);\n }\n return mUserId;\n }\n\n public void setUserId(long mUserId) {\n this.mUserId = mUserId;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putLong(AbstractYasmeActivity.USER_ID, mUserId);\n editor.apply();\n }\n\n public long getDeviceId() {\n if (-1 == mDeviceId) {\n mDeviceId = getSharedPreferences().getLong(AbstractYasmeActivity.DEVICE_ID, -1);\n }\n return mDeviceId;\n }\n\n public void setDeviceId(long mDeviceId) {\n this.mDeviceId = mDeviceId;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putLong(AbstractYasmeActivity.DEVICE_ID, mDeviceId);\n editor.apply();\n }\n\n public String getAccessToken() {\n if (null == mAccessToken) {\n mAccessToken = getSharedPreferences().getString(AbstractYasmeActivity.ACCESSTOKEN, null);\n }\n return mAccessToken;\n }\n\n public void setAccessToken(String accessToken) {\n this.mAccessToken = accessToken;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(AbstractYasmeActivity.ACCESSTOKEN, mAccessToken);\n editor.commit();\n }\n\n public long getServerInfoUpdateTime() {\n if (-1 == serverInfoUpdateTime) {\n serverInfoUpdateTime = getSharedPreferences().getLong(AbstractYasmeActivity.SERVERINFOUPDATETIME, -1);\n }\n return serverInfoUpdateTime;\n }\n\n public void setServerInfoUpdateTime() {\n this.serverInfoUpdateTime = System.currentTimeMillis();\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putLong(AbstractYasmeActivity.SERVERINFOUPDATETIME, serverInfoUpdateTime);\n editor.commit();\n }\n\n public ServerInfo getServerInfo() {\n return serverInfo;\n }\n\n public void setServerInfo(ServerInfo serverInfo) {\n this.serverInfo = serverInfo;\n }\n\n public String getUserEmail() {\n if (null == mUserEmail || \"\" == mUserEmail) {\n mUserEmail = getSharedPreferences().getString(AbstractYasmeActivity.USER_MAIL, null);\n }\n return mUserEmail;\n }\n\n public void setUserEmail(String mUserEmail) {\n this.mUserEmail = mUserEmail;\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(AbstractYasmeActivity.USER_MAIL, mUserEmail);\n editor.commit();\n }\n\n public NewMessageNotificationManager getNotifier() {\n if (notifier == null) {\n notifier = new NewMessageNotificationManager();\n }\n return notifier;\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/EditTextWithX.java\npublic class EditTextWithX {\n private EditText et;\n private Drawable x;\n\n public EditTextWithX(Context context) {\n et = new EditText(context);\n x = context.getResources().getDrawable(R.drawable.ic_action_cancel);\n x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());\n et.setCompoundDrawables(null, null, et.getText().toString().equals(\"\") ? null : x, null);\n et.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent) {\n if (et.getCompoundDrawables()[2] == null) {\n return false;\n }\n if (motionEvent.getAction() != MotionEvent.ACTION_UP) {\n return false;\n }\n if (motionEvent.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {\n et.setText(\"\");\n et.setCompoundDrawables(null, null, null, null);\n }\n return false;\n }\n });\n et.addTextChangedListener(new TextWatcher() {\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n et.setCompoundDrawables(null, null, et.getText().toString().equals(\"\") ? null : x, null);\n }\n\n @Override\n public void afterTextChanged(Editable arg0) {\n\n }\n\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n });\n }\n\n public EditText getEditText() {\n return et;\n }\n}\nyasme/src/main/java/de/fau/cs/mad/yasme/android/entities/User.java\n@JsonIgnoreProperties(ignoreUnknown = true)\n@DatabaseTable(tableName = DatabaseConstants.USER_TABLE)\npublic class User implements Serializable {\n\n @DatabaseField(columnName = DatabaseConstants.USER_ID, id = true)\n private long id;\n\n @DatabaseField(columnName = DatabaseConstants.USER_NAME)\n private String name;\n\n //@DatabaseField(columnName = DatabaseConstants.USER_EMAIL)\n private String email;\n\n private String pw;\n\n @JsonIgnore\n private List devices; // Just for convenience\n\n @DatabaseField(columnName = DatabaseConstants.USER_LAST_MODIFIED)\n private Date lastModified;\n\n @DatabaseField(columnName = DatabaseConstants.USER_CREATED)\n private Date created;\n\n @JsonIgnore\n @DatabaseField(columnName = DatabaseConstants.USER_PICTURE)\n private String profilePicture;\n\n\n @JsonIgnore\n @DatabaseField(columnName = DatabaseConstants.CONTACT)\n private int contactFlag = 0;\n\n\n public User(String pw, String name, String email) {\n this.pw = pw;\n this.name = name;\n this.email = email;\n }\n\n public User(String email, String pw) {\n this.email = email;\n this.pw = pw;\n }\n\n public User(String name, long id) {\n this.name = name;\n this.id = id;\n }\n\n public User(long id) {\n this.id = id;\n }\n\n public User(String name, String email, long id) {\n this.name = name;\n this.email = email;\n this.id = id;\n }\n\n public User() {\n // ORMLite needs a no-arg constructor\n }\n\n /*\n * Getters\n */\n\n @JsonIgnoreProperties({\"id\", \"user\", \"publicKey\", \"product\", \"lastModified\"})\n public List getDevices() {\n return devices;\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getName() {\n return name;\n }\n\n public String getPw() {\n return pw;\n }\n\n public long getId() {\n return id;\n }\n\n public Date getLastModified() {\n return lastModified;\n }\n\n public Date getCreated() {\n return created;\n }\n\n public String getProfilePicture() {\n return profilePicture;\n }\n\n /*\n * Setters\n */\n\n public void setDevices(List devices) {\n this.devices = devices;\n }\n\n public void setPw(String pw) {\n this.pw = pw;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public void setLastModified(Date lastModified) {\n this.lastModified = lastModified;\n }\n\n public void setCreated(Date created) {\n this.created = created;\n }\n\n public void setProfilePicture(String profilePicture) {\n this.profilePicture = profilePicture;\n }\n\n @JsonIgnore\n public void addToContacts() {\n contactFlag = 1;\n }\n\n @JsonIgnore\n public void removeFromContacts() {\n contactFlag = 0;\n }\n\n @JsonIgnore\n public boolean isContact() {\n return contactFlag == 1;\n }\n\n}\n", "answers": [" ServerInfo serverInfo = DatabaseManager.INSTANCE.getServerInfo();"], "length": 4173, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ff7ec850f9147662c5e3f1a8824443b3df40809f1dce6f22"} {"input": "from libmich.core.element import Bit, Int, Str, Layer, show, showattr, log, \\\n ERR, WNG, DBG\nfrom libmich.core.IANA_dict import IANA_dict\nfrom .L3Mobile_24007 import *\nfrom .L2GSM import LengthRR\nfrom .L3Mobile_MM import CKSN_dict\nfrom .L3Mobile_IE import ID, LAI, MSCm2, MSCm3\nfrom .L3GSM_IE import *\nfrom .L3GSM_rest import *\n# TS 44.018 defines Radio Ressource Control protocol\n# which is carried over the data-link\n#\n# section 8: basic structures\n# section 9: messages stuctures (pffff...)\n# section 10: general aspect and IE coding\n##################\n# 44018, section 10.1\n# Header field\n#\n# 44018, section 9.1\n# RRC procedures dictionnary\nGSM_RR_dict = {\n 0:'SYSTEM INFORMATION TYPE 13',\n 1:'SYSTEM INFORMATION TYPE 14',\n 2:'SYSTEM INFORMATION TYPE 2 bis',\n 3:'SYSTEM INFORMATION TYPE 2 ter',\n 4:'SYSTEM INFORMATION TYPE 9',\n 5:'SYSTEM INFORMATION TYPE 5 bis',\n 6:'SYSTEM INFORMATION TYPE 5 ter',\n 7:'SYSTEM INFORMATION TYPE 2 quater',\n 9:'VGCS UPLINK GRANT',\n 10:'PARTIAL RELEASE',\n 13:'CHANNEL RELEASE',\n 14:'UPLINK RELEASE',\n 15:'PARTIAL RELEASE COMPLETE',\n 16:'CHANNEL MODE MODIFY',\n 17:'TALKER INDICATION',\n 18:'RR STATUS',\n 19:'CLASSMARK ENQUIRY',\n 20:'FREQUENCY REDEFINITION',\n 21:'MEASUREMENT REPORT',\n 22:'CLASSMARK CHANGE',\n #22:'MBMS ANNOUNCEMENT',\n 23:'CHANNEL MODE MODIFY ACKNOWLEDGE',\n 24:'SYSTEM INFORMATION TYPE 8',\n 25:'SYSTEM INFORMATION TYPE 1',\n 26:'SYSTEM INFORMATION TYPE 2',\n 27:'SYSTEM INFORMATION TYPE 3',\n 28:'SYSTEM INFORMATION TYPE 4',\n 29:'SYSTEM INFORMATION TYPE 5',\n 30:'SYSTEM INFORMATION TYPE 6',\n 31:'SYSTEM INFORMATION TYPE 7',\n 32:'NOTIFICATION/NCH',\n 33:'PAGING REQUEST TYPE 1',\n 34:'PAGING REQUEST TYPE 2',\n 36:'PAGING REQUEST TYPE 3',\n 38:'NOTIFICATION/RESPONSE',\n 39:'PAGING RESPONSE',\n 40:'HANDOVER FAILURE',\n 41:'ASSIGNMENT COMPLETE',\n 42:'UPLINK BUSY',\n 43:'HANDOVER COMMAND',\n 44:'HANDOVER COMPLETE',\n 45:'PHYSICAL INFORMATION',\n 46:'ASSIGNMENT COMMAND',\n 47:'ASSIGNMENT FAILURE',\n 48:'CONFIGURATION CHANGE COMMAND',\n 49:'CONFIGURATION CHANGE ACK',\n 50:'CIPHERING MODE COMPLETE',\n 51:'CONFIGURATION CHANGE REJECT',\n 52:'GPRS SUSPENSION REQUEST',\n 53:'CIPHERING MODE COMMAND',\n 54:'EXTENDED MEASUREMENT REPORT',\n 54:'SERVICE INFORMATION',\n 55:'EXTENDED MEASUREMENT ORDER',\n 56:'APPLICATION INFORMATION',\n 57:'IMMEDIATE ASSIGNMENT EXTENDED',\n 58:'IMMEDIATE ASSIGNMENT REJECT',\n 59:'ADDITIONAL ASSIGNMENT',\n 61:'SYSTEM INFORMATION TYPE 16',\n 62:'SYSTEM INFORMATION TYPE 17',\n 63:'IMMEDIATE ASSIGNMENT',\n 64:'SYSTEM INFORMATION TYPE 18',\n 65:'SYSTEM INFORMATION TYPE 19',\n 66:'SYSTEM INFORMATION TYPE 20',\n 67:'SYSTEM INFORMATION TYPE 15',\n 68:'SYSTEM INFORMATION TYPE 13 alt',\n 69:'SYSTEM INFORMATION TYPE 2 n',\n 70:'SYSTEM INFORMATION TYPE 21',\n 72:'DTM ASSIGNMENT FAILURE',\n 73:'DTM REJECT',\n 74:'DTM REQUEST',\n 75:'PACKET ASSIGNMENT',\n 76:'DTM ASSIGNMENT COMMAND',\n 77:'DTM INFORMATION',\n 78:'PACKET NOTIFICATION',\n 96:'UTRAN CLASSMARK CHANGE',\n 98:'CDMA 2000 CLASSMARK CHANGE',\n 99:'INTER SYSTEM TO UTRAN HANDOVER COMMAND',\n 100:'INTER SYSTEM TO CDMA2000 HANDOVER COMMAND',\n 101:'GERAN IU MODE CLASSMARK CHANGE',\n 102:'PRIORITY UPLINK REQUEST',\n 103:'DATA INDICATION',\n 104:'DATA INDICATION 2'}\n\nCause_dict = {\n 0:'Normal event',\n 1:'Abnormal release, unspecified',\n 2:'Abnormal release, channel unacceptable',\n 3:'Abnormal release, timer expired',\n 4:'Abnormal release, no activity on the radio path',\n 5:'Preemptive release',\n 6:'UTRAN configuration unknown',\n 8:'Handover impossible, timing advance out of range',\n 9:'Channel mode unacceptable',\n 10:'Frequency not implemented',\n 11:'Originator or talker leaving group call area',\n 12:'Lower layer failure',\n 65:'Call already cleared',\n 95:'Semantically incorrect message',\n 96:'Invalid mandatory information',\n 97:'Message type non-existent or not implemented',\n 98:'Message type not compatible with protocol state',\n 100:'Conditional IE error',\n 101:'No cell allocation available',\n 111:'Protocol error unspecified'}\n\n# 44018, section 10.1\n# standard RRC header\n", "context": "libmich/formats/L3Mobile_IE.py\nclass MSCm2(Layer):\n constructorList = [\n Bit('spare1', Pt=0, BitLen=1),\n Bit('rev', Pt=1, BitLen=2, Repr='hum', Dict=Revision_level),\n Bit('ES', ReprName='Controlled early classmark sending', \\\n Pt=0, BitLen=1, Repr='hum'),\n Bit('noA51', Pt=0, BitLen=1, Repr='hum'),\n Bit('RFclass', Pt=0, BitLen=3, Repr='hum', Dict=RFclass_dict),\n Bit('spare2', Pt=0, BitLen=1),\n Bit('PScap', Pt=0, BitLen=1, Repr='hum'),\n Bit('SSscreen', Pt=0, BitLen=2, Dict=SSscreen_dict, Repr='hum'),\n Bit('SMcap', Pt=0, BitLen=1, Repr='hum'),\n Bit('VBSnotif', Pt=0, BitLen=1, Repr='hum'),\n Bit('VGCSnotif', Pt=0, BitLen=1, Repr='hum'),\n Bit('Freqcap', Pt=0, BitLen=1, Repr='hum'),\n Bit('Classmark3', Pt=0, BitLen=1, Repr='hum'),\n Bit('spare3', Pt=0, BitLen=1),\n Bit('LCSVAcap', Pt=0, BitLen=1, Repr='hum'),\n Bit('UCS2', Pt=0, BitLen=1, Repr='hum'),\n Bit('SoLSA', Pt=0, BitLen=1, Repr='hum'),\n Bit('CMSP', ReprName='CM service prompt', Pt=0, \\\n BitLen=1, Repr='hum'),\n Bit('A53', Pt=0, BitLen=1, Repr='hum'),\n Bit('A52', Pt=0, BitLen=1, Repr='hum')]\nlibmich/formats/L3Mobile_IE.py\nclass MSCm3(CSN1):\n csn1List = [\n Bit('spare', Pt=0, BitLen=1),\n {'000':A5bits(),\n '101':(A5bits(), \\\n Bit('AssociatedRadioCapability2', Pt=0, BitLen=4), \\\n Bit('AssociatedRadioCapability1', Pt=0, BitLen=4)),\n '110':(A5bits(), \\\n Bit('AssociatedRadioCapability2', Pt=0, BitLen=4), \\\n Bit('AssociatedRadioCapability1', Pt=0, BitLen=4)),\n '001':(A5bits(), \\\n Bit('spare', Pt=0, BitLen=4), \\\n Bit('AssociatedRadioCapability1', Pt=0, BitLen=4)),\n '010':(A5bits(), \\\n Bit('spare', Pt=0, BitLen=4), \\\n Bit('AssociatedRadioCapability1', Pt=0, BitLen=4)),\n '100':(A5bits(), \\\n Bit('spare', Pt=0, BitLen=4), \\\n Bit('AssociatedRadioCapability1', Pt=0, BitLen=4))},\n {'0':BREAK, '1':RSupport()},\n {'0':BREAK, '1':HSCSDMultiSlotCapability()},\n Bit('UCS2treatment', Pt=0, BitLen=1),\n Bit('ExtendedMeasurementCapability', Pt=0, BitLen=1),\n {'0':BREAK, '1':MSMeasurementCapability()},\n {'0':BREAK, '1':MSPositioningMethodCapability()},\n {'0':BREAK, '1':ECSDMultiSlotCapability()},\n {'0':BREAK, '1':PSK8()},\n {'0':BREAK, '1':(Bit('GSM400BandsSupported', Pt=1, BitLen=2),\n Bit('GSM400AssociatedRadioCapability', Pt=0, BitLen=4))},\n {'0':BREAK, '1':Bit('GSM850AssociatedRadioCapability', Pt=0, BitLen=4)},\n {'0':BREAK, '1':Bit('GSM1900AssociatedRadioCapability', Pt=0, BitLen=4)},\n Bit('UMTSFDDRadioAccessTechnologyCapability', Pt=0, BitLen=1),\n Bit('UMTS384McpsTDDRadioAccessTechnologyCapability', Pt=0, BitLen=1),\n Bit('CDMA2000RadioAccessTechnologyCapability', Pt=0, BitLen=1),\n {'0':BREAK, \n '1':(Bit('DTMGPRSMultiSlotClass', Pt=0, BitLen=2),\n Bit('SingleSlotDTM', Pt=0, BitLen=1),\n {'0':BREAK, '1':Bit('DTMEGPRSMultiSlotClass', Pt=0, BitLen=2)})},\n # Rel.4:\n {'0':BREAK, '1':SingleBandSupport()},\n {'0':BREAK, '1':Bit('GSM750AssociatedRadioCapability', Pt=0, BitLen=4)},\n Bit('UMTS128McpsTDDRadioAccessTechnologyCapability', Pt=0, BitLen=1),\n Bit('GERANFeaturePackage1', Pt=0, BitLen=1),\n {'0':BREAK, \n '1':(Bit('ExtendedDTMGPRSMultiSlotClass', Pt=0, BitLen=2),\n Bit('ExtendedDTMEGPRSMultiSlotClass', Pt=0, BitLen=2))},\n # Rel.5:\n {'0':BREAK, '1':Bit('HighMultislotCapability', Pt=0, BitLen=2)},\n {'0':BREAK, '1':GERANIuModeCapabilities()},\n Bit('GERANFeaturePackage2', Pt=0, BitLen=1),\n Bit('GMSKMultislotPowerProfile', Pt=0, BitLen=2),\n Bit('PSK8MultislotPowerProfile', Pt=0, BitLen=2),\n # Rel.6:\n {'0':BREAK, '1':(Bit('TGSM400BandsSupported', Pt=1, BitLen=2),\n Bit('TGSM400AssociatedRadioCapability', Pt=0, BitLen=4))},\n Bit('unused', Pt=0, BitLen=1),\n Bit('DownlinkAdvancedReceiverPerformance', Pt=0, BitLen=2),\n Bit('DTMEnhancementsCapability', Pt=0, BitLen=1),\n {'0':BREAK,\n '1':(Bit('DTMGPRSHighMultiSlotClass', Pt=0, BitLen=3),\n Bit('OffsetRequired', Pt=0, BitLen=1),\n {'0':BREAK, '1':Bit('DTMEGPRSHighMultiSlotClass', Pt=0, BitLen=3)})},\n Bit('RepeatedACCHCapability', Pt=0, BitLen=1),\n # Rel.7:\n {'0':BREAK, '1':Bit('GSM710AssociatedRadioCapability', Pt=0, BitLen=4)},\n {'0':BREAK, '1':Bit('TGSM810AssociatedRadioCapability', Pt=0, BitLen=4)},\n Bit('CipheringModeSettingCapability', Pt=0, BitLen=1),\n Bit('AdditionalPositioningCapabilities', Pt=0, BitLen=1),\n # Rel.8:\n Bit('EUTRAFDDSupport', Pt=0, BitLen=1),\n Bit('EUTRATDDSupport', Pt=0, BitLen=1),\n Bit('EUTRAMeasurementAndReportingSupport', Pt=0, BitLen=1),\n Bit('PriorityBasedReselectionSupport', Pt=0, BitLen=1),\n Bit('spare', Pt=0, BitLen=1),\n # Rel.9:\n Bit('UTRACSGCellsReporting', Pt=0, BitLen=1),\n Bit('VAMOSLevel', Pt=0, BitLen=2),\n # Rel.10:\n Bit('TIGHTERCapability', Pt=0, BitLen=2),\n Bit('SelectiveCipheringDownlinkSACCH', Pt=0, BitLen=1),\n # Rel.11:\n Bit('CStoPSSRVCCfromGERANtoUTRA', Pt=0, BitLen=2),\n Bit('CStoPSSRVCCfromGERANtoEUTRA', Pt=0, BitLen=2),\n Bit('GERANNetworkSharing', Pt=0, BitLen=1),\n Bit('EUTRAWidebandRSRQmeasurements', Pt=0, BitLen=1),\n # Rel.12:\n Bit('ERBand', Pt=0, BitLen=1),\n Bit('UTRAMultipleFrequencyBandInd', Pt=0, BitLen=1),\n Bit('EUTRAMultipleFrequencyBandInd', Pt=0, BitLen=1),\n Bit('Extended TSCSetCapability', Pt=0, BitLen=1),\n Bit('ExtendedEARFCNValueRange', Pt=0, BitLen=1)\n ]\nlibmich/core/element.py\nclass Str(Element):\n '''\n class defining a standard Element, \n managed like a stream of byte(s), or string.\n It is always byte-aligned (in term of length, at least)\n \n attributes:\n Pt: to point to another stream object (can simply be a string);\n PtFunc: when defined, PtFunc(Pt) is used \n to generate the str() / len() representation;\n Val: when defined, overwrites the Pt (and PtFunc) string value, \n used when mapping a string buffer to the element;\n Len: can be set to a fixed int value, or to another object\n when called by LenFunc\n LenFunc: to be used when mapping string buffer with variable length\n (e.g. in TLV object), LenFunc(Len) is used;\n Repr: python representation; binary, hexa, human or ipv4;\n Trans: to define transparent element which has empty str() and len() to 0,\n it \"nullifies\" its existence; can point to something for automation;\n TransFunc: when defined, TransFunc(Trans) is used to automate the \n transparency aspect: used e.g. for conditional element;\n '''\n \n # this is used when printing the object representation\n _repr_limit = 1024\n _reprs = ['hex', 'bin', 'hum', 'ipv4']\n \n # padding is used when .Pt and .Val are None, \n # but Str instance has still a defined .Len attribute\n _padding_byte = '\\0'\n \n def __init__(self, CallName='', ReprName=None, \n Pt=None, PtFunc=None, Val=None, \n Len=None, LenFunc=None,\n Repr=\"hum\",\n Trans=False, TransFunc=None):\n if CallName or not self.CallName:\n self.CallName = CallName\n if ReprName is None :\n self.ReprName = ''\n else :\n self.ReprName = ReprName\n self.Pt = Pt\n self.PtFunc = PtFunc\n self.Val = Val\n self.Len = Len\n self.LenFunc = LenFunc\n self.Type = 'stream'\n self.Repr = Repr\n self.Trans = Trans\n self.TransFunc = TransFunc\n \n def __setattr__(self, attr, val):\n # ensures no bullshit is provided into element's attributes \n # (however, it is not a exhaustive test...)\n # managed with the class \"safe\" trigger\n if self.safe :\n if attr == 'CallName' :\n if type(val) is not str or len(val) == 0 :\n raise AttributeError('CallName must be a non-null string')\n elif attr == 'ReprName' :\n if type(val) is not str:\n raise AttributeError('ReprName must be a string')\n elif attr == 'PtFunc' :\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('PtFunc must be a function')\n elif attr == 'Val' :\n if val is not None and not isinstance(val, \\\n (str, bytes, Element, Layer, Block, tuple, list)) :\n raise AttributeError('Val must be a string or something ' \\\n 'that makes a string at the end...')\n elif attr == 'Len' :\n if val is not None and not isinstance(val, \\\n (int, tuple, Element, type_funcs)) :\n raise AttributeError('Len must be an int or element')\n elif attr == 'LenFunc' :\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('LenFunc must be a function')\n elif attr == 'Repr' :\n if val not in self._reprs :\n raise AttributeError('Repr %s does not exist, only: %s' \\\n % (val, self._reprs))\n elif attr == 'TransFunc' :\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('TransFunc must be a function')\n # this is for Layer() pointed by Pt attr in Str() object\n #if isinstance(self.Pt, Layer) and hasattr(self.Pt, attr):\n # setattr(self.Pt, attr, val)\n # ...does not work properly\n # and the final standard python behaviour\n object.__setattr__(self, attr, val)\n \n def __getattr__(self, attr):\n # this is for Layer() pointed by Pt attr in Str() object\n if isinstance(self.Pt, Layer) and hasattr(self.Pt, attr):\n return getattr(self.Pt, attr)\n # and the final standard python behaviour\n object.__getattr__(self, attr)\n \n # the libmich internal instances check\n # this is highly experimental...\n def __is_intern_inst(self, obj):\n return isinstance(obj, (Element, Layer, Block))\n \n # building basic methods for manipulating easily the Element \n # from its attributes\n def __call__(self, l=None):\n # when length has fixed value:\n if not l and type(self.Len) is int:\n l = self.Len\n #else:\n # l = None\n # when no values are defined at all:\n if self.Val is None and self.Pt is None: \n if l: return l * self._padding_byte\n else: return ''\n # returning the right string:\n # if defined, self.Val overrides self.Pt capabilities\n elif self.Val is not None:\n # allow to pass tuple or list of libmich internal instances\n if isinstance(self.Val, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Val):\n return ''.join(map(str, self.Val))[:l]\n return str(self.Val)[:l]\n # else: use self.Pt capabilities to get the string\n elif self.PtFunc is not None: \n if self.safe: \n assert(hasattr(self.PtFunc(self.Pt), '__str__'))\n return str(self.PtFunc(self.Pt))[:l]\n else:\n # allow to pass tuple or list of libmich internal instances\n if isinstance(self.Pt, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Pt):\n return ''.join(map(str, self.Pt))[:l]\n # otherwise, handle simply as is\n if self.safe: \n assert(hasattr(self.Pt, '__str__'))\n return str(self.Pt)[:l]\n \n def __str__(self):\n # when Element is Transparent:\n if self.is_transparent():\n return ''\n #else:\n return self()\n \n def __len__(self):\n # does not take the LenFunc(Len) into account\n # When a Str is defined, the length is considered dependent of the Str\n # the Str is dependent of the LenFunc(Len) only \n # when mapping data into the Element\n return len(self.__str__())\n \n def bit_len(self):\n return len(self)*8\n \n def map_len(self):\n # need special length definition \n # when mapping a string to the 'Str' element \n # that has no fixed length\n #\n # uses LenFunc, applied to Len, when length is variable:\n # and TransFunc, applied to Trans, to managed potential transparency\n # (e.g. for optional element triggered by other element)\n #\n if self.Len is None:\n return None\n #return 0\n if self.LenFunc is None: \n return self.Len\n else:\n if self.safe:\n assert( type(self.LenFunc(self.Len)) in (int, long) )\n return self.LenFunc(self.Len)\n \n def __int__(self):\n # big endian integer representation of the string buffer\n return shtr(self).left_val(len(self)*8)\n \n def __bin__(self):\n # does not use the standard python 'bin' function to keep \n # the right number of prefixed 0 bits\n h = hex(self)\n binary = ''\n for i in xrange(0, len(h), 2):\n b = format( int(h[i:i+2], 16), 'b' )\n binary += ( 8-len(b) ) * '0' + b\n return binary\n \n def __hex__(self):\n return self().encode('hex')\n \n def __repr__(self):\n # check for simple representations\n if self.Pt is None and self.Val is None: \n return repr(None)\n if self.Repr == 'ipv4':\n #if self.safe: assert( len(self) == 4 )\n if len(self) != 4:\n return '0x%s' % hex(self)\n return inet_ntoa( self.__str__() )\n elif self.Repr == 'hex': \n ret = '0x%s' % hex(self)\n elif self.Repr == 'bin': \n ret = '0b%s' % self.__bin__()\n # check for the best human-readable representation\n elif self.Repr == 'hum':\n # standard return\n ret = repr( self() )\n # complex return:\n # allow to assign a full Block or Layer to a Str...\n if self.__is_intern_inst(self.Pt):\n ret = repr(self.Pt)\n if self.__is_intern_inst(self.Val):\n ret = repr(self.Val)\n # allow to assign a list or tuple of Block or Layer...\n if isinstance(self.Pt, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Pt):\n ret = '|'.join(map(repr, self.Pt))\n if isinstance(self.Val, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Val):\n ret = '|'.join(map(repr, self.Val))\n # finally, self.Val can be a raw value... still\n if self.Val is not None and hasattr(self.Val, '__repr__'):\n ret = repr(self.Val)\n # truncate representation if string too long:\n # avoid terminal panic...\n if len(ret) <= self._repr_limit:\n return ret\n else:\n return ret[:self._repr_limit-3]+'...'\n \n # some more methods for checking Element's attributes:\n def getattr(self):\n return ['CallName', 'ReprName', 'Pt', 'PtFunc', 'Val', 'Len',\n 'LenFunc', 'Type', 'Repr', 'Trans', 'TransFunc']\n \n def showattr(self):\n for a in self.getattr():\n print('%s : %s' % (a, repr(self.__getattribute__(a))) )\n \n # cloning an Element, useful for \"duplicating\" an Element \n # without keeping any dependency\n # used in Layer with Element\n # However,\n #...\n # This is not that true, as an object pointed by .Pt or .Len or .Trans\n # will not be updated to its clone()\n # Conclusion:\n # use this with care\n def clone(self):\n clone = self.__class__(\n self.CallName, self.ReprName,\n self.Pt, self.PtFunc,\n self.Val, \n self.Len, self.LenFunc,\n self.Repr,\n self.Trans, self.TransFunc )\n return clone\n \n # standard method map() to map a string to the Element\n def map(self, string=''):\n if not self.is_transparent():\n l = self.map_len()\n if l is not None:\n self.Val = string[:l]\n else:\n self.Val = string\n if self.dbg >= DBG:\n log(DBG, '(Element) mapping %s on %s, %s' \\\n % (repr(string), self.CallName, repr(self)))\n \n def map_ret(self, string=''):\n self.map(string)\n return string[len(self):]\n \n # shar manipulation interface\n def to_shar(self):\n ret = shar()\n ret.set_buf(self())\n return ret\n \n def map_shar(self, sh):\n if not self.is_transparent():\n l = self.map_len()\n if l is not None:\n self.Val = sh.get_buf(l*8)\n else:\n self.Val = sh.get_buf()\n if self.dbg >= DBG:\n log(DBG, '(Element) mapping %s on %s, %s' \\\n % (repr(string), self.CallName, repr(self)))\nlibmich/core/element.py\nclass Int(Element):\n '''\n class defining a standard element, managed like an integer.\n It can be signed (int) or unsigned (uint),\n and support arbitrary byte-length:\n int8, int16, int24, int32, int40, int48, int56, int64, int72, ...\n uint8, uint16, uint24, uint32, ..., uint128, ...\n and why not int65536 !\n It is always byte-aligned (in term of length, at least).\n \n attributes:\n Pt: to point to another object or direct integer value;\n PtFunc: when defined, PtFunc(Pt) is used to generate the integer value;\n Val: when defined, overwrites the Pt (and PtFunc) integer value, \n used when mapping a string buffer to the element;\n Type: type of integer for encoding, 8,16,24,32,40,48,56,64 bits signed or\n unsigned integer;\n Dict: dictionnary to use for a look-up when representing \n the element into python;\n Repr: representation style, binary, hexa or human: human uses Dict \n if defined;\n Trans: to define transparent element which has empty str() and len() to 0,\n it \"nullifies\" its existence; can point to something for automation;\n TransFunc: when defined, TransFunc(Trans) is used to automate the \n transparency aspect: used e.g. for conditional element;\n '''\n # endianness is 'little' / 'l' or 'big' / 'b'\n _endian = 'big'\n # types format for struct library\n # 24 (16+8), 40 (32+8), 48 (32+16), 56 (32+16+8)\n _types = { 'int8':'b', 'int16':'h', 'int32':'i', 'int64':'q',\n #'int24':None, 'int40':None, 'int48':None, 'int56':None,\n 'uint8':'B', 'uint16':'H', 'uint32':'I', 'uint64':'Q',\n #'uint24':None, 'uint40':None, 'uint48':None, 'uint56':None,\n }\n #\n # for object representation\n _reprs = ['hex', 'bin', 'hum']\n \n def __init__(self, CallName='', ReprName=None,\n Pt=None, PtFunc=None, Val=None,\n Type='int32', Dict=None, DictFunc=None,\n Repr='hum',\n Trans=False, TransFunc=None):\n if CallName or not self.CallName:\n self.CallName = CallName\n if ReprName is None:\n self.ReprName = ''\n else:\n self.ReprName = ReprName\n self.Pt = Pt\n self.PtFunc = PtFunc\n self.Val = Val\n self.Type = Type\n self.Dict = Dict\n self.DictFunc = DictFunc\n self.Repr = Repr\n self.Trans = Trans\n self.TransFunc = TransFunc\n # automated attributes:\n self.Len = int(self.Type.lstrip('uint'))//8\n \n def __setattr__(self, attr, val):\n # ensures no bullshit is provided into element's attributes \n # (however, it is not a complete test...)\n if self.safe:\n if attr == 'CallName':\n if type(val) is not str or len(val) == 0:\n raise AttributeError('CallName must be a non-null string')\n elif attr == 'ReprName':\n if type(val) is not str:\n raise AttributeError('ReprName must be a string')\n elif attr == 'PtFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('PtFunc must be a function')\n elif attr == 'Val':\n if val is not None and not isinstance(val, (int, long)):\n raise AttributeError('Val must be an int or long')\n elif attr == 'Type':\n cur = 0\n if val[cur] == 'u':\n cur = 1\n if val[cur:cur+3] != 'int' or int(val[cur+3:]) % 8 != 0:\n raise AttributeError('Type must be intX / uintX with X '\\\n 'multiple of 8 bits (e.g. int24, uint32, int264, ...)')\n elif attr == 'DictFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('DictFunc must be a function')\n elif attr == 'Repr':\n if val not in self._reprs:\n raise AttributeError('Repr %s does not exist, use in: %s' \\\n % (val, self._reprs))\n elif attr == 'TransFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('TransFunc must be a function')\n if attr == 'Type':\n self.Len = int(val.lstrip('uint'))//8\n object.__setattr__(self, attr, val)\n \n def __call__(self):\n # when no values are defined at all, arbitrary returns None:\n if self.Val is None and self.Pt is None:\n # instead of \"return None\" \n # that triggers error when calling __str__() method\n return 0\n # else, Val overrides Pt capabilities:\n # transparency are not taken into account in __call__, \n # only for the __str__ representation\n elif self.Val is not None: \n return self.__confine( self.Val )\n elif self.PtFunc is not None: \n if self.safe: \n assert( type(self.PtFunc(self.Pt)) in (int, long) )\n return self.__confine(self.PtFunc(self.Pt))\n else:\n return self.__confine(int(self.Pt))\n \n def __confine(self, value):\n # unsigned\n if self.Type[0] == 'u':\n return max(0, min(2**(8*self.Len)-1, value))\n # signed\n else:\n return max(-2**(8*self.Len-1), min(2**(8*self.Len-1)-1, value))\n \n def __str__(self):\n # manages Element transparency\n if self.is_transparent():\n return ''\n # otherwise returns standard string values\n return self.__pack()\n \n def __len__(self):\n if self.is_transparent(): \n return 0\n return self.Len\n \n def bit_len(self):\n return 8*self.__len__()\n \n # map_len() is a-priori not needed in \"Int\" element, \n # but still kept for Element API uniformity\n def map_len(self):\n return self.__len__()\n \n # define integer value\n def __int__(self):\n return self()\n \n def __bin__(self):\n # unsigned or positive signed:\n val = self()\n if self.Type[0] == 'u' \\\n or self.Type[0] == 'i' and val >= 0 : \n binstr = bin(val)[2:]\n if self._endian[0] == 'l':\n # little endian\n bs = '0'*(8*self.__len__() - len(binstr)) + binstr\n bs = [bs[i:i+8] for i in range(0, len(bs), 8)]\n bs.reverse()\n return ''.join(bs)\n else:\n # big endian\n return '0'*(8*self.__len__() - len(binstr)) + binstr\n # negative signed\n else : \n # takes 2' complement to the signed val\n binstr = bin(val + 2**(8*self.__len__()-1))[2:]\n if self._endian[0] == 'l':\n # little endian\n bs = '1' + '0'*(8*self.__len__() - len(binstr) - 1) + binstr\n bs = [bs[i:i+8] for i in range(0, len(bs), 8)]\n bs.reverse()\n return ''.join(bs)\n else:\n # big endian\n return '1' + '0'*(8*self.__len__() - len(binstr) - 1) + binstr\n \n def __hex__(self):\n return hexlify(self.__pack())\n \n def __repr__(self):\n if self.Pt is None and self.Val is None:\n return repr(None)\n if self.Repr == 'hex':\n return '0x%s' % self.__hex__()\n elif self.Repr == 'bin':\n return '0b%s' % self.__bin__()\n elif self.Repr == 'hum':\n value = self()\n if self.DictFunc:\n if self.safe:\n assert(hasattr(self.DictFunc(self.Dict), '__getitem__'))\n try:\n val = '%i : %s' % (value, self.DictFunc(self.Dict)[value])\n except KeyError:\n val = value\n elif self.Dict:\n try:\n val = '%i : %s' % (value, self.Dict[value])\n except KeyError:\n val = value\n else:\n val = value\n rep = repr(val)\n if rep[-1] == 'L':\n return rep[:-1]\n return rep\n \n def getattr(self):\n return ['CallName', 'ReprName', 'Pt', 'PtFunc', 'Val', 'Len',\n 'Type', 'Dict', 'DictFunc', 'Repr', 'Trans', 'TransFunc']\n \n def showattr(self):\n for a in self.getattr():\n if a == \"Dict\" and self.Dict is not None:\n print('%s : %s' % ( a, self.__getattribute__(a).__class__) )\n else:\n print('%s : %s' % ( a, repr(self.__getattribute__(a))) )\n \n def clone(self):\n clone = self.__class__(\n self.CallName, self.ReprName,\n self.Pt, self.PtFunc,\n self.Val, self.Type,\n self.Dict, self.DictFunc, self.Repr, \n self.Trans, self.TransFunc )\n #clone._endian = self._endian\n return clone\n \n def map(self, string=''):\n if not self.is_transparent():\n # error log will be done by the Layer().map() method\n # but do this not to throw exception\n if len(string) < self.Len:\n if self.dbg >= WNG:\n log(WNG, '(%s) %s map(string) : string not long enough' \\\n % (self.__class__, self.CallName))\n return\n self.Val = self.__unpack(string[:self.Len])\n \n def map_ret(self, string=''):\n l = self.__len__()\n if 0 < l <= len(string):\n self.map(string)\n return string[l:]\n else:\n return string\n \n def __pack(self):\n # manage endianness (just in case...)\n if self._endian[0] == 'l':\n e = '<'\n else:\n e = '>'\n if self.Len == 0:\n return ''\n elif self.Len in (1, 2, 4, 8):\n # standard types for using Python struct\n return pack(e+self._types[self.Type], self())\n elif self.Type[0] == 'u':\n # non-standard unsigned int types\n return self.__pack_uX(e)\n else:\n # non-standard signed int types\n return self.__pack_iX(e)\n \n def __unpack(self, string):\n if self._endian[0] == 'l':\n e = '<'\n else:\n e = '>'\n if self.Len == 0:\n return\n elif self.Len in (1, 2, 4, 8):\n # standard types for using Python struct\n return unpack(e+self._types[self.Type], string[:self.Len])[0]\n elif self.Type[0] == 'u':\n # non-standard unsigned int types\n return self.__unpack_uX(string[:self.Len], e)\n else:\n # non-standard signed int types\n return self.__unpack_iX(string[:self.Len], e)\n \n def __pack_uX(self, e='>'):\n if e == '<':\n # little endian, support indefinite uint (e.g. uint3072)\n if self.Len <= 8:\n return pack('Q', self())[-self.Len:]\n else:\n u64 = decompose(0x10000000000000000, self())\n u64_len = 8*len(u64)\n u64_pad = 0\n if u64_len < self.Len:\n rest_len = self.Len - u64_len\n u64_pad = rest_len // 8\n if rest_len % 8:\n u64_pad += 1\n u64.extend( [0]*u64_pad )\n u64.reverse()\n return pack('>'+len(u64)*'Q', *u64)[-self.Len:]\n \n def __pack_iX(self, e='>'):\n val = self()\n # positive values are encoded just like uint\n if val >= 0:\n return self.__pack_uX(e)\n #\n # negative values, 2's complement encoding\n if e == '<':\n # little endian\n if self.Len <= 8:\n return pack('Q', 2**(self.Len*8) - abs(val))[-self.Len:]\n else:\n i8 = decompose(0x100, 2**(self.Len*8) - abs(val))\n if len(i8) < self.Len:\n i8.extend( [0]*(self.Len-len(i8)) )\n i8.reverse()\n return pack('>'+self.Len*'B', *i8)\n \n def __unpack_uX(self, string, e='>'):\n if e == '<':\n # little endian, support indefinite uint (e.g. uint3072)\n if self.Len <= 8:\n return unpack('Q', '\\0'*(8 - self.Len) + string)[0]\n else:\n #'''\n u64_len, u64_pad = self.Len // 8, self.Len % 8\n if u64_pad:\n u64_len += 1\n string = '\\0'*u64_pad + string\n u64 = unpack('>'+u64_len*'Q', string)\n return reduce(lambda x,y:(x<<64)+y, u64)\n \n def __unpack_iX(self, string, e='>'):\n if e == '<':\n # little endian\n if ord(string[-1]) & 0x80 == 0:\n # check if it is a positive value\n return self.__unpack_uX(string, e)\n elif self.Len <= 8:\n return unpack('Q', '\\0'*(8 - self.Len) + string)[0] \\\n - 2**(self.Len*8)\n else:\n i8 = unpack('>'+self.Len*'B', string)\n return reduce(lambda x,y:(x<<8)+y, i8) - 2**(self.Len*8)\n \n # shar manipulation interface\n def to_shar(self):\n ret = shar()\n ret.set_buf(self.__str__())\n return ret\n \n def map_shar(self, sh):\n if len(sh)*8 < self.Len:\n if self.dbg >= WNG:\n log(WNG, '(%s) %s map(string) : shar buffer not long enough' \\\n % (self.__class__, self.CallName))\n return\n # standard handling\n if not self.is_transparent():\n self.map(sh.get_buf(len(self)*8))\nlibmich/core/element.py\ndef showattr(self):\n for a in self.getattr():\n print('%s : %s' % (a, repr(self.__getattribute__(a))) )\nlibmich/core/element.py\nERR = 1\nlibmich/formats/L3Mobile_IE.py\nclass ID(Layer):\n constructorList = [\n Bit('digit1', Pt=0, BitLen=4, Repr='hum'),\n Bit('odd', Pt=1, BitLen=1, Repr='hum'),\n Bit('type', BitLen=3, Dict=IDtype_dict, Repr='hum')]\n \n def __init__(self, val='0', type='No Identity'):\n Layer.__init__(self)\n self.type > IDtype_dict[type]\n if type in ('IMSI', 'IMEI', 'IMEISV'):\n self.__handle_digits(val)\n if len(val)%2 == 0:\n self.odd > 0\n elif type == 'TMSI':\n self.digit1 > 0b1111\n self.odd > 0\n self.append(Str('tmsi', Pt=val[0:4], Len=4, Repr='hex'))\n elif self.type() > 4:\n self.append(Str('data', Pt=val, Repr='hex'))\n \n def map(self, s=''):\n Layer.map(self, s)\n # imsi, imei, imeisv\n if self.type() in (1,2,3):\n self.__handle_digits(''.join(['0']*(len(s[1:9])*2)))\n #if self.odd() == 0:\n # self[-1].CallName = 'end'\n # tmsi\n elif self.type() == 4:\n self.append(Str('tmsi', Len=4, Repr='hex'))\n elif self.type() > 4:\n self.append(Str('data', Repr='hex'))\n Layer.map(self, s)\n \n def __handle_digits(self, digits=''):\n try:\n self.digit1 > int(digits[0])\n except ValueError:\n debug(self.dbg, 2, '(ID) non digit character: %s' % digits[0])\n ext, i = [], 2\n for d in digits[1:]:\n try:\n ext.append(Bit('digit%i'%i, Pt=int(d), BitLen=4, Repr='hum'))\n except ValueError:\n ext.append(Bit('digit%i'%i, Pt=0, BitLen=4, Repr='hum'))\n if len(ext) == 2:\n ext.reverse()\n self.extend(ext)\n ext = []\n i+=1\n if len(ext) == 1:\n ext.append(Bit('digit%i'%i, Pt=0b1111, BitLen=4, Repr='hum'))\n #ext.append(Bit('end', Pt=0b1111, BitLen=4, Repr='hum'))\n ext.reverse()\n self.extend(ext)\n \n def __repr__(self):\n t = self.type()\n # no id\n if t == 0:\n repr = IDtype_dict[t]\n # imsi, imei, imeisv\n elif self.type() in (1, 2, 3):\n repr = '%s:%s' % (IDtype_dict[t], self.get_bcd())\n # tmsi\n elif t == 4:\n repr = '%s:0x%s' % (IDtype_dict[t], hex(self.tmsi))\n # not handled\n else:\n repr = '%s:0x%s' % (IDtype_dict[t], hex(self.data))\n return '<[ID]: %s>' % repr\n \n def get_imsi(self):\n if self.type() == 1:\n return self.get_bcd()\n else:\n return ''\n \n def get_imei(self):\n if self.type() in (2, 3):\n return self.get_bcd()\n else:\n return ''\n \n def get_bcd(self):\n return ''.join([str(getattr(self, 'digit%s'%i)()) \\\n for i in range(1, len(self)*2+self.odd()-1)])\n \n def anon(self):\n # for IMSI and IMEI, clear some digits to anonymize identities \n if self.type() in (1, 2, 3):\n if hasattr(self, 'digit8'):\n self.digit8 < None\n self.digit8 > 0\n if hasattr(self, 'digit9'):\n self.digit9 < None\n self.digit9 > 0\n if hasattr(self, 'digit10'):\n self.digit10 < None\n self.digit10 > 0\n if hasattr(self, 'digit11'):\n self.digit11 < None\n self.digit11 > 0\n if hasattr(self, 'digit12'):\n self.digit12 < None\n self.digit12 > 0\nlibmich/core/element.py\ndef log(level=DBG, string=''):\n # if needed, can be changed to write somewhere else\n # will redirect all logs from the library\n print('[libmich %s] %s' % (debug_level[level], string))\nlibmich/formats/L2GSM.py\nclass LengthRR(Layer):\r\n constructorList = [\r\n Bit('len', ReprName='L2 pseudo length', Pt=0, BitLen=6, Repr='hum'),\r\n Bit('M', ReprName='More data bit', Pt=0, BitLen=1),\r\n Bit('EL', ReprName='Length field not extended', Pt=1, BitLen=1)]\r\nlibmich/core/element.py\nWNG = 2\nlibmich/core/element.py\nclass Layer(object):\n '''\n class built from stack of \"Str\", \"Int\", \"Bit\" and \"Layer\" objects\n got from the initial constructorList.\n Layer object is recursive: it can contain other Layer() instances\n Layer does not require to be byte-aligned. This happens depending of the\n presence of Bit() instances.\n \n when instantiated:\n clones the list of \"Str\", \"Int\", \"Bit\" elements in the constructorList\n to build a dynamic elementList, that can be changed afterwards (adding /\n removing objects);\n A common hierarchy level for the whole Layer is defined, it is useful \n when used into \"Block\" to create hierarchical relationships: \n self.hierarchy (int), self.inBlock (bool)\n when .inBlock is True, provides: .get_payload(), .get_header(), \n .has_next(), .get_next(), .get_previous(), and .Block\n It provides several methods for calling elements in the layer:\n by CallName / ReprName passed in attribute\n by index in the elementList\n can be iterated too\n and many other manipulations are defined\n It has also some common methods with \"Str\", \"Int\" and \"Bit\" to emulate \n a common handling:\n __str__, __len__, __int__, bit_len, getattr, showattr, show, map\n '''\n #\n # debugging threshold for Layer:\n dbg = ERR\n # add some sanity checks\n #safe = True\n safe = False\n # define the type of str() and map() method\n _byte_aligned = True\n # reserved attributes:\n Reservd = ['CallName', 'ReprName', 'elementList', 'Len', 'BitLen',\n 'hierarchy', 'inBlock', 'Trans', 'ConstructorList',\n 'dbg', 'Reservd']\n #\n # represent transparent elements in __repr__()\n _repr_trans = True\n \n # structure description:\n constructorList = []\n \n def __init__(self, CallName='', ReprName='', Trans=False, **kwargs):\n if type(CallName) is not str:\n raise AttributeError('CallName must be a string')\n elif len(CallName) == 0:\n self.CallName = self.__class__.__name__\n else:\n self.CallName = CallName\n if type(ReprName) is str and len(ReprName) > 0: \n self.ReprName = ReprName\n else: \n self.ReprName = ''\n self.elementList = []\n self.set_hierarchy(0)\n self.inBlock = False\n self.Trans = Trans\n \n CallNames = []\n for e in self.constructorList:\n # This is for little players\n #if isinstance(e, Element):\n # OK, now let's put the balls on the table and\n # make Layer recursive (so will have Layer() into Layer())\n if isinstance(e, (Element, Layer)):\n if e.CallName in self.Reservd:\n if self.safe or self.dbg >= ERR:\n log(ERR, '(Layer - %s) using a reserved '\n 'attribute as CallName %s: aborting...' \\\n % (self.__class__, e.CallName))\n return\n if e.CallName in CallNames:\n if self.dbg >= WNG:\n log(WNG, '(Layer - %s) different elements have ' \\\n 'the same CallName %s' % (self.__class__, e.CallName))\n if isinstance(e, Element):\n self.append(e.clone())\n # do not clone Layer() as it breaks dynamic element inside\n # i.e. element with PtFunc, LenFunc, DictFunc, TransFunc defined\n # TODO: patch Layer().clone() method to solve this...\n # lets try with deepcopy()\n elif isinstance(e, Layer):\n self.append(e.clone())\n CallNames.append(e.CallName)\n \n # check for bit alignment until we lost information on the Layer length\n # also check if fixed length can be deduced\n self.BitLen = 0\n for e in self.elementList:\n if self.dbg >= DBG:\n log(DBG, '(Layer - %s) length verification for %s' \\\n % (self.__class__, e.CallName))\n if isinstance(e, Bit):\n self.BitLen += e.bit_len()\n elif hasattr(e, 'Len') and type(e.Len) is int:\n self.BitLen += (e.Len)*8\n else:\n self.BitLen, self.Len = 'var', 'var'\n break\n if type(self.BitLen) is int :\n if self.BitLen % 8:\n if self.dbg >= WNG and self._byte_aligned:\n log(WNG, '(Layer - %s) Elements seem not to be '\\\n 'byte-aligned: hope you expect it!' \\\n % self.__class__)\n # record length in bit (precise one) and in bytes (unprecised)\n self.Len = 1 + self.BitLen//8\n else:\n self.Len = self.BitLen//8\n #\n # check additional args that would correspond to contained Element\n args = kwargs.keys()\n if self.dbg >= DBG:\n log(DBG, '(Layer - %s) init kwargs: %s' % (self.__class__, args))\n for e in self:\n if hasattr(e, 'CallName') and e.CallName in args:\n if hasattr(e, 'Pt'):\n e.Pt = kwargs[e.CallName]\n else:\n kwe = kwargs[e.CallName]\n if isinstance(kwe, (tuple, list)):\n e.__init__(*kwe)\n elif isinstance(kwe, dict):\n e.__init__(**kwe)\n \n # define some basic list facilities for managing elements into the Layer, \n # through the \"elementList\" attribute:\n def __iter__(self):\n if 'elementList' in self.__dict__.keys():\n return self.__dict__['elementList'].__iter__()\n else: return [].__iter__()\n \n def __getitem__(self, num):\n return self.elementList[num]\n \n def __getslice__(self, i, j):\n l = Layer('_slice_')\n if not i or i < 0:\n i=0\n #maxj = len(self.elementList)-1\n maxj = len(self.elementList)\n if not j or j > maxj:\n j = maxj\n #\n for k in xrange(i, j):\n l.append( self[k] )\n return l\n \n def __setitem__(self, num, value):\n # special handling here: \n # use to override the element value \n # with its \"Val\" attribute (like when mapping a string)\n self.elementList[num].Val = value\n \n def append(self, element):\n #if isinstance(element, Element):\n # make Layer recursive:\n if isinstance(element, (Element, Layer)):\n if self.dbg >= WNG and element.CallName in self.getattr():\n log(WNG, '(Layer - %s) different elements have the same '\\\n 'CallName %s' % (self.__class__, element.CallName))\n self.elementList.append(element)\n \n def __lshift__(self, element):\n self.append(element)\n if isinstance(element, Layer):\n element.inc_hierarchy(self.hierarchy)\n \n def insert(self, index, element):\n CallNames = self.getattr()\n #if isinstance(element, Element):\n # make Layer recursive:\n if isinstance(element, (Element, Layer)):\n if self.dbg >= WNG and element.CallName in CallNames:\n log(WNG, '(Layer - %s) different elements have the same '\\\n 'CallName %s' % (self.__class__, element.CallName))\n self.elementList.insert(index, element)\n \n def __rshift__(self, element):\n self.insert(0, element)\n if isinstance(element, Layer):\n element.inc_hierarchy(self.hierarchy)\n \n def extend(self, newElementList):\n for e in newElementList:\n self.append(e)\n \n def remove(self, element):\n for e in self:\n if e == element:\n self.elementList.remove(element)\n \n def replace(self, current_element, new_element):\n # check index of the element ro replace\n index = 0\n for elt in self.elementList:\n if elt == current_element:\n self.remove(current_element)\n self.insert(index, new_element)\n return\n else:\n index += 1\n \n # define some attribute facilities for managing elements \n # by their CallName into the Layer\n # warning: dangerous when parsing data into Layer, \n # with elements which could have same CallName\n # \n # list facilities can be preferred in this case\n def __getattr__(self, name):\n names = [x.CallName for x in self.elementList]\n if name in names:\n return self.elementList[ names.index(name) ]\n names = [x.ReprName for x in self.elementList]\n if name in names:\n return self.elementList[ names.index(name) ]\n #\n return object.__getattribute__(self, name)\n #return self.__getattribute__(name)\n #return getattr(self, name)\n \n def __setattr__(self, name, value):\n # special handling here: use to override the element value \n # with its \"Val\" attribute (like when mapping a string)\n for e in self:\n if name == e.CallName or name == e.ReprName: \n e.Val = value\n return\n return object.__setattr__(self, name, value)\n raise AttributeError( '\"Layer\" has no \"%s\" attribute: %s' \\\n % (name, self.getattr()) )\n \n def __hasattr__(self, name):\n for e in self:\n if name == e.CallName or name == e.ReprName: \n return True\n #return object.__hasattr__(self, name): \n # not needed (does not work in the code... but works in python...)\n raise AttributeError( '\"Layer\" has no \"%s\" attribute: %s' \\\n % (name, self.getattr()) )\n \n # method for managing the Layer hierarchy (easy):\n def set_hierarchy(self, hier=0):\n self.hierarchy = hier\n for e in self:\n if isinstance(e, Layer):\n e.set_hierarchy(hier)\n \n def inc_hierarchy(self, ref=None):\n if ref is None:\n self.set_hierarchy(self.hierarchy+1)\n else: \n self.set_hierarchy(self.hierarchy+ref+1)\n #for l in self:\n # if isinstance(l, Layer):\n # l.hierarchy = self.hierarchy\n \n def dec_hierarchy(self, ref=None):\n if ref is None: \n self.set_hierarchy(self.hierarchy-1)\n else: \n self.set_hierarchy(self.hierarchy+ref-1)\n #for l in self:\n # if isinstance(l, Layer):\n # l.hierarchy = self.hierarchy\n \n # define same methods as \"Element\" type for being use the same way\n def __str__(self):\n if self.dbg >= DBG:\n log(DBG, '(Layer.__str__) entering str() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return ''\n # dispatch to the right method depending of byte alignment\n if self._byte_aligned is True:\n return self.__str_aligned()\n else:\n return self.__str_unaligned()\n \n def __str_unaligned(self):\n # then init resulting string \n # and bit offset needed to shift unaligned strings\n s = []\n off = 0\n # loop on each element into the Layer\n # also on Layer into Layer...\n for e in self:\n shtr_e, bitlen_e = e.shtr(), e.bit_len()\n rest_e = bitlen_e % 8\n if self.dbg >= DBG:\n log(DBG, '(Layer.__str__) %s: %s, %i, offset: %i' \\\n % (e.CallName, hexlify(shtr_e), bitlen_e, off))\n # if s is not byte-aligned and e is not transparent\n # update the last component of s\n if off and shtr_e:\n # 1st update last bits of s with MSB of e, \n # before stacking with the rest of e\n # (8 - off) is the room left in the LSB of s\n s[-1] = ''.join((s[-1][:-1],\n chr(ord(s[-1][-1]) + shtr_e.left_val(8-off)),\n (shtr_e << (8-off))\n ))\n # take care in case the shifting of e voids its last byte\n if rest_e and rest_e-(8-off) <= 0:\n s[-1] = s[-1][:-1]\n # update offset\n if rest_e:\n off += bitlen_e\n off %= 8\n # in case s is already aligned, append a new component to s\n elif shtr_e:\n s.append(shtr_e)\n # update offset\n if rest_e:\n off += rest_e\n if self.dbg >= DBG:\n log(DBG, '(Layer.__str__) %s' % hexlify(s))\n # well done!\n return ''.join(s)\n \n def __str_aligned(self):\n s = []\n BitStream = ''\n # loop on each element in the Layer\n # also on Layer into Layer...\n for e in self:\n # need special processing for stacking \"Bit\" element: \n # using \"BitStream\" variable\n # works only with contiguous \"Bit\" elements \n # to avoid byte-misalignment of other element in the Layer \n # (and programming complexity with shifting everywhere...)\n if isinstance(e, Bit):\n # manage element transparency with (Trans, TranFunc)\n # and build a bitstream ('100110011...1101011') from Bit values\n if not e.is_transparent():\n BitStream += str(e.__bin__())\n # when arriving on a byte boundary from bitstream, \n # create bytes and put it into the s variable\n if len(BitStream) >= 8:\n while 1:\n s.append( pack('!B', int(BitStream[:8], 2)) )\n BitStream = BitStream[8:]\n if len(BitStream) < 8:\n break\n if self.dbg >= DBG:\n log(DBG, '(Element) %s: %s, %s\\nBitstream: %s' \\\n % (e.CallName, e(), e.__bin__(), BitStream))\n # when going to standard Str or Int element, \n # or directly end of __str__ function \n # verify the full BitStream has been consumed\n # and continue to build the resulting string easily...\n else:\n # possible byte mis-alignment for Str / Int is not managed...\n self.__is_aligned(BitStream)\n BitStream = ''\n if isinstance(e, Layer) and not e.Trans \\\n or isinstance(e, Element):\n s.append( str(e) )\n self.__is_aligned(BitStream)\n return ''.join(s)\n \n def __is_aligned(self, BitStream):\n if BitStream and self.dbg >= ERR:\n log(ERR, '(Layer - %s) some of the Bit elements have not been ' \\\n 'stacked in the \"str(Layer)\"\\nremaining bitstream: %s' \\\n % (self.__class__, BitStream))\n if self.safe:\n assert(not BitStream)\n \n def __call__(self):\n return self.__str__()\n \n def __len__(self):\n return len(self.__str__())\n \n def shtr(self):\n return shtr(self.__str__())\n \n def bit_len(self):\n # just go over all internal elements to track their own bit length\n # updated attributes initialized when Layer was constructed\n self.BitLen = 0\n for e in self:\n if hasattr(e, 'bit_len'):\n self.BitLen += e.bit_len()\n elif hasattr(e, '__len__'):\n self.BitLen += len(e)*8\n self.Len = 1 + (self.BitLen // 8) if self.BitLen % 8 \\\n else (self.BitLen // 8)\n return self.BitLen\n \n def __hex__(self):\n bit_len = self.bit_len()\n hex_len = bit_len/4\n if bit_len%4:\n hex_len += 1\n #\n return self.__str__().encode('hex')[:hex_len]\n \n def __bin__(self):\n bits = []\n for e in self:\n bits.append( e.__bin__() )\n return ''.join(bits)\n \n def __int__(self):\n # big endian integer representation of the string buffer\n if self._byte_aligned:\n return shtr(self).left_val(len(self)*8)\n else:\n return shtr(self).left_val(self.bit_len())\n \n def __repr__(self):\n t = ''\n if self.Trans:\n t = ' - transparent '\n s = '<%s[%s]%s: ' % ( self.ReprName, self.CallName, t )\n for e in self:\n if self._repr_trans or not e.is_transparent():\n s += '%s(%s):%s, ' % ( e.CallName, e.ReprName, repr(e) )\n s = s[:-2] + '>'\n return s\n \n def map_len(self):\n return len(self)\n \n def getattr(self):\n return [e.CallName for e in self.elementList]\n \n def showattr(self):\n for a in self.getattr():\n print('%s : %s' % ( a, repr(self.__getattr__(a))) )\n \n def clone2(self):\n # TODO: deepcopy is not adapted here, can create errors...\n return deepcopy(self)\n \n def clone(self):\n #\n # build a new constructorList made of clones\n constructorList_new = []\n for e in self:\n constructorList_new.append(e.clone())\n #\n # substitute the current constructorList with the one made of clones\n constructorList_ori = self.__class__.constructorList\n self.__class__.constructorList = constructorList_new\n # instantiate the clone\n c = self.__class__()\n c.CallName = self.CallName\n if hasattr(self, 'ReprName'):\n c.ReprName = self.ReprName\n if hasattr(self, 'Trans'):\n c.Trans = self.Trans\n # restore the original constructorList\n self.__class__.constructorList = constructorList_ori\n #\n return c\n \n def is_transparent(self):\n if self.Trans:\n return True\n else:\n return False\n \n def show(self, with_trans=False):\n re, tr = '', ''\n if self.ReprName != '':\n re = '%s ' % self.ReprName\n if self.is_transparent():\n # TODO: eval the best convinience here\n if not with_trans:\n return ''\n tr = ' - transparent'\n # Layer content\n str_lst = [e.show().replace('\\n', '\\n ') for e in self]\n # insert spaces for nested layers and filter out empty content\n str_lst = [' %s\\n' % s for s in str_lst if s]\n # insert layer's title\n str_lst.insert(0, '### %s[%s]%s ###\\n' % (re, self.CallName, tr))\n # return full inline string without last CR\n return ''.join(str_lst)[:-1]\n \n def map(self, string=''):\n if self.dbg >= DBG:\n log(DBG, '(Layer.map) entering map() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return\n # dispatch to the right method depending of byte alignment\n if self._byte_aligned is True:\n self.__map_aligned(string)\n else:\n self.__map_unaligned(string)\n \n def __map_unaligned(self, string=''):\n s = shtr(string)\n # otherwise go to map() over all elements\n for e in self:\n if self.dbg >= DBG:\n log(DBG, '(Layer.__map_unaligned) %s, bit length: %i' \\\n % (e.CallName, e.bit_len()))\n log(DBG, '(Layer.__map_unaligned) string: %s' % hexlify(s))\n # this is beautiful\n s = e.map_ret(s)\n \n def __map_aligned(self, string=''):\n # Bit() elements are processed intermediary: \n # 1st placed into BitStack\n # and when BitStack is byte-aligned (check against BitStack_len)\n # string buffer is then mapped to it\n self.__BitStack = []\n self.__BitStack_len = 0\n # Furthermore, it manages only contiguous Bit elements \n # for commodity... otherwise, all other elements should be shifted\n #\n for e in self:\n # special processing for Bit() element:\n if isinstance(e, Bit):\n self.__add_to_bitstack(e)\n # if BitStack is byte aligned, map string to it:\n if self.__BitStack_len % 8 == 0:\n string = self.__map_to_bitstack(string)\n # for other elements (Str(), Int(), Layer()), standard processing: \n else:\n if self.__BitStack_len > 0 and self.dbg >= ERR:\n log(WNG, '(Layer - %s) some of the Bit elements have not ' \\\n 'been mapped in the \"Layer\": not byte-aligned' \\\n % self.__class__)\n if isinstance(e, (Layer, Element)) and not e.is_transparent():\n if len(string) < e.map_len() and self.dbg >= WNG:\n log(WNG, '(Layer - %s) String buffer not long ' \\\n 'enough for %s' % (self.__class__, e.CallName))\n #if self.safe:\n # return\n e.map(string)\n string = string[e.map_len():]\n # delete .map() *internal* attributes\n del self.__BitStack\n del self.__BitStack_len\n \n def __add_to_bitstack(self, bit_elt):\n # check for Bit() element transparency\n if not bit_elt.is_transparent():\n self.__BitStack += [bit_elt]\n self.__BitStack_len += bit_elt.bit_len()\n \n def __map_to_bitstack(self, string):\n # 1st check if string is long enough for the prepared BitStack\n if len(string) < self.__BitStack_len//8 and self.dbg >= ERR:\n log(ERR, '(Layer - %s) String buffer not long enough for %s' \\\n % (self.__class__, self.__BitStack[-1].CallName))\n #if self.safe:\n # return\n # string buffer parsing is done through intermediary\n # string buffer \"s_stack\"\n s_stack = string[:self.__BitStack_len//8]\n # create a bitstream \"s_bin\" for getting the full BitStack\n s_bin = ''\n for char in s_stack:\n # convert to bitstream thanks to python native bit repr\n s_bin_tmp = bin(ord(char))[2:]\n # prepend 0 to align on byte (python does not do it)\n # and append to the bitstream \"s_bin\" (string of 0 and 1)\n s_bin = ''.join((s_bin, (8-len(s_bin_tmp))*'0', s_bin_tmp))\n # map the bitstream \"s_bin\" into each BitStack element\n for bit_elt in self.__BitStack:\n bitlen = bit_elt.bit_len()\n if bitlen:\n # convert the bitstream \"s_bin\" into integer \n # according to the length in bit of bit_elt\n bit_elt.map_bit( int(s_bin[:bit_elt.bit_len()], 2) )\n # truncate the \"s_bin\" bitstream\n s_bin = s_bin[bit_elt.bit_len():]\n # consume the global string buffer that has been mapped \n # (from s_stack internal variable)\n # and reinitialize self.__BitStack* attributes\n string = string[self.__BitStack_len//8:]\n self.__BitStack = []\n self.__BitStack_len = 0\n # finally return string to parent method .map()\n return string\n \n # map_ret() maps a buffer to a Layer, the unaligned way,\n # and returns the rest of the buffer that was not mapped\n def map_ret(self, string=''):\n if self.dbg >= DBG:\n log(DBG, '(Layer.map_ret) entering map_ret() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return string\n if self._byte_aligned is True:\n self.__map_aligned(string)\n return string[len(self):]\n else:\n # actually, map_ret() is only interesting for unaligned layers\n s = shtr(string)\n for e in self:\n if self.dbg >= DBG:\n log(DBG, '(Layer.map_ret) %s, bit length: %i' \\\n % (e.CallName, e.bit_len()))\n log(DBG, '(Layer.map_ret) string: %s' % hexlify(s))\n # this is beautiful\n s = e.map_ret(s)\n return s\n \n # define methods when Layer is in a Block:\n # next, previous, header: return Layer object reference\n # payload: returns Block object reference\n def get_index(self):\n if self.inBlock is not True: \n return 0\n i = 0\n for l in self.Block:\n if l == self: return i\n else: i += 1\n # could happen if Layer is placed in several Block()\n # and the last Block used is deleted\n return False\n \n def has_next(self):\n if self.inBlock is not True: \n return False\n return self.Block.has_index(self.get_index()+1)\n \n def get_next(self):\n if self.has_next():\n return self.Block[self.get_index()+1]\n return RawLayer()\n \n def has_previous(self):\n if self.inBlock is not True: \n return False\n index = self.get_index()\n if index <= 0:\n return False\n return self.Block.has_index(index-1)\n \n def get_previous(self):\n if self.has_previous():\n return self.Block[self.get_index()-1]\n return RawLayer()\n \n def get_header(self):\n if self.has_previous():\n index = self.get_index()\n i = index - 1\n while i >= 0:\n if self.Block[i].hierarchy == self.hierarchy-1:\n return self.Block[i]\n else:\n i -= 1\n return RawLayer()\n \n def get_payload(self):\n # return a Block, not a Layer like other methods \n # for management into a Block\n pay = Block('pay')\n if self.has_next():\n index = self.get_index()\n for l in self.Block[ index+1 : ]:\n if l.hierarchy > self.hierarchy:\n #pay.append( l.clone() )\n # not needed to append a clone\n # better keep reference to original layer\n pay.append( l )\n else:\n break\n if pay.num() == 0:\n pay.append( RawLayer() )\n return pay\n pay.append( RawLayer() )\n return pay\n \n def num(self):\n return 1\n \n # this is to retrieve full Layer's dynamicity from a mapped layer\n def reautomatize(self):\n for e in self:\n if hasattr(e, 'reautomatize'):\n e.reautomatize()\n \n def parse(self, s=''):\n self.map(s)\n \n # shar manipulation interface\n def to_shar(self):\n if hasattr(self, 'Trans') and self.Trans:\n return shar()\n bits = []\n for e in self:\n bits.append( e.to_shar().get_bits() )\n s = shar()\n s.set_bits( bits )\n return s\n \n def map_shar(self, sh):\n if self.dbg >= DBG:\n log(DBG, '(Layer.map) entering map() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return\n if not isinstance(sh, shar):\n sh = shar(sh)\n for e in self:\n e.map_shar(sh)\nlibmich/formats/L3Mobile_MM.py\nclass Header(Layer):\r\nclass IMSI_DETACH_INDICATION(Layer3):\r\nclass LOCATION_UPDATING_ACCEPT(Layer3):\r\nclass LOCATION_UPDATING_REJECT(Layer3):\r\nclass LOCATION_UPDATING_REQUEST(Layer3):\r\nclass AUTHENTICATION_REJECT(Layer3):\r\nclass AUTHENTICATION_REQUEST(Layer3):\r\nclass AUTHENTICATION_RESPONSE(Layer3):\r\nclass AUTHENTICATION_FAILURE(Layer3):\r\nclass IDENTITY_REQUEST(Layer3):\r\nclass IDENTITY_RESPONSE(Layer3):\r\nclass TMSI_REALLOCATION_COMMAND(Layer3):\r\nclass TMSI_REALLOCATION_COMPLETE(Layer3):\r\nclass CM_SERVICE_ACCEPT(Layer3):\r\nclass CM_SERVICE_PROMPT(Layer3):\r\nclass CM_SERVICE_REJECT(Layer3):\r\nclass CM_SERVICE_ABORT(Layer3):\r\nclass CM_SERVICE_REQUEST(Layer3):\r\nclass CM_REESTABLISHMENT_REQUEST(Layer3):\r\nclass ABORT(Layer3):\r\nclass MM_INFORMATION(Layer3):\r\nclass MM_STATUS(Layer3):\r\nclass MM_NULL(Layer3):\r\n def __init__(self, prot=5, type=48):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\n def __init__(self, with_options=True, **kwargs):\r\nlibmich/core/IANA_dict.py\nclass IANA_dict(dict):\r\n '''\r\n Class to manage dictionnaries with integer as keys \r\n and 2-tuples of string as items,\r\n such as IANA protocols parameters reference: http://www.iana.org/protocols/\r\n \r\n call it like this:\r\n IANA_dict( { integer : (\"parameter name\", \"parameter abbreviation\"), \r\n integer: \"parameter name\", ... } )\r\n '''\r\n \r\n def __init__(self, IANA_dict={}):\r\n '''\r\n initialize like a dict\r\n [+] if 'key' is not integer, raises error\r\n [+] if value 'value' is not string or 2-tuple of string, raises error\r\n [+] if value is string, transforms it in 2-tuple (\"value\", \"\")\r\n i.e. value must be (\"value name\", value abbreviation\")\r\n '''\r\n # 1st: rearrange string item to 2-tuple of string\r\n items = dict.items(IANA_dict)\r\n for i in items:\r\n if type(i[1]) is str:\r\n dict.__setitem__( IANA_dict, i[0], (i[1], \"\") )\r\n \r\n # 2nd: verification: key is int / long, and item is 2-tuple of string\r\n items = dict.items(IANA_dict)\r\n for i in items:\r\n if type(i[0]) not in (int, long):\r\n raise KeyError('%s : key must be integer' % i[0])\r\n if type(i[1]) is not tuple or len(i[1]) != 2:\r\n raise ValueError('%s : value must be string or 2-tuple of ' \\\r\n 'string' % i[1])\r\n \r\n dict.update(self, IANA_dict)\r\n \r\n def __getitem__(self, key):\r\n '''\r\n Same as dict.__getitem__(key)\r\n [+] If 'key' is integer and does not exist,\r\n returns the item corresponding to the last existing key,\r\n except if key is over the last key.\r\n [+] If 'key' is string and exists as value (name or abbreviation),\r\n returns first key found corresponding to the value.\r\n '''\r\n values = []\r\n for e in self.values():\r\n for v in e:\r\n if type(v) is str and len(v) > 0:\r\n values.append(v)\r\n \r\n if self.__contains__(key):\r\n return dict.__getitem__(self, key)[0]\r\n \r\n elif type(key) in (int, long) \\\r\n and self.s_keys()[0] < key < self.s_keys().pop():\r\n i = 0\r\n while self.__contains__(key-i) is False: i += 1\r\n return dict.__getitem__(self, key-i)[0]\r\n \r\n elif type(key) is str and key in values:\r\n i = 0\r\n while key not in self.items()[i][1]: i += 1\r\n return self.items()[i][0]\r\n \r\n else: \r\n try: return dict.__getitem__(self, key)\r\n except KeyError: return key\r\n \r\n def __setitem__(self, key, item):\r\n '''\r\n Same as dict.__setitem__(key)\r\n [+] If 'key' is not integer, raises error\r\n [+] If 'value' is not string or 2-tuple of strings, raises error\r\n '''\r\n if type(key) not in [int, long]:\r\n raise KeyError('%s : key must be integer' % key)\r\n if type(item) is str:\r\n item = (item, \"\")\r\n if type(item) is not tuple or len(item) != 2:\r\n raise ValueError('%s : value must be string or 2-tuple of '\\\r\n 'string' % item)\r\n dict.__setitem__(self, key, item)\r\n \r\n def s_keys(self):\r\n '''\r\n returns a sorted list of keys\r\n ''' \r\n s_keys = dict.keys(self)\r\n s_keys.sort()\r\n return s_keys\r\n \r\n def items(self):\r\n '''\r\n returns the list of (key, value), following the order of sorted keys.\r\n '''\r\n items = []\r\n s_keys = self.s_keys()\r\n for k in s_keys:\r\n items.append( (k, dict.__getitem__(self, k)) )\r\n return items\r\nlibmich/core/element.py\nclass Bit(Element):\n '''\n class defining a standard element, managed like a bit (e.g. a flag)\n or bit-stream of variable bit length\n Values are corresponding to unsigned integer: from 0 to pow(2, bit_len)-1.\n It does not require to be byte-aligned.\n \n attributes:\n Pt: to point to another object or direct integer value;\n PtFunc: when defined, PtFunc(Pt) is used to generate the integer value;\n Val: when defined, overwrites the Pt (and PtFunc) integer value, \n used when mapping string to the element;\n BitLen: length in bits of the bit stream;\n BitLenFunc: to be used when mapping string with variable bit-length, \n BitLenFunc(BitLen) is used;\n Dict: dictionnary to use for a look-up when representing \n the element into python;\n Repr: representation style, binary, hexa or human: human uses Dict;\n Trans: to define transparent element which has empty str() and len() to 0,\n it \"nullifies\" its existence; can point to something for automation;\n TransFunc: when defined, TransFunc(Trans) is used to automate the \n transparency aspect: used e.g. for conditional element;\n '''\n # for object representation\n _reprs = ['hex', 'bin', 'hum']\n \n def __init__(self, CallName='', ReprName=None, \n Pt=None, PtFunc=None, Val=None, \n BitLen=1, BitLenFunc=None,\n Dict=None, DictFunc=None, Repr='bin', \n Trans=False, TransFunc=None):\n if CallName or not self.CallName:\n self.CallName = CallName\n if ReprName is None: \n self.ReprName = ''\n else: \n self.ReprName = ReprName\n self.Pt = Pt\n self.PtFunc = PtFunc\n self.Val = Val\n self.BitLen = BitLen\n self.BitLenFunc = BitLenFunc\n self.Dict = Dict\n self.DictFunc = DictFunc\n self.Repr = Repr\n self.Trans = Trans\n self.TransFunc = TransFunc\n \n def __setattr__(self, attr, val):\n # ensures no bullshit is provided into element's attributes \n # (however, it is not a complete test...)\n if self.safe:\n if attr == 'CallName':\n if type(val) is not str or len(val) == 0:\n raise AttributeError('CallName must be a non-null string')\n elif attr == 'ReprName':\n if type(val) is not str:\n raise AttributeError('ReprName must be a string')\n elif attr == 'PtFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('PtFunc must be a function')\n elif attr == 'Val':\n if val is not None and not isinstance(val, (int, long)):\n raise AttributeError('Val must be an int')\n elif attr == 'BitLenFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('BitLenFunc must be a function')\n elif attr == 'DictFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('DictFunc must be a function')\n elif attr == 'Repr':\n if val not in self._reprs:\n raise AttributeError('Repr %s does not exist, use in: %s' \\\n % (val, self._reprs))\n elif attr == 'TransFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('TransFunc must be a function')\n object.__setattr__(self, attr, val)\n \n def __call__(self):\n if self.Val is None and self.Pt is None: return 0\n if self.Val is not None: return self.__confine(self.Val) \n elif self.PtFunc is not None:\n if self.safe:\n assert( type(self.PtFunc(self.Pt)) is int )\n return self.__confine(self.PtFunc(self.Pt))\n else: return self.__confine(int(self.Pt))\n \n def __confine(self, value):\n # makes sure value provided does not overflow bit length\n return max( 0, min( pow(2, self.bit_len())-1, value ))\n \n def __str__(self):\n # return the string representation of the integer value\n # big-endian encoded\n # left-aligned according to the bit length\n # -> last bits of the last byte are nullified\n # \n # manages Element transparency\n if self.is_transparent():\n return ''\n # do it the dirty way:\n h = self.__hex__()\n if not h:\n return ''\n if len(h) % 2: h = ''.join(('0', h))\n return str(shtr(unhexlify(h)) << (8-(self.bit_len()%8))%8)\n \n def _shar__str__(self):\n bitlen = self.bit_len()\n if bitlen == 0:\n return ''\n ret = shar()\n ret.set_uint(self(), bitlen)\n return ret.to_buf()\n \n def __len__(self):\n # just for fun here, \n # but do not use this in program...\n bitlen = self.bit_len()\n if bitlen % 8:\n return (bitlen//8) + 1\n return bitlen//8\n \n def bit_len(self):\n # manages Element transparency\n if self.is_transparent():\n return 0\n # and standard bit length processing\n if self.BitLenFunc is not None:\n if self.safe:\n assert( type(self.BitLenFunc(self.BitLen)) is int )\n return self.BitLenFunc(self.BitLen)\n else:\n if self.safe:\n assert( type(self.BitLen) is int )\n return self.BitLen\n \n def map_len(self):\n bitlen = self.bit_len()\n if bitlen % 8:\n return (bitlen//8)+1\n return bitlen//8\n \n def __hex__(self):\n bitlen = self.bit_len()\n if not bitlen:\n return ''\n hexa = hex(self())[2:]\n if hexa[-1] == 'L':\n # thx to Python to add 'L' for long on hex repr...\n hexa = hexa[:-1]\n if self.bit_len()%4: \n return '0'*(self.bit_len()//4 + 1 - len(hexa)) + hexa\n else: \n return '0'*(self.bit_len()//4 - len(hexa)) + hexa\n \n def __int__(self):\n return self()\n \n def __bin__(self):\n bitlen = self.bit_len()\n if not bitlen:\n return ''\n binary = format(self(), 'b')\n return (bitlen - len(binary))*'0' + binary\n \n def __repr__(self):\n if self.Repr == 'hex': return '0x%s' % self.__hex__()\n elif self.Repr == 'bin': return '0b%s' % self.__bin__()\n elif self.Repr == 'hum':\n value = self()\n if self.DictFunc:\n if self.safe:\n assert(hasattr(self.DictFunc(self.Dict), '__getitem__'))\n try: val = '%i : %s' % (value, self.DictFunc(self.Dict)[value])\n except KeyError: val = value\n elif self.Dict:\n try: val = '%i : %s' % (value, self.Dict[value])\n except KeyError: val = value\n else:\n val = value\n #return repr(val)\n rep = repr(val)\n if rep[-1] == 'L':\n rep = rep[:-1]\n return rep\n \n def getattr(self):\n return ['CallName', 'ReprName', 'Pt', 'PtFunc', 'Val', 'BitLen',\n 'BitLenFunc', 'Dict', 'DictFunc', 'Repr', 'Trans', 'TransFunc']\n \n def showattr(self):\n for a in self.getattr():\n if a == 'Dict' and self.Dict is not None: \n print('%s : %s' % ( a, self.__getattribute__(a).__class__) )\n else: \n print('%s : %s' % ( a, repr(self.__getattribute__(a))) )\n \n # cloning an element, used in set of elements\n def clone(self):\n clone = self.__class__(\n self.CallName, self.ReprName,\n self.Pt, self.PtFunc,\n self.Val, \n self.BitLen, self.BitLenFunc,\n self.Dict, self.DictFunc, self.Repr,\n self.Trans, self.TransFunc )\n return clone\n \n def map(self, string=''):\n # map each bit of the string from left to right\n # using the shtr() class to shift the string\n # string must be ascii-encoded (see shtr)\n if not self.is_transparent():\n self.map_bit( shtr(string).left_val(self.bit_len()) )\n \n def map_bit(self, value=0):\n # map an int / long value\n if self.safe:\n assert( 0 <= value <= pow(2, self.bit_len()) )\n self.Val = value\n \n def map_ret(self, string=''):\n if self.is_transparent():\n return string\n else:\n shtring = shtr(string)\n bitlen = self.bit_len()\n self.map_bit( shtring.left_val(bitlen) )\n return shtring << bitlen\n \n # shar manipulation interface\n def to_shar(self):\n ret = shar()\n ret.set_uint(self(), self.bit_len())\n return ret\n \n def map_shar(self, sh):\n if not self.is_transparent():\n self.map_bit( sh.get_uint(self.bit_len()) )\nlibmich/core/element.py\ndef show(self, with_trans=False):\n tr, re = '', ''\n if self.is_transparent():\n # TODO: eval the best convinience here\n if not with_trans:\n return ''\n tr = ' - transparent'\n else:\n tr = ''\n if self.ReprName != '':\n re = ''.join((self.ReprName, ' '))\n return '<%s[%s%s] : %s>' % ( re, self.CallName, tr, repr(self) )\nlibmich/formats/L3Mobile_IE.py\nclass LAI(Layer):\n constructorList = [\n PLMN(),\n Int('LAC', Pt=0, Type='uint16', Repr='hex')\n ]\n \n def __init__(self, MCCMNC='00101', LAC=0x0000):\n Layer.__init__(self)\n self.PLMN.set_mcc(MCCMNC[:3])\n self.PLMN.set_mnc(MCCMNC[3:])\n self.LAC > LAC\n \n def __repr__(self):\n return '<[LAI]: %s / LAC: 0x%.4x>' % (self.PLMN.__repr__(), self.LAC())\nlibmich/core/element.py\nDBG = 3\n", "answers": ["class Header(Layer):"], "length": 8631, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "dc4ff2fc6f100b17de1ad7eb2d14d1eb33ecd406c9bfa88e"} {"input": "from libmich.core.element import Bit, Int, Str, Layer, show, debug\r\nfrom libmich.core.IANA_dict import IANA_dict\r\nfrom libmich.core.shtr import shtr\r\nfrom libmich.formats.L3Mobile_24007 import Type1_TV, Type2, \\\r\n Type3_V, Type3_TV, Type4_LV, Type4_TLV, PD_dict, \\\r\n Layer3\r\nfrom libmich.formats.L3Mobile_IE import BCDNumber, StrBCD, BCDType_dict, \\\r\n NumPlan_dict\r\nfrom math import ceil\r\nfrom binascii import unhexlify as unh\r\nfrom re import split\r\n# −*− coding: UTF−8 −*−\r\n#/**\r\n# * Software Name : libmich \r\n# * Version : 0.2.2\r\n# *\r\n# * Copyright © 2012. Benoit Michau. ANSSI / FlUxIuS\r\n# * Many thanks to FlUxIuS for its submission (greatly appreciated)\r\n# *\r\n# * This program is free software: you can redistribute it and/or modify\r\n# * it under the terms of the GNU General Public License version 2 as published\r\n# * by the Free Software Foundation. \r\n# *\r\n# * This program is distributed in the hope that it will be useful,\r\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# * GNU General Public License for more details. \r\n# *\r\n# * You will find a copy of the terms and conditions of the GNU General Public\r\n# * License version 2 in the \"license.txt\" file or\r\n# * see http://www.gnu.org/licenses/ or write to the Free Software Foundation,\r\n# * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n# *\r\n# *--------------------------------------------------------\r\n# * File Name : formats/L3Mobile_SMS.py\r\n# * Created : 2012-08-28 \r\n# * Authors : Benoit Michau \r\n# *--------------------------------------------------------\r\n#*/ \r\n\r\n#!/usr/bin/env python\r\n\r\n#\r\n\r\n\r\n# export filter\r\n__all__ = ['CP_DATA', 'CP_ACK', 'CP_ERROR', \\\r\n 'RP_DATA_MSToNET', 'RP_DATA_NETToMS', 'RP_SMMA', 'RP_ACK_MSToNET', 'RP_ACK_NETToMS', \\\r\n 'RP_ERROR', 'RP_Originator_Address', 'RP_Destination_Address', \\\r\n 'TP_Address', 'TP_Originating_Address', 'TP_Destination_Address', \\\r\n 'TP_Recipient_Address', 'TP_PID', 'TP_DCS', 'TP_SCTS', 'TP_VP_rel', \\\r\n 'TP_VP_abs', 'TP_DT', 'TP_PI', 'Str7b', 'TP_UDH_TLV', 'SMS_DELIVER', \\\r\n 'SMS_DELIVER_REPORT_RP_ERROR', 'SMS_DELIVER_REPORT_RP_ACK', \\\r\n 'SMS_SUBMIT', 'SMS_SUBMIT_REPORT_RP_ERROR', 'SMS_SUBMIT_REPORT_RP_ACK', \\\r\n 'SMS_STATUS_REPORT', 'SMS_COMMAND', \\\r\n ]\r\n\r\n# TS 24.011 defines SMS lower layer signalling for mobile networks\r\n# section 7 and 8: message format and IE coding.\r\n# It defines the control and relay layers for SMS-PP\r\n# SM-CP : Short Message Control Protocol\r\n# SM-RP : Short Message Relay Protocol, on top of SM-CP\r\n\r\n# TS 23.040 defines SMS transport and application layers\r\n# section 9: message format and IE coding.\r\n# It defines the highest layers of the SMS protocol signalling for SMS-PP\r\n# and how the content of the message itself is encoded\r\n# SM-TL : Short Message Transport Protocol\r\n# SM-AL : Short Message Application Layer\r\n\r\n\r\n# 24007, section 11.2.3.1.2\r\nTI_dict = {\r\n 0:'allocated by sender',\r\n 1:'allocated by receiver',\r\n }\r\n\r\n# 24011, section 8.1: SM-CP\r\n# CS Mobility Management procedures dict\r\nSMSCP_dict = IANA_dict({\r\n 1:(\"SMS CP-DATA\", \"DATA\"),\r\n 4:(\"SMS CP-ACK\", \"ACK\"),\r\n 16:(\"SMS CP-ERROR\", \"ERR\"),\r\n })\r\n\r\n# section 8.1.4.2\r\nCPCause_dict = {\r\n 17 : 'Network failure',\r\n 22 : 'Congestion',\r\n 81 : 'Invalid Transaction Identifier value',\r\n 95 : 'Semantically incorrect message',\r\n 96 : 'Invalid mandatory information',\r\n 97 : 'Message type non existent or not implemented',\r\n 98 : 'Message not compatible with the short message protocol state',\r\n 99 : 'Information element non existent or not implemented',\r\n 111 : 'Protocol error, unspecified',\r\n }\r\n\r\n###################\r\n# message formats #\r\n###################\r\n### Control Protocol ###\r\nclass Header(Layer):\r\n constructorList = [\r\n", "context": "libmich/core/element.py\nclass Bit(Element):\n '''\n class defining a standard element, managed like a bit (e.g. a flag)\n or bit-stream of variable bit length\n Values are corresponding to unsigned integer: from 0 to pow(2, bit_len)-1.\n It does not require to be byte-aligned.\n \n attributes:\n Pt: to point to another object or direct integer value;\n PtFunc: when defined, PtFunc(Pt) is used to generate the integer value;\n Val: when defined, overwrites the Pt (and PtFunc) integer value, \n used when mapping string to the element;\n BitLen: length in bits of the bit stream;\n BitLenFunc: to be used when mapping string with variable bit-length, \n BitLenFunc(BitLen) is used;\n Dict: dictionnary to use for a look-up when representing \n the element into python;\n Repr: representation style, binary, hexa or human: human uses Dict;\n Trans: to define transparent element which has empty str() and len() to 0,\n it \"nullifies\" its existence; can point to something for automation;\n TransFunc: when defined, TransFunc(Trans) is used to automate the \n transparency aspect: used e.g. for conditional element;\n '''\n # for object representation\n _reprs = ['hex', 'bin', 'hum']\n \n def __init__(self, CallName='', ReprName=None, \n Pt=None, PtFunc=None, Val=None, \n BitLen=1, BitLenFunc=None,\n Dict=None, DictFunc=None, Repr='bin', \n Trans=False, TransFunc=None):\n if CallName or not self.CallName:\n self.CallName = CallName\n if ReprName is None: \n self.ReprName = ''\n else: \n self.ReprName = ReprName\n self.Pt = Pt\n self.PtFunc = PtFunc\n self.Val = Val\n self.BitLen = BitLen\n self.BitLenFunc = BitLenFunc\n self.Dict = Dict\n self.DictFunc = DictFunc\n self.Repr = Repr\n self.Trans = Trans\n self.TransFunc = TransFunc\n \n def __setattr__(self, attr, val):\n # ensures no bullshit is provided into element's attributes \n # (however, it is not a complete test...)\n if self.safe:\n if attr == 'CallName':\n if type(val) is not str or len(val) == 0:\n raise AttributeError('CallName must be a non-null string')\n elif attr == 'ReprName':\n if type(val) is not str:\n raise AttributeError('ReprName must be a string')\n elif attr == 'PtFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('PtFunc must be a function')\n elif attr == 'Val':\n if val is not None and not isinstance(val, (int, long)):\n raise AttributeError('Val must be an int')\n elif attr == 'BitLenFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('BitLenFunc must be a function')\n elif attr == 'DictFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('DictFunc must be a function')\n elif attr == 'Repr':\n if val not in self._reprs:\n raise AttributeError('Repr %s does not exist, use in: %s' \\\n % (val, self._reprs))\n elif attr == 'TransFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('TransFunc must be a function')\n object.__setattr__(self, attr, val)\n \n def __call__(self):\n if self.Val is None and self.Pt is None: return 0\n if self.Val is not None: return self.__confine(self.Val) \n elif self.PtFunc is not None:\n if self.safe:\n assert( type(self.PtFunc(self.Pt)) is int )\n return self.__confine(self.PtFunc(self.Pt))\n else: return self.__confine(int(self.Pt))\n \n def __confine(self, value):\n # makes sure value provided does not overflow bit length\n return max( 0, min( pow(2, self.bit_len())-1, value ))\n \n def __str__(self):\n # return the string representation of the integer value\n # big-endian encoded\n # left-aligned according to the bit length\n # -> last bits of the last byte are nullified\n # \n # manages Element transparency\n if self.is_transparent():\n return ''\n # do it the dirty way:\n h = self.__hex__()\n if not h:\n return ''\n if len(h) % 2: h = ''.join(('0', h))\n return str(shtr(unhexlify(h)) << (8-(self.bit_len()%8))%8)\n \n def _shar__str__(self):\n bitlen = self.bit_len()\n if bitlen == 0:\n return ''\n ret = shar()\n ret.set_uint(self(), bitlen)\n return ret.to_buf()\n \n def __len__(self):\n # just for fun here, \n # but do not use this in program...\n bitlen = self.bit_len()\n if bitlen % 8:\n return (bitlen//8) + 1\n return bitlen//8\n \n def bit_len(self):\n # manages Element transparency\n if self.is_transparent():\n return 0\n # and standard bit length processing\n if self.BitLenFunc is not None:\n if self.safe:\n assert( type(self.BitLenFunc(self.BitLen)) is int )\n return self.BitLenFunc(self.BitLen)\n else:\n if self.safe:\n assert( type(self.BitLen) is int )\n return self.BitLen\n \n def map_len(self):\n bitlen = self.bit_len()\n if bitlen % 8:\n return (bitlen//8)+1\n return bitlen//8\n \n def __hex__(self):\n bitlen = self.bit_len()\n if not bitlen:\n return ''\n hexa = hex(self())[2:]\n if hexa[-1] == 'L':\n # thx to Python to add 'L' for long on hex repr...\n hexa = hexa[:-1]\n if self.bit_len()%4: \n return '0'*(self.bit_len()//4 + 1 - len(hexa)) + hexa\n else: \n return '0'*(self.bit_len()//4 - len(hexa)) + hexa\n \n def __int__(self):\n return self()\n \n def __bin__(self):\n bitlen = self.bit_len()\n if not bitlen:\n return ''\n binary = format(self(), 'b')\n return (bitlen - len(binary))*'0' + binary\n \n def __repr__(self):\n if self.Repr == 'hex': return '0x%s' % self.__hex__()\n elif self.Repr == 'bin': return '0b%s' % self.__bin__()\n elif self.Repr == 'hum':\n value = self()\n if self.DictFunc:\n if self.safe:\n assert(hasattr(self.DictFunc(self.Dict), '__getitem__'))\n try: val = '%i : %s' % (value, self.DictFunc(self.Dict)[value])\n except KeyError: val = value\n elif self.Dict:\n try: val = '%i : %s' % (value, self.Dict[value])\n except KeyError: val = value\n else:\n val = value\n #return repr(val)\n rep = repr(val)\n if rep[-1] == 'L':\n rep = rep[:-1]\n return rep\n \n def getattr(self):\n return ['CallName', 'ReprName', 'Pt', 'PtFunc', 'Val', 'BitLen',\n 'BitLenFunc', 'Dict', 'DictFunc', 'Repr', 'Trans', 'TransFunc']\n \n def showattr(self):\n for a in self.getattr():\n if a == 'Dict' and self.Dict is not None: \n print('%s : %s' % ( a, self.__getattribute__(a).__class__) )\n else: \n print('%s : %s' % ( a, repr(self.__getattribute__(a))) )\n \n # cloning an element, used in set of elements\n def clone(self):\n clone = self.__class__(\n self.CallName, self.ReprName,\n self.Pt, self.PtFunc,\n self.Val, \n self.BitLen, self.BitLenFunc,\n self.Dict, self.DictFunc, self.Repr,\n self.Trans, self.TransFunc )\n return clone\n \n def map(self, string=''):\n # map each bit of the string from left to right\n # using the shtr() class to shift the string\n # string must be ascii-encoded (see shtr)\n if not self.is_transparent():\n self.map_bit( shtr(string).left_val(self.bit_len()) )\n \n def map_bit(self, value=0):\n # map an int / long value\n if self.safe:\n assert( 0 <= value <= pow(2, self.bit_len()) )\n self.Val = value\n \n def map_ret(self, string=''):\n if self.is_transparent():\n return string\n else:\n shtring = shtr(string)\n bitlen = self.bit_len()\n self.map_bit( shtring.left_val(bitlen) )\n return shtring << bitlen\n \n # shar manipulation interface\n def to_shar(self):\n ret = shar()\n ret.set_uint(self(), self.bit_len())\n return ret\n \n def map_shar(self, sh):\n if not self.is_transparent():\n self.map_bit( sh.get_uint(self.bit_len()) )\nlibmich/core/shtr.py\nclass shtr(str):\r\n '''\r\n shtr are strings that can be shifted !\r\n \r\n When a shtr is shifted (<< X or >> X), it returns the resulting string.\r\n When right shifted (>> X), null bytes are appended left-side.\r\n \r\n Methods .left_val(X) and .right_val(X) returns the integer value corresponding to \r\n the X bits left or right side of the shtr.\r\n '''\r\n \r\n def __init__(self, s):\r\n self._bitlen = len(s)*8\r\n \r\n def left_val(self, bitlen):\r\n '''\r\n returns big endian integer value from the `bitlen' left bits of the shtr\r\n '''\r\n if bitlen > self._bitlen:\r\n bitlen = self._bitlen\r\n # 0)\r\n reg64 = bitlen//64\r\n reg8 = (bitlen%64)//8\r\n reg1 = bitlen%8\r\n acc, start, stop = 0, 0, 0\r\n # 1)\r\n if reg64:\r\n stop = 8*reg64\r\n acc += reduce(lambda x,y: (x<<64)+y,\r\n unpack('>'+reg64*'Q', self[:stop]))\r\n # 2)\r\n if reg8:\r\n acc <<= 8*reg8\r\n start = stop\r\n stop = start + reg8\r\n acc += reduce(lambda x,y: (x<<8)+y,\r\n unpack('>'+reg8*'B', self[start:stop]))\r\n # 3)\r\n if reg1:\r\n acc <<= reg1\r\n acc += (ord(self[stop:stop+1]) >> (8-reg1))\r\n #\r\n return acc\r\n \r\n def right_val(self, val):\r\n '''\r\n returns big endian integer value from the `val' right bits of the shtr\r\n '''\r\n if val > self._bitlen: val = self._bitlen\r\n acc = 0\r\n # 1) get value of full bytes\r\n for i in xrange(val/8):\r\n acc += ord(self[-1-i]) << (i*8)\r\n # 2) get value of last bits\r\n if val%8 and val/8 < len(self):\r\n acc += (ord(self[-1-(val/8)]) & ((1<<(val%8))-1)) << (8*(val/8))\r\n return acc\r\n \r\n def __lshift__(self, bitlen):\r\n '''\r\n returns resulting shtr after shifting left of `bitlen' bits\r\n '''\r\n if bitlen > self._bitlen:\r\n bitlen = self._bitlen\r\n # 0) full byte shifting\r\n buf = self[bitlen//8:]\r\n # 1) bit shifting\r\n reg1 = bitlen%8\r\n if reg1:\r\n buflen = len(buf)\r\n reg64 = buflen//8\r\n reg8 = buflen%8\r\n reg1inv = 8-reg1\r\n reg1inv64 = 64-reg1\r\n fmt = '>'+reg64*'Q'+reg8*'B'\r\n values = unpack(fmt, buf)\r\n #print values\r\n if reg64:\r\n #print('reg64')\r\n chars = map(lambda X: ((X[0]<>reg1inv64),\r\n zip(values[:reg64], values[1:reg64]))\r\n if reg8:\r\n #print('reg8')\r\n chars.append( ((values[reg64-1]<>reg1inv) )\r\n chars.extend( map(lambda X: ((X[0]<>reg1inv),\r\n zip(values[reg64:], values[reg64+1:])) )\r\n chars.append( (values[-1]<>reg1inv),\r\n zip(values, values[1:]))\r\n chars.append( (values[-1]<>bsh) + ((ord(buf[i-1])&pbsh)<>bsh )\r\n strlist.reverse()\r\n #\r\n #return shtr(''.join(map(chr, strlist)))\r\n ret = shtr(''.join(map(chr, strlist)))\r\n ret._bitlen = self._bitlen + val\r\n return ret\r\nlibmich/core/element.py\nclass Int(Element):\n '''\n class defining a standard element, managed like an integer.\n It can be signed (int) or unsigned (uint),\n and support arbitrary byte-length:\n int8, int16, int24, int32, int40, int48, int56, int64, int72, ...\n uint8, uint16, uint24, uint32, ..., uint128, ...\n and why not int65536 !\n It is always byte-aligned (in term of length, at least).\n \n attributes:\n Pt: to point to another object or direct integer value;\n PtFunc: when defined, PtFunc(Pt) is used to generate the integer value;\n Val: when defined, overwrites the Pt (and PtFunc) integer value, \n used when mapping a string buffer to the element;\n Type: type of integer for encoding, 8,16,24,32,40,48,56,64 bits signed or\n unsigned integer;\n Dict: dictionnary to use for a look-up when representing \n the element into python;\n Repr: representation style, binary, hexa or human: human uses Dict \n if defined;\n Trans: to define transparent element which has empty str() and len() to 0,\n it \"nullifies\" its existence; can point to something for automation;\n TransFunc: when defined, TransFunc(Trans) is used to automate the \n transparency aspect: used e.g. for conditional element;\n '''\n # endianness is 'little' / 'l' or 'big' / 'b'\n _endian = 'big'\n # types format for struct library\n # 24 (16+8), 40 (32+8), 48 (32+16), 56 (32+16+8)\n _types = { 'int8':'b', 'int16':'h', 'int32':'i', 'int64':'q',\n #'int24':None, 'int40':None, 'int48':None, 'int56':None,\n 'uint8':'B', 'uint16':'H', 'uint32':'I', 'uint64':'Q',\n #'uint24':None, 'uint40':None, 'uint48':None, 'uint56':None,\n }\n #\n # for object representation\n _reprs = ['hex', 'bin', 'hum']\n \n def __init__(self, CallName='', ReprName=None,\n Pt=None, PtFunc=None, Val=None,\n Type='int32', Dict=None, DictFunc=None,\n Repr='hum',\n Trans=False, TransFunc=None):\n if CallName or not self.CallName:\n self.CallName = CallName\n if ReprName is None:\n self.ReprName = ''\n else:\n self.ReprName = ReprName\n self.Pt = Pt\n self.PtFunc = PtFunc\n self.Val = Val\n self.Type = Type\n self.Dict = Dict\n self.DictFunc = DictFunc\n self.Repr = Repr\n self.Trans = Trans\n self.TransFunc = TransFunc\n # automated attributes:\n self.Len = int(self.Type.lstrip('uint'))//8\n \n def __setattr__(self, attr, val):\n # ensures no bullshit is provided into element's attributes \n # (however, it is not a complete test...)\n if self.safe:\n if attr == 'CallName':\n if type(val) is not str or len(val) == 0:\n raise AttributeError('CallName must be a non-null string')\n elif attr == 'ReprName':\n if type(val) is not str:\n raise AttributeError('ReprName must be a string')\n elif attr == 'PtFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('PtFunc must be a function')\n elif attr == 'Val':\n if val is not None and not isinstance(val, (int, long)):\n raise AttributeError('Val must be an int or long')\n elif attr == 'Type':\n cur = 0\n if val[cur] == 'u':\n cur = 1\n if val[cur:cur+3] != 'int' or int(val[cur+3:]) % 8 != 0:\n raise AttributeError('Type must be intX / uintX with X '\\\n 'multiple of 8 bits (e.g. int24, uint32, int264, ...)')\n elif attr == 'DictFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('DictFunc must be a function')\n elif attr == 'Repr':\n if val not in self._reprs:\n raise AttributeError('Repr %s does not exist, use in: %s' \\\n % (val, self._reprs))\n elif attr == 'TransFunc':\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('TransFunc must be a function')\n if attr == 'Type':\n self.Len = int(val.lstrip('uint'))//8\n object.__setattr__(self, attr, val)\n \n def __call__(self):\n # when no values are defined at all, arbitrary returns None:\n if self.Val is None and self.Pt is None:\n # instead of \"return None\" \n # that triggers error when calling __str__() method\n return 0\n # else, Val overrides Pt capabilities:\n # transparency are not taken into account in __call__, \n # only for the __str__ representation\n elif self.Val is not None: \n return self.__confine( self.Val )\n elif self.PtFunc is not None: \n if self.safe: \n assert( type(self.PtFunc(self.Pt)) in (int, long) )\n return self.__confine(self.PtFunc(self.Pt))\n else:\n return self.__confine(int(self.Pt))\n \n def __confine(self, value):\n # unsigned\n if self.Type[0] == 'u':\n return max(0, min(2**(8*self.Len)-1, value))\n # signed\n else:\n return max(-2**(8*self.Len-1), min(2**(8*self.Len-1)-1, value))\n \n def __str__(self):\n # manages Element transparency\n if self.is_transparent():\n return ''\n # otherwise returns standard string values\n return self.__pack()\n \n def __len__(self):\n if self.is_transparent(): \n return 0\n return self.Len\n \n def bit_len(self):\n return 8*self.__len__()\n \n # map_len() is a-priori not needed in \"Int\" element, \n # but still kept for Element API uniformity\n def map_len(self):\n return self.__len__()\n \n # define integer value\n def __int__(self):\n return self()\n \n def __bin__(self):\n # unsigned or positive signed:\n val = self()\n if self.Type[0] == 'u' \\\n or self.Type[0] == 'i' and val >= 0 : \n binstr = bin(val)[2:]\n if self._endian[0] == 'l':\n # little endian\n bs = '0'*(8*self.__len__() - len(binstr)) + binstr\n bs = [bs[i:i+8] for i in range(0, len(bs), 8)]\n bs.reverse()\n return ''.join(bs)\n else:\n # big endian\n return '0'*(8*self.__len__() - len(binstr)) + binstr\n # negative signed\n else : \n # takes 2' complement to the signed val\n binstr = bin(val + 2**(8*self.__len__()-1))[2:]\n if self._endian[0] == 'l':\n # little endian\n bs = '1' + '0'*(8*self.__len__() - len(binstr) - 1) + binstr\n bs = [bs[i:i+8] for i in range(0, len(bs), 8)]\n bs.reverse()\n return ''.join(bs)\n else:\n # big endian\n return '1' + '0'*(8*self.__len__() - len(binstr) - 1) + binstr\n \n def __hex__(self):\n return hexlify(self.__pack())\n \n def __repr__(self):\n if self.Pt is None and self.Val is None:\n return repr(None)\n if self.Repr == 'hex':\n return '0x%s' % self.__hex__()\n elif self.Repr == 'bin':\n return '0b%s' % self.__bin__()\n elif self.Repr == 'hum':\n value = self()\n if self.DictFunc:\n if self.safe:\n assert(hasattr(self.DictFunc(self.Dict), '__getitem__'))\n try:\n val = '%i : %s' % (value, self.DictFunc(self.Dict)[value])\n except KeyError:\n val = value\n elif self.Dict:\n try:\n val = '%i : %s' % (value, self.Dict[value])\n except KeyError:\n val = value\n else:\n val = value\n rep = repr(val)\n if rep[-1] == 'L':\n return rep[:-1]\n return rep\n \n def getattr(self):\n return ['CallName', 'ReprName', 'Pt', 'PtFunc', 'Val', 'Len',\n 'Type', 'Dict', 'DictFunc', 'Repr', 'Trans', 'TransFunc']\n \n def showattr(self):\n for a in self.getattr():\n if a == \"Dict\" and self.Dict is not None:\n print('%s : %s' % ( a, self.__getattribute__(a).__class__) )\n else:\n print('%s : %s' % ( a, repr(self.__getattribute__(a))) )\n \n def clone(self):\n clone = self.__class__(\n self.CallName, self.ReprName,\n self.Pt, self.PtFunc,\n self.Val, self.Type,\n self.Dict, self.DictFunc, self.Repr, \n self.Trans, self.TransFunc )\n #clone._endian = self._endian\n return clone\n \n def map(self, string=''):\n if not self.is_transparent():\n # error log will be done by the Layer().map() method\n # but do this not to throw exception\n if len(string) < self.Len:\n if self.dbg >= WNG:\n log(WNG, '(%s) %s map(string) : string not long enough' \\\n % (self.__class__, self.CallName))\n return\n self.Val = self.__unpack(string[:self.Len])\n \n def map_ret(self, string=''):\n l = self.__len__()\n if 0 < l <= len(string):\n self.map(string)\n return string[l:]\n else:\n return string\n \n def __pack(self):\n # manage endianness (just in case...)\n if self._endian[0] == 'l':\n e = '<'\n else:\n e = '>'\n if self.Len == 0:\n return ''\n elif self.Len in (1, 2, 4, 8):\n # standard types for using Python struct\n return pack(e+self._types[self.Type], self())\n elif self.Type[0] == 'u':\n # non-standard unsigned int types\n return self.__pack_uX(e)\n else:\n # non-standard signed int types\n return self.__pack_iX(e)\n \n def __unpack(self, string):\n if self._endian[0] == 'l':\n e = '<'\n else:\n e = '>'\n if self.Len == 0:\n return\n elif self.Len in (1, 2, 4, 8):\n # standard types for using Python struct\n return unpack(e+self._types[self.Type], string[:self.Len])[0]\n elif self.Type[0] == 'u':\n # non-standard unsigned int types\n return self.__unpack_uX(string[:self.Len], e)\n else:\n # non-standard signed int types\n return self.__unpack_iX(string[:self.Len], e)\n \n def __pack_uX(self, e='>'):\n if e == '<':\n # little endian, support indefinite uint (e.g. uint3072)\n if self.Len <= 8:\n return pack('Q', self())[-self.Len:]\n else:\n u64 = decompose(0x10000000000000000, self())\n u64_len = 8*len(u64)\n u64_pad = 0\n if u64_len < self.Len:\n rest_len = self.Len - u64_len\n u64_pad = rest_len // 8\n if rest_len % 8:\n u64_pad += 1\n u64.extend( [0]*u64_pad )\n u64.reverse()\n return pack('>'+len(u64)*'Q', *u64)[-self.Len:]\n \n def __pack_iX(self, e='>'):\n val = self()\n # positive values are encoded just like uint\n if val >= 0:\n return self.__pack_uX(e)\n #\n # negative values, 2's complement encoding\n if e == '<':\n # little endian\n if self.Len <= 8:\n return pack('Q', 2**(self.Len*8) - abs(val))[-self.Len:]\n else:\n i8 = decompose(0x100, 2**(self.Len*8) - abs(val))\n if len(i8) < self.Len:\n i8.extend( [0]*(self.Len-len(i8)) )\n i8.reverse()\n return pack('>'+self.Len*'B', *i8)\n \n def __unpack_uX(self, string, e='>'):\n if e == '<':\n # little endian, support indefinite uint (e.g. uint3072)\n if self.Len <= 8:\n return unpack('Q', '\\0'*(8 - self.Len) + string)[0]\n else:\n #'''\n u64_len, u64_pad = self.Len // 8, self.Len % 8\n if u64_pad:\n u64_len += 1\n string = '\\0'*u64_pad + string\n u64 = unpack('>'+u64_len*'Q', string)\n return reduce(lambda x,y:(x<<64)+y, u64)\n \n def __unpack_iX(self, string, e='>'):\n if e == '<':\n # little endian\n if ord(string[-1]) & 0x80 == 0:\n # check if it is a positive value\n return self.__unpack_uX(string, e)\n elif self.Len <= 8:\n return unpack('Q', '\\0'*(8 - self.Len) + string)[0] \\\n - 2**(self.Len*8)\n else:\n i8 = unpack('>'+self.Len*'B', string)\n return reduce(lambda x,y:(x<<8)+y, i8) - 2**(self.Len*8)\n \n # shar manipulation interface\n def to_shar(self):\n ret = shar()\n ret.set_buf(self.__str__())\n return ret\n \n def map_shar(self, sh):\n if len(sh)*8 < self.Len:\n if self.dbg >= WNG:\n log(WNG, '(%s) %s map(string) : shar buffer not long enough' \\\n % (self.__class__, self.CallName))\n return\n # standard handling\n if not self.is_transparent():\n self.map(sh.get_buf(len(self)*8))\nlibmich/core/element.py\ndef show(self, with_trans=False):\n tr, re = '', ''\n if self.is_transparent():\n # TODO: eval the best convinience here\n if not with_trans:\n return ''\n tr = ' - transparent'\n else:\n tr = ''\n if self.ReprName != '':\n re = ''.join((self.ReprName, ' '))\n return '<%s[%s%s] : %s>' % ( re, self.CallName, tr, repr(self) )\nlibmich/core/IANA_dict.py\nclass IANA_dict(dict):\r\n '''\r\n Class to manage dictionnaries with integer as keys \r\n and 2-tuples of string as items,\r\n such as IANA protocols parameters reference: http://www.iana.org/protocols/\r\n \r\n call it like this:\r\n IANA_dict( { integer : (\"parameter name\", \"parameter abbreviation\"), \r\n integer: \"parameter name\", ... } )\r\n '''\r\n \r\n def __init__(self, IANA_dict={}):\r\n '''\r\n initialize like a dict\r\n [+] if 'key' is not integer, raises error\r\n [+] if value 'value' is not string or 2-tuple of string, raises error\r\n [+] if value is string, transforms it in 2-tuple (\"value\", \"\")\r\n i.e. value must be (\"value name\", value abbreviation\")\r\n '''\r\n # 1st: rearrange string item to 2-tuple of string\r\n items = dict.items(IANA_dict)\r\n for i in items:\r\n if type(i[1]) is str:\r\n dict.__setitem__( IANA_dict, i[0], (i[1], \"\") )\r\n \r\n # 2nd: verification: key is int / long, and item is 2-tuple of string\r\n items = dict.items(IANA_dict)\r\n for i in items:\r\n if type(i[0]) not in (int, long):\r\n raise KeyError('%s : key must be integer' % i[0])\r\n if type(i[1]) is not tuple or len(i[1]) != 2:\r\n raise ValueError('%s : value must be string or 2-tuple of ' \\\r\n 'string' % i[1])\r\n \r\n dict.update(self, IANA_dict)\r\n \r\n def __getitem__(self, key):\r\n '''\r\n Same as dict.__getitem__(key)\r\n [+] If 'key' is integer and does not exist,\r\n returns the item corresponding to the last existing key,\r\n except if key is over the last key.\r\n [+] If 'key' is string and exists as value (name or abbreviation),\r\n returns first key found corresponding to the value.\r\n '''\r\n values = []\r\n for e in self.values():\r\n for v in e:\r\n if type(v) is str and len(v) > 0:\r\n values.append(v)\r\n \r\n if self.__contains__(key):\r\n return dict.__getitem__(self, key)[0]\r\n \r\n elif type(key) in (int, long) \\\r\n and self.s_keys()[0] < key < self.s_keys().pop():\r\n i = 0\r\n while self.__contains__(key-i) is False: i += 1\r\n return dict.__getitem__(self, key-i)[0]\r\n \r\n elif type(key) is str and key in values:\r\n i = 0\r\n while key not in self.items()[i][1]: i += 1\r\n return self.items()[i][0]\r\n \r\n else: \r\n try: return dict.__getitem__(self, key)\r\n except KeyError: return key\r\n \r\n def __setitem__(self, key, item):\r\n '''\r\n Same as dict.__setitem__(key)\r\n [+] If 'key' is not integer, raises error\r\n [+] If 'value' is not string or 2-tuple of strings, raises error\r\n '''\r\n if type(key) not in [int, long]:\r\n raise KeyError('%s : key must be integer' % key)\r\n if type(item) is str:\r\n item = (item, \"\")\r\n if type(item) is not tuple or len(item) != 2:\r\n raise ValueError('%s : value must be string or 2-tuple of '\\\r\n 'string' % item)\r\n dict.__setitem__(self, key, item)\r\n \r\n def s_keys(self):\r\n '''\r\n returns a sorted list of keys\r\n ''' \r\n s_keys = dict.keys(self)\r\n s_keys.sort()\r\n return s_keys\r\n \r\n def items(self):\r\n '''\r\n returns the list of (key, value), following the order of sorted keys.\r\n '''\r\n items = []\r\n s_keys = self.s_keys()\r\n for k in s_keys:\r\n items.append( (k, dict.__getitem__(self, k)) )\r\n return items\r\nlibmich/core/element.py\nclass Layer(object):\n '''\n class built from stack of \"Str\", \"Int\", \"Bit\" and \"Layer\" objects\n got from the initial constructorList.\n Layer object is recursive: it can contain other Layer() instances\n Layer does not require to be byte-aligned. This happens depending of the\n presence of Bit() instances.\n \n when instantiated:\n clones the list of \"Str\", \"Int\", \"Bit\" elements in the constructorList\n to build a dynamic elementList, that can be changed afterwards (adding /\n removing objects);\n A common hierarchy level for the whole Layer is defined, it is useful \n when used into \"Block\" to create hierarchical relationships: \n self.hierarchy (int), self.inBlock (bool)\n when .inBlock is True, provides: .get_payload(), .get_header(), \n .has_next(), .get_next(), .get_previous(), and .Block\n It provides several methods for calling elements in the layer:\n by CallName / ReprName passed in attribute\n by index in the elementList\n can be iterated too\n and many other manipulations are defined\n It has also some common methods with \"Str\", \"Int\" and \"Bit\" to emulate \n a common handling:\n __str__, __len__, __int__, bit_len, getattr, showattr, show, map\n '''\n #\n # debugging threshold for Layer:\n dbg = ERR\n # add some sanity checks\n #safe = True\n safe = False\n # define the type of str() and map() method\n _byte_aligned = True\n # reserved attributes:\n Reservd = ['CallName', 'ReprName', 'elementList', 'Len', 'BitLen',\n 'hierarchy', 'inBlock', 'Trans', 'ConstructorList',\n 'dbg', 'Reservd']\n #\n # represent transparent elements in __repr__()\n _repr_trans = True\n \n # structure description:\n constructorList = []\n \n def __init__(self, CallName='', ReprName='', Trans=False, **kwargs):\n if type(CallName) is not str:\n raise AttributeError('CallName must be a string')\n elif len(CallName) == 0:\n self.CallName = self.__class__.__name__\n else:\n self.CallName = CallName\n if type(ReprName) is str and len(ReprName) > 0: \n self.ReprName = ReprName\n else: \n self.ReprName = ''\n self.elementList = []\n self.set_hierarchy(0)\n self.inBlock = False\n self.Trans = Trans\n \n CallNames = []\n for e in self.constructorList:\n # This is for little players\n #if isinstance(e, Element):\n # OK, now let's put the balls on the table and\n # make Layer recursive (so will have Layer() into Layer())\n if isinstance(e, (Element, Layer)):\n if e.CallName in self.Reservd:\n if self.safe or self.dbg >= ERR:\n log(ERR, '(Layer - %s) using a reserved '\n 'attribute as CallName %s: aborting...' \\\n % (self.__class__, e.CallName))\n return\n if e.CallName in CallNames:\n if self.dbg >= WNG:\n log(WNG, '(Layer - %s) different elements have ' \\\n 'the same CallName %s' % (self.__class__, e.CallName))\n if isinstance(e, Element):\n self.append(e.clone())\n # do not clone Layer() as it breaks dynamic element inside\n # i.e. element with PtFunc, LenFunc, DictFunc, TransFunc defined\n # TODO: patch Layer().clone() method to solve this...\n # lets try with deepcopy()\n elif isinstance(e, Layer):\n self.append(e.clone())\n CallNames.append(e.CallName)\n \n # check for bit alignment until we lost information on the Layer length\n # also check if fixed length can be deduced\n self.BitLen = 0\n for e in self.elementList:\n if self.dbg >= DBG:\n log(DBG, '(Layer - %s) length verification for %s' \\\n % (self.__class__, e.CallName))\n if isinstance(e, Bit):\n self.BitLen += e.bit_len()\n elif hasattr(e, 'Len') and type(e.Len) is int:\n self.BitLen += (e.Len)*8\n else:\n self.BitLen, self.Len = 'var', 'var'\n break\n if type(self.BitLen) is int :\n if self.BitLen % 8:\n if self.dbg >= WNG and self._byte_aligned:\n log(WNG, '(Layer - %s) Elements seem not to be '\\\n 'byte-aligned: hope you expect it!' \\\n % self.__class__)\n # record length in bit (precise one) and in bytes (unprecised)\n self.Len = 1 + self.BitLen//8\n else:\n self.Len = self.BitLen//8\n #\n # check additional args that would correspond to contained Element\n args = kwargs.keys()\n if self.dbg >= DBG:\n log(DBG, '(Layer - %s) init kwargs: %s' % (self.__class__, args))\n for e in self:\n if hasattr(e, 'CallName') and e.CallName in args:\n if hasattr(e, 'Pt'):\n e.Pt = kwargs[e.CallName]\n else:\n kwe = kwargs[e.CallName]\n if isinstance(kwe, (tuple, list)):\n e.__init__(*kwe)\n elif isinstance(kwe, dict):\n e.__init__(**kwe)\n \n # define some basic list facilities for managing elements into the Layer, \n # through the \"elementList\" attribute:\n def __iter__(self):\n if 'elementList' in self.__dict__.keys():\n return self.__dict__['elementList'].__iter__()\n else: return [].__iter__()\n \n def __getitem__(self, num):\n return self.elementList[num]\n \n def __getslice__(self, i, j):\n l = Layer('_slice_')\n if not i or i < 0:\n i=0\n #maxj = len(self.elementList)-1\n maxj = len(self.elementList)\n if not j or j > maxj:\n j = maxj\n #\n for k in xrange(i, j):\n l.append( self[k] )\n return l\n \n def __setitem__(self, num, value):\n # special handling here: \n # use to override the element value \n # with its \"Val\" attribute (like when mapping a string)\n self.elementList[num].Val = value\n \n def append(self, element):\n #if isinstance(element, Element):\n # make Layer recursive:\n if isinstance(element, (Element, Layer)):\n if self.dbg >= WNG and element.CallName in self.getattr():\n log(WNG, '(Layer - %s) different elements have the same '\\\n 'CallName %s' % (self.__class__, element.CallName))\n self.elementList.append(element)\n \n def __lshift__(self, element):\n self.append(element)\n if isinstance(element, Layer):\n element.inc_hierarchy(self.hierarchy)\n \n def insert(self, index, element):\n CallNames = self.getattr()\n #if isinstance(element, Element):\n # make Layer recursive:\n if isinstance(element, (Element, Layer)):\n if self.dbg >= WNG and element.CallName in CallNames:\n log(WNG, '(Layer - %s) different elements have the same '\\\n 'CallName %s' % (self.__class__, element.CallName))\n self.elementList.insert(index, element)\n \n def __rshift__(self, element):\n self.insert(0, element)\n if isinstance(element, Layer):\n element.inc_hierarchy(self.hierarchy)\n \n def extend(self, newElementList):\n for e in newElementList:\n self.append(e)\n \n def remove(self, element):\n for e in self:\n if e == element:\n self.elementList.remove(element)\n \n def replace(self, current_element, new_element):\n # check index of the element ro replace\n index = 0\n for elt in self.elementList:\n if elt == current_element:\n self.remove(current_element)\n self.insert(index, new_element)\n return\n else:\n index += 1\n \n # define some attribute facilities for managing elements \n # by their CallName into the Layer\n # warning: dangerous when parsing data into Layer, \n # with elements which could have same CallName\n # \n # list facilities can be preferred in this case\n def __getattr__(self, name):\n names = [x.CallName for x in self.elementList]\n if name in names:\n return self.elementList[ names.index(name) ]\n names = [x.ReprName for x in self.elementList]\n if name in names:\n return self.elementList[ names.index(name) ]\n #\n return object.__getattribute__(self, name)\n #return self.__getattribute__(name)\n #return getattr(self, name)\n \n def __setattr__(self, name, value):\n # special handling here: use to override the element value \n # with its \"Val\" attribute (like when mapping a string)\n for e in self:\n if name == e.CallName or name == e.ReprName: \n e.Val = value\n return\n return object.__setattr__(self, name, value)\n raise AttributeError( '\"Layer\" has no \"%s\" attribute: %s' \\\n % (name, self.getattr()) )\n \n def __hasattr__(self, name):\n for e in self:\n if name == e.CallName or name == e.ReprName: \n return True\n #return object.__hasattr__(self, name): \n # not needed (does not work in the code... but works in python...)\n raise AttributeError( '\"Layer\" has no \"%s\" attribute: %s' \\\n % (name, self.getattr()) )\n \n # method for managing the Layer hierarchy (easy):\n def set_hierarchy(self, hier=0):\n self.hierarchy = hier\n for e in self:\n if isinstance(e, Layer):\n e.set_hierarchy(hier)\n \n def inc_hierarchy(self, ref=None):\n if ref is None:\n self.set_hierarchy(self.hierarchy+1)\n else: \n self.set_hierarchy(self.hierarchy+ref+1)\n #for l in self:\n # if isinstance(l, Layer):\n # l.hierarchy = self.hierarchy\n \n def dec_hierarchy(self, ref=None):\n if ref is None: \n self.set_hierarchy(self.hierarchy-1)\n else: \n self.set_hierarchy(self.hierarchy+ref-1)\n #for l in self:\n # if isinstance(l, Layer):\n # l.hierarchy = self.hierarchy\n \n # define same methods as \"Element\" type for being use the same way\n def __str__(self):\n if self.dbg >= DBG:\n log(DBG, '(Layer.__str__) entering str() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return ''\n # dispatch to the right method depending of byte alignment\n if self._byte_aligned is True:\n return self.__str_aligned()\n else:\n return self.__str_unaligned()\n \n def __str_unaligned(self):\n # then init resulting string \n # and bit offset needed to shift unaligned strings\n s = []\n off = 0\n # loop on each element into the Layer\n # also on Layer into Layer...\n for e in self:\n shtr_e, bitlen_e = e.shtr(), e.bit_len()\n rest_e = bitlen_e % 8\n if self.dbg >= DBG:\n log(DBG, '(Layer.__str__) %s: %s, %i, offset: %i' \\\n % (e.CallName, hexlify(shtr_e), bitlen_e, off))\n # if s is not byte-aligned and e is not transparent\n # update the last component of s\n if off and shtr_e:\n # 1st update last bits of s with MSB of e, \n # before stacking with the rest of e\n # (8 - off) is the room left in the LSB of s\n s[-1] = ''.join((s[-1][:-1],\n chr(ord(s[-1][-1]) + shtr_e.left_val(8-off)),\n (shtr_e << (8-off))\n ))\n # take care in case the shifting of e voids its last byte\n if rest_e and rest_e-(8-off) <= 0:\n s[-1] = s[-1][:-1]\n # update offset\n if rest_e:\n off += bitlen_e\n off %= 8\n # in case s is already aligned, append a new component to s\n elif shtr_e:\n s.append(shtr_e)\n # update offset\n if rest_e:\n off += rest_e\n if self.dbg >= DBG:\n log(DBG, '(Layer.__str__) %s' % hexlify(s))\n # well done!\n return ''.join(s)\n \n def __str_aligned(self):\n s = []\n BitStream = ''\n # loop on each element in the Layer\n # also on Layer into Layer...\n for e in self:\n # need special processing for stacking \"Bit\" element: \n # using \"BitStream\" variable\n # works only with contiguous \"Bit\" elements \n # to avoid byte-misalignment of other element in the Layer \n # (and programming complexity with shifting everywhere...)\n if isinstance(e, Bit):\n # manage element transparency with (Trans, TranFunc)\n # and build a bitstream ('100110011...1101011') from Bit values\n if not e.is_transparent():\n BitStream += str(e.__bin__())\n # when arriving on a byte boundary from bitstream, \n # create bytes and put it into the s variable\n if len(BitStream) >= 8:\n while 1:\n s.append( pack('!B', int(BitStream[:8], 2)) )\n BitStream = BitStream[8:]\n if len(BitStream) < 8:\n break\n if self.dbg >= DBG:\n log(DBG, '(Element) %s: %s, %s\\nBitstream: %s' \\\n % (e.CallName, e(), e.__bin__(), BitStream))\n # when going to standard Str or Int element, \n # or directly end of __str__ function \n # verify the full BitStream has been consumed\n # and continue to build the resulting string easily...\n else:\n # possible byte mis-alignment for Str / Int is not managed...\n self.__is_aligned(BitStream)\n BitStream = ''\n if isinstance(e, Layer) and not e.Trans \\\n or isinstance(e, Element):\n s.append( str(e) )\n self.__is_aligned(BitStream)\n return ''.join(s)\n \n def __is_aligned(self, BitStream):\n if BitStream and self.dbg >= ERR:\n log(ERR, '(Layer - %s) some of the Bit elements have not been ' \\\n 'stacked in the \"str(Layer)\"\\nremaining bitstream: %s' \\\n % (self.__class__, BitStream))\n if self.safe:\n assert(not BitStream)\n \n def __call__(self):\n return self.__str__()\n \n def __len__(self):\n return len(self.__str__())\n \n def shtr(self):\n return shtr(self.__str__())\n \n def bit_len(self):\n # just go over all internal elements to track their own bit length\n # updated attributes initialized when Layer was constructed\n self.BitLen = 0\n for e in self:\n if hasattr(e, 'bit_len'):\n self.BitLen += e.bit_len()\n elif hasattr(e, '__len__'):\n self.BitLen += len(e)*8\n self.Len = 1 + (self.BitLen // 8) if self.BitLen % 8 \\\n else (self.BitLen // 8)\n return self.BitLen\n \n def __hex__(self):\n bit_len = self.bit_len()\n hex_len = bit_len/4\n if bit_len%4:\n hex_len += 1\n #\n return self.__str__().encode('hex')[:hex_len]\n \n def __bin__(self):\n bits = []\n for e in self:\n bits.append( e.__bin__() )\n return ''.join(bits)\n \n def __int__(self):\n # big endian integer representation of the string buffer\n if self._byte_aligned:\n return shtr(self).left_val(len(self)*8)\n else:\n return shtr(self).left_val(self.bit_len())\n \n def __repr__(self):\n t = ''\n if self.Trans:\n t = ' - transparent '\n s = '<%s[%s]%s: ' % ( self.ReprName, self.CallName, t )\n for e in self:\n if self._repr_trans or not e.is_transparent():\n s += '%s(%s):%s, ' % ( e.CallName, e.ReprName, repr(e) )\n s = s[:-2] + '>'\n return s\n \n def map_len(self):\n return len(self)\n \n def getattr(self):\n return [e.CallName for e in self.elementList]\n \n def showattr(self):\n for a in self.getattr():\n print('%s : %s' % ( a, repr(self.__getattr__(a))) )\n \n def clone2(self):\n # TODO: deepcopy is not adapted here, can create errors...\n return deepcopy(self)\n \n def clone(self):\n #\n # build a new constructorList made of clones\n constructorList_new = []\n for e in self:\n constructorList_new.append(e.clone())\n #\n # substitute the current constructorList with the one made of clones\n constructorList_ori = self.__class__.constructorList\n self.__class__.constructorList = constructorList_new\n # instantiate the clone\n c = self.__class__()\n c.CallName = self.CallName\n if hasattr(self, 'ReprName'):\n c.ReprName = self.ReprName\n if hasattr(self, 'Trans'):\n c.Trans = self.Trans\n # restore the original constructorList\n self.__class__.constructorList = constructorList_ori\n #\n return c\n \n def is_transparent(self):\n if self.Trans:\n return True\n else:\n return False\n \n def show(self, with_trans=False):\n re, tr = '', ''\n if self.ReprName != '':\n re = '%s ' % self.ReprName\n if self.is_transparent():\n # TODO: eval the best convinience here\n if not with_trans:\n return ''\n tr = ' - transparent'\n # Layer content\n str_lst = [e.show().replace('\\n', '\\n ') for e in self]\n # insert spaces for nested layers and filter out empty content\n str_lst = [' %s\\n' % s for s in str_lst if s]\n # insert layer's title\n str_lst.insert(0, '### %s[%s]%s ###\\n' % (re, self.CallName, tr))\n # return full inline string without last CR\n return ''.join(str_lst)[:-1]\n \n def map(self, string=''):\n if self.dbg >= DBG:\n log(DBG, '(Layer.map) entering map() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return\n # dispatch to the right method depending of byte alignment\n if self._byte_aligned is True:\n self.__map_aligned(string)\n else:\n self.__map_unaligned(string)\n \n def __map_unaligned(self, string=''):\n s = shtr(string)\n # otherwise go to map() over all elements\n for e in self:\n if self.dbg >= DBG:\n log(DBG, '(Layer.__map_unaligned) %s, bit length: %i' \\\n % (e.CallName, e.bit_len()))\n log(DBG, '(Layer.__map_unaligned) string: %s' % hexlify(s))\n # this is beautiful\n s = e.map_ret(s)\n \n def __map_aligned(self, string=''):\n # Bit() elements are processed intermediary: \n # 1st placed into BitStack\n # and when BitStack is byte-aligned (check against BitStack_len)\n # string buffer is then mapped to it\n self.__BitStack = []\n self.__BitStack_len = 0\n # Furthermore, it manages only contiguous Bit elements \n # for commodity... otherwise, all other elements should be shifted\n #\n for e in self:\n # special processing for Bit() element:\n if isinstance(e, Bit):\n self.__add_to_bitstack(e)\n # if BitStack is byte aligned, map string to it:\n if self.__BitStack_len % 8 == 0:\n string = self.__map_to_bitstack(string)\n # for other elements (Str(), Int(), Layer()), standard processing: \n else:\n if self.__BitStack_len > 0 and self.dbg >= ERR:\n log(WNG, '(Layer - %s) some of the Bit elements have not ' \\\n 'been mapped in the \"Layer\": not byte-aligned' \\\n % self.__class__)\n if isinstance(e, (Layer, Element)) and not e.is_transparent():\n if len(string) < e.map_len() and self.dbg >= WNG:\n log(WNG, '(Layer - %s) String buffer not long ' \\\n 'enough for %s' % (self.__class__, e.CallName))\n #if self.safe:\n # return\n e.map(string)\n string = string[e.map_len():]\n # delete .map() *internal* attributes\n del self.__BitStack\n del self.__BitStack_len\n \n def __add_to_bitstack(self, bit_elt):\n # check for Bit() element transparency\n if not bit_elt.is_transparent():\n self.__BitStack += [bit_elt]\n self.__BitStack_len += bit_elt.bit_len()\n \n def __map_to_bitstack(self, string):\n # 1st check if string is long enough for the prepared BitStack\n if len(string) < self.__BitStack_len//8 and self.dbg >= ERR:\n log(ERR, '(Layer - %s) String buffer not long enough for %s' \\\n % (self.__class__, self.__BitStack[-1].CallName))\n #if self.safe:\n # return\n # string buffer parsing is done through intermediary\n # string buffer \"s_stack\"\n s_stack = string[:self.__BitStack_len//8]\n # create a bitstream \"s_bin\" for getting the full BitStack\n s_bin = ''\n for char in s_stack:\n # convert to bitstream thanks to python native bit repr\n s_bin_tmp = bin(ord(char))[2:]\n # prepend 0 to align on byte (python does not do it)\n # and append to the bitstream \"s_bin\" (string of 0 and 1)\n s_bin = ''.join((s_bin, (8-len(s_bin_tmp))*'0', s_bin_tmp))\n # map the bitstream \"s_bin\" into each BitStack element\n for bit_elt in self.__BitStack:\n bitlen = bit_elt.bit_len()\n if bitlen:\n # convert the bitstream \"s_bin\" into integer \n # according to the length in bit of bit_elt\n bit_elt.map_bit( int(s_bin[:bit_elt.bit_len()], 2) )\n # truncate the \"s_bin\" bitstream\n s_bin = s_bin[bit_elt.bit_len():]\n # consume the global string buffer that has been mapped \n # (from s_stack internal variable)\n # and reinitialize self.__BitStack* attributes\n string = string[self.__BitStack_len//8:]\n self.__BitStack = []\n self.__BitStack_len = 0\n # finally return string to parent method .map()\n return string\n \n # map_ret() maps a buffer to a Layer, the unaligned way,\n # and returns the rest of the buffer that was not mapped\n def map_ret(self, string=''):\n if self.dbg >= DBG:\n log(DBG, '(Layer.map_ret) entering map_ret() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return string\n if self._byte_aligned is True:\n self.__map_aligned(string)\n return string[len(self):]\n else:\n # actually, map_ret() is only interesting for unaligned layers\n s = shtr(string)\n for e in self:\n if self.dbg >= DBG:\n log(DBG, '(Layer.map_ret) %s, bit length: %i' \\\n % (e.CallName, e.bit_len()))\n log(DBG, '(Layer.map_ret) string: %s' % hexlify(s))\n # this is beautiful\n s = e.map_ret(s)\n return s\n \n # define methods when Layer is in a Block:\n # next, previous, header: return Layer object reference\n # payload: returns Block object reference\n def get_index(self):\n if self.inBlock is not True: \n return 0\n i = 0\n for l in self.Block:\n if l == self: return i\n else: i += 1\n # could happen if Layer is placed in several Block()\n # and the last Block used is deleted\n return False\n \n def has_next(self):\n if self.inBlock is not True: \n return False\n return self.Block.has_index(self.get_index()+1)\n \n def get_next(self):\n if self.has_next():\n return self.Block[self.get_index()+1]\n return RawLayer()\n \n def has_previous(self):\n if self.inBlock is not True: \n return False\n index = self.get_index()\n if index <= 0:\n return False\n return self.Block.has_index(index-1)\n \n def get_previous(self):\n if self.has_previous():\n return self.Block[self.get_index()-1]\n return RawLayer()\n \n def get_header(self):\n if self.has_previous():\n index = self.get_index()\n i = index - 1\n while i >= 0:\n if self.Block[i].hierarchy == self.hierarchy-1:\n return self.Block[i]\n else:\n i -= 1\n return RawLayer()\n \n def get_payload(self):\n # return a Block, not a Layer like other methods \n # for management into a Block\n pay = Block('pay')\n if self.has_next():\n index = self.get_index()\n for l in self.Block[ index+1 : ]:\n if l.hierarchy > self.hierarchy:\n #pay.append( l.clone() )\n # not needed to append a clone\n # better keep reference to original layer\n pay.append( l )\n else:\n break\n if pay.num() == 0:\n pay.append( RawLayer() )\n return pay\n pay.append( RawLayer() )\n return pay\n \n def num(self):\n return 1\n \n # this is to retrieve full Layer's dynamicity from a mapped layer\n def reautomatize(self):\n for e in self:\n if hasattr(e, 'reautomatize'):\n e.reautomatize()\n \n def parse(self, s=''):\n self.map(s)\n \n # shar manipulation interface\n def to_shar(self):\n if hasattr(self, 'Trans') and self.Trans:\n return shar()\n bits = []\n for e in self:\n bits.append( e.to_shar().get_bits() )\n s = shar()\n s.set_bits( bits )\n return s\n \n def map_shar(self, sh):\n if self.dbg >= DBG:\n log(DBG, '(Layer.map) entering map() for %s' % self.CallName)\n # First take care of transparent Layer (e.g. in L3Mobile)\n if hasattr(self, 'Trans') and self.Trans:\n return\n if not isinstance(sh, shar):\n sh = shar(sh)\n for e in self:\n e.map_shar(sh)\nlibmich/formats/L3Mobile_IE.py\nclass StrBCD(Str):\nclass BCDNumber(Layer):\nclass PLMN(Layer):\nclass PLMNList(Layer):\nclass LAI(Layer):\nclass RAI(Layer):\nclass ID(Layer):\nclass MSCm1(Layer):\nclass MSCm2(Layer):\nclass A5bits(CSN1):\nclass RSupport(CSN1):\nclass HSCSDMultiSlotCapability(CSN1):\nclass MSMeasurementCapability(CSN1):\nclass MSPositioningMethodCapability(CSN1):\nclass ECSDMultiSlotCapability(CSN1):\nclass PSK8(CSN1):\nclass SingleBandSupport(CSN1):\nclass GERANIuModeCapabilities(CSN1):\nclass MSCm3(CSN1):\nclass NetName(Layer):\nclass AuxState(Layer):\nclass BearerCap(Layer):\nclass CCCap(Layer):\nclass QoS(Layer):\nclass PDPAddr(Layer):\nclass ProtID(Layer):\nclass ProtConfig(Layer):\nclass PacketFlowID(Layer):\nclass DRX(Layer):\nclass VoicePref(Layer):\nclass CodecBitmap(Layer):\nclass CodecSysID(Layer):\nclass SuppCodecs(Layer):\nclass ExtGEABits(CSN1):\nclass MSNetCap(CSN1):\nclass MSRAA5bits(CSN1):\nclass MultislotCap(CSN1):\nclass GERANIuModeCap(CSN1):\nclass EnhancedFlexibleTimeslotAssign(CSN1):\nclass MSRAContent(CSN1):\nclass MSRAAccessCap(CSN1):\nclass MSRAAddTech(CSN1):\nclass MSRAAdd(CSN1):\nclass MSRACap(CSN1):\nclass NASSecToEUTRA(Layer):\nclass GUTI(Layer):\nclass EPSFeatSup(Layer):\nclass TAI(Layer):\nclass PartialTAIList(Layer):\nclass PartialTAIList0(PartialTAIList):\nclass PartialTAIList1(PartialTAIList):\nclass PartialTAIList2(PartialTAIList):\nclass TAIList(Layer):\nclass UENetCap(Layer):\nclass UESecCap(Layer):\nclass APN_AMBR(Layer):\nclass SSversion(Layer):\nclass AccessTechnology(Layer):\n def decode(self):\n def encode(self, num='12345'):\n def __repr__(self):\n def __init__(self, **kwargs):\n def __init__(self, MCCMNC='00101'):\n def get_mcc(self):\n def get_mnc(self):\n def get_mccmnc(self):\n def set_mcc(self, MCC='001'):\n def set_mnc(self, MNC='01'):\n def set_mccmnc(self, MCCMNC='000101'):\n def __repr__(self):\n def interpret(self):\n def __init__(self, *args, **kwargs):\n def add_plmn(self, *args):\n def add_PLMN(self, plmn=PLMN()):\n def map(self, s=''):\n def interpret(self):\n def __init__(self, MCCMNC='00101', LAC=0x0000):\n def __repr__(self):\n def __init__(self, MCCMNC='00101', LAC=0x0000, RAC=0x00):\n def __repr__(self):\n def __init__(self, val='0', type='No Identity'):\n def map(self, s=''):\n def __handle_digits(self, digits=''):\n def __repr__(self):\n def get_imsi(self):\n def get_imei(self):\n def get_bcd(self):\n def anon(self):\n def __init__(self, **kwargs):\n def __init__(self, **kwargs):\n def map(self, s=''):\n def __init__(self, **kwargs):\n def __init__(self, **kwargs):\n def map(self, s=''):\n def map(self, s=''):\n def map(self, buf=''):\n def __init__(self, **kwargs):\n def map(self, buf=''):\n def map(self, buf=''):\n def map(self, s=''):\n def __init__(self, *args, **kwargs):\n def __init__(self, *args, **kwargs):\n def map(self, s='', byte_offset=0):\n def map(self, s='', byte_offset=0):\n def map(self, s=''):\n def __init__(self, MCCMNC='00101', **kwargs):\n def __init__(self, MCCMNC='00101', TAC=0x0000):\n def __init__(self, *args, **kwargs):\n def _set_plmn(self, plmn):\n def add_tac(self, *args):\n def add_tai(self, *args):\n def map(self, s):\n def __init__(self, *args, **kwargs):\n def __init__(self, *args, **kwargs):\n def __init__(self, *args, **kwargs):\n def __init__(self, *args):\n def map(self, s=''):\n def map(self, s='\\0\\0'):\n def map(self, s=2*'\\0'):\n def __init__(self, **kwargs):\n def _gen_dict(self, d={}):\n def _gen_ext_dict(self, d={}):\n def _gen_ext2_dict(self, d={}):\n def get_AT(self):\n def __repr__(self):\n MCC, MNC = int(self.get_mcc()), int(self.get_mnc())\n AT = []\nlibmich/core/element.py\ndef debug(thres, level, string):\n if level and level<=thres:\n print('[%s] %s' %(debug_level[level], string))\nlibmich/core/element.py\nclass Str(Element):\n '''\n class defining a standard Element, \n managed like a stream of byte(s), or string.\n It is always byte-aligned (in term of length, at least)\n \n attributes:\n Pt: to point to another stream object (can simply be a string);\n PtFunc: when defined, PtFunc(Pt) is used \n to generate the str() / len() representation;\n Val: when defined, overwrites the Pt (and PtFunc) string value, \n used when mapping a string buffer to the element;\n Len: can be set to a fixed int value, or to another object\n when called by LenFunc\n LenFunc: to be used when mapping string buffer with variable length\n (e.g. in TLV object), LenFunc(Len) is used;\n Repr: python representation; binary, hexa, human or ipv4;\n Trans: to define transparent element which has empty str() and len() to 0,\n it \"nullifies\" its existence; can point to something for automation;\n TransFunc: when defined, TransFunc(Trans) is used to automate the \n transparency aspect: used e.g. for conditional element;\n '''\n \n # this is used when printing the object representation\n _repr_limit = 1024\n _reprs = ['hex', 'bin', 'hum', 'ipv4']\n \n # padding is used when .Pt and .Val are None, \n # but Str instance has still a defined .Len attribute\n _padding_byte = '\\0'\n \n def __init__(self, CallName='', ReprName=None, \n Pt=None, PtFunc=None, Val=None, \n Len=None, LenFunc=None,\n Repr=\"hum\",\n Trans=False, TransFunc=None):\n if CallName or not self.CallName:\n self.CallName = CallName\n if ReprName is None :\n self.ReprName = ''\n else :\n self.ReprName = ReprName\n self.Pt = Pt\n self.PtFunc = PtFunc\n self.Val = Val\n self.Len = Len\n self.LenFunc = LenFunc\n self.Type = 'stream'\n self.Repr = Repr\n self.Trans = Trans\n self.TransFunc = TransFunc\n \n def __setattr__(self, attr, val):\n # ensures no bullshit is provided into element's attributes \n # (however, it is not a exhaustive test...)\n # managed with the class \"safe\" trigger\n if self.safe :\n if attr == 'CallName' :\n if type(val) is not str or len(val) == 0 :\n raise AttributeError('CallName must be a non-null string')\n elif attr == 'ReprName' :\n if type(val) is not str:\n raise AttributeError('ReprName must be a string')\n elif attr == 'PtFunc' :\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('PtFunc must be a function')\n elif attr == 'Val' :\n if val is not None and not isinstance(val, \\\n (str, bytes, Element, Layer, Block, tuple, list)) :\n raise AttributeError('Val must be a string or something ' \\\n 'that makes a string at the end...')\n elif attr == 'Len' :\n if val is not None and not isinstance(val, \\\n (int, tuple, Element, type_funcs)) :\n raise AttributeError('Len must be an int or element')\n elif attr == 'LenFunc' :\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('LenFunc must be a function')\n elif attr == 'Repr' :\n if val not in self._reprs :\n raise AttributeError('Repr %s does not exist, only: %s' \\\n % (val, self._reprs))\n elif attr == 'TransFunc' :\n if val is not None and not isinstance(val, type_funcs) :\n raise AttributeError('TransFunc must be a function')\n # this is for Layer() pointed by Pt attr in Str() object\n #if isinstance(self.Pt, Layer) and hasattr(self.Pt, attr):\n # setattr(self.Pt, attr, val)\n # ...does not work properly\n # and the final standard python behaviour\n object.__setattr__(self, attr, val)\n \n def __getattr__(self, attr):\n # this is for Layer() pointed by Pt attr in Str() object\n if isinstance(self.Pt, Layer) and hasattr(self.Pt, attr):\n return getattr(self.Pt, attr)\n # and the final standard python behaviour\n object.__getattr__(self, attr)\n \n # the libmich internal instances check\n # this is highly experimental...\n def __is_intern_inst(self, obj):\n return isinstance(obj, (Element, Layer, Block))\n \n # building basic methods for manipulating easily the Element \n # from its attributes\n def __call__(self, l=None):\n # when length has fixed value:\n if not l and type(self.Len) is int:\n l = self.Len\n #else:\n # l = None\n # when no values are defined at all:\n if self.Val is None and self.Pt is None: \n if l: return l * self._padding_byte\n else: return ''\n # returning the right string:\n # if defined, self.Val overrides self.Pt capabilities\n elif self.Val is not None:\n # allow to pass tuple or list of libmich internal instances\n if isinstance(self.Val, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Val):\n return ''.join(map(str, self.Val))[:l]\n return str(self.Val)[:l]\n # else: use self.Pt capabilities to get the string\n elif self.PtFunc is not None: \n if self.safe: \n assert(hasattr(self.PtFunc(self.Pt), '__str__'))\n return str(self.PtFunc(self.Pt))[:l]\n else:\n # allow to pass tuple or list of libmich internal instances\n if isinstance(self.Pt, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Pt):\n return ''.join(map(str, self.Pt))[:l]\n # otherwise, handle simply as is\n if self.safe: \n assert(hasattr(self.Pt, '__str__'))\n return str(self.Pt)[:l]\n \n def __str__(self):\n # when Element is Transparent:\n if self.is_transparent():\n return ''\n #else:\n return self()\n \n def __len__(self):\n # does not take the LenFunc(Len) into account\n # When a Str is defined, the length is considered dependent of the Str\n # the Str is dependent of the LenFunc(Len) only \n # when mapping data into the Element\n return len(self.__str__())\n \n def bit_len(self):\n return len(self)*8\n \n def map_len(self):\n # need special length definition \n # when mapping a string to the 'Str' element \n # that has no fixed length\n #\n # uses LenFunc, applied to Len, when length is variable:\n # and TransFunc, applied to Trans, to managed potential transparency\n # (e.g. for optional element triggered by other element)\n #\n if self.Len is None:\n return None\n #return 0\n if self.LenFunc is None: \n return self.Len\n else:\n if self.safe:\n assert( type(self.LenFunc(self.Len)) in (int, long) )\n return self.LenFunc(self.Len)\n \n def __int__(self):\n # big endian integer representation of the string buffer\n return shtr(self).left_val(len(self)*8)\n \n def __bin__(self):\n # does not use the standard python 'bin' function to keep \n # the right number of prefixed 0 bits\n h = hex(self)\n binary = ''\n for i in xrange(0, len(h), 2):\n b = format( int(h[i:i+2], 16), 'b' )\n binary += ( 8-len(b) ) * '0' + b\n return binary\n \n def __hex__(self):\n return self().encode('hex')\n \n def __repr__(self):\n # check for simple representations\n if self.Pt is None and self.Val is None: \n return repr(None)\n if self.Repr == 'ipv4':\n #if self.safe: assert( len(self) == 4 )\n if len(self) != 4:\n return '0x%s' % hex(self)\n return inet_ntoa( self.__str__() )\n elif self.Repr == 'hex': \n ret = '0x%s' % hex(self)\n elif self.Repr == 'bin': \n ret = '0b%s' % self.__bin__()\n # check for the best human-readable representation\n elif self.Repr == 'hum':\n # standard return\n ret = repr( self() )\n # complex return:\n # allow to assign a full Block or Layer to a Str...\n if self.__is_intern_inst(self.Pt):\n ret = repr(self.Pt)\n if self.__is_intern_inst(self.Val):\n ret = repr(self.Val)\n # allow to assign a list or tuple of Block or Layer...\n if isinstance(self.Pt, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Pt):\n ret = '|'.join(map(repr, self.Pt))\n if isinstance(self.Val, (list, tuple)) \\\n and False not in map(self.__is_intern_inst, self.Val):\n ret = '|'.join(map(repr, self.Val))\n # finally, self.Val can be a raw value... still\n if self.Val is not None and hasattr(self.Val, '__repr__'):\n ret = repr(self.Val)\n # truncate representation if string too long:\n # avoid terminal panic...\n if len(ret) <= self._repr_limit:\n return ret\n else:\n return ret[:self._repr_limit-3]+'...'\n \n # some more methods for checking Element's attributes:\n def getattr(self):\n return ['CallName', 'ReprName', 'Pt', 'PtFunc', 'Val', 'Len',\n 'LenFunc', 'Type', 'Repr', 'Trans', 'TransFunc']\n \n def showattr(self):\n for a in self.getattr():\n print('%s : %s' % (a, repr(self.__getattribute__(a))) )\n \n # cloning an Element, useful for \"duplicating\" an Element \n # without keeping any dependency\n # used in Layer with Element\n # However,\n #...\n # This is not that true, as an object pointed by .Pt or .Len or .Trans\n # will not be updated to its clone()\n # Conclusion:\n # use this with care\n def clone(self):\n clone = self.__class__(\n self.CallName, self.ReprName,\n self.Pt, self.PtFunc,\n self.Val, \n self.Len, self.LenFunc,\n self.Repr,\n self.Trans, self.TransFunc )\n return clone\n \n # standard method map() to map a string to the Element\n def map(self, string=''):\n if not self.is_transparent():\n l = self.map_len()\n if l is not None:\n self.Val = string[:l]\n else:\n self.Val = string\n if self.dbg >= DBG:\n log(DBG, '(Element) mapping %s on %s, %s' \\\n % (repr(string), self.CallName, repr(self)))\n \n def map_ret(self, string=''):\n self.map(string)\n return string[len(self):]\n \n # shar manipulation interface\n def to_shar(self):\n ret = shar()\n ret.set_buf(self())\n return ret\n \n def map_shar(self, sh):\n if not self.is_transparent():\n l = self.map_len()\n if l is not None:\n self.Val = sh.get_buf(l*8)\n else:\n self.Val = sh.get_buf()\n if self.dbg >= DBG:\n log(DBG, '(Element) mapping %s on %s, %s' \\\n % (repr(string), self.CallName, repr(self)))\nlibmich/formats/L3Mobile_24007.py\nclass LayerTLV(Layer):\nclass Type1_V(LayerTLV):\nclass Type1_TV(LayerTLV):\nclass Type2(LayerTLV):\nclass Type3_V(LayerTLV):\nclass Type3_TV(LayerTLV):\nclass Type4_LV(LayerTLV):\nclass Type4_TLV(LayerTLV):\nclass Type6_LVE(LayerTLV):\nclass Type6_TLVE(LayerTLV):\nclass StrRR(Str):\nclass Layer3(Layer):\n def getobj(self):\n def __init__(self, CallName='', ReprName='', V=0):\n def __init__(self, CallName='', ReprName='', T=0, V=0, \\\n Trans=False, Dict=None):\n def __len__(self):\n def __init__(self, CallName='', ReprName='', T=0, Trans=False):\n def __len__(self):\n def __init__(self, CallName='', ReprName='', V='\\0', Len=1):\n def __init__(self, CallName='', ReprName='', T=0, V='\\0', \\\n Len=1, Trans=False):\n def __len__(self):\n def __init__(self, CallName='', ReprName='', V='\\0'):\n def __init__(self, CallName='', ReprName='', T=0, V='\\0', Trans=False):\n def __len__(self):\n def __init__(self, CallName='', ReprName='', V='\\0'):\n def __init__(self, CallName='', ReprName='', T=0, V='\\0', Trans=False):\n def __len__(self):\n def __call__(self):\n def __init__(self, CallName='', ReprName='', Trans=False, **kwargs):\n def _post_init(self, with_options=True, **kwargs):\n def _len_gsmrr(self, string=''):\n def map(self, string=''):\n def interpret_IE(self, field, cn):\n def __map_opts(self, string=''):\n def _select_tag_old_(self, s='\\0', taglist=[]):\n def _select_tag(self, s='\\0', taglist=[]):\n def __get_opts(self):\n def __map_opt(self, tag, string, opt_ie):\n def __map_unknown_opt(self, string):\n def show(self, with_trans=False):\n GSM_RR = False\n", "answers": [" Bit('TI', ReprName='Transaction Identifier Flag', Pt=0, BitLen=1, \\\r"], "length": 8734, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "aafd3311f9a9da23bf9d842df610fdd89b24b3efe9c0679e"} {"input": "from django import forms\nfrom django.contrib import admin\nfrom dashboard.forms import TextArrayField\nfrom dashboard.constants import (\n TRANSPLATFORM_ENGINES, RELSTREAM_SLUGS, TRANSIFEX_SLUGS, ZANATA_SLUGS,\n DAMNEDLIES_SLUGS, WEBLATE_SLUGS, MEMSOURCE_SLUGS\n)\nfrom dashboard.models import (\n Language, LanguageSet, Platform, Product, Release,\n Package, Visitor, CIPipeline\n)\nfrom dashboard.managers.inventory import InventoryManager\n# Copyright 2016 Red Hat, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n# django\n\n# dashboard\n\nENGINE_CHOICES = tuple([(engine, engine.upper())\n for engine in TRANSPLATFORM_ENGINES])\n\nRELSTR_CHOICES = tuple([(relstream, relstream)\n for relstream in RELSTREAM_SLUGS])\n\nall_platform_slugs = []\nall_platform_slugs.extend(TRANSIFEX_SLUGS)\nall_platform_slugs.extend(ZANATA_SLUGS)\nall_platform_slugs.extend(DAMNEDLIES_SLUGS)\n", "context": "dashboard/models.py\nclass Product(models.Model):\n \"\"\"\n Product Model\n \"\"\"\n product_id = models.AutoField(primary_key=True)\n product_name = models.CharField(\n max_length=200, verbose_name=\"Product Name\"\n )\n product_slug = models.CharField(\n max_length=400, unique=True, verbose_name=\"Product SLUG\"\n )\n product_url = models.URLField(\n max_length=500, unique=True, verbose_name=\"Product URL\", null=True\n )\n product_api_url = models.URLField(\n max_length=500, verbose_name=\"Product API URL\", null=True\n )\n product_server = models.URLField(\n max_length=500, verbose_name=\"Product Server\"\n )\n product_build_system = models.CharField(\n max_length=200, null=True, verbose_name=\"Release Build System\"\n )\n product_build_tags = ArrayField(\n models.CharField(max_length=200, blank=True),\n default=list, null=True, verbose_name=\"Release Build Tags\"\n )\n product_build_tags_last_updated = models.DateTimeField(null=True)\n src_pkg_format = models.CharField(\n max_length=50, null=True, verbose_name=\"Source Package Format\"\n )\n top_url = models.URLField(max_length=500, verbose_name=\"Top URL\")\n web_url = models.URLField(max_length=500, null=True, verbose_name=\"Web URL\")\n krb_service = models.CharField(\n max_length=200, null=True, blank=True, verbose_name=\"Kerberos Service\"\n )\n auth_type = models.CharField(max_length=200, null=True, blank=True, verbose_name=\"Auth Type\")\n amqp_server = models.CharField(\n max_length=500, null=True, blank=True, verbose_name=\"AMQP Server\"\n )\n msgbus_exchange = models.CharField(\n max_length=200, null=True, blank=True, verbose_name=\"Message Bus Exchange\"\n )\n major_milestones = ArrayField(\n models.CharField(max_length=1000, blank=True),\n default=list, null=True, verbose_name=\"Major Milestones\"\n )\n product_phases = ArrayField(\n models.CharField(max_length=200, blank=True),\n default=list, null=True, verbose_name=\"Release Stream Phases\"\n )\n product_status = models.BooleanField(verbose_name=\"Enable/Disable\")\n\n def __str__(self):\n return self.product_name\n\n class Meta:\n db_table = TABLE_PREFIX + 'products'\n verbose_name = \"Product\"\ndashboard/constants.py\nWEBLATE_SLUGS = ('WLTEPUB', 'WLTEFED')\ndashboard/models.py\nclass Visitor(models.Model):\n \"\"\"\n Visitors Model\n \"\"\"\n visitor_id = models.AutoField(primary_key=True)\n visitor_ip = models.GenericIPAddressField()\n visitor_user_agent = models.CharField(max_length=500)\n visitor_accept = models.CharField(max_length=500, null=True, blank=True)\n visitor_encoding = models.CharField(max_length=500, null=True, blank=True)\n visitor_language = models.CharField(max_length=500, null=True, blank=True)\n visitor_host = models.CharField(max_length=500, null=True, blank=True)\n first_visit_time = models.DateTimeField()\n last_visit_time = models.DateTimeField()\n\n def save(self, *args, **kwargs):\n if not self.visitor_id:\n self.first_visit_time = timezone.now()\n self.last_visit_time = timezone.now()\n return super(Visitor, self).save(*args, **kwargs)\n\n def __str__(self):\n return \"%s: %s\" % (str(self.visitor_ip), self.visitor_user_agent)\n\n class Meta:\n db_table = TABLE_PREFIX + 'visitors'\n verbose_name = \"Visitor\"\ndashboard/models.py\nclass Package(ModelMixin, models.Model):\n \"\"\"\n Packages Model\n \"\"\"\n package_id = models.AutoField(primary_key=True)\n package_name = models.CharField(max_length=1000, unique=True, verbose_name=\"Package Name\")\n upstream_name = models.CharField(max_length=1000, null=True, blank=True,\n verbose_name=\"Upstream Name\")\n downstream_name = models.CharField(max_length=1000, null=True, blank=True,\n verbose_name=\"Downstream Name\")\n component = models.CharField(max_length=200, null=True, blank=True, verbose_name=\"Component\")\n upstream_url = models.URLField(max_length=2000, unique=True, verbose_name=\"Upstream URL\")\n upstream_l10n_url = models.URLField(max_length=2000, null=True, blank=True,\n verbose_name=\"Upstream Localization URL\")\n platform_slug = models.ForeignKey(\n Platform, on_delete=models.PROTECT,\n to_field='platform_slug', verbose_name=\"Translation Platform\"\n )\n platform_name = models.CharField(max_length=1000, null=True, blank=True,\n verbose_name=\"Package Name at Translation Platform\")\n # translation platform project http url\n platform_url = models.URLField(max_length=500, null=True, blank=True,\n verbose_name=\"Translation Platform Project URL\")\n products = ArrayField(\n models.CharField(max_length=400, blank=True),\n default=list, null=True, verbose_name=\"Release Streams\"\n )\n package_details_json_str = models.TextField(null=True, blank=True)\n details_json_last_updated = models.DateTimeField(null=True)\n package_name_mapping_json_str = models.TextField(null=True, blank=True)\n name_map_last_updated = models.DateTimeField(null=True, blank=True)\n release_branch_mapping = models.TextField(null=True, blank=True)\n release_branch_map_last_updated = models.DateTimeField(null=True, blank=True)\n package_latest_builds = models.TextField(null=True, blank=True)\n package_latest_builds_last_updated = models.DateTimeField(null=True, blank=True)\n stats_diff = models.TextField(null=True, blank=True)\n stats_diff_last_updated = models.DateTimeField(null=True, blank=True)\n platform_last_updated = models.DateTimeField(null=True, blank=True)\n upstream_last_updated = models.DateTimeField(null=True, blank=True)\n downstream_last_updated = models.DateTimeField(null=True, blank=True)\n translation_file_ext = models.CharField(\n max_length=10, null=True, blank=True, default='po',\n verbose_name=\"Translation Format (po)\"\n )\n created_by = models.EmailField(null=True)\n maintainers = models.TextField(null=True, blank=True)\n\n @property\n def package_details_json(self):\n return self.str2json(self.package_details_json_str)\n\n @property\n def package_name_mapping_json(self):\n return self.str2json(self.package_name_mapping_json_str)\n\n @property\n def release_branch_mapping_json(self):\n return self.str2json(self.release_branch_mapping)\n\n @property\n def package_latest_builds_json(self):\n return self.str2json(self.package_latest_builds)\n\n @property\n def release_branch_mapping_health(self):\n release_branch_mapping_dict = \\\n self.str2json(self.release_branch_mapping)\n if not release_branch_mapping_dict:\n return False\n for release, mapping in release_branch_mapping_dict.items():\n if isinstance(mapping, dict):\n for k, v in mapping.items():\n if not mapping.get(k):\n return False\n return True\n\n @property\n def stats_diff_json(self):\n return self.str2json(self.stats_diff)\n\n @property\n def stats_diff_health(self):\n stats_diff_dict = self.str2json(self.stats_diff)\n if not stats_diff_dict:\n return True\n for release, diff in stats_diff_dict.items():\n if stats_diff_dict.get(release):\n return False\n return True\n\n @property\n def maintainers_json(self):\n return self.str2json(self.maintainers)\n\n def __str__(self):\n return self.package_name\n\n class Meta:\n db_table = TABLE_PREFIX + 'packages'\n verbose_name = \"Package\"\ndashboard/constants.py\nTRANSPLATFORM_ENGINES = ('damnedlies', 'transifex', 'zanata', 'weblate', 'memsource')\ndashboard/models.py\nclass Language(models.Model):\n \"\"\"\n Language Model\n \"\"\"\n locale_id = models.CharField(\n max_length=50, primary_key=True, verbose_name=\"Locale ID\"\n )\n lang_name = models.CharField(\n max_length=400, unique=True, verbose_name=\"Language Name\"\n )\n locale_alias = models.CharField(\n max_length=50, unique=True, null=True, blank=True, verbose_name=\"Locale Alias\"\n )\n locale_script = models.CharField(\n max_length=100, null=True, blank=True, verbose_name=\"Locale Script\"\n )\n lang_status = models.BooleanField(verbose_name=\"Enable/Disable\")\n\n def __str__(self):\n return self.lang_name\n\n class Meta:\n db_table = TABLE_PREFIX + 'languages'\n verbose_name = \"Language\"\ndashboard/constants.py\nZANATA_SLUGS = ('ZNTAPUB', 'ZNTAFED', 'ZNTAJBS', 'ZNTARHT', 'ZNTAVDR')\ndashboard/models.py\nclass Release(ModelMixin, models.Model):\n \"\"\"\n Releases Model\n \"\"\"\n release_id = models.AutoField(primary_key=True)\n release_name = models.CharField(max_length=500, verbose_name=\"Release Name\")\n release_slug = models.CharField(max_length=500, unique=True, verbose_name=\"Release SLUG\")\n product_slug = models.ForeignKey(\n Product, on_delete=models.PROTECT,\n to_field='product_slug', verbose_name=\"Product\"\n )\n language_set_slug = models.ForeignKey(\n LanguageSet, on_delete=models.PROTECT,\n to_field='lang_set_slug', verbose_name=\"Language Set\"\n )\n scm_branch = models.CharField(max_length=100, null=True, blank=True, verbose_name=\"SCM Branch Name\")\n created_on = models.DateTimeField()\n current_phase = models.CharField(max_length=200, null=True, verbose_name=\"Current Phase\")\n calendar_url = models.URLField(max_length=500, unique=True, null=True, verbose_name=\"Calender iCal URL\")\n schedule_json_str = models.TextField(null=True, blank=True)\n sync_calendar = models.BooleanField(default=True, verbose_name=\"Sync Calender\")\n notifications_flag = models.BooleanField(default=True, verbose_name=\"Notification\")\n track_trans_flag = models.BooleanField(default=True, verbose_name=\"Track Translation\")\n created_by = models.EmailField(null=True)\n\n @property\n def schedule_json(self):\n return self.str2json(self.schedule_json_str)\n\n def __str__(self):\n return self.release_name\n\n class Meta:\n db_table = TABLE_PREFIX + 'releases'\n verbose_name_plural = \"Release\"\ndashboard/constants.py\nMEMSOURCE_SLUGS = ('MSRCPUB', )\ndashboard/models.py\nclass LanguageSet(models.Model):\n \"\"\"\n Language Set Model\n \"\"\"\n lang_set_id = models.AutoField(primary_key=True)\n lang_set_name = models.CharField(\n max_length=1000, verbose_name=\"Language Set Name\"\n )\n lang_set_slug = models.CharField(\n max_length=400, unique=True, verbose_name=\"Language Set SLUG\"\n )\n lang_set_color = models.CharField(\n max_length=100, unique=True, verbose_name=\"Tag Colour\"\n )\n locale_ids = ArrayField(\n models.CharField(max_length=50, blank=True),\n default=list, null=True, verbose_name=\"Locale IDs\"\n )\n\n def __str__(self):\n return self.lang_set_name\n\n class Meta:\n db_table = TABLE_PREFIX + 'langset'\n verbose_name = \"Language Set\"\ndashboard/constants.py\nDAMNEDLIES_SLUGS = ('DMLSPUB', )\ndashboard/models.py\nclass CIPipeline(ModelMixin, models.Model):\n \"\"\"\n Continuous Integration Pipeline Model\n \"\"\"\n ci_pipeline_id = models.AutoField(primary_key=True)\n ci_pipeline_uuid = models.UUIDField(default=uuid4, unique=True, editable=False)\n ci_package = models.ForeignKey(\n Package, on_delete=models.PROTECT, verbose_name=\"Package\"\n )\n ci_platform = models.ForeignKey(\n Platform, on_delete=models.PROTECT, verbose_name=\"Platform\"\n )\n ci_release = models.ForeignKey(\n Release, on_delete=models.PROTECT, verbose_name=\"Release\", null=True\n )\n ci_push_job_template = models.ForeignKey(\n JobTemplate, on_delete=models.PROTECT, verbose_name=\"Push Job Template\",\n related_name=\"push_template\", null=True\n )\n ci_pull_job_template = models.ForeignKey(\n JobTemplate, on_delete=models.PROTECT, verbose_name=\"Pull Job Template\",\n related_name=\"pull_template\", null=True\n )\n ci_project_web_url = models.URLField(max_length=500, null=True, blank=True,\n verbose_name=\"Platform Project URL\")\n ci_project_details_json_str = models.TextField(null=True, blank=True)\n ci_platform_jobs_json_str = models.TextField(null=True, blank=True)\n ci_project_analyses_json_str = models.TextField(null=True, blank=True)\n ci_project_import_settings_json_str = models.TextField(null=True, blank=True)\n ci_project_assign_templates_json_str = models.TextField(null=True, blank=True)\n ci_project_workflow_steps_json_str = models.TextField(null=True, blank=True)\n ci_project_providers_json_str = models.TextField(null=True, blank=True)\n ci_project_term_bases_json_str = models.TextField(null=True, blank=True)\n ci_project_qa_checks_json_str = models.TextField(null=True, blank=True)\n ci_project_trans_memory_json_str = models.TextField(null=True, blank=True)\n ci_pipeline_last_updated = models.DateTimeField(null=True, blank=True)\n ci_pipeline_visibility = models.BooleanField(\n default=True, verbose_name='CI Pipeline Visibility'\n )\n\n @property\n def ci_project_details_json(self):\n return self.str2json(self.ci_project_details_json_str)\n\n @property\n def ci_platform_jobs_json(self):\n return self.str2json(self.ci_platform_jobs_json_str)\n\n @property\n def ci_project_analyses_json(self):\n return self.str2json(self.ci_project_analyses_json_str)\n\n @property\n def ci_project_import_settings_json(self):\n return self.str2json(self.ci_project_import_settings_json_str)\n\n @property\n def ci_project_assign_templates_json(self):\n return self.str2json(self.ci_project_assign_templates_json_str)\n\n @property\n def ci_project_workflow_steps_json(self):\n return self.str2json(self.ci_project_workflow_steps_json_str)\n\n @property\n def ci_project_providers_json(self):\n return self.str2json(self.ci_project_providers_json_str)\n\n @property\n def ci_project_term_bases_json(self):\n return self.str2json(self.ci_project_term_bases_json_str)\n\n @property\n def ci_project_qa_checks_json(self):\n return self.str2json(self.ci_project_qa_checks_json_str)\n\n @property\n def ci_project_trans_memory_json(self):\n return self.str2json(self.ci_project_trans_memory_json_str)\n\n def __str__(self):\n return \"{} | {}\".format(\n str(self.ci_pipeline_uuid)[:8],\n self.ci_package.package_name\n )\n\n class Meta:\n db_table = TABLE_PREFIX + 'cipipeline'\n verbose_name = \"CI Pipeline\"\ndashboard/models.py\nclass Platform(ModelMixin, models.Model):\n \"\"\"\n Translation Platforms Model\n \"\"\"\n platform_id = models.AutoField(primary_key=True)\n engine_name = models.CharField(\n max_length=200, verbose_name=\"Platform Engine\"\n )\n subject = models.CharField(\n max_length=200, null=True, verbose_name=\"Platform Subject\"\n )\n api_url = models.URLField(max_length=500, unique=True, verbose_name=\"Server URL\")\n platform_slug = models.CharField(\n max_length=400, unique=True, verbose_name=\"Platform SLUG\"\n )\n server_status = models.BooleanField(verbose_name=\"Enable/Disable\")\n ci_status = models.BooleanField(verbose_name=\"CI Enable/Disable\", default=False)\n projects_json_str = models.TextField(null=True, blank=True)\n projects_last_updated = models.DateTimeField(null=True)\n auth_login_id = models.CharField(\n max_length=200, null=True, blank=True, verbose_name=\"Auth User\"\n )\n auth_token_key = models.CharField(\n max_length=200, null=True, blank=True, verbose_name=\"Auth Password/Token\"\n )\n token_api_json_str = models.TextField(null=True, blank=True, verbose_name=\"Auth Token JSON\")\n token_expiry = models.DateTimeField(null=True, blank=True, verbose_name=\"Auth Token Expiry\")\n\n @property\n def projects_json(self):\n return self.str2json(self.projects_json_str)\n\n @property\n def token_api_json(self):\n return self.str2json(self.token_api_json_str)\n\n @property\n def token_status(self):\n if not self.token_expiry:\n return\n return self.token_expiry > timezone.now()\n\n def __str__(self):\n return \"{0} {1}\".format(self.engine_name, self.subject)\n\n class Meta:\n db_table = TABLE_PREFIX + 'platforms'\n verbose_name = \"Translation Platform\"\ndashboard/constants.py\nTRANSIFEX_SLUGS = ('TNFXPUB', )\ndashboard/constants.py\nRELSTREAM_SLUGS = ('RHEL', 'fedora', 'RHV', 'satellite')\n", "answers": ["all_platform_slugs.extend(WEBLATE_SLUGS)"], "length": 1258, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"} {"input": "from datetime import tzinfo\nfrom typing import Optional, Union\nfrom ._common import _to_unicode\nfrom ._logger import logger\nfrom ._parser import PingParser # noqa\nfrom ._parser import (\n AlpineLinuxPingParser,\n LinuxPingParser,\n MacOsPingParser,\n NullPingParser,\n WindowsPingParser,\n)\nfrom ._pingtransmitter import PingResult\nfrom ._stats import PingStats\nfrom .error import ParseError, ParseErrorReason\nimport pyparsing as pp\nimport typepy\n\"\"\"\n.. codeauthor:: Tsuyoshi Hombashi \n\"\"\"\n\n\n\n\n\nclass PingParsing:\n \"\"\"\n Parser class to parsing ping command output.\n\n Args:\n timezone (Optional[tzinfo]):\n Time zone for parsing timestamps.\n \"\"\"\n\n def __init__(self, timezone: Optional[tzinfo] = None) -> None:\n self.__parser: PingParser = NullPingParser()\n self.__timezone = timezone\n\n @property\n def parser_name(self) -> str:\n return self.__parser._parser_name\n\n", "context": "pingparsing/_parser.py\nclass WindowsPingParser(PingParser):\n @property\n def _parser_name(self) -> str:\n return \"Windows\"\n\n @property\n def _icmp_reply_pattern(self) -> str:\n return (\n \" from \"\n + self._DEST_PATTERN\n + rf\":\\s*bytes=(?P<{IcmpReplyKey.BYTES}>[0-9]+)\"\n + self._TIME_PATTERN\n + \"ms\"\n + self._TTL_PATTERN\n )\n\n @property\n def _stats_headline_pattern(self) -> str:\n return rf\"^Ping statistics for {self._DEST_PATTERN}\"\n\n @property\n def _is_support_packet_duplicate(self) -> bool:\n return False\n\n def parse(self, ping_message: Sequence[str]) -> PingStats:\n icmp_replies = self._parse_icmp_reply(ping_message)\n stats_headline, packet_info_line, body_line_list = self._preprocess_parse_stats(\n lines=ping_message\n )\n packet_pattern = (\n pp.Literal(\"Packets: Sent = \")\n + pp.Word(pp.nums)\n + pp.Literal(\", Received = \")\n + pp.Word(pp.nums)\n )\n\n destination = self._parse_destination(stats_headline)\n duplicates = self._parse_duplicate(packet_info_line)\n\n parse_list = packet_pattern.parseString(_to_unicode(packet_info_line))\n packet_transmit = int(parse_list[1])\n packet_receive = int(parse_list[3])\n\n is_valid_data = True\n try:\n rtt_line = body_line_list[2].strip()\n except IndexError:\n is_valid_data = False\n\n if not is_valid_data or typepy.is_null_string(rtt_line):\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n icmp_replies=icmp_replies,\n )\n\n rtt_pattern = (\n pp.Literal(\"Minimum = \")\n + pp.Word(pp.nums)\n + pp.Literal(\"ms, Maximum = \")\n + pp.Word(pp.nums)\n + pp.Literal(\"ms, Average = \")\n + pp.Word(pp.nums)\n )\n parse_list = rtt_pattern.parseString(_to_unicode(rtt_line))\n\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n rtt_min=float(parse_list[1]),\n rtt_avg=float(parse_list[5]),\n rtt_max=float(parse_list[3]),\n icmp_replies=icmp_replies,\n )\npingparsing/_pingtransmitter.py\nclass PingResult(namedtuple(\"PingResult\", \"stdout stderr returncode\")):\n \"\"\"\n Data class to store ``ping`` command execution result.\n\n .. py:attribute:: stdout\n :type: Optional[str]\n\n Standard output of ``ping`` command execution result.\n\n .. py:attribute:: stderr\n :type: Optional[str]\n\n Standard error of ``ping`` command execution result.\n\n .. py:attribute:: returncode\n :type: int\n\n Return code of ``ping`` command execution result.\n \"\"\"\npingparsing/_parser.py\nclass MacOsPingParser(PingParser):\n @property\n def _parser_name(self) -> str:\n return \"macOS\"\n\n @property\n def _icmp_reply_pattern(self) -> str:\n return (\n self._BYTES_PATTERN\n + r\"\\s+from \"\n + self._DEST_PATTERN\n + \":\"\n + self._ICMP_SEQ_PATTERN\n + self._TTL_PATTERN\n + self._TIME_PATTERN\n )\n\n @property\n def _stats_headline_pattern(self) -> str:\n return rf\"--- {self._DEST_PATTERN} ping statistics ---\"\n\n @property\n def _is_support_packet_duplicate(self) -> bool:\n return True\n\n def parse(self, ping_message: Sequence[str]) -> PingStats:\n icmp_replies = self._parse_icmp_reply(ping_message)\n stats_headline, packet_info_line, body_line_list = self._preprocess_parse_stats(\n lines=ping_message\n )\n packet_pattern = (\n pp.Word(pp.nums)\n + pp.Literal(\"packets transmitted,\")\n + pp.Word(pp.nums)\n + pp.Literal(\"packets received,\")\n )\n\n destination = self._parse_destination(stats_headline)\n duplicates = self._parse_duplicate(packet_info_line)\n\n parse_list = packet_pattern.parseString(_to_unicode(packet_info_line))\n packet_transmit = int(parse_list[0])\n packet_receive = int(parse_list[2])\n\n is_valid_data = True\n try:\n rtt_line = body_line_list[1]\n except IndexError:\n is_valid_data = False\n\n if not is_valid_data or typepy.is_null_string(rtt_line):\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n icmp_replies=icmp_replies,\n )\n\n rtt_pattern = (\n pp.Literal(\"round-trip min/avg/max/stddev =\")\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + pp.Word(pp.nums + \"ms\")\n )\n parse_list = rtt_pattern.parseString(_to_unicode(rtt_line))\n\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n rtt_min=float(parse_list[1]),\n rtt_avg=float(parse_list[3]),\n rtt_max=float(parse_list[5]),\n rtt_mdev=float(parse_list[7]),\n icmp_replies=icmp_replies,\n )\npingparsing/_parser.py\nclass PingParser(PingParserInterface):\n\n _BYTES_PATTERN = rf\"\\s*(?P<{IcmpReplyKey.BYTES}>[0-9]+) bytes\"\n _DEST_PATTERN = r\"(?P<{key}>[a-zA-Z0-9:\\-\\.\\(\\)% ]+)\".format(\n key=IcmpReplyKey.DESTINATION\n ) # host or ipv4/ipv6 addr\n _IPADDR_PATTERN = r\"(\\d{1,3}\\.){3}\\d{1,3}\"\n _ICMP_SEQ_PATTERN = rf\"\\s*icmp_seq=(?P<{IcmpReplyKey.SEQUENCE_NO}>\\d+)\"\n _TTL_PATTERN = rf\"\\s*ttl=(?P<{IcmpReplyKey.TTL}>\\d+)\"\n _TIME_PATTERN = rf\"\\s*time[=<](?P<{IcmpReplyKey.TIME}>[0-9\\.]+)\"\n\n def __init__(self, timezone: Optional[tzinfo] = None) -> None:\n self.__timezone = timezone\n\n @abc.abstractproperty\n def _parser_name(self) -> str: # pragma: no cover\n pass\n\n @abc.abstractproperty\n def _icmp_reply_pattern(self) -> str: # pragma: no cover\n pass\n\n @property\n def _icmp_no_ans_pattern(self) -> str:\n return \"(?!x)x\" # never matching anything\n\n @property\n def _duplicate_packet_pattern(self) -> str:\n return r\".+ \\(DUP!\\)$\"\n\n @abc.abstractproperty\n def _stats_headline_pattern(self) -> str: # pragma: no cover\n pass\n\n @abc.abstractproperty\n def _is_support_packet_duplicate(self) -> bool: # pragma: no cover\n pass\n\n def _parse_icmp_reply(self, ping_lines: Sequence[str]) -> IcmpReplies:\n icmp_reply_regexp = re.compile(self._icmp_reply_pattern, re.IGNORECASE)\n icmp_no_ans_regexp = re.compile(self._icmp_no_ans_pattern, re.IGNORECASE)\n duplicate_packet_regexp = re.compile(self._duplicate_packet_pattern)\n icmp_reply_list = []\n\n for line in ping_lines:\n match = icmp_reply_regexp.search(line)\n if not match:\n match = icmp_no_ans_regexp.search(line)\n if not match:\n continue\n\n results = match.groupdict()\n reply: Dict[str, Union[str, bool, float, int, datetime]] = {}\n\n if IcmpReplyKey.DESTINATION in results:\n reply[IcmpReplyKey.DESTINATION] = results[IcmpReplyKey.DESTINATION]\n\n if IcmpReplyKey.BYTES in results:\n reply[IcmpReplyKey.BYTES] = int(results[IcmpReplyKey.BYTES])\n\n if results.get(IcmpReplyKey.TIMESTAMP):\n reply[IcmpReplyKey.TIMESTAMP] = self.__timestamp_to_datetime(\n results[IcmpReplyKey.TIMESTAMP]\n )\n elif results.get(IcmpReplyKey.TIMESTAMP_NO_ANS):\n reply[IcmpReplyKey.TIMESTAMP] = self.__timestamp_to_datetime(\n results[IcmpReplyKey.TIMESTAMP_NO_ANS]\n )\n\n if IcmpReplyKey.SEQUENCE_NO in results:\n reply[IcmpReplyKey.SEQUENCE_NO] = int(results[IcmpReplyKey.SEQUENCE_NO])\n\n if IcmpReplyKey.TTL in results:\n reply[IcmpReplyKey.TTL] = int(results[IcmpReplyKey.TTL])\n\n if IcmpReplyKey.TIME in results:\n reply[IcmpReplyKey.TIME] = float(results[IcmpReplyKey.TIME])\n\n if duplicate_packet_regexp.search(line):\n reply[IcmpReplyKey.DUPLICATE] = True\n else:\n reply[IcmpReplyKey.DUPLICATE] = False\n\n icmp_reply_list.append(reply)\n\n return icmp_reply_list\n\n def _preprocess_parse_stats(self, lines: Sequence[str]) -> Tuple[str, str, Sequence[str]]:\n logger.debug(f\"parsing as {self._parser_name:s} ping result format\")\n\n stats_headline_idx = self.__find_stats_headline_idx(\n lines, re.compile(self._stats_headline_pattern)\n )\n body_line_list = lines[stats_headline_idx + 1 :]\n self.__validate_stats_body(body_line_list)\n\n packet_info_line = body_line_list[0]\n\n return (lines[stats_headline_idx], packet_info_line, body_line_list)\n\n def _parse_destination(self, stats_headline: str) -> str:\n match = re.search(self._stats_headline_pattern, stats_headline)\n if not match:\n return \"unknown\"\n\n return match.groupdict()[IcmpReplyKey.DESTINATION].strip(\":\")\n\n def __find_stats_headline_idx(self, lines: Sequence[str], re_stats_header: Pattern) -> int:\n for i, line in enumerate(lines):\n if re_stats_header.search(line):\n break\n else:\n raise ParseError(reason=ParseErrorReason.HEADER_NOT_FOUND)\n\n return i\n\n def __timestamp_to_datetime(self, timestamp: str) -> datetime:\n return DateTime(timestamp.lstrip(\"[\").rstrip(\"]\"), timezone=self.__timezone).force_convert()\n\n def __validate_stats_body(self, body_line_list: Sequence[str]) -> None:\n if typepy.is_empty_sequence(body_line_list):\n raise ParseError(reason=ParseErrorReason.EMPTY_STATISTICS)\n\n def _parse_duplicate(self, line: str) -> Optional[int]:\n if not self._is_support_packet_duplicate:\n return None\n\n packet_pattern = (\n pp.SkipTo(pp.Word(\"+\" + pp.nums) + pp.Literal(\"duplicates,\"))\n + pp.Word(\"+\" + pp.nums)\n + pp.Literal(\"duplicates,\")\n )\n\n try:\n duplicate_parse_list = packet_pattern.parseString(_to_unicode(line))\n except pp.ParseException:\n return 0\n\n return int(duplicate_parse_list[-2].strip(\"+\"))\npingparsing/_stats.py\nclass PingStats:\n def __init__(self, *args, **kwargs) -> None:\n self.__destination = kwargs.pop(\"destination\", None)\n self.__packet_transmit = kwargs.pop(\"packet_transmit\", None)\n self.__packet_receive = kwargs.pop(\"packet_receive\", None)\n self.__rtt_min = kwargs.pop(\"rtt_min\", None)\n self.__rtt_avg = kwargs.pop(\"rtt_avg\", None)\n self.__rtt_max = kwargs.pop(\"rtt_max\", None)\n self.__rtt_mdev = kwargs.pop(\"rtt_mdev\", None)\n self.__duplicates = kwargs.pop(\"duplicates\", None)\n\n self.__icmp_replies = kwargs.pop(\"icmp_replies\", [])\n\n @property\n def destination(self) -> str:\n \"\"\"\n The ping destination.\n\n Returns:\n |str|:\n \"\"\"\n\n return self.__destination\n\n @property\n def packet_transmit(self) -> Optional[int]:\n \"\"\"\n Number of packets transmitted.\n\n Returns:\n |int|:\n \"\"\"\n\n return self.__packet_transmit\n\n @property\n def packet_receive(self) -> Optional[int]:\n \"\"\"\n Number of packets received.\n\n Returns:\n |int|:\n \"\"\"\n\n return self.__packet_receive\n\n @property\n def packet_loss_count(self) -> Optional[int]:\n \"\"\"\n Number of packet losses.\n\n Returns:\n |int|: |None| if the value is not a number.\n \"\"\"\n\n try:\n return cast(int, self.packet_transmit) - cast(int, self.packet_receive)\n except TypeError:\n return None\n\n @property\n def packet_loss_rate(self) -> Optional[float]:\n \"\"\"\n Percentage of packet loss |percent_unit|.\n\n Returns:\n |float|: |None| if the value is not a number.\n \"\"\"\n\n try:\n return (cast(int, self.packet_loss_count) / cast(int, self.packet_transmit)) * 100\n except (TypeError, ZeroDivisionError, OverflowError):\n return None\n\n @property\n def rtt_min(self) -> Optional[float]:\n \"\"\"\n Minimum round trip time of transmitted ICMP packets |msec_unit|.\n\n Returns:\n |float|:\n \"\"\"\n\n return self.__rtt_min\n\n @property\n def rtt_avg(self) -> Optional[float]:\n \"\"\"\n Average round trip time of transmitted ICMP packets |msec_unit|.\n\n Returns:\n |float|:\n \"\"\"\n\n return self.__rtt_avg\n\n @property\n def rtt_max(self) -> Optional[float]:\n \"\"\"\n Maximum round trip time of transmitted ICMP packets |msec_unit|.\n\n Returns:\n |float|:\n \"\"\"\n\n return self.__rtt_max\n\n @property\n def rtt_mdev(self) -> Optional[float]:\n \"\"\"\n Standard deviation of transmitted ICMP packets.\n\n Returns:\n |float|: |None| when parsing Windows ping result.\n \"\"\"\n\n return self.__rtt_mdev\n\n @property\n def packet_duplicate_count(self) -> Optional[int]:\n \"\"\"\n Number of duplicated packets.\n\n Returns:\n |int|: |None| when parsing Windows ping result.\n \"\"\"\n\n return self.__duplicates\n\n @property\n def packet_duplicate_rate(self) -> Optional[float]:\n \"\"\"\n Percentage of duplicated packets |percent_unit|.\n\n Returns:\n |float|: |None| if the value is not a number.\n \"\"\"\n\n try:\n return (cast(int, self.packet_duplicate_count) / cast(int, self.packet_receive)) * 100\n except (TypeError, ZeroDivisionError, OverflowError):\n return None\n\n @property\n def icmp_replies(self) -> IcmpReplies:\n \"\"\"\n ICMP packet reply information.\n\n .. note:\n ``time<1ms`` considered as ``time=1``\n\n Returns:\n |list| of |dict|:\n \"\"\"\n\n return self.__icmp_replies\n\n def is_empty(self):\n return all(\n [\n self.destination is None,\n self.packet_transmit is None,\n self.packet_receive is None,\n self.packet_loss_count is None,\n self.packet_loss_rate is None,\n self.packet_duplicate_count is None,\n self.packet_duplicate_rate is None,\n self.rtt_min is None,\n self.rtt_avg is None,\n self.rtt_max is None,\n self.rtt_mdev is None,\n not self.icmp_replies,\n ]\n )\n\n def as_dict(\n self, include_icmp_replies: bool = False\n ) -> Dict[str, Union[str, int, float, IcmpReplies, None]]:\n \"\"\"\n ping statistics.\n\n Returns:\n |dict|:\n\n Examples:\n >>> import pingparsing\n >>> parser = pingparsing.PingParsing()\n >>> parser.parse(ping_result)\n >>> parser.as_dict()\n {\n \"destination\": \"google.com\",\n \"packet_transmit\": 60,\n \"packet_receive\": 60,\n \"packet_loss_rate\": 0.0,\n \"packet_loss_count\": 0,\n \"rtt_min\": 61.425,\n \"rtt_avg\": 99.731,\n \"rtt_max\": 212.597,\n \"rtt_mdev\": 27.566,\n \"packet_duplicate_rate\": 0.0,\n \"packet_duplicate_count\": 0\n }\n \"\"\"\n\n d: Dict[str, Union[str, int, float, IcmpReplies, None]] = {\n \"destination\": self.destination,\n \"packet_transmit\": self.packet_transmit,\n \"packet_receive\": self.packet_receive,\n \"packet_loss_count\": self.packet_loss_count,\n \"packet_loss_rate\": self.packet_loss_rate,\n \"rtt_min\": self.rtt_min,\n \"rtt_avg\": self.rtt_avg,\n \"rtt_max\": self.rtt_max,\n \"rtt_mdev\": self.rtt_mdev,\n \"packet_duplicate_count\": self.packet_duplicate_count,\n \"packet_duplicate_rate\": self.packet_duplicate_rate,\n }\n if include_icmp_replies:\n d[\"icmp_replies\"] = self.icmp_replies\n\n return d\n\n def as_tuple(self) -> Tuple:\n \"\"\"\n ping statistics.\n\n Returns:\n |namedtuple|:\n\n Examples:\n >>> import pingparsing\n >>> parser = pingparsing.PingParsing()\n >>> parser.parse(ping_result)\n >>> parser.as_tuple()\n PingResult(destination='google.com', packet_transmit=60, packet_receive=60, packet_loss_rate=0.0, packet_loss_count=0, rtt_min=61.425, rtt_avg=99.731, rtt_max=212.597, rtt_mdev=27.566, packet_duplicate_rate=0.0, packet_duplicate_count=0)\n \"\"\" # noqa\n\n from collections import namedtuple\n\n ping_result = self.as_dict()\n\n return namedtuple(\"PingStatsTuple\", ping_result.keys())(**ping_result) # type: ignore\npingparsing/error.py\nclass ParseErrorReason(enum.Enum):\n HEADER_NOT_FOUND = \"ping statistics not found\"\n EMPTY_STATISTICS = \"ping statistics is empty\"\npingparsing/_parser.py\nclass AlpineLinuxPingParser(LinuxPingParser):\n @property\n def _parser_name(self) -> str:\n return \"AlpineLinux\"\n\n @property\n def _icmp_reply_pattern(self) -> str:\n return (\n self._BYTES_PATTERN\n + r\"\\s+from \"\n + self._DEST_PATTERN\n + \": \"\n + rf\"seq=(?P<{IcmpReplyKey.SEQUENCE_NO}>\\d+) \"\n + self._TTL_PATTERN\n + self._TIME_PATTERN\n )\n\n @property\n def _is_support_packet_duplicate(self) -> bool:\n return True\n\n def parse(self, ping_message: Sequence[str]) -> PingStats:\n icmp_replies = self._parse_icmp_reply(ping_message)\n stats_headline, packet_info_line, body_line_list = self._preprocess_parse_stats(\n lines=ping_message\n )\n packet_pattern = (\n pp.Word(pp.nums)\n + pp.Literal(\"packets transmitted,\")\n + pp.Word(pp.nums)\n + pp.Literal(\"packets received,\")\n )\n\n destination = self._parse_destination(stats_headline)\n duplicates = self._parse_duplicate(packet_info_line)\n\n parse_list = packet_pattern.parseString(_to_unicode(packet_info_line))\n packet_transmit = int(parse_list[0])\n packet_receive = int(parse_list[2])\n\n is_valid_data = True\n try:\n rtt_line = body_line_list[1]\n except IndexError:\n is_valid_data = False\n\n if not is_valid_data or typepy.is_null_string(rtt_line):\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n icmp_replies=icmp_replies,\n )\n\n rtt_pattern = (\n pp.Literal(\"round-trip min/avg/max =\")\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + pp.Word(pp.nums + \"ms\")\n )\n parse_list = rtt_pattern.parseString(_to_unicode(rtt_line))\n\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n rtt_min=float(parse_list[1]),\n rtt_avg=float(parse_list[3]),\n rtt_max=float(parse_list[5]),\n icmp_replies=icmp_replies,\n )\n\n def _parse_duplicate(self, line: str) -> int:\n packet_pattern = (\n pp.SkipTo(pp.Word(pp.nums) + pp.Literal(\"duplicates,\"))\n + pp.Word(pp.nums)\n + pp.Literal(\"duplicates,\")\n )\n try:\n duplicate_parse_list = packet_pattern.parseString(_to_unicode(line))\n except pp.ParseException:\n return 0\n\n return int(duplicate_parse_list[-2])\npingparsing/_logger.py\nMODULE_NAME = \"pingparsing\"\nclass NullLogger:\n def remove(self, handler_id=None): # pragma: no cover\n def add(self, sink, **kwargs): # pragma: no cover\n def disable(self, name): # pragma: no cover\n def enable(self, name): # pragma: no cover\n def critical(self, __message, *args, **kwargs): # pragma: no cover\n def debug(self, __message, *args, **kwargs): # pragma: no cover\n def error(self, __message, *args, **kwargs): # pragma: no cover\n def exception(self, __message, *args, **kwargs): # pragma: no cover\n def info(self, __message, *args, **kwargs): # pragma: no cover\n def log(self, __level, __message, *args, **kwargs): # pragma: no cover\n def success(self, __message, *args, **kwargs): # pragma: no cover\n def trace(self, __message, *args, **kwargs): # pragma: no cover\n def warning(self, __message, *args, **kwargs): # pragma: no cover\ndef set_logger(is_enable: bool, propagation_depth: int = 1) -> None:\ndef set_log_level(log_level):\npingparsing/_common.py\ndef _to_unicode(text: Union[str, bytes]) -> str:\n try:\n return text.decode(\"ascii\") # type: ignore\n except AttributeError:\n return cast(str, text)\npingparsing/error.py\nclass ParseError(Exception):\n \"\"\"\n Exception raised when failed to parse ping results.\n \"\"\"\n\n @property\n def reason(self) -> Union[str]:\n return self.__reason\n\n def __init__(self, *args, **kwargs):\n self.__reason = kwargs.pop(\"reason\", None)\n\n super().__init__(*args, **kwargs)\npingparsing/_parser.py\nclass LinuxPingParser(PingParser):\n @property\n def _parser_name(self) -> str:\n return \"Linux\"\n\n _TIMESTAMP_PATTERN = rf\"(?P<{IcmpReplyKey.TIMESTAMP}>\\[[0-9\\.]+\\])\"\n _NO_ANS_TIMESTAMP_PATTERN = rf\"(?P<{IcmpReplyKey.TIMESTAMP_NO_ANS}>\\[[0-9\\.]+\\])\"\n\n @property\n def _icmp_no_ans_pattern(self) -> str:\n return self._NO_ANS_TIMESTAMP_PATTERN + \" no answer yet for \" + self._ICMP_SEQ_PATTERN\n\n @property\n def _icmp_reply_pattern(self) -> str:\n return (\n self._TIMESTAMP_PATTERN\n + \"?\"\n + self._BYTES_PATTERN\n + r\"\\s+from \"\n + self._DEST_PATTERN\n + \":\"\n + self._ICMP_SEQ_PATTERN\n + self._TTL_PATTERN\n + self._TIME_PATTERN\n )\n\n @property\n def _stats_headline_pattern(self) -> str:\n return rf\"--- {self._DEST_PATTERN} ping statistics ---\"\n\n @property\n def _is_support_packet_duplicate(self) -> bool:\n return True\n\n def parse(self, ping_message: Sequence[str]) -> PingStats:\n icmp_replies = self._parse_icmp_reply(ping_message)\n stats_headline, packet_info_line, body_line_list = self._preprocess_parse_stats(\n lines=ping_message\n )\n packet_pattern = (\n pp.Word(pp.nums)\n + pp.Literal(\"packets transmitted,\")\n + pp.Word(pp.nums)\n + pp.Literal(\"received,\")\n )\n\n destination = self._parse_destination(stats_headline)\n duplicates = self._parse_duplicate(packet_info_line)\n\n parse_list = packet_pattern.parseString(_to_unicode(packet_info_line))\n packet_transmit = int(parse_list[0])\n packet_receive = int(parse_list[2])\n\n is_valid_data = True\n try:\n rtt_line = body_line_list[1]\n except IndexError:\n is_valid_data = False\n\n if not is_valid_data or typepy.is_null_string(rtt_line):\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n icmp_replies=icmp_replies,\n )\n\n rtt_pattern = (\n pp.Literal(\"rtt min/avg/max/mdev =\")\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + \"/\"\n + pp.Word(pp.nums + \".\")\n + pp.Word(pp.nums + \"ms\")\n )\n try:\n parse_list = rtt_pattern.parseString(_to_unicode(rtt_line))\n except pp.ParseException:\n if not re.search(r\"\\s*pipe \\d+\", rtt_line):\n raise ValueError\n\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n icmp_replies=icmp_replies,\n )\n\n return PingStats(\n destination=destination,\n packet_transmit=packet_transmit,\n packet_receive=packet_receive,\n duplicates=duplicates,\n rtt_min=float(parse_list[1]),\n rtt_avg=float(parse_list[3]),\n rtt_max=float(parse_list[5]),\n rtt_mdev=float(parse_list[7]),\n icmp_replies=icmp_replies,\n )\npingparsing/_parser.py\nclass NullPingParser(PingParser):\n @property\n def _parser_name(self) -> str:\n return \"null\"\n\n @property\n def _icmp_reply_pattern(self) -> str:\n return \"\"\n\n @property\n def _stats_headline_pattern(self) -> str:\n return \"\"\n\n @property\n def _is_support_packet_duplicate(self) -> bool: # pragma: no cover\n return False\n\n def parse(self, ping_message: Sequence[str]) -> PingStats: # pragma: no cover\n return PingStats()\n\n def _preprocess_parse_stats(\n self, lines: Sequence[str]\n ) -> Tuple[str, str, List[str]]: # pragma: no cover\n return (\"\", \"\", [])\n", "answers": [" def parse(self, ping_message: Union[str, PingResult]) -> PingStats:"], "length": 1973, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "81259943df8714cd065c48803df03c7352f265bd9bde3b82"} {"input": "import logging\nfrom twisted.web import server\nfrom twisted.internet.task import LoopingCall\nfrom twisted.web.wsgi import WSGIResource\nfrom flask import Flask, render_template\nfrom flask_restful import Api\nfrom huginn.protocols import ControlsProtocol, SimulatorDataProtocol\nfrom huginn.http import (SimulatorDataWebSocketFactory,\n SimulatorDataWebSocketProtocol)\nfrom huginn.rest import (FDMResource, AircraftResource, GPSResource,\n AccelerometerResource, GyroscopeResource,\n ThermometerResource, PressureSensorResource,\n PitotTubeResource, InertialNavigationSystemResource,\n EngineResource, FlightControlsResource,\n SimulatorControlResource, AccelerationsResource,\n VelocitiesResource, OrientationResource,\n AtmosphereResource, ForcesResource,\n InitialConditionResource, PositionResource,\n AirspeedIndicatorResource, AltimeterResource,\n AttitudeIndicatorResource, HeadingIndicatorResource,\n VerticalSpeedIndicatorResource, WaypointResource,\n WaypointsResource)\n\n reactor.listenUDP(port, controls_protocol)\n\n\ndef initialize_simulator_data_server(reactor, simulator, clients):\n \"\"\"Initialize the simulator data server\n\n Arguments:\n reactor: a Twisted reactor to use\n simulator: a Simulator object\n clients: a list of (address, port) tuples of the listening clients\n \"\"\"\n for address, port, update_rate in clients:\n logger.debug(\"Sending fdm data to %s:%d every %f seconds\",\n address, port, update_rate)\n\n simulator_data_protocol = SimulatorDataProtocol(simulator,\n address,\n port)\n\n reactor.listenUDP(0, simulator_data_protocol)\n\n simulator_data_updater = LoopingCall(\n simulator_data_protocol.send_simulator_data)\n\n simulator_data_updater.start(update_rate)\n\n\ndef initialize_websocket_server(reactor, simulator, host, port, database):\n \"\"\"Initialize the web socket server\n\n Arguments:\n reactor: a twisted reactor object\n simulator: an Simulator object\n host: the server host\n port: the port to listen to\n database: the database that contains the simulator data\n \"\"\"\n logger.debug(\"The websocket interface runs on %s:%d\", host, port)\n\n factory = SimulatorDataWebSocketFactory(\n simulator,\n database,\n \"ws://%s:%d\" % (host, port),\n )\n\n factory.protocol = SimulatorDataWebSocketProtocol\n\n reactor.listenTCP(port, factory)\n\n\ndef _add_fdm_resources(api, fdm, aircraft):\n api.add_resource(FDMResource, \"/fdm\",\n resource_class_args=(fdm, aircraft))\n\n api.add_resource(AccelerationsResource, \"/fdm/accelerations\",\n resource_class_args=(fdm.fdmexec,))\n\n api.add_resource(VelocitiesResource, \"/fdm/velocities\",\n resource_class_args=(fdm.fdmexec,))\n\n api.add_resource(OrientationResource, \"/fdm/orientation\",\n resource_class_args=(fdm.fdmexec,))\n\n api.add_resource(AtmosphereResource, \"/fdm/atmosphere\",\n resource_class_args=(fdm.fdmexec,))\n\n api.add_resource(ForcesResource, \"/fdm/forces\",\n resource_class_args=(fdm.fdmexec,))\n\n api.add_resource(InitialConditionResource, \"/fdm/initial_condition\",\n resource_class_args=(fdm.fdmexec,))\n\n api.add_resource(PositionResource, \"/fdm/position\",\n resource_class_args=(fdm.fdmexec,))\n\n\ndef _add_instrument_resources(api, instruments):\n api.add_resource(GPSResource, \"/aircraft/instruments/gps\",\n resource_class_args=(instruments.gps,))\n\n api.add_resource(\n AirspeedIndicatorResource,\n \"/aircraft/instruments/airspeed_indicator\",\n resource_class_args=(instruments.airspeed_indicator,)\n )\n\n api.add_resource(\n AltimeterResource,\n \"/aircraft/instruments/altimeter\",\n resource_class_args=(instruments.altimeter,)\n )\n\n api.add_resource(\n AttitudeIndicatorResource,\n \"/aircraft/instruments/attitude_indicator\",\n resource_class_args=(instruments.attitude_indicator,)\n )\n\n api.add_resource(\n HeadingIndicatorResource,\n \"/aircraft/instruments/heading_indicator\",\n resource_class_args=(instruments.heading_indicator,)\n )\n\n api.add_resource(\n VerticalSpeedIndicatorResource,\n \"/aircraft/instruments/vertical_speed_indicator\",\n resource_class_args=(instruments.vertical_speed_indicator,)\n )\n\n\ndef _add_sensor_resources(api, sensors):\n api.add_resource(\n AccelerometerResource,\n \"/aircraft/sensors/accelerometer\",\n resource_class_args=(sensors.accelerometer,)\n )\n\n api.add_resource(\n", "context": "huginn/rest.py\nclass InitialConditionResource(ObjectResource):\n \"\"\"The InitialConditionResource object contain the simulator initial\n conditions\"\"\"\n\n def __init__(self, fdmexec):\n \"\"\"Create a new InitialConditionResource object\n\n Arguments:\n fdmexec: a jsbsim FGFDMExec object\n \"\"\"\n self.fdmexec = fdmexec\n self.initial_condition = InitialCondition(fdmexec)\n self.initial_condition_schema = InitialConditionSchema()\n\n super(InitialConditionResource, self).__init__(\n self.initial_condition,\n self.initial_condition_schema\n )\n\n def update_initial_conditions(self, initial_condition):\n \"\"\"Update the simulator initial conditions\n\n Arguments:\n initial_conditions: a dictionary with the initial conditions of the\n simulator\n \"\"\"\n if \"latitude\" in initial_condition:\n self.initial_condition.latitude = initial_condition[\"latitude\"]\n\n if \"longitude\" in initial_condition:\n self.initial_condition.longitude = initial_condition[\"longitude\"]\n\n if \"airspeed\" in initial_condition:\n self.initial_condition.airspeed = initial_condition[\"airspeed\"]\n\n if \"altitude\" in initial_condition:\n self.initial_condition.altitude = initial_condition[\"altitude\"]\n\n if \"heading\" in initial_condition:\n self.initial_condition.heading = initial_condition[\"heading\"]\n\n def post(self):\n \"\"\"Update the simulator condition when a POST request is executed\"\"\"\n data = request.json\n\n ic_schema = InitialConditionSchema()\n\n initial_condition = ic_schema.load(data)\n\n self.update_initial_conditions(initial_condition.data)\n\n return {\"result\": \"ok\"}\nhuginn/rest.py\nclass ThermometerResource(Resource):\n \"\"\"The ThermometerResource class contains the measurements from the\n temperature sensor\"\"\"\n\n def __init__(self, thermometer):\n \"\"\"Create a new ThermometerResource object\n\n Arguments:\n thermometer: a Thermometer object\n \"\"\"\n self.thermometer = thermometer\n\n def get(self):\n \"\"\"Returns the thermometer measurements\"\"\"\n thermometer_data = {\n \"temperature\": self.thermometer.temperature,\n }\n\n return thermometer_data\nhuginn/rest.py\nclass AccelerationsResource(ObjectResource):\n \"\"\"The AccelerationsResource object returns the fdm accelerations\"\"\"\n\n def __init__(self, fdmexec):\n \"\"\"Create a new AccelerationsResource object\n\n Arguments:\n fdmexec: a jsbsim FGFDMExec object\n \"\"\"\n self.fdmexec = fdmexec\n self.accelerations = Accelerations(self.fdmexec)\n self.acceleration_schema = AccelerationsSchema()\n\n super(AccelerationsResource, self).__init__(self.accelerations,\n self.acceleration_schema)\nhuginn/rest.py\nclass GPSResource(Resource):\n \"\"\"The GPSResource returns the gps data\"\"\"\n\n def __init__(self, gps):\n \"\"\"Create a new GPSResource object\n\n Arguments:\n gps: A GPS object\n \"\"\"\n self.gps = gps\n\n def get(self):\n \"\"\"Return the gps data\"\"\"\n gps_data = {\n \"latitude\": self.gps.latitude,\n \"longitude\": self.gps.longitude,\n \"altitude\": self.gps.altitude,\n \"airspeed\": self.gps.airspeed,\n \"heading\": self.gps.heading\n }\n\n return gps_data\nhuginn/rest.py\nclass HeadingIndicatorResource(ObjectResource):\n \"\"\"The HeadingIndicatorResource object returns the aircraft's heading\n indicator data\"\"\"\n\n def __init__(self, heading_indicator):\n \"\"\"Create a new HeadingIndicatorResource object\n\n Arguments:\n heading_indicator: a HeadingIndicator object\n \"\"\"\n self.heading_indicator = heading_indicator\n self.heading_indicator_schema = HeadingIndicatorSchema()\n\n super(HeadingIndicatorResource, self).__init__(\n self.heading_indicator,\n self.heading_indicator_schema\n )\nhuginn/rest.py\nclass PitotTubeResource(Resource):\n \"\"\"The PitotTubeResource returns the measurements from the pitot tube\"\"\"\n\n def __init__(self, pitot_tube):\n \"\"\"Create a new PitotTubeResource object\n\n Arguments:\n pitot_tube: A PitotTube object\n \"\"\"\n self.pitot_tube = pitot_tube\n\n def get(self):\n \"\"\"Returns the pitot tube measurements\"\"\"\n pitot_tube_data = {\n \"total_pressure\": self.pitot_tube.pressure,\n }\n\n return pitot_tube_data\nhuginn/rest.py\nclass VelocitiesResource(ObjectResource):\n \"\"\"The VelocitiesResource object returns the fdm velocities\"\"\"\n\n def __init__(self, fdmexec):\n \"\"\"Create a new VelocitiesResource object\n\n Arguments:\n fdmexec: a jsbsim FGFDMExec object\n \"\"\"\n self.fdmexec = fdmexec\n self.velocities = Velocities(self.fdmexec)\n self.velocities_schema = VelocitiesSchema()\n\n super(VelocitiesResource, self).__init__(self.velocities,\n self.velocities_schema)\nhuginn/rest.py\nclass AirspeedIndicatorResource(ObjectResource):\n \"\"\"The AirspeedIndicatorResource object returns the aircraft's true\n airspeed\"\"\"\n\n def __init__(self, airspeed_indicator):\n \"\"\"Create a new AirspeedindicatorResource object\n\n Arguments:\n airspeed_indicator: an AirspeedIndicator object\n \"\"\"\n self.airspeed_indicator = airspeed_indicator\n self.airspeed_indicator_schema = AirspeedIndicatorSchema()\n\n super(AirspeedIndicatorResource, self).__init__(\n self.airspeed_indicator,\n self.airspeed_indicator_schema\n )\nhuginn/protocols.py\nclass SimulatorDataProtocol(DatagramProtocol):\n \"\"\"The FDMDataProtocol class is used to transmit the flight dynamics model\n data to the client\"\"\"\n def __init__(self, simulator, remote_host, port):\n self.simulator = simulator\n self.fdmexec = simulator.fdmexec\n self.aircraft = simulator.aircraft\n self.remote_host = remote_host\n self.port = port\n\n def _fill_gps_data(self, simulator_data):\n \"\"\"Fill the gps data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n simulator_data.gps.latitude = self.aircraft.instruments.gps.latitude\n simulator_data.gps.longitude = self.aircraft.instruments.gps.longitude\n simulator_data.gps.altitude = self.aircraft.instruments.gps.altitude\n simulator_data.gps.airspeed = self.aircraft.instruments.gps.airspeed\n simulator_data.gps.heading = self.aircraft.instruments.gps.heading\n\n def _fill_accelerometer_data(self, simulator_data):\n \"\"\"Fill the accelerometer data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n sensors = self.aircraft.sensors\n\n simulator_data.accelerometer.x = sensors.accelerometer.x\n simulator_data.accelerometer.y = sensors.accelerometer.y\n simulator_data.accelerometer.z = sensors.accelerometer.z\n\n def _fill_gyroscope_data(self, simulator_data):\n \"\"\"Fill the gyroscope data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n sensors = self.aircraft.sensors\n\n simulator_data.gyroscope.roll_rate = sensors.gyroscope.roll_rate\n simulator_data.gyroscope.pitch_rate = sensors.gyroscope.pitch_rate\n simulator_data.gyroscope.yaw_rate = sensors.gyroscope.yaw_rate\n\n def _fill_thermometer_data(self, simulator_data):\n \"\"\"Fill the thermometer data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n thermometer = self.aircraft.sensors.thermometer\n\n simulator_data.thermometer.temperature = thermometer.temperature\n\n def _fill_pressure_sensor_data(self, simulator_data):\n \"\"\"Fill the pressure sensor data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n pressure_sensor = self.aircraft.sensors.pressure_sensor\n pitot_tube = self.aircraft.sensors.pitot_tube\n\n simulator_data.pressure_sensor.pressure = pressure_sensor.pressure\n simulator_data.pitot_tube.pressure = pitot_tube.pressure\n\n def _fill_engine_data(self, simulator_data):\n \"\"\"Fill the engine data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n simulator_data.engine.thrust = self.aircraft.engine.thrust\n simulator_data.engine.throttle = self.aircraft.engine.throttle\n\n def _fill_aircraft_controls_data(self, simulator_data):\n \"\"\"Fill the aircraft controls data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n simulator_data.controls.aileron = self.aircraft.controls.aileron\n simulator_data.controls.elevator = self.aircraft.controls.elevator\n simulator_data.controls.rudder = self.aircraft.controls.rudder\n simulator_data.controls.throttle = self.aircraft.controls.throttle\n\n def _fill_ins_data(self, simulator_data):\n \"\"\"Fill the inertial navigation system data in the SimulatorData\n object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n ins = self.aircraft.sensors.inertial_navigation_system\n\n simulator_data.ins.roll = ins.roll\n simulator_data.ins.pitch = ins.pitch\n simulator_data.ins.latitude = ins.latitude\n simulator_data.ins.longitude = ins.longitude\n simulator_data.ins.altitude = ins.altitude\n simulator_data.ins.airspeed = ins.airspeed\n simulator_data.ins.heading = ins.heading\n\n def _fill_accelerations(self, simulator_data):\n \"\"\"Fill the fdm accelerations data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n accelerations = self.simulator.fdm.accelerations\n\n simulator_data.accelerations.x = accelerations.x\n simulator_data.accelerations.y = accelerations.y\n simulator_data.accelerations.z = accelerations.z\n simulator_data.accelerations.p_dot = accelerations.p_dot\n simulator_data.accelerations.q_dot = accelerations.q_dot\n simulator_data.accelerations.r_dot = accelerations.r_dot\n simulator_data.accelerations.u_dot = accelerations.u_dot\n simulator_data.accelerations.v_dot = accelerations.v_dot\n simulator_data.accelerations.w_dot = accelerations.w_dot\n simulator_data.accelerations.gravity = accelerations.gravity\n\n def _fill_velocities(self, simulator_data):\n \"\"\"Fill the fdm velocities data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n velocities = self.simulator.fdm.velocities\n\n simulator_data.velocities.p = velocities.p\n simulator_data.velocities.q = velocities.q\n simulator_data.velocities.r = velocities.r\n simulator_data.velocities.u = velocities.u\n simulator_data.velocities.v = velocities.v\n simulator_data.velocities.w = velocities.w\n simulator_data.velocities.true_airspeed = velocities.true_airspeed\n\n calibrated_airspeed = velocities.calibrated_airspeed\n simulator_data.velocities.calibrated_airspeed = calibrated_airspeed\n\n equivalent_airspeed = velocities.equivalent_airspeed\n simulator_data.velocities.equivalent_airspeed = equivalent_airspeed\n\n simulator_data.velocities.climb_rate = velocities.climb_rate\n simulator_data.velocities.ground_speed = velocities.ground_speed\n\n def _fill_position(self, simulator_data):\n \"\"\"Fill the fdm position data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n position = self.simulator.fdm.position\n\n simulator_data.position.latitude = position.latitude\n simulator_data.position.longitude = position.longitude\n simulator_data.position.altitude = position.altitude\n simulator_data.position.heading = position.heading\n\n def _fill_orientation(self, simulator_data):\n \"\"\"Fill the fdm orientation data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n orientation = self.simulator.fdm.orientation\n\n simulator_data.orientation.phi = orientation.phi\n simulator_data.orientation.theta = orientation.theta\n simulator_data.orientation.psi = orientation.psi\n\n def _fill_atmosphere(self, simulator_data):\n \"\"\"Fill the fdm atmospheric data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n atmosphere = self.simulator.fdm.atmosphere\n\n simulator_data.atmosphere.pressure = atmosphere.pressure\n\n sea_level_pressure = atmosphere.sea_level_pressure\n simulator_data.atmosphere.sea_level_pressure = sea_level_pressure\n\n simulator_data.atmosphere.temperature = atmosphere.temperature\n\n sea_level_temperature = atmosphere.sea_level_temperature\n simulator_data.atmosphere.sea_level_temperature = sea_level_temperature\n\n simulator_data.atmosphere.density = atmosphere.density\n\n sea_level_density = atmosphere.sea_level_density\n simulator_data.atmosphere.sea_level_density = sea_level_density\n\n def _fill_forces(self, simulator_data):\n \"\"\"Fill the fdm atmospheric data in the SimulatorData object\n\n Arguments:\n simulator_data: the protocol buffer SimulatorData object\n \"\"\"\n forces = self.simulator.fdm.forces\n\n simulator_data.forces.x_body = forces.x_body\n simulator_data.forces.y_body = forces.y_body\n simulator_data.forces.z_body = forces.z_body\n simulator_data.forces.x_wind = forces.x_wind\n simulator_data.forces.y_wind = forces.y_wind\n simulator_data.forces.z_wind = forces.z_wind\n simulator_data.forces.x_total = forces.x_total\n simulator_data.forces.y_total = forces.y_total\n simulator_data.forces.z_total = forces.z_total\n\n def get_simulator_data(self):\n \"\"\"Return the simulator data\"\"\"\n simulator_data = fdm_pb2.SimulatorData()\n\n simulator_data.time = self.fdmexec.GetSimTime()\n\n self._fill_gps_data(simulator_data)\n self._fill_accelerometer_data(simulator_data)\n self._fill_gyroscope_data(simulator_data)\n self._fill_thermometer_data(simulator_data)\n self._fill_pressure_sensor_data(simulator_data)\n self._fill_engine_data(simulator_data)\n self._fill_aircraft_controls_data(simulator_data)\n self._fill_ins_data(simulator_data)\n self._fill_accelerations(simulator_data)\n self._fill_velocities(simulator_data)\n self._fill_position(simulator_data)\n self._fill_orientation(simulator_data)\n self._fill_atmosphere(simulator_data)\n self._fill_forces(simulator_data)\n\n return simulator_data\n\n def send_simulator_data(self):\n \"\"\"Transmit the simulator data\"\"\"\n simulator_data = self.get_simulator_data()\n\n datagram = simulator_data.SerializeToString()\n\n self.transport.write(datagram, (self.remote_host, self.port))\nhuginn/rest.py\nclass PressureSensorResource(Resource):\n \"\"\"The PressureSensorResource class returns the pressure sensor\n measurements\"\"\"\n\n def __init__(self, pressure_sensor):\n \"\"\"Create a new PressureSensorResource object\n\n Arguments:\n pressure_sensor: a PressureSensor object\n \"\"\"\n self.pressure_sensor = pressure_sensor\n\n def get(self):\n \"\"\"Returns the pressure sensor data\"\"\"\n pressure_sensor_data = {\n \"static_pressure\": self.pressure_sensor.pressure,\n }\n\n return pressure_sensor_data\nhuginn/http.py\nclass SimulatorDataWebSocketFactory(WebSocketServerFactory):\n \"\"\"The SimulatorDataWebSocketFactory class is a factory that creates the\n protocol objects for the simulator data transmission through web sockets\"\"\"\n def __init__(self, simulator, database, *args, **kwargs):\n WebSocketServerFactory.__init__(self, *args, **kwargs)\n\n self.simulator = simulator\n self.database = database\nhuginn/rest.py\nclass InertialNavigationSystemResource(Resource):\n \"\"\"The InertialNavigationSystemResource returns the measurements from the\n inertial navigation system\"\"\"\n\n def __init__(self, inertial_navigation_system):\n \"\"\"Create a new InertialNavigationSystemResource object\n\n Arguments:\n inertial_navigation_system: An InertialNavigationSystem object\n \"\"\"\n self.inertial_navigation_system = inertial_navigation_system\n\n def get(self):\n \"\"\"Returns the ins measurements\"\"\"\n inertial_navigation_system_data = {\n \"latitude\": self.inertial_navigation_system.latitude,\n \"longitude\": self.inertial_navigation_system.longitude,\n \"altitude\": self.inertial_navigation_system.altitude,\n \"airspeed\": self.inertial_navigation_system.airspeed,\n \"heading\": self.inertial_navigation_system.heading,\n \"roll\": self.inertial_navigation_system.roll,\n \"pitch\": self.inertial_navigation_system.pitch,\n }\n\n return inertial_navigation_system_data\nhuginn/rest.py\nclass FlightControlsResource(Resource):\n \"\"\"The FlightControlsResource return the flight controls values\"\"\"\n\n def __init__(self, controls):\n \"\"\"Create a new FlightControlsResource object\n\n Arguments:\n controls: A Controls object\n \"\"\"\n self.controls = controls\n\n def get(self):\n \"\"\"returns the flight controls values\"\"\"\n flight_controls_data = {\n \"aileron\": self.controls.aileron,\n \"elevator\": self.controls.elevator,\n \"rudder\": self.controls.rudder,\n \"throttle\": self.controls.throttle,\n }\n\n return flight_controls_data\nhuginn/rest.py\nclass PositionResource(ObjectResource):\n \"\"\"The PositionResource object contain the aircraft position data\"\"\"\n\n def __init__(self, fdmexec):\n \"\"\"Create a new PositionResource object\n\n Arguments:\n fdmexec: a jsbsim FGFDMExec object\n \"\"\"\n self.fdmexec = fdmexec\n self.position = Position(fdmexec)\n self.position_schema = PositionSchema()\n\n super(PositionResource, self).__init__(\n self.position,\n self.position_schema\n )\nhuginn/rest.py\nclass WaypointResource(Resource):\n \"\"\"The WaypointResource is used to ad, delete and update waypoints\"\"\"\n def __init__(self, db):\n self.db = db\n\n @marshal_with(request_models.waypoint)\n def get(self, name):\n \"\"\"Get the waypoint's data\"\"\"\n Document = Query()\n\n waypoints = self.db.search(Document.type == \"waypoints\")[0]\n\n waypoint = waypoints[\"waypoints\"].get(name)\n\n if waypoint is not None:\n return waypoint\n else:\n abort(404, error=\"waypoint doesn't exist\", name=name)\n\n @marshal_with(request_models.waypoint)\n def post(self, name):\n \"\"\"Add a new waypoint or update an existing waypoint's data\"\"\"\n waypoint = request_parsers.waypoint.parse_args()\n waypoint[\"name\"] = name\n\n Document = Query()\n\n waypoints = self.db.search(Document.type == \"waypoints\")[0]\n\n waypoints[\"waypoints\"][name] = waypoint\n\n self.db.update(waypoints, Document.type == \"waypoints\")\n\n return waypoint\n\n @marshal_with(request_models.waypoint)\n def delete(self, name):\n \"\"\"Delete a waypoint\"\"\"\n Document = Query()\n\n waypoints = self.db.search(Document.type == \"waypoints\")[0]\n\n waypoint = waypoints[\"waypoints\"].get(name)\n\n if waypoint is not None:\n del waypoints[\"waypoints\"][name]\n return waypoint\n else:\n abort(404, error=\"waypoint doesn't exist\", name=name)\nhuginn/rest.py\nclass AccelerometerResource(Resource):\n \"\"\"The AccelerometerResource returns the accelerometer measurements\"\"\"\n\n def __init__(self, accelerometer):\n \"\"\"Create a new AccelerometerResource object\n\n Arguments:\n accelerometer: an Accelerometer object\n \"\"\"\n self.accelerometer = accelerometer\n\n def get(self):\n \"\"\"Returns the accelerometer measurements\"\"\"\n accelerometer_data = {\n \"x\": self.accelerometer.x,\n \"y\": self.accelerometer.y,\n \"z\": self.accelerometer.z,\n }\n\n return accelerometer_data\nhuginn/protocols.py\nclass ControlsProtocol(DatagramProtocol):\n \"\"\"The ControlsProtocol is used to receive and update tha aircraft's\n controls\"\"\"\n def __init__(self, fdmexec):\n self.fdmexec = fdmexec\n\n def update_aircraft_controls(self, aileron, elevator, rudder, throttle):\n \"\"\"Set the new aircraft controls values\"\"\"\n if aileron > 1.0:\n aileron = 1.0\n elif aileron < -1.0:\n aileron = -1.0\n\n self.fdmexec.GetFCS().SetDaCmd(aileron)\n\n if elevator > 1.0:\n elevator = 1.0\n elif elevator < -1.0:\n elevator = -1.0\n\n self.fdmexec.GetFCS().SetDeCmd(elevator)\n\n if rudder > 1.0:\n rudder = 1.0\n elif rudder < -1.0:\n rudder = -1.0\n\n self.fdmexec.GetFCS().SetDrCmd(rudder)\n\n if throttle > 1.0:\n throttle = 1.0\n elif throttle < 0.0:\n throttle = 0.0\n\n for i in range(self.fdmexec.GetPropulsion().GetNumEngines()):\n self.fdmexec.GetFCS().SetThrottleCmd(i, throttle)\n\n def datagramReceived(self, datagram, addr):\n controls = fdm_pb2.Controls()\n\n try:\n controls.ParseFromString(datagram)\n except DecodeError:\n logger.exception(\"Failed to parse control data\")\n print(\"Failed to parse control data\")\n return\n\n self.update_aircraft_controls(controls.aileron,\n controls.elevator,\n controls.rudder,\n controls.throttle)\nhuginn/rest.py\nclass AtmosphereResource(ObjectResource):\n \"\"\"The AtmosphereResource object return the fdm atmospheric data\"\"\"\n\n def __init__(self, fdmexec):\n \"\"\"Create a new AtmosphereResource object\n\n Arguments:\n fdmexec: a jsbsim FGFDMExec object\n \"\"\"\n self.fdmexec = fdmexec\n self.atmosphere = Atmosphere(fdmexec)\n self.atmosphere_schema = AtmosphereShema()\n\n super(AtmosphereResource, self).__init__(self.atmosphere,\n self.atmosphere_schema)\nhuginn/rest.py\nclass AircraftResource(Resource):\n \"\"\"The AircraftResource returns infomration about the aircraft\"\"\"\n\n def __init__(self, aircraft):\n \"\"\"Create a new AircraftResource object\n\n Arguments:\n aircraft: an Aircraft object\n \"\"\"\n self.aircraft = aircraft\n\n def get(self):\n \"\"\"Get the aircraft information\"\"\"\n return {\"type\": self.aircraft.type}\nhuginn/rest.py\nclass SimulatorControlResource(Resource):\n \"\"\"The SimulatorControlResource provides the endpoint that is used to\n control the simulator\"\"\"\n\n def __init__(self, simulator):\n \"\"\"Create a new SimulatorControlResource object\n\n Arguments:\n simulator: a Simulator object\n \"\"\"\n self.simulator = simulator\n\n def get(self):\n \"\"\"Returns the simulator state\"\"\"\n simulator_state = {\n \"time\": self.simulator.simulation_time,\n \"dt\": self.simulator.dt,\n \"running\": not self.simulator.is_paused(),\n \"crashed\": self.simulator.crashed\n }\n\n return simulator_state\n\n def execute_command(self, command, params=None):\n \"\"\"Execute the simulator command\n\n Arguments:\n command: the command to execute\n params: the parameters of the command\n \"\"\"\n if command == \"reset\":\n self.simulator.reset()\n\n response = {\"result\": \"ok\",\n \"command\": command}\n elif command == \"pause\":\n self.simulator.pause()\n\n response = {\"result\": \"ok\",\n \"command\": command}\n elif command == \"resume\":\n self.simulator.resume()\n\n response = {\"result\": \"ok\",\n \"command\": command}\n elif command == \"step\":\n self.simulator.step()\n\n response = {\"result\": \"ok\",\n \"command\": command}\n elif command == \"run_for\":\n if params:\n time_to_run = params[\"time_to_run\"]\n else:\n time_to_run = None\n\n if not time_to_run:\n response = {\"error\": \"no time to run provided\",\n \"command\": command}\n else:\n self.simulator.run_for(time_to_run)\n\n response = {\"result\": \"ok\",\n \"command\": \"run_for\"}\n elif command == \"start_paused\":\n self.simulator.start_paused = True\n\n response = {\"result\": \"ok\",\n \"command\": \"start_paused\"}\n elif command == \"start_running\":\n self.simulator.start_paused = False\n\n response = {\"result\": \"ok\",\n \"command\": \"start_running\"}\n else:\n response = {\"error\": \"unknown command\",\n \"command\": command}\n\n return response\n\n def post(self):\n \"\"\"Execute a command on the simulator\"\"\"\n parser = reqparse.RequestParser()\n\n parser.add_argument(\"command\", type=str, required=True)\n parser.add_argument(\"time_to_run\", type=float)\n parser.add_argument(\"paused\", type=bool)\n\n args = parser.parse_args()\n\n command = args.command\n\n params = {}\n\n if args.time_to_run:\n params[\"time_to_run\"] = args.time_to_run\n\n if args.paused:\n params[\"paused\"] = args.paused\n\n return self.execute_command(command, params)\nhuginn/rest.py\nclass AttitudeIndicatorResource(ObjectResource):\n \"\"\"The AttitudeIndicatorResource object returns the aircraft's attitude\n indicator data\"\"\"\n\n def __init__(self, attitude_indicator):\n \"\"\"Create a new AttitudeIndicatorResource object\n\n Arguments:\n attitude_indicator: an AttitudeIndicator object\n \"\"\"\n self.attitude_indicator = attitude_indicator\n self.attitude_indicator_schema = AttitudeIndicatorSchema()\n\n super(AttitudeIndicatorResource, self).__init__(\n self.attitude_indicator,\n self.attitude_indicator_schema\n )\nhuginn/rest.py\nclass AltimeterResource(ObjectResource):\n \"\"\"The AltimeterResource object returns the aircraft's altimeter data\"\"\"\n\n def __init__(self, altimeter):\n \"\"\"Create a new AltimeterResource object\n\n Arguments:\n altimeter: an Altimeter object\n \"\"\"\n self.altimeter = altimeter\n self.altimeter_schema = AltimeterSchema()\n\n super(AltimeterResource, self).__init__(\n self.altimeter,\n self.altimeter_schema\n )\nhuginn/rest.py\nclass GyroscopeResource(Resource):\n \"\"\"The GyroscopeResource returns the data from the gyroscope sensor\"\"\"\n\n def __init__(self, gyroscope):\n \"\"\"Create a new GyroscopeResource object\n\n Arguments:\n gyroscope: A Gyroscope object\n \"\"\"\n self.gyroscope = gyroscope\n\n def get(self):\n \"\"\"Returns the gyroscope measurements\"\"\"\n gyroscope_data = {\n \"roll_rate\": self.gyroscope.roll_rate,\n \"pitch_rate\": self.gyroscope.pitch_rate,\n \"yaw_rate\": self.gyroscope.yaw_rate\n }\n\n return gyroscope_data\nhuginn/http.py\nclass SimulatorDataWebSocketProtocol(WebSocketServerProtocol):\n \"\"\"The SimulatorDataWebSocketProtocol class if the protocol class that\n transmits the simulator data using a web socket\"\"\"\n def onMessage(self, payload, isBinary):\n try:\n request = json.loads(payload)\n except:\n logger.exception(\"failed to parse websocket command\")\n return\n\n if \"command\" not in request:\n logger.debug(\"The request doesn't contain a command field\")\n return\n\n command = request[\"command\"]\n\n if command == \"flight_data\":\n self.send_flight_data()\n elif command == \"waypoints\":\n self.send_waypoint_data()\n else:\n logger.warning(\"Unknown web socket command %s\", command)\n\n def send_flight_data(self):\n \"\"\"Send the fdm data\"\"\"\n fdm = self.factory.simulator.fdm\n\n flight_data = {\n \"command\": \"flight_data\",\n \"data\": {\n \"roll\": fdm.orientation.phi,\n \"pitch\": fdm.orientation.theta,\n \"airspeed\": fdm.velocities.true_airspeed,\n \"latitude\": fdm.position.latitude,\n \"longitude\": fdm.position.longitude,\n \"altitude\": fdm.position.altitude,\n \"heading\": fdm.position.heading,\n \"climb_rate\": fdm.velocities.climb_rate\n },\n }\n\n payload = json.dumps(flight_data).encode(\"utf8\")\n\n self.sendMessage(payload, False)\n\n def send_waypoint_data(self):\n \"\"\"Send the waypoint information\"\"\"\n Document = Query()\n\n waypoints = self.factory.database.search(\n Document.type == \"waypoints\")[0]\n\n response = {\n \"command\": \"waypoints\",\n \"data\": waypoints[\"waypoints\"].values()\n }\n\n payload = json.dumps(response).encode(\"utf8\")\n\n self.sendMessage(payload, False)\nhuginn/rest.py\nclass OrientationResource(ObjectResource):\n \"\"\"The OrientationResource object returns the orientations of the\n aircraft\"\"\"\n\n def __init__(self, fdmexec):\n \"\"\"Create a new OrientationResource object\n\n Arguments:\n fdmexec: a jsbsim FGFDMExec object\n \"\"\"\n self.fdmexec = fdmexec\n self.orientation = Orientation(fdmexec)\n self.orientation_schema = OrientationSchema()\n\n super(OrientationResource, self).__init__(self.orientation,\n self.orientation_schema)\nhuginn/rest.py\nclass FDMResource(Resource):\n \"\"\"The FDMResource will return the data from the flight dynamics model\"\"\"\n\n def __init__(self, fdm, aircraft):\n \"\"\"Create a new FDMResource object\n\n Arguments:\n fdm: an FDM object\n aircraft: an aircraft object\n \"\"\"\n self.fdm = fdm\n self.aircraft = aircraft\n\n def get(self):\n \"\"\"Get the fdm data\"\"\"\n sensors = self.aircraft.sensors\n\n flight_data = {\n \"time\": self.fdm.fdmexec.GetSimTime(),\n \"dt\": self.fdm.fdmexec.GetDeltaT(),\n \"latitude\": self.fdm.position.latitude,\n \"longitude\": self.fdm.position.longitude,\n \"altitude\": self.fdm.position.altitude,\n \"airspeed\": self.fdm.velocities.true_airspeed,\n \"heading\": self.fdm.orientation.psi,\n \"x_acceleration\": self.fdm.accelerations.x,\n \"y_acceleration\": self.fdm.accelerations.y,\n \"z_acceleration\": self.fdm.accelerations.z,\n \"roll_rate\": self.fdm.velocities.p,\n \"pitch_rate\": self.fdm.velocities.q,\n \"yaw_rate\": self.fdm.velocities.r,\n \"temperature\": self.fdm.atmosphere.temperature,\n \"static_pressure\": self.fdm.atmosphere.pressure,\n \"total_pressure\": sensors.pitot_tube.true_pressure,\n \"roll\": self.fdm.orientation.phi,\n \"pitch\": self.fdm.orientation.theta,\n \"climb_rate\": self.fdm.velocities.climb_rate\n }\n\n return flight_data\nhuginn/rest.py\nclass VerticalSpeedIndicatorResource(ObjectResource):\n \"\"\"The VerticalSpeedIndicatorResource object returns the aircraft's heading\n indicator data\"\"\"\n\n def __init__(self, vertical_speed_indicator):\n \"\"\"Create a new VerticalSpeedIndicatorResource object\n\n Arguments:\n vertical_speed_indicator: a VerticalSpeedIndicator object\n \"\"\"\n self.vertical_speed_indicator = vertical_speed_indicator\n self.vertical_speed_indicator_schema = VerticalSpeedIndicatorSchema()\n\n super(VerticalSpeedIndicatorResource, self).__init__(\n self.vertical_speed_indicator,\n self.vertical_speed_indicator_schema\n )\nhuginn/rest.py\nclass WaypointsResource(Resource):\n \"\"\"The WaypointsResource is used to retrieve all the available waypoints\"\"\"\n def __init__(self, db):\n self.db = db\n\n @marshal_with(request_models.waypoint)\n def get(self):\n \"\"\"Get a list of the available waypoints\"\"\"\n Document = Query()\n\n waypoints = self.db.search(Document.type == \"waypoints\")[0]\n\n return waypoints[\"waypoints\"].values()\nhuginn/rest.py\nclass ForcesResource(ObjectResource):\n \"\"\"The ForcesResource object contains the forces that act on the\n aircraft\"\"\"\n\n def __init__(self, fdmexec):\n \"\"\"Create a new ForcesResource object\n\n Arguments:\n fdmexec: a jsbsim FGFDMExec object\n \"\"\"\n self.fdmexec = fdmexec\n self.forces = Forces(fdmexec)\n self.forces_schema = ForcesSchema()\n\n super(ForcesResource, self).__init__(self.forces,\n self.forces_schema)\nhuginn/rest.py\nclass EngineResource(Resource):\n \"\"\"The EngineResource class returns the engine data\"\"\"\n def __init__(self, engine):\n \"\"\"Create a new EngineResource object\n\n Arguments:\n engine: An Engine object\n \"\"\"\n self.engine = engine\n\n def get(self):\n \"\"\"Returns the engine data\"\"\"\n engine_data = {\n \"thrust\": self.engine.thrust,\n \"throttle\": self.engine.throttle,\n }\n\n return engine_data\n", "answers": [" GyroscopeResource,"], "length": 2638, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "34c565cc605e911208da5d857eaf1c4af5e31f01f6e5a7f6"} {"input": "import getpass\nimport netrc\nimport optparse\nimport os\nimport shlex\nimport sys\nimport textwrap\nimport time\nimport urllib.request\n import kerberos\nimport event_log\nimport gitc_utils\n import trace\nfrom color import SetDefaultColoring\nfrom repo_trace import SetTrace\nfrom git_command import user_agent\nfrom git_config import RepoConfig\nfrom git_trace2_event_log import EventLog\nfrom command import InteractiveCommand\nfrom command import MirrorSafeCommand\nfrom command import GitcAvailableCommand, GitcClientCommand\nfrom subcmds.version import Version\nfrom editor import Editor\nfrom error import DownloadError\nfrom error import InvalidProjectGroupsError\nfrom error import ManifestInvalidRevisionError\nfrom error import ManifestParseError\nfrom error import NoManifestException\nfrom error import NoSuchProjectError\nfrom error import RepoChangedException\nfrom manifest_xml import GitcClient, RepoClient\nfrom pager import RunPager, TerminatePager\nfrom wrapper import WrapperPath, Wrapper\nfrom subcmds import all_commands\n def __init__(self, repodir):\n self.repodir = repodir\n self.commands = all_commands\n\n def _PrintHelp(self, short: bool = False, all_commands: bool = False):\n \"\"\"Show --help screen.\"\"\"\n global_options.print_help()\n print()\n if short:\n commands = ' '.join(sorted(self.commands))\n wrapped_commands = textwrap.wrap(commands, width=77)\n print('Available commands:\\n %s' % ('\\n '.join(wrapped_commands),))\n print('\\nRun `repo help ` for command-specific details.')\n print('Bug reports:', Wrapper().BUG_URL)\n else:\n cmd = self.commands['help']()\n if all_commands:\n cmd.PrintAllCommandsBody()\n else:\n cmd.PrintCommonCommandsBody()\n\n def _ParseArgs(self, argv):\n \"\"\"Parse the main `repo` command line options.\"\"\"\n for i, arg in enumerate(argv):\n if not arg.startswith('-'):\n name = arg\n glob = argv[:i]\n argv = argv[i + 1:]\n break\n else:\n name = None\n glob = argv\n argv = []\n gopts, _gargs = global_options.parse_args(glob)\n\n if name:\n name, alias_args = self._ExpandAlias(name)\n argv = alias_args + argv\n\n return (name, gopts, argv)\n\n def _ExpandAlias(self, name):\n \"\"\"Look up user registered aliases.\"\"\"\n # We don't resolve aliases for existing subcommands. This matches git.\n if name in self.commands:\n return name, []\n\n key = 'alias.%s' % (name,)\n alias = RepoConfig.ForRepository(self.repodir).GetString(key)\n if alias is None:\n alias = RepoConfig.ForUser().GetString(key)\n if alias is None:\n return name, []\n\n args = alias.strip().split(' ', 1)\n name = args[0]\n if len(args) == 2:\n args = shlex.split(args[1])\n else:\n args = []\n return name, args\n\n def _Run(self, name, gopts, argv):\n \"\"\"Execute the requested subcommand.\"\"\"\n result = 0\n\n if gopts.trace:\n SetTrace()\n\n # Handle options that terminate quickly first.\n if gopts.help or gopts.help_all:\n self._PrintHelp(short=False, all_commands=gopts.help_all)\n return 0\n elif gopts.show_version:\n # Always allow global --version regardless of subcommand validity.\n name = 'version'\n elif gopts.show_toplevel:\n print(os.path.dirname(self.repodir))\n return 0\n elif not name:\n # No subcommand specified, so show the help/subcommand.\n self._PrintHelp(short=True)\n return 1\n\n SetDefaultColoring(gopts.color)\n\n git_trace2_event_log = EventLog()\n outer_client = RepoClient(self.repodir)\n repo_client = outer_client\n if gopts.submanifest_path:\n repo_client = RepoClient(self.repodir,\n submanifest_path=gopts.submanifest_path,\n outer_client=outer_client)\n gitc_manifest = None\n gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())\n if gitc_client_name:\n gitc_manifest = GitcClient(self.repodir, gitc_client_name)\n repo_client.isGitcClient = True\n\n try:\n cmd = self.commands[name](\n repodir=self.repodir,\n client=repo_client,\n manifest=repo_client.manifest,\n outer_client=outer_client,\n outer_manifest=outer_client.manifest,\n gitc_manifest=gitc_manifest,\n git_event_log=git_trace2_event_log)\n except KeyError:\n print(\"repo: '%s' is not a repo command. See 'repo help'.\" % name,\n file=sys.stderr)\n return 1\n\n Editor.globalConfig = cmd.client.globalConfig\n\n if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:\n print(\"fatal: '%s' requires a working directory\" % name,\n file=sys.stderr)\n return 1\n\n", "context": "command.py\nclass GitcAvailableCommand(object):\n \"\"\"Command that requires GITC to be available, but does\n not require the local client to be a GITC client.\n \"\"\"\nerror.py\nclass NoManifestException(Exception):\n \"\"\"The required manifest does not exist.\n \"\"\"\n\n def __init__(self, path, reason):\n super().__init__(path, reason)\n self.path = path\n self.reason = reason\n\n def __str__(self):\n return self.reason\nmanifest_xml.py\nclass RepoClient(XmlManifest):\n \"\"\"Manages a repo client checkout.\"\"\"\n\n def __init__(self, repodir, manifest_file=None, submanifest_path='', **kwargs):\n self.isGitcClient = False\n submanifest_path = submanifest_path or ''\n if submanifest_path:\n self._CheckLocalPath(submanifest_path)\n prefix = os.path.join(repodir, SUBMANIFEST_DIR, submanifest_path)\n else:\n prefix = repodir\n\n if os.path.exists(os.path.join(prefix, LOCAL_MANIFEST_NAME)):\n print('error: %s is not supported; put local manifests in `%s` instead' %\n (LOCAL_MANIFEST_NAME, os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME)),\n file=sys.stderr)\n sys.exit(1)\n\n if manifest_file is None:\n manifest_file = os.path.join(prefix, MANIFEST_FILE_NAME)\n local_manifests = os.path.abspath(os.path.join(prefix, LOCAL_MANIFESTS_DIR_NAME))\n super().__init__(repodir, manifest_file, local_manifests,\n submanifest_path=submanifest_path, **kwargs)\n\n # TODO: Completely separate manifest logic out of the client.\n self.manifest = self\nerror.py\nclass RepoChangedException(Exception):\n \"\"\"Thrown if 'repo sync' results in repo updating its internal\n repo or manifest repositories. In this special case we must\n use exec to re-execute repo with the new code and manifest.\n \"\"\"\n\n def __init__(self, extra_args=None):\n super().__init__(extra_args)\n self.extra_args = extra_args or []\nsubcmds/version.py\nclass Version(Command, MirrorSafeCommand):\n wrapper_version = None\n wrapper_path = None\n\n COMMON = False\n helpSummary = \"Display the version of repo\"\n helpUsage = \"\"\"\n%prog\n\"\"\"\n\n def Execute(self, opt, args):\n rp = self.manifest.repoProject\n rem = rp.GetRemote(rp.remote.name)\n branch = rp.GetBranch('default')\n\n # These might not be the same. Report them both.\n src_ver = RepoSourceVersion()\n rp_ver = rp.bare_git.describe(HEAD)\n print('repo version %s' % rp_ver)\n print(' (from %s)' % rem.url)\n print(' (tracking %s)' % branch.merge)\n print(' (%s)' % rp.bare_git.log('-1', '--format=%cD', HEAD))\n\n if self.wrapper_path is not None:\n print('repo launcher version %s' % self.wrapper_version)\n print(' (from %s)' % self.wrapper_path)\n\n if src_ver != rp_ver:\n print(' (currently at %s)' % src_ver)\n\n print('repo User-Agent %s' % user_agent.repo)\n print('git %s' % git.version_tuple().full)\n print('git User-Agent %s' % user_agent.git)\n print('Python %s' % sys.version)\n uname = platform.uname()\n if sys.version_info.major < 3:\n # Python 3 returns a named tuple, but Python 2 is simpler.\n print(uname)\n else:\n print('OS %s %s (%s)' % (uname.system, uname.release, uname.version))\n print('CPU %s (%s)' %\n (uname.machine, uname.processor if uname.processor else 'unknown'))\n print('Bug reports:', Wrapper().BUG_URL)\ngit_command.py\nGIT = 'git'\nMIN_GIT_VERSION_SOFT = (1, 9, 1)\nMIN_GIT_VERSION_HARD = (1, 7, 2)\nGIT_DIR = 'GIT_DIR'\nLAST_GITDIR = None\nLAST_CWD = None\n LAST_CWD = cwd\n LAST_GITDIR = env[GIT_DIR]\nclass _GitCall(object):\nclass UserAgent(object):\nclass GitCommand(object):\n def version_tuple(self):\n def __getattr__(self, name):\n def fun(*cmdv):\ndef RepoSourceVersion():\n def os(self):\n def repo(self):\n def git(self):\ndef git_require(min_version, fail=False, msg=''):\n def __init__(self,\n project,\n cmdv,\n bare=False,\n input=None,\n capture_stdout=False,\n capture_stderr=False,\n merge_output=False,\n disable_editor=False,\n ssh_proxy=None,\n cwd=None,\n gitdir=None,\n objdir=None):\n def _GetBasicEnv():\n def Wait(self):\nmanifest_xml.py\nclass GitcClient(RepoClient, GitcManifest):\n \"\"\"Manages a GitC client checkout.\"\"\"\n\n def __init__(self, repodir, gitc_client_name):\n \"\"\"Initialize the GitcManifest object.\"\"\"\n self.gitc_client_name = gitc_client_name\n self.gitc_client_dir = os.path.join(gitc_utils.get_gitc_manifest_dir(),\n gitc_client_name)\n\n super().__init__(repodir, os.path.join(self.gitc_client_dir, '.manifest'))\n self.isGitcClient = True\ncommand.py\nclass InteractiveCommand(Command):\n \"\"\"Command which requires user interaction on the tty and\n must not run within a pager, even if the user asks to.\n \"\"\"\n\n def WantPager(self, _opt):\n return False\ncommand.py\nclass MirrorSafeCommand(object):\n \"\"\"Command permits itself to run within a mirror,\n and does not require a working directory.\n \"\"\"\ncommand.py\nclass GitcClientCommand(object):\n \"\"\"Command that requires the local client to be a GITC\n client.\n \"\"\"\nerror.py\nclass DownloadError(Exception):\n \"\"\"Cannot download a repository.\n \"\"\"\n\n def __init__(self, reason):\n super().__init__(reason)\n self.reason = reason\n\n def __str__(self):\n return self.reason\nerror.py\nclass ManifestInvalidRevisionError(ManifestParseError):\n \"\"\"The revision value in a project is incorrect.\n \"\"\"\ngit_config.py\nclass RepoConfig(GitConfig):\n \"\"\"User settings for repo itself.\"\"\"\n\n _USER_CONFIG = '~/.repoconfig/config'\ngit_trace2_event_log.py\nclass EventLog(object):\n \"\"\"Event log that records events that occurred during a repo invocation.\n\n Events are written to the log as a consecutive JSON entries, one per line.\n Entries follow the git trace2 EVENT format.\n\n Each entry contains the following common keys:\n - event: The event name\n - sid: session-id - Unique string to allow process instance to be identified.\n - thread: The thread name.\n - time: is the UTC time of the event.\n\n Valid 'event' names and event specific fields are documented here:\n https://git-scm.com/docs/api-trace2#_event_format\n \"\"\"\n\n def __init__(self, env=None):\n \"\"\"Initializes the event log.\"\"\"\n self._log = []\n # Try to get session-id (sid) from environment (setup in repo launcher).\n KEY = 'GIT_TRACE2_PARENT_SID'\n if env is None:\n env = os.environ\n\n now = datetime.datetime.utcnow()\n\n # Save both our sid component and the complete sid.\n # We use our sid component (self._sid) as the unique filename prefix and\n # the full sid (self._full_sid) in the log itself.\n self._sid = 'repo-%s-P%08x' % (now.strftime('%Y%m%dT%H%M%SZ'), os.getpid())\n parent_sid = env.get(KEY)\n # Append our sid component to the parent sid (if it exists).\n if parent_sid is not None:\n self._full_sid = parent_sid + '/' + self._sid\n else:\n self._full_sid = self._sid\n\n # Set/update the environment variable.\n # Environment handling across systems is messy.\n try:\n env[KEY] = self._full_sid\n except UnicodeEncodeError:\n env[KEY] = self._full_sid.encode()\n\n # Add a version event to front of the log.\n self._AddVersionEvent()\n\n @property\n def full_sid(self):\n return self._full_sid\n\n def _AddVersionEvent(self):\n \"\"\"Adds a 'version' event at the beginning of current log.\"\"\"\n version_event = self._CreateEventDict('version')\n version_event['evt'] = \"2\"\n version_event['exe'] = RepoSourceVersion()\n self._log.insert(0, version_event)\n\n def _CreateEventDict(self, event_name):\n \"\"\"Returns a dictionary with the common keys/values for git trace2 events.\n\n Args:\n event_name: The event name.\n\n Returns:\n Dictionary with the common event fields populated.\n \"\"\"\n return {\n 'event': event_name,\n 'sid': self._full_sid,\n 'thread': threading.currentThread().getName(),\n 'time': datetime.datetime.utcnow().isoformat() + 'Z',\n }\n\n def StartEvent(self):\n \"\"\"Append a 'start' event to the current log.\"\"\"\n start_event = self._CreateEventDict('start')\n start_event['argv'] = sys.argv\n self._log.append(start_event)\n\n def ExitEvent(self, result):\n \"\"\"Append an 'exit' event to the current log.\n\n Args:\n result: Exit code of the event\n \"\"\"\n exit_event = self._CreateEventDict('exit')\n\n # Consider 'None' success (consistent with event_log result handling).\n if result is None:\n result = 0\n exit_event['code'] = result\n self._log.append(exit_event)\n\n def CommandEvent(self, name, subcommands):\n \"\"\"Append a 'command' event to the current log.\n\n Args:\n name: Name of the primary command (ex: repo, git)\n subcommands: List of the sub-commands (ex: version, init, sync)\n \"\"\"\n command_event = self._CreateEventDict('command')\n command_event['name'] = name\n command_event['subcommands'] = subcommands\n self._log.append(command_event)\n\n def LogConfigEvents(self, config, event_dict_name):\n \"\"\"Append a |event_dict_name| event for each config key in |config|.\n\n Args:\n config: Configuration dictionary.\n event_dict_name: Name of the event dictionary for items to be logged under.\n \"\"\"\n for param, value in config.items():\n event = self._CreateEventDict(event_dict_name)\n event['param'] = param\n event['value'] = value\n self._log.append(event)\n\n def DefParamRepoEvents(self, config):\n \"\"\"Append a 'def_param' event for each repo.* config key to the current log.\n\n Args:\n config: Repo configuration dictionary\n \"\"\"\n # Only output the repo.* config parameters.\n repo_config = {k: v for k, v in config.items() if k.startswith('repo.')}\n self.LogConfigEvents(repo_config, 'def_param')\n\n def GetDataEventName(self, value):\n \"\"\"Returns 'data-json' if the value is an array else returns 'data'.\"\"\"\n return 'data-json' if value[0] == '[' and value[-1] == ']' else 'data'\n\n def LogDataConfigEvents(self, config, prefix):\n \"\"\"Append a 'data' event for each config key/value in |config| to the current log.\n\n For each keyX and valueX of the config, \"key\" field of the event is '|prefix|/keyX'\n and the \"value\" of the \"key\" field is valueX.\n\n Args:\n config: Configuration dictionary.\n prefix: Prefix for each key that is logged.\n \"\"\"\n for key, value in config.items():\n event = self._CreateEventDict(self.GetDataEventName(value))\n event['key'] = f'{prefix}/{key}'\n event['value'] = value\n self._log.append(event)\n\n def ErrorEvent(self, msg, fmt):\n \"\"\"Append a 'error' event to the current log.\"\"\"\n error_event = self._CreateEventDict('error')\n error_event['msg'] = msg\n error_event['fmt'] = fmt\n self._log.append(error_event)\n\n def _GetEventTargetPath(self):\n \"\"\"Get the 'trace2.eventtarget' path from git configuration.\n\n Returns:\n path: git config's 'trace2.eventtarget' path if it exists, or None\n \"\"\"\n path = None\n cmd = ['config', '--get', 'trace2.eventtarget']\n # TODO(https://crbug.com/gerrit/13706): Use GitConfig when it supports\n # system git config variables.\n p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,\n bare=True)\n retval = p.Wait()\n if retval == 0:\n # Strip trailing carriage-return in path.\n path = p.stdout.rstrip('\\n')\n elif retval != 1:\n # `git config --get` is documented to produce an exit status of `1` if\n # the requested variable is not present in the configuration. Report any\n # other return value as an error.\n print(\"repo: error: 'git config --get' call failed with return code: %r, stderr: %r\" % (\n retval, p.stderr), file=sys.stderr)\n return path\n\n def Write(self, path=None):\n \"\"\"Writes the log out to a file.\n\n Log is only written if 'path' or 'git config --get trace2.eventtarget'\n provide a valid path to write logs to.\n\n Logging filename format follows the git trace2 style of being a unique\n (exclusive writable) file.\n\n Args:\n path: Path to where logs should be written.\n\n Returns:\n log_path: Path to the log file if log is written, otherwise None\n \"\"\"\n log_path = None\n # If no logging path is specified, get the path from 'trace2.eventtarget'.\n if path is None:\n path = self._GetEventTargetPath()\n\n # If no logging path is specified, exit.\n if path is None:\n return None\n\n if isinstance(path, str):\n # Get absolute path.\n path = os.path.abspath(os.path.expanduser(path))\n else:\n raise TypeError('path: str required but got %s.' % type(path))\n\n # Git trace2 requires a directory to write log to.\n\n # TODO(https://crbug.com/gerrit/13706): Support file (append) mode also.\n if not os.path.isdir(path):\n return None\n # Use NamedTemporaryFile to generate a unique filename as required by git trace2.\n try:\n with tempfile.NamedTemporaryFile(mode='x', prefix=self._sid, dir=path,\n delete=False) as f:\n # TODO(https://crbug.com/gerrit/13706): Support writing events as they\n # occur.\n for e in self._log:\n # Dump in compact encoding mode.\n # See 'Compact encoding' in Python docs:\n # https://docs.python.org/3/library/json.html#module-json\n json.dump(e, f, indent=None, separators=(',', ':'))\n f.write('\\n')\n log_path = f.name\n except FileExistsError as err:\n print('repo: warning: git trace2 logging failed: %r' % err,\n file=sys.stderr)\n return None\n return log_path\nerror.py\nclass NoSuchProjectError(Exception):\n \"\"\"A specified project does not exist in the work tree.\n \"\"\"\n\n def __init__(self, name=None):\n super().__init__(name)\n self.name = name\n\n def __str__(self):\n if self.name is None:\n return 'in current directory'\n return self.name\nerror.py\nclass InvalidProjectGroupsError(Exception):\n \"\"\"A specified project is not suitable for the specified groups\n \"\"\"\n\n def __init__(self, name=None):\n super().__init__(name)\n self.name = name\n\n def __str__(self):\n if self.name is None:\n return 'in current directory'\n return self.name\nerror.py\nclass ManifestParseError(Exception):\n \"\"\"Failed to parse the manifest file.\n \"\"\"\n", "answers": [" if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():"], "length": 2013, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "67d6dcbd1a506a1177d4afb8cf485294d33660a551415ab3"} {"input": "import math\nimport collections\nimport functools\nimport os\nimport unittest\nfrom datetime import datetime\nfrom arxpy.bitvector.operation import Concat, BvComp\nfrom arxpy.differential.difference import XorDiff\nfrom arxpy.smt.search import DerMode, ChSearchMode, _get_smart_print\nfrom arxpy.smt.tests.test_search import test_search_ch_skch\nfrom arxpy.primitives.chaskey import ChaskeyPi\nfrom arxpy.primitives.picipher import PiPermutation\nfrom arxpy.primitives import speck\nfrom arxpy.primitives import simon\nfrom arxpy.primitives import simeck\nfrom arxpy.primitives.hight import HightCipher\nfrom arxpy.primitives.lea import LeaCipher\nfrom arxpy.primitives.shacal1 import Shacal1Cipher\nfrom arxpy.primitives.shacal2 import Shacal2Cipher\nfrom arxpy.primitives.feal import FealCipher\nfrom arxpy.primitives.tea import TeaCipher\nfrom arxpy.primitives.xtea import XteaCipher\nfrom arxpy.primitives import cham\n\"\"\"Tests for cryptographic primitives.\"\"\"\n\n\n\n\n\n# from arxpy.primitives.threefish import ThreefishCipher\n\n\nOUTPUT_FILE = False\nVERBOSE_LEVEL = 0\n# 0: quiet\n# 1: basic info\n# 2: + ssa, model\n# 3: + hrepr\n# 4: + full hrepr\nCHECK = True\n\n\n# *_rounds should have trivial characteristics but *_rounds + 1 not (with ProbabilityOne)\nBvFunction = collections.namedtuple('BVF', ['function', 'rounds'])\n\n\nSpeck32 = speck.get_Speck_instance(speck.SpeckInstance.speck_32_64)\nSimon32 = simon.get_Simon_instance(simon.SimonInstance.simon_32_64)\nSimeck32 = simeck.get_Simeck_instance(simeck.SimeckInstance.simeck_32_64)\n", "context": "arxpy/primitives/lea.py\nclass LeaCipher(Cipher):\n key_schedule = LeaKeySchedule\n encryption = LeaEncryption\n rounds = 24\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n cls.key_schedule.set_rounds(new_rounds)\n cls.encryption.set_rounds(new_rounds)\n\n @classmethod\n def test(cls):\n old_rounds = cls.rounds\n cls.set_rounds(24)\n key = [\n Constant(0x3c2d1e0f, 32),\n Constant(0x78695a4b, 32),\n Constant(0xb4a59687, 32),\n Constant(0xf0e1d2c3, 32)\n ]\n pt = [\n Constant(0x13121110, 32),\n Constant(0x17161514, 32),\n Constant(0x1b1a1918, 32),\n Constant(0x1f1e1d1c, 32)\n ]\n ct = [\n Constant(0x354ec89f, 32),\n Constant(0x18c6c628, 32),\n Constant(0xa7c73255, 32),\n Constant(0xfd8b6404, 32)\n ]\n assert cls(pt, key) == tuple(ct)\n cls.set_rounds(old_rounds)\narxpy/smt/search.py\ndef _get_smart_print(filename=None):\n def smart_print(*msg, **kwargs):\n if filename is not None:\n with open(filename, \"a\") as fh:\n print(*msg, file=fh, flush=True, **kwargs)\n else:\n print(*msg, flush=True, **kwargs)\n return smart_print\narxpy/primitives/simeck.py\nclass SimeckRF(SimonRF):\nclass XDSimeckRF(XDSimonRF):\nclass SimeckInstance(enum.Enum):\n class SimeckKeySchedule(KeySchedule):\n class SimeckEncryption(Encryption):\n class SimeckCipher(Cipher):\n def xor_derivative(cls, input_diff):\ndef get_Simeck_instance(simeck_instance):\n def rf(x, y, k):\n def set_rounds(cls, new_rounds):\n def eval(cls, *master_key):\n def set_rounds(cls, new_rounds):\n def eval(cls, x, y):\n def set_rounds(cls, new_rounds):\n def test(cls):\n C = (2 ** n - 4) ^ int(z[i % len(z)])\narxpy/primitives/picipher.py\nclass PiPermutation(BvFunction):\n \"\"\"Encryption function.\"\"\"\n\n rounds = 3 * 2\n input_widths = [16 for _ in range(N * 4)]\n output_widths = [16 for _ in range(N * 4)]\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n\n # noinspection PyTypeChecker\n @classmethod\n def mul(cls, x, y):\n assert len(x) == 4\n assert len(y) == 4\n\n # mu\n T = [None for _ in range(12)]\n # order?\n aux01 = x[0] + x[1]\n aux23 = x[2] + x[3]\n T[0] = ROL(aux01 + (PI_MU_CONST_0 + x[2]), PI_MU_ROT_CONST_0)\n T[1] = ROL(aux01 + (PI_MU_CONST_1 + x[3]), PI_MU_ROT_CONST_1)\n T[2] = ROL((x[0] + PI_MU_CONST_2) + aux23, PI_MU_ROT_CONST_2)\n T[3] = ROL((x[1] + PI_MU_CONST_3) + aux23, PI_MU_ROT_CONST_3)\n T[4] = T[0] ^ T[1] ^ T[3]\n T[5] = T[0] ^ T[1] ^ T[2]\n T[6] = T[1] ^ T[2] ^ T[3]\n T[7] = T[0] ^ T[2] ^ T[3]\n\n # ny\n aux01 = y[0] + y[1]\n aux23 = y[2] + y[3]\n T[0] = ROL((PI_NY_CONST_0 + y[0]) + aux23, PI_NY_ROT_CONST_0)\n T[1] = ROL((PI_NY_CONST_1 + y[1]) + aux23, PI_NY_ROT_CONST_1)\n T[2] = ROL(aux01 + (PI_NY_CONST_2 + y[2]), PI_NY_ROT_CONST_2)\n T[3] = ROL(aux01 + (PI_NY_CONST_3 + y[3]), PI_NY_ROT_CONST_3)\n T[8] = T[1] ^ T[2] ^ T[3]\n T[9] = T[0] ^ T[2] ^ T[3]\n T[10] = T[0] ^ T[1] ^ T[3]\n T[11] = T[0] ^ T[1] ^ T[2]\n\n # sigma\n z3 = T[4] + T[8]\n z0 = T[5] + T[9]\n z1 = T[6] + T[10]\n z2 = T[7] + T[11]\n\n return z0, z1, z2, z3\n\n @classmethod\n def e1(cls, c, j):\n j[:4] = cls.mul(c, j[:4])\n if N > 1:\n for i in range(1, N):\n j[4*i:4*i+4] = cls.mul(j[4*i-4:4*i], j[4*i:4*i+4])\n return j\n\n @classmethod\n def e2(cls, c, i):\n i[-4:] = cls.mul(i[-4:], c)\n if N > 1:\n for j in range(N-2, -1, -1):\n i[4*j:4*j+4] = cls.mul(i[4*j:4*j+4], i[4*j+4:4*j+8])\n # i[-4*j-4:-4*j]= cls.mul(i[-4*j-4:-4*j], i[-4*j:-4*j+4])\n return i\n\n @classmethod\n def eval(cls, *args): # p0, p1, ...\n x = list(args)\n for i in range(cls.rounds):\n if i % 2 == 0:\n i = i // 2 # due to duplicating the number of rounds\n x = cls.e1(PI_CONST[2*i], x)\n else:\n i = (i - 1) // 2\n x = cls.e2(PI_CONST[2*i + 1], x)\n return x\n\n @classmethod\n def test(cls):\n old_rounds = cls.rounds\n\n cls.set_rounds(1)\n pt = [Constant(0x00000000, 16)] * (N * 4)\n ct = (0xe9f5, 0xcfab, 0x5198, 0x9eec,\n 0xcb81, 0x7fb0, 0xd47a, 0x45b7,\n 0xa5b5, 0xd8da, 0x2cc5, 0x0aa1,\n 0x7bc9, 0x97f0, 0xc515, 0x7224)\n assert cls(*pt) == tuple(ct), \"{}\".format(cls(*pt))\n\n cls.set_rounds(2)\n pt = [Constant(0x00000000, 16)] * (N * 4)\n ct = (0x4d2f, 0x383a, 0xa84d, 0xe12c,\n 0xee36, 0x2b82, 0xb624, 0x1e15,\n 0x39f9, 0x2ded, 0x54c3, 0x15c9,\n 0x58fe, 0xbff0, 0x44ad, 0x2b57)\n assert cls(*pt) == tuple(ct), \"{}\".format(cls(*pt))\n\n cls.set_rounds(6)\n pt = [Constant(0x00000000, 16)] * (N * 4)\n ct = (0x0274, 0x2a3d, 0x9d5e, 0x0319,\n 0x32b4, 0x2751, 0x745b, 0xa328,\n 0xd2d4, 0x1ae9, 0x8e70, 0x0fe6,\n 0x9506, 0xe58d, 0x996b, 0x6075)\n assert cls(*pt) == tuple(ct), \"{}\".format(cls(*pt))\n\n cls.set_rounds(old_rounds)\narxpy/primitives/shacal1.py\nclass Shacal1Cipher(Cipher):\n key_schedule = Shacal1KeySchedule\n encryption = Shacal1Encryption\n rounds = 80\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n cls.key_schedule.set_rounds(new_rounds)\n cls.encryption.set_rounds(new_rounds)\n\n # noinspection SpellCheckingInspection\n @classmethod\n def test(cls):\n # https://www.cosic.esat.kuleuven.be/nessie/testvectors/\n # key = 80000000000000000000000000000000\n # 00000000000000000000000000000000\n # 00000000000000000000000000000000\n # 00000000000000000000000000000000\n # plain = 0000000000000000000000000000000000000000\n # cipher = 0FFD8D43 B4E33C7C 53461BD1 0F27A546 1050D90D\n\n old_rounds = cls.rounds\n cls.set_rounds(80)\n\n global REFERENCE_VERSION\n\n for ref_v in [True, False]:\n REFERENCE_VERSION = ref_v\n\n key = [Constant(0x80000000, 32)]\n key.extend([Constant(0, 32) for _ in range(1, N)])\n pt = [Constant(0, 32) for _ in range(5)]\n ct = [\n Constant(0x0FFD8D43, 32),\n Constant(0xB4E33C7C, 32),\n Constant(0x53461BD1, 32),\n Constant(0x0F27A546, 32),\n Constant(0x01050D90D, 32)\n ]\n assert cls(pt, key) == tuple(ct)\n\n if N == 16:\n # key = 00010203 04050607 08090A0B 0C0D0E0F\n # 10111213 14151617 18191A1B 1C1D1E1F\n # 20212223 24252627 28292A2B 2C2D2E2F\n # 30313233 34353637 38393A3B 3C3D3E3F\n # plain = 00112233 44556677 8899AABB CCDDEEFF 10213243\n # cipher = 213A4657 59CE3572 CA2A86D5 A680E948 45BEAA6B\n\n key = [\n Constant(0x00010203, 32), Constant(0x04050607, 32), Constant(0x08090A0B, 32), Constant(0x0C0D0E0F, 32),\n Constant(0x10111213, 32), Constant(0x14151617, 32), Constant(0x18191A1B, 32), Constant(0x1C1D1E1F, 32),\n Constant(0x20212223, 32), Constant(0x24252627, 32), Constant(0x28292A2B, 32), Constant(0x2C2D2E2F, 32),\n Constant(0x30313233, 32), Constant(0x34353637, 32), Constant(0x38393A3B, 32), Constant(0x3C3D3E3F, 32),\n ]\n pt = [\n Constant(0x00112233, 32),\n Constant(0x44556677, 32),\n Constant(0x8899AABB, 32),\n Constant(0xCCDDEEFF, 32),\n Constant(0x10213243, 32),\n ]\n ct = [\n Constant(0x213A4657, 32),\n Constant(0x59CE3572, 32),\n Constant(0xCA2A86D5, 32),\n Constant(0xA680E948, 32),\n Constant(0x45BEAA6B, 32)\n ]\n assert cls(pt, key) == tuple(ct)\n\n cls.set_rounds(old_rounds)\narxpy/primitives/cham.py\nclass ChamInstance(enum.Enum):\n class ChamKeySchedule(KeySchedule):\n class ChamEncryption(Encryption):\n class ChamCipher(Cipher):\ndef get_Cham_instance(cham_instance):\n def set_rounds(cls, new_rounds):\n def eval(cls, *master_key):\n def set_rounds(cls, new_rounds):\n def eval(cls, p0, p1, p2, p3):\n def set_rounds(cls, new_rounds):\n def test(cls):\narxpy/primitives/chaskey.py\nclass ChaskeyPi(BvFunction):\n rounds = 8\n input_widths = [32, 32, 32, 32]\n output_widths = [32, 32, 32, 32]\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n\n @classmethod\n def eval(cls, v0, v1, v2, v3):\n for i in range(cls.rounds):\n v0 += v1\n v1 = RotateLeft(v1, 5)\n v1 ^= v0\n v0 = RotateLeft(v0, 16)\n\n v2 += v3\n v3 = RotateLeft(v3, 8)\n v3 ^= v2\n\n v0 += v3\n v3 = RotateLeft(v3, 13)\n v3 ^= v0\n\n v2 += v1\n v1 = RotateLeft(v1, 7)\n v1 ^= v2\n v2 = RotateLeft(v2, 16)\n\n return v0, v1, v2, v3\n\n @classmethod\n def test(cls):\n old_rounds = cls.rounds\n cls.set_rounds(8)\n\n pt = [\n Constant(0x00000000, 32)\n ] * 4\n ct = [\n Constant(0x00000000, 32)\n ] * 4\n assert cls(*pt) == tuple(ct)\n\n cls.set_rounds(old_rounds)\narxpy/primitives/feal.py\nclass FealCipher(Cipher):\n key_schedule = FealXKeySchedule if FEALX else FealKeySchedule\n encryption = FealEncryption\n rounds = 8\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n cls.encryption.set_rounds(new_rounds)\n cls.key_schedule.set_rounds(new_rounds)\n\n @classmethod\n def test(cls):\n \"\"\"Test FEAL with official test vectors.\"\"\"\n # Extracted from \"The FEAL Cipher Family\"\n old_rounds = cls.rounds\n cls.set_rounds(8)\n\n if not FEALX:\n plaintext = (0, 0, 0, 0, 0, 0, 0, 0)\n key = (0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF)\n ciphertext = (0xCE, 0xEF, 0x2C, 0x86, 0xF2, 0x49, 0x07, 0x52)\n assert cls(plaintext, key) == ciphertext\n else:\n plaintext = (0, 0, 0, 0, 0, 0, 0, 0)\n key = (0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF)\n key += key # double the size\n ciphertext = (0x92, 0xBE, 0xB6, 0x5D, 0x0E, 0x93, 0x82, 0xFB)\n assert cls(plaintext, key) == ciphertext\n\n cls.set_rounds(old_rounds)\narxpy/bitvector/operation.py\nclass Concat(Operation):\n \"\"\"Concatenation operation.\n\n Given the bit-vectors :math:`(x_{n-1}, \\dots, x_0)` and\n :math:`(y_{m-1}, \\dots, y_0)`, ``Concat(x, y)`` returns the bit-vector\n :math:`(x_{n-1}, \\dots, x_0, y_{m-1}, \\dots, y_0)`.\n\n >>> from arxpy.bitvector.core import Constant, Variable\n >>> from arxpy.bitvector.operation import Concat\n >>> Concat(Constant(0x12, 8), Constant(0x345, 12))\n 0x12345\n >>> Concat(Variable(\"x\", 8), Variable(\"y\", 8))\n x :: y\n\n \"\"\"\n\n arity = [2, 0]\n is_symmetric = False\n infix_symbol = \"::\"\n\n @classmethod\n def output_width(cls, x, y):\n return x.width + y.width\n\n @classmethod\n def eval(cls, x, y):\n def doit(x, y):\n \"\"\"Concatenation when both operands are int.\"\"\"\n return int(x.bin() + y.bin()[2:], 2)\n\n if isinstance(x, core.Constant) and isinstance(y, core.Constant):\n return core.Constant(doit(x, y), cls.output_width(x, y))\n elif isinstance(x, core.Constant) and isinstance(y, Concat) and \\\n isinstance(y.args[0], core.Constant):\n return Concat(Concat(x, y.args[0]), y.args[1])\n elif isinstance(y, core.Constant) and isinstance(x, Concat) and \\\n isinstance(x.args[1], core.Constant):\n return Concat(x.args[0], Concat(x.args[1], y))\n elif isinstance(x, Extract) and isinstance(y, Extract):\n # x[5:4] concat x[3:2] = x[5:2]\n if x.args[0] == y.args[0] and x.args[2] == y.args[1] + 1:\n return Extract(x.args[0], x.args[1], y.args[2])\narxpy/differential/difference.py\nclass XorDiff(Difference):\n \"\"\"Represent XOR differences.\n\n The XOR difference of two `Term` is given by the XOR\n of the terms. In other words, the *difference operation*\n of `XorDiff` is the `BvXor` (see `Difference`).\n\n >>> from arxpy.bitvector.core import Constant, Variable\n >>> from arxpy.differential.difference import XorDiff\n >>> x, y = Constant(0b000, 3), Constant(0b000, 3)\n >>> alpha = XorDiff.from_pair(x, y)\n >>> alpha\n XorDiff(0b000)\n >>> alpha.get_pair_element(x)\n 0b000\n >>> x, y = Constant(0b010, 3), Constant(0b101, 3)\n >>> alpha = XorDiff.from_pair(x, y)\n >>> alpha\n XorDiff(0b111)\n >>> alpha.get_pair_element(x)\n 0b101\n >>> k = Variable(\"k\", 8)\n >>> alpha = XorDiff.from_pair(k, k)\n >>> alpha\n XorDiff(0x00)\n >>> alpha.get_pair_element(k)\n k\n \"\"\"\n\n diff_op = operation.BvXor\n inv_diff_op = operation.BvXor\n\n @classmethod\n def derivative(cls, op, input_diff):\n \"\"\"Return the derivative of ``op`` at the point ``input_diff``.\n\n See `Difference.derivative` for more information.\n\n >>> from arxpy.bitvector.core import Variable, Constant\n >>> from arxpy.bitvector.operation import BvAdd, BvXor, RotateLeft, BvSub\n >>> from arxpy.bitvector.extraop import make_partial_operation\n >>> from arxpy.differential.difference import XorDiff\n >>> d1, d2 = XorDiff(Variable(\"d1\", 8)), XorDiff(Variable(\"d2\", 8))\n >>> XorDiff.derivative(BvXor, [d1, d2])\n XorDiff(d1 ^ d2)\n >>> Xor1 = make_partial_operation(BvXor, tuple([None, Constant(1, 8)]))\n >>> XorDiff.derivative(Xor1, d1)\n XorDiff(d1)\n >>> Rotate1 = make_partial_operation(RotateLeft, tuple([None, 1]))\n >>> XorDiff.derivative(Rotate1, d1)\n XorDiff(d1 <<< 1)\n >>> XorDiff.derivative(BvAdd, [d1, d2])\n XDA(XorDiff(d1), XorDiff(d2))\n >>> XorDiff.derivative(BvSub, [d1, d2])\n XDS(XorDiff(d1), XorDiff(d2))\n >>> CteAdd1 = make_partial_operation(BvAdd, tuple([None, Constant(1, 8)]))\n >>> XorDiff.derivative(CteAdd1, d1)\n XDCA_0x01(XorDiff(d1))\n\n \"\"\"\n input_diff = _tuplify(input_diff)\n assert len(input_diff) == sum(op.arity)\n\n msg = \"invalid arguments: op={}, input_diff={}\".format(\n op.__name__,\n [d.vrepr() if isinstance(d, core.Term) else d for d in input_diff])\n\n if not all(isinstance(diff, cls) for diff in input_diff):\n raise ValueError(msg)\n\n if op == operation.BvNot:\n return input_diff[0]\n\n if op == operation.BvXor:\n return cls(op(*[d.val for d in input_diff]))\n\n if op == operation.Concat:\n return cls(op(*[d.val for d in input_diff]))\n\n if op == operation.BvAdd:\n from arxpy.differential import derivative\n return derivative.XDA(input_diff)\n\n if op == operation.BvSub:\n from arxpy.differential import derivative\n return derivative.XDS(input_diff)\n\n if issubclass(op, extraop.PartialOperation):\n if op.base_op == operation.BvXor:\n assert len(input_diff) == 1\n d1 = input_diff[0]\n val = op.fixed_args[0] if op.fixed_args[0] is not None else op.fixed_args[1]\n d2 = cls.from_pair(val, val)\n input_diff = [d1, d2]\n return cls(op.base_op(*[d.val for d in input_diff]))\n\n if op.base_op == operation.BvAnd:\n assert len(input_diff) == 1\n d1 = input_diff[0]\n val = op.fixed_args[0] if op.fixed_args[0] is not None else op.fixed_args[1]\n if isinstance(val, core.Constant):\n return cls(op.base_op(d1.val, val))\n\n if op.base_op in [operation.RotateLeft, operation.RotateRight]:\n if op.fixed_args[0] is None and op.fixed_args[1] is not None:\n assert len(input_diff) == 1\n d = input_diff[0]\n return cls(op.base_op(d.val, op.fixed_args[1]))\n else:\n raise ValueError(msg)\n\n if op.base_op in [operation.BvShl, operation.BvLshr]:\n if op.fixed_args[0] is None and op.fixed_args[1] is not None:\n assert len(input_diff) == 1\n d = input_diff[0]\n return cls(op.base_op(d.val, op.fixed_args[1]))\n else:\n raise ValueError(msg)\n\n if op.base_op == operation.Extract:\n if op.fixed_args[0] is None and op.fixed_args[1] is not None and op.fixed_args[2] is not None:\n assert len(input_diff) == 1\n d = input_diff[0]\n return cls(op.base_op(d.val, op.fixed_args[1], op.fixed_args[2]))\n else:\n raise ValueError(msg)\n\n if op.base_op == operation.Concat:\n assert len(input_diff) == 1\n d1 = input_diff[0]\n if op.fixed_args[0] is not None:\n val = op.fixed_args[0]\n input_diff = [cls.from_pair(val, val), d1]\n else:\n val = op.fixed_args[1]\n input_diff = [d1, cls.from_pair(val, val)]\n return cls(op.base_op(*[d.val for d in input_diff]))\n\n if op.base_op == operation.BvAdd:\n assert len(input_diff) == 1\n d = input_diff[0]\n cte = op.fixed_args[0] if op.fixed_args[0] is not None else op.fixed_args[1]\n from arxpy.differential import derivative\n return derivative.XDCA(d, cte)\n else:\n raise ValueError(msg)\n\n if hasattr(op, \"xor_derivative\"):\n return op.xor_derivative(input_diff)\n\n raise ValueError(msg)\narxpy/primitives/xtea.py\nclass XteaCipher(Cipher):\n key_schedule = XteaKeySchedule\n encryption = XteaEncryption\n rounds = 64\n\n @classmethod\n def set_rounds(cls, new_rounds):\n # assert new_rounds >= 2\n cls.rounds = new_rounds\n cls.encryption.set_rounds(new_rounds)\n cls.key_schedule.set_rounds(new_rounds)\n\n @classmethod\n def test(cls):\n \"\"\"Test Xtea with official test vectors.\"\"\"\n # https://go.googlesource.com/crypto/+/master/xtea/xtea_test.go\n plaintext = (0x41424344, 0x45464748)\n key = (0, 0, 0, 0)\n assert cls(plaintext, key) == (0xa0390589, 0xf8b8efa5)\n\n plaintext = (0x41424344, 0x45464748)\n key = (0x00010203, 0x04050607, 0x08090A0B, 0x0C0D0E0F)\n assert cls(plaintext, key) == (0x497df3d0, 0x72612cb5)\narxpy/bitvector/operation.py\nclass BvComp(Operation):\n \"\"\"Equality operator.\n\n Provides Automatic Constant Conversion. See `Operation` for more\n information.\n\n >>> from arxpy.bitvector.core import Constant, Variable\n >>> from arxpy.bitvector.operation import BvComp\n >>> BvComp(Constant(1, 8), Constant(2, 8))\n 0b0\n >>> BvComp(Constant(1, 8), 2)\n 0b0\n >>> BvComp(Constant(1, 8), Variable(\"y\", 8))\n 0x01 == y\n\n The operator == is used for exact structural equality testing and\n it returns either True or False. On the other hand, BvComp\n performs symbolic equality testing and it leaves the relation unevaluated\n if it cannot prove the objects are equal (or unequal).\n\n >>> Variable(\"x\", 8) == Variable(\"y\", 8)\n False\n >>> BvComp(Variable(\"x\", 8), Variable(\"y\", 8)) # symbolic equality\n x == y\n\n \"\"\"\n\n arity = [2, 0]\n is_symmetric = True\n is_simple = True\n infix_symbol = \"==\"\n\n @classmethod\n def condition(cls, x, y):\n return x.width == y.width\n\n @classmethod\n def output_width(cls, x, y):\n return 1\n\n @classmethod\n def eval(cls, x, y):\n zero = core.Constant(0, 1)\n one = core.Constant(1, 1)\n\n if x is y:\n return one\n elif isinstance(x, core.Constant) and isinstance(y, core.Constant):\n return one if x.val == y.val else zero\narxpy/primitives/speck.py\nclass SpeckInstance(enum.Enum):\n class SpeckKeySchedule(KeySchedule):\n class SpeckEncryption(Encryption):\n class SpeckCipher(Cipher):\ndef get_Speck_instance(speck_instance):\n def rf(x, y, k):\n def set_rounds(cls, new_rounds):\n def eval(cls, *master_key):\n def set_rounds(cls, new_rounds):\n def eval(cls, x, y):\n def set_rounds(cls, new_rounds):\n def test(cls):\narxpy/primitives/simon.py\nclass SimonRF(Operation):\nclass XDSimonRF(Derivative):\nclass SimonInstance(enum.Enum):\n class SimonKeySchedule(KeySchedule):\n class SimonEncryption(Encryption):\n class SimonCipher(Cipher):\n def output_width(cls, x):\n def eval(cls, x):\n def xor_derivative(cls, input_diff):\n def is_possible(self, output_diff):\n def is_even(x):\n def has_probability_one(self, output_diff):\n def weight(self, output_diff):\n def max_weight(self):\n def exact_weight(self, output_diff):\n def num_frac_bits(self):\n def error(self):\ndef get_Simon_instance(simon_instance):\n def set_rounds(cls, new_rounds):\n def eval(cls, *master_key):\n def set_rounds(cls, new_rounds):\n def eval(cls, x, y):\n def set_rounds(cls, new_rounds):\n def test(cls):\narxpy/smt/tests/test_search.py\ndef test_search_ch_skch(bvf_cipher, diff_type, initial_weight, solver_name, rounds, der_mode, search_mode, check,\n verbose_level, filename):\n smart_print = _get_smart_print(filename)\n\n if rounds is not None:\n bvf_cipher.set_rounds(rounds)\n\n if issubclass(bvf_cipher, BvFunction):\n num_inputs = len(bvf_cipher.input_widths)\n input_diff_names = [\"dp\" + str(i) for i in range(num_inputs)]\n ch = BvCharacteristic(bvf_cipher, diff_type, input_diff_names)\n else:\n assert issubclass(bvf_cipher, Cipher)\n ch = SingleKeyCh(bvf_cipher, diff_type)\n\n if verbose_level >= 1:\n str_rounds = \"\" if rounds is None else \"{} rounds\".format(rounds)\n smart_print(str_rounds, bvf_cipher.__name__, diff_type.__name__, type(ch).__name__)\n if verbose_level >= 2:\n smart_print(\"Characteristic:\")\n smart_print(ch)\n\n if issubclass(bvf_cipher, BvFunction):\n problem = SearchCh(ch, der_mode=der_mode)\n else:\n problem = SearchSkCh(ch, der_mode=der_mode)\n\n if verbose_level >= 1:\n smart_print(type(problem).__name__, der_mode, search_mode, solver_name,\n \"size:\", problem.formula_size())\n if verbose_level >= 2:\n smart_print(problem.hrepr(verbose_level >= 3))\n\n sol = problem.solve(initial_weight,\n solver_name=solver_name,\n search_mode=search_mode,\n check=check,\n verbose_level=verbose_level,\n filename=filename)\n\n if verbose_level >= 1:\n if sol is None:\n smart_print(\"\\nUnsatisfiable\")\n else:\n smart_print(\"\\nSolution:\")\n smart_print(sol)\n if verbose_level >= 2:\n if isinstance(sol, collections.abc.Sequence):\n # for search_mode TopDifferentials\n smart_print(sol[0].vrepr())\n else:\n smart_print(sol.vrepr())\n smart_print()\n\n return sol\narxpy/primitives/tea.py\nclass TeaCipher(Cipher):\n key_schedule = TeaKeySchedule\n encryption = TeaEncryption\n rounds = 32\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n cls.encryption.set_rounds(new_rounds)\n\n @classmethod\n def test(cls):\n \"\"\"Test tea with official test vectors.\"\"\"\n cls.set_rounds(32)\n\n plaintext = (0, 0)\n key = (0, 0, 0, 0)\n assert cls(plaintext, key) == (0x41EA3A0A, 0x94BAA940)\n\n plaintext = (0x01020304, 0x05060708)\n key = (0x00112233, 0x44556677, 0x8899AABB, 0xCCDDEEFF)\n assert cls(plaintext, key) == (0xDEB1C0A2, 0x7E745DB3)\narxpy/primitives/shacal2.py\nclass Shacal2Cipher(Cipher):\n key_schedule = Shacal2KeySchedule\n encryption = Shacal2Encryption\n rounds = 64\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n cls.key_schedule.set_rounds(new_rounds)\n cls.encryption.set_rounds(new_rounds)\n\n # noinspection SpellCheckingInspection\n @classmethod\n def test(cls):\n # https://www.cosic.esat.kuleuven.be/nessie/testvectors/\n # key =\n # 80000000000000000000000000000000\n # 00000000000000000000000000000000\n # 00000000000000000000000000000000\n # 00000000000000000000000000000000\n # plain =\n # 00000000000000000000000000000000\n # 00000000000000000000000000000000\n # cipher =\n # 361AB632 2FA9E7A7 BB23818D 839E01BD\n # DAFDF473 05426EDD 297AEDB9 F6202BAE\n\n old_rounds = cls.rounds\n cls.set_rounds(64)\n\n global REFERENCE_VERSION\n\n for ref_v in [True, False]:\n REFERENCE_VERSION = ref_v\n\n key = [Constant(0x80000000, 32)]\n key.extend([Constant(0, 32) for _ in range(1, N)])\n pt = [Constant(0, 32) for _ in range(8)]\n ct = [\n Constant(0x361AB632, 32),\n Constant(0x2FA9E7A7, 32),\n Constant(0xBB23818D, 32),\n Constant(0x839E01BD, 32),\n Constant(0xDAFDF473, 32),\n Constant(0x05426EDD, 32),\n Constant(0x297AEDB9, 32),\n Constant(0xF6202BAE, 32),\n ]\n assert cls(pt, key) == tuple(ct)\n\n if N == 16:\n # key =\n # 00010203 04050607 08090A0B 0C0D0E0F\n # 10111213 14151617 18191A1B 1C1D1E1F\n # 20212223 24252627 28292A2B 2C2D2E2F\n # 30313233 34353637 38393A3B 3C3D3E3F\n # plain =\n # 00112233 44556677 8899AABB CCDDEEFF\n # 10213243 54657687 98A9BACB DCEDFE0F\n # cipher =\n # 1A6B234A 20EAD408 C2D83B35 8AC81D7A\n # 648ED25D 01B7C9EC 9CC4C9E2 5CFA813E\n\n key = [\n Constant(0x00010203, 32), Constant(0x04050607, 32), Constant(0x08090A0B, 32), Constant(0x0C0D0E0F, 32),\n Constant(0x10111213, 32), Constant(0x14151617, 32), Constant(0x18191A1B, 32), Constant(0x1C1D1E1F, 32),\n Constant(0x20212223, 32), Constant(0x24252627, 32), Constant(0x28292A2B, 32), Constant(0x2C2D2E2F, 32),\n Constant(0x30313233, 32), Constant(0x34353637, 32), Constant(0x38393A3B, 32), Constant(0x3C3D3E3F, 32),\n ]\n pt = [\n Constant(0x00112233, 32),\n Constant(0x44556677, 32),\n Constant(0x8899AABB, 32),\n Constant(0xCCDDEEFF, 32),\n Constant(0x10213243, 32),\n Constant(0x54657687, 32),\n Constant(0x98A9BACB, 32),\n Constant(0xDCEDFE0F, 32),\n ]\n ct = [\n Constant(0x1A6B234A, 32),\n Constant(0x20EAD408, 32),\n Constant(0xC2D83B35, 32),\n Constant(0x8AC81D7A, 32),\n Constant(0x648ED25D, 32),\n Constant(0x01B7C9EC, 32),\n Constant(0x9CC4C9E2, 32),\n Constant(0x5CFA813E, 32),\n ]\n assert cls(pt, key) == tuple(ct)\n\n cls.set_rounds(old_rounds)\narxpy/primitives/hight.py\nclass HightCipher(Cipher):\n key_schedule = HightKeySchedule\n encryption = HightEncryption\n rounds = 32\n\n @classmethod\n def set_rounds(cls, new_rounds):\n cls.rounds = new_rounds\n cls.key_schedule.set_rounds(new_rounds)\n cls.encryption.set_rounds(new_rounds)\n\n @classmethod\n def test(cls):\n \"\"\"Test Hight with official test vectors.\"\"\"\n # https://tools.ietf.org/html/draft-kisa-hight-00#section-5\n old_rounds = cls.rounds\n cls.set_rounds(32)\n\n plaintext = (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)\n key = (0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff)\n assert cls(plaintext, key) == (0x00, 0xf4, 0x18, 0xae, 0xd9, 0x4f, 0x03, 0xf2)\n\n plaintext = (0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77)\n key = (0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00)\n assert cls(plaintext, key) == (0x23, 0xce, 0x9f, 0x72, 0xe5, 0x43, 0xe6, 0xd8)\n\n cls.set_rounds(old_rounds)\narxpy/smt/search.py\nclass DerMode(enum.Enum):\n \"\"\"Represent the different constraints available for the derivative weights of a characteristic.\n\n Attributes:\n Default: no additional constraint is added\n ProbabilityOne: fix all derivative weights to zero\n Valid: only the validity constraint is added (weight is ignored)\n XDCA_Approx: for the weights of `XDCA`, the ``precision`` is set to ``0``\n\n \"\"\"\n Default = enum.auto()\n ProbabilityOne = enum.auto()\n Valid = enum.auto()\n XDCA_Approx = enum.auto()\narxpy/smt/search.py\nclass ChSearchMode(enum.Enum):\n \"\"\"Represent the different options for searching `BvCharacteristic`.\n\n A characteristic is said to be *valid* if its weight\n :math:`w = - \\log_2(p)`, where *p* is the probability of the characteristic,\n is lower than the bit-size of the input difference.\n\n A derivative weight is said to be *non-exact* if its weight\n does not match its exact weight.\n\n Attributes:\n FirstCh: returns the 1st characteristic found by iteratively searching with increasing weight.\n The characteristic found is returned as a `ChFound` object, but it may not have\n optimal theoretical weight if it contains a non-exact derivative weight\n or it may be empirically invalid. If no characteristic is found,\n ``None`` is returned.\n FirstChValid: similar to `FirstCh`, but if the characteristic found is\n empirically invalid (after computing its empirical weight), the search continues.\n Optimal: similar to `FirstCh`, but several characteristics are found to ensure\n that the one returned has the optimal theoretical weight.\n (only differs from `FirstCh` if there is a non-exact derivative weight).\n OptimalDifferential: similar to `Optimal`, but once a characteristic is found,\n only characteristics with different input/output differences are searched.\n AllOptimal: similar to `Optimal`, but the search never stops.\n TopDifferentials: searches for `MAX_CH_FOUND` characteristics\n (as in `FirstCh`) and return the differentials obtained\n by gathering those characteristics.\n AllValid: a non-stop search of valid characteristics with no\n additional constraints.\n\n \"\"\"\n FirstCh = enum.auto()\n FirstChValid = enum.auto()\n Optimal = enum.auto()\n OptimalDifferential = enum.auto()\n AllOptimal = enum.auto()\n AllValid = enum.auto()\n TopDifferentials = enum.auto()\n", "answers": ["Cham64 = cham.get_Cham_instance(cham.ChamInstance.cham_64_128)"], "length": 3108, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "7abdb12c3b4e4f5e4839ed86f80a549757d753c16078bf0f"} {"input": "import multiprocessing as mp\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport time\nimport tqdm\nfrom abc import ABCMeta\nfrom queue import Empty\nfrom typing import Dict, List, Optional\nfrom montreal_forced_aligner.abc import MfaWorker, TemporaryDirectoryMixin\nfrom montreal_forced_aligner.corpus.base import CorpusMixin\nfrom montreal_forced_aligner.corpus.classes import File\nfrom montreal_forced_aligner.corpus.features import (\n CalcFmllrArguments,\n CalcFmllrFunction,\n ComputeVadFunction,\n FeatureConfigMixin,\n MfccArguments,\n MfccFunction,\n VadArguments,\n)\nfrom montreal_forced_aligner.corpus.helper import find_exts\nfrom montreal_forced_aligner.corpus.multiprocessing import CorpusProcessWorker\nfrom montreal_forced_aligner.data import TextFileType\nfrom montreal_forced_aligner.dictionary.multispeaker import MultispeakerDictionaryMixin\nfrom montreal_forced_aligner.exceptions import TextGridParseError, TextParseError\nfrom montreal_forced_aligner.helper import load_scp\nfrom montreal_forced_aligner.textgrid import parse_aligned_textgrid\nfrom montreal_forced_aligner.utils import KaldiProcessWorker, Stopped, thirdparty_binary\n \"There were some issues with files in the corpus. \"\n \"Please look at the log file or run the validator for more information.\"\n )\n self.log_debug(f\"{k} showed {len(return_dict[k])} errors:\")\n if k == \"textgrid_read_errors\":\n getattr(self, k).update(return_dict[k])\n for f, e in return_dict[k].items():\n self.log_debug(f\"{f}: {e.error}\")\n else:\n self.log_debug(\", \".join(return_dict[k]))\n setattr(self, k, return_dict[k])\n\n except KeyboardInterrupt:\n self.log_info(\"Detected ctrl-c, please wait a moment while we clean everything up...\")\n self.stopped.stop()\n finished_adding.stop()\n job_queue.join()\n self.stopped.set_sigint_source()\n while True:\n try:\n _ = return_queue.get(timeout=1)\n if self.stopped.stop_check():\n continue\n except Empty:\n for proc in procs:\n if not proc.finished_processing.stop_check():\n break\n else:\n break\n finally:\n\n finished_adding.stop()\n job_queue.join()\n for p in procs:\n p.join()\n if self.stopped.stop_check():\n self.log_info(\n f\"Stopped parsing early ({time.process_time() - begin_time} seconds)\"\n )\n if self.stopped.source():\n sys.exit(0)\n else:\n self.log_debug(\n f\"Parsed corpus directory with {self.num_jobs} jobs in {time.process_time() - begin_time} seconds\"\n )\n\n def _load_corpus_from_source(self) -> None:\n \"\"\"\n Load a corpus without using multiprocessing\n \"\"\"\n begin_time = time.time()\n sanitize_function = None\n if hasattr(self, \"sanitize_function\"):\n sanitize_function = self.sanitize_function\n\n all_sound_files = {}\n use_audio_directory = False\n if self.audio_directory and os.path.exists(self.audio_directory):\n use_audio_directory = True\n for root, _, files in os.walk(self.audio_directory, followlinks=True):\n if self.stopped.stop_check():\n return\n exts = find_exts(files)\n exts.wav_files = {k: os.path.join(root, v) for k, v in exts.wav_files.items()}\n exts.other_audio_files = {\n k: os.path.join(root, v) for k, v in exts.other_audio_files.items()\n }\n all_sound_files.update(exts.other_audio_files)\n all_sound_files.update(exts.wav_files)\n self.log_debug(f\"Walking through {self.corpus_directory}...\")\n for root, _, files in os.walk(self.corpus_directory, followlinks=True):\n exts = find_exts(files)\n relative_path = root.replace(self.corpus_directory, \"\").lstrip(\"/\").lstrip(\"\\\\\")\n if self.stopped.stop_check():\n return\n self.log_debug(f\"Inside relative root {relative_path}:\")\n self.log_debug(f\" Found {len(exts.identifiers)} identifiers\")\n self.log_debug(f\" Found {len(exts.wav_files)} .wav files\")\n self.log_debug(f\" Found {len(exts.other_audio_files)} other audio files\")\n self.log_debug(f\" Found {len(exts.lab_files)} .lab files\")\n self.log_debug(f\" Found {len(exts.textgrid_files)} .TextGrid files\")\n if not use_audio_directory:\n all_sound_files = {}\n wav_files = {k: os.path.join(root, v) for k, v in exts.wav_files.items()}\n other_audio_files = {\n k: os.path.join(root, v) for k, v in exts.other_audio_files.items()\n }\n all_sound_files.update(other_audio_files)\n all_sound_files.update(wav_files)\n for file_name in exts.identifiers:\n\n wav_path = None\n transcription_path = None\n if file_name in all_sound_files:\n wav_path = all_sound_files[file_name]\n if file_name in exts.lab_files:\n lab_name = exts.lab_files[file_name]\n transcription_path = os.path.join(root, lab_name)\n elif file_name in exts.textgrid_files:\n tg_name = exts.textgrid_files[file_name]\n transcription_path = os.path.join(root, tg_name)\n if wav_path is None and transcription_path is None: # Not a file for MFA\n continue\n if wav_path is None:\n self.transcriptions_without_wavs.append(transcription_path)\n continue\n if transcription_path is None:\n self.no_transcription_files.append(wav_path)\n try:\n file = File.parse_file(\n file_name,\n wav_path,\n transcription_path,\n relative_path,\n self.speaker_characters,\n sanitize_function,\n )\n self.add_file(file)\n except TextParseError as e:\n self.decode_error_files.append(e)\n", "context": "montreal_forced_aligner/utils.py\ndef thirdparty_binary(binary_name: str) -> str:\n \"\"\"\n Generate full path to a given binary name\n\n Notes\n -----\n With the move to conda, this function is deprecated as conda will manage the path much better\n\n Parameters\n ----------\n binary_name: str\n Executable to run\n\n Returns\n -------\n str\n Full path to the executable\n \"\"\"\n bin_path = shutil.which(binary_name)\n if bin_path is None:\n if binary_name in [\"fstcompile\", \"fstarcsort\", \"fstconvert\"] and sys.platform != \"win32\":\n raise ThirdpartyError(binary_name, open_fst=True)\n else:\n raise ThirdpartyError(binary_name)\n return bin_path\nmontreal_forced_aligner/corpus/features.py\nclass ComputeVadFunction(KaldiFunction):\n \"\"\"\n Multiprocessing function to compute voice activity detection\n\n See Also\n --------\n :meth:`.AcousticCorpusMixin.compute_vad`\n Main function that calls this function in parallel\n :meth:`.AcousticCorpusMixin.compute_vad_arguments`\n Job method for generating arguments for this function\n :kaldi_src:`compute-vad`\n Relevant Kaldi binary\n\n Parameters\n ----------\n args: :class:`~montreal_forced_aligner.corpus.features.VadArguments`\n Arguments for the function\n \"\"\"\n\n progress_pattern = re.compile(\n r\"^LOG.*processed (?P\\d+) utterances.*(?P\\d+) had.*(?P\\d+) were.*\"\n )\n\n def __init__(self, args: VadArguments):\n self.log_path = args.log_path\n self.feats_scp_path = args.feats_scp_path\n self.vad_scp_path = args.vad_scp_path\n self.vad_options = args.vad_options\n\n def run(self):\n \"\"\"Run the function\"\"\"\n with open(self.log_path, \"w\") as log_file:\n feats_scp_path = self.feats_scp_path\n vad_scp_path = self.vad_scp_path\n vad_proc = subprocess.Popen(\n [\n thirdparty_binary(\"compute-vad\"),\n f\"--vad-energy-mean-scale={self.vad_options['energy_mean_scale']}\",\n f\"--vad-energy-threshold={self.vad_options['energy_threshold']}\",\n f\"scp:{feats_scp_path}\",\n f\"ark,t:{vad_scp_path}\",\n ],\n stderr=subprocess.PIPE,\n encoding=\"utf8\",\n env=os.environ,\n )\n for line in vad_proc.stderr:\n log_file.write(line)\n m = self.progress_pattern.match(line.strip())\n if m:\n yield int(m.group(\"done\")), int(m.group(\"no_feats\")), int(m.group(\"unvoiced\"))\nmontreal_forced_aligner/textgrid.py\ndef parse_aligned_textgrid(\n path: str, root_speaker: typing.Optional[str] = None\n) -> Dict[str, List[CtmInterval]]:\n tg = tgio.openTextgrid(path, includeEmptyIntervals=False, reportingMode=\"silence\")\n data = {}\n num_tiers = len(tg.tierNameList)\n if num_tiers == 0:\n raise TextGridParseError(path, \"Number of tiers parsed was zero\")\n phone_tier_pattern = re.compile(r\"(.*) ?- ?phones\")\n for tier_name in tg.tierNameList:\n ti = tg.tierDict[tier_name]\n if not isinstance(ti, tgio.IntervalTier):\n continue\n if \"phones\" not in tier_name:\n continue\n m = phone_tier_pattern.match(tier_name)\n if m:\n speaker_name = m.groups()[0]\n elif root_speaker:\n speaker_name = root_speaker\n else:\n speaker_name = \"\"\n if speaker_name not in data:\n data[speaker_name] = []\n for begin, end, text in ti.entryList:\n text = text.lower().strip()\n if not text:\n continue\n begin, end = round(begin, 4), round(end, 4)\n if end - begin < 0.01:\n continue\n interval = CtmInterval(begin, end, text, speaker_name)\n data[speaker_name].append(interval)\n return data\nmontreal_forced_aligner/helper.py\ndef load_scp(path: str, data_type: Optional[Type] = str) -> CorpusMappingType:\n \"\"\"\n Load a Kaldi script file (.scp)\n\n Scp files in Kaldi can either be one-to-one or one-to-many, with the first element separated by\n whitespace as the key and the remaining whitespace-delimited elements the values.\n\n Returns a dictionary of key to value for\n one-to-one mapping case and a dictionary of key to list of values for one-to-many case.\n\n See Also\n --------\n :kaldi_docs:`io#io_sec_scp_details`\n For more information on the SCP format\n\n Parameters\n ----------\n path : str\n Path to Kaldi script file\n data_type : type\n Type to coerce the data to\n\n Returns\n -------\n CorpusMappingType\n Dictionary where the keys are the first column and the values are all\n other columns in the scp file\n\n \"\"\"\n scp = {}\n with open(path, \"r\", encoding=\"utf8\") as f:\n for line in f:\n line = line.strip()\n if line == \"\":\n continue\n line_list = line.split()\n key = load_scp_safe(line_list.pop(0))\n if len(line_list) == 1:\n value = data_type(line_list[0])\n if isinstance(value, str):\n value = load_scp_safe(value)\n else:\n value = [data_type(x) for x in line_list if x not in [\"[\", \"]\"]]\n scp[key] = value\n return scp\nmontreal_forced_aligner/corpus/helper.py\ndef find_exts(files: typing.List[str]) -> FileExtensions:\n \"\"\"\n Find and group sound file extensions and transcription file extensions\n\n Parameters\n ----------\n files: List\n List of filename\n\n Returns\n -------\n :class:`~montreal_forced_aligner.data.FileExtensions`\n Data class for files found\n \"\"\"\n exts = FileExtensions([], {}, {}, {}, {})\n for full_filename in files:\n filename, fext = os.path.splitext(full_filename)\n fext = fext.lower()\n if fext == \".wav\":\n exts.wav_files[filename] = full_filename\n elif fext == \".lab\":\n exts.lab_files[filename] = full_filename\n elif (\n fext == \".txt\" and filename not in exts.lab_files\n ): # .lab files have higher priority than .txt files\n exts.lab_files[filename] = full_filename\n elif fext == \".textgrid\":\n exts.textgrid_files[filename] = full_filename\n elif fext in supported_audio_extensions and shutil.which(\"sox\") is not None:\n exts.other_audio_files[filename] = full_filename\n if filename not in exts.identifiers:\n exts.identifiers.append(filename)\n return exts\nmontreal_forced_aligner/abc.py\nclass TemporaryDirectoryMixin(metaclass=abc.ABCMeta):\n \"\"\"\n Abstract mixin class for MFA temporary directories\n\n Parameters\n ----------\n temporary_directory: str, optional\n Path to store temporary files\n \"\"\"\n\n def __init__(\n self,\n temporary_directory: str = None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n if not temporary_directory:\n from .config import get_temporary_directory\n\n temporary_directory = get_temporary_directory()\n self.temporary_directory = temporary_directory\n self._corpus_output_directory = None\n self._dictionary_output_directory = None\n self._language_model_output_directory = None\n\n @property\n @abc.abstractmethod\n def identifier(self) -> str:\n \"\"\"Identifier to use in creating the temporary directory\"\"\"\n ...\n\n @property\n @abc.abstractmethod\n def data_source_identifier(self) -> str:\n \"\"\"Identifier for the data source (generally the corpus being used)\"\"\"\n ...\n\n @property\n @abc.abstractmethod\n def output_directory(self) -> str:\n \"\"\"Root temporary directory\"\"\"\n ...\n\n @property\n def corpus_output_directory(self) -> str:\n \"\"\"Temporary directory containing all corpus information\"\"\"\n if self._corpus_output_directory:\n return self._corpus_output_directory\n return os.path.join(self.output_directory, f\"{self.data_source_identifier}\")\n\n @corpus_output_directory.setter\n def corpus_output_directory(self, directory: str) -> None:\n self._corpus_output_director = directory\n\n @property\n def dictionary_output_directory(self) -> str:\n \"\"\"Temporary directory containing all dictionary information\"\"\"\n if self._dictionary_output_directory:\n return self._dictionary_output_directory\n return os.path.join(self.output_directory, \"dictionary\")\n\n @dictionary_output_directory.setter\n def dictionary_output_directory(self, directory: str) -> None:\n self._dictionary_output_directory = directory\n\n @property\n def language_model_output_directory(self) -> str:\n \"\"\"Temporary directory containing all dictionary information\"\"\"\n if self._language_model_output_directory:\n return self._language_model_output_directory\n return os.path.join(self.output_directory, \"language_model\")\n\n @language_model_output_directory.setter\n def language_model_output_directory(self, directory: str) -> None:\n self._language_model_output_directory = directory\nmontreal_forced_aligner/abc.py\nclass MfaWorker(metaclass=abc.ABCMeta):\n \"\"\"\n Abstract class for MFA workers\n\n Parameters\n ----------\n use_mp: bool\n Flag to run in multiprocessing mode, defaults to True\n debug: bool\n Flag to run in debug mode, defaults to False\n verbose: bool\n Flag to run in verbose mode, defaults to False\n\n Attributes\n ----------\n dirty: bool\n Flag for whether an error was encountered in processing\n \"\"\"\n\n def __init__(\n self,\n use_mp: bool = True,\n debug: bool = False,\n verbose: bool = False,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.debug = debug\n self.verbose = verbose\n self.use_mp = use_mp\n self.dirty = False\n\n def log_debug(self, message: str) -> None:\n \"\"\"\n Print a debug message\n\n Parameters\n ----------\n message: str\n Debug message to log\n \"\"\"\n print(message)\n\n def log_error(self, message: str) -> None:\n \"\"\"\n Print an error message\n\n Parameters\n ----------\n message: str\n Error message to log\n \"\"\"\n print(message)\n\n def log_info(self, message: str) -> None:\n \"\"\"\n Print an info message\n\n Parameters\n ----------\n message: str\n Info message to log\n \"\"\"\n print(message)\n\n def log_warning(self, message: str) -> None:\n \"\"\"\n Print a warning message\n\n Parameters\n ----------\n message: str\n Warning message to log\n \"\"\"\n print(message)\n\n @classmethod\n def extract_relevant_parameters(cls, config: MetaDict) -> Tuple[MetaDict, List[str]]:\n \"\"\"\n Filter a configuration dictionary to just the relevant parameters for the current worker\n\n Parameters\n ----------\n config: dict[str, Any]\n Configuration dictionary\n\n Returns\n -------\n dict[str, Any]\n Filtered configuration dictionary\n list[str]\n Skipped keys\n \"\"\"\n skipped = []\n new_config = {}\n for k, v in config.items():\n if k in cls.get_configuration_parameters():\n new_config[k] = v\n else:\n skipped.append(k)\n return new_config, skipped\n\n @classmethod\n def get_configuration_parameters(cls) -> Dict[str, Type]:\n \"\"\"\n Get the types of parameters available to be configured\n\n Returns\n -------\n dict[str, Type]\n Dictionary of parameter names and their types\n \"\"\"\n mapping = {Dict: dict, Tuple: tuple, List: list, Set: set}\n configuration_params = {}\n for t, ty in get_type_hints(cls.__init__).items():\n configuration_params[t] = ty\n try:\n if ty.__origin__ == Union:\n configuration_params[t] = ty.__args__[0]\n except AttributeError:\n pass\n\n for c in cls.mro():\n try:\n for t, ty in get_type_hints(c.__init__).items():\n configuration_params[t] = ty\n try:\n if ty.__origin__ == Union:\n configuration_params[t] = ty.__args__[0]\n except AttributeError:\n pass\n except AttributeError:\n pass\n for t, ty in configuration_params.items():\n for v in mapping.values():\n try:\n if ty.__origin__ == v:\n configuration_params[t] = v\n break\n except AttributeError:\n break\n return configuration_params\n\n @property\n def configuration(self) -> MetaDict:\n \"\"\"Configuration parameters\"\"\"\n return {\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"use_mp\": self.use_mp,\n \"dirty\": self.dirty,\n }\n\n @property\n @abc.abstractmethod\n def working_directory(self) -> str:\n \"\"\"Current working directory\"\"\"\n ...\n\n @property\n def working_log_directory(self) -> str:\n \"\"\"Current working log directory\"\"\"\n return os.path.join(self.working_directory, \"log\")\n\n @property\n @abc.abstractmethod\n def data_directory(self) -> str:\n \"\"\"Data directory\"\"\"\n ...\nmontreal_forced_aligner/utils.py\nclass Stopped(object):\n \"\"\"\n Multiprocessing class for detecting whether processes should stop processing and exit ASAP\n\n Attributes\n ----------\n val: :func:`~multiprocessing.Value`\n 0 if not stopped, 1 if stopped\n lock: :class:`~multiprocessing.Lock`\n Lock for process safety\n _source: multiprocessing.Value\n 1 if it was a Ctrl+C event that stopped it, 0 otherwise\n \"\"\"\n\n def __init__(self, initval: Union[bool, int] = False):\n self.val = mp.Value(\"i\", initval)\n self.lock = mp.Lock()\n self._source = mp.Value(\"i\", 0)\n\n def stop(self) -> None:\n \"\"\"Signal that work should stop asap\"\"\"\n with self.lock:\n self.val.value = True\n\n def stop_check(self) -> int:\n \"\"\"Check whether a process should stop\"\"\"\n with self.lock:\n return self.val.value\n\n def set_sigint_source(self) -> None:\n \"\"\"Set the source as a ctrl+c\"\"\"\n with self.lock:\n self._source.value = True\n\n def source(self) -> int:\n \"\"\"Get the source value\"\"\"\n with self.lock:\n return self._source.value\nmontreal_forced_aligner/data.py\nclass TextFileType(enum.Enum):\n \"\"\"Enum for types of text files\"\"\"\n\n NONE = 0\n TEXTGRID = 1\n LAB = 2\nmontreal_forced_aligner/corpus/classes.py\nclass File(MfaCorpusClass):\n \"\"\"\n File class for representing metadata and associations of Files\n\n Parameters\n ----------\n wav_path: str, optional\n Sound file path\n text_path: str, optional\n Transcription file path\n relative_path: str, optional\n Relative path to the corpus root\n\n Attributes\n ----------\n utterances: :class:`~montreal_forced_aligner.corpus.classes.UtteranceCollection`\n Utterances in the file\n speaker_ordering: list[Speaker]\n Ordering of speakers in the transcription file\n wav_info: :class:`~montreal_forced_aligner.data.SoundFileInformation`\n Information about sound file\n waveform: numpy.array\n Audio samples\n aligned: bool\n Flag for whether a file has alignments\n\n Raises\n ------\n :class:`~montreal_forced_aligner.exceptions.CorpusError`\n If both wav_path and text_path are None\n \"\"\"\n\n textgrid_regex = re.compile(r\"\\.textgrid$\", flags=re.IGNORECASE)\n wav_regex = re.compile(r\"\\.wav$\", flags=re.IGNORECASE)\n\n def __init__(\n self,\n wav_path: Optional[str] = None,\n text_path: Optional[str] = None,\n relative_path: Optional[str] = None,\n name: Optional[str] = None,\n ):\n self.wav_path = wav_path\n self.text_path = text_path\n wav_check = self.wav_path is not None\n text_check = self.text_path is not None\n self._name = name\n if not self._name:\n if wav_check:\n self._name = os.path.splitext(os.path.basename(self.wav_path))[0]\n elif text_check:\n self._name = os.path.splitext(os.path.basename(self.text_path))[0]\n else:\n raise CorpusError(\"File objects must have either a wav_path or text_path\")\n self.relative_path = relative_path\n self.wav_info: Optional[SoundFileInformation] = None\n self.waveform = None\n self.speaker_ordering: List[Speaker] = []\n self.utterances = UtteranceCollection()\n self.aligned = False\n if text_check:\n if self.text_path.lower().endswith(\".textgrid\"):\n self.text_type = TextFileType.TEXTGRID\n else:\n self.text_type = TextFileType.LAB\n else:\n self.text_type = TextFileType.NONE\n if wav_check:\n\n if self.wav_path.lower().endswith(\".wav\"):\n self.sound_type = SoundFileType.WAV\n else:\n self.sound_type = SoundFileType.SOX\n else:\n self.sound_type = SoundFileType.NONE\n\n @property\n def multiprocessing_data(self) -> FileData:\n \"\"\"\n Data object for the file\n \"\"\"\n return FileData(\n self._name,\n self.wav_path,\n self.text_path,\n self.relative_path,\n self.wav_info,\n [s.name for s in self.speaker_ordering],\n [u.multiprocessing_data for u in self.utterances],\n )\n\n @classmethod\n def load_from_mp_data(cls, file_data: FileData) -> File:\n \"\"\"\n Construct a File from a multiprocessing file data class\n\n Parameters\n ----------\n file_data: :class:`~montreal_forced_aligner.data.FileData`\n Data for the loaded file\n\n Returns\n -------\n :class:`~montreal_forced_aligner.corpus.classes.File`\n Loaded file\n \"\"\"\n file = File(\n file_data.wav_path,\n file_data.text_path,\n relative_path=file_data.relative_path,\n name=file_data.name,\n )\n file.wav_info = file_data.wav_info\n for s in file_data.speaker_ordering:\n file.add_speaker(Speaker(s))\n for u in file_data.utterances:\n u = Utterance.load_from_mp_data(u, file)\n file.utterances.add_utterance(u)\n return file\n\n @classmethod\n def parse_file(\n cls,\n file_name: str,\n wav_path: Optional[str],\n text_path: Optional[str],\n relative_path: str,\n speaker_characters: Union[int, str],\n sanitize_function: Optional[MultispeakerSanitizationFunction] = None,\n ):\n \"\"\"\n Parse a collection of sound file and transcription file into a File\n\n Parameters\n ----------\n file_name: str\n File identifier\n wav_path: str\n Full sound file path\n text_path: str\n Full transcription path\n relative_path: str\n Relative path from the corpus directory root\n speaker_characters: int, optional\n Number of characters in the file name to specify the speaker\n sanitize_function: Callable, optional\n Function to sanitize words and strip punctuation\n\n Returns\n -------\n :class:`~montreal_forced_aligner.corpus.classes.File`\n Parsed file\n \"\"\"\n file = File(wav_path, text_path, relative_path=relative_path, name=file_name)\n if file.has_sound_file:\n root = os.path.dirname(wav_path)\n file.wav_info = get_wav_info(wav_path)\n else:\n root = os.path.dirname(text_path)\n if not speaker_characters:\n speaker_name = os.path.basename(root)\n elif isinstance(speaker_characters, int):\n speaker_name = file_name[:speaker_characters]\n elif speaker_characters == \"prosodylab\":\n speaker_name = file_name.split(\"_\")[1]\n else:\n speaker_name = file_name\n root_speaker = None\n if speaker_characters or file.text_type != TextFileType.TEXTGRID:\n root_speaker = Speaker(speaker_name)\n file.load_text(\n root_speaker=root_speaker,\n sanitize_function=sanitize_function,\n )\n return file\n\n def __eq__(self, other: Union[File, str]) -> bool:\n \"\"\"Check if a File is equal to another File\"\"\"\n if isinstance(other, File):\n return other.name == self.name\n if isinstance(other, str):\n return self.name == other\n raise TypeError(\"Files can only be compared to other files and strings.\")\n\n def __lt__(self, other: Union[File, str]) -> bool:\n \"\"\"Check if a File is less than another File\"\"\"\n if isinstance(other, File):\n return other.name < self.name\n if isinstance(other, str):\n return self.name < other\n raise TypeError(\"Files can only be compared to other files and strings.\")\n\n def __gt__(self, other: Union[File, str]) -> bool:\n \"\"\"Check if a File is greater than another File\"\"\"\n if isinstance(other, File):\n return other.name > self.name\n if isinstance(other, str):\n return self.name > other\n raise TypeError(\"Files can only be compared to other files and strings.\")\n\n def __hash__(self) -> hash:\n \"\"\"Get the hash of the file\"\"\"\n return hash(self.name)\n\n @property\n def name(self) -> str:\n \"\"\"Name of the file\"\"\"\n name = self._name\n if self.relative_path:\n prefix = self.relative_path.replace(\"/\", \"\").replace(\"\\\\\", \"\")\n if not name.startswith(prefix):\n name = f\"{prefix}_{name}\"\n return name\n\n @property\n def is_fully_aligned(self) -> bool:\n \"\"\"\n Check if all utterances have been aligned\n \"\"\"\n for u in self.utterances:\n if u.ignored:\n continue\n if u.word_labels is None:\n return False\n if u.phone_labels is None:\n return False\n return True\n\n def __repr__(self) -> str:\n \"\"\"Representation of File objects\"\"\"\n return f''\n\n def save(\n self,\n output_directory: Optional[str] = None,\n text_type: Optional[TextFileType] = None,\n save_transcription: bool = False,\n ) -> None:\n \"\"\"\n Output File to TextGrid or lab. If ``text_type`` is not specified, the original file type will be used,\n but if there was no text file for the file, it will guess lab format if there is only one utterance, otherwise\n it will output a TextGrid file.\n\n Parameters\n ----------\n output_directory: str, optional\n Directory to output file, if None, then it will overwrite the original file\n backup_output_directory: str, optional\n If specified, then it will check whether it would overwrite an existing file and\n instead use this directory\n text_type: TextFileType, optional\n Text type to save as, if not provided, it will use either the original file type or guess the file type\n save_transcription: bool\n Flag for whether the hypothesized transcription text should be saved instead of the default text\n \"\"\"\n utterance_count = len(self.utterances)\n if text_type is None:\n text_type = self.text_type\n if text_type == TextFileType.NONE:\n if utterance_count == 1:\n text_type = TextFileType.LAB\n else:\n text_type = TextFileType.TEXTGRID\n if text_type == TextFileType.LAB:\n if utterance_count == 0 and os.path.exists(self.text_path) and not save_transcription:\n os.remove(self.text_path)\n return\n elif utterance_count == 0:\n return\n output_path = self.construct_output_path(output_directory, enforce_lab=True)\n with open(output_path, \"w\", encoding=\"utf8\") as f:\n for u in self.utterances:\n if save_transcription:\n f.write(u.transcription_text if u.transcription_text else \"\")\n else:\n f.write(u.text)\n return\n elif text_type == TextFileType.TEXTGRID:\n output_path = self.construct_output_path(output_directory)\n max_time = self.duration\n tiers = {}\n for speaker in self.speaker_ordering:\n if speaker is None:\n tiers[\"speech\"] = textgrid.IntervalTier(\"speech\", [], minT=0, maxT=max_time)\n else:\n tiers[speaker] = textgrid.IntervalTier(speaker.name, [], minT=0, maxT=max_time)\n\n tg = textgrid.Textgrid()\n tg.maxTimestamp = max_time\n for utterance in self.utterances:\n\n if utterance.speaker is None:\n speaker = \"speech\"\n else:\n speaker = utterance.speaker\n if not self.aligned:\n\n if save_transcription:\n tiers[speaker].entryList.append(\n Interval(\n start=utterance.begin,\n end=utterance.end,\n label=utterance.transcription_text\n if utterance.transcription_text\n else \"\",\n )\n )\n else:\n tiers[speaker].entryList.append(\n Interval(\n start=utterance.begin, end=utterance.end, label=utterance.text\n )\n )\n for t in tiers.values():\n tg.addTier(t)\n tg.save(output_path, includeBlankSpaces=True, format=\"long_textgrid\")\n\n @property\n def meta(self) -> Dict[str, Any]:\n \"\"\"Metadata for the File\"\"\"\n return {\n \"wav_path\": self.wav_path,\n \"text_path\": self.text_path,\n \"name\": self._name,\n \"relative_path\": self.relative_path,\n \"wav_info\": self.wav_info.meta,\n \"speaker_ordering\": [x.name for x in self.speaker_ordering],\n }\n\n @property\n def has_sound_file(self) -> bool:\n \"\"\"Flag for whether the File has a sound file\"\"\"\n return self.sound_type != SoundFileType.NONE\n\n @property\n def has_text_file(self) -> bool:\n \"\"\"Flag for whether the File has a text file\"\"\"\n return self.text_type != TextFileType.NONE\n\n @property\n def aligned_data(self) -> Dict[str, Dict[str, List[CtmInterval]]]:\n \"\"\"\n Word and phone alignments for the file\n\n Returns\n -------\n dict[str, dict[str, list[CtmInterval]]]\n Dictionary of word and phone intervals for each speaker in the file\n \"\"\"\n data = {}\n for s in self.speaker_ordering:\n if s.name not in data:\n data[s.name] = {\"words\": [], \"phones\": []}\n for u in self.utterances:\n if u.word_labels is None:\n continue\n data[u.speaker_name][\"words\"].extend(u.word_labels)\n data[u.speaker_name][\"phones\"].extend(u.phone_labels)\n return data\n\n def clean_up(self) -> None:\n \"\"\"\n Recombine words that were split up as part of initial text processing\n \"\"\"\n for u in self.utterances:\n if not u.word_labels:\n continue\n cur_ind = 0\n actual_labels = []\n dictionary = u.speaker.dictionary\n for word in u.text.split():\n splits = dictionary.lookup(word)\n b = 1000000\n e = -1\n for w in splits:\n cur = u.word_labels[cur_ind]\n if w == cur.label or cur.label == dictionary.oov_word:\n if cur.begin < b:\n b = cur.begin\n if cur.end > e:\n e = cur.end\n cur_ind += 1\n lab = CtmInterval(b, e, word, u.name)\n actual_labels.append(lab)\n u.word_labels = actual_labels\n u.phone_labels = [\n x for x in u.phone_labels if x.label != dictionary.optional_silence_phone\n ]\n\n def construct_output_path(\n self,\n output_directory: Optional[str] = None,\n enforce_lab: bool = False,\n ) -> str:\n \"\"\"\n Construct the output path for the File\n\n Parameters\n ----------\n output_directory: str, optional\n Directory to output to, if None, it will overwrite the original file\n enforce_lab: bool\n Flag for whether to enforce generating a lab file over a TextGrid\n\n Returns\n -------\n str\n Output path\n \"\"\"\n if enforce_lab:\n extension = \".lab\"\n else:\n extension = \".TextGrid\"\n if output_directory is None:\n if self.text_path is None:\n return os.path.splitext(self.wav_path)[0] + extension\n return self.text_path\n if self.relative_path:\n relative = os.path.join(output_directory, self.relative_path)\n else:\n relative = output_directory\n tg_path = os.path.join(relative, self._name + extension)\n os.makedirs(os.path.dirname(tg_path), exist_ok=True)\n return tg_path\n\n def load_text(\n self,\n root_speaker: Optional[Speaker] = None,\n sanitize_function: Optional[MultispeakerSanitizationFunction] = None,\n ) -> None:\n \"\"\"\n Load the transcription text from the text_file of the object\n\n Parameters\n ----------\n root_speaker: :class:`~montreal_forced_aligner.corpus.classes.Speaker`, optional\n Speaker derived from the root directory, ignored for TextGrids\n sanitize_function: :class:`~montreal_forced_aligner.dictionary.mixins.SanitizeFunction`, optional\n Function to sanitize words and strip punctuation\n \"\"\"\n if self.text_type == TextFileType.LAB:\n try:\n text = load_text(self.text_path)\n except UnicodeDecodeError:\n raise TextParseError(self.text_path)\n utterance = Utterance(speaker=root_speaker, file=self, text=text)\n utterance.parse_transcription(sanitize_function)\n self.add_utterance(utterance)\n elif self.text_type == TextFileType.TEXTGRID:\n try:\n tg = textgrid.openTextgrid(self.text_path, includeEmptyIntervals=False)\n except Exception:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n raise TextGridParseError(\n self.text_path,\n \"\\n\".join(traceback.format_exception(exc_type, exc_value, exc_traceback)),\n )\n\n num_tiers = len(tg.tierNameList)\n if num_tiers == 0:\n raise TextGridParseError(self.text_path, \"Number of tiers parsed was zero\")\n if self.num_channels > 2:\n raise (Exception(\"More than two channels\"))\n for tier_name in tg.tierNameList:\n ti = tg.tierDict[tier_name]\n if tier_name.lower() == \"notes\":\n continue\n if not isinstance(ti, textgrid.IntervalTier):\n continue\n if not root_speaker:\n speaker_name = tier_name.strip()\n speaker = Speaker(speaker_name)\n self.add_speaker(speaker)\n else:\n speaker = root_speaker\n for begin, end, text in ti.entryList:\n text = text.lower().strip()\n if not text:\n continue\n begin, end = round(begin, 4), round(end, 4)\n end = min(end, self.duration)\n utt = Utterance(speaker=speaker, file=self, begin=begin, end=end, text=text)\n utt.parse_transcription(sanitize_function)\n if not utt.text:\n continue\n self.add_utterance(utt)\n else:\n utterance = Utterance(speaker=root_speaker, file=self)\n self.add_utterance(utterance)\n\n def add_speaker(self, speaker: Speaker) -> None:\n \"\"\"\n Add a speaker to a file\n\n Parameters\n ----------\n speaker: :class:`~montreal_forced_aligner.corpus.classes.Speaker`\n Speaker to add\n \"\"\"\n if speaker not in self.speaker_ordering:\n self.speaker_ordering.append(speaker)\n\n def add_utterance(self, utterance: Utterance) -> None:\n \"\"\"\n Add an utterance to a file\n\n Parameters\n ----------\n utterance: :class:`~montreal_forced_aligner.corpus.classes.Utterance`\n Utterance to add\n \"\"\"\n self.utterances.add_utterance(utterance)\n self.add_speaker(utterance.speaker)\n\n def delete_utterance(self, utterance: Utterance) -> None:\n \"\"\"\n Delete an utterance from the file\n\n Parameters\n ----------\n utterance: :class:`~montreal_forced_aligner.corpus.classes.Utterance`\n Utterance to remove\n \"\"\"\n identifier = utterance.name\n del self.utterances[identifier]\n\n def load_info(self) -> None:\n \"\"\"\n Load sound file info if it hasn't been already\n \"\"\"\n if self.wav_path is not None:\n self.wav_info = get_wav_info(self.wav_path)\n\n @property\n def duration(self) -> float:\n \"\"\"Get the duration of the sound file\"\"\"\n if self.wav_path is None:\n return 0\n if not self.wav_info:\n self.load_info()\n return self.wav_info.duration\n\n @property\n def num_channels(self) -> int:\n \"\"\"Get the number of channels of the sound file\"\"\"\n if self.wav_path is None:\n return 0\n if not self.wav_info:\n self.load_info()\n return self.wav_info.num_channels\n\n @property\n def num_utterances(self) -> int:\n \"\"\"Get the number of utterances for the sound file\"\"\"\n return len(self.utterances)\n\n @property\n def num_speakers(self) -> int:\n \"\"\"Get the number of speakers in the sound file\"\"\"\n return len(self.speaker_ordering)\n\n @property\n def sample_rate(self) -> int:\n \"\"\"Get the sample rate of the sound file\"\"\"\n if self.wav_path is None:\n return 0\n if not self.wav_info:\n self.load_info()\n return self.wav_info.sample_rate\n\n @property\n def format(self) -> str:\n \"\"\"Get the sound file format\"\"\"\n if not self.wav_info:\n self.load_info()\n return self.wav_info.format\n\n @property\n def sox_string(self) -> str:\n \"\"\"String used for converting sound file via SoX within Kaldi\"\"\"\n if not self.wav_info:\n self.load_info()\n return self.wav_info.sox_string\n\n def load_wav_data(self) -> None:\n \"\"\"\n Load the sound file into memory as a numpy array\n \"\"\"\n self.waveform, _ = librosa.load(self.wav_path, sr=None, mono=False)\n\n def normalized_waveform(\n self, begin: float = 0, end: Optional[float] = None\n ) -> Tuple[np.array, np.array]:\n if self.waveform is None:\n self.load_wav_data()\n if end is None or end > self.duration:\n end = self.duration\n\n begin_sample = int(begin * self.sample_rate)\n end_sample = int(end * self.sample_rate)\n if len(self.waveform.shape) > 1 and self.waveform.shape[0] == 2:\n y = self.waveform[:, begin_sample:end_sample] / np.max(\n np.abs(self.waveform[:, begin_sample:end_sample]), axis=0\n )\n y[np.isnan(y)] = 0\n else:\n y = self.waveform[begin_sample:end_sample] / np.max(\n np.abs(self.waveform[begin_sample:end_sample]), axis=0\n )\n x = np.arange(start=begin_sample, stop=end_sample) / self.sample_rate\n return x, y\n\n def for_wav_scp(self) -> str:\n \"\"\"\n Generate the string to use in feature generation\n\n Returns\n -------\n str\n SoX string if necessary, the sound file path otherwise\n \"\"\"\n if self.sox_string:\n return self.sox_string\n return self.wav_path\nmontreal_forced_aligner/dictionary/multispeaker.py\nclass MultispeakerDictionaryMixin(TemporaryDictionaryMixin, metaclass=abc.ABCMeta):\n \"\"\"\n Mixin class containing information about a pronunciation dictionary with different dictionaries per speaker\n\n Parameters\n ----------\n dictionary_path : str\n Dictionary path\n kwargs : kwargs\n Extra parameters to passed to parent classes (see below)\n\n See Also\n --------\n :class:`~montreal_forced_aligner.dictionary.mixins.DictionaryMixin`\n For dictionary parsing parameters\n :class:`~montreal_forced_aligner.abc.TemporaryDirectoryMixin`\n For temporary directory parameters\n\n\n Attributes\n ----------\n dictionary_model: :class:`~montreal_forced_aligner.models.DictionaryModel`\n Dictionary model\n speaker_mapping: dict[str, str]\n Mapping of speaker names to dictionary names\n dictionary_mapping: dict[str, :class:`~montreal_forced_aligner.dictionary.pronunciation.PronunciationDictionary`]\n Mapping of dictionary names to pronunciation dictionary\n \"\"\"\n\n def __init__(self, dictionary_path: str = None, **kwargs):\n super().__init__(**kwargs)\n self.dictionary_model = DictionaryModel(\n dictionary_path, phone_set_type=self.phone_set_type\n )\n self.speaker_mapping = {}\n self.dictionary_mapping: Dict[str, PronunciationDictionary] = {}\n\n @property\n def sanitize_function(self) -> MultispeakerSanitizationFunction:\n \"\"\"Sanitization function for the dictionary\"\"\"\n sanitize_function = SanitizeFunction(\n self.punctuation,\n self.clitic_markers,\n self.compound_markers,\n self.brackets,\n self.ignore_case,\n )\n split_functions = {}\n for dictionary_name, dictionary in self.dictionary_mapping.items():\n split_functions[dictionary_name] = SplitWordsFunction(\n self.clitic_markers,\n self.compound_markers,\n dictionary.clitic_set,\n set(dictionary.actual_words.keys()),\n )\n return MultispeakerSanitizationFunction(\n self.speaker_mapping, sanitize_function, split_functions\n )\n\n def dictionary_setup(self):\n \"\"\"Setup the dictionary for processing\"\"\"\n auto_set = {PhoneSetType.AUTO, PhoneSetType.UNKNOWN, \"AUTO\", \"UNKNOWN\"}\n if not isinstance(self.phone_set_type, PhoneSetType):\n self.phone_set_type = PhoneSetType[self.phone_set_type]\n\n options = self.dictionary_options\n pretrained = False\n if self.non_silence_phones:\n pretrained = True\n\n for speaker, dictionary in self.dictionary_model.load_dictionary_paths().items():\n self.speaker_mapping[speaker] = dictionary.name\n if dictionary.name not in self.dictionary_mapping:\n if not pretrained:\n options[\"non_silence_phones\"] = set()\n self.dictionary_mapping[dictionary.name] = PronunciationDictionary(\n dictionary_path=dictionary.path,\n temporary_directory=self.dictionary_output_directory,\n root_dictionary=self,\n **options,\n )\n if self.phone_set_type not in auto_set:\n if (\n self.phone_set_type\n != self.dictionary_mapping[dictionary.name].phone_set_type\n ):\n raise DictionaryError(\n f\"Mismatch found in phone sets: {self.phone_set_type} vs {self.dictionary_mapping[dictionary.name].phone_set_type}\"\n )\n else:\n self.phone_set_type = self.dictionary_mapping[dictionary.name].phone_set_type\n\n self.excluded_phones.update(\n self.dictionary_mapping[dictionary.name].excluded_phones\n )\n self.excluded_pronunciation_count += self.dictionary_mapping[\n dictionary.name\n ].excluded_pronunciation_count\n for dictionary in self.dictionary_mapping.values():\n self.non_silence_phones.update(dictionary.non_silence_phones)\n for dictionary in self.dictionary_mapping.values():\n dictionary.non_silence_phones = self.non_silence_phones\n\n @property\n def name(self) -> str:\n \"\"\"Name of the dictionary\"\"\"\n return self.dictionary_model.name\n\n def calculate_oovs_found(self) -> None:\n \"\"\"Sum the counts of oovs found in pronunciation dictionaries\"\"\"\n for dictionary in self.dictionary_mapping.values():\n self.oovs_found.update(dictionary.oovs_found)\n self.save_oovs_found(self.output_directory)\n\n @property\n def default_dictionary(self) -> PronunciationDictionary:\n \"\"\"Default pronunciation dictionary\"\"\"\n return self.get_dictionary(\"default\")\n\n def get_dictionary_name(self, speaker: Union[str, Speaker]) -> str:\n \"\"\"\n Get the dictionary name for a given speaker\n\n Parameters\n ----------\n speaker: Union[Speaker, str]\n Speaker to look up\n\n Returns\n -------\n str\n Dictionary name for the speaker\n \"\"\"\n if not isinstance(speaker, str):\n speaker = speaker.name\n if speaker not in self.speaker_mapping:\n return self.speaker_mapping[\"default\"]\n return self.speaker_mapping[speaker]\n\n def get_dictionary(self, speaker: Union[Speaker, str]) -> PronunciationDictionary:\n \"\"\"\n Get a dictionary for a given speaker\n\n Parameters\n ----------\n speaker: Union[Speaker, str]\n Speaker to look up\n\n Returns\n -------\n :class:`~montreal_forced_aligner.dictionary.PronunciationDictionary`\n Pronunciation dictionary for the speaker\n \"\"\"\n return self.dictionary_mapping[self.get_dictionary_name(speaker)]\n\n def write_lexicon_information(self, write_disambiguation: Optional[bool] = False) -> None:\n \"\"\"\n Write all child dictionaries to the temporary directory\n\n Parameters\n ----------\n write_disambiguation: bool, optional\n Flag to use disambiguation symbols in the output\n \"\"\"\n os.makedirs(self.phones_dir, exist_ok=True)\n for d in self.dictionary_mapping.values():\n d.generate_mappings()\n if d.max_disambiguation_symbol > self.max_disambiguation_symbol:\n self.max_disambiguation_symbol = d.max_disambiguation_symbol\n self._write_word_boundaries()\n self._write_phone_sets()\n self._write_phone_symbol_table()\n self._write_disambig()\n self._write_topo()\n self._write_extra_questions()\n for d in self.dictionary_mapping.values():\n d.write(write_disambiguation, debug=getattr(self, \"debug\", False))\n\n def set_lexicon_word_set(self, word_set: Collection[str]) -> None:\n \"\"\"\n Limit output to a subset of overall words\n\n Parameters\n ----------\n word_set: Collection[str]\n Word set to limit generated files to\n \"\"\"\n for d in self.dictionary_mapping.values():\n d.set_lexicon_word_set(word_set)\n\n @property\n def output_paths(self) -> Dict[str, str]:\n \"\"\"\n Mapping of output directory for child directories\n \"\"\"\n return {d.name: d.dictionary_output_directory for d in self.dictionary_mapping.values()}\nmontreal_forced_aligner/corpus/features.py\nclass MfccArguments(NamedTuple):\n \"\"\"\n Arguments for :class:`~montreal_forced_aligner.corpus.features.MfccFunction`\n \"\"\"\n\n log_path: str\n wav_path: str\n segment_path: str\n feats_scp_path: str\n mfcc_options: MetaDict\nmontreal_forced_aligner/corpus/base.py\nclass CorpusMixin(MfaWorker, TemporaryDirectoryMixin, metaclass=ABCMeta):\n \"\"\"\n Mixin class for processing corpora\n\n Notes\n -----\n Using characters in files to specify speakers is generally finicky and leads to errors, so I would not\n recommend using it. Additionally, consider it deprecated and could be removed in future versions\n\n Parameters\n ----------\n corpus_directory: str\n Path to corpus\n speaker_characters: int or str, optional\n Number of characters in the file name to specify the speaker\n ignore_speakers: bool\n Flag for whether to discard any parsed speaker information during top-level worker's processing\n\n See Also\n --------\n :class:`~montreal_forced_aligner.abc.MfaWorker`\n For MFA processing parameters\n :class:`~montreal_forced_aligner.abc.TemporaryDirectoryMixin`\n For temporary directory parameters\n\n Attributes\n ----------\n speakers: :class:`~montreal_forced_aligner.corpus.classes.SpeakerCollection`\n Dictionary of speakers in the corpus\n files: :class:`~montreal_forced_aligner.corpus.classes.FileCollection`\n Dictionary of files in the corpus\n utterances: :class:`~montreal_forced_aligner.corpus.classes.UtteranceCollection`\n Dictionary of utterances in the corpus\n jobs: list[Job]\n List of jobs for processing the corpus and splitting speakers\n word_counts: Counter\n Counts of words in the corpus\n stopped: Stopped\n Stop check for loading the corpus\n decode_error_files: list[str]\n List of text files that could not be loaded with utf8\n textgrid_read_errors: list[str]\n List of TextGrid files that had an error in loading\n \"\"\"\n\n def __init__(\n self,\n corpus_directory: str,\n speaker_characters: Union[int, str] = 0,\n ignore_speakers: bool = False,\n **kwargs,\n ):\n if not os.path.exists(corpus_directory):\n raise CorpusError(f\"The directory '{corpus_directory}' does not exist.\")\n if not os.path.isdir(corpus_directory):\n raise CorpusError(\n f\"The specified path for the corpus ({corpus_directory}) is not a directory.\"\n )\n self.speakers = SpeakerCollection()\n self.files = FileCollection()\n self.utterances = UtteranceCollection()\n self.corpus_directory = corpus_directory\n self.speaker_characters = speaker_characters\n self.ignore_speakers = ignore_speakers\n self.word_counts = Counter()\n self.stopped = Stopped()\n self.decode_error_files = []\n self.textgrid_read_errors = {}\n self.jobs: List[Job] = []\n super().__init__(**kwargs)\n\n def _initialize_from_json(self, data):\n pass\n\n @property\n def corpus_meta(self):\n return {}\n\n @property\n def features_directory(self) -> str:\n \"\"\"Feature directory of the corpus\"\"\"\n return os.path.join(self.corpus_output_directory, \"features\")\n\n @property\n def features_log_directory(self) -> str:\n \"\"\"Feature log directory\"\"\"\n return os.path.join(self.split_directory, \"log\")\n\n @property\n def split_directory(self) -> str:\n \"\"\"Directory used to store information split by job\"\"\"\n return os.path.join(self.corpus_output_directory, f\"split{self.num_jobs}\")\n\n def write_corpus_information(self) -> None:\n \"\"\"\n Output information to the temporary directory for later loading\n \"\"\"\n os.makedirs(self.split_directory, exist_ok=True)\n self._write_speakers()\n self._write_files()\n self._write_utterances()\n self._write_spk2utt()\n self._write_corpus_info()\n\n def _write_spk2utt(self):\n \"\"\"Write spk2utt scp file for Kaldi\"\"\"\n data = {\n speaker.name: sorted(u.name for u in speaker.utterances) for speaker in self.speakers\n }\n output_mapping(data, os.path.join(self.corpus_output_directory, \"spk2utt.scp\"))\n\n def write_utt2spk(self):\n \"\"\"Write utt2spk scp file for Kaldi\"\"\"\n data = {u.name: u.speaker.name for u in self.utterances}\n output_mapping(data, os.path.join(self.corpus_output_directory, \"utt2spk.scp\"))\n\n def _write_corpus_info(self):\n \"\"\"Write speaker information for speeding up future runs\"\"\"\n with open(\n os.path.join(self.corpus_output_directory, \"corpus.json\"), \"w\", encoding=\"utf8\"\n ) as f:\n json.dump(self.corpus_meta, f)\n\n def _write_speakers(self):\n \"\"\"Write speaker information for speeding up future runs\"\"\"\n with open(\n os.path.join(self.corpus_output_directory, \"speakers.jsonl\"), \"w\", encoding=\"utf8\"\n ) as f:\n writer = jsonlines.Writer(f, dumps=jsonl_encoder)\n for speaker in self.speakers:\n writer.write(speaker.meta)\n\n def _write_files(self):\n \"\"\"Write file information for speeding up future runs\"\"\"\n with open(\n os.path.join(self.corpus_output_directory, \"files.jsonl\"), \"w\", encoding=\"utf8\"\n ) as f:\n writer = jsonlines.Writer(f, dumps=jsonl_encoder)\n for file in self.files:\n writer.write(file.meta)\n\n def _write_utterances(self):\n \"\"\"Write utterance information for speeding up future runs\"\"\"\n with open(\n os.path.join(self.corpus_output_directory, \"utterances.jsonl\"), \"w\", encoding=\"utf8\"\n ) as f:\n writer = jsonlines.Writer(f, dumps=jsonl_encoder)\n for utterance in self.utterances:\n writer.write(utterance.meta)\n\n def create_corpus_split(self) -> None:\n \"\"\"Create split directory and output information from Jobs\"\"\"\n split_dir = self.split_directory\n os.makedirs(os.path.join(split_dir, \"log\"), exist_ok=True)\n for job in self.jobs:\n job.output_to_directory(split_dir)\n\n @property\n def file_speaker_mapping(self) -> Dict[str, List[str]]:\n \"\"\"Speaker ordering for each file\"\"\"\n return {file.name: file.speaker_ordering for file in self.files}\n\n def get_word_frequency(self) -> Dict[str, float]:\n \"\"\"\n Calculate the relative word frequency across all the texts in the corpus\n\n Returns\n -------\n dict[str, float]\n Dictionary of words and their relative frequencies\n \"\"\"\n word_counts = Counter()\n for u in self.utterances:\n text = u.text\n speaker = u.speaker\n d = speaker.dictionary\n new_text = []\n text = text.split()\n for t in text:\n\n lookup = d.split_clitics(t)\n if lookup is None:\n continue\n new_text.extend(x for x in lookup if x != \"\")\n word_counts.update(new_text)\n return {k: v / sum(word_counts.values()) for k, v in word_counts.items()}\n\n @property\n def corpus_word_set(self) -> List[str]:\n \"\"\"Set of words used in the corpus\"\"\"\n return sorted(self.word_counts)\n\n def add_utterance(self, utterance: Utterance) -> None:\n \"\"\"\n Add an utterance to the corpus\n\n Parameters\n ----------\n utterance: :class:`~montreal_forced_aligner.corpus.classes.Utterance`\n Utterance to add\n \"\"\"\n self.utterances.add_utterance(utterance)\n if utterance.speaker not in self.speakers:\n self.speakers.add_speaker(utterance.speaker)\n speaker = self.speakers[utterance.speaker.name]\n speaker.add_utterance(utterance)\n utterance.speaker = speaker\n if utterance.file not in self.files:\n self.files.add_file(utterance.file)\n file = self.files[utterance.file.name]\n utterance.file = file\n file.add_utterance(utterance)\n utterance.file = file\n\n def delete_utterance(self, utterance: Union[str, Utterance]) -> None:\n \"\"\"\n Delete an utterance from the corpus\n\n Parameters\n ----------\n utterance: :class:`~montreal_forced_aligner.corpus.classes.Utterance`\n Utterance to delete\n \"\"\"\n if isinstance(utterance, str):\n utterance = self.utterances[utterance]\n speaker = self.speakers[utterance.speaker.name]\n file = self.files[utterance.file.name]\n speaker.delete_utterance(utterance)\n file.delete_utterance(utterance)\n del self.utterances[utterance.name]\n\n def initialize_jobs(self) -> None:\n \"\"\"\n Initialize the corpus's Jobs\n \"\"\"\n self.log_info(\"Setting up training data...\")\n if len(self.speakers) < self.num_jobs:\n self.num_jobs = len(self.speakers)\n self.jobs = [Job(i) for i in range(self.num_jobs)]\n job_ind = 0\n for s in sorted(self.speakers):\n self.jobs[job_ind].add_speaker(s)\n job_ind += 1\n if job_ind == self.num_jobs:\n job_ind = 0\n\n def add_file(self, file: File) -> None:\n \"\"\"\n Add a file to the corpus\n\n Parameters\n ----------\n file: :class:`~montreal_forced_aligner.corpus.classes.File`\n File to be added\n \"\"\"\n self.files.add_file(file)\n for i, speaker in enumerate(file.speaker_ordering):\n if speaker.name not in self.speakers:\n self.speakers.add_speaker(speaker)\n else:\n file.speaker_ordering[i] = self.speakers[speaker.name]\n for u in file.utterances:\n self.add_utterance(u)\n if u.text:\n self.word_counts.update(u.text.split())\n if u.normalized_text:\n self.word_counts.update(u.normalized_text)\n\n @property\n def data_source_identifier(self) -> str:\n \"\"\"Corpus name\"\"\"\n return os.path.basename(self.corpus_directory)\n\n def create_subset(self, subset: int) -> None:\n \"\"\"\n Create a subset of utterances to use for training\n\n Parameters\n ----------\n subset: int\n Number of utterances to include in subset\n \"\"\"\n self.log_debug(f\"Creating subset_{subset} directory...\")\n subset_directory = os.path.join(self.corpus_output_directory, f\"subset_{subset}\")\n\n larger_subset_num = subset * 10\n if larger_subset_num < len(self.utterances):\n # Get all shorter utterances that are not one word long\n utts = sorted(\n (utt for utt in self.utterances if utt.text and \" \" in utt.text),\n key=lambda x: x.duration,\n )\n larger_subset = utts[:larger_subset_num]\n else:\n larger_subset = sorted(self.utterances)\n random.seed(1234) # make it deterministic sampling\n subset_utts = UtteranceCollection()\n subset_utts.update(random.sample(larger_subset, subset))\n log_dir = os.path.join(subset_directory, \"log\")\n os.makedirs(log_dir, exist_ok=True)\n\n for j in self.jobs:\n j.set_subset(subset_utts)\n j.output_to_directory(subset_directory)\n\n @property\n def num_utterances(self) -> int:\n \"\"\"Number of utterances in the corpus\"\"\"\n return len(self.utterances)\n\n @property\n def num_speakers(self) -> int:\n \"\"\"Number of speakers in the corpus\"\"\"\n return len(self.speakers)\n\n def subset_directory(self, subset: Optional[int]) -> str:\n \"\"\"\n Construct a subset directory for the corpus\n\n Parameters\n ----------\n subset: int, optional\n Number of utterances to include, if larger than the total number of utterance or not specified, the\n split_directory is returned\n\n Returns\n -------\n str\n Path to subset directory\n \"\"\"\n if subset is None or subset >= len(self.utterances) or subset <= 0:\n for j in self.jobs:\n j.set_subset(None)\n return self.split_directory\n directory = os.path.join(self.corpus_output_directory, f\"subset_{subset}\")\n if not os.path.exists(directory):\n self.create_subset(subset)\n return directory\n\n def _load_corpus(self) -> None:\n \"\"\"\n Load the corpus\n \"\"\"\n self.log_info(\"Setting up corpus information...\")\n loaded = self._load_corpus_from_temp()\n if not loaded:\n self.log_debug(\"Could not load from temp\")\n self.log_info(\"Loading corpus from source files...\")\n if self.use_mp:\n\n self._load_corpus_from_source_mp()\n else:\n self._load_corpus_from_source()\n else:\n self.log_debug(\"Successfully loaded from temporary files\")\n if not self.files:\n raise CorpusError(\n \"There were no files found for this corpus. Please validate the corpus.\"\n )\n num_speakers = len(self.speakers)\n if not num_speakers:\n raise CorpusError(\n \"There were no sound files found of the appropriate format. Please double check the corpus path \"\n \"and/or run the validation utility (mfa validate).\"\n )\n average_utterances = sum(len(x.utterances) for x in self.speakers) / num_speakers\n self.log_info(\n f\"Number of speakers in corpus: {num_speakers}, \"\n f\"average number of utterances per speaker: {average_utterances}\"\n )\n\n def _load_corpus_from_temp(self) -> bool:\n \"\"\"\n Load a corpus from saved data in the temporary directory\n\n Returns\n -------\n bool\n Whether loading from temporary files was successful\n \"\"\"\n begin_time = time.time()\n if not os.path.exists(self.corpus_output_directory):\n return False\n for f in os.listdir(self.corpus_output_directory):\n if f.startswith(\"split\"):\n old_num_jobs = int(f.replace(\"split\", \"\"))\n if old_num_jobs != self.num_jobs:\n self.log_info(\n f\"Found old run with {old_num_jobs} rather than the current {self.num_jobs}, \"\n f\"setting to {old_num_jobs}. If you would like to use {self.num_jobs}, re-run the command \"\n f\"with --clean.\"\n )\n self.num_jobs = old_num_jobs\n format = \"jsonl\"\n corpus_path = os.path.join(self.corpus_output_directory, \"corpus.json\")\n speakers_path = os.path.join(self.corpus_output_directory, \"speakers.jsonl\")\n files_path = os.path.join(self.corpus_output_directory, \"files.jsonl\")\n utterances_path = os.path.join(self.corpus_output_directory, \"utterances.jsonl\")\n if not os.path.exists(speakers_path):\n format = \"yaml\"\n speakers_path = os.path.join(self.corpus_output_directory, \"speakers.yaml\")\n files_path = os.path.join(self.corpus_output_directory, \"files.yaml\")\n utterances_path = os.path.join(self.corpus_output_directory, \"utterances.yaml\")\n\n if not os.path.exists(speakers_path):\n self.log_debug(f\"Could not find {speakers_path}, cannot load from temp\")\n return False\n if not os.path.exists(files_path):\n self.log_debug(f\"Could not find {files_path}, cannot load from temp\")\n return False\n if not os.path.exists(utterances_path):\n self.log_debug(f\"Could not find {utterances_path}, cannot load from temp\")\n return False\n self.log_debug(\"Loading from temporary files...\")\n\n if os.path.exists(corpus_path):\n with open(corpus_path, \"r\", encoding=\"utf8\") as f:\n data = json.load(f)\n self._initialize_from_json(data)\n\n with open(speakers_path, \"r\", encoding=\"utf8\") as f:\n if format == \"jsonl\":\n speaker_data = jsonlines.Reader(f)\n else:\n speaker_data = yaml.safe_load(f)\n\n for entry in speaker_data:\n self.speakers.add_speaker(Speaker(entry[\"name\"]))\n self.speakers[entry[\"name\"]].cmvn = entry[\"cmvn\"]\n\n with open(files_path, \"r\", encoding=\"utf8\") as f:\n if format == \"jsonl\":\n files_data = jsonlines.Reader(f)\n else:\n files_data = yaml.safe_load(f)\n for entry in files_data:\n file = File(\n name=entry[\"name\"],\n wav_path=entry[\"wav_path\"],\n text_path=entry[\"text_path\"],\n relative_path=entry[\"relative_path\"],\n )\n self.files.add_file(file)\n self.files[file.name].speaker_ordering = [\n self.speakers[x] for x in entry[\"speaker_ordering\"]\n ]\n self.files[file.name].wav_info = SoundFileInformation(**entry[\"wav_info\"])\n\n with open(utterances_path, \"r\", encoding=\"utf8\") as f:\n if format == \"jsonl\":\n utterances_data = jsonlines.Reader(f)\n else:\n utterances_data = yaml.safe_load(f)\n for entry in utterances_data:\n s = self.speakers[entry[\"speaker\"]]\n f = self.files[entry[\"file\"]]\n u = Utterance(\n s,\n f,\n begin=entry[\"begin\"],\n end=entry[\"end\"],\n channel=entry[\"channel\"],\n text=entry[\"text\"],\n )\n u.oovs = set(entry[\"oovs\"])\n u.normalized_text = entry[\"normalized_text\"]\n if u.text:\n self.word_counts.update(u.text.split())\n if u.normalized_text:\n self.word_counts.update(u.normalized_text)\n u.word_error_rate = entry.get(\"word_error_rate\", None)\n u.character_error_rate = entry.get(\"character_error_rate\", None)\n u.transcription_text = entry.get(\"transcription_text\", None)\n u.phone_error_rate = entry.get(\"phone_error_rate\", None)\n u.alignment_score = entry.get(\"alignment_score\", None)\n u.alignment_log_likelihood = entry.get(\"alignment_log_likelihood\", None)\n u.reference_phone_labels = [\n CtmInterval(**x) for x in entry.get(\"reference_phone_labels\", [])\n ]\n\n phone_labels = entry.get(\"phone_labels\", None)\n if phone_labels:\n u.phone_labels = [CtmInterval(**x) for x in phone_labels]\n word_labels = entry.get(\"word_labels\", None)\n if word_labels:\n u.word_labels = [CtmInterval(**x) for x in word_labels]\n u.features = entry.get(\"features\", None)\n u.ignored = entry.get(\"ignored\", False)\n self.add_utterance(u)\n\n self.log_debug(\n f\"Loaded from corpus_data temp directory in {time.time() - begin_time} seconds\"\n )\n return True\n\n @property\n def base_data_directory(self) -> str:\n \"\"\"Corpus data directory\"\"\"\n return self.corpus_output_directory\n\n @property\n def data_directory(self) -> str:\n \"\"\"Corpus data directory\"\"\"\n return self.split_directory\n\n @abstractmethod\n def _load_corpus_from_source_mp(self) -> None:\n \"\"\"Abstract method for loading a corpus with multiprocessing\"\"\"\n ...\n\n @abstractmethod\n def _load_corpus_from_source(self) -> None:\n \"\"\"Abstract method for loading a corpus without multiprocessing\"\"\"\n ...\nmontreal_forced_aligner/corpus/features.py\nclass CalcFmllrArguments(NamedTuple):\n \"\"\"Arguments for :class:`~montreal_forced_aligner.corpus.features.CalcFmllrFunction`\"\"\"\n\n log_path: str\n dictionaries: List[str]\n feature_strings: Dict[str, str]\n ali_paths: Dict[str, str]\n ali_model_path: str\n model_path: str\n spk2utt_paths: Dict[str, str]\n trans_paths: Dict[str, str]\n fmllr_options: MetaDict\nmontreal_forced_aligner/corpus/features.py\nclass CalcFmllrFunction(KaldiFunction):\n \"\"\"\n Multiprocessing function for calculating fMLLR transforms\n\n See Also\n --------\n :meth:`.AcousticCorpusMixin.calc_fmllr`\n Main function that calls this function in parallel\n :meth:`.AcousticCorpusMixin.calc_fmllr_arguments`\n Job method for generating arguments for this function\n :kaldi_src:`gmm-est-fmllr`\n Relevant Kaldi binary\n :kaldi_src:`gmm-est-fmllr-gpost`\n Relevant Kaldi binary\n :kaldi_src:`gmm-post-to-gpost`\n Relevant Kaldi binary\n :kaldi_src:`ali-to-post`\n Relevant Kaldi binary\n :kaldi_src:`weight-silence-post`\n Relevant Kaldi binary\n :kaldi_src:`compose-transforms`\n Relevant Kaldi binary\n :kaldi_src:`transform-feats`\n Relevant Kaldi binary\n\n Parameters\n ----------\n args: :class:`~montreal_forced_aligner.corpus.features.CalcFmllrArguments`\n Arguments for the function\n \"\"\"\n\n progress_pattern = re.compile(r\"^LOG.*For speaker (?P.*),.*$\")\n\n def __init__(self, args: CalcFmllrArguments):\n self.log_path = args.log_path\n self.dictionaries = args.dictionaries\n self.feature_strings = args.feature_strings\n self.ali_paths = args.ali_paths\n self.ali_model_path = args.ali_model_path\n self.model_path = args.model_path\n self.spk2utt_paths = args.spk2utt_paths\n self.trans_paths = args.trans_paths\n self.fmllr_options = args.fmllr_options\n\n def run(self):\n \"\"\"Run the function\"\"\"\n with open(self.log_path, \"w\", encoding=\"utf8\") as log_file:\n for dict_name in self.dictionaries:\n feature_string = self.feature_strings[dict_name]\n ali_path = self.ali_paths[dict_name]\n spk2utt_path = self.spk2utt_paths[dict_name]\n trans_path = self.trans_paths[dict_name]\n initial = True\n if os.path.exists(trans_path):\n initial = False\n post_proc = subprocess.Popen(\n [thirdparty_binary(\"ali-to-post\"), f\"ark:{ali_path}\", \"ark:-\"],\n stderr=log_file,\n stdout=subprocess.PIPE,\n env=os.environ,\n )\n\n weight_proc = subprocess.Popen(\n [\n thirdparty_binary(\"weight-silence-post\"),\n \"0.0\",\n self.fmllr_options[\"silence_csl\"],\n self.ali_model_path,\n \"ark:-\",\n \"ark:-\",\n ],\n stderr=log_file,\n stdin=post_proc.stdout,\n stdout=subprocess.PIPE,\n env=os.environ,\n )\n\n temp_trans_path = trans_path + \".tmp\"\n if self.ali_model_path != self.model_path:\n post_gpost_proc = subprocess.Popen(\n [\n thirdparty_binary(\"gmm-post-to-gpost\"),\n self.ali_model_path,\n feature_string,\n \"ark:-\",\n \"ark:-\",\n ],\n stderr=log_file,\n stdin=weight_proc.stdout,\n stdout=subprocess.PIPE,\n env=os.environ,\n )\n est_proc = subprocess.Popen(\n [\n thirdparty_binary(\"gmm-est-fmllr-gpost\"),\n \"--verbose=4\",\n f\"--fmllr-update-type={self.fmllr_options['fmllr_update_type']}\",\n f\"--spk2utt=ark:{spk2utt_path}\",\n self.model_path,\n feature_string,\n \"ark,s,cs:-\",\n f\"ark:{temp_trans_path}\",\n ],\n stderr=subprocess.PIPE,\n encoding=\"utf8\",\n stdin=post_gpost_proc.stdout,\n env=os.environ,\n )\n\n else:\n\n if not initial:\n temp_composed_trans_path = trans_path + \".cmp.tmp\"\n est_proc = subprocess.Popen(\n [\n thirdparty_binary(\"gmm-est-fmllr\"),\n \"--verbose=4\",\n f\"--fmllr-update-type={self.fmllr_options['fmllr_update_type']}\",\n f\"--spk2utt=ark:{spk2utt_path}\",\n self.model_path,\n feature_string,\n \"ark:-\",\n f\"ark:{temp_trans_path}\",\n ],\n stderr=subprocess.PIPE,\n encoding=\"utf8\",\n stdin=weight_proc.stdout,\n stdout=subprocess.PIPE,\n env=os.environ,\n )\n else:\n est_proc = subprocess.Popen(\n [\n thirdparty_binary(\"gmm-est-fmllr\"),\n \"--verbose=4\",\n f\"--fmllr-update-type={self.fmllr_options['fmllr_update_type']}\",\n f\"--spk2utt=ark:{spk2utt_path}\",\n self.model_path,\n feature_string,\n \"ark,s,cs:-\",\n f\"ark:{trans_path}\",\n ],\n stderr=subprocess.PIPE,\n encoding=\"utf8\",\n stdin=weight_proc.stdout,\n env=os.environ,\n )\n\n for line in est_proc.stderr:\n log_file.write(line)\n m = self.progress_pattern.match(line.strip())\n if m:\n yield m.group(\"speaker\")\n if not initial:\n compose_proc = subprocess.Popen(\n [\n thirdparty_binary(\"compose-transforms\"),\n \"--b-is-affine=true\",\n f\"ark:{temp_trans_path}\",\n f\"ark:{trans_path}\",\n f\"ark:{temp_composed_trans_path}\",\n ],\n stderr=log_file,\n env=os.environ,\n )\n compose_proc.communicate()\n\n os.remove(trans_path)\n os.remove(temp_trans_path)\n os.rename(temp_composed_trans_path, trans_path)\nmontreal_forced_aligner/corpus/features.py\nclass MfccFunction(KaldiFunction):\n \"\"\"\n Multiprocessing function for generating MFCC features\n\n See Also\n --------\n :meth:`.AcousticCorpusMixin.mfcc`\n Main function that calls this function in parallel\n :meth:`.AcousticCorpusMixin.mfcc_arguments`\n Job method for generating arguments for this function\n :kaldi_src:`compute-mfcc-feats`\n Relevant Kaldi binary\n :kaldi_src:`extract-segments`\n Relevant Kaldi binary\n :kaldi_src:`copy-feats`\n Relevant Kaldi binary\n :kaldi_src:`feat-to-len`\n Relevant Kaldi binary\n\n Parameters\n ----------\n args: :class:`~montreal_forced_aligner.corpus.features.MfccArguments`\n Arguments for the function\n \"\"\"\n\n progress_pattern = re.compile(r\"^LOG.* Copied (?P\\d+) feature matrices.\")\n\n def __init__(self, args: MfccArguments):\n self.log_path = args.log_path\n self.wav_path = args.wav_path\n self.segment_path = args.segment_path\n self.feats_scp_path = args.feats_scp_path\n self.mfcc_options = args.mfcc_options\n\n def run(self):\n \"\"\"Run the function\"\"\"\n with open(self.log_path, \"w\") as log_file:\n mfcc_base_command = [thirdparty_binary(\"compute-mfcc-feats\"), \"--verbose=2\"]\n raw_ark_path = self.feats_scp_path.replace(\".scp\", \".ark\")\n for k, v in self.mfcc_options.items():\n mfcc_base_command.append(f\"--{k.replace('_', '-')}={make_safe(v)}\")\n if os.path.exists(self.segment_path):\n mfcc_base_command += [\"ark:-\", \"ark:-\"]\n seg_proc = subprocess.Popen(\n [\n thirdparty_binary(\"extract-segments\"),\n f\"scp,p:{self.wav_path}\",\n self.segment_path,\n \"ark:-\",\n ],\n stdout=subprocess.PIPE,\n stderr=log_file,\n env=os.environ,\n )\n comp_proc = subprocess.Popen(\n mfcc_base_command,\n stdout=subprocess.PIPE,\n stderr=log_file,\n stdin=seg_proc.stdout,\n env=os.environ,\n )\n else:\n mfcc_base_command += [f\"scp,p:{self.wav_path}\", \"ark:-\"]\n comp_proc = subprocess.Popen(\n mfcc_base_command, stdout=subprocess.PIPE, stderr=log_file, env=os.environ\n )\n copy_proc = subprocess.Popen(\n [\n thirdparty_binary(\"copy-feats\"),\n \"--verbose=2\",\n \"--compress=true\",\n \"ark:-\",\n f\"ark,scp:{raw_ark_path},{self.feats_scp_path}\",\n ],\n stdin=comp_proc.stdout,\n stderr=subprocess.PIPE,\n env=os.environ,\n encoding=\"utf8\",\n )\n for line in copy_proc.stderr:\n m = self.progress_pattern.match(line.strip())\n if m:\n yield int(m.group(\"num_utterances\"))\nmontreal_forced_aligner/utils.py\nclass KaldiProcessWorker(mp.Process):\n \"\"\"\n Multiprocessing function work\n\n Parameters\n ----------\n job_name: int\n Integer number of job\n job_q: :class:`~multiprocessing.Queue`\n Job queue to pull arguments from\n function: KaldiFunction\n Multiprocessing function to call on arguments from job_q\n return_dict: dict\n Dictionary for collecting errors\n stopped: :class:`~montreal_forced_aligner.utils.Stopped`\n Stop check\n return_info: dict[int, Any], optional\n Optional dictionary to fill if the function should return information to main thread\n \"\"\"\n\n def __init__(\n self,\n job_name: int,\n return_q: mp.Queue,\n function: KaldiFunction,\n error_dict: dict,\n stopped: Stopped,\n ):\n mp.Process.__init__(self)\n self.job_name = job_name\n self.function = function\n self.return_q = return_q\n self.error_dict = error_dict\n self.stopped = stopped\n self.finished = Stopped()\n\n def run(self) -> None:\n \"\"\"\n Run through the arguments in the queue apply the function to them\n \"\"\"\n try:\n for result in self.function.run():\n self.return_q.put(result)\n except Exception:\n self.stopped.stop()\n self.error_dict[self.job_name] = Exception(traceback.format_exception(*sys.exc_info()))\n finally:\n self.finished.stop()\nmontreal_forced_aligner/corpus/features.py\nclass FeatureConfigMixin:\n \"\"\"\n Class to store configuration information about MFCC generation\n\n Attributes\n ----------\n feature_type : str\n Feature type, defaults to \"mfcc\"\n use_energy : bool\n Flag for whether first coefficient should be used, defaults to False\n frame_shift : int\n number of milliseconds between frames, defaults to 10\n snip_edges : bool\n Flag for enabling Kaldi's snip edges, should be better time precision\n pitch : bool\n Flag for including pitch in features, currently nonfunctional, defaults to False\n low_frequency : int\n Frequency floor\n high_frequency : int\n Frequency ceiling\n sample_frequency : int\n Sampling frequency\n allow_downsample : bool\n Flag for whether to allow downsampling, default is True\n allow_upsample : bool\n Flag for whether to allow upsampling, default is True\n speaker_independent : bool\n Flag for whether features are speaker independent, default is True\n uses_cmvn : bool\n Flag for whether to use CMVN, default is True\n uses_deltas : bool\n Flag for whether to use delta features, default is True\n uses_splices : bool\n Flag for whether to use splices and LDA transformations, default is False\n uses_speaker_adaptation : bool\n Flag for whether to use speaker adaptation, default is False\n fmllr_update_type : str\n Type of fMLLR estimation, defaults to \"full\"\n silence_weight : float\n Weight of silence in calculating LDA or fMLLR\n splice_left_context : int or None\n Number of frames to splice on the left for calculating LDA\n splice_right_context : int or None\n Number of frames to splice on the right for calculating LDA\n \"\"\"\n\n def __init__(\n self,\n feature_type: str = \"mfcc\",\n use_energy: bool = False,\n frame_shift: int = 10,\n snip_edges: bool = True,\n pitch: bool = False,\n low_frequency: int = 20,\n high_frequency: int = 7800,\n sample_frequency: int = 16000,\n allow_downsample: bool = True,\n allow_upsample: bool = True,\n speaker_independent: bool = True,\n uses_cmvn: bool = True,\n uses_deltas: bool = True,\n uses_splices: bool = False,\n uses_voiced: bool = False,\n uses_speaker_adaptation: bool = False,\n fmllr_update_type: str = \"full\",\n silence_weight: float = 0.0,\n splice_left_context: int = 3,\n splice_right_context: int = 3,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.feature_type = feature_type\n self.use_energy = use_energy\n self.frame_shift = frame_shift\n self.snip_edges = snip_edges\n self.pitch = pitch\n self.low_frequency = low_frequency\n self.high_frequency = high_frequency\n self.sample_frequency = sample_frequency\n self.allow_downsample = allow_downsample\n self.allow_upsample = allow_upsample\n self.speaker_independent = speaker_independent\n self.uses_cmvn = uses_cmvn\n self.uses_deltas = uses_deltas\n self.uses_splices = uses_splices\n self.uses_voiced = uses_voiced\n self.uses_speaker_adaptation = uses_speaker_adaptation\n self.fmllr_update_type = fmllr_update_type\n self.silence_weight = silence_weight\n self.splice_left_context = splice_left_context\n self.splice_right_context = splice_right_context\n\n @property\n def vad_options(self) -> MetaDict:\n \"\"\"Abstract method for VAD options\"\"\"\n raise NotImplementedError\n\n @property\n def alignment_model_path(self) -> str: # needed for fmllr\n \"\"\"Abstract method for alignment model path\"\"\"\n raise NotImplementedError\n\n @property\n def model_path(self) -> str: # needed for fmllr\n \"\"\"Abstract method for model path\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def working_directory(self) -> str:\n \"\"\"Abstract method for working directory\"\"\"\n ...\n\n @property\n @abstractmethod\n def corpus_output_directory(self) -> str:\n \"\"\"Abstract method for working directory of corpus\"\"\"\n ...\n\n @property\n @abstractmethod\n def data_directory(self) -> str:\n \"\"\"Abstract method for corpus data directory\"\"\"\n ...\n\n @property\n def feature_options(self) -> MetaDict:\n \"\"\"Parameters for feature generation\"\"\"\n options = {\n \"type\": self.feature_type,\n \"use_energy\": self.use_energy,\n \"frame_shift\": self.frame_shift,\n \"snip_edges\": self.snip_edges,\n \"low_frequency\": self.low_frequency,\n \"high_frequency\": self.high_frequency,\n \"sample_frequency\": self.sample_frequency,\n \"allow_downsample\": self.allow_downsample,\n \"allow_upsample\": self.allow_upsample,\n \"pitch\": self.pitch,\n \"uses_cmvn\": self.uses_cmvn,\n \"uses_deltas\": self.uses_deltas,\n \"uses_voiced\": self.uses_voiced,\n \"uses_splices\": self.uses_splices,\n \"uses_speaker_adaptation\": self.uses_speaker_adaptation,\n }\n if self.uses_splices:\n options.update(\n {\n \"splice_left_context\": self.splice_left_context,\n \"splice_right_context\": self.splice_right_context,\n }\n )\n return options\n\n @abstractmethod\n def calc_fmllr(self) -> None:\n \"\"\"Abstract method for calculating fMLLR transforms\"\"\"\n ...\n\n @property\n def fmllr_options(self) -> MetaDict:\n \"\"\"Options for use in calculating fMLLR transforms\"\"\"\n return {\n \"fmllr_update_type\": self.fmllr_update_type,\n \"silence_weight\": self.silence_weight,\n \"silence_csl\": getattr(\n self, \"silence_csl\", \"\"\n ), # If we have silence phones from a dictionary, use them\n }\n\n @property\n def mfcc_options(self) -> MetaDict:\n \"\"\"Parameters to use in computing MFCC features.\"\"\"\n return {\n \"use-energy\": self.use_energy,\n \"frame-shift\": self.frame_shift,\n \"low-freq\": self.low_frequency,\n \"high-freq\": self.high_frequency,\n \"sample-frequency\": self.sample_frequency,\n \"allow-downsample\": self.allow_downsample,\n \"allow-upsample\": self.allow_upsample,\n \"snip-edges\": self.snip_edges,\n }\nmontreal_forced_aligner/corpus/multiprocessing.py\nclass CorpusProcessWorker(mp.Process):\n \"\"\"\n Multiprocessing corpus loading worker\n\n Attributes\n ----------\n job_q: :class:`~multiprocessing.Queue`\n Job queue for files to process\n return_dict: dict\n Dictionary to catch errors\n return_q: :class:`~multiprocessing.Queue`\n Return queue for processed Files\n stopped: :class:`~montreal_forced_aligner.utils.Stopped`\n Stop check for whether corpus loading should exit\n finished_adding: :class:`~montreal_forced_aligner.utils.Stopped`\n Signal that the main thread has stopped adding new files to be processed\n \"\"\"\n\n def __init__(\n self,\n name: int,\n job_q: mp.Queue,\n return_dict: dict,\n return_q: mp.Queue,\n stopped: Stopped,\n finished_adding: Stopped,\n speaker_characters: Union[int, str],\n sanitize_function: Optional[MultispeakerSanitizationFunction],\n ):\n mp.Process.__init__(self)\n self.name = str(name)\n self.job_q = job_q\n self.return_dict = return_dict\n self.return_q = return_q\n self.stopped = stopped\n self.finished_adding = finished_adding\n self.finished_processing = Stopped()\n self.sanitize_function = sanitize_function\n self.speaker_characters = speaker_characters\n\n def run(self) -> None:\n \"\"\"\n Run the corpus loading job\n \"\"\"\n\n while True:\n try:\n file_name, wav_path, text_path, relative_path = self.job_q.get(timeout=1)\n except Empty:\n if self.finished_adding.stop_check():\n break\n continue\n self.job_q.task_done()\n if self.stopped.stop_check():\n continue\n try:\n file = File.parse_file(\n file_name,\n wav_path,\n text_path,\n relative_path,\n self.speaker_characters,\n self.sanitize_function,\n )\n\n self.return_q.put(file.multiprocessing_data)\n except TextParseError as e:\n self.return_dict[\"decode_error_files\"].append(e)\n except TextGridParseError as e:\n self.return_dict[\"textgrid_read_errors\"][e.file_name] = e\n except Exception:\n self.stopped.stop()\n self.return_dict[\"error\"] = file_name, Exception(\n traceback.format_exception(*sys.exc_info())\n )\n self.finished_processing.stop()\n return\nmontreal_forced_aligner/exceptions.py\nclass TextGridParseError(CorpusReadError):\n \"\"\"\n Class capturing TextGrid reading errors\n\n Parameters\n ----------\n file_name: str\n File name that had the error\n error: str\n Error in TextGrid file\n \"\"\"\n\n def __init__(self, file_name: str, error: str):\n super().__init__(\"\")\n self.file_name = file_name\n self.error = error\n self.message_lines.extend(\n [\n f\"Reading {self.printer.emphasized_text(file_name)} has the following error:\",\n \"\",\n \"\",\n self.error,\n ]\n )\nmontreal_forced_aligner/corpus/features.py\nclass VadArguments(NamedTuple):\n \"\"\"Arguments for :class:`~montreal_forced_aligner.corpus.features.ComputeVadFunction`\"\"\"\n\n log_path: str\n feats_scp_path: str\n vad_scp_path: str\n vad_options: MetaDict\nmontreal_forced_aligner/exceptions.py\nclass TextParseError(CorpusReadError):\n \"\"\"\n Class for errors parsing lab and txt files\n\n Parameters\n ----------\n file_name: str\n File name that had the error\n \"\"\"\n\n def __init__(self, file_name: str):\n super().__init__(\"\")\n self.message_lines = [\n f\"There was an error decoding {self.printer.error_text(file_name)}, \"\n f\"maybe try resaving it as utf8?\"\n ]\n", "answers": [" except TextGridParseError as e:"], "length": 7167, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "22c117c8abe6743194231c984f203fe4cde9113524085dad"} {"input": "import binascii\nimport calendar\nimport six\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom .types import EmbeddedSignatureHeader\nfrom .types import Signature\nfrom ...constants import CompressionAlgorithm\nfrom ...constants import Features as _Features\nfrom ...constants import HashAlgorithm\nfrom ...constants import KeyFlags as _KeyFlags\nfrom ...constants import KeyServerPreferences as _KeyServerPreferences\nfrom ...constants import NotationDataFlags\nfrom ...constants import PubKeyAlgorithm\nfrom ...constants import RevocationKeyClass\nfrom ...constants import RevocationReason\nfrom ...constants import SymmetricKeyAlgorithm\nfrom ...decorators import sdproperty\nfrom ...types import Fingerprint\n from ..packets import SignatureV4\n bits are for future expansion to other kinds of authorizations. This\n is found on a self-signature.\n\n If the \"sensitive\" flag is set, the keyholder feels this subpacket\n contains private trust information that describes a real-world\n sensitive relationship. If this flag is set, implementations SHOULD\n NOT export this signature to other users except in cases where the\n data needs to be available: when the signature is being sent to the\n designated revoker, or when it is accompanied by a revocation\n signature from that revoker. Note that it may be appropriate to\n isolate this subpacket within a separate signature so that it is not\n combined with other subpackets that need to be exported.\n \"\"\"\n __typeid__ = 0x0C\n\n @sdproperty\n def keyclass(self):\n return self._keyclass\n\n @keyclass.register(list)\n def keyclass_list(self, val):\n self._keyclass = val\n\n @keyclass.register(int)\n @keyclass.register(RevocationKeyClass)\n def keyclass_int(self, val):\n self._keyclass += RevocationKeyClass & val\n\n @keyclass.register(bytearray)\n def keyclass_bytearray(self, val):\n self.keyclass = self.bytes_to_int(val)\n\n @sdproperty\n def algorithm(self):\n return self._algorithm\n\n @algorithm.register(int)\n @algorithm.register(PubKeyAlgorithm)\n def algorithm_int(self, val):\n self._algorithm = PubKeyAlgorithm(val)\n\n @algorithm.register(bytearray)\n def algorithm_bytearray(self, val):\n self.algorithm = self.bytes_to_int(val)\n\n @sdproperty\n def fingerprint(self):\n return self._fingerprint\n\n @fingerprint.register(str)\n @fingerprint.register(six.text_type)\n @fingerprint.register(Fingerprint)\n def fingerprint_str(self, val):\n self._fingerprint = Fingerprint(val)\n\n @fingerprint.register(bytearray)\n def fingerprint_bytearray(self, val):\n self.fingerprint = ''.join('{:02x}'.format(c) for c in val).upper()\n\n def __init__(self):\n super(RevocationKey, self).__init__()\n self.keyclass = []\n self.algorithm = PubKeyAlgorithm.Invalid\n self._fingerprint = \"\"\n\n def __bytearray__(self):\n _bytes = super(RevocationKey, self).__bytearray__()\n _bytes += self.int_to_bytes(sum(self.keyclass))\n _bytes += self.int_to_bytes(self.algorithm.value)\n _bytes += self.fingerprint.__bytes__()\n return _bytes\n\n def parse(self, packet):\n super(RevocationKey, self).parse(packet)\n self.keyclass = packet[:1]\n del packet[:1]\n self.algorithm = packet[:1]\n del packet[:1]\n self.fingerprint = packet[:20]\n del packet[:20]\n\n\nclass Issuer(Signature):\n __typeid__ = 0x10\n\n @sdproperty\n def issuer(self):\n return self._issuer\n\n @issuer.register(bytearray)\n def issuer_bytearray(self, val):\n self._issuer = binascii.hexlify(val).upper().decode('latin-1')\n\n def __init__(self):\n super(Issuer, self).__init__()\n self.issuer = bytearray()\n\n def __bytearray__(self):\n _bytes = super(Issuer, self).__bytearray__()\n _bytes += binascii.unhexlify(self._issuer.encode())\n return _bytes\n\n def parse(self, packet):\n super(Issuer, self).parse(packet)\n self.issuer = packet[:8]\n del packet[:8]\n\n\nclass NotationData(Signature):\n __typeid__ = 0x14\n\n @sdproperty\n def flags(self):\n return self._flags\n\n @flags.register(list)\n def flags_list(self, val):\n self._flags = val\n\n @flags.register(int)\n", "context": "src/leap/mx/vendor/pgpy/constants.py\nclass KeyFlags(FlagEnum):\n #: Signifies that a key may be used to certify keys and user ids. Primary keys always have this, even if it is not specified.\n Certify = 0x01\n #: Signifies that a key may be used to sign messages and documents.\n Sign = 0x02\n #: Signifies that a key may be used to encrypt messages.\n EncryptCommunications = 0x04\n #: Signifies that a key may be used to encrypt storage. Currently equivalent to :py:obj:`~pgpy.constants.EncryptCommunications`.\n EncryptStorage = 0x08\n #: Signifies that the private component of a given key may have been split by a secret-sharing mechanism. Split\n #: keys are not currently supported by PGPy.\n Split = 0x10\n #: Signifies that a key may be used for authentication.\n Authentication = 0x20\n #: Signifies that the private component of a key may be in the possession of more than one person.\n MultiPerson = 0x80\nsrc/leap/mx/vendor/pgpy/packet/subpackets/types.py\nclass EmbeddedSignatureHeader(VersionedHeader):\n def __bytearray__(self):\n return bytearray([self.version])\n\n def parse(self, packet):\n self.tag = 2\n super(EmbeddedSignatureHeader, self).parse(packet)\nsrc/leap/mx/vendor/pgpy/constants.py\nclass HashAlgorithm(IntEnum):\n Invalid = 0x00\n MD5 = 0x01\n SHA1 = 0x02\n RIPEMD160 = 0x03\n _reserved_1 = 0x04\n _reserved_2 = 0x05\n _reserved_3 = 0x06\n _reserved_4 = 0x07\n SHA256 = 0x08\n SHA384 = 0x09\n SHA512 = 0x0A\n SHA224 = 0x0B\n\n def __init__(self, *args):\n super(self.__class__, self).__init__()\n self._tuned_count = 0\n\n @property\n def hasher(self):\n return hashlib.new(self.name)\n\n @property\n def digest_size(self):\n return self.hasher.digest_size\n\n @property\n def tuned_count(self):\n if self._tuned_count == 0:\n self.tune_count()\n\n return self._tuned_count\n\n def tune_count(self):\n start = end = 0\n htd = _hashtunedata[:]\n\n while start == end:\n # potentially do this multiple times in case the resolution of time.time is low enough that\n # hashing 100 KiB isn't enough time to produce a measurable difference\n # (e.g. if the timer for time.time doesn't have enough precision)\n htd = htd + htd\n h = self.hasher\n\n start = time.time()\n h.update(htd)\n end = time.time()\n\n # now calculate how many bytes need to be hashed to reach our expected time period\n # GnuPG tunes for about 100ms, so we'll do that as well\n _TIME = 0.100\n ct = int(len(htd) * (_TIME / (end - start)))\n c1 = ((ct >> (ct.bit_length() - 5)) - 16)\n c2 = (ct.bit_length() - 11)\n c = ((c2 << 4) + c1)\n\n # constrain self._tuned_count to be between 0 and 255\n self._tuned_count = max(min(c, 255), 0)\nsrc/leap/mx/vendor/pgpy/constants.py\nclass Features(FlagEnum):\n ModificationDetection = 0x01\n\n @classproperty\n def pgpy_features(cls):\n return Features.ModificationDetection\nsrc/leap/mx/vendor/pgpy/constants.py\nclass PubKeyAlgorithm(IntEnum):\n Invalid = 0x00\n #: Signifies that a key is an RSA key.\n RSAEncryptOrSign = 0x01\n RSAEncrypt = 0x02 # deprecated\n RSASign = 0x03 # deprecated\n #: Signifies that a key is an ElGamal key.\n ElGamal = 0x10\n #: Signifies that a key is a DSA key.\n DSA = 0x11\n #: Signifies that a key is an ECDH key.\n ECDH = 0x12\n #: Signifies that a key is an ECDSA key.\n ECDSA = 0x13\n FormerlyElGamalEncryptOrSign = 0x14 # deprecated - do not generate\n # DiffieHellman = 0x15 # X9.42\n\n @property\n def can_gen(self):\n return self in {PubKeyAlgorithm.RSAEncryptOrSign,\n PubKeyAlgorithm.DSA,\n PubKeyAlgorithm.ECDSA,\n PubKeyAlgorithm.ECDH}\n\n @property\n def can_encrypt(self): # pragma: no cover\n return self in {PubKeyAlgorithm.RSAEncryptOrSign, PubKeyAlgorithm.ElGamal, PubKeyAlgorithm.ECDH}\n\n @property\n def can_sign(self):\n return self in {PubKeyAlgorithm.RSAEncryptOrSign, PubKeyAlgorithm.DSA, PubKeyAlgorithm.ECDSA}\n\n @property\n def deprecated(self):\n return self in {PubKeyAlgorithm.RSAEncrypt,\n PubKeyAlgorithm.RSASign,\n PubKeyAlgorithm.FormerlyElGamalEncryptOrSign}\nsrc/leap/mx/vendor/pgpy/types.py\nclass Fingerprint(str):\n \"\"\"\n A subclass of ``str``. Can be compared using == and != to ``str``, ``unicode``, and other :py:obj:`Fingerprint` instances.\n\n Primarily used as a key for internal dictionaries, so it ignores spaces when comparing and hashing\n \"\"\"\n @property\n def keyid(self):\n return str(self).replace(' ', '')[-16:]\n\n @property\n def shortid(self):\n return str(self).replace(' ', '')[-8:]\n\n def __new__(cls, content):\n if isinstance(content, Fingerprint):\n return content\n\n # validate input before continuing: this should be a string of 40 hex digits\n content = content.upper().replace(' ', '')\n if not bool(re.match(r'^[A-F0-9]{40}$', content)):\n raise ValueError(\"Expected: String of 40 hex digits\")\n\n # store in the format: \"AAAA BBBB CCCC DDDD EEEE FFFF 0000 1111 2222 3333\"\n # ^^ note 2 spaces here\n spaces = [ ' ' if i != 4 else ' ' for i in range(10) ]\n chunks = [ ''.join(g) for g in six.moves.zip_longest(*[iter(content)] * 4) ]\n content = ''.join(j for i in six.moves.zip_longest(chunks, spaces, fillvalue='') for j in i).strip()\n\n return str.__new__(cls, content)\n\n def __eq__(self, other):\n if isinstance(other, Fingerprint):\n return str(self) == str(other)\n\n if isinstance(other, (six.text_type, bytes, bytearray)):\n if isinstance(other, (bytes, bytearray)): # pragma: no cover\n other = other.decode('latin-1')\n\n other = str(other).replace(' ', '')\n return any([self.replace(' ', '') == other,\n self.keyid == other,\n self.shortid == other])\n\n return False # pragma: no cover\n\n def __ne__(self, other):\n return not (self == other)\n\n def __hash__(self):\n return hash(str(self.replace(' ', '')))\n\n def __bytes__(self):\n return binascii.unhexlify(six.b(self.replace(' ', '')))\nsrc/leap/mx/vendor/pgpy/constants.py\nclass RevocationKeyClass(FlagEnum):\n Sensitive = 0x40\n Normal = 0x80\nsrc/leap/mx/vendor/pgpy/constants.py\nclass CompressionAlgorithm(IntEnum):\n #: No compression\n Uncompressed = 0x00\n #: ZIP DEFLATE\n ZIP = 0x01\n #: ZIP DEFLATE with zlib headers\n ZLIB = 0x02\n #: Bzip2\n BZ2 = 0x03\n\n def compress(self, data):\n if self is CompressionAlgorithm.Uncompressed:\n return data\n\n if self is CompressionAlgorithm.ZIP:\n return zlib.compress(data)[2:-4]\n\n if self is CompressionAlgorithm.ZLIB:\n return zlib.compress(data)\n\n if self is CompressionAlgorithm.BZ2:\n return bz2.compress(data)\n\n raise NotImplementedError(self)\n\n def decompress(self, data):\n if six.PY2:\n data = bytes(data)\n\n if self is CompressionAlgorithm.Uncompressed:\n return data\n\n if self is CompressionAlgorithm.ZIP:\n return zlib.decompress(data, -15)\n\n if self is CompressionAlgorithm.ZLIB:\n return zlib.decompress(data)\n\n if self is CompressionAlgorithm.BZ2:\n return bz2.decompress(data)\n\n raise NotImplementedError(self)\nsrc/leap/mx/vendor/pgpy/decorators.py\ndef sdproperty(fget):\n def defset(obj, val): # pragma: no cover\n raise TypeError(str(val.__class__))\n\n class SDProperty(property):\n def register(self, cls=None, fset=None):\n return self.fset.register(cls, fset)\n\n def setter(self, fset):\n self.register(object, fset)\n return type(self)(self.fget, self.fset, self.fdel, self.__doc__)\n\n return SDProperty(fget, sdmethod(defset))\nsrc/leap/mx/vendor/pgpy/constants.py\nclass NotationDataFlags(FlagEnum):\n HumanReadable = 0x80\nsrc/leap/mx/vendor/pgpy/constants.py\nclass SymmetricKeyAlgorithm(IntEnum):\n \"\"\"Supported symmetric key algorithms.\"\"\"\n Plaintext = 0x00\n #: .. warning::\n #: IDEA is insecure. PGPy only allows it to be used for decryption, not encryption!\n IDEA = 0x01\n #: Triple-DES with 168-bit key derived from 192\n TripleDES = 0x02\n #: CAST5 (or CAST-128) with 128-bit key\n CAST5 = 0x03\n #: Blowfish with 128-bit key and 16 rounds\n Blowfish = 0x04\n #: AES with 128-bit key\n AES128 = 0x07\n #: AES with 192-bit key\n AES192 = 0x08\n #: AES with 256-bit key\n AES256 = 0x09\n # Twofish with 256-bit key - not currently supported\n Twofish256 = 0x0A\n #: Camellia with 128-bit key\n Camellia128 = 0x0B\n #: Camellia with 192-bit key\n Camellia192 = 0x0C\n #: Camellia with 256-bit key\n Camellia256 = 0x0D\n\n @property\n def cipher(self):\n bs = {SymmetricKeyAlgorithm.IDEA: algorithms.IDEA,\n SymmetricKeyAlgorithm.TripleDES: algorithms.TripleDES,\n SymmetricKeyAlgorithm.CAST5: algorithms.CAST5,\n SymmetricKeyAlgorithm.Blowfish: algorithms.Blowfish,\n SymmetricKeyAlgorithm.AES128: algorithms.AES,\n SymmetricKeyAlgorithm.AES192: algorithms.AES,\n SymmetricKeyAlgorithm.AES256: algorithms.AES,\n SymmetricKeyAlgorithm.Twofish256: namedtuple('Twofish256', ['block_size'])(block_size=128),\n SymmetricKeyAlgorithm.Camellia128: algorithms.Camellia,\n SymmetricKeyAlgorithm.Camellia192: algorithms.Camellia,\n SymmetricKeyAlgorithm.Camellia256: algorithms.Camellia}\n\n if self in bs:\n return bs[self]\n\n raise NotImplementedError(repr(self))\n\n @property\n def is_insecure(self):\n insecure_ciphers = {SymmetricKeyAlgorithm.IDEA}\n return self in insecure_ciphers\n\n @property\n def block_size(self):\n return self.cipher.block_size\n\n @property\n def key_size(self):\n ks = {SymmetricKeyAlgorithm.IDEA: 128,\n SymmetricKeyAlgorithm.TripleDES: 192,\n SymmetricKeyAlgorithm.CAST5: 128,\n SymmetricKeyAlgorithm.Blowfish: 128,\n SymmetricKeyAlgorithm.AES128: 128,\n SymmetricKeyAlgorithm.AES192: 192,\n SymmetricKeyAlgorithm.AES256: 256,\n SymmetricKeyAlgorithm.Twofish256: 256,\n SymmetricKeyAlgorithm.Camellia128: 128,\n SymmetricKeyAlgorithm.Camellia192: 192,\n SymmetricKeyAlgorithm.Camellia256: 256}\n\n if self in ks:\n return ks[self]\n\n raise NotImplementedError(repr(self))\n\n def gen_iv(self):\n return os.urandom(self.block_size // 8)\n\n def gen_key(self):\n return os.urandom(self.key_size // 8)\nsrc/leap/mx/vendor/pgpy/constants.py\nclass KeyServerPreferences(IntEnum):\n Unknown = 0x00\n NoModify = 0x80\nsrc/leap/mx/vendor/pgpy/packet/subpackets/types.py\nclass Signature(SubPacket):\n __typeid__ = -1\nsrc/leap/mx/vendor/pgpy/constants.py\nclass RevocationReason(IntEnum):\n #: No reason was specified. This is the default reason.\n NotSpecified = 0x00\n #: The key was superseded by a new key. Only meaningful when revoking a key.\n Superseded = 0x01\n #: Key material has been compromised. Only meaningful when revoking a key.\n Compromised = 0x02\n #: Key is retired and no longer used. Only meaningful when revoking a key.\n Retired = 0x03\n #: User ID information is no longer valid. Only meaningful when revoking a certification of a user id.\n UserID = 0x20\n", "answers": [" @flags.register(NotationDataFlags)"], "length": 1585, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "1932e992e6770fd3ef9fe44bcc4b7ae549836afbfb522499"} {"input": "import abc\nimport itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pathlib import Path\nfrom cliff.command import Command\nfrom audeep.backend.data.data_set import load, Partition\nfrom audeep.backend.enum_parser import EnumType\nfrom audeep.backend.evaluation import CrossValidatedEvaluation, PartitionedEvaluation\nfrom audeep.backend.formatters import ConfusionMatrixFormatter\nfrom audeep.backend.learners import TensorflowMLPLearner, LearnerBase, LibLINEARLearner\nfrom audeep.backend.log import LoggingMixin\n action=\"store_true\",\n help=\"Balance classes in the training partitions/splits\")\n parser.add_argument(\"--majority-vote\",\n action=\"store_true\",\n help=\"Use majority voting to determine the labels of chunked instances\")\n parser.add_argument(\"--repeat\",\n metavar=\"N\",\n default=1,\n type=int,\n help=\"Repeat evaluation N times and compute the mean accuracy (default 1)\")\n\n return parser\n\n def plot_confusion_matrix(self, cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=\"Blues\"):\n \"\"\"\n This function plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n cm_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n plt.imshow(cm_norm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=90)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm_norm\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if normalize:\n plt.text(j, i, \"%1.2f\" % cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n else:\n plt.text(j, i, \"%.0f\" % cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.show()\n\n @abc.abstractmethod\n def _get_learner(self, parsed_args) -> LearnerBase:\n pass\n\n def take_action(self, parsed_args):\n self._learner = self._get_learner(parsed_args)\n\n if not parsed_args.input.exists():\n raise IOError(\"failed to open data file at {}\".format(parsed_args.input))\n\n if parsed_args.train_partitions is None and parsed_args.eval_partitions is None and not parsed_args.cross_validate:\n raise ValueError(\"must select either cross validated or partitioned evaluation\")\n if (parsed_args.train_partitions is not None or parsed_args.eval_partitions is not None) \\\n and parsed_args.cross_validate:\n raise ValueError(\"partitioned evaluation and cross validated evaluation are mutually exclusive\")\n if not parsed_args.cross_validate and ((parsed_args.train_partitions is not None)\n ^ (parsed_args.eval_partitions is not None)):\n raise ValueError(\"at least one train and eval partition required\")\n\n data_set = load(parsed_args.input)\n\n accuracies = []\n uars = []\n confusion_matrices = []\n\n if parsed_args.cross_validate:\n accuracy_confidence_intervals = []\n uar_confidence_intervals = []\n\n for _ in range(parsed_args.repeat):\n evaluation = CrossValidatedEvaluation(learner=self._learner,\n upsample=parsed_args.upsample,\n majority_vote=parsed_args.majority_vote)\n evaluation.run(data_set)\n\n accuracies.append(evaluation.accuracy)\n uars.append(evaluation.uar)\n accuracy_confidence_intervals.append(evaluation.accuracy_confidence_interval)\n uar_confidence_intervals.append(evaluation.uar_confidence_interval)\n confusion_matrices.append(evaluation.confusion_matrix)\n\n accuracy = np.mean(accuracies)\n accuracy_confidence_interval = np.mean(accuracy_confidence_intervals)\n uar = np.mean(uars)\n uar_confidence_interval = np.mean(uar_confidence_intervals)\n\n self.log.info(\"cross validation accuracy: %2.2f%% (+/- %2.2f%%)\", 100 * accuracy,\n 100 * accuracy_confidence_interval)\n self.log.info(\"cross validation UAR: %2.2f%% (+/- %2.2f%%)\", 100 * uar, 100 * uar_confidence_interval)\n else:\n for _ in range(parsed_args.repeat):\n # noinspection PyTypeChecker\n evaluation = PartitionedEvaluation(learner=self._learner,\n train_partitions=parsed_args.train_partitions,\n eval_partitions=parsed_args.eval_partitions,\n upsample=parsed_args.upsample,\n majority_vote=parsed_args.majority_vote)\n evaluation.run(data_set)\n\n accuracies.append(evaluation.accuracy)\n uars.append(evaluation.uar)\n confusion_matrices.append(evaluation.confusion_matrix)\n\n accuracy = np.mean(accuracies)\n uar = np.mean(uars)\n\n # noinspection PyTypeChecker,PyStringFormat\n self.log.info(\"accuracy on %s: %2.2f%% (UAR %2.2f%%)\" % (\n \" & \".join([p.name for p in parsed_args.eval_partitions]), 100 * accuracy, 100 * uar))\n\n confusion_matrix = np.sum(confusion_matrices, axis=0)\n\n", "context": "audeep/backend/formatters.py\nclass ConfusionMatrixFormatter:\n \"\"\"\n Formatter for printing a confusion matrix with labels to stdout.\n \"\"\"\n\n def __init__(self,\n decimals: int = None,\n normalize: bool = False,\n abbrev_labels: int = 3):\n \"\"\"\n Create a new ConfusionMatrixFormatter.\n \n Number of decimals can only be specified if normalization is enabled, otherwise it is ignored.\n \n Parameters\n ----------\n decimals: int, optional\n Number of decimals to print for each confusion matrix entry\n normalize: bool, default False\n Normalize confusion matrix to represent probabilities instead of counts.\n abbrev_labels: int, default 3\n Abbreviate nominal labels to have the specified length\n \"\"\"\n self._normalize = normalize\n self._abbrev_labels = abbrev_labels\n\n if normalize:\n if decimals is not None:\n self._decimals = decimals\n else:\n self._decimals = 2\n\n def format(self,\n confusion_matrix: np.ndarray,\n label_map: Mapping[str, int]) -> str:\n \"\"\"\n Print the specified confusion matrix using the specified label map.\n \n The `confusion_matrix` parameter must be a square numpy matrix, and the `label_map` parameter must be a mapping\n of nominal to numeric labels, containing one entry for each confusion matrix row/column.\n \n Parameters\n ----------\n confusion_matrix: numpy.ndarray\n A confusion matrix\n label_map: map of str to int\n A label map\n\n Returns\n -------\n str\n A string representation of the confusion matrix\n \"\"\"\n if len(confusion_matrix.shape) != 2:\n raise ValueError(\"confusion matrix must be 2D, is: {}\".format(len(confusion_matrix.shape)))\n elif confusion_matrix.shape[0] != confusion_matrix.shape[1]:\n raise ValueError(\"confusion matrix must be square, is {}\".format(confusion_matrix.shape))\n elif confusion_matrix.shape[0] != len(label_map):\n raise ValueError(\"number of labels must match confusion matrix size, expected: {}, got: {}\"\n .format(confusion_matrix.shape[0], len(label_map)))\n\n # order nominal labels by numeric values\n ordered_labels = sorted(label_map.items(), key=lambda t: t[1])\n ordered_labels = list(zip(*ordered_labels))[0]\n\n if self._abbrev_labels is not None:\n ordered_labels = [label[:self._abbrev_labels] if len(label) > self._abbrev_labels else label\n for label in ordered_labels]\n\n max_label_len = max(map(len, ordered_labels))\n\n if self._normalize:\n confusion_matrix = confusion_matrix / np.sum(confusion_matrix, axis=1)[:, np.newaxis]\n\n column_width = max(2 + self._decimals, max_label_len)\n number_pattern = \" %%%d.%df\" % (column_width, self._decimals)\n else:\n max_digits = int(math.ceil(math.log10(np.max(confusion_matrix))))\n\n column_width = max(max_digits, max_label_len)\n number_pattern = \" %%%dd\" % column_width\n\n result = \"\"\n\n label_pattern = \"%%%ds\" % column_width\n\n # print header row\n for col in range(confusion_matrix.shape[1] + 1):\n if col == 0:\n result += \" \" * max_label_len\n else:\n result += \" \" + label_pattern % ordered_labels[col - 1]\n\n result += \"\\n\"\n\n label_pattern = \"%%%ds\" % max_label_len\n\n for row in range(confusion_matrix.shape[0]):\n result += label_pattern % ordered_labels[row]\n\n for col in range(confusion_matrix.shape[1]):\n result += number_pattern % confusion_matrix[row, col]\n\n result += \"\\n\"\n\n return result\naudeep/backend/learners.py\nclass TensorflowMLPLearner(LearnerBase):\n \"\"\"\n A learner using Tensorflow to build an MLP classifier.\n \"\"\"\n\n def __init__(self,\n checkpoint_dir: Path,\n num_layers: int,\n num_units: int,\n learning_rate=0.001,\n num_epochs=400,\n keep_prob=0.6,\n shuffle_training=False):\n \"\"\"\n Create and initialize a new TensorflowMLPLearner with the specified parameters.\n \n Due to limitations of Tensorflow (or my inability to find a better solution), this learner has to serialize\n trained model to the hard disk between invocations of the `fit` and `predict` methods.\n \n Furthermore, the entire training data is copied to GPU memory to increase training performance. Thus, only \n moderately-sized models can be trained using this learner.\n \n Parameters\n ----------\n checkpoint_dir: pathlib.Path\n A directory in which temporary models can be stored\n num_layers: int\n The number of layers in the MLP\n num_units: int\n The number of units in each layer\n learning_rate: float, default 0.001\n The learning rate for training\n num_epochs: int, default 400\n The number of training epochs\n keep_prob: float, default 0.6\n The probability to keep hidden activations\n shuffle_training: bool, default False\n Shuffle training data between epochs\n \"\"\"\n self._checkpoint_dir = checkpoint_dir\n self._latest_checkpoint = None\n self._num_labels = None\n self._model = MLPModel(num_layers, num_units)\n self._learning_rate = learning_rate\n self._num_epochs = num_epochs\n self._keep_prob = keep_prob\n self._shuffle_training = shuffle_training\n\n def fit(self,\n data_set: DataSet):\n # generic parameter checks\n super().fit(data_set)\n\n self._num_labels = len(data_set.label_map)\n\n graph = tf.Graph()\n\n with graph.as_default():\n tf_inputs = tf.Variable(initial_value=data_set.features, trainable=False, dtype=tf.float32)\n tf_labels = tf.Variable(initial_value=data_set.labels_numeric, trainable=False, dtype=tf.int32)\n\n if self._shuffle_training:\n tf_inputs = tf.random_shuffle(tf_inputs, seed=42)\n tf_labels = tf.random_shuffle(tf_labels, seed=42)\n\n with tf.variable_scope(\"mlp\"):\n tf_logits = self._model.inference(tf_inputs, self._keep_prob, self._num_labels)\n tf_loss = self._model.loss(tf_logits, tf_labels)\n tf_train_op = self._model.optimize(tf_loss, self._learning_rate)\n\n tf_init_op = tf.global_variables_initializer()\n tf_saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=\"mlp\"))\n\n session = tf.Session(graph=graph)\n session.run(tf_init_op)\n\n for epoch in range(self._num_epochs):\n session.run(tf_train_op)\n\n # timestamped model file\n self._latest_checkpoint = self._checkpoint_dir / \"model_{:%Y%m%d%H%M%S%f}\".format(datetime.datetime.now())\n tf_saver.save(session, str(self._latest_checkpoint), write_meta_graph=False)\n\n session.close()\n\n def predict(self,\n data_set: DataSet):\n # generic parameter checks\n super().predict(data_set)\n\n if self._latest_checkpoint is None:\n raise RuntimeError(\"no model has been built yet. Invoke fit before predict\")\n\n graph = tf.Graph()\n\n with graph.as_default():\n tf_inputs = tf.placeholder(shape=[None, self.num_features], dtype=tf.float32, name=\"inputs\")\n\n with tf.variable_scope(\"mlp\"):\n tf_logits = self._model.inference(tf_inputs, 1.0, self._num_labels)\n tf_prediction = self._model.prediction(tf_logits)\n\n tf_saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=\"mlp\"))\n\n with tf.Session(graph=graph) as session:\n tf_saver.restore(session, str(self._latest_checkpoint))\n\n predictions = session.run(tf_prediction, feed_dict={tf_inputs: data_set.features})\n\n return predictions\naudeep/backend/data/data_set.py\ndef load(path: Path) -> DataSet:\n \"\"\"\n Loads a data set from the specified NetCDF4 file.\n \n Parameters\n ----------\n path: pathlib.Path\n Path to the file which should be loaded.\n\n Returns\n -------\n DataSet\n The data set loaded from the specified file\n \"\"\"\n log = logging.getLogger(__name__)\n log.info(\"loading data set from %s\", path)\n\n data = xr.open_dataset(str(path)) # type: xr.Dataset\n\n # restore data types\n data[_DataVar.FILENAME] = data[_DataVar.FILENAME].astype(np.object).fillna(None)\n data[_DataVar.CHUNK_NR] = data[_DataVar.CHUNK_NR].astype(np.object).fillna(None)\n data[_DataVar.CV_FOLDS] = data[_DataVar.CV_FOLDS].astype(np.object).fillna(None)\n data[_DataVar.PARTITION] = data[_DataVar.PARTITION].astype(np.object).fillna(None)\n data[_DataVar.LABEL_NOMINAL] = data[_DataVar.LABEL_NOMINAL].astype(np.object).fillna(None)\n data[_DataVar.LABEL_NUMERIC] = data[_DataVar.LABEL_NUMERIC].astype(np.object)\n data[_DataVar.FEATURES] = data[_DataVar.FEATURES].astype(np.float32)\n\n return DataSet(data=data,\n mutable=False)\naudeep/backend/learners.py\nclass LibLINEARLearner(LearnerBase):\n \"\"\"\n A learner using LibLINEAR for classification. \n \"\"\"\n\n def __init__(self,\n complexity: float):\n \"\"\"\n Create and initialize a new LibLINEARLearner with the specified SVM complexity parameter.\n \n Parameters\n ----------\n complexity: float\n The SVM complexity parameter\n \"\"\"\n self._model = LinearSVC(C=complexity)\n\n def fit(self,\n data_set: DataSet):\n # generic parameter checks\n super().fit(data_set)\n\n self._model.fit(X=data_set.features, y=data_set.labels_numeric)\n\n def predict(self,\n data_set: DataSet):\n # generic parameter checks\n super().predict(data_set)\n\n return self._model.predict(data_set.features)\naudeep/backend/evaluation.py\nclass CrossValidatedEvaluation(LoggingMixin):\n \"\"\"\n Cross-validated evaluation of a learner on some data.\n \n Given a data set and a learner, this class computes cross-validated accuracy and unweighted average recall, and a\n 95% confidence interval for both values. Additionally, a confusion matrix is summed over all cross-validation folds.\n \"\"\"\n\n def __init__(self,\n learner: LearnerBase,\n upsample: bool,\n majority_vote: bool):\n \"\"\"\n Creates and initializes a new cross-validated evaluation of the specified learner.\n \n The `run` method has to be invoked on some data before results can be retrieved.\n \n Parameters\n ----------\n learner: LearnerBase\n A learner which should be evaluated\n upsample: bool\n Balance classes in the training splits of each fold by upsampling instances\n \"\"\"\n super().__init__()\n\n self._learner = learner\n self._upsample = upsample\n self._majority_vote = majority_vote\n self._accuracy = None\n self._accuracy_confidence_interval = None\n self._uar = None\n self._uar_confidence_interval = None\n self._confusion_matrix = None\n\n @property\n def accuracy(self) -> float:\n \"\"\"\n Returns the accuracy of the learner.\n \n This property returns the accuracy on the last data set on which the `run` method has been invoked. As a \n consequence, this property returns None if the `run` method has not yet been invoked.\n \n Returns\n -------\n float\n Returns the accuracy of the learner on the last data set passed to the `run` method\n \"\"\"\n return self._accuracy\n\n @property\n def accuracy_confidence_interval(self) -> float:\n \"\"\"\n Returns a 95% confidence interval for the accuracy of the learner.\n \n This property returns the confidence interval on the last data set on which the `run` method has been invoked. \n As a consequence, this property returns None if the `run` method has not yet been invoked.\n \n Returns\n -------\n float\n Returns a 95% confidence interval for the accuracy of the learner on the last data set passed to the `run` \n method\n \"\"\"\n return self._accuracy_confidence_interval\n\n @property\n def uar(self) -> float:\n \"\"\"\n Returns the unweighted average recall of the learner.\n \n This property returns the unweighted average recall on the last data set on which the `run` method has been \n invoked. As a consequence, this property returns None if the `run` method has not yet been invoked.\n \n Returns\n -------\n float\n Returns the unweighted average recall of the learner on the last data set passed to the `run` method\n \"\"\"\n return self._uar\n\n @property\n def uar_confidence_interval(self) -> float:\n \"\"\"\n Returns a 95% confidence interval for the unweighted average recall of the learner.\n \n This property returns the confidence interval on the last data set on which the `run` method has been invoked. \n As a consequence, this property returns None if the `run` method has not yet been invoked.\n \n Returns\n -------\n float\n Returns a 95% confidence interval for the unweighted average recall of the learner on the last data set \n passed to the `run` method\n \"\"\"\n return self._uar_confidence_interval\n\n @property\n def confusion_matrix(self) -> np.ndarray:\n \"\"\"\n Returns the confusion matrix of the learner.\n \n This property returns the confusion matrix on the last data set on which the `run` method has been invoked. \n As a consequence, this property returns None if the `run` method has not yet been invoked. The confusion matrix\n is computed as the sum of the confusion matrices on the individual cross-validation folds.\n \n Returns\n -------\n numpy.ndarray\n The confusion matrix of the learner on the last data set passed to the `run` method\n \"\"\"\n return self._confusion_matrix\n\n def run(self,\n data_set: DataSet):\n \"\"\"\n Evaluates the learner on the specified data set using cross-validation.\n \n Sets the various properties of this instance to the values obtained during evaluation on the specified data set.\n \n Parameters\n ----------\n data_set: DataSet\n The data set on which the learner should be evaluated\n\n Raises\n ------\n ValueError \n If the specified data set does not have cross-validation information\n \"\"\"\n if not data_set.has_cv_info:\n raise ValueError(\"data set does not have cross validation info\")\n\n accuracies = []\n uars = []\n confusion_matrices = []\n\n # order numeric labels by nominal value\n ordered_labels = sorted(data_set.label_map.items(), key=lambda t: t[0])\n ordered_labels = list(zip(*ordered_labels))[1]\n\n for fold in range(data_set.num_folds):\n self.log.info(\"processing cross validation fold %d...\", fold + 1)\n\n learner_wrapper = PreProcessingWrapper(learner=self._learner,\n upsample=self._upsample,\n majority_vote=self._majority_vote)\n\n train_split = data_set.split(fold=fold,\n split=Split.TRAIN)\n valid_split = data_set.split(fold=fold,\n split=Split.VALID)\n\n learner_wrapper.fit(train_split)\n\n # IMPORTANT: these methods return maps of filename to label, since order may (or most certainly will) be\n # different\n predictions = learner_wrapper.predict(valid_split)\n true_labels = valid_split.filename_labels_numeric\n\n # sort labels and predictions by filename\n predictions = np.array([item[1] for item in sorted(predictions.items(), key=lambda item: item[0])])\n true_labels = np.array([item[1] for item in sorted(true_labels.items(), key=lambda item: item[0])])\n\n accuracy = accuracy_score(true_labels, predictions)\n uar = uar_score(true_labels, predictions)\n\n accuracies.append(accuracy)\n uars.append(uar)\n confusion_matrices.append(confusion_matrix(y_true=true_labels,\n y_pred=predictions,\n labels=ordered_labels))\n\n self.log.info(\"fold %d accuracy is %2.2f%% (UAR %2.2f%%)\", fold + 1, 100 * accuracy, 100 * uar)\n\n self._accuracy = np.mean(accuracies)\n self._accuracy_confidence_interval = 2 * np.std(accuracies)\n self._uar = np.mean(uars)\n self._uar_confidence_interval = 2 * np.std(uars)\n self._confusion_matrix = np.sum(confusion_matrices, axis=0)\naudeep/backend/learners.py\nclass LearnerBase:\n \"\"\"\n Defines a common interface for all classification algorithms.\n \"\"\"\n __metaclass__ = ABCMeta\n\n _num_features = None\n\n @property\n def num_features(self):\n \"\"\"\n Returns the number of features for which the learner was trained.\n \n This property is updated each time the `fit` method is called on some data. Any subsequent calls to the\n `predict` method then expect the same number of features.\n \n Returns\n -------\n int\n The number of features for which the learner was trained\n \"\"\"\n return self._num_features\n\n @abstractmethod\n def fit(self,\n data_set: DataSet):\n \"\"\"\n Fit the learner to the specified data.\n \n Parameters\n ----------\n data_set: DataSet\n The data set on which to train the learner. Must be fully labelled.\n\n Raises\n ------\n ValueError\n If the feature matrix has invalid shape\n \"\"\"\n if len(data_set.feature_shape) != 1:\n raise ValueError(\"invalid number of feature dimensions: {}\".format(len(data_set.feature_shape)))\n\n self._num_features = data_set.feature_shape[0]\n\n @abstractmethod\n def predict(self,\n data_set: DataSet):\n \"\"\"\n Predict the labels of the specified data set.\n \n Parameters\n ----------\n data_set: DataSet\n Data set containing instances for which to predict labels.\n\n Returns\n -------\n numpy.ndarray\n The predicted labels of the specified data\n \n Raises\n ------\n ValueError\n If the specified feature matrix has invalid shape\n \"\"\"\n if len(data_set.feature_shape) != 1:\n raise ValueError(\"invalid number of feature dimensions: {}\".format(len(data_set.feature_shape)))\n if data_set.feature_shape[0] != self.num_features:\n raise ValueError(\"learner was trained with different number of features\")\naudeep/backend/log.py\nclass LoggingMixin:\n \"\"\"\n A logging mixin, which adds a log attribute to a class.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Create and initialize the LoggingMixin.\n \n Any parameters passed to this constructor will be passed to the base class unchanged.\n \n Parameters\n ----------\n args\n Positional arguments\n kwargs\n Keyword arguments\n \"\"\"\n # noinspection PyArgumentList\n super().__init__(*args, **kwargs)\n\n self.log = logging.getLogger(self.__class__.__name__)\naudeep/backend/data/data_set.py\nclass Partition(Enum):\n \"\"\"\n Identifiers for different data partitions.\n \"\"\"\n TRAIN = 0\n DEVEL = 1\n TEST = 2\naudeep/backend/enum_parser.py\nclass EnumType:\n \"\"\"\n Performs case-insensitive parsing of string arguments to enum members.\n \n Consider, for example, an enum type with a member called MEMBER. Then, all string values with lower case \n equivalent \"member\" will be parsed to the enum member MEMBER.\n \"\"\"\n\n def __init__(self,\n enum_class: Type[Enum]):\n \"\"\"\n Create and initialize a new EnumParser for the specified Enum type.\n \n Parameters\n ----------\n enum_class: Type[Enum]\n The enum class for which values should be parsed\n \"\"\"\n self._enum_class = enum_class\n self._member_map = {x.name.lower(): x.name for x in enum_class}\n\n def __call__(self, arg: str):\n \"\"\"\n Try to parse the specified string to an enum member.\n \n Parameters\n ----------\n arg: str\n The string value which should be parsed\n\n Returns\n -------\n enum\n A member of the enum type passed to this class which has the specified name\n \n Raises\n ------\n argparse.ArgumentTypeError\n If the enum does not have a member with the specified name\n \"\"\"\n arg_lower = arg.lower()\n\n if not arg_lower in self._member_map:\n raise ArgumentTypeError(\"invalid choice %s (choose from %s)\" % (arg, \", \".join(self._member_map.values())))\n\n return self._enum_class[self._member_map[arg_lower]]\naudeep/backend/evaluation.py\nclass PartitionedEvaluation(LoggingMixin):\n \"\"\"\n Partitioned evaluation of a learner on some data set.\n \n The learner is trained on specific partitions of the data set, and evaluated on some other specific partitions of\n the data set. Typically, a the learner is tuned by training on the train partition and evaluating on the development\n partition of a data set. Once tuning is complete, the learner is trained on the train and development partitions, \n and evaluated on the test partition.\n \"\"\"\n\n def __init__(self,\n learner: LearnerBase,\n train_partitions: Sequence[Partition],\n eval_partitions: Sequence[Partition],\n upsample: bool,\n majority_vote: bool):\n \"\"\"\n Create a new partitioned evaluation of the specified learner.\n \n Evaluation is performed by training the learner on the specified training partitions, and evaluating the \n learner on the specified evaluation partitions.\n \n Parameters\n ----------\n learner: LearnerBase\n The learner which should be evaluated\n train_partitions: list of Partition\n The partitions on which the learner should be trained\n eval_partitions: list of Partition\n The partitions on which the learner should be evaluted\n upsample: bool\n Balance classes in the training partitions by upsampling instances\n \"\"\"\n super().__init__()\n\n self._learner = learner\n self._train_partitions = train_partitions\n self._eval_partitions = eval_partitions\n self._upsample = upsample\n self._majority_vote = majority_vote\n self._accuracy = None\n self._uar = None\n self._confusion_matrix = None\n\n @property\n def accuracy(self) -> float:\n \"\"\"\n Returns the accuracy of the learner.\n \n This property returns the accuracy on the last data set on which the `run` method has been invoked. As a \n consequence, this property returns None if the `run` method has not yet been invoked.\n \n Returns\n -------\n float\n Returns the accuracy of the learner on the last data set passed to the `run` method\n \"\"\"\n return self._accuracy\n\n @property\n def uar(self) -> float:\n \"\"\"\n Returns the unweighted average recall of the learner.\n \n This property returns the unweighted average recall on the last data set on which the `run` method has been \n invoked. As a consequence, this property returns None if the `run` method has not yet been invoked.\n \n Returns\n -------\n float\n Returns the unweighted average recall of the learner on the last data set passed to the `run` method\n \"\"\"\n return self._uar\n\n @property\n def confusion_matrix(self) -> np.ndarray:\n \"\"\"\n Returns the confusion matrix of the learner.\n \n This property returns the confusion matrix on the last data set on which the `run` method has been invoked. \n As a consequence, this property returns None if the `run` method has not yet been invoked.\n \n Returns\n -------\n numpy.ndarray\n The confusion matrix of the learner on the last data set passed to the `run` method\n \"\"\"\n return self._confusion_matrix\n\n def run(self,\n data_set: DataSet):\n \"\"\"\n Evaluates the learner on the specified data set.\n \n Sets the various properties of this instance to the values obtained during evaluation on the specified data set.\n \n Parameters\n ----------\n data_set: DataSet\n The data set on which the learner should be evaluated\n\n Raises\n ------\n ValueError \n If the specified data set does not have partition information\n \"\"\"\n if not data_set.has_partition_info:\n raise ValueError(\"data set does not have partition info\")\n\n self.log.info(\"training classifier\")\n\n learner_wrapper = PreProcessingWrapper(learner=self._learner,\n upsample=self._upsample,\n majority_vote=self._majority_vote)\n\n train_split = data_set.partitions(self._train_partitions)\n eval_split = data_set.partitions(self._eval_partitions)\n\n learner_wrapper.fit(train_split)\n\n # IMPORTANT: these methods return maps of filename to label, since order may (or most certainly will) be\n # different\n predictions = learner_wrapper.predict(eval_split)\n true_labels = eval_split.filename_labels_numeric\n\n # sort labels and predictions by filename\n predictions = np.array([item[1] for item in sorted(predictions.items(), key=lambda item: item[0])])\n true_labels = np.array([item[1] for item in sorted(true_labels.items(), key=lambda item: item[0])])\n\n self._accuracy = accuracy_score(true_labels, predictions)\n self._uar = uar_score(true_labels, predictions)\n\n # order numeric labels by nominal value\n ordered_labels = sorted(data_set.label_map.items(), key=lambda t: t[0])\n ordered_labels = list(zip(*ordered_labels))[1]\n\n self._confusion_matrix = confusion_matrix(y_true=true_labels,\n y_pred=predictions,\n labels=ordered_labels)\n", "answers": [" formatter = ConfusionMatrixFormatter()"], "length": 3014, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "2d5c0adcc8c945f9b6315f3b7a9278d8ca123f1a7c921b14"} {"input": "from .property import *\nfrom .exceptions import ReservedWordError\nfrom .declarative import DeclarativeMeta, DeclarativeType\nfrom .vertex import Vertex\nfrom .edge import Edge\nfrom .broker import get_broker\nfrom .query import Query\nfrom .batch import Batch\nfrom .commands import VertexCommand, CreateEdgeCommand\nfrom ..utils import to_unicode\nfrom collections import namedtuple\nfrom os.path import isfile\nimport pyorient\n\n def create_vertex(self, vertex_cls, **kwargs):\n result = self.client.command(\n to_unicode(self.create_vertex_command(vertex_cls, **kwargs)))[0]\n\n props = result.oRecordData\n return vertex_cls.from_graph(self, result._rid,\n self.props_from_db[vertex_cls](props))\n\n def create_vertex_command(self, vertex_cls, **kwargs):\n class_name = vertex_cls.registry_name\n\n if kwargs:\n db_props = Graph.props_to_db(vertex_cls, kwargs, self.strict)\n set_clause = u' SET {}'.format(\n u','.join(u'{}={}'.format(\n PropertyEncoder.encode_name(k), PropertyEncoder.encode_value(v))\n for k, v in db_props.items()))\n else:\n set_clause = u''\n\n return VertexCommand(\n u'CREATE VERTEX {}{}'.format(class_name, set_clause))\n\n def delete_vertex(self, vertex, where = None, limit=None, batch=None):\n # TODO FIXME Parse delete result\n result = self.client.command(to_unicode(self.delete_vertex_command(vertex, where, limit, batch)))\n\n def delete_vertex_command(self, vertex, where=None, limit=None, batch=None):\n vertex_clause = getattr(vertex, 'registry_name', None) or vertex\n\n delete_clause = ''\n if where is not None:\n where_clause = ''\n if isinstance(where, dict):\n where_clause = u' and '.join(u'{0}={1}'\n .format(PropertyEncoder.encode_name(k)\n , PropertyEncoder.encode_value(v))\n for k,v in where.items())\n else:\n where_clause = Query.filter_string(where)\n\n delete_clause += ' WHERE {}'.format(where_clause)\n if limit is not None:\n delete_clause += ' LIMIT {}'.format(limit)\n if batch is not None:\n delete_clause += ' BATCH {}'.format(batch)\n\n return VertexCommand(\n u'DELETE VERTEX {}{}'.format(\n vertex_clause, delete_clause))\n\n def create_edge(self, edge_cls, from_vertex, to_vertex, **kwargs):\n result = self.client.command(\n to_unicode(self.create_edge_command(edge_cls\n , from_vertex\n , to_vertex\n , **kwargs)))[0]\n\n return self.edge_from_record(result, edge_cls)\n\n def create_edge_command(self, edge_cls, from_vertex, to_vertex, **kwargs):\n class_name = edge_cls.registry_name\n\n if kwargs:\n db_props = Graph.props_to_db(edge_cls, kwargs, self.strict)\n set_clause = u' SET {}'.format(\n u','.join(u'{}={}'.format(\n PropertyEncoder.encode_name(k), PropertyEncoder.encode_value(v))\n for k, v in db_props.items()))\n else:\n set_clause = ''\n\n return CreateEdgeCommand(\n u'CREATE EDGE {} FROM {} TO {}{}'.format(\n class_name, from_vertex._id, to_vertex._id, set_clause))\n\n def create_function(self, name, code, parameters=None, idempotent=False, language='javascript'):\n parameter_str = ' PARAMETERS [' + ','.join(parameters) + ']' if parameters else ''\n\n self.client.command(\n u'CREATE FUNCTION {} \\'{}\\' {} IDEMPOTENT {} LANGUAGE {}'.format(\n name, code, parameter_str, 'true' if idempotent else 'false', language))\n\n def get_vertex(self, vertex_id):\n record = self.client.command('SELECT FROM {}'.format(vertex_id))\n return self.vertex_from_record(record[0]) if record else None\n\n def get_edge(self, edge_id):\n record = self.client.command('SELECT FROM {}'.format(edge_id))\n return self.edge_from_record(record[0]) if record else None\n\n def get_element(self, elem_id):\n record = self.client.command('SELECT FROM {}'.format(elem_id))\n return self.element_from_record(record[0]) if record else None\n\n def save_element(self, element_class, props, elem_id):\n \"\"\":returns: True if successful, False otherwise\"\"\"\n if isinstance(element_class, str):\n name = element_class\n element_class = self.registry.get(element_class)\n if not element_class:\n raise KeyError(\n 'Class \\'{}\\' not registered with graph.'.format(name))\n\n if props:\n db_props = Graph.props_to_db(element_class, props, self.strict)\n set_clause = u' SET {}'.format(\n u','.join(u'{}={}'.format(\n PropertyEncoder.encode_name(k), PropertyEncoder.encode_value(v))\n for k, v in db_props.items()))\n else:\n set_clause = ''\n\n result = self.client.command(u'UPDATE {}{}'.format(elem_id, set_clause))\n return result and result[0] == b'1'\n\n def query(self, first_entity, *entities):\n return Query(self, (first_entity,) + entities)\n\n", "context": "pyorient/ogm/edge.py\nclass Edge(GraphElement):\n Broker = EdgeBroker\n\n def __init__(self, **kwargs):\n super(Edge, self).__init__(**kwargs)\n\n self._in = None\n self._out = None\n\n @classmethod\n def from_graph(cls, graph, element_id, in_hash, out_hash, props):\n edge = super(Edge, cls).from_graph(graph, element_id, props);\n edge._in = in_hash\n edge._out = out_hash\n\n return edge\n\n def outV(self):\n g = self._graph\n return g.get_vertex(self._out) if g else None\n\n def inV(self):\n g = self._graph\n return g.get_vertex(self._in) if g else None\npyorient/ogm/vertex.py\nclass Vertex(GraphElement):\n Broker = VertexBroker\n\n # TODO\n # Edge information is carried in vertexes retrieved from database,\n # as OrientBinaryObject. Can likely optimise these traversals\n # when we know how to parse these.\n def outE(self, *edge_classes):\n g = self._graph\n return g.outE(self._id, *edge_classes) if g else None\n\n def inE(self, *edge_classes):\n g = self._graph\n return g.inE(self._id, *edge_classes) if g else None\n\n def bothE(self, *edge_classes):\n g = self._graph\n return g.bothE(self._id, *edge_classes) if g else None\n\n def out(self, *edge_classes):\n g = self._graph\n return g.out(self._id, *edge_classes) if g else None\n\n def in_(self, *edge_classes):\n g = self._graph\n return g.in_(self._id, *edge_classes) if g else None\n\n def both(self, *edge_classes):\n g = self._graph\n return g.both(self._id, *edge_classes) if g else None\n\n def __call__(self, edge_or_broker):\n \"\"\"Provides syntactic sugar for creating edges.\"\"\"\n if hasattr(edge_or_broker, 'broker'):\n edge_or_broker = edge_or_broker.broker.element_cls\n elif hasattr(edge_or_broker, 'element_cls'):\n edge_or_broker = edge_or_broker.element_cls\n\n if edge_or_broker.decl_type == 1:\n return VertexVector(self, edge_or_broker.objects)\npyorient/ogm/declarative.py\nclass DeclarativeType(object):\n \"\"\"Marker for graph database element types\"\"\"\n Vertex = 0\n Edge = 1\npyorient/ogm/exceptions.py\nclass ReservedWordError(Exception):\n pass\npyorient/ogm/commands.py\nclass VertexCommand(object):\n def __init__(self, command_text):\n self.command_text = command_text\n\n def __str__(self):\n return to_str(self.__unicode__())\n\n def __unicode__(self):\n return u'{}'.format(self.command_text)\npyorient/ogm/broker.py\ndef get_broker(cls):\n for v in cls.__dict__.values():\n if isinstance(v, Broker):\n return v\n return None\npyorient/ogm/query.py\nclass Query(object):\n def __init__(self, graph, entities):\n \"\"\"Query against a class or a selection of its properties.\n\n :param graph: Graph to query\n :param entities: Vertex/Edge class/a collection of its properties,\n an instance of such a class, or a subquery.\n \"\"\"\n self._graph = graph\n self._subquery = None\n\n first_entity = entities[0]\n\n if isinstance(first_entity, Property):\n self.source_name = first_entity._context.registry_name\n self._class_props = entities\n elif isinstance(first_entity, GraphElement):\n # Vertex or edge instance\n self.source_name = first_entity._id\n self._class_props = tuple()\n pass\n elif isinstance(first_entity, Query):# \\\n #or isinstance(first_entity, Traverse):\n # Subquery\n self._subquery = first_entity\n self.source_name = first_entity.source_name\n self._class_props = tuple()\n pass\n elif isinstance(first_entity, QV):\n self.source_name = self.build_what(first_entity)\n self._class_props = tuple()\n else:\n self.source_name = first_entity.registry_name\n self._class_props = tuple(entities[1:])\n\n self._params = {}\n\n @classmethod\n def sub(cls, source):\n \"\"\"Shorthand for defining a sub-query, which does not need a Graph\"\"\"\n return cls(None, (source, ))\n\n def __iter__(self):\n params = self._params\n\n # TODO Don't ignore initial skip value\n with TempParams(params, skip='#-1:-1', limit=1):\n optional_clauses = self.build_optional_clauses(params, None)\n\n prop_names = []\n props, lets = self.build_props(params, prop_names, for_iterator=True)\n if len(prop_names) > 1:\n prop_prefix = self.source_name.translate(sanitise_ids)\n\n selectuple = namedtuple(prop_prefix + '_props',\n [Query.sanitise_prop_name(name)\n for name in prop_names])\n wheres = self.build_wheres(params)\n\n g = self._graph\n while True:\n current_skip = params['skip']\n where = u'WHERE {0}'.format(\n u' and '.join(\n [self.rid_lower(current_skip)] + wheres))\n\n select = self.build_select(props, lets + [where] + optional_clauses)\n\n response = g.client.command(select)\n if response:\n response = response[0]\n\n if prop_names:\n next_skip = response.oRecordData.get('rid')\n if next_skip:\n self.skip(next_skip)\n\n if len(prop_names) > 1:\n yield selectuple(\n *tuple(self.parse_record_prop(\n response.oRecordData.get(name))\n for name in prop_names))\n else:\n yield self.parse_record_prop(\n response.oRecordData[prop_names[0]])\n else:\n yield g.element_from_record(response)\n break\n else:\n if '-' in response._rid:\n # Further queries would yield the same\n # TODO Find out if any single iteration queries\n # return multiple values\n yield next(iter(response.oRecordData.values()))\n break\n elif response._rid == current_skip:\n # OrientDB bug?\n # expand() makes for strange responses\n break\n else:\n self.skip(response._rid)\n\n yield g.element_from_record(response)\n else:\n break\n\n def __getitem__(self, key):\n \"\"\"Set query slice, or just get result by index.\"\"\"\n if isinstance(key, slice):\n if key.stop is None:\n if key.start is not None:\n self._params['skip'] = key.start\n return self\n elif key.start is None:\n key.start = 0\n\n return self.slice(key.start, key.stop)\n\n with TempParams(self._params, skip=key, limit=1):\n response = self.all()\n return response[0] if response else None\n\n def __str__(self):\n props, lets, where, optional_clauses = self.prepare()\n return self.build_select(props, lets + where + optional_clauses)\n\n def __len__(self):\n return self.count()\n\n def prepare(self, prop_names=None):\n params = self._params\n props, lets = self.build_props(params, prop_names)\n skip = params.get('skip')\n if skip and ':' in str(skip):\n rid_clause = [self.rid_lower(skip)]\n skip = None\n else:\n rid_clause = []\n optional_clauses = self.build_optional_clauses(params, skip)\n\n wheres = rid_clause + self.build_wheres(params)\n where = [u'WHERE {0}'.format(u' and '.join(wheres))] if wheres else []\n\n return props, lets, where, optional_clauses\n\n def all(self):\n prop_names = []\n props, lets, where, optional_clauses = self.prepare(prop_names)\n if len(prop_names) > 1:\n prop_prefix = self.source_name.translate(sanitise_ids)\n\n selectuple = namedtuple(prop_prefix + '_props',\n [Query.sanitise_prop_name(name)\n for name in prop_names])\n select = self.build_select(props, lets + where + optional_clauses)\n\n g = self._graph\n\n response = g.client.command(select)\n if response:\n # TODO Determine which other queries always take only one iteration\n list_query = 'count' not in self._params\n\n if list_query:\n if prop_names:\n if len(prop_names) > 1:\n return [\n selectuple(*tuple(\n self.parse_record_prop(\n record.oRecordData.get(name))\n for name in prop_names))\n for record in response]\n else:\n prop_name = prop_names[0]\n return [\n self.parse_record_prop(\n record.oRecordData[prop_name])\n for record in response]\n else:\n if self._params.get('reify', False) and len(response) == 1:\n # Simplify query for subsequent uses\n del self._params['kw_filters']\n self.source_name = response[0]._rid\n\n return g.elements_from_records(response)\n else:\n return next(iter(response[0].oRecordData.values()))\n else:\n return []\n\n def first(self, reify=False):\n with TempParams(self._params, limit=1, reify=reify):\n response = self.all()\n return response[0] if response else None\n\n def one(self, reify=False):\n with TempParams(self._params, limit=2):\n responses = self.all()\n num_responses = len(responses)\n if num_responses > 1:\n raise MultipleResultsFound(\n 'Expecting one result for query; got more.')\n elif num_responses < 1:\n raise NoResultFound('Expecting one result for query; got none.')\n else:\n return responses[0]\n\n def scalar(self):\n try:\n response = self.one()\n except NoResultFound:\n return None\n else:\n return response[0] if isinstance(response, tuple) else response\n\n def count(self, field=None):\n params = self._params\n\n if not field:\n whats = params.get('what')\n if whats and len(whats) == 1:\n field = self.build_what(whats[0])\n elif len(self._class_props) == 1:\n field = self._class_props[0]\n else:\n field = '*'\n\n with TempParams(params, count=field):\n return self.all()\n\n def what(self, *whats):\n self._params['what'] = whats\n return self\n\n def let(self, **kwargs):\n self._params['let'] = kwargs\n return self\n\n def filter(self, expression):\n self._params['filter'] = expression\n return self\n\n def filter_by(self, **kwargs):\n self._params['kw_filters'] = kwargs\n return self\n\n def group_by(self, *criteria):\n self._params['group_by'] = criteria\n return self\n\n def order_by(self, *criteria, **kwargs):\n self._params['order_by'] = (criteria, kwargs.get('reverse', False))\n return self\n\n def unwind(self, field):\n self._params['unwind'] = field\n return self\n\n def skip(self, skip):\n self._params['skip'] = skip\n return self\n\n def limit(self, limit):\n self._params['limit'] = limit\n return self\n\n def slice(self, start, stop):\n \"\"\"Give bounds on how many records to retrieve\n\n :param start: If a string, must denote the id of the record _preceding_\n that to be retrieved next, or '#-1:-1'. Otherwise denotes how many\n records to skip.\n\n :param stop: If 'start' was a string, denotes a limit on how many\n records to retrieve. Otherwise, the index one-past-the-last\n record to retrieve.\n \"\"\"\n self._params['skip'] = start\n if isinstance(start, str):\n self._params['limit'] = stop\n else:\n self._params['limit'] = stop - start\n return self\n\n def lock(self):\n self._params['lock'] = True\n\n @classmethod\n def filter_string(cls, expression_root):\n op = expression_root.operator\n\n left = expression_root.operands[0]\n right = expression_root.operands[1]\n if isinstance(left, IdentityOperand):\n if isinstance(left, Property):\n left_str = left.context_name()\n elif isinstance(left, ArithmeticOperation):\n left_str = u'({})'.format(cls.arithmetic_string(left))\n elif isinstance(left, ChainableWhat):\n left_str = cls.build_what(left)\n else:\n raise ValueError(\n 'Operator {} not supported as a filter'.format(op))\n\n if op is Operator.Equal:\n return u'{0} = {1}'.format(\n left_str, ArgConverter.convert_to(ArgConverter.Vertex\n , right, cls))\n elif op is Operator.GreaterEqual:\n return u'{0} >= {1}'.format(\n left_str, ArgConverter.convert_to(ArgConverter.Value\n , right, cls))\n elif op is Operator.Greater:\n return u'{0} > {1}'.format(\n left_str, ArgConverter.convert_to(ArgConverter.Value\n , right, cls))\n elif op is Operator.LessEqual:\n return u'{0} <= {1}'.format(\n left_str, ArgConverter.convert_to(ArgConverter.Value\n , right, cls))\n elif op is Operator.Less:\n return u'{0} < {1}'.format(\n left_str, ArgConverter.convert_to(ArgConverter.Value\n , right, cls))\n elif op is Operator.NotEqual:\n return u'{0} <> {1}'.format(\n left_str, ArgConverter.convert_to(ArgConverter.Vertex\n , right, cls))\n elif op is Operator.Between:\n far_right = PropertyEncoder.encode_value(expression_root.operands[2])\n return u'{0} BETWEEN {1} and {2}'.format(\n left_str, PropertyEncoder.encode_value(right), far_right)\n elif op is Operator.Contains:\n if isinstance(right, LogicalConnective):\n return u'{0} contains({1})'.format(\n left_str, cls.filter_string(right))\n else:\n return u'{} in {}'.format(\n PropertyEncoder.encode_value(right), left_str)\n elif op is Operator.EndsWith:\n return u'{0} like {1}'.format(left_str, PropertyEncoder.encode_value('%' + right))\n elif op is Operator.Is:\n if not right: # :)\n return '{0} is null'.format(left_str)\n elif op is Operator.IsNot:\n if not right:\n return '{} is not null'.format(left_str)\n elif op is Operator.Like:\n return u'{0} like {1}'.format(\n left_str, PropertyEncoder.encode_value(right))\n elif op is Operator.Matches:\n return u'{0} matches {1}'.format(\n left_str, PropertyEncoder.encode_value(right))\n elif op is Operator.StartsWith:\n return u'{0} like {1}'.format(\n left_str, PropertyEncoder.encode_value(right + '%'))\n elif op is Operator.InstanceOf:\n return u'{0} instanceof {1}'.format(\n left_str, repr(right.registry_name))\n else:\n raise AssertionError('Unhandled Operator type: {}'.format(op))\n else:\n return u'{0} {1} {2}'.format(\n cls.filter_string(left)\n , 'and' if op is Operator.And else 'or'\n , cls.filter_string(right))\n\n @classmethod\n def arithmetic_string(cls, operation_root):\n if isinstance(operation_root, ArithmeticOperation):\n op = operation_root.operator\n if operation_root.paren:\n lp = '('\n rp = ')'\n else:\n lp = rp = ''\n\n left = operation_root.operands[0]\n # Unary operators not yet supported?\n right = operation_root.operands[1]\n\n if op is Operator.Add:\n exp = '{} + {}'.format(\n cls.arithmetic_string(left)\n , cls.arithmetic_string(right))\n elif op is Operator.Sub:\n exp = '{} - {}'.format(\n cls.arithmetic_string(left)\n , cls.arithmetic_string(right))\n elif op is Operator.Mul:\n exp = '{} * {}'.format(\n cls.arithmetic_string(left)\n , cls.arithmetic_string(right))\n elif op is Operator.Div:\n exp = '{} / {}'.format(\n cls.arithmetic_string(left)\n , cls.arithmetic_string(right))\n elif op is Operator.Mod:\n exp = '{} % {}'.format(\n cls.arithmetic_string(left)\n , cls.arithmetic_string(right))\n\n return '{}{}{}'.format(lp,exp,rp)\n elif isinstance(operation_root, Property):\n return operation_root.context_name()\n else:\n return operation_root\n\n\n def build_props(self, params, prop_names=None, for_iterator=False):\n let = params.get('let')\n if let:\n lets = ['LET {}'.format(\n ','.join('${} = {}'.format(\n PropertyEncoder.encode_name(k),\n u'({})'.format(v) if isinstance(v, Query) else\n self.build_what(v)) for k,v in let.items()))]\n else:\n lets = []\n\n count_field = params.get('count')\n if count_field:\n if isinstance(count_field, Property):\n count_field = count_field.context_name()\n\n # Record response will use the same (lower-)case as the request\n return ['count({})'.format(count_field or '*')], lets\n\n whats = params.get('what')\n if whats:\n props = [self.build_what(what, prop_names) for what in whats]\n\n if prop_names is not None:\n # Multiple, distinct what's can alias to the same name\n # Make unique; consistent with what OrientDB assumes\n used_names = {}\n for idx, name in enumerate(prop_names):\n prop_names[idx] = Query.unique_prop_name(name, used_names)\n else:\n props = [e.context_name() for e in self._class_props]\n if prop_names is not None:\n prop_names.extend(props)\n\n if props and for_iterator:\n props[0:0] = ['@rid']\n\n return props, lets\n\n def build_wheres(self, params):\n kw_filters = params.get('kw_filters')\n kw_where = [u' and '.join(u'{0}={1}'\n .format(PropertyEncoder.encode_name(k), PropertyEncoder.encode_value(v))\n for k,v in kw_filters.items())] if kw_filters else []\n\n filter_exp = params.get('filter')\n exp_where = [self.filter_string(filter_exp)] if filter_exp else []\n\n return kw_where + exp_where\n\n def rid_lower(self, skip):\n return '@rid > {}'.format(skip)\n\n def build_optional_clauses(self, params, skip):\n '''LET, while being an optional clause, must precede WHERE\n and is therefore handled separately.'''\n optional_clauses = []\n\n group_by = params.get('group_by')\n if group_by:\n group_clause = 'GROUP BY {}'.format(\n ','.join([by.context_name() for by in group_by]))\n optional_clauses.append(group_clause)\n\n order_by = params.get('order_by')\n if order_by:\n order_clause = 'ORDER BY {0} {1}'.format(\n ','.join([by.context_name() for by in order_by[0]])\n , 'DESC' if order_by[1] else 'ASC')\n optional_clauses.append(order_clause)\n\n unwind = params.get('unwind')\n if unwind:\n unwind_clause = 'UNWIND {}'.format(\n unwind.context_name()\n if isinstance(unwind, Property) else unwind)\n optional_clauses.append(unwind_clause)\n\n if skip:\n optional_clauses.append('SKIP {}'.format(skip))\n\n # TODO Determine other functions for which limit is useless\n if 'count' not in params:\n limit = params.get('limit')\n if limit:\n optional_clauses.append('LIMIT {}'.format(limit))\n\n lock = params.get('lock')\n if lock:\n optional_clauses.append('LOCK RECORD')\n\n return optional_clauses\n\n WhatFunction = namedtuple('what', ['max_args', 'fmt', 'expected'])\n WhatFunctions = {\n # TODO handle GraphElement args\n What.Out: WhatFunction(1, 'out({})', (ArgConverter.Label,))\n , What.In: WhatFunction(1, 'in({})', (ArgConverter.Label,))\n , What.Both: WhatFunction(1, 'both({})', (ArgConverter.Label,))\n , What.OutE: WhatFunction(1, 'outE({})', (ArgConverter.Label,))\n , What.InE: WhatFunction(1, 'inE({})', (ArgConverter.Label,))\n , What.BothE: WhatFunction(1, 'bothE({})', (ArgConverter.Label,))\n , What.OutV: WhatFunction(0, 'outV()', tuple())\n , What.InV: WhatFunction(0, 'inV()', tuple())\n , What.Eval: WhatFunction(1, 'eval({})', (ArgConverter.Expression,))\n , What.Coalesce: WhatFunction(None, 'coalesce({})'\n , (ArgConverter.Field,))\n , What.If: WhatFunction(3, 'if({})'\n , (ArgConverter.Boolean, ArgConverter.Value\n , ArgConverter.Value))\n , What.IfNull: WhatFunction(2, 'ifnull({})'\n , (ArgConverter.Field, ArgConverter.Value))\n , What.Expand: WhatFunction(1, 'expand({})', (ArgConverter.Field,))\n , What.First: WhatFunction(1, 'first({})', (ArgConverter.Field,))\n , What.Last: WhatFunction(1, 'last({})', (ArgConverter.Field,))\n , What.Count: WhatFunction(1, 'count({})', (ArgConverter.Field,))\n , What.Min: WhatFunction(None, 'min({})', (ArgConverter.Field,))\n , What.Max: WhatFunction(None, 'max({})', (ArgConverter.Field,))\n , What.Avg: WhatFunction(1, 'avg({})', (ArgConverter.Field,))\n , What.Mode: WhatFunction(1, 'mode({})', (ArgConverter.Field,))\n , What.Median: WhatFunction(1, 'median({})', (ArgConverter.Field,))\n , What.Percentile: WhatFunction(None, 'percentile({})'\n , (ArgConverter.Field,))\n , What.Variance: WhatFunction(1, 'variance({})', (ArgConverter.Field,))\n , What.StdDev: WhatFunction(1, 'stddev({})', (ArgConverter.Field,))\n , What.Sum: WhatFunction(1, 'sum({})', (ArgConverter.Field,))\n , What.Date: WhatFunction(3, 'date({})'\n , (ArgConverter.String, ArgConverter.String\n , ArgConverter.String))\n , What.SysDate: WhatFunction(2, 'sysdate({})'\n , (ArgConverter.String\n , ArgConverter.String))\n , What.Format: WhatFunction(None, 'format({})'\n , (ArgConverter.Format, ArgConverter.Field))\n , What.Dijkstra:\n WhatFunction(4, 'dijkstra({})'\n , (ArgConverter.Vertex, ArgConverter.Vertex\n , ArgConverter.Label, ArgConverter.Value))\n , What.ShortestPath:\n WhatFunction(4, 'shortestPath({})'\n , (ArgConverter.Vertex, ArgConverter.Vertex\n , ArgConverter.Value, ArgConverter.Label))\n , What.Distance:\n WhatFunction(4, 'distance({})'\n , (ArgConverter.Field, ArgConverter.Field\n , ArgConverter.Value, ArgConverter.Value))\n , What.Distinct: WhatFunction(1, 'distinct({})', (ArgConverter.Field,))\n , What.UnionAll: WhatFunction(None, 'unionall({})'\n , (ArgConverter.Field,))\n , What.Intersect: WhatFunction(None, 'intersect({})'\n , (ArgConverter.Field,))\n , What.Difference: WhatFunction(None, 'difference({})'\n , (ArgConverter.Field,))\n , What.SymmetricDifference:\n WhatFunction(None, 'symmetricDifference({})', (ArgConverter.Field,))\n # FIXME Don't understand usage of these, yet.\n , What.Set: WhatFunction(1, 'set({})', (ArgConverter.Field,))\n , What.List: WhatFunction(1, 'list({})', (ArgConverter.Field,))\n , What.Map: WhatFunction(2, 'map({})', (ArgConverter.Field\n , ArgConverter.Field))\n , What.TraversedElement:\n WhatFunction(2, 'traversedElement({})'\n , (ArgConverter.Value, ArgConverter.Value))\n , What.TraversedEdge:\n WhatFunction(2, 'traversedEdge({})'\n , (ArgConverter.Value, ArgConverter.Value))\n , What.TraversedVertex:\n WhatFunction(2, 'traversedVertex({})'\n , (ArgConverter.Value, ArgConverter.Value))\n , What.Any: WhatFunction(0, 'any()', tuple())\n , What.All: WhatFunction(0, 'all()', tuple())\n # Methods\n , What.Append: WhatFunction(1, 'append({})', (ArgConverter.Value,))\n , What.AsBoolean: WhatFunction(0, 'asBoolean()', tuple())\n , What.AsDate: WhatFunction(0, 'asDate()', tuple())\n , What.AsDatetime: WhatFunction(0, 'asDatetime()', tuple())\n , What.AsDecimal: WhatFunction(0, 'asDecimal()', tuple())\n , What.AsFloat: WhatFunction(0, 'asFloat()', tuple())\n , What.AsInteger: WhatFunction(0, 'asInteger()', tuple())\n , What.AsList: WhatFunction(0, 'asList()', tuple())\n , What.AsLong: WhatFunction(0, 'asLong()', tuple())\n , What.AsMap: WhatFunction(0, 'asMap()', tuple())\n , What.AsSet: WhatFunction(0, 'asSet()', tuple())\n , What.AsString: WhatFunction(0, 'asString()', tuple())\n , What.CharAt: WhatFunction(1, 'charAt({})', (ArgConverter.Field,))\n , What.Convert: WhatFunction(1, 'convert({})', (ArgConverter.Value,))\n , What.Exclude: WhatFunction(None, 'exclude({})', (ArgConverter.Value,))\n , What.FormatMethod: WhatFunction(1, 'format({})', (ArgConverter.Value,))\n , What.Hash: WhatFunction(1, 'hash({})', (ArgConverter.Value,))\n , What.Include: WhatFunction(None, 'include({})', (ArgConverter.Value,))\n , What.IndexOf: WhatFunction(2, 'indexOf({})', (ArgConverter.Value, ArgConverter.Value))\n , What.JavaType: WhatFunction(0, 'javaType()', tuple())\n , What.Keys: WhatFunction(0, 'keys()', tuple())\n , What.Left: WhatFunction(1, 'left({})', (ArgConverter.Value,))\n , What.Length: WhatFunction(0, 'length()', tuple())\n , What.Normalize: WhatFunction(2, 'normalize({})', (ArgConverter.Value, ArgConverter.Value))\n , What.Prefix: WhatFunction(1, 'prefix({})', (ArgConverter.Value,))\n , What.Remove: WhatFunction(None, 'remove({})', (ArgConverter.Value,))\n , What.RemoveAll: WhatFunction(None, 'removeAll({})', (ArgConverter.Value,))\n , What.Replace: WhatFunction(2, 'replace({})', (ArgConverter.Value, ArgConverter.Value))\n , What.Right: WhatFunction(1, 'right({})', (ArgConverter.Value,))\n , What.Size: WhatFunction(0, 'size()', tuple())\n , What.SubString: WhatFunction(2, 'substring({})', (ArgConverter.Value, ArgConverter.Value))\n , What.Trim: WhatFunction(0, 'trim()', tuple())\n , What.ToJSON: WhatFunction(0, 'toJSON()', tuple()) # FIXME TODO Figure out format argument\n , What.ToLowerCase: WhatFunction(0, 'toLowerCase()', tuple())\n , What.ToUpperCase: WhatFunction(0, 'toUpperCase()', tuple())\n , What.Type: WhatFunction(0, 'type()', tuple())\n , What.Values: WhatFunction(0, 'values()', tuple())\n , What.WhatLet: WhatFunction(1, '${}', (ArgConverter.Name, ))\n , What.AtThis: WhatFunction(0, '@this', tuple())\n , What.AtRid: WhatFunction(0, '@rid', tuple())\n , What.AtClass: WhatFunction(0, '@class', tuple())\n , What.AtVersion: WhatFunction(0, '@version', tuple())\n , What.AtSize: WhatFunction(0, '@size', tuple())\n , What.AtType: WhatFunction(0, '@type', tuple())\n }\n\n @classmethod\n def append_what_function(cls, chain, func_key, func_args):\n what_function = Query.WhatFunctions[func_key]\n max_args = what_function.max_args\n if max_args > 0 or max_args is None:\n chain.append(\n what_function.fmt.format(\n ','.join(cls.what_args(what_function.expected,\n func_args[1]))))\n else:\n chain.append(what_function.fmt)\n\n @classmethod\n def build_what(cls, what, prop_names=None):\n if isinstance(what, Property):\n prop_name = what.context_name()\n if prop_names is not None:\n prop_names.append(prop_name)\n return prop_name\n elif not isinstance(what, What):\n if isinstance(what, str):\n what_str = json.dumps(what)\n else:\n what_str = str(what)\n\n if prop_names is not None:\n period = what_str.find('.')\n if period >= 0:\n prop_names.append(what_str[0:period])\n else:\n prop_names.append(what_str.replace('\"', ''))\n return what_str\n\n name_override = what.name_override\n as_str = ' AS {}'.format(name_override) if name_override else ''\n\n if isinstance(what, FunctionWhat):\n func = what.chain[0][0]\n what_function = Query.WhatFunctions[func]\n\n if prop_names is not None:\n # Projections not allowed with Expand\n counted = func is not What.Expand\n if counted:\n prop_names.append(\n cls.parse_prop_name(what_function.fmt, name_override))\n\n return '{}{}'.format(\n what_function.fmt.format(\n ','.join(cls.what_args(what_function.expected,\n what.chain[0][1]))), as_str)\n elif isinstance(what, ChainableWhat):\n chain = []\n for func_args in what.chain:\n func_key = func_args[0]\n if func_key == What.WhatFilter:\n filter_exp = func_args[1]\n chain[-1] += '[{}]'.format(ArgConverter.convert_to(ArgConverter.Filter, filter_exp, cls))\n continue\n elif func_key == What.WhatCustom:\n chain.append('{}({})'.format(func_args[1], ','.join(cls.what_args(func_args[2], func_args[3]))))\n continue\n\n cls.append_what_function(chain, func_key, func_args)\n\n for prop in what.props:\n if isinstance(prop, tuple):\n func_key = prop[0]\n cls.append_what_function(chain, func_key, prop)\n else:\n chain.append(prop)\n\n if prop_names is not None:\n prop_names.append(\n cls.parse_prop_name(chain[0], name_override))\n return '{}{}'.format('.'.join(chain), as_str)\n\n @staticmethod\n def unique_prop_name(name, used_names):\n used = used_names.get(name, None)\n if used is None:\n used_names[name] = 1\n return name\n else:\n used_names[name] += 1\n return name + str(used_names[name])\n\n @staticmethod\n def sanitise_prop_name(name):\n if iskeyword(name):\n return name + '_'\n elif name[0] == '$':\n return 'qv_'+ name[1:]\n else:\n return name\n\n @staticmethod\n def parse_prop_name(from_str, override):\n if override:\n return override\n else:\n paren_idx = from_str.find('(')\n if paren_idx < 0:\n return from_str\n else:\n return from_str[:paren_idx]\n\n @classmethod\n def what_args(cls, expected, args):\n if args:\n return [ArgConverter.convert_to(conversion, arg, cls)\n for arg, conversion in\n zip_longest(args, expected\n , fillvalue=expected[-1])\n if arg is not None]\n else:\n return []\n\n def build_select(self, props, optional_clauses):\n # This 'is not None' is important; don't want to implicitly call\n # __len__ (which invokes count()) on subquery.\n if self._subquery is not None:\n src = u'({})'.format(self._subquery)\n else:\n src = self.source_name\n\n optional_string = ' '.join(optional_clauses)\n if props:\n return u'SELECT {} FROM {} {}'.format(\n ','.join(props), src, optional_string)\n else:\n return u'SELECT FROM {} {}'.format(src, optional_string)\n\n def parse_record_prop(self, prop):\n if isinstance(prop, list):\n g = self._graph\n return g.elements_from_links(prop) if len(prop) > 0 and isinstance(prop[0], pyorient.OrientRecordLink) else prop\n elif isinstance(prop, pyorient.OrientRecordLink):\n return self._graph.element_from_link(prop)\n return prop\npyorient/ogm/batch.py\nclass Batch(object):\n READ_COMMITTED = 0\n REPEATABLE_READ = 1\n\n def __init__(self, graph, isolation_level=READ_COMMITTED):\n self.graph = graph\n self.objects = {}\n self.variables = {}\n\n if isolation_level == Batch.REPEATABLE_READ:\n self.commands = 'BEGIN ISOLATION REPEATABLE_READ\\n'\n else:\n self.commands = 'BEGIN\\n'\n\n for name,cls in graph.registry.items():\n broker = get_broker(cls)\n if broker:\n self.objects[cls] = broker = BatchBroker(broker)\n else:\n self.objects[cls] = broker = BatchBroker(cls.objects)\n\n broker_name = getattr(cls, 'registry_plural', None)\n if broker_name is not None:\n setattr(self, broker_name, broker)\n\n def __setitem__(self, key, value):\n command = str(value)\n if isinstance(key, slice):\n self.commands += '{}\\n'.format(command)\n else:\n key = Batch.clean_name(key) if Batch.clean_name else key\n\n self.commands += 'LET {} = {}\\n'.format(key, command)\n\n VarType = BatchVariable\n if isinstance(value, VertexCommand):\n VarType = BatchVertexVariable\n self.variables[key] = VarType('${}'.format(key), value)\n\n def sleep(self, ms):\n self.commands += 'sleep {}'.format(ms)\n\n def clear(self):\n self.objects.clear()\n self.variables.clear()\n\n self.commands = self.commands[:self.commands.index('\\n') + 1]\n\n def __getitem__(self, key):\n \"\"\"Commit batch with return value, or reference a previously defined\n variable.\n\n Using a plain string as a key commits and returns the named variable.\n\n Slicing with only a 'stop' value does not commit - it is the syntax for\n using a variable. Otherwise slicing can give finer control over commits;\n step values give a retry limit, and a start value denotes the returned\n variable.\n \"\"\"\n\n returned = None\n if isinstance(key, slice):\n if key.step:\n if key.start:\n returned = Batch.return_string(key.start)\n self.commands += \\\n 'COMMIT RETRY {}\\nRETURN {}'.format(key.step, returned)\n else:\n self.commands += 'COMMIT RETRY {}'.format(key.step)\n elif key.stop:\n # No commit.\n\n if Batch.clean_name:\n return self.variables[Batch.clean_name(key.stop)]\n elif any(c in Batch.INVALID_CHARS for c in key.stop):\n raise ValueError(\n 'Variable name \\'{}\\' contains invalid character(s).'\n .format(key.stop))\n\n return self.variables[key.stop]\n else:\n if key.start:\n returned = Batch.return_string(key.start)\n self.commands += 'COMMIT\\nRETURN {}'.format(returned)\n else:\n self.commands += 'COMMIT'\n else:\n returned = Batch.return_string(key)\n self.commands += 'COMMIT\\nRETURN {}'.format(returned)\n\n g = self.graph\n if returned:\n response = g.client.batch(self.commands)\n self.clear()\n\n if returned[0] in ('[','{'):\n return g.elements_from_records(response) if response else None\n else:\n return g.element_from_record(response[0]) if response else None\n else:\n g.client.batch(self.commands)\n self.clear()\n\n def commit(self, retries=None):\n \"\"\"Commit batch with no return value.\"\"\"\n self.commands += 'COMMIT' + (' RETRY {}'.format(retries) if retries else '')\n\n g = self.graph\n g.client.batch(self.commands)\n self.clear()\n\n @staticmethod\n def return_string(variables):\n cleaned = Batch.clean_name or (lambda s:s)\n\n if isinstance(variables, (list, tuple)):\n return '[' + ','.join(\n '${}'.format(cleaned(var)) for var in variables) + ']'\n elif isinstance(variables, dict):\n return '{' + ','.join(\n '{}:${}'.format(repr(k),cleaned(v))\n for k,v in variables.items()) + '}'\n else:\n # Since any value can be returned from a batch,\n # '$' must be used when a variable is referenced\n if isinstance(variables, str):\n if variables[0] == '$':\n return '{}'.format('$' + cleaned(variables[1:]))\n else:\n return repr(variables)\n else:\n return '{}'.format(variables)\n\n INVALID_CHARS = set(string.punctuation + string.whitespace)\n\n @staticmethod\n def default_name_cleaner(name):\n rx = '[' + re.escape(''.join(Batch.INVALID_CHARS)) + ']'\n return re.sub(rx, '_', name)\n\n clean_name = None\n @classmethod\n def use_name_cleaner(cls, cleaner=default_name_cleaner):\n cls.clean_name = cleaner\npyorient/ogm/declarative.py\nclass DeclarativeMeta(type):\n \"\"\"Metaclass for registering node and relationship types.\n\n Node and relationship metadata is mostly ignored until their classes are\n created in a Graph. The main benefit is to allow 'self-referencing'\n properties with LinkedClassProperty subclasses.\n \"\"\"\n def __init__(cls, class_name, bases, attrs):\n if not hasattr(cls, 'registry'):\n cls.registry = OrderedDict()\n cls.decl_root = cls\n else:\n decl_bases = set(\n base.decl_root for base in bases\n if hasattr(base, 'decl_root') and base is not base.decl_root)\n if len(decl_bases) > 1:\n raise TypeError(\n 'When multiply-inheriting graph elements, they must share '\n 'the same declarative base class. '\n 'Note: Each call to declarative_*() returns a new base class.')\n\n if cls.decl_type is DeclarativeType.Vertex:\n cls.registry_name = attrs.get('element_type'\n , cls.__name__.lower())\n\n plural = attrs.get('element_plural')\n if plural:\n cls.registry_plural = plural\n else:\n label = attrs.get('label')\n if label:\n cls.registry_name = cls.registry_plural = label\n else:\n cls.registry_name = cls.__name__.lower()\n\n # See also __setattr__ for properties added after class definition\n for prop in cls.__dict__.values():\n if not isinstance(prop, Property):\n continue\n prop._context = cls\n\n # FIXME Only want bases that correspond to vertex/edge classes.\n cls.registry[cls.registry_name] = cls\n\n return super(DeclarativeMeta, cls).__init__(class_name, bases, attrs)\n\n def __setattr__(self, name, value):\n if isinstance(value, Property):\n if value.context:\n raise ValueError(\n 'Attempt to add a single Property to multiple classes.')\n value.context = self\n return super(DeclarativeMeta, self).__setattr__(name, value)\n\n def __format__(self, format_spec):\n \"\"\"Quoted class-name for specifying class as string argument.\n\n Use 'registry_name' when it is possible to refer to schema entities\n directly.\n \"\"\"\n return repr(self.registry_name)\npyorient/ogm/commands.py\nclass CreateEdgeCommand(object):\n def __init__(self, command_text):\n self.command_text = command_text\n self.retries = None\n\n def __str__(self):\n return to_str(self.__unicode__())\n\n def __unicode__(self):\n if self.retries:\n return u'{} RETRY {}'.format(self.command_text, self.retries)\n else:\n return u'{}'.format(self.command_text)\n\n def retry(self, retries):\n self.retries = retries\n return self\n", "answers": [" def batch(self, isolation_level=Batch.READ_COMMITTED):"], "length": 3701, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "c73f4b63802074ee64e04fb6e84bbd5cee72e90931f0e11f"} {"input": "import com.github.heuermh.personalgenome.client.Genome;\nimport com.github.heuermh.personalgenome.client.Genotype;\nimport com.github.heuermh.personalgenome.client.Haplogroup;\nimport com.github.heuermh.personalgenome.client.PersonalGenomeClientException;\nimport com.github.heuermh.personalgenome.client.Relative;\nimport com.github.heuermh.personalgenome.client.Risk;\nimport com.github.heuermh.personalgenome.client.Trait;\nimport com.github.heuermh.personalgenome.client.User;\nimport com.github.heuermh.personalgenome.client.UserName;\nimport java.io.InputStream;\nimport java.util.List;\nimport com.github.heuermh.personalgenome.client.Ancestry;\nimport com.github.heuermh.personalgenome.client.Carrier;\nimport com.github.heuermh.personalgenome.client.DrugResponse;\n/*\n\n personal-genome-client Java client for the 23andMe Personal Genome API.\n Copyright (c) 2012-2013 held jointly by the individual authors.\n\n This library is free software; you can redistribute it and/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 3 of the License, or (at\n your option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this library; if not, write to the Free Software Foundation,\n Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.\n\n > http://www.fsf.org/licensing/licenses/lgpl.html\n > http://www.opensource.org/licenses/lgpl-license.php\n\n*/\npackage com.github.heuermh.personalgenome.client;\n\n\n\n\n/**\n * Converter.\n */\npublic interface PersonalGenomeConverter {\n\n /**\n * Parse the specified input stream and return a personal genome client exception.\n *\n * @param inputStream input stream, must not be null\n * @return the specified input stream parsed into a personal genome client exception\n */\n PersonalGenomeClientException parseException(InputStream inputStream);\n\n /**\n * Parse the specified input stream and return a user.\n *\n * @param inputStream input stream, must not be null\n * @return the specified input stream parsed into a user\n */\n User parseUser(InputStream inputStream);\n\n /**\n * Parse the specified input stream and return user names.\n *\n * @param inputStream input stream, must not be null\n * @return the specified input stream parsed into user names\n */\n UserName parseNames(InputStream inputStream);\n\n /**\n * Parse the specified input stream and return haplogroups.\n *\n * @param inputStream input stream, must not be null\n * @return the specified input stream parsed into haplogroups\n */\n Haplogroup parseHaplogroups(InputStream inputStream);\n\n /**\n * Parse the specified input stream and return genotypes.\n *\n * @param inputStream input stream, must not be null\n * @return the specified input stream parsed into genotypes\n */", "context": "client/src/main/java/com/github/heuermh/personalgenome/client/DrugResponse.java\n@Immutable\npublic final class DrugResponse {\n private final String profileId;\n private final String reportId;\n private final String description;\n private final String status;\n\n public DrugResponse(final String profileId, final String reportId, final String description, final String status) {\n checkNotNull(profileId);\n checkNotNull(reportId);\n checkNotNull(description);\n checkNotNull(status);\n this.profileId = profileId;\n this.reportId = reportId;\n this.description = description;\n this.status = status;\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public String getReportId() {\n return reportId;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String getStatus() {\n return status;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/Carrier.java\n@Immutable\npublic final class Carrier {\n private final String profileId;\n private final String reportId;\n private final String description;\n private final int mutations;\n\n public Carrier(final String profileId, final String reportId, final String description, final int mutations) {\n checkNotNull(profileId);\n checkNotNull(reportId);\n checkNotNull(description);\n this.profileId = profileId;\n this.reportId = reportId;\n this.description = description;\n this.mutations = mutations;\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public String getReportId() {\n return reportId;\n }\n\n public String getDescription() {\n return description;\n }\n\n public int getMutations() {\n return mutations;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/Genotype.java\n@Immutable\npublic final class Genotype {\n private final String profileId;\n private final Map values;\n\n public Genotype(final String profileId, final Map values) {\n checkNotNull(profileId);\n checkNotNull(values);\n this.profileId = profileId;\n this.values = ImmutableMap.copyOf(values);\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public Map getValues() {\n return values;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/Risk.java\n@Immutable\npublic final class Risk {\n private final String profileId;\n private final String reportId;\n private final String description;\n private final double risk;\n private final double populationRisk;\n\n public Risk(final String profileId, final String reportId, final String description, final double risk, final double populationRisk) {\n checkNotNull(profileId);\n checkNotNull(reportId);\n checkNotNull(description);\n this.profileId = profileId;\n this.reportId = reportId;\n this.description = description;\n this.risk = risk;\n this.populationRisk = populationRisk;\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public String getReportId() {\n return reportId;\n }\n\n public String getDescription() {\n return description;\n }\n\n public double getRisk() {\n return risk;\n }\n\n public double getPopulationRisk() {\n return populationRisk;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/Haplogroup.java\n@Immutable\npublic final class Haplogroup {\n private final String profileId;\n private final String paternal; // may be null\n private final String maternal;\n private final List paternalTerminalSnps; // may be null\n private final List maternalTerminalSnps;\n\n public Haplogroup(final String profileId,\n final String paternal,\n final String maternal,\n final List paternalTerminalSnps,\n final List maternalTerminalSnps) {\n checkNotNull(profileId);\n checkNotNull(maternal);\n checkNotNull(maternalTerminalSnps);\n this.profileId = profileId;\n this.paternal = paternal;\n this.maternal = maternal;\n this.paternalTerminalSnps = paternalTerminalSnps == null ? null : ImmutableList.copyOf(paternalTerminalSnps);\n this.maternalTerminalSnps = ImmutableList.copyOf(maternalTerminalSnps);\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public String getPaternal() {\n return paternal;\n }\n\n public String getMaternal() {\n return maternal;\n }\n\n public List getPaternalTerminalSnps() {\n return paternalTerminalSnps;\n }\n\n public List getMaternalTerminalSnps() {\n return maternalTerminalSnps;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/Ancestry.java\n@Immutable\npublic final class Ancestry {\n private final String profileId;\n private final String label;\n private final double proportion;\n private final double unassigned;\n private final List subPopulations;\n\n public Ancestry(final String profileId, final String label, final double proportion, final double unassigned, final List subPopulations)\n {\n checkNotNull(profileId);\n checkNotNull(label);\n checkNotNull(subPopulations);\n this.profileId = profileId;\n this.label = label;\n this.proportion = proportion;\n this.unassigned = unassigned;\n this.subPopulations = ImmutableList.copyOf(subPopulations);\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public String getLabel() {\n return label;\n }\n\n public double getProportion() {\n return proportion;\n }\n\n public double getUnassigned() {\n return unassigned;\n }\n\n public List getSubPopulations() {\n return subPopulations;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/PersonalGenomeClientException.java\npublic class PersonalGenomeClientException extends RuntimeException {\n\n /**\n * Create a new personal genome client exception with the specified error description.\n *\n * @param description error description\n */\n public PersonalGenomeClientException(final String description) {\n super(description);\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/User.java\n@Immutable\npublic final class User {\n private final String id;\n private final List profiles;\n\n public User(final String id, final List profiles) {\n checkNotNull(id);\n checkNotNull(profiles);\n this.id = id;\n this.profiles = ImmutableList.copyOf(profiles);\n }\n\n public String getId() {\n return id;\n }\n\n public List getProfiles() {\n return profiles;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/UserName.java\n@Immutable\npublic final class UserName {\n private final String id;\n private final String firstName;\n private final String lastName;\n private final List profileNames;\n\n public UserName(final String id, final String firstName, final String lastName, final List profileNames) {\n checkNotNull(id);\n checkNotNull(firstName);\n checkNotNull(lastName);\n checkNotNull(profileNames);\n this.id = id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.profileNames = ImmutableList.copyOf(profileNames);\n }\n\n public String getId() {\n return id;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public List getProfileNames() {\n return profileNames;\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/Genome.java\n@Immutable\npublic final class Genome {\n private final String profileId;\n private final String values;\n\n public Genome(final String profileId, final String values) {\n checkNotNull(profileId);\n checkNotNull(values);\n this.profileId = profileId;\n this.values = values;\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public String getValues() {\n return values;\n }\n\n public Genotype asGenotype() {\n return asGenotype(Locations.locations());\n }\n\n public Genotype asGenotype(final String... locations) {\n checkNotNull(locations);\n Map genotypeValues = new HashMap(locations.length);\n for (String location : locations) {\n checkNotNull(location);\n int index = Locations.index(location);\n if (index >= 0 && index < values.length() - 1) {\n genotypeValues.put(location, values.substring(index, index + 2));\n }\n }\n return new Genotype(profileId, genotypeValues);\n }\n\n public Genotype asGenotype(final Iterable locations) {\n checkNotNull(locations);\n Map genotypeValues = new HashMap();\n for (String location : locations) {\n checkNotNull(location);\n int index = Locations.index(location);\n if (index >= 0 && index < values.length() - 1) {\n genotypeValues.put(location, values.substring(index, index + 2));\n }\n }\n return new Genotype(profileId, genotypeValues);\n }\n}\nclient/src/main/java/com/github/heuermh/personalgenome/client/Trait.java\n@Immutable\npublic final class Trait {\n private final String profileId;\n private final String reportId;\n private final String description;\n\n // todo: trait is a value in possible_traits, or null if the profile's not analyzed at those markers\n private final String trait;\n\n private final Set possibleTraits;\n\n public Trait(final String profileId, final String reportId, final String description, final String trait, final Set possibleTraits) {\n checkNotNull(profileId);\n checkNotNull(reportId);\n checkNotNull(description);\n checkNotNull(trait);\n checkNotNull(possibleTraits);\n if (!possibleTraits.contains(trait)) {\n throw new IllegalArgumentException(\"trait must be contained in possible traits\");\n }\n this.profileId = profileId;\n this.reportId = reportId;\n this.description = description;\n this.trait = trait;\n this.possibleTraits = ImmutableSet.copyOf(possibleTraits);\n }\n\n public String getProfileId() {\n return profileId;\n }\n\n public String getReportId() {\n return reportId;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String getTrait() {\n return trait;\n }\n\n public Set getPossibleTraits() {\n return possibleTraits;\n }\n}\n", "answers": [" Genotype parseGenotypes(InputStream inputStream);"], "length": 1330, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "e63deab76df8b07154c470c607756c30c7cd9bfd027e7d3c"} {"input": "import logging\nimport multiprocessing as mp\nimport os\nimport re\nimport shutil\nimport statistics\nimport subprocess\nimport time\nimport tqdm\nfrom abc import abstractmethod\nfrom queue import Empty\nfrom typing import TYPE_CHECKING, Dict, List, NamedTuple, Optional, Tuple\nfrom montreal_forced_aligner.abc import MfaWorker, ModelExporterMixin, TrainerMixin\nfrom montreal_forced_aligner.alignment import AlignMixin\nfrom montreal_forced_aligner.alignment.multiprocessing import AccStatsArguments, AccStatsFunction\nfrom montreal_forced_aligner.corpus.acoustic_corpus import AcousticCorpusPronunciationMixin\nfrom montreal_forced_aligner.corpus.features import FeatureConfigMixin\nfrom montreal_forced_aligner.exceptions import KaldiProcessingError\nfrom montreal_forced_aligner.helper import align_phones\nfrom montreal_forced_aligner.models import AcousticModel\nfrom montreal_forced_aligner.textgrid import process_ctm_line\nfrom montreal_forced_aligner.utils import (\n KaldiProcessWorker,\n Stopped,\n log_kaldi_errors,\n parse_logs,\n run_mp,\n run_non_mp,\n thirdparty_binary,\n)\n from montreal_forced_aligner.abc import MetaDict\n from montreal_forced_aligner.corpus.classes import UtteranceCollection\n from montreal_forced_aligner.corpus.multiprocessing import Job\n from montreal_forced_aligner.textgrid import CtmInterval\n from datetime import datetime\n from ..utils import get_mfa_version\n return self.worker\n\n @property\n def utterances(self) -> UtteranceCollection:\n return self.worker.utterances\n\n def log_debug(self, message: str) -> None:\n \"\"\"\n Log a debug message. This function is a wrapper around the worker's :meth:`logging.Logger.debug`\n\n Parameters\n ----------\n message: str\n Debug message to log\n \"\"\"\n self.worker.log_debug(message)\n\n def log_error(self, message: str) -> None:\n \"\"\"\n Log an info message. This function is a wrapper around the worker's :meth:`logging.Logger.info`\n\n Parameters\n ----------\n message: str\n Info message to log\n \"\"\"\n self.worker.log_error(message)\n\n def log_warning(self, message: str) -> None:\n \"\"\"\n Log a warning message. This function is a wrapper around the worker's :meth:`logging.Logger.warning`\n\n Parameters\n ----------\n message: str\n Warning message to log\n \"\"\"\n self.worker.log_warning(message)\n\n def log_info(self, message: str) -> None:\n \"\"\"\n Log an error message. This function is a wrapper around the worker's :meth:`logging.Logger.error`\n\n Parameters\n ----------\n message: str\n Error message to log\n \"\"\"\n self.worker.log_info(message)\n\n @property\n def logger(self) -> logging.Logger:\n \"\"\"Top-level worker's logger\"\"\"\n return self.worker.logger\n\n @property\n def jobs(self) -> List[Job]:\n \"\"\"Top-level worker's job objects\"\"\"\n return self.worker.jobs\n\n @property\n def disambiguation_symbols_int_path(self) -> str:\n \"\"\"Path to the disambiguation int file\"\"\"\n return self.worker.disambiguation_symbols_int_path\n\n def construct_feature_proc_strings(\n self, speaker_independent: bool = False\n ) -> List[Dict[str, str]]:\n \"\"\"Top-level worker's feature strings\"\"\"\n return self.worker.construct_feature_proc_strings(speaker_independent)\n\n def construct_base_feature_string(self, all_feats: bool = False) -> str:\n \"\"\"Top-level worker's base feature string\"\"\"\n return self.worker.construct_base_feature_string(all_feats)\n\n @property\n def data_directory(self) -> str:\n \"\"\"Get the current data directory based on subset\"\"\"\n return self.worker.data_directory\n\n @property\n def corpus_output_directory(self) -> str:\n \"\"\"Directory of the corpus\"\"\"\n return self.worker.corpus_output_directory\n\n @property\n def num_utterances(self) -> int:\n \"\"\"Number of utterances of the corpus\"\"\"\n if self.subset:\n return self.subset\n return self.worker.num_utterances\n\n def initialize_training(self) -> None:\n \"\"\"Initialize training\"\"\"\n self.compute_calculated_properties()\n self.current_gaussians = 0\n begin = time.time()\n dirty_path = os.path.join(self.working_directory, \"dirty\")\n done_path = os.path.join(self.working_directory, \"done\")\n if os.path.exists(dirty_path): # if there was an error, let's redo from scratch\n shutil.rmtree(self.working_directory)\n self.logger.info(f\"Initializing training for {self.identifier}...\")\n if os.path.exists(done_path):\n self.training_complete = True\n return\n os.makedirs(self.working_directory, exist_ok=True)\n os.makedirs(self.working_log_directory, exist_ok=True)\n if self.subset and self.subset >= len(self.worker.utterances):\n self.logger.warning(\n \"Subset specified is larger than the dataset, \"\n \"using full corpus for this training block.\"\n )\n self.subset = 0\n self.worker.current_subset = 0\n try:\n self._trainer_initialization()\n parse_logs(self.working_log_directory)\n except Exception as e:\n with open(dirty_path, \"w\"):\n pass\n", "context": "montreal_forced_aligner/utils.py\ndef run_mp(\n function: Callable,\n argument_list: List[Tuple[Any, ...]],\n log_directory: str,\n return_info: bool = False,\n) -> Optional[Dict[int, Any]]:\n \"\"\"\n Apply a function for each job in parallel\n\n Parameters\n ----------\n function: Callable\n Multiprocessing function to apply\n argument_list: list\n List of arguments for each job\n log_directory: str\n Directory that all log information from the processes goes to\n return_info: dict, optional\n If the function returns information, supply the return dict to populate\n \"\"\"\n from .config import BLAS_THREADS\n\n os.environ[\"OPENBLAS_NUM_THREADS\"] = f\"{BLAS_THREADS}\"\n os.environ[\"MKL_NUM_THREADS\"] = f\"{BLAS_THREADS}\"\n stopped = Stopped()\n manager = mp.Manager()\n job_queue = manager.Queue()\n return_dict = manager.dict()\n info = None\n if return_info:\n info = manager.dict()\n for a in argument_list:\n job_queue.put(a)\n procs = []\n for i in range(len(argument_list)):\n p = ProcessWorker(i, job_queue, function, return_dict, stopped, info)\n procs.append(p)\n p.start()\n\n for p in procs:\n p.join()\n if \"error\" in return_dict:\n _, exc = return_dict[\"error\"]\n raise exc\n\n parse_logs(log_directory)\n if return_info:\n return info\nmontreal_forced_aligner/corpus/acoustic_corpus.py\nclass AcousticCorpusPronunciationMixin(\n AcousticCorpusMixin, MultispeakerDictionaryMixin, metaclass=ABCMeta\n):\n \"\"\"\n Mixin for acoustic corpora with Pronunciation dictionaries\n\n See Also\n --------\n :class:`~montreal_forced_aligner.corpus.acoustic_corpus.AcousticCorpusMixin`\n For corpus parsing parameters\n :class:`~montreal_forced_aligner.dictionary.multispeaker.MultispeakerDictionaryMixin`\n For dictionary parsing parameters\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def load_corpus(self) -> None:\n \"\"\"\n Load the corpus\n \"\"\"\n all_begin = time.time()\n self.dictionary_setup()\n self.log_debug(f\"Using {self.phone_set_type}\")\n self.log_debug(f\"Loaded dictionary in {time.time() - all_begin}\")\n\n begin = time.time()\n self._load_corpus()\n self.log_debug(f\"Loaded corpus in {time.time() - begin}\")\n\n begin = time.time()\n self.set_lexicon_word_set(self.corpus_word_set)\n self.log_debug(f\"Set up lexicon word set in {time.time() - begin}\")\n\n begin = time.time()\n\n self.log_debug(\"Topology:\")\n for k, v in self.kaldi_phones_for_topo.items():\n self.log_debug(f\"{k}: {', '.join(v)}\")\n self.log_debug(\"Extra questions:\")\n for k, v in self.extra_questions_mapping.items():\n self.log_debug(f\"{k}: {', '.join(v)}\")\n self.write_lexicon_information()\n self.log_debug(f\"Wrote lexicon information in {time.time() - begin}\")\n\n begin = time.time()\n for speaker in self.speakers:\n speaker.set_dictionary(self.get_dictionary(speaker.name))\n self.log_debug(f\"Set dictionaries for speakers in {time.time() - begin}\")\n\n begin = time.time()\n self.initialize_jobs()\n self.log_debug(f\"Initialized jobs in {time.time() - begin}\")\n begin = time.time()\n self.write_corpus_information()\n self.log_debug(f\"Wrote corpus information in {time.time() - begin}\")\n\n begin = time.time()\n self.create_corpus_split()\n self.log_debug(f\"Created corpus split directory in {time.time() - begin}\")\n\n begin = time.time()\n self.generate_features()\n self.log_debug(f\"Generated features in {time.time() - begin}\")\n\n begin = time.time()\n self.calculate_oovs_found()\n self.log_debug(f\"Calculated oovs found in {time.time() - begin}\")\n self.log_debug(f\"Setting up corpus took {time.time() - all_begin} seconds\")\nmontreal_forced_aligner/alignment/multiprocessing.py\nclass AccStatsFunction(KaldiFunction):\n \"\"\"\n Multiprocessing function for accumulating stats in GMM training.\n\n See Also\n --------\n :meth:`.AcousticModelTrainingMixin.acc_stats`\n Main function that calls this function in parallel\n :meth:`.AcousticModelTrainingMixin.acc_stats_arguments`\n Job method for generating arguments for this function\n :kaldi_src:`gmm-acc-stats-ali`\n Relevant Kaldi binary\n\n Parameters\n ----------\n args: :class:`~montreal_forced_aligner.alignment.multiprocessing.AccStatsArguments`\n Arguments for the function\n \"\"\"\n\n progress_pattern = re.compile(\n r\"^LOG \\(gmm-acc-stats-ali.* Processed (?P\\d+) utterances;.*\"\n )\n\n done_pattern = re.compile(\n r\"^LOG \\(gmm-acc-stats-ali.*Done (?P\\d+) files, (?P\\d+) with errors.$\"\n )\n\n def __init__(self, args: AccStatsArguments):\n self.log_path = args.log_path\n self.dictionaries = args.dictionaries\n self.feature_strings = args.feature_strings\n self.model_path = args.model_path\n self.ali_paths = args.ali_paths\n self.acc_paths = args.acc_paths\n\n def run(self):\n \"\"\"Run the function\"\"\"\n processed_count = 0\n with open(self.log_path, \"w\", encoding=\"utf8\") as log_file:\n for dict_name in self.dictionaries:\n acc_proc = subprocess.Popen(\n [\n thirdparty_binary(\"gmm-acc-stats-ali\"),\n self.model_path,\n self.feature_strings[dict_name],\n f\"ark,s,cs:{self.ali_paths[dict_name]}\",\n self.acc_paths[dict_name],\n ],\n stderr=subprocess.PIPE,\n encoding=\"utf8\",\n env=os.environ,\n )\n for line in acc_proc.stderr:\n log_file.write(line)\n m = self.progress_pattern.match(line.strip())\n if m:\n now_processed = int(m.group(\"utterances\"))\n progress_update = now_processed - processed_count\n processed_count = now_processed\n yield progress_update, 0\n else:\n m = self.done_pattern.match(line.strip())\n if m:\n now_processed = int(m.group(\"utterances\"))\n progress_update = now_processed - processed_count\n yield progress_update, int(m.group(\"errors\"))\nmontreal_forced_aligner/abc.py\nclass ModelExporterMixin(ExporterMixin, metaclass=abc.ABCMeta):\n \"\"\"\n Abstract mixin class for exporting MFA models\n \"\"\"\n\n @property\n @abc.abstractmethod\n def meta(self) -> MetaDict:\n \"\"\"Training configuration parameters\"\"\"\n ...\n\n @abc.abstractmethod\n def export_model(self, output_model_path: str) -> None:\n \"\"\"\n Abstract method to export an MFA model\n\n Parameters\n ----------\n output_model_path: str\n Path to export model\n \"\"\"\n ...\nmontreal_forced_aligner/helper.py\ndef align_phones(\n ref: List[CtmInterval],\n test: List[CtmInterval],\n silence_phone: str,\n custom_mapping: Optional[Dict[str, str]] = None,\n) -> Tuple[float, float]:\n \"\"\"\n Align phones based on how much they overlap and their phone label, with the ability to specify a custom mapping for\n different phone labels to be scored as if they're the same phone\n\n Parameters\n ----------\n ref: list[:class:`~montreal_forced_aligner.data.CtmInterval`]\n List of CTM intervals as reference\n test: list[:class:`~montreal_forced_aligner.data.CtmInterval`]\n List of CTM intervals to compare to reference\n silence_phones: set[str]\n Set of silence phones (these are ignored in the final calculation)\n custom_mapping: dict[str, str], optional\n Mapping of phones to treat as matches even if they have different symbols\n\n Returns\n -------\n float\n Score based on the average amount of overlap in phone intervals\n float\n Phone error rate\n \"\"\"\n from Bio import pairwise2\n\n if custom_mapping is None:\n score_func = functools.partial(overlap_scoring, silence_phone=silence_phone)\n else:\n score_func = functools.partial(\n overlap_scoring, silence_phone=silence_phone, mapping=custom_mapping\n )\n alignments = pairwise2.align.globalcs(\n ref, test, score_func, -5, -5, gap_char=[\"-\"], one_alignment_only=True\n )\n overlap_count = 0\n overlap_sum = 0\n num_insertions = 0\n num_deletions = 0\n num_substitutions = 0\n for a in alignments:\n for i, sa in enumerate(a.seqA):\n sb = a.seqB[i]\n if sa == \"-\":\n if sb.label != silence_phone:\n num_insertions += 1\n else:\n continue\n elif sb == \"-\":\n if sa.label != silence_phone:\n num_deletions += 1\n else:\n continue\n else:\n overlap_sum += abs(sa.begin - sb.begin) + abs(sa.end - sb.end)\n overlap_count += 1\n if compare_labels(sa.label, sb.label, silence_phone, mapping=custom_mapping) > 0:\n num_substitutions += 1\n if overlap_count:\n score = overlap_sum / overlap_count\n else:\n score = None\n phone_error_rate = (num_insertions + num_deletions + (2 * num_substitutions)) / len(ref)\n return score, phone_error_rate\nmontreal_forced_aligner/alignment/multiprocessing.py\nclass AccStatsArguments(NamedTuple):\n \"\"\"\n Arguments for :class:`~montreal_forced_aligner.alignment.multiprocessing.AccStatsFunction`\n \"\"\"\n\n log_path: str\n dictionaries: List[str]\n feature_strings: Dict[str, str]\n ali_paths: Dict[str, str]\n acc_paths: Dict[str, str]\n model_path: str\nmontreal_forced_aligner/exceptions.py\nclass KaldiProcessingError(MFAError):\n \"\"\"\n Exception class for when a Kaldi binary has an exception\n\n Parameters\n ----------\n error_logs: list[str]\n List of Kaldi logs that had errors\n log_file: str, optional\n Overall log file to find more information\n \"\"\"\n\n def __init__(self, error_logs: List[str], log_file: Optional[str] = None):\n super().__init__(\n f\"There were {len(error_logs)} job(s) with errors when running Kaldi binaries.\"\n )\n\n if log_file is not None:\n self.message_lines.append(\n f\" For more details, please check {self.printer.error_text(log_file)}\"\n )\n self.error_logs = error_logs\n self.log_file = log_file\n\n def update_log_file(self, logger: logging.Logger) -> None:\n \"\"\"\n Update the log file output\n\n Parameters\n ----------\n logger: logging.Logger\n Logger\n \"\"\"\n if logger.handlers:\n self.log_file = logger.handlers[0].baseFilename\n self.message_lines = [\n f\"There were {len(self.error_logs)} job(s) with errors when running Kaldi binaries.\"\n ]\n if self.log_file is not None:\n self.message_lines.append(\n f\" For more details, please check {self.printer.error_text(self.log_file)}\"\n )\nmontreal_forced_aligner/alignment/mixins.py\nclass AlignMixin(DictionaryMixin):\n \"\"\"\n Configuration object for alignment\n\n Parameters\n ----------\n transition_scale : float\n Transition scale, defaults to 1.0\n acoustic_scale : float\n Acoustic scale, defaults to 0.1\n self_loop_scale : float\n Self-loop scale, defaults to 0.1\n boost_silence : float\n Factor to boost silence probabilities, 1.0 is no boost or reduction\n beam : int\n Size of the beam to use in decoding, defaults to 10\n retry_beam : int\n Size of the beam to use in decoding if it fails with the initial beam width, defaults to 40\n\n\n See Also\n --------\n :class:`~montreal_forced_aligner.dictionary.mixins.DictionaryMixin`\n For dictionary parsing parameters\n\n Attributes\n ----------\n logger: logging.Logger\n Eventual top-level worker logger\n jobs: list[Job]\n Jobs to process\n use_mp: bool\n Flag for using multiprocessing\n \"\"\"\n\n logger: logging.Logger\n jobs: List[Job]\n use_mp: bool\n\n def __init__(\n self,\n transition_scale: float = 1.0,\n acoustic_scale: float = 0.1,\n self_loop_scale: float = 0.1,\n boost_silence: float = 1.0,\n beam: int = 10,\n retry_beam: int = 40,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.transition_scale = transition_scale\n self.acoustic_scale = acoustic_scale\n self.self_loop_scale = self_loop_scale\n self.boost_silence = boost_silence\n self.beam = beam\n self.retry_beam = retry_beam\n if self.retry_beam <= self.beam:\n self.retry_beam = self.beam * 4\n self.unaligned_files = set()\n\n @property\n def tree_path(self):\n \"\"\"Path to tree file\"\"\"\n return os.path.join(self.working_directory, \"tree\")\n\n @property\n @abstractmethod\n def data_directory(self):\n \"\"\"Corpus data directory\"\"\"\n ...\n\n @abstractmethod\n def construct_feature_proc_strings(self) -> List[Dict[str, str]]:\n \"\"\"Generate feature strings\"\"\"\n ...\n\n def compile_train_graphs_arguments(self) -> List[CompileTrainGraphsArguments]:\n \"\"\"\n Generate Job arguments for :class:`~montreal_forced_aligner.alignment.multiprocessing.CompileTrainGraphsFunction`\n\n Returns\n -------\n list[:class:`~montreal_forced_aligner.alignment.multiprocessing.CompileTrainGraphsArguments`]\n Arguments for processing\n \"\"\"\n args = []\n for j in self.jobs:\n lexicon_fst_paths = {\n dictionary.name: dictionary.lexicon_fst_path\n for dictionary in j.current_dictionaries\n }\n model_path = self.model_path\n if not os.path.exists(model_path):\n model_path = self.alignment_model_path\n args.append(\n CompileTrainGraphsArguments(\n os.path.join(self.working_log_directory, f\"compile_train_graphs.{j.name}.log\"),\n j.current_dictionary_names,\n os.path.join(self.working_directory, \"tree\"),\n model_path,\n j.construct_path_dictionary(self.data_directory, \"text\", \"int.scp\"),\n self.disambiguation_symbols_int_path,\n lexicon_fst_paths,\n j.construct_path_dictionary(self.working_directory, \"fsts\", \"scp\"),\n )\n )\n return args\n\n def align_arguments(self) -> List[AlignArguments]:\n \"\"\"\n Generate Job arguments for :class:`~montreal_forced_aligner.alignment.multiprocessing.AlignFunction`\n\n Returns\n -------\n list[:class:`~montreal_forced_aligner.alignment.multiprocessing.AlignArguments`]\n Arguments for processing\n \"\"\"\n args = []\n feat_strings = self.construct_feature_proc_strings()\n iteration = getattr(self, \"iteration\", None)\n for j in self.jobs:\n if iteration is not None:\n log_path = os.path.join(\n self.working_log_directory, f\"align.{iteration}.{j.name}.log\"\n )\n else:\n log_path = os.path.join(self.working_log_directory, f\"align.{j.name}.log\")\n args.append(\n AlignArguments(\n log_path,\n j.current_dictionary_names,\n j.construct_path_dictionary(self.working_directory, \"fsts\", \"scp\"),\n feat_strings[j.name],\n self.alignment_model_path,\n j.construct_path_dictionary(self.working_directory, \"ali\", \"ark\"),\n self.align_options,\n )\n )\n return args\n\n def compile_information_arguments(self) -> List[CompileInformationArguments]:\n \"\"\"\n Generate Job arguments for :func:`~montreal_forced_aligner.alignment.multiprocessing.compile_information_func`\n\n Returns\n -------\n list[:class:`~montreal_forced_aligner.alignment.multiprocessing.CompileInformationArguments`]\n Arguments for processing\n \"\"\"\n args = []\n iteration = getattr(self, \"iteration\", None)\n for j in self.jobs:\n if iteration is not None:\n log_path = os.path.join(\n self.working_log_directory, f\"align.{iteration}.{j.name}.log\"\n )\n else:\n log_path = os.path.join(self.working_log_directory, f\"align.{j.name}.log\")\n args.append(CompileInformationArguments(log_path))\n return args\n\n @property\n def align_options(self) -> MetaDict:\n \"\"\"Options for use in aligning\"\"\"\n return {\n \"transition_scale\": self.transition_scale,\n \"acoustic_scale\": self.acoustic_scale,\n \"self_loop_scale\": self.self_loop_scale,\n \"beam\": self.beam,\n \"retry_beam\": self.retry_beam,\n \"boost_silence\": self.boost_silence,\n \"optional_silence_csl\": self.optional_silence_csl,\n }\n\n def alignment_configuration(self) -> MetaDict:\n \"\"\"Configuration parameters\"\"\"\n return {\n \"transition_scale\": self.transition_scale,\n \"acoustic_scale\": self.acoustic_scale,\n \"self_loop_scale\": self.self_loop_scale,\n \"boost_silence\": self.boost_silence,\n \"beam\": self.beam,\n \"retry_beam\": self.retry_beam,\n }\n\n def compile_train_graphs(self) -> None:\n \"\"\"\n Multiprocessing function that compiles training graphs for utterances.\n\n See Also\n --------\n :class:`~montreal_forced_aligner.alignment.multiprocessing.CompileTrainGraphsFunction`\n Multiprocessing helper function for each job\n :meth:`.AlignMixin.compile_train_graphs_arguments`\n Job method for generating arguments for the helper function\n :kaldi_steps:`align_si`\n Reference Kaldi script\n :kaldi_steps:`align_fmllr`\n Reference Kaldi script\n \"\"\"\n begin = time.time()\n log_directory = self.working_log_directory\n os.makedirs(log_directory, exist_ok=True)\n self.logger.info(\"Compiling training graphs...\")\n error_sum = 0\n arguments = self.compile_train_graphs_arguments()\n with tqdm.tqdm(total=self.num_utterances) as pbar:\n if self.use_mp:\n manager = mp.Manager()\n error_dict = manager.dict()\n return_queue = manager.Queue()\n stopped = Stopped()\n procs = []\n for i, args in enumerate(arguments):\n function = CompileTrainGraphsFunction(args)\n p = KaldiProcessWorker(i, return_queue, function, error_dict, stopped)\n procs.append(p)\n p.start()\n while True:\n try:\n done, errors = return_queue.get(timeout=1)\n if stopped.stop_check():\n continue\n except Empty:\n for proc in procs:\n if not proc.finished.stop_check():\n break\n else:\n break\n continue\n pbar.update(done + errors)\n error_sum += errors\n for p in procs:\n p.join()\n if error_dict:\n for v in error_dict.values():\n raise v\n else:\n self.logger.debug(\"Not using multiprocessing...\")\n for args in arguments:\n function = CompileTrainGraphsFunction(args)\n for done, errors in function.run():\n pbar.update(done + errors)\n error_sum += errors\n if error_sum:\n self.logger.warning(\n f\"Compilation of training graphs failed for {error_sum} utterances.\"\n )\n self.logger.debug(f\"Compiling training graphs took {time.time() - begin}\")\n\n def align_utterances(self) -> None:\n \"\"\"\n Multiprocessing function that aligns based on the current model.\n\n See Also\n --------\n :class:`~montreal_forced_aligner.alignment.multiprocessing.AlignFunction`\n Multiprocessing helper function for each job\n :meth:`.AlignMixin.align_arguments`\n Job method for generating arguments for the helper function\n :kaldi_steps:`align_si`\n Reference Kaldi script\n :kaldi_steps:`align_fmllr`\n Reference Kaldi script\n \"\"\"\n begin = time.time()\n self.unaligned_files = set()\n self.logger.info(\"Generating alignments...\")\n with tqdm.tqdm(total=self.num_utterances) as pbar:\n if self.use_mp:\n manager = mp.Manager()\n error_dict = manager.dict()\n return_queue = manager.Queue()\n stopped = Stopped()\n procs = []\n for i, args in enumerate(self.align_arguments()):\n function = AlignFunction(args)\n p = KaldiProcessWorker(i, return_queue, function, error_dict, stopped)\n procs.append(p)\n p.start()\n while True:\n try:\n utterance, log_likelihood = return_queue.get(timeout=1)\n if stopped.stop_check():\n continue\n except Empty:\n for proc in procs:\n if not proc.finished.stop_check():\n break\n else:\n break\n continue\n if hasattr(self, \"utterances\"):\n if hasattr(self, \"frame_shift\"):\n num_frames = int(\n self.utterances[utterance].duration * self.frame_shift\n )\n else:\n num_frames = self.utterances[utterance].duration\n self.utterances[utterance].alignment_log_likelihood = (\n log_likelihood / num_frames\n )\n pbar.update(1)\n for p in procs:\n p.join()\n if error_dict:\n for v in error_dict.values():\n raise v\n else:\n self.logger.debug(\"Not using multiprocessing...\")\n for args in self.align_arguments():\n function = AlignFunction(args)\n for utterance, log_likelihood in function.run():\n if hasattr(self, \"utterances\"):\n if hasattr(self, \"frame_shift\"):\n num_frames = int(\n self.utterances[utterance].duration * self.frame_shift\n )\n else:\n num_frames = self.utterances[utterance].duration\n self.utterances[utterance].alignment_log_likelihood = (\n log_likelihood / num_frames\n )\n pbar.update(1)\n\n self.compile_information()\n self.logger.debug(f\"Alignment round took {time.time() - begin}\")\n\n def compile_information(self):\n \"\"\"\n Compiles information about alignment, namely what the overall log-likelihood was\n and how many files were unaligned.\n\n See Also\n --------\n :func:`~montreal_forced_aligner.alignment.multiprocessing.compile_information_func`\n Multiprocessing helper function for each job\n :meth:`.AlignMixin.compile_information_arguments`\n Job method for generating arguments for the helper function\n \"\"\"\n compile_info_begin = time.time()\n\n jobs = self.compile_information_arguments()\n\n if self.use_mp:\n alignment_info = run_mp(\n compile_information_func, jobs, self.working_log_directory, True\n )\n else:\n alignment_info = run_non_mp(\n compile_information_func, jobs, self.working_log_directory, True\n )\n\n avg_like_sum = 0\n avg_like_frames = 0\n average_logdet_sum = 0\n average_logdet_frames = 0\n beam_too_narrow_count = 0\n too_short_count = 0\n for data in alignment_info.values():\n beam_too_narrow_count += len(data[\"unaligned\"])\n too_short_count += len(data[\"too_short\"])\n avg_like_frames += data[\"total_frames\"]\n avg_like_sum += data[\"log_like\"] * data[\"total_frames\"]\n if \"logdet_frames\" in data:\n average_logdet_frames += data[\"logdet_frames\"]\n average_logdet_sum += data[\"logdet\"] * data[\"logdet_frames\"]\n\n if hasattr(self, \"utterances\"):\n csv_path = os.path.join(self.working_directory, \"alignment_log_likelihood.csv\")\n with open(csv_path, \"w\", newline=\"\", encoding=\"utf8\") as f:\n writer = csv.writer(f)\n writer.writerow([\"utterance\", \"loglikelihood\"])\n for u in self.utterances:\n writer.writerow([u.name, u.alignment_log_likelihood])\n\n if not avg_like_frames:\n self.logger.warning(\n \"No files were aligned, this likely indicates serious problems with the aligner.\"\n )\n else:\n if too_short_count:\n self.logger.debug(\n f\"There were {too_short_count} utterances that were too short to be aligned.\"\n )\n if beam_too_narrow_count:\n self.logger.debug(\n f\"There were {beam_too_narrow_count} utterances that could not be aligned with \"\n f\"the current beam settings.\"\n )\n average_log_like = avg_like_sum / avg_like_frames\n if average_logdet_sum:\n average_log_like += average_logdet_sum / average_logdet_frames\n self.logger.debug(f\"Average per frame likelihood for alignment: {average_log_like}\")\n self.logger.debug(f\"Compiling information took {time.time() - compile_info_begin}\")\n\n @property\n @abstractmethod\n def working_directory(self) -> str:\n \"\"\"Working directory\"\"\"\n ...\n\n @property\n @abstractmethod\n def working_log_directory(self) -> str:\n \"\"\"Working log directory\"\"\"\n ...\n\n @property\n def model_path(self) -> str:\n \"\"\"Acoustic model file path\"\"\"\n return os.path.join(self.working_directory, \"final.mdl\")\n\n @property\n def alignment_model_path(self) -> str:\n \"\"\"Acoustic model file path for speaker-independent alignment\"\"\"\n path = os.path.join(self.working_directory, \"final.alimdl\")\n if os.path.exists(path):\n return path\n return self.model_path\nmontreal_forced_aligner/utils.py\ndef log_kaldi_errors(error_logs: List[str], logger: logging.Logger) -> None:\n \"\"\"\n Save details of Kaldi processing errors to a logger\n\n Parameters\n ----------\n error_logs: list[str]\n Kaldi log files with errors\n logger: :class:`~logging.Logger`\n Logger to output to\n \"\"\"\n logger.debug(f\"There were {len(error_logs)} kaldi processing files that had errors:\")\n for path in error_logs:\n logger.debug(\"\")\n logger.debug(path)\n with open(path, \"r\", encoding=\"utf8\") as f:\n for line in f:\n logger.debug(\"\\t\" + line.strip())\nmontreal_forced_aligner/utils.py\ndef run_non_mp(\n function: Callable,\n argument_list: List[Tuple[Any, ...]],\n log_directory: str,\n return_info: bool = False,\n) -> Optional[Dict[Any, Any]]:\n \"\"\"\n Similar to :func:`run_mp`, but no additional processes are used and the jobs are evaluated in sequential order\n\n Parameters\n ----------\n function: Callable\n Multiprocessing function to evaluate\n argument_list: list\n List of arguments to process\n log_directory: str\n Directory that all log information from the processes goes to\n return_info: dict, optional\n If the function returns information, supply the return dict to populate\n\n Returns\n -------\n dict, optional\n If the function returns information, returns the dictionary it was supplied with\n \"\"\"\n if return_info:\n info = {}\n for i, args in enumerate(argument_list):\n info[i] = function(*args)\n parse_logs(log_directory)\n return info\n\n for args in argument_list:\n function(*args)\n parse_logs(log_directory)\nmontreal_forced_aligner/utils.py\ndef parse_logs(log_directory: str) -> None:\n \"\"\"\n Parse the output of a Kaldi run for any errors and raise relevant MFA exceptions\n\n Parameters\n ----------\n log_directory: str\n Log directory to parse\n\n Raises\n ------\n KaldiProcessingError\n If any log files contained error lines\n\n \"\"\"\n error_logs = []\n for name in os.listdir(log_directory):\n log_path = os.path.join(log_directory, name)\n with open(log_path, \"r\", encoding=\"utf8\") as f:\n for line in f:\n line = line.strip()\n if \"error while loading shared libraries: libopenblas.so.0\" in line:\n raise ThirdpartyError(\"libopenblas.so.0\", open_blas=True)\n for libc_version in [\"GLIBC_2.27\", \"GLIBCXX_3.4.20\"]:\n if libc_version in line:\n raise ThirdpartyError(libc_version, libc=True)\n if \"sox FAIL formats\" in line:\n f = line.split(\" \")[-1]\n raise ThirdpartyError(f, sox=True)\n if line.startswith(\"ERROR\") or line.startswith(\"ASSERTION_FAILED\"):\n error_logs.append(log_path)\n break\n if error_logs:\n raise KaldiProcessingError(error_logs)\nmontreal_forced_aligner/textgrid.py\ndef process_ctm_line(line: str) -> CtmInterval:\n \"\"\"\n Helper function for parsing a line of CTM file to construct a CTMInterval\n\n Parameters\n ----------\n line: str\n Input string\n\n Returns\n -------\n :class:`~montreal_forced_aligner.data.CtmInterval`\n Extracted data from the line\n \"\"\"\n line = line.split(\" \")\n utt = line[0]\n if len(line) == 5:\n begin = round(float(line[2]), 4)\n duration = float(line[3])\n end = round(begin + duration, 4)\n label = line[4]\n else:\n begin = round(float(line[1]), 4)\n duration = float(line[2])\n end = round(begin + duration, 4)\n label = line[3]\n return CtmInterval(begin, end, label, utt)\nmontreal_forced_aligner/corpus/features.py\nclass FeatureConfigMixin:\n \"\"\"\n Class to store configuration information about MFCC generation\n\n Attributes\n ----------\n feature_type : str\n Feature type, defaults to \"mfcc\"\n use_energy : bool\n Flag for whether first coefficient should be used, defaults to False\n frame_shift : int\n number of milliseconds between frames, defaults to 10\n snip_edges : bool\n Flag for enabling Kaldi's snip edges, should be better time precision\n pitch : bool\n Flag for including pitch in features, currently nonfunctional, defaults to False\n low_frequency : int\n Frequency floor\n high_frequency : int\n Frequency ceiling\n sample_frequency : int\n Sampling frequency\n allow_downsample : bool\n Flag for whether to allow downsampling, default is True\n allow_upsample : bool\n Flag for whether to allow upsampling, default is True\n speaker_independent : bool\n Flag for whether features are speaker independent, default is True\n uses_cmvn : bool\n Flag for whether to use CMVN, default is True\n uses_deltas : bool\n Flag for whether to use delta features, default is True\n uses_splices : bool\n Flag for whether to use splices and LDA transformations, default is False\n uses_speaker_adaptation : bool\n Flag for whether to use speaker adaptation, default is False\n fmllr_update_type : str\n Type of fMLLR estimation, defaults to \"full\"\n silence_weight : float\n Weight of silence in calculating LDA or fMLLR\n splice_left_context : int or None\n Number of frames to splice on the left for calculating LDA\n splice_right_context : int or None\n Number of frames to splice on the right for calculating LDA\n \"\"\"\n\n def __init__(\n self,\n feature_type: str = \"mfcc\",\n use_energy: bool = False,\n frame_shift: int = 10,\n snip_edges: bool = True,\n pitch: bool = False,\n low_frequency: int = 20,\n high_frequency: int = 7800,\n sample_frequency: int = 16000,\n allow_downsample: bool = True,\n allow_upsample: bool = True,\n speaker_independent: bool = True,\n uses_cmvn: bool = True,\n uses_deltas: bool = True,\n uses_splices: bool = False,\n uses_voiced: bool = False,\n uses_speaker_adaptation: bool = False,\n fmllr_update_type: str = \"full\",\n silence_weight: float = 0.0,\n splice_left_context: int = 3,\n splice_right_context: int = 3,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.feature_type = feature_type\n self.use_energy = use_energy\n self.frame_shift = frame_shift\n self.snip_edges = snip_edges\n self.pitch = pitch\n self.low_frequency = low_frequency\n self.high_frequency = high_frequency\n self.sample_frequency = sample_frequency\n self.allow_downsample = allow_downsample\n self.allow_upsample = allow_upsample\n self.speaker_independent = speaker_independent\n self.uses_cmvn = uses_cmvn\n self.uses_deltas = uses_deltas\n self.uses_splices = uses_splices\n self.uses_voiced = uses_voiced\n self.uses_speaker_adaptation = uses_speaker_adaptation\n self.fmllr_update_type = fmllr_update_type\n self.silence_weight = silence_weight\n self.splice_left_context = splice_left_context\n self.splice_right_context = splice_right_context\n\n @property\n def vad_options(self) -> MetaDict:\n \"\"\"Abstract method for VAD options\"\"\"\n raise NotImplementedError\n\n @property\n def alignment_model_path(self) -> str: # needed for fmllr\n \"\"\"Abstract method for alignment model path\"\"\"\n raise NotImplementedError\n\n @property\n def model_path(self) -> str: # needed for fmllr\n \"\"\"Abstract method for model path\"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def working_directory(self) -> str:\n \"\"\"Abstract method for working directory\"\"\"\n ...\n\n @property\n @abstractmethod\n def corpus_output_directory(self) -> str:\n \"\"\"Abstract method for working directory of corpus\"\"\"\n ...\n\n @property\n @abstractmethod\n def data_directory(self) -> str:\n \"\"\"Abstract method for corpus data directory\"\"\"\n ...\n\n @property\n def feature_options(self) -> MetaDict:\n \"\"\"Parameters for feature generation\"\"\"\n options = {\n \"type\": self.feature_type,\n \"use_energy\": self.use_energy,\n \"frame_shift\": self.frame_shift,\n \"snip_edges\": self.snip_edges,\n \"low_frequency\": self.low_frequency,\n \"high_frequency\": self.high_frequency,\n \"sample_frequency\": self.sample_frequency,\n \"allow_downsample\": self.allow_downsample,\n \"allow_upsample\": self.allow_upsample,\n \"pitch\": self.pitch,\n \"uses_cmvn\": self.uses_cmvn,\n \"uses_deltas\": self.uses_deltas,\n \"uses_voiced\": self.uses_voiced,\n \"uses_splices\": self.uses_splices,\n \"uses_speaker_adaptation\": self.uses_speaker_adaptation,\n }\n if self.uses_splices:\n options.update(\n {\n \"splice_left_context\": self.splice_left_context,\n \"splice_right_context\": self.splice_right_context,\n }\n )\n return options\n\n @abstractmethod\n def calc_fmllr(self) -> None:\n \"\"\"Abstract method for calculating fMLLR transforms\"\"\"\n ...\n\n @property\n def fmllr_options(self) -> MetaDict:\n \"\"\"Options for use in calculating fMLLR transforms\"\"\"\n return {\n \"fmllr_update_type\": self.fmllr_update_type,\n \"silence_weight\": self.silence_weight,\n \"silence_csl\": getattr(\n self, \"silence_csl\", \"\"\n ), # If we have silence phones from a dictionary, use them\n }\n\n @property\n def mfcc_options(self) -> MetaDict:\n \"\"\"Parameters to use in computing MFCC features.\"\"\"\n return {\n \"use-energy\": self.use_energy,\n \"frame-shift\": self.frame_shift,\n \"low-freq\": self.low_frequency,\n \"high-freq\": self.high_frequency,\n \"sample-frequency\": self.sample_frequency,\n \"allow-downsample\": self.allow_downsample,\n \"allow-upsample\": self.allow_upsample,\n \"snip-edges\": self.snip_edges,\n }\nmontreal_forced_aligner/abc.py\nclass TrainerMixin(ModelExporterMixin):\n \"\"\"\n Abstract mixin class for MFA trainers\n\n Parameters\n ----------\n num_iterations: int\n Number of training iterations\n\n Attributes\n ----------\n iteration: int\n Current iteration\n \"\"\"\n\n def __init__(self, num_iterations: int = 40, **kwargs):\n super().__init__(**kwargs)\n self.iteration: int = 0\n self.num_iterations = num_iterations\n\n @abc.abstractmethod\n def initialize_training(self) -> None:\n \"\"\"Initialize training\"\"\"\n ...\n\n @abc.abstractmethod\n def train(self) -> None:\n \"\"\"Perform training\"\"\"\n ...\n\n @abc.abstractmethod\n def train_iteration(self) -> None:\n \"\"\"Run one training iteration\"\"\"\n ...\n\n @abc.abstractmethod\n def finalize_training(self) -> None:\n \"\"\"Finalize training\"\"\"\n ...\nmontreal_forced_aligner/models.py\nclass AcousticModel(Archive):\n \"\"\"\n Class for storing acoustic models in MFA, exported as zip files containing the necessary Kaldi files\n to be reused\n\n \"\"\"\n\n files = [\"final.mdl\", \"final.alimdl\", \"final.occs\", \"lda.mat\", \"tree\"]\n extensions = [\".zip\", \".am\"]\n\n model_type = \"acoustic\"\n\n def __init__(self, source: str, root_directory: Optional[str] = None):\n if source in AcousticModel.get_available_models():\n source = AcousticModel.get_pretrained_path(source)\n\n super().__init__(source, root_directory)\n\n def add_meta_file(self, trainer: ModelExporterMixin) -> None:\n \"\"\"\n Add metadata file from a model trainer\n\n Parameters\n ----------\n trainer: :class:`~montreal_forced_aligner.abc.ModelExporterMixin`\n Trainer to supply metadata information about the acoustic model\n \"\"\"\n with open(os.path.join(self.dirname, \"meta.json\"), \"w\", encoding=\"utf8\") as f:\n json.dump(trainer.meta, f)\n\n @property\n def parameters(self) -> MetaDict:\n \"\"\"Parameters to pass to top-level workers\"\"\"\n params = {**self.meta[\"features\"]}\n params[\"non_silence_phones\"] = {x for x in self.meta[\"phones\"]}\n params[\"oov_phone\"] = self.meta[\"oov_phone\"]\n params[\"optional_silence_phone\"] = self.meta[\"optional_silence_phone\"]\n params[\"other_noise_phone\"] = self.meta[\"other_noise_phone\"]\n params[\"phone_set_type\"] = self.meta[\"phone_set_type\"]\n return params\n\n @property\n def meta(self) -> MetaDict:\n \"\"\"\n Metadata information for the acoustic model\n \"\"\"\n default_features = {\n \"feature_type\": \"mfcc\",\n \"use_energy\": False,\n \"frame_shift\": 10,\n \"snip_edges\": True,\n \"low_frequency\": 20,\n \"high_frequency\": 7800,\n \"sample_frequency\": 16000,\n \"allow_downsample\": True,\n \"allow_upsample\": True,\n \"pitch\": False,\n \"uses_cmvn\": True,\n \"uses_deltas\": True,\n \"uses_splices\": False,\n \"uses_voiced\": False,\n \"uses_speaker_adaptation\": False,\n \"silence_weight\": 0.0,\n \"fmllr_update_type\": \"full\",\n \"splice_left_context\": 3,\n \"splice_right_context\": 3,\n }\n if not self._meta:\n meta_path = os.path.join(self.dirname, \"meta.json\")\n format = \"json\"\n if not os.path.exists(meta_path):\n meta_path = os.path.join(self.dirname, \"meta.yaml\")\n format = \"yaml\"\n if not os.path.exists(meta_path):\n self._meta = {\n \"version\": \"0.9.0\",\n \"architecture\": \"gmm-hmm\",\n \"features\": default_features,\n }\n else:\n with open(meta_path, \"r\", encoding=\"utf8\") as f:\n if format == \"yaml\":\n self._meta = yaml.safe_load(f)\n else:\n self._meta = json.load(f)\n if self._meta[\"features\"] == \"mfcc+deltas\":\n self._meta[\"features\"] = default_features\n if \"phone_type\" not in self._meta:\n self._meta[\"phone_type\"] = \"triphone\"\n if \"optional_silence_phone\" not in self._meta:\n self._meta[\"optional_silence_phone\"] = \"sil\"\n if \"oov_phone\" not in self._meta:\n self._meta[\"oov_phone\"] = \"spn\"\n if \"other_noise_phone\" not in self._meta:\n self._meta[\"other_noise_phone\"] = \"sp\"\n if \"phone_set_type\" not in self._meta:\n self._meta[\"phone_set_type\"] = \"UNKNOWN\"\n self._meta[\"phones\"] = set(self._meta.get(\"phones\", []))\n if (\n \"uses_speaker_adaptation\" not in self._meta[\"features\"]\n or not self._meta[\"features\"][\"uses_speaker_adaptation\"]\n ):\n self._meta[\"features\"][\"uses_speaker_adaptation\"] = os.path.exists(\n os.path.join(self.dirname, \"final.alimdl\")\n )\n if (\n \"uses_splices\" not in self._meta[\"features\"]\n or not self._meta[\"features\"][\"uses_splices\"]\n ):\n self._meta[\"features\"][\"uses_splices\"] = os.path.exists(\n os.path.join(self.dirname, \"lda.mat\")\n )\n if self._meta[\"features\"][\"uses_splices\"]:\n self._meta[\"features\"][\"uses_deltas\"] = False\n self.parse_old_features()\n return self._meta\n\n def pretty_print(self) -> None:\n \"\"\"\n Prints the metadata information to the terminal\n \"\"\"\n from .utils import get_mfa_version\n\n printer = TerminalPrinter()\n configuration_data = {\"Acoustic model\": {\"name\": (self.name, \"green\"), \"data\": {}}}\n version_color = \"green\"\n if self.meta[\"version\"] != get_mfa_version():\n version_color = \"red\"\n configuration_data[\"Acoustic model\"][\"data\"][\"Version\"] = (\n self.meta[\"version\"],\n version_color,\n )\n\n if \"citation\" in self.meta:\n configuration_data[\"Acoustic model\"][\"data\"][\"Citation\"] = self.meta[\"citation\"]\n if \"train_date\" in self.meta:\n configuration_data[\"Acoustic model\"][\"data\"][\"Train date\"] = self.meta[\"train_date\"]\n configuration_data[\"Acoustic model\"][\"data\"][\"Architecture\"] = self.meta[\"architecture\"]\n configuration_data[\"Acoustic model\"][\"data\"][\"Phone type\"] = self.meta[\"phone_type\"]\n configuration_data[\"Acoustic model\"][\"data\"][\"Features\"] = {\n \"Feature type\": self.meta[\"features\"][\"feature_type\"],\n \"Frame shift\": self.meta[\"features\"][\"frame_shift\"],\n \"Performs speaker adaptation\": self.meta[\"features\"][\"uses_speaker_adaptation\"],\n \"Performs LDA on features\": self.meta[\"features\"][\"uses_splices\"],\n }\n if self.meta[\"phones\"]:\n configuration_data[\"Acoustic model\"][\"data\"][\"Phones\"] = self.meta[\"phones\"]\n else:\n configuration_data[\"Acoustic model\"][\"data\"][\"Phones\"] = (\"None found!\", \"red\")\n\n printer.print_config(configuration_data)\n\n def add_model(self, source: str) -> None:\n \"\"\"\n Add file into archive\n\n Parameters\n ----------\n source: str\n File to add\n \"\"\"\n for f in self.files:\n if os.path.exists(os.path.join(source, f)):\n copyfile(os.path.join(source, f), os.path.join(self.dirname, f))\n\n def export_model(self, destination: str) -> None:\n \"\"\"\n Extract the model files to a new directory\n\n Parameters\n ----------\n destination: str\n Destination directory to extract files to\n \"\"\"\n os.makedirs(destination, exist_ok=True)\n for f in self.files:\n if os.path.exists(os.path.join(self.dirname, f)):\n copyfile(os.path.join(self.dirname, f), os.path.join(destination, f))\n\n def log_details(self, logger: Logger) -> None:\n \"\"\"\n Log metadata information to a logger\n\n Parameters\n ----------\n logger: :class:`~logging.Logger`\n Logger to send debug information to\n \"\"\"\n logger.debug(\"\")\n logger.debug(\"====ACOUSTIC MODEL INFO====\")\n logger.debug(\"Acoustic model root directory: \" + self.root_directory)\n logger.debug(\"Acoustic model dirname: \" + self.dirname)\n meta_path = os.path.join(self.dirname, \"meta.json\")\n if not os.path.exists(meta_path):\n meta_path = os.path.join(self.dirname, \"meta.yaml\")\n logger.debug(\"Acoustic model meta path: \" + meta_path)\n if not os.path.exists(meta_path):\n logger.debug(\"META.YAML DOES NOT EXIST, this may cause issues in validating the model\")\n logger.debug(\"Acoustic model meta information:\")\n stream = yaml.dump(self.meta)\n logger.debug(stream)\n logger.debug(\"\")\n\n def validate(self, dictionary: DictionaryMixin) -> None:\n \"\"\"\n Validate this acoustic model against a pronunciation dictionary to ensure their\n phone sets are compatible\n\n Parameters\n ----------\n dictionary: :class:`~montreal_forced_aligner.dictionary.mixins.DictionaryMixin`\n DictionaryMixin to compare phone sets with\n\n Raises\n ------\n :class:`~montreal_forced_aligner.exceptions.PronunciationAcousticMismatchError`\n If there are phones missing from the acoustic model\n \"\"\"\n if isinstance(dictionary, G2PModel):\n missing_phones = dictionary.meta[\"phones\"] - set(self.meta[\"phones\"])\n else:\n missing_phones = dictionary.non_silence_phones - set(self.meta[\"phones\"])\n if missing_phones:\n raise (PronunciationAcousticMismatchError(missing_phones))\nmontreal_forced_aligner/abc.py\nclass MfaWorker(metaclass=abc.ABCMeta):\n \"\"\"\n Abstract class for MFA workers\n\n Parameters\n ----------\n use_mp: bool\n Flag to run in multiprocessing mode, defaults to True\n debug: bool\n Flag to run in debug mode, defaults to False\n verbose: bool\n Flag to run in verbose mode, defaults to False\n\n Attributes\n ----------\n dirty: bool\n Flag for whether an error was encountered in processing\n \"\"\"\n\n def __init__(\n self,\n use_mp: bool = True,\n debug: bool = False,\n verbose: bool = False,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.debug = debug\n self.verbose = verbose\n self.use_mp = use_mp\n self.dirty = False\n\n def log_debug(self, message: str) -> None:\n \"\"\"\n Print a debug message\n\n Parameters\n ----------\n message: str\n Debug message to log\n \"\"\"\n print(message)\n\n def log_error(self, message: str) -> None:\n \"\"\"\n Print an error message\n\n Parameters\n ----------\n message: str\n Error message to log\n \"\"\"\n print(message)\n\n def log_info(self, message: str) -> None:\n \"\"\"\n Print an info message\n\n Parameters\n ----------\n message: str\n Info message to log\n \"\"\"\n print(message)\n\n def log_warning(self, message: str) -> None:\n \"\"\"\n Print a warning message\n\n Parameters\n ----------\n message: str\n Warning message to log\n \"\"\"\n print(message)\n\n @classmethod\n def extract_relevant_parameters(cls, config: MetaDict) -> Tuple[MetaDict, List[str]]:\n \"\"\"\n Filter a configuration dictionary to just the relevant parameters for the current worker\n\n Parameters\n ----------\n config: dict[str, Any]\n Configuration dictionary\n\n Returns\n -------\n dict[str, Any]\n Filtered configuration dictionary\n list[str]\n Skipped keys\n \"\"\"\n skipped = []\n new_config = {}\n for k, v in config.items():\n if k in cls.get_configuration_parameters():\n new_config[k] = v\n else:\n skipped.append(k)\n return new_config, skipped\n\n @classmethod\n def get_configuration_parameters(cls) -> Dict[str, Type]:\n \"\"\"\n Get the types of parameters available to be configured\n\n Returns\n -------\n dict[str, Type]\n Dictionary of parameter names and their types\n \"\"\"\n mapping = {Dict: dict, Tuple: tuple, List: list, Set: set}\n configuration_params = {}\n for t, ty in get_type_hints(cls.__init__).items():\n configuration_params[t] = ty\n try:\n if ty.__origin__ == Union:\n configuration_params[t] = ty.__args__[0]\n except AttributeError:\n pass\n\n for c in cls.mro():\n try:\n for t, ty in get_type_hints(c.__init__).items():\n configuration_params[t] = ty\n try:\n if ty.__origin__ == Union:\n configuration_params[t] = ty.__args__[0]\n except AttributeError:\n pass\n except AttributeError:\n pass\n for t, ty in configuration_params.items():\n for v in mapping.values():\n try:\n if ty.__origin__ == v:\n configuration_params[t] = v\n break\n except AttributeError:\n break\n return configuration_params\n\n @property\n def configuration(self) -> MetaDict:\n \"\"\"Configuration parameters\"\"\"\n return {\n \"debug\": self.debug,\n \"verbose\": self.verbose,\n \"use_mp\": self.use_mp,\n \"dirty\": self.dirty,\n }\n\n @property\n @abc.abstractmethod\n def working_directory(self) -> str:\n \"\"\"Current working directory\"\"\"\n ...\n\n @property\n def working_log_directory(self) -> str:\n \"\"\"Current working log directory\"\"\"\n return os.path.join(self.working_directory, \"log\")\n\n @property\n @abc.abstractmethod\n def data_directory(self) -> str:\n \"\"\"Data directory\"\"\"\n ...\nmontreal_forced_aligner/utils.py\nclass KaldiProcessWorker(mp.Process):\n \"\"\"\n Multiprocessing function work\n\n Parameters\n ----------\n job_name: int\n Integer number of job\n job_q: :class:`~multiprocessing.Queue`\n Job queue to pull arguments from\n function: KaldiFunction\n Multiprocessing function to call on arguments from job_q\n return_dict: dict\n Dictionary for collecting errors\n stopped: :class:`~montreal_forced_aligner.utils.Stopped`\n Stop check\n return_info: dict[int, Any], optional\n Optional dictionary to fill if the function should return information to main thread\n \"\"\"\n\n def __init__(\n self,\n job_name: int,\n return_q: mp.Queue,\n function: KaldiFunction,\n error_dict: dict,\n stopped: Stopped,\n ):\n mp.Process.__init__(self)\n self.job_name = job_name\n self.function = function\n self.return_q = return_q\n self.error_dict = error_dict\n self.stopped = stopped\n self.finished = Stopped()\n\n def run(self) -> None:\n \"\"\"\n Run through the arguments in the queue apply the function to them\n \"\"\"\n try:\n for result in self.function.run():\n self.return_q.put(result)\n except Exception:\n self.stopped.stop()\n self.error_dict[self.job_name] = Exception(traceback.format_exception(*sys.exc_info()))\n finally:\n self.finished.stop()\nmontreal_forced_aligner/utils.py\nclass Stopped(object):\n \"\"\"\n Multiprocessing class for detecting whether processes should stop processing and exit ASAP\n\n Attributes\n ----------\n val: :func:`~multiprocessing.Value`\n 0 if not stopped, 1 if stopped\n lock: :class:`~multiprocessing.Lock`\n Lock for process safety\n _source: multiprocessing.Value\n 1 if it was a Ctrl+C event that stopped it, 0 otherwise\n \"\"\"\n\n def __init__(self, initval: Union[bool, int] = False):\n self.val = mp.Value(\"i\", initval)\n self.lock = mp.Lock()\n self._source = mp.Value(\"i\", 0)\n\n def stop(self) -> None:\n \"\"\"Signal that work should stop asap\"\"\"\n with self.lock:\n self.val.value = True\n\n def stop_check(self) -> int:\n \"\"\"Check whether a process should stop\"\"\"\n with self.lock:\n return self.val.value\n\n def set_sigint_source(self) -> None:\n \"\"\"Set the source as a ctrl+c\"\"\"\n with self.lock:\n self._source.value = True\n\n def source(self) -> int:\n \"\"\"Get the source value\"\"\"\n with self.lock:\n return self._source.value\nmontreal_forced_aligner/utils.py\ndef thirdparty_binary(binary_name: str) -> str:\n \"\"\"\n Generate full path to a given binary name\n\n Notes\n -----\n With the move to conda, this function is deprecated as conda will manage the path much better\n\n Parameters\n ----------\n binary_name: str\n Executable to run\n\n Returns\n -------\n str\n Full path to the executable\n \"\"\"\n bin_path = shutil.which(binary_name)\n if bin_path is None:\n if binary_name in [\"fstcompile\", \"fstarcsort\", \"fstconvert\"] and sys.platform != \"win32\":\n raise ThirdpartyError(binary_name, open_fst=True)\n else:\n raise ThirdpartyError(binary_name)\n return bin_path\n", "answers": [" if isinstance(e, KaldiProcessingError):"], "length": 4864, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "ea576f502a5c03c3c320c5b03f33547d9a312f89f191adbb"} {"input": "package io.github.memfis19.cadar.view;\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.os.Looper;\nimport android.os.Process;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.util.SparseArray;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.view.ViewTreeObserver;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.List;\nimport io.github.memfis19.cadar.CalendarController;\nimport io.github.memfis19.cadar.R;\nimport io.github.memfis19.cadar.data.entity.Event;\nimport io.github.memfis19.cadar.event.CalendarPrepareCallback;\nimport io.github.memfis19.cadar.event.DisplayEventCallback;\nimport io.github.memfis19.cadar.event.OnDayChangeListener;\nimport io.github.memfis19.cadar.event.OnMonthChangeListener;\nimport io.github.memfis19.cadar.internal.helper.ScrollManager;\nimport io.github.memfis19.cadar.internal.process.EventsProcessor;\nimport io.github.memfis19.cadar.internal.process.MonthEventsProcessor;\nimport io.github.memfis19.cadar.internal.ui.month.MonthCalendarHelper;\nimport io.github.memfis19.cadar.internal.ui.month.adapter.MonthAdapter;\nimport io.github.memfis19.cadar.internal.ui.month.adapter.MonthHandlerThread;\nimport io.github.memfis19.cadar.internal.utils.DateUtils;\nimport io.github.memfis19.cadar.settings.MonthCalendarConfiguration;\n\n\n\n\n\n/**\n * Created by memfis on 7/14/16.\n */\npublic class MonthCalendar extends LinearLayout implements ViewPager.OnPageChangeListener,\n ScrollManager.OnScrollChanged, CalendarController, ViewTreeObserver.OnPreDrawListener {\n\n private static final String TAG = \"MonthView3\";\n\n private Calendar currentMonth;\n private int currentPosition = 0;\n\n private MonthHandlerThread monthHandlerThread;\n private EventsProcessor>> eventsAsyncProcessor;\n\n private LayoutInflater layoutInflater;\n private ViewGroup monthHeaderView;\n private ViewPager monthGridView;\n\n private MonthAdapter monthAdapter;\n\n private MonthCalendarConfiguration monthCalendarConfiguration;\n private SimpleDateFormat weekDayFormatter;\n", "context": "cadar/src/main/java/io/github/memfis19/cadar/CalendarController.java\npublic interface CalendarController {\n\n void prepareCalendar(T configuration);\n\n void releaseCalendar();\n\n void setSelectedDay(Calendar selectedDay, boolean scrollToSelectedDay);\n\n void displayEvents(List eventList, @Nullable DisplayEventCallback callback);\n}\ncadar/src/main/java/io/github/memfis19/cadar/internal/process/MonthEventsProcessor.java\npublic class MonthEventsProcessor extends EventsProcessor>> {\n\n public MonthEventsProcessor(boolean shouldProcess, EventCalculator eventProcessor) {\n super(shouldProcess, eventProcessor, false);\n }\n\n @Override\n protected SparseArray> processEvents(Calendar target) {\n\n List result;\n\n final SparseArray> calendarEvents = new SparseArray<>();\n\n if (isShouldProcess()) {\n Date start = DateUtils.setTimeToMonthStart(target.getTime());\n Date end = DateUtils.setTimeToMonthEnd(target.getTime());\n\n result = getEventProcessor().getEventsForPeriod(start, end);\n } else\n result = new ArrayList<>(getEventList() == null ? new ArrayList() : getEventList());\n\n Calendar temp = DateUtils.getCalendarInstance();\n for (Event event : result) {\n temp.setTime(event.getEventStartDate());\n\n if (!DateUtils.isSameMonth(temp, target)) continue;\n\n List events = calendarEvents.get(temp.get(Calendar.DAY_OF_MONTH), new ArrayList());\n events.add(event);\n\n calendarEvents.put(temp.get(Calendar.DAY_OF_MONTH), events);\n }\n result.clear();\n\n return calendarEvents;\n }\n}\ncadar/src/main/java/io/github/memfis19/cadar/internal/utils/DateUtils.java\npublic final class DateUtils {\n\n private final static String TAG = \"DateUtils\";\n\n public static final int MAX_YEAR_RANGE = 50;\n\n public static final long WEEK_TIME_MILLIS = 7 * 24 * 60 * 60 * 1000;\n\n public static final String MMMM_yyyy = \"MMMM yyyy\";\n public static final String cccc_dd = \"cccc dd\";\n\n public static final Calendar today = getCalendarInstance();//TODO: need update current value correctly\n\n public static Locale danish = new Locale(\"da\", \"DK\");\n public static Map map = new HashMap<>();\n\n public static Locale getLocale() {\n return danish;\n }\n\n public static Calendar getCalendarInstance() {\n try {\n return Calendar.getInstance(getTimeZone(), getLocale());\n } catch (Exception e) {\n Log.e(TAG, \"Can't create instance of the specified calendar. \");\n }\n return Calendar.getInstance();\n }\n\n public static TimeZone getTimeZone() {\n return TimeZone.getDefault();\n }\n\n public static Calendar setTimeToYearStart(Calendar calendar) {\n calendar.set(Calendar.MONTH, Calendar.JANUARY);\n calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));\n calendar.set(Calendar.HOUR_OF_DAY, 0);\n calendar.set(Calendar.MINUTE, 0);\n calendar.set(Calendar.SECOND, 0);\n calendar.set(Calendar.MILLISECOND, 0);\n return calendar;\n }\n\n\n public static Calendar setTimeToYearEnd(Calendar calendar) {\n calendar.set(Calendar.MONTH, Calendar.DECEMBER);\n calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n calendar.set(Calendar.HOUR_OF_DAY, 23);\n calendar.set(Calendar.MINUTE, 59);\n calendar.set(Calendar.SECOND, 59);\n calendar.set(Calendar.MILLISECOND, 999);\n return calendar;\n }\n\n public static Date setTimeToYearStart(Date date) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n setTimeToMidnight(calendar);\n calendar.set(Calendar.MONTH, Calendar.JANUARY);\n calendar.set(Calendar.DAY_OF_YEAR, 1);\n return calendar.getTime();\n }\n\n public static Date setTimeToYearEnd(Date date) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n setTimeToEndOfTheDay(calendar);\n calendar.set(Calendar.MONTH, Calendar.DECEMBER);\n calendar.set(Calendar.DAY_OF_MONTH, 31);\n return calendar.getTime();\n }\n\n public static Date setTimeToMonthStart(Date date) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n setTimeToMidnight(calendar);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n return calendar.getTime();\n }\n\n public static Calendar setTimeToMonthStart(Calendar calendar) {\n calendar = setTimeToMidnight(calendar);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n return calendar;\n }\n\n public static Date setTimeToMonthEnd(Date date) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n setTimeToEndOfTheDay(calendar);\n calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n return calendar.getTime();\n }\n\n public static Calendar setTimeToMidnight(Calendar calendar) {\n calendar.set(Calendar.HOUR_OF_DAY, 0);\n calendar.set(Calendar.MINUTE, 0);\n calendar.set(Calendar.SECOND, 0);\n calendar.set(Calendar.MILLISECOND, 0);\n\n return calendar;\n }\n\n /**\n * Sets the date time to the midnight.\n *\n * @param date - to set the time\n * @return - the same date with new time\n */\n public static Date setTimeToMidnight(Date date) {\n Calendar calendar = getCalendarInstance();\n calendar.setTimeInMillis(date.getTime());\n calendar = setTimeToMidnight(calendar);\n\n return calendar.getTime();\n }\n\n public static Calendar setTimeToEndOfTheDay(Calendar calendar) {\n calendar.set(Calendar.HOUR_OF_DAY, 23);\n calendar.set(Calendar.MINUTE, 59);\n calendar.set(Calendar.SECOND, 59);\n calendar.set(Calendar.MILLISECOND, 0);\n\n return calendar;\n }\n\n /**\n * Sets the date time to the end of the day.\n *\n * @param date - to set the time\n * @return - the same date with new time\n */\n public static Date setTimeToEndOfTheDay(Date date) {\n Calendar calendar = getCalendarInstance();\n calendar.setTimeInMillis(date.getTime());\n calendar = setTimeToEndOfTheDay(calendar);\n\n\n return calendar.getTime();\n }\n\n /**\n * Method returns number of days between two dates using hours/minutes for calculation.\n * Example: start = 20/12/2015T15:00:00, end = 21/12/2015T13:00:00, result = 0 days.\n * Use the same time for different dates to avoid such problem.\n *\n * @param start - start date\n * @param end - end period\n * @return - number of years between start and end date.\n * @see #setTimeToMidnight(java.util.Date)\n * @see #setTimeToEndOfTheDay(java.util.Date)\n */\n public static int daysBetween(Date start, Date end) {\n DateTime startDateTime = new DateTime(start);\n DateTime endDateTime = new DateTime(end);\n\n return Days.daysBetween(startDateTime, endDateTime).getDays();\n }\n\n public static int daysBetweenPure(Date start, Date end) {\n DateTime startDateTime = new DateTime(setTimeToMidnight(start));\n DateTime endDateTime = new DateTime(setTimeToMidnight(end));\n\n return Days.daysBetween(startDateTime, endDateTime).getDays();\n }\n\n public static int monthBetween(Date start, Date end) {\n DateTime startDateTime = new DateTime(start);\n DateTime endDateTime = new DateTime(end);\n\n return Months.monthsBetween(startDateTime, endDateTime).getMonths();\n }\n\n public static int monthBetweenPure(Date start, Date end) {\n Calendar startCalendar = getCalendarInstance();\n startCalendar.setTime(start);\n Calendar endCalendar = getCalendarInstance();\n endCalendar.setTime(end);\n\n int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);\n int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);\n return diffMonth;\n }\n\n\n public static int weeksBetween(Date start, Date end) {\n DateTime startDateTime = new DateTime(start);\n DateTime endDateTime = new DateTime(end);\n\n return Weeks.weeksBetween(startDateTime, endDateTime).getWeeks();\n }\n\n /**\n * Method returns number of years between two dates using day/month for calculation.\n * Example: start = 20/12/2015, end = 20/11/2016, result = 0 years.\n *\n * @param start - start date\n * @param end - end period\n * @return - number of years between start and end date.\n */\n public static int yearsBetween(Date start, Date end) {\n DateTime startDateTime = new DateTime(start);\n DateTime endDateTime = new DateTime(end);\n\n return Years.yearsBetween(startDateTime, endDateTime).getYears();\n }\n\n /**\n * Method returns number of years between two dates using years for calculation.\n * Example: start = 20/12/2015, end = 20/11/2016, result = 1 year.\n *\n * @param start - start date\n * @param end - end period\n * @return - number of years between start and end date.\n */\n public static int yearsBetweenPure(Date start, Date end) {\n DateTime startDateTime = new DateTime(start);\n DateTime endDateTime = new DateTime(end);\n\n return Math.abs(endDateTime.getYear() - startDateTime.getYear());\n }\n\n public static void resetTime(GregorianCalendar calendar) {\n calendar.set(Calendar.HOUR_OF_DAY, 0);\n calendar.set(Calendar.MINUTE, 0);\n calendar.set(Calendar.SECOND, 0);\n calendar.set(Calendar.MILLISECOND, 0);\n }\n\n /**\n * Return the minimum date for using in application. Now it is 01/01/1900\n *\n * @return - minimum supported date.\n */\n public static Date getMinimumSupportedDate() {\n DateTime minimumDate = new DateTime(1900, 1, 1, 0, 0);\n return minimumDate.toDate();\n }\n\n /**\n * Return the maximum date for using in application.\n *\n * @return - maximum supported date.\n */\n public static Date getMaximumSupportedDate() {\n DateTime maximumDate = new DateTime(DateTime.now().year().get() + MAX_YEAR_RANGE / 2, 1, 1, 0, 0);\n return maximumDate.toDate();\n }\n\n public static Date getCurrentDate() {\n DateTime dateTime = new DateTime();\n DateTime currentDate = new DateTime(dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth(), 0, 0);\n return currentDate.toDate();\n }\n\n public static long getCurrentTime() {\n Calendar calendar = getCalendarInstance();\n long offset = calendar.get(Calendar.ZONE_OFFSET);\n return calendar.getTimeInMillis() - offset;\n }\n\n public static boolean isLastDayOfTheMonth(Date date) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n return calendar.get(Calendar.DAY_OF_MONTH) == calendar.getActualMaximum(Calendar.DAY_OF_MONTH);\n }\n\n public static Date addYearToDate(Date date, int yearsToAdd) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n calendar.add(Calendar.YEAR, yearsToAdd);\n return calendar.getTime();\n }\n\n public static Date addMonthToDate(Date date, int monthsToAdd) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n calendar.add(Calendar.MONTH, monthsToAdd);\n return calendar.getTime();\n }\n\n public static Date addDayToDate(Date date, int daysToAdd) {\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);\n return calendar.getTime();\n }\n\n public static String dateToString(Calendar calendar, String pattern) {\n Date date = calendarToDate(calendar);\n return dateToString(date, pattern);\n }\n\n public static Date calendarToDate(Calendar calendar) {\n return new Date(calendar.getTimeInMillis());\n }\n\n public static String dateToString(Date date, String pattern) {\n return getDateFormat(pattern).format(date);\n }\n\n public static DateFormat getDateFormat(String pattern) {\n if (!map.containsKey(pattern)) {\n DateFormat df = new SimpleDateFormat(pattern, getLocale());\n map.put(pattern, df);\n }\n return map.get(pattern);\n }\n\n public static boolean isSameDay(Date firstDate, Date secondDate) {\n Calendar firstCalendar = getCalendarInstance();\n Calendar secondCalendar = getCalendarInstance();\n\n firstCalendar.setTime(firstDate);\n secondCalendar.setTime(secondDate);\n\n return isSameDay(firstCalendar, secondCalendar);\n }\n\n public static boolean isSameMonth(Calendar firstCalendar, Calendar secondCalendar) {\n if (firstCalendar == null || secondCalendar == null) return false;\n return firstCalendar.get(Calendar.YEAR) == secondCalendar.get(Calendar.YEAR)\n && firstCalendar.get(Calendar.MONTH) == secondCalendar.get(Calendar.MONTH);\n }\n\n public static boolean isSameYear(Calendar firstCalendar, Calendar secondCalendar) {\n if (firstCalendar == null || secondCalendar == null) return false;\n return firstCalendar.get(Calendar.YEAR) == secondCalendar.get(Calendar.YEAR);\n }\n\n public static boolean isSameDay(Calendar firstDate, Calendar secondDate) {\n return (firstDate.get(Calendar.DAY_OF_YEAR) == secondDate.get(Calendar.DAY_OF_YEAR)\n && firstDate.get(Calendar.YEAR) == secondDate.get(Calendar.YEAR));\n }\n\n //TODO: find other solution without creation of Calendar instance for performance\n\n public static Date roundDateToMinute(Date date) {\n if (date == null) return null;\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n\n if (calendar.get(Calendar.SECOND) > 30) {\n calendar.add(Calendar.MINUTE, 1);\n }\n\n calendar.set(Calendar.SECOND, 0);\n\n return calendar.getTime();\n }\n\n public static Date cutDateSeconds(Date date) {\n if (date == null) return null;\n Calendar calendar = getCalendarInstance();\n calendar.setTime(date);\n calendar.set(Calendar.SECOND, 0);\n return calendar.getTime();\n }\n\n /**\n *

Checks if a date is today.

\n *\n * @param date the date, not altered, not null.\n * @return true if the date is today.\n * @throws IllegalArgumentException if the date is null\n */\n public static boolean isToday(Date date) {\n return isSameDay(date, today.getTime());\n }\n\n /**\n *

Checks if a calendar date is today.

\n *\n * @param calendar the calendar, not altered, not null\n * @return true if cal date is today\n * @throws IllegalArgumentException if the calendar is null\n */\n public static boolean isToday(Calendar calendar) {\n return isSameDay(calendar, today);\n }\n}\ncadar/src/main/java/io/github/memfis19/cadar/internal/ui/month/adapter/MonthHandlerThread.java\npublic class MonthHandlerThread extends HandlerThread {\n\n private static final String TAG = \"MonthHandlerThread\";\n\n private static final int REQUEST_MONTH_PREPARATION = 852;\n\n private static final int NUM_OF_DAYS_IN_WEEK = 7;\n\n private class MonthInfoDto {\n private Calendar calendar;\n private Integer shiftValue;\n private RecyclerView recyclerView;\n\n MonthInfoDto(Calendar calendar, Integer shiftValue, RecyclerView recyclerView) {\n this.calendar = calendar;\n this.shiftValue = shiftValue;\n this.recyclerView = recyclerView;\n }\n }\n\n interface AdapterPrepareListener {\n void onReadyAdapter(Calendar month, List monthDays, RecyclerView recyclerView);\n }\n\n private boolean hasQuit = false;\n\n private Handler requestHandler;\n private Handler responseHandler;\n private AdapterPrepareListener adapterPrepareListener;\n\n public MonthHandlerThread() {\n super(TAG, Process.THREAD_PRIORITY_BACKGROUND);\n }\n\n void setAdapterPrepareListener(AdapterPrepareListener adapterPrepareListener) {\n this.adapterPrepareListener = adapterPrepareListener;\n }\n\n @Override\n protected void onLooperPrepared() {\n responseHandler = new Handler(Looper.getMainLooper());\n\n requestHandler = new Handler(Looper.myLooper()) {\n @Override\n public void handleMessage(Message msg) {\n if (msg.what == REQUEST_MONTH_PREPARATION) {\n handlePreparation((MonthInfoDto) msg.obj);\n }\n }\n };\n }\n\n @Override\n public boolean quit() {\n hasQuit = true;\n return super.quit();\n }\n\n @Override\n public boolean quitSafely() {\n hasQuit = true;\n return (Build.VERSION.SDK_INT > 17) ? super.quitSafely() : super.quit();\n }\n\n void queuePreparation(Calendar calendar, Integer shiftValue, RecyclerView recyclerView) {\n if (hasQuit || requestHandler == null) return;\n requestHandler.obtainMessage(REQUEST_MONTH_PREPARATION,\n new MonthInfoDto(calendar, shiftValue, recyclerView)).sendToTarget();\n }\n\n private void handlePreparation(final MonthInfoDto monthInfoDto) {\n final Calendar month = (Calendar) monthInfoDto.calendar.clone();\n month.add(Calendar.MONTH, monthInfoDto.shiftValue);\n\n month.set(Calendar.DAY_OF_MONTH, 1);\n final List monthDays = prepare(month);\n\n if (!hasQuit && adapterPrepareListener != null)\n responseHandler.post(new Runnable() {\n @Override\n public void run() {\n adapterPrepareListener.onReadyAdapter(month, monthDays, monthInfoDto.recyclerView);\n }\n });\n }\n\n private List prepare(Calendar monthCalendar) {\n\n List monthDays = new ArrayList<>();\n Calendar iterator = (Calendar) monthCalendar.clone();\n\n int month = iterator.get(Calendar.MONTH);\n int lastDay = iterator.getActualMaximum(Calendar.DATE);\n\n iterator.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);\n if (iterator.get(Calendar.MONTH) == month && iterator.get(Calendar.DATE) > 1) {\n iterator.add(Calendar.DATE, -7);\n }\n\n boolean finish = false;\n while (!finish) {\n\n for (int i = 0; i < NUM_OF_DAYS_IN_WEEK; i++) {\n if (month == iterator.get(Calendar.MONTH) && lastDay == iterator.get(Calendar.DATE)) {\n finish = true;\n }\n monthDays.add((Calendar) iterator.clone());\n iterator.add(Calendar.DATE, 1);\n }\n }\n\n return monthDays;\n }\n\n}\ncadar/src/main/java/io/github/memfis19/cadar/internal/helper/ScrollManager.java\npublic final class ScrollManager {\n\n static private Map viewScrollManagerMap = new HashMap<>();\n\n public static final int SCROLL_STATE_IDLE = 1;\n public static final int SCROLL_STATE_DRAGGING = 2;\n public static final int SCROLL_STATE_SETTLING = 3;\n\n @IntDef({SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING})\n @Retention(RetentionPolicy.SOURCE)\n public @interface ScrollState {\n }\n\n public interface OnScrollChanged {\n void onScrollStateChanged(@ScrollState int scrollState);\n }\n\n private View view;\n private int currentScrollState = SCROLL_STATE_IDLE;\n private List> subscribers = new ArrayList<>();\n\n public static ScrollManager geViewInstance(View view) {\n if (viewScrollManagerMap.get(view) == null) {\n viewScrollManagerMap.put(view, new ScrollManager(view));\n }\n return viewScrollManagerMap.get(view);\n }\n\n public void releaseScrollManager() {\n subscribers = null;\n viewScrollManagerMap.remove(view);\n view = null;\n }\n\n private ScrollManager(View view) {\n this.view = view;\n subscribers = new ArrayList<>();\n }\n\n public void notifyScrollStateChanged(@ScrollState int scrollState) {\n if (currentScrollState != scrollState) {\n currentScrollState = scrollState;\n notifyAllSubscribers();\n }\n }\n\n public int getCurrentScrollState() {\n return currentScrollState;\n }\n\n public void subscribeForScrollStateChanged(OnScrollChanged onScrollChanged) {\n subscribers.add(new WeakReference<>(onScrollChanged));\n }\n\n public void unSubscribeForScrollStateChanged(@NonNull OnScrollChanged onScrollChanged) {\n for (WeakReference weakReference : subscribers) {\n if (onScrollChanged.equals(weakReference.get())) {\n subscribers.remove(weakReference);\n return;\n }\n }\n }\n\n private void notifyAllSubscribers() {\n for (WeakReference weakReference : subscribers) {\n if (weakReference.get() != null)\n weakReference.get().onScrollStateChanged(currentScrollState);\n else subscribers.remove(weakReference);\n }\n }\n\n}\ncadar/src/main/java/io/github/memfis19/cadar/settings/MonthCalendarConfiguration.java\npublic final class MonthCalendarConfiguration extends BaseCalendarConfiguration {\n\n @CadarSettings.DayOfWeeks\n private int firstDayOfWeek = Calendar.MONDAY;\n\n private boolean displayDaysOutOfMonth = true;\n\n private MonthDayDecoratorFactory monthDayDecoratorFactory;\n private WeekDayDecorator weekDayDecorator;\n private EventsProcessor>> eventsProcessor;\n\n\n @LayoutRes\n private int\n monthLayoutId = R.layout.month_calendar_event_layout,\n weekTitleLayoutId = R.layout.month_calendar_day_of_week_layout;\n\n\n private MonthCalendarConfiguration() {\n super();\n }\n\n public static class Builder extends BaseCalendarConfigurationBuilder {\n\n private MonthCalendarConfiguration monthCalendarConfiguration;\n\n public Builder() {\n super();\n monthCalendarConfiguration = new MonthCalendarConfiguration();\n }\n\n public Builder setFirstDayOfWeek(@CadarSettings.DayOfWeeks int firstDayOfWeek) {\n monthCalendarConfiguration.firstDayOfWeek = firstDayOfWeek;\n return this;\n }\n\n public Builder setMonthDayLayout(@LayoutRes int monthLayoutId, MonthDayDecoratorFactory monthDayDecoratorFactory) {\n monthCalendarConfiguration.monthLayoutId = monthLayoutId;\n monthCalendarConfiguration.monthDayDecoratorFactory = monthDayDecoratorFactory;\n return this;\n }\n\n public Builder setEventsProcessor(EventsProcessor>> eventsProcessor) {\n monthCalendarConfiguration.eventsProcessor = eventsProcessor;\n return this;\n }\n\n public Builder setDayWeekTitleLayout(@LayoutRes int weekTitleLayoutId, WeekDayDecorator weekDayDecorator) {\n monthCalendarConfiguration.weekTitleLayoutId = weekTitleLayoutId;\n monthCalendarConfiguration.weekDayDecorator = weekDayDecorator;\n return this;\n }\n\n public Builder setDisplayDaysOutOfMonth(boolean displayDaysOutOfMonth) {\n monthCalendarConfiguration.displayDaysOutOfMonth = displayDaysOutOfMonth;\n return this;\n }\n\n @Override\n public MonthCalendarConfiguration build() throws NullPointerException, IllegalStateException, IllegalArgumentException {\n if (initialDay == null)\n throw new NullPointerException(\"Passed initial day can't be null.\");\n monthCalendarConfiguration.initialDay = initialDay;\n\n if (eventProcessingEnabled && eventCalculator == null)\n throw new IllegalStateException(\"Configuration set to process events. But event processor not passed or null.\");\n monthCalendarConfiguration.eventProcessingEnabled = eventProcessingEnabled;\n monthCalendarConfiguration.eventCalculator = eventCalculator;\n\n if (eventProcessingEnabled && eventFactory == null)\n throw new NullPointerException(\"Event factory is null. Please setup it.\");\n monthCalendarConfiguration.eventFactory = eventFactory;\n monthCalendarConfiguration.eventCalculator.setEventFactory(monthCalendarConfiguration.eventFactory);\n\n if (weekDayTitleTranslationEnabled) {\n if (mondayTitle == 0\n || tuesdayTitle == 0\n || wednesdayTitle == 0\n || thursdayTitle == 0\n || fridayTitle == 0\n || saturdayTitle == 0\n || sundayTitle == 0) {\n throw new IllegalArgumentException(\"Configuration set to override default week day titles, but not all titles are passed.\");\n }\n }\n monthCalendarConfiguration.weekDayTitleTranslationEnabled = weekDayTitleTranslationEnabled;\n if (monthCalendarConfiguration.weekDayTitleTranslationEnabled) {\n monthCalendarConfiguration.mondayTitle = mondayTitle;\n monthCalendarConfiguration.tuesdayTitle = tuesdayTitle;\n monthCalendarConfiguration.wednesdayTitle = wednesdayTitle;\n monthCalendarConfiguration.thursdayTitle = thursdayTitle;\n monthCalendarConfiguration.fridayTitle = fridayTitle;\n monthCalendarConfiguration.saturdayTitle = saturdayTitle;\n monthCalendarConfiguration.sundayTitle = sundayTitle;\n }\n\n if (periodType != Calendar.MONTH && periodType != Calendar.YEAR)\n throw new IllegalArgumentException(\"Period type should be Calendar.MONTH or Calendar.YEAR only.\");\n if (periodValue < 1)\n throw new IllegalArgumentException(\"Period value should be more then 1.\");\n if (periodType == Calendar.MONTH && periodValue < 3)\n throw new IllegalStateException(\"In case with Calendar.MONTH period type, minimum value should be GE 3.\");\n\n monthCalendarConfiguration.periodType = periodType;\n monthCalendarConfiguration.periodValue = periodValue;\n\n return monthCalendarConfiguration;\n }\n }\n\n public int getFirstDayOfWeek() {\n return firstDayOfWeek;\n }\n\n public int getMonthLayoutId() {\n return monthLayoutId;\n }\n\n public MonthDayDecoratorFactory getMonthDayDecoratorFactory() {\n return monthDayDecoratorFactory;\n }\n\n public int getWeekTitleLayoutId() {\n return weekTitleLayoutId;\n }\n\n public WeekDayDecorator getWeekDayDecorator() {\n return weekDayDecorator;\n }\n\n public boolean isDisplayDaysOutOfMonth() {\n return displayDaysOutOfMonth;\n }\n\n public EventsProcessor>> getEventsProcessor() {\n return eventsProcessor;\n }\n}\ncadar/src/main/java/io/github/memfis19/cadar/internal/ui/month/MonthCalendarHelper.java\npublic final class MonthCalendarHelper {\n\n private final static Calendar today = DateUtils.getCalendarInstance();\n private static Calendar selectedDay = today;\n\n private MonthCalendarHelper() {\n\n }\n\n public static Calendar getToday() {\n return today;\n }\n\n public static Calendar getSelectedDay() {\n return selectedDay;\n }\n\n public static void updateSelectedDay(Calendar selectedDay) {\n MonthCalendarHelper.selectedDay = selectedDay;\n }\n\n}\ncadar/src/main/java/io/github/memfis19/cadar/data/entity/Event.java\npublic interface Event extends Serializable {\n\n Long getEventId();\n\n String getEventTitle();\n\n String getEventDescription();\n\n Date getOriginalEventStartDate();\n\n Date getEventStartDate();\n\n Date getEventEndDate();\n\n /***\n * Sets the new start date for new generating event.\n *\n * @param startEventDate\n */\n void setEventStartDate(Date startEventDate);\n\n /***\n * Sets the new end date for new generating event.\n *\n * @param endEventDate\n */\n void setEventEndDate(Date endEventDate);\n\n /***\n * Sets calendarId field generated with system calendar after sync it\n *\n * @param calendarId\n * @see SyncUtils\n */\n void setCalendarId(Long calendarId);\n\n /***\n * Return calendarId field generated with system calendar after sync it\n *\n * @return\n * @see SyncUtils\n */\n Long getCalendarId();\n\n /***\n * @return repeat period for current entity instance\n * @see EventProperties.RepeatPeriod\n */\n @EventProperties.RepeatPeriod\n int getEventRepeatPeriod();\n\n /***\n * @return event icon url\n */\n String getEventIconUrl();\n\n /***\n * @return boolean which indicates is event editable\n */\n Boolean isEditable();\n\n /***\n * @return boolean which indicates is event length All day long\n */\n Boolean isAllDayEvent();\n}\ncadar/src/main/java/io/github/memfis19/cadar/event/OnMonthChangeListener.java\npublic interface OnMonthChangeListener {\n void onMonthChanged(Calendar calendar);\n}\ncadar/src/main/java/io/github/memfis19/cadar/internal/ui/month/adapter/MonthAdapter.java\npublic class MonthAdapter extends PagerAdapter implements OnDayChangeListener,\n EventsProcessorCallback>>, MonthHandlerThread.AdapterPrepareListener {\n\n private static final String TAG = \"MonthAdapter\";\n\n private static int CAPACITY = 11;\n private static int CAPACITY_STEP = 11;\n\n private Context context;\n private LayoutInflater inflater;\n private MonthCalendarConfiguration monthCalendarConfiguration;\n\n private MonthHandlerThread monthHandlerThread;\n private Handler backgroundHandler;\n private Handler uiHandler;\n\n private Set events = new HashSet<>();\n private List eventList = new ArrayList<>();\n\n private EventsProcessor>> eventsAsyncProcessor;\n private OnDayChangeListener onDateChangeListener;\n private DisplayEventCallback callback;\n private MonthGridCallback monthGridCallback;\n\n public interface MonthGridCallback {\n void onMonthGridReady(Calendar month);\n }\n\n @LayoutRes\n private int monthDayLayoutId;\n private MonthDayDecoratorFactory monthDayDecoratorFactory;\n\n private List monthFragments = new ArrayList<>();\n\n private Calendar initialDate = DateUtils.getCalendarInstance();\n\n private static int INITIAL_POSITION = 0;\n\n public MonthAdapter(Context context,\n MonthHandlerThread monthHandlerThread,\n EventsProcessor>> eventsAsyncProcessor,\n MonthCalendarConfiguration monthCalendarConfiguration) {\n\n this(context, eventsAsyncProcessor, monthCalendarConfiguration.getMonthLayoutId(), monthCalendarConfiguration.getMonthDayDecoratorFactory());\n\n this.monthCalendarConfiguration = monthCalendarConfiguration;\n\n Calendar calendar = DateUtils.getCalendarInstance();\n calendar = DateUtils.setTimeToMidnight(calendar);\n\n Calendar startPeriod = DateUtils.setTimeToMonthStart((Calendar) calendar.clone());\n startPeriod.set(monthCalendarConfiguration.getPeriodType(), calendar.get(monthCalendarConfiguration.getPeriodType()) - monthCalendarConfiguration.getPeriodValue());\n\n Calendar endPeriod = DateUtils.setTimeToMonthStart((Calendar) calendar.clone());\n endPeriod.set(monthCalendarConfiguration.getPeriodType(), calendar.get(monthCalendarConfiguration.getPeriodType()) + monthCalendarConfiguration.getPeriodValue());\n\n CAPACITY = DateUtils.monthBetweenPure(startPeriod.getTime(), endPeriod.getTime());\n CAPACITY_STEP = CAPACITY;\n\n this.initialDate = monthCalendarConfiguration.getInitialDay();\n this.monthHandlerThread = monthHandlerThread;\n this.monthHandlerThread.setAdapterPrepareListener(this);\n\n backgroundHandler = new Handler(monthHandlerThread.getLooper());\n uiHandler = new Handler(Looper.getMainLooper());\n }\n\n MonthAdapter(Context context,\n EventsProcessor>> eventsAsyncProcessor,\n @LayoutRes int monthDayLayoutId,\n MonthDayDecoratorFactory monthDayDecoratorFactory) {\n this.context = context;\n inflater = LayoutInflater.from(context);\n\n this.eventsAsyncProcessor = eventsAsyncProcessor;\n this.monthDayLayoutId = monthDayLayoutId;\n this.monthDayDecoratorFactory = monthDayDecoratorFactory;\n\n this.eventsAsyncProcessor.setEventsProcessorCallback(this);\n }\n\n public void setMonthGridCallback(MonthGridCallback monthGridCallback) {\n this.monthGridCallback = monthGridCallback;\n }\n\n public void setOnDateChangeListener(OnDayChangeListener onDateChangeListener) {\n this.onDateChangeListener = onDateChangeListener;\n }\n\n public static int getInitialPosition(Calendar initialDate) {\n if (INITIAL_POSITION == 0) {\n INITIAL_POSITION = CAPACITY / 2 + 1;\n }\n return INITIAL_POSITION;\n }\n\n public Calendar getDayForPosition(int position) {\n Calendar month = (Calendar) initialDate.clone();\n int shiftValue = position - getInitialPosition(initialDate);\n month.add(Calendar.MONTH, shiftValue);\n return month;\n }\n\n @Override\n public int getItemPosition(Object object) {\n return getInitialPosition(initialDate) + (Integer) ((RecyclerView) object).getTag();\n// return getDayPosition(((MonthGridAdapter) ((RecyclerView) object).getAdapter()).getMonth());\n }\n\n @Override\n public int getCount() {\n return CAPACITY;\n }\n\n @Override\n public boolean isViewFromObject(View view, Object object) {\n return view.equals(object);\n }\n\n @Override\n public Object instantiateItem(ViewGroup collection, int position) {\n RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.month_grid_layout, collection, false);\n monthFragments.add(recyclerView);\n\n int shiftValue = position - getInitialPosition(initialDate);\n\n recyclerView.setTag(shiftValue);\n monthHandlerThread.queuePreparation(initialDate, shiftValue, recyclerView);\n\n collection.addView(recyclerView);\n return recyclerView;\n }\n\n public int getCountOfInstantiateItems() {\n return monthFragments.size();\n }\n\n @Override\n public void destroyItem(ViewGroup collection, int position, Object view) {\n monthFragments.remove(view);\n\n collection.removeView((View) view);\n }\n\n public void refresh() {\n this.callback = null;\n displayEvents();\n }\n\n public void displayEvents(List eventList, DisplayEventCallback callback) {\n events.clear();\n events.addAll(eventList);\n\n this.eventList.clear();\n this.eventList.addAll(events);\n\n this.callback = callback;\n\n eventsAsyncProcessor.setEvents(this.eventList);\n displayEvents();\n }\n\n public void addEvents(List eventList) {\n events.addAll(eventList);\n\n this.eventList.clear();\n this.eventList.addAll(events);\n\n eventsAsyncProcessor.setEvents(this.eventList);\n displayEvents();\n }\n\n public void displayEvents() {\n for (RecyclerView recyclerView : monthFragments) {\n if (recyclerView.getAdapter() != null)\n ((MonthGridAdapter) recyclerView.getAdapter()).requestMonthEvents();\n }\n }\n\n public void notifyDayWasSelected() {\n for (RecyclerView recyclerView : monthFragments) {\n if (recyclerView.getAdapter() != null)\n ((MonthGridAdapter) recyclerView.getAdapter()).notifyMonthSetChanged();\n }\n }\n\n public int getDayPosition(Calendar day) {\n int shiftValue = DateUtils.monthBetweenPure(initialDate.getTime(), day.getTime());\n return getInitialPosition(initialDate) + shiftValue;\n }\n\n @Override\n public void onDayChanged(Calendar calendar) {\n notifyDayWasSelected();\n\n if (onDateChangeListener != null) onDateChangeListener.onDayChanged(calendar);\n }\n\n @Override\n public void onEventsProcessed(Calendar calendar, SparseArray> calendarEvents) {\n for (RecyclerView recyclerView : monthFragments) {\n if (recyclerView.getAdapter() != null)\n if (((MonthGridAdapter) recyclerView.getAdapter()).getMonth().equals(calendar)) {\n ((MonthGridAdapter) recyclerView.getAdapter()).displayEventsForMonth(calendarEvents);\n if (callback != null) callback.onEventsDisplayed(calendar);\n }\n }\n }\n\n public final static int FORWARD = 1;\n public final static int BACKWARD = 2;\n\n public void increaseSize(int direction) {\n if (direction == FORWARD) {\n CAPACITY += CAPACITY_STEP;\n\n notifyDataSetChanged();\n } else if (direction == BACKWARD) {\n CAPACITY += CAPACITY_STEP;\n INITIAL_POSITION += CAPACITY_STEP;\n\n notifyDataSetChanged();\n }\n }\n\n @Override\n public void onReadyAdapter(Calendar month, List monthDays, RecyclerView recyclerView) {\n MonthGridAdapter monthGridAdapter = new MonthGridAdapter(month, monthDays, monthCalendarConfiguration.isDisplayDaysOutOfMonth());\n\n monthGridAdapter.setOnDateChangeListener(this);\n monthGridAdapter.setEventsAsyncProcessor(eventsAsyncProcessor);\n monthGridAdapter.setMonthDayLayoutId(monthDayLayoutId);\n monthGridAdapter.setMonthDayDecoratorFactory(monthDayDecoratorFactory);\n\n CalendarLayoutManager gridLayoutManager = new CalendarLayoutManager(context, 7);\n recyclerView.setLayoutManager(gridLayoutManager);\n recyclerView.setAdapter(monthGridAdapter);\n\n if (monthGridCallback != null) monthGridCallback.onMonthGridReady(month);\n// monthGridAdapter.requestDisplayEvents();\n }\n\n private class CalendarLayoutManager extends GridLayoutManager {\n\n\n public CalendarLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n }\n\n public CalendarLayoutManager(Context context, int spanCount) {\n super(context, spanCount);\n }\n\n public CalendarLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {\n super(context, spanCount, orientation, reverseLayout);\n }\n\n @Override\n public boolean supportsPredictiveItemAnimations() {\n return false;\n }\n\n /***\n * Workaround for know RV issue\n * @link https://code.google.com/p/android/issues/detail?id=77846#c10\n */\n @Override\n public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {\n try {\n super.onLayoutChildren(recycler, state);\n } catch (IndexOutOfBoundsException e) {\n Log.e(MonthAdapter.TAG, \"IndexOutOfBoundsException in RecyclerView happens\");\n }\n }\n }\n}\ncadar/src/main/java/io/github/memfis19/cadar/event/CalendarPrepareCallback.java\npublic interface CalendarPrepareCallback {\n void onCalendarReady(CalendarController calendar);\n}\ncadar/src/main/java/io/github/memfis19/cadar/internal/process/EventsProcessor.java\npublic abstract class EventsProcessor extends HandlerThread implements ScrollManager.OnScrollChanged {\n\n private static final String TAG = \"EventsProcessor\";\n\n private static final int MESSAGE_EVENTS_PROCESS = 126;\n\n private EventCalculator eventCalculator;\n private List eventList;\n private Queue> resultQueue = new CircularFifoQueue<>(3);\n\n private boolean shouldProcess;\n private boolean processAsync = false;\n private boolean hasQuit = false;\n\n private Handler requestHandler;\n private Handler responseHandler = new Handler(Looper.getMainLooper());\n\n private EventsProcessorCallback eventsProcessorCallback;\n\n private ScrollManager scrollManager;\n\n public EventsProcessor(boolean shouldProcess, EventCalculator eventProcessor, boolean processAsync) {\n super(String.valueOf(System.currentTimeMillis()), Process.THREAD_PRIORITY_BACKGROUND);\n\n this.shouldProcess = shouldProcess;\n this.eventCalculator = eventProcessor;\n this.processAsync = processAsync;\n }\n\n public void setScrollManager(ScrollManager scrollManager) {\n this.scrollManager = scrollManager;\n this.scrollManager.subscribeForScrollStateChanged(this);\n }\n\n protected EventCalculator getEventProcessor() {\n return eventCalculator;\n }\n\n protected List getEventList() {\n return eventList;\n }\n\n protected boolean isShouldProcess() {\n return shouldProcess;\n }\n\n public void setEventProcessor(EventCalculator eventProcessor) {\n this.eventCalculator = eventProcessor;\n }\n\n public void setEvents(List eventList) {\n this.eventList = eventList;\n this.eventCalculator.setEventsToProcess(eventList);\n }\n\n public void setEventsProcessorCallback(EventsProcessorCallback eventsProcessorCallback) {\n this.eventsProcessorCallback = eventsProcessorCallback;\n }\n\n public void queueEventsProcess(T target) {\n if (target == null) return;\n requestHandler.obtainMessage(MESSAGE_EVENTS_PROCESS, target).sendToTarget();\n }\n\n @Override\n protected void onLooperPrepared() {\n requestHandler = new Handler(Looper.myLooper()) {\n @Override\n public void handleMessage(Message message) {\n if (message.what == MESSAGE_EVENTS_PROCESS) {\n T target = (T) message.obj;\n handleRequest(target);\n }\n }\n };\n }\n\n @Override\n public boolean quit() {\n release();\n return super.quit();\n }\n\n @Override\n public boolean quitSafely() {\n release();\n return (Build.VERSION.SDK_INT > 17) ? super.quitSafely() : super.quit();\n }\n\n private void release() {\n hasQuit = true;\n resultQueue.clear();\n if (scrollManager != null) scrollManager.unSubscribeForScrollStateChanged(this);\n }\n\n private void handleRequest(final T target) {\n if (processAsync) processEventsAsync(target, eventsProcessorCallback);\n else deliverResult(target, processEvents(target));\n }\n\n protected E processEvents(final T target) {\n return null;\n }\n\n protected void processEventsAsync(final T target, EventsProcessorCallback eventsProcessorCallback) {\n }\n\n private void deliverResult(final T target, final E result) {\n if (scrollManager != null && scrollManager.getCurrentScrollState() == ScrollManager.SCROLL_STATE_IDLE) {\n responseHandler.post(new Runnable() {\n @Override\n public void run() {\n if (hasQuit) return;\n\n if (eventsProcessorCallback != null)\n eventsProcessorCallback.onEventsProcessed(target, result);\n\n }\n });\n } else {\n resultQueue.add(new Pair<>(target, result));\n }\n }\n\n @Override\n public void onScrollStateChanged(@ScrollManager.ScrollState int scrollState) {\n if (scrollState == ScrollManager.SCROLL_STATE_IDLE) {\n for (final Pair pair : resultQueue) {\n responseHandler.post(new Runnable() {\n @Override\n public void run() {\n if (hasQuit) return;\n\n if (eventsProcessorCallback != null)\n eventsProcessorCallback.onEventsProcessed(pair.first, pair.second);\n\n resultQueue.remove(pair);\n }\n });\n }\n }\n }\n\n}\ncadar/src/main/java/io/github/memfis19/cadar/event/OnDayChangeListener.java\npublic interface OnDayChangeListener {\n void onDayChanged(Calendar calendar);\n}\ncadar/src/main/java/io/github/memfis19/cadar/event/DisplayEventCallback.java\npublic interface DisplayEventCallback {\n void onEventsDisplayed(T period);\n}\n", "answers": [" private Calendar workingCalendar = DateUtils.getCalendarInstance();"], "length": 3589, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "c286e42687fa9ed99da88e7dc82b5e91f0424100688babf5"} {"input": "import org.junit.Rule;\nimport org.junit.Test;\nimport com.github.olivergondza.dumpling.DisposeRule;\nimport com.github.olivergondza.dumpling.Util;\nimport com.github.olivergondza.dumpling.TestThread;\nimport com.github.olivergondza.dumpling.factory.ThreadDumpFactory;\nimport com.github.olivergondza.dumpling.model.ProcessRuntime;\nimport com.github.olivergondza.dumpling.model.ProcessThread;\nimport com.github.olivergondza.dumpling.model.StackTrace;\nimport com.github.olivergondza.dumpling.model.ThreadStatus;\nimport com.github.olivergondza.dumpling.model.dump.ThreadDumpRuntime;\nimport static com.github.olivergondza.dumpling.model.ProcessThread.nameIs;\nimport static org.hamcrest.Matchers.equalTo;\nimport static org.hamcrest.Matchers.not;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.startsWith;\nimport java.io.ByteArrayInputStream;\n/*\n * The MIT License\n *\n * Copyright (c) 2015 Red Hat, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage com.github.olivergondza.dumpling.cli;\n\n\n\n\n\npublic class SourceTest extends AbstractCliTest {\n\n @Rule public DisposeRule disposer = new DisposeRule();\n\n @Test\n public void cliNoSuchFile() {\n run(\"deadlocks\", \"--in\", \"threaddump:/there_is_no_such_file\");\n assertThat(exitValue, equalTo(-1));\n assertThat(out.toString(), equalTo(\"\"));\n // Error message is platform specific\n assertThat(err.toString(), not(equalTo(\"\")));\n }\n\n @Test\n public void jmxRemoteConnectViaCli() throws Exception {\n TestThread.JMXProcess process = disposer.register(TestThread.runJmxObservableProcess(false));\n stdin(\"runtime.threads.where(nameIs('remotely-observed-thread'))\");\n run(\"groovy\", \"--in\", \"jmx:\" + process.JMX_CONNECTION);\n\n assertThat(err.toString(), equalTo(\"\"));\n // Reuse verification logic re-parsing the output as thread dump", "context": "core/src/main/java/com/github/olivergondza/dumpling/model/ProcessRuntime.java\npublic abstract class ProcessRuntime<\n RuntimeType extends ProcessRuntime,\n SetType extends ThreadSet,\n ThreadType extends ProcessThread\n> extends ModelObject {\n\n private final @Nonnull SetType threads;\n private final @Nonnull SetType emptySet;\n\n public ProcessRuntime(@Nonnull Set> builders) {\n this.threads = createThreads(builders);\n this.emptySet = createSet(Collections.emptySet());\n checkSanity();\n }\n\n private @Nonnull SetType createThreads(@Nonnull Set> builders) {\n Set threads = new LinkedHashSet(builders.size());\n for (ProcessThread.Builder builder: builders) {\n threads.add(createThread(builder));\n }\n\n int buildersSize = builders.size();\n int threadsSize = threads.size();\n if (buildersSize != threadsSize) throw new IllegalRuntimeStateException(\n \"%d builders produced %d threads\", buildersSize, threadsSize\n );\n\n return createSet(Collections.unmodifiableSet(threads));\n }\n\n private void checkSanity() {\n // At most one thread should own the monitor/synchronizer\n HashMap monitors = new HashMap();\n HashMap synchronizers = new HashMap();\n for (ThreadType t: threads) {\n for (ThreadLock lock: t.getAcquiredMonitors()) {\n ThreadType existing = monitors.put(lock, t);\n if (existing != null) {\n throw new IllegalRuntimeStateException(\n \"Multiple threads own the same monitor '%s':%n%s%n%nAND%n%n%s%n\",\n lock, existing, t\n );\n }\n }\n\n for (ThreadLock lock: t.getAcquiredSynchronizers()) {\n ThreadType existing = synchronizers.put(lock, t);\n if (existing != null) {\n throw new IllegalRuntimeStateException(\n \"Multiple threads own the same synchronizer '%s':%n%s%n%nAND%n%n%s%n\",\n lock, existing, t\n );\n }\n }\n }\n }\n\n protected abstract @Nonnull SetType createSet(@Nonnull Set threads);\n\n protected abstract @Nonnull ThreadType createThread(@Nonnull ProcessThread.Builder builder);\n\n /**\n * All threads in current runtime.\n */\n public @Nonnull SetType getThreads() {\n return threads;\n }\n\n public @Nonnull SetType getEmptyThreadSet() {\n return emptySet;\n }\n\n /**\n * Instantiate {@link ThreadSet} scoped to this runtime.\n */\n public @Nonnull SetType getThreadSet(@Nonnull Collection threads) {\n if (threads.isEmpty()) return emptySet;\n\n Set threadSet = threads instanceof Set\n ? (Set) threads\n : new LinkedHashSet(threads)\n ;\n return createSet(threadSet);\n }\n\n /**\n * Run query against all threads in the runtime.\n *\n * @see ThreadSet#query(SingleThreadSetQuery)\n */\n public > T query(SingleThreadSetQuery query) {\n return threads.query(query);\n }\n\n @Override\n public void toString(PrintStream stream, Mode mode) {\n threads.toString(stream, mode);\n }\n}\ntest-utils/src/main/java/com/github/olivergondza/dumpling/DisposeRule.java\npublic class DisposeRule implements TestRule {\n\n private final List discard = new ArrayList();\n\n public T register(final T thread) {\n if (thread == null) return thread;\n\n discard.add(new Disposable() {\n @Override @SuppressWarnings(\"deprecation\")\n public void dispose() throws Exception {\n thread.stop();\n }\n });\n return thread;\n }\n\n public T register(final T process) {\n if (process == null) return process;\n\n discard.add(new Disposable() {\n @Override\n public void dispose() throws Exception {\n process.destroy();\n process.waitFor();\n }\n });\n return process;\n }\n\n @Override\n public Statement apply(final Statement base, Description description) {\n return new Statement() {\n @Override\n public void evaluate() throws Throwable {\n try {\n base.evaluate();\n } finally {\n for (Disposable item: discard) {\n try {\n item.dispose();\n } catch (Exception ex) {\n ex.printStackTrace(System.err);\n }\n }\n }\n }\n };\n }\n\n private interface Disposable {\n void dispose() throws Exception;\n }\n}\ntest-utils/src/main/java/com/github/olivergondza/dumpling/Util.java\npublic class Util {\n\n public static final @Nonnull String NL = System.getProperty(\"line.separator\", \"\\n\");\n\n public static InputStream resource(Class testClass, String resource) {\n InputStream res = testClass.getResourceAsStream(testClass.getSimpleName() + \"/\" + resource);\n if (res == null) throw new AssertionError(\"Resource does not exist: \" + testClass.getSimpleName() + \"/\" + resource);\n return res;\n }\n\n public static InputStream resource(String resource) {\n if (!resource.startsWith(\"/\")) {\n resource = \"/\" + resource;\n }\n InputStream res = Util.class.getResourceAsStream(resource);\n if (res == null) throw new AssertionError(\"Resource does not exist: \" + resource);\n return res;\n }\n\n public static File asFile(InputStream is, File file) throws IOException {\n FileWriter fw = new FileWriter(file);\n try {\n byte[] buffer = new byte[1024];\n int length;\n while ((length = is.read(buffer)) != -1) {\n fw.append(new String(buffer, 0, length));\n }\n } finally {\n fw.close();\n }\n\n return file;\n }\n\n public static File asFile(InputStream is) {\n File file = null;\n try {\n file = File.createTempFile(\"dumpling\", \"streamFile\");\n file.deleteOnExit();\n return asFile(is, file);\n } catch (IOException ex) {\n if (file != null) {\n file.delete();\n }\n throw new AssertionError(ex);\n }\n }\n\n public static String asString(InputStream is) {\n StringBuilder sb = new StringBuilder();\n try {\n byte[] buffer = new byte[1024];\n int length;\n while ((length = is.read(buffer)) != -1) {\n sb.append(new String(buffer, 0, length));\n }\n return sb.toString();\n } catch (IOException ex) {\n throw new AssertionError(ex);\n }\n }\n\n public static void forwardStream(InputStream in, PrintStream out) throws IOException {\n byte[] buffer = new byte[1024];\n int len;\n while ((len = in.read(buffer)) != -1) {\n out.write(buffer, 0, len);\n }\n }\n\n public static void pause(int time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException ex) {\n }\n }\n\n public static String formatTrace(String... frames) {\n StringBuilder sb = new StringBuilder();\n for (String frame: frames) {\n sb.append('\\t').append(frame).append(NL);\n }\n\n return sb.toString();\n }\n\n public static String multiline(String... lines) {\n StringBuilder sb = new StringBuilder();\n for (String line: lines) {\n sb.append(line).append(NL);\n }\n\n return sb.toString();\n }\n\n public static int currentPid() {\n return Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().replaceAll(\"@.*\", \"\"));\n }\n\n public static T only(Iterable set) {\n Iterator it = set.iterator();\n T elem = it.next();\n if (elem == null || it.hasNext()) throw new AssertionError(\n \"One set element expected: \" + set\n );\n\n return elem;\n }\n\n public static String currentProcessOut(InputStream os) {\n final StringBuilder out = new StringBuilder();\n try {\n int length = os.available();\n byte[] buffer = new byte[length];\n int read = os.read(buffer, 0, length);\n if (read != -1) { // No out\n out.append(new String(buffer));\n }\n } catch (IOException ex) {\n throw new Error(ex);\n }\n\n return out.toString();\n }\n\n public static String fileContents(File file) throws IOException {\n Scanner scanner = null;\n try {\n scanner = new Scanner(file);\n return scanner.useDelimiter(\"\\\\A\").next();\n } catch (NoSuchElementException ex) {\n return \"\"; // empty\n } finally {\n if (scanner != null) scanner.close();\n }\n }\n\n public static Error processTerminatedPrematurely(Process process, int exit, String line) {\n AssertionError error = new AssertionError(\n String.format(\n \"Process under test '%s' probably terminated prematurely. Exit code: %d%nSTDOUT: %s%nSTDERR: %s\",\n line,\n exit,\n Util.asString(process.getInputStream()), // Process exited - we are ok to blocking read the outs.\n Util.asString(process.getErrorStream())\n )\n );\n return error;\n }\n\n public static ProcessBuilder processBuilder() {\n ProcessBuilder pb = new ProcessBuilder();\n try { // Inherit error out on JAVA 7 and above\n Class redirect = Class.forName(\"java.lang.ProcessBuilder$Redirect\");\n Object inherit = redirect.getDeclaredField(\"INHERIT\").get(null);\n ProcessBuilder.class.getMethod(\"redirectError\", redirect).invoke(pb, inherit);\n return pb;\n } catch (Throwable e) {\n System.err.println(\"Java 6 detected - unable to diagnose test process failures: \" + e.toString());\n }\n\n return pb;\n }\n}\ncore/src/main/java/com/github/olivergondza/dumpling/model/ProcessThread.java\npublic class ProcessThread<\n ThreadType extends ProcessThread,\n SetType extends ThreadSet,\n RuntimeType extends ProcessRuntime\n> extends ModelObject {\n\n private final @Nonnull RuntimeType runtime;\n private final @Nonnull Builder state;\n\n protected ProcessThread(@Nonnull RuntimeType runtime, @Nonnull Builder builder) {\n this.runtime = runtime;\n this.state = builder.clone();\n\n checkSanity();\n }\n\n private void checkSanity() {\n if (state.name == null || state.name.isEmpty()) throw new IllegalRuntimeStateException(\"Thread name not set\");\n if (state.status == null) throw new IllegalRuntimeStateException(\"Thread status not set\");\n\n if (state.id == null && state.tid == null && state.nid == null) {\n throw new IllegalRuntimeStateException(\"No thread identifier set\");\n }\n\n if (state.status.isBlocked() && state.waitingToLock == null) {\n throw new IllegalRuntimeStateException(\n \"Blocked thread does not declare monitor: >>>\\n%s\\n<<<\\n\", state\n );\n }\n }\n\n public @Nonnull RuntimeType getRuntime() {\n return runtime;\n }\n\n public @Nonnull String getName() {\n return state.name;\n }\n\n /**\n * Java thread id.\n *\n * @return null when not available in threaddump.\n */\n public @CheckForNull Long getId() {\n return state.id;\n }\n\n /**\n * Native thread id.\n *\n * @return null when not available in threaddump.\n */\n public @CheckForNull Long getNid() {\n return state.nid;\n }\n\n /**\n * @return null when not available in threaddump.\n */\n public @CheckForNull Long getTid() {\n return state.tid;\n }\n\n public @Nonnull ThreadStatus getStatus() {\n return state.status;\n }\n\n /**\n * {@link java.lang.Thread.State} of current thread.\n *\n * @return null if was not able to determine thread state.\n */\n public @CheckForNull Thread.State getState() {\n return state.status.getState();\n }\n\n public Integer getPriority() {\n return state.priority;\n }\n\n public boolean isDaemon() {\n return state.daemon;\n }\n\n public @Nonnull StackTrace getStackTrace() {\n return state.stackTrace;\n }\n\n /**\n * Monitor thread is waiting to be notified.\n *\n * @return null is the thread is not in {@link Object#wait()}.\n */\n public @CheckForNull ThreadLock getWaitingOnLock() {\n return state.waitingOnLock;\n }\n\n /**\n * Monitor thread is waiting to acquire.\n *\n * @return null then the thread is not BLOCKED acquiring the monitor.\n */\n public @CheckForNull ThreadLock getWaitingToLock() {\n return state.waitingToLock;\n }\n\n public @Nonnull Set getAcquiredLocks() {\n // Convert to Set not to expose duplicates\n LinkedHashSet locks = new LinkedHashSet(\n state.acquiredMonitors.size() + state.acquiredSynchronizers.size()\n );\n for (Monitor m: state.acquiredMonitors) {\n locks.add(m.getLock());\n }\n locks.addAll(state.acquiredSynchronizers);\n return locks;\n }\n\n public @Nonnull Set getAcquiredMonitors() {\n LinkedHashSet locks = new LinkedHashSet(state.acquiredMonitors.size());\n for (Monitor m: state.acquiredMonitors) {\n locks.add(m.getLock());\n }\n return locks;\n }\n\n public @Nonnull Set getAcquiredSynchronizers() {\n return new LinkedHashSet(state.acquiredSynchronizers);\n }\n\n /**\n * Get threads that are waiting for lock held by this thread.\n */\n public @Nonnull SetType getBlockedThreads() {\n Set acquiredMonitors = getAcquiredMonitors();\n\n Set blocked = new LinkedHashSet();\n for (ThreadType thread: runtime.getThreads()) {\n if (thread == this) continue;\n if (acquiredMonitors.contains(thread.getWaitingToLock()) || isParkingBlocking(this, thread)) {\n blocked.add(thread);\n assert thread.getBlockingThread() == this; // Verify consistency of back references\n } else {\n assert thread.getBlockingThread() != this; // Verify consistency of back references\n }\n }\n\n return runtime.getThreadSet(blocked);\n }\n\n /**\n * Some threads are blocked by other particular ones when parking, but not all parking threads are blocked by a\n * thread (we can identify). This naive implementation seems to work reasonably well. These notes might be of value:\n *\n * Not detectable:\n *\n * com.google.common.util.concurrent.AbstractFuture$Sync\n * java.util.concurrent.CountDownLatch$Sync\n * java.util.concurrent.FutureTask\n * java.util.concurrent.FutureTask$Sync\n * java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject\n * java.util.concurrent.Semaphore$NonfairSync\n * java.util.concurrent.SynchronousQueue$TransferStack (Idle ThreadPoolExecutor$Worker)\n *\n * Detectable in certain situations:\n *\n * java.util.concurrent.locks.ReentrantLock$NonfairSync\n * java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync (both write lock or write/read lock blockage)\n */\n // Cannot be a private instance method since ths and tht are statically distinct types javac fail to permit private access on - strange\n private static boolean isParkingBlocking(ProcessThread ths, ProcessThread tht) {\n return tht.getStatus().isParked() && ths.getAcquiredSynchronizers().contains(tht.getWaitingOnLock());\n }\n\n /**\n * Get threads holding lock this thread is trying to acquire.\n *\n * @return {@link ThreadSet} that contains blocked thread or empty set if this thread does not hold any lock.\n */\n public @Nonnull SetType getBlockingThreads() {\n final ThreadType blocking = getBlockingThread();\n if (blocking == null) return runtime.getEmptyThreadSet();\n\n return runtime.getThreadSet(Collections.singleton(blocking));\n }\n\n /**\n * Get thread blocking this threads execution.\n * @return Blocking thread or null if not block by a thread.\n */\n public @CheckForNull ThreadType getBlockingThread() {\n if (state.waitingToLock == null && state.waitingOnLock == null) {\n return null;\n }\n\n for (ThreadType thread: runtime.getThreads()) {\n if (thread == this) continue;\n Set acquired = thread.getAcquiredMonitors();\n if (acquired.contains(state.waitingToLock)) return thread;\n if (isParkingBlocking(thread, this)) return thread;\n }\n\n return null;\n }\n\n /**\n * @see #printHeader(PrintStream, Mode).\n */\n public @Nonnull String getHeader() {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n toString(new PrintStream(baos), Mode.HUMAN);\n return baos.toString();\n }\n\n /**\n * Appends thread header to stream.\n *\n * Subclasses are encouraged to only append to the existing output rather than modifying it.\n *\n * @param stream Output.\n * @param mode Output mode.\n */\n public void printHeader(PrintStream stream, Mode mode) {\n state.printHeader(stream, mode);\n }\n\n @Override\n public void toString(PrintStream stream, Mode mode) {\n state.toString(stream, mode);\n }\n\n @Override\n public boolean equals(Object rhs) {\n if (rhs == null) return false;\n if (!rhs.getClass().equals(this.getClass())) return false;\n\n ProcessThread other = (ProcessThread) rhs;\n\n if (state.tid == null ? other.state.tid != null : !state.tid.equals(other.state.tid)) return false;\n if (state.nid == null ? other.state.nid != null : !state.nid.equals(other.state.nid)) return false;\n if (state.id == null ? other.state.id != null : !state.id.equals(other.state.id)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n Long tid = state.tid;\n if (tid == null) tid = 0L;\n\n Long nid = state.nid;\n if (nid == null) nid = 0L;\n\n Long id = state.id;\n if (id == null) id = 0L;\n\n return new Long(7 + 31 * tid + 17 * nid + 11 * id).hashCode();\n }\n\n public static class Builder<\n BuilderType extends Builder\n > extends ModelObject implements Cloneable {\n\n private @Nonnull String name = \"\";\n private boolean daemon;\n // priority might not be present in threaddump\n private Integer priority;\n // https://gist.github.com/rednaxelafx/843622\n private Long id, nid, tid;\n private @Nonnull StackTrace stackTrace = new StackTrace();\n private @Nonnull ThreadStatus status = ThreadStatus.UNKNOWN;\n private @CheckForNull ThreadLock waitingToLock;\n private @CheckForNull ThreadLock waitingOnLock;\n private @Nonnull List acquiredMonitors = Collections.emptyList();\n private @Nonnull List acquiredSynchronizers = Collections.emptyList();\n\n @Override\n protected @Nonnull BuilderType clone() {\n try {\n return (BuilderType) super.clone();\n } catch (CloneNotSupportedException ex) {\n throw new AssertionError();\n }\n }\n\n public @Nonnull BuilderType setName(@Nonnull String name) {\n this.name = name;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setId(long id) {\n this.id = id;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setNid(long nid) {\n this.nid = nid;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setTid(long tid) {\n this.tid = tid;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setDaemon(boolean daemon) {\n this.daemon = daemon;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setPriority(Integer priority) {\n this.priority = priority;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setStacktrace(@Nonnull StackTraceElement... stackTrace) {\n this.stackTrace = new StackTrace(stackTrace);\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setStacktrace(@Nonnull StackTrace stackTrace) {\n this.stackTrace = stackTrace;\n return (BuilderType) this;\n }\n\n public @Nonnull StackTrace getStacktrace() {\n return stackTrace;\n }\n\n public @Nonnull BuilderType setThreadStatus(@Nonnull ThreadStatus status) {\n this.status = status;\n return (BuilderType) this;\n }\n\n public ThreadStatus getThreadStatus() {\n return status;\n }\n\n public @Nonnull BuilderType setWaitingOnLock(ThreadLock lock) {\n this.waitingOnLock = lock;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setWaitingToLock(ThreadLock lock) {\n this.waitingToLock = lock;\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setAcquiredSynchronizers(List synchronizers) {\n this.acquiredSynchronizers = Collections.unmodifiableList(synchronizers);\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setAcquiredSynchronizers(ThreadLock... synchronizers) {\n List data = new ArrayList(synchronizers.length);\n Collections.addAll(data, synchronizers);\n return setAcquiredSynchronizers(data);\n }\n\n public @Nonnull BuilderType setAcquiredMonitors(List monitors) {\n this.acquiredMonitors = Collections.unmodifiableList(monitors);\n return (BuilderType) this;\n }\n\n public @Nonnull BuilderType setAcquiredMonitors(ThreadLock.Monitor... monitors) {\n ArrayList data = new ArrayList(monitors.length);\n Collections.addAll(data, monitors);\n return setAcquiredMonitors(data);\n }\n\n public @Nonnull List getAcquiredMonitors() {\n return new ArrayList(acquiredMonitors);\n }\n\n private List getMonitorsByDepth(int depth) {\n List monitors = new ArrayList();\n\n for (Monitor monitor: acquiredMonitors) {\n if (monitor.getDepth() == depth) {\n monitors.add(monitor.getLock());\n }\n }\n\n return monitors;\n }\n\n @Override\n public void toString(@Nonnull PrintStream stream, @Nonnull Mode mode) {\n printHeader(stream, mode);\n stream.format(\"%n java.lang.Thread.State: %s\", status.getName());\n\n int depth = 0;\n for (StackTraceElement traceLine: stackTrace.getElements()) {\n printTraceElement(stream, traceLine);\n\n if (depth == 0) {\n if (waitingToLock != null) {\n stream.println();\n stream.append(\"\\t- \").append(waitingVerb()).append(' ');\n waitingToLock.toString(stream, mode);\n }\n if (waitingOnLock != null) {\n stream.println();\n stream.append(\"\\t- \").append(waitingVerb()).append(' ');\n waitingOnLock.toString(stream, mode);\n }\n }\n\n for (ThreadLock monitor: getMonitorsByDepth(depth)) {\n stream.println();\n stream.append(\"\\t- locked \");\n monitor.toString(stream, mode);\n }\n\n depth++;\n }\n\n if (!acquiredSynchronizers.isEmpty()) {\n stream.format(\"%n%n Locked ownable synchronizers:%n\");\n for (ThreadLock synchronizer: acquiredSynchronizers) {\n stream.append(\"\\t- \");\n synchronizer.toString(stream, mode);\n stream.println();\n }\n }\n }\n\n private String waitingVerb() {\n if (status.isParked()) return \"parking to wait for\";\n if (status.isWaiting()) return \"waiting on\";\n if (status.isBlocked()) return \"waiting to lock\";\n\n throw new AssertionError(status + \" thread can not declare a lock: \" + name);\n }\n\n // Stolen from StackTraceElement#toString() in Java 8 to prevent the new fields from Java 9+ to be printed\n // as they can not be parsed correctly at the moment. Note this affect JMX/JVM factory reparsing only - threaddump is fine\n private void printTraceElement(PrintStream stream, StackTraceElement traceLine) {\n String fileName = traceLine.getFileName();\n int lineNumber = traceLine.getLineNumber();\n String source = traceLine.isNativeMethod() ? \"(Native Method)\":\n (fileName != null && lineNumber >= 0 ?\n \"(\" + fileName + \":\" + lineNumber + \")\":\n (fileName != null ? \"(\" + fileName + \")\": \"(Unknown Source)\"));\n stream.format(\"%n\\tat %s.%s%s\", traceLine.getClassName(), traceLine.getMethodName(), source);\n }\n\n /**\n * Appends thread header to stream.\n *\n * Subclasses are encouraged to only append to the existing output rather than modifying it.\n *\n * @param stream Output.\n * @param mode Output mode.\n */\n protected void printHeader(PrintStream stream, Mode mode) {\n stream.append('\"').append(name).append('\"');\n if (id != null) stream.append(\" #\").append(id.toString());\n if (daemon) stream.append(\" daemon\");\n if (priority != null) stream.append(\" prio=\").append(priority.toString());\n\n if (tid != null) {\n String format = !mode.isHuman() ? \"0x%016x\": \"0x%x\";\n stream.append(\" tid=\").format(format, tid);\n }\n if (nid != null) {\n String format = mode.isHuman() ? \"%d\" : \"0x%x\";\n stream.append(\" nid=\").format(format, nid);\n }\n }\n }\n\n /**\n * {@link ProcessThread} predicate.\n *\n * @author ogondza\n * @see ThreadSet#where(ProcessThread.Predicate)\n */\n public interface Predicate {\n boolean isValid(@Nonnull ProcessThread thread);\n }\n\n /**\n * Match thread by name.\n */\n public static @Nonnull Predicate nameIs(final @Nonnull String name) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n return thread.getName().equals(name);\n }\n };\n }\n\n /**\n * Match thread its name contains pattern.\n */\n public static @Nonnull Predicate nameContains(final @Nonnull Pattern pattern) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n return pattern.matcher(thread.getName()).find();\n }\n };\n }\n\n /**\n * Match thread its name contains string.\n */\n public static @Nonnull Predicate nameContains(final @Nonnull String pattern) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n return thread.getName().contains(pattern);\n }\n };\n }\n\n /**\n * Match waiting thread waiting for given thread to be notified.\n */\n public static @Nonnull Predicate waitingOnLock(final @Nonnull String className) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n final ThreadLock lock = thread.getWaitingOnLock();\n return lock != null && lock.getClassName().equals(className);\n }\n };\n }\n\n /**\n * Match thread that is waiting on lock identified by className.\n */\n public static @Nonnull Predicate waitingToLock(final @Nonnull String className) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n final ThreadLock lock = thread.getWaitingToLock();\n return lock != null && lock.getClassName().equals(className);\n }\n };\n }\n\n /**\n * Match thread that has acquired lock identified by className.\n */\n public static @Nonnull Predicate acquiredLock(final @Nonnull String className) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n for (ThreadLock lock: thread.getAcquiredLocks()) {\n if (lock.getClassName().equals(className)) return true;\n }\n return false;\n }\n };\n }\n\n /**\n * Match thread its stacktrace contains frame that exactly matches pattern.\n *\n * @param pattern Fully qualified method name like \"com.github.olivergondza.dumpling.model.ProcessThread.evaluating\".\n */\n public static @Nonnull Predicate evaluating(final @Nonnull String pattern) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n for (StackTraceElement element : thread.getStackTrace().getElements()) {\n if ((element.getClassName() + \".\" + element.getMethodName()).equals(pattern)) return true;\n }\n return false;\n }\n };\n }\n}\ncore/src/main/java/com/github/olivergondza/dumpling/model/dump/ThreadDumpRuntime.java\npublic final class ThreadDumpRuntime extends ProcessRuntime {\n\n /**\n * Threaddump header, either empty or terminated wit blank line so it can be prepended to the ThreadSet.\n */\n private final @Nonnull List header;\n\n public ThreadDumpRuntime(@Nonnull Set builders, @Nonnull List header) {\n super(builders);\n this.header = new ArrayList(header);\n }\n\n @Override\n protected ThreadDumpThreadSet createSet(Set threads) {\n return new ThreadDumpThreadSet(this, threads);\n }\n\n @Override\n protected ThreadDumpThread createThread(Builder builder) {\n return new ThreadDumpThread(this, (ThreadDumpThread.Builder) builder);\n }\n\n @Override\n public void toString(PrintStream stream, Mode mode) {\n if (!header.isEmpty()) {\n for (String line: header) {\n stream.println(line);\n }\n stream.println();\n }\n\n super.toString(stream, mode);\n }\n}\ncore/src/main/java/com/github/olivergondza/dumpling/model/ThreadStatus.java\npublic enum ThreadStatus {\n NEW (\"NEW\", State.NEW),\n RUNNABLE (\"RUNNABLE\", State.RUNNABLE),\n SLEEPING (\"TIMED_WAITING (sleeping)\", State.TIMED_WAITING),\n\n /**\n * Thread in {@link Object#wait()}.\n *\n * @see java.lang.Thread.State#WAITING\n */\n IN_OBJECT_WAIT (\"WAITING (on object monitor)\", State.WAITING),\n\n /**\n * Thread in {@link Object#wait(long)}.\n *\n * @see java.lang.Thread.State#TIMED_WAITING\n */\n IN_OBJECT_WAIT_TIMED(\"TIMED_WAITING (on object monitor)\", State.TIMED_WAITING),\n\n /**\n * Thread in {@link LockSupport#park()}.\n *\n * @see java.lang.Thread.State#WAITING\n */\n PARKED (\"WAITING (parking)\", State.WAITING),\n\n /**\n * Thread in {@link LockSupport#parkNanos}.\n *\n * @see java.lang.Thread.State#TIMED_WAITING\n */\n PARKED_TIMED (\"TIMED_WAITING (parking)\", State.TIMED_WAITING),\n\n BLOCKED (\"BLOCKED (on object monitor)\", State.BLOCKED),\n TERMINATED (\"TERMINATED\", State.TERMINATED),\n\n /**\n * Runtime factory was not able to determine thread state.\n *\n * This can happen for service threads in threaddump.\n */\n UNKNOWN (\"UNKNOWN\", null);\n\n /**\n * Description used in thread dump.\n */\n private final @Nonnull String name;\n\n /**\n * Matching java.lang.Thread.State.\n */\n private final State state;\n\n ThreadStatus(@Nonnull String name, State state) {\n this.name = name;\n this.state = state;\n }\n\n public @Nonnull String getName() {\n return name;\n }\n\n public @CheckForNull State getState() {\n return state;\n }\n\n /**\n * Newly create thread\n *\n * @see java.lang.Thread.State#NEW\n */\n public boolean isNew() {\n return this == NEW;\n }\n\n /**\n * Thread that is runnable / running.\n *\n * @see java.lang.Thread.State#RUNNABLE\n */\n public boolean isRunnable() {\n return this == RUNNABLE;\n }\n\n /**\n * Thread in {@link Thread#sleep(long)} or {@link Thread#sleep(long, int)} waiting to be notified.\n *\n * @see java.lang.Thread.State#TIMED_WAITING\n */\n public boolean isSleeping() {\n return this == SLEEPING;\n }\n\n /**\n * Thread in {@link Object#wait()} or {@link Object#wait(long)}.\n *\n * @see java.lang.Thread.State#WAITING\n * @see java.lang.Thread.State#TIMED_WAITING\n */\n public boolean isWaiting() {\n return this == IN_OBJECT_WAIT || this == IN_OBJECT_WAIT_TIMED;\n }\n\n /**\n * Thread in {@link LockSupport#park()} or {@link LockSupport#parkNanos}.\n *\n * @see java.lang.Thread.State#WAITING\n * @see java.lang.Thread.State#TIMED_WAITING\n */\n public boolean isParked() {\n return this == PARKED || this == PARKED_TIMED;\n }\n\n /**\n * Thread (re-)entering a synchronization block.\n *\n * @see java.lang.Thread.State#BLOCKED\n */\n public boolean isBlocked() {\n return this == BLOCKED;\n }\n\n /**\n * Thread that terminated execution.\n *\n * @see java.lang.Thread.State#TERMINATED\n */\n public boolean isTerminated() {\n return this == TERMINATED;\n }\n\n public static @Nonnull ThreadStatus fromString(String title) {\n try {\n\n @SuppressWarnings(\"null\")\n final @Nonnull ThreadStatus value = Enum.valueOf(ThreadStatus.class, title);\n return value;\n } catch (IllegalArgumentException ex) {\n\n for (ThreadStatus value: values()) {\n if (value.getName().equals(title)) return value;\n }\n\n throw ex;\n }\n }\n\n public static @Nonnull ThreadStatus fromState(@Nonnull Thread.State state, @CheckForNull StackTraceElement head) {\n switch (state) {\n case NEW: return NEW;\n case RUNNABLE: return RUNNABLE;\n case BLOCKED: return BLOCKED;\n case WAITING: return waitingState(false, head); // Not exact\n case TIMED_WAITING: return waitingState(true, head); // Not exact\n case TERMINATED: return TERMINATED;\n default: return UNKNOWN;\n }\n }\n\n private static @Nonnull ThreadStatus waitingState(boolean timed, @CheckForNull StackTraceElement head) {\n if (head == null) return ThreadStatus.UNKNOWN;\n if (\"sleep\".equals(head.getMethodName()) && \"java.lang.Thread\".equals(head.getClassName())) return SLEEPING;\n if (\"wait\".equals(head.getMethodName()) && \"java.lang.Object\".equals(head.getClassName())) {\n return timed ? IN_OBJECT_WAIT_TIMED : IN_OBJECT_WAIT;\n }\n\n if (\"park\".equals(head.getMethodName()) && UNSAFE.contains(head.getClassName())) {\n return timed ? PARKED_TIMED : PARKED;\n }\n\n throw new AssertionError(\"Unable to infer ThreadStatus from WAITING state in \" + head);\n }\n\n public static final List UNSAFE = Arrays.asList(\n \"sun.misc.Unsafe\", // hotspot JDK 8 and older\n \"jdk.internal.misc.Unsafe\" // hotspot JDK 9\n );\n}\ncore/src/main/java/com/github/olivergondza/dumpling/model/StackTrace.java\npublic class StackTrace extends ModelObject {\n\n public static StackTraceElement element(String declaringClass, String methodName, String fileName, int lineNumber) {\n return new StackTraceElement(declaringClass, methodName, fileName, lineNumber);\n }\n\n /**\n * Get {@link StackTraceElement} its source line number is unknown.\n */\n public static StackTraceElement element(String declaringClass, String methodName, String fileName) {\n return new StackTraceElement(declaringClass, methodName, fileName, -1);\n }\n\n /**\n * Get {@link StackTraceElement} its source (file name and line number) is unknown.\n */\n public static StackTraceElement element(String declaringClass, String methodName) {\n return new StackTraceElement(declaringClass, methodName, null, -1);\n }\n\n /**\n * Get {@link StackTraceElement} for native method.\n */\n public static StackTraceElement nativeElement(String declaringClass, String methodName) {\n return new StackTraceElement(declaringClass, methodName, null, -2);\n }\n\n /**\n * Get {@link StackTraceElement} for native method.\n *\n * Some native method {@link StackTraceElement}s have filename, even though it is not shown.\n */\n public static StackTraceElement nativeElement(String declaringClass, String methodName, String fileName) {\n return new StackTraceElement(declaringClass, methodName, fileName, -2);\n }\n\n private @Nonnull StackTraceElement[] elements;\n\n public StackTrace(@Nonnull StackTraceElement... elements) {\n this.elements = elements.clone(); // Shallow copy is ok here as StackTraceElement is immutable\n }\n\n public StackTrace(@Nonnull List elements) {\n this.elements = elements.toArray(new StackTraceElement[elements.size()]);\n }\n\n public int size() {\n return elements.length;\n }\n\n /**\n * Get element of given stack depth.\n *\n * @return Stack element of null if not present.\n */\n public @CheckForNull StackTraceElement getElement(@Nonnegative int depth) {\n if (depth < 0) throw new ArrayIndexOutOfBoundsException(depth);\n\n return elements.length > depth\n ? elements[depth]\n : null\n ;\n }\n\n /**\n * Get innermost stack frame or null when there is no trace attached.\n */\n public @CheckForNull StackTraceElement getHead() {\n return getElement(0);\n }\n\n public @CheckForNull StackTraceElement head() {\n return getElement(0);\n }\n\n /**\n * Get all the stack trace elements.\n */\n public @Nonnull List getElements() {\n return Arrays.asList(elements);\n }\n\n @Override\n public void toString(PrintStream stream, Mode mode) {\n for (StackTraceElement e: elements) {\n stream.println();\n stream.append(\"\\tat \").append(e.toString());\n }\n\n stream.println();\n }\n\n @Override\n public int hashCode() {\n return 31 * Arrays.hashCode(elements);\n }\n\n @Override\n public boolean equals(Object rhs) {\n if (this == rhs) return true;\n if (rhs == null) return false;\n if (getClass() != rhs.getClass()) return false;\n\n StackTrace other = (StackTrace) rhs;\n if (!Arrays.equals(elements, other.elements)) return false;\n return true;\n }\n}\ntest-utils/src/main/java/com/github/olivergondza/dumpling/TestThread.java\npublic final class TestThread {\n\n public static final @Nonnull String JMX_HOST = \"localhost\";\n public static final @Nonnull String JMX_USER = \"user\";\n public static final @Nonnull String JMX_PASSWD = \"secret_passwd\";\n\n public static final String MARKER = \"DUMPLING-SUT-IS-READY\";\n\n // Observable process entry point - not to be invoked directly\n public static synchronized void main(String... args) throws InterruptedException {\n runThread();\n\n System.out.println(MARKER);\n\n // Block process forever\n TestThread.class.wait();\n throw new Error(\"Should never get here\");\n }\n\n public static Thread runThread() {\n final CountDownLatch cdl = new CountDownLatch(1);\n Thread thread = new Thread(\"remotely-observed-thread\") {\n @Override\n public synchronized void run() {\n try {\n cdl.countDown();\n this.wait();\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }\n }\n };\n thread.setDaemon(true);\n thread.setPriority(7);\n thread.start();\n\n try {\n cdl.await();\n } catch (InterruptedException ex) {\n throw new AssertionError(ex);\n }\n\n return thread;\n }\n\n public static Thread setupSleepingThreadWithLock() {\n final ReentrantLock lock = new ReentrantLock();\n Thread thread = new Thread(\"sleepingThreadWithLock\") {\n @Override\n public void run() {\n lock.lock();\n pause(10000);\n }\n };\n thread.start();\n while(!lock.isLocked()) {\n pause(1000);\n }\n return thread;\n }\n\n private static int getFreePort() throws IOException {\n ServerSocket serverSocket = new ServerSocket(0);\n try {\n return serverSocket.getLocalPort();\n } finally {\n serverSocket.close();\n }\n }\n\n /* Client is expected to dispose the thread */\n public static JMXProcess runJmxObservableProcess(boolean auth) throws Exception {\n int jmxPort = getFreePort();\n\n String //cp = \"target/test-classes:target/classes\"; // Current module\n // Use file to convert URI to a path platform FS would understand,\n cp = new File(TestThread.class.getProtectionDomain().getCodeSource().getLocation().toURI().getSchemeSpecificPart()).getAbsolutePath();\n List args = new ArrayList();\n args.add(\"java\");\n args.add(\"-cp\");\n args.add(cp);\n args.add(\"-Djava.util.logging.config.file=\" + Util.asFile(Util.resource(TestThread.class, \"logging.properties\")).getAbsolutePath());\n args.add(\"-Dcom.sun.management.jmxremote\");\n args.add(\"-Dcom.sun.management.jmxremote.port=\" + jmxPort);\n args.add(\"-Dcom.sun.management.jmxremote.local.only=false\");\n args.add(\"-Dcom.sun.management.jmxremote.authenticate=\" + auth);\n args.add(\"-Dcom.sun.management.jmxremote.ssl=false\");\n args.add(\"-Djava.rmi.server.hostname=127.0.0.1\");\n if (auth) {\n args.add(\"-Dcom.sun.management.jmxremote.password.file=\" + getCredFile(\"jmxremote.password\"));\n args.add(\"-Dcom.sun.management.jmxremote.access.file=\" + getCredFile(\"jmxremote.access\"));\n }\n args.add(\"com.github.olivergondza.dumpling.TestThread\");\n ProcessBuilder pb = processBuilder().command(args);\n String processLine = pb.command().toString();\n final Process process = pb.start();\n\n BufferedInputStream bis = new BufferedInputStream(process.getInputStream());\n bis.mark(1024 * 1024 * 1);\n String out = \"never_tried\";\n for (int i = 0; i < 10; i++) {\n out = isUp(bis);\n if (out != null) return new JMXProcess(process, jmxPort);\n\n try {\n int exit = process.exitValue();\n throw processTerminatedPrematurely(process, exit, processLine);\n } catch (IllegalThreadStateException ex) {\n // Still running\n }\n\n Thread.sleep(500);\n }\n\n throw new AssertionError(\"Unable to bring to SUT up in time: \" + out);\n }\n\n public static final class JMXProcess extends Process {\n\n private final Process p;\n public final int JMX_PORT;\n public final @Nonnull String JMX_CONNECTION;\n public final @Nonnull String JMX_AUTH_CONNECTION;\n\n public JMXProcess(Process p, int port) {\n this.p = p;\n JMX_PORT = port;\n JMX_CONNECTION = JMX_HOST + \":\" + JMX_PORT;\n JMX_AUTH_CONNECTION = JMX_USER + \":\" + JMX_PASSWD + \"@\" + JMX_CONNECTION;\n }\n\n @Override public OutputStream getOutputStream() {\n return p.getOutputStream();\n }\n\n @Override public InputStream getInputStream() {\n return p.getInputStream();\n }\n\n @Override public InputStream getErrorStream() {\n return p.getErrorStream();\n }\n\n @Override public int waitFor() throws InterruptedException {\n return p.waitFor();\n }\n\n @Override public int exitValue() {\n return p.exitValue();\n }\n\n @Override public void destroy() {\n p.destroy();\n }\n\n public Process getNativeProcess() {\n return p;\n }\n\n // Copy&paste from PidRuntimeFactory\n public long pid() {\n Throwable problem = null;\n try {\n Method pidMethod = Process.class.getMethod(\"pid\");\n return (long) (Long) pidMethod.invoke(p);\n } catch (NoSuchMethodException e) {\n // Not Java 9 - Fallback\n } catch (IllegalAccessException e) {\n throw new AssertionError(e);\n } catch (InvocationTargetException e) {\n Throwable cause = e.getCause();\n if (cause instanceof UnsupportedOperationException) {\n // Process impl might not support management - Fallback\n problem = cause;\n } else if (cause instanceof SecurityException) {\n // Access to monitoring is rejected - Fallback\n problem = cause;\n } else {\n throw new AssertionError(e);\n }\n }\n\n // Fallback for Java6+ on unix. This is known not to work for Java8 on Windows.\n if (!\"java.lang.UNIXProcess\".equals(p.getClass().getName())) throw new UnsupportedOperationException(\n \"Unknown java.lang.Process implementation: \" + p.getClass().getName(),\n problem\n );\n\n try {\n // Protected class\n Class clazz = Class.forName(\"java.lang.UNIXProcess\");\n Field pidField = clazz.getDeclaredField(\"pid\");\n pidField.setAccessible(true);\n return pidField.getLong(p);\n } catch (ClassNotFoundException e) {\n throw new UnsupportedOperationException(\"Unable to find java.lang.UNIXProcess\", e);\n } catch (NoSuchFieldException e) {\n throw new UnsupportedOperationException(\"Unable to find java.lang.UNIXProcess.pid\", e);\n } catch (IllegalAccessException e) {\n throw new UnsupportedOperationException(\"Unable to access java.lang.UNIXProcess.pid\", e);\n }\n }\n }\n\n private static String isUp(BufferedInputStream is) throws IOException {\n is.reset();\n byte[] buffer = new byte[1024];\n int length;\n while ((length = is.read(buffer)) != -1) {\n String line = new String(buffer, 0, length);\n if (line.contains(MARKER)) return line;\n }\n\n return null;\n }\n\n private static String getCredFile(String path) throws Exception {\n String file = Util.asFile(Util.resource(TestThread.class, path)).getAbsolutePath();\n // Workaround http://jira.codehaus.org/browse/MRESOURCES-132\n Process process = new ProcessBuilder(\"chmod\", \"600\", file).start();\n if (process.waitFor() != 0) {\n throw new RuntimeException(\n \"Failed to adjust permissions: \" + Util.asString(process.getErrorStream())\n );\n }\n return file;\n }\n}\ncore/src/main/java/com/github/olivergondza/dumpling/factory/ThreadDumpFactory.java\npublic class ThreadDumpFactory {\n\n private static final Logger LOG = Logger.getLogger(ThreadDumpFactory.class.getName());\n\n private static final StackTraceElement WAIT_TRACE_ELEMENT = StackTrace.nativeElement(\"java.lang.Object\", \"wait\");\n\n private static final String NL = \"(?:\\\\r\\\\n|\\\\n)\";\n private static final String LOCK_SUBPATTERN = \"<(?:0x)?(\\\\w+)> \\\\(a ([^\\\\)]+)\\\\)\";\n\n private static final Pattern THREAD_DELIMITER = Pattern.compile(NL + \"(?:\" + NL + \"(?!\\\\s)|(?=\\\"))\");\n // TODO the regex is ignoring module name and version at the time: java.lang.Thread.sleep(java.base@9-ea/Native Method)\n private static final Pattern STACK_TRACE_ELEMENT_LINE = Pattern.compile(\" *at (\\\\S+)\\\\.(\\\\S+)\\\\((?:.+/)?([^:]+?)(\\\\:\\\\d+)?\\\\)\");\n private static final Pattern ACQUIRED_LINE = Pattern.compile(\"- locked \" + LOCK_SUBPATTERN);\n // Oracle/OpenJdk puts unnecessary space after 'parking to wait for'\n private static final Pattern WAITING_ON_LINE = Pattern.compile(\"- (?:waiting on|parking to wait for ?) \" + LOCK_SUBPATTERN);\n private static final Pattern WAITING_TO_LOCK_LINE = Pattern.compile(\"- waiting to lock \" + LOCK_SUBPATTERN);\n private static final Pattern OWNABLE_SYNCHRONIZER_LINE = Pattern.compile(\"- \" + LOCK_SUBPATTERN);\n private static final Pattern THREAD_HEADER = Pattern.compile(\n \"^\\\"(.*)\\\" ([^\\\\n\\\\r]+)(?:\" + NL + \"\\\\s+java.lang.Thread.State: ([^\\\\n\\\\r]+)(?:\" + NL + \"(.+))?)?\",\n Pattern.DOTALL\n );\n\n private boolean failOnErrors = false;\n\n /**\n * Historically, dumpling tolerates some of the errors silently.\n *\n * Turning this on will replace log records for failures to parse the threaddump.\n */\n public ThreadDumpFactory failOnErrors(boolean failOnErrors) {\n this.failOnErrors = failOnErrors;\n return this;\n }\n\n /**\n * Create runtime from thread dump.\n *\n * @throws IOException File could not be loaded.\n */\n public @Nonnull ThreadDumpRuntime fromFile(@Nonnull File threadDump) throws IOException {\n FileInputStream fis = new FileInputStream(threadDump);\n try {\n return fromStream(fis);\n } finally {\n fis.close();\n }\n }\n\n public @Nonnull ThreadDumpRuntime fromStream(@Nonnull InputStream stream) {\n Set threads = new LinkedHashSet();\n List header = new ArrayList();\n\n Scanner scanner = new Scanner(stream);\n scanner.useDelimiter(THREAD_DELIMITER);\n try {\n while (scanner.hasNext()) {\n String singleChunk = scanner.next();\n // Java until 8 vs. Java after 9\n if (singleChunk.startsWith(\"JNI global references\") || singleChunk.startsWith(\"JNI global refs\")) {\n // Nothing interesting is expected after this point. Also, this is a convenient way to eliminate the\n // deadlock report that is spread over several chunks\n break;\n }\n\n ThreadDumpThread.Builder thread = thread(singleChunk);\n if (thread != null) {\n threads.add(thread);\n continue;\n }\n\n if (header.isEmpty()) { // Still reading header\n header.addAll(Arrays.asList(singleChunk.split(NL)));\n continue;\n }\n\n // New info in Java 9\n if (singleChunk.startsWith(\"Threads class SMR info:\")) {\n continue;\n }\n\n String msg = \"Skipping unrecognized chunk: >>>\" + singleChunk + \"<<<\";\n if (failOnErrors) {\n throw new IllegalRuntimeStateException(msg);\n } else {\n LOG.warning(msg);\n }\n }\n } finally {\n scanner.close();\n }\n\n if (threads.isEmpty()) throw new IllegalRuntimeStateException(\n \"No threads found in threaddump\"\n );\n\n return new ThreadDumpRuntime(threads, header);\n }\n\n public @Nonnull ThreadDumpRuntime fromString(@Nonnull String runtime) {\n try {\n InputStream is = new ByteArrayInputStream(runtime.getBytes(\"UTF-8\"));\n try {\n return fromStream(is);\n } finally {\n try {\n is.close();\n } catch (IOException ex) {} // Ignore\n }\n } catch (UnsupportedEncodingException ex) {\n throw new AssertionError(ex);\n }\n }\n\n private ThreadDumpThread.Builder thread(String singleThread) {\n\n Matcher matcher = THREAD_HEADER.matcher(singleThread);\n if (!matcher.find()) return null;\n\n ThreadDumpThread.Builder builder = new ThreadDumpThread.Builder();\n builder.setName(matcher.group(1));\n initHeader(builder, matcher.group(2));\n\n String status = matcher.group(3);\n if (status != null) {\n builder.setThreadStatus(ThreadStatus.fromString(status));\n }\n\n final String trace = matcher.group(4);\n if (trace != null) {\n builder = initStacktrace(builder, trace, singleThread);\n }\n\n return builder;\n }\n\n private Builder initStacktrace(Builder builder, String trace, String wholeThread) {\n ArrayList traceElements = new ArrayList();\n\n List monitors = new ArrayList();\n List synchronizers = new ArrayList();\n ThreadLock waitingToLock = null; // Block waiting on monitor\n ThreadLock waitingOnLock = null; // in Object.wait()\n int depth = -1;\n\n StringTokenizer tokenizer = new StringTokenizer(trace, \"\\n\");\n while (tokenizer.hasMoreTokens()) {\n String line = tokenizer.nextToken();\n\n StackTraceElement elem = traceElement(line);\n if (elem != null) {\n traceElements.add(elem);\n depth++;\n continue;\n }\n\n Matcher acquiredMatcher = ACQUIRED_LINE.matcher(line);\n if (acquiredMatcher.find()) {\n monitors.add(new ThreadLock.Monitor(createLock(acquiredMatcher), depth));\n continue;\n }\n\n Matcher waitingToMatcher = WAITING_TO_LOCK_LINE.matcher(line);\n if (waitingToMatcher.find()) {\n if (waitingToLock != null) throw new IllegalRuntimeStateException(\n \"Waiting to lock reported several times per single thread >>>%n%s%n<<<%n\", trace\n );\n waitingToLock = createLock(waitingToMatcher);\n continue;\n }\n\n Matcher waitingOnMatcher = WAITING_ON_LINE.matcher(line);\n if (waitingOnMatcher.find()) {\n if (waitingOnLock != null) throw new IllegalRuntimeStateException(\n \"Waiting on lock reported several times per single thread >>>%n%s%n<<<%n\", trace\n );\n waitingOnLock = createLock(waitingOnMatcher);\n continue;\n }\n\n if (line.contains(\"Locked ownable synchronizers:\")) {\n while (tokenizer.hasMoreTokens()) {\n line = tokenizer.nextToken();\n\n if (line.contains(\"- None\")) break;\n Matcher matcher = OWNABLE_SYNCHRONIZER_LINE.matcher(line);\n if (matcher.find()) {\n synchronizers.add(createLock(matcher));\n } else {\n throw new IllegalRuntimeStateException(\"Unable to parse ownable synchronizer: \" + line);\n }\n }\n }\n }\n\n builder.setStacktrace(new StackTrace(traceElements));\n\n ThreadStatus status = builder.getThreadStatus();\n StackTraceElement innerFrame = builder.getStacktrace().getElement(0);\n\n // Probably a bug in JVM/jstack but let's see what we can do\n if (waitingOnLock == null && !status.isRunnable() && WAIT_TRACE_ELEMENT.equals(innerFrame)) {\n HashSet acquiredLocks = new HashSet(monitors.size());\n for (Monitor m: monitors) {\n acquiredLocks.add(m.getLock());\n }\n if (acquiredLocks.size() == 1) {\n waitingOnLock = acquiredLocks.iterator().next();\n LOG.fine(\"FIXUP: Adjust lock state from 'locked' to 'waiting on' when thread entering Object.wait()\");\n LOG.fine(wholeThread);\n }\n }\n\n if (waitingOnLock != null) {\n // Eliminate self lock that is presented in threaddumps when in Object.wait(). It is a matter or convenience - not really a FIXUP\n filterMonitors(monitors, waitingOnLock);\n\n // 'waiting on' is reported even when blocked re-entering the monitor. Convert it from waitingOn to waitingTo\n if (builder.getThreadStatus().isBlocked()) {\n LOG.fine(\"FIXUP: Adjust lock state from 'waiting on' to 'waiting to' when thread re-acquiring the monitor after Object.wait()\");\n LOG.fine(wholeThread);\n waitingToLock = waitingOnLock;\n waitingOnLock = null;\n }\n }\n\n // https://github.com/olivergondza/dumpling/issues/43\n if (waitingOnLock != null && status.isRunnable()) {\n // Presumably when entering or leaving the parked state.\n // Remove the lock instead of fixing the thread status as there is\n // no general way to tell PARKED and PARKED_TIMED apart.\n LOG.fine(\"FIXUP: Remove 'waiting to' lock declared on RUNNABLE thread\");\n LOG.fine(wholeThread);\n waitingOnLock = null;\n }\n\n // https://github.com/olivergondza/dumpling/issues/46\n // The lock state is changed ahead of the thread state while there can be other threads still holding the monitor\n if (status.isBlocked() && waitingToLock == null) {\n Monitor monitor = getMonitorJustAcquired(monitors);\n if (monitor != null) {\n LOG.fine(\"FIXUP: Adjust lock state from 'locked' to 'waiting to' on BLOCKED thread\");\n LOG.fine(wholeThread);\n waitingToLock = monitor.getLock();\n monitors.remove(0);\n } else {\n LOG.fine(\"FIXUP: Adjust thread state from 'BLOCKED' to 'RUNNABLE' when monitor is missing\");\n LOG.fine(wholeThread);\n builder.setThreadStatus(status = ThreadStatus.RUNNABLE);\n }\n }\n\n if (waitingToLock != null && !status.isBlocked()) throw new IllegalRuntimeStateException(\n \"%s thread declares waitingTo lock: >>>%n%s%n<<<%n\", status, wholeThread\n );\n if (waitingOnLock != null && !status.isWaiting() && !status.isParked()) throw new IllegalRuntimeStateException(\n \"%s thread declares waitingOn lock: >>>%n%s%n<<<%n\", status, wholeThread\n );\n\n builder.setAcquiredMonitors(monitors);\n builder.setAcquiredSynchronizers(synchronizers);\n builder.setWaitingToLock(waitingToLock);\n builder.setWaitingOnLock(waitingOnLock);\n\n return builder;\n }\n\n // get monitor acquired on current stackframe, null when it was acquired earlier or not monitor is held\n private Monitor getMonitorJustAcquired(List monitors) {\n if (monitors.isEmpty()) return null;\n Monitor monitor = monitors.get(0);\n if (monitor.getDepth() != 0) return null;\n\n for (Monitor duplicateCandidate: monitors) {\n if (monitor.equals(duplicateCandidate)) continue; // skip first - equality includes monitor depth\n\n if (monitor.getLock().equals(duplicateCandidate.getLock())) return null; // Acquired earlier\n }\n\n return monitor;\n }\n\n private static final WeakHashMap traceElementCache = new WeakHashMap();\n private StackTraceElement traceElement(String line) {\n if (!line.startsWith(\"\\tat \") && !line.matches(\"( )+at .*\")) return null;\n\n StackTraceElement cached = traceElementCache.get(line);\n if (cached != null) return cached;\n\n Matcher match = STACK_TRACE_ELEMENT_LINE.matcher(line);\n if (!match.find()) return null;\n\n String sourceFile = match.group(3);\n int sourceLine = match.group(4) == null\n ? -1\n : Integer.parseInt(match.group(4).substring(1))\n ;\n\n if (sourceLine == -1 && \"Native Method\".equals(match.group(3))) {\n sourceFile = null;\n sourceLine = -2; // Magic value for native methods\n }\n\n StackTraceElement element = StackTrace.element(\n match.group(1), match.group(2), sourceFile, sourceLine\n );\n traceElementCache.put(line, element);\n return element;\n }\n\n private void filterMonitors(List monitors, ThreadLock lock) {\n for (Iterator it = monitors.iterator(); it.hasNext();) {\n Monitor m = it.next();\n\n if (m.getLock().equals(lock)) {\n it.remove();\n }\n }\n }\n\n private @Nonnull ThreadLock createLock(Matcher matcher) {\n return new ThreadLock(matcher.group(2), parseLong(matcher.group(1)));\n }\n\n private void initHeader(ThreadDumpThread.Builder builder, String attrs) {\n StringTokenizer tknzr = new StringTokenizer(attrs, \" \");\n while (tknzr.hasMoreTokens()) {\n String token = tknzr.nextToken();\n if (\"daemon\".equals(token)) builder.setDaemon(true);\n else if (token.startsWith(\"prio=\")) builder.setPriority(Integer.parseInt(token.substring(5)));\n else if (token.startsWith(\"tid=\")) builder.setTid(parseLong(token.substring(4)));\n else if (token.startsWith(\"nid=\")) builder.setNid(parseNid(token.substring(4)));\n else if (token.matches(\"#\\\\d+\")) builder.setId(Integer.parseInt(token.substring(1)));\n }\n }\n\n private long parseNid(String value) {\n return value.startsWith(\"0x\")\n ? parseLong(value.substring(2))\n : Long.parseLong(value) // Dumpling human readable output\n ;\n }\n\n /*package*/ static long parseLong(String value) {\n if (value.startsWith(\"0x\")) {\n // Oracle JDK on OS X do not use prefix for tid - so we need to be able to read both\n // https://github.com/olivergondza/dumpling/issues/59\n value = value.substring(2);\n }\n\n // Long.parseLong is faster but unsuitable in some cases: https://github.com/olivergondza/dumpling/issues/71\n return new BigInteger(value, 16).longValue();\n }\n}\ncore/src/main/java/com/github/olivergondza/dumpling/model/ProcessThread.java\npublic static @Nonnull Predicate nameIs(final @Nonnull String name) {\n return new Predicate() {\n @Override\n public boolean isValid(@Nonnull ProcessThread thread) {\n return thread.getName().equals(name);\n }\n };\n}\n", "answers": [" ThreadDumpRuntime reparsed = new ThreadDumpFactory().fromStream(new ByteArrayInputStream(out.toByteArray()));"], "length": 6160, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "62074387121c20e772ef8c7044ac3c627342a9b93b3c9f6b"} {"input": "package io.github.jokoframework.fragment;\nimport android.app.ActionBar;\nimport android.app.Activity;\nimport android.app.Fragment;\nimport android.content.SharedPreferences;\nimport android.content.res.Configuration;\nimport android.os.Bundle;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ExpandableListView;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport java.util.ArrayList;\nimport java.util.List;\nimport androidx.drawerlayout.widget.DrawerLayout;\nimport androidx.appcompat.app.ActionBarDrawerToggle;\nimport io.github.jokoframework.R;\nimport io.github.jokoframework.activity.AboutActivity;\nimport io.github.jokoframework.activity.BarChartActivity;\nimport io.github.jokoframework.activity.ChangePasswordActivity;\nimport io.github.jokoframework.activity.CountryActivity;\nimport io.github.jokoframework.activity.HorizontalBarChartActivity;\nimport io.github.jokoframework.activity.LineChartActivity;\nimport io.github.jokoframework.activity.LogOutActivity;\nimport io.github.jokoframework.activity.MultipleLineChartActivity;\nimport io.github.jokoframework.adapter.CustomExpandableListAdapter;\nimport io.github.jokoframework.mboehaolib.constants.Constants;\nimport io.github.jokoframework.mboehaolib.pojo.Event;\nimport io.github.jokoframework.mboehaolib.pojo.EventParent;\nimport io.github.jokoframework.mboehaolib.util.Utils;\nimport io.github.jokoframework.otp.OtpActivity;\n\n\n/**\n * Created by joaquin on 23/08/17.\n *\n * @author joaquin\n * @author afeltes\n */\n\npublic class NavigationDrawerFragment extends Fragment {\n\n private static final String EVENTS = \"events\";\n private static final String LOG_TAG = NavigationDrawerCallbacks.class.getSimpleName();\n\n private static final long MENU_ID_IMAGE1 = 1L;\n private static final long MENU_ID_IMAGE2 = 2L;\n private static final long MENU_ID_IMAGE3 = 3L;\n private static final long MENU_ID_IMAGE4 = 4L;\n private static final long MENU_ID_LOGOUT = 5L;\n private static final long MENU_ID_HELP = 6L;\n\n //OTP//\n private static final long MENU_ID_OTP = 7L;\n\n private static final long MENU_ID_CHANGEPASS = 8L;\n private static final long MENU_ID_COUNTRIES = 9L;\n\n /**\n * A pointer to the current callbacks instance (the Activity).\n */\n private NavigationDrawerCallbacks mCallbacks;\n\n /**\n * Helper component that ties the action bar to the navigation drawer.\n */\n private ActionBarDrawerToggle mDrawerToggle;\n private DrawerLayout mDrawerLayout;\n private ListView mDrawerListView;\n private View mFragmentContainerView;\n public View header;\n private boolean mFromSavedInstanceState;\n private boolean mUserLearnedDrawer;\n private List mEvents;\n private List mEventParents;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n // Read in the flag indicating whether or not the user has demonstrated awareness of the\n // drawer. See PREF_USER_LEARNED_DRAWER for details.\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());\n mUserLearnedDrawer = sp.getBoolean(Constants.PREF_USER_LEARNED_DRAWER, false);\n\n if (savedInstanceState != null) { // if activity existed before, then...\n mFromSavedInstanceState = true;\n mEvents = (List) savedInstanceState.getSerializable(EVENTS);\n }\n\n mEventParents = new ArrayList<>();\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n // Indicate that this fragment would like to influence the set of actions in the action bar.\n setHasOptionsMenu(true);\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer, container, false);\n header = getSideMenuHeader(inflater, container);\n mDrawerListView.addHeaderView(header);\n initializeEvents();\n addDrawerItems();\n return mDrawerListView;\n }\n\n private void addDrawerItems() {\n CustomExpandableListAdapter adapter = new CustomExpandableListAdapter(this.getActivity(), mEventParents);\n\n ExpandableListView mExpandableListView = mDrawerListView.findViewById(R.id.menuList);\n mExpandableListView.setAdapter(adapter);\n\n // Expandir todos los grupos por default...\n for (int i = 0; i < adapter.getGroupCount(); i++) {\n mExpandableListView.expandGroup(i);\n }\n\n mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {\n @Override\n public boolean onChildClick(ExpandableListView parent, View v,\n int groupPosition, int childPosition, long id) {\n // Se maneja el evento por hijo...\n selectGroupItem(groupPosition, childPosition);\n return false;\n }\n });\n\n mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {\n @Override\n public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long id) {\n int childrenCount = expandableListView.getExpandableListAdapter().getChildrenCount(groupPosition);\n // Solo es es un grupo sin hijos\n // va a tener una accion asociada\n if (childrenCount == 0) {\n selectGroupItem(groupPosition, null);\n }\n return false;\n }\n });\n }\n\n private View getSideMenuHeader(LayoutInflater inflater, ViewGroup container) {\n\n View header = inflater.inflate(R.layout.side_menu_header, container, false);\n //Implementa la cabecera del menu...\n TextView welcomeString = (TextView) header.findViewById(R.id.personalize_welcome);\n", "context": "app/src/main/java/io/github/jokoframework/activity/CountryActivity.java\npublic class CountryActivity extends Activity {\n\n private static final String LOG_TAG = \"COUNTRYACTIVITY\";\n\n public static List countryList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_country);\n\n final TableLayout tableLayout = findViewById(R.id.tableLayout);\n final MaterialButton button = findViewById(R.id.show_countries);\n\n findViewById(R.id.volver2).setOnClickListener(v -> {\n Intent backHome = new Intent(CountryActivity.this, HomeActivity.class);\n startActivity(backHome);\n finish();\n overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);\n });\n\n //Clearing old records from database\n //CountryDatabase.getAppDataBase(this).countryDao().deleteAll();\n\n // Show all country from database\n tableLayout.removeAllViews();\n\n if (countryList.size() == 0){\n View tableRow = LayoutInflater.from(CountryActivity.this).inflate(R.layout.table_item, null, false);\n TextView countryName = tableRow.findViewById(R.id.countryName);\n countryName.setText(\"Sin paises.\");\n tableLayout.addView(tableRow);\n } else {\n for (int i = 0; i < countryList.size(); i++) {\n View tableRow = LayoutInflater.from(CountryActivity.this).inflate(R.layout.table_item, null, false);\n TextView cID = tableRow.findViewById(R.id.cid);\n TextView countryName = tableRow.findViewById(R.id.countryName);\n TextView countryCode = tableRow.findViewById(R.id.countryCode);\n\n cID.setText(String.valueOf(countryList.get(i).getCid()));\n countryName.setText(countryList.get(i).getCountryName());\n countryCode.setText(countryList.get(i).getCountryCode());\n tableLayout.addView(tableRow);\n }\n }\n\n button.setOnClickListener(v -> {\n try {\n Intent mServiceIntent = new Intent(getBaseContext(), io.github.jokoframework.service.CountryHelper.class);\n getBaseContext().startService(mServiceIntent);\n Utils.showToast(getBaseContext(), \"Actualizando lista...\");\n } catch (RuntimeException e) {\n Utils.showToast(getBaseContext(), \"Fallo de CountryHelper\");\n Toast.makeText(getBaseContext(), getBaseContext().getString(R.string.no_network_connection), Toast.LENGTH_SHORT).show();\n Log.e(LOG_TAG, getBaseContext().getString(R.string.no_network_connection), e);\n }\n\n tableLayout.removeAllViews();\n\n if (countryList.size() == 0){\n View tableRow = LayoutInflater.from(CountryActivity.this).inflate(R.layout.table_item, null, false);\n TextView countryName = tableRow.findViewById(R.id.countryName);\n countryName.setText(\"Sin paises.\");\n tableLayout.addView(tableRow);\n } else {\n for (int i = 0; i < countryList.size(); i++) {\n View tableRow = LayoutInflater.from(CountryActivity.this).inflate(R.layout.table_item, null, false);\n TextView cID = tableRow.findViewById(R.id.cid);\n TextView countryName = tableRow.findViewById(R.id.countryName);\n TextView countryCode = tableRow.findViewById(R.id.countryCode);\n\n cID.setText(String.valueOf(countryList.get(i).getCid()));\n countryName.setText(countryList.get(i).getCountryName());\n countryCode.setText(countryList.get(i).getCountryCode());\n tableLayout.addView(tableRow);\n }\n }\n });\n }\n\n @Override\n protected void onDestroy() {\n CountryDatabase.destroyInstance();\n super.onDestroy();\n }\n}\nmboehaolib/src/main/java/io/github/jokoframework/mboehaolib/util/Utils.java\npublic class Utils {\n private static final String LOG_TAG = Utils.class.getName();\n\n private static Random random = new Random();\n\n private Utils() {\n Utils.random.setSeed(System.currentTimeMillis());\n }\n\n public static void throwToast(String msg, Context context) {\n Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);\n toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);\n toast.setDuration(Toast.LENGTH_SHORT);\n toast.show();\n }\n\n public static void showStickyMessage(Activity activity, String message, Style style) {\n showMessage(activity, message, style, Configuration.DURATION_INFINITE, Boolean.TRUE);\n }\n\n public static void showStickyMessage(Activity activity, String message) {\n showInfoMessage(activity, message, Configuration.DURATION_INFINITE, Boolean.TRUE);\n }\n\n public static void showMessage(Activity activity, String message, Style style, Integer duration, Boolean sticky) {\n final Configuration configuration = new Configuration.Builder()\n .setDuration(duration)\n .build();\n final Crouton crouton = Crouton.makeText(activity, message, style)\n .setConfiguration(configuration);\n if (sticky) {\n crouton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Crouton.hide(crouton);\n }\n });\n }\n crouton.show();\n }\n\n public static void showInfoMessage(final Activity activity, final String message,\n final Integer duration, final Boolean sticky) {\n if (activity != null) {\n activity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n final Configuration configuration = new Configuration.Builder()\n .setDuration(duration)\n .build();\n // Define custom styles for crouton\n Style style = new Style.Builder().build();\n // Display notice with custom style and configuration\n final Crouton crouton = Crouton.makeText(activity, message, style)\n .setConfiguration(configuration);\n if (sticky) {\n crouton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Crouton.hide(crouton);\n }\n });\n }\n crouton.show();\n }\n });\n }\n }\n\n public static boolean isValidPassword(String password) {\n return password.length() >= Constants.PASSWORD_MIN_LENGTH;\n }\n\n public static String getPrefs(Context context, String id) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n return prefs.getString(id, \"\");\n } else {\n Log.e(LOG_TAG, \"Se intentó guardar una preferencia con el context null. getPrefs)\");\n return \"\";\n }\n }\n\n public static Boolean getBooleanPrefs(Context context, String id) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n return prefs.getBoolean(id, false);\n } else {\n Log.e(LOG_TAG, \"Se intentó guardar una preferencia con el context null. getBooleanPrefs)\");\n return false;\n }\n }\n\n //BEGIN-IGNORE-SONARQUBE\n private static SharedPreferences getSharedPreferences(Context context) {\n // afeltes - 2017-01-23\n //Para revisar con más cuidado, no sabemos si antes del mboehaolib se usaba el \"id\" para algo\n return context.getSharedPreferences(\"SimplePref\", Context.MODE_MULTI_PROCESS);\n }\n //BEGIN-IGNORE-SONARQUBE\n\n public static boolean getBoolPrefs(Context context, String id) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n return prefs.getBoolean(id, false);\n } else {\n Log.e(LOG_TAG, \"Se intentó guardar una preferencia con el context null. getBoolPrefs)\");\n return false;\n }\n }\n\n public static int getIntPrefs(Context context, String id) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n return prefs.getInt(id, 0);\n } else {\n Log.e(LOG_TAG, \"Se intentó guardar una preferencia con el context null. getInt)\");\n return 0;\n }\n }\n\n public static long getLongPrefs(Context context, String id) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n long myLongValue = 0;\n return prefs.getLong(id, myLongValue);\n } else {\n Log.e(LOG_TAG, \"Se intentó guardar una preferencia con el context null. getLong)\");\n return 0L;\n }\n }\n\n public static void addPrefs(Context context, String id, String value) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putString(id, value);\n edit.commit();\n } else {\n Log.e(LOG_TAG, \"El Context que se desea utilizar es nulo. addPrefs(..String)\");\n }\n }\n\n public static void addPrefs(Context context, String id, Boolean value) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putBoolean(id, value);\n edit.commit();\n } else {\n Log.e(LOG_TAG, \"El Context que se desea utilizar es nulo. addPrefs(..Boolean)\");\n }\n }\n\n public static void addPrefs(Context context, String id, long value) {\n if (context != null) {\n SharedPreferences prefs = getSharedPreferences(context);\n SharedPreferences.Editor edit = prefs.edit();\n edit.putLong(id, value);\n edit.commit();\n } else {\n Log.e(LOG_TAG, \"Se intentó guardar una preferencia con el context null. addPrefs(... long)\");\n }\n }\n\n\n public static boolean isNetworkAvailable(Activity activity) {\n return isNetworkAvailable((Context) activity);\n }\n\n public static String getShareableImageName(String suffix) {\n return String.format(\"mboehao-linechart-%s-%s.png\", StringUtils.isBlank(suffix) ? \"test\" : suffix, Utils.getFormattedDate(new Date()));\n }\n\n public static String getFormattedDate(Date savedAt) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd-MM-yy\");\n return sdf.format(savedAt);\n }\n\n public static boolean isNetworkAvailable(Context context) {\n boolean isNetworkAvailable = false;\n if (context != null) {\n ConnectivityManager connectivityManager\n = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();\n isNetworkAvailable = activeNetworkInfo != null && activeNetworkInfo.isConnected();\n }\n return isNetworkAvailable;\n }\n\n public static boolean isParseSessionActive() {\n return false;\n }\n\n public static File getShareImagesFolder() {\n return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + \"/Mboehao/\");\n }\n\n public static void showToast(final Context context, final String message) {\n if (context != null) {\n Handler handler = new Handler(Looper.getMainLooper());\n handler.post(new Runnable() {\n @Override\n public void run() {\n Toast.makeText(context, message, Toast.LENGTH_SHORT).show();\n }\n });\n }\n }\n\n public static void sleep(long time) {\n try {\n Thread.sleep(time);\n } catch (InterruptedException e) {\n Log.e(LOG_TAG, \"Error durmiendo thread\", e);\n }\n }\n}\napp/src/main/java/io/github/jokoframework/activity/LineChartActivity.java\npublic class LineChartActivity extends Activity {\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_linechart);\n\n ImageView backButton = findViewById(R.id.backButton2);\n\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n backToHome();\n }\n });\n\n //Points to be in the graph...\n List data = new ArrayList<>();\n data.add(new FloatDataPair(0f,15000f));\n data.add(new FloatDataPair(0.1f,17500f));\n data.add(new FloatDataPair(0.2f,16500f));\n data.add(new FloatDataPair(0.3f,18500f));\n data.add(new FloatDataPair(0.4f,20500f));\n\n // The Chart whe are gonna use...\n LineChart lineChart = findViewById(R.id.line_chart);\n\n //Configs...\n Description desc = new Description();\n desc.setText(getString(R.string.chart_description));\n desc.setTextColor(R.color.white);\n lineChart.setMarker(new MyMarkView(this));\n lineChart.setDrawMarkers(true);\n lineChart.setDescription(desc);\n lineChart.setBackgroundColor(getResources().getColor(R.color.white));\n lineChart.animateX(3000);\n lineChart.setHighlightPerDragEnabled(false);\n lineChart.setHighlightPerTapEnabled(true);\n\n //More configs to Axis representation...\n setFormatAxis(lineChart);\n\n // insertion of the entries ...\n dataChartInsertion(data, lineChart,this); // data introduccio & styling,others...\n\n }\n\n public void dataChartInsertion(List dataObjects, LineChart chart, Context context){\n List entries = new ArrayList<>();\n\n for (FloatDataPair data : dataObjects) {\n entries.add(new Entry(data.getX(), data.getY()));// The constructer gives you the chance to add a Drawable icon...\n }\n\n LineDataSet dataSet = new LineDataSet(entries, \"Testing Chart\");// add entries to dataset\n dataSet.setColors(new int[] { R.color.group_divider_color, R.color.colorPrimary}, context);\n dataSet.setHighlightEnabled(true);\n dataSet.setCircleColors(new int[] {R.color.group_divider_color},context);\n dataSet.setCircleRadius(0.4f);\n dataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);\n dataSet.setLineWidth(0.5f);\n List colorText = new ArrayList();\n colorText.add(R.color.progress_bar);\n dataSet.setValueTextColors(colorText);\n\n\n List dataSets = new ArrayList<>(); // if it must be more than 1 dataset...\n dataSets.add(dataSet);\n\n LineData lineData = new LineData(dataSets);\n\n chart.setData(lineData);\n chart.invalidate(); // refresh, could be a sync button...\n }\n\n public void setFormatAxis(LineChart mLineChart){\n // Eje X...\n XAxis xAxis = mLineChart.getXAxis();\n xAxis.setDrawAxisLine(true);\n xAxis.setDrawGridLines(false);\n\n // Eje Y...\n //Right\n YAxis yAxisR = mLineChart.getAxisRight();\n yAxisR.setDrawAxisLine(false);\n yAxisR.setDrawGridLines(false);\n yAxisR.setDrawLabels(false);\n //Left\n YAxis yAxisL = mLineChart.getAxisLeft();\n yAxisL.setDrawAxisLine(true);\n yAxisL.setDrawGridLines(false);\n\n mLineChart.setDrawGridBackground(false);\n }\n\n private void backToHome() {\n Intent intent = new Intent(this, HomeActivity.class);\n startActivity(intent);\n finish();\n overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);\n }\n\n}\napp/src/main/java/io/github/jokoframework/otp/OtpActivity.java\npublic class OtpActivity extends Activity{\n private TokenAdapter mTokenAdapter;\n public static final String ACTION_IMAGE_SAVED = \"io.github.jokoframework.otp.ACTION_IMAGE_SAVED\";\n RefreshListBroadcastReceiver receiver = new RefreshListBroadcastReceiver();\n\n private class RefreshListBroadcastReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n mTokenAdapter.notifyDataSetChanged();\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.M)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_otp);\n\n findViewById(R.id.scanImage).setOnClickListener(v -> tryOpenCamera());\n\n findViewById(R.id.back1).setOnClickListener(v -> {\n Intent intent = new Intent(OtpActivity.this, HomeActivity.class);\n startActivity(intent);\n finish();\n overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);\n });\n\n mTokenAdapter = new TokenAdapter(this);\n registerReceiver(receiver, new IntentFilter(ACTION_IMAGE_SAVED));\n ((GridView) findViewById(R.id.grid)).setAdapter(mTokenAdapter);\n\n // Don't permit screenshots since these might contain OTP codes.\n getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);\n\n DataSetObserver mDataSetObserver = new DataSetObserver() {\n @Override\n public void onChanged() {\n super.onChanged();\n if (mTokenAdapter.getCount() == 0)\n findViewById(android.R.id.empty).setVisibility(View.VISIBLE);\n else\n findViewById(android.R.id.empty).setVisibility(View.GONE);\n }\n };\n mTokenAdapter.registerDataSetObserver(mDataSetObserver);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n mTokenAdapter.notifyDataSetChanged();\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n mTokenAdapter.notifyDataSetChanged();\n }\n\n @RequiresApi(api = Build.VERSION_CODES.M)\n private void tryOpenCamera() {\n if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {\n int PERMISSIONS_REQUEST_CAMERA = 1;\n requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);\n }\n else {\n // permission is already granted\n openCamera();\n }\n }\n\n private void openCamera() {\n startActivity(new Intent(this, ScanActivity.class));\n overridePendingTransition(R.anim.fadein, R.anim.fadeout);\n }\n}\napp/src/main/java/io/github/jokoframework/activity/LogOutActivity.java\npublic class LogOutActivity extends BaseActivity {\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Intent login = new Intent(this, LoginActivity.class);\n doLogout(login);\n }\n\n private void doLogout(Intent intent) {\n if(getApp().getUserData() != null) {\n getApp().getUserData().logout();\n }\n startActivity(intent);\n finish();\n }\n}\napp/src/main/java/io/github/jokoframework/activity/HorizontalBarChartActivity.java\npublic class HorizontalBarChartActivity extends Activity {\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_horizontalbarchart);\n\n ImageView backButton = findViewById(R.id.backButton4);\n\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n backToHome();\n }\n });\n\n //Points to be in the graph...\n List data = new ArrayList<>();\n\n data.add(new FloatDataPair(0,110f));\n data.add(new FloatDataPair(1,70f));\n data.add(new FloatDataPair(2,300f));\n data.add(new FloatDataPair(3,220f));\n data.add(new FloatDataPair(4,350f));\n\n // The Chart whe are gonna use...\n HorizontalBarChart horizontalBarChart = findViewById(R.id.horizontalbar_chart);\n //Configs...\n Description desc = new Description();\n desc.setText(getString(R.string.chart_description));\n desc.setTextColor(R.color.white);\n horizontalBarChart.setDescription(desc);\n horizontalBarChart.setBackgroundColor(getResources().getColor(R.color.white));\n horizontalBarChart.setMarker(new MyDialogMarkView(this)); // se puede hacer varias clases de Marks, segun graficos o topicos...\n horizontalBarChart.setScaleEnabled(true);\n horizontalBarChart.animateXY(2000,2000);\n\n //More configs to Axis representation...\n setFormatAxis(horizontalBarChart);\n\n // insertion of the entries ...\n dataChartInsertion(data, horizontalBarChart); // data introduccio & styling,others...\n\n }\n\n public void dataChartInsertion(List dataObjects, HorizontalBarChart chart){\n\n List entries = new ArrayList<>();\n\n for (FloatDataPair data : dataObjects) {\n entries.add(new BarEntry(data.getXi(), data.getY()));// The constructer gives you the chance to add a Drawable icon...\n }\n\n BarDataSet dataSet = new BarDataSet(entries, \"Testing HorizontalBarChart\");\n // add entries to dataset\n dataSet.setColors(new int[]{getResources().getColor(R.color.background_drawer_group),\n getResources().getColor(R.color.colorAccent),\n getResources().getColor(R.color.colorPrimary),\n getResources().getColor(R.color.black),\n getResources().getColor(R.color.drawer_text)});\n dataSet.setHighlightEnabled(true);\n dataSet.setValueTextColor(getResources().getColor(R.color.progress_bar));\n\n List dataSets = new ArrayList<>(); // if it must be more than 1 dataset...\n dataSets.add(dataSet);\n\n BarData barData = new BarData(dataSet);\n barData.setBarWidth(0.9f); // set custom bar width\n chart.setData(barData);\n\n chart.invalidate(); // refresh, could be a sync button...\n }\n\n private void setFormatAxis(HorizontalBarChart hbarChart){\n String[] labels = new String[] {\"08/2017\",\"09/2017\",\"10/2017\",\"11/2017\",\"12/2017\"};\n\n class LabelFormatter implements IAxisValueFormatter {\n private final String[] mLabels;\n\n public LabelFormatter(String[] labels) {\n mLabels = labels;\n }\n\n @Override\n public String getFormattedValue(float value, AxisBase axis) {\n return mLabels[(int) value];\n }\n\n }\n\n // Eje X...\n XAxis xAxis = hbarChart.getXAxis();\n xAxis.setDrawAxisLine(true);\n xAxis.setDrawGridLines(false);\n xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);\n xAxis.setValueFormatter(new LabelFormatter(labels));\n\n // Eje Y...\n //Right\n YAxis yAxisR = hbarChart.getAxisRight();\n yAxisR.setDrawAxisLine(true);\n yAxisR.setDrawGridLines(false);\n yAxisR.setDrawLabels(true);\n //Left\n YAxis yAxisL = hbarChart.getAxisLeft();\n yAxisL.setDrawAxisLine(true);\n yAxisL.setDrawGridLines(false);\n\n hbarChart.setDrawGridBackground(false);\n hbarChart.setFitBars(true); // make the x-axis fit exactly all bars\n\n }\n\n private void backToHome() {\n Intent intent = new Intent(this, HomeActivity.class);\n startActivity(intent);\n finish();\n overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);\n }\n}\napp/src/main/java/io/github/jokoframework/activity/ChangePasswordActivity.java\npublic class ChangePasswordActivity extends Activity {\n\n private static final String LOG_TAG = ChangePasswordActivity.class.getSimpleName();\n\n private Activity self;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n self = this;\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_options);\n\n final EditText currentPasswordEdit = findViewById(R.id.EditTextCurrentPassword);\n final EditText password1 = findViewById(R.id.EditText_Pwd1);\n final EditText password2 = findViewById(R.id.EditText_Pwd2);\n final TextView error = findViewById(R.id.TextView_PwdProblem);\n\n password2.addTextChangedListener(new TextWatcher() {\n public void afterTextChanged(Editable s) {\n checkNewPasswords(password1, password2, error);\n }\n\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n //not needed...\n }\n\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n //not needed...\n }\n });\n\n password1.addTextChangedListener(new TextWatcher() {\n public void afterTextChanged(Editable s) {\n if (password2.getText() != null && StringUtils.isNotBlank(password2.getText().toString())) {\n checkNewPasswords(password1, password2, error);\n }\n }\n\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n //not needed...\n }\n\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n //not needed...\n }\n });\n\n View acceptButton = findViewById(R.id.save_change_password);\n View refusetButton = findViewById(R.id.cancel_change_password);\n\n acceptButton.setOnClickListener(view -> {\n String currentStoredPassword = SecurityUtils.decrypt(Utils.getPrefs(self, Constants.USER_PREFS_PW));\n Log.d(LOG_TAG, \"Guardando contraseña\");\n if (currentPasswordEdit.getText() != null) {\n String currentPassword = currentPasswordEdit.getText().toString();\n if (StringUtils.isBlank(currentPassword) || !currentPassword.equals(currentStoredPassword)) { // No es doble comprobante de que esta vacia la currentPassword.?\n showCurrentPasswordWarning(error, currentPasswordEdit);\n } else {\n String strPassword1 = password1.getText().toString();\n final String strPassword2 = password2.getText().toString();\n if (strPassword1.equals(strPassword2)) {\n doChangePassword(strPassword2, error, currentPasswordEdit);\n }\n }\n } else {\n showCurrentPasswordWarning(error, currentPasswordEdit);\n }\n });\n\n refusetButton.setOnClickListener(view -> {\n Log.d(LOG_TAG, \"No se guarda la contraseña\");\n Intent intent = new Intent(self, HomeActivity.class);\n startActivity(intent);\n });\n }\n\n protected void checkNewPasswords(EditText password1, EditText password2, TextView error) {\n String strPass1 = password1.getText().toString();\n String strPass2 = password2.getText().toString();\n if (strPass1.equals(strPass2)\n && strPass1.trim().length() >= Constants.MIN_PASSWORD_LENGTH) {\n error.setText(R.string.settings_pwd_equal);\n } else {\n if (strPass1.trim().length() >= Constants.MIN_PASSWORD_LENGTH) {\n error.setText(R.string.settings_pwd_not_equal);\n } else {\n error.setText(R.string.settings_pwd_too_short);\n }\n }\n }\n\n protected void doChangePassword(final String strPassword2, TextView error, EditText currentPasswodEdit) {\n error.setText(null);\n currentPasswodEdit.setBackgroundColor(Color.GREEN);\n currentPasswodEdit.requestFocus();\n }\n\n protected void showCurrentPasswordWarning(TextView error, EditText currentPasswodEdit) {\n error.setText(R.string.current_password_warning);\n currentPasswodEdit.setBackgroundColor(getResources().getColor(R.color.warningColor));\n currentPasswodEdit.requestFocus();\n }\n\n}\napp/src/main/java/io/github/jokoframework/activity/AboutActivity.java\npublic class AboutActivity extends Activity implements ImageView.OnClickListener {\n\n private final int NUM_CLICKS_REQUIRED = 6;\n\n //List treated circularly to track last NUM_CLICKS_REQUIRED number of clicks\n private long[] clickTimestamps = new long[NUM_CLICKS_REQUIRED];\n private int oldestIndex = 0;\n private int nextIndex = 0;\n //-------------------------------------------------------------------------------------//\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n requestWindowFeature(Window.FEATURE_NO_TITLE);\n initilizeUI();\n }\n\n private void initilizeUI() {\n setContentView(R.layout.activity_about);\n\n findViewById(R.id.volver).setOnClickListener(v -> {\n Intent intent = new Intent(AboutActivity.this, HomeActivity.class);\n startActivity(intent);\n finish();\n overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);\n });\n\n TextView tv = findViewById(R.id.version_number);\n tv.setText(getString( R.string.version_name));\n ImageView jokoAbout = findViewById(R.id.imageViewHelp);\n jokoAbout.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n long timeMillis = (new Date()).getTime();\n // If we have at least the min number of clicks on record\n if (nextIndex == (NUM_CLICKS_REQUIRED - 1) || oldestIndex > 0) {\n // Check that all required clicks were in required time\n int diff = (int) (timeMillis - clickTimestamps[oldestIndex]);\n //------- Instrumentation to handle number of clicks on default medication switch --------//\n //Require X clicks in Y seconds to trigger secret action\n double SECONDS_FOR_CLICKS = 2;\n if (diff < SECONDS_FOR_CLICKS * 1000) {\n // if accomplish then...\n showAlertDialog(this,\"Easter-Egg!!\",getString(R.string.easter_egg_msg));\n }\n oldestIndex++;\n }\n // If not done, record click time, and bump indices\n clickTimestamps[nextIndex] = timeMillis;\n nextIndex++;\n if (nextIndex == NUM_CLICKS_REQUIRED) {\n nextIndex = 0;\n }\n if (oldestIndex == NUM_CLICKS_REQUIRED) {\n oldestIndex = 0;\n }\n }\n\n private void showAlertDialog(Context mContext, String mTitle, String mBody){\n MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(mContext);\n builder.setCancelable(true);\n\n if(mTitle.length()>0)\n builder.setTitle(mTitle);\n if(mBody.length()>0)\n builder.setTitle(mBody);\n\n builder.setPositiveButton(\"OK\", (dialog, which) -> dialog.dismiss());\n builder.create().show();\n }\n\n}\napp/src/main/java/io/github/jokoframework/activity/BarChartActivity.java\npublic class BarChartActivity extends Activity {\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_barchart);\n\n ImageView backButton = findViewById(R.id.backButton3);\n\n backButton.setOnClickListener(v -> backToHome());\n\n //Points to be in the graph...\n List data = new ArrayList<>();\n data.add(new FloatDataPair(0,150f));\n data.add(new FloatDataPair(1,130f));\n data.add(new FloatDataPair(2,200f));\n data.add(new FloatDataPair(3,300f));\n data.add(new FloatDataPair(4,473f));\n\n // The Chart whe are gonna use...\n BarChart barChart = findViewById(R.id.bar_chart);\n// //Configs...\n Description desc = new Description();\n desc.setText(getString(R.string.chart_description));\n desc.setTextColor(R.color.white);\n barChart.setDescription(desc);\n barChart.setBackgroundColor(getResources().getColor(R.color.white));\n barChart.setDrawGridBackground(false);\n barChart.setMarker(new MyMarkView(this));\n barChart.setScaleEnabled(true);\n barChart.animateXY(2000,2000);\n\n// //More configs to Axis representation...\n setFormatAxis(barChart);\n\n // insertion of the entries ...\n dataChartInsertion(data, barChart); // data introduccio & styling,others...\n\n }\n\n public void dataChartInsertion(List dataObjects, BarChart chart){\n\n List entries = new ArrayList<>();\n\n for (FloatDataPair data : dataObjects) {\n entries.add(new BarEntry(data.getXi(), data.getY()));// The constructer gives you the chance to add a Drawable icon...\n }\n\n BarDataSet dataSet = new BarDataSet(entries, \"Testing BarChart\");\n // add entries to dataset\n dataSet.setColors(getResources().getColor(R.color.background_drawer_group),\n getResources().getColor(R.color.colorAccent),\n getResources().getColor(R.color.colorPrimary),\n getResources().getColor(R.color.black),\n getResources().getColor(R.color.drawer_text));\n dataSet.setHighlightEnabled(true);\n dataSet.setValueTextColor(getResources().getColor(R.color.progress_bar));\n\n List dataSets = new ArrayList<>(); // if it must be more than 1 dataset...\n dataSets.add(dataSet);\n\n BarData barData = new BarData(dataSet);\n barData.setBarWidth(0.9f); // set custom bar width\n chart.setData(barData);\n\n chart.invalidate(); // refresh, could be a sync button...\n }\n\n private void setFormatAxis(BarChart mbarChart){\n String[] labels = new String[] {\"08/2017\",\"09/2017\",\"10/2017\",\"11/2017\",\"12/2017\"};\n\n class LabelFormatter implements IAxisValueFormatter {\n private final String[] mLabels;\n\n public LabelFormatter(String[] labels) {\n mLabels = labels;\n }\n\n @Override\n public String getFormattedValue(float value, AxisBase axis) {\n return mLabels[(int) value];\n }\n }\n\n // Eje X...\n XAxis xAxis = mbarChart.getXAxis();\n xAxis.setDrawAxisLine(true);\n xAxis.setDrawGridLines(false);\n xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);\n xAxis.setValueFormatter(new LabelFormatter(labels));\n\n // Eje Y...\n //Right\n YAxis yAxisR = mbarChart.getAxisRight();\n yAxisR.setDrawAxisLine(false);\n yAxisR.setDrawGridLines(false);\n yAxisR.setDrawLabels(false);\n //Left\n YAxis yAxisL = mbarChart.getAxisLeft();\n yAxisL.setDrawAxisLine(true);\n yAxisL.setDrawGridLines(false);\n\n\n mbarChart.setDrawGridBackground(false);\n mbarChart.setFitBars(true); // make the x-axis fit exactly all bars\n\n }\n\n private void backToHome() {\n Intent intent = new Intent(this, HomeActivity.class);\n startActivity(intent);\n finish();\n overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);\n }\n}\nmboehaolib/src/main/java/io/github/jokoframework/mboehaolib/pojo/Event.java\npublic class Event implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private Long id;\n private String description;\n private Integer resourceIconId;\n private Integer iconMenu;\n\n public Event(Long id) {\n this.id = id;\n }\n private Class activity;\n\n public Class getActivity() {\n return activity;\n }\n\n public void setActivity(Class activity) {\n this.activity = activity;\n }\n\n public Event(int idSelected) {\n setId(Long.valueOf(idSelected));\n }\n\n public Integer getIconMenu() {\n return iconMenu;\n }\n\n public void setIconMenu(Integer iconMenu) {\n this.iconMenu = iconMenu;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Integer getResourceIconId() {\n return resourceIconId;\n }\n\n public void setResourceIconId(Integer resourceIconId) {\n this.resourceIconId = resourceIconId;\n }\n\n @Override\n public String toString() {\n return \"Event{\" +\n \"id=\" + id +\n \", description='\" + description + '\\'' +\n \", resourceIconId=\" + resourceIconId +\n \", iconMenu=\" + iconMenu +\n '}';\n }\n}\nmboehaolib/src/main/java/io/github/jokoframework/mboehaolib/constants/Constants.java\npublic class Constants {\n\n public static final long CRON_INTERVAL = (60 * 60 * 1000);\n public static final long FIRST_TIME = (12 * 1000);\n\n\n public static final double DATABASE_VERSION = 1.0;\n public static final String DATABASE_NAME = String.format(\"mboehao-v%s.db\", DATABASE_VERSION);\n public static final int VERSION_CODE = 33;\n\n /**\n * Constantes de tiempos comúnmente utilizadas, en milisegundos\n */\n public static final long ONE_SECOND = 1000L;\n public static final long ONE_MINUTE = ONE_SECOND * 60L;\n public static final long ONE_HOUR = ONE_MINUTE * 60L;\n public static final long ONE_DAY = ONE_HOUR * 24L;\n\n public static final Map errors = new HashMap<>();\n\n\n /**\n * Si tiene este valor, quiere decir que no hay al menos 4 muestras de dailyTests disponibles\n * para calcular el promedio. Cambiamos a este valor, debido a una incompatibilidad con el cliente\n * iOS que no soportaba el Double.MIN_VALUE\n */\n public static final double HD_VERTICAL_RESOLUTION = 1280;\n public static final double TABLET_VERTICAL_RESOLUTION = 1920;\n public static final double HVGA_VERTICAL_RESOLUTION = 480;\n\n\n //Miscelaneos\n public static final String DATE_TIME_FORMAT_ISO_8601 = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\";\n\n public static final String API_URL = \"/joko/api\";\n\n // Para pruebas en servidores de Testing\n public static final String SERVER_NAME = \"testing.sodep.com.py\";\n public static final String SERVER_PORT = \"443\";\n public static final String BASE_URL = \"https://\" + SERVER_NAME + \":\" + SERVER_PORT;\n\n //Firebase Configuration...\n public static final String SENDER_ID = \"1037867417276\";\n public static final String CURRENT_MBOEHAO_VERSION = \"1.0\";\n public static Integer msgId = 0;\n\n public static final String FACEBOOK_PROFILE_DATA = \"FACEBOOK_PROFILE_INFO\";\n\n\n public static final String FROM_BACKGROUND_SERVICE = \"FROM_BACKGROUND_SERVICE\";\n public static final String APP_NEWS = \"appNews\";\n public static final String USER_PREFERENCE_APP_NEWS = \"_appNews\";\n public static final String USER_PREFERENCE_APP_NEWS_SHOWED_TIME = \"_appNewsShowed\";\n\n\n public static final String PREF_USER_LEARNED_DRAWER = \"navigation_drawer_learned\";\n\n public static final String HEADER_AUTH = \"X-JOKO-AUTH\";\n public static final String HEADER_VERSION = \"X-JOKO-SECURITY-VERSION\";\n\n public static final String KEY_REFRESH_TOKEN = \"REFRESH_TOKEN\";\n public static final String KEY_EXPIRATION = \"EXPIRATION_TOKEN\";\n public static final String KEY_USERNAME = \"USERNAME\";\n public static final String KEY_ACTIVE = \"ACTIVE\";\n public static final String KEY_FIRST_NAME = \"FIRSTNAME\";\n public static final String KEY_SURNAME = \"SURNAME\";\n public static final String KEY_CLIENT_REFERENCE_NUMBER = \"CLIENT_REFERENCE_NUMBER\";\n public static final String KEY_REMEMBER_ME = \"REMEMBER_ME\";\n public static final String KEY_SHOW_TAG_MESSAGE = \"SHOW_TAG_MESSAGE\";\n public static final String KEY_USER_ID = \"USER_ID\";\n public static final String USER_PREFS_USER = \"U\";\n public static final String USER_PREFS_PW = \"P\";\n\n //Referentes al parse\n public static final String PARSE_PARAMETER = \"Parameter\";\n public static final String PARSE_PARAMETER_DESCRIPTION = \"description\";\n public static final String PARSE_PARAMETER_VALUE = \"value\";\n public static final String PARSE_CLASS_REMOTE_LOG = \"RemoteLog\";\n public static final String PARSE_ATTRIBUTE_LEVEL = \"level\";\n public static final String IMAGE_PNG = \"image/png\";\n public static final String PARSE_ATTRIBUTE_LOG_TAG = \"logTag\";\n public static final String PARSE_ATTRIBUTE_MESSAGE = \"message\";\n public static final String PARSE_ATTRIBUTE_OBJECT_ID = \"objectId\";\n public static final String PARSE_ATTRIBUTE_SAVED_AT = \"savedAt\";\n public static final String PARSE_ATTRIBUTE_STACKTRACE = \"stackTrace\";\n public static final String PARSE_ATTRIBUTE_APP_VERSION = \"appVersion\";\n public static final String PARSE_ATTRIBUTE_USERNAME = \"username\";\n public static final String PARSE_ATTRIBUTE_USER_AS_USERNAME = \"user\";\n public static final int PASSWORD_MIN_LENGTH = 4;\n public static final int MIN_PASSWORD_LENGTH = 8;\n public static final String HTML_SCALED_FONT_SIZE = \"3\";\n public static final String SHARED_MBOEHAO_PREF = \"MboehaoPref\";\n public static final int NOTIFICATION_ID = 13;\n public static final String SIMBOLO_GUARANI = \"Gs. \";\n public static final String CURRENCY_SYMBOL = Constants.SIMBOLO_GUARANI;\n public static final String SECRET = \"0Twrt564w1rb56GhIJa3ur53VjYF2wkewegwernglkmergECfIZcLzT1MGYNO4hia_HsoVxpU7vp0sFNix3_JgK4ZHEwrthL3dmaTIrIMkdI2u3wethwQ1AvHPoU58X2H3w0Kf\";\n public static final int SECONDS_TO_REFRESH = 3600; // 1 hora\n public static final int SECONDS_TO_RESET = 300; // 5 minutos\n public static final String PREFERENCE_ATTRIBUTE_NOTIFICATION_CHECKED = \"preference_attribute_notification_checked\";\n public static final String LOGIN_PROVIDER_FACEBOOK = \"FACEBOOK\";\n public static final String LOGIN_PROVIDER = \"loginProvider\";\n public static final String ACCESS_TOKEN = \"accessToken\";\n public static final String PREFERENCES_ATTRIBUTES = \"prefereces_attributes\";\n public static final String DEVICE_TYPE = \"ANDROID\";\n\n private Constants() {\n /*Porque los constructores no tienen que tener instancias...\n Y menos esta clase de constantes...*/\n }\n\n //Startup Result\n public enum StartUpKeys {\n LOGGED,\n EXPIRED,\n NOT_LOGGED,\n LOGGED_ELSEWHERE,\n LOGIN_ERROR,\n LOGIN_ERROR_MSG\n }\n\n\n}\napp/src/main/java/io/github/jokoframework/adapter/CustomExpandableListAdapter.java\npublic class CustomExpandableListAdapter extends BaseExpandableListAdapter{\n\n\n public static final String LOG_TAG = CustomExpandableListAdapter.class.getSimpleName();\n\n private LayoutInflater mLayoutInflater;\n\n private List mEventParents;\n\n public CustomExpandableListAdapter(Context context, List eventParents) {\n Context mContext = context;\n mEventParents = eventParents;\n mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n }\n\n @Override\n public Object getChild(int groupPosition, int childPosition) {\n return mEventParents.get(groupPosition).getEvents().get(childPosition);\n }\n\n @Override\n public long getChildId(int listPosition, int expandedListPosition) {\n return expandedListPosition;\n }\n\n @Override\n public View getChildView(int listPosition, final int expandedListPosition,\n boolean isLastChild, View converterView, ViewGroup parent) {\n\n final Event event = (Event) getChild(listPosition, expandedListPosition);\n View currentConvertView = converterView;\n if (event == null) {\n //Acá el event siempre es null\n Log.d(LOG_TAG, String.format(\"EVENT NULL position: %s\", expandedListPosition));\n } else {\n if (currentConvertView == null) {\n currentConvertView = mLayoutInflater.inflate(R.layout.drawer_item_child, null);\n }\n\n TextView expandedListTextView = (TextView) currentConvertView\n .findViewById(R.id.drawerText);\n expandedListTextView.setText(event.getDescription());\n\n ImageView imageView = (ImageView) currentConvertView.findViewById(R.id.imageViewSideMenu);\n imageView.setImageResource(event.getIconMenu());\n }\n\n return currentConvertView;\n }\n\n\n @Override\n public int getChildrenCount(int groupPosition) {\n return mEventParents.get(groupPosition).getEvents().size();\n }\n\n @Override\n public Object getGroup(int listPosition) {\n return mEventParents.get(listPosition);\n }\n\n @Override\n public int getGroupCount() {\n return mEventParents.size();\n }\n\n @Override\n public long getGroupId(int listPosition) {\n return listPosition;\n }\n\n @Override\n public View getGroupView(int listPosition, boolean isExpanded,\n View converterView, ViewGroup parent) {\n EventParent eventParent = (EventParent) getGroup(listPosition);\n View currentConvertView;\n // Performance wise, this should not be commented,\n // but for now we avoid a weird bug of reordering of\n // the menu items\n // http://stackoverflow.com/questions/26530049/expandablelistview-reorganizes-children-views-order-on-every-group-expand\n if (eventParent.getEvent() != null) {\n // Menu drawer item with image and no childs\n Event e = eventParent.getEvent();\n currentConvertView = mLayoutInflater.inflate(R.layout.drawer_item_parent, null);\n TextView txtTitle = (TextView) currentConvertView.findViewById(R.id.drawerText);\n txtTitle.setText(e.getDescription());\n } else {\n currentConvertView = mLayoutInflater.inflate(R.layout.drawer_group, null);\n TextView listTitleTextView = (TextView) currentConvertView\n .findViewById(R.id.listTitle);\n listTitleTextView.setText(eventParent.getTitle());\n\n }\n\n return currentConvertView;\n }\n\n\n @Override\n public boolean hasStableIds() {\n return false;\n }\n\n @Override\n public boolean isChildSelectable(int listPosition, int expandedListPosition) {\n return true;\n }\n\n\n}\nmboehaolib/src/main/java/io/github/jokoframework/mboehaolib/pojo/EventParent.java\npublic class EventParent {\n\n\n private String title;\n\n private List events;\n\n private String iconId;\n\n private Event event;\n\n public EventParent(String title, List events) {\n this.title = title;\n this.events = events;\n }\n\n public EventParent(Event event) {\n this.title = event.getDescription();\n this.events = new ArrayList<>();\n this.event = event;\n }\n\n public String getTitle() {\n return this.title;\n }\n\n public List getEvents() {\n return this.events;\n }\n\n public String getIconId() {\n return this.iconId;\n }\n\n public Event getEvent() {\n return this.event;\n }\n}\napp/src/main/java/io/github/jokoframework/activity/MultipleLineChartActivity.java\npublic class MultipleLineChartActivity extends Activity {\n\n private static final String LOG_TAG = MultipleLineChartActivity.class.getSimpleName();\n private Spinner mSpinner;\n private LineChart mlineChart;\n private HashMap> mMultipleChartData;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_multiplelinechart);\n\n ImageView backButton = findViewById(R.id.backButton5);\n\n backButton.setOnClickListener(v -> backToHome());\n\n // The Chart whe are gonna use...\n mlineChart = findViewById(R.id.multiple_line_chart);\n mSpinner = findViewById(R.id.content_chooser_spinner);\n mMultipleChartData = new HashMap<>();\n loadMultipleChartData();\n initializeSpinner();\n initializeChart();\n displayDialog();\n }\n\n private void loadMultipleChartData() {\n List contentLabels = Arrays.asList(getResources().getStringArray(\n R.array.test_label_array));\n\n List data1 = getFloatDataPairs();\n List data2 = getFloatDataPairs();\n Utils.sleep(100);\n List data3 = getFloatDataPairs();\n Utils.sleep(100);\n List data4 = getFloatDataPairs();\n Utils.sleep(100);\n List data5 = getFloatDataPairs();\n Utils.sleep(100);\n List data6 = getFloatDataPairs();\n Utils.sleep(100);\n\n mMultipleChartData.put(contentLabels.get(0), data1);\n mMultipleChartData.put(contentLabels.get(1), data2);\n mMultipleChartData.put(contentLabels.get(2), data3);\n mMultipleChartData.put(contentLabels.get(3), data4);\n mMultipleChartData.put(contentLabels.get(4), data5);\n mMultipleChartData.put(contentLabels.get(5), data6);\n }\n\n private List getFloatDataPairs() {\n Random random = new Random(System.currentTimeMillis());\n //Points to be in the graph...\n List data = new ArrayList<>();\n data.add(new FloatDataPair(0f,Float.valueOf(random.nextInt(20000))));\n data.add(new FloatDataPair(0.1f,Float.valueOf((random.nextInt(20000)))));\n data.add(new FloatDataPair(0.2f,Float.valueOf((random.nextInt(20000)))));\n data.add(new FloatDataPair(0.3f,Float.valueOf((random.nextInt(20000)))));\n data.add(new FloatDataPair(0.4f,Float.valueOf((random.nextInt(20000)))));\n return data;\n }\n\n private void initializeSpinner() {\n List contentLabels = Arrays.asList(getResources().getStringArray(\n R.array.test_label_array));\n\n ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, contentLabels);\n mSpinner.setAdapter(adapter);\n mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {\n @Override\n public void onItemSelected(AdapterView parentView, View selectedItemView, int position, long id) {\n graphChart(position);\n }\n\n @Override\n public void onNothingSelected(AdapterView parentView) {\n // your code here\n }\n });\n }\n\n private void initializeChart() {\n\n //Configs...\n mlineChart.setMarker(new MyMarkView(this));\n mlineChart.setDrawMarkers(true);\n mlineChart.setBackgroundColor(getResources().getColor(R.color.white));\n mlineChart.animateX(3000);\n mlineChart.setHighlightPerDragEnabled(false);\n mlineChart.setHighlightPerTapEnabled(true);\n\n //More configs to Axis representation...\n setFormatAxis(mlineChart);\n }\n\n private void displayDialog() {\n List contentLabels = Arrays.asList(getResources().getStringArray(\n R.array.test_label_array));\n\n ContentChooserDialog mSpinnerDialog = new ContentChooserDialog(this, contentLabels,\n new ContentChooserDialog.DialogListener() {\n public void cancelled() {\n // do your code here\n Log.d(LOG_TAG, \"No content selected\");\n }\n\n public void ready(int idSelected) {\n graphChart(idSelected);\n mSpinner.setSelection(idSelected);\n }\n });\n mSpinnerDialog.show();\n }\n\n private void graphChart(int id) {\n String label = (String) mMultipleChartData.keySet().toArray()[id];\n List data = mMultipleChartData.get(label);\n\n //Configs...\n Description desc = new Description();\n desc.setText(label);\n mlineChart.setDescription(desc);\n // insertion of the entries ...\n assert data != null;\n dataChartInsertion(data, mlineChart,this); // data introduccio & styling,others...\n }\n\n public void dataChartInsertion(List dataObjects, LineChart chart, Context context){\n List entries = new ArrayList<>();\n\n for (FloatDataPair data : dataObjects) {\n entries.add(new Entry(data.getX(), data.getY()));// The constructer gives you the chance to add a Drawable icon...\n }\n\n LineDataSet dataSet = new LineDataSet(entries, \"Testing Chart\");// add entries to dataset\n dataSet.setColors(new int[] { R.color.group_divider_color, R.color.colorPrimary}, context);\n dataSet.setHighlightEnabled(true);\n dataSet.setCircleColors(new int[] {R.color.group_divider_color},context);\n dataSet.setCircleRadius(0.4f);\n dataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);\n dataSet.setLineWidth(0.5f);\n List colorText = new ArrayList();\n colorText.add(R.color.progress_bar);\n dataSet.setValueTextColors(colorText);\n\n List dataSets = new ArrayList<>(); // if it must be more than 1 dataset...\n dataSets.add(dataSet);\n\n LineData lineData = new LineData(dataSets);\n\n chart.setData(lineData);\n chart.invalidate(); // refresh, could be a sync button...\n }\n\n public void setFormatAxis(LineChart mLineChart){\n // Eje X...\n XAxis xAxis = mLineChart.getXAxis();\n xAxis.setDrawAxisLine(true);\n xAxis.setDrawGridLines(false);\n\n // Eje Y...\n //Right\n YAxis yAxisR = mLineChart.getAxisRight();\n yAxisR.setDrawAxisLine(false);\n yAxisR.setDrawGridLines(false);\n yAxisR.setDrawLabels(false);\n //Left\n YAxis yAxisL = mLineChart.getAxisLeft();\n yAxisL.setDrawAxisLine(true);\n yAxisL.setDrawGridLines(false);\n\n mLineChart.setDrawGridBackground(false);\n }\n\n private void backToHome() {\n Intent intent = new Intent(this, HomeActivity.class);\n startActivity(intent);\n finish();\n overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);\n }\n}\n", "answers": [" if (Utils.getPrefs(getActivity(), Constants.FACEBOOK_PROFILE_DATA) == null) {"], "length": 4536, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "bfa8cae7a4d93002461470be0784b0b57393175bdb2293a0"} {"input": "package fr.insee.eno.test;\nimport java.io.File;\nimport java.io.IOException;\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\nimport org.xmlunit.diff.Diff;\nimport fr.insee.eno.generation.DDI2XFORMSGenerator;\nimport fr.insee.eno.postprocessing.Postprocessor;\nimport fr.insee.eno.postprocessing.xforms.XFORMSBrowsingPostprocessor;\nimport fr.insee.eno.service.GenerationService;\nimport fr.insee.eno.preprocessing.DDICleaningPreprocessor;\nimport fr.insee.eno.preprocessing.DDIDereferencingPreprocessor;\nimport fr.insee.eno.preprocessing.DDIMarkdown2XhtmlPreprocessor;\nimport fr.insee.eno.preprocessing.DDIMultimodalSelectionPreprocessor;\nimport fr.insee.eno.preprocessing.DDITitlingPreprocessor;\nimport fr.insee.eno.preprocessing.Preprocessor;\n\n\n\n\npublic class TestDDI2XFORMS {\n\t\n\tprivate DDI2XFORMSGenerator ddi2xforms = new DDI2XFORMSGenerator();\n\t\n\tprivate XMLDiff xmlDiff = new XMLDiff();\n\n\t@Test\n\tpublic void simpleDiffTest() {\n\t\ttry {\n\t\t\tString basePath = \"src/test/resources/ddi-to-xforms\";\n\t\t\t", "context": "src/main/java/fr/insee/eno/generation/DDI2XFORMSGenerator.java\npublic class DDI2XFORMSGenerator implements Generator {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DDI2XFORMSGenerator.class);\n\n\tprivate XslTransformation saxonService = new XslTransformation();\n\n\tprivate static final String styleSheetPath = Constants.TRANSFORMATIONS_DDI2XFORMS_DDI2XFORMS_XSL;\n\n\t@Override\n\tpublic File generate(File finalInput, byte[] parameters, String surveyName) throws Exception {\n\t\tlogger.info(\"DDI2XFORMS Target : START\");\n\t\tlogger.debug(\"Arguments : finalInput : \" + finalInput + \" surveyName \" + surveyName);\n\t\tString formNameFolder = null;\n\t\tString outputBasicFormPath = null;\n\n\t\tformNameFolder = getFormNameFolder(finalInput);\n\n\t\tlogger.debug(\"formNameFolder : \" + formNameFolder);\n\t\tString sUB_TEMP_FOLDER = Constants.sUB_TEMP_FOLDER(surveyName);\n\t\toutputBasicFormPath = Constants.tEMP_XFORMS_FOLDER(sUB_TEMP_FOLDER) + \"/\" + formNameFolder + \"/\"\n\t\t\t\t+ Constants.BASIC_FORM_TMP_FILENAME;\n\t\tlogger.debug(\"Output folder for basic-form : \" + outputBasicFormPath);\n\n\t\t\n\t\ttry (\n\t\t\tInputStream isTRANSFORMATIONS_DDI2XFORMS_DDI2XFORMS_XSL = Constants\n\t\t\t\t.getInputStreamFromPath(styleSheetPath);\n\t\t\tInputStream isFinalInput = FileUtils.openInputStream(finalInput);\n\t\t\tOutputStream osOutputBasicForm = FileUtils.openOutputStream(new File(outputBasicFormPath));){\n\t\t\t\n\t\t\tsaxonService.transformDDI2XFORMS(isFinalInput, osOutputBasicForm, isTRANSFORMATIONS_DDI2XFORMS_DDI2XFORMS_XSL,\n\t\t\t\t\tparameters);\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = String.format(\"An error was occured during the %s transformation. %s : %s\",\n\t\t\t\t\tin2out(),\n\t\t\t\t\te.getMessage(),\n\t\t\t\t\tUtils.getErrorLocation(styleSheetPath,e));\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\n\t\treturn new File(outputBasicFormPath);\n\t}\n\n\t/**\n\t * @param finalInput\n\t * @return\n\t */\n\tprivate String getFormNameFolder(File finalInput) {\n\t\tString formNameFolder;\n\t\tformNameFolder = FilenameUtils.getBaseName(finalInput.getAbsolutePath());\n\t\tformNameFolder = FilenameUtils.removeExtension(formNameFolder);\n\t\tformNameFolder = formNameFolder.replace(XslParameters.TITLED_EXTENSION, \"\");\n\t\treturn formNameFolder;\n\t}\n\n\tpublic String in2out() {\n\t\treturn \"ddi2xforms\";\n\t}\n\n}\nsrc/main/java/fr/insee/eno/preprocessing/Preprocessor.java\npublic interface Preprocessor {\n\n\t/**\n\t * This method handles the preprocessing of an input file. TODO Exception is\n\t * also weak, change to a more robust Exception\n\t * \n\t * @param inputFile\n\t * The file to preprocess\n\t * @param parameters\n\t * An optional parameters file\n\t * @param survey\n\t * An optional parameters file\n\t * @return the preprocessed file\n\t * @throws Exception\n\t * when it goes wrong\n\t */\n\tpublic File process(File inputFile, byte[] parameters, String survey, String in2out) throws Exception;\n\n\tpublic String toString();\n}\nsrc/main/java/fr/insee/eno/postprocessing/Postprocessor.java\npublic interface Postprocessor {\n\n\tFile process(File input, byte[] parametersFile, String survey) throws Exception;\n\n\tdefault File process(File input, byte[] parametersFile, byte[] metadata, String survey) throws Exception{\n\t\treturn this.process(input,parametersFile,survey);\n\t}\n\t\n\tdefault File process(File input, byte[] parametersFile, byte[] metadata, byte[] specificTreatmentXsl, String survey) throws Exception{\n\t\treturn this.process(input,parametersFile,metadata,survey);\n\t}\n\t\n\tdefault File process(File input, byte[] parametersFile, byte[] metadata, byte[] specificTreatmentXsl, byte[] mapping, String survey) throws Exception{\n\t\treturn this.process(input,parametersFile,metadata,specificTreatmentXsl,survey);\n\t}\n\t\n\tpublic String toString();\n}\nsrc/main/java/fr/insee/eno/preprocessing/DDIMarkdown2XhtmlPreprocessor.java\npublic class DDIMarkdown2XhtmlPreprocessor implements Preprocessor {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DDIMarkdown2XhtmlPreprocessor.class);\n\n\tprivate XslTransformation saxonService = new XslTransformation();\n\n\tprivate static final String styleSheetPath = Constants.UTIL_DDI_MD2XHTML_XSL;\n\n\t@Override\n\tpublic File process(File input, byte[] parameters, String survey, String in2out) throws Exception {\n\n\t\tlogger.info(\"DDIMarkdown2XhtmlPreprocessor Target : START\");\n\t\tString md2xhtmlOutput = FilenameUtils.removeExtension(input.getPath()) + Constants.MD_EXTENSION;\n\t\t// ----- mw2xhtml\n\t\tlogger.debug(\"Markdown to XHTML : -Input : \" + input + \" -Output : \" + md2xhtmlOutput + \" -Stylesheet : \"\n\t\t\t\t+ Constants.UTIL_DDI_MD2XHTML_XSL + \" -Parameters : \" + Constants.sUB_TEMP_FOLDER(survey));\n\n\t\tInputStream isDDI_MW2XHTML_XSL = Constants.getInputStreamFromPath(styleSheetPath);\n\t\tInputStream isInputFile = FileUtils.openInputStream(input);\n\n\t\tOutputStream osTEMP_NULL_TMP = FileUtils.openOutputStream(new File(md2xhtmlOutput));\n\n\t\ttry {\n\t\t\tsaxonService.transformMw2XHTML(isInputFile, isDDI_MW2XHTML_XSL, osTEMP_NULL_TMP,\n\t\t\t\t\tConstants.SUB_TEMP_FOLDER_FILE(survey));\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = String.format(\"An error was occured during the Markdown2Xhtml transformation. %s : %s\",\n\t\t\t\t\te.getMessage(),\n\t\t\t\t\tUtils.getErrorLocation(styleSheetPath,e));\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\t\tisInputFile.close();\n\t\tisDDI_MW2XHTML_XSL.close();\n\t\tosTEMP_NULL_TMP.close();\n\n\t\t// ----- tweak-xhtml-for-ddi\n\t\t// tweak-xhtml-for-ddi-input = mw2xhtml-output\n\n\t\tString outputTweakXhtmlForDdi = FilenameUtils.removeExtension(input.getPath()) + Constants.MD2_EXTENSION;\n\n\t\tlogger.debug(\"Tweak-xhtml-for-ddi : -Input : \" + md2xhtmlOutput + \" -Output : \" + outputTweakXhtmlForDdi\n\t\t\t\t+ \" -Stylesheet : \" + Constants.UTIL_DDI_TWEAK_XHTML_FOR_DDI_XSL + \" -Parameters : \"\n\t\t\t\t+ (parameters == null ? \"Default parameters\" : \"Provided parameters\"));\n\n\t\tInputStream isTweakXhtmlForDdi = FileUtils.openInputStream(new File(md2xhtmlOutput));\n\t\tInputStream isUTIL_DDI_TWEAK_XHTML_FOR_DDI_XSL = Constants\n\t\t\t\t.getInputStreamFromPath(Constants.UTIL_DDI_TWEAK_XHTML_FOR_DDI_XSL);\n\t\tOutputStream osTweakXhtmlForDdi = FileUtils.openOutputStream(new File(outputTweakXhtmlForDdi));\n\t\ttry {\n\t\t\tsaxonService.transformTweakXhtmlForDdi(isTweakXhtmlForDdi, isUTIL_DDI_TWEAK_XHTML_FOR_DDI_XSL,\n\t\t\t\t\tosTweakXhtmlForDdi, Constants.SUB_TEMP_FOLDER_FILE(survey));\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = \"An error has occurred during the Markdown2Xhtml transformation. \"+e.getMessage();\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\t\tisTweakXhtmlForDdi.close();\n\t\tisUTIL_DDI_TWEAK_XHTML_FOR_DDI_XSL.close();\n\t\tosTweakXhtmlForDdi.close();\n\n\t\tlogger.debug(\"DDIMarkdown2XhtmlPreprocessor : END\");\n\t\treturn new File(outputTweakXhtmlForDdi);\n\n\t}\n\n}\nsrc/main/java/fr/insee/eno/postprocessing/xforms/XFORMSBrowsingPostprocessor.java\npublic class XFORMSBrowsingPostprocessor implements Postprocessor {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(XFORMSBrowsingPostprocessor.class);\n\n\tprivate XslTransformation saxonService = new XslTransformation();;\n\n\tprivate static final String styleSheetPath = Constants.UTIL_XFORMS_BROWSING_XSL;\n\n\t@Override\n\tpublic File process(File input, byte[] parameters, String survey) throws Exception {\n\n\t\tFile outputForFRFile = new File(input.getParent(),\n\t\t\t\tConstants.BASE_NAME_FORM_FILE +\n\t\t\t\tConstants.BROWSING_XFORMS_EXTENSION);\n\n\t\tlogger.debug(\"Output folder for basic-form : \" + outputForFRFile.getAbsolutePath());\n\n\t\tInputStream FO_XSL = Constants.getInputStreamFromPath(styleSheetPath);\n\n\t\tInputStream inputStream = FileUtils.openInputStream(input);\n\t\tOutputStream outputStream = FileUtils.openOutputStream(outputForFRFile);\n\t\ttry {\n\t\t\tsaxonService.transformBrowsingXforms(inputStream, outputStream, FO_XSL);\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = String.format(\"An error was occured during the %s transformation. %s : %s\",\n\t\t\t\t\ttoString(),\n\t\t\t\t\te.getMessage(),\n\t\t\t\t\tUtils.getErrorLocation(styleSheetPath,e));\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\n\t\tinputStream.close();\n\t\toutputStream.close();\n\t\tFO_XSL.close();\n\t\tlogger.info(\"End of Browsing post-processing \" + outputForFRFile.getAbsolutePath());\n\n\t\treturn outputForFRFile;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn PostProcessing.XFORMS_BROWSING.name();\n\t}\n\n\n}\nsrc/main/java/fr/insee/eno/preprocessing/DDIDereferencingPreprocessor.java\npublic class DDIDereferencingPreprocessor implements Preprocessor {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DDIDereferencingPreprocessor.class);\n\n\tprivate XslTransformation saxonService = new XslTransformation();\n\n\tprivate static final String styleSheetPath = Constants.UTIL_DDI_DEREFERENCING_XSL;\n\n\t@Override\n\tpublic File process(File inputFile, byte[] parametersFile, String survey, String in2out) throws Exception {\n\t\tlogger.info(\"DDIPreprocessing Target : START\");\n\n\t\tString sUB_TEMP_FOLDER = Constants.sUB_TEMP_FOLDER(survey);\n\t\t// ----- Dereferencing\n\t\tlogger.debug(\"Dereferencing : -Input : \" + inputFile + \" -Output : \" + Constants.tEMP_NULL_TMP(sUB_TEMP_FOLDER)\n\t\t+ \" -Stylesheet : \" + styleSheetPath + \" -Parameters : \" + sUB_TEMP_FOLDER);\n\n\t\tInputStream isDDI_DEREFERENCING_XSL = Constants.getInputStreamFromPath(styleSheetPath);\n\t\tInputStream isInputFile = FileUtils.openInputStream(inputFile);\n\t\tOutputStream osTEMP_NULL_TMP = FileUtils.openOutputStream(Constants.tEMP_NULL_TMP(sUB_TEMP_FOLDER));\n\n\t\ttry {\n\t\t\tsaxonService.transformDereferencing(isInputFile, isDDI_DEREFERENCING_XSL, osTEMP_NULL_TMP,\n\t\t\t\t\tConstants.SUB_TEMP_FOLDER_FILE(survey));\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = String.format(\"An error was occured during the %s transformation. %s : %s\",\n\t\t\t\t\ttoString(),\n\t\t\t\t\te.getMessage(),\n\t\t\t\t\tUtils.getErrorLocation(styleSheetPath,e));\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\n\t\tisInputFile.close();\n\t\tisDDI_DEREFERENCING_XSL.close();\n\t\tosTEMP_NULL_TMP.close();\n\t\t// ----- Cleaning\n\t\tlogger.debug(\"Cleaning target\");\n\t\tFile f = Constants.SUB_TEMP_FOLDER_FILE(survey);\n\t\tFile[] matchCleaningInput = f.listFiles(new FilenameFilter() {\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\treturn !(name.startsWith(\"null\")||name.contains(\"-modal\")) && name.endsWith(\".tmp\");\n\t\t\t}\n\t\t});\n\n\t\tString cleaningInput = null;\n\n\t\tlogger.debug(\"Searching matching files in : \" + sUB_TEMP_FOLDER);\n\t\tfor (File file : matchCleaningInput) {\n\t\t\tif(!file.isDirectory()) {\n\t\t\t\tcleaningInput = file.getAbsolutePath();\n\t\t\t\tlogger.debug(\"Found : \" + cleaningInput);\n\t\t\t}\n\t\t}\n\t\tif(cleaningInput==null) {\n\t\t\tthrow new EnoGenerationException(\"DDIDereferencing produced no file.\");\n\t\t}\n\n\t\tlogger.debug(\"DDIPreprocessing Dereferencing : END\");\n\t\treturn new File(cleaningInput);\n\t}\n\n\tpublic String toString() {\n\t\treturn PreProcessing.DDI_DEREFERENCING.name();\n\t}\n\n\n}\nsrc/main/java/fr/insee/eno/service/GenerationService.java\npublic class GenerationService {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(GenerationService.class);\n\n\tprivate final Preprocessor[] preprocessors;\n\tprivate final Generator generator;\n\tprivate final Postprocessor[] postprocessors;\n\n\tprivate byte[] parameters;\n\tprivate byte[] metadata;\n\tprivate byte[] specificTreatment;\n\tprivate byte[] mapping;\n\t\n\tprivate boolean cleaningFolder;\n\n\t@Inject\n\tpublic GenerationService(final Preprocessor[] preprocessors, final Generator generator,\n\t\t\tfinal Postprocessor[] postprocessors) {\n\t\tthis.preprocessors = preprocessors;\n\t\tthis.generator = generator;\n\t\tthis.postprocessors = postprocessors;\n\t\tthis.cleaningFolder = true;\n\t}\n\n\t@Inject\n\tpublic GenerationService(final Preprocessor preprocessor, final Generator generator,\n\t\t\tfinal Postprocessor[] postprocessors) {\n\t\tthis.preprocessors = new Preprocessor[] { preprocessor };\n\t\tthis.generator = generator;\n\t\tthis.postprocessors = postprocessors;\n\t\tthis.cleaningFolder = true;\n\t}\n\n\t@Inject\n\tpublic GenerationService(final Preprocessor preprocessor, final Generator generator,\n\t\t\tfinal Postprocessor postprocessor) {\n\t\tthis.preprocessors = new Preprocessor[] { preprocessor };\n\t\tthis.generator = generator;\n\t\tthis.postprocessors = new Postprocessor[] { postprocessor };\n\t\tthis.cleaningFolder = true;\n\t}\n\n\t/**\n\t * Launch every step needed in order to generate the target questionnaire.\n\t * \n\t * @param inputFile\n\t * The source file\n\t * \n\t * @return The generated file\n\t * @throws Exception\n\t * bim\n\t */\n\tpublic File generateQuestionnaire(File inputFile, String surveyName) throws Exception {\n\t\tlogger.info(this.toString());\n\t\tlogger.info(\"Generating questionnaire for: \" + surveyName);\n\n\t\tString tempFolder = System.getProperty(\"java.io.tmpdir\") + \"/\" + surveyName;\n\t\tlogger.debug(\"Temp folder: \" + tempFolder);\n\t\tif(cleaningFolder) {\n\t\t\tcleanTempFolder(surveyName);\n\t\t}\n\t\tFile preprocessResultFileName = null;\n\t\t\n\t\tpreprocessResultFileName = this.preprocessors[0].process(inputFile, parameters, surveyName,generator.in2out());\t\n\t\t\n\t\tfor (int i = 1; i < preprocessors.length; i++) {\n\t\t\tpreprocessResultFileName = this.preprocessors[i].process(preprocessResultFileName, parameters, surveyName,\n\t\t\t\t\tgenerator.in2out());\n\t\t}\n\n\t\tFile generatedForm = this.generator.generate(preprocessResultFileName, parameters, surveyName);\n\t\tFile outputForm = this.postprocessors[0].process(generatedForm, parameters, metadata, specificTreatment, mapping, surveyName);\n\t\tfor (int i = 1; i < postprocessors.length; i++) {\n\t\t\toutputForm = this.postprocessors[i].process(outputForm, parameters, metadata, specificTreatment, mapping,surveyName);\n\t\t}\n\t\tFile finalForm = new File(outputForm.getParent()+Constants.BASE_NAME_FORM_FILE+\".\"+FilenameUtils.getExtension(outputForm.getAbsolutePath()));\n\t\tif(!finalForm.equals(outputForm)) {\n\t\t\tFiles.move(outputForm, finalForm);\n\t\t}\n\t\tlogger.debug(\"Path to generated questionnaire: \" + finalForm.getAbsolutePath());\n\n\t\treturn finalForm;\n\t}\n\t\n\t\n\tpublic void setParameters(ByteArrayOutputStream parametersBAOS) {\n\t\tthis.parameters = parametersBAOS.toByteArray();\n\t}\t\n\n\tpublic void setParameters(InputStream parametersIS) throws IOException {\n\t\tif(parametersIS!=null) {\n\t\t\tthis.parameters = IOUtils.toByteArray(parametersIS);\n\t\t}\n\t}\n\t\n\tpublic void setMetadata(InputStream metadataIS) throws IOException {\n\t\tif(metadataIS!=null) {\n\t\t\tthis.metadata = IOUtils.toByteArray(metadataIS);\n\t\t}\n\t}\n\t\n\tpublic void setSpecificTreatment(InputStream specificTreatmentIS) throws IOException {\n\t\tif(specificTreatmentIS!=null) {\n\t\t\tthis.specificTreatment = IOUtils.toByteArray(specificTreatmentIS);\n\t\t}\n\t}\n\t\n\tpublic void setMapping(InputStream mappingIS) throws IOException {\n\t\tif(mappingIS!=null) {\n\t\t\tthis.mapping = IOUtils.toByteArray(mappingIS);\n\t\t}\n\t}\n\n\tpublic byte[] getParameters() {\n\t\treturn parameters;\n\t}\n\tpublic byte[] getMetadata() {\n\t\treturn metadata;\n\t}\n\tpublic byte[] getSpecificTreatment() {\n\t\treturn specificTreatment;\n\t}\n\tpublic byte[] getMapping() {\n\t\treturn mapping;\n\t}\n\t\n\tpublic void setCleaningFolder(boolean cleaning) {\n\t\tthis.cleaningFolder = cleaning;\n\t}\n\t\n\n\n\t/**\n\t * Clean the temp dir if it exists\n\t * \n\t * @throws IOException\n\t * \n\t */\n\tpublic void cleanTempFolder(String name) throws IOException {\n\t\tif (Constants.TEMP_FOLDER_PATH != null) {\n\t\t\tFile folderTemp = new File(Constants.TEMP_FOLDER_PATH + \"/\" + name);\n\t\t\tcleanTempFolder(folderTemp);\n\t\t} else {\n\t\t\tlogger.debug(\"Temp Folder is null\");\n\t\t}\n\t}\n\n\t/**\n\t * Clean the temp dir if it exists\n\t * \n\t * @throws IOException\n\t * \n\t */\n\tpublic void cleanTempFolder() throws IOException {\n\t\tif (Constants.TEMP_FOLDER_PATH != null) {\n\t\t\tFile folderTemp = new File(Constants.TEMP_FOLDER_PATH);\n\t\t\tcleanTempFolder(folderTemp);\n\t\t} else {\n\t\t\tlogger.debug(\"Temp Folder is null\");\n\t\t}\n\t}\n\n\t/**\n\t * Clean the temp dir if it exists\n\t * \n\t * @throws IOException\n\t * \n\t */\n\tprivate void cleanTempFolder(File folder) throws IOException {\n\t\tFolderCleaner cleanService = new FolderCleaner();\n\t\tif (folder != null) {\n\t\t\tcleanService.cleanOneFolder(folder);\n\t\t} else {\n\t\t\tlogger.debug(\"Temp Folder is null\");\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"GenerationService [preprocessors=\" + Arrays.toString(preprocessors) + \", generator=\" + generator.in2out()\n\t\t\t\t+ \", postprocessors=\" + Arrays.toString(postprocessors) + \"]\";\n\t}\n\t\n\t\n\n}\nsrc/main/java/fr/insee/eno/preprocessing/DDICleaningPreprocessor.java\npublic class DDICleaningPreprocessor implements Preprocessor {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DDICleaningPreprocessor.class);\n\n\tprivate XslTransformation saxonService = new XslTransformation();\n\n\tprivate static final String styleSheetPath = Constants.UTIL_DDI_CLEANING_XSL;\n\n\t@Override\n\tpublic File process(File inputFile, byte[] parametersFile, String survey, String in2out) throws Exception {\n\t\tlogger.info(\"DDIPreprocessing Target : START\");\n\n\t\tString cleaningOutput=null;\n\t\tString cleaningInput = inputFile.getAbsolutePath();\n\t\tcleaningOutput = FilenameUtils.removeExtension(cleaningInput) + Constants.CLEANED_EXTENSION;\n\n\t\tlogger.debug(\"Cleaned output file to be created : \" + cleaningOutput);\n\t\tlogger.debug(\"Cleaning : -Input : \" + cleaningInput + \" -Output : \" + cleaningOutput + \" -Stylesheet : \"\n\t\t\t\t+ styleSheetPath);\n\n\t\tInputStream isCleaningIn = FileUtils.openInputStream(new File(cleaningInput));\n\t\tOutputStream osCleaning = FileUtils.openOutputStream(new File(cleaningOutput));\n\t\tInputStream isUTIL_DDI_CLEANING_XSL = Constants.getInputStreamFromPath(styleSheetPath);\n\n\t\ttry {\n\t\t\tsaxonService.transformCleaning(isCleaningIn, isUTIL_DDI_CLEANING_XSL, osCleaning, in2out);\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = String.format(\"An error was occured during the %s transformation. %s : %s\",\n\t\t\t\t\ttoString(),\n\t\t\t\t\te.getMessage(),\n\t\t\t\t\tUtils.getErrorLocation(styleSheetPath,e));\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\n\t\tisCleaningIn.close();\n\t\tisUTIL_DDI_CLEANING_XSL.close();\n\t\tosCleaning.close();\n\n\t\tlogger.debug(\"DDIPreprocessing Cleaning: END\");\n\t\treturn new File(cleaningOutput);\n\t}\n\n\tpublic String toString() {\n\t\treturn PreProcessing.DDI_CLEANING.name();\n\t}\n\n\n}\nsrc/main/java/fr/insee/eno/preprocessing/DDITitlingPreprocessor.java\npublic class DDITitlingPreprocessor implements Preprocessor {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DDITitlingPreprocessor.class);\n\n\tprivate XslTransformation saxonService = new XslTransformation();\n\n\tprivate static final String styleSheetPath = Constants.UTIL_DDI_TITLING_XSL;\n\n\t@Override\n\tpublic File process(File inputFile, byte[] parametersFile, String survey, String in2out) throws Exception {\n\t\tlogger.info(\"DDIPreprocessing Target : START\");\n\n\t\tString outputTitling = null;\n\t\tString titlingInput = inputFile.getAbsolutePath();\n\n\t\toutputTitling = titlingInput.replace(Constants.CLEANED_EXTENSION, Constants.FINAL_EXTENSION);\n\n\t\tlogger.debug(\"Titling : -Input : \" + titlingInput + \" -Output : \" + outputTitling + \" -Stylesheet : \"\n\t\t\t\t+ styleSheetPath + \" -Parameters : \"\n\t\t\t\t+ (parametersFile == null ? \"Default parameters\" : \"Provided parameters\"));\n\n\t\tInputStream isCleaningTitling = FileUtils.openInputStream(new File(titlingInput));\n\t\tInputStream isUTIL_DDI_TITLING_XSL = Constants.getInputStreamFromPath(styleSheetPath);\n\t\tOutputStream osTitling = FileUtils.openOutputStream(new File(outputTitling));\n\n\t\ttry {\n\t\t\tsaxonService.transformTitling(isCleaningTitling, isUTIL_DDI_TITLING_XSL, osTitling, parametersFile);\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = String.format(\"An error was occured during the %s transformation. %s : %s\",\n\t\t\t\t\ttoString(),\n\t\t\t\t\te.getMessage(),\n\t\t\t\t\tUtils.getErrorLocation(styleSheetPath,e));\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\n\t\tisCleaningTitling.close();\n\t\tisUTIL_DDI_TITLING_XSL.close();\n\t\tosTitling.close();\n\t\tlogger.debug(\"DDIPreprocessing titling: END\");\n\t\treturn new File(outputTitling);\n\t}\n\n\tpublic String toString() {\n\t\treturn PreProcessing.DDI_TITLING.name();\n\t}\n\n}\nsrc/main/java/fr/insee/eno/preprocessing/DDIMultimodalSelectionPreprocessor.java\npublic class DDIMultimodalSelectionPreprocessor implements Preprocessor {\n\t\n\tprivate static final Logger logger = LoggerFactory.getLogger(DDIMultimodalSelectionPreprocessor.class);\n\n\tprivate XslTransformation saxonService = new XslTransformation();\n\n\tprivate static final String styleSheetPath = Constants.UTIL_DDI_MULTIMODAL_SELECTION_XSL;\n\n\t@Override\n\tpublic File process(File inputFile, byte[] parametersFile, String survey, String in2out) throws Exception {\n\t\tlogger.info(\"DDIPreprocessing Target : START\");\n\n\t\tString sUB_TEMP_FOLDER = Constants.sUB_TEMP_FOLDER(survey);\n\t\tString modalSelectionOutput=null;\n\t\tString multimodalInput = inputFile.getAbsolutePath();\n\t\tmodalSelectionOutput = sUB_TEMP_FOLDER + \"\\\\\" + FilenameUtils.getBaseName(multimodalInput) + Constants.MULTIMODAL_EXTENSION;\n\n\t\tlogger.debug(\"Modal DDI output file to be created : \" + modalSelectionOutput);\n\t\tlogger.debug(\"Multimodal Selection : -Input : \" + multimodalInput + \" -Output : \" + modalSelectionOutput + \" -Stylesheet : \"\n\t\t\t\t+ styleSheetPath + \" -Parameters : \" + (parametersFile == null ? \"Default parameters\" : \"Provided parameters\"));\n\n\t\tInputStream isMultimodalIn = FileUtils.openInputStream(new File(multimodalInput));\n\t\tOutputStream osModalSelection = FileUtils.openOutputStream(new File(modalSelectionOutput));\n\t\tInputStream isUTIL_DDI_MULTIMODAL_SELECTION_XSL = Constants.getInputStreamFromPath(styleSheetPath);\n\n\t\ttry {\n\t\t\tsaxonService.transformModalSelection(isMultimodalIn, isUTIL_DDI_MULTIMODAL_SELECTION_XSL, osModalSelection, parametersFile);\n\t\t}catch(Exception e) {\n\t\t\tString errorMessage = String.format(\"An error has occurred during the %s transformation. %s : %s\",\n\t\t\t\t\ttoString(),\n\t\t\t\t\te.getMessage(),\n\t\t\t\t\tUtils.getErrorLocation(styleSheetPath,e));\n\t\t\tlogger.error(errorMessage);\n\t\t\tthrow new EnoGenerationException(errorMessage);\n\t\t}\n\n\t\tisMultimodalIn.close();\n\t\tisUTIL_DDI_MULTIMODAL_SELECTION_XSL.close();\n\t\tosModalSelection.close();\n\n\t\tlogger.debug(\"DDIPreprocessing Multimodal Selection: END\");\n\t\treturn new File(modalSelectionOutput);\n\t}\n\n\tpublic String toString() {\n\t\treturn PreProcessing.DDI_MULTIMODAL_SELECTION.name();\n\t}\n\n\t\n}\n", "answers": ["\t\t\tPreprocessor[] preprocessors = {"], "length": 1962, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "95465d405209abdbe4c60d86a21b4996707e349c168e57d4"} {"input": "package com.balch.mocktrade;\nimport android.Manifest;\nimport android.app.Activity;\nimport android.app.Application;\nimport androidx.lifecycle.ViewModelProviders;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.content.pm.ActivityInfo;\nimport android.content.pm.PackageManager;\nimport android.content.res.ColorStateList;\nimport android.graphics.drawable.Drawable;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport androidx.annotation.ColorRes;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.StringRes;\nimport com.google.android.material.appbar.AppBarLayout;\nimport com.google.android.material.snackbar.Snackbar;\nimport androidx.core.app.ActivityCompat;\nimport androidx.core.content.ContextCompat;\nimport androidx.localbroadcastmanager.content.LocalBroadcastManager;\nimport androidx.core.graphics.drawable.DrawableCompat;\nimport androidx.appcompat.app.AlertDialog;\nimport androidx.appcompat.widget.Toolbar;\nimport android.util.Log;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.Toast;\nimport com.balch.android.app.framework.PresenterActivity;\nimport com.balch.android.app.framework.core.EditActivity;\nimport com.balch.android.app.framework.types.Money;\nimport com.balch.mocktrade.account.Account;\nimport com.balch.mocktrade.account.AccountEditController;\nimport com.balch.mocktrade.order.Order;\nimport com.balch.mocktrade.order.OrderEditController;\nimport com.balch.mocktrade.order.OrderListActivity;\nimport com.balch.mocktrade.services.PerformanceItemUpdateBroadcaster;\nimport com.balch.mocktrade.services.QuoteService;\nimport com.balch.mocktrade.settings.SettingsActivity;\n\n\n\npublic class MainActivity extends PresenterActivity {\n private static final String TAG = MainActivity.class.getSimpleName();\n\n private static final int NEW_ACCOUNT_RESULT = 0;\n private static final int NEW_ORDER_RESULT = 1;\n\n private static final int PERMS_REQUEST_BACKUP = 0;\n private static final int PERMS_REQUEST_RESTORE = 1;\n\n private MenuItem menuProgressBar;\n private MenuItem menuRefreshButton;\n private MenuItem menuHideExcludeAccounts;\n private MenuItem menuDemoMode;\n\n private Handler uiHandler = new Handler(Looper.getMainLooper());\n\n private AccountUpdateReceiver accountUpdateReceiver;\n\n @Override\n public void onCreateBase(Bundle bundle) {\n\n ViewProvider viewProvider = (ViewProvider) getApplication();\n\n if (viewProvider.isTablet(this)) {\n setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);\n }\n\n Toolbar toolbar = findViewById(R.id.portfolio_view_toolbar);\n if (toolbar != null) {\n toolbar.setTitle(\"\");\n setSupportActionBar(toolbar);\n\n // tint the overflow icon\n ColorStateList colorSelector = ContextCompat.getColorStateList(this, R.color.nav_on_color);\n Drawable icon = toolbar.getOverflowIcon();\n if (icon != null) {\n DrawableCompat.setTintList(icon, colorSelector);\n toolbar.setOverflowIcon(icon);\n }\n }\n\n final AppBarLayout appBarLayout = findViewById(R.id.portfolio_view_app_bar);\n if (appBarLayout != null) {\n if (bundle == null) {\n uiHandler.postDelayed(() -> appBarLayout.setExpanded(false), 500);\n } else {\n appBarLayout.setExpanded(false, false);\n }\n }\n }\n\n @Override\n public MainPortfolioView createView() {\n return new MainPortfolioView(this,\n (accountId, daysToReturn) ->\n getPortfolioViewModel().setGraphSelectionCriteria(accountId, daysToReturn));\n }\n\n @Override\n protected MainPresenter createPresenter(MainPortfolioView view) {\n Application application = getApplication();\n return new MainPresenter((TradeModelProvider) application,\n (ViewProvider) application,\n getPortfolioViewModel(), this, view,\n new MainPresenter.ActivityBridge() {\n @Override\n public void showProgress(boolean show) {\n MainActivity.this.showProgress(show);\n }\n\n @Override\n public void startNewAccountActivity() {\n MainActivity.this.showNewAccountActivity();\n }\n\n @Override\n public void showSnackBar(View parent, String displayMsg, @ColorRes int colorId) {\n getSnackbar(parent, displayMsg, Snackbar.LENGTH_LONG,\n R.color.snackbar_background,\n colorId,\n com.google.android.material.R.id.snackbar_text)\n .show();\n }\n\n @Override\n public void requestStoragePermission(int requestCode) {\n ActivityCompat.requestPermissions(MainActivity.this,\n new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},\n requestCode);\n }\n\n @Override\n public void startOrderListActivity(Account account) {\n startActivity(OrderListActivity.newIntent(MainActivity.this, account.getId()));\n }\n\n @Override", "context": "MockTradeApp/src/main/java/com/balch/mocktrade/order/OrderEditController.java\npublic class OrderEditController implements ExternalController, Parcelable {\n public OrderEditController() {\n }\n\n @Override\n public void onChanged(Context context, ColumnDescriptor descriptor, Object value, ControlMap controlMap) throws ValidatorException {\n if (descriptor.getField().getName().equals(Order.FLD_STRATEGY)) {\n onChangeStrategy((Order.OrderStrategy) value, controlMap);\n } else if (descriptor.getField().getName().equals(Order.FLD_ACTION)) {\n onChangeAction(context, (Order.OrderAction) value, controlMap);\n }\n }\n\n @Override\n public void validate(Context context, Order order, ControlMap controlMap) throws ValidatorException {\n StockSymbolLayout symbolControl = controlMap.get(Order.FLD_SYMBOL);\n Money price = symbolControl.getPrice();\n if (order.getStrategy() == Order.OrderStrategy.MANUAL) {\n price = order.getLimitPrice();\n }\n Money cost = Money.multiply(price, order.getQuantity());\n\n boolean hasAvailableFunds = ((order.getAction() == Order.OrderAction.SELL) ||\n (cost.getDollars() <= order.getAccount().getAvailableFunds().getDollars()));\n\n QuantityPriceLayout quantityControl = controlMap.get(Order.FLD_QUANTITY);\n quantityControl.setCost(cost, hasAvailableFunds);\n\n if (!hasAvailableFunds) {\n throw new ValidatorException(quantityControl.getContext().getString(R.string.quantity_edit_error_insufficient_funds));\n } else if ((cost.getDollars() == 0.0) && (order.getStrategy() != Order.OrderStrategy.MANUAL)) {\n throw new ValidatorException(quantityControl.getContext().getString(R.string.quantity_edit_error_invalid_amount));\n }\n }\n\n @Override\n public void initialize(Context context, Order order, ControlMap controlMap) {\n\n boolean controlEnabled = (order.getAction() == Order.OrderAction.BUY);\n\n TradeModelProvider modelProvider = ((TradeModelProvider)context.getApplicationContext());\n FinanceModel financeModel = modelProvider.getFinanceModel();\n\n QuantityPriceLayout quantityControl = controlMap.get(Order.FLD_QUANTITY);\n quantityControl.setOrderInfo(order);\n quantityControl.setMarketIsOpen(financeModel.isMarketOpen());\n quantityControl.setAccountInfo(order.getAccount());\n quantityControl.setEnabled(controlEnabled);\n\n EditLayout control = controlMap.get(Order.FLD_SYMBOL);\n control.setEnabled(controlEnabled);\n }\n\n private void showControl(EditLayout control, boolean visible) {\n if (control != null) {\n if (control instanceof ViewGroup) {\n ((ViewGroup) control).setVisibility(visible ? View.VISIBLE : View.GONE);\n }\n }\n }\n\n private void onChangeStrategy(Order.OrderStrategy strategy, ControlMap controlMap) {\n boolean showLimitPrice = false;\n boolean showStopPrice = false;\n boolean showStopPercent = false;\n\n switch (strategy) {\n case LIMIT:\n case MANUAL:\n showLimitPrice = true;\n break;\n case STOP_LOSS:\n showStopPrice = true;\n break;\n case TRAILING_STOP_AMOUNT_CHANGE:\n showStopPrice = true;\n break;\n case TRAILING_STOP_PERCENT_CHANGE:\n showStopPercent = true;\n break;\n }\n\n showControl(controlMap.get(Order.FLD_LIMIT_PRICE), showLimitPrice);\n showControl(controlMap.get(Order.FLD_STOP_PERCENT), showStopPercent);\n showControl(controlMap.get(Order.FLD_STOP_PRICE), showStopPrice);\n }\n\n private void onChangeAction(Context context, Order.OrderAction action, ControlMap controlMap) {\n EditLayout control = controlMap.get(Order.FLD_STRATEGY);\n if (control instanceof EnumEditLayout) {\n int selectionIndex = 0;\n Order.OrderStrategy strategy = (Order.OrderStrategy) control.getValue();\n List enumValues = new ArrayList<>();\n List displayValues = new ArrayList<>();\n\n String [] masterDisplayValues = context.getResources().getStringArray(strategy.getListResId());\n\n for (int x = 0; x < Order.OrderStrategy.values().length; x++) {\n Order.OrderStrategy s = Order.OrderStrategy.values()[x];\n if ( ((action == Order.OrderAction.BUY) && s.isBuySupported()) ||\n ((action == Order.OrderAction.SELL) && s.isSellSupported())) {\n if (s == strategy) {\n selectionIndex = x;\n }\n enumValues.add(s);\n displayValues.add(masterDisplayValues[x]);\n }\n }\n\n ((EnumEditLayout)control).setOptions(enumValues, displayValues, selectionIndex);\n }\n }\n\n private OrderEditController(Parcel in) {\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n @Override\n public OrderEditController createFromParcel(Parcel in) {\n return new OrderEditController(in);\n }\n\n @Override\n public OrderEditController[] newArray(int size) {\n return new OrderEditController[size];\n }\n };\n\n}\nMockTradeApp/src/main/java/com/balch/mocktrade/services/PerformanceItemUpdateBroadcaster.java\npublic class PerformanceItemUpdateBroadcaster {\n private static final String TAG = PerformanceItemUpdateBroadcaster.class.getSimpleName();\n\n private static final String EXTRA_ACCOUNT_ID = \"extra_account_id\";\n private static final String EXTRA_DAYS_COUNT = \"extra_days_count\";\n\n public static final String ACTION = PerformanceItemUpdateBroadcaster.class.getName();\n\n public static class PerformanceItemUpdateData {\n public final long accountId;\n public final int days;\n\n PerformanceItemUpdateData(long accountId, int days) {\n this.accountId = accountId;\n this.days = days;\n }\n }\n\n static void broadcast(Context context, long accountId, int days) {\n Log.d(TAG, \"broadcast sent:\" + ACTION);\n Intent intent = new Intent(ACTION);\n intent.putExtra(EXTRA_ACCOUNT_ID, accountId);\n intent.putExtra(EXTRA_DAYS_COUNT, days);\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n\n public static PerformanceItemUpdateData getData(Intent intent) {\n return new PerformanceItemUpdateData(intent.getLongExtra(EXTRA_ACCOUNT_ID, -1), intent.getIntExtra(EXTRA_DAYS_COUNT, -1));\n }\n\n}\nMockTradeApp/src/main/java/com/balch/mocktrade/account/Account.java\npublic class Account extends DomainObject implements Parcelable {\n\n static final String FLD_STRATEGY = \"strategy\";\n static final String FLD_NAME = \"name\";\n\n @ColumnEdit(order = 1, labelResId = R.string.account_name_label, hints = {\"MAX_CHARS=32\",\"NOT_EMPTY=true\"})\n @ColumnNew(order = 1, labelResId = R.string.account_name_label, hints = {\"MAX_CHARS=32\",\"NOT_EMPTY=true\"})\n private String name;\n\n @ColumnEdit(order = 2, labelResId = R.string.account_description_label, hints = {\"MAX_CHARS=256\",\"DISPLAY_LINES=2\"})\n @ColumnNew(order = 2, labelResId = R.string.account_description_label, hints = {\"MAX_CHARS=256\",\"DISPLAY_LINES=2\"})\n private String description;\n\n @ColumnEdit(order = 3, labelResId = R.string.account_init_balance_label, state = EditState.READONLY, hints = {\"NON_NEGATIVE=true\",\"HIDE_CENTS=true\"})\n @ColumnNew(order = 3, labelResId = R.string.account_init_balance_label, hints = {\"NON_NEGATIVE=true\",\"HIDE_CENTS=true\"})\n private Money initialBalance;\n\n @ColumnEdit(order = 4, labelResId = R.string.account_strategy_label, state = EditState.READONLY)\n @ColumnNew(order = 4,labelResId = R.string.account_strategy_label)\n private Strategy strategy;\n\n private Money availableFunds;\n\n @ColumnEdit(order = 5, labelResId = R.string.account_exclude_from_totals_label, state = EditState.READONLY)\n @ColumnNew(order = 5,labelResId = R.string.account_exclude_from_totals_label)\n private Boolean excludeFromTotals;\n\n public Account() {\n this(\"\", \"\", new Money(0), Strategy.NONE, false);\n }\n\n public Account(String name, String description, Money initialBalance, Strategy strategy, boolean excludeFromTotals) {\n this(name, description, initialBalance, initialBalance.clone(), strategy, excludeFromTotals);\n }\n\n public Account(String name, String description, Money initialBalance, Money availableFunds,\n Strategy strategy, boolean excludeFromTotals) {\n this.name = name;\n this.description = description;\n this.initialBalance = initialBalance;\n this.availableFunds = availableFunds;\n this.strategy = strategy;\n this.excludeFromTotals = excludeFromTotals;\n }\n\n\n protected Account(Parcel in) {\n super(in);\n name = in.readString();\n description = in.readString();\n initialBalance = in.readParcelable(Money.class.getClassLoader());\n strategy = Strategy.valueOf(in.readString());\n availableFunds = in.readParcelable(Money.class.getClassLoader());\n excludeFromTotals = (in.readByte() == 1) ? Boolean.TRUE : Boolean.FALSE;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n dest.writeString(name);\n dest.writeString(description);\n dest.writeParcelable(initialBalance, flags);\n dest.writeString(strategy.name());\n dest.writeParcelable(availableFunds, flags);\n dest.writeByte(((excludeFromTotals != null) && excludeFromTotals.equals(Boolean.TRUE)) ? (byte)1 : 0);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n @Override\n public Account createFromParcel(Parcel in) {\n return new Account(in);\n }\n\n @Override\n public Account[] newArray(int size) {\n return new Account[size];\n }\n };\n\n public void aggregate(Account account) {\n this.initialBalance.add(account.initialBalance);\n this.availableFunds.add(account.availableFunds);\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Money getInitialBalance() {\n return initialBalance;\n }\n\n public void setInitialBalance(Money initialBalance) {\n this.initialBalance = initialBalance;\n }\n\n public Money getAvailableFunds() {\n return availableFunds;\n }\n\n public void setAvailableFunds(Money availableFunds) {\n this.availableFunds = availableFunds;\n }\n\n public Strategy getStrategy() {\n return strategy;\n }\n\n public void setStrategy(Strategy strategy) {\n this.strategy = strategy;\n }\n\n public Boolean getExcludeFromTotals() {\n return excludeFromTotals;\n }\n\n public void setExcludeFromTotals(Boolean excludeFromTotals) {\n this.excludeFromTotals = excludeFromTotals;\n }\n\n public PerformanceItem getPerformanceItem(List investments, Date timestamp) {\n Money currentBalance = new Money(this.getAvailableFunds().getMicroCents());\n Money todayChange = new Money(0);\n\n if (investments != null) {\n for (Investment i : investments) {\n currentBalance.add(i.getValue());\n\n if (i.isPriceCurrent()) {\n todayChange.add(Money.subtract(i.getValue(),i.getPrevDayValue()));\n }\n }\n }\n\n return new PerformanceItem(this.getId(), timestamp, this.initialBalance, currentBalance, todayChange);\n }\n\n @Override\n public String toString() {\n return \"Account{\" +\n \"name='\" + name + '\\'' +\n \", description='\" + description + '\\'' +\n \", initialBalance=\" + initialBalance +\n \", availableFunds=\" + availableFunds +\n \", strategy=\" + strategy +\n \", excludeFromTotals=\" + excludeFromTotals +\n '}';\n }\n\n public enum Strategy implements MetadataUtils.EnumResource {\n NONE(null),\n DOGS_OF_THE_DOW(DogsOfTheDow.class),\n TRIPLE_MOMENTUM(TripleMomentum.class);\n\n protected final Class strategyClazz;\n\n Strategy(Class strategyClazz) {\n this.strategyClazz = strategyClazz;\n }\n\n public Class getStrategyClazz() {\n return strategyClazz;\n }\n\n @Override\n public int getListResId() {\n return R.array.account_strategy_display_values;\n }\n }\n\n\n}\nMockTradeApp/src/main/java/com/balch/mocktrade/services/QuoteService.java\npublic class QuoteService extends IntentService {\n private static final String TAG = QuoteService.class.getSimpleName();\n\n public static final int SNAPSHOT_DAYS_TO_KEEP = 3650;\n\n public QuoteService() {\n super(QuoteService.class.getName());\n }\n\n @Override\n protected void onHandleIntent(final Intent intent) {\n\n try {\n Log.i(TAG, \"QuoteService onHandleIntent\");\n\n // get the investment list from the db\n TradeModelProvider modelProvider = ((TradeModelProvider) this.getApplication());\n FinanceModel financeModel = modelProvider.getFinanceModel();\n final PortfolioModel portfolioModel = new PortfolioSqliteModel(modelProvider.getContext(),\n modelProvider.getSqlConnection(),\n financeModel,\n modelProvider.getSettings());\n final List investments = portfolioModel.getAllInvestments();\n Settings settings = ((TradeModelProvider) this.getApplication()).getSettings();\n\n if (investments.size() > 0) {\n final List accounts = portfolioModel.getAccounts(true);\n\n final LongSparseArray> accountIdToInvestmentMap = new LongSparseArray<>(accounts.size());\n List symbols = new ArrayList<>(investments.size());\n for (Investment i : investments) {\n symbols.add(i.getSymbol());\n\n // aggregate investments by account\n List list = accountIdToInvestmentMap.get(i.getAccount().getId());\n if (list == null) {\n list = new ArrayList<>();\n accountIdToInvestmentMap.put(i.getAccount().getId(), list);\n }\n list.add(i);\n }\n\n // get quotes over the wire\n try {\n Map quoteMap = financeModel.getQuotes(symbols).blockingFirst();\n if (quoteMap != null) {\n boolean newHasQuotes = false;\n for (Investment i : investments) {\n try {\n Quote quote = quoteMap.get(i.getSymbol());\n if (quote != null) {\n if (quote.getLastTradeTime().after(i.getLastTradeTime())) {\n newHasQuotes = true;\n i.setPrevDayClose(quote.getPreviousClose());\n i.setPrice(quote.getPrice(), quote.getLastTradeTime());\n portfolioModel.updateInvestment(i);\n }\n }\n } catch (Exception ex) {\n Log.e(TAG, \"updateInvestment exception\", ex);\n }\n }\n\n boolean isFirstSyncOfDay = !DateUtils.isToday(settings.getLastSyncTime());\n if (isFirstSyncOfDay) {\n portfolioModel.purgeSnapshots(SNAPSHOT_DAYS_TO_KEEP);\n }\n\n if (newHasQuotes) {\n portfolioModel.createSnapshotTotals(accounts, accountIdToInvestmentMap);\n }\n\n processAccountStrategies(accounts, accountIdToInvestmentMap, quoteMap, isFirstSyncOfDay);\n\n settings.setLastSyncTime(System.currentTimeMillis());\n\n startService(WearSyncService.getIntent(getApplicationContext()));\n }\n } catch (Exception ex1) {\n Log.e(TAG, \"updateInvestment exception\", ex1);\n\n }\n }\n\n // if the market is closed reset alarm to next market open time\n if (!financeModel.isInPollTime()) {\n TradeApplication.backupDatabase(getApplicationContext(), true);\n financeModel.setQuoteServiceAlarm();\n }\n\n } catch (Exception ex) {\n Log.e(TAG, \"financeModel.getQuotes(symbols exception\", ex);\n } finally {\n PortfolioUpdateBroadcaster.broadcast(QuoteService.this);\n QuoteReceiver.completeWakefulIntent(intent);\n }\n }\n\n public static Intent getIntent(Context context) {\n return new Intent(context, QuoteService.class);\n }\n\n protected void processAccountStrategies(List accounts,\n LongSparseArray> accountIdToInvestmentMap,\n Map quoteMap, boolean doDailyUpdate) {\n for (Account account : accounts) {\n Class strategyClazz = account.getStrategy().getStrategyClazz();\n if (strategyClazz != null) {\n try {\n TradeModelProvider modelProvider = ((TradeModelProvider)this.getApplication());\n BaseStrategy strategy = BaseStrategy.createStrategy(strategyClazz,\n modelProvider.getContext(),\n modelProvider.getFinanceModel(),\n modelProvider.getSqlConnection(),\n modelProvider.getSettings());\n if (doDailyUpdate) {\n strategy.dailyUpdate(account, accountIdToInvestmentMap.get(account.getId()), quoteMap);\n }\n strategy.pollUpdate(account, accountIdToInvestmentMap.get(account.getId()), quoteMap);\n } catch (Exception ex) {\n Log.e(TAG, \"Error calling strategy.pollUpdate\", ex);\n }\n }\n }\n }\n\n}\nAppFramework/src/main/java/com/balch/android/app/framework/PresenterActivity.java\npublic abstract class PresenterActivity\n extends AppCompatActivity {\n private static final String TAG = PresenterActivity.class.getSimpleName();\n\n private String className;\n\n protected P presenter;\n\n /**\n * Override abstract method to create a view of type V used by the Presenter.\n * The view id will be managed by this class if not specified\n * @return View containing view logic in the MVP pattern\n */\n protected abstract V createView();\n\n protected abstract P createPresenter(V view);\n\n // override-able activity functions\n public void onCreateBase(Bundle savedInstanceState) {\n }\n\n public void onResumeBase() {\n }\n\n public void onPauseBase() {\n }\n\n public void onStartBase() {\n }\n\n public void onStopBase() {\n }\n\n public void onDestroyBase() {\n }\n\n public void onSaveInstanceStateBase(Bundle outState) {\n }\n\n public void onActivityResultBase(int requestCode, int resultCode, Intent data) {\n }\n\n public boolean onHandleException(String logMsg, Exception ex) {\n return false;\n }\n\n public PresenterActivity() {\n this.className = this.getClass().getSimpleName();\n }\n\n private boolean handleException(String logMsg, Exception ex) {\n Log.e(TAG, logMsg, ex);\n return onHandleException(logMsg, ex);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n final protected void onCreate(Bundle savedInstanceState) {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" OnCreate - Begin\");\n try {\n super.onCreate(savedInstanceState);\n V view = this.createView();\n\n this.setContentView(view);\n\n Application application = getApplication();\n if (!(application instanceof ModelProvider)) {\n throw new IllegalStateException(\"Android Application object must be derived from Model Provider\");\n }\n\n presenter = this.createPresenter(view);\n\n this.onCreateBase(savedInstanceState);\n\n } catch (Exception ex) {\n if (!handleException(\"OnCreate \", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" OnCreate - End (ms):\" + sw.stop());\n }\n\n @Override\n final public void onStart() {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" onStart - Begin\");\n try {\n super.onStart();\n onStartBase();\n } catch (Exception ex) {\n if (!handleException(\"onStart \", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" onStart - End (ms):\" + sw.stop());\n }\n\n @Override\n final public void onResume() {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" onResume - Begin\");\n try {\n super.onResume();\n onResumeBase();\n } catch (Exception ex) {\n if (!handleException(\"onResume \", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" onResume - End (ms):\" + sw.stop());\n }\n\n @Override\n final public void onSaveInstanceState(Bundle outState) {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" onSaveInstanceState - Begin\");\n try {\n super.onSaveInstanceState(outState);\n onSaveInstanceStateBase(outState);\n } catch (Exception ex) {\n if (!handleException(\"onSaveInstanceState \", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" onSaveInstanceState - End (ms):\" + sw.stop());\n }\n\n @Override\n final public void onPause() {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" onPause - Begin\");\n try {\n onPauseBase();\n super.onPause();\n } catch (Exception ex) {\n if (!handleException(\"onPause \", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" onPause - End (ms):\" + sw.stop());\n }\n\n @Override\n final public void onStop() {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" onStop - Begin\");\n\n try {\n onStopBase();\n super.onStop();\n } catch (Exception ex) {\n if (!handleException(\"onStop\", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" onStop - End (ms):\" + sw.stop());\n }\n\n @Override\n final public void onDestroy() {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" onDestroy - Begin\");\n try {\n onDestroyBase();\n presenter.cleanup();\n presenter = null;\n } catch (Exception ex) {\n if (!handleException(\"onDestroy\", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" onDestroy - End (ms):\" + sw.stop());\n super.onDestroy();\n }\n\n @Override\n final public void onActivityResult(int requestCode, int resultCode, Intent data) {\n StopWatch sw = StopWatch.newInstance();\n Log.d(TAG, this.className + \" onActivityResult - Begin\");\n super.onActivityResult(requestCode, resultCode, data);\n try {\n onActivityResultBase(requestCode, resultCode, data);\n } catch (Exception ex) {\n if (!handleException(\"onActivityResult\", ex)) {\n throw ex;\n }\n }\n Log.i(TAG, this.className + \" onActivityResult - End (ms):\" + sw.stop());\n }\n\n public Snackbar getSnackbar(View parent, String msg, int length) {\n return Snackbar.make(parent, msg, length);\n }\n\n public Snackbar getSnackbar(View parent, String msg, int length,\n @ColorRes int backgroundColorId) {\n Snackbar snackbar = getSnackbar(parent, msg, length);\n ViewGroup group = (ViewGroup) snackbar.getView();\n group.setBackgroundColor(ContextCompat.getColor(this, backgroundColorId));\n return snackbar;\n }\n\n /**\n * TODO: figure out why android.support.design.R.id.snackbar_text\n * does not resolve in aar\n */\n public Snackbar getSnackbar(View parent, String msg, int length,\n @ColorRes int backgroundColorId,\n @ColorRes int textColorId,\n @IdRes int snackBarTextId) {\n Snackbar snackbar = getSnackbar(parent, msg, length, backgroundColorId);\n ViewGroup group = (ViewGroup) snackbar.getView();\n\n ((TextView) group.findViewById(snackBarTextId))\n .setTextColor(ContextCompat.getColor(this, textColorId));\n\n return snackbar;\n }\n\n}\nMockTradeApp/src/main/java/com/balch/mocktrade/settings/SettingsActivity.java\npublic class SettingsActivity extends AppCompatActivity\n implements SharedPreferences.OnSharedPreferenceChangeListener {\n\n\n public static Intent newIntent(Context context) {\n return new Intent(context, SettingsActivity.class);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.settings_view);\n\n Toolbar toolbar = (Toolbar) findViewById(R.id.settings_view_toolbar);\n setSupportActionBar(toolbar);\n\n ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setDisplayHomeAsUpEnabled(true);\n actionBar.setDisplayShowHomeEnabled(true);\n }\n\n getFragmentManager().beginTransaction().replace(R.id.settings_view_content_frame, new SettingsPreferenceFragment()).commit();\n }\n\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {\n Settings.Key settingKey = Settings.Key.fromKey(key);\n if (settingKey == Settings.Key.PREF_POLL_INTERVAL) {\n TradeModelProvider modelProvider = ((TradeModelProvider) this.getApplication());\n FinanceModel financeModel = modelProvider.getFinanceModel();\n financeModel.setQuoteServiceAlarm();\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onPause() {\n PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);\n super.onPause();\n }\n\n public static class SettingsPreferenceFragment extends PreferenceFragment {\n @Override\n public void onCreate(final Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n addPreferencesFromResource(R.xml.settings_pref_screen);\n\n PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference(\"settings_version\");\n preferenceGroup.setTitle(\"Version: \" + VersionUtils.getVersion(this.getActivity(), BuildConfig.DEBUG));\n\n }\n }\n}\nMockTradeApp/src/main/java/com/balch/mocktrade/order/OrderListActivity.java\npublic class OrderListActivity extends PresenterActivity {\n\n private static final String EXTRA_ACCOUNT_ID = \"EXTRA_ACCOUNT_ID\";\n\n public static Intent newIntent(Context context, long accountId) {\n Intent intent = new Intent(context, OrderListActivity.class);\n intent.putExtra(EXTRA_ACCOUNT_ID, accountId);\n return intent;\n }\n\n @Override\n public void onCreateBase(Bundle bundle) {\n\n Toolbar toolbar = findViewById(R.id.order_list_view_toolbar);\n setSupportActionBar(toolbar);\n\n ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setDisplayHomeAsUpEnabled(true);\n actionBar.setDisplayShowHomeEnabled(true);\n }\n\n presenter.reload(true);\n }\n\n @Override\n public OrderListView createView() {\n return new OrderListView(this);\n }\n\n @Override\n protected OrderPresenter createPresenter(OrderListView view) {\n return new OrderPresenter((TradeModelProvider) getApplication(),\n getOrderViewModel(), getIntent().getLongExtra(EXTRA_ACCOUNT_ID, 0),\n this, view, new OrderPresenter.ActivityBridge() {\n @Override\n public void showProgress(boolean show) {\n OrderListActivity.this.showProgress(show);\n }\n\n @Override\n public void finish() {\n OrderListActivity.this.finish();\n }\n });\n }\n\n public void showProgress(boolean show) {\n// this.progressBar.setVisibility(show ? View.VISIBLE: View.GONE);\n// this.refreshImageButton.setVisibility(show ? View.GONE : View.VISIBLE);\n }\n\n\n private OrderViewModel getOrderViewModel() {\n return ViewModelProviders.of(this).get(OrderViewModel.class);\n }\n}\nAppFramework/src/main/java/com/balch/android/app/framework/core/EditActivity.java\npublic class EditActivity extends PresenterActivity {\n protected static final String EXTRA_ISNEW = \"isNew\";\n protected static final String EXTRA_ITEM = \"item\";\n protected static final String EXTRA_VALIDATOR = \"validator\";\n protected static final String EXTRA_TITLE_RESID = \"titleResId\";\n protected static final String EXTRA_OK_BUTTON_RESID = \"okButtonResId\";\n protected static final String EXTRA_CANCEL_BUTTON_RESID = \"cancelButtonResId\";\n protected static final String EXTRA_RESULT = \"EditActivityResult\";\n\n protected static final String STATE_COLUMN_VIEW_IDS = \"col_view_ids\";\n\n protected ArrayList columnViewIDs = new ArrayList<>();\n\n protected ExternalController validator;\n protected DomainObject item;\n protected boolean isNew;\n protected int okButtonResId;\n protected int cancelButtonResId;\n\n @Override\n public void onCreateBase(Bundle savedInstanceState) {\n Intent intent = this.getIntent();\n int titleResId = intent.getIntExtra(EXTRA_TITLE_RESID, 0);\n if (titleResId != 0) {\n setTitle(titleResId);\n }\n\n Toolbar toolbar = findViewById(R.id.edit_view_toolbar);\n setSupportActionBar(toolbar);\n\n validator = intent.getParcelableExtra(EXTRA_VALIDATOR);\n item = intent.getParcelableExtra(EXTRA_ITEM);\n isNew = intent.getBooleanExtra(EXTRA_ISNEW, false);\n okButtonResId = intent.getIntExtra(EXTRA_OK_BUTTON_RESID, 0);\n cancelButtonResId = intent.getIntExtra(EXTRA_CANCEL_BUTTON_RESID, 0);\n\n if (savedInstanceState != null) {\n this.columnViewIDs = savedInstanceState.getIntegerArrayList(STATE_COLUMN_VIEW_IDS);\n }\n\n presenter.initialize(item, isNew, validator, okButtonResId, cancelButtonResId, columnViewIDs,\n new EditView.EditViewListener() {\n @Override\n public void onSave(DomainObject item) {\n Intent intent = getIntent();\n intent.putExtra(EXTRA_RESULT, item);\n setResult(RESULT_OK, intent);\n finish();\n }\n\n @Override\n public void onCancel() {\n Intent intent = getIntent();\n setResult(RESULT_CANCELED, intent);\n finish();\n }\n });\n }\n\n @Override\n public void onSaveInstanceStateBase(Bundle outState) {\n outState.putIntegerArrayList(STATE_COLUMN_VIEW_IDS, columnViewIDs);\n }\n\n @Override\n public EditView createView() {\n return new EditView(this);\n }\n\n @Override\n protected EditPresenter createPresenter(EditView view) {\n return new EditPresenter(view);\n }\n\n public static Intent getIntent(Context context, int titleResId, DomainObject domainObject, ExternalController externalController,\n int okButtonResId, int cancelButtonResId) {\n Intent intent = new Intent(context, EditActivity.class);\n\n intent.putExtra(EXTRA_ISNEW, (domainObject.getId() == null));\n intent.putExtra(EXTRA_ITEM, domainObject);\n intent.putExtra(EXTRA_VALIDATOR, externalController);\n intent.putExtra(EXTRA_TITLE_RESID, titleResId);\n intent.putExtra(EXTRA_OK_BUTTON_RESID, okButtonResId);\n intent.putExtra(EXTRA_CANCEL_BUTTON_RESID, cancelButtonResId);\n\n return intent;\n }\n\n public static T getResult(Intent intent) {\n return (T) intent.getParcelableExtra(EXTRA_RESULT);\n }\n}\nAppFramework/src/main/java/com/balch/android/app/framework/types/Money.java\npublic class Money implements Cloneable, Parcelable, Comparable {\n private static final String TAG = Money.class.getSimpleName();\n\n protected static final int DOLLAR_TO_MICRO_CENT = 10000;\n\n // $1 = 10000mc\n private long microCents;\n private Currency currency = Currency.getInstance(\"USD\");\n\n public Money() {\n this(0L);\n }\n\n public Money(long microCents) {\n this.setMicroCents(microCents);\n }\n\n public Money(double dollars) {\n this.setDollars(dollars);\n }\n\n public Money(String dollars) {\n this.setDollars(dollars);\n }\n\n protected Money(Parcel in) {\n microCents = in.readLong();\n currency = Currency.getInstance(in.readString());\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeLong(microCents);\n dest.writeString(currency.getCurrencyCode());\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n @Override\n public Money createFromParcel(Parcel in) {\n return new Money(in);\n }\n\n @Override\n public Money[] newArray(int size) {\n return new Money[size];\n }\n };\n\n public long getMicroCents() {\n return microCents;\n }\n\n public void setMicroCents(long microCents) {\n this.microCents = microCents;\n }\n\n public double getDollars() {\n return microCents/(double)DOLLAR_TO_MICRO_CENT;\n }\n\n public void setDollars(double dollars) {\n this.microCents = (long)(dollars * DOLLAR_TO_MICRO_CENT);\n }\n\n public void setCurrency(Currency currency) {\n this.currency = currency;\n }\n\n public void setDollars(String dollars) {\n Double val = 0.0;\n\n if (!TextUtils.isEmpty(dollars)) {\n String symbol = getSymbol();\n if (dollars.startsWith(symbol)) {\n dollars = dollars.substring(symbol.length());\n }\n\n val = Double.valueOf(dollars.replace(\",\",\"\"));\n }\n this.setDollars(val);\n }\n\n public String getFormatted() {\n return getFormatted(2);\n }\n\n public Spannable getFormattedWithColor() {\n String sign = (microCents >= 0) ? \"+\" : \"-\";\n ForegroundColorSpan spanColor = new ForegroundColorSpan((microCents >= 0)? Color.GREEN:Color.RED);\n\n String val = String.format(Locale.getDefault(), \"%s%s%.02f\", sign, getSymbol(), Math.abs(microCents)/1000f);\n SpannableStringBuilder spanString = new SpannableStringBuilder(val);\n spanString.setSpan(spanColor, 0, val.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);\n\n return spanString;\n }\n\n\n public String getFormatted(int decimalPlaces) {\n double dollars = getDollars();\n\n StringBuilder patternBuilder = new StringBuilder(getSymbol());\n patternBuilder.append(\"#,##0\");\n\n if (decimalPlaces == 1) {\n patternBuilder.append(\".0\");\n } else if (decimalPlaces >= 2) {\n patternBuilder.append(\".00\");\n for (int x = 0 ; x < decimalPlaces - 2; x++) {\n patternBuilder.append(\"#\");\n }\n }\n\n String pattern = patternBuilder.toString();\n DecimalFormat format = new DecimalFormat(pattern + \";-\" + pattern);\n return format.format(dollars);\n }\n\n public String getSymbol() {\n return currency.getSymbol();\n }\n\n public String getCurrencyNoGroupSep(int decimalPlaces) {\n double dollars = getDollars();\n return String.format(\"%1$.0\"+decimalPlaces+\"f\", dollars);\n }\n\n public void multiply(long value) {\n this.microCents *= value;\n }\n\n public void add(Money money) {\n this.microCents += money.microCents;\n }\n\n public void subtract(Money money) {\n this.microCents -= money.microCents;\n }\n\n public static Money multiply(Money money, long quantity) {\n return new Money(money.microCents * quantity);\n }\n\n public static Money add(Money money1, Money money2) {\n return new Money(money1.microCents + money2.microCents);\n }\n\n public static Money subtract(Money money1, Money money2) {\n return new Money(money1.microCents - money2.microCents);\n }\n\n public Money clone() {\n Money clone = null;\n try {\n clone = (Money)super.clone();\n } catch (CloneNotSupportedException e) {\n Log.wtf(TAG, e);\n }\n return clone;\n }\n\n @Override\n public String toString() {\n return \"Money{\" +\n \"microCents=\" + microCents +\n \", currency=\" + getFormatted() +\n '}';\n }\n\n @Override\n public int compareTo(Money another) {\n int compare = 0;\n if (this.microCents != another.microCents) {\n compare = (this.microCents < another.microCents) ? -1 : 1;\n }\n return compare;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Money money = (Money) o;\n\n if (microCents != money.microCents) return false;\n return !(currency != null ? !currency.equals(money.currency) : money.currency != null);\n\n }\n\n @Override\n public int hashCode() {\n int result = (int) (microCents ^ (microCents >>> 32));\n result = 31 * result + (currency != null ? currency.hashCode() : 0);\n return result;\n }\n}\nMockTradeApp/src/main/java/com/balch/mocktrade/account/AccountEditController.java\npublic class AccountEditController implements ExternalController, Parcelable {\n public AccountEditController() {\n }\n\n @Override\n public void onChanged(Context context, ColumnDescriptor descriptor, Object value, ControlMap controlMap) throws ValidatorException {\n if (descriptor.getField().getName().equals(Account.FLD_STRATEGY)) {\n Account.Strategy strategy = (Account.Strategy)value;\n if (strategy != Account.Strategy.NONE) {\n String [] displayVals = context.getResources().getStringArray(strategy.getListResId());\n EditLayout control = controlMap.get(Account.FLD_NAME);\n control.setValue(displayVals[strategy.ordinal()]);\n }\n }\n }\n\n @Override\n public void validate(Context context, Account account, ControlMap controlMap) throws ValidatorException {\n }\n\n @Override\n public void initialize(Context context, Account account, ControlMap controlMap) {\n }\n\n private AccountEditController(Parcel in) {\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n @Override\n public AccountEditController createFromParcel(Parcel in) {\n return new AccountEditController(in);\n }\n\n @Override\n public AccountEditController[] newArray(int size) {\n return new AccountEditController[size];\n }\n };\n\n}\nMockTradeApp/src/main/java/com/balch/mocktrade/order/Order.java\npublic class Order extends DomainObject implements Parcelable {\n\n static final String FLD_LIMIT_PRICE = \"limitPrice\";\n static final String FLD_STOP_PRICE = \"stopPrice\";\n static final String FLD_STOP_PERCENT = \"stopPercent\";\n static final String FLD_SYMBOL = \"symbol\";\n static final String FLD_ACTION = \"action\";\n static final String FLD_STRATEGY = \"strategy\";\n static final String FLD_QUANTITY = \"quantity\";\n\n private Account account;\n\n @ColumnEdit(order = 1, state = EditState.READONLY, labelResId = R.string.order_symbol_label, hints = {\"MAX_CHARS=32\",\"NOT_EMPTY=true\"})\n @ColumnNew(order = 1, customControl = StockSymbolLayout.class, labelResId = R.string.order_symbol_label, hints = {\"MAX_CHARS=32\",\"NOT_EMPTY=true\"})\n private String symbol;\n\n private OrderStatus status;\n\n @ColumnEdit(order = 2, state = EditState.READONLY, labelResId = R.string.order_action_label)\n @ColumnNew(order = 2, state = EditState.READONLY, labelResId = R.string.order_action_label)\n private OrderAction action;\n\n @ColumnEdit(order = 3, state = EditState.READONLY, labelResId = R.string.order_strategy_label)\n @ColumnNew(order = 3, labelResId = R.string.order_strategy_label)\n private OrderStrategy strategy;\n\n private OrderDuration duration;\n\n @ColumnEdit(order = 4, labelResId = R.string.order_limit_price_label)\n @ColumnNew(order = 4, labelResId = R.string.order_limit_price_label, hints = {\"INIT_EMPTY=true\"})\n private Money limitPrice;\n\n @ColumnEdit(order = 5, labelResId = R.string.order_stop_price_label)\n @ColumnNew(order = 5, labelResId = R.string.order_stop_price_label, hints = {\"INIT_EMPTY=true\"})\n private Money stopPrice;\n\n @ColumnEdit(order = 6, labelResId = R.string.order_stop_percent_label, hints = {\"PERCENT=true\"})\n @ColumnNew(order = 6, labelResId = R.string.order_stop_percent_label, hints = {\"PERCENT=true\",\"INIT_EMPTY=true\"})\n private Double stopPercent;\n\n @ColumnEdit(order = 7, labelResId = R.string.order_quantity_label, customControl = QuantityPriceLayout.class)\n @ColumnNew(order = 7, labelResId = R.string.order_quantity_label, customControl = QuantityPriceLayout.class)\n private Long quantity;\n\n private Money highestPrice;\n\n public Order() {\n this.symbol = \"\";\n this.status = OrderStatus.OPEN;\n this.action = OrderAction.BUY;\n this.strategy = OrderStrategy.MARKET;\n this.duration = OrderDuration.GOOD_TIL_CANCELED;\n this.quantity = 0L;\n this.limitPrice = new Money(0);\n this.stopPrice = new Money(0);\n this.stopPercent = 0.0;\n this.highestPrice = new Money(0);\n }\n\n protected Order(Parcel in) {\n super(in);\n account = in.readParcelable(Account.class.getClassLoader());\n symbol = in.readString();\n status = (OrderStatus)in.readSerializable();\n action = (OrderAction) in.readSerializable();\n strategy = (OrderStrategy) in.readSerializable();\n duration = (OrderDuration) in.readSerializable();\n limitPrice = in.readParcelable(Money.class.getClassLoader());\n stopPrice = in.readParcelable(Money.class.getClassLoader());\n stopPercent = (Double)in.readSerializable();\n quantity = (Long)in.readSerializable();\n highestPrice = in.readParcelable(Money.class.getClassLoader());\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n dest.writeParcelable(account, flags);\n dest.writeString(symbol);\n dest.writeSerializable(status);\n dest.writeSerializable(action);\n dest.writeSerializable(strategy);\n dest.writeSerializable(duration);\n dest.writeParcelable(limitPrice, flags);\n dest.writeParcelable(stopPrice, flags);\n dest.writeSerializable(stopPercent);\n dest.writeSerializable(quantity);\n dest.writeParcelable(highestPrice, flags);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n @Override\n public Order createFromParcel(Parcel in) {\n return new Order(in);\n }\n\n @Override\n public Order[] newArray(int size) {\n return new Order[size];\n }\n };\n\n public Account getAccount() {\n return account;\n }\n\n public void setAccount(Account account) {\n this.account = account;\n }\n\n public String getSymbol() {\n return symbol;\n }\n\n public void setSymbol(String symbol) {\n this.symbol = symbol;\n }\n\n public OrderStatus getStatus() {\n return status;\n }\n\n public void setStatus(OrderStatus status) {\n this.status = status;\n }\n\n public OrderAction getAction() {\n return action;\n }\n\n public void setAction(OrderAction action) {\n this.action = action;\n }\n\n public OrderStrategy getStrategy() {\n return strategy;\n }\n\n public void setStrategy(OrderStrategy strategy) {\n this.strategy = strategy;\n }\n\n public OrderDuration getDuration() {\n return duration;\n }\n\n public void setDuration(OrderDuration duration) {\n this.duration = duration;\n }\n\n public Long getQuantity() {\n return quantity;\n }\n\n public Long getQuantityDelta() {\n return (this.action==OrderAction.BUY) ?\n this.quantity :\n -this.quantity;\n }\n\n public void setQuantity(Long quantity) {\n this.quantity = quantity;\n }\n\n public Money getLimitPrice() {\n return limitPrice;\n }\n\n public void setLimitPrice(Money limitPrice) {\n this.limitPrice = limitPrice;\n }\n\n public Double getStopPercent() {\n return stopPercent;\n }\n\n public void setStopPercent(Double stopPercent) {\n this.stopPercent = stopPercent;\n }\n\n public Money getStopPrice() {\n return stopPrice;\n }\n\n public void setStopPrice(Money stopPrice) {\n this.stopPrice = stopPrice;\n }\n\n public Money getHighestPrice() {\n return highestPrice;\n }\n\n public void setHighestPrice(Money highestPrice) {\n this.highestPrice = highestPrice;\n }\n\n public Money getCost(Money price) {\n return Money.multiply(price, this.getQuantityDelta());\n }\n\n public enum OrderStatus implements MetadataUtils.EnumResource {\n OPEN,\n FULFILLED,\n ERROR,\n CANCELED;\n\n @Override\n public int getListResId() {\n return R.array.order_status_display_values;\n }\n }\n\n public enum OrderAction implements MetadataUtils.EnumResource {\n BUY,\n SELL;\n\n @Override\n public int getListResId() {\n return R.array.order_type_display_values;\n }\n }\n\n private static final int FLAG_BUY = (1);\n private static final int FLAG_SELL = (1<<1);\n public enum OrderStrategy implements MetadataUtils.EnumResource {\n MARKET(FLAG_BUY | FLAG_SELL),\n MANUAL(FLAG_BUY | FLAG_SELL),\n LIMIT(FLAG_BUY | FLAG_SELL),\n STOP_LOSS(FLAG_SELL),\n TRAILING_STOP_AMOUNT_CHANGE(FLAG_SELL),\n TRAILING_STOP_PERCENT_CHANGE(FLAG_SELL);\n\n\n private int supportedActions;\n\n OrderStrategy(int flags) {\n this.supportedActions = flags;\n }\n\n @Override\n public int getListResId() {\n return R.array.order_strategy_display_values;\n }\n\n public boolean isBuySupported() {\n return ((this.supportedActions & FLAG_BUY) != 0);\n }\n\n public boolean isSellSupported() {\n return ((this.supportedActions & FLAG_SELL) != 0);\n }\n\n }\n\n enum OrderDuration implements MetadataUtils.EnumResource {\n GOOD_TIL_CANCELED,\n DAY;\n\n @Override\n public int getListResId() {\n return R.array.order_duration_display_values;\n }\n }\n\n}\n", "answers": [" public void startNewOrderActivity(Order order, @StringRes int stringId) {"], "length": 4161, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "dda77c779e73567603ed5a2bfecfd39905ac6f820c3cbd63"} {"input": "import android.util.Log;\nimport com.sonova.difian.communication.messaging.HiMuteStatus;\nimport com.sonova.difian.communication.messaging.HiSide;\nimport com.sonova.difian.communication.messaging.HiStatusMessage;\nimport com.sonova.difian.communication.messaging.Message;\nimport com.sonova.difian.communication.messaging.MessageReader;\nimport com.sonova.difian.communication.messaging.MessageReaderException;\nimport com.sonova.difian.communication.messaging.MessageType;\nimport com.sonova.difian.communication.messaging.MessageWriter;\nimport com.sonova.difian.communication.messaging.SmartMessage;\nimport com.sonova.difian.communication.messaging.SmartReplyMessage;\nimport com.sonova.difian.communication.messaging.StreamHelpers;\nimport com.sonova.difian.communication.messaging.TypingMessage;\nimport com.sonova.difian.communication.messaging.UserInfoMessage;\nimport com.sonova.difian.communication.messaging.UserInfoRequestMessage;\nimport com.sonova.difian.communication.utilities.SocketHelpers;\nimport com.sonova.difian.utilities.Contract;\nimport com.sonova.difian.utilities.StringHelpers;\nimport org.xmlpull.v1.XmlPullParserException;\nimport org.yaler.AcceptCallback;\nimport org.yaler.AcceptCallbackState;\nimport org.yaler.YalerSSLServerSocket;\nimport javax.net.SocketFactory;\nimport javax.net.ssl.SSLSocketFactory;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.AbstractList;\nimport java.util.ArrayDeque;\nimport java.util.ArrayList;\nimport java.util.Queue;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n if (id.equals(currentId))\n {\n handleMessage(message);\n }\n }\n }\n\n byte[] rspBytes = StringHelpers.convertToBytes(\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\");\n\n try\n {\n s.getOutputStream().write(rspBytes);\n }\n catch (IOException e)\n {\n Log.w(TAG, \"IOException while writing chat response.\", e);\n ok = false;\n }\n\n synchronized (_lockObject)\n {\n currentId = _id;\n }\n }\n\n synchronized (_lockObject)\n {\n try\n {\n s.close();\n }\n catch (IOException e)\n {\n Log.w(TAG, \"IOException while closing chat socket.\", e);\n }\n _rxChatSockets.remove(s);\n }\n }\n catch (Throwable t)\n {\n Log.e(TAG, \"Uncaught exception in startRx()\", t);\n throw new RuntimeException(t);\n }\n }\n }).start();\n }\n }\n\n private void handleMessage(Message message)\n {\n synchronized (_lockObject)\n {\n Contract.check(message != null);\n\n Log.i(TAG, String.format(\"Retrieved message: %s\", message));\n\n if (message.getType() == MessageType.USER_INFO)\n {\n _pendingAudiologistInfo = false;\n UserInfoMessage m = (UserInfoMessage)message;\n\n _audiologistInfo = new AudiologistInfo(m.getName(), m.getImage());\n }\n else if (message.getType() == MessageType.HI_STATUS)\n {\n HiStatusMessage m = (HiStatusMessage)message;\n\n HiMuteStatus newLeft = m.getMuteStatus(HiSide.LEFT);\n HiMuteStatus newRight = m.getMuteStatus(HiSide.RIGHT);\n\n if ((_muteStatusLeft != newLeft) && (_muteStatusRight != newRight) && (newLeft == newRight))\n {\n if (newLeft == HiMuteStatus.MUTED)\n {\n addMessage(new ChatMessage(ChatMessageSource.SYSTEM, ChatMessage.TEXT_HI_MUTED_BOTH));\n }\n else if (newLeft == HiMuteStatus.UNMUTED)\n {\n addMessage(new ChatMessage(ChatMessageSource.SYSTEM, ChatMessage.TEXT_HI_UNMUTED_BOTH));\n }\n }\n else\n {\n if (_muteStatusLeft != newLeft)\n {\n if (newLeft == HiMuteStatus.MUTED)\n {\n addMessage(new ChatMessage(ChatMessageSource.SYSTEM, ChatMessage.TEXT_HI_MUTED_LEFT));\n }\n else if (newLeft == HiMuteStatus.UNMUTED)\n {\n addMessage(new ChatMessage(ChatMessageSource.SYSTEM, ChatMessage.TEXT_HI_UNMUTED_LEFT));\n }\n }\n if (_muteStatusRight != newRight)\n {\n if (newRight == HiMuteStatus.MUTED)\n {\n addMessage(new ChatMessage(ChatMessageSource.SYSTEM, ChatMessage.TEXT_HI_MUTED_RIGHT));\n }\n else if (newRight == HiMuteStatus.UNMUTED)\n {\n addMessage(new ChatMessage(ChatMessageSource.SYSTEM, ChatMessage.TEXT_HI_UNMUTED_RIGHT));\n }\n }\n }\n\n _muteStatusLeft = newLeft;\n _muteStatusRight = newRight;\n }\n else if (message.getType() == MessageType.SMART)\n {\n SmartMessage m = (SmartMessage)message;\n\n addMessage(new ChatMessage(ChatMessageSource.AUDIOLOGIST, m));\n\n _isTyping = false;\n }\n else if (message.getType() == MessageType.TYPING)\n {", "context": "Difian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/MessageReaderException.java\n@SuppressWarnings(\"SerializableHasSerializationMethods\")\npublic final class MessageReaderException extends Exception\n{\n private static final long serialVersionUID = 1L;\n\n MessageReaderException()\n {\n }\n\n MessageReaderException(String message)\n {\n super(message);\n }\n\n MessageReaderException(String message, Throwable cause)\n {\n super(message, cause);\n }\n\n MessageReaderException(Throwable cause)\n {\n super(cause);\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/utilities/StringHelpers.java\npublic final class StringHelpers\n{\n private StringHelpers()\n {\n }\n\n public static byte[] convertToBytes(String source)\n {\n char[] chars = source.toCharArray();\n byte[] result = new byte[chars.length];\n for (int i = 0; i < chars.length; i++)\n {\n result[i] = (byte)chars[i];\n }\n return result;\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/MessageWriter.java\npublic final class MessageWriter\n{\n private static final String TAG = MessageWriter.class.getName();\n private static final MessageWriter _instance = new MessageWriter();\n\n private MessageWriter()\n {\n }\n\n public static MessageWriter getInstance()\n {\n return _instance;\n }\n\n @SuppressWarnings(\"UnnecessaryCodeBlock\")\n public void transmit(OutputStream stream, String host, String id, Message message) throws IOException\n {\n if (stream == null)\n {\n throw new IllegalArgumentException(\"stream == null in transmit\");\n }\n if (host == null)\n {\n throw new IllegalArgumentException(\"host == null\");\n }\n if (id == null)\n {\n throw new IllegalArgumentException(\"id == null\");\n }\n if (message == null)\n {\n throw new IllegalArgumentException(\"message == null\");\n }\n if ((message.getType() != MessageType.USER_INFO_REQUEST) && (message.getType() != MessageType.SMART_REPLY))\n {\n throw new IllegalArgumentException(String.format(\"Unsupported message type while writing: %s\", message.getType()));\n }\n\n StringWriter messageString = new StringWriter();\n\n XmlSerializer x = Xml.newSerializer();\n x.setOutput(messageString);\n\n // Prepare message.\n x.startDocument(\"ASCII\", true);\n {\n x.startTag(\"\", XmlConstants.MESSAGE);\n {\n x.attribute(\"\", \"v\", \"3\");\n //noinspection UnnecessaryToStringCall\n x.attribute(\"\", \"guid\", UUID.randomUUID().toString());\n x.attribute(\"\", \"date\", new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSS\", Locale.US).format(new Date()));\n if (message.getType() == MessageType.USER_INFO_REQUEST)\n {\n x.attribute(\"\", \"type\", \"user_info_request\");\n }\n else if (message.getType() == MessageType.SMART_REPLY)\n {\n x.attribute(\"\", \"type\", \"smart_reply\");\n\n SmartReplyMessage m = (SmartReplyMessage)message;\n\n if (m.getReMessage() != null)\n {\n x.attribute(\"\", XmlConstants.RE_MESSAGE_GUID, m.getReMessage().getGuid());\n }\n else\n {\n x.attribute(\"\", XmlConstants.RE_MESSAGE_GUID, \"00000000-0000-0000-0000-000000000000\");\n }\n\n String sel;\n String text;\n\n if (m.getSelectionCount() != 0)\n {\n StringBuilder selBuilder = new StringBuilder();\n StringBuilder textBuilder = new StringBuilder();\n for (int i = 0; i < m.getSelectionCount(); i++)\n {\n if (i != 0)\n {\n selBuilder.append(';');\n textBuilder.append(';');\n }\n selBuilder.append(m.getSelection(i).getId());\n textBuilder.append(m.getSelection(i).getText());\n }\n sel = selBuilder.toString();\n text = textBuilder.toString();\n }\n else\n {\n text = m.getReText();\n sel = \"\";\n }\n\n x.startTag(\"\", \"re_text\");\n {\n x.text(text);\n }\n x.endTag(\"\", \"re_text\");\n x.startTag(\"\", XmlConstants.SELECTION);\n {\n x.attribute(\"\", XmlConstants.OPTION_IDS, sel);\n }\n x.endTag(\"\", XmlConstants.SELECTION);\n }\n }\n x.endTag(\"\", XmlConstants.MESSAGE);\n }\n x.endDocument();\n\n String m = messageString.toString();\n Log.v(MessageWriter.class.getSimpleName(), m);\n\n // Send HTTP header.\n stream.write(String.format(\"PUT /%s_-1 HTTP/1.1\\r\\n\", id).getBytes());\n stream.write(\"Content-Type: text/xml; charset=utf-8\\r\\n\".getBytes());\n stream.write(String.format(\"Host: %s\\r\\n\", host).getBytes());\n stream.write(String.format(\"Content-Length: %d\\r\\n\", m.length()).getBytes());\n stream.write(\"\\r\\n\".getBytes());\n stream.write(m.getBytes());\n }\n}\nDifian/YalerAndroidLibrary/src/main/java/org/yaler/AcceptCallbackState.java\npublic enum AcceptCallbackState {\n Undefined,\n Accessible,\n Connected\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/Message.java\npublic abstract class Message\n{\n private String _guid;\n\n public abstract MessageType getType();\n\n public final void setGuid(String guid)\n {\n _guid = guid;\n }\n\n public final String getGuid()\n {\n return _guid;\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/MessageType.java\npublic enum MessageType\n{\n USER_INFO_REQUEST, USER_INFO, SMART, SMART_REPLY, ALERT, ALERT_REPLY, FD_STATUS, HI_STATUS, TYPING\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/UserInfoMessage.java\npublic final class UserInfoMessage extends Message\n{\n private String _name;\n private String _lang;\n private String _text;\n private String _image;\n\n UserInfoMessage(XmlPullParser parser) throws MessageReaderException, XmlPullParserException, IOException\n {\n parser.nextTag();\n parser.require(XmlPullParser.START_TAG, null, XmlConstants.USER_NAME);\n setName(parser.nextText());\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.USER_NAME);\n while (parser.nextTag() == XmlPullParser.START_TAG)\n {\n if (XmlConstants.USER_LANG.equals(parser.getName()))\n {\n setLang(parser.nextText());\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.USER_LANG);\n }\n else if (XmlConstants.USER_TEXT.equals(parser.getName()))\n {\n setText(parser.nextText());\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.USER_TEXT);\n }\n else if (XmlConstants.IMAGE_BASE64.equals(parser.getName()))\n {\n setImage(parser.nextText());\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.IMAGE_BASE64);\n }\n else\n {\n throw new MessageReaderException(\"Invalid tag in \\\"user_info\\\" .\");\n }\n }\n }\n\n @Override\n public MessageType getType()\n {\n return MessageType.USER_INFO;\n }\n\n public String getName()\n {\n return _name;\n }\n\n private void setName(String name)\n {\n _name = name;\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public String getLang()\n {\n return _lang;\n }\n\n private void setLang(String lang)\n {\n _lang = lang;\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public String getText()\n {\n return _text;\n }\n\n private void setText(String text)\n {\n _text = text;\n }\n\n public String getImage()\n {\n return _image;\n }\n\n private void setImage(String image)\n {\n _image = image;\n }\n}\nDifian/YalerAndroidLibrary/src/main/java/org/yaler/AcceptCallback.java\npublic interface AcceptCallback {\n void statusChanged(AcceptCallbackState state);\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/HiStatusMessage.java\npublic final class HiStatusMessage extends Message\n{\n private final HiConnectionStatus[] _status = new HiConnectionStatus[2];\n private final HiMuteStatus[] _muteStatus = new HiMuteStatus[2];\n\n HiStatusMessage(XmlPullParser parser) throws MessageReaderException, XmlPullParserException, IOException\n {\n for (int i = 0; i < 2; i++)\n {\n parser.nextTag();\n parser.require(XmlPullParser.START_TAG, null, XmlConstants.HI);\n\n String sideString = parser.getAttributeValue(null, XmlConstants.SIDE);\n HiSide side;\n if (XmlConstants.LEFT.equals(sideString))\n {\n side = HiSide.LEFT;\n }\n else if (XmlConstants.RIGHT.equals(sideString))\n {\n side = HiSide.RIGHT;\n }\n else\n {\n throw new MessageReaderException(String.format(\"Invalid side in \\\"hi_status\\\" : \\\"%s\\\".\", sideString));\n }\n\n String statusString = parser.getAttributeValue(null, XmlConstants.STATUS);\n HiConnectionStatus status;\n if (XmlConstants.CONNECTED.equals(statusString))\n {\n status = HiConnectionStatus.CONNECTED;\n }\n else if (XmlConstants.DISCONNECTED.equals(statusString))\n {\n status = HiConnectionStatus.DISCONNECTED;\n }\n else if (XmlConstants.NOT_CONNECTED.equals(statusString))\n {\n status = HiConnectionStatus.NOT_CONNECTED;\n }\n else if (XmlConstants.UNDEFINED.equals(statusString))\n {\n status = HiConnectionStatus.UNDEFINED;\n }\n else\n {\n throw new MessageReaderException(\"Invalid status in \\\"hi_status\\\" .\");\n }\n\n String muteStatusString = parser.getAttributeValue(null, XmlConstants.MUTE_STATUS);\n HiMuteStatus muteStatus;\n if (XmlConstants.MUTED.equals(muteStatusString))\n {\n muteStatus = HiMuteStatus.MUTED;\n }\n else if (XmlConstants.UNMUTED.equals(muteStatusString))\n {\n muteStatus = HiMuteStatus.UNMUTED;\n }\n else if (XmlConstants.UNDEFINED.equals(muteStatusString))\n {\n muteStatus = HiMuteStatus.UNDEFINED;\n }\n else\n {\n throw new MessageReaderException(\"Invalid mute_status in \\\"hi_status\\\" .\");\n }\n\n setStatus(side, status);\n setMuteStatus(side, muteStatus);\n\n parser.nextTag();\n parser.require(XmlPullParser.END_TAG, null, \"hi\");\n }\n }\n\n @Override\n public MessageType getType()\n {\n return MessageType.HI_STATUS;\n }\n\n public HiConnectionStatus getStatus(HiSide side)\n {\n HiConnectionStatus result = _status[side.ordinal()];\n return (result != null) ? result : HiConnectionStatus.UNDEFINED;\n }\n\n private void setStatus(HiSide side, HiConnectionStatus status)\n {\n _status[side.ordinal()] = status;\n }\n\n public HiMuteStatus getMuteStatus(HiSide side)\n {\n HiMuteStatus result = _muteStatus[side.ordinal()];\n return (result != null) ? result : HiMuteStatus.UNDEFINED;\n }\n\n private void setMuteStatus(HiSide side, HiMuteStatus muteStatus)\n {\n _muteStatus[side.ordinal()] = muteStatus;\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/SmartMessage.java\npublic final class SmartMessage extends Message\n{\n private String _text;\n private String _image;\n private SmartMessageOptionsType _optionsType;\n private final List _options = new ArrayList();\n\n SmartMessage(XmlPullParser parser) throws MessageReaderException, XmlPullParserException, IOException\n {\n while (parser.nextTag() == XmlPullParser.START_TAG)\n {\n if (\"text\".equals(parser.getName()))\n {\n setText(parser.nextText());\n parser.require(XmlPullParser.END_TAG, null, \"text\");\n }\n else if (XmlConstants.IMAGE_BASE64.equals(parser.getName()))\n {\n setImage(parser.nextText());\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.IMAGE_BASE64);\n }\n else if (XmlConstants.OPTIONS.equals(parser.getName()))\n {\n String optionsType = parser.getAttributeValue(null, \"type\");\n if (\"button\".equals(optionsType))\n {\n setOptionsType(SmartMessageOptionsType.BUTTON);\n }\n else if (\"radio\".equals(optionsType))\n {\n setOptionsType(SmartMessageOptionsType.RADIO);\n }\n else if (\"checkbox\".equals(optionsType))\n {\n setOptionsType(SmartMessageOptionsType.CHECKBOX);\n }\n else if (\"text\".equals(optionsType))\n {\n setOptionsType(SmartMessageOptionsType.TEXT);\n }\n else\n {\n throw new MessageReaderException(\"Invalid type in \\\"smart\\\" \\\"options\\\".\");\n }\n\n while (parser.nextTag() == XmlPullParser.START_TAG)\n {\n if (XmlConstants.OPTION.equals(parser.getName()))\n {\n String optionId = parser.getAttributeValue(null, \"id\");\n String optionText = null;\n String optionImage = null;\n if ((optionId == null) || !optionId.matches(\"^[a-z0-9]+$\"))\n {\n throw new MessageReaderException(String.format(\"Invalid option id: %s.\", optionId));\n }\n while (parser.nextTag() == XmlPullParser.START_TAG)\n {\n if (\"text\".equals(parser.getName()))\n {\n optionText = parser.nextText();\n parser.require(XmlPullParser.END_TAG, null, \"text\");\n }\n else if (XmlConstants.IMAGE_BASE64.equals(parser.getName()))\n {\n optionImage = parser.nextText();\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.IMAGE_BASE64);\n }\n else\n {\n throw new MessageReaderException(\"Invalid tag in \\\"smart\\\" \\\"option\\\".\");\n }\n }\n if (optionText == null)\n {\n throw new MessageReaderException(\"No option text in \\\"smart\\\" .\");\n }\n addOption(new SmartMessageOption(optionId, optionText, optionImage));\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.OPTION);\n }\n else\n {\n throw new MessageReaderException(\"Invalid tag in \\\"smart\\\" \\\"options\\\".\");\n }\n }\n parser.require(XmlPullParser.END_TAG, null, XmlConstants.OPTIONS);\n }\n else\n {\n throw new MessageReaderException(\"Invalid tag in \\\"smart\\\" .\");\n }\n }\n if (getText() == null)\n {\n throw new MessageReaderException(\"No text in \\\"smart\\\" .\");\n }\n }\n\n @Override\n public MessageType getType()\n {\n return MessageType.SMART;\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public String getText()\n {\n return _text;\n }\n\n private void setText(String text)\n {\n _text = text;\n }\n\n public String getImage()\n {\n return _image;\n }\n\n private void setImage(String image)\n {\n _image = image;\n }\n\n public SmartMessageOptionsType getOptionsType()\n {\n return _optionsType;\n }\n\n private void setOptionsType(SmartMessageOptionsType optionsType)\n {\n _optionsType = optionsType;\n }\n\n public int getOptionsCount()\n {\n return _options.size();\n }\n\n public SmartMessageOption getOption(int id)\n {\n return _options.get(id);\n }\n\n private void addOption(SmartMessageOption option)\n {\n _options.add(option);\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/HiSide.java\npublic enum HiSide\n{\n LEFT, RIGHT\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/UserInfoRequestMessage.java\npublic final class UserInfoRequestMessage extends Message\n{\n @Override\n public MessageType getType()\n {\n return MessageType.USER_INFO_REQUEST;\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/StreamHelpers.java\npublic final class StreamHelpers\n{\n private static final String TAG = StreamHelpers.class.getName();\n\n private StreamHelpers()\n {\n }\n\n public static String readLine(InputStream stream) throws IOException\n {\n if (stream == null)\n {\n throw new IllegalArgumentException(\"stream == null in readLine\");\n }\n StringBuilder line = new StringBuilder();\n int b;\n do\n {\n b = stream.read();\n if (b != -1)\n {\n if (line.length() < 4096)\n {\n line.append((char)b);\n } else {\n throw new IOException(\"line too long\", null);\n }\n }\n else\n {\n throw new IOException(\"unexpected end of stream\", null);\n }\n } while (b != '\\n');\n String result;\n if ((line.length() >= 2) && (line.charAt(line.length() - 2) == '\\r')) {\n result = line.substring(0, line.length() - 2).trim();\n } else {\n result = line.substring(0, line.length() - 1).trim();\n }\n return result;\n }\n\n public static boolean consumeHttpHeaders (InputStream stream) throws IOException\n {\n boolean continueExpected = false;\n String line = readLine(stream);\n while (!line.equals(\"\"))\n {\n Log.v(TAG, line);\n if (line.equals(\"Expect: 100-continue\"))\n {\n continueExpected = true;\n }\n line = readLine(stream);\n }\n return continueExpected;\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/utilities/Contract.java\npublic final class Contract\n{\n private Contract()\n {\n }\n\n @SuppressWarnings(\"NonBooleanMethodNameMayNotStartWithQuestion\")\n public static void check(boolean condition)\n {\n if (!condition)\n {\n throw new AssertionError();\n }\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/utilities/SocketHelpers.java\npublic final class SocketHelpers\n{\n private SocketHelpers()\n {\n }\n\n public static Socket createSocket(SocketFactory factory, int soTimeout)\n {\n Socket result = null;\n try\n {\n result = factory.createSocket();\n }\n catch (IOException e)\n {\n Log.e(SocketHelpers.class.getSimpleName(), \"Exception while creating socket.\", e);\n throw new RuntimeException(e);\n }\n\n try\n {\n result.setSoTimeout(soTimeout);\n }\n catch (SocketException e)\n {\n Log.e(SocketHelpers.class.getSimpleName(), \"Exception while setting socket timeout.\", e);\n throw new RuntimeException(e);\n }\n\n try\n {\n result.setTcpNoDelay(true);\n }\n catch (SocketException e)\n {\n Log.e(SocketHelpers.class.getSimpleName(), \"Exception while setting TcpNoDelay option.\", e);\n throw new RuntimeException(e);\n }\n\n return result;\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/SmartReplyMessage.java\npublic final class SmartReplyMessage extends Message\n{\n private final String _reText;\n\n private final SmartMessage _reMessage;\n private final List _selection = new ArrayList();\n\n private final ChatMessage _message;\n\n public SmartReplyMessage(ChatMessage message)\n {\n Contract.check(message != null);\n _message = message;\n\n if (message.getMessage() == null)\n {\n _reText = message.getText();\n _reMessage = null;\n }\n else\n {\n _reText = null;\n _reMessage = message.getMessage();\n for (SmartMessageOption o : message.getSelection())\n {\n addSelection(o);\n }\n }\n }\n\n @Override\n public MessageType getType()\n {\n return MessageType.SMART_REPLY;\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public void addSelection(SmartMessageOption selection)\n {\n Contract.check(_reMessage != null);\n\n _selection.add(selection);\n }\n\n public String getReText()\n {\n return _reText;\n }\n\n public SmartMessage getReMessage()\n {\n return _reMessage;\n }\n\n public int getSelectionCount()\n {\n return _selection.size();\n }\n\n public SmartMessageOption getSelection(int id)\n {\n return _selection.get(id);\n }\n\n public void ack()\n {\n _message.ack();\n }\n\n public void retry()\n {\n _message.retry();\n }\n\n public boolean isFailed()\n {\n return _message.isFailed();\n }\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/MessageReader.java\npublic final class MessageReader\n{\n private static final String TAG = MessageReader.class.getName();\n\n private static final MessageReader _instance = new MessageReader();\n\n public static MessageReader getInstance()\n {\n return _instance;\n }\n\n private MessageReader()\n {\n }\n\n public Message parse(InputStream stream) throws XmlPullParserException, IOException, MessageReaderException\n {\n if (stream == null)\n {\n throw new IllegalArgumentException(\"stream == null in parse\");\n }\n\n Message result;\n\n XmlPullParser parser = Xml.newPullParser();\n parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);\n parser.setInput(stream, null);\n parser.nextTag();\n\n parser.require(XmlPullParser.START_TAG, null, XmlConstants.MESSAGE);\n String v = parser.getAttributeValue(null, \"v\");\n if ((v == null) || !\"3\".equals(v))\n {\n if ((v != null) && \"0\".equals(v))\n {\n // ignore, treat like v = 3\n Log.w(TAG, \"Received with \\\"v\\\" = \\\"0\\\".\");\n }\n else\n {\n throw new MessageReaderException(String.format(\"Invalid format at attribute \\\"v\\\" : %s.\", v));\n }\n }\n String guid = parser.getAttributeValue(null, \"guid\");\n String type = parser.getAttributeValue(null, \"type\");\n if (type == null)\n {\n throw new MessageReaderException(\"\\\"type\\\" attribute does not exist in .\");\n }\n if (\"user_info\".equals(type))\n {\n result = new UserInfoMessage(parser);\n }\n else if (\"hi_status\".equals(type))\n {\n result = new HiStatusMessage(parser);\n }\n else if (\"smart\".equals(type))\n {\n result = new SmartMessage(parser);\n }\n else if (\"typing\".equals(type))\n {\n result = new TypingMessage(parser);\n }\n else\n {\n Log.w(TAG, String.format(\"Skipped message of type %s\", type));\n throw new MessageReaderException(String.format(\"Unsupported message type while reading: %s\", type));\n }\n result.setGuid(guid);\n\n return result;\n }\n}\nDifian/YalerAndroidLibrary/src/main/java/org/yaler/YalerSSLServerSocket.java\npublic final class YalerSSLServerSocket extends YalerServerSocket {\n\tpublic YalerSSLServerSocket(String host, int port, String id) {\n\t\tsuper(host, port, id);\n\t}\n\n\tpublic YalerSSLServerSocket(String host, int port, String id, Proxy proxy) {\n\t\tsuper(host, port, id, proxy);\n\t}\n\n\t@Override\n\tpublic YalerSocketFactory getYalerSocketFactory() {\n\t\treturn YalerSSLSocketFactory.getInstance();\n\t}\n\n\t@Override\n\tpublic InetSocketAddress findLocation(InputStream stream) throws IOException {\n\t\treturn StreamHelper.findLocation(stream, \"https\", 443);\n\t}\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/HiMuteStatus.java\npublic enum HiMuteStatus\n{\n MUTED, UNMUTED, UNDEFINED\n}\nDifian/DifianApp/src/main/java/com/sonova/difian/communication/messaging/TypingMessage.java\npublic final class TypingMessage extends Message\n{\n private final boolean _typing;\n\n TypingMessage(XmlPullParser parser) throws MessageReaderException\n {\n String typingString = parser.getAttributeValue(null, \"is_saving\");\n if (typingString == null)\n {\n throw new MessageReaderException(\"is_saving attribute not present in typing message\");\n }\n _typing = Boolean.parseBoolean(typingString);\n }\n\n @Override\n public MessageType getType()\n {\n return MessageType.TYPING;\n }\n\n public boolean isTyping()\n {\n return _typing;\n }\n}\n", "answers": [" TypingMessage m = (TypingMessage)message;"], "length": 2216, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "f2c380901413d687f5153f54212145b6451a0e3277a08475"} {"input": "import os\nimport numpy as np\nimport nibabel as nib\nimport argparse as ap\nimport pandas as pd\nfrom tfce_mediation.tfce import CreateAdjSet\nfrom tfce_mediation.pyfunc import write_vertStat_img, write_voxelStat_img, create_adjac_vertex, create_adjac_voxel, reg_rm_ancova_one_bs_factor, reg_rm_ancova_two_bs_factor, glm_typeI, glm_cosinor, calc_indirect, dummy_code, column_product, stack_ones, import_voxel_neuroimage, lm_residuals, dummy_code_cosine\n\t\t\tEXOG_B.append(dmy_leftvar)\n\n\t\t\tTvalues_A = glm_typeI(dmy_rightvar,\n\t\t\t\t\t\tEXOG_A,\n\t\t\t\t\t\tdmy_covariates=dmy_covariates,\n\t\t\t\t\t\toutput_fvalues = False,\n\t\t\t\t\t\toutput_tvalues = True,\n\t\t\t\t\t\toutput_reduced_residuals = False)[1]\n\n\t\t\tTvalues_B = glm_typeI(data,\n\t\t\t\t\t\tEXOG_B,\n\t\t\t\t\t\tdmy_covariates=dmy_covariates,\n\t\t\t\t\t\toutput_fvalues = False,\n\t\t\t\t\t\toutput_tvalues = True,\n\t\t\t\t\t\toutput_reduced_residuals = False)[1]\n\n\t\telse:\n\t\t\tprint(\"ERROR: Invalid mediation type: %s\" % medtype)\n\t\t\tquit()\n\n\t\tSobelZ = calc_indirect(Tvalues_A, Tvalues_B, alg = \"aroian\")\n\n\t\tif opts.surfaceinputfolder:\n\t\t\tsave_temporary_files('mediation', modality_type = surface,\n\t\t\t\tall_vertex = all_vertex,\n\t\t\t\tnum_vertex_lh = num_vertex_lh,\n\t\t\t\tmask_lh = mask_lh,\n\t\t\t\tmask_rh = mask_rh,\n\t\t\t\toutdata_mask_lh = outdata_mask_lh,\n\t\t\t\toutdata_mask_rh = outdata_mask_rh,\n\t\t\t\taffine_mask_lh = affine_mask_lh,\n\t\t\t\taffine_mask_rh = affine_mask_rh,\n\t\t\t\tadjac_lh = adjac_lh,\n\t\t\t\tadjac_rh = adjac_rh,\n\t\t\t\tvdensity_lh = vdensity_lh,\n\t\t\t\tvdensity_rh = vdensity_rh,\n\t\t\t\tdmy_leftvar = dmy_leftvar,\n\t\t\t\tdmy_rightvar = dmy_rightvar,\n\t\t\t\tdmy_covariates = dmy_covariates,\n\t\t\t\toptstfce = optstfce,\n\t\t\t\tmedtype = medtype,\n\t\t\t\tnonzero = nonzero.astype(np.float32, order = \"C\"),\n\t\t\t\tdata = data.astype(np.float32, order = \"C\"))\n\n\t\t\toutdir = \"output_mediation_%s\" % (surface)\n\t\t\tif not os.path.exists(outdir):\n\t\t\t\tos.mkdir(outdir)\n\t\t\tos.chdir(outdir)\n\n\t\t\twrite_vertStat_img('Zstat_%s' % medtype,\n\t\t\t\tSobelZ[:num_vertex_lh],\n\t\t\t\toutdata_mask_lh,\n\t\t\t\taffine_mask_lh,\n\t\t\t\tsurface,\n\t\t\t\t'lh',\n\t\t\t\tmask_lh,\n\t\t\t\tcalcTFCE_lh,\n\t\t\t\tmask_lh.shape[0],\n\t\t\t\tvdensity_lh)\n\t\t\twrite_vertStat_img('Zstat_%s' % medtype,\n\t\t\t\tSobelZ[num_vertex_lh:],\n\t\t\t\toutdata_mask_rh,\n\t\t\t\taffine_mask_rh,\n\t\t\t\tsurface,\n\t\t\t\t'rh',\n\t\t\t\tmask_rh,\n\t\t\t\tcalcTFCE_rh,\n\t\t\t\tmask_rh.shape[0],\n\t\t\t\tvdensity_rh)\n\n\t\tif opts.volumetricinputs or opts.volumetricinputlist:\n\t\t\tsave_temporary_files('mediation', modality_type = \"volume\",\n\t\t\t\tmask_index = mask_index,\n\t\t\t\tdata_mask = data_mask,\n\t\t\t\taffine_mask = affine_mask,\n\t\t\t\tadjac = adjac,\n\t\t\t\tdmy_leftvar = dmy_leftvar,\n\t\t\t\tdmy_rightvar = dmy_rightvar,\n\t\t\t\tdmy_covariates = dmy_covariates,\n\t\t\t\toptstfce = optstfce,\n\t\t\t\tmedtype = medtype,\n\t\t\t\tnonzero = nonzero.astype(np.float32, order = \"C\"),\n\t\t\t\tdata = data.astype(np.float32, order = \"C\"))\n\n\t\t\toutdir = \"output_mediation_volume\"\n\t\t\tif not os.path.exists(outdir):\n\t\t\t\tos.mkdir(outdir)\n\t\t\tos.chdir(outdir)\n\n\t\t\twrite_voxelStat_img('Zstat_%s' % medtype,\n\t\t\t\tSobelZ,\n\t\t\t\tdata_mask,\n\t\t\t\tmask_index,\n\t\t\t\taffine_mask,\n\t\t\t\tcalcTFCE,\n\t\t\t\timgext)\n\n\n\tif opts.cosinormediation:\n\t\tmedtype = 'Y'\n\t\tdata = data[0] # There should only be one interval...\n\t\ttime_var = pdCSV[\"%s\" % opts.cosinormediation[0]]\n\t\tperiod = float(opts.cosinormediation[1])\n\t\tdmy_mediator = dummy_code(np.array(pdCSV[opts.cosinormediation[2]]), iscontinous = True, demean = demean_flag)\n\t\tprint(\"Coding mediator %s as continous variable\" % opts.cosinormediation[2])\n\n\t\tif opts.initcovar:\n\t\t\tinit_covars, init_covarsnames = load_vars(pdCSV, variables = opts.initcovar, exog = [], names = [], demean_flag = False)\n\t\t\tdmy_init_covars = np.concatenate(init_covars,1)\n\t\t\tdata = lm_residuals(data, dmy_init_covars)\n\n\t\tif opts.covariates:\n\t\t\tdmy_covariates = np.concatenate(covars,1)\n\t\telse:\n\t\t\tdmy_covariates = None\n\n\n\t\tEXOG = []\n\t\tEXOG.append(dmy_mediator)\n\n", "context": "tfce_mediation/pyfunc.py\ndef write_vertStat_img(statname, vertStat, outdata_mask, affine_mask, surf, hemi, bin_mask, TFCEfunc, all_vertex, density_corr = 1, TFCE = True):\n\tvertStat_out=np.zeros(all_vertex).astype(np.float32, order = \"C\")\n\tvertStat_out[bin_mask] = vertStat\n\tif TFCE:\n\t\tvertStat_TFCE = np.zeros_like(vertStat_out).astype(np.float32, order = \"C\")\n\t\tTFCEfunc.run(vertStat_out, vertStat_TFCE)\n\t\toutdata_mask[:,0,0] = vertStat_TFCE * (vertStat[np.isfinite(vertStat)].max()/100) * density_corr\n\t\tfsurfname = \"%s_%s_%s_TFCE.mgh\" % (statname,surf,hemi)\n\t\tos.system(\"echo %s_%s_%s,%f >> max_TFCE_contrast_values.csv\" % (statname,surf,hemi, outdata_mask[np.isfinite(outdata_mask[:,0,0])].max()))\n\t\tnib.save(nib.freesurfer.mghformat.MGHImage(outdata_mask,affine_mask),fsurfname)\n\toutdata_mask[:,0,0] = vertStat_out\n\tfsurfname = \"%s_%s_%s.mgh\" % (statname,surf,hemi)\n\tnib.save(nib.freesurfer.mghformat.MGHImage(outdata_mask,affine_mask),fsurfname)\ntfce_mediation/pyfunc.py\ndef reg_rm_ancova_two_bs_factor(data, dmy_factor1, dmy_factor2, dmy_subjects, dmy_covariates = None, data_format = 'short', output_sig = False, verbose = True, rand_array = None, use_reduced_residuals = False, output_reduced_residuals = False):\n\t\"\"\"\n\tTwo factor repeated measure ANCOVA for longitudinal dependent variables\n\tNote: Type 1 Sum of Squares is used, therefore order matters\n\t\n\tParameters\n\t----------\n\tdata : array\n\t\tData array (N_intervals, N_individuals, N_dependent variables)\n\tdmy_factor1 : array\n\t\tdummy coded factor 1\n\tdmy_factor2 : array\n\t\tdummy coded factor 2\n\tdmy_subjects : array\n\t\tdummy coded subjects\n\t\n\tOptional Parameters\n\t----------\n\tdmy_covariates : array\n\t\tdummy coded covariates of no interest\n\trand_array : arrays\n\t\trandomised shuffled array (used for permutation testing)\n\t\n\tOptional Flags\n\t----------\n\toutput_sig : bool\n\t\toutputs p-values of F-statistics\n\tverbose : bool\n\t\tprints the max F-statistics values and degrees of freedom\n\tuse_reduced_residuals : bool\n\t\tThe residuals after regressing the fixed effect exogenous variable(s) is shuffled for permutations testing.\n\toutput_reduced_residuals : bool\n\t\tOutputs the residuals array after regressing the fixed effect exogenous variable(s).\n\t\n\tReturns\n\t-------\n\tF_a : array\n\t\tF-statistics of the between-subject factor1\n\tF_b : array\n\t\tF-statistics of the between-subject factor2\n\tF_ab : array\n\t\tF-statistics of the between-subject interaction of factor1*factor2\n\tF_s : array\n\t\tF-statistics of the within-subject interval\n\tF_sb : array\n\t\tF-statistics of the factor1*interval interaction\n\tF_sb : array\n\t\tF-statistics of the factor2*interval interaction\n\tF_sab : array\n\t\tF-statistics of the factor1*factor2*interval interaction\n\t\n\tOptional returns\n\t-------\n\t\n\tP_a : array\n\t\tP-statistics of the between-subject factor1\n\tP_b : array\n\t\tP-statistics of the between-subject factor2\n\tP_ab : array\n\t\tP-statistics of the between-subject interaction of factor1*factor2\n\tP_s : array\n\t\tP-statistics of the within-subject interval\n\tP_sa : array\n\t\tP-statistics of the factor1*interval interaction\n\tP_sb : array\n\t\tP-statistics of the factor2*interval interaction\n\tP_sab : array\n\t\tP-statistics of the factor1*factor2*interval interaction\n\t\n\tOR\n\t\n\treduced_data : array\n\t\tResiduals array after regressing the fixed effect exogenous variable(s) in long format.\n\t\t\n\t\"\"\"\n\t\n\tif data_format == 'short':\n\t\tif data.ndim == 2:\n\t\t\tdata = data[:,:,np.newaxis]\n\t\t# get shapes for df\n\t\tn = data.shape[1]\n\t\ts = data.shape[0]\n\t\tendog_arr = data.reshape(s*n,data.shape[2])\n\telif data_format == 'long':\n\t\tn = len(dmy_factor1)\n\t\ts = len(data)/n\n\t\tendog_arr = data\n\telse:\n\t\tprint(\"Error: data format must be short or long.\")\n\tdel data # reduce ram usage\n\t\n\tif dmy_factor1.ndim == 1:\n\t\tfa = 2\n\telse:\n\t\tfa = dmy_factor1.shape[1] + 1\n\tif dmy_factor2.ndim == 1:\n\t\tfb = 2\n\telse:\n\t\tfb = dmy_factor2.shape[1] + 1\n\n\tif rand_array is not None:\n\t\tif use_reduced_residuals:\n\t\t\tr_dmy_factor1_long = dmy_factor1\n\t\t\tr_dmy_factor2_long = dmy_factor2\n\t\t\tr_dmy_interaction_long = column_product(dmy_factor1,dmy_factor2)\n\t\t\tif dmy_covariates is not None:\n\t\t\t\tr_dmy_covars_long = dmy_covariates\n\t\t\tfor i in range(s-1):\n\t\t\t\tr_dmy_factor1_long = np.concatenate((r_dmy_factor1_long,dmy_factor1),0)\n\t\t\t\tr_dmy_factor2_long = np.concatenate((r_dmy_factor2_long,dmy_factor2),0)\n\t\t\t\tr_dmy_interaction_long = np.concatenate((r_dmy_interaction_long,column_product(dmy_factor1,dmy_factor2)),0)\n\t\t\t\tif dmy_covariates is not None:\n\t\t\t\t\tr_dmy_covars_long = np.concatenate((r_dmy_covars_long, dmy_covariates),0)\n\t\t\texog_vars = stack_ones(r_dmy_factor1_long)\n\t\t\texog_vars = np.column_stack((exog_vars, r_dmy_factor2_long))\n\t\t\texog_vars = np.column_stack((exog_vars, r_dmy_interaction_long))\n\t\t\tif dmy_covariates is not None:\n\t\t\t\texog_vars = np.column_stack((exog_vars, r_dmy_covars_long))\n\t\t\ta = cy_lin_lstsqr_mat(exog_vars,endog_arr)\n\t\t\tendog_arr = endog_arr - np.dot(exog_vars,a)\n\t\t\tdel a\n\t\tnp.random.shuffle(endog_arr)\n\t\tdmy_factor1 = dmy_factor1[rand_array]\n\t\tdmy_factor2 = dmy_factor2[rand_array]\n\t\tif dmy_covariates is not None:\n\t\t\tdmy_covariates = dmy_covariates[rand_array]\n\n\t# code the interaction\n\tdmy_interaction = column_product(dmy_factor1, dmy_factor2)\n\n\t# convert to long form\n\tinterval_long = np.zeros(n)\n\tdmy_factor1_long = dmy_factor1\n\tdmy_factor2_long = dmy_factor2\n\tdmy_interaction_long = dmy_interaction\n\tdmy_subjects_long = dmy_subjects\n\tif dmy_covariates is not None:\n\t\tdmy_covars_long = dmy_covariates\n\n\tfor i in range(s-1):\n\t\tdmy_factor1_long = np.concatenate((dmy_factor1_long,dmy_factor1),0)\n\t\tdmy_factor2_long = np.concatenate((dmy_factor2_long,dmy_factor2),0)\n\t\tdmy_interaction_long = np.concatenate((dmy_interaction_long,dmy_interaction),0)\n\t\tdmy_subjects_long = np.concatenate((dmy_subjects_long,dmy_subjects),0)\n\t\tinterval_long = np.concatenate((interval_long, np.ones(n)*(i+1)))\n\t\tif dmy_covariates is not None:\n\t\t\tdmy_covars_long = np.concatenate((dmy_covars_long, dmy_covariates),0)\n\tdmy_interval_long = dummy_code(interval_long, demean = False)\n\n\t# SS Totals\n\texog_vars = stack_ones(dmy_subjects_long)\n\tSS_WithinSubjects = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_Total = np.sum((endog_arr - np.mean(endog_arr, axis = 0))**2, axis = 0)\n\tSS_BetweenSubjects = SS_Total - SS_WithinSubjects\n\n\t# SS between subject\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_factor2_long))\n\texog_vars = np.column_stack((exog_vars, dmy_interaction_long))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\tif output_reduced_residuals:\n\t\ta, residuals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)\n\t\treduced_data = endog_arr - np.dot(exog_vars,a)\n\t\tdel a\n\telse:\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_cells_ab = SS_Total - residuals\n\n\texog_vars = stack_ones(np.column_stack((dmy_factor1_long, dmy_factor2_long)))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_ab = SS_cells_ab - (SS_Total - residuals)\n\t# correct SS_ab\n\n\tif dmy_covariates is not None:\n\t\texog_vars = stack_ones(dmy_covars_long)\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\t\tSS_covars =(SS_Total - residuals)\n\telse:\n\t\tSS_covars = 0\n\n\t# SSb\n\texog_vars = stack_ones(dmy_factor1_long)\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_a = (SS_Total - residuals) - SS_covars\n\n\t# SSa\n\tSS_b = SS_cells_ab - SS_covars - SS_ab - SS_a\n\n\tSS_WithinFactors = SS_BetweenSubjects - SS_a - SS_b - SS_ab - SS_covars\n\n\t# SS time\n\texog_vars = stack_ones(dmy_interval_long)\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_s = SS_Total - residuals\n\n\t# SS Cells s*a*b\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_factor2_long))\n\texog_vars = np.column_stack((exog_vars, dmy_interaction_long))\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor1_long,dmy_interval_long)))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor2_long,dmy_interval_long)))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_interaction_long,dmy_interval_long)))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_cells_sab = SS_Total - residuals\n\n\t# SS Cells s*a*b\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_factor2_long))\n\texog_vars = np.column_stack((exog_vars, dmy_interaction_long))\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor1_long,dmy_interval_long)))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor2_long,dmy_interval_long)))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_sab = SS_cells_sab - (SS_Total - residuals)\n\n\t# SS covariates (same as above int then minus int)\n\tif dmy_covariates is not None:\n\t\texog_vars = stack_ones(dmy_covars_long)\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\t\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\t\tSS_cells_scovars = (SS_Total - residuals)\n\t\texog_vars = stack_ones(dmy_covars_long)\n\t\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\t\tSS_scovars = SS_cells_scovars - (SS_Total - residuals)\n\telse:\n\t\tSS_scovars = 0\n\n\t# SS Cells s*a\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor1_long,dmy_interval_long)))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_Cells_sa = (SS_Total - residuals)\n\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_sa = SS_Cells_sa - (SS_Total - residuals)\n\n\t# SS Cells s*b\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_factor2_long))\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor1_long,dmy_interval_long)))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor2_long,dmy_interval_long)))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_Cells_sb = (SS_Total - residuals)\n\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_factor2_long))\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor1_long,dmy_interval_long)))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_sb = SS_Cells_sb - (SS_Total - residuals)\n\n\tSS_sWithinFactors = SS_WithinSubjects - SS_s - SS_sa - SS_sb - SS_sab - SS_scovars\n\n\t# Between subjects df\n\tdf_BetweenSubjects = n - 1\n\tdf_a = fa - 1\n\tdf_b = fb - 1\n\tdf_ab = df_a * df_b\n\tif dmy_covariates is not None:\n\t\tif dmy_covariates.ndim == 1:\n\t\t\tdf_covars = 1\n\t\telse:\n\t\t\tdf_covars = dmy_covariates.shape[1]\n\telse:\n\t\tdf_covars = 0\n\tdf_WithinFactors = df_BetweenSubjects - df_a - df_b - df_ab - df_covars\n\n\t# Within subjects df\n\tdf_s = s - 1\n\tdf_sa = df_a * df_s\n\tdf_sb = df_b * df_s\n\tdf_sab = df_ab * df_s\n\tdf_sWithinFactor = df_WithinFactors * df_s\n\n\t# F-stats\n\t# Between subjects\n\tms_WithinFactors = np.divide(SS_WithinFactors, df_WithinFactors)\n\tF_a = np.divide(np.divide(SS_a, df_a), ms_WithinFactors)\n\tF_b = np.divide(np.divide(SS_b, df_b), ms_WithinFactors)\n\tF_ab = np.divide(np.divide(SS_ab, df_ab), ms_WithinFactors)\n\n\t# Within subjects\n\tms_sWithinFactor = np.divide(SS_sWithinFactors, df_sWithinFactor)\n\tF_s = np.divide(np.divide(SS_s, df_s), ms_sWithinFactor)\n\tF_sa = np.divide(np.divide(SS_sa, df_sa), ms_sWithinFactor)\n\tF_sb = np.divide(np.divide(SS_sb, df_sb), ms_sWithinFactor)\n\tF_sab = np.divide(np.divide(SS_sab, df_sab), ms_sWithinFactor)\n\n\tif verbose:\n\t\tprint(\"Source\\t\\tDF\\tF(Max)\")\n\t\tprint(\"Factor1\\t\\t(%d,%d)\\t%.2f\" % (df_a, df_WithinFactors, F_a.max()))\n\t\tprint(\"Factor2\\t\\t(%d,%d)\\t%.2f\" % (df_b, df_WithinFactors, F_b.max()))\n\t\tprint(\"F1*F2\\t\\t(%d,%d)\\t%.2f\" % (df_ab, df_WithinFactors, F_ab.max()))\n\t\tprint(\"Time\\t\\t(%d,%d)\\t%.2f\" % (df_s, df_sWithinFactor, F_s.max()))\n\t\tprint(\"F1*Time\\t\\t(%d,%d)\\t%.2f\" % (df_sa, df_sWithinFactor, F_sa.max()))\n\t\tprint(\"F2*Time\\t\\t(%d,%d)\\t%.2f\" % (df_sb, df_sWithinFactor, F_sb.max()))\n\t\tprint(\"F1*F2*Time\\t(%d,%d)\\t%.2f\" % (df_sab, df_sWithinFactor, F_sab.max()))\n\n\tif output_sig:\n\t\t# Between subjects\n\t\tP_a = 1 - f.cdf(F_a,df_a,df_WithinFactors)\n\t\tP_b = 1 - f.cdf(F_b,df_b,df_WithinFactors)\n\t\tP_ab = 1 - f.cdf(F_ab,df_ab,df_WithinFactors)\n\t\t# Within subjects\n\t\tP_s = 1 - f.cdf(F_s,df_s,df_sWithinFactor)\n\t\tP_sa = 1 - f.cdf(F_sa,df_sa,df_sWithinFactor)\n\t\tP_sb = 1 - f.cdf(F_sb,df_sb,df_sWithinFactor)\n\t\tP_sab = 1 - f.cdf(F_sab,df_sab,df_sWithinFactor)\n\t\treturn (F_a, F_b, F_ab, F_s, F_sa, F_sb, F_sab, P_a, P_b, P_ab, P_s, P_sa, P_sb, P_sab)\n\telse:\n\t\tif output_reduced_residuals:\n\t\t\treturn (F_a, F_b, F_ab, F_s, F_sa, F_sb, F_sab, reduced_data)\n\t\telse:\n\t\t\treturn (F_a, F_b, F_ab, F_s, F_sa, F_sb, F_sab)\ntfce_mediation/pyfunc.py\ndef calc_indirect(ta, tb, alg = \"aroian\"):\n\t\"\"\"\n\tCalculates the indirect effect of simple mediation\n\t\n\tParameters\n\t----------\n\tta : array\n\t\tT-values from Path A\n\ttb : array\n\t\tT-values from Path B\n\talg : string\n\t\tThe algorithm used for mediation (default = \"aroian\") \n\n\tReturns\n\t---------\n\tSobelZ : array\n\t\tSobel-Z statistics of the indirect effect.\n\t\n\t\"\"\"\n\tif alg == 'aroian':\n\t\t#Aroian variant\n\t\tSobelZ = 1/np.sqrt((1/(tb**2))+(1/(ta**2))+(1/(ta**2*tb**2)))\n\telif alg == 'sobel':\n\t\t#Sobel variant\n\t\tSobelZ = 1/np.sqrt((1/(tb**2))+(1/(ta**2)))\n\telif alg == 'goodman':\n\t\t#Goodman variant\n\t\tSobelZ = 1/np.sqrt((1/(tb**2))+(1/(ta**2))-(1/(ta**2*tb**2)))\n\telse:\n\t\tprint(\"Unknown indirect test algorithm\")\n\t\texit()\n\treturn SobelZ\ntfce_mediation/pyfunc.py\ndef dummy_code_cosine(time, period = 24.0):\n\t\"\"\"\n\tDummy codes a time variable into a cosine\n\tC1 = (2.0*Pi*time)/period)\n\tC2 = sin(2.0*Pi*time)/period)\n\n\tParameters\n\t----------\n\ttime : array\n\t\t1D array variable of any type \n\tperiod : float\n\t\tDefined period (i.e., for one entire cycle) for the time variable\n\n\tReturns\n\t---------\n\tcosine_curve : array\n\t\t2D array cos and sine curves \n\t\n\t\"\"\"\n\n\tcosine_curve = np.cos(np.divide(2.0*np.pi*time, period))\n\tcosine_curve = np.column_stack((cosine_curve,np.sin(np.divide(2.0*np.pi*time, period))))\n\treturn cosine_curve\ntfce_mediation/pyfunc.py\ndef dummy_code(variable, iscontinous = False, demean = True):\n\t\"\"\"\n\tDummy codes a variable\n\t\n\tParameters\n\t----------\n\tvariable : array\n\t\t1D array variable of any type \n\n\tReturns\n\t---------\n\tdummy_vars : array\n\t\tdummy coded array of shape [(# subjects), (unique variables - 1)]\n\t\n\t\"\"\"\n\tif iscontinous:\n\t\tif demean:\n\t\t\tdummy_vars = variable - np.mean(variable,0)\n\t\telse:\n\t\t\tdummy_vars = variable\n\telse:\n\t\tunique_vars = np.unique(variable)\n\t\tdummy_vars = []\n\t\tfor var in unique_vars:\n\t\t\ttemp_var = np.zeros((len(variable)))\n\t\t\ttemp_var[variable == var] = 1\n\t\t\tdummy_vars.append(temp_var)\n\t\tdummy_vars = np.array(dummy_vars)[1:] # remove the first column as reference variable\n\t\tdummy_vars = np.squeeze(dummy_vars).astype(np.int).T\n\t\tif demean:\n\t\t\tdummy_vars = dummy_vars - np.mean(dummy_vars,0)\n\treturn dummy_vars\ntfce_mediation/pyfunc.py\ndef create_adjac_vertex(vertices,faces): # basic version\n\tadjacency = [set([]) for i in range(vertices.shape[0])]\n\tfor i in range(faces.shape[0]):\n\t\tadjacency[faces[i, 0]].add(faces[i, 1])\n\t\tadjacency[faces[i, 0]].add(faces[i, 2])\n\t\tadjacency[faces[i, 1]].add(faces[i, 0])\n\t\tadjacency[faces[i, 1]].add(faces[i, 2])\n\t\tadjacency[faces[i, 2]].add(faces[i, 0])\n\t\tadjacency[faces[i, 2]].add(faces[i, 1])\n\treturn adjacency\ntfce_mediation/pyfunc.py\ndef glm_cosinor(endog, time_var, exog = None, dmy_covariates = None, rand_array = None, interaction_var = None, period = [24.0], calc_MESOR = True, output_fit_only = False):\n\t\"\"\"\n\tCOSINOR model using GLM\n\t\n\tParameters\n\t----------\n\tendog : array\n\t\tEndogenous (dependent) variable array (Nsubjects, Nvariables)\n\ttime_var : array\n\t\tTime variable [0-23.99] (Nsubjects).\n\texog : array\n\t\tExogenous (independent) dummy coded variables\n\t\texog is an array of arrays (Nvariables, Nsubjects, Kvariable).\n\tdmy_covariates : array\n\t\tDummy coded array of covariates of no interest.\n\tinit_covars : array\n\t\tDummy coded array of covariates for two-step regression.\n\trand_array : array\n\t\trandomized array for permutations (Nsubjects).\n\tperiod : array\n\t\tPeriod(s) as an array of floats for cosinor model.\n\tReturns\n\t---------\n\tTo-do\n\t\"\"\"\n\n\tn = endog.shape[0]\n\t# add cosinor terms\n\tnum_period = len(period)\n\texog_vars = np.ones((n))\n\tfor i in range(num_period):\n\t\texog_vars = np.column_stack((exog_vars,np.cos(np.divide(2.0*np.pi*time_var, period[i]))))\n\t\texog_vars = np.column_stack((exog_vars,np.sin(np.divide(2.0*np.pi*time_var, period[i]))))\n\n\tif interaction_var is not None:\n\t\tfor i in range(num_period):\n\t\t\texog_vars = np.column_stack((exog_vars, exog_vars[i+1] * interaction_var))\n\n\n\tkvars = []\n\t# add other exogenous variables to the model (currently not implemented)\n\tif exog is not None:\n\t\tfor var in exog:\n\t\t\tvar = np.array(var)\n\t\t\tif var.ndim == 1:\n\t\t\t\tkvars.append((3))\n\t\t\telse:\n\t\t\t\tkvars.append((var.shape[1]))\n\t\t\texog_vars = np.column_stack((exog_vars,var))\n\n\t# add covariates (i.e., exogenous variables that will not be outputed)\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covariates))\n\texog_vars = np.array(exog_vars)\n\n\tif rand_array is not None:\n\t\texog_vars = exog_vars[rand_array]\n\n\t# calculate model fit (Fmodel and R-sqr)\n\tk = exog_vars.shape[1]\n\tDF_Between = k - 1 # aka df model\n\tDF_Within = n - k # aka df residuals\n\t#DF_Total = n - 1\n\n\ta, SS_Residuals = cy_lin_lstsqr_mat_residual(exog_vars,endog)\n\tif output_fit_only:\n\t\tAMPLITUDE = []\n\t\tACROPHASE = []\n\t\tMESOR = a[0]\n\t\tfor i in range(num_period):\n\t\t\t# beta, gamma\n\t\t\tAMPLITUDE.append(np.sqrt((a[1+(i*2),:]**2) + (a[2+(i*2),:]**2)))\n\t\t\t# Acrophase calculation\n\t\t\tif i == 0: # awful hack\n\t\t\t\tACROPHASE = np.arctan(np.abs(np.divide(-a[2+(i*2),:], a[1+(i*2),:])))\n\t\t\t\tACROPHASE = ACROPHASE[np.newaxis,:]\n\t\t\telse:\n\t\t\t\ttemp_acro = np.arctan(np.abs(np.divide(-a[2+(i*2),:], a[1+(i*2),:])))\n\t\t\t\ttemp_acro = temp_acro[np.newaxis,:]\n\t\t\t\tACROPHASE = np.append(ACROPHASE,temp_acro, axis=0)\n\t\t\tACROPHASE = np.array(ACROPHASE)\n\t\t\tACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] >= 0)] = -ACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] >= 0)]\n\t\t\tACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] < 0)] = (-1*np.pi) + ACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] < 0)]\n\t\t\tACROPHASE[i, (a[2+(i*2),:] < 0) & (a[1+(i*2),:] <= 0)] = (-1*np.pi) - ACROPHASE[i, (a[2+(i*2),:] < 0) & (a[1+(i*2),:] <= 0)]\n\t\t\tACROPHASE[i, (a[2+(i*2),:] <= 0) & (a[1+(i*2),:] > 0)] = (-2*np.pi) + ACROPHASE[i, (a[2+(i*2),:] <= 0) & (a[1+(i*2),:] > 0)]\n\t\treturn MESOR, np.array(AMPLITUDE), np.array(ACROPHASE)\n\telse:\n\t\tSS_Total = np.sum((endog - np.mean(endog,0))**2,0)\n\t\tSS_Between = SS_Total - SS_Residuals\n\t\tMS_Residuals = (SS_Residuals / DF_Within)\n\t\tFmodel = (SS_Between/DF_Between) / MS_Residuals\n\t\t# Calculates sigma sqr and T-value (intercept) for MESOR\n\t\tsigma = np.sqrt(SS_Residuals / DF_Within)\n\t\tinvXX = np.linalg.inv(np.dot(exog_vars.T, exog_vars))\n\n\t\tif (calc_MESOR) or (exog is not None):\n\t\t\tif endog.ndim == 1:\n\t\t\t\tse = np.sqrt(np.diag(sigma * sigma * invXX))\n\t\t\t\tTvalues = a / se\n\t\t\t\tMESOR = a[0]\n\t\t\t\ttMESOR = Tvalues[0]\n\t\t\t\tSE_MESOR = se[0]\n\t\t\t\ta = a[:, np.newaxis]\n\t\t\telse:\n\t\t\t\tnum_depv = endog.shape[1]\n\t\t\t\tse = se_of_slope(num_depv,invXX,sigma**2,k)\n\t\t\t\tTvalues = a / se\n\t\t\t\tMESOR = a[0,:]\n\t\t\t\ttMESOR = Tvalues[0,:]\n\t\t\t\tSE_MESOR = se[0,:]\n\t\t\tif exog is not None:\n\t\t\t\ttEXOG = Tvalues[(3+(2*(num_period-1))):,:]\n\t\t\telse:\n\t\t\t\ttEXOG = None\n\t\telse:\n\t\t\tMESOR = tMESOR = SE_MESOR = tEXOG = None\n\n\t\tAMPLITUDE = []\n\t\tACROPHASE = []\n\t\tSE_ACROPHASE = []\n\t\tSE_AMPLITUDE = []\n\t\ttAMPLITUDE = []\n\t\ttACROPHASE = []\n\t\t\n\t\tfor i in range(num_period):\n\t\t\t# beta, gamma\n\t\t\tAMPLITUDE.append(np.sqrt((a[1+(i*2),:]**2) + (a[2+(i*2),:]**2)))\n\t\t\t# Acrophase calculation\n\t\t\tif i == 0: # awful hack\n\t\t\t\tACROPHASE = np.arctan(np.abs(np.divide(-a[2+(i*2),:], a[1+(i*2),:])))\n\t\t\t\tACROPHASE = ACROPHASE[np.newaxis,:]\n\t\t\telse:\n\t\t\t\ttemp_acro = np.arctan(np.abs(np.divide(-a[2+(i*2),:], a[1+(i*2),:])))\n\t\t\t\ttemp_acro = temp_acro[np.newaxis,:]\n\t\t\t\tACROPHASE = np.append(ACROPHASE,temp_acro, axis=0)\n\n\t\t\t# standard errors from error propagation\n\t\t\tSE_ACROPHASE.append(sigma * np.sqrt((invXX[(1+(i*2)),1+(i*2)]*np.sin(ACROPHASE[i])**2) + (2*invXX[1+(i*2),2+(i*2)]*np.sin(ACROPHASE[i])*np.cos(ACROPHASE[i])) + (invXX[2+(i*2),2+(i*2)]*np.cos(ACROPHASE[i])**2)) / AMPLITUDE[i])\n\t\t\tSE_AMPLITUDE.append(sigma * np.sqrt((invXX[(1+(i*2)),1+(i*2)]*np.cos(ACROPHASE[i])**2) - (2*invXX[1+(i*2),2+(i*2)]*np.sin(ACROPHASE[i])*np.cos(ACROPHASE[i])) + (invXX[2+(i*2),2+(i*2)]*np.sin(ACROPHASE[i])**2)))\n\n\t\t\tACROPHASE = np.array(ACROPHASE)\n\t\t\tif rand_array is None:\n\t\t\t\tACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] >= 0)] = -ACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] >= 0)]\n\t\t\t\tACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] < 0)] = (-1*np.pi) + ACROPHASE[i, (a[2+(i*2),:] > 0) & (a[1+(i*2),:] < 0)]\n\t\t\t\tACROPHASE[i, (a[2+(i*2),:] < 0) & (a[1+(i*2),:] <= 0)] = (-1*np.pi) - ACROPHASE[i, (a[2+(i*2),:] < 0) & (a[1+(i*2),:] <= 0)]\n\t\t\t\tACROPHASE[i, (a[2+(i*2),:] <= 0) & (a[1+(i*2),:] > 0)] = (-2*np.pi) + ACROPHASE[i, (a[2+(i*2),:] <= 0) & (a[1+(i*2),:] > 0)]\n\t\t\t# t values\n\t\t\ttAMPLITUDE.append(np.divide(AMPLITUDE[i], SE_AMPLITUDE[i]))\n\t\t\ttACROPHASE.append(np.divide(1.0, SE_ACROPHASE[i]))\n\n\t\t# Do not output R-squared during permutations testing.\n\t\tif rand_array is None:\n\t\t\tR2 = 1 - (SS_Residuals/SS_Total)\n\t\telse:\n\t\t\tR2 = None\n\t\treturn R2, MESOR, SE_MESOR, np.array(AMPLITUDE), np.array(SE_AMPLITUDE), np.array(ACROPHASE), np.array(SE_ACROPHASE), Fmodel, tMESOR, np.abs(tAMPLITUDE), np.abs(tACROPHASE), np.array(tEXOG)\ntfce_mediation/pyfunc.py\ndef write_voxelStat_img(statname, voxelStat, out_path, data_index, affine, TFCEfunc, imgext = '.nii.gz', TFCE = True):\n\tif TFCE:\n\t\tvoxelStat_out = voxelStat.astype(np.float32, order = \"C\")\n\t\tvoxelStat_TFCE = np.zeros_like(voxelStat_out).astype(np.float32, order = \"C\")\n\t\tTFCEfunc.run(voxelStat_out, voxelStat_TFCE)\n\t\tout_path[data_index] = voxelStat_TFCE * (voxelStat_out.max()/100)\n\t\tnib.save(nib.Nifti1Image(out_path,affine),\"%s_TFCE%s\" % (statname, imgext))\n\t\tos.system(\"echo %s,%f >> max_TFCE_contrast_values.csv\" % (statname,out_path.max()))\n\tout_path[data_index] = voxelStat\n\tnib.save(nib.Nifti1Image(out_path,affine),\"%s%s\" % (statname, imgext))\ntfce_mediation/pyfunc.py\ndef column_product(arr1, arr2):\n\t\"\"\"\n\tMultiply two dummy codes arrays\n\t\n\tParameters\n\t----------\n\tarr1 : array\n\t\t2D array variable dummy coded array (nlength, nvars)\n\n\tarr2 : array\n\t\t2D array variable dummy coded array (nlength, nvars)\n\n\tReturns\n\t---------\n\tprod_arr : array\n\t\tdummy coded array [nlength, nvars(arr1)*nvars(arr2)]\n\t\n\t\"\"\"\n\tl1 = len(arr1)\n\tl2 = len(arr2)\n\tif l1 == l2:\n\t\tarr1 = np.array(arr1)\n\t\tarr2 = np.array(arr2)\n\t\tprod_arr = []\n\t\tif arr1.ndim == 1:\n\t\t\tprod_arr = (arr1*arr2.T).T\n\t\telif arr2.ndim == 1:\n\t\t\tprod_arr = (arr2*arr1.T).T\n\t\telse:\n\t\t\tfor i in range(arr1.shape[1]):\n\t\t\t\tprod_arr.append((arr1[:,i]*arr2.T).T)\n\t\t\tprod_arr = np.array(prod_arr)\n\t\t\tif prod_arr.ndim == 3:\n\t\t\t\tprod_arr = np.concatenate(prod_arr, axis=1)\n\t\tprod_arr[prod_arr==0]=0\n\t\treturn prod_arr\n\telse:\n\t\tprint(\"Error: arrays must be of same length\")\n\t\tquit()\ntfce_mediation/pyfunc.py\ndef create_adjac_voxel(data_index, data_mask, num_voxel, dirtype=26): # default is 26 directions\n\tind = np.where(data_index)\n\tdm = np.zeros_like(data_mask)\n\tx_dim, y_dim, z_dim = data_mask.shape\n\tadjacency = [set([]) for i in range(num_voxel)]\n\tlabel = 0\n\tfor x,y,z in zip(ind[0],ind[1],ind[2]):\n\t\tdm[x,y,z] = label\n\t\tlabel += 1\n\tfor x,y,z in zip(ind[0],ind[1],ind[2]):\n\t\txMin=max(x-1, 0)\n\t\txMax=min(x+1, x_dim-1)\n\t\tyMin=max(y-1, 0)\n\t\tyMax=min(y+1, y_dim-1)\n\t\tzMin=max(z-1, 0)\n\t\tzMax=min(z+1, z_dim-1)\n\t\tlocal_area = dm[xMin:xMax+1,yMin:yMax+1,zMin:zMax+1]\n\t\tif int(dirtype)==6:\n\t\t\tif local_area.shape!=(3,3,3): # check to prevent calculating adjacency at walls\n\t\t\t\tlocal_area = dm[x,y,z]\n\t\t\telse:\n\t\t\t\tlocal_area = local_area * np.array([0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,1,0,0,0,0]).reshape(3,3,3)\n\t\tcV = int(dm[x,y,z])\n\t\tfor j in local_area[local_area>0]:\n\t\t\tadjacency[cV].add(int(j))\n\t# convert to list\n\tadjacency = np.array([[x for x in sorted(i) if x != index] for index, i in enumerate(adjacency)]) # just convoluted enough\n\tadjacency[0] = []\n\treturn adjacency\ntfce_mediation/pyfunc.py\ndef lm_residuals(endog, exog):\n\t\"\"\"\n\t\"\"\"\n\tif exog.ndim == 1:\n\t\texog = stack_ones(exog)\n\tif np.mean(exog[:,0]) != 1:\n\t\texog = stack_ones(exog)\n\ta = cy_lin_lstsqr_mat(exog,endog)\n\tendog = endog - np.dot(exog,a)\n\treturn endog\ntfce_mediation/pyfunc.py\ndef stack_ones(arr):\n\t\"\"\"\n\tAdd a column of ones to an array\n\t\n\tParameters\n\t----------\n\tarr : array\n\n\tReturns\n\t---------\n\tarr : array\n\t\tarray with a column of ones\n\t\n\t\"\"\"\n\treturn np.column_stack([np.ones(len(arr)),arr])\ntfce_mediation/pyfunc.py\ndef reg_rm_ancova_one_bs_factor(data, dmy_factor1, dmy_subjects, data_format = 'short', dmy_covariates = None, output_sig = False, verbose = True, rand_array = None, use_reduced_residuals = False, output_reduced_residuals = False):\n\t\"\"\"\n\tOne factor repeated measure ANCOVA for longitudinal dependent variables\n\t\n\tParameters\n\t----------\n\tdata : array\n\t\tData array (N_intervals, N_individuals, N_dependent variables)\n\tdmy_factor1 : array\n\t\tdummy coded factor 1\n\tdmy_subjects : array\n\t\tdummy coded subjects\n\t\n\tOptional Parameters\n\t----------\n\tdmy_covariates : array\n\t\tdummy coded covariates of no interest\n\t\n\tOptional Flags\n\t----------\n\toutput_sig : bool\n\t\toutputs p-values of F-statistics\n\t\n\tReturns\n\t-------\n\tF_a : array\n\t\tF-statistics of the between-subject factor1\n\tF_s : array\n\t\tF-statistics of the within-subject interval\n\tF_sa : array\n\t\tF-statistics of the factor1*interval interaction\n\t\n\tOptional returns\n\t-------\n\t\n\tP_a : array\n\t\tP-statistics of the between-subject factor1\n\tP_s : array\n\t\tP-statistics of the within-subject interval\n\tP_sa : array\n\t\tP-statistics of the factor1*interval interaction\n\t\n\t\"\"\"\n\n\tif data_format == 'short':\n\t\tif data.ndim == 2:\n\t\t\tdata = data[:,:,np.newaxis]\n\t\t# get shapes for df\n\t\ts = data.shape[0]\n\t\tn = data.shape[1]\n\t\tendog_arr = data.reshape(s*n,data.shape[2])\n\telif data_format == 'long':\n\t\tn = len(dmy_factor1)\n\t\ts = len(data)/n\n\t\tendog_arr = data\n\telse:\n\t\tprint(\"Error: data format must be short or long.\")\n\n\t#ram clean-up\n\tdel data \n\n\tif dmy_factor1.ndim == 1:\n\t\tfa = 2\n\telse:\n\t\tfa = dmy_factor1.shape[1] + 1\n\n\tif rand_array is not None:\n\t\tif use_reduced_residuals:\n\t\t\tr_dmy_factor1_long = dmy_factor1\n\t\t\tif dmy_covariates is not None:\n\t\t\t\tr_dmy_covars_long = dmy_covariates\n\t\t\tfor i in range(s-1):\n\t\t\t\tr_dmy_factor1_long = np.concatenate((r_dmy_factor1_long,dmy_factor1),0)\n\t\t\t\tif dmy_covariates is not None:\n\t\t\t\t\tr_dmy_covars_long = np.concatenate((r_dmy_covars_long, dmy_covariates),0)\n\t\t\texog_vars = stack_ones(r_dmy_factor1_long)\n\t\t\tif dmy_covariates is not None:\n\t\t\t\texog_vars = np.column_stack((exog_vars, r_dmy_covars_long))\n\t\t\ta = cy_lin_lstsqr_mat(exog_vars,endog_arr)\n\t\t\tendog_arr = endog_arr - np.dot(exog_vars,a)\n\t\tnp.random.shuffle(endog_arr)\n\t\tdmy_factor1 = dmy_factor1[rand_array]\n\t\tif dmy_covariates is not None:\n\t\t\tdmy_covariates = dmy_covariates[rand_array]\n\n\t# convert to exogenous variables to long form\n\tinterval_long = np.zeros(n)\n\tdmy_factor1_long = dmy_factor1\n\tdmy_subjects_long = dmy_subjects\n\tif dmy_covariates is not None:\n\t\tdmy_covars_long = dmy_covariates\n\tfor i in range(s-1):\n\t\tdmy_factor1_long = np.concatenate((dmy_factor1_long,dmy_factor1),0)\n\t\tdmy_subjects_long = np.concatenate((dmy_subjects_long,dmy_subjects),0)\n\t\tinterval_long = np.concatenate((interval_long, np.ones(n)*(i+1)))\n\t\tif dmy_covariates is not None:\n\t\t\tdmy_covars_long = np.concatenate((dmy_covars_long, dmy_covariates),0)\n\tdmy_interval_long = dummy_code(interval_long, demean = False)\n\n\t# SS Totals\n\texog_vars = stack_ones(dmy_subjects_long)\n\tendog_arr = np.squeeze(endog_arr)\n\tSS_WithinSubjects = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_Total = np.sum((endog_arr - np.mean(endog_arr, axis = 0))**2, axis = 0)\n\tSS_BetweenSubjects = SS_Total - SS_WithinSubjects\n\n\t# SS between subject\n\texog_vars = stack_ones(dmy_factor1_long)\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\tif output_reduced_residuals:\n\t\ta, residuals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)\n\t\treduced_data = endog_arr - np.dot(exog_vars,a)\n\t\tdel a\n\telse:\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_cells_a = SS_Total - residuals\n\n\tif dmy_covariates is not None:\n\t\texog_vars = stack_ones(dmy_covars_long)\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\t\tSS_covars =(SS_Total - residuals)\n\telse:\n\t\tSS_covars = 0\n\n\tSS_a = SS_cells_a - SS_covars\n\tSS_WithinFactors = SS_BetweenSubjects - SS_a - SS_covars\n\n\t# SS time\n\texog_vars = stack_ones(dmy_interval_long)\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_s = SS_Total - residuals\n\n\t# SS covariates (same as above int then minus int)\n\tif dmy_covariates is not None:\n\t\texog_vars = stack_ones(dmy_covars_long)\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\t\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\t\tSS_cells_scovars = (SS_Total - residuals)\n\t\texog_vars = stack_ones(dmy_covars_long)\n\t\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\t\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\t\tSS_scovars = SS_cells_scovars - (SS_Total - residuals)\n\telse:\n\t\tSS_scovars = 0\n\n\t# SS Cells s*a\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\texog_vars = np.column_stack((exog_vars, column_product(dmy_factor1_long,dmy_interval_long)))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_Cells_sa = (SS_Total - residuals)\n\n\texog_vars = stack_ones(dmy_factor1_long)\n\texog_vars = np.column_stack((exog_vars, dmy_interval_long))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covars_long))\n\t\texog_vars = np.column_stack((exog_vars, column_product(dmy_covars_long,dmy_interval_long)))\n\tresiduals = cy_lin_lstsqr_mat_residual(exog_vars,endog_arr)[1]\n\tSS_sa = SS_Cells_sa - (SS_Total - residuals)\n\n\tSS_sWithinFactors = SS_WithinSubjects - SS_s - SS_sa - SS_scovars\n\n\t# Between subjects df\n\tdf_BetweenSubjects = n - 1\n\tdf_a = fa - 1\n\tif dmy_covariates is not None:\n\t\tif dmy_covariates.ndim == 1:\n\t\t\tdf_covars = 1\n\t\telse:\n\t\t\tdf_covars = dmy_covariates.shape[1]\n\telse:\n\t\tdf_covars = 0\n\tdf_WithinFactors = df_BetweenSubjects - df_a - df_covars\n\n\t# Within subjects df\n\tdf_s = s - 1\n\tdf_sa = df_a * df_s\n\tdf_sWithinFactor = df_WithinFactors * df_s\n\n\t# F-stats\n\t# Between subjects\n\tms_WithinFactors = np.divide(SS_WithinFactors, df_WithinFactors)\n\tF_a = np.divide(np.divide(SS_a, df_a), ms_WithinFactors)\n\n\t# Within subjects\n\tms_sWithinFactor = np.divide(SS_sWithinFactors, df_sWithinFactor)\n\tF_s = np.divide(np.divide(SS_s, df_s), ms_sWithinFactor)\n\n\tF_sa = np.divide(np.divide(SS_sa, df_sa), ms_sWithinFactor)\n\n\tif verbose:\n\t\tprint(\"Source\\t\\tDF\\tF(Max)\")\n\t\tprint(\"Factor\\t\\t(%d,%d)\\t%.2f\" % (df_a, df_WithinFactors, F_a.max()))\n\t\tprint(\"Time\\t\\t(%d,%d)\\t%.2f\" % (df_s, df_sWithinFactor, F_s.max()))\n\t\tprint(\"Factor*Time\\t(%d,%d)\\t%.2f\" % (df_sa, df_sWithinFactor, F_sa.max()))\n\n\tif output_sig:\n\t\t# Between subjects\n\t\tP_a = 1 - f.cdf(F_a,df_a,df_WithinFactors)\n\t\t# Within subjects\n\t\tP_s = 1 - f.cdf(F_s,df_s,df_sWithinFactor)\n\t\tP_sa = 1 - f.cdf(F_sa,df_sa,df_sWithinFactor)\n\t\treturn (F_a, F_s, F_sa, P_a, P_s, P_sa)\n\telse:\n\t\tif output_reduced_residuals:\n\t\t\treturn (F_a, F_s, F_sa, reduced_data)\n\t\telse:\n\t\t\treturn (F_a, F_s, F_sa)\ntfce_mediation/pyfunc.py\ndef import_voxel_neuroimage(image_path, mask_index = None):\n\t\"\"\"\n\tLow-RAM voxel-image importer using nibabel\n\t\n\tParameters\n\t----------\n\timage_path : string\n\t\tPATH/TO/IMAGE\n\t\n\tFlags\n\t----------\n\tmask_index : index array (bool or binary)\n\t\tMasks the image by non-zero index (Default = None)\n\t\n\tReturns\n\t-------\n\timage : array\n\t\tnibable image object\n\t\n\tOR\n\t\n\timage_data : array\n\t\tnumpy array of masked image data\n\t\n\t\"\"\"\n\tif not os.path.exists(image_path):\n\t\tprint('Error: %s not found' % image_path)\n\t\tquit()\n\tbase, file_ext = os.path.splitext(image_path)\n\tif file_ext == '.gz':\n\t\tfile_ext = os.path.splitext(base)[1]\n\t\tif file_ext == '.nii':\n\t\t\tif os.path.getsize(image_path) < 50000000:\n\t\t\t\timage = nib.load(image_path)\n\t\t\t\timage_data = image.get_data()\n\t\t\telse:\n\t\t\t\ttempname = str(uuid.uuid4().hex) + '.nii'\n\t\t\t\tos.system(\"zcat %s > %s\" % (image_path,tempname))\n\t\t\t\timage = nib.load(tempname)\n\t\t\t\timage_data = image.get_data()\n\t\t\t\tos.system(\"rm %s\" % tempname)\n\t\telse:\n\t\t\tprint('Error: filetype for %s is not supported' % image_path)\n\telif file_ext == '.nii':\n\t\timage = nib.load(image_path)\n\t\timage_data = image.get_data()\n\telif file_ext == '.mnc':\n\t\timage = nib.load(image_path)\n\t\timage_data = image.get_data()\n\telse:\n\t\tprint('Error filetype for %s is not supported' % file_ext)\n\t\tquit()\n\tprint(\"Imported:\\t%s\" % image_path)\n\tif mask_index is not None:\n\t\timage_data = image_data[mask_index]\n\t\treturn image_data\n\telse:\n\t\treturn image, image_data\ntfce_mediation/pyfunc.py\ndef glm_typeI(endog, exog, dmy_covariates = None, output_fvalues = True, output_tvalues = False, output_pvalues = False, verbose = True, rand_array = None, use_reduced_residuals = False, output_reduced_residuals = False, exog_names = None):\n\t\"\"\"\n\tGeneralized ANCOVA using Type I Sum of Squares\n\t\n\tParameters\n\t----------\n\tendog : array\n\t\tEndogenous (dependent) variable array (Nsubjects, Nvariables)\n\texog : array\n\t\tExogenous (independent) dummy coded variables\n\t\texog is an array of arrays (Nvariables, Nsubjects, Kvariable)\n\tdmy_covariates : array\n\t\tDummy coded array of covariates of no interest\n\t\n\tReturns\n\t---------\n\tTo-do\n\t\"\"\"\n\t\n\tn = endog.shape[0]\n\t\n\tkvars = []\n\texog_vars = np.ones((n))\n\tfor var in exog:\n\t\tvar = np.array(var)\n\t\tif var.ndim == 1:\n\t\t\tkvars.append((1))\n\t\telse:\n\t\t\tkvars.append((var.shape[1]))\n\t\texog_vars = np.column_stack((exog_vars,var))\n\tif dmy_covariates is not None:\n\t\texog_vars = np.column_stack((exog_vars, dmy_covariates))\n\texog_vars = np.array(exog_vars)\n\n\tif rand_array is not None:\n\t\tif use_reduced_residuals:\n\t\t\ta = cy_lin_lstsqr_mat(exog_vars,endog)\n\t\t\tendog = endog - np.dot(exog_vars,a)\n\t\texog_vars = exog_vars[rand_array]\n\n\tif output_reduced_residuals:\n\t\ta = cy_lin_lstsqr_mat(exog_vars,endog)\n\t\treduced_data = endog - np.dot(exog_vars,a)\n\n\tk = exog_vars.shape[1]\n\n\tDF_Between = k - 1 # aka df model\n\tDF_Within = n - k # aka df residuals\n\tDF_Total = n - 1\n\n\tSS_Total = np.sum((endog - np.mean(endog,0))**2,0)\n\ta, SS_Residuals = cy_lin_lstsqr_mat_residual(exog_vars,endog)\n\n\tif output_fvalues:\n\t\tSS_Between = SS_Total - SS_Residuals\n\t\tMS_Residuals = (SS_Residuals/DF_Within)\n\t\tFvalues = (SS_Between/DF_Between) / MS_Residuals\n\n\t\tif verbose:\n\t\t\tprint(\"Source\\t\\tDF\\tF(Max)\")\n\t\t\tprint(\"Model\\t\\t(%d,%d)\\t%.2f\" % (DF_Between, DF_Within, Fvalues.max()))\n\n\t\t# F value for exog\n\t\tFvar = []\n\t\tPvar = []\n\t\tstart = 1\n\t\tfor i, col in enumerate(kvars):\n\t\t\tstop = start + col\n\t\t\tSS_model = np.array(SS_Total - cy_lin_lstsqr_mat_residual(np.delete(exog_vars,np.s_[start:stop],1),endog)[1])\n\t\t\tFtemp = (SS_Between - SS_model)/(MS_Residuals*kvars[i])\n\t\t\tFvar.append(Ftemp)\n\t\t\tif verbose:\n\t\t\t\tif exog_names is not None:\n\t\t\t\t\tprint(\"%s\\t\\t(%d,%d)\\t%.2f\" % (exog_names[i], col, DF_Within, Ftemp.max()))\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Exog%d\\t\\t(%d,%d)\\t%.2f\" % ((i+1), col, DF_Within, Ftemp.max()))\n\t\t\tstart += col\n\t\t\tif output_pvalues:\n\t\t\t\tPvar.append(f.sf(Fvar[i],col,DF_Within))\n\n\tif output_tvalues:\n\t\tsigma2 = np.sum((endog - np.dot(exog_vars,a))**2,axis=0) / (n - k)\n\t\tinvXX = np.linalg.inv(np.dot(exog_vars.T, exog_vars))\n\t\tif endog.ndim == 1:\n\t\t\tse = np.sqrt(np.diag(sigma2 * invXX))\n\t\telse:\n\t\t\tnum_depv = endog.shape[1]\n\t\t\tse = se_of_slope(num_depv,invXX,sigma2,k)\n\t\tTvalues = a / se\n\t# return values\n\tif output_tvalues and output_fvalues:\n\t\tif output_pvalues:\n\t\t\tPmodel = f.sf(Fvalues,DF_Between,DF_Within)\n\t\t\tPvalues = t.sf(np.abs(Tvalues), DF_Total)*2\n\t\t\treturn (Fvalues, np.array(Fvar), Tvalues, Pmodel, np.array(Pvar), Pvalues)\n\t\telse:\n\t\t\tif output_reduced_residuals:\n\t\t\t\treturn (Fvalues, np.array(Fvar), Tvalues, reduced_data)\n\t\t\telse:\n\t\t\t\treturn (Fvalues, np.array(Fvar), Tvalues)\n\telif output_tvalues:\n\t\tif output_pvalues:\n\t\t\tPvalues = t.sf(np.abs(Tvalues), DF_Total)*2\n\t\t\treturn (Tvalues, Pvalues)\n\t\telse:\n\t\t\tif output_reduced_residuals:\n\t\t\t\treturn (Tvalues, reduced_data)\n\t\t\telse:\n\t\t\t\treturn Tvalues\n\telif output_fvalues:\n\t\tif output_pvalues:\n\t\t\tPmodel = f.sf(Fvalues,DF_Between,DF_Within)\n\t\t\treturn (Fvalues, np.array(Fvar), Pmodel, np.array(Pvar))\n\t\telse:\n\t\t\tif output_reduced_residuals:\n\t\t\t\treturn (Fvalues, np.array(Fvar), reduced_data)\n\t\t\telse:\n\t\t\t\treturn (Fvalues, np.array(Fvar))\n\telse:\n\t\tprint(\"No output has been selected\")\n", "answers": ["\t\t_, _, _, _, _, _, _, _, _, tAMPLITUDE_A, _, _ = glm_cosinor(endog = dmy_mediator, "], "length": 4296, "dataset": "repobench-p", "language": "python", "all_classes": null, "_id": "38b0fdc2e6ba905f92e2be3be48cfa03e3c67a82b1707555"}