text:
pub use super::artifact_content::ArtifactContent;
use crate::config::ProjectConfig;
use common::SourceLocationKey;
use intern::string_key::StringKey;
use relay_typegen::TypegenLanguage;
use std::path::PathBuf;

/// This function will create a correct path for artifact based on the project configuration
pub fn create_path_for_artifact(
    project_config: &ProjectConfig,
    source_file: SourceLocationKey,
    artifact_file_name: String,
) -> PathBuf {
    if let Some(output) = &project_config.output {
        // If an output directory is specified, output into that directory.
        if project_config.shard_output {
            if let Some(ref regex) = project_config.shard_strip_regex {
                let full_source_path = regex.replace_all(source_file.path(), "");
                let mut output = output.join(full_source_path.to_string());
                output.pop();
                output
            } else {
                output.join(source_file.get_dir())
            }
            .join(artifact_file_name)
        } else {
            output.join(artifact_file_name)
        }
    } else {
        // Otherwise, output into a file relative to the source.
        source_file
            .get_dir()
            .join("__generated__")
            .join(artifact_file_name)
    }
}

pub fn path_for_artifact(
    project_config: &ProjectConfig,
    source_file: SourceLocationKey,
    definition_name: StringKey,
) -> PathBuf {
    let filename = if let Some(filename_for_artifact) = &project_config.filename_for_artifact {
        filename_for_artifact(source_file, definition_name)
    } else {
        match &project_config.typegen_config.language {
            TypegenLanguage::Flow => format!("{}.graphql.js", definition_name),
            TypegenLanguage::TypeScript => format!("{}.graphql.ts", definition_name),
        }
    };
    create_path_for_artifact(project_config, source_file, filename)
}


text:
/*
 * AcquisitorTask.cpp
 *
 *  Created on: Apr 18, 2017
 *      Author: Zarnowski
 */

#include <sensor-net/tasks/AcquisitorTask.hpp>

static const int MAX_RETRY_ATTEMPTS = 10;
static int nextTaskId = 0;

AcquisitorTask::AcquisitorTask(shared_ptr<PhysicalSensor> sensor, shared_ptr<spdlog::logger> logger)
: sensor(sensor), logger(logger), attempts(0), taskId(++nextTaskId) {

}

int AcquisitorTask::getSensorId() {
  return sensor->getId();
}

int AcquisitorTask::getTaskId() {
  return taskId;
}

bool AcquisitorTask::execute() {

  logger->info("Acquisition task {} begin", taskId);
  attempts++;
  if (innerExecute() == true) {
    logger->info("Task {} succeed", taskId);
    return true;
  }

  bool notRetry = attempts > MAX_RETRY_ATTEMPTS;
  if (notRetry == true) {
    giveUp();
  }
  logger->warn("Acquisition task {} from {}({}) failed, we will retry:{}", taskId, sensor->getName(),
      sensor->getAddress(), notRetry ? "NO" : "YES");
  return notRetry;
}

void AcquisitorTask::giveUp() {
  //we will not try to execute again...
  logger->warn("Giving up with task id {}", taskId);
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Scalr\Service\Aws\Plugin;

use Scalr\Service\Aws\Event\EventType;
use Scalr\Service\Aws\Event\EventInterface;
use Scalr\Service\Aws\Exception;

/**
 * AWS EventObserver
 *
 * @author    Vitaliy Demidov   <vitaliy@scalr.com>
 * @since     26.09.2013
 *
 * @method    bool hasStatistics()
 *            hasStatistics()
 *            Checks whether Statistic plugin is defined and enabled
 *
 * @method    \Scalr\Service\Aws\Plugin\Handlers\StatisticsPlugin getStatistics()
 *            getStatistics()
 *            Gets statistic plugin
 */
class EventObserver
{

    /**
     * Aws instance
     *
     * @var \Scalr\Service\Aws
     */
    private $aws;

    /**
     * The list of the plugins
     *
     * @var \ArrayObject
     */
    private $plugins;

    /**
     * The list of the enabled plugins
     *
     * @var array
     */
    private $enabled;

    /**
     * List of the subscriptions to the events
     *
     * @var array
     */
    private $subscriptions;

    /**
     * Fires an AWS Client Event
     *
     * @param   EventInterface $event An AWS Client Event
     */
    public function fireEvent(EventInterface $event)
    {
        if (!empty($this->subscriptions[$event->getName()])) {
            $subscribed = $this->subscriptions[$event->getName()];
            foreach ($subscribed as $lcPlugin => $priority) {
                if ($event->isPropagationStopped()) {
                    break;
                }
                if ($this->enabled[$lcPlugin]) {
                    $plugin = $this->plugins[$lcPlugin];
                    if ($plugin instanceof PluginInterface) {
                        $plugin->handle($event);
                    }
                }
            }
        }
    }

    /**
     * Checks whether the observer has subscritpions to specified event
     *
     * @param   EventType|string   $eventType  The type of the AWS client event
     * @return  bool  Returns true if the observer has subscriptions to specified event
     */
    public function isSubscribed($eventType)
    {
        $eventName = (string)$eventType;
        return !empty($this->subscriptions[$eventName]);
    }

    /**
     * Constructor
     */
    public function __construct(\Scalr\Service\Aws $aws)
    {
        $this->plugins = new \ArrayObject(array());
        $this->aws = $aws;

        $cfEnabled = $this->aws->getContainer()->config('scalr.aws.plugins.enabled');
        if (!is_array($cfEnabled)) {
            $cfEnabled = (array)$cfEnabled;
        }

        foreach (EventType::getAllowedValues() as $eventName) {
            $this->subscriptions[$eventName] = array();
        }

        foreach (glob(__DIR__ . DIRECTORY_SEPARATOR . 'Handlers' . DIRECTORY_SEPARATOR . '*Plugin.php', GLOB_NOSORT) as $filename) {
            $plugin = substr(basename($filename), 0, -4);
            $class = __NAMESPACE__ . '\\Handlers\\' . $plugin;

            $p = new $class;
            if (!($p instanceof PluginInterface)) {
                trigger_error(sprintf('AWS client plugin "%s" must implement PluginInterface.', $class), E_USER_WARNING);
                continue;
            }

            $p->setAws($this->aws);
            $p->setContainer($this->aws->getContainer());
            $subscribed = $p->getSubscribedEvents();
            if (empty($subscribed)) {
                continue;
            }

            $lcPlugin = strtolower(substr($plugin, 0, -6));

            foreach ($subscribed as $eventName) {
                if (isset($this->subscriptions[$eventName])) {
                    $this->subscriptions[$eventName][$lcPlugin] = $p->priority;
                } else {
                    throw new Exception\PluginException(sprintf('AWS client plugin "%s" is subscribed to unknown event "%s".', $class, $eventName));
                }
            }

            $this->plugins[$lcPlugin] = $p;
            $this->enabled[$lcPlugin] = in_array($lcPlugin, $cfEnabled) ? true : null;
        }

        //Sorts subscriptions by plugin priority
        foreach ($this->subscriptions as $eventName => $v) {
            if (!empty($v)) {
                arsort($this->subscriptions[$eventName]);
            }
        }
    }

    /**
     * Checks whether the specified plugin is defined and enabled
     *
     * @param   string  $plugin The name of the plugin provided in the lower case
     * @return  bool    Returns true if plugin is defined and enabled
     */
    public function has($plugin)
    {
        return isset($this->plugins[$plugin]) && !empty($this->enabled[$plugin]);
    }

    /**
     * Gets plugin from the container
     *
     * @param   string          $plugin The name of the plugin provided in the lower case
     * @return  PluginInterface Returns plugin
     * @throws  \Scalr\Service\Aws\Exception\PluginException
     */
    public function get($plugin)
    {
        if (!isset($this->plugins[$plugin])) {
            throw new Exception\PluginException(sprintf(
                'AWS client plugin "%s" does not exist.', $plugin
            ));
        } elseif (empty($this->enabled[$plugin])) {
            throw new Exception\PluginException(sprintf(
                'AWS client plugin "%s" has not been allowed.', $plugin
            ));
        } else {
            return $this->plugins[$plugin];
        }
    }

    /**
     * Enables plugin
     *
     * @param   string      $plugin  The name of the AWS client plugin
     * @throws  Exception\PluginException
     * @return  \Scalr\Service\Aws\Plugin\EventObserver
     */
    public function enable($plugin)
    {
        if (!isset($this->plugins[$plugin])) {
            throw new Exception\PluginException(sprintf(
                'AWS client plugin "%s" does not exist.', $plugin
            ));
        }
        $this->enabled[$plugin] = true;

        return $this;
    }

    /**
     * Disables plugin
     *
     * @param   string      $plugin  The name of the AWS client plugin
     * @throws  Exception\PluginException
     * @return  \Scalr\Service\Aws\Plugin\EventObserver
     */
    public function disable($plugin)
    {
        if (!isset($this->plugins[$plugin])) {
            throw new Exception\PluginException(sprintf(
                'AWS client plugin "%s" does not exist.', $plugin
            ));
        }
        $this->enabled[$plugin] = null;

        return $this;
    }

    /**
     * Gets all defined plugins.
     *
     * @return   \ArrayObject  Returns all defined plugins
     */
    public function all()
    {
        return $this->plugins;
    }

    public function __call($method, $args)
    {
        $prefix = substr($method, 0, 3);
        $pluginName = strtolower(substr($method, 3));
        if ($prefix == 'has') {
            return $this->has($pluginName);
        } else if ($prefix == 'get') {
            return $this->get($pluginName);
        } else if ($prefix == 'let') {
            return $this->enable($pluginName);
        }
        throw new \BadFunctionCallException(sprintf(
            'Method "%s" has not been defined for %s', $method, get_class($this)
        ));
    }
}


text:
Step 3: Listener support
========================

[Listeners](http://symfony.com/doc/master/cookbook/service_container/event_listener.html)
are a way to hook into the request handling. This Bundle provides various events
from decoding the request content in the request (body listener), determining the
correct response format (format listener), reading parameters from the request
(parameter fetcher listener), to formatting the response either with a template engine
like twig or to f.e. xml or json using a serializer (view response listener)) as well
as automatically setting the accepted http methods in the response (accept listener).

With this in mind we now turn to explain each one of them.

All listeners except the ``mime_type`` one are disabled by default.  You can
enable one or more of these listeners.  For example, below you can see how to
enable all listeners:

```yaml
# app/config/config.yml
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'
```

### View Response listener

The view response listener makes it possible to simply return a ``View``
instance from action controllers. The final output will then automatically be
processed via the listener by the ``fos_rest.view_handler`` service.

This requires adding the SensioFrameworkExtraBundle to your vendors:

http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/index.html

Now inside a controller its possible to simply return a ``View`` instance.

```php
<?php

use FOS\RestBundle\View\View;

class UsersController
{
    public function getUsersAction()
    {
        $view = View::create();

        ...

        $view->setData($data);
        return $view;
    }
}
```

As this feature is heavily based on the SensioFrameworkBundle, the example can
further be simplified by using the various annotations supported by that
bundle. There is also one additional annotation called ``@View()`` which
extends from the ``@Template()`` annotation.

The ``@View()`` and ``@Template()`` annotations behave essentially the same
with a minor difference. When ``view_response_listener`` is set to ``true``
instead of ``force`` and ``@View()`` is not used, then rendering
will be delegated to SensioFrameworkExtraBundle.

Note that it is necessary to disable view annotations in
SensioFrameworkExtraBundle so that FOSRestBundle can take over the handling.

```yaml
# app/config/config.yml
fos_rest:
    view:
        view_response_listener: force

sensio_framework_extra:
    view:    { annotations: false }
    router:  { annotations: true }
```

```php
<?php

use FOS\RestBundle\Controller\Annotations\View;

class UsersController
{
    /**
     * @View()
     */
    public function getUsersAction()
    {
        ...

        return $data;
    }
}
```
If ``@View()`` is used, the template variable name used to render templating
formats can be configured (default  ``'data'``):

```php
<?php

/**
 * @View(templateVar="users")
 */
public function getUsersAction()
{
    //...
}
```

The status code of the view can also be configured:

```php
<?php

/**
 * @View(statusCode=204)
 */
public function deleteUserAction()
{
    //...
}
```

The groups for the serializer can be configured as follows:

```php
<?php

/**
 * @View(serializerGroups={"group1", "group2"})
 */
public function getUsersAction()
{
    //...
}
```

See the following example code for more details:
https://github.com/liip/LiipHelloBundle/blob/master/Controller/ExtraController.php

### Body listener

The Request body decoding listener makes it possible to decode the contents of
a request in order to populate the "request" parameter bag of the Request. This
for example allows to receive data that normally would be sent via POST as
``application/x-www-form-urlencode`` in a different format (for example
application/json) in a PUT.

You can add a decoder for a custom format. You can also replace the default
decoder services provided by the bundle for the ``json`` and ``xml`` formats.
Below you can see how to override the decoder for the json format (the xml
decoder is explicitly kept to its default service):

```yaml
# app/config/config.yml
fos_rest:
    body_listener:
        decoders:
            json: acme.decoder.json
            xml: fos_rest.decoder.xml
```

Your custom decoder service must use a class that implements the
``FOS\Rest\Decoder\DecoderInterface``.

### Format listener

The Request format listener attempts to determine the best format for the
request based on the Request's Accept-Header and the format priority
configuration. This way it becomes possible to leverage Accept-Headers to
determine the request format, rather than a file extension (like foo.json).

The ``default_priorities`` define the order of formats as the application
prefers.  The algorithm iteratively examines the provided Accept header first
looking at all the options with the highest ``q``. The first priority that
matches is returned. If none match the next lowest set of Accept headers with
equal ``q`` is examined and so on until there are no more Accept headers to
check. In this case ``fallback_format`` is used.

Note that if ``_format`` is matched inside the route, then a virtual Accept
header setting is added with a ``q`` setting one lower than the lowest Accept
header, meaning that format is checked for a match in the priorities last. If
``prefer_extension`` is set to ``true`` then the virtual Accept header will be
one higher than the highest ``q`` causing the extension to be checked first.

Note that setting ``default_priorities`` to a non empty array enables Accept
header negotiations, while adding '*/*' to the priorities will effectively
cause any priority to match.

```yaml
# app/config/config.yml
fos_rest:
    format_listener:
        default_priorities: ['json', html, '*/*']
        fallback_format: json
        prefer_extension: true
```

For example using the above configuration and the following Accept header:
```
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
```

And the following route:

```yaml
hello:
    pattern:  /foo.{_format}
    defaults: { _controller: foo.controller:indexAction, _format: ~ }
```

When calling:

* ``/foo`` will lead to setting the request format to ``json``
* ``/foo.html`` will lead to setting the request format to ``html``

Note that the format needs to either be supported by the ``Request`` class
natively or it needs to be added as documented here:
http://symfony.com/doc/current/cookbook/request/mime_type.html

### Mime type listener

This listener allows registering additional mime types in the ``Request``
class.  It works similar to the following cookbook entry:
http://symfony.com/doc/current/cookbook/request/mime_type.html

```yaml
# app/config/config.yml
fos_rest:
    view:
        mime_types: {'jsonp': ['application/javascript', 'application/javascript+jsonp']}
```

### Param fetcher listener

The param fetcher listener simply sets the ParamFetcher instance as a request attribute
configured for the matched controller so that the user does not need to do this manually.

```yaml
# app/config/config.yml
fos_rest:
    param_fetcher_listener: true
```

```php
<?php

use FOS\RestBundle\Request\ParamFetcher;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use FOS\RestBundle\Controller\Annotations\QueryParam;

class FooController extends Controller
{
    /**
     * Will look for a page query parameter, ie. ?page=XX
     * If not passed it will be automatically be set to the default of "1"
     * If passed but doesn't match the requirement "\d+" it will be also be set to the default of "1"
     * Note that if the value matches the default then no validation is run.
     * So make sure the default value really matches your expectations.
     *
     * @QueryParam(name="page", requirements="\d+", default="1", description="Page of the overview.")
     *
     * In some case you also want to have a strict requirements but accept a null value, this is possible
     * thanks to the nullable option.
     * If ?count= parameter is set, the requirements will be checked strictly, if not, the null value will be used.
     * If you set the strict parameter without a nullable option, this will result in an error if the parameter is
     * missing from the query.
     *
     * @QueryParam(name="count", requirements="\d+", strict=true, nullable=true, description="Item count limit")
     *
     * Will look for a firstname request parameters, ie. firstname=foo in POST data.
     * If not passed it will error out when read out of the ParamFetcher since RequestParam defaults to strict=true
     * If passed but doesn't match the requirement "\d+" it will also error out (400 Bad Request)
     * Note that if the value matches the default then no validation is run.
     * So make sure the default value really matches your expectations.
     *
     * @RequestParam(name="firstname", requirements="[a-z]+", description="Firstname.")
     *
     * If you want to work with array: ie. ?ids[]=1&ids[]=2&ids[]=1337, use:
     *
     * @QueryParam(array="true", name="ids", requirements="\d+", default="1", description="List of ids")
     * (works with QueryParam and RequestParam)
     *
     * It will validate each entries of ids with your requirement, by this way, if an entry is invalid,
     * this one will be replaced by default value.
     *
     * ie: ?ids[]=1337&ids[]=notinteger will return array(1337, 1);
     * If ids is not defined, array(1) will be given
     *
     * Array must have a single depth or it will return default value. It's difficult to validate with
     * preg_match each deeps of array, if you want to deal with that, use another validation system.
     *
     * @param ParamFetcher $paramFetcher
     */
    public function getArticlesAction(ParamFetcher $paramFetcher)
    {
        $page = $paramFetcher->get('page');
        $articles = array('bim', 'bam', 'bingo');

        return array('articles' => $articles, 'page' => $page);
    }
```

Note: There is also ``$paramFetcher->all()`` to fetch all configured query parameters at once. And also
both ``$paramFetcher->get()`` and ``$paramFetcher->all()`` support and optional ``$strict`` parameter
to throw a ``\RuntimeException`` on a validation error.

Optionally the listener can also already set all configured query parameters as request attributes

```yaml
# app/config/config.yml
fos_rest:
    param_fetcher_listener: force
```

```php
<?php

class FooController extends Controller
{
    /**
     * @QueryParam(name="page", requirements="\d+", default="1", description="Page of the overview.")
     *
     * @param string $page
     */
    public function getArticlesAction($page)
    {
        $articles = array('bim', 'bam', 'bingo');

        return array('articles' => $articles, 'page' => $page);
    }
```

### Allowed Http Methods Listener

This listener add the ``Allow`` HTTP header to each request appending all allowed methods for a given resource.

Let's say we have the following routes:
```
api_get_users
api_post_users
api_get_user
```

A ``GET`` request to ``api_get_users`` will response in:

```
< HTTP/1.0 200 OK
< Date: Sat, 16 Jun 2012 15:17:22 GMT
< Server: Apache/2.2.22 (Ubuntu)
< allow: GET, POST
```

You need to enable this listener like this as it is disabled by default:

```
fos_rest:
    allowed_methods_listener: true
```

### Security Exception Listener

By default it is the responsibility of firewall access points to deal with AccessDeniedExceptions.
For example the ``form`` entry point will redirect to the login page. However for a RESTful application
proper response HTTP status codes should be provided. This listener is triggered before the normal exception listener
and firewall entry points and forces returning either a 403 or 401 status code for any of the formats configured.

It will return 401 for `Symfony\Component\Security\Core\Exception\AuthenticationException` or 403 for
`Symfony\Component\Security\Core\Exception\AccessDeniedException`.

You need to enable this listener like this as it is disabled by default:

```
fos_rest:
    access_denied_listener:
        # all requests using the 'json' format will return a 403 on an access denied violation
        json: true
```

It is also recommended to enable the exception controller described in the next chapter.

## That was it!
[Return to the index](index.md) or continue reading about [ExceptionController support](4-exception-controller-support.md).


text:
#include "qbitmap.h"
#include "qevent.h"
#include "qstylepainter.h"
#include "qrubberband.h"
#include "qtimer.h"

#ifndef QT_NO_RUBBERBAND

#include "qstyle.h"
#include "qstyleoption.h"
#ifdef Q_WS_MAC
#  include <private/qt_mac_p.h>
#  include <private/qt_cocoa_helpers_mac_p.h>
#endif

#include <qdebug.h>

#include <private/qwidget_p.h>

QT_BEGIN_NAMESPACE

//### a rubberband window type would be a more elegant solution
#define RUBBERBAND_WINDOW_TYPE Qt::ToolTip

class QRubberBandPrivate : public QWidgetPrivate
{
    Q_DECLARE_PUBLIC(QRubberBand)
public:
    QRect rect;
    QRubberBand::Shape shape;
    QRegion clipping;
    void updateMask();
};

/*!
    Initialize \a option with the values from this QRubberBand. This method
    is useful for subclasses when they need a QStyleOptionRubberBand, but don't want
    to fill in all the information themselves.

    \sa QStyleOption::initFrom()
*/
void QRubberBand::initStyleOption(QStyleOptionRubberBand *option) const
{
    if (!option)
        return;
    option->initFrom(this);
    option->shape = d_func()->shape;
#ifndef Q_OS_MAC
    option->opaque = true;
#else
    option->opaque = windowFlags() & RUBBERBAND_WINDOW_TYPE;
#endif
}

/*!
    \class QRubberBand
    \brief The QRubberBand class provides a rectangle or line that can
    indicate a selection or a boundary.

    \inmodule QtWidgets

    A rubber band is often used to show a new bounding area (as in a
    QSplitter or a QDockWidget that is undocking). Historically this has
    been implemented using a QPainter and XOR, but this approach
    doesn't always work properly since rendering can happen in the
    window below the rubber band, but before the rubber band has been
    "erased".

    You can create a QRubberBand whenever you need to render a rubber band
    around a given area (or to represent a single line), then call
    setGeometry(), move() or resize() to position and size it. A common
    pattern is to do this in conjunction with mouse events. For example:

    \snippet code/src_gui_widgets_qrubberband.cpp 0

    If you pass a parent to QRubberBand's constructor, the rubber band will
    display only inside its parent, but stays on top of other child widgets.
    If no parent is passed, QRubberBand will act as a top-level widget.

    Call show() to make the rubber band visible; also when the
    rubber band is not a top-level. Hiding or destroying
    the widget will make the rubber band disappear. The rubber band
    can be a \l Rectangle or a \l Line (vertical or horizontal),
    depending on the shape() it was given when constructed.
*/

// ### DOC: How about some nice convenience constructors?
//QRubberBand::QRubberBand(QRubberBand::Type t, const QRect &rect, QWidget *p)
//QRubberBand::QRubberBand(QRubberBand::Type t, int x, int y, int w, int h, QWidget *p)

/*!
    Constructs a rubber band of shape \a s, with parent \a p.

    By default a rectangular rubber band (\a s is \c Rectangle) will
    use a mask, so that a small border of the rectangle is all
    that is visible. Some styles (e.g., native Mac OS X) will
    change this and call QWidget::setWindowOpacity() to make a
    semi-transparent filled selection rectangle.
*/
QRubberBand::QRubberBand(Shape s, QWidget *p)
    : QWidget(*new QRubberBandPrivate, p, (p && p->windowType() != Qt::Desktop) ? Qt::Widget : RUBBERBAND_WINDOW_TYPE)
{
    Q_D(QRubberBand);
    d->shape = s;
    setAttribute(Qt::WA_TransparentForMouseEvents);
#ifndef Q_WS_WIN
    setAttribute(Qt::WA_NoSystemBackground);
#endif //Q_WS_WIN
    setAttribute(Qt::WA_WState_ExplicitShowHide);
    setVisible(false);
#ifdef Q_WS_MAC
    if (isWindow()) {
        createWinId();
        extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
        macWindowSetHasShadow(qt_mac_window_for(this), false);
    }
#endif
}

/*!
    Destructor.
*/
QRubberBand::~QRubberBand()
{
}

/*!
    \enum QRubberBand::Shape

    This enum specifies what shape a QRubberBand should have. This is
    a drawing hint that is passed down to the style system, and can be
    interpreted by each QStyle.

    \value Line A QRubberBand can represent a vertical or horizontal
                line. Geometry is still given in rect() and the line
                will fill the given geometry on most styles.

    \value Rectangle A QRubberBand can represent a rectangle. Some
                     styles will interpret this as a filled (often
                     semi-transparent) rectangle, or a rectangular
                     outline.
*/

/*!
  Returns the shape of this rubber band. The shape can only be set
  upon construction.
*/
QRubberBand::Shape QRubberBand::shape() const
{
    Q_D(const QRubberBand);
    return d->shape;
}

/*!
    \internal
*/
void QRubberBandPrivate::updateMask()
{
    Q_Q(QRubberBand);
    QStyleHintReturnMask mask;
    QStyleOptionRubberBand opt;
    q->initStyleOption(&opt);
    if (q->style()->styleHint(QStyle::SH_RubberBand_Mask, &opt, q, &mask)) {
        q->setMask(mask.region);
    } else {
        q->clearMask();
    }
}

/*!
    \reimp
*/
void QRubberBand::paintEvent(QPaintEvent *)
{
    QStylePainter painter(this);
    QStyleOptionRubberBand option;
    initStyleOption(&option);
    painter.drawControl(QStyle::CE_RubberBand, option);
}

/*!
    \reimp
*/
void QRubberBand::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::ParentChange:
        if (parent()) {
            setWindowFlags(windowFlags() & ~RUBBERBAND_WINDOW_TYPE);
        } else {
            setWindowFlags(windowFlags() | RUBBERBAND_WINDOW_TYPE);
        }
        break;
    default:
        break;
    }

    if (e->type() == QEvent::ZOrderChange)
        raise();
}

/*!
    \reimp
*/
void QRubberBand::showEvent(QShowEvent *e)
{
    raise();
    e->ignore();
}

/*!
    \reimp
*/
void QRubberBand::resizeEvent(QResizeEvent *)
{
    Q_D(QRubberBand);
    d->updateMask();
}

/*!
    \reimp
*/
void QRubberBand::moveEvent(QMoveEvent *)
{
    Q_D(QRubberBand);
    d->updateMask();
}

/*!
    \fn void QRubberBand::move(const QPoint &p);

    \overload

    Moves the rubberband to point \a p.

    \sa resize()
*/

/*!
    \fn void QRubberBand::move(int x, int y);

    Moves the rubberband to point (\a x, \a y).

    \sa resize()
*/

/*!
    \fn void QRubberBand::resize(const QSize &size);

    \overload

    Resizes the rubberband so that its new size is \a size.

    \sa move()
*/

/*!
    \fn void QRubberBand::resize(int width, int height);

    Resizes the rubberband so that its width is \a width, and its
    height is \a height.

    \sa move()
*/

/*!
    \fn void QRubberBand::setGeometry(const QRect &rect)

    Sets the geometry of the rubber band to \a rect, specified in the coordinate system
    of its parent widget.

    \sa QWidget::geometry
*/
void QRubberBand::setGeometry(const QRect &geom)
{
    QWidget::setGeometry(geom);
}

/*!
    \fn void QRubberBand::setGeometry(int x, int y, int width, int height)
    \overload

    Sets the geometry of the rubberband to the rectangle whose top-left corner lies at
    the point (\a x, \a y), and with dimensions specified by \a width and \a height.
    The geometry is specified in the parent widget's coordinate system.
*/

/*! \reimp */
bool QRubberBand::event(QEvent *e)
{
    return QWidget::event(e);
}

QT_END_NAMESPACE

#endif // QT_NO_RUBBERBAND


text:
package pl.sloniec.frontend.screens;

import javax.swing.JPanel;

import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class StartScreen extends JPanel {

	private static final long serialVersionUID = 1L;
	public JTextField textFieldPassLen;
	public JTextField textFieldSignsNum;
	public JTextField textFieldPartSize;

	public StartScreen() {
		init();
	}

	private void init() {
		setLayout(null);

		JLabel lblNewLabel = new JLabel("Press 'Start' to initialize the server");
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel.setBounds(200, 350, 200, 20);
		add(lblNewLabel);

		textFieldPassLen = new JTextField();
		textFieldPassLen.setHorizontalAlignment(SwingConstants.CENTER);
		textFieldPassLen.setBounds(300, 60, 86, 20);
		add(textFieldPassLen);
		textFieldPassLen.setColumns(10);

		textFieldSignsNum = new JTextField();
		textFieldSignsNum.setHorizontalAlignment(SwingConstants.CENTER);
		textFieldSignsNum.setBounds(300, 91, 86, 20);
		add(textFieldSignsNum);
		textFieldSignsNum.setColumns(10);

		textFieldPartSize = new JTextField();
		textFieldPartSize.setHorizontalAlignment(SwingConstants.CENTER);
		textFieldPartSize.setBounds(300, 122, 86, 20);
		add(textFieldPartSize);
		textFieldPartSize.setColumns(10);

		JLabel lblNewLabel_1 = new JLabel("Maximum password length");
		lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
		lblNewLabel_1.setBounds(90, 63, 200, 14);
		add(lblNewLabel_1);

		JLabel lblNewLabel_2 = new JLabel("Signs table size");
		lblNewLabel_2.setHorizontalAlignment(SwingConstants.RIGHT);
		lblNewLabel_2.setBounds(90, 94, 200, 14);
		add(lblNewLabel_2);

		JLabel lblNewLabel_3 = new JLabel("Distributed partition size");
		lblNewLabel_3.setHorizontalAlignment(SwingConstants.RIGHT);
		lblNewLabel_3.setBounds(90, 125, 200, 14);
		add(lblNewLabel_3);

		JTextArea textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setEnabled(false);
		textArea.setBounds(396, 58, 194, 84);
		add(textArea);

	}
}


text:
require 'spec_helper'

describe UpdateUserActivityWorker, :redis do
  let(:user_active_2_days_ago) { create(:user, current_sign_in_at: 10.months.ago) }
  let(:user_active_yesterday_1) { create(:user) }
  let(:user_active_yesterday_2) { create(:user) }
  let(:user_active_today) { create(:user) }
  let(:data) do
    {
      user_active_2_days_ago.id.to_s => 2.days.ago.at_midday.to_i.to_s,
      user_active_yesterday_1.id.to_s => 1.day.ago.at_midday.to_i.to_s,
      user_active_yesterday_2.id.to_s => 1.day.ago.at_midday.to_i.to_s,
      user_active_today.id.to_s => Time.now.to_i.to_s
    }
  end

  it 'updates users.last_activity_on' do
    subject.perform(data)

    aggregate_failures do
      expect(user_active_2_days_ago.reload.last_activity_on).to eq(2.days.ago.to_date)
      expect(user_active_yesterday_1.reload.last_activity_on).to eq(1.day.ago.to_date)
      expect(user_active_yesterday_2.reload.last_activity_on).to eq(1.day.ago.to_date)
      expect(user_active_today.reload.reload.last_activity_on).to eq(Date.today)
    end
  end

  it 'deletes the pairs from Redis' do
    data.each { |id, time| Gitlab::UserActivities.record(id, time) }

    subject.perform(data)

    expect(Gitlab::UserActivities.new.to_a).to be_empty
  end
end


text:
import click
from .openligadb import OpenLigaDB
from . import helpers

pass_openligadb = click.make_pass_decorator(OpenLigaDB)

@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
    """
    Bundesliga results and stats for hackers.

    bundesliga-cli is a CLI tool that provides access to Bundesliga
    results and stats.

    Uses openligadb-json-api.heroku.com API which is itself a JSON wrapper
    around the OpenligaDB API (http://www.openligadb.de).
    """
    ctx.obj = OpenLigaDB()

@cli.command()
@click.option('--matchday', '-d', help='Defines the matchday')
@click.option('--league', '-l', help='Defines the league (e.g. bl1, bl2, bl3)')
@click.option('--season', '-s', help='Defines the season (e.g. 2014, 2013)')
@pass_openligadb
def matchday(openligadb, season, matchday, league):
    """
    Match results for the given matchday.

    Get all available league shortcuts with 'buli leagues'.

    Season format: e.g. 2014 or 2011
    """
    if not league:
        league = openligadb.ERSTE_LIGA

    if not matchday:
        matchday = openligadb.getNextMatchday(league)

    if not season:
        season = openligadb.getCurrentSeason(league)  # ['name']

    matches = openligadb.getMatchdayResults(matchday, season, league)
    matches = helpers.process_matches(matches)

    table = helpers.create_results_table()
    for match in matches:
        table.add_row(match)

    print(table)

@cli.command()
@click.option('--league', '-l', help='Defines the league')
@pass_openligadb
def next(openligadb, league):
    """
    Shows the match results for the next/current matchday.

    Get all available league shortcuts with 'buli leagues'.
    """
    if not league:
        league = openligadb.ERSTE_LIGA

    matchday = openligadb.getNextMatchday(league)

    season = openligadb.getCurrentSeason(league)

    matches = openligadb.getMatchdayResults(matchday=matchday, season=season,
                                            league=league)
    matches = helpers.process_matches(matches)

    table = helpers.create_results_table()
    for match in matches:
        table.add_row(match)

    print(table)

@cli.command()
@click.option('--league', '-l', help='Defines the league')
@pass_openligadb
def last(openligadb, league):
    """
    Shows the match results for the last matchday.

    Get all available league shortcuts with 'buli leagues'.
    """
    matchday = openligadb.getRecentMatchday()

    if not league:
        league = openligadb.ERSTE_LIGA

    season = openligadb.getCurrentSeason(league)

    matches = openligadb.getMatchdayResults(matchday=matchday, season=season,
                                            league=league)
    matches = helpers.process_matches(matches)

    table = helpers.create_results_table()
    for match in matches:
        table.add_row(match)

    print(table)

@cli.command()
@click.option('--league', '-l', help='Defines the league')
@click.option('--season', '-s', help='Defines the season')
@pass_openligadb
def table(openligadb, league, season):
    """
    Shows the league table.

    By default the league table for the 1. Bundesliga and the currrent
    season is displayed.

    Get all available league shortcuts with 'buli leagues'.

    Season format: e.g. 2014 or 2011
    """
    if not league:
        league = openligadb.ERSTE_LIGA

    if not season:
        season = openligadb.getCurrentSeason(league)  # ['name']

    table_stats = openligadb.getTable(season, league)
    rows = helpers.process_table_stats(table_stats)

    click.echo(helpers.create_table_table(rows))

@cli.command()
@click.option('--league', '-l', help='Defines the league')
@click.option('--season', '-s', help='Defines the season')
@pass_openligadb
def teams(openligadb, league, season):
    """
    Shows the teams for a league and season.

    If no season is specified, the current season will be used.
    If no league is specified, the 1. Fussball Bundesliga will be used.

    League format: 'bl1' for 1. Bundesliga, 'bl2' for 2. Bundesliga, etc.

    Get all available league shortcuts with 'buli leagues'.

    Season format: e.g. 2014 or 2011
    """
    if not league:
        league = openligadb.ERSTE_LIGA

    if not season:
        season = openligadb.getCurrentSeason(league)

    table = helpers.create_teams_table()
    teams = openligadb.getTeams(season, league)

    for team in teams:
        row = [team['TeamName']]
        table.add_row(row)

    print(table)

# depreceated
# @pass_openligadb
# def leagues(openligadb):
#     """
#     Shows all available soccer leagues.

#     The 'league shortcut' can be used to specify the league option for
#     the other options.
#     """
#     table = helpers.create_leagues_table()
#     leagues = openligadb.getAvailLeagues()

#     for l in leagues:
#         row = [l['leagueName'], l['leagueSaison'], l['leagueShortcut']]
#         table.add_row(row)

#     print(table)

if __name__ == '__main__':
        cli(obj={})


text:
package org.apache.ivy.core.module.descriptor;

import java.util.Map;

/**
 * A configuration which is actually a group of several configurations.
 */
public class ConfigurationGroup extends Configuration {

    private final Map<String, Configuration> members;

    public ConfigurationGroup(String confName, Map<String, Configuration> members) {
        super(confName);
        this.members = members;
    }

    /**
     * Returns the list of configurations' names this object is a group of.
     *

     * This list is built from the configuration name, if some of these configuration names have
     * actually not been recognized in the module, they will be null when accessed from
     * {@link org.apache.ivy.core.module.descriptor.ConfigurationIntersection#getIntersectedConfiguration(String)}.
     *

     *
     * @return the list of configurations' names this object is an intersection of.
     */
    public String[] getMembersConfigurationNames() {
        return members.keySet().toArray(new String[members.size()]);
    }

    /**
     * Returns the {@link Configuration} object for the given conf name, or null if the
     * given conf name is not part of this group or if this conf name isn't defined in the module in
     * which this group has been built.
     *
     * @param confName
     *            the name of the configuration to return.
     * @return the member {@link Configuration} object for the given conf name
     */
    public Configuration getMemberConfiguration(String confName) {
        return members.get(confName);
    }

    public Visibility getVisibility() {
        for (Configuration c : members.values()) {
            if (c != null && Visibility.PRIVATE.equals(c.getVisibility())) {
                return Visibility.PRIVATE;
            }
        }
        return Visibility.PUBLIC;
    }
}


text:
#include <quantify/dimensions.h>
#include <cstring>

namespace Quantify {

Dimensions::Dimensions(char length, char mass, char time, char electricCurrent, char thermodynamicTemperature, char amountOfSubstance, char luminousIntensity)
{
    setLength(length);
    setMass(mass);
    setTime(time);
    setElectricCurrent(electricCurrent);
    setThermodynamicTemperature(thermodynamicTemperature);
    setAmountOfSubstance(amountOfSubstance);
    setLuminousIntensity(luminousIntensity);
}

Dimensions::Dimensions(const Dimensions &other)
{
    copyFrom(other);
}

Dimensions::Dimensions(Dimensions &&other)
{
    moveFrom(other);
}

Dimensions &Dimensions::operator=(const Dimensions &other)
{
    if(this != &other)
    {
        copyFrom(other);
    }

    return *this;
}

Dimensions &Dimensions::operator=(Dimensions &&other)
{
    if(this != &other)
    {
        moveFrom(other);
    }

    return *this;
}

char Dimensions::getLength() const
{
    return dimensions[QUANTIFY_DIMENSIONS_LENGTH_ID];
}

char Dimensions::getMass() const
{
    return dimensions[QUANTIFY_DIMENSIONS_MASS_ID];
}

char Dimensions::getTime() const
{
    return dimensions[QUANTIFY_DIMENSIONS_TIME_ID];
}

char Dimensions::getElectricCurrent() const
{
    return dimensions[QUANTIFY_DIMENSIONS_ELECTRIC_CURRENT_ID];
}

char Dimensions::getThermodynamicTemperature() const
{
    return dimensions[QUANTIFY_DIMENSIONS_THERMODYNAMIC_TEMPERATURE_ID];
}

char Dimensions::getAmountOfSubstance() const
{
    return dimensions[QUANTIFY_DIMENSIONS_AMOUNT_OF_SUBSTANCE_ID];
}

char Dimensions::getLuminousIntensity() const
{
   return dimensions[QUANTIFY_DIMENSIONS_LUMINOUS_INTENSITY_ID];
}

void Dimensions::setLength(char value)
{
    dimensions[QUANTIFY_DIMENSIONS_LENGTH_ID] = value;
}

void Dimensions::setMass(char value)
{
    dimensions[QUANTIFY_DIMENSIONS_MASS_ID] = value;
}

void Dimensions::setTime(char value)
{
    dimensions[QUANTIFY_DIMENSIONS_TIME_ID] = value;
}

void Dimensions::setElectricCurrent(char value)
{
    dimensions[QUANTIFY_DIMENSIONS_ELECTRIC_CURRENT_ID] = value;
}

void Dimensions::setThermodynamicTemperature(char value)
{
    dimensions[QUANTIFY_DIMENSIONS_THERMODYNAMIC_TEMPERATURE_ID] = value;
}

void Dimensions::setAmountOfSubstance(char value)
{
    dimensions[QUANTIFY_DIMENSIONS_AMOUNT_OF_SUBSTANCE_ID] = value;
}

void Dimensions::setLuminousIntensity(char value)
{
    dimensions[QUANTIFY_DIMENSIONS_LUMINOUS_INTENSITY_ID] = value;
}

bool Dimensions::equals(const Dimensions &other) const
{
    return memcmp(&dimensions, &(other.dimensions), QUANTIFY_DIMENSIONS_COUNT) == 0;
}

Dimensions Dimensions::multiplyBy(const Dimensions &other) const
{
    Dimensions result = *this;

    for(int i=0; i<QUANTIFY_DIMENSIONS_COUNT; ++i)
        result.dimensions[i] += other.dimensions[i];

    return result;
}

Dimensions Dimensions::divideBy(const Dimensions &other) const
{
    Dimensions result = *this;

    for(int i=0; i<QUANTIFY_DIMENSIONS_COUNT; ++i)
        result.dimensions[i] -= other.dimensions[i];

    return result;
}

Dimensions Dimensions::power(int power) const
{
    Dimensions result = *this;

    for(int i=0; i<QUANTIFY_DIMENSIONS_COUNT; ++i)
        result.dimensions[i] *= power;

    return result;
}

void Dimensions::copyFrom(const Dimensions &other)
{
    setLength(other.getLength());
    setMass(other.getMass());
    setTime(other.getTime());
    setElectricCurrent(other.getElectricCurrent());
    setThermodynamicTemperature(other.getThermodynamicTemperature());
    setAmountOfSubstance(other.getAmountOfSubstance());
    setLuminousIntensity(other.getLuminousIntensity());
}

void Dimensions::moveFrom(Dimensions &other)
{
    setLength(other.getLength());
    setMass(other.getMass());
    setTime(other.getTime());
    setElectricCurrent(other.getElectricCurrent());
    setThermodynamicTemperature(other.getThermodynamicTemperature());
    setAmountOfSubstance(other.getAmountOfSubstance());
    setLuminousIntensity(other.getLuminousIntensity());

    memset(other.dimensions, 0, QUANTIFY_DIMENSIONS_COUNT);
}

}


text:
import './test-blacklist';
import './test-client';


text:
'use strict';
var express       = require('express'),
    router        = express.Router(),
    bodyParser    = require('body-parser'),
    fs            = require('fs'),
    _             = require('lodash'),
    excel         = require('xlsx'),
    model         = require('../model'),
    util          = require('../helper/util'),
    logger        = require('../helper/logger'),
    q             = require('q');

var DEFAULT_TRAINING_PROGRAM_TYPE = 'Professional Skills/Other';

var COL_TRAINING_TITLE = 'Course Title';
var COL_COMPLETE_STATUS = 'Completion Status';
var COL_PERSION_NAME = 'Person Full Name';
var COL_PERSION_EMAIL = 'Person E-mail';
var COL_PERSION_EID = 'Person Person No';
var COL_PERSION_STATUS = 'Person Status';
var COL_PERSION_EMPLOYEE_TYPE = 'Person Employee Type';
var COL_PERSION_TYPE = 'Person Type';
var COL_CLASS_START_DATE = 'Class Start Date';
var COL_CLASS_COMPLETE_DATE = 'Completed Courses (Transcript) Ended/Completed On Date';
var COL_COURSE_ID = 'Course Course ID';
var COL_COURSE_PROGRAM_TYPE = 'Course Program';
var COL_CLASS_DELIVERY_NAME = 'Class Delivery Name';
var COL_CLASS_ID = 'Class ID';
var COL_CLASS_DURATION = 'Completed Courses (Transcript) Duration (HH:MM)';
var COL_IS_HOC_TRANSCRIPT = 'Is ad hoc transcript';
var COL_HEAD_COUNT = 'Head Count';

router
    .route('/file/updateStatus')
    .post(function (req, res) {
        if (req.file.path) {
            var trainingCollection = [];
            var userCollection = [];
            var training = { classList: [] };
            var user = {};
            var trainingClass = {};
            var workbook = excel.readFile(req.file.path);
            workbook.SheetNames.forEach(function (value, index) {
                if (value === 'list') {
                    var recordList = excel.utils.sheet_to_json(workbook.Sheets[value]);
                    console.log('total record count: ' + Object.keys(recordList).length);
                    var record = {};
                    var trainingStatus = '';
                    var trainingClass = {};
                    for (var i = 0; i < Object.keys(recordList).length; i+=1) {
                        record = recordList[i];
                        if (record[COL_TRAINING_TITLE]) {
                            // console.log('This is a training: ' + record[COL_TRAINING_TITLE]);
                            if (training.title) {
                                trainingCollection.push(training);
                                training = { title: record[COL_TRAINING_TITLE], classList: [] };
                            } else {
                                training.title = record[COL_TRAINING_TITLE];
                            }
                        } else if (record[COL_COMPLETE_STATUS]) {
                            // console.log('This is a training status: ' + record[COL_COMPLETE_STATUS]);
                            if (trainingStatus !== record[COL_COMPLETE_STATUS]) {
                                trainingStatus = record[COL_COMPLETE_STATUS];
                            }
                        } else if (record[COL_PERSION_EMAIL] !== '') {
                            if (record[COL_COURSE_ID]) {
                                training.trainingId = record[COL_COURSE_ID];
                            }
                            if (record[COL_COURSE_PROGRAM_TYPE]) {
                                training.programType = record[COL_COURSE_PROGRAM_TYPE];
                            } else {
                                training.programType = DEFAULT_TRAINING_PROGRAM_TYPE;
                            }

                            trainingClass = { status: trainingStatus };
                            if (record[COL_CLASS_START_DATE]) {
                                trainingClass.startDate = new Date(record[COL_CLASS_START_DATE]);
                            }
                            if (record[COL_CLASS_COMPLETE_DATE]) {
                                trainingClass.completeDate = new Date(record[COL_CLASS_COMPLETE_DATE]);
                            }
                            if (record[COL_CLASS_DELIVERY_NAME]) {
                                trainingClass.delivery = record[COL_CLASS_DELIVERY_NAME];
                            }
                            if (record[COL_CLASS_ID]) {
                                trainingClass.classID = record[COL_CLASS_ID];
                            }
                            if (record[COL_IS_HOC_TRANSCRIPT]) {
                                trainingClass.isHOC = record[COL_IS_HOC_TRANSCRIPT];
                            }
                            if (record[COL_HEAD_COUNT]) {
                                trainingClass.headCount = record[COL_HEAD_COUNT];
                            }
                            if (record[COL_PERSION_EMAIL]) {
                                trainingClass.userEmail = record[COL_PERSION_EMAIL];
                                training.classList.push(trainingClass); // TODO: ask aaron how to understand the duration
                            } else {
                                logger.info();
                            }

                            if (!_.find(userCollection, {'employeeID': record[COL_PERSION_EID]}) && record[COL_PERSION_EID]) {
                                user = {};
                                if (record[COL_PERSION_NAME]) {
                                    user.userName = record[COL_PERSION_NAME];
                                }
                                if (record[COL_PERSION_EMAIL]) {
                                    user.email = record[COL_PERSION_EMAIL];
                                }
                                if (record[COL_PERSION_EID]) {
                                    user.employeeID = record[COL_PERSION_EID];
                                }
                                if (record[COL_PERSION_TYPE]) {
                                    user.type = record[COL_PERSION_TYPE];
                                }
                                if (record[COL_PERSION_EMPLOYEE_TYPE]) {
                                    user.employeeType = record[COL_PERSION_EMPLOYEE_TYPE];
                                }
                                if (record[COL_PERSION_STATUS]) {
                                    user.status = record[COL_PERSION_EMPLOYEE_TYPE];
                                }

                                userCollection.push(user);
                            }
                        }
                    }

                    if (training.title) {
                        trainingCollection.push(training);
                    }

                    var trainingCount = 0;

                    q
                    .nfcall(model.trainingClass.insert, trainingCollection)
                    .then(function(docs) {
                        if (docs) {
                            trainingCount = docs.length;
                            console.log('find all users here');
                            return q.nfcall(model.users.findAll);
                        }
                    })
                    .then(function (users) {
                        var tempUser = {};
                        var promiseArray = [];
                        _.each(userCollection, function (user) {
                            if (user.email) {
                                tempUser = _.find(users, {email: user.email});
                                if (tempUser) {
                                    tempUser.userName = user.userName;
                                    tempUser.employeeID = user.employeeID;
                                    tempUser.type = user.type;
                                    tempUser.status = user.status;
                                    tempUser.employeeType = user.employeeType;
                                    promiseArray.push(q.nfcall(model.users.update, { _id: tempUser._id }, tempUser));
                                } else {
                                    promiseArray.push(q.nfcall(model.users.insert, user));
                                }
                            }
                        });

                        console.log(promiseArray.length);
                        return q.all(promiseArray);
                    })
                    .catch(function (err) {
                        logger.error('error happens when insert training class collection', err);
                        throw err;
                    })
                    .done(function () {
                        fs.unlink(req.file.path);
                        res.json({
                            success: true,
                            message: 'successfully upload ' + trainingCount + ' courses'
                        });
                    });
                }
            });
        }
    });

router
    .route('/file/upload')
    .post(function (req, res) {
        if (req.file.path) {
            var trainingCollection = [];
            var workbook = excel.readFile(req.file.path);
            workbook.SheetNames.forEach(function (value, index) {
                if (value === 'Course list') {
                    var previousRow = '1';
                    var training = {};
                    for (var z in workbook.Sheets[value]) {
                        if (z[0] !== '!') {
                            var row = z.match(/\d+/)[0];
                            if (row === '1') {
                                continue; // skip the header row
                            }

                            if (row !== previousRow) {
                                if (previousRow !== '1') {
                                    trainingCollection.push(training);
                                    training = {};
                                }
                                previousRow = row;
                            }

                            var col = z.match(/[A-Z]+/)[0];
                            var cellValue = _.trim(workbook.Sheets[value][z].v.toString()).replace(/\r?\n|\r/gm, '');

                            switch (col) {
                                case 'A':
                                    training.name = cellValue;
                                    break;
                                case 'B':
                                    training.courseId = cellValue;
                                    break;
                                case 'C':
                                    training.programType = cellValue;
                                    break;
                                case 'D':
                                    training.duration = cellValue;
                                    break;
                                case 'E':
                                    training.city = cellValue;
                                    break;
                                case 'F':
                                    training.seat = cellValue;
                                    break;
                                case 'G':
                                    training.cost = cellValue;
                                    break;
                                case 'H':
                                    training.instructor = cellValue;
                                    break;

                            }
                        }
                    }
                    trainingCollection.push(training);
                    training = {};

                    // insert colleciont into db
                    model.trainings.insert(trainingCollection, function (err, data) {
                        fs.unlink(req.file.path);
                        res.json({
                            success: true,
                            message: 'successfully upload ' + data.length + ' courses'
                        });
                    });
                }
            });
        }
    });

router
    .route('/')
    .get(function (req, res) {
        var loopCount = 0;
        model.trainings.findAll(function (err, trainingList) {
            _.each(trainingList, function (training) {
                var query = {
                    trainingList: {
                        $elemMatch: {
                            _id: training._id.toString()
                        }
                    }
                };

                model.users.find(query, function (err, userList) {
                    if (userList) {
                        _.each(userList, function (user) {
                            _.each(user, function (val, key) {
                                if (key !== '_id' && key !== 'NTAccount' && key !== 'userName') {
                                    delete user[key];
                                }
                            });
                        });
                        training.userList = userList;
                    }

                    if (++loopCount === trainingList.length) {
                        res.json(trainingList);
                    }
                });
            });
        });
    });

router
    .use(bodyParser.json())
    .param('id', function (req, res, next) {
        req.dbQuery = {
            _id: util.strToMongoId(req.params.id.toString())
        }; // here 10 means 10 base decimal system
        next();
    })
    .route('/:id')
    .get(function (req, res) {
        model.trainings.findOne(req.dbQuery, function (err, training) {
            if (training) {
                var query = {
                    trainingList: {
                        $elemMatch: {
                            _id: training._id.toString()
                        }
                    }
                };

                model.users.find(query, function (err, userList) {
                    if (userList) {
                        _.each(userList, function (user) {
                            _.each(user, function (val, key) {
                                if (key !== '_id' && key !== 'NTAccount' && key !== 'userName') {
                                    delete user[key];
                                }
                            });
                        });
                        training.userList = userList;
                    }

                    res.json(training);
                });
            }
        });
    })
    .delete(function (req, res) {
        model.trainings.remove(req.dbQuery, true, function (result) {
            res.json(result);
        });
    })
    .put(function (req, res) {
        var training = req.body;
        delete training._id;
        delete training.$promise;
        delete training.$resolved;
        model.trainings.update(req.dbQuery, training, function (result) {
            res.json(result);
        });
    });

module.exports = router;


text:
#include <aws/core/client/AWSError.h>
#include <aws/elasticbeanstalk/ElasticBeanstalkErrorMarshaller.h>
#include <aws/elasticbeanstalk/ElasticBeanstalkErrors.h>

using namespace Aws::Client;
using namespace Aws::ElasticBeanstalk;

AWSError<CoreErrors> ElasticBeanstalkErrorMarshaller::FindErrorByName(const char* errorName) const
{
  AWSError<CoreErrors> error = ElasticBeanstalkErrorMapper::GetErrorForName(errorName);
  if(error.GetErrorType() != CoreErrors::UNKNOWN)
  {
    return error;
  }

  return AWSErrorMarshaller::FindErrorByName(errorName);
}


text:
using namespace boost;
using namespace impala;
using namespace llvm;
using namespace std;

SubExprElimination::SubExprElimination(LlvmCodeGen* codegen) :
    codegen_(codegen) {
}

// Before running the standard llvm optimization passes, first remove redundant calls
// to slotref expression.  SlotRefs are more heavyweight due to the null handling that
// is required and after they are inlined, llvm is unable to eliminate the redundant
// inlined code blocks.
// For example:
//   select colA + colA would generate an inner loop with 2 calls to the colA slot ref,
// rather than doing subexpression elimination.  To handle this, we will:
//   1. inline all call sites in the original function except calls to SlotRefs
//   2. for all call sites to SlotRefs except the first to that SlotRef, replace the
//      results from the secondary calls with the result from the first and remove
//      the call instruction.
//   3. Inline calls to the SlotRefs (there should only be one for each slot ref).
//
// In the above example, the input function would look something like:
// int ArithmeticAdd(TupleRow* row, bool* is_null) {
//   bool lhs_is_null, rhs_is_null;
//   int lhs_value = SlotRef(row, &lhs_is_null);
//   if (lhs_is_null) { *is_null = true; return 0; }
//   int rhs_value = SlotRef(row, &rhs_is_null);
//   if (rhs_is_null) { *is_null = true; return 0; }
//   *is_null = false; return lhs_value + rhs_value;
// }
// During step 2, we'd substitute the second call to SlotRef with the results from
// the first call.
// int ArithmeticAdd(TupleRow* row, bool* is_null) {
//   bool lhs_is_null, rhs_is_null;
//   int lhs_value = SlotRef(row, &lhs_is_null);
//   if (lhs_is_null) { *is_null = true; return 0; }
//   int rhs_value = lhs_value;
//   rhs_is_null = lhs_is_null;
//   if (rhs_is_null) { *is_null = true; return 0; }
//   *is_null = false; return lhs_value + rhs_value;
// }
// And then rely on llvm to finish the removing the redundant code, resulting in:
// int ArithmeticAdd(TupleRow* row, bool* is_null) {
//   bool lhs_is_null, rhs_is_null;
//   int lhs_value = SlotRef(row, &lhs_is_null);
//   if (lhs_is_null) { *is_null = true; return 0; }
//   *is_null = false; return lhs_value + lhs_value;
// }
// Details on how to do this:
// http://llvm.org/docs/ProgrammersManual.html#replacing-an-instruction-with-another-value

// Step 2 requires more manipulation to ensure the resulting IR is still valid IR.
// The call to the expr returns two things, both of which need to be replaced.
// The value of the function as the return argument and whether or not the result was
// null as a function output argument.
//    1. The return value is trivial since with SSA, it is easy to identity all uses of
//       We simply replace the subsequent call instructions with the value.
//    2. For the is_null result ptr, we replace the call to the expr with a store
//       instruction of the cached value.
//       i.e:
//           val1 = Call(is_null_ptr);
//           is_null1 = *is_null_ptr
//           ...
//           val2 = Call(is_null_ptr);
//           is_null2 = *is_null_ptr
//       Becomes:
//           val1 = Call(is_null_ptr);
//           is_null1 = *is_null_ptr
//           ...
//           val2 = val1;
//           *is_null_ptr = is_null1;
//           is_null2 = *is_null_ptr
//       We do this because the is_null ptr is not SSA form, making manipulating it
//       complex. The above approach exactly preserves the Call function, including
//       all writes to ptrs. We then rely on the llvm load/store removal pass which
//       will remove the redundant loads (which is tricky since you have to track
//       other instructions that wrote to the ptr, etc).
// When doing the eliminations, we need to consider the call graph to make sure
// the instruction we are replacing with dominates the instruction we are replacing;
// that is, we need to guarantee the instruction we are replacing with always executes
// before the replacee instruction in all code paths.
// TODO: remove all this with expr refactoring. Everything will be SSA form then.
struct CachedExprResult {
  // First function call result. Subsequent calls will be replaced with this value
  CallInst* result;
  // First is null result. Subsequent calls will be replaced with this value.
  Instruction* is_null_value;
};

bool SubExprElimination::Run(Function* fn) {
  // Step 1:
  int num_inlined;
  do {
    // This assumes that all redundant exprs have been registered.
    num_inlined = codegen_->InlineCallSites(fn, true);
  } while (num_inlined > 0);

  // Mapping of (expr eval function, its 'row' arg) to cached result.  We want to remove
  // redundant calls to the same function with the same argument.
  map<pair<Function*, Value*>, CachedExprResult> cached_slot_ref_results;

  // Step 2:
  DominatorTree dom_tree;
  dom_tree.runOnFunction(*fn);

  inst_iterator fn_end = inst_end(fn);
  inst_iterator instr_iter = inst_begin(fn);
  // Loop over every instruction in the function.
  while (instr_iter != fn_end) {
    Instruction* instr = &*instr_iter;
    ++instr_iter;
    // Look for call instructions
    if (!CallInst::classof(instr)) continue;

    CallInst* call_instr = reinterpret_cast<CallInst*>(instr);
    Function* called_fn = call_instr->getCalledFunction();
    if (codegen_->registered_exprs_.find(called_fn) ==
        codegen_->registered_exprs_.end()) {
      continue;
    }

    // Found a registered expr function.  We generate the IR in a very specific way
    // when calling the expr.  The call instruction is always followed by loading the
    // resulting is_null result.  We need to update both.
    // TODO: we need to update this to do more analysis since we are relying on a very
    // specific code structure to do this.

    // Arguments are (row, scratch_buffer, is_null);
    DCHECK_EQ(call_instr->getNumArgOperands(), 3);
    Value* row_arg = call_instr->getArgOperand(0);

    DCHECK(BitCastInst::classof(row_arg));
    BitCastInst* row_cast = reinterpret_cast<BitCastInst*>(row_arg);
    // Get at the underlying row arg.  We need to differentiate between
    // call Fn(row1) and call Fn(row2). (identical fns but different input).
    row_arg = row_cast->getOperand(0);

    instr = &*instr_iter;
    ++instr_iter;

    if (!LoadInst::classof(instr)) continue;
    LoadInst* is_null_value = reinterpret_cast<LoadInst*>(instr);
    Value* loaded_ptr = is_null_value->getPointerOperand();

    // Subexpr elimination requires the IR to be a very specific form.
    //   call SlotRef(row, NULL, is_null_ptr)
    //   load is_null_ptr
    // Since we generate this IR currently, we can enforce this logic in our exprs
    // TODO: this should be removed/generalized with expr refactoring
    DCHECK_EQ(loaded_ptr, call_instr->getArgOperand(2));

    pair<Function*, Value*> call_desc = make_pair(called_fn, row_arg);
    if (cached_slot_ref_results.find(call_desc) == cached_slot_ref_results.end()) {
      CachedExprResult cache_entry;
      cache_entry.result = call_instr;
      cache_entry.is_null_value = is_null_value;
      cached_slot_ref_results[call_desc] = cache_entry;
    } else {
      // Reuse the result.
      CachedExprResult& cache_entry = cached_slot_ref_results[call_desc];
      if (dom_tree.dominates(cache_entry.result, call_instr)) {
        new StoreInst(cache_entry.is_null_value, loaded_ptr, call_instr);
        call_instr->replaceAllUsesWith(cache_entry.result);
        call_instr->eraseFromParent();
      }
    }
  }

  // Step 3:
  codegen_->InlineCallSites(fn, false);
  return true;
}


text:
#include "DFR_LCDKeypad.h"
/*
 * File: DFR_LCDKeypad.cpp
 * Hardware: DFRobot LCD Keypad Shield for Arduino
 * Author: Paul R. Nelson III
 * Version: 1.0
 * License: BSD 2-clause
 * Description:  Library for easy interaction with 'DFRobot LCD Keypad Shield V1.0'
 *   This library works conjunction with the LiquidCrystal library, and adds DFRobot
 *   specific features, such as backlight control on pin 10.  Readability, functionality
 *   and byte count are all concerns.
 *   Features - buttonUp, buttonDown, buttonHeld callbacks
 *            - setBrightness(byte brightness) function
 */
DFR_LCDKeypad::DFR_LCDKeypad(byte brightness)
		: _buttonDown(0), _buttonUp(0), _buttonHeld(0), _prevMs(0),
		  _buttonState(eNone), _heldInterval(cDefaultHeldInterval),
		  _brightness(brightness)
{
	// initialize backlight default to full brightness, if no parameter
	pinMode(cBacklightPin, OUTPUT);
	analogWrite(cBacklightPin, _brightness);
}

// Called from within loop() to update button state and dispatch calls to button handler
// callbacks as necessary.   Conditions checked for are button down, button up and button held
// longer than setable interval.  I believe debounce code is unnecessary because
// the A/D conversion appears to be soaking up any transients.
// (not entirely true, seeing some bounce if rapidly pressing button like a frantic monkey.)
// Typical use case seemes to be fine.
//
// _buttonUp() resets _heldInterval to cDefaultHeldInterval. - my usage, saves doing it in
// each client's buttonUp routine(s) using a function call.
//
// Note: the magic occuring in the first line turns an analog value to a key enumeration,
//   using a degree=1 least squares fit of the midpoint values between the analog key values.
//   this allows creating a reverse mapping of value to key without using a series of
//   if/then/else statements.  The code squeezes and additional 70 bytes out of the
//   equivalent if/then/else code at the cost of code clarity.
//   For full discussion, see ReadMe.txt
void
DFR_LCDKeypad::update()
{
	int kv = ((analogRead(cKeyPin) + 71) * 6) >> 10;   // MAGIC NUMBERS see ReadMe.txt
	eDFRKey keyRead = (kv < eNone) ? eDFRKey(kv) : eNone;

    // if button state differs from previous state, call appropriate callback function
	if( keyRead != _buttonState) {
		// accept the extra overhead of a temporary for previous state so that
		// client code can safely call getState() and have current button status.
		eDFRKey prevKey = _buttonState;
		_buttonState = keyRead;
		if( prevKey == eNone ) {
			if(_buttonDown)
				(*_buttonDown)(keyRead);	// call button down callback
		} else {
			if(_buttonUp) {
				_heldInterval = cDefaultHeldInterval;
				(*_buttonUp)(prevKey);		// call button up callback
			}
		}

	} else {
		if(_buttonState != eNone && _buttonHeld) {
			// button held down - check update interval
			unsigned long current = millis();
			if(current - _prevMs > _heldInterval) {
				_prevMs = current;
				(*_buttonHeld)(keyRead);	// call button held callback
			}
		}
		return;
	}
}


text:
Getting Started
================

**Requirements**

The following must be available and configured:

* python
* virtualenv

**Development Requirements**

* jshint (Available via: ``npm install -g jshint``)

**Getting Started**

Clone the repository to your disk, and then run ``setup`` - this will download all requirements and set up the database.


text:
package db

import (
	"fmt"

	"github.com/codegangsta/cli"
	apipb "github.com/otsimo/otsimopb"
	"github.com/otsimo/distribution/models"
)

type ListGameStream interface {
	Send(*apipb.ListItem) error
}

type Driver interface {
	Name() string
	GetTokenRepo() TokenRepo
	GetGameRepo() GameRepo
	GetGameReleaseRepo() GameReleaseRepo
	GetTarballRepo() TarballRepo
	ListGames(v models.ServerVersion, state apipb.ListGamesRequest_InnerState, limit int32, lang string, stream ListGameStream) error
	AllGames() Iterator
	GetABRepo() ABRepo
	GetCategoryRepo() CategoryRepo
	GetClientRepo() ClientRepo
	NewID() string
	Healthy() error
}

type RegisteredDriver struct {
	New   func(*cli.Context) (Driver, error)
	Flags []cli.Flag
}

var drivers map[string]*RegisteredDriver

func init() {
	drivers = make(map[string]*RegisteredDriver)
}

func Register(name string, rd *RegisteredDriver) error {
	if _, ext := drivers[name]; ext {
		return fmt.Errorf("Name already registered %s", name)
	}
	drivers[name] = rd
	return nil
}

func GetDriverNames() []string {
	drives := make([]string, 0)

	for name := range drivers {
		drives = append(drives, name)
	}
	return drives
}

func GetDriver(name string) *RegisteredDriver {
	return drivers[name]
}


text:
using views::Widget;

namespace {

const int kWidth = 500;

class TestLayoutDelegate : public OpaqueBrowserFrameViewLayoutDelegate {
 public:
  enum WindowState {
    STATE_NORMAL,
    STATE_MAXIMIZED,
    STATE_MINIMIZED,
    STATE_FULLSCREEN
  };

  TestLayoutDelegate()
      : show_avatar_(false),
        show_caption_buttons_(true),
        window_state_(STATE_NORMAL) {
  }

  virtual ~TestLayoutDelegate() {}

  void SetWindowTitle(const base::string16& title) {
    window_title_ = title;
  }

  void SetShouldShowAvatar(bool show_avatar) {
    show_avatar_ = show_avatar;
  }

  void SetShouldShowCaptionButtons(bool show_caption_buttons) {
    show_caption_buttons_ = show_caption_buttons;
  }

  void SetWindowState(WindowState state) {
    window_state_ = state;
  }

  // OpaqueBrowserFrameViewLayoutDelegate overrides:

  virtual bool ShouldShowWindowIcon() const OVERRIDE {
    return !window_title_.empty();
  }

  virtual bool ShouldShowWindowTitle() const OVERRIDE {
    return !window_title_.empty();
  }

  virtual base::string16 GetWindowTitle() const OVERRIDE {
    return window_title_;
  }

  virtual int GetIconSize() const OVERRIDE {
    // The value on linux_aura and non-aura windows.
    return 17;
  }

  virtual bool ShouldLeaveOffsetNearTopBorder() const OVERRIDE {
    return !IsMaximized();
  }

  virtual gfx::Size GetBrowserViewMinimumSize() const OVERRIDE {
    // Taken from a calculation in BrowserViewLayout.
    return gfx::Size(168, 64);
  }

  virtual bool ShouldShowCaptionButtons() const OVERRIDE {
    return show_caption_buttons_;
  }

  virtual bool ShouldShowAvatar() const OVERRIDE {
    return show_avatar_;
  }

  virtual bool IsRegularOrGuestSession() const OVERRIDE {
    return true;
  }

  virtual gfx::ImageSkia GetOTRAvatarIcon() const OVERRIDE {
    // The calculations depend on the size of the OTR resource, and chromeos
    // uses a different sized image, so hard code the size of the current
    // windows/linux one.
    gfx::ImageSkiaRep rep(gfx::Size(40, 29), 1.0f);
    gfx::ImageSkia image(rep);
    return image;
  }

  virtual bool IsMaximized() const OVERRIDE {
    return window_state_ == STATE_MAXIMIZED;
  }

  virtual bool IsMinimized() const OVERRIDE {
    return window_state_ == STATE_MINIMIZED;
  }

  virtual bool IsFullscreen() const OVERRIDE {
    return window_state_ == STATE_FULLSCREEN;
  }

  virtual bool IsTabStripVisible() const OVERRIDE {
    return window_title_.empty();
  }

  virtual int GetTabStripHeight() const OVERRIDE {
    return IsTabStripVisible() ? Tab::GetMinimumUnselectedSize().height() : 0;
  }

  virtual int GetAdditionalReservedSpaceInTabStrip() const OVERRIDE {
    return 0;
  }

  virtual gfx::Size GetTabstripPreferredSize() const OVERRIDE {
    // Measured from Tabstrip::GetPreferredSize().
    return IsTabStripVisible() ? gfx::Size(78, 29) : gfx::Size(0, 0);
  }

 private:
  base::string16 window_title_;
  bool show_avatar_;
  bool show_caption_buttons_;
  WindowState window_state_;

  DISALLOW_COPY_AND_ASSIGN(TestLayoutDelegate);
};

}  // namespace

class OpaqueBrowserFrameViewLayoutTest : public views::ViewsTestBase {
 public:
  OpaqueBrowserFrameViewLayoutTest() {}
  virtual ~OpaqueBrowserFrameViewLayoutTest() {}

  virtual void SetUp() OVERRIDE {
    views::ViewsTestBase::SetUp();

    delegate_.reset(new TestLayoutDelegate);
    layout_manager_ = new OpaqueBrowserFrameViewLayout(delegate_.get());
    layout_manager_->set_extra_caption_y(0);
    layout_manager_->set_window_caption_spacing(0);
    widget_ = new Widget;
    widget_->Init(CreateParams(Widget::InitParams::TYPE_POPUP));
    root_view_ = widget_->GetRootView();
    root_view_->SetSize(gfx::Size(kWidth, kWidth));
    root_view_->SetLayoutManager(layout_manager_);

    // Add the caption buttons. We use fake images because we're modeling the
    // Windows assets here, while the linux version uses differently sized
    // assets.
    //
    // TODO(erg): In a follow up patch, separate these sizes out into virtual
    // accessors so we can test both the windows and linux behaviours once we
    // start modifying the code.
    minimize_button_ = InitWindowCaptionButton(
        VIEW_ID_MINIMIZE_BUTTON, gfx::Size(26, 18));
    maximize_button_ = InitWindowCaptionButton(
        VIEW_ID_MAXIMIZE_BUTTON, gfx::Size(25, 18));
    restore_button_ = InitWindowCaptionButton(
        VIEW_ID_RESTORE_BUTTON, gfx::Size(25, 18));
    close_button_ = InitWindowCaptionButton(
        VIEW_ID_CLOSE_BUTTON, gfx::Size(43, 18));
  }

  virtual void TearDown() OVERRIDE {
    widget_->CloseNow();

    views::ViewsTestBase::TearDown();
  }

 protected:
  views::ImageButton* InitWindowCaptionButton(ViewID view_id,
                                              const gfx::Size& size) {
    views::ImageButton* button = new views::ImageButton(NULL);
    gfx::ImageSkiaRep rep(size, 1.0f);
    gfx::ImageSkia image(rep);
    button->SetImage(views::CustomButton::STATE_NORMAL, &image);
    button->set_id(view_id);
    root_view_->AddChildView(button);
    return button;
  }

  void AddWindowTitleIcons() {
    tab_icon_view_ = new TabIconView(NULL, NULL);
    tab_icon_view_->set_is_light(true);
    tab_icon_view_->set_id(VIEW_ID_WINDOW_ICON);
    root_view_->AddChildView(tab_icon_view_);

    window_title_ = new views::Label(delegate_->GetWindowTitle());
    window_title_->SetVisible(delegate_->ShouldShowWindowTitle());
    window_title_->SetEnabledColor(SK_ColorWHITE);
    window_title_->SetBackgroundColor(0x00000000);
    window_title_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
    window_title_->set_id(VIEW_ID_WINDOW_TITLE);
    root_view_->AddChildView(window_title_);
  }

  void AddAvatarButton() {
    menu_button_ = new AvatarMenuButton(NULL, false);
    menu_button_->set_id(VIEW_ID_AVATAR_BUTTON);
    delegate_->SetShouldShowAvatar(true);
    root_view_->AddChildView(menu_button_);
  }

  void AddAvatarLabel() {
    avatar_label_ = new AvatarLabel(NULL);
    avatar_label_->set_id(VIEW_ID_AVATAR_LABEL);
    root_view_->AddChildView(avatar_label_);

    // The avatar label should only be used together with the avatar button.
    AddAvatarButton();
  }

  void AddNewAvatarButton() {
   new_avatar_button_ =
       new views::MenuButton(NULL, base::string16(), NULL, false);
   new_avatar_button_->set_id(VIEW_ID_NEW_AVATAR_BUTTON);
   root_view_->AddChildView(new_avatar_button_);
  }

  void ExpectBasicWindowBounds() {
    EXPECT_EQ("428,1 25x18", maximize_button_->bounds().ToString());
    EXPECT_EQ("402,1 26x18", minimize_button_->bounds().ToString());
    EXPECT_EQ("0,0 0x0", restore_button_->bounds().ToString());
    EXPECT_EQ("453,1 43x18", close_button_->bounds().ToString());
  }

  Widget* widget_;
  views::View* root_view_;
  OpaqueBrowserFrameViewLayout* layout_manager_;
  scoped_ptr<TestLayoutDelegate> delegate_;

  // Widgets:
  views::ImageButton* minimize_button_;
  views::ImageButton* maximize_button_;
  views::ImageButton* restore_button_;
  views::ImageButton* close_button_;

  TabIconView* tab_icon_view_;
  views::Label* window_title_;

  AvatarLabel* avatar_label_;
  AvatarMenuButton* menu_button_;
  views::MenuButton* new_avatar_button_;

  DISALLOW_COPY_AND_ASSIGN(OpaqueBrowserFrameViewLayoutTest);
};

TEST_F(OpaqueBrowserFrameViewLayoutTest, BasicWindow) {
  // Tests the layout of a default chrome window with no avatars, no window
  // titles, and a tabstrip.
  root_view_->Layout();

  ExpectBasicWindowBounds();

  // After some visual inspection, it really does look like the tabstrip is
  // initally positioned out of our view.
  EXPECT_EQ("-1,13 398x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("261x73", layout_manager_->GetMinimumSize(kWidth).ToString());

  // A normal window with no window icon still produces icon bounds for
  // Windows, which has a hidden icon that a user can double click on to close
  // the window.
  EXPECT_EQ("6,4 17x17", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, BasicWindowMaximized) {
  // Tests the layout of a default chrome window with no avatars, no window
  // titles, and a tabstrip, but maximized this time.
  delegate_->SetWindowState(TestLayoutDelegate::STATE_MAXIMIZED);
  root_view_->Layout();

  // Note how the bounds start at the exact top of the window while maximized
  // while they start 1 pixel below when unmaximized.
  EXPECT_EQ("0,0 0x0", maximize_button_->bounds().ToString());
  EXPECT_EQ("403,0 26x18", minimize_button_->bounds().ToString());
  EXPECT_EQ("429,0 25x18", restore_button_->bounds().ToString());
  EXPECT_EQ("454,0 46x18", close_button_->bounds().ToString());

  EXPECT_EQ("-5,-3 392x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("262x61", layout_manager_->GetMinimumSize(kWidth).ToString());

  // In the maximized case, OpaqueBrowserFrameView::NonClientHitTest() uses
  // this rect, extended to the top left corner of the window.
  EXPECT_EQ("2,0 17x17", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, MaximizedWithYOffset) {
  // Tests the layout of a basic chrome window with the caption buttons slightly
  // offset from the top of the screen (as they are on Linux).
  layout_manager_->set_extra_caption_y(2);
  delegate_->SetWindowState(TestLayoutDelegate::STATE_MAXIMIZED);
  root_view_->Layout();

  // Note how the bounds start at the exact top of the window, DESPITE the
  // caption Y offset of 2. This ensures that we obey Fitts' Law (the buttons
  // are clickable on the top edge of the screen). However, the buttons are 2
  // pixels taller, so the images appear to be offset by 2 pixels.
  EXPECT_EQ("0,0 0x0", maximize_button_->bounds().ToString());
  EXPECT_EQ("403,0 26x20", minimize_button_->bounds().ToString());
  EXPECT_EQ("429,0 25x20", restore_button_->bounds().ToString());
  EXPECT_EQ("454,0 46x20", close_button_->bounds().ToString());

  EXPECT_EQ("-5,-3 392x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("262x61", layout_manager_->GetMinimumSize(kWidth).ToString());

  // In the maximized case, OpaqueBrowserFrameView::NonClientHitTest() uses
  // this rect, extended to the top left corner of the window.
  EXPECT_EQ("2,0 17x17", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, WindowButtonsOnLeft) {
  // Tests the layout of a chrome window with caption buttons on the left.
  std::vector<views::FrameButton> leading_buttons;
  std::vector<views::FrameButton> trailing_buttons;
  leading_buttons.push_back(views::FRAME_BUTTON_CLOSE);
  leading_buttons.push_back(views::FRAME_BUTTON_MINIMIZE);
  leading_buttons.push_back(views::FRAME_BUTTON_MAXIMIZE);
  layout_manager_->SetButtonOrdering(leading_buttons, trailing_buttons);
  root_view_->Layout();

  EXPECT_EQ("73,1 25x18", maximize_button_->bounds().ToString());
  EXPECT_EQ("47,1 26x18", minimize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", restore_button_->bounds().ToString());
  EXPECT_EQ("4,1 43x18", close_button_->bounds().ToString());

  EXPECT_EQ("93,13 398x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("261x73", layout_manager_->GetMinimumSize(kWidth).ToString());

  // If the buttons are on the left, there should be no hidden icon for the user
  // to double click.
  EXPECT_EQ("0,0 0x0", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, WithoutCaptionButtons) {
  // Tests the layout of a default chrome window with no caption buttons (which
  // should force the tab strip to be condensed).
  delegate_->SetShouldShowCaptionButtons(false);
  root_view_->Layout();

  EXPECT_EQ("0,0 0x0", maximize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", minimize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", restore_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", close_button_->bounds().ToString());

  EXPECT_EQ("-5,-3 500x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("251x61", layout_manager_->GetMinimumSize(kWidth).ToString());

  // A normal window with no window icon still produces icon bounds for
  // Windows, which has a hidden icon that a user can double click on to close
  // the window.
  EXPECT_EQ("2,0 17x17", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, MaximizedWithoutCaptionButtons) {
  // Tests the layout of a maximized chrome window with no caption buttons.
  delegate_->SetWindowState(TestLayoutDelegate::STATE_MAXIMIZED);
  delegate_->SetShouldShowCaptionButtons(false);
  root_view_->Layout();

  EXPECT_EQ("0,0 0x0", maximize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", minimize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", restore_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", close_button_->bounds().ToString());

  EXPECT_EQ("-5,-3 500x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("251x61", layout_manager_->GetMinimumSize(kWidth).ToString());

  // In the maximized case, OpaqueBrowserFrameView::NonClientHitTest() uses
  // this rect, extended to the top left corner of the window.
  EXPECT_EQ("2,0 17x17", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, WithWindowTitleAndIcon) {
  // Tests the layout of pop up windows.
  delegate_->SetWindowTitle(base::ASCIIToUTF16("Window Title"));
  AddWindowTitleIcons();
  root_view_->Layout();

  // We should have the right hand side should match the BasicWindow case.
  ExpectBasicWindowBounds();

  // Check the location of the tab icon and window title.
  EXPECT_EQ("6,3 17x17", tab_icon_view_->bounds().ToString());
  EXPECT_EQ("27,3 370x17", window_title_->bounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, WindowWithAvatar) {
  // Tests a normal tabstrip window with an avatar icon.
  AddAvatarButton();
  root_view_->Layout();

  ExpectBasicWindowBounds();

  // Check the location of the avatar
  EXPECT_EQ("7,11 40x29", menu_button_->bounds().ToString());
  EXPECT_EQ("45,13 352x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("261x73", layout_manager_->GetMinimumSize(kWidth).ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, WindowWithAvatarWithButtonsOnLeft) {
  // Tests the layout of a chrome window with an avatar icon and caption buttons
  // on the left. The avatar icon should therefore be on the right.
  // AddAvatarLabel() also adds the avatar button.
  AddAvatarLabel();
  std::vector<views::FrameButton> leading_buttons;
  std::vector<views::FrameButton> trailing_buttons;
  leading_buttons.push_back(views::FRAME_BUTTON_CLOSE);
  leading_buttons.push_back(views::FRAME_BUTTON_MINIMIZE);
  leading_buttons.push_back(views::FRAME_BUTTON_MAXIMIZE);
  layout_manager_->SetButtonOrdering(leading_buttons, trailing_buttons);
  root_view_->Layout();

  EXPECT_EQ("73,1 25x18", maximize_button_->bounds().ToString());
  EXPECT_EQ("47,1 26x18", minimize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", restore_button_->bounds().ToString());
  EXPECT_EQ("4,1 43x18", close_button_->bounds().ToString());

  // Check the location of the avatar
  EXPECT_EQ("454,11 40x29", menu_button_->bounds().ToString());

  // Check the tab strip bounds.
  gfx::Rect tab_strip_bounds = layout_manager_->GetBoundsForTabStrip(
      delegate_->GetTabstripPreferredSize(), kWidth);
  EXPECT_GT(tab_strip_bounds.x(), maximize_button_->bounds().x());
  EXPECT_GT(maximize_button_->bounds().right(), tab_strip_bounds.x());
  EXPECT_EQ(13, tab_strip_bounds.y());
  EXPECT_EQ(29, tab_strip_bounds.height());
  EXPECT_GT(avatar_label_->bounds().x(), tab_strip_bounds.right());
  EXPECT_EQ("261x73", layout_manager_->GetMinimumSize(kWidth).ToString());

  // Check the relative location of the avatar label to the avatar. The right
  // end of the avatar label should be slightly to the right of the right end of
  // the avatar icon.
  EXPECT_GT(avatar_label_->bounds().right(), menu_button_->bounds().right());
  EXPECT_GT(menu_button_->bounds().x(), avatar_label_->bounds().x());
  EXPECT_GT(menu_button_->bounds().bottom(),
            avatar_label_->bounds().bottom());
  EXPECT_GT(avatar_label_->bounds().y(), menu_button_->bounds().y());

  // This means that the menu will pop out facing the left (if it were to face
  // the right, it would go outside the window frame and be clipped).
  EXPECT_TRUE(menu_button_->button_on_right());

  // If the buttons are on the left, there should be no hidden icon for the user
  // to double click.
  EXPECT_EQ("0,0 0x0", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest,
       WindowWithAvatarWithoutCaptionButtonsOnLeft) {
  // Tests the layout of a chrome window with an avatar icon and no caption
  // buttons. However, the caption buttons *would* be on the left if they
  // weren't hidden, and therefore, the avatar icon should be on the right.
  // The lack of caption buttons should force the tab strip to be condensed.
  AddAvatarButton();
  std::vector<views::FrameButton> leading_buttons;
  std::vector<views::FrameButton> trailing_buttons;
  leading_buttons.push_back(views::FRAME_BUTTON_CLOSE);
  leading_buttons.push_back(views::FRAME_BUTTON_MINIMIZE);
  leading_buttons.push_back(views::FRAME_BUTTON_MAXIMIZE);
  layout_manager_->SetButtonOrdering(leading_buttons, trailing_buttons);
  delegate_->SetShouldShowCaptionButtons(false);
  root_view_->Layout();

  EXPECT_EQ("0,0 0x0", maximize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", minimize_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", restore_button_->bounds().ToString());
  EXPECT_EQ("0,0 0x0", close_button_->bounds().ToString());

  // Check the location of the avatar
  EXPECT_EQ("458,0 40x24", menu_button_->bounds().ToString());
  EXPECT_EQ("-5,-3 458x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("251x61", layout_manager_->GetMinimumSize(kWidth).ToString());

  // A normal window with no window icon still produces icon bounds for
  // Windows, which has a hidden icon that a user can double click on to close
  // the window.
  EXPECT_EQ("2,0 17x17", layout_manager_->IconBounds().ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, WindowWithNewAvatar) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kNewProfileManagement);

  // Tests a normal tabstrip window with the new style avatar icon.
  AddNewAvatarButton();
  root_view_->Layout();

  ExpectBasicWindowBounds();

  // Check the location of the caption button
  EXPECT_EQ("385,1 12x20", new_avatar_button_->bounds().ToString());
  // The basic window bounds are (-1, 13 398x29). There should not be an icon
  // avatar in the left, and the new avatar button has an offset of 5 to its
  // next control.
  EXPECT_EQ("-1,13 381x29",
            layout_manager_->GetBoundsForTabStrip(
                delegate_->GetTabstripPreferredSize(), kWidth).ToString());
  EXPECT_EQ("261x73", layout_manager_->GetMinimumSize(kWidth).ToString());
}

TEST_F(OpaqueBrowserFrameViewLayoutTest, WindowWithAvatarLabelAndButtonOnLeft) {
  AddAvatarLabel();
  root_view_->Layout();

  ExpectBasicWindowBounds();

  // Check the location of the avatar label relative to the avatar button if
  // both are displayed on the left side.
  // The label height and width depends on the font size and the text displayed.
  // This may possibly change, so we don't test it here.
  EXPECT_EQ(menu_button_->bounds().x() - 2, avatar_label_->bounds().x());
  EXPECT_EQ(
      menu_button_->bounds().bottom() - 3 - avatar_label_->bounds().height(),
      avatar_label_->bounds().y());
}


text:
"""
Django settings for {{ project_name }} project.

Generated by 'django-admin startproject' using Django 2.2.4.

For more information on this file, see
https://docs.djangoproject.com/en/{{ docs_version }}/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/
"""
# flake8: noqa
# pylint: disable=line-too-long,bad-continuation

import datetime
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "{{ secret_key }}"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    "django.contrib.flatpages",
    "rest_framework",
    "rest_framework_jwt",
    "corsheaders",
    "imagekit",
    "manifest",
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "{{ project_name }}.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, "{{ project_name }}", "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
            "builtins": [
                "django.templatetags.i18n",
                "manifest.templatetags.manifest",
            ],
        },
    }
]

WSGI_APPLICATION = "{{ project_name }}.wsgi.application"

# Database
# https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation"
        ".UserAttributeSimilarityValidator"
    },
    {
        "NAME": "django.contrib.auth.password_validation"
        ".MinimumLengthValidator"
    },
    {
        "NAME": "django.contrib.auth.password_validation"
        ".CommonPasswordValidator"
    },
    {
        "NAME": "django.contrib.auth.password_validation"
        ".NumericPasswordValidator"
    },
]

# Internationalization
# https://docs.djangoproject.com/en/{{ docs_version }}/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/{{ docs_version }}/howto/static-files/

STATIC_URL = "/static/"

# Manifest Specific Settings
# https://docs.djangoproject.com/en/{{ docs_version }}/howto/static-files/

SITE_ID = 1

AUTH_USER_MODEL = "manifest.User"

AUTHENTICATION_BACKENDS = (
    # Django Contrib
    "django.contrib.auth.backends.ModelBackend",
    # Django Manifest
    "manifest.backends.AuthenticationBackend",
)
WEBPACK_LOADER = {
    "DEFAULT": {
        "BUNDLE_DIR_NAME": "bundles/",
        "STATS_FILE": os.path.join(BASE_DIR, "webpack-stats.json"),
    }
}

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated"
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework_jwt.authentication.JSONWebTokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.BasicAuthentication",
    ],
    "DEFAULT_RENDERER_CLASSES": [
        "djangorestframework_camel_case.render.CamelCaseJSONRenderer",
        "rest_framework.renderers.JSONRenderer",
    ],
    "DEFAULT_PARSER_CLASSES": [
        "djangorestframework_camel_case.parser.CamelCaseFormParser",
        "djangorestframework_camel_case.parser.CamelCaseMultiPartParser",
        "djangorestframework_camel_case.parser.CamelCaseJSONParser",
        "rest_framework.parsers.JSONParser",
        "rest_framework.parsers.FormParser",
        "rest_framework.parsers.MultiPartParser",
    ],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 5,
    "JSON_UNDERSCOREIZE": {"no_underscore_before_number": True},
}

JWT_AUTH = {
    "JWT_ALLOW_REFRESH": True,
    "JWT_EXPIRATION_DELTA": datetime.timedelta(hours=1),
    "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7),
}

# local_settings.py is used to override environment-specific settings
# like DATABASES that differ between development and production.
try:
    # pylint: disable=wildcard-import, unused-wildcard-import
    from .local_settings import *  # noqa: F401, F403
except ImportError:
    pass