text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.redisenterprise.generated;

import com.azure.core.util.Context;

/** Samples for Databases Delete. */
public final class DatabasesDeleteSamples {
    /*
     * x-ms-original-file: specification/redisenterprise/resource-manager/Microsoft.Cache/stable/2022-01-01/examples/RedisEnterpriseDatabasesDelete.json
     */
    /**
     * Sample code: RedisEnterpriseDatabasesDelete.
     *
     * @param manager Entry point to RedisEnterpriseManager.
     */
    public static void redisEnterpriseDatabasesDelete(
        com.azure.resourcemanager.redisenterprise.RedisEnterpriseManager manager) {
        manager.databases().delete("rg1", "cache1", "db1", Context.NONE);
    }
}


text:
s ()    # Starts or restores named screens
{
    if [ -n "$1" ]; then
        VIRTUALENV=$1
        if [[ -n $(screen -ls|egrep "^\s+[1-9]+\.$VIRTUALENV") ]]; then
            screen -x $VIRTUALENV
        else
            shift   # Drops $1 from args
            screen -S $VIRTUALENV -t $VIRTUALENV -U ${@}
        fi
    else
        screen ${@}
    fi
}

virtualenvwrapper='virtualenvwrapper_lazy.sh'
if (( $+commands[$virtualenvwrapper] )); then
  source ${${virtualenvwrapper}:c}

    # If inside a screen, and the screen name matches a virtualenv, switch to it
    if [ -n "$STY" ]; then
        SESSION_NAME=$(echo $STY | cut -f 2 -d ".")
        # FIXME: This breaks if virtualenvwrapper isn't loaded yet
        if [ $(workon | grep "^${SESSION_NAME}$") ]; then
            workon $SESSION_NAME
        fi
    fi
else
  print "zsh virtualenvwrapper plugin: Cannot find ${virtualenvwrapper}. Please install with \`pip install virtualenvwrapper\`."
fi

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 169: 370 (1995)

#### Original name
Setomyces genipae Bat. & Peres

### Remarks
null


text:
IDS
---------------------

.. automodule:: google.cloud.ids_v1.services.ids
    :members:
    :inherited-members:

.. automodule:: google.cloud.ids_v1.services.ids.pagers
    :members:
    :inherited-members:


text:
#import "AAPLMasterViewController.h"

#if DEBUG
// Alpha should only be compiled and used in debug builds.
#import "ALPHAManager.h"
#endif

@implementation AAPLMasterViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

#if DEBUG
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Alpha" style:UIBarButtonItemStylePlain target:self action:@selector(alphaButtonTapped:)];
#endif
}

- (void)alphaButtonTapped:(id)sender
{
#if DEBUG
    [[ALPHAManager defaultManager] setHidden:NO];
#endif
}

// When a segue from the AAPLMasterViewController's table view is triggered, we want to ensure that the current detail view controller's
// "More" bar button item is correctly transferred to the destination detail view controller's navigation item. We are only concerned about
// this change when the application is in portrait mode since this is the only time that the "More" bar button item will be visible.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    //if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
    if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait) {
        UINavigationController *newDetailViewController = [segue destinationViewController];
        UINavigationController *oldDetailViewController = [self.splitViewController.viewControllers lastObject];

        // In order for a segue to occur when the view controller is in portrait, the "More" bar button item must be visible.
        // However, the "More" bar button item is only visible if the detail view controller's root view controller is
        // visible (otherwise there would be a "Back" bar button item). We can then query the old detail view controller's top view
        // controller for the current "More" bar button item.
        UIBarButtonItem *currentDetailBarButtonItem = oldDetailViewController.topViewController.navigationItem.leftBarButtonItem;

        // The new detail view controller's root view controller will be the top view controller when it's initially
        // pushed onto the detail navigation controller.
        newDetailViewController.topViewController.navigationItem.leftBarButtonItem = currentDetailBarButtonItem;
    }
}

@end


text:
OrderEditShippingAddressHandler = Class.create();
OrderEditShippingAddressHandler.prototype = Object.extend(new CommonHandler(), {

    // ---------------------------------------

    initialize: function(countryElementId, regionContainerElementId, regionElementName)
    {
        this.countryElementId = countryElementId;
        this.regionContainerElementId = regionContainerElementId;
        this.regionElementName = regionElementName;
    },

    // ---------------------------------------

    countryCodeChange: function()
    {
        var self = OrderEditShippingAddressHandlerObj;

        new Ajax.Request(M2ePro.url.get('adminhtml_order/getCountryRegions'), {
            method: 'get',
            asynchronous: true,
            parameters: {
                country: $(self.countryElementId).value
            },
            onSuccess: function(transport) {
                self.renderRegions(transport.responseText.evalJSON(true));
            }
        });
    },

    renderRegions: function(data)
    {
        var self = OrderEditShippingAddressHandlerObj,
            regionContainer = $(self.regionContainerElementId),
            html = '';

        if (data.length == 0) {
            html = '<input type="text" name="%name%" class="input-text" value="%value%" />'
                .replace(/%name%/, self.regionElementName)
                .replace(/%value%/, M2ePro.formData.region);
        } else {
            html += '<select name="'+self.regionElementName+'">';
            data.each(function(item) {
                var selected = (item.value == M2ePro.formData.region) ? 'selected="selected"' : '';
                html += '<option value="'+item.value+'" '+selected+'>'+item.label+'</option>';
            });
            html += '</select>';
        }

        regionContainer.innerHTML = html;
    }

    // ---------------------------------------
});


text:
Forge ChangeLog
===============

## 1.3.0 - 2022-03-17

### Security
- Three RSA PKCS#1 v1.5 signature verification issues were reported by Moosa
  Yahyazadeh (moosa-yahyazadeh@uiowa.edu).
- **HIGH**: Leniency in checking `digestAlgorithm` structure can lead to
  signature forgery.
  - The code is lenient in checking the digest algorithm structure. This can
    allow a crafted structure that steals padding bytes and uses unchecked
    portion of the PKCS#1 encoded message to forge a signature when a low
    public exponent is being used. For more information, please see
    ["Bleichenbacher's RSA signature forgery based on implementation
    error"](https://mailarchive.ietf.org/arch/msg/openpgp/5rnE9ZRN1AokBVj3VqblGlP63QE/)
    by Hal Finney.
  - CVE ID: [CVE-2022-24771](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-24771)
  - GHSA ID: [GHSA-cfm4-qjh2-4765](https://github.com/digitalbazaar/forge/security/advisories/GHSA-cfm4-qjh2-4765)
- **HIGH**: Failing to check tailing garbage bytes can lead to signature
  forgery.
  - The code does not check for tailing garbage bytes after decoding a
    `DigestInfo` ASN.1 structure. This can allow padding bytes to be removed
    and garbage data added to forge a signature when a low public exponent is
    being used.  For more information, please see ["Bleichenbacher's RSA
    signature forgery based on implementation
    error"](https://mailarchive.ietf.org/arch/msg/openpgp/5rnE9ZRN1AokBVj3VqblGlP63QE/)
    by Hal Finney.
  - CVE ID: [CVE-2022-24772](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-24772)
  - GHSA ID: [GHSA-x4jg-mjrx-434g](https://github.com/digitalbazaar/forge/security/advisories/GHSA-x4jg-mjrx-434g)
- **MEDIUM**: Leniency in checking type octet.
  - `DigestInfo` is not properly checked for proper ASN.1 structure. This can
    lead to successful verification with signatures that contain invalid
    structures but a valid digest.
  - CVE ID: [CVE-2022-24773](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-24773)
  - GHSA ID: [GHSA-2r2c-g63r-vccr](https://github.com/digitalbazaar/forge/security/advisories/GHSA-2r2c-g63r-vccr)

### Fixed
- [asn1] Add fallback to pretty print invalid UTF8 data.
- [asn1] `fromDer` is now more strict and will default to ensuring all input
  bytes are parsed or throw an error. A new option `parseAllBytes` can disable
  this behavior.
  - **NOTE**: The previous behavior is being changed since it can lead to
    security issues with crafted inputs. It is possible that code doing custom
    DER parsing may need to adapt to this new behavior and optional flag.
- [rsa] Add and use a validator to check for proper structure of parsed ASN.1
  `RSASSA-PKCS-v1_5` `DigestInfo` data. Additionally check that the hash
  algorithm identifier is a known value from RFC 8017
  `PKCS1-v1-5DigestAlgorithms`. An invalid `DigestInfo` or algorithm identifier
  will now throw an error.
  - **NOTE**: The previous lenient behavior is being changed to be more strict
    since it could lead to security issues with crafted inputs. It is possible
    that code may have to handle the errors from these stricter checks.

### Added
- [oid] Added missing RFC 8017 PKCS1-v1-5DigestAlgorithms algorithm
  identifiers:
  - `1.2.840.113549.2.2` / `md2`
  - `2.16.840.1.101.3.4.2.4` / `sha224`
  - `2.16.840.1.101.3.4.2.5` / `sha512-224`
  - `2.16.840.1.101.3.4.2.6` / `sha512-256`

## 1.2.1 - 2022-01-11

### Fixed
- [tests]: Load entire module to improve top-level testing and coverage
  reporting.
- [log]: Refactor logging setup to avoid use of `URLSearchParams`.

## 1.2.0 - 2022-01-07

### Fixed
- [x509] 'Expected' and 'Actual' issuers were backwards in verification failure
  message.

### Added
- [oid,x509]: Added OID `1.3.14.3.2.29 / sha1WithRSASignature` for sha1 with
  RSA. Considered a deprecated equivalent to `1.2.840.113549.1.1.5 /
  sha1WithRSAEncryption`. See [discussion and
  links](https://github.com/digitalbazaar/forge/issues/825).

### Changed
- [x509]: Reduce duplicate code. Add helper function to create a signature
  digest given an signature algorithm OID. Add helper function to verify
  signatures.

## 1.1.0 - 2022-01-06

### Fixed
- [x509]: Correctly compute certificate issuer and subject hashes to match
  behavior of openssl.
- [pem]: Accept certificate requests with "NEW" in the label. "BEGIN NEW
  CERTIFICATE REQUEST" handled as "BEGIN CERTIFICATE REQUEST".

## 1.0.0 - 2022-01-04

### Notes
- **1.0.0**!
- This project is over a decade old! Time for a 1.0.0 release.
- The URL related changes may expose bugs in some of the networking related
  code (unrelated to the much wider used cryptography code). The automated and
  manual test coverage for this code is weak at best. Issues or patches to
  update the code or tests would be appreciated.

### Removed
- **SECURITY**, **BREAKING**: Remove `forge.debug` API. The API has the
  potential for prototype pollution. This API was only briefly used by the
  maintainers for internal project debug purposes and was never intended to be
  used with untrusted user inputs. This API was not documented or advertised
  and is being removed rather than fixed.
- **SECURITY**, **BREAKING**: Remove `forge.util.parseUrl()` (and
  `forge.http.parseUrl` alias) and use the [WHATWG URL
  Standard](https://url.spec.whatwg.org/). `URL` is supported by modern browers
  and modern Node.js. This change is needed to address URL parsing security
  issues. If `forge.util.parseUrl()` is used directly or through `forge.xhr` or
  `forge.http` APIs, and support is needed for environments without `URL`
  support, then a polyfill must be used.
- **BREAKING**: Remove `forge.task` API. This API was never used, documented,
  or advertised by the maintainers. If anyone was using this API and wishes to
  continue development it in other project, please let the maintainers know.
  Due to use in the test suite, a modified version is located in
  `tests/support/`.
- **BREAKING**: Remove `forge.util.makeLink`, `forge.util.makeRequest`,
  `forge.util.parseFragment`, `forge.util.getQueryVariables`. Replace with
  `URL`, `URLSearchParams`, and custom code as needed.

### Changed
- **BREAKING**: Increase supported Node.js version to 6.13.0 for URL support.
- **BREAKING**: Renamed `master` branch to `main`.
- **BREAKING**: Release process updated to use tooling that prefixes versions
  with `v`. Other tools, scripts, or scanners may need to adapt.
- **BREAKING**: Remove docs related to Bower and
  [forge-dist](https://github.com/digitalbazaar/forge-dist). Install using
  [another method](./README.md#installation).

### Added
- OIDs for `surname`, `title`, and `givenName`.

### Fixed
- **BREAKING**: OID 2.5.4.5 name fixed from `serialName` to `serialNumber`.
  Depending on how applications used this id to name association it could cause
  compatibility issues.

## 0.10.0 - 2020-09-01

### Changed
- **BREAKING**: Node.js 4 no longer supported. The code *may* still work, and
  non-invasive patches to keep it working will be considered. However, more
  modern tools no longer support old Node.js versions making testing difficult.

### Removed
- **BREAKING**: Remove `util.getPath`, `util.setPath`, and `util.deletePath`.
  `util.setPath` had a potential prototype pollution security issue when used
  with unsafe inputs. These functions are not used by `forge` itself. They date
  from an early time when `forge` was targeted at providing general helper
  functions. The library direction changed to be more focused on cryptography.
  Many other excellent libraries are more suitable for general utilities. If
  you need a replacement for these functions, consider `get`, `set`, and `unset`
  from [lodash](https://lodash.com/). But also consider the potential similar
  security issues with those APIs.

## 0.9.2 - 2020-09-01

### Changed
- Added `util.setPath` security note to function docs and to README.

### Notes
- **SECURITY**: The `util.setPath` function has the potential to cause
  prototype pollution if used with unsafe input.
  - This function is **not** used internally by `forge`.
  - The rest of the library is unaffected by this issue.
  - **Do not** use unsafe input with this function.
  - Usage with known input should function as expected. (Including input
    intentionally using potentially problematic keys.)
  - No code changes will be made to address this issue in 0.9.x. The current
    behavior *could* be considered a feature rather than a security issue.
    0.10.0 will be released that removes `util.getPath` and `util.setPath`.
    Consider `get` and `set` from [lodash](https://lodash.com/) if you need
    replacements. But also consider the potential similar security issues with
    those APIs.
  - https://snyk.io/vuln/SNYK-JS-NODEFORGE-598677
  - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-7720

## 0.9.1 - 2019-09-26

### Fixed
- Ensure DES-CBC given IV is long enough for block size.

## 0.9.0 - 2019-09-04

### Added
- Add ed25519.publicKeyFromAsn1 and ed25519.privateKeyFromAsn1 APIs.
- A few OIDs used in EV certs.

### Fixed
- Improve ed25519 NativeBuffer check.

## 0.8.5 - 2019-06-18

### Fixed
- Remove use of `const`.

## 0.8.4 - 2019-05-22

### Changed
- Replace all instances of Node.js `new Buffer` with `Buffer.from` and `Buffer.alloc`.

## 0.8.3 - 2019-05-15

### Fixed
- Use basic character set for code.

## 0.8.2 - 2019-03-18

### Fixed
- Fix tag calculation when continuing an AES-GCM block.

### Changed
- Switch to eslint.

## 0.8.1 - 2019-02-23

### Fixed
- Fix off-by-1 bug with kem random generation.

## 0.8.0 - 2019-01-31

### Fixed
- Handle creation of certificates with `notBefore` and `notAfter` dates less
  than Jan 1, 1950 or greater than or equal to Jan 1, 2050.

### Added
- Add OID 2.5.4.13 "description".
- Add OID 2.16.840.1.113730.1.13 "nsComment".
  - Also handle extension when creating a certificate.
- `pki.verifyCertificateChain`:
  - Add `validityCheckDate` option to allow checking the certificate validity
    period against an arbitrary `Date` or `null` for no check at all. The
    current date is used by default.
- `tls.createConnection`:
  - Add `verifyOptions` option that passes through to
    `pki.verifyCertificateChain`. Can be used for the above `validityCheckDate`
    option.

### Changed
- Support WebCrypto API in web workers.
- `rsa.generateKeyPair`:
  - Use `crypto.generateKeyPair`/`crypto.generateKeyPairSync` on Node.js if
    available (10.12.0+) and not in pure JS mode.
  - Use JS fallback in `rsa.generateKeyPair` if `prng` option specified since
    this isn't supported by current native APIs.
  - Only run key generation comparison tests if keys will be deterministic.
- PhantomJS is deprecated, now using Headless Chrome with Karma.
- **Note**: Using Headless Chrome vs PhantomJS may cause newer JS features to
  slip into releases without proper support for older runtimes and browsers.
  Please report such issues and they will be addressed.
- `pki.verifyCertificateChain`:
  - Signature changed to `(caStore, chain, options)`. Older `(caStore, chain,
    verify)` signature is still supported. New style is to to pass in a
    `verify` option.

## 0.7.6 - 2018-08-14

### Added
- Test on Node.js 10.x.
- Support for PKCS#7 detached signatures.

### Changed
- Improve webpack/browser detection.

## 0.7.5 - 2018-03-30

### Fixed
- Remove use of `const`.

## 0.7.4 - 2018-03-07

### Fixed
- Potential regex denial of service in form.js.

### Added
- Support for ED25519.
- Support for baseN/base58.

## 0.7.3 - 2018-03-05

- Re-publish with npm 5.6.0 due to file timestamp issues.

## 0.7.2 - 2018-02-27

### Added
- Support verification of SHA-384 certificates.
- `1.2.840.10040.4.3'`/`dsa-with-sha1` OID.

### Fixed
- Support importing PKCS#7 data with no certificates. RFC 2315 sec 9.1 states
  certificates are optional.
- `asn1.equals` loop bug.
- Fortuna implementation bugs.

## 0.7.1 - 2017-03-27

### Fixed

- Fix digestLength for hashes based on SHA-512.

## 0.7.0 - 2017-02-07

### Fixed

- Fix test looping bugs so all tests are run.
- Improved ASN.1 parsing. Many failure cases eliminated. More sanity checks.
  Better behavior in default mode of parsing BIT STRINGs. Better handling of
  parsed BIT STRINGs in `toDer()`. More tests.
- Improve X.509 BIT STRING handling by using new capture modes.

### Changed

- Major refactor to use CommonJS plus a browser build system.
- Updated tests, examples, docs.
- Updated dependencies.
- Updated flash build system.
- Improve OID mapping code.
- Change test servers from Python to JavaScript.
- Improve PhantomJS support.
- Move Bower/bundle support to
  [forge-dist](https://github.com/digitalbazaar/forge-dist).
- **BREAKING**: Require minimal digest algorithm dependencies from individual
  modules.
- Enforce currently supported bit param values for byte buffer access. May be
  **BREAKING** for code that depended on unspecified and/or incorrect behavior.
- Improve `asn1.prettyPrint()` BIT STRING display.

### Added

- webpack bundler support via `npm run build`:
  - Builds `.js`, `.min.js`, and basic sourcemaps.
  - Basic build: `forge.js`.
  - Build with extra utils and networking support: `forge.all.js`.
  - Build WebWorker support: `prime.worker.js`.
- Browserify support in package.json.
- Karma browser testing.
- `forge.options` field.
- `forge.options.usePureJavaScript` flag.
- `forge.util.isNodejs` flag (used to select "native" APIs).
- Run PhantomJS tests in Travis-CI.
- Add "Donations" section to README.
- Add IRC to "Contact" section of README.
- Add "Security Considerations" section to README.
- Add pbkdf2 usePureJavaScript test.
- Add rsa.generateKeyPair async and usePureJavaScript tests.
- Add .editorconfig support.
- Add `md.all.js` which includes all digest algorithms.
- Add asn1 `equals()` and `copy()`.
- Add asn1 `validate()` capture options for BIT STRING contents and value.

### Removed

- **BREAKING**: Can no longer call `forge({...})` to create new instances.
- Remove a large amount of old cruft.

### Migration from 0.6.x to 0.7.x

- (all) If you used the feature to create a new forge instance with new
  configuration options you will need to rework your code. That ability has
  been removed due to implementation complexity. The main rare use was to set
  the option to use pure JavaScript. That is now available as a library global
  flag `forge.options.usePureJavaScript`.
- (npm,bower) If you used the default main file there is little to nothing to
  change.
- (npm) If you accessed a sub-resource like `forge/js/pki` you should either
  switch to just using the main `forge` and access `forge.pki` or update to
  `forge/lib/pki`.
- (bower) If you used a sub-resource like `forge/js/pki` you should switch to
  just using `forge` and access `forge.pki`. The bower release bundles
  everything in one minified file.
- (bower) A configured workerScript like
  `/bower_components/forge/js/prime.worker.js` will need to change to
  `/bower_components/forge/dist/prime.worker.min.js`.
- (all) If you used the networking support or flash socket support, you will
  need to use a custom build and/or adjust where files are loaded from. This
  functionality is not included in the bower distribution by default and is
  also now in a different directory.
- (all) The library should now directly support building custom bundles with
  webpack, browserify, or similar.
- (all) If building a custom bundle ensure the correct dependencies are
  included. In particular, note there is now a `md.all.js` file to include all
  digest algorithms. Individual files limit what they include by default to
  allow smaller custom builds. For instance, `pbdkf2.js` has a `sha1` default
  but does not include any algorithm files by default. This allows the
  possibility to include only `sha256` without the overhead of `sha1` and
  `sha512`.

### Notes

- This major update requires updating the version to 0.7.x. The existing
  work-in-progress "0.7.x" branch will be painfully rebased on top of this new
  0.7.x and moved forward to 0.8.x or later as needed.
- 0.7.x is a start of simplifying forge based on common issues and what has
  appeared to be the most common usage. Please file issues with feedback if the
  changes are problematic for your use cases.

## 0.6.x - 2016 and earlier

- See Git commit log or https://github.com/digitalbazaar/forge.


text:
<Alloy>
	<Window class="container">
		<ImageView width="350" height="250" top="150" image="/img/quest.jpg"></ImageView>

	</Window>
</Alloy>


text:
<?php

namespace Carrooi\NoGrid\DataSource;

use Carrooi\NoGrid\Condition;
use Carrooi\NoGrid\NoGrid;
use Carrooi\NoGrid\NotImplementedException;
use Nette\Utils\Strings;

/**
 *
 * @author David Kudera <kudera.d@gmail.com>
 */
class ArrayDataSource implements IDataSource
{

	/** @var array */
	private $dataDefinition;

	/** @var array */
	private $data;

	/**
	 * @param array $data
	 */
	public function __construct(array $data)
	{
		$this->dataDefinition = $data;
	}

	/**
	 * @param \Carrooi\NoGrid\NoGrid $grid
	 */
	public function configure(NoGrid $grid)
	{
	}

	/**
	 * @return int
	 */
	public function getCount()
	{
		$this->fetchData();
		return count($this->data);
	}

	/**
	 * @return array
	 */
	public function &getData()
	{
		return $this->dataDefinition;
	}

	/**
	 * @return array
	 */
	public function fetchData()
	{
		if ($this->data === null) {
			$this->data = $this->dataDefinition;
		}

		return $this->data;
	}

	/**
	 * @param \Carrooi\NoGrid\Condition[] $conditions
	 */
	public function filter(array $conditions)
	{
		foreach ($conditions as $condition) {
			$this->data = array_filter($this->fetchData(), function($row) use ($condition) {
				if (!isset($row[$condition->getColumn()])) {
					return false;
				}

				return $this->compare($condition->getType(), $row[$condition->getColumn()], $condition->getValue(), $condition->getOptions());
			});
		}
	}

	/**
	 * @param int $offset
	 * @param int $limit
	 */
	public function limit($offset, $limit)
	{
		$this->data = array_slice($this->fetchData(), $offset, $limit);
	}

	/**
	 * @param int $type
	 * @param mixed $actual
	 * @param mixed $expected
	 * @param array $options
	 * @return bool
	 */
	private function compare($type, $actual, $expected = null, array $options = [])
	{
		if (isset($options[Condition::CASE_INSENSITIVE]) && $options[Condition::CASE_INSENSITIVE]) {
			$actual = Strings::lower($actual);
			$expected = Strings::lower($expected);
		}

		if ($type === Condition::SAME) {
			return $actual === $expected;

		} elseif ($type === Condition::NOT_SAME) {
			return $actual !== $expected;

		} elseif ($type === Condition::IS_NULL) {
			return $actual === null;

		} elseif ($type === Condition::IS_NOT_NULL) {
			return $actual !== null;

		} elseif ($type === Condition::LIKE) {
			$actual = Strings::toAscii($actual);
			$expected = Strings::toAscii($expected);

			$pattern = str_replace('%', '(.|\s)*', preg_quote($expected, '/'));
			return (bool) preg_match("/^{$pattern}$/i", $actual);

		} else {
			throw new NotImplementedException('Filtering condition is not implemented.');
		}
	}

}


text:
/*!
* \file kgl_render_pass.h
* \date 2017/12/31 13:57
*
* \author www.xionggf.com
* Contact: sun_of_lover@sina.com
*
* \brief 封装了render pass的基本属性和操作,可以作为具体的render pass的基类以作继承
*
* TODO: 一个render pass含有一个camera,一个gpu program
*       提供了若干常用的uniform变量传递接口:
*       world matrix, view matrix, projection matrix
* \note
*/

#ifndef kgl_render_pass_h__
#define kgl_render_pass_h__

#include "kgl_camera.h"
#include "kgl_gpu_program.h"

namespace kgl
{
    class RenderPass
    {
    public:
        /// <summary>
        /// 构造函数,创建一个 <see cref="RenderPass"/> 类的对象实例时被调用.
        /// </summary>
        RenderPass();

        /// <summary>
        /// 析构函数,删除一个<see cref="RenderPass"/>类的对象实例时被调用.
        /// </summary>
        virtual ~RenderPass();

        /// <summary>
        /// 向本render pass绑定一个主摄像机
        /// </summary>
        /// <param name="camera">The camera.</param>
        void AttachCamera(CameraSPtr camera);

        /// <summary>
        /// 给本render pass绑定一个主shadow
        /// </summary>
        /// <param name="program"></param>
        void AttachGPUProgram(GPUProgramSPtr program);

        /// <summary>
        /// Creates the and attach gpu program.
        /// </summary>
        /// <param name="vs_file">The vs_file.</param>
        /// <param name="fs_file">The fs_file.</param>
        /// <param name="gs_file">The gs_file.</param>
        void CreateAndAttachGPUProgram(const GLchar* vs_file, const GLchar* fs_file, const GLchar* gs_file = nullptr);

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        virtual void Initialize();

        /// <summary>
        /// Sets the world matrix.
        /// </summary>
        /// <param name="world_matrix">The world_matrix.</param>
        /// <param name="need_transpose">The need_transpose.</param>
        virtual void SetWorldMatrix(const glm::mat4& world_matrix, bool need_transpose = false);

        /// <summary>
        /// Sets the view matrix.
        /// </summary>
        /// <param name="view_matrix">The view_matrix.</param>
        /// <param name="need_transpose">The need_transpose.</param>
        virtual void SetViewMatrix(const glm::mat4& view_matrix, bool need_transpose = false);

        /// <summary>
        /// Sets the projection matrix.
        /// </summary>
        /// <param name="projection_matrix">The projection_matrix.</param>
        /// <param name="need_transpose">The need_transpose.</param>
        virtual void SetProjectionMatrix(const glm::mat4& projection_matrix, bool need_transpose = false);

        /// <summary>
        /// Sets the camera world position.
        /// </summary>
        /// <param name="world_position">The world_position.</param>
        virtual void SetCameraWorldPosition(const glm::vec3& world_position);

        /// <summary>
        /// Updates the specified current_time.
        /// </summary>
        /// <param name="current_time">The current_time.</param>
        virtual void Update(float current_time);

        virtual void PrepareRendering();
    protected:
        /// <summary>
        /// Gets the world matrix location.
        /// </summary>
        /// <param name="uniform_name">The uniform_name.</param>
        void GetWorldMatrixLocation(const char* uniform_name);

        /// <summary>
        /// Gets the view matrix location.
        /// </summary>
        /// <param name="uniform_name">The uniform_name.</param>
        void GetViewMatrixLocation(const char* uniform_name);

        /// <summary>
        /// Gets the projection matrix location.
        /// </summary>
        /// <param name="uniform_name">The uniform_name.</param>
        void GetProjectionMatrixLocation(const char* uniform_name);

        /// <summary>
        /// Gets the camera world position location.
        /// </summary>
        /// <param name="uniform_name">The uniform_name.</param>
        void GetCameraWorldPositionLocation(const char* uniform_name);
    protected:
        /// <summary>
        /// 执行本render pass要使用到的camera
        /// </summary>
        CameraSPtr camera_;

        /// <summary>
        /// 执行本render pass要使用到的gpu program
        /// </summary>
        GPUProgramSPtr gpu_program_;

        /// <summary>
        /// The location_world_matrix_
        /// </summary>
        GLint location_world_matrix_ = -1;

        /// <summary>
        /// The location_project_matrix
        /// </summary>
        GLint location_projection_matrix_ = -1;

        /// <summary>
        /// The location_view_matrix
        /// </summary>
        GLint location_view_matrix_ = -1;

        GLint location_camera_world_position_ = -1;
    };

    typedef std::shared_ptr<RenderPass> RenderPassSPtr;
}

#endif // kgl_render_pass_h__


text:
//Translated from zone_filler.rb using babyruby2js
'use strict';

var CONST = require('../../../constants');

var GRID_BORDER = CONST.GRID_BORDER;
var BORDER = CONST.BORDER;

/** @class public read-only attribute: grid
 *  if a grid is given, it is used as starting point;
 *  otherwise, the goban scoring_grid is used.
 */
function ZoneFiller(goban, grid) {
    if (!grid) {
        grid = goban.scoringGrid.initFromGoban(goban);
    }
    this.goban = goban;
    this.grid = grid;
    this.yx = grid.yx;
    this.groups = null;
}
module.exports = ZoneFiller;

// "Color" a goban zone.
// to_replace can be EMPTY or a zone code (but cannot be a real color like BLACK)
// neighbors, if given should be an array of n arrays, with n == number of colors
// if neighbors are not given, we do simple "coloring"
ZoneFiller.prototype.fillWithColor = function (startI, startJ, toReplace, color, neighbors) {
    if (this.yx[startJ][startI] !== toReplace) return 0;
    var vcount = 0;
    this.toReplace = toReplace;
    this.groups = neighbors;
    var gap, gaps = [[startI, startJ, startJ]];

    while ((gap = gaps.pop())) {
        var i = gap[0], j0 = gap[1], j1 = gap[2];

        if (this.yx[j0][i] !== toReplace) continue; // gap already done by another path

        while (this._check(i, j0 - 1)) j0--;
        while (this._check(i, j1 + 1)) j1++;

        vcount += j1 - j0 + 1;
        for (var ix = i - 1; ix <= i + 1; ix += 2) {
            var curgap = null;
            for (var j = j0; j <= j1; j++) {
                if (ix < i) this.yx[j][i] = color;
                if (this._check(ix, j)) {
                    if (!curgap) {
                        curgap = j; // gap start
                    }
                } else if (curgap) {
                    gaps.push([ix, curgap, j - 1]);
                    curgap = null;
                }
            } // for j
            if (curgap) gaps.push([ix, curgap, j1]); // last gap
        } // for ix
    } // while gap
    return vcount;
};

//private

// Returns true if the replacement is needed (=> i,j has a color equal to the replaced one)
ZoneFiller.prototype._check = function (i, j) {
    var color = this.yx[j][i];
    if (color === GRID_BORDER || color === BORDER) return false;
    if (color === this.toReplace) return true;

    if (this.groups && color < 2) {
        var group = this.goban.stoneAt(i, j).group;
        if (group && this.groups[color].indexOf(group) < 0) {
            this.groups[color].push(group);
        }
    }
    return false;
};


text:
#ifndef TEST_CONVENIENCES_H
#define TEST_CONVENIENCES_H

#include <bson/bson.h>

#include "mongoc/mongoc.h"
#include "mongoc/mongoc-read-prefs-private.h"
#include "mongoc/mongoc-client-private.h"

/* TODO: split this header up.
 * Move bson_lookup_* functions under bsonutil.
 * Move temporary helpers into a separate header.
 */

/* Initialize global test convenience structures.
 * Safe to call repeatedly, or after calling test_conveniences_cleanup().
 */
void
test_conveniences_init ();

/* Tear down global test conveniences.
 * Safe to call repeatedly.
 * Called automatically at process exit.
 */
void
test_conveniences_cleanup (void);

/* Return a bson_t representation from a single-quoted JSON string, with
 * possible printf format directives.
 * bson_t is freed automatically at test cleanup.
 * E.g. tmp_bson ("{'key': %d}", 123); */
bson_t *
tmp_bson (const char *json, ...);

/* Return a string, with possible printf format directives. String is
 * automatically freed at test cleanup. */
const char *
tmp_str (const char *fmt, ...);

/* Return a JSON string representation of BSON. String is freed automatically at
 * test cleanup. */
const char *
tmp_json (const bson_t *bson);

void
bson_iter_bson (const bson_iter_t *iter, bson_t *bson);

/* create a bson_t containing all types of values, and an empty key. The
 * returned bson_t does not need to be freed. This corresponds to the same
 * document in json_with_all_types. */
bson_t *
bson_with_all_types ();

/* returns a json string with all types of values, and an empty key. This
 * corresponds to the same document in bson_with_all_types. */
const char *
json_with_all_types ();

#ifndef PATH_MAX
#define PATH_MAX 1024
#endif

#ifdef _WIN32
#define realpath(path, expanded) \
   GetFullPathName (path, PATH_MAX, expanded, NULL)
#endif

const char *
bson_lookup_utf8 (const bson_t *b, const char *key);

void
value_init_from_doc (bson_value_t *value, const bson_t *doc);

void
bson_lookup_value (const bson_t *b, const char *key, bson_value_t *value);

bson_t *
bson_lookup_bson (const bson_t *b, const char *key);

void
bson_lookup_doc (const bson_t *b, const char *key, bson_t *doc);

void
bson_lookup_doc_null_ok (const bson_t *b, const char *key, bson_t *doc);

bool
bson_lookup_bool (const bson_t *b, const char *key);

int32_t
bson_lookup_int32 (const bson_t *b, const char *key);

int64_t
bson_lookup_int64 (const bson_t *b, const char *key);

mongoc_read_concern_t *
bson_lookup_read_concern (const bson_t *b, const char *key);

mongoc_write_concern_t *
bson_lookup_write_concern (const bson_t *b, const char *key);

mongoc_read_prefs_t *
bson_lookup_read_prefs (const bson_t *b, const char *key);

void
bson_lookup_database_opts (const bson_t *b,
                           const char *key,
                           mongoc_database_t *database);

void
bson_lookup_collection_opts (const bson_t *b,
                             const char *key,
                             mongoc_collection_t *collection);

mongoc_transaction_opt_t *
bson_lookup_txn_opts (const bson_t *b, const char *key);

mongoc_session_opt_t *
bson_lookup_session_opts (const bson_t *b, const char *key);

mongoc_client_session_t *
bson_lookup_session (const bson_t *b, const char *key, mongoc_client_t *client);

bool
bson_init_from_value (bson_t *b, const bson_value_t *v);

char *
single_quotes_to_double (const char *str);

/* match_action_t determines if default check for a field is overridden. */
typedef enum {
   MATCH_ACTION_SKIP,    /* do not use the default check. */
   MATCH_ACTION_ABORT,   /* an error occurred, stop checking. */
   MATCH_ACTION_CONTINUE /* use the default check. */
} match_action_t;

struct _match_ctx_t;
/* doc_iter may be null if the pattern field is not found. */
typedef match_action_t (*match_visitor_fn) (struct _match_ctx_t *ctx,
                                            bson_iter_t *pattern_iter,
                                            bson_iter_t *doc_iter);

typedef struct _match_ctx_t {
   char errmsg[1000];
   bool strict_numeric_types;
   /* if retain_dots_in_keys is true, then don't consider a path with dots to
    * indicate recursing into a sub document. */
   bool retain_dots_in_keys;
   /* if allow_placeholders is true, treats 42 and "42" as placeholders. I.e.
    * comparing 42 to anything is ok. */
   bool allow_placeholders;
   /* path is the dot separated breadcrumb trail of keys. */
   char path[1000];
   /* if visitor_fn is not NULL, this is called on for every key in the pattern.
    * The returned match_action_t can override the default match behavior. */
   match_visitor_fn visitor_fn;
   void *visitor_ctx;
   /* if is_command is true, then compare the first key case insensitively. */
   bool is_command;
} match_ctx_t;

void
assert_match_bson (const bson_t *doc, const bson_t *pattern, bool is_command);

bool
match_bson (const bson_t *doc, const bson_t *pattern, bool is_command);

int64_t
bson_value_as_int64 (const bson_value_t *value);

bool
match_bson_value (const bson_value_t *doc,
                  const bson_value_t *pattern,
                  match_ctx_t *ctx);

bool
match_bson_with_ctx (const bson_t *doc,
                     const bson_t *pattern,
                     match_ctx_t *ctx);

bool
match_json (const bson_t *doc,
            bool is_command,
            const char *filename,
            int lineno,
            const char *funcname,
            const char *json_pattern,
            ...);

#define ASSERT_MATCH(doc, ...)                                                 \
   do {                                                                        \
      BSON_ASSERT (                                                            \
         match_json (doc, false, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__)); \
   } while (0)

bool
mongoc_write_concern_append_bad (mongoc_write_concern_t *write_concern,
                                 bson_t *command);

#define FOUR_MB 1024 * 1024 * 4

const char *
huge_string (mongoc_client_t *client);

size_t
huge_string_length (mongoc_client_t *client);

const char *
four_mb_string ();

void
assert_no_duplicate_keys (const bson_t *doc);

void
match_in_array (const bson_t *doc, const bson_t *array, match_ctx_t *ctx);

void
match_err (match_ctx_t *ctx, const char *fmt, ...);

void
assert_wc_oob_error (bson_error_t *error);

typedef struct {
   int major;
   int minor;
   bool has_minor;
   int patch;
   bool has_patch;
} semver_t;

void
semver_parse (const char *str, semver_t *out);

void
server_semver (mongoc_client_t *client, semver_t *out);

int
semver_cmp (semver_t *a, semver_t *b);

int
semver_cmp_str (semver_t *a, const char *str);

const char *
semver_to_string (semver_t *str);

/* Iterate over a BSON document or array.
 *
 * Example of iterating and printing an array of BSON documents:
 *
 * bson_iter_t iter;
 * bson_t *arr = my_func();
 *
 * BSON_FOREACH (arr, iter) {
 *    bson_t el;
 *    bson_iter_bson (&iter, &el);
 *    printf ("%d: %s", bson_iter_key (&iter), tmp_json (&el));
 * }
 */
#define BSON_FOREACH(bson, iter_varname)          \
   for (bson_iter_init (&(iter_varname), (bson)); \
        bson_iter_next (&(iter_varname));)

#define TEST_ERROR_DOMAIN 123456
#define TEST_ERROR_CODE 654321
#define test_set_error(error, ...) \
   bson_set_error (error, TEST_ERROR_DOMAIN, TEST_ERROR_CODE, __VA_ARGS__)

#endif /* TEST_CONVENIENCES_H */


text:
describe('service : NPCService ', function () {
    var srv, $httpBackend;

    beforeEach(module('rpgNoteApp'));

    beforeEach(function () {
        // inject the mock for the http backend
        inject(function (_$httpBackend_) {
            $httpBackend = _$httpBackend_;
        });

        // inject the service to be tested
        inject(function (_NpcService_) {
            srv = _NpcService_;
        });
    });

    afterEach(function() {
         $httpBackend.verifyNoOutstandingExpectation();
         $httpBackend.verifyNoOutstandingRequest();
       });

    it('should exist', function () {
        expect( !! srv).toBe(true);
    });

    it('query() should return everyone', function () {

        // mock the response to a particular get request
        $httpBackend.whenGET('/api/npc').respond([{
            id: 1,
            note: 'toto',
            name: 'note1'
        }, {
            id: 2,
            note: 'tata',
            name: 'note2'
        }]);

        // send request to get everyone
        var data = srv.query();

        // flush the pending resuest
        $httpBackend.flush();
        expect(JSON.stringify(data)).toBe(JSON.stringify([{
             id: 1,
             note: 'toto',
             name: 'note1'
           }, {
            id: 2,
            note: 'tata',
            name: 'note2'
        }]));
    });

    it('get({id: 1}) should return object with id=1', function () {
        // mock the response to a particular get request
        $httpBackend.whenGET('/api/npc/1').respond({
            id: 1,
            note: 'toto',
            name:'npc'
        });
        var data = srv.get({
            id: 1
        });
        $httpBackend.flush();
        expect(JSON.stringify(data)).toBe(JSON.stringify({
            id: 1,
            note: 'toto',
            name: 'npc'
        }));
    });

    it ('post a new note', function () {
        $httpBackend.whenPOST('/api/npc', {note: 'note', name: 'npc', id:'1'}).respond(201, '');
        var data = srv.save();
        $httpBackend.flush();
        expect(data).not.toBe(null);
    });
});


text:
<?php

class XenAuction_CronEntry_Auction
{

	/**
	 * Expire auctions
	 *
	 * Scans for auctions that have exceeded their expiration date and expires them
	 *
	 * @todo: 	Account for situations where there would be a huge amount of auctions to expire
	 *
	 * @return void
	 */
	public static function runExpireAuctions()
	{
		// Set fetch conditions
		$fetchConditions = array(
			'status' 	=> XenAuction_Model_Auction::STATUS_ACTIVE,
			'expired'	=> true
		);

		// Retrieve auctions
		$auctionModel 	= XenForo_Model::create('XenAuction_Model_Auction');
		$auctions 		= $auctionModel->getAuctions($fetchConditions);

		// Loop through auctions and expire them individually (as special actions need to be performed)
		foreach ($auctions AS $auction)
		{
			self::runExpireAuction($auction);
		}
	}

	/**
	 * Expire a specific auction
	 *
	 * Sends "auction won" notification when applicable
	 *
	 * @param array   $auction
	 *
	 * @return void
	 */
	public static function runExpireAuction(array $auction)
	{

		// Prepare datawriter
		$dwAuction = XenForo_DataWriter::create('XenAuction_DataWriter_Auction');
		$dwAuction->setExistingData($auction);
		$dwAuction->bulkSet(array(
			'status'			=> XenAuction_Model_Auction::STATUS_EXPIRED,
			'expiration_date'	=> XenForo_Application::$time
		));

		// Check if this auction had a top bidder
		if ($auction['top_bidder'])
		{
			// Retrieve top bid data
			$auctionModel 	= XenForo_Model::create('XenAuction_Model_Auction');
			$bid 			= $auctionModel->getWinningBid($auction['auction_id']);

			if ($auction['availability'] === 0)
			{
				// Prepare auction data to be updated
				$dwAuction->set('top_bidder',	0); // Set top_bidder to 0 as a workaround

				// Parse notification title and message
				$title 		= new XenForo_Phrase('lost_auction_x', $auction);
				$message	= new XenForo_Phrase('lost_auction_message', $auction);

				// Send notification
				XenAuction_Helper_Notification::sendNotification($bid['bid_user_id'], $title, $message);

				// Update status of old winning bid
				$dwBid = XenForo_DataWriter::create('XenAuction_DataWriter_Bid');
				$dwBid->setExistingData($bid);
				$dwBid->set('bid_status', XenAuction_Model_Auction::BID_STATUS_OUTBID);
				$dwBid->save();
			}
			else
			{
				// Update sales amount for auction
				$dwAuction->set('sales',	$auction['sales'] + 1);

				// Set phrase params
				$args 			= array_merge($auction, $bid);

				// Get user configured payment address
				$fieldModel 			= XenForo_Model::create('XenForo_Model_UserField');
				$args['invoice_link']	= XenForo_Link::buildPublicLink('full:auctions/invoice', '', array('id' => $bid['bid_id']));
				$args['payment_address']= $fieldModel->getUserFieldValue('auctionPaymentAddress', $auction['user_id']);
				$args['payment_address']= str_replace('{bidid}', $bid['bid_id'], $args['payment_address']);
				$args['payment_address']= str_replace('{invoice_link}', $args['invoice_link'], $args['payment_address']);

				// Parse notification title and message
				$title 		= new XenForo_Phrase('won_auction_x', $auction);
				$message	= new XenForo_Phrase('won_auction_message', $args);

				// Send notification
				XenAuction_Helper_Notification::sendNotification($bid['bid_user_id'], $title, $message);

				// Set sale date of bid
				$dwBid = XenForo_DataWriter::create('XenAuction_DataWriter_Bid');
				$dwBid->setExistingData($bid);
				$dwBid->set('sale_date', XenForo_Application::$time);
				$dwBid->save();
			}

		}

		// Update auction (expire it)
		$dwAuction->save();

	}

}


text:
from twisted.trial import unittest

from twistedchecker.checkers.docstring import DocstringChecker

class DocstringTestCase(unittest.TestCase):
    """
    Test for twistedchecker.checkers.docstring
    """

    def test_getLineIndent(self):
        """
        Test of twistedchecker.checkers.docstring._getLineIndent.
        """
        checker = DocstringChecker()
        indentNoSpace = checker._getLineIndent("foo")
        indentTwoSpaces = checker._getLineIndent("  foo")
        indentFourSpaces = checker._getLineIndent("    foo")
        self.assertEqual(indentNoSpace, 0)
        self.assertEqual(indentTwoSpaces, 2)
        self.assertEqual(indentFourSpaces, 4)


text:
import React, { Component } from "react";
//	React native components
import {
	Button,
} from "react-native";

class ScreenOne extends Component {

	//	Validate proptypes
	static propTypes = {

		navigation: React.PropTypes.object,
	};

	//	Default constructor
	constructor (props) {

		super (props);
	}

	render () {

		return (

			<Button
				title="Zippy"
				onPress={() => this.props.navigation.navigate ("ScreenTwo")}
				label="Go to notifications"/>
		);
	}
}

export default ScreenOne;


text:
<?php

namespace Laminas\Form\Annotation;

/**
 * Name annotation
 *
 * Use this annotation to specify a name other than the property or class name
 * when building the form, element, or input. The value should be a string.
 *
 * @Annotation
 */
class Name extends AbstractStringAnnotation
{
    /**
     * Retrieve the name
     *
     * @return null|string
     */
    public function getName()
    {
        return $this->value;
    }
}


text:
{-# OPTIONS_GHC -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Control.Comonad.Zipper
-- Copyright   :  (C) 2008 Edward Kmett
-- License     :  BSD-style (see the file LICENSE)
--
-- Maintainer  :  Edward Kmett <ekmett@gmail.com>
-- Stability   :  experimental
-- Portability :  non-portable (MPTCs)
--
----------------------------------------------------------------------------
module Control.Comonad.Pointer where

import Control.Arrow ((&&&), first)
import Data.Array
import Data.Foldable
import Control.Monad
import Control.Comonad

{-

data Pointer i a = Pointer { index :: i, array :: Array i e } deriving (Show,Read)

instance Ix i => Functor (Pointer i) where
	fmap f (Pointer i a) = Pointer i (fmap f a)

instance Ix i => Comonad (Pointer i) where
	extract (Pointer i a) = a ! i
	extend f (Pointer i a) = Pointer i . listArray bds $ fmap (f . flip Pointer a) (range bds) where
		bds = bounds a

distPointer :: (Monad m, Ix i) => Dist m (Pointer i)
distPointer (Pointer i ma) = do
	let bds = bounds ma
	a <- sequence (elems ma)
	return $ Pointer i (listArray bds a)

-}


text:
package server

import (
	"go-common/app/service/main/resource/conf"
	"go-common/app/service/main/resource/model"
	"go-common/app/service/main/resource/service"
	"go-common/library/ecode"
	"go-common/library/net/rpc"
	"go-common/library/net/rpc/context"
)

// RPC struct
type RPC struct {
	s *service.Service
}

// New init rpc server.
func New(c *conf.Config, s *service.Service) (svr *rpc.Server) {
	r := &RPC{s: s}
	svr = rpc.NewServer(c.RPCServer)
	if err := svr.Register(r); err != nil {
		panic(err)
	}
	return
}

// Ping check connection success.
func (r *RPC) Ping(c context.Context, arg *struct{}, res *struct{}) (err error) {
	return
}

// ResourceAll get all resource.
func (r *RPC) ResourceAll(c context.Context, a *struct{}, res *[]*model.Resource) (err error) {
	*res = r.s.ResourceAll(c)
	return
}

// AssignmentAll get all assignment.
func (r *RPC) AssignmentAll(c context.Context, a *struct{}, res *[]*model.Assignment) (err error) {
	*res = r.s.AssignmentAll(c)
	return
}

// DefBanner get default banner.
func (r *RPC) DefBanner(c context.Context, a *struct{}, as *model.Assignment) (err error) {
	res := r.s.DefBanner(c)
	if res == nil {
		err = ecode.NothingFound
		return
	}
	*as = *res
	return
}

// Resource get resource.
func (r *RPC) Resource(c context.Context, arg *model.ArgRes, res *model.Resource) (err error) {
	rs := r.s.Resource(c, arg.ResID)
	if rs == nil {
		err = ecode.NothingFound
		return
	}
	*res = *rs
	return
}

// Resources get resource.
func (r *RPC) Resources(c context.Context, as *model.ArgRess, res *map[int]*model.Resource) (err error) {
	*res = r.s.Resources(c, as.ResIDs)
	return
}

// Banners get banners.
func (r *RPC) Banners(c context.Context, ab *model.ArgBanner, res *model.Banners) (err error) {
	// func Banners already new rs, rs can not be nil.
	rs := r.s.Banners(c, ab.Plat, ab.Build, ab.AID, ab.MID, ab.ResIDs, ab.Channel, ab.IP, ab.Buvid, ab.Network, ab.MobiApp, ab.Device, ab.OpenEvent, ab.AdExtra, ab.Version, ab.IsAd)
	*res = *rs
	return
}

// PasterAPP get paster for APP.
func (r *RPC) PasterAPP(c context.Context, arg *model.ArgPaster, res *model.Paster) (err error) {
	var rs *model.Paster
	if rs, err = r.s.PasterAPP(c, arg.Platform, arg.AdType, arg.Aid, arg.TypeId, arg.Buvid); err == nil {
		*res = *rs
	}
	return
}

// IndexIcon get index icon.
func (r *RPC) IndexIcon(c context.Context, a *struct{}, res *map[string][]*model.IndexIcon) (err error) {
	*res = r.s.IndexIcon(c)
	return
}

// PlayerIcon get player icon config.
func (r *RPC) PlayerIcon(c context.Context, arg *struct{}, res *model.PlayerIcon) (err error) {
	var rs *model.PlayerIcon
	rs, err = r.s.PlayerIcon(c)
	if err == nil {
		*res = *rs
	}
	return
}

// Cmtbox get live box.
func (r *RPC) Cmtbox(c context.Context, cb *model.ArgCmtbox, res *model.Cmtbox) (err error) {
	rs, err := r.s.Cmtbox(c, cb.ID)
	if err == nil {
		*res = *rs
	}
	return
}

// SideBars get sode bar.
func (r *RPC) SideBars(c context.Context, a *struct{}, res *model.SideBars) (err error) {
	sbs := r.s.SideBars(c)
	*res = *sbs
	return
}

// AbTest get abtest.
func (r *RPC) AbTest(c context.Context, ab *model.ArgAbTest, res *map[string]*model.AbTest) (err error) {
	*res = r.s.AbTest(c, ab.Groups, ab.IP)
	return
}

// PasterCID get all Paster's cid.
func (r *RPC) PasterCID(c context.Context, a *struct{}, res *map[int64]int64) (err error) {
	*res, err = r.s.PasterCID(c)
	return
}


text:
import theano.sandbox.cuda.basic_ops as sbcuda
import numpy as np
# import pandas as pd
import keras.backend as T
import load_data
import realtime_augmentation as ra
import time
import csv
import os
import cPickle as pickle
from datetime import datetime, timedelta

from keras.models import Sequential, Model
from keras.layers import Dense, Activation, MaxPooling1D, Dropout, Input, Convolution2D
from keras.layers.core import Lambda, Flatten, Reshape, Permute
from keras.optimizers import SGD, Adam
from keras.engine.topology import Merge
from keras.callbacks import LearningRateScheduler
from keras import initializations
import functools

from keras_extra_layers import kerasCudaConvnetPooling2DLayer, kerasCudaConvnetConv2DLayer, fPermute
from custom_for_keras import kaggle_MultiRotMergeLayer_output, OptimisedDivGalaxyOutput, kaggle_input, kaggle_sliced_accuracy, dense_weight_init_values, rmse

# import matplotlib.pyplot as plt
# plt.ion()
# import utils

debug = True
predict = False

continueAnalysis = False
saveAtEveryLearningRate = True

getWinSolWeights = False

if getWinSolWeights:
	WINSOL_PATH = "analysis/final/try_convent_gpu1_win_sol_net_on_0p0775_validation.pkl"
	analysis = np.load(WINSOL_PATH)
	l_weights =  analysis['param_values']
	#w_pairs=[]
	#for i in range(len(l_weights)/2):
    	#	w_pairs.append([l_weights[2*i],l_weights[2*i+1]])
	w_kSorted=[]
	for i in range(len(l_weights)/2):
		w_kSorted.append(l_weights[-2-2*i])
		w_kSorted.append(l_weights[-1-2*i])

CATEGORISED = False
y_train = np.load("data/solutions_train.npy")
if  CATEGORISED: y_train = np.load("data/solutions_train_categorised.npy")
ra.y_train=y_train

# split training data into training + a small validation set
ra.num_train = y_train.shape[0]

ra.num_valid = ra.num_train // 20 # integer division, is defining validation size
ra.num_train -= ra.num_valid

ra.y_valid = ra.y_train[ra.num_train:]
ra.y_train = ra.y_train[:ra.num_train]

load_data.num_train=y_train.shape[0]
load_data.train_ids = np.load("data/train_ids.npy")

ra.load_data.num_train = load_data.num_train
ra.load_data.train_ids = load_data.train_ids

ra.valid_ids = load_data.train_ids[ra.num_train:]
ra.train_ids = load_data.train_ids[:ra.num_train]

train_ids = load_data.train_ids
test_ids = load_data.test_ids

num_train = ra.num_train
num_test = len(test_ids)

num_valid = ra.num_valid

y_valid = ra.y_valid
y_train = ra.y_train

valid_ids = ra.valid_ids
train_ids = ra.train_ids

train_indices = np.arange(num_train)
valid_indices = np.arange(num_train, num_train + num_valid)
test_indices = np.arange(num_test)

BATCH_SIZE = 4

NUM_INPUT_FEATURES = 3

LEARNING_RATE_SCHEDULE = {  #if adam is used the learning rate doesnt follow the schedule
    0: 0.04,
    200: 0.05,
    400: 0.001,
    800: 0.0005
    #500: 0.04,
    #0: 0.01,
    #1800: 0.004,
    #2300: 0.0004,
   # 0: 0.08,
   # 50: 0.04,
   # 2000: 0.008,
   # 3200: 0.0008,
   # 4600: 0.0004,
}
if continueAnalysis or getWinSolWeights :
    LEARNING_RATE_SCHEDULE = {
        0: 0.0001,
        500: 0.002,
        #800: 0.0004,
        3200: 0.0002,
        4600: 0.0001,
    }

MOMENTUM = 0.9
WEIGHT_DECAY = 0.0
CHUNK_SIZE = 2000#1008#10000 # 30000 # this should be a multiple of the batch size, ideally.
NUM_CHUNKS = 2#1000#7000 #2500 # 3000 # 1500 # 600 # 600 # 600 # 500
VALIDATE_EVERY = 1 #20 # 12 # 6 # 6 # 6 # 5 # validate only every 5 chunks. MUST BE A DIVISOR OF NUM_CHUNKS!!!
# else computing the analysis data does not work correctly, since it assumes that the validation set is still loaded.
print("The training is running for %s chunks, each with %s images. That are about %s epochs. The validation sample contains %s images. \n" % (NUM_CHUNKS,CHUNK_SIZE,CHUNK_SIZE*NUM_CHUNKS / (ra.num_train-CHUNK_SIZE) ,  ra.num_valid ))
NUM_CHUNKS_NONORM =  1 # train without normalisation for this many chunks, to get the weights in the right 'zone'.
# this should be only a few, just 1 hopefully suffices.

#FIXME
CHUNK_SIZE=NUM_CHUNKS*CHUNK_SIZE
NUM_CHUNKS=1
while (CHUNK_SIZE-CHUNK_SIZE*0.5) % BATCH_SIZE:
	CHUNK_SIZE-=1

if debug: print CHUNK_SIZE

USE_ADAM = False #TODO not implemented

USE_LLERROR=False #TODO not implemented

USE_WEIGHTS=False #TODO not implemented

if USE_LLERROR and USE_WEIGHTS: print 'combination of weighted classes and log loss fuction not implemented yet'

WEIGHTS=np.ones((37))
#WEIGHTS[2]=1  #star or artifact
WEIGHTS[3]=1.5  #edge on yes
WEIGHTS[4]=1.5  #edge on no
#WEIGHTS[5]=1  #bar feature yes
#WEIGHTS[7]=1  #spiral arms yes
#WEIGHTS[14]=1  #anything odd? no
#WEIGHTS[18]=1  #ring
#WEIGHTS[19]=1  #lence
#WEIGHTS[20]=1  #disturbed
#WEIGHTS[21]=1  #irregular
#WEIGHTS[22]=1  #other
#WEIGHTS[23]=1  #merger
#WEIGHTS[24]=1  #dust lane
WEIGHTS=WEIGHTS/WEIGHTS[WEIGHTS.argmax()]

GEN_BUFFER_SIZE = 1

TRAIN_LOSS_SF_PATH = "trainingNmbrs_keras_hist_batchsize8.txt"

#TARGET_PATH = "predictions/final/try_convnet.csv"
ANALYSIS_PATH = "analysis/final/try_convent_keras_hist_batchsize8.pkl"

with open(TRAIN_LOSS_SF_PATH, 'a')as f:
	if continueAnalysis:
		f.write('#continuing from ')
		f.write(ANALYSIS_PATH)
	f.write("#wRandFlip \n")
	f.write("#The training is running for %s chunks, each with %s images. That are about %s epochs. The validation sample contains %s images. \n" % (NUM_CHUNKS,CHUNK_SIZE,CHUNK_SIZE*NUM_CHUNKS / (ra.num_train-CHUNK_SIZE) ,  ra.num_valid ))
	f.write("#round  ,time, mean_train_loss , mean_valid_loss, mean_sliced_accuracy, mean_train_loss_test, mean_accuracy \n")

if continueAnalysis:
    print "Loading model-loss data"
    analysis = np.load(ANALYSIS_PATH)

print "Set up data loading"

input_sizes = [(69, 69), (69, 69)]
PART_SIZE=45

ds_transforms = [
    ra.build_ds_transform(3.0, target_size=input_sizes[0]),
    ra.build_ds_transform(3.0, target_size=input_sizes[1]) + ra.build_augmentation_transform(rotation=45)
    ]

num_input_representations = len(ds_transforms)

augmentation_params = {
    'zoom_range': (1.0 / 1.3, 1.3),
    'rotation_range': (0, 360),
    'shear_range': (0, 0),
    'translation_range': (-4, 4),
    'do_flip': True,
}

augmented_data_gen = ra.realtime_augmented_data_gen(num_chunks=NUM_CHUNKS, chunk_size=CHUNK_SIZE,
                                                    augmentation_params=augmentation_params, ds_transforms=ds_transforms,
                                                    target_sizes=input_sizes)

post_augmented_data_gen = ra.post_augment_brightness_gen(augmented_data_gen, std=0.5)

train_gen = load_data.buffered_gen_mp(post_augmented_data_gen, buffer_size=GEN_BUFFER_SIZE)

def create_train_gen():
    """
    this generates the training data in order, for postprocessing. Do not use this for actual training.
    """
    data_gen_train = ra.realtime_fixed_augmented_data_gen(train_indices, 'train',
        ds_transforms=ds_transforms, chunk_size=CHUNK_SIZE, target_sizes=input_sizes)
    return load_data.buffered_gen_mp(data_gen_train, buffer_size=GEN_BUFFER_SIZE)

def create_valid_gen():
    data_gen_valid = ra.realtime_fixed_augmented_data_gen(valid_indices, 'train',
        ds_transforms=ds_transforms, chunk_size=CHUNK_SIZE, target_sizes=input_sizes)
    return load_data.buffered_gen_mp(data_gen_valid, buffer_size=GEN_BUFFER_SIZE)

def create_test_gen():
    data_gen_test = ra.realtime_fixed_augmented_data_gen(test_indices, 'test',
        ds_transforms=ds_transforms, chunk_size=CHUNK_SIZE, target_sizes=input_sizes)
    return load_data.buffered_gen_mp(data_gen_test, buffer_size=GEN_BUFFER_SIZE)

'''
print "Preprocess validation data upfront"
start_time = time.time()
xs_valid = [[] for _ in xrange(num_input_representations)]

for data, length in create_valid_gen():
    for x_valid_list, x_chunk in zip(xs_valid, data):
        x_valid_list.append(x_chunk[:length])

xs_valid = [np.vstack(x_valid) for x_valid in xs_valid]
xs_valid = [x_valid.transpose(0, 3, 1, 2) for x_valid in xs_valid] # move the colour dimension up

print "  took %.2f seconds" % (time.time() - start_time)
'''

N_INPUT_VARIATION=2

print "Build model"

if debug : print("input size: %s x %s x %s x %s" % (input_sizes[0][0],input_sizes[0][1],NUM_INPUT_FEATURES,BATCH_SIZE))

input_tensor = Input(batch_shape=(BATCH_SIZE, NUM_INPUT_FEATURES, input_sizes[0][0], input_sizes[0][1]) , dtype='float32', name='input_tensor')
input_tensor_45 = Input(batch_shape=(BATCH_SIZE, NUM_INPUT_FEATURES, input_sizes[0][0], input_sizes[0][1]) , dtype='float32', name='input_tensor_45')

input_0 = Lambda(lambda x: x,output_shape=(NUM_INPUT_FEATURES, input_sizes[0][0], input_sizes[0][1]),batch_input_shape=(BATCH_SIZE, NUM_INPUT_FEATURES, input_sizes[0][0], input_sizes[0][1]),name='lambda_input_0')
input_45 = Lambda(lambda x: x,output_shape=(NUM_INPUT_FEATURES, input_sizes[1][0], input_sizes[1][1]),batch_input_shape=(BATCH_SIZE, NUM_INPUT_FEATURES, input_sizes[0][0], input_sizes[0][1]),name='lambda_input_45')

model1 = Sequential()
model1.add(input_0)

model2 = Sequential()
model2.add(input_45)

if debug :print model1.output_shape

model = Sequential()

model.add(Merge([model1, model2], mode=kaggle_input , output_shape=lambda x: (BATCH_SIZE*4*N_INPUT_VARIATION, NUM_INPUT_FEATURES, PART_SIZE, PART_SIZE) , arguments={'part_size':PART_SIZE, 'n_input_var': N_INPUT_VARIATION, 'include_flip':False, 'random_flip':True}  ))

if debug : print model.output_shape

#needed for the pylearn moduls used by kerasCudaConvnetConv2DLayer and kerasCudaConvnetPooling2DLayer
model.add(fPermute((1,2,3,0)))

if debug : print model.output_shape

model.add(kerasCudaConvnetConv2DLayer(n_filters=32, filter_size=6 , untie_biases=True))
if debug : print model.output_shape
model.add(kerasCudaConvnetPooling2DLayer())

if debug : print model.output_shape

model.add(kerasCudaConvnetConv2DLayer(n_filters=64, filter_size=5 , untie_biases=True))
if debug : print model.output_shape
model.add(kerasCudaConvnetPooling2DLayer())

model.add(kerasCudaConvnetConv2DLayer(n_filters=128, filter_size=3 , untie_biases=True))
model.add(kerasCudaConvnetConv2DLayer(n_filters=128, filter_size=3,  weights_std=0.1 , untie_biases=True ))

if debug : print model.output_shape

model.add(kerasCudaConvnetPooling2DLayer())

if debug : print model.output_shape

model.add(fPermute((3,0,1,2)))

if debug : print model.output_shape

model.add(Lambda(function=kaggle_MultiRotMergeLayer_output, output_shape=lambda x : ( x[0]//4//N_INPUT_VARIATION, (x[1]*x[2]*x[3]*4* N_INPUT_VARIATION) ) , arguments={'num_views':N_INPUT_VARIATION}) )

if debug : print model.output_shape

#model.add(Dense(output_dim=4096, init=functools.partial(initializations.normal, scale=0.001) ))
model.add(Dropout(0.5))
model.add(Dense(output_dim=4096, weights = dense_weight_init_values(model.output_shape[-1],4096) ))
#model.add(Dropout(0.5))
model.add(Reshape((model.output_shape[-1],1)))
model.add(MaxPooling1D())
model.add(Reshape((model.output_shape[1],)))
model.add(Dropout(0.5))
model.add(Dense(output_dim=4096, weights = dense_weight_init_values(model.output_shape[-1],4096) ))

if debug : print model.output_shape

#model.add(Dropout(0.5))
model.add(Reshape((model.output_shape[-1],1)))
model.add(MaxPooling1D())

if debug : print model.output_shape

model.add(Reshape((model.output_shape[1],)))
model.add(Dropout(0.5))
model.add(Dense(output_dim=37, weights = dense_weight_init_values(model.output_shape[-1],37 ,w_std = 0.01 , b_init_val = 0.1 ) ))
#model.add(Dropout(0.5))
#model.add(Dropout(0.))

if debug : print model.output_shape

model_seq=model([input_tensor,input_tensor_45])

output_layer_norm = Lambda(function=OptimisedDivGalaxyOutput , output_shape=lambda x: x ,arguments={'mb_size': BATCH_SIZE,'normalised':True,'categorised':CATEGORISED})(model_seq)
output_layer_noNorm = Lambda(function=OptimisedDivGalaxyOutput , output_shape=lambda x: x ,arguments={'mb_size': BATCH_SIZE,'normalised':False,'categorised':CATEGORISED})(model_seq)

model_norm=Model(input=[input_tensor,input_tensor_45],output=output_layer_norm)
model_norm_metrics = Model(input=[input_tensor,input_tensor_45],output=output_layer_norm)
model_noNorm=Model(input=[input_tensor,input_tensor_45],output=output_layer_noNorm)

if debug : print model_norm.output_shape

if debug : print model_noNorm.output_shape

current_lr=LEARNING_RATE_SCHEDULE[0]
def lr_function(e):
	global current_lr
	if e in LEARNING_RATE_SCHEDULE:
		_current_lr = LEARNING_RATE_SCHEDULE[e]
		current_lr = _current_lr
	else: _current_lr =  current_lr
	return _current_lr
lr_callback = LearningRateScheduler(lr_function)

if getWinSolWeights:
	w_load_worked = False
	for l in model_norm.layers:
		if debug: print '---'
		if debug: print len(l.get_weights())
		l_weights = l.get_weights()
		if len(l_weights)==len(w_kSorted):
			if debug:
				for i in range(len(l_weights)):
    					print type(l_weights[i])
    					print np.shape(l_weights[i])
					if not np.shape(l_weights[i]) == np.shape(w_kSorted[i]): "somethings wrong with the loaded weight shapes"
			l.set_weights(w_kSorted)
			w_load_worked = True
	if not w_load_worked: print "no matching weight length were found"

model_norm.compile(loss='mean_squared_error', optimizer=SGD(lr=LEARNING_RATE_SCHEDULE[0], momentum=MOMENTUM, nesterov=True) )#, metrics=[rmse, 'categorical_accuracy',kaggle_sliced_accuracy])
model_noNorm.compile(loss='mean_squared_error', optimizer=SGD(lr=LEARNING_RATE_SCHEDULE[0], momentum=MOMENTUM, nesterov=True), metrics=['categorical_accuracy'])

model_norm_metrics.compile(loss='mean_squared_error', optimizer=SGD(lr=LEARNING_RATE_SCHEDULE[0], momentum=MOMENTUM, nesterov=True), metrics=[rmse, 'categorical_accuracy',kaggle_sliced_accuracy])

#adam = Adam(lr=LEARNING_RATE_SCHEDULE[0], beta_1=0.9, beta_2=0.999, epsilon=1e-07, decay=0.0)

#model_norm.compile(loss='mean_squared_error', optimizer=adam, metrics=['categorical_accuracy',kaggle_sliced_accuracy])
#model_noNorm.compile(loss='mean_squared_error', optimizer=adam, metrics=['categorical_accuracy'])

#xs_shared = [T.variable(np.zeros((1,1,1,1), dtype='float32')) for _ in xrange(num_input_representations)]
#y_shared = T.variable(np.zeros((1,1), dtype='float32'))

xs_shared = [np.zeros((1,1,1,1), dtype='float32') for _ in xrange(num_input_representations)]
y_shared = np.zeros((1,1), dtype='float32')

if continueAnalysis:#TODO
    print "Load model weights"
    model_norm.load_weights(filepath)

print "Train model"
start_time = time.time()
prev_time = start_time

#num_batches_valid = x_valid.shape[0] // BATCH_SIZE
losses_train = []
losses_valid = []

if debug: print("Free GPU Mem before training step %s MiB " % (sbcuda.cuda_ndarray.cuda_ndarray.mem_info()[0]/1024./1024.))
chunk_data, chunk_length = train_gen.next()
y_chunk = chunk_data.pop() # last element is labels.
xs_chunk = chunk_data

    # need to transpose the chunks to move the 'channels' dimension up
xs_chunk = [x_chunk.transpose(0, 3, 1, 2) for x_chunk in xs_chunk]

l0_input_var = xs_chunk[0]
l0_45_input_var = xs_chunk[1]
l6_target_var = y_chunk

    # train without normalisation for the first # chunks.
#if e >= NUM_CHUNKS_NONORM or continueAnalysis or getWinSolWeights:
model_inUse = model_norm
        #if  USE_LLERROR:  train = train_norm_ll
#else:
#    model_inUse = model_noNorm
        #if  USE_LLERROR:  train = train_nonorm_ll

model_inUse.summary()

print model_norm_metrics.metrics_names
evalHistdic = {}
for n in model_norm_metrics.metrics_names:
	evalHistdic[n]=[]

evalHist = model_norm_metrics.evaluate(x=[l0_input_var,l0_45_input_var] , y=l6_target_var,batch_size=BATCH_SIZE, verbose=1)
for i in range(len(model_norm_metrics.metrics_names)):
	evalHistdic[model_norm_metrics.metrics_names[i]].append(evalHist[i])

print evalHistdic

eval_epochs = 5

hist = model_inUse.fit(x=[l0_input_var,l0_45_input_var] , y=l6_target_var,batch_size=BATCH_SIZE, nb_epoch=eval_epochs, verbose=1, callbacks=[lr_callback], validation_split=0.5) #loss is squared!!!
hists=hist.history

for i in range(2):
	evalHist = model_norm_metrics.evaluate(x=[l0_input_var,l0_45_input_var] , y=l6_target_var,batch_size=BATCH_SIZE, verbose=1)
	for i in range(len(model_norm_metrics.metrics_names)):
		evalHistdic[model_norm_metrics.metrics_names[i]].append(evalHist[i])

	print evalHistdic

	hist = model_inUse.fit(x=[l0_input_var,l0_45_input_var] , y=l6_target_var,batch_size=BATCH_SIZE, nb_epoch=eval_epochs*(i+2), initial_epoch=eval_epochs*(i+1), verbose=1, callbacks=[lr_callback], validation_split=0.5)

	print hist.history
	for k in hists:
		hists[k]+=hist.history[k]

evalHist = model_norm_metrics.evaluate(x=[l0_input_var,l0_45_input_var] , y=l6_target_var,batch_size=BATCH_SIZE, verbose=1)
for i in range(len(model_norm_metrics.metrics_names)):
	evalHistdic[model_norm_metrics.metrics_names[i]].append(evalHist[i])

print evalHistdic

LR_PATH = (ANALYSIS_PATH.split('.',1)[0]+'.h5')
model_inUse.save_weights(LR_PATH)

#print hists.epoch

import json

with open(TRAIN_LOSS_SF_PATH, 'a')as f:
	f.write("#eval losses and metrics:\n")
	f.write(json.dumps(evalHistdic))
	f.write("\n")
	f.write("#fit losses:\n")
	f.write(json.dumps(hists))
	f.write("\n")

print "Done!"
exit()


text:
package netflix.adminresources;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Singleton;
import com.netflix.config.ConfigurationManager;
import com.netflix.governator.lifecycle.ClasspathScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Singleton
public class AdminPageRegistry {
    private static final Logger LOG = LoggerFactory.getLogger(AdminPageRegistry.class);
    public final static String PROP_ID_ADMIN_PAGES_SCAN = "netflix.platform.admin.pages.packages";
    public static final String DEFAULT_SCAN_PKG = "netflix";
    public final static String PROP_ID_ADMIN_PAGE_ANNOTATION = "netflix.platform.admin.pages.annotation";
    public static final String DEFAULT_ADMIN_PAGE_ANNOTATION = "netflix.adminresources.AdminPage";

    private Map<String, AdminPageInfo> baseServerPageInfoMap;

    public AdminPageRegistry() {
        this.baseServerPageInfoMap = new ConcurrentHashMap<>();
    }

    public void add(AdminPageInfo baseServerPageInfo) {
        Preconditions.checkNotNull(baseServerPageInfo);
        baseServerPageInfoMap.put(baseServerPageInfo.getPageId(), baseServerPageInfo);
    }

    public void remove(AdminPageInfo baseServerPageInfo) {
        Preconditions.checkNotNull(baseServerPageInfo);
        baseServerPageInfoMap.remove(baseServerPageInfo.getPageId());
    }

    public AdminPageInfo getPageInfo(String pageId) {
        return baseServerPageInfoMap.get(pageId);
    }

    public Collection<AdminPageInfo> getAllPages() {
        List<AdminPageInfo> pages = Lists.newArrayList(baseServerPageInfoMap.values());
        List<AdminPageInfo> enabledPages = getEnabledPages(pages);

        // list needs to be sorted by page titles if available
        Collections.sort(enabledPages, new Comparator<AdminPageInfo>() {
            public int compare(AdminPageInfo left, AdminPageInfo right) {
                String leftVal = left.getName() != null ? left.getName() : left.getPageId();
                String rightVal = right.getName() != null ? right.getName() : right.getPageId();
                return leftVal.compareToIgnoreCase(rightVal);
            }
        });

        return enabledPages;
    }

    public void registerAdminPagesWithClasspathScan() {
        List<Class<? extends Annotation>> annotationList = getAdminPageAnnotations();
        ClasspathScanner cs = new ClasspathScanner(getAdminPagesPackagesToScan(), annotationList);
        for (Class<?> baseServerAdminPageClass : cs.getClasses()) {
            if (derivedFromAbstractBaseServePageInfo(baseServerAdminPageClass) ||
                    implementsAdminPageInfo(baseServerAdminPageClass)) {
                try {
                    AdminPageInfo baseServerPageInfo = (AdminPageInfo) baseServerAdminPageClass.newInstance();
                    add(baseServerPageInfo);
                } catch (Exception e) {
                    LOG.warn(String.format("Exception registering %s admin page", baseServerAdminPageClass.getName()), e);
                }
            }
        }
    }

    public String buildJerseyResourcePkgListForAdminPages() {
        StringBuilder stringBuilder = new StringBuilder();
        Collection<AdminPageInfo> adminPages = getAllPages();
        int i = 0;
        for (AdminPageInfo adminPage : adminPages) {
            if (i > 0) {
                stringBuilder.append(";");
            }
            String pkgList = adminPage.getJerseyResourcePackageList();
            if (pkgList != null) {
                stringBuilder.append(pkgList);
            }
            i++;
        }
        return stringBuilder.toString();
    }

    private List<String> getAdminPagesPackagesToScan() {
        final String adminPagesPkgPath = ConfigurationManager.getConfigInstance().getString(PROP_ID_ADMIN_PAGES_SCAN, DEFAULT_SCAN_PKG);
        String[] pkgPaths = adminPagesPkgPath.split(";");
        return Lists.newArrayList(pkgPaths);
    }

    private boolean implementsAdminPageInfo(Class<?> baseServerAdminPageClass) {
        Class<?>[] interfacesImplemented = baseServerAdminPageClass.getInterfaces();

        for (Class<?> interfaceObj : interfacesImplemented) {
            if (interfaceObj.equals(AdminPageInfo.class)) {
                return true;
            }
        }
        return false;
    }

    private boolean derivedFromAbstractBaseServePageInfo(Class<?> baseServerAdminPageClass) {
        Class<?> superClass = baseServerAdminPageClass.getSuperclass();
        while (superClass != null) {
            if (superClass.equals(AbstractAdminPageInfo.class)) {
                return true;
            }
            superClass = superClass.getSuperclass();
        }
        return false;
    }

    public List<Class<? extends Annotation>> getAdminPageAnnotations() {
        final String adminPageAnnotationClasses = ConfigurationManager.getConfigInstance().getString(PROP_ID_ADMIN_PAGE_ANNOTATION, DEFAULT_ADMIN_PAGE_ANNOTATION);
        String[] clsNameList = adminPageAnnotationClasses.split(";");
        List<Class<? extends Annotation>> clsList = new ArrayList<>(clsNameList.length);
        for (String clsName : clsNameList) {
            try {
                final Class<?> aClass = Class.forName(clsName);
                if (aClass.isAnnotation()) {
                    clsList.add(aClass.asSubclass(Annotation.class));
                }
            } catch (ClassNotFoundException e) {
                LOG.warn("Invalid AdminPage Annotation class - " + clsName);
            }
        }
        return clsList;
    }

    private List<AdminPageInfo> getEnabledPages(List<AdminPageInfo> pages) {
        List<AdminPageInfo> enabledPages = Lists.newArrayList();
        for (AdminPageInfo page : pages) {
            if (page.isEnabled()) {
                enabledPages.add(page);
            }
        }
        return enabledPages;
    }
}


text:
#ifndef include_ducxxling_base_h
#define include_ducxxling_base_h

#include "ducxxling/dti.h"
#include "ducxxling/except.h"

namespace Ducxxling {

    class BaseType {
        DTI_DECLARE_DYNAMIC_TYPE;
    public:
        BaseType();
        virtual ~BaseType();

        /**
         * Create a copy of the this object and return a pointer.
         */
        virtual BaseType *dup() const = 0;

        /**
         * Check whether the current object is the same type as the given object.
         *
         * \param   base    Object to compare against.
         * \return  true if object and base share a type; false if not.
         */
        bool is_a(const BaseType &base) const;

        template<class T>
        bool is_a() const
        {
            return get_dti_type().is_a(&T::type_);
        }

        /**
         * Test equality.
         */
        virtual bool equals(const BaseType &value) const = 0;

        /**
         * Perform assignment.
         */
        virtual BaseType &assign(const BaseType &) = 0;

        /**
         * Prevent this instance from being updated.
         */
        void freeze();

    protected:
        /*
         * Frozen objects should not be alterable.
         */
        bool frozen_;
    };

} // namespace Ducxxling

#endif // include_ducxxling_base_h


text:
"""
Utility functions to support the Echo Nest web API interface.  This
module is not meant for other uses and should not be used unless
modifying or extending the package.
"""

import time
import urllib
import urllib2
import xml.dom.minidom
import xml.etree.ElementTree

import config
import urllib2_file

SUCCESS_STATUS_CODES = ( 0, )
FAILURE_THING_ID_STATUS_CODES = (7, 6)
FAILURE_API_KEY_STATUS_CODES = (12,)

CALL_LOG = []

def parse_http_response(response):
    response = xml.etree.ElementTree.fromstring(response)
    return check_status(response)

def call(method, params, POST=False):
    rate_limit_exceeded = not check_call_log()
    while rate_limit_exceeded:
        time.sleep(0.5)
        rate_limit_exceeded = not check_call_log()
    params.update({'api_key': config.ECHO_NEST_API_KEY, 'version': 3})
    for k,v in params.items():
        if isinstance(v, unicode):
            params[k] = v.encode('utf-8')
    params = urllib.urlencode(params)
    if(POST):
        url = 'http://%s%s%s' % (config.API_HOST, config.API_SELECTOR, method)
        f = urllib.urlopen(url, params)
    else:
        url = 'http://%s%s%s?%s' % (config.API_HOST, config.API_SELECTOR,
                                    method, params)
        f = urllib.urlopen(url)
    response = xml.etree.ElementTree.fromstring(f.read())
    return check_status(response)

def check_call_log():
    if not config.OBEY_RATE_LIMIT:
        return True
    global CALL_LOG
    CALL_LOG = filter(lambda x: x > (time.time() - 60), CALL_LOG)
    if len(CALL_LOG) >= 120:
        return False
    CALL_LOG.append(time.time())
    return True

def check_status(etree):
    code = int(etree._children[0]._children[0].text)
    message = etree._children[0]._children[1].text
    if code!=0:
        raise EchoNestAPIError(code, message)
    else:
        return etree

class EchoNestAPIError(Exception):
    """
    Generic API errors.
    """
    def __init__(self, code, message):
        self.code = code
        self._message = message
    def __str__(self):
        return repr(self)
    def __repr__(self):
        return 'Echo Nest API Error %d: %s' % (self.code, self._message)

class EchoNestAPIKeyError(EchoNestAPIError):
    """
    An Error returned by the API regarding the API Key.
    """
    pass

class EchoNestAPIThingIDError(EchoNestAPIError):
    """
    An Error returned by the API regarding the ThingID.
    """
    pass

def postChunked(host, selector, fields, files):
    """
    Attempt to replace postMultipart() with nearly-identical interface.
    (The files tuple no longer requires the filename, and we only return
    the response body.)
    Uses the urllib2_file.py originally from
    http://fabien.seisen.org which was also drawn heavily from
    http://code.activestate.com/recipes/146306/ .

    This urllib2_file.py is more desirable because of the chunked
    uploading from a file pointer (no need to read entire file into
    memory) and the ability to work from behind a proxy (due to its
    basis on urllib2).
    """
    params = urllib.urlencode(fields)
    url = 'http://%s%s?%s' % (host, selector, params)
    u = urllib2.urlopen(url, files)
    result = u.read()
    [fp.close() for (key, fp) in files]
    return result


text:
from __future__ import annotations

from typing import Any, TYPE_CHECKING

import simplejson as json
from flask import request
from flask_appbuilder import expose
from flask_appbuilder.api import rison
from flask_appbuilder.security.decorators import has_access_api

from superset import db, event_logger
from superset.charts.commands.exceptions import (
    TimeRangeAmbiguousError,
    TimeRangeParseFailError,
)
from superset.legacy import update_time_range
from superset.models.slice import Slice
from superset.superset_typing import FlaskResponse
from superset.utils import core as utils
from superset.utils.date_parser import get_since_until
from superset.views.base import api, BaseSupersetView, handle_api_exception

if TYPE_CHECKING:
    from superset.common.query_context_factory import QueryContextFactory

get_time_range_schema = {"type": "string"}

class Api(BaseSupersetView):
    query_context_factory = None

    @event_logger.log_this
    @api
    @handle_api_exception
    @has_access_api
    @expose("/v1/query/", methods=["POST"])
    def query(self) -> FlaskResponse:
        """
        Takes a query_obj constructed in the client and returns payload data response
        for the given query_obj.

        raises SupersetSecurityException: If the user cannot access the resource
        """
        query_context = self.get_query_context_factory().create(
            **json.loads(request.form["query_context"])
        )
        query_context.raise_for_access()
        result = query_context.get_payload()
        payload_json = result["queries"]
        return json.dumps(
            payload_json, default=utils.json_int_dttm_ser, ignore_nan=True
        )

    @event_logger.log_this
    @api
    @handle_api_exception
    @has_access_api
    @expose("/v1/form_data/", methods=["GET"])
    def query_form_data(self) -> FlaskResponse:  # pylint: disable=no-self-use
        """
        Get the formdata stored in the database for existing slice.
        params: slice_id: integer
        """
        form_data = {}
        slice_id = request.args.get("slice_id")
        if slice_id:
            slc = db.session.query(Slice).filter_by(id=slice_id).one_or_none()
            if slc:
                form_data = slc.form_data.copy()

        update_time_range(form_data)

        return json.dumps(form_data)

    @api
    @handle_api_exception
    @has_access_api
    @rison(get_time_range_schema)
    @expose("/v1/time_range/", methods=["GET"])
    def time_range(self, **kwargs: Any) -> FlaskResponse:
        """Get actually time range from human readable string or datetime expression"""
        time_range = kwargs["rison"]
        try:
            since, until = get_since_until(time_range)
            result = {
                "since": since.isoformat() if since else "",
                "until": until.isoformat() if until else "",
                "timeRange": time_range,
            }
            return self.json_response({"result": result})
        except (ValueError, TimeRangeParseFailError, TimeRangeAmbiguousError) as error:
            error_msg = {"message": f"Unexpected time range: {error}"}
            return self.json_response(error_msg, 400)

    def get_query_context_factory(self) -> QueryContextFactory:
        if self.query_context_factory is None:
            # pylint: disable=import-outside-toplevel
            from superset.common.query_context_factory import QueryContextFactory

            self.query_context_factory = QueryContextFactory()
        return self.query_context_factory


text: Note: You need to make sure that your arduino is flashed with Standard Firmata. Instructions for doing so can be found [here](https://github.com/rwaldron/johnny-five/wiki/Getting-Started#trouble-shooting).


text:
    **
    Idicon can be used to produce 5x5 user identifiable unique icons, also known as identicons.
    These are similar to the default icons used with github.
    Idicon supports 5x5 identicons in svg, png, or raw_bitmap, with custom padding.

    (String eg. User name) -> Idicon -> Image that is (mostly) unique to the user.
    Since the identicon can be produced repeatedly from the same input, it is not necessary
    to save the produced image anywhere. Instead, it can be rendered each time it is requested. **

## Installation

The package can be installed
by adding `identicon` to your list of dependencies in `mix.exs`:

```elixir
def deps do
  [{:idicon, "~> 0.1.1"}]
end
```

The documentation can be found at [https://hexdocs.pm/idicon](https://hexdocs.pm/idicon).


text:
package org.vitrivr.cineast.core.features;

import org.vitrivr.cineast.core.data.entities.SimpleFulltextFeatureDescriptor;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.features.abstracts.AbstractTextRetriever;

public class SubtitleFulltextSearch extends AbstractTextRetriever {

  /**
   * Default constructor for {@link SubtitleFulltextSearch}.
   */
  public SubtitleFulltextSearch() {
    super("features_asr");
  }

  /**
   * Extracts the subtitle text and ingests it using the {@link SimpleFulltextFeatureDescriptor}.
   *
   * @param shot The {@link SegmentContainer} that should be processed.
   */
  @Override
  public void processSegment(SegmentContainer shot) {
    shot.getSubtitleItems().stream()
        .map(s -> new SimpleFulltextFeatureDescriptor(shot.getId(), s.getText()))
        .forEach(s -> this.writer.write(s));
  }
}


text:
$(document).on('submit', '#new-payment', function (e) {
    e.preventDefault();

    var $this = $(this);

    var l = Ladda.create(document.querySelector('#new-payment-button'));
    l.start();

    if ($('input[name=pricing]:checked', $this).length <= 0) {
        l.stop();
        $('input[name=pricing]', $this).first().focus();
        return false;
    }

    $.ajax({
        method: 'POST',
        url: $this.attr('action'),
        data: {
            pricing_id: $.trim($('input[name=pricing]:checked', $this).
                first().val()),
            authenticity_token: $.trim($('meta[name=csrf-token]').attr('content'))
        },
        success: function (response) {
            l.stop();
            swal({
                title: response.data.title,
                text: response.data.text,
                type: response.data.type,
                confirmButtonText: response.data.confirmButtonText
            }, function () {
                if (response.data.redirect_url !== null) {
                    window.location.href = response.data.redirect_url;
                }
            });
        },
        error: function () {
            l.stop();
            var locales_error = $('#locales_error');
            swal({
                title: locales_error.data('title'),
                text: locales_error.data('text'),
                type: 'error',
                confirmButtonText: locales_error.data('confirmButtonText')
            });
        }
    });
});


text:
"use strict"

var util = require('./index'),
    events = require('events')

/**
 * @namespace
 */
var remote_resources = {}

/**
 * @class
 * @memberOf remote_resources
 */
function RemoteResource(url, path) {
    this.url = url
    this.path = path
}
remote_resources.RemoteResource = RemoteResource

/**
 * Load the remote resource via ajax
 */
remote_resources.RemoteResource.prototype.load = function () {
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            __jah__.resources[this.path].data = xhr.responseText
            __jah__.resources[this.path].loaded = true

            events.trigger(this, 'load', this)
        }
    }.bind(this)

    xhr.open('GET', this.url, true)
    xhr.send(null)
}

/**
 * @class
 * @memberOf remote_resources
 * @extends remote_resources.RemoteResource
 */
function RemoteImage(url, path) {
    RemoteResource.apply(this, arguments)
}
remote_resources.RemoteImage = RemoteImage

remote_resources.RemoteImage.prototype = Object.create(RemoteResource.prototype)

remote_resources.RemoteImage.prototype.load = function () {
    var img = new Image()
    __jah__.resources[this.path].data = img

    /**
     * @ignore
     */
    img.onload = function () {
        __jah__.resources[this.path].loaded = true
        events.trigger(this, 'load', this)
    }.bind(this)

    /**
     * @ignore
     */
    img.onerror = function () {
        console.warn("Failed to load resource: [%s] from [%s]", this.path, img.src)
        __jah__.resources[this.path].loaded = true
        events.trigger(this, 'load', this)
    }.bind(this)

    img.src = this.url

    return img
}

/**
 * @class
 * @memberOf remote_resources
 * @extends remote_resources.RemoteResource
 */
function RemoteScript(url, path) {
    RemoteResource.apply(this, arguments)
}
remote_resources.RemoteScript = RemoteScript

remote_resources.RemoteScript.prototype = Object.create(RemoteResource.prototype)

remote_resources.RemoteScript.prototype.load = function () {
    var script = document.createElement('script')
    __jah__.resources[this.path].data = script

    /**
     * @ignore
     */
    script.onload = function () {
        __jah__.resources[this.path].loaded = true
        events.trigger(this, 'load', this)
    }.bind(this)

    script.src = this.url
    document.getElementsByTagName('head')[0].appendChild(script)

    return script
}

remote_resources.getRemoteResourceConstructor = function (mime) {
    mime = mime.split('/')

    var RemoteObj
    if (mime[0] == 'image') {
        RemoteObj = RemoteImage
    } else if(mime[1] == 'javascript') {
        RemoteObj = RemoteScript
    } else {
        RemoteObj = RemoteResource
    }

    return RemoteObj
}

remote_resources.getRemoteResource = function (resourcePath) {
    var resource = __jah__.resources[resourcePath]

    if (!resource) {
        return null
    }

    if (resource.remoteResource) {
        return resource.remoteResource
    }

    var RemoteObj = remote_resources.getRemoteResourceConstructor(resource.mimetype)

    resource.remoteResource = new RemoteObj(resource.data, resourcePath)

    return resource.remoteResource
}

module.exports = remote_resources


text:
<?php
function dump($data)
{
  echo "
";
  echo var_dump($data);
  echo "
";
}

function breadcrumbs($home = 'Home') {
    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array(" $home");

    // Find out the index for the last value in our path array
    $last = end($path);

    // Build the rest of the breadcrumbs
    foreach ($path AS $x => $crumb) {
        // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
        $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));

        // If we are not on the last index, then display an  tag
        if ($x != $last)
            $breadcrumbs[] = "$title";
        // Otherwise, just display the title (minus)
        else
            $breadcrumbs[] = '' . $title . '';
    }

    // Build our temporary array (pieces of bread) into one big string :)
    return "
" . implode($breadcrumbs) . "
";
}
// breadcrumbs()
// breadcrumbs(' > ')
// breadcrumbs(' ^^ ', 'Index')


text:
package com.imminentmeals.prestige.annotations.meta;

/**
 *
Basic implementation scope values. {@link #PRODUCTION} is the default implementation that is provided, and any other
 * scope can be provided on top of that to replace production implementations. You are not limited to the provided values,
 * they are provided merely for convenience.

 * @author Dandre Allison
 */
public interface Implementations {
	/** Default implementation scope, and the one that provides production app implementations */
	String PRODUCTION = "production";
	String TEST = "test";
	String DEVELOPMENT = "development";
}


text:
{% load wagtailcore_tags core_tags gem_tags %}

{% comment %}
    1. Display default or custom image
    2. Display color theme
    3. On Main.html - Display on separate position
    4. If User is authenticated show GCN Competition
{% endcomment %}
    <div class="gcn-competition gcn-competition--homepage gcn-competition{{form_page.get_effective_extra_style_hints}}">
        {% include "patterns/basics/forms/forms-modules/forms_gcn-heading.html" with pagetype=survey %}
        {%  if form_page.homepage_introduction %}
            {% include "patterns/basics/headings/sp_variations/heading.html" with type="subheading" htmltag="p" title=form_page.homepage_introduction|smarttruncatechars:100|safe %}
        {% endif %}

        {% trans "Take GCN competition" as buttontext %}
        {% with trans_buttontext=form_page.homepage_button_text|default:buttontext %}
        {% pageurl form_page.specific as the_url %}
        {% include "patterns/basics/buttons/sp_variations/button.html" with type="primary" hyperlink=the_url text=trans_buttontext %}
        {% endwith %}
    </div>


text:
/**
 * 带滚动条的滚动层
 * @author zsq
 * @version 20150122
 */
(function() {

	var ScrollView = cc.Node.extend({
		initWithConfig: function(data) {
			var width = data.width || 300;
			var height = data.height || 300;
			this.width = width;
			this.height = height;
			var direction;
			if (data.hbar && data.vbar) {
				direction = ccui.ScrollView.DIR_BOTH;
			} else if (data.hbar) {
				direction = ccui.ScrollView.DIR_HORIZONTAL;
			} else if (data.vbar) {
				direction = ccui.ScrollView.DIR_VERTICAL;
			} else {
				direction = ccui.ScrollView.DIR_NONE;
			}
			var scrollView = ccui.ScrollView.create();
			scrollView.setDirection(direction);
			scrollView.setTouchEnabled(true);
			if (data.bounce) {
				scrollView.setBounceEnabled(true);
			}
			scrollView.setSize(cc.size(width, height));
			//scrollView.setInnerContainerSize(cc.size(width, height));
			this.addChild(scrollView);
			this.scrollView = scrollView;

			this.hbar = null;
			this.vbar = null;
			var barWidth = 10;
			/*横向滚动条*/
			if (data.hbar) {
				var hbar = ccui.Layout.create();
				hbar.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID);
				hbar.setBackGroundColor(cc.color(255, 0, 0));
				hbar.setSize(cc.size(width, barWidth));
				hbar.setClippingEnabled(true);
				hbar.setCascadeOpacityEnabled(true);
				hbar.y = -barWidth - 5;
				var thumb = ccui.Layout.create();
				thumb.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID);
				thumb.setBackGroundColor(cc.color(0, 255, 0));
				thumb.setSize(cc.size(width / 2, barWidth));
				hbar.addChild(thumb);
				this.addChild(hbar);
				this.hbar = hbar;
			}
			/*竖向滚动条*/
			if (data.vbar) {
				var vbar = ccui.Layout.create();
				vbar.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID);
				vbar.setBackGroundColor(cc.color(255, 0, 0));
				vbar.setSize(cc.size(barWidth, height));
				vbar.setClippingEnabled(true);
				vbar.setCascadeOpacityEnabled(true);
				vbar.x = width;
				var thumb = ccui.Layout.create();
				thumb.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID);
				thumb.setBackGroundColor(cc.color(0, 255, 0));
				thumb.setSize(cc.size(barWidth, height / 2));
				vbar.addChild(thumb);
				this.addChild(vbar);
				this.vbar = vbar;
			}
			/*滚动条的自动隐藏*/
			this.autoHideBar = null;
			var autoHideTime = data.autoHideTime || 2000;
			if(data.autoHideBar){
				var hideBarAction = (function(){
					if(this.hbar && this.hbar.visible){
						var act = cc.fadeOut(0.2);
						this.hbar.runAction(act);
					}
					if(this.vbar && this.vbar.visible){
						var act = cc.fadeOut(0.2);
						this.vbar.runAction(act);
					}
				}).bind(this);
				this.autoHideBar = _.debounce(hideBarAction, autoHideTime);

			}
			this.scrollView.addEventListenerScrollView(this.onScroll, this);
		},
		onScroll: function(sender, scrollType) {
			this.updateThumbPos();
		},
		assignScrollNode: function(node) {
			var container = this.scrollView.getInnerContainer();
			container.removeAllChildren();
			this.scrollView.addChild(node);
			this.scrollView.setInnerContainerSize(cc.size(node.width, node.height));
			if (typeof node.getDirection == 'function') {
				var direction = node.getDirection();
				if (direction == 0) {
					var w = this.scrollView.width - node.width;
					var h = this.scrollView.height - node.height;
					container.setPosition(w * 0.5, h * 0.5);
				} else if (direction == 1) {
					container.y = 0;
				} else if (direction == 2) {

				} else if (direction == 3) {
					container.setPosition(this.scrollView.width - node.width, this.scrollView.height - node.height);
				} else if (direction == 4) {
					container.setPosition(this.scrollView.width - node.width, 0);
				}
			}
			this.updateThumbSize();
			if(this.hbar) this.hbar.opacity = 0;
			if(this.vbar) this.vbar.opacity = 0;
		},
		updateThumbPos: function() {
			var innerNode = this.scrollView.getInnerContainer();
			if (this.hbar) {
				var thumb = this.hbar.children[0];
				var width1 = innerNode.width - this.scrollView.width;
				var width2 = this.hbar.width - thumb.width;
				thumb.x = -innerNode.x / width1 * width2;
			}
			if (this.vbar) {
				var thumb = this.vbar.children[0];
				var height1 = innerNode.height - this.scrollView.height;
				var height2 = this.vbar.height - thumb.height;
				thumb.y = -innerNode.y / height1 * height2;
			}
			if(this.autoHideBar){
				if(this.hbar) this.hbar.opacity = 255;
				if(this.vbar) this.vbar.opacity = 255;
				this.autoHideBar();
			}
		},
		updateThumbSize: function() {
			var node = this.getScollContentNode();
			if (!node) return;
			if (this.hbar) {
				var thumb = this.hbar.children[0];
				var w = this.hbar.width * this.scrollView.width / node.width;
				this.hbar.children[0].width = w;
			}
			if (this.vbar) {
				var thumb = this.vbar.children[0];
				var h = this.vbar.height * this.scrollView.height / node.height;
				thumb.height = h;
			}
			this.updateThumbPos();
		},
		getScollContentNode: function() {
			var container = this.scrollView.getInnerContainer();
			return container.children[0];
		}
	});

	ScrollView.create = function(data) {
		var node = new ScrollView();
		node.initWithConfig(data);
		return node;
	};

	module.exports = ScrollView;
})();