text:
HA_CONFIG_NAME=${OPENSHIFT_HA_CONFIG_NAME:-"OpenShift-IPFailover"}

#  IP Failover config selector.
HA_SELECTOR=${OPENSHIFT_HA_SELECTOR:-""}

#  List of virtual IP addresses.
#
#  The value entries are comma-separated entries of the form:
#     <ipaddress-range|ipaddress>
#
#     where:  ipaddress-range = <start-ipaddress>-<endip>
#
#  Example:
#     OPENSHIFT_HA_VIRTUAL_IPS="10.42.42.42,10.100.1.20-24"
#
HA_VIPS=${OPENSHIFT_HA_VIRTUAL_IPS:-""}

#  Interface (ethernet) to use - bound by vrrp.
NETWORK_INTERFACE=${OPENSHIFT_HA_NETWORK_INTERFACE:-""}  # "enp0s8"

#  Service port to monitor for failover.
HA_MONITOR_PORT=${OPENSHIFT_HA_MONITOR_PORT:-"80"}

#  Number of initial replicas.
HA_REPLICA_COUNT=${OPENSHIFT_HA_REPLICA_COUNT:-"1"}

#  Offset value to use to set the virtual router ids. Using different offset
#  values allows multiple ipfailover configurations to exist within the
#  same cluster.
#     HA_VRRP_ID_OFFSET=30
#
HA_VRRP_ID_OFFSET=${OPENSHIFT_HA_VRRP_ID_OFFSET:-"0"}

#  ========================================================================
#  Default settings - not currently exposed or overriden on OpenShift.
#  ========================================================================

#  If your environment doesn't support multicast, you can send VRRP adverts
#  to a list of IPv{4,6} addresses using unicast.
#  Example:
#     UNICAST_PEERS="5.6.7.8,9.10.11.12,13.14.15.16"
UNICAST_PEERS=${OPENSHIFT_HA_UNICAST_PEERS:-""}

#  List of emails to send admin messages to. If the list of email ids is
#  too long, you can use a DL (distribution list) ala:
#   ADMIN_EMAILS=("ramr@redhat.com" "cops@acme.org")
ADMIN_EMAILS=(${OPENSHIFT_HA_ADMIN_EMAILS:-"root@localhost"})

#  Email sender - the from address in the email headers.
EMAIL_FROM="ipfailover@openshift.local"

#  IP address of the SMTP server.
SMTP_SERVER=${OPENSHIFT_HA_SMTP_SERVER:-"127.0.0.1"}

#  SMTP connect timeout (in seconds).
SMTP_CONNECT_TIMEOUT=30

#  VRRP will preempt a lower priority machine when a higher priority one
#  comes back online. You can change the preemption strategy to either:
#     "nopreempt"  - which allows the lower priority machine to maintain its
#                    'MASTER' status.
#     OR
#     "preempt_delay 300"  - waits 5 mins (in seconds) after startup to
#                            preempt lower priority MASTERs.
PREEMPTION="preempt_delay 300"

#  By default, the IP for binding vrrpd is the primary IP on the above
#  specified interface. If you want to hide the location of vrrpd, you can
#  specify a src_addr for multicast/unicast vrrp packets.
#     MULTICAST_SOURCE_IPADDRESS="1.2.3.4"
#     UNICAST_SOURCE_IPADDRESS="1.2.3.4"


text:
module B where

import A

{-# ANN module FromA #-}

redpajama_set_name: RedPajamaGithub


text:
.. _lino.tutorial.writing_fixtures:
.. _lino.tutorial.dpy:

================================
Writing Python fixtures
================================

.. to test just this doc:

    $ doctest docs/dev/pyfixtures/index.rst

   doctest init::

    >>> from atelier.sheller import Sheller
    >>> shell = Sheller('docs/dev/pyfixtures')

This tutorial shows how to use :doc:`the Python serializer
</topics/dpy>` for writing and loading demonstration data samples for
application prototypes and test suites.

We suppose that you have followed the :ref:`lino.tutorial.hello`
tutorial.

.. contents::
    :depth: 1
    :local:

Introduction
============

You know that a *fixture* is a collection of data records in one or
several tables which can be loaded into a database.  Django's
`Providing initial data for models
<https://docs.djangoproject.com/en/3.1/howto/initial-data/>`__ article
says that "fixtures can be written as XML, YAML, or JSON documents".
Well, Lino adds another format to this list: Python.

Here is a fictive minimal example of a Python fixture::

  from myapp.models import Foo
  def objects():
      yield Foo(name="First")
      yield Foo(name="Second")

A Python fixture is a normal Python module, stored in a file ending
with :file:`.py` and designed to being imported and exectued during
Django's :manage:`loaddata` command.  It is furthermore expected to
contain a function named ``objects`` which must take no parameters and
which must return (or yield) a list of database objects.

Writing your own fixture
========================

Create a directory named :xfile:`fixtures` in your local project
directory (the one you created in :ref:`lino.tutorial.hello`)::

   $ cd ~/projects/hello
   $ mkdir fixtures

Create an empty file :xfile:`__init__.py` in that directory to mark is
as a package::

   $ touch fixtures/__init__.py

Create a file `dumpy1.py` in that directory with the following
content, but don't hesitate to put your real name and data, this is
your local file.

.. literalinclude:: fixtures/dumpy1.py
    :linenos:

Initialize your database using this fixture::

  $ python manage.py initdb dumpy1

The output should be as follows:

>>> shell("python manage.py initdb dumpy1 --noinput")
... #doctest: +ELLIPSIS +REPORT_UDIFF +NORMALIZE_WHITESPACE
`initdb dumpy1` started on database .../default.db.
Operations to perform:
  Synchronize unmigrated apps: about, bootstrap3, cal, checkdata, contacts, countries, export_excel, extjs, gfks, jinja, lino, office, printing, staticfiles, system, users, xl
  Apply all migrations: contenttypes, sessions
Synchronizing apps without migrations:
  Creating tables...
    Creating table system_siteconfig
    Creating table users_user
    Creating table users_authority
    Creating table countries_country
    Creating table countries_place
    Creating table contacts_partner
    Creating table contacts_person
    Creating table contacts_companytype
    Creating table contacts_company
    Creating table contacts_roletype
    Creating table contacts_role
    Creating table gfks_helptext
    Creating table checkdata_problem
    Creating table cal_remotecalendar
    Creating table cal_room
    Creating table cal_eventtype
    Creating table cal_guestrole
    Creating table cal_calendar
    Creating table cal_subscription
    Creating table cal_task
    Creating table cal_eventpolicy
    Creating table cal_recurrentevent
    Creating table cal_event
    Creating table cal_guest
    Running deferred SQL...
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying sessions.0001_initial... OK
Loading data from .../docs/dev/pyfixtures/fixtures/dumpy1.py
Installed 2 object(s) from 1 fixture(s)

Let's use the :manage:`show` command to see whether our data has been
imported::

    $ python manage.py show users.Users

The output should be as follows:

>>> shell("python manage.py show users.AllUsers")
... #doctest: +ELLIPSIS
========== =========== ============ ===========
 Username   User type   First name   Last name
---------- ----------- ------------ -----------
 jdupond                Jean         Dupond
 pbommel                Piet         Bommel
========== =========== ============ ===========

.. _tutorial.instantiator:

The ``Instantiator`` class
==========================

Since `.py` fixtures are normal Python modules, there are no more
limits to our phantasy when creating new objects.  A first thing that
might drop into our mind is that there should be a more "compact" way
to create many records of a same table.

A quick generic method for writing more compact fixtures this is the
:class:`Instantiator <lino.utils.instantiator.Instantiator>` class.
Here is the same fixture using an instantiator:

.. literalinclude:: fixtures/dumpy2.py
    :linenos:

Note that the name ``User`` in that file refers to the :meth:`build
<lino.utils.instantiator.Instantiator.build>` method of an
:class:`Instantiator <lino.utils.instantiator.Instantiator>` instance,
not to some User model.

The :class:`Instantiator <lino.utils.instantiator.Instantiator>` class
is just a little utility. It helps us to eliminate some lines of the
code, nothing more (and nothing less). Compare the two source files on
this page and imagine you want to maintain these fixtures. For example
add a third user, or add a new field for every user.  Which one will
be easier to maintain?

Python fixtures are intelligent
===============================

Note the difference between "intelligent" and "dumped" fixtures: An
**intelligent fixture** is written by a human and used to provide demo
data to a Lino application (see :doc:`/dev/pyfixtures/index`).  A **dumped
fixture** is generated by the :command:`dumpdata` or
:command:`dump2py` command and looks much less readable because it is
optimized to allow automated database migrations.

Python fixtures are a powerful tool.  You can use them to generate
demo data in many different ways. Look for example at the source code
of the following fixtures:

- :mod:`lino_xl.lib.notes.fixtures.demo`.

- :mod:`lino.modlib.users.fixtures.demo_users`

- :mod:`lino_xl.lib.countries.fixtures.few_countries`

- :mod:`lino_xl.lib.countries.fixtures.all_countries`

- :mod:`lino_xl.lib.countries.fixtures.few_cities`
- :mod:`lino_xl.lib.countries.fixtures.all_cities`
- :mod:`lino_xl.lib.countries.fixtures.be`
- :mod:`lino_xl.lib.countries.fixtures.eesti`

- :mod:`lino.modlib.languages.fixtures.few_languages`
- :mod:`lino.modlib.languages.fixtures.all_languages`

Play with them by trying your own combinations::

  $ python manage.py initdb std all_countries be few_languages props demo
  $ python manage.py initdb std few_languages few_countries few_cities demo
  ...

Exercise
========

- Get inspired by the examples above and extend your :file:`dumpy2.py`
  fixture.

- Publish your code somewhere (e.g. in a blog or on GitHub) so that we
  can refer to it here and others can learn from it.

Python fixtures are modularizable
=================================

Lino encourages fine-grained modularity of your fixtures because as an
application developer your can use the :attr:`demo_fixtures
<lino.core.site.Site.demo_fixtures>` setting in order to specify a
**default set** of fixture names to be loaded.  Check the
:ref:`demo_fixtures` section in case you didn't know this.

Python fixtures don't like relative imports
===========================================

There is one (minor) limitation to your phantasy when writing Python
fixtures: you cannot use relative imports in a Python
fixture.  See `here
<http://stackoverflow.com/questions/4907054/loading-each-py-file-in-a-path-imp-load-module-complains-about-relative-impor>`__

Conclusion
==========

Python fixtures are an important tool for application developers
because

- they are more flexible than json or xml fixtures and easy to adapt
  when your database structure changes.

- they provide a simple and modular way to deploy demo data for your
  application


text:
<system>
	<factory>
		<!-- Providers -->

		<instance name="subtypeInfoProvider" class="BeeeOn::SubtypeInfoProvider">
			<set name="enumsFile" text="${spec.enums.xml}" />
			<set name="bitmapsFile" text="${spec.bitmaps.xml}" />
		</instance>

		<instance name="typeInfoProvider" class="BeeeOn::TypeInfoProvider">
			<set name="typesFile" text="${spec.types.xml}" />
		</instance>

		<instance name="deviceInfoProvider" class="BeeeOn::DeviceInfoProvider">
			<set name="typeInfoProvider" ref="typeInfoProvider" />
			<set name="subtypeInfoProvider" ref="subtypeInfoProvider" />
			<set name="devicesFile" text="${spec.devices.xml}" />
		</instance>

		<instance name="devicePropertiesCryptoConfig" class="BeeeOn::CryptoConfig">
			<set name="algorithm" text="${secure.device_properties.algorithm}" />
			<set name="passphrase" text="${secure.device_properties.passphrase}" />
		</instance>

		<instance name="pocoRandomProvider"
				class="BeeeOn::PocoRandomProvider" />

		<instance name="mockRandomProvider"
				class="BeeeOn::MockRandomProvider">
			<set name="nextRandom" text="0123456789abcdef" />
		</instance>

		<instance name="insecureRandomProvider"
				class="BeeeOn::InsecureRandomProvider">
			<set name="providerImpl" ref="mockRandomProvider" />
		</instance>

		<instance name="loggingQueryProfiler" class="BeeeOn::LoggingQueryProfiler" />

		<!-- RPC communication -->

		<instance name="fakeGatewayRPC" class="BeeeOn::FakeGatewayRPC">
			<set name="deviceDao" ref="deviceDao" />
			<set name="asyncExecutor" ref="eventsExecutor" />
		</instance>

		<instance name="asyncGatewayRPC" class="BeeeOn::AsyncGatewayRPC">
			<set name="gatewayCommunicator" ref="gatewayCommunicator" />
			<set name="responseExpectedQueue" ref="responseExpectedQueue" />
			<set name="defaultTimeout" time="${gateway-rpc.async.defaultTimeout}" />
			<set name="devicePropertyDao" ref="devicePropertyDao" />
			<set name="cryptoConfig" ref="devicePropertiesCryptoConfig" />
		</instance>

		<alias name="gatewayRPC" ref="${gateway-rpc.type}GatewayRPC" />

		<!-- Data access layer -->

		<alias name="userDao" ref="sqlUserDao" />
		<alias name="gatewayDao" ref="sqlGatewayDao" />
		<alias name="gatewayMessageDao" ref="sqlGatewayMessageDao" />
		<alias name="gatewayStatusDao" ref="sqlGatewayStatusDao" />
		<alias name="locationDao" ref="sqlLocationDao" />
		<alias name="deviceDao" ref="sqlDeviceDao" />
		<alias name="devicePropertyDao" ref="sqlDevicePropertyDao" />
		<alias name="identityDao" ref="sqlIdentityDao" />
		<alias name="verifiedIdentityDao" ref="sqlVerifiedIdentityDao" />
		<alias name="roleInGatewayDao" ref="sqlRoleInGatewayDao" />
		<alias name="sensorHistoryDao" ref="sqlSensorHistoryDao" />
		<alias name="controlDao" ref="sqlControlDao" />
		<alias name="fcmTokenDao" ref="sqlFcmTokenDao" />
		<alias name="fcmRecipientsDao" ref="sqlFcmRecipientsDao" />

		<instance name="primaryDaoManager"
				class="BeeeOn::PocoDaoManager">
			<set name="connector" ref="${database.backend}Connector" />
			<set name="connectionString" text="${database.connector}" />
			<set name="connectionTimeout" time="${database.timeout}" />
			<set name="features" text="${database.features}" />
			<set name="maxSessions" number="${database.pool}" />
			<add name="initializers" ref="primaryTestSchemaInitializer" if-yes="${testing.enable}" />
			<add name="initializers" ref="primaryTestDataInitializer" if-yes="${testing.enable}" />
		</instance>

		<instance name="primaryTestSchemaInitializer" class="BeeeOn::PocoSqitchInitializer">
			<set name="planFile" text="db/pgsql/sqitch.plan" />
			<set name="baseDir" text="${application.configDir}../db/pgsql" />
		</instance>

		<instance name="primaryTestDataInitializer" class="BeeeOn::PocoSimpleDBInitializer">
			<set name="script" text="${application.configDir}../t/testing-data.sql" />
		</instance>

		<constant name="cassandra.pool" number="${cassandra.pool}" />

		<instance name="cassandraDaoManager"
				class="BeeeOn::PocoDaoManager">
			<set name="connector" ref="cassandraConnector" />
			<set name="connectionString" text="${cassandra.connector}" />
			<set name="connectionTimeout" time="${cassandra.timeout}" />
			<set name="features" text="${cassandra.features}" />
			<set name="maxSessions" number="${cassandra.pool}" />
		</instance>

		<instance name="pocoTransactionFactory"
				class="BeeeOn::PocoTransactionFactory">
			<set name="daoManager" ref="primaryDaoManager" />
		</instance>

		<instance name="transactionManager" class="BeeeOn::ThreadLocalTransactionManager">
			<set name="factory" ref="pocoTransactionFactory" />
		</instance>

		<instance name="sqliteConnector"
				class="BeeeOn::PocoSQLiteConnectorLoader"
				library="BeeeOnServerSQLiteConnector" />

		<instance name="odbcConnector"
				class="BeeeOn::PocoODBCConnectorLoader"
				library="BeeeOnServerODBCConnector" />

		<instance name="cassandraConnector"
				class="BeeeOn::PocoCassandraConnectorLoader"
				library="BeeeOnServerCassandraConnector" />

		<instance name="sqlUserDao" class="BeeeOn::PocoSQLUserDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="localeManager" ref="localeManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlIdentityDao" class="BeeeOn::PocoSQLIdentityDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlVerifiedIdentityDao"
				class="BeeeOn::PocoSQLVerifiedIdentityDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="localeManager" ref="localeManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlRoleInGatewayDao"
				class="BeeeOn::PocoSQLRoleInGatewayDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
			<set name="timeZoneProvider" ref="timeZoneProvider" />
		</instance>

		<instance name="sqlGatewayDao" class="BeeeOn::PocoSQLGatewayDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
			<set name="timeZoneProvider" ref="timeZoneProvider" />
			<set name="communicator" ref="gatewayCommunicator" />
		</instance>

		<instance name="sqlGatewayMessageDao" class="BeeeOn::PocoSQLGatewayMessageDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlGatewayStatusDao" class="BeeeOn::PocoSQLGatewayStatusDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlLocationDao" class="BeeeOn::PocoSQLLocationDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlDeviceDao" class="BeeeOn::PocoSQLDeviceDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="deviceInfoProvider" ref="deviceInfoProvider" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlDevicePropertyDao" class="BeeeOn::PocoSQLDevicePropertyDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlSensorHistoryDao" class="BeeeOn::PocoSQLSensorHistoryDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlControlDao" class="BeeeOn::PocoSQLControlDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlFcmTokenDao" class="BeeeOn::PocoSQLFCMTokenDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="sqlFcmRecipientsDao" class="BeeeOn::PocoSQLFCMRecipientsDao">
			<set name="daoManager" ref="primaryDaoManager" />
			<set name="transactionManager" ref="transactionManager" />
			<set name="sqlLoader" ref="sqlLoader" />
			<set name="profiler" ref="loggingQueryProfiler" />
		</instance>

		<instance name="iniSqlLoader" class="BeeeOn::IniFileQueryLoader">
			<set name="database" text="beeeon" />
			<set name="file" text="${database.queries.ini.file}" />
		</instance>

		<instance name="fsSqlLoader" class="BeeeOn::FilesystemQueryLoader">
			<set name="rootPath" text="${database.queries.fs.rootDir}" />
			<set name="extension" text="sql" />
			<add name="preprocessors" ref="sqlQuerySimplifier" />
		</instance>

		<instance name="sqlQuerySimplifier" class="BeeeOn::SQLPreprocessor">
			<add name="preserveUnneededLines" number="${database.queries.fs.preserveLines}" />
		</instance>

		<alias name="sqlLoader" ref="${database.queries.impl}SqlLoader" />
	</factory>
</system>


text:
#ifndef llamaos_net_intel_regs_xontxc_h_
#define llamaos_net_intel_regs_xontxc_h_

#include <cstdint>

#include <ostream>

namespace apps {
namespace net {
namespace intel {
namespace regs {

/**
 * @brief XON Transmitted Count register.
 *
 */
class XONTXC
{
public:

   /**
    * @breif Construct from value.
    *
    * @param value Initial value (usually read from hardware).
    *
    */
   XONTXC (uint32_t value);

   /**
    * @breif Convert to 32-bit integer.
    *
    */
   operator uint32_t () const;

private:
   uint32_t value;

};

/**
 * @brief Stream insertion operator.
 *
 */
std::ostream &operator<< (std::ostream &, const XONTXC &);

} } } }

#endif // llamaos_net_intel_regs_xontxc_h_


text:
'use strict';

require('array.prototype.find');
var util = require('./util');

var extractPrData = function (pr) {
    // BitBucket api is not returning the PR url for all actions so far (2014-09-26, only create action)
    var getKey = util.getPossiblyUndefinedKeyValue.bind(this, pr);

    var data = {
        prAuthor            : getKey('author.display_name'),
        prUrl               : getKey('links.html.href'),
        prTitle             : getKey('title'),

        user                : getKey('user.display_name'),

        repoName            : getKey('source.repository.name'),
        repoSourceName      : getKey('source.branch.name'),
        repoDestinationName : getKey('destination.branch.name'),

        reason              : getKey('reason'),
        state               : getKey('state'),
        description         : getKey('description'),

        commentUrl          : getKey('links.html.href'),
        commentContentRaw   : getKey('content.raw')
    };

    return data;
};

module.exports = (function () {
    var baseHandler = function (pr) {
        var data = extractPrData(pr);

        var result = {
            fields: [{
                title: data.prTitle,
                value: 'State: ' + data.state + '.',
                short: true
            }, {
                title: 'Repo / Branches:',
                value: data.repoName + ' (' + data.repoSourceName + ' → ' + data.repoDestinationName + ')',
                short: true
            }]
        };

        if (data.reason) {
            result.fields.push({
                title: 'Reason:',
                value: data.reason
            });
        }

        return { result: result, data: data };
    };

    var messageHandlers = {
        created: function (pr) {
            var data = extractPrData(pr);

            var result = {
                fallback: '<' + data.prUrl + '|PR *created* by ' + data.prAuthor + '> for ' + data.repoName + ':',
                color: util.COLORS.blue,
                fields: [{
                    title: data.prTitle,
                    value: data.repoSourceName + ' → ' + data.repoDestinationName
                }, {
                    title: 'Repo / Branches:',
                    value: data.repoName + ' (' + data.repoSourceName + ' → ' + data.repoDestinationName + ')',
                    short: true
                }]
            };

            return result;
        },

        updated: function (pr) {
            var handled = baseHandler(pr);
            var result = handled.result;
            var data = handled.data;

            result.fallback = 'PR *updated* by ' + data.prAuthor + ' for ' + data.repoName + ':';
            result.color = util.COLORS.blue;

            return result;
        },

        approve: function (pr) {
            var data = extractPrData(pr);

            var result = {
                fallback: data.user + ' *approved* a PR.',
                color: util.COLORS.green
            };

            return result;
        },

        unapprove: function (pr) {
            var data = extractPrData(pr);

            var result = {
                fallback: data.user + ' *UNapproved* a PR.',
                color: util.COLORS.yellow
            };

            return result;
        },

        declined: function (pr) {
            var handled = baseHandler(pr);
            var result = handled.result;

            result.fallback = 'PR *declined*:';
            result.color = util.COLORS.red;

            return result;
        },

        merged: function (pr) {
            var handled = baseHandler(pr);
            var result = handled.result;

            result.fallback = 'PR *merged*:';
            result.color = util.COLORS.green;

            return result;
        },

        comment_created: function (pr) {
            var data = extractPrData(pr);

            var result = {
                fallback: data.user + ' *posted* <' + data.commentUrl + '|a comment> on a PR:',
                color: util.COLORS.yellow,
                fields: [{
                    value: util.truncate(data.commentContentRaw)
                }]
            };

            return result;
        },

        comment_deleted: function (pr) {
            var data = extractPrData(pr);

            var result = {
                fallback: data.user + ' *deleted* <' + data.commentUrl + '|a comment> on a PR:',
                color: util.COLORS.yellow,
                fields: [{
                    value: util.truncate(data.commentContentRaw)
                }]
            };

            return result;
        },

        comment_updated: function (pr) {
            var data = extractPrData(pr);

            var result = {
                fallback: data.user + ' *updated* <' + data.commentUrl + '|a comment> on a PR:',
                color: util.COLORS.yellow,
                fields: [{
                    value: util.truncate(data.commentContentRaw)
                }]
            };

            return result;
        }
    };

    /**
     * Examine the message from Bitbucket to determine the message to send
     * to the notification service. See [0] for the messages Bitbucket
     * may send.
     *
     * 0: https://confluence.atlassian.com/display/BITBUCKET/Pull+Request+POST+hook+management
     **/
    var generateMessage = function (message) {
        var supportedActions = [
            'created',
            'updated',
            'approve',
            'unapprove',
            'declined',
            'merged',
            'comment_created',
            'comment_deleted',
            'comment_updated'
        ];

        var action = supportedActions.find(function (action) {
            return message['pullrequest_' + action] !== undefined;
        });

        if (!action) {
            console.log('An unknown action was submitted:', message);
            return undefined;
        }

        return messageHandlers[action](message['pullrequest_' + action]);
    };

    return {
        generateMessage: generateMessage
    };
})();


text:
package org.frameworkset.util;

import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
Title: BridgeMethodResolver.java

 *
Description:

 *
bboss workgroup

 *
Copyright (c) 2008

 * @Date 2010-10-24
 * @author biaoping.yin
 * @version 1.0
 */
public abstract class BridgeMethodResolver {

	/**
	 * Find the original method for the supplied {@link Method bridge Method}.
	 *
It is safe to call this method passing in a non-bridge {@link Method} instance.
	 * In such a case, the supplied {@link Method} instance is returned directly to the caller.
	 * Callers are not required to check for bridging before calling this method.
	 * @throws IllegalStateException if no bridged {@link Method} can be found
	 */
	public static Method findBridgedMethod(Method bridgeMethod) {
		if (bridgeMethod == null || !bridgeMethod.isBridge()) {
			return bridgeMethod;
		}

		// Gather all methods with matching name and parameter size.
		List candidateMethods = new ArrayList();
		Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass());
		for (int i = 0; i < methods.length; i++) {
			Method candidateMethod = methods[i];
			if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) {
				candidateMethods.add(candidateMethod);
			}
		}

		Method result;
		// Now perform simple quick checks.
		if (candidateMethods.size() == 1) {
			result = (Method) candidateMethods.get(0);
		}
		else {
			result = searchCandidates(candidateMethods, bridgeMethod);
		}

		if (result == null) {
			throw new IllegalStateException(
					"Unable to locate bridged method for bridge method '" + bridgeMethod + "'");
		}

		return result;
	}

	/**
	 * Searches for the bridged method in the given candidates.
	 * @param candidateMethods the List of candidate Methods
	 * @param bridgeMethod the bridge method
	 * @return the bridged method, or null if none found
	 */
	private static Method searchCandidates(List candidateMethods, Method bridgeMethod) {
		Map typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass());
		for (int i = 0; i < candidateMethods.size(); i++) {
			Method candidateMethod = (Method) candidateMethods.get(i);
			if (isBridgeMethodFor(bridgeMethod, candidateMethod, typeParameterMap)) {
				return candidateMethod;
			}
		}
		return null;
	}

	/**
	 * Returns true if the supplied 'candidateMethod' can be
	 * consider a validate candidate for the {@link Method} that is {@link Method#isBridge() bridged}
	 * by the supplied {@link Method bridge Method}. This method performs inexpensive
	 * checks and can be used quickly filter for a set of possible matches.
	 */
	private static boolean isBridgedCandidateFor(Method candidateMethod, Method bridgeMethod) {
		return (!candidateMethod.isBridge() && !candidateMethod.equals(bridgeMethod) &&
				candidateMethod.getName().equals(bridgeMethod.getName()) &&
				candidateMethod.getParameterTypes().length == bridgeMethod.getParameterTypes().length);
	}

	/**
	 * Determines whether or not the bridge {@link Method} is the bridge for the
	 * supplied candidate {@link Method}.
	 */
	static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map typeVariableMap) {
		if (isResolvedTypeMatch(candidateMethod, bridgeMethod, typeVariableMap)) {
			return true;
		}
		Method method = findGenericDeclaration(bridgeMethod);
		return (method != null && isResolvedTypeMatch(method, candidateMethod, typeVariableMap));
	}

	/**
	 * Searches for the generic {@link Method} declaration whose erased signature
	 * matches that of the supplied bridge method.
	 * @throws IllegalStateException if the generic declaration cannot be found
	 */
	private static Method findGenericDeclaration(Method bridgeMethod) {
		// Search parent types for method that has same signature as bridge.
		Class superclass = bridgeMethod.getDeclaringClass().getSuperclass();
		while (!Object.class.equals(superclass)) {
			Method method = searchForMatch(superclass, bridgeMethod);
			if (method != null && !method.isBridge()) {
				return method;
			}
			superclass = superclass.getSuperclass();
		}

		// Search interfaces.
		Class[] interfaces = ClassUtils.getAllInterfacesForClass(bridgeMethod.getDeclaringClass());
		for (int i = 0; i < interfaces.length; i++) {
			Class anInterface = interfaces[i];
			Method method = searchForMatch(anInterface, bridgeMethod);
			if (method != null && !method.isBridge()) {
				return method;
			}
		}

		return null;
	}

	/**
	 * Returns true if the {@link Type} signature of both the supplied
	 * {@link Method#getGenericParameterTypes() generic Method} and concrete {@link Method}
	 * are equal after resolving all {@link TypeVariable TypeVariables} using the supplied
	 * TypeVariable Map, otherwise returns false.
	 */
	private static boolean isResolvedTypeMatch(Method genericMethod, Method candidateMethod, Map typeVariableMap) {
		Type[] genericParameters = genericMethod.getGenericParameterTypes();
		Class[] candidateParameters = candidateMethod.getParameterTypes();
		if (genericParameters.length != candidateParameters.length) {
			return false;
		}
		for (int i = 0; i < genericParameters.length; i++) {
			Type genericParameter = genericParameters[i];
			Class candidateParameter = candidateParameters[i];
			if (candidateParameter.isArray()) {
				// An array type: compare the component type.
				Type rawType = GenericTypeResolver.getRawType(genericParameter, typeVariableMap);
				if (rawType instanceof GenericArrayType) {
					if (!candidateParameter.getComponentType().equals(
							GenericTypeResolver.resolveType(((GenericArrayType) rawType).getGenericComponentType(), typeVariableMap))) {
						return false;
					}
					break;
				}
			}
			// A non-array type: compare the type itself.
			if (!candidateParameter.equals(GenericTypeResolver.resolveType(genericParameter, typeVariableMap))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * If the supplied {@link Class} has a declared {@link Method} whose signature matches
	 * that of the supplied {@link Method}, then this matching {@link Method} is returned,
	 * otherwise null is returned.
	 */
	private static Method searchForMatch(Class type, Method bridgeMethod) {
		return ReflectionUtils.findMethod(type, bridgeMethod.getName(), bridgeMethod.getParameterTypes());
	}

}


text:
class ValueListImpl;

namespace lldb {

class LLDB_API SBValueList {
public:
  SBValueList();

  SBValueList(const lldb::SBValueList &rhs);

  ~SBValueList();

  bool IsValid() const;

  void Clear();

  void Append(const lldb::SBValue &val_obj);

  void Append(const lldb::SBValueList &value_list);

  uint32_t GetSize() const;

  lldb::SBValue GetValueAtIndex(uint32_t idx) const;

  lldb::SBValue GetFirstValueByName(const char *name) const;

  lldb::SBValue FindValueObjectByUID(lldb::user_id_t uid);

  const lldb::SBValueList &operator=(const lldb::SBValueList &rhs);

protected:
  // only useful for visualizing the pointer or comparing two SBValueLists to
  // see if they are backed by the same underlying Impl.
  void *opaque_ptr();

private:
  friend class SBFrame;

  SBValueList(const ValueListImpl *lldb_object_ptr);

  void Append(lldb::ValueObjectSP &val_obj_sp);

  void CreateIfNeeded();

  ValueListImpl *operator->();

  ValueListImpl &operator*();

  const ValueListImpl *operator->() const;

  const ValueListImpl &operator*() const;

  ValueListImpl &ref();

  std::unique_ptr<ValueListImpl> m_opaque_ap;
};

} // namespace lldb

#endif // LLDB_SBValueList_h_


text:
from itertools import permutations
def numbers_game(lis):
    for perm in permutations(lis):
        valid = True
        for i in range(0, len(lis)-1):
            #To the right of each even number must be either be an odd number, or the same evennumber.
            if perm[i] % 2 == 0:
                if not(perm[i+1] % 2 != 0 or perm[i] == perm[i+1]):
                    valid = False
                    break
            #To the right of each odd number must be either a larger even number or a strictly smaller odd number.
            if perm[i] % 2 != 0:
                if not((perm[i+1] > perm[i] and perm[i+1] % 2 == 0) or (perm[i+1] < perm[i] and perm[i+1] % 2 != 0)):
                    valid = False
                    break

        if valid:
            return True
    return valid

##def numbers_game(lis):
##    for perm in permutations(lis):
##        if isValid(perm):
##            return True
##    return False
##
##def isValid(perm):
##    for i in range(0, len(perm)-1):
##        # To the right of each even number must be either be an odd number, or the same even number.
##        if perm[i] % 2 == 0:
##            if (perm[i+1] % 2 != 0 or perm[i] == perm[i+1]):
##                continue
##            else:
##                return False
##        # To the right of each odd number must be either a larger even number or a strictly smaller odd number.
##        if perm[i] % 2 != 0:
##            if (perm[i+1] > perm[i] and perm[i+1] % 2 == 0) or (perm[i+1] < perm[i] and perm[i+1] % 2 != 0):
##                continue
##            else:
##                return False
##
##    return True

print(numbers_game([8,3,29,12,7,1,20,39]))
#True
print(numbers_game([3,2,4,6,3,3,15,3]))
#False


text:
package cn.com.newcapec.citycard.system.dao.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import cn.com.newcapec.common.dao.impl.BaseDao;
import cn.com.newcapec.common.domain.NameValue;
import cn.com.newcapec.citycard.common.po.TOrgMapUserRole;
import cn.com.newcapec.citycard.common.po.TOrgRole;
import cn.com.newcapec.citycard.system.dao.IRoleInfoDao;

/**
 * <p>
 * 角色操作类用到的特殊DAO
 *
 * @author: Wangjian
 * @version: 1.0 May 8, 2008 10:34:33
 */
public class RoleInfoDao extends BaseDao implements IRoleInfoDao {

	/**
	 * 查询当前满足查询条件的记录总数
	 *
	 * @param roleInfo:
	 *            RoleInfo对象
	 * @return 根据给定的roleInfo返回记录总数
	 */
	public Integer getRoleInfoCountByQuery(TOrgRole roleInfo) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(TOrgRole.class);
		if (null != roleInfo) {
			String roleName = roleInfo.getRoleName();
			detachedCriteria.add(Restrictions.like(TOrgRole.PROP_ROLE_NAME,
					roleName.trim(), MatchMode.ANYWHERE));
		}
//		detachedCriteria.addOrder(Order.asc(TOrgRole.PROP_ID));
		return getCountsByCriteria(detachedCriteria);
	}

	/**
	 * 功能描述:得到满足查询条件的角色分页列表
	 *
	 * @param roleInfo
	 *            查询条件
	 * @param firstResult
	 *            从第几条开始
	 * @param maxResults
	 *            共取几条
	 *
	 * @return List 角色类型列表
	 */
	@SuppressWarnings("unchecked")
	public List<TOrgRole> getRoleInfoListByQuery(TOrgRole roleInfo,
			int firstResult, int maxResults) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(TOrgRole.class);
		if (null != roleInfo) {
			String roleName = roleInfo.getRoleName();
			detachedCriteria.add(Restrictions.like(TOrgRole.PROP_ROLE_NAME,
					roleName.trim(), MatchMode.ANYWHERE));
		}
		detachedCriteria.addOrder(Order.asc(TOrgRole.PROP_ID));
		return this.getPaginationListByCriteria(detachedCriteria, firstResult,
				maxResults);
	}

	/**
	 * 功能描述:检索重复角色的记录数
	 *
	 * @param RoleInfo
	 *            角色
	 *
	 * @return Integer 重复角色的记录数
	 */
	public Integer getRoleInfoCountByName(String roleName) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(
				TOrgRole.class).add(
				Restrictions.eq(TOrgRole.PROP_ROLE_NAME, roleName));
		return getCountsByCriteria(detachedCriteria);
	}

	/**
	 * 功能描述:得到所有的角色
	 *
	 *
	 * @return List 角色列表
	 */
	@SuppressWarnings("unchecked")
	public List<TOrgRole> getRoleInfoList() {
		return getAll(TOrgRole.class);
	}

	/**
	 * 获得所有可用角色名值对列表
	 *
	 * @author Wangjian
	 *
	 * @return list 角色名值对列表
	 */
	@SuppressWarnings("unchecked")
	public List getRoleInfoNameValueList() {
		return getListByHQL(getRoleInfoNameValueList);
	}

	private static final String getRoleInfoNameValueList = "select new cn.com.newcapec.common.domain.NameValue(roleName,id) from TOrgRole order by id";

	/**
	 * 判断角色用户表中是否有相应角色的用户存在
	 *
	 * @return 根据给定的idList返回记录总数
	 */
	public Integer checkUserRoleInfoCountByIdList(List<Integer> idList) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(
				TOrgMapUserRole.class).add(
				Restrictions.in(TOrgMapUserRole.PROP_FK_ROLE, idList));
		return getCountsByCriteria(detachedCriteria);
	}

	/**
	 * 删除指定的角色记录
	 *
	 * @param idList
	 *            角色名称ID列表
	 */
	@SuppressWarnings("unchecked")
	public void deleteRoleInfoByIdList(List idList) {

		if (checkUserRoleInfoCountByIdList(idList) > 0) {
			bulkUpdate(deleteUserRoleByIdList, new String[] { "idList" },
					new Object[] { idList });
		}
		bulkUpdate(deleteRoleByIdList, new String[] { "idList" },
				new Object[] { idList });
	}

	private static final String deleteUserRoleByIdList = "delete TOrgMapUserRole where fkRole in (:idList)";

	private static final String deleteRoleByIdList = "delete TOrgRole where id in (:idList)";

	/**
	 * 查找指定的用户已分配的角色列表
	 * @param userId  用户ID
	 * @return List 指定的用户已分配的角色列表
	 */
	@SuppressWarnings("unchecked")
	public List<NameValue> getUserHaveRoleInfoListByUserId(Integer userId){
		return getListByHQL(getUserHaveRoleInfoListByUserId,new Object[]{userId});
	}

	private static final String getUserHaveRoleInfoListByUserId = "select new cn.com.newcapec.common.domain.NameValue(roleName,id) from TOrgRole where "
		                                                        +"  id in (select fkRole from TOrgMapUserRole where fkUser=?) order by id";

	/**
	 * 查找指定的用户未分配的角色列表
	 * @param userId  用户ID
	 * @return List 指定的用户未分配的角色列表
	 */
	@SuppressWarnings("unchecked")
	public List<NameValue> getUserNoRoleInfoListByUserId(Integer userId){
		return getListByHQL(getUserNoRoleInfoListByUserId,new Object[]{userId});
	}

	private static final String getUserNoRoleInfoListByUserId = "select new cn.com.newcapec.common.domain.NameValue(roleName,id) from TOrgRole where "
        +"  id not in (select fkRole from TOrgMapUserRole where fkUser=?) order by id";

}


text:
require.paths.unshift('spec', '/opt/local/lib/ruby/gems/1.8/gems/jspec-4.1.0/lib', 'lib')
require('jspec')
require('unit/spec.helper')

JSpec
  .exec('spec/unit/spec.js')
  .run({ reporter: JSpec.reporters.Terminal, fixturePath: 'spec/fixtures', failuresOnly: true })
  .report()


text:
/*	$NetBSD: defs.h,v 1.11 2011/08/31 13:32:40 joerg Exp $	*/

/*
 * Copyright (c) 1988, 1992 The University of Utah and the Center
 *	for Software Science (CSS).
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * the Center for Software Science of the University of Utah Computer
 * Science Department.  CSS requests users of this software to return
 * to css-dist@cs.utah.edu any improvements that they make and grant
 * CSS redistribution rights.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	from: @(#)defs.h	8.1 (Berkeley) 6/4/93
 *
 * From: Utah Hdr: defs.h 3.1 92/07/06
 * Author: Jeff Forys, University of Utah CSS
 */

#include "rmp.h"
#include "rmp_var.h"

/*
**  Common #define's and external variables.  All other files should
**  include this.
*/

/*
 *  This may be defined in <sys/param.h>, if not, it's defined here.
 */
#ifndef	MAXHOSTNAMELEN
#define	MAXHOSTNAMELEN 64
#endif

/*
 *  SIGUSR1 and SIGUSR2 are defined in <signal.h> for 4.3BSD systems.
 */
#ifndef SIGUSR1
#define	SIGUSR1 SIGEMT
#endif
#ifndef SIGUSR2
#define	SIGUSR2 SIGFPE
#endif

/*
 *  These can be faster & more efficient than strcmp()/strncmp()...
 */
#define	STREQN(s1,s2)		((*s1 == *s2) && (strcmp(s1,s2) == 0))
#define	STRNEQN(s1,s2,n)	((*s1 == *s2) && (strncmp(s1,s2,n) == 0))

/*
 *  Configuration file limitations.
 */
#define	C_MAXFILE	10		/* max number of boot-able files */
#define	C_LINELEN	1024		/* max length of line */

/*
 *  Direction of packet (used as argument to DispPkt).
 */
#define	DIR_RCVD	0
#define	DIR_SENT	1
#define	DIR_NONE	2

/*
 *  These need not be functions, so...
 */
#define	FreeStr(str)	free(str)
#define	FreeClient(cli)	free(cli)
#define	GenSessID()	(++SessionID ? SessionID: ++SessionID)

/*
 *  Converting an Ethernet address to a string is done in many routines.
 *  Using `rmp.hp_hdr.saddr' works because this field is *never* changed;
 *  it will *always* contain the source address of the packet.
 */
#define	EnetStr(rptr)	GetEtherAddr(&(rptr)->rmp.hp_hdr.saddr[0])

/*
 *  Every machine we can boot will have one of these allocated for it
 *  (unless there are no restrictions on who we can boot).
 */
typedef struct client_s {
	u_int8_t		addr[RMP_ADDRLEN];	/* addr of machine */
	char			*files[C_MAXFILE];	/* boot-able files */
	struct client_s		*next;			/* ptr to next */
} CLIENT;

/*
 *  Every active connection has one of these allocated for it.
 */
typedef struct rmpconn_s {
	struct rmp_packet	rmp;			/* RMP packet */
	int			rmplen;			/* length of packet */
	struct timeval		tstamp;			/* last time active */
	int			bootfd;			/* open boot file */
	struct rmpconn_s	*next;			/* ptr to next */
} RMPCONN;

/*
 *  All these variables are defined in "conf.c".
 */
extern	char	MyHost[MAXHOSTNAMELEN+1]; /* this hosts' name */
extern	int	DebugFlg;		/* set true if debugging */
extern	int	BootAny;		/* set true if we can boot anyone */

extern	const char *ConfigFile;		/* configuration file */
extern	const char *DfltConfig;		/* default configuration file */
extern	const char *DbgFile;		/* debug output file */
extern	const char *PidFile;		/* file containing pid of server */
extern	const char *BootDir;		/* directory w/boot files */

extern	FILE	*DbgFp;			/* debug file pointer */
extern	char	*IntfName;		/* interface we are attached to */

extern	u_int16_t SessionID;		/* generated session ID */

extern	char	*BootFiles[];		/* list of boot files */

extern	CLIENT	*Clients;		/* list of addrs we'll accept */
extern	RMPCONN	*RmpConns;		/* list of active connections */

extern	u_int8_t RmpMcastAddr[];	/* RMP multicast address */

void	 AddConn __P((RMPCONN *));
int	 BootDone __P((RMPCONN *));
void	 BpfClose __P((void));
char	*BpfGetIntfName __P((char **));
int	 BpfOpen __P((void));
int	 BpfRead __P((RMPCONN *, int));
int	 BpfWrite __P((RMPCONN *));
void	 DebugOff __P((int));
void	 DebugOn __P((int));
void	 DispPkt __P((RMPCONN *, int));
void	 DoTimeout __P((void));
void	 DspFlnm __P((u_int, char *));
void	 Exit __P((int)) __dead;
CLIENT	*FindClient __P((RMPCONN *));
RMPCONN	*FindConn __P((RMPCONN *));
void	 FreeClients __P((void));
void	 FreeConn __P((RMPCONN *));
void	 FreeConns __P((void));
int	 GetBootFiles __P((void));
char	*GetEtherAddr __P((u_int8_t *));
CLIENT	*NewClient __P((u_int8_t *));
RMPCONN	*NewConn __P((RMPCONN *));
char	*NewStr __P((char *));
u_int8_t *ParseAddr __P((char *));
int	 ParseConfig __P((void));
void	 ProcessPacket __P((RMPCONN *, CLIENT *));
void	 ReConfig __P((int));
void	 RemoveConn __P((RMPCONN *));
int	 SendBootRepl __P((struct rmp_packet *, RMPCONN *, char *[]));
int	 SendFileNo __P((struct rmp_packet *, RMPCONN *, char *[]));
int	 SendPacket __P((RMPCONN *));
int	 SendReadRepl __P((RMPCONN *));
int	 SendServerID __P((RMPCONN *));


text:
var app = app || {};

app.host = "http://localhost:8000";


text:
<?php
namespace LolAPI\Exceptions;

class TeamNotFoundException extends LolAPIException {}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~
  -->

<eventReceiver name="cacheInvalidationWso2EventReceiver" statistics="disable"
    trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
    <from eventAdapterType="wso2event">
        <property name="events.duplicated.in.cluster">false</property>
    </from>
    <mapping customMapping="disable" type="wso2event"/>
    <to streamName="org.wso2.apimgt.cache.invalidation.stream" version="1.0.0"/>
</eventReceiver>


text:
\section{Bibliographie et ressources d'intérêt}

\begin{description}
	\item[Rapport de Francis Ngougo]{}
	\item[Thales]{http://www.thalesgroup.com}
	\item[Wikipedia]{http://www.wikipedia.org}
	\item[Hudson]{http://hudson-ci.org}
	\item[Jenkins]{http://jenkins-ci.org}
	\item[Sonar]{http://sonarsource.org}
	\item[JAXB]{http://jaxb.java.net}
	\item[Jersey]{http://jersey.java.net}
	\item[Apache DB DdlUtils]{http://db.apache.org/ddlutils}
\end{description}

\section{Annexe}
\subsection{Manuel utilisateur}


text:
<?php

// Check environment
if ( !defined( 'MEDIAWIKI' ) ) {
	echo( "This is an extension to the MediaWiki package and cannot be run standalone.\n" );
	die( -1 );
}

/* Configuration */

// Credits
$wgExtensionCredits['parserhook'][] = array(
	'path'           => __FILE__,
	'name'           => 'InputBox',
	'author'         => array( 'Erik Moeller', 'Leonardo Pimenta', 'Rob Church', 'Trevor Parscal', 'DaSch' ),
	'version'        => '0.2.0',
	'url'            => 'https://www.mediawiki.org/wiki/Extension:InputBox',
	'description'    => 'Allow inclusion of predefined HTML forms.',
	'descriptionmsg' => 'inputbox-desc',
);

// Shortcut to this extension directory
$dir = __DIR__ . '/';

// Internationalization
$wgMessagesDirs['InputBox'] = __DIR__ . '/i18n';
$wgExtensionMessagesFiles['InputBox'] = $dir . 'InputBox.i18n.php';

// Register auto load for the special page class
$wgAutoloadClasses['InputBoxHooks'] = $dir . 'InputBox.hooks.php';
$wgAutoloadClasses['InputBox'] = $dir . 'InputBox.classes.php';

// Register parser hook
$wgHooks['ParserFirstCallInit'][] = 'InputBoxHooks::register';
$wgHooks['MediaWikiPerformAction'][] = 'InputBoxHooks::onMediaWikiPerformAction';
$wgHooks['SpecialPageBeforeExecute'][] = 'InputBoxHooks::onSpecialPageBeforeExecute';


text:
title: Вариант 6 - «Пропускная система в офисе»
keywords: Tasks
sidebar: guide-tasks_sidebar
toc: true
permalink: ru/gt_flexberry-ember-case-06.html
lang: ru
summary: Вариант сквозного задания на проектирование и разработку с использованием фреймворка Flexberry Ember
---

## Задание

В рамках выполнения практической части курса вами будет разработан сквозной пример: приложение «Пропускная система в офисе» (ИС для автоматизации учета перемещения сотрудников офиса).

Первая часть практического задания будет посвящена освоению базовых технологий, таких как C#, базы данных, клиентские технологии и т.п., вторая часть будет включать изучение возможностей платформы Flexberry для эффективного создания приложений.

## Общее описание предметной области

В офисе компании Х вводится пропускная система на основе персональных пропускных карт. При помощи карты сотрудник может попасть на любой этаж в офисе, в общественные места (кухня, переговорка и т.п.) и только в свой кабинет. Требуется разработать информационную систему, в которой будет вестись информация как о выданных персональных пропускных картах, так и информация о перемещениях сотрудников. Все двери кабинетов, в которых работают сотрудники могут находиться в 2-х состояниях: `замок открыт` и `замок закрыт`. Во время рабочего дня, если в кабинете находятся сотрудники, как правило дверь находится в состоянии `замок открыт`. Таким образом, при перемещении между кабинетами офиса сотрудники не всегда используют карты. На входе и выходе из здания офиса все сотрудники обязаны использовать карту в индивидуальном порядке, это позволяет зафиксировать время прихода сотрудника в офис и время его ухода.

Технические требования:

*	Приложение реализуется в виде [SPA-приложения](https://ru.wikipedia.org/wiki/%D0%9E%D0%B4%D0%BD%D0%BE%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%87%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) с бакендом на C# и фронтендом на EmberJS.
*	Данные хранятся в БД Postgres.

## Практическое задание №1 - Серверная разработка (C#, .NET, ASP.NET)

Для реализации потребуется:

* Microsoft Visual Studio 2017
* Git for Windows

### Задание

Требуется реализовать алгоритм вычисления дружеских связей сотрудников на основе информации о совместном обеде или приходе и уходе из офиса. Если несколько сотрудников в течение недели выходили на обед с разницей не более 5 минут и возвращались с обеда с такой же небольшой разницей не менее 3-х раз, то они считаются друзьями. Если сотрудники приходят в офис утром и уходят вечером в одно и то же время с разницей не более 5-ти минут не менее 3-х раз, то тоже считаются друзьями.
На вход алгоритму подаётся массив структур, которые содержат:

* ФИО сотрудника и его id
* Массив кортежей: дата-время прихода в офис и дата-время ухода из офиса

На выходе должен быть массив кортежей, каждый из которых содержит информацию о дружеских отношениях между сотрудниками.
Реализацию следует сделать в виде .net-библиотеки и подготовить модульные тесты для неё (xUnit), продемонстрировать процент покрытия кода модульными тестами (чем больше, тем лучше).

### Предоставление результатов выполнения работы на проверку

Реализованное решение (Visual Studio Solution) полностью разместить в репозитории на GitHub (решение должно компилироваться и запускаться). Ссылку на репозиторий предоставить преподавателям курса.

## Практическое задание №2 - Клиентская разработка (HTML, CSS, JS, jQuery)

Для реализации потребуется:

* Редактор кода для клиентской разработки: Visual Studio Code
* Git for Windows

### Задание

С использованием возможностей HTML, CSS, JS, jQuery сверстать форму, на которой пользователь может указать ФИО сотрудника, год, месяц и получить информацию о его посещениях офиса с детализацией до каждого дня. Форма должна напоминать месячный календарь, т.е. в таблице должно быть 7 столбцов (пн, вт, ср, чт, пт, сб, вс) и недели в строках. В каждой ячейке таблицы должно быть указано число и время прихода-ухода в офис (сотрудник может несколько раз посещать офис).

### Предоставление результатов

Реализованный проект разместить в репозитории на GitHub в виде встроенных страниц GitHub Pages, позволяющих просматривать готовый результат. Ссылку на репозиторий и опубликованный таким образом проект предоставить преподавателям курса.

## Практическое задание №3 - Клиентская разработка с использованием SPA-фреймфорка (EmberJS)

Для реализации потребуется:

* Редактор кода для клиентской разработки: Visual Studio Code
* Git for Windows

### Задание

Требуется реализовать EmberJS приложение, в котором будет реализована форма, на которой пользователь может указать ФИО сотрудника, год, месяц и получить информацию о его посещениях офиса с детализацией до каждого дня. Форма должна напоминать месячный календарь, т.е. в таблице должно быть 7 столбцов (пн, вт, ср, чт, пт, сб, вс) и недели в строках. В каждой ячейке таблицы должно быть указано число и время прихода-ухода в офис (сотрудник может несколько раз посещать офис). Под календарём должен выводить список вероятных друзей данного сотрудника (EmberJS-компонент).

В виде EmberJS-утилиты требуется реализовать алгоритм вычисления дружеских связей сотрудников на основе информации о совместном обеде или приходе и уходе из офиса (см. задание №1).

Требуется реализовать компонент, в который передаётся id сотрудника, год и месяц, а он отображает список сотрудников, которые могут являться друзьями данного сотрудника. Использовать в компоненте EmberJS-утилиту с алгоритмом вычисления дружеских связей.

### Предоставление результатов

Реализованный проект разместить в репозитории на GitHub в виде проекта EmberJS и опубликованного приложения в GitHub Pages, которые позволяют просматривать готовый результат. Ссылку на репозиторий и опубликованный таким образом проект предоставить преподавателям курса.

## Практическое задание №4 - Базы данных

Для реализации потребуется:

*	Postgres
*	pgAdmin
*	Git for Windows

### Задание

Для указанной предметной области реализовать базу данных, заполнить базу скриптами (минимум по 5 записей на таблицу). Реализовать скрипты по созданию ограничений, индексов.

Подготовить SQL-скрипты для получения следующей информации:

1. Вывести топ-5 сотрудников, которые проводят в офисе больше всего времени
2. Вывести информацию о количестве открываний-закрываний двери на каждом из этажей в порядке убывания
3. Вывести информацию о рабочих днях максимальном, среднем и минимальном количестве сотрудников, посетивших офис
4. Вывести информацию об общем времени работы всех сотрудников в офисе по месяцам
5. Вывести топ-5 кабинетов, которые больше всего простаивают (чаше других закрыты на ключ)

### Предоставление результатов

Реализованные скрипты создания БД и заполнения, бекап БД закоммитить в GitHub-репозиторий. Ссылку на репозиторий предоставить преподавателям курса.

## Практическое задание №5 - Проектирование ИС

Для реализации потребуется:

*	Flexberry Designer

### Задание

Нарисовать UML-диаграммы для обозначенной предметной области. Состав диаграмм определяется самим слушателем курсов, но должен обеспечивать полноценное описание предметной области.

### Предоставление результатов

Результатом работы является выгруженная в формате CRP стадия из Flexberry Designer. Стадию (файл с расширением *.CRP) следует закоммитить в репозиторий на GitHub, ссылку предоставить преподавателям курса.

## Практическое задание №6 - Объектный дизайн и генерация приложений

Для реализации потребуется:

*	Flexberry Designer
*	Microsoft Visual Studio 2017
*	Postgres
*	Git for Windows

### Задание

Выполнить объектный дизайн и генерацию Ember-приложения для описанной предметной области. В качестве основы использовать реализованные ранее UML-модели. Генерация приложения и БД должна быть выполнена средствами Flexberry Designer приложение должно соответствовать требованиям и быть полностью работоспособным. Представления должны быть качественно настроены, подписи к классам и атрибутам на формах должны быть адекватными. Перечень форм и атрибутивный состав должны соответствовать предметной области и покрывать все требуемые бизнес-функции.

### Предоставление результатов

Сгенерированное приложение и скрипты создания БД следует выложить в репозиторий на GitHub. Предоставить преподавателям ссылку на репозиторий.

## Практическое задание №7 - Разработка бизнес-логики приложений

Для реализации потребуется:

* Flexberry Designer
* Microsoft Visual Studio 2017
* Postgres
* Git for Windows

### Задание

В сгенерированном при помощи Flexberry Designer приложении требуется реализовать следующую бизнес-логику.

1. Реализовать бизнес-сервер, который будет контролировать, что сотрудник не выходит из здания, если он не входил в него и наоборот - не входит, если не выходил. Должно быть сгенерировано событие, которое свидетельствует о неисправности оборудования.
2. Реализовать бизнес-сервер, который будет запрещать удаление объектов с информацией о проходе по карте (чтобы нельзя было скрыть преступление).
3. Реализовать бизнес-сервер, который будет контролировать закрыли ли сотрудники дверь кабинета перед уходом. Если сотрудник кабинета выходит последним из здания, а дверь кабинета находится в состоянии `замок открыт`, то нужно сгенерировать событие с информацией о сотруднике и номере кабинета.
4. Добавить не хранимое поле в класс Сотрудник, которое будет представлять ФИО одной строкой из Фамилии Имени и Отчества.
5. Добавить не хранимое поле ВОфисе в класс сотдудник, которое будет сигнализировать о том в офисе находится сотрудник или нет.

### Предоставление результатов

Доработанная бизнес-логика должна быть включена в разрабатываемое приложение и закоммичена в соответствующий репозиторий. Ссылка на репозиторий предоставляется для проверки преподавателям курса.

## Практическое задание №8 - Разработка UI-логики приложения

Для реализации потребуется:

*	Microsoft Visual Studio 2017
*	Postgres
*	Редактор кода для клиентской разработки: Visual Studio Code
*	Git for Windows

### Задание

Привязать реализованные ранее EmberJS дополнительные формы и компоненты к данным из БД.
Перенести в сгенерированное приложение и реализовать интеграцию формы из задания №3 с бизнес-логикой приложения.
На форме для элементов управления с выбором - данные должны браться из БД (через ORM и Lookup). Заполнение данных также должно работать с сохранением в БД.
Требуется настроить красивый внешний вид для всех форм приложения. Улучшить визуальную тему оформления. Реализовать ярлыки на рабочем столе приложения для быстрого доступа к часто используемым функциям.
Реализовать дополнительные формы, которые будут выводить результаты выполнения запросов из задания по БД.

### Предоставление результатов

Доработанная UI-логика должна быть включена в разрабатываемое приложение и закоммичена в соответствующий репозиторий. Ссылка на репозиторий предоставляется для проверки преподавателям курса.

## Практическое задание №9 - Функциональные подсистемы Flexberry

Для реализации потребуется:

*	Flexberry Designer
*	Microsoft Visual Studio 2017
*	Редактор кода для клиентской разработки: Visual Studio Code
*	Postgres
*	Git for Windows

### Задание

Для реализованного приложения настроить подсистему полномочий. Сотрудники и карты должны заводиться администратором приложения. Авторизация на основе форм. Создать иерархию ролей, добавить операции на просмотр сведений и выдать права только администраторам. Настроить несколько ролей и назначить эти роли пользователям.
Настроить подсистему аудита. В разрабатываемом приложении все изменения объектов данных должно фиксироваться в подсистеме аудита. В навигационное меню следует добавить формы аудита, которые должны показываться только администраторам.

### Предоставление результатов

Доработанное приложение должно быть закоммичено в соответствующий репозиторий. Дополнительно в репозиторий должны быть добавлены SQL-скрипты, которые нужно выполнить для функционирования приложения с подсистемой полномочий и аудита. Ссылка на репозиторий предоставляется для проверки преподавателям курса.


text:
import {Component, Input, Output, EventEmitter, NgZone, OnChanges, SimpleChange} from 'angular2/core';

@Component({
    selector: 'map',
    templateUrl: 'app/components/map/map.html',
    styleUrls: ['app/components/map/map.css'],
    providers: [],
    directives: [],
    pipes: []
})
export class Map {
    @Input() hosts: Array<any>;
    @Output() aHostWasSelected = new EventEmitter<Object>();
    map: Object;
    markersArr: Array<any> = [];
    zone: NgZone;
    @Input() clearSelected: boolean;
    @Input() selectThis: Object = {};
    public a;

    // only called if there is an @input variable set by parent.
    ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
        if (changes["clearSelected"] && (changes["clearSelected"].currentValue && !changes["clearSelected"].previousValue)) {
            this.setMarkersVisibility(undefined);
        }
        if (changes["selectThis"] && changes["selectThis"].currentValue.name) {
            this.setMarkersVisibility(changes["selectThis"].currentValue);
            this.selectThis = {};
        }
        if (changes["hosts"]) {
            this.paintMarkers(this.window, this.map);
        }

    }

    constructor(private window: Window, zone: NgZone) {
        let that = this;
        this.zone = zone;
        interface Window {
            google?: any;
        }
        this.map = {};

        setTimeout(() => {

            this.map = new this.window["google"].maps.Map(document.getElementById('map'), {
                center: { lat: 4.651602, lng: -74.057372 },
                zoom: 11
            });
            this.map["addListener"]('click', function(e) {
                that.setMarkersVisibility(undefined);
                that.emitClick({});
            });

        }, 0);
    }

    emitClick(hostObject: Object) {
        // http://blog.thoughtram.io/angular/2016/01/22/understanding-zones.html && http://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html
        this.zone.run(() => {
            this.aHostWasSelected.next(hostObject);
        })
    }
    paintMarkers(window, map) {
        let that = this;
        let aMarker;

        this.hosts.map(function(host) {
            aMarker = new window.google.maps.Marker({
                position: host.location.coordinates,
                map: map,
                title: host.name
            });
            aMarker.addListener('click', function(e) {
                that.emitClick(host);
                that.setMarkersVisibility(host);
            });

            that.markersArr.push(aMarker);
        })

    }

    setMarkersVisibility(currentHost) {
        let that = this;

        that.markersArr.map(function(marker) {
            if (currentHost) {
                if (marker.title !== currentHost.name) {
                    marker.setVisible(false);
                }
            } else {
                marker.setVisible(true);
            }
        })
    }

}


text:
Screen Shot Comparer

        <form class="form-horizontal" name="CompareForm" ng-submit="">

First Screen Shot

                Scheduler

                  <select class="form-control" ng-model="CompareData.SchedulerIdFirst"
                          ng-options="scheduler.Id as scheduler.Name for scheduler in schedulerList"
                          ng-change="onSchedulerFirstChange()" name="SchedulerFirst" required>
                    <option style="display:none" value="">--Select--</option>
                  </select>

0">
                Group Name

                  <select class="form-control" ng-model="CompareData.GroupNameFirst"
                          ng-options="schedulerHistory.GroupName as schedulerHistory.GroupName for schedulerHistory in schedulerHistoryFirstList"
                          ng-change="onGroupNameFirstChange()" name="GroupNameFirst" required>
                    <option style="display:none" value="">--Select--</option>
                  </select>

                Test name

                  {{reportFirst.JsonValue.Description}} ( {{reportFirst.JsonValue.Os}} -
                  {{reportFirst.JsonValue.BrowserName}}-{{reportFirst.JsonValue.BrowserVersion}} )

Second Screen Shot

                Scheduler

                  <select class="form-control" ng-model="CompareData.SchedulerIdSecond"
                          ng-options="scheduler.Id as scheduler.Name for scheduler in schedulerList"
                          ng-change="onSchedulerSecondChange()" name="SchedulerSecond" required>
                    <option style="display:none" value="">--Select--</option>
                  </select>

0">
                Group Name

                  <select class="form-control" ng-model="CompareData.GroupNameSecond"
                          ng-options="schedulerHistory.GroupName as schedulerHistory.GroupName for schedulerHistory in schedulerHistorySecondList"
                          ng-change="onGroupNameSecondChange()" name="GroupNameSecond" required>
                    <option style="display:none" value="">--Select--</option>
                  </select>

                Test name

                  {{reportSecond.JsonValue.Description}} ( {{reportSecond.JsonValue.Os}} -
                  {{reportSecond.JsonValue.BrowserName}}-{{reportSecond.JsonValue.BrowserVersion}} )

        </form>

First Screen Shot's

0">

                        {{$index+1}}. {{getPageName(slide.Name)}}

Second Screen Shot's

0">

                        {{$index+1}}. {{getPageName(slide.Name)}}

Screen Shot Comparision

      Filters:

      <select id="first" class="form-control setting1" onchange="applyCompareSettings(this)">
        <option value="raw">Ignore nothing</option>
        <option value="colors">Ignore colors</option>
        <option value="antialising">Ignore antialiasing</option>
      </select>

      <select id="second" class="form-control setting2" onchange="applyCompareSettings(this)">
        <option value="pink">Pink</option>
        <option value="yellow">Yellow</option>
      </select>

      <select id="third" class="form-control setting3" onchange="applyCompareSettings(this)">
        <option value="flat">Flat</option>
        <option value="movement">Movement</option>
        <option value="flatDifferenceIntensity">Flat with diff intensity</option>
        <option value="movementDifferenceIntensity">Movement with diff intensity</option>
      </select>

      <select id="fourth" class="form-control setting4" onchange="applyCompareSettings(this)">
        <option value="1">Opaque</option>
        <option value="0.3">Transparent</option>
      </select>

      Result:

        The second image is 0% different compared to the first.
        And they have different dimensions.

        These images are the same!


text:
#include "customdownload.h"
#include "monitordata.h"
#include "monitordatamap.h"
#include "networkresources.h"
#include <QtNetwork/QHostInfo>

CustomDownload::CustomDownload(QNetworkReply *reply,
                               QIODevice *device,
                               qint64 dnsLookupTime,
                               qint64 requestStartTime)
{

    this->isWaiting = true;
    this->requestStartTime = requestStartTime;
    this->waitingTime =  QDateTime::currentDateTime().toMSecsSinceEpoch();
    this->dnsLookupTime = dnsLookupTime;
    this->request = reply->request();
    this->reply = reply;
    this->device = device;
    this->bytesTotal = 0;

    connect(reply, SIGNAL(finished()),
                 this, SLOT(onFinished()));

    connect(reply, SIGNAL(downloadProgress(qint64, qint64)),
                 this, SLOT(onDownloadProgress(qint64, qint64)));

    connect(reply, SIGNAL(metaDataChanged()),
                 this, SLOT(onMetaDataChanged()));

    /*
    connect(reply, SIGNAL(uploadProgress(qint64, qint64)),
                 this, SLOT(onUploadProgress(qint64, qint64)));
    */
}

qint64 CustomDownload::max(qint64 num1, qint64 num2)
{
    return num1 > num2 ? num1 : num2;
}

void CustomDownload::onMetaDataChanged()
{
    if (isWaiting) {
        waitingTime = QDateTime::currentDateTime().toMSecsSinceEpoch()
                - waitingTime;
        isWaiting = false;

        downloadTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
    }
}

void CustomDownload::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    if (bytesReceived == bytesTotal) {
        this->bytesTotal = bytesTotal;
    }
}

void CustomDownload::onFinished()
{
    // 触发自定义信号
    emit requestFinished(request.url().toString());

    // 其他数据计算
    requestEndTime = QDateTime::currentDateTime().toMSecsSinceEpoch();

    totalTime = requestEndTime - requestStartTime;

    downloadTime =
            QDateTime::currentDateTime().toMSecsSinceEpoch()
            - downloadTime;

    MonitorData *monitorData = new MonitorData();

    // TODO: 此部分参见
    // http://doc.qt.nokia.com/4.7-snapshot/qnetworkrequest.html
    // http://doc.qt.nokia.com/4.7-snapshot/qnetworkreply.html

    monitorData->StatusCode =
            reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    // 状态码短语:OK/Not Found....
    monitorData->ReasonPhrase =
            reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    // 是否来自缓存内容
    monitorData->FromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
    monitorData->RequestURL = request.url().toString();
    monitorData->ResponseSize = bytesTotal;
    monitorData->ResponseDuration = totalTime;
    monitorData->ResponseDNSLookupDuration = dnsLookupTime;
    monitorData->ResponseWaitingDuration =  waitingTime;
    monitorData->ResponseDownloadDuration = downloadTime;
    monitorData->RequestStartTime = requestStartTime;
    monitorData->RequestEndTime = requestEndTime;

    // GET or POST
    // TODO: 这里有6中状态 偶们把它们都记录下来
    //       参看 http://doc.qt.nokia.com/4.7/qnetworkaccessmanager.html
    monitorData->ResponseMethod =
            (reply->operation() == QNetworkAccessManager::GetOperation)
            ? "GET" : (reply->operation() == QNetworkAccessManager::PostOperation)
            ? "POST" : (reply->operation() == QNetworkAccessManager::HeadOperation)
            ? "HEAD" : (reply->operation() == QNetworkAccessManager::PutOperation)
            ? "PUT" : (reply->operation() == QNetworkAccessManager::DeleteOperation)
            ? "DELETE" : (reply->operation() == QNetworkAccessManager::CustomOperation)
            ? "CUSTOM": "Unknown";

    monitorData->UserAgent = request.rawHeader("User-Agent");
    monitorData->Accept = request.rawHeader("Accept");
    monitorData->Referer = request.rawHeader("Referer");

    QList<QPair<QByteArray, QByteArray> > rawHeaderPairs = reply->rawHeaderPairs();
    int c = rawHeaderPairs.size();

    for (int i = 0; i < c; ++i) {
        QString key = rawHeaderPairs.at(i).first;
        QString value = rawHeaderPairs.at(i).second;

        //qDebug()<< rawHeaderPairs.at(i).first << " : " << rawHeaderPairs.at(i).second;
        // 蛋疼的赋值……
        if ("Age" == key) {
            monitorData->Age = value;
        } else if ("Access-Control-Allow-Origin" == key) {
            monitorData->AccessControlAllowOrigin = value;
        } else if ("Cache-Control" == key) {
            monitorData->CacheControl = value;
        } else if ("Connection" == key) {
            monitorData->Connection = value;
        } else if ("Content-Type" == key) {
            monitorData->ContentType = value;
        } else if ("Content-Length" == key) {
            monitorData->ContentLength = value.toUInt();
        } else if ("Content-Encoding" == key) {
            monitorData->ContentEncoding = value;
        } else if ("Content-Language" == key) {
            monitorData->ContentLanguage = value;
        } else if ("Location" == key) {
            monitorData->Location = value;
        } else if ("Cookie" == key) {
            monitorData->Cookie = value;
        } else if ("Date" == key) {
            monitorData->Date = value;
        } else if ("ETag" == key) {
            monitorData->ETag= value;
        } else if ("Expires" == key) {
            monitorData->Expires = value;
        } else if ("If-Modified-Since" == key) {
            monitorData->IfModifiedSince= value;
        } else if ("Last-Modified" == key) {
            monitorData->LastModified = value;
        } else if ("Server" == key) {
            monitorData->Server = value;
        } else if ("Set-Cookie" == key) {
            monitorData->SetCookie = value;
        } else if ("P3P" == key) {
            monitorData->P3P = value;
        } else if ("Accept-Ranges" == key) {
            monitorData->AcceptRanges = value;
        } else if ("Vary" == key) {
            monitorData->Vary = value;
        } else if ("Transfer-Encoding" == key) {
            monitorData->TransferEncoding = value;
        } else if ("Via" == key) {
            monitorData->Via = value;
        } else if ("X-Via" == key) {
            monitorData->XVia = value;
        } else if ("X-DEBUG-IDC" == key) {
            monitorData->XDEBUGIDC = value;
        } else if ("X-Powered-By" == key) {
            monitorData->XPoweredBy = value;
        } else if ("X-Cache" == key) {
            monitorData->XCache = value;
        } else if ("X-Cache-Lookup" == key) {
            monitorData->XCacheLookup = value;
        } else if ("X-Cache-Varnish" == key) {
            monitorData->XCacheVarnish = value;
        } else if ("Powered-By-ChinaCache" == key) {
            monitorData->PoweredByChinaCache = value;
        } else if ("SINA-LB" == key) {
            monitorData->SINALB = value;
        } else {
            monitorData->other[key] = value;
        }
        QHostInfo info = QHostInfo::fromName(reply->url().host());
        if (!info.addresses().isEmpty()) {
            monitorData->ServerIPAddress = info.addresses().first().toString();
        }
        MonitorDataMap::getMonitorDataMap()->set(monitorData->RequestURL, monitorData);
    }

    QMap<QString, qint64> responseOtherData;
    responseOtherData["blocked"] =  0;
    responseOtherData["dns"] = monitorData->ResponseDNSLookupDuration;;
    responseOtherData["connect"] = 0;
    responseOtherData["send"] = 0;
    responseOtherData["wait"] =  monitorData->ResponseWaitingDuration;
    responseOtherData["receive"] = monitorData->ResponseDownloadDuration;
    responseOtherData["size"] = monitorData->ResponseSize;
    responseOtherData["start"] = monitorData->RequestStartTime;
    responseOtherData["end"] = monitorData->RequestEndTime;
    NetworkResources* nwr = NetworkResources::getInstance();
    nwr->addData(reply, device, responseOtherData);
}


text:
layout: post
title: A night in the life
date: '2015-05-04T19:27:00.001-06:00'
author: Jacob .
tags:
- front-page
modified_time: '2015-05-04T20:36:28.826-06:00'
blogger_id: tag:blogger.com,1999:blog-6400085873105072120.post-6936274602326527108
blogger_orig_url: http://www.svlark.com/2015/05/a-night-in-life.html
---

Beautiful evening.  Luxuriously caressing breeze.  Two anchor lights past the point, oceanside.  Flickering shadows from tiki torches ashore.  Distant lightning toward Cuba.  I'm glad we're not out there...


text:
var React = require('react');
var ReactPropTypes = React.PropTypes;
var TodoItem = require('./TodoItem.react');
var todos = require('../models/todos');

var MainSection = React.createClass({

  propTypes: {
    allTodos: ReactPropTypes.object.isRequired,
    areAllComplete: ReactPropTypes.bool.isRequired
  },

  /**
   * @return {object}
   */
  render: function() {
    // This section should be hidden by default
    // and shown when there are todos.
    if (this.props.allTodos.size < 1) {
      return null;
    }

    var allTodos = this.props.allTodos;
    var todos = [];

    allTodos.forEach((val, key) => {
      todos.push(<TodoItem key={key} todo={val} />);
    });

    return (

        <input
          id="toggle-all"
          type="checkbox"
          onChange={this._onToggleAllCompleted}
          checked={this.props.areAllComplete ? 'checked' : ''}
        />
        Mark all as complete

{todos}

    );
  },

  /**
   * Event handler to mark all TODOs as complete
   */
  _onToggleAllCompleted: function() {
    todos.toggleAllCompleted();
  }

});

module.exports = MainSection;


text:
PFNGLXCREATECONTEXT pOAglXCreateContext = NULL;
PFNGLXDESTROYCONTEXT pOAglXDestroyContext = NULL;
PFNGLXMAKECURRENT pOAglXMakeCurrent = NULL;
PFNGLXQUERYEXTENSIONSSTRING pOAglXQueryExtensionsString = NULL;
PFNGLXGETPROCADDRESS pOAglXGetProcAddress = NULL;
PFNGLXGETCONFIG pOAglXGetConfig = NULL;
PFNGLXCHOOSEVISUAL pOAglXChooseVisual = NULL;

// ---------------------------------------------------------------------------
// Name:        oaLoadGLXFunctionPointers
// Description: Loads all GLX functions needed by the GROSWrappers module.
// Return Val:  bool - Success / failure.
// Author:      AMD Developer Tools Team
// Date:        8/4/2010
// ---------------------------------------------------------------------------
bool oaLoadGLXFunctionPointers()
{
    // This function could fail if any function was not yet acquired:
    bool retVal = !((pOAglXCreateContext == NULL) || (pOAglXDestroyContext == NULL) || (pOAglXMakeCurrent == NULL) ||
                    (pOAglXQueryExtensionsString == NULL) || (pOAglXGetProcAddress == NULL) || (pOAglXGetConfig == NULL) ||
                    (pOAglXChooseVisual == NULL));

    // Make sure we have all function pointers:
    if (!retVal)
    {
        // We are supposed to have all functions, or none at all:
        GT_ASSERT((pOAglXCreateContext == NULL) && (pOAglXDestroyContext == NULL) && (pOAglXMakeCurrent == NULL) &&
                  (pOAglXQueryExtensionsString == NULL) && (pOAglXGetProcAddress == NULL) && (pOAglXGetConfig == NULL) &&
                  (pOAglXChooseVisual == NULL));

        // Make sure the system OpenGL module is loaded:
        bool rcMod = oaLoadSystemOpenGLModule();
        GT_IF_WITH_ASSERT(rcMod)
        {
            // Get the OpenGL module handle:
            osModuleHandle systemOpenGLModuleHandle = oaSystemOpenGLModuleHandle();
            GT_IF_WITH_ASSERT(systemOpenGLModuleHandle != OS_NO_MODULE_HANDLE)
            {
                // Get the function pointers:
                osProcedureAddress pglXCreateContext = NULL;
                bool rc1 = osGetProcedureAddress(systemOpenGLModuleHandle, "glXCreateContext", pglXCreateContext);
                osProcedureAddress pglXDestroyContext = NULL;
                bool rc2 = osGetProcedureAddress(systemOpenGLModuleHandle, "glXDestroyContext", pglXDestroyContext);
                osProcedureAddress pglXMakeCurrent = NULL;
                bool rc3 = osGetProcedureAddress(systemOpenGLModuleHandle, "glXMakeCurrent", pglXMakeCurrent);
                osProcedureAddress pglXQueryExtensionsString = NULL;
                bool rc4 = osGetProcedureAddress(systemOpenGLModuleHandle, "glXQueryExtensionsString", pglXQueryExtensionsString);
                osProcedureAddress pglXGetProcAddress = NULL;
                bool rc5 = osGetProcedureAddress(systemOpenGLModuleHandle, "glXGetProcAddress", pglXGetProcAddress);
                osProcedureAddress pglXGetConfig = NULL;
                bool rc6 = osGetProcedureAddress(systemOpenGLModuleHandle, "glXGetConfig", pglXGetConfig);
                osProcedureAddress pglXChooseVisual = NULL;
                bool rc7 = osGetProcedureAddress(systemOpenGLModuleHandle, "glXChooseVisual", pglXChooseVisual);
                GT_IF_WITH_ASSERT(rc1 && (pglXCreateContext != NULL) && rc2 && (pglXDestroyContext != NULL) &&
                                  rc3 && (pglXMakeCurrent != NULL) && rc4 && (pglXQueryExtensionsString  != NULL) &&
                                  rc5 && (pglXGetProcAddress  != NULL) && rc6 && (pglXGetConfig != NULL) &&
                                  rc7 && (pglXChooseVisual != NULL))
                {
                    // Copy the pointers to the variables:
                    pOAglXCreateContext = (PFNGLXCREATECONTEXT)pglXCreateContext;
                    pOAglXDestroyContext = (PFNGLXDESTROYCONTEXT)pglXDestroyContext;
                    pOAglXMakeCurrent = (PFNGLXMAKECURRENT)pglXMakeCurrent;
                    pOAglXQueryExtensionsString = (PFNGLXQUERYEXTENSIONSSTRING)pglXQueryExtensionsString;
                    pOAglXGetProcAddress = (PFNGLXGETPROCADDRESS)pglXGetProcAddress;
                    pOAglXGetConfig = (PFNGLXGETCONFIG)pglXGetConfig;
                    pOAglXChooseVisual = (PFNGLXCHOOSEVISUAL)pglXChooseVisual;

                    retVal = true;
                }
            }
        }
    }

    return retVal;
}


text:
const router = require('express').Router();
const User = require('../models/user');
const ensureAuth = require('../auth/ensure-auth')();
const tokenService = require('../auth/token-service');

function hasEmailAndPassword(req, res, next) {
    const user = req.body;
    if (!user.email || !user.password) {
        return next({
            code: 400,
            error: 'Email and password must be entered.'
        });
    }
    next();
}

router
    .get('/verify', ensureAuth, (req, res) => {
        res.send({ valid: true });
    })

    .post('/signup', hasEmailAndPassword, (req, res, next) => {
        const name = req.body.name;
        const email = req.body.email;
        const password = req.body.password;
        delete req.body.password;
        User.find({ email })
            .count()
            .then(count => {
                if (count > 0) { throw { code: 400, error: 'This email is already in use' }; }
                const user = new User({
                    name: name,
                    email: email
                });
                user.generateHash(password);
                return user.save();
            })
            .then(user => {
                return tokenService.sign(user);
            })
            .then(token => {
                res.redirect('https://hops-music.herokuapp.com/spotify/login?access_token=' + token);
            })
            .catch(next);
    })

    .post('/signin', hasEmailAndPassword, (req, res, next) => {
        const email = req.body.email;
        const password = req.body.password;
        delete req.body.password;

        User.findOne({ email })
            .then(user => {
                if (!user || !user.comparePassword(password)) {
                    throw { code: 401, error: 'Invalid Login' };
                }
                return user;
            })
            .then(user => tokenService.sign(user))
            .then(token => {
                res.redirect('https://hops-music.herokuapp.com/spotify/login?access_token=' + token);
            })
            .catch(next);
    });

module.exports = router;


text:
package jef.codegen.support;

import jef.tools.string.RegexpUtils;

/**
 * 使用正则表达式的名称过滤器
 *
 * @author Administrator
 *
 */
public class RegexpNameFilter implements NameFilter{
	private String includePattern;
	private String[] excludePatter;

	public RegexpNameFilter(){};

	/**
	 * 构造
	 * @param include  要包含的正则表达式
	 * @param exclude  要排除的正则表达式
	 */
	public RegexpNameFilter(String include,String... exclude){
		this.includePattern=include;
		this.excludePatter=exclude;
	}

	/**
	 * 计算传入的文件名是否匹配正则表达式模板
	 * @param 传入文件名
	 * @return 如果指定了包含正则表达式,不匹配的话就返回false;
	 *
	 * 如果指定了排除正则表达式,并匹配了的话,返回false。
	 *
	 * 剩余情况都返回true
	 */
	public boolean accept(String name) {
		if (this.includePattern != null) {
			if (!RegexpUtils.matches(name, includePattern)) {
				return false;
			}
		}
		if (this.excludePatter != null) {
			for (String sp : excludePatter) {
				if (RegexpUtils.matches(name, sp)) {
					return false;
				}
			}
		}
		return true;
	}
}


text:
set -e

# Source repository
repo="git@github.com:symfony/demo.git"

# Files to import
cat >sparse-checkout <<eof
src/Entity
src/Pagination
src/Repository
LICENSE
eof

# -----

# Check working directory
if [ "$0" != "./update.sh" ]
then
	echo "Unexpected working directory." >&2
	exit 1
fi

# Remove everything
find ./ -maxdepth 1 -mindepth 1 -not -path ./update.sh -not -path ./sparse-checkout -print0 | xargs -0 rm -fr --

# Download Git repository and checkout selected files
git init .
git remote add origin "$repo"
git config core.sparseCheckout true
mv sparse-checkout .git/info/sparse-checkout
git fetch origin --depth 1
git checkout origin/master --detach --force
rm -rf .git

# Get rid of the src subdirectory
mv src/* ./
rmdir src/

# Change PHP namespace
find ./ -type f -name '*.php' -print0 \
| xargs -0 sed -i -e 's/\<App\\/Smalldb\\StateMachine\\Test\\SymfonyDemo\\/'


text:
package org.apache.hadoop.fs;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class TestFSMainOperationsLocalFileSystem extends FSMainOperationsBaseTest {

  @Before
  public void setUp() throws Exception {
    fSys = FileSystem.getLocal(new Configuration());
    super.setUp();
  }

  static Path wd = null;
  protected Path getDefaultWorkingDirectory() throws IOException {
    if (wd == null)
      wd = FileSystem.getLocal(new Configuration()).getWorkingDirectory();
    return wd;
  }

  @After
  public void tearDown() throws Exception {
    super.tearDown();
  }

  @Test
  @Override
  public void testWDAbsolute() throws IOException {
    Path absoluteDir = FileSystemTestHelper.getTestRootPath(fSys,
        "test/existingDir");
    fSys.mkdirs(absoluteDir);
    fSys.setWorkingDirectory(absoluteDir);
    Assert.assertEquals(absoluteDir, fSys.getWorkingDirectory());
  }
}


text:
package main

import (
	"flag"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"k8s.io/test-infra/boskos/client"
	"k8s.io/test-infra/boskos/common"
	awsboskos "k8s.io/test-infra/boskos/common/aws"
	"k8s.io/test-infra/maintenance/aws-janitor/regions"
	"k8s.io/test-infra/maintenance/aws-janitor/resources"
)

var (
	boskosURL          = flag.String("boskos-url", "http://boskos", "Boskos URL")
	sweepCount         = flag.Int("sweep-count", 3, "Number of times to sweep the resources")
	sweepSleep         = flag.String("sweep-sleep", "30s", "The duration to pause between sweeps")
	sweepSleepDuration time.Duration
)

const (
	sleepTime = time.Minute
)

func main() {
	flag.Parse()
	if d, err := time.ParseDuration(*sweepSleep); err != nil {
		sweepSleepDuration = time.Second * 30
	} else {
		sweepSleepDuration = d
	}

	logrus.SetFormatter(&logrus.JSONFormatter{})

	boskos := client.NewClient("AWSJanitor", *boskosURL)
	if err := run(boskos); err != nil {
		logrus.WithError(err).Error("Janitor failure")
	}
}

func run(boskos *client.Client) error {
	for {
		if res, err := boskos.Acquire(awsboskos.ResourceType, common.Dirty, common.Cleaning); errors.Cause(err) == client.ErrNotFound {
			logrus.Info("no resource acquired. Sleeping.")
			time.Sleep(sleepTime)
			continue
		} else if err != nil {
			return errors.Wrap(err, "Couldn't retrieve resources from Boskos")
		} else {
			logrus.WithField("name", res.Name).Info("Acquired resource")
			if err := cleanResource(res); err != nil {
				return errors.Wrapf(err, "Couldn't clean resource %q", res.Name)
			}
			if err := boskos.ReleaseOne(res.Name, common.Free); err != nil {
				return errors.Wrapf(err, "Failed to release resoures %q", res.Name)
			}
		}
	}
}

func cleanResource(res *common.Resource) error {
	val, err := awsboskos.GetAWSCreds(res)
	if err != nil {
		return errors.Wrapf(err, "Couldn't get AWS creds from %q", res.Name)
	}
	creds := credentials.NewStaticCredentialsFromCreds(val)
	s, err := session.NewSession(aws.NewConfig().WithCredentials(creds))
	if err != nil {
		return errors.Wrapf(err, "Failed to create AWS session")

	}
	logrus.WithField("name", res.Name).Info("beginning cleaning")
	start := time.Now()

	for i := 0; i < *sweepCount; i++ {
		if err := resources.CleanAll(s, regions.Default); err != nil {
			if i == *sweepCount-1 {
				logrus.WithError(err).Warningf("Failed to clean resource %q", res.Name)
			}
		}
		if i < *sweepCount-1 {
			time.Sleep(sweepSleepDuration)
		}
	}

	duration := time.Since(start)

	logrus.WithFields(logrus.Fields{"name": res.Name, "duration": duration.Seconds()}).Info("Finished cleaning")
	return nil
}


text:
module KinectMachine
  module VideoServer

    def self.extended(base)
      base.instance_eval do
        alias :close_target :close
        alias :close :close_video
      end
    end

    attr_reader :video_running, :frame_count

    def start_video(data)
      if format = data['video_format']
        @video_running = true
        @frame_count = 0
        video_mode = Freenect.find_video_mode(format.to_sym)
        send({
          :action => :start_video,
          :data   => {:format => format}
        })
        run_video(video_mode)
      else
        raise "'video_format' PARAM MISSING"
      end
    end

    def run_video(video_mode)
      if video_running
        EventMachine.next_tick do
          send_frame(Freenect.get_video(video_mode))
          run_video(video_mode)
        end
      end
    end

    def close_video
      @video_running = false
      close_target
    end

    def send_frame(frame)
      @frame_count += 1
      p frame.size
      logger.info "SENDING FRAME: #{frame_count}"
      socket.send(frame)
    end

  end
end


text:
require 'csv'
require 'set'

module InputParser
  class << self
    # Given an uploaded file, returns the parsed version suitable for
    # Evaluation#add_data
    #
    # Throws InputParser::ParseError if the file is malformed
    def parse(file)
      type = File.extname(file.original_filename)
      content = file.read.force_encoding 'UTF-8'

      begin
        case type
        when '.json'
          return parse_json(content)
        when '.csv'
          return parse_csv(content, ',')
        when '.tsv'
          return parse_csv(content, "\t")
        else
          raise ParseError.new("Unsupported file extension")
        end
      rescue CSV::MalformedCSVError => e
        raise ParseError.new("Malformed CSV", e)
      rescue MultiJson::DecodeError => e
        raise ParseError.new("Malformed JSON", e)
      end
    end

    private

    # Just parse the json
    def parse_json content
      json = ActiveSupport::JSON.decode(content)

      # validation
      validate json.kind_of?(Array), "JSON was not an array"

      json.each do |item|
        validate item.kind_of?(Hash), "JSON was not an array of objects"
        validate (item.keys.to_set == json.first.keys.to_set),
                 "JSON objects did not have consistent keys"
      end
    end

    # Convert the CSV to the equivalent JSON
    def parse_csv content, sep
      CSV.parse(content, :col_sep => sep,
                         :converters => [:numeric],
                         :headers => true,
                         :skip_blanks => true).
          map{ |row| row.to_hash }
    end

    # Raises a ParseError if bool is false, using the given message
    def validate bool, message
      unless bool
        raise ParseError.new message
      end
    end
  end

  class ParseError < RuntimeError
    attr_reader :msg, :source

    def initialize msg, source=nil
      @msg = msg
      @source = source
    end
  end
end


text:
package ezgames.utils.collections;

import java.util.Iterator;

import ezgames.math.EZRandom;
import ezgames.utils.Weighted;
import ezgames.utils.exceptions.ImpossibleException;

public class WeightedZArray<T> implements RceCollection<T>
{
	//**************************************************************************
	// Static factory methods
	//**************************************************************************
	public static <T> WeightedZArray<T> createFromWeights(Iterable<T> objs, Iterable<Integer> weights)
	{
		//TODO
		return null;
	}

	public static <T> WeightedZArray<T> createFromRanges(Iterable<Weighted<T>> weightedObjs)
	{
		//TODO
		return null;
	}

	//**************************************************************************
	// Public API methods
	//**************************************************************************
	@Override
	public Iterator<T> iterator()
	{
		return new WeightedIterator<T>(elements.iterator());
	}

	@Override
	public boolean contains(T obj)
	{
		return indexOf(obj) != -1;
	}

	@Override
	public T get(int index)
	{
		return elements.get(index).object();
	}

	@Override
	public int indexOf(T obj)
	{
		//TODO: if I ever get Streams from ZArrays, use Stream.map(..)?
		int index = 0;

		for(Weighted<T> el : elements)
		{
			if(objectsEqual(el, obj))
			{
				return index;
			}
			++index;
		}
		return -1;
	}

	@Override
	public int size()
	{
		return elements.size();
	}

	@Override
	public T random()
	{
		int randIndex = EZRandom.randomNumBetween(1, totalWeight());
		return getFromWeightedIndex(randIndex);
	}

	//**************************************************************************
	// Private fields
	//**************************************************************************
	private ZArray<Weighted<T>> elements;

	//**************************************************************************
	// Private helper methods
	//**************************************************************************
	private boolean objectsEqual(Weighted<T> wt, T o)
	{
		return wt.object().equals(o);
	}

	private int totalWeight()
	{
		int total = 0;
		for(Weighted<T> el : elements)
		{
			total += el.weight();
		}
		return total;
	}

	private T getFromWeightedIndex(int weightedIndex)
	{
		check(weightedIndex); //should never throw an exception, since we shouldn't have incorrect values being generated TODO: remove after testing

		int elementMaxIndex = 0;

		for(Weighted<T> el : elements)
		{
			elementMaxIndex = updateMaxIndex(elementMaxIndex, el.weight());
			if(found(weightedIndex, elementMaxIndex))
			{
				return el.object();
			}
		}
		return null; //satisfy the compiler
	}

	private void check(int weightedIndex)
	{
		if(weightedIndex < 1)
		{
			throw new ImpossibleException("internally-generated value failed invariants", new IndexOutOfBoundsException("weightedIndex of " + weightedIndex + " is below the minimum weighted index value of 1"));
		}

		int totalWeight = totalWeight();
		if(weightedIndex > totalWeight)
		{
			throw new ImpossibleException("internally-generated value failed invariants", new IndexOutOfBoundsException("weightedIndex of " + weightedIndex + " exceeds total weight of " + totalWeight));
		}
	}

	private int updateMaxIndex(int currentMaxIndex, int elementWeight)
	{
		return currentMaxIndex + elementWeight;
	}

	private boolean found(int weightedIndex, int elementMaxIndex)
	{
		return weightedIndex <= elementMaxIndex;
	}
}