text:
package org.apache.storm.redis.trident.state;

import java.util.List;
import java.util.Map;
import org.apache.storm.redis.common.config.JedisPoolConfig;
import org.apache.storm.redis.common.mapper.RedisDataTypeDescription;
import org.apache.storm.task.IMetricsContext;
import org.apache.storm.trident.state.OpaqueValue;
import org.apache.storm.trident.state.Serializer;
import org.apache.storm.trident.state.State;
import org.apache.storm.trident.state.StateFactory;
import org.apache.storm.trident.state.StateType;
import org.apache.storm.trident.state.TransactionalValue;
import org.apache.storm.trident.state.map.CachedMap;
import org.apache.storm.trident.state.map.MapState;
import org.apache.storm.trident.state.map.NonTransactionalMap;
import org.apache.storm.trident.state.map.OpaqueMap;
import org.apache.storm.trident.state.map.SnapshottableMap;
import org.apache.storm.trident.state.map.TransactionalMap;
import org.apache.storm.tuple.Values;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

/**
 * IBackingMap implementation for single Redis environment.
 *
 * @param <T> value's type class
 * @see AbstractRedisMapState
 */
public class RedisMapState<T> extends AbstractRedisMapState<T> {
    private JedisPool jedisPool;
    private Options options;
    private Serializer serializer;
    private KeyFactory keyFactory;

    /**
     * Constructor
     *
     * @param jedisPool JedisPool
     * @param options options of State
     * @param serializer Serializer
     * @param keyFactory KeyFactory
     */
    public RedisMapState(JedisPool jedisPool, Options options,
                         Serializer<T> serializer, KeyFactory keyFactory) {
        this.jedisPool = jedisPool;
        this.options = options;
        this.serializer = serializer;
        this.keyFactory = keyFactory;
    }

    /**
     * Provides StateFactory for opaque transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @return StateFactory
     */
    public static StateFactory opaque(JedisPoolConfig jedisPoolConfig) {
        return opaque(jedisPoolConfig, new Options());
    }

    /**
     * Provides StateFactory for opaque transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param dataTypeDescription definition of data type
     * @return StateFactory
     */
    public static StateFactory opaque(JedisPoolConfig jedisPoolConfig, RedisDataTypeDescription dataTypeDescription) {
        Options opts = new Options();
        opts.dataTypeDescription = dataTypeDescription;
        return opaque(jedisPoolConfig, opts);
    }

    /**
     * Provides StateFactory for opaque transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param factory key factory
     * @return StateFactory
     */
    public static StateFactory opaque(JedisPoolConfig jedisPoolConfig, KeyFactory factory) {
        Options opts = new Options();
        opts.keyFactory = factory;
        return opaque(jedisPoolConfig, opts);
    }

    /**
     * Provides StateFactory for opaque transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param opts options of State
     * @return StateFactory
     */
    public static StateFactory opaque(JedisPoolConfig jedisPoolConfig, Options<OpaqueValue> opts) {
        return new Factory(jedisPoolConfig, StateType.OPAQUE, opts);
    }

    /**
     * Provides StateFactory for transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @return StateFactory
     */
    public static StateFactory transactional(JedisPoolConfig jedisPoolConfig) {
        return transactional(jedisPoolConfig, new Options());
    }

    /**
     * Provides StateFactory for transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param dataTypeDescription definition of data type
     * @return StateFactory
     */
    public static StateFactory transactional(JedisPoolConfig jedisPoolConfig, RedisDataTypeDescription dataTypeDescription) {
        Options opts = new Options();
        opts.dataTypeDescription = dataTypeDescription;
        return transactional(jedisPoolConfig, opts);
    }

    /**
     * Provides StateFactory for transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param factory key factory
     * @return StateFactory
     */
    public static StateFactory transactional(JedisPoolConfig jedisPoolConfig, KeyFactory factory) {
        Options opts = new Options();
        opts.keyFactory = factory;
        return transactional(jedisPoolConfig, opts);
    }

    /**
     * Provides StateFactory for transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param opts options of State
     * @return StateFactory
     */
    public static StateFactory transactional(JedisPoolConfig jedisPoolConfig, Options<TransactionalValue> opts) {
        return new Factory(jedisPoolConfig, StateType.TRANSACTIONAL, opts);
    }

    /**
     * Provides StateFactory for non transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @return StateFactory
     */
    public static StateFactory nonTransactional(JedisPoolConfig jedisPoolConfig) {
        return nonTransactional(jedisPoolConfig, new Options());
    }

    /**
     * Provides StateFactory for non transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param dataTypeDescription definition of data type
     * @return StateFactory
     */
    public static StateFactory nonTransactional(JedisPoolConfig jedisPoolConfig, RedisDataTypeDescription dataTypeDescription) {
        Options opts = new Options();
        opts.dataTypeDescription = dataTypeDescription;
        return nonTransactional(jedisPoolConfig, opts);
    }

    /**
     * Provides StateFactory for non transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param factory key factory
     * @return StateFactory
     */
    public static StateFactory nonTransactional(JedisPoolConfig jedisPoolConfig, KeyFactory factory) {
        Options opts = new Options();
        opts.keyFactory = factory;
        return nonTransactional(jedisPoolConfig, opts);
    }

    /**
     * Provides StateFactory for non transactional.
     *
     * @param jedisPoolConfig configuration for JedisPool
     * @param opts options of State
     * @return StateFactory
     */
    public static StateFactory nonTransactional(JedisPoolConfig jedisPoolConfig, Options<Object> opts) {
        return new Factory(jedisPoolConfig, StateType.NON_TRANSACTIONAL, opts);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Serializer getSerializer() {
        return serializer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected KeyFactory getKeyFactory() {
        return keyFactory;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected List<String> retrieveValuesFromRedis(List<String> keys) {
        String[] stringKeys = keys.toArray(new String[keys.size()]);

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();

            RedisDataTypeDescription description = this.options.dataTypeDescription;
            switch (description.getDataType()) {
                case STRING:
                    return jedis.mget(stringKeys);

                case HASH:
                    return jedis.hmget(description.getAdditionalKey(), stringKeys);

                default:
                    throw new IllegalArgumentException("Cannot process such data type: " + description.getDataType());
            }

        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void updateStatesToRedis(Map<String, String> keyValues) {
        Jedis jedis = null;

        try {
            jedis = jedisPool.getResource();

            RedisDataTypeDescription description = this.options.dataTypeDescription;
            switch (description.getDataType()) {
                case STRING:
                    String[] keyValue = buildKeyValuesList(keyValues);
                    jedis.mset(keyValue);
                    if (this.options.expireIntervalSec > 0) {
                        Pipeline pipe = jedis.pipelined();
                        for (int i = 0; i < keyValue.length; i += 2) {
                            pipe.expire(keyValue[i], this.options.expireIntervalSec);
                        }
                        pipe.sync();
                    }
                    break;

                case HASH:
                    jedis.hmset(description.getAdditionalKey(), keyValues);
                    if (this.options.expireIntervalSec > 0) {
                        jedis.expire(description.getAdditionalKey(), this.options.expireIntervalSec);
                    }
                    break;

                default:
                    throw new IllegalArgumentException("Cannot process such data type: " + description.getDataType());
            }

        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    private String[] buildKeyValuesList(Map<String, String> keyValues) {
        String[] keyValueLists = new String[keyValues.size() * 2];

        int idx = 0;
        for (Map.Entry<String, String> kvEntry : keyValues.entrySet()) {
            keyValueLists[idx++] = kvEntry.getKey();
            keyValueLists[idx++] = kvEntry.getValue();
        }

        return keyValueLists;
    }

    /**
     * RedisMapState.Factory provides single Redis environment version of StateFactory.
     */
    protected static class Factory implements StateFactory {
        public static final redis.clients.jedis.JedisPoolConfig DEFAULT_POOL_CONFIG = new redis.clients.jedis.JedisPoolConfig();

        JedisPoolConfig jedisPoolConfig;

        StateType type;
        Serializer serializer;
        KeyFactory keyFactory;
        Options options;

        /**
         * Constructor
         *
         * @param jedisPoolConfig configuration for JedisPool
         * @param type StateType
         * @param options options of State
         */
        public Factory(JedisPoolConfig jedisPoolConfig, StateType type, Options options) {
            this.jedisPoolConfig = jedisPoolConfig;
            this.type = type;
            this.options = options;

            this.keyFactory = options.keyFactory;
            if (this.keyFactory == null) {
                this.keyFactory = new KeyFactory.DefaultKeyFactory();
            }
            this.serializer = options.serializer;
            if (this.serializer == null) {
                this.serializer = DEFAULT_SERIALIZERS.get(type);
                if (this.serializer == null) {
                    throw new RuntimeException("Couldn't find serializer for state type: " + type);
                }
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public State makeState(Map<String, Object> conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
            JedisPool jedisPool = new JedisPool(DEFAULT_POOL_CONFIG,
                                                jedisPoolConfig.getHost(),
                                                jedisPoolConfig.getPort(),
                                                jedisPoolConfig.getTimeout(),
                                                jedisPoolConfig.getPassword(),
                                                jedisPoolConfig.getDatabase());
            RedisMapState state = new RedisMapState(jedisPool, options, serializer, keyFactory);
            CachedMap c = new CachedMap(state, options.localCacheSize);

            MapState ms;
            if (type == StateType.NON_TRANSACTIONAL) {
                ms = NonTransactionalMap.build(c);

            } else if (type == StateType.OPAQUE) {
                ms = OpaqueMap.build(c);

            } else if (type == StateType.TRANSACTIONAL) {
                ms = TransactionalMap.build(c);

            } else {
                throw new RuntimeException("Unknown state type: " + type);
            }

            return new SnapshottableMap(ms, new Values(options.globalKey));
        }
    }
}


text:
#ifdef SHOULD_COMPILE_LOOKIN_SERVER

//
//  UIImage+LookinServer.h
//  LookinServer
//
//  Created by Li Kai on 2019/5/14.
//  https://lookin.work
//

#import <UIKit/UIKit.h>

@interface UIImage (LookinServer)

@property(nonatomic, copy) NSString *lks_imageSourceName;

- (NSData *)lookin_data;

@end

#endif /* SHOULD_COMPILE_LOOKIN_SERVER */

redpajama_set_name: RedPajamaGithub


text:
class ShortLinksController < ApplicationController
  def post
    # TODO: add logging for analytics
    redirect_to post_url(params[:id], host: 'www.rubygamedev.com'), status: :moved_permanently
  end
end


text:
db.books.aggregate(
   { $group: { 0_id: "$editorial", editionSum: { $sum: "$edition" } } }
);

### match
db.books.aggregate(
[
   { $group: { 0_id: "$editorial", editionSum: { $sum: "$edition" } } },
   { $match: { editionSum: {$lt : 20000}} }
]
);

### References

#### Aggregation Zip Codes example

https://docs.mongodb.com/manual/tutorial/aggregation-zip-code-data-set/


text:
<?php

namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Flat;

use Magento\Framework\App\ResourceConnection;

class TableDataTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Framework\DB\Adapter\AdapterInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $_connectionMock;

    /**
     * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
     */
    protected $_objectManager;

    /**
     * @var Resource|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $_resourceMock;

    protected function setUp()
    {
        $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->_connectionMock = $this->getMock('Magento\Framework\DB\Adapter\AdapterInterface');
        $this->_resourceMock = $this->getMock('Magento\Framework\App\ResourceConnection', [], [], '', false);
    }

    /**
     * @param string $flatTable
     * @param bool $isFlatTableExists
     * @param string $flatDropName
     * @param string $temporaryFlatTableName
     * @param array $expectedRenameTablesArgument
     * @dataProvider moveDataProvider
     */
    public function testMove(
        $flatTable,
        $isFlatTableExists,
        $flatDropName,
        $temporaryFlatTableName,
        $expectedRenameTablesArgument
    ) {
        $this->_connectionMock->expects($this->exactly(2))->method('dropTable')->with($flatDropName);
        $this->_connectionMock->expects(
            $this->once()
        )->method(
            'isTableExists'
        )->with(
            $flatTable
        )->will(
            $this->returnValue($isFlatTableExists)
        );

        $this->_connectionMock->expects(
            $this->once()
        )->method(
            'renameTablesBatch'
        )->with(
            $expectedRenameTablesArgument
        );

        $this->_resourceMock->expects(
            $this->any()
        )->method(
            'getConnection'
        )->will(
            $this->returnValue($this->_connectionMock)
        );

        $model = $this->_objectManager->getObject(
            'Magento\Catalog\Model\Indexer\Product\Flat\TableData',
            ['resource' => $this->_resourceMock]
        );

        $model->move($flatTable, $flatDropName, $temporaryFlatTableName);
    }

    /**
     * @return array
     */
    public function moveDataProvider()
    {
        return [
            [
                'flat_table',
                true,
                'flat_table_to_drop',
                'flat_tmp',
                [
                    ['oldName' => 'flat_table', 'newName' => 'flat_table_to_drop'],
                    ['oldName' => 'flat_tmp', 'newName' => 'flat_table']
                ],
            ],
            [
                'flat_table',
                false,
                'flat_table_to_drop',
                'flat_tmp',
                [['oldName' => 'flat_tmp', 'newName' => 'flat_table']]
            ]
        ];
    }
}


text:
set -e

DISTFILES="package.json webpack.config.js webpack.config.electron.js LICENSE share bin server"

cd $(dirname $0)/..

export NODE_ENV=production

webpack --config webpack.config.electron.js
cp -r $DISTFILES dist/
cd dist/
yarn
rm -rf ../HTerminal-darwin-x64/
../node_modules/.bin/electron-packager ./ HTerminal \
  --platform=darwin --arch=x64 \
  --app-bundle-id=com.cgamesplay.hterminal \
  --app-category-type=app-category-type=public.app-category.developer-tools \
  --version 0.37.9 \
  --overwrite --prune --package-manager=yarn --out=..


text:
#ifndef _BREACH_HPP
#define _BREACH_HPP 1

#include "matrix.hpp"
#include "renderable.hpp"
#include "walls.hpp"

/**
 * @brief Defines a breach.
 */
class Breach {
    public:
        //! @brief Default breach width
        static const float DEFAULT_BREACH_WIDTH;
        //! @brief Default breach height
        static const float DEFAULT_BREACH_HEIGHT;

    private:
        //! @brief A breach can be either opened or closed (and not yet shot)
        bool opened;
        //! @brief The porting wall. Transformations are relative to it.
        const Wall* wall;
        //! @brief The breach color.
        Matrix<float,4,1> color;
        //! @brief Original shot point.
        Matrix<float,2,1> shotPoint;
        /**
        * @brief The transformation matrix to apply to translate, orient and scale the breach.
        *
        * After applying this transformation,
        * the breach must be rendered as a (possibly tesseled) quad,
        * using -1/+1 for X and Y, and 0 for Z.
        */
        Matrix<float,4,4> transformation;

        static Matrix<float,2,1> getAdjustedShotPoint     (const Wall& wall, const Matrix<float,2,1> shotPoint);
        static Matrix<float,4,4> getTransformationFromWall(const Wall& wall, const Matrix<float,2,1> shotPoint);

    public:
        static bool shootBreach(unsigned int index, const Wall& wall, Matrix<float,2,1> shotPoint);

        Breach(Matrix<float,4,1> color);
        Breach(bool opened, const Wall& wall, Matrix<float,4,1> color, Matrix<float,2,1> shotPoint); //Matrix<float,4,4> transformation);
        virtual ~Breach();

        bool isOpened() const;
        const Wall* getWall() const;
        Matrix<float,4,1> getColor() const;
        Matrix<float,2,1> getShotPoint() const;
        Matrix<float,4,4> getTransformation() const;
};

/**
 * @brief Renders a breach.
 */
class BreachRenderer : public SelectableLeafRenderable, public MatrixTransformerRenderable {
    protected:
        //! @brief Breach to render
        Breach& breach;
        Texturer& texturer;
        Texturer& highlightTexturer;
        //! @brief Tesseled rectangle used for both rendering hidden highlight
        TesseledRectangle renderRenderable;

    public:
        //! @brief Constructs a breach renderer for the given breach with the given name.
        //! @param wall The breach to render
        //! @param name The name of the breach
        BreachRenderer(Breach& breach, GLuint name, Texturer& texturer, Texturer& highlightTexturer);
        //! @brief Destructor.
        virtual ~BreachRenderer();

        //! @brief Updates the transformation before applying it
        virtual void loadTransform(GLenum renderingMode);
        //! @brief Renders the breach
        virtual void render(GLenum renderingMode);
};

//! @brief The defined breaches
//! @see initBreaches()
extern std::vector<Breach> breaches;

//! @brief Renderable for all the breaches
//! @see initBreaches()
extern IRenderable* breachesRenderer;

//! @brief Initializes \link ::breaches \endlink and \link ::breachesRenderer \endlink.
void initBreaches(Texture texture, Texture highlight);

#endif /*_BREACH_HPP*/


text:
layout: api
page_title: HTTP API
sidebar_current: api-overview
description: |-
  Consul exposes a RESTful HTTP API to control almost every aspect of the
  Consul agent.
---

# HTTP API

The main interface to Consul is a RESTful HTTP API. The API can basic perform
CRUD operations on nodes, services, checks, configuration, and more.

## Version Prefix

All API routes are prefixed with `/v1/`.

This documentation is only for the v1 API.

~> **Backwards compatibility:** At the current version, Consul does not yet
promise backwards compatibility even with the v1 prefix. We'll remove this
warning when this policy changes. We expect to reach API stability by Consul
1.0.

## ACLs

Several endpoints in Consul use or require ACL tokens to operate. An agent
can be configured to use a default token in requests using the `acl_token`
configuration option. However, the token can also be specified per-request
by using the `X-Consul-Token` request header or the `token` query string
parameter. The request header takes precedence over the default token, and
the query string parameter takes precedence over everything.

For more details about ACLs, please see the [ACL Guide](/docs/guides/acl.html).

## Authentication

When authentication is enabled, a Consul token should be provided to API
requests using the  `X-Consul-Token` header. This reduces the probability of the
token accidentally getting logged or  exposed. When using authentication,
clients should communicate via TLS.

Here is an example using `curl`:

```text
$ curl \
    --header "X-Consul-Token: abcd1234" \
    https://consul.rocks/v1/agent/members
```

Previously this was provided via a `?token=` query parameter. This functionality
exists on many endpoints for backwards compatibility, but its use is **highly
discouraged**, since it can show up in access logs as part of the URL.

## Blocking Queries

Many endpoints in Consul support a feature known as "blocking queries". A
blocking query is used to wait for a potential change using long polling. Not
all endpoints support blocking, but each endpoint uniquely documents its support
for blocking queries in the documentation.

Endpoints that support blocking queries return an HTTP header named
`X-Consul-Index`. This is a unique identifier representing the current state of
the requested resource.

On subsequent requests for this resource, the client can set the `index` query
string parameter to the value of `X-Consul-Index`, indicating that the client
wishes to wait for any changes subsequent to that index.

When this is provided, the HTTP request will "hang" until a change in the system
occurs, or the maximum timeout is reached. A critical note is that the return of
a blocking request is **no guarantee** of a change. It is possible that the
timeout was reached or that there was an idempotent write that does not affect
the result of the query.

In addition to `index`, endpoints that support blocking will also honor a `wait`
parameter specifying a maximum duration for the blocking request. This is
limited to 10 minutes. If not set, the wait time defaults to 5 minutes. This
value can be specified in the form of "10s" or "5m" (i.e., 10 seconds or 5
minutes, respectively). A small random amount of additional wait time is added
to the supplied maximum `wait` time to spread out the wake up time of any
concurrent requests. This adds up to `wait / 16` additional time to the maximum
duration.

## Consistency Modes

Most of the read query endpoints support multiple levels of consistency. Since
no policy will suit all clients' needs, these consistency modes allow the user
to have the ultimate say in how to balance the trade-offs inherent in a
distributed system.

The three read modes are:

- `default` - If not specified, the default is strongly consistent in almost all
  cases. However, there is a small window in which a new leader may be elected
  during which the old leader may service stale values. The trade-off is fast
  reads but potentially stale values. The condition resulting in stale reads is
  hard to trigger, and most clients should not need to worry about this case.
  Also, note that this race condition only applies to reads, not writes.

- `consistent` - This mode is strongly consistent without caveats. It requires
  that a leader verify with a quorum of peers that it is still leader. This
  introduces an additional round-trip to all server nodes. The trade-off is
  increased latency due to an extra round trip. Most clients should not use this
  unless they cannot tolerate a stale read.

- `stale` - This mode allows any server to service the read regardless of
  whether it is the leader. This means reads can be arbitrarily stale; however,
  results are generally consistent to within 50 milliseconds of the leader. The
  trade-off is very fast and scalable reads with a higher likelihood of stale
  values. Since this mode allows reads without a leader, a cluster that is
  unavailable will still be able to respond to queries.

To switch these modes, either the `stale` or `consistent` query parameters
should be provided on requests. It is an error to provide both.

To support bounding the acceptable staleness of data, responses provide the
`X-Consul-LastContact` header containing the time in milliseconds that a server
was last contacted by the leader node. The `X-Consul-KnownLeader` header also
indicates if there is a known leader. These can be used by clients to gauge the
staleness of a result and take appropriate action.

## Formatted JSON Output

By default, the output of all HTTP API requests is minimized JSON. If the client
passes `pretty` on the query string, formatted JSON will be returned.

## HTTP Methods

Consul's API aims to be RESTful, although there are some exceptions. The API
responds to the standard HTTP verbs GET, PUT, and DELETE. Each API method will
clearly document the verb(s) it responds to and the generated response. The same
path with different verbs may trigger different behavior. For example:

```text
PUT /v1/kv/foo
GET /v1/kv/foo
```

Even though these share a path, the `PUT` operation creates a new key whereas
the `GET` operation reads an existing key.

Here is the same example using `curl`:

```shell
$ curl \
    --request PUT \
    --data 'hello consul' \
    https://consul.rocks/v1/kv/foo
```

## Translated Addresses

Consul 0.7 added the ability to translate addresses in HTTP response based on
the configuration setting for
[`translate_wan_addrs`](/docs/agent/options.html#translate_wan_addrs). In order
to allow clients to know if address translation is in effect, the
`X-Consul-Translate-Addresses` header will be added if translation is enabled,
and will have a value of `true`. If translation is not enabled then this header
will not be present.


text:
package sn.customtypes;

import com.clearspring.analytics.stream.frequency.CountMinSketch;
import sn.utils.Names;
import storm.trident.tuple.TridentTuple;

/**
 * Created by sumanthn on 5/4/14.
 */
public class DataVolumeAggregator extends CMSCombineAggregator {

    public DataVolumeAggregator() {
    }

    public DataVolumeAggregator(int keyCount) {
        super(keyCount);
    }

    @Override
    public CountMinSketch init(TridentTuple tuple) {

        CountMinSketch sketch = zero();
        long bytes = tuple.getLongByField(Names.BYTES_FLD);
        sketch.add(tuple.getStringByField(Names.HOSTNAME_FLD), bytes);

        return sketch;
    }
}


text:
package com.google.security.zynamics.binnavi.API.debug;

import java.util.List;

import com.google.common.collect.Lists;
import com.google.security.zynamics.binnavi.API.disassembly.Address;
import com.google.security.zynamics.binnavi.debug.connection.packets.replies.AnyBreakpointRemovedReply;
import com.google.security.zynamics.binnavi.debug.connection.packets.replies.AnyBreakpointSetReply;
import com.google.security.zynamics.binnavi.disassembly.RelocatedAddress;
import com.google.security.zynamics.zylib.general.Pair;

public class DebuggerAnyBreakpointSetReply extends DebuggerReply {

  public DebuggerAnyBreakpointSetReply(final AnyBreakpointSetReply reply) {
    super(reply);
  }

  public List<Pair<Address, Integer>> getAddresses() {
    final List<Pair<Address, Integer>> addresses = Lists.newArrayList();
    for (final Pair<RelocatedAddress, Integer> address : ((AnyBreakpointRemovedReply) reply)
        .getAddresses()) {
      addresses.add(new Pair<Address, Integer>(new Address(address.first().getAddress()
          .toBigInteger()), address.second()));
    }
    return addresses;
  }

}


text:
class Answer < ApplicationRecord
	acts_as_votable
	belongs_to :user
	belongs_to :question
	validates  :question_id, :user_id, :text, presence: true
end


text:
A collection of custom local transforms for the [Maltego](http://www.paterva.com/web6/products/maltego.php)
OSINT gathering tool.

## local_pull_aliases.py, local_pull_hashtags.py, local_pull_urls.py, local_tweet_to_words.py
Extracts entities from Tweets just like the built-in transforms, but faster as they
don't send the Tweets off the the remote servers, but extract the entities locally in code.

### Requirements:
Depends on [twitter-text-python](https://github.com/edburnett/twitter-text-python) which
can be installed with `pip install twitter-text-python`.

**local_tweet_to_words.py** also depends on [Natural Language Toolkit](http://www.nltk.org/)
which can be installed with `pip install nltk`. After installation, execute
`python -c "import nltk; nltk.download()"` in a terminal and download the `stopwords`
package under the Corpora tab.

## follow_redirects.py
URL transform that follows up to 15 HTTP redirects and returns the final URL.
Convenient if a transform returns a shortened or obfuscated URL.

**Note:** Running this transform will potentially engage target systems,
so if you're doing passive reconnaissance, this transform should not be used!


text:
from __future__ import absolute_import, unicode_literals

from .views import PollCRUDL, PollRunCRUDL, ResponseCRUDL

urlpatterns = PollCRUDL().as_urlpatterns()
urlpatterns += PollRunCRUDL().as_urlpatterns()
urlpatterns += ResponseCRUDL().as_urlpatterns()


text:
Set traffic control to a docker container
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Execute ``tcconfig`` with ``--docker`` option on a Docker host:

.. code-block:: console

    # tcset <container name or ID> --docker ...

You could use ``--src-container``/``--dst-container`` options to specify source/destination container.

Set traffic control within a docker container
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You need to run a container with ``--cap-add NET_ADMIN`` option
if you you would like to set a tc rule within a container:

.. code-block:: console

    docker run -d --cap-add NET_ADMIN -t <docker image>

A container image that builtin tcconfig can be available at https://hub.docker.com/r/thombashi/tcconfig/


text:
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from . import views

urlpatterns = [
    # example of url /simpleplantms/sites/
    url(r'^$', login_required(views.IndexView.as_view()), name='sites-index'),
    # example of url /simpleplantms/sites/20/
    url(r'^(?P<pk>[0-9]+)/$', login_required(views.DetailView.as_view()),
        name='sites-details'),
    # example of url /simpleplantms/sites/34/update/
    url(r'^(?P<pk>[0-9]+)/update/$',
        login_required(views.UpdateView.as_view()), name='sites-update'),
    # example of url /simpleplantms/sites/34/delete/
    url(r'^(?P<pk>[0-9]+)/delete/$',
        login_required(views.DeleteView.as_view()), name='sites-delete'),
    # example of url /simpleplantms/sites/create/
    url(r'^create/', login_required(views.CreateView.as_view()), name='sites-create'),
]


text:
<?php include('header.php'); ?>
<?php include('dbconn.php'); ?>

<title>Employee home page</title>

View Employees

Home

Insert

Employee

Customer

Account

View

Employee

Customer

Account

Transactions

About

Logout

<?php

require_once("config.php");

$employeequery = "SELECT * from customer_service_manager";
//#$employeequery = "SELECT  from employee e1, employee e2 where e1.emp_id = e2.manager";
$employeeslist = @mysql_query($employeequery);
if(isset($_POST['update'])) {
	if (isset($_POST['select'])){
		$_SESSION['empid'] = $_POST['select'];
		header("location: employee_update.php");
	}
	else{
		$msg = "no rows selected";
	}
#include 'employee_update.php';
}
if(isset($_POST['delete'])) {
	if (isset($_POST['select'])){
		$query = "DELETE FROM employee WHERE emp_id=".$_POST['select'];
		$result = @mysql_query($query);
		if ($result){
			$msg = "Sucessfully deleted employee id ".$_POST['select'];
			$employeeslist = @mysql_query($employeequery);
		}
	}
	else{
		$msg = "No rows selected";
	}
}

echo "<form method='post' action=".$_SERVER['PHP_SELF'].">";
echo "
";
echo "
SelectEmployee IDName Login  Mananger Name  SSN No
";
  while ($row = mysql_fetch_assoc($employeeslist)){
  $query="select name from employee where emp_id=".$row['manager'];
  if ($result1 = @mysql_query($query)){
	$managerResult = mysql_fetch_assoc($result1);

   echo "
<input type='radio' name='select' value='".$row['emp_id']."'>".$row['emp_id']."".$row['name']."".$row['login']."".$managerResult['name']."".$row['ssn'];
  }
  }
   ?>

   <input type="submit" name="update" value="Update Record">
   <input type="submit" name="delete" value="Delete Record">
</form>

<?php
if(isset($_POST['delete'])||isset($_POST['update'])){
	echo $msg;
	}
?>
<?php require_once('footer.php') ?>


text:
def separate_comma(number)
	number = number.to_s #no destructive version

	count = 0
	new_string = ""
	number.split("").reverse.each {|i| #iterates through each character of the number backwards.
		new_string += i
		count += 1
		if(count >= 3) #every 3rd character it adds a comma.
			new_string += ","
			count = 0
		end
	}
	new_string.reverse! #the output of the above loop is in reverse, so fix that

	if(new_string[0] == ","); new_string[0] = "" end #it's possible to have a comma at the beginning, so it checks for that.

	return new_string
end

=begin

Reflection:

What was your process for breaking the problem down? What different approaches did you consider?

	I thought of what exactly I would be doing and each step I would need to do to get the desired result.

Was your pseudocode effective in helping you build a successful initial solution?

	For this challenge I found it more effective to just write it all out in code. I didn't find this challenge very difficult.

What new Ruby method(s) did you use when refactoring your solution? Describe your experience of using the Ruby documentation to implement it/them (any difficulties, etc.). Did it/they significantly change the way your code works? If so, how?

	I used string's split method to divide the string into an array. I didn't have very much difficulty using the ruby docs.

How did you initially iterate through the data structure?

	I used the .each method.

Do you feel your refactored solution is more readable than your initial solution? Why?

	Yes, mostly because I added comments though.

=end


text:
using EventStore.Core.TransactionLog.LogRecords;

namespace EventStore.Projections.Core.Services.Processing
{
    internal struct PrepareInfo
    {
        private readonly PrepareLogRecord _prepareRecord;

        public PrepareInfo(PrepareLogRecord prepareRecord)
            : this()
        {
            _prepareRecord = prepareRecord;
        }

        public long Size
        {
            get { return PrepareRecord.InMemorySize; }
        }

        public PrepareLogRecord PrepareRecord
        {
            get { return _prepareRecord; }
        }
    }
}


text:
require File.dirname(__FILE__) + '/spec_helper'
load_file 'mingle_connector'

include MingleConnector
describe Platform do
  before do
    @os_name = ENV_JAVA['os.name']
  end

  it "should return the correct file location for windows" do
    ENV_JAVA['os.name'] = "Windows"
    file_path = File.expand_path(File.dirname(__FILE__) + '/../mingle_connector.pid')
    Platform.new.pid_file_path.should == file_path
  end

  it "it should return the correct file location for Mac" do
    ENV_JAVA['os.name'] = "Mac OS X"
    file_path = "/tmp/mingle_connector.pid"
    Platform.new.pid_file_path.should == file_path
  end

  it "it should return the correct file location for Linux" do
    ENV_JAVA['os.name'] = "Linux"
    file_path = "/tmp/mingle_connector.pid"
    Platform.new.pid_file_path.should == file_path
  end

  after do
    ENV_JAVA['os.name'] = @os_name
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Measurement Tool MapStore2</title>
<meta name="author" content="GeoSolutions & Chef Studio" />
<link rel="shortcut icon" href="favicon.ico">
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>

<link href="../../theme/default/css/css.css" rel="stylesheet">
<link href="../../theme/default/css/custom.css" rel="stylesheet">
<link href="../../theme/default/css/font.css" rel="stylesheet">
<link href="../../theme/default/css/map.css" rel="stylesheet">

<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">

    <button type="button" class="close-sidebar btn-default" data-dismiss="modal">

</button>

            <button type="button" class="btn btn-lg btn-primary square-button">

    		</button>

            <button type="button" class="btn btn-lg btn-primary square-button">

    		</button>

            <button type="button" class="btn btn-lg btn-primary square-button">

    		</button>

MEASUREMENT TOOL

<button data-toggle="modal" data-target="#print">MEASURE DISTANCE</button>

<button data-toggle="modal" data-target="#print">MEASURE PATH</button>

<button data-toggle="modal" data-target="#print">MEASURE AREA</button>

<button data-toggle="modal" data-target="#print">BEARING</button>


text:
<?php

/**
* Classe EngineException
* @author Guillaume Marques <guillaume.marques33@gmail.com>
* @author Kevin Barreau <kevin.barreau.info@gmail.com>
*
* LR 25/01/2013
*/

class EngineException extends ErrorException
{

	function __construct($message, $id = 0, $code = 0, $fichier = 0, $ligne = 0)
	{
		parent::__construct($message, $id, $code, $fichier, $ligne);
	}

	public function __toString()
	{
		$html = '
';
		$html .= 'Oooops! An error has occurred!
 Please, reload the page or send a mail at  '.MAILPOSTMASTER;
		$html .= ' containing the following message:

';

		$html .= '
[SEVE] '.$this->severity;
		$html .= '
[MESS] '.$this->message;
		$html .= '
[LOCA] '.$this->file.'  line '.$this->line.'

';

		$html .= 'A developer will step in as soon as possible. Thanks! :)';
		$html .='
';

		return $html;
	}
}

function error2exception($code, $message, $fichier, $ligne)
{
	throw new EngineException($message, 0, $code, $fichier, $ligne);
}

set_error_handler('error2exception');


text:
% Note that the text in the [] brackets is the one that will
% appear in the table of contents, whilst the text in the {}
% brackets will appear in the main thesis.

%% CHAPTER HEADER /////////////////////////////////////////////////////////////////////////////////////
\chapter[Section 5]{Section 5}
\label{ch5}

%% CHAPTER INTRODUCTION ///////////////////////////////////////////////////////////////////////////////

\lipsum[1]

%% INCLUDE SECTIONS ///////////////////////////////////////////////////////////////////////////////////

\input{Chapters/Chapter5/sect51}
\input{Chapters/Chapter5/sect52}
\input{Chapters/Chapter5/sect53}


text:
package org.apache.felix.ipojo.runtime.core.api.components;

import org.osgi.framework.ServiceReference;

public class HostImpl {

    public void arrival(ServiceReference ref) {

    }

    public void departure(ServiceReference ref) {

    }

    public void modification(ServiceReference ref) {

    }

}


text:
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>
      {% if page.title %}
        {{ page.title }}
      {% else %}
        Default Page Title
      {% endif %}
    </title>

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="{{'/css/bootstrap.min.css' | prepend: site.baseurl }}" type="text/css">

    <!-- Custom Fonts -->
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="{{'/font-awesome/css/font-awesome.min.css' | prepend: site.baseurl }}" type="text/css">

    <!-- Plugin CSS -->
    <link rel="stylesheet" href="{{'/css/animate.min.css' | prepend: site.baseurl }}" type="text/css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="{{'/css/creative.css' | prepend: site.baseurl }}" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body id="page-top">
    {% include nav.html %}

    {{ content }}

       <!-- jQuery -->
    <script src="{{'/js/jquery.js' | prepend: site.baseurl }}"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="{{'/js/bootstrap.min.js' | prepend: site.baseurl }}"></script>

    <!-- Plugin JavaScript -->
    <script src="{{'/js/jquery.easing.min.js' | prepend: site.baseurl }}"></script>
    <script src="{{'/js/jquery.fittext.js' | prepend: site.baseurl }}"></script>
    <script src="{{'/js/wow.min.js' | prepend: site.baseurl }}"></script>

    <!-- Custom Theme JavaScript -->
    <script src="{{'/js/creative.js' | prepend: site.baseurl }}"></script>

</body>

</html>


text:
package org.zstack.test.securitygroup;

import org.junit.BeforeClass;
import org.junit.Test;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.network.securitygroup.SecurityGroupInventory;
import org.zstack.network.securitygroup.SecurityGroupRuleTO;
import org.zstack.simulator.SimulatorSecurityGroupBackend;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import java.util.concurrent.TimeUnit;

/**
 *
 * @author frank
 *
 * @condition
 * 1. create two security groups: sg1, sg2
 * 2. create vm1
 * 3. add vm1 to sg1, sg2
 * 4. remove sg2
 *
 * @test
 * confirm rules of sg1 are still on vm1
 */
public class TestSecurityGroupRuleInTwoGroup4 {
    static CLogger logger = Utils.getLogger(TestSecurityGroupRuleInTwoGroup4.class);
    static Deployer deployer;
    static Api api;
    static ComponentLoader loader;
    static DatabaseFacade dbf;
    static SimulatorSecurityGroupBackend sbkd;

    @BeforeClass
    public static void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/securityGroup/TestApplySeurityGroupRulesInTwoGroup.xml", con);
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        dbf = loader.getComponent(DatabaseFacade.class);
        sbkd = loader.getComponent(SimulatorSecurityGroupBackend.class);
    }

    @Test
    public void test() throws ApiSenderException, InterruptedException {
        SecurityGroupInventory scinv = deployer.securityGroups.get("test");
        VmInstanceInventory vm1 = deployer.vms.get("TestVm");
        VmNicInventory vm1Nic = vm1.getVmNics().get(0);

        api.addVmNicToSecurityGroup(scinv.getUuid(), vm1Nic.getUuid());

        SecurityGroupInventory scinv2 = deployer.securityGroups.get("test1");

        api.addVmNicToSecurityGroup(scinv2.getUuid(), vm1Nic.getUuid());

        TimeUnit.MILLISECONDS.sleep(500);

        api.deleteSecurityGroup(scinv2.getUuid());
        TimeUnit.MILLISECONDS.sleep(500);
        SecurityGroupRuleTO tovm1 = sbkd.getRulesOnHost(vm1.getHostUuid(), vm1Nic.getInternalName());
        SecurityGroupTestValidator.validate(tovm1, scinv.getRules());
    }
}


text:
package com.linecorp.centraldogma.common;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Ascii;

/**
 * The type of a {@link Change}.
 */
public enum ChangeType {
    /**
     * Adds a new JSON file or replaces an existing file. {@link Change#content()} will return
     * the {@link JsonNode} that represents the content of the file.
     */
    UPSERT_JSON(JsonNode.class),

    /**
     * Adds a new text file or replaces an existing file. {@link Change#content()} will return
     * the {@link String} that represents the content of the file.
     */
    UPSERT_TEXT(String.class),

    /**
     * Removes an existing file. The {@link Change#content()} of this type is always {@code null}.
     */
    REMOVE(Void.class),

    /**
     * Renames an existing file. The {@link Change#content()} of this type is the new path of the renamed file.
     */
    RENAME(String.class),

    /**
     * Applies a JSON patch to a JSON file. The {@link Change#content()} of this type is a JSON patch object,
     * as defined in RFC 6902.
     */
    APPLY_JSON_PATCH(JsonNode.class),

    /**
     * Applies a textual patch to a text file. The {@link Change#content()} of this type is a
     * unified format string.
     */
    APPLY_TEXT_PATCH(String.class);

    private final Class<?> contentType;

    ChangeType(Class<?> contentType) {
        this.contentType = contentType;
    }

    /**
     * Returns the type of the content returned by {@link Change#content()}.
     */
    public Class<?> contentType() {
        return contentType;
    }

    /**
     * Returns a {@link ChangeType} from the specified {@code value} case-insensitively.
     */
    public static ChangeType parse(String value) {
        requireNonNull(value, "value");
        checkArgument(!value.isEmpty(), "the value for ChangeType should not be empty.");

        return valueOf(Ascii.toUpperCase(value));
    }
}


text:
using Scada.Admin.Project;
using Scada.Agent.Connector;
using Scada.Comm.Shell.Code;
using Scada.Server.Shell.Code;
using System;

namespace Scada.Admin.App.Code
{
    /// <summary>
    /// Represents a system instance ready to change.
    /// <para>Представляет экземпляр системы, готовый к изменениям.</para>
    /// </summary>
    internal class LiveInstance
    {
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public LiveInstance(Instance instance)
        {
            Instance = instance ?? throw new ArgumentNullException("instance");
            AgentClient = null;
            ServerEnvironment = null;
            CommEnvironment = null;
            IsReady = false;
        }

        /// <summary>
        /// Gets the system instance.
        /// </summary>
        public Instance Instance { get; private set; }

        /// <summary>
        /// Gets or sets the client of the Agent service.
        /// </summary>
        public IAgentClient AgentClient { get; set; }

        /// <summary>
        /// Gets or sets the Server environment.
        /// </summary>
        public ServerEnvironment ServerEnvironment { get; set; }

        /// <summary>
        /// Gets or sets the Communicator environment.
        /// </summary>
        public CommEnvironment CommEnvironment { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this object is ready to use.
        /// </summary>
        public bool IsReady { get; set; }
    }
}


text:
function AddressBookItem(input){
  this.name = input.name;
  this.email = input.email;
  this.github = input.github;
  this.phone = input.phone;
  this.uid = Date.now() + "-" + Math.random();
}


text:
Related Posts

<?php foreach(get_the_category() as $category){ $cat = $category->cat_ID; } query_posts('cat=' . $cat . '&orderby=rand&showposts=3'); ?>
<?php while (have_posts()) : the_post();
$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'large'); ?>

<?php if ( has_post_thumbnail() ) {  ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail('related-image'); ?>
<?php } ?>

<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?>

<?php the_news_excerpt('15','','','plain','no'); ?>

<?php endwhile; wp_reset_query(); ?>


text:
package de.mwg.web.domain;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;

/**
 * A Task.
 */
@Entity
@Table(name = "task")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Task implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description")
    private String description;

    @OneToOne
    @JoinColumn(unique = true)
    private Task nextTask;

    @JsonIgnore
    @ManyToOne
    private Scenario scenario;

    // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public Task name(String name) {
        this.name = name;
        return this;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public Task description(String description) {
        this.description = description;
        return this;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Task getNextTask() {
        return nextTask;
    }

    public Task nextTask(Task task) {
        this.nextTask = task;
        return this;
    }

    public void setNextTask(Task task) {
        this.nextTask = task;
    }

    public Scenario getScenario() {
        return scenario;
    }

    public Task scenario(Scenario scenario) {
        this.scenario = scenario;
        return this;
    }

    public void setScenario(Scenario scenario) {
        this.scenario = scenario;
    }
    // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Task task = (Task) o;
        if (task.getId() == null || getId() == null) {
            return false;
        }
        return Objects.equals(getId(), task.getId());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getId());
    }

    @Override
    public String toString() {
        return "Task{" +
            "id=" + getId() +
            ", name='" + getName() + "'" +
            ", description='" + getDescription() + "'" +
            "}";
    }
}


text:
<?php

$env = new Twig_Environment(new Twig_Loader_Array(array()));
$env->addTest(new Twig_SimpleTest('anonymous', function () {}));

return $env;


text:
Adds civilization names to leader names in brackets for civilization Battle Royal Mk. II at /r/civbattleroyal
Inspired by: https://www.reddit.com/r/civbattleroyale/comments/3lanpf/a_small_request_to_the_narrators_use_country/cv5c7if

HOW-TO USE:

Remember to have civBR_civ_leader.tsv present in the same folder.
Run from command line as:
python civ_battleroyal_leader_civ_adder.py TEXTFILE
where TEXTFILE is a plain text file with the script.

Your resulting textfile with civilizations in brackets after leadernames will be written to a file called TEXTFILE_with_civs

KNOW BUGS:
In the rare case where a sentence is builded such that two different leader names matches, no civ is return. For example:
'(...) Lincoln. I (...)'
Will be parsed as: ['Lincoln','I'], which matches Lincoln, but also 'Osei Tutu I' (because of the 'I'), Alexios I Komnenos and others, all equally well.
Thus no civ will be the 'best' civ, eventhough a human would know it should be Lincoln. I have not yet coded such a logic into my script.


text:
using System;
using HealthMonitoring.Model;

namespace HealthMonitoring.Monitors.Core.Exchange.Client
{
    public class ChangedEndpoints
    {
        public DateTimeOffset CheckTime { get; set; }
        public EndpointIdentity[] NewEndpoints { get; set; }
        public EndpointIdentity[] DeletedEndpoints { get; set; }
    }
}


text:
package lore

/*
ModelInterface provides a generic interface for enabling external models to interface with internal
machinery here.
*/
type ModelInterface interface {
	/*
		DbTableName provides the name of the corresponding table in the database for this model.
	*/
	DbTableName() string
	/*
		DbFieldMap builds a map for this model instance from field/column name to this instance's
		current value for that field/column. Note that this should NOT include auto-managed db
		fields, such as SERIAL/AUTO-INCREMENTING KEYS, unless you want to try to specifically
		override these each time (typically not the case).

		This is used to provide Insert and Update functionality convenience by providing all of the
		columns and values to write into the table row.
	*/
	DbFieldMap() map[string]interface{}
	/*
		DbPrimaryFieldKey returns a string indicating the column name of the primary field of the
		model. This is used for Update and Delete queries for the WHERE condition.

		If the implementing model does not have such a field, an empty string can be returned, which
		will result in an error being thrown if any methods are called that require a non-empty
		field (such as an UPDATE that should have a non-empty WHERE condition for updating by
		primary key). If multiple columns define the primary field, you will have to implement the
		condition yourself instead.
	*/
	DbPrimaryFieldKey() string
	/*
		DbPrimaryFieldValue returns the current value of the primary field of the model. This is
		used for Update and Delete queries for the WHERE condition in conjunction with
		DbPrimaryFieldKey.

		If the implementing model does not have such a primary field, nil can be returned. Note that
		an error will be thrown if the DbPrimaryFieldKey method returns an empty string (see
		DbPrimaryFieldKey), but an error is not necessarily thrown if DbPrimaryFieldKey is
		non-empty and DbPrimaryFieldValue is nil (i.e., nil is a valid value to set for a primary
		field value if you really want).
	*/
	DbPrimaryFieldValue() interface{}
}


text:
var HttpError = require('../errors/http');

var OaeshUtil = require('../util');
var RestAPI = require('oae-rest');

module.exports = {
    'description': 'Logout of the current session.',
    'help': 'Usage: logout',
    'invoke': function(session, args, callback) {
        var restCtx = session.env('current').ctx;
        RestAPI.Authentication.logout(restCtx, function(err) {
            if (err) {
                throw new HttpError(err.code, err.msg);
            }

            OaeshUtil.switchUser(session, restCtx, function(err) {
                if (err) {
                    throw new HttpError(err.code, err.msg);
                }

                return callback();
            });
        });
    }
};


text:
package org.apache.gora.examples.generated;

import java.nio.ByteBuffer;
import java.util.Map;
import java.util.HashMap;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Protocol;
import org.apache.avro.util.Utf8;
import org.apache.avro.ipc.AvroRemoteException;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.FixedSize;
import org.apache.avro.specific.SpecificExceptionBase;
import org.apache.avro.specific.SpecificRecordBase;
import org.apache.avro.specific.SpecificRecord;
import org.apache.avro.specific.SpecificFixed;
import org.apache.gora.persistency.StateManager;
import org.apache.gora.persistency.impl.PersistentBase;
import org.apache.gora.persistency.impl.StateManagerImpl;
import org.apache.gora.persistency.StatefulHashMap;
import org.apache.gora.persistency.ListGenericArray;

@SuppressWarnings("all")
public class WebPage extends PersistentBase {
  public static final Schema _SCHEMA = Schema.parse("{\"type\":\"record\",\"name\":\"WebPage\",\"namespace\":\"org.apache.gora.examples.generated\",\"fields\":[{\"name\":\"url\",\"type\":\"string\"},{\"name\":\"content\",\"type\":[\"null\",\"bytes\"]},{\"name\":\"parsedContent\",\"type\":{\"type\":\"array\",\"items\":\"string\"}},{\"name\":\"outlinks\",\"type\":{\"type\":\"map\",\"values\":\"string\"}},{\"name\":\"metadata\",\"type\":{\"type\":\"record\",\"name\":\"Metadata\",\"fields\":[{\"name\":\"version\",\"type\":\"int\"},{\"name\":\"data\",\"type\":{\"type\":\"map\",\"values\":\"string\"}}]}}]}");
  public static enum Field {
    URL(0,"url"),
    CONTENT(1,"content"),
    PARSED_CONTENT(2,"parsedContent"),
    OUTLINKS(3,"outlinks"),
    METADATA(4,"metadata"),
    ;
    private int index;
    private String name;
    Field(int index, String name) {this.index=index;this.name=name;}
    public int getIndex() {return index;}
    public String getName() {return name;}
    public String toString() {return name;}
  };
  public static final String[] _ALL_FIELDS = {"url","content","parsedContent","outlinks","metadata",};
  static {
    PersistentBase.registerFields(WebPage.class, _ALL_FIELDS);
  }
  private Utf8 url;
  private ByteBuffer content;
  private GenericArray<Utf8> parsedContent;
  private Map<Utf8,Utf8> outlinks;
  private Metadata metadata;
  public WebPage() {
    this(new StateManagerImpl());
  }
  public WebPage(StateManager stateManager) {
    super(stateManager);
    parsedContent = new ListGenericArray<Utf8>(getSchema().getField("parsedContent").schema());
    outlinks = new StatefulHashMap<Utf8,Utf8>();
  }
  public WebPage newInstance(StateManager stateManager) {
    return new WebPage(stateManager);
  }
  public Schema getSchema() { return _SCHEMA; }
  public Object get(int _field) {
    switch (_field) {
    case 0: return url;
    case 1: return content;
    case 2: return parsedContent;
    case 3: return outlinks;
    case 4: return metadata;
    default: throw new AvroRuntimeException("Bad index");
    }
  }
  @SuppressWarnings(value="unchecked")
  public void put(int _field, Object _value) {
    if(isFieldEqual(_field, _value)) return;
    getStateManager().setDirty(this, _field);
    switch (_field) {
    case 0:url = (Utf8)_value; break;
    case 1:content = (ByteBuffer)_value; break;
    case 2:parsedContent = (GenericArray<Utf8>)_value; break;
    case 3:outlinks = (Map<Utf8,Utf8>)_value; break;
    case 4:metadata = (Metadata)_value; break;
    default: throw new AvroRuntimeException("Bad index");
    }
  }
  public Utf8 getUrl() {
    return (Utf8) get(0);
  }
  public void setUrl(Utf8 value) {
    put(0, value);
  }
  public ByteBuffer getContent() {
    return (ByteBuffer) get(1);
  }
  public void setContent(ByteBuffer value) {
    put(1, value);
  }
  public GenericArray<Utf8> getParsedContent() {
    return (GenericArray<Utf8>) get(2);
  }
  public void addToParsedContent(Utf8 element) {
    getStateManager().setDirty(this, 2);
    parsedContent.add(element);
  }
  public Map<Utf8, Utf8> getOutlinks() {
    return (Map<Utf8, Utf8>) get(3);
  }
  public Utf8 getFromOutlinks(Utf8 key) {
    if (outlinks == null) { return null; }
    return outlinks.get(key);
  }
  public void putToOutlinks(Utf8 key, Utf8 value) {
    getStateManager().setDirty(this, 3);
    outlinks.put(key, value);
  }
  public Utf8 removeFromOutlinks(Utf8 key) {
    if (outlinks == null) { return null; }
    getStateManager().setDirty(this, 3);
    return outlinks.remove(key);
  }
  public Metadata getMetadata() {
    return (Metadata) get(4);
  }
  public void setMetadata(Metadata value) {
    put(4, value);
  }
}


text:
This pages contains answers regarding questions about the styles published through this project. For questions regarding the citations and bibliography tool in general, check the [developer FAQ](FAQ).

* [Why is a new style not showing up in Word when I add it to the Style directory?](#Q1)
* [In Word 2008, new styles are only added for citations. How can I use the new styles for bibliographies?](#Q2)
* [Why does it take Word so long to show the dropdown list with style names the first time?](#Q3)
* [Why do I get 'BO' instead of a number when using certain styles?](#Q4)
* [Why do certain styles have a * at the end of their name?](#Q5)
* [Can I request to get a certain style?](#Q6)
* [Can I (not) link my in-text citations to their bibliography entries?](#Q7)
* [Can I change the surrounding brackets for in-text citations?](#Q8)
* [How do I get my in-text citations in superscript?](#Q9)
* [How do I convert all my in-text citations to static text in one go?](#Q10)
* [Is there an easy way to get rid of sources which are not cited in the text?](#Q11)
* [How do I set the indentation of my bibliography?](#Q12)
* [Is it possible to group several citations? Currently I have something like (1)(2) and I want (1,2).](#Q13)
* [Only the name of the first author is displayed correctly, all other author names are abbreviated. Is this a bug?](#Q14)
* [When using a numbered style (e.g. IEEE), the number is wrapped over multiple lines. Is this a bug?](#Q15)
* [My in-text citations are displayed in bold. How do I change this?](#Q16)

_**Q:**_ Why is a new style not showing up in Word when I add it to the Style directory?

_**A:** The list of available reference styles gets loaded only once. So when you add a new style to the style directory, you need to restart Word._

_**Q:**_ In Word 2008, new styles are only added for citations. How can I use the new styles for bibliographies?

_**A:** Add the bibliography using one of the four predefined styles. Then go to the citation toolbox and select the style you want. This will update all the citations and bibliographies in your text to the new style._

_**Q:**_ Why does it take Word so long to show the dropdown list with style names the first time?

_**A:** Word has to retrieve the style names of every XSL in the style directory the first time. Hence, the more styles you put in the directory, the more time Word needs to fill the drop down list._

_**Q:**_ Why do I get 'BO' instead of a number when using certain styles?

_**A:** 'BO' is often printed when the BibOrder number is not available. Use the [BibWord Extender](BibWord-Extender) tool on the document to add the missing numbers._

_**Q:**_ Why do certain styles have a **{"**"}** at the end of their name?

_**A:** Although the usage of a **{"**"}** is not mandatory, it often indicates that part of the functionality of the style can only be used in combination with the [BibWord Extender](BibWord-Extender) tool._

_**Q:**_ Can I request to get a certain style?

_**A:** **No.** Using [BibWord](BibWord), you really should try to create the style yourself. Keep in mind that even if you find someone prepared to create the style for you that you will have to provide him/her with detailed information about the formatting guidelines for your style. Messages containing "I need style x." will most likely be ignored._

_**Q:**_ Can I (not) link my in-text citations to their bibliography entries?

_**A:** Yes. Set the value of **{"citation_as_link"}** to 'yes' if you want in-text citations to link to their specific bibliography entry, or to any other value if you do not._

_**Q:**_ Can I change the surrounding brackets for in-text citations?

_**A:** Yes. You can change the surrounding brackets by changing the values of **{"openbracket"}** and **{"closebracket"}**_
```xml
<openbracket>(</openbracket>
<closebracket>)</closebracket>
```

_**Q:**_ How do I get my in-text citations in superscript?

_**A:** In-text citations inherit the style of their surroundings. Only limited formatting (bold, underline, italic) can be applied to them through the reference style. For any further formatting, such as superscript, a character style has to be applied to all CITATION fields._

_The following macro creates a character style called **In-Text Citation** if it does not yet exist. When the style is newly created, it sets the font to superscript. Then the style is applied to all CITATION fields in the document. By changing/updating the style **In-Text Citation** you can then update the formatting of all citations_

```vbscript
Sub ApplyCitationStyle()
    Dim stylename As String
    Dim exists As Boolean
    Dim s As Style
    Dim fld As Field

    stylename = "In-Text Citation"

    ' Check if the style already exists.
    exists = False

    For Each s In ActiveDocument.Styles
        If s.NameLocal = stylename Then
           exists = True
           Exit For
        End If
    Next

    ' If the style did not exist yet, create it.
    If exists = False Then
        Set s = ActiveDocument.Styles.Add(stylename, wdStyleTypeCharacter)
        s.BaseStyle = ActiveDocument.Styles(wdStyleDefaultParagraphFont).BaseStyle
        s.Font.Superscript = True
    End If

    ' Now that the style really exists, select it.
    Set s = ActiveDocument.Styles(stylename)

    ' Apply the style to all in-text citations.
    For Each fld In ActiveDocument.Fields
        If fld.Type = wdFieldCitation Then
            fld.Select
            Selection.Style = s
        End If
    Next

End Sub
```

_**Q:**_ How do I convert all my in-text citations to static text in one go?

_**A:** You can use the following macro to convert all in-text citations:_

```vbscript
Sub CitationsToStaticText()
    Dim fld As Field

    ' Go over all stories, including main, footnotes, ...
    For Each sr In ActiveDocument.StoryRanges
        ' Find all citation fields and convert them to static text.
        For Each fld In sr.Fields
            If fld.Type = wdFieldCitation Then
                fld.Select
                WordBasic.BibliographyCitationToText
            End If
        Next
    Next

End Sub
```

_**Q:**_ Is there an easy way to get rid of sources which are not cited in the text?

_**A:** You can use the following macro to remove all uncited sources from a document:_

```vbscript
Sub RemoveUnusedCitations()
    ' Get the number of sources.
    idx = ActiveDocument.Bibliography.Sources.Count

    ' Remmove unused sources starting from the last one.
    Do While (idx > 0)
        If ActiveDocument.Bibliography.Sources(idx).Cited = False Then
            ActiveDocument.Bibliography.Sources(idx).Delete
        End If
        idx = idx - 1
    Loop
End Sub
```

_**Q:**_ How do I set the indentation of my bibliography?

_**A:** Add a bibliography to your document. Open the 'Styles' pane {"(CTRL+ALT+SHIFT+S)"} and look for a style called 'Bibliography' (or a localized translation of the word 'Bibliography'). Change the indentation settings there. That way, whenever your bibliography gets updated, the indentation will remain correct._

_**Q:**_ Is it possible to group several citations? Currently I have something like (1)(2) and I want (1,2).

_**A:** Yes. You can add a second source to a citation by using the '\m' switch and the tag of the source you want to add. In Word 2007, if you want to add a source with tag 'Bee99' to an existing citation, right click the citation and select 'Edit Field...'. It will show you something like 'CITATION Gup97 \l 2060'. To add the extra source, change it to 'CITATION Gup97 \l 2060 \m Bee99'. For more information, also see the Microsoft Office online help topic on the [CITATION](http://office.microsoft.com/en-us/word/HA102157071033.aspx) field code._

_Alternatively, you can put your cursor inside any in-text citation, then go to 'References' tab in the ribbon and click 'Insert Citation'._

_To change the separator between two grouped in-text citations, BibWord uses the **separator** element._

_**Q:**_ Only the name of the first author is displayed correctly, all other author names are abbreviated. Is this a bug?

_**A:** No. You probably made a mistake when entering the different author names. You should enter them one by one in the dialog that comes up when clicking the "Edit..." button next to the author field. That way you will not make a mistake._

_If you really want to enter them as a string, then be aware that the correct format is "Last1, First1 Middle1; Last2, First2 Middle2; ...". So the names are separated by a ";" while name parts are separated by a ","._

_Note that there is a bug in Word where sometimes the name conversion goes wrong. For more info, see [release:here](27834)._

_**Q:**_ When using a numbered style (e.g. IEEE), the number is wrapped over multiple lines. Is this a bug?

_**A:** No. Numbered styles are mostly represented using a 2 column table where the first column contains the number and the second column contains the text. The text wrap you see is caused by the first column not being wide enough. You can simple solve this by positioning your cursor on the the table border between the first and second column and drag it to the right._

_This can also be used to add extra white space after the number if you set the halign element to left of the first column._

_**Q:**_ My in-text citations are displayed in bold. How do I change this?

_**A:** If you link your in-text citation to your bibliography, Word formats the link using the 'Heading 2 Character style'. So if that style is configured to use bold, so will the in-text citation. Assuming you cannot or do not want to change that style, there are two possible solutions:_
* _Disable linking between in-text citations and bibliographies. This can be done easily be setting the value of **citation_as_link** to 'no' in the xsl file._
* _Format each in-text citation with another character style. This way you will be able to keep using the links between in-text citations and bibliographies. To ease this job, you could use the following macro which you can run every time you insert an in-text citation or once at the end._
```vbscript
Sub ApplyCitationStyle()
    Dim stylename As String
    Dim exists As Boolean
    Dim s As Style
    Dim fld As Field

    stylename = "In-Text Citation"

    ' Check if the style already exists.
    exists = False

    For Each s In ActiveDocument.Styles
        If s.NameLocal = stylename Then
           exists = True
           Exit For
        End If
    Next

    ' If the style did not exist yet, create it.
    If exists = False Then
        Set s = ActiveDocument.Styles.Add(stylename, wdStyleTypeCharacter)
        s.BaseStyle = ActiveDocument.Styles(wdStyleDefaultParagraphFont).BaseStyle
        s.Font.Bold = False
    End If

    ' Now that the style really exists, select it.
    Set s = ActiveDocument.Styles(stylename)

    ' Apply the style to all in-text citations.
    For Each fld In ActiveDocument.Fields
        If fld.Type = wdFieldCitation Then
            fld.Select
            Selection.Style = s
        End If
    Next

End Sub
```


text:
import re
import datetime
import flask
import pymysql.cursors

from donut import constants

username_regex = re.compile(r'^[a-z][a-z0-9_-]*$', re.I)
name_regex = re.compile(r"^[a-z][a-z '-]{0,30}[a-z]$", re.I)
uid_regex = re.compile(r'^[0-9]{7}$')
year_regex = re.compile(r'^[0-9]{4}$')
email_regex = re.compile(r'^[a-z0-9\.\_\%\+\-]+@[a-z0-9\.\-]+\.[a-z]+$', re.I)

def validate_username(username, flash_errors=True):
    """
  Checks to make sure username is valid. If flash_errors is True, then the
  errors will be displayed as flashes. Returns True if valid, else False.
  """
    error = None
    if len(username) == 0:
        error = 'You must provide a username!'
    elif len(username) < constants.MIN_USERNAME_LENGTH:
        error = 'Username must be at least {0} characters long!'.format(
            constants.MIN_USERNAME_LENGTH)
    elif len(username) > constants.MAX_USERNAME_LENGTH:
        error = 'Username cannot be more than {0} characters long!'.format(
            constants.MAX_USERNAME_LENGTH)
    elif username_regex.match(username) is None:
        error = 'Username may contain only alphanumeric characters, hyphens, or underscores and must begin with a letter.'
    else:
        # Check if username is already in use.
        query = "SELECT 1 FROM users WHERE username = %s"
        with flask.g.pymysql_db.cursor() as cursor:
            cursor.execute(query, username)
            result = cursor.fetchone()
        if result is not None:
            error = 'Username is already in use!'

    if error is not None:
        if flash_errors:
            flask.flash(error)
        return False
    return True

def validate_password(password, password2, flash_errors=True):
    """
  Checks to make sure a password is valid. password and password2 should be the
  values from both times the user enters a password. If you need to check a
  password outside of the context of a user setting/changing a password, then
  use the same value for both inputs. If flash_errors is set to True, then the
  errors will be displayed as flashes.
  Returns True if valid, else False.
  """
    error = None
    if len(password) == 0:
        error = 'You must provide a password!'
    elif len(password2) == 0:
        error = 'You must confirm your password!'
    elif password != password2:
        error = 'Passwords do not match. Please try again!'
    elif len(password) < constants.MIN_PASSWORD_LENGTH:
        error = 'Your password must be at least {0} characters long!'.format(
            constants.MIN_PASSWORD_LENGTH)
    elif len(password) > constants.MAX_PASSWORD_LENGTH:
        error = 'Your password cannot be more than {0} characters long!'.format(
            constants.MAX_PASSWORD_LENGTH)

    if error is not None:
        if flash_errors:
            flask.flash(error)
        return False
    return True

def validate_name(name, flash_errors=True):
    """Validates a name. Flashes errors if flash_errors is True."""
    # Allow letters, spaces, hyphens, and apostrophes.
    # First and last characters must be letters.
    if not name_regex.match(name):
        if flash_errors:
            flask.flash("'{0}' is not a valid name.".format(name))
        return False
    return True

def validate_uid(uid, flash_errors=True):
    """Validates a UID. Flashes errors if flash_errors is True."""
    if not uid_regex.match(uid):
        if flash_errors:
            flask.flash("'{0}' is not a valid UID.".format(uid))
        return False
    return True

def check_uid_exists(uid):
    """Returns True if the UID exists in the database."""
    if not validate_uid(uid, flash_errors=False):
        return False

    query = "SELECT 1 FROM members WHERE uid = %s"
    with flask.g.pymysql_db.cursor() as cursor:
        cursor.execute(query, uid)
        result = cursor.fetchone()
    return result is not None

def validate_year(year, flash_errors=True):
    """Validates a year. Flashes errors if flash_errors is True."""
    # Also check that the year is in the range supported by MySQL's year type.
    if year_regex.match(year) \
        and int(year) >= 1901 \
        and int(year) <= 2155:
        return True
    if flash_errors:
        flask.flash("'{0}' is not a valid year.".format(year))
    return False

def validate_email(email, flash_errors=True):
    """Validates an email. Flashes errrors if flash_errors is True."""
    if not email_regex.match(email):
        if flash_errors:
            flask.flash("'{0}' is not a valid email.".format(email))
        return False
    return True

def validate_date(date, flash_errors=True):
    """
  Validates date string. Format should be YYYY-MM-DD. Flashes errors if
  flash_errors is True.
  """
    try:
        datetime.datetime.strptime(date, '%Y-%m-%d')
    except ValueError:
        if flash_errors:
            flask.flash(
                'Invalid date provided. Make sure dates are in YYYY-MM-DD format.'
            )
        return False
    return True

def validate_exists(form, param, flash_errors=True):
    """
    Validates that the specified parameter exists in the POST data
    """
    if param not in form:
        if flash_errors:
            flask.flash("Missing form parameter: " + param)
        return False
    return True

def validate_in(value, values, flash_errors=True):
    """
    Validates that value is in the iterable values
    """
    if value not in values:
        if flash_errors:
            flask.flash("'" + value + "' not in " + str(values))
        return False
    return True

def validate_int(int_str, min=None, max=None, flash_errors=True):
    """
    Requires that the given string represent an integer
    and the integer lies between the bounds (inclusive) if provided
    """
    try:
        int_value = int(int_str)
    except ValueError:
        if flash_errors:
            flask.flash("Not an integer: '" + int_str + "'")
        return False

    if not ((min is None or min <= int_value) and
            (max is None or int_value <= max)):
        if flash_errors:
            flask.flash("Not between " + str(min) + " and " + str(max) + ": " +
                        int_str)
        return False

    return True

def validate_matches(value1, value2, flash_errors=True):
    """
    Validates that the two values match
    """
    matches = value1 == value2
    if not matches and flash_errors:
        flask.flash(repr(value1) + " and " + repr(value2) + " do not match")
    return matches


text:
(function(angular) {

'use strict';
function AmountPaidModalController($state){
	var ctrl = this;

	ctrl.save = function(){

	}

	ctrl.cancel = function(){
		ctrl.modalInstance.close();
	}
}

angular.module('amountPaidModalModule')
	.component('amountPaidModalComponent',{
		templateUrl: 'warehouse/confirmOrder-modal/confirmOrder-modal.template.html',
		controller:['$state', AmountPaidModalController],
		bindings:{
			modalInstance: '<',
			resolve: '<'
		}
	});

})(window.angular);


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/frameworks/base/core/java/android/text/Spannable.java
//

#ifndef _AndroidTextSpannable_H_
#define _AndroidTextSpannable_H_

#include "J2ObjC_header.h"
#include "android/text/Spanned.h"

@protocol JavaLangCharSequence;

/*!
 @brief This is the interface for text to which markup objects can be
 attached and detached.
 Not all Spannable classes have mutable text;
 see Editable for that.
 */
@protocol AndroidTextSpannable < AndroidTextSpanned, NSObject, JavaObject >

/*!
 @brief Attach the specified markup object to the range start…end
 of the text, or move the object to that range if it was already
 attached elsewhere.
 See Spanned for an explanation of
 what the flags mean.  The object can be one that has meaning only
 within your application, or it can be one that the text system will
 use to affect text display or behavior.  Some noteworthy ones are
 android.text.TextWatcher and android.text.SpanWatcher.
 */
- (void)setSpanWithId:(id)what
              withInt:(jint)start
              withInt:(jint)end
              withInt:(jint)flags;

/*!
 @brief Remove the specified object from the range of text to which it
 was attached, if any.
 It is OK to remove an object that was never
 attached in the first place.
 */
- (void)removeSpanWithId:(id)what;

@end

J2OBJC_EMPTY_STATIC_INIT(AndroidTextSpannable)

J2OBJC_TYPE_LITERAL_HEADER(AndroidTextSpannable)

/*!
 @brief Factory used by TextView to create new Spannables.
 You can subclass
 it to provide something other than SpannableString.
 */
@interface AndroidTextSpannable_Factory : NSObject

#pragma mark Public

- (instancetype)init;

/*!
 @brief Returns the standard Spannable Factory.
 */
+ (AndroidTextSpannable_Factory *)getInstance;

/*!
 @brief Returns a new SpannableString from the specified CharSequence.
 You can override this to provide a different kind of Spannable.
 */
- (id<AndroidTextSpannable>)newSpannableWithJavaLangCharSequence:(id<JavaLangCharSequence>)source OBJC_METHOD_FAMILY_NONE;

@end

J2OBJC_STATIC_INIT(AndroidTextSpannable_Factory)

FOUNDATION_EXPORT AndroidTextSpannable_Factory *AndroidTextSpannable_Factory_getInstance();

FOUNDATION_EXPORT void AndroidTextSpannable_Factory_init(AndroidTextSpannable_Factory *self);

FOUNDATION_EXPORT AndroidTextSpannable_Factory *new_AndroidTextSpannable_Factory_init() NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(AndroidTextSpannable_Factory)

#endif // _AndroidTextSpannable_H_


text:
/*
 *
 */
package org.ksoft.kf.megamenu.view.managedbean;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import jodd.bean.BeanUtil;

import org.ksoft.kf.megamenu.service.MenuBuilder;
import org.ksoft.kf.megamenu.service.impl.XmlMenuBuilder;
import org.ksoft.kf.megamenu.view.viewbean.MegaMenuViewBean;
import org.primefaces.model.menu.DefaultMenuColumn;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuElement;

/**
 *
 * @author hjosekarlo
 *
 */
@ManagedBean
@ViewScoped
public class MegaMenu implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 6825984805619239475L;

	/**
	 * @return the menu
	 * @throws Exception
	 */
	public final MegaMenuViewBean getMenu() throws Exception {
		MenuBuilder menuBuilder = new XmlMenuBuilder();

		return menuBuilder.build(null);
	}

	public DefaultMenuModel getMenuModel() {
		/*
		<p:column>
			<p:submenu label="TV.1" >
				<p:menuitem value="TV.1.1" url="#" />
				<p:menuitem value="TV.1.2" url="#" />
			</p:submenu>
			<p:submenu label="TV.2" >
				<p:menuitem value="TV.2.1" url="#" />
				<p:menuitem value="TV.2.2" url="#" />
				<p:menuitem value="TV.2.3" url="#" />
			</p:submenu>
			<p:submenu label="TV.3">
				<p:menuitem value="TV.3.1" url="#" />
				<p:menuitem value="TV.3.2" url="#" />
			</p:submenu>
		</p:column>

		<p:column>
			<p:submenu label="TV.4">
				<p:menuitem value="TV.4.1" url="#" />
				<p:menuitem value="TV.4.2" url="#" />
			</p:submenu>
			<p:submenu label="TV.5">
				<p:menuitem value="TV.5.1" url="#" />
				<p:menuitem value="TV.5.2" url="#" />
				<p:menuitem value="TV.5.3" url="#" />
			</p:submenu>
		</p:column>
		 */

		DefaultMenuModel model = new DefaultMenuModel();
		DefaultSubMenu subMenu1 = new DefaultSubMenu();
		subMenu1.setLabel("TV.1");

		DefaultMenuColumn firstColumn = new DefaultMenuColumn();
		DefaultMenuColumn secondColumn = new DefaultMenuColumn();
		subMenu1.addElement(firstColumn);
		subMenu1.addElement(secondColumn);

		DefaultSubMenu subMenu11 = new DefaultSubMenu();
		subMenu11.setLabel("TV.1.1");
		DefaultMenuItem menuItem111 = new DefaultMenuItem();
		menuItem111.setValue("TV.1.1.1");
		DefaultMenuItem menuItem112 = new DefaultMenuItem();
		menuItem112.setValue("TV.1.1.2");

		subMenu11.addElement(menuItem111);
		subMenu11.addElement(menuItem112);

		DefaultSubMenu subMenu12 = new DefaultSubMenu();
		subMenu12.setLabel("TV.1.2");

		DefaultMenuItem menuItem121 = new DefaultMenuItem();
		menuItem121.setValue("TV.1.2.1");
		DefaultMenuItem menuItem122 = new DefaultMenuItem();
		menuItem122.setValue("TV.1.2.2");

		subMenu12.addElement(menuItem121);
		subMenu12.addElement(menuItem122);

		firstColumn.addElement(subMenu11);
		firstColumn.addElement(subMenu12);

		//2nd Column
		DefaultSubMenu subMenu13 = new DefaultSubMenu();
		subMenu13.setLabel("TV.1.3");
		DefaultMenuItem menuItem131 = new DefaultMenuItem();
		menuItem131.setValue("TV.1.3.1");
		DefaultMenuItem menuItem132 = new DefaultMenuItem();
		menuItem132.setValue("TV.1.3.2");

		subMenu13.addElement(menuItem131);
		subMenu13.addElement(menuItem132);

		DefaultSubMenu subMenu14 = new DefaultSubMenu();
		subMenu14.setLabel("TV.1.4");

		DefaultMenuItem menuItem141 = new DefaultMenuItem();
		menuItem141.setValue("TV.1.4.1");
		DefaultMenuItem menuItem142 = new DefaultMenuItem();
		menuItem142.setValue("TV.1.4.2");

		subMenu14.addElement(menuItem141);
		subMenu14.addElement(menuItem142);

		secondColumn.addElement(subMenu13);
		secondColumn.addElement(subMenu14);

		model.addElement(subMenu1);

		/*
		DefaultMenuModel model = new DefaultMenuModel();

		DefaultMenuColumn firstColumn = new DefaultMenuColumn();
		DefaultSubMenu subMenu1 = new DefaultSubMenu();
		subMenu1.setLabel("TV.1");

		DefaultMenuItem dmi11 = new DefaultMenuItem();
		dmi11.setValue("TV.1.1");

		DefaultMenuItem dmi12 = new DefaultMenuItem();
		dmi12.setValue("TV.1.2");

		subMenu1.addElement(dmi11);
		subMenu1.addElement(dmi12);

		DefaultSubMenu subMenu2 = new DefaultSubMenu();
		subMenu2.setLabel("TV.2");

		DefaultMenuItem dmi21 = new DefaultMenuItem();
		dmi21.setValue("TV.2.1");

		DefaultMenuItem dmi22 = new DefaultMenuItem();
		dmi22.setValue("TV.2.2");

		DefaultMenuItem dmi23 = new DefaultMenuItem();
		dmi23.setValue("TV.2.3");

		subMenu2.addElement(dmi21);
		subMenu2.addElement(dmi22);
		subMenu2.addElement(dmi23);

		DefaultSubMenu subMenu3 = new DefaultSubMenu();
		subMenu3.setLabel("TV.3");

		DefaultMenuItem dmi31 = new DefaultMenuItem();
		dmi31.setValue("TV.3.1");

		DefaultMenuItem dmi32 = new DefaultMenuItem();
		dmi32.setValue("TV.3.2");

		subMenu3.addElement(dmi31);
		subMenu3.addElement(dmi32);

		firstColumn.addElement(subMenu1);
		firstColumn.addElement(subMenu2);
		firstColumn.addElement(subMenu3);

		//2nd column

		DefaultMenuColumn secondColumn = new DefaultMenuColumn();
		DefaultSubMenu subMenu4 = new DefaultSubMenu();
		subMenu4.setLabel("TV.4");

		DefaultMenuItem dmi41 = new DefaultMenuItem();
		dmi41.setValue("TV.4.1");

		DefaultMenuItem dmi42 = new DefaultMenuItem();
		dmi42.setValue("TV.4.2");

		subMenu4.addElement(dmi41);
		subMenu4.addElement(dmi42);

		DefaultSubMenu subMenu5 = new DefaultSubMenu();
		subMenu5.setLabel("TV.5");

		DefaultMenuItem dmi51 = new DefaultMenuItem();
		dmi51.setValue("TV.5.1");

		DefaultMenuItem dmi52 = new DefaultMenuItem();
		dmi52.setValue("TV.5.2");

		DefaultMenuItem dmi53 = new DefaultMenuItem();
		dmi53.setValue("TV.5.3");

		subMenu5.addElement(dmi51);
		subMenu5.addElement(dmi52);
		subMenu5.addElement(dmi53);

		secondColumn.addElement(subMenu4);
		secondColumn.addElement(subMenu5);

		model.addElement(firstColumn);
		//model.addElement(secondColumn);

		 */

		//((DefaultMenuItem)((DefaultSubMenu)model.getElements().get(0)).getElements().get(0)).getValue();
		System.out.println(model.getClass());
		List<MenuElement> list = model.getElements();
		for (MenuElement me : list) {
			System.out.println("\t" + me.getClass());
			List<MenuElement> s = ((DefaultSubMenu)me).getElements();
			for (MenuElement me1 : s) {
				System.out.println("\t\t" + me1.getClass());
				//DefaultMenuColumn
				List<MenuElement> t = ((DefaultMenuColumn)me1).getElements();
				for (MenuElement me2 : t) {
					System.out.println("\t\t\t" + me2.getClass());
					//DefaultSubMenu
					List<MenuElement> u = ((DefaultSubMenu)me2).getElements();
					for (MenuElement me3 : u) {
						System.out.println("\t\t\t\t" + me3.getClass());
						/*
						((DefaultMenuItem)me3).setAjax(true);
						((DefaultMenuItem)me3).setAsync(false);
						((DefaultMenuItem)me3).setCommand("");;
						((DefaultMenuItem)me3).setContainerStyle("");
						((DefaultMenuItem)me3).setContainerStyleClass("");
						((DefaultMenuItem)me3).setDelay("");
						((DefaultMenuItem)me3).setDisableClientWindow(false);
						((DefaultMenuItem)me3).setDisabled(false);
						((DefaultMenuItem)me3).setFragment("");
						((DefaultMenuItem)me3).setGlobal(false);
						((DefaultMenuItem)me3).setHref("");
						((DefaultMenuItem)me3).setIcon("");
						((DefaultMenuItem)me3).setIconPos("");
						((DefaultMenuItem)me3).setId("");
						((DefaultMenuItem)me3).setIgnoreAutoUpdate(false);
						((DefaultMenuItem)me3).setImmediate(false);
						((DefaultMenuItem)me3).setIncludeViewParams(false);

						((DefaultMenuItem)me3).setOutcome("");
						((DefaultMenuItem)me3).setPartialSubmit(false);
						((DefaultMenuItem)me3).setParams(null);
						((DefaultMenuItem)me3).setParam(null, "");
						((DefaultMenuItem)me3).setProcess("");
						((DefaultMenuItem)me3).setRendered(false);
						((DefaultMenuItem)me3).setResetValues(false);
						((DefaultMenuItem)me3).setStyle("");
						((DefaultMenuItem)me3).setStyleClass("");
						((DefaultMenuItem)me3).setTarget("");
						((DefaultMenuItem)me3).setTitle("");
						((DefaultMenuItem)me3).setUpdate("");
						((DefaultMenuItem)me3).setUrl("");
						((DefaultMenuItem)me3).setValue("");
						*/
					}
				}
			}
		}
		      //DefaultSubMenu       DefaultMenuColumn    DefaultSubMenu       DefaultMenuItem
		//model.getElements().get(0).getElements().get(0).getElements().get(0).getElements().get(0)
		//DefaultMenuModel defaultMenuModel = new DefaultMenuModel();
		//BeanUtil.setDeclaredPropertyForced(defaultMenuModel, "elements[0].elements[0].elements[0].elements[0].value", "Characteristics - Income");
		return model;
	}

	public DefaultMenuModel getOther(){
		DefaultMenuModel model = new DefaultMenuModel();

		DefaultSubMenu voidSubmenu = new DefaultSubMenu("Void Submenu");

		//First submenu
		DefaultSubMenu firstSubmenu = new DefaultSubMenu("Dynamic Submenu");

		DefaultMenuColumn column = new DefaultMenuColumn();

		DefaultMenuItem item = new DefaultMenuItem("External");
		item.setUrl("http://www.primefaces.org");
		item.setIcon("ui-icon-home");
		firstSubmenu.addElement(item);

		column.addElement(firstSubmenu);

		//Second submenu
		DefaultSubMenu secondSubmenu = new DefaultSubMenu("Dynamic Actions");

		item = new DefaultMenuItem("Save");
		item.setIcon("ui-icon-disk");
		item.setCommand("#{mantClienteMB.save}");
		item.setUpdate("messages");
		secondSubmenu.addElement(item);

		item = new DefaultMenuItem("Delete");
		item.setIcon("ui-icon-close");
		item.setCommand("#{menuBean.delete}");
		item.setAjax(false);
		secondSubmenu.addElement(item);

		item = new DefaultMenuItem("Redirect");
		item.setIcon("ui-icon-search");
		secondSubmenu.addElement(item);

		column.addElement(secondSubmenu);

		voidSubmenu.addElement(column);

		model.addElement(voidSubmenu);

		return model;
	}

}


text:
using AggregateSource.EventStore.Framework;

[assembly: EventStoreIntegration]