text:
package com.amazonaws.services.rekognition.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Provides face metadata. In addition, it also provides the confidence in the match of this face with the input face.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class FaceMatch implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * Confidence in the match of this face with the input face.
     *

     */
    private Float similarity;

    private Face face;

    /**
     *

     * Confidence in the match of this face with the input face.
     *

     *
     * @param similarity
     *        Confidence in the match of this face with the input face.
     */

    public void setSimilarity(Float similarity) {
        this.similarity = similarity;
    }

    /**
     *

     * Confidence in the match of this face with the input face.
     *

     *
     * @return Confidence in the match of this face with the input face.
     */

    public Float getSimilarity() {
        return this.similarity;
    }

    /**
     *

     * Confidence in the match of this face with the input face.
     *

     *
     * @param similarity
     *        Confidence in the match of this face with the input face.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public FaceMatch withSimilarity(Float similarity) {
        setSimilarity(similarity);
        return this;
    }

    /**
     * @param face
     */

    public void setFace(Face face) {
        this.face = face;
    }

    /**
     * @return
     */

    public Face getFace() {
        return this.face;
    }

    /**
     * @param face
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public FaceMatch withFace(Face face) {
        setFace(face);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSimilarity() != null)
            sb.append("Similarity: ").append(getSimilarity()).append(",");
        if (getFace() != null)
            sb.append("Face: ").append(getFace());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof FaceMatch == false)
            return false;
        FaceMatch other = (FaceMatch) obj;
        if (other.getSimilarity() == null ^ this.getSimilarity() == null)
            return false;
        if (other.getSimilarity() != null && other.getSimilarity().equals(this.getSimilarity()) == false)
            return false;
        if (other.getFace() == null ^ this.getFace() == null)
            return false;
        if (other.getFace() != null && other.getFace().equals(this.getFace()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSimilarity() == null) ? 0 : getSimilarity().hashCode());
        hashCode = prime * hashCode + ((getFace() == null) ? 0 : getFace().hashCode());
        return hashCode;
    }

    @Override
    public FaceMatch clone() {
        try {
            return (FaceMatch) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.rekognition.model.transform.FaceMatchMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
/*
 * Changes for GemFireXD distributed data platform (some marked by "GemStone changes")
 *
 * Portions Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You
 * may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License. See accompanying
 * LICENSE file.
 */
package com.pivotal.gemfirexd.internal.client.net;

import com.pivotal.gemfirexd.internal.client.am.Configuration;
import com.pivotal.gemfirexd.internal.client.am.ProductLevel;
import com.pivotal.gemfirexd.internal.client.am.SqlException;

// GemStone changes BEGIN
// made abstract to enable compilation with both JDK 1.4 and 1.6
abstract
// GemStone changes END
public class NetDatabaseMetaData extends com.pivotal.gemfirexd.internal.client.am.DatabaseMetaData {

    /** True if the server supports QRYCLSIMP. */
    private boolean supportsQryclsimp_;

    private boolean supportsLayerBStreaming_;

    /**
     * True if the server supports session data caching
     */
    private boolean supportsSessionDataCaching_;

    /** True if the server supports UDTs */
    private boolean supportsUDTs_;

    public NetDatabaseMetaData(NetAgent netAgent, NetConnection netConnection) {
        // Consider setting product level during parse
        super(netAgent, netConnection, new ProductLevel(netConnection.productID_,
                netConnection.targetSrvclsnm_,
                netConnection.targetSrvrlslv_));
    }

    //---------------------------call-down methods--------------------------------

    public String getURL_() throws SqlException {
        String urlProtocol;
      if (((NetConnection)connection_).isSnappyDRDAProtocol())
        urlProtocol = Configuration.jdbcSnappyNETProtocol;
      else
        urlProtocol = Configuration.jdbcDerbyNETProtocol;
        return
                urlProtocol +

                connection_.serverNameIP_ +
                "[" +
                connection_.portNumber_ +
                "]/" +
                connection_.databaseName_;
    }

    //-----------------------------helper methods---------------------------------

    // Set flags describing the level of support for this connection.
    // Flags will be set based on manager level and/or specific product identifiers.
    // Support for a specific server version can be set as follows. For example
    // if (productLevel_.greaterThanOrEqualTo(11,1,0))
    //  supportsTheBestThingEver = true
    //
    // WARNING WARNING WARNING !!!!
    //
    // If you define an instance variable of NetDatabaseMetaData that
    // you want computeFeatureSet_() to compute, DO NOT assign an
    // initial value to the variable in the
    // declaration. NetDatabaseMetaData's constructor will invoke
    // DatabaseMetaData's constructor, which then invokes
    // computeFeatureSet_(). Initialization of instance variables in
    // NetDatabaseMetaData will happen *after* the invocation of
    // computeFeatureSet_() and will therefore overwrite the computed
    // values. So, LEAVE INSTANCE VARIABLES UNINITIALIZED!
    //
    // END OF WARNING
    protected void computeFeatureSet_() {

        // Support for QRYCLSIMP was added in 10.2.0
        if (productLevel_.greaterThanOrEqualTo(10, 2, 0)) {
            supportsQryclsimp_ = true;
        } else {
            supportsQryclsimp_ = false;
        }

        supportsLayerBStreaming_ =
            productLevel_.greaterThanOrEqualTo(10, 3, 0);

        supportsSessionDataCaching_ =
                productLevel_.greaterThanOrEqualTo(10, 4, 0);

        supportsUDTs_ =
                productLevel_.greaterThanOrEqualTo(10, 4, 0);
    }

    /**
     * Check whether the server has full support for the QRYCLSIMP
     * parameter in OPNQRY.
     *
     * @return true if QRYCLSIMP is fully supported
     */
    final boolean serverSupportsQryclsimp() {
        return supportsQryclsimp_;
    }

    final boolean serverSupportsLayerBStreaming() {
        return supportsLayerBStreaming_;
    }

    /**
     * Check if server supports session data caching
     * @return true if the server supports this
     */
    final boolean serverSupportsSessionDataCaching() {
        return supportsSessionDataCaching_;
    }

    /**
     * Check if server supports UDTs
     * @return true if the server supports this
     */
    final boolean serverSupportsUDTs() {
        return supportsUDTs_;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Recently, while attempting to set up an Elastic Beanstalk (EB) application on Amazon Web Services (AWS), I was frustrated to find that there are many disparate tutorials floating online that address the various parts of the set up process. The problem, however, is that when a particular blog post or walkthrough or whatever references another article, the installations and small underlying configurations tend to be slightly different.

You can imagine that this is kind of frustrating, especially when certain parts of the setup could be lumped together, making the whole process a lot more effortless. This repo is an attempt to do just that (and a way for me to be able to get started on future projects quickly!). As a result, it starts from the beginning (literally, from installing Python on your local computer) and takes you through the entire journey of getting an Elastic Beanstalk up and running in record time with minimal tab switching. This guide is written for use on macOS Sierra, but many parts should be easily replicated on other systems.

Below are the packages and tools I've used throughout this walkthrough. In most cases, you should be able to do these tasks if you're on different versions, but I make no guarantees that the steps below will work with different versions of these tools and packages. Here they are:
- Anaconda 4.3.0 running Python 3.6.0 (though you should also be able to follow along with virtualenv)
- Homebrew
- PostgreSQL (installed through Homebrew)
- Postgres.app (free online, link below)
- pip 9.0.1
- django 1.10.6
- psycopg2 2.7
- django-storages 1.5.2
- boto 2.46.1
- awsebcli 3.10.0

Without any further ado, let's get started!

## Step 1: Getting Anaconda on your computer

First things first: we need to get a working version of Python installed on our computer. This tutorial assumes you're using Anaconda to create your virtual environments, but you're more than welcome to skip the Anaconda installation and simply use virtualenv instead. If you want to do that, just install [Python 3.6](https://www.python.org/downloads/release/python-360/) and run `pip install virtualenv awsebcli` in terminal and skip to Step 2.

1. Download and install anaconda for Python3 from https://www.continuum.io/downloads
2. Fire up the terminal and run the following code to update your Anaconda installation (if necessary), create a new virtual environment, and install the AWS EB command line interface to allow us to interact with EB through terminal. We'll install `awsebcli` in the main Anaconda installation rather than inside the virtual environment so we can make deployments without needing to go into a virtual env in the future. If you want to keep everything inside the virtual environment, then run `source activate ebenv` before you pip install awsebcli.
```shell
$ conda update conda
$ conda create -n ebenv python=3.6
$ pip install awsebcli
```

You may want to test out your installation to make sure it works; just type `source activate ebenv` in terminal and your terminal should change from
```shell
$ My-MacBook-Pro: ~myusername$
```

to:

```shell
(ebenv) $ My-MacBook-Pro: ~myusername$
```

If that happened, then the virtual environment was configured successfully.

## Step 2: Installing Homebrew + PostgreSQL

There are multiple ways of getting PostgreSQL onto your computer, but I found that the best way to install it and make sure that all the symlinks are in place is through Homebrew. The installer from PostgreSQL's own website was quite frustrating as I spent a while trying to get `psql` to do anything. Eventually, I gave up and just went with Homebrew instead. Conveniently, that's also where you'll get your git installation for version control, so it's really a win-win. Plus, I love Homebrew's little beer emojis as it "brews" your apps. :beers:

1. If it's not open already, fire up the terminal and run the following:
```shell
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ brew install postgresql
$ brew install git
```
2. Download and install [Postgres.app](https://postgresapp.com/). This will help you easily run a local PostgreSQL server.
3. Launch the Postgres.app.
4. Check to make sure that the server port is `5432` from Server Settings.
5. Initialize the server by pressing "Start".
6. Now, go back to terminal. We're going to run the following, which will let you:
  1. Open a postgres command line interface
  2. List all of the the databases currently available
  3. Create a new database called `maindb` that we'll use throught the rest of this tutorial
  4. Ensure that the right users exist in the database

```shell
$ psql
$ \list
$ CREATE DATABASE maindb ENCODING=utf8;
$ SELECT * FROM pg_user;
```

7. If the user `postgres` exists, then run `ALTER USER postgres PASSWORD 'postgres';`
8. If the user `postgres` does not exist, then run `CREATE USER postgres PASSWORD 'postgres';`
9. Quit the postgres cli with `\q` and go back to terminal.
```
Hopefully, you got no errors during that entire process. If that's the case, let's move on to create a virtual environment and begin installing the tools we'll need to make this happen!

## Step 3: Initializing virtualenv and creating a local Django installation

Now, let's start creating our django server! First things first: we want to make sure we have all the right packages in place. Run the following in terminal:
```shell
$ source activate ebenv
$ pip install django, django-storages, psycopg2, boto
$ django-admin startproject ebdjango
$ cd ebdjango
$ nano ebdjango/settings.py
```

Now, your terminal should be in editor mode with `settings.py` in place. Alternatively, feel free to open up `settings.py` with your favorite text editor (shoutout to [Sublime](sublimetext.com)). Once the file is open, continue following these steps. Replace `DATABASES` with the following snippet. You'll notice that the part in the first `if` statement refers to `os.environ`. This will let us link up to AWS' Relational Database Service (RDS), which we'll use to run our databases off of.
```python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'maindb',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
```

eplace `ALLOWED_HOSTS` with the following snippet, changing `.example.com` with your own domain, if applicable.
```python
ALLOWED_HOSTS = ['.elasticbeanstalk.com',
                 'localhost',
                 '127.0.0.1',
                 '.example.com']
```

This will let you run the website off AWS, locally, and through your domain without getting any annoying errors. Lastly:
1. Add `storages` to `INSTALLED_APPS`
2. Update timezone with your timezone, such that you get something like `TIME_ZONE = 'America/New_York'`
3. Change We're done with `settings.py` for now, time to save and close (Ctrl+X, Y, Enter). If you were using a text editor, go back to terminal and run the following:
```shell
$ mkdir .ebextensions
$ nano .ebextensions/01_packages.config
```

This lets us create a directory where we'll tell EB to install certain packages to your Elastic Compute Cloud (EC2) installations. Time for a quick sidebar for those who are new to Elastic Beanstalk or to AWS in general about the basic philosophy of EB. In a traditional EC2 server, you have individual instances running your website. These instances need to be maintained individually and are limited in how automatically they can be scaled should, say, your website suddenly experience a significant jump in traffic. If you're like me, you dread the idea of having to closely monitor your EC2 instances and worry about whether you're using a sufficient amount of resources, because you want to focus on the product itself. AWS Elastic Beanstalk is Amazin's wonderful solution to this problem: rather than set up individual EC2 instances, RDS databases, and S3 buckets, EB gives you a convenient way to set them all up in one go.

An important difference here, in practice, is how you configure instances. For this tutorial, you need to make sure PostgreSQL is installed on your EC2 instances. In a traditional EC2 setup, you'd just SSH into the EC2 instance and use something like `yum install postgresql95`. This doesn't work so well with EB, as when the beanstalk auto-scales your instances up or down, all changes made to individual instances get destroyed, so you'd have to SSH into every new instance and reinstall the dependencies lest your website stop working, over and over and over again. Not fun. Instead, you use `.config` files that are placed into the folder we just created, `.ebextensions` and instruct the EB to make sure that all new EC2 instances have the pre-requisite tools and apps installed as they are deployed. Awesome, right? :bowtie:

To do this, copy the following code, go back to your terminal, and paste it into 01_packages.config:
```shell
packages:
  yum:
    git: []
    postgresql95: []
    postgresql95-devel: []
    postgresql95-server: []
    postgresql95-contrib: []
    postgresql95-docs: []
```

Save and close. Now, type:
```shell
$ nano .ebextensions/django.config
```

Into this new config file, paste the following, save and close:

```shell
option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: ebdjango.settings
    PYTHONPATH: $PYTHONPATH
  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango/wsgi.py
```

In the above, we instruct the server to correctly use the Django configuration. To make sure that the the right python packages are installed onto the EC2 instances, we also want to make sure that we store a list of the required packages. To do so, enter:
```shell
$ pip freeze > requirements.txt
```

To make your life a little easier, it might be helpful to edit the `requirements.txt` and remove the versions to make sure that there are no errors during installation in case `pip` is unable to find the exact version of the package you're looking for. Obviously, this is potentially dangerous as different versions might introduce/remove features you're using, so exercise best judgment here (i.e. leave them if you're unsure).

## Step 3: Creating an AWS EB application, environemnts, and deployment

Now that we have a basic working version of the Django setup written, go back to the terminal and type the following:
```shell
$ eb init

Select a default region
1) us-east-1 : US East (N. Virginia)
2) us-west-1 : US West (N. California)
3) us-west-2 : US West (Oregon)
4) eu-west-1 : EU (Ireland)
5) eu-central-1 : EU (Frankfurt)
6) ap-south-1 : Asia Pacific (Mumbai)
7) ap-southeast-1 : Asia Pacific (Singapore)
8) ap-southeast-2 : Asia Pacific (Sydney)
9) ap-northeast-1 : Asia Pacific (Tokyo)
10) ap-northeast-2 : Asia Pacific (Seoul)
11) sa-east-1 : South America (Sao Paulo)
12) cn-north-1 : China (Beijing)
13) us-east-2 : US East (Ohio)
14) ca-central-1 : Canada (Central)
15) eu-west-2 : EU (London)
(default is 3):
```

Select whatever is closest to you.

```shell
(aws-access-id):
```

Here, you need to create an IAM account if you haven't already. Before you do anything on terminal, go to the IAM Management Console and [create a new user](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html). For simplicity, give the user `AWSElasticBeanstalkFullAccess` permissions. You may want to tweak this later on. Additionally, once you're all set up, you probably want to create groups. give permissions to those and include users within them to make user management easier. For info on groups, click [here](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_create.html). Once you've created your user, copy the `Access key ID` and paste it in your terminal. Don't close that page, as you'll also need the `Secret access key` for the next step, which is:
```shell
(aws-secret-key):
```

After you enter your secret key, you'll get a new prompt:
```shell
Enter Application Name
(default is "django-postgresql-awsebcli"):
```

You can just enter and continue for this exercise. In the future, just name your application something memorable. Next:

```shell
It appears you are using Python. Is this correct?
(Y/n):
```

2 guesses: which is the right answer? SPOILER ALERT: type `Y` and continue.

```shell
Select a platform version.
1) Python 3.4
2) Python
3) Python 2.7
4) Python 3.4 (Preconfigured - Docker)
(default is 1):
```

Press enter and continue (we want to be using Python 3.x).

```shell
Note: Elastic Beanstalk now supports AWS CodeCommit; a fully-managed source control service. To learn more, see Docs: https://aws.amazon.com/codecommit/
Do you wish to continue with CodeCommit? (y/N) (default is n):
```

If you want to use AWS' version control service press y, otherwise just press enter and continue.

```shell
Do you want to set up SSH for your instances?
(Y/n):
```

As mentioned earlier, SSH'ing into your EC2 instances in an EB setup is not a very good idea, so I select `n` and continue. Now that application is set up, we'll go ahead and get our environments going. Type the following:
```shell
$ eb create
Enter Environment Name
(default is django-postgresql-awsebcli-dev):
```

Again, make it memorable. If you want to configure a staging/test/qa/etc. server in the future, just change the last bit from `-dev` and you're good to go. Press enter and now you'll see:
```shell
Enter DNS CNAME prefix
(default is django-postgresql-awsebcli-dev):
```

If this is already installed, it won't work so change this up a little until the ebcli accepts it. Next up:
```shell
Select a load balancer type
1) classic
2) application
(default is 1):
```

Press enter and keep going here and the EB CLI will begin to work its magic, creating all of your environments including EC2 instances, security groups, a load balancer, and more! This usually takes around 5 minutes. Once that's done, we want to deploy our newly minted Django app onto our EB application! Type the following:
```shell
$ eb open
```

![Django splash](https://github.com/haldunanil/ebdjango/blob/master/first-debug.png)

Congratulations, you just successfully deployed a Django site to AWS Elastic Beanstalk! Now, go celebrate, you champion.

## Step 4: Setting up RDS and a new Django app to let you login to admin

Now that the Django website is running, let's set up an RDS instance to connect our database! Go back to the terminal and type the following (or manually navigate to the EB console):
```shell
$ eb console
```

On the left hand side, you'll see a button that reads `Configuration`, press that and scroll to the bottom of the page that just popped up. Press `Create a new RDS database`. On the next page, enter values such that the page looks like this:

![RDS setup](https://github.com/haldunanil/ebdjango/blob/master/rds-setup.png)

Once you save the changes, EB will create the RDS. Afterward, go back to the terminal and type:

```shell
$ python manage.py migrate
$ python manage.py createsuperuser
Username (leave blank to use 'XXX'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
```

Now, we want to make sure that all the pieces of the admin interface works properly. To make sure that happens, add `STATIC_ROOT = 'static'` to the end of `settings.py`. Next, run the following:

```shell
$ python manage.py collectstatic
```

Now, let's set up our RDS server. Navigate to `settings.py` and replace the `DATABASE` section with:

```python
if 'RDS_DB_NAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'maindb',
            'USER': 'postgres',
            'PASSWORD': 'postgres',
            'HOST': 'localhost',
            'PORT': '5432',
        }
    }
```

Now, we need to create our first app. For the sake of simplicity, the only purpose of this app will be to create superusers during EB initialization. Of course, in your instance, you can use this app for other purposes as well. Go back to terminal and type these:

```shell
$ python manage.py startapp su
$ mkdir su/management
$ mkdir su/management/commands
$ nano su/management/__init__.py             # leave empty, save and close
$ nano su/management/commands/__init__.py    # leave empty, save and close
$ nano su/management/commands/createsu.py
```

Once you've started editing the `createsu.py`, paste the following:

```python
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

class Command(BaseCommand):

    def handle(self, *args, **options):
        if not User.objects.filter(username="admin").exists():
            User.objects.create_superuser("admin", "", "admin")
```

Reopen `settings.py` and enter `'su'` into `INSTALLED_APPS` to make sure that our Django server can use the superuser creator that we just wrote. Next, run the following:

```shell
$ nano .ebextensions/02_rds.config
```

Once you've begun editing, paste the following text in there:

```shell
container_commands:
  01_migrate:
    command: "python manage.py migrate"
    leader_only: true
  02_collectstatic:
    command: "python manage.py collectstatic --noinput"
  03_createsu:
    command: "python manage.py createsu"
    leader_only: true
```

We're at the homestretch! Run the following to deploy the updated version of our website to EB:

```shell
$ git add .
$ git commit -m "Migrate db, add staticfiles and createsu"
$ eb deploy
```

To check that everything works, let's now navigate to `XXX.elasticbeanstalk.com/admin` where `XXX` is the DNS name we've been using for our EB environment. Assuming everything went well, enter `admin` as your username and password to see the following page:

![Admin page](https://github.com/haldunanil/ebdjango/blob/master/admin.png)

## Step 5: Setting up S3 and hooking it up to the Django config

Before proceeding, let's recall the core philosophy of AWS Elastic Beanstalk: EC2 instances can (and will) be auto-scaled depending on the volume of traffic coming to your website. As a result, we generally want to refrain from making any edits directly to any EC2 instance or store any static files there. As your website gets more and more pieces and content up, it'll be slower and more costly to attempt to serve everything from the EC2 instances. And what about other pieces, like profile images that may be uploaded by users? This is where S3 comes in: S3 provides a way to store static files and media independently of the EC2 instances, making sure that if/when EC2 instances are destroyed or spun up, all of your data continues to be available and also is served quickly on demand. Added bonus: when you configure CloudFront to work with your S3 instance, you can speed up the delivery of your static content even further!

Now, let's set this up. Start by adding the following to the bottom of your `settings.py` file:

```python
# S3 hookup

AWS_STORAGE_BUCKET_NAME = 'XXX'
AWS_ACCESS_KEY_ID = 'YYY'
AWS_SECRET_ACCESS_KEY = 'ZZZ'

# Tell django-storages that when coming up with the URL for an item in S3 storage, keep
# it simple - just use this domain plus the path. (If this isn't set, things get complicated).
# This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it.
# We also use it in the next setting.
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

# This is used by the `static` template tag from `static`, if you're using that. Or if anything else
# refers directly to STATIC_URL. So it's safest to always set it.
STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN

# Tell the staticfiles app to use S3Boto storage when writing the collected static files (when
# you run `collectstatic`).
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
```

Now, we need to configure Cross-Origin Resource Sharing (CORS) on our S3 bucket to make sure that browsers visiting our website know to interact with resources (like images, CSS, JS, etc. files) coming from a different domain. To do so:
1. Go back to the S3 bucket
2. Open up `Properties`
3. Click `Add CORS Configuration`
4. Paste the following in there:

```html
<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
```

Note: it might already be there (it was in my case), in which case, just verify that it matches up.

Now, we've ensured that `static` files (the ones _we_ upload) are in S3. Next up, we want to ensure that `media` files (uploaded by _users_) also go on S3. We also want to make sure that they don't collide and start overwriting each other. There are two approaches to making this happen: 1) create separate directories in the S3 bucket for your `static` files and your `media` files or 2) create separate buckets for the two. To keep things together, we'll follow the first one.

Now, let's go back to terminal, ensure that we're in the root folder `ebdjango` (the one with `manage.py` in it, NOT the one with `settings.py` in it). Let's do the following:

```shell
$ nano custom_storages.py
```

Into that file, paste the following:

```python
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

class StaticStorage(S3BotoStorage):
    location = settings.STATICFILES_LOCATION

class MediaStorage(S3BotoStorage):
    location = settings.MEDIAFILES_LOCATION
```

Save and close the file. As explained above, this file will route all static files into a folder called `/static/` and all the media files into a folder called `/media/`. We also need to make sure that our `settings.py` file recognizes this new file. To make it do so, we insert the following:

```python
STATICFILES_LOCATION = 'static'
STATICFILES_STORAGE = 'custom_storages.StaticStorage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

MEDIAFILES_LOCATION = 'media'
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
```

Let's deploy our website! Run the following:

```shell
$ eb deploy
$ eb open
```

Inspect individual elements to see that they're pulling CSS files and such from S3. If that's the case, you've done it!

## Step 6: Compressing elements to increase delivery speed

To make sure that everything happens quickly, let's set up gzip compression. To do so, run the following in terminal:

```shell
$ nano .ebextensions/03_apache.config
```

In that file, paste:

```shell
container_commands:
  01_setup_apache:
    command: "cp .ebextensions/enable_mod_deflate.conf /etc/httpd/conf.d/enable_mod_deflate.conf"
```

As you'll notice, we're referring to a file called `enable_mdo_deflate.conf`. Let's add that too:

```shell
$ nano .ebextensions/enable_mod_deflate.conf
```

Into _that_ file, insert:

```html
# mod_deflate configuration
<IfModule mod_deflate.c>
  # Restrict compression to these MIME types
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE application/xml+rss
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/css
  # Level of compression (Highest 9 - Lowest 1)
  DeflateCompressionLevel 9
  # Netscape 4.x has some problems.
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  # Netscape 4.06-4.08 have some more problems
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  # MSIE masquerades as Netscape, but it is fine
  BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
<IfModule mod_headers.c>
  # Make sure proxies don't deliver the wrong content
  Header append Vary User-Agent env=!dont-vary
</IfModule>
</IfModule>
```

Save and close. This should help speed up the delivery of your website!

## Step 7: Configuring the load balancer to route all traffic through HTTPS

Now that everything's up, we want to secure our website. Especially for websites where there's logins and such, using `HTTPS` is going to be an important aspect of making sure nobody's passwords get compromised. The great thing about AWS Elastic Beanstalk is that it enables a load balancer for you, which we'll use to route all traffic through `HTTPS`-- even if people use URLs that aren't secure. Let's get started!

First, create an SSL certificate through AWS Certificate Manager (process is [here](http://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request.html)). Next, copy the ARN of the SSL certificate you created. Now, going back to terminal (remember to have it open in the root directory) and type:

```shell
$ nano .ebextensions/securelistener.config
```

Into the file, paste the following (making sure to replace `ARN_KEY_HERE` with the ARN key you copied moments ago):

```shell
option_settings:
  aws:elb:listener:443:
    SSLCertificateId: ARN_KEY_HERE
    ListenerProtocol: HTTPS
    InstancePort: 80
```

Save and close-- you just configured your load balancer to accept HTTPS requests! Now, we add the Apache config that redirects all calls (whether it's `HTTP` or `HTTPS`) to HTTPS for every page. Start by creating an apache config file:

```shell
$ nano .ebextensions/04_apache.config
```

Add the following:

```shell
files:
  "/etc/httpd/conf.d/ssl_rewrite.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      RewriteEngine On
      <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'">
      RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
      </If>
```

In terminal, type:

```shell
$ eb deploy
$ eb open
```

Note that, unless you configure your DNS name with an ALIAS record to redirect to the EB application, the security note on the right-hand side will say `Not Secure`, since your security certificate does not include "elasticbeanstalk.com" domain(s). Let's fix that in the next section!

## Step 8: Make sure people can find you easily on the interwebz

We want to make sure that we can easily be found on the internet. You don't get to Google by typing `google-prod.elasticbeanstalk.com` so it doesn't make sense to do that with your website either. Assuming you've already purchased your own domain, here's how to assign proper forwarding for your website.

1. Go to AWS' `Route 53`
2. On the left-hand section, click on `Hosted zones`
3. Again, assuming you've already imported your main domain and configured your `NS` records (and if not, you can get started [here](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/welcome-domain-registration.html)), click on your domain
4. Now, click on `Create Record Set`
5. If you want to create a subdomain (like `test.example.com`, add its name in the `Name` section), if not skip to the next step
6. Leave `Type` as "A - IPv4 address"
7. Check "Yes" for `Alias`
8. For `Alias Target`, find "Elastic Beanstalk environments" and click the text underneath
9. Leave `Routing Policy` as "Simple"
10. Leave `Evaluate Target Health` as "No"
11. Click `Create`

Wait a few moments and navigate to the `Name` you just configured. You should see the home page for your website and your HTTPS tag should now say `Secured` with a green lock sign next to it. Congrats, your website is online! :confetti_ball: :

## Step 9: Goodbye and cleanup

With that, you probably want to clean up after yourself. Once you're done playing around with your website and basking in its glory, type:

```shell
$ eb terminate ebdjango-dev
```

The above will delete your environment, but NOT your application. For that (and to be sure):
1. Go to the Elastic Beanstalk Console
2. Make sure you're looking at the page titled `All Applications`
3. Click the `Actions` button on the right
4. Click `Delete Application`

AWS will take care of the rest. The application should disappear completely from your console within ~1 hour. That's it, you're done and all the additional resources created for you (EC2 instances, the RDS instance, etc. _excluding_ your S3 bucket) should also be deleted as part of the EB deletion process.

## Step 10: Quick start and closing thoughts

You're probably thinking to yourself: quick start? Now?! Yes. The reason why I put it down here is so you would follow along and learn how to deploy an EB application all by yourself rather than just copying off me. Give a man a fish, he eats for a day. _Teach_ a man how to fish...

In the future and for a quick start (or if you were lazy and just skipped straight down here), simply:
1. Fork the GitHub repo on this page
2. Open a console in the root directory
3. Run `$ eb init` and follow the steps in Step 3 above
4. Run `$ eb create` and keep following the steps (you should see a database connection error, don't worry about that)
5. Go to your Elastic Beanstalk console and follow the instructions at the beginning of Step 4 to create an RDS instance
6. Open up your `settings.py` file and edit your S3 location and permissions at the bottom; specifically the fields that are marked `XXXXX`, `YYYYY`, and `ZZZZZ`
7. Once everything's in place, deploy using `$ eb deploy`; you should get no errors!
8. Follow Step 8 to configure your DNS alias to forward to your Elastic Beanstalk instance

And you're done! See? Easy :)

If you have any unforeseen issues or errors while doing the above, please drop me a line and I'll try to fix whatever the issue may be. Happy web developing!


text:
#include "test_precomp.hpp"

namespace opencv_test { namespace {

#if defined(HAVE_OPENCV_XFEATURES2D) && defined(OPENCV_ENABLE_NONFREE)

TEST(SurfFeaturesFinder, CanFindInROIs)
{
    Ptr<Feature2D> finder = xfeatures2d::SURF::create();
    Mat img  = imread(string(cvtest::TS::ptr()->get_data_path()) + "cv/shared/lena.png");

    vector<Rect> rois;
    rois.push_back(Rect(0, 0, img.cols / 2, img.rows / 2));
    rois.push_back(Rect(img.cols / 2, img.rows / 2, img.cols - img.cols / 2, img.rows - img.rows / 2));

    // construct mask
    Mat mask = Mat::zeros(img.size(), CV_8U);
    for (const Rect &roi : rois)
    {
        Mat(mask, roi) = 1;
    }

    detail::ImageFeatures roi_features;
    detail::computeImageFeatures(finder, img, roi_features, mask);

    int tl_rect_count = 0, br_rect_count = 0, bad_count = 0;
    for (const auto &keypoint : roi_features.keypoints)
    {
        if (rois[0].contains(keypoint.pt))
            tl_rect_count++;
        else if (rois[1].contains(keypoint.pt))
            br_rect_count++;
        else
            bad_count++;
    }

    EXPECT_GT(tl_rect_count, 0);
    EXPECT_GT(br_rect_count, 0);
    EXPECT_EQ(bad_count, 0);
}

#endif // HAVE_OPENCV_XFEATURES2D && OPENCV_ENABLE_NONFREE

TEST(ParallelFeaturesFinder, IsSameWithSerial)
{
    Ptr<Feature2D> para_finder = ORB::create();
    Ptr<Feature2D> serial_finder = ORB::create();
    Mat img  = imread(string(cvtest::TS::ptr()->get_data_path()) + "stitching/a3.png", IMREAD_GRAYSCALE);

    detail::ImageFeatures serial_features;
    detail::computeImageFeatures(serial_finder, img, serial_features);

    vector<Mat> imgs(50, img);
    vector<detail::ImageFeatures> para_features(imgs.size());
    detail::computeImageFeatures(para_finder, imgs, para_features);  // FIXIT This call doesn't use parallel_for_()

    // results must be the same
    Mat serial_descriptors;
    serial_features.descriptors.copyTo(serial_descriptors);
    for(size_t i = 0; i < para_features.size(); ++i)
    {
        SCOPED_TRACE(cv::format("i=%zu", i));
        EXPECT_EQ(serial_descriptors.size(), para_features[i].descriptors.size());
#if 0 // FIXIT ORB descriptors are not bit-exact (perhaps due internal parallel_for usage)
        ASSERT_EQ(0, cv::norm(u_serial_descriptors, para_features[i].descriptors, NORM_L1))
            << "serial_size=" << u_serial_descriptors.size()
            << " par_size=" << para_features[i].descriptors.size()
            << endl << u_serial_descriptors.getMat(ACCESS_READ)
            << endl << endl << para_features[i].descriptors.getMat(ACCESS_READ);
#endif
        EXPECT_EQ(serial_features.img_size, para_features[i].img_size);
        EXPECT_EQ(serial_features.keypoints.size(), para_features[i].keypoints.size());
    }
}

TEST(RangeMatcher, MatchesRangeOnly)
{
    Ptr<Feature2D> finder = ORB::create();

    Mat img0 = imread(string(cvtest::TS::ptr()->get_data_path()) + "stitching/a1.png", IMREAD_GRAYSCALE);
    Mat img1 = imread(string(cvtest::TS::ptr()->get_data_path()) + "stitching/a2.png", IMREAD_GRAYSCALE);
    Mat img2 = imread(string(cvtest::TS::ptr()->get_data_path()) + "stitching/a3.png", IMREAD_GRAYSCALE);

    vector<detail::ImageFeatures> features(3);

    computeImageFeatures(finder, img0, features[0]);
    computeImageFeatures(finder, img1, features[1]);
    computeImageFeatures(finder, img2, features[2]);

    vector<detail::MatchesInfo> pairwise_matches;
    Ptr<detail::FeaturesMatcher> matcher = makePtr<detail::BestOf2NearestRangeMatcher>(1);

    (*matcher)(features, pairwise_matches);

    // matches[1] will be image 0 and image 1, should have non-zero confidence
    EXPECT_NE(pairwise_matches[1].confidence, .0);

    // matches[2] will be image 0 and image 2, should have zero confidence due to range_width=1
    EXPECT_DOUBLE_EQ(pairwise_matches[2].confidence, .0);
}

}} // namespace


text:
<?php

namespace app\models\Fregat;

use Yii;

/**
 * This is the model class for table "spismat".
 *
 * @property string $spismat_id
 * @property integer $id_mol
 * @property string $spismat_date
 *
 * @property Employee $idMol
 * @property Spismatmaterials[] $spismatmaterials
 */
class Spismat extends \yii\db\ActiveRecord
{
    public $spismat_spisinclude;
    public $period;
    public $period_beg;
    public $period_end;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'spismat';
    }

    public function attributes()
    {
        // add related fields to searchable attributes
        return array_merge(parent::attributes(), [
            'period_beg',
            'period_end',
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_mol', 'spismat_date'], 'required'],
            [['id_mol', 'spismat_spisinclude'], 'integer'],
            [['spismat_date', 'period_beg', 'period_end'], 'date', 'format' => 'yyyy-MM-dd'],
            [['spismat_date', 'period_beg', 'period_end'], 'compare', 'compareValue' => date('Y-m-d'), 'operator' => '<=', 'message' => 'Значение {attribute} должно быть меньше или равно значения «' . Yii::$app->formatter->asDate(date('Y-m-d')) . '».'],
            //   [['period_beg'], 'compare', 'compareAttribute' => 'period_end', 'operator' => '<=', 'message' => 'Дата начала периода должна быть меньше или равно даты окончания периода'],
            [['period_beg', 'period_end'], 'DateRangeValid'],
            [['id_mol'], 'exist', 'skipOnError' => true, 'targetClass' => Employee::className(), 'targetAttribute' => ['id_mol' => 'employee_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'spismat_id' => 'Номер ведомости',
            'id_mol' => 'Материально-ответственное лицо',
            'spismat_date' => 'Дата ведомости',
            'spismat_spisinclude' => 'Включить в ведомость списанные материалы',
            'period' => 'Включить в ведомость материалы, установленные в данный период',
            'period_beg' => 'Начало перода',
            'period_end' => 'Окончание периода',
        ];
    }

    public function DateRangeValid($attribute)
    {
        if (empty($this->period_beg))
            $this->addError($attribute, 'Заполните дату начала периода');

        if (empty($this->period_end))
            $this->addError($attribute, 'Заполните дату окончания периода');

        if (!empty($this->period_beg) && !empty($this->period_end)) {
            if ($this->period_beg > $this->period_end)
                $this->addError($attribute, 'Дата начала периода не может быть больше даты окончания');
        }
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdMol()
    {
        return $this->hasOne(Employee::className(), ['employee_id' => 'id_mol'])->from(['idMol' => Employee::tableName()]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSpismatmaterials()
    {
        return $this->hasMany(Spismatmaterials::className(), ['id_spismat' => 'spismat_id'])->from(['spismatmaterials' => Spismatmaterials::tableName()]);
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

namespace Microsoft.Azure.WebJobs.Host.FunctionalTests.TestDoubles
{
    internal class MemoryCloudAppendBlobStream : CloudBlobStream
    {
        private readonly MemoryStream _buffer;
        private readonly Action<byte[]> _commitAction;

        private bool _committed;
        private bool _disposed;

        public MemoryCloudAppendBlobStream(Action<byte[]> commitAction)
        {
            _buffer = new MemoryStream();
            _commitAction = commitAction;
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return _buffer.CanWrite; }
        }

        public override long Length
        {
            get { throw new NotSupportedException(); }
        }

        public override long Position
        {
            get { return _buffer.Position; }
            set { throw new NotSupportedException(); }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!_disposed)
                {
                    if (!_committed)
                    {
                        Commit();
                    }

                    _buffer.Dispose();
                    _disposed = true;
                }
            }

            base.Dispose(disposing);
        }

        public override void Commit()
        {
            ThrowIfDisposed();
            ThrowIfCommitted();

            _commitAction.Invoke(_buffer.ToArray());
            _committed = true;
        }

        public override ICancellableAsyncResult BeginCommit(AsyncCallback callback, object state)
        {
            Commit();

            ICancellableAsyncResult result = new CompletedCancellableAsyncResult(state);

            if (callback != null)
            {
                callback.Invoke(result);
            }

            return result;
        }

        public override void EndCommit(IAsyncResult asyncResult)
        {
            // Always completes synchronously
        }

        public override void Flush()
        {
            _buffer.Flush();
        }

        public override ICancellableAsyncResult BeginFlush(AsyncCallback callback, object state)
        {
            Flush();

            ICancellableAsyncResult result = new CompletedCancellableAsyncResult(state);

            if (callback != null)
            {
                callback.Invoke(result);
            }

            return result;
        }

        public override void EndFlush(IAsyncResult asyncResult)
        {
            // Always completes synchronously
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            ThrowIfDisposed();
            ThrowIfCommitted();
            _buffer.Write(buffer, offset, count);
        }

        private void ThrowIfCommitted()
        {
            if (_committed)
            {
                throw new InvalidOperationException("The blob stream has already been committed once.");
            }
        }

        private void ThrowIfDisposed()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(null);
            }
        }
    }
}


text:
#pragma once
#include <aws/route53resolver/Route53Resolver_EXPORTS.h>
#include <aws/route53resolver/Route53ResolverRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Route53Resolver
{
namespace Model
{

  /**
   */
  class AWS_ROUTE53RESOLVER_API GetResolverRulePolicyRequest : public Route53ResolverRequest
  {
  public:
    GetResolverRulePolicyRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetResolverRulePolicy"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline GetResolverRulePolicyRequest& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline GetResolverRulePolicyRequest& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
The ID of the Resolver rule that you want to get the Resolver rule policy
     * for.

     */
    inline GetResolverRulePolicyRequest& WithArn(const char* value) { SetArn(value); return *this;}

  private:

    Aws::String m_arn;
    bool m_arnHasBeenSet;
  };

} // namespace Model
} // namespace Route53Resolver
} // namespace Aws


text:
> API-compatible in-memory sham for browser Storage

## Install

```
$ npm install --save storage-sham
```

## Usage

```js
var Storage = require('storage-sham')
var storage = Storage()

storage.setItem('foo', 'bar')
storage.getItem('foo')
//=> bar
```

## Related

* Adapted from [node-localStorage](https://github.com/coolaj86/node-localStorage)

## License

MIT © [Ben Drucker](http://bendrucker.me)


text:
<?php

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HouseControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/index');
    }

    public function testAddhouse()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/addHouse');
    }

    public function testViewhouse()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/viewHouse');
    }

}


text:
#ifndef CHMHMapArc_H
#define CHMHMapArc_H

#include <mrpt/slam/CSensoryFrame.h>
#include <mrpt/hmtslam/CHMHMapNode.h>
#include <mrpt/utils/CSerializable.h>

namespace mrpt
{
	namespace hmtslam
	{
		using namespace mrpt::slam;
		class HMTSLAM_IMPEXP CHierarchicalMHMap;

		/** A class for representing an arc between two nodes in a hierarchical, multi-hypothesis map.
		 *   The arc itself will be considered only if some given hypothesisID matchs its own ID.
		 * \note Create objects by invoking the class factory "::Create"
		 *
		 * \sa CHierarchicalMHMap,CHMHMapNode
		  * \ingroup mrpt_hmtslam_grp
		 */
		class HMTSLAM_IMPEXP CHMHMapArc : public mrpt::utils::CSerializable
		{
			friend class HMTSLAM_IMPEXP CHierarchicalMHMap;
			friend class HMTSLAM_IMPEXP CHMHMapNode;
			friend class HMTSLAM_IMPEXP CHierarchicalMapMHPartition;
			friend class TArcList;

			// This must be added to any CSerializable derived class:
			DEFINE_SERIALIZABLE( CHMHMapArc )

		public:
			/** The hypothesis IDs under which this arc exists.
			  */
			THypothesisIDSet		m_hypotheses;

		protected:
			/** The origin/target nodes for this arc.
			  */
			CHMHMapNode::TNodeID	m_nodeFrom, m_nodeTo;

			/** The hierarchical graph in which this object is into.
			  */
			safe_ptr<CHierarchicalMHMap>	m_parent;

			 /** Event handler to be called just before a node is being destroyed: it should be called only for nodes involved in the arc, altought other cases must be handled without effects
			  *   When a node involved in the arc is delected, the corresponding pointer in the arc will be set to NULL and the arc is no longer a valid one.
			  */
			 void  onNodeDestruction(CHMHMapNode *node);

		private:
			/** Private constructor (see ::Create class factory)
			  */
			CHMHMapArc(
				const CHMHMapNode::TNodeID		&from =0,
				const CHMHMapNode::TNodeID		&to   =0,
				const THypothesisIDSet			&hyps = THypothesisIDSet(),
				CHierarchicalMHMap		*parent=NULL);

			/** Alternative constructor, using pointers for convenience.
			  */
			CHMHMapArc(
				CHMHMapNodePtr		&from,
				CHMHMapNodePtr		&to,
				const THypothesisIDSet		&hyps,
				CHierarchicalMHMap			*parent);

		public:
			/** Constructor from node IDs
			  */
			static CHMHMapArcPtr Create(
				const CHMHMapNode::TNodeID		&from,
				const CHMHMapNode::TNodeID		&to,
				const THypothesisIDSet			&hyps = THypothesisIDSet(),
				CHierarchicalMHMap		*parent=NULL);

			/** Alternative constructor, using pointers for convenience.
			  */
			static CHMHMapArcPtr Create(
				CHMHMapNodePtr		&from,
				CHMHMapNodePtr		&to,
				const THypothesisIDSet		&hyps,
				CHierarchicalMHMap			*parent);

			/** Destructor
			  */
			virtual ~CHMHMapArc();

			/** Return the starting node of the arc:
			  */
			CHMHMapNode::TNodeID	 getNodeFrom() const { ASSERT_(m_nodeFrom!=AREAID_INVALID); return m_nodeFrom; }

			/** Return the ending node of the arc:
			  */
			CHMHMapNode::TNodeID	 getNodeTo() const { ASSERT_(m_nodeTo!=AREAID_INVALID); return m_nodeTo; }

			/** The type of the arc, the possibilities are:
					- "Membership": for abstractions
					- "Navegability"
					- "RelativePose"
			  */
			utils::CTypeSelector			m_arcType;

			/** The annotations of the arc, see the general description of the class for possible properties and values.
			  */
			utils::CMHPropertiesValuesList	m_annotations;

		}; // End of class def.

	} // End of namespace
} // End of namespace

#endif


text:
import {currentIdentity} from "../lib/identity";
import spinner from "../lib/spin";
import merge from "lodash/merge";

const apiPath = "/pdp/api";
let csrfToken = null;

function apiUrl(path) {
    return apiPath + path;
}

function validateResponse(res) {
    spinner.stop();

    if (!res.ok) {
        const error = new Error(res.statusText);
        error.response = res;
        throw error;
    }

    csrfToken = res.headers.get("x-csrf-token");

    const sessionAlive = res.headers.get("x-session-alive");

    if (sessionAlive !== "true") {
        window.location.reload(true);
    }

    return res;
}

export function parseJson(res) {
    return res.json();
}

function validFetch(path, options) {
    const contentHeaders = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": csrfToken
    };

    let identityHeaders = {};
    if (currentIdentity) {
        identityHeaders = {
            "X-IDP-ENTITY-ID": currentIdentity.idpEntityId,
            "X-UNSPECIFIED-NAME-ID": currentIdentity.unspecifiedNameId,
            "X-DISPLAY-NAME": currentIdentity.displayName,
            "X-IMPERSONATE": true
        };
    }

    const fetchOptions = merge({}, {headers: {...contentHeaders, ...identityHeaders}}, options, {
        credentials: "same-origin"
    });

    spinner.start();
    return fetch(apiUrl(path), fetchOptions)
        .catch(err => {
            spinner.stop();
            throw err;
        })
        .then(validateResponse);
}

export function fetchJson(path, options = {}) {
    return validFetch(path, options)
        .then(parseJson);
}

function postJson(path, body, options = {}) {
    return validFetch(path, Object.assign({}, {method: "post", body: JSON.stringify(body)}, options));
}

function putJson(path, body, options = {}) {
    return validFetch(path, Object.assign({}, {method: "put", body: JSON.stringify(body)}, options));
}

export function fetchDelete(path) {
    return validFetch(path, {method: "delete"});
}

export function getUserData() {
    return fetchJson("/internal/users/me");
}

export function reportError(error) {
    return postJson("/internal/users/error", error);
}

export function getIdentityProviders() {
    return fetchJson("/internal/identityProviders");
}

export function getScopedIdentityProviders() {
    return fetchJson("/internal/identityProviders/scoped");
}

export function getServiceProviders() {
    return fetchJson("/internal/serviceProviders");
}

export function getAllowedAttributes() {
    return fetchJson("/internal/attributes");
}

export function getAllowedLoas() {
    return fetchJson("/internal/loas");
}

export function ipInfo(ipAddress, networkPrefix) {
    if (networkPrefix) {
        return fetchJson("/internal/ipinfo?ipAddress=" + encodeURIComponent(ipAddress) + "&networkPrefix=" + networkPrefix);
    }
    return fetchJson("/internal/ipinfo?ipAddress=" + encodeURIComponent(ipAddress));
}

export function getPolicies() {
    return fetchJson("/internal/policies");
}

export function deletePolicy(policyId) {
    return fetchDelete(`/internal/policies/${ policyId }`);
}

export function getRevisions(policyId) {
    return fetchJson(`/internal/revisions/${policyId}`);
}

export function getNewPolicy(type) {
    return fetchJson("/internal/default-policy/" + type);
}

export function getPolicy(policyId) {
    return fetchJson(`/internal/policies/${policyId}`);
}

export function createPolicy(policy) {
    return postJson("/internal/policies", policy, {
        headers: {
            "Content-Type": "application/json"
        }
    });
}

export function updatePolicy(policy) {
    return putJson("/internal/policies", policy, {
        headers: {
            "Content-Type": "application/json"
        }
    });
}

export function getViolations() {
    return fetchJson("/internal/violations");
}

export function getPolicyViolations(policyId) {
    return fetchJson(`/internal/violations/${policyId}`);
}

export function getConflicts() {
    return fetchJson("/internal/conflicts");
}

export function getSamlAllowedAttributes() {
    return fetchJson("/internal/saml-attributes");
}

export function postPdpRequest(pdpRequest) {
    return postJson("/internal/decide/policy", pdpRequest).then(parseJson);
}


text:
package VMOMI::ClusterDrsVmConfigSpec;
use parent 'VMOMI::ArrayUpdateSpec';

use strict;
use warnings;

our @class_ancestors = (
    'ArrayUpdateSpec',
    'DynamicData',
);

our @class_members = (
    ['info', 'ClusterDrsVmConfigInfo', 0, 1],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require(dirname(__FILE__).'/../../config.php');
require_once(dirname(__FILE__).'/locallib.php');
require_once(dirname(__FILE__).'/edit_form.php');

$cmid       = required_param('cmid', PARAM_INT);  // Book Course Module ID
$chapterid  = optional_param('id', 0, PARAM_INT); // Chapter ID
$pagenum    = optional_param('pagenum', 0, PARAM_INT);
$subchapter = optional_param('subchapter', 0, PARAM_BOOL);

$cm = get_coursemodule_from_id('book', $cmid, 0, false, MUST_EXIST);
$course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
$book = $DB->get_record('book', array('id'=>$cm->instance), '*', MUST_EXIST);

require_login($course, false, $cm);

$context = context_module::instance($cm->id);
require_capability('mod/book:edit', $context);

$PAGE->set_url('/mod/book/edit.php', array('cmid'=>$cmid, 'id'=>$chapterid, 'pagenum'=>$pagenum, 'subchapter'=>$subchapter));
$PAGE->set_pagelayout('admin'); // TODO: Something. This is a bloody hack!

if ($chapterid) {
    $chapter = $DB->get_record('book_chapters', array('id'=>$chapterid, 'bookid'=>$book->id), '*', MUST_EXIST);
} else {
    $chapter = new stdClass();
    $chapter->id         = null;
    $chapter->subchapter = $subchapter;
    $chapter->pagenum    = $pagenum + 1;
}
$chapter->cmid = $cm->id;

$options = array('noclean'=>true, 'subdirs'=>true, 'maxfiles'=>-1, 'maxbytes'=>0, 'context'=>$context);
$chapter = file_prepare_standard_editor($chapter, 'content', $options, $context, 'mod_book', 'chapter', $chapter->id);

$mform = new book_chapter_edit_form(null, array('chapter'=>$chapter, 'options'=>$options));

// If data submitted, then process and store.
if ($mform->is_cancelled()) {
    if (empty($chapter->id)) {
        redirect("view.php?id=$cm->id");
    } else {
        redirect("view.php?id=$cm->id&chapterid=$chapter->id");
    }

} else if ($data = $mform->get_data()) {

    if ($data->id) {
        // store the files
        $data->timemodified = time();
        $data = file_postupdate_standard_editor($data, 'content', $options, $context, 'mod_book', 'chapter', $data->id);
        $DB->update_record('book_chapters', $data);
        $DB->set_field('book', 'revision', $book->revision+1, array('id'=>$book->id));

        add_to_log($course->id, 'course', 'update mod', '../mod/book/view.php?id='.$cm->id, 'book '.$book->id);
        add_to_log($course->id, 'book', 'update chapter', 'view.php?id='.$cm->id.'&chapterid='.$data->id, $data->id, $cm->id);

    } else {
        // adding new chapter
        $data->bookid        = $book->id;
        $data->hidden        = 0;
        $data->timecreated   = time();
        $data->timemodified  = time();
        $data->importsrc     = '';
        $data->content       = '';          // updated later
        $data->contentformat = FORMAT_HTML; // updated later

        // make room for new page
        $sql = "UPDATE {book_chapters}
                   SET pagenum = pagenum + 1
                 WHERE bookid = ? AND pagenum >= ?";
        $DB->execute($sql, array($book->id, $data->pagenum));

        $data->id = $DB->insert_record('book_chapters', $data);

        // store the files
        $data = file_postupdate_standard_editor($data, 'content', $options, $context, 'mod_book', 'chapter', $data->id);
        $DB->update_record('book_chapters', $data);
        $DB->set_field('book', 'revision', $book->revision+1, array('id'=>$book->id));

        add_to_log($course->id, 'course', 'update mod', '../mod/book/view.php?id='.$cm->id, 'book '.$book->id);
        add_to_log($course->id, 'book', 'add chapter', 'view.php?id='.$cm->id.'&chapterid='.$data->id, $data->id, $cm->id);
    }

    book_preload_chapters($book); // fix structure
    redirect("view.php?id=$cm->id&chapterid=$data->id");
}

// Otherwise fill and print the form.
$PAGE->set_title($book->name);
$PAGE->set_heading($course->fullname);

echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('editingchapter', 'mod_book'));

$mform->display();

echo $OUTPUT->footer();


text:
// 6. Rewrite the same using XDocument and LINQ query.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

class PreviousTasksUsingLINQ
{
    static void Main()
    {
        //1. creating the catalog
        Console.WriteLine("------Task 1------");
        CreateCatalog();
        Console.WriteLine("------task 1 completed!------");

        //2. artists in the catalog
        Console.WriteLine("\n------Task 2------");
        ArtistsInCatalog();
        Console.WriteLine("------Task 2 completed!------");

        //3. the same as 2

        //4. delete in the albums that cost >20
        Console.WriteLine("\n------Task 4------");
        DeleteExpensiveAlbums(20);
        Console.WriteLine("------Task 4 completed!------");

        //5. find all songs
        Console.WriteLine("\n------Task 5------");
        AllSongsFromTheCatalog();
        Console.WriteLine("------Task 5 completed!------");
    }

    // for task 5
    private static void AllSongsFromTheCatalog()
    {
        XDocument xmlDoc = XDocument.Load("../../../6. CatalogByLINQ.xml");

        var allSongs =
            from songs in xmlDoc.Descendants("title")
            select songs.Value;

        foreach (var song in allSongs)
        {
            Console.WriteLine(song);
        }
    }

    // for task 4
    private static void DeleteExpensiveAlbums(decimal price)
    {
        XDocument xmlDoc = XDocument.Load("../../../6. CatalogByLINQ.xml");
        var expensiveAlbums =
            (from album in xmlDoc.Descendants("album")
            where decimal.Parse(album.Element("price").Value) > price
            select album).ToList();

        foreach (var album in expensiveAlbums)
        {
            album.Remove();
        }

        xmlDoc.Save("../../../6. NEWCatalogByLINQ.xml");
    }

    // for task 2
    private static void ArtistsInCatalog()
    {
        XDocument xmlDoc = XDocument.Load("../../../6. CatalogByLINQ.xml");
        var artists =
            from album in xmlDoc.Descendants("album")
            group album by album.Element("artist").Value into artis
            select new
            {
                Name = artis.Key,
                Count = artis.Count()
            };

        foreach (var artist in artists)
        {
            Console.WriteLine("Artist name:{0} has {1} albums", artist.Name, artist.Count);
        }
    }

    // for task 1
    private static void CreateCatalog()
    {
        XElement catalogXml = new XElement("catalog",
            new XElement("album",
                new XElement("name", "Album 1"),
                new XElement("artist", "Artist 1"),
                new XElement("year", "2000"),
                new XElement("producer", "Producer 1"),
                new XElement("price", "10"),
                new XElement("songs",
                    new XElement("song",
                        new XElement("title", "Song 1 in album 1"),
                        new XElement("duration", "11")
                                ),
                    new XElement("song",
                        new XElement("title", "Song 2 in album 1"),
                        new XElement("duration", "21")
                            )
                    )
                ),
                new XElement("album",
                new XElement("name", "Album 2"),
                new XElement("artist", "Artist 2"),
                new XElement("year", "2000"),
                new XElement("producer", "Producer 2"),
                new XElement("price", "20"),
                new XElement("songs",
                    new XElement("song",
                        new XElement("title", "Song 1 in album 2"),
                        new XElement("duration", "12")
                                ),
                    new XElement("song",
                        new XElement("title", "Song 2 in album 2"),
                        new XElement("duration", "22")
                            )
                    )
                ),
                new XElement("album",
                new XElement("name", "Album 3"),
                new XElement("artist", "Artist 1"),
                new XElement("year", "2001"),
                new XElement("producer", "Producer 3"),
                new XElement("price", "30"),
                new XElement("songs",
                    new XElement("song",
                        new XElement("title", "Song 1 in album 3"),
                        new XElement("duration", "13")
                                ),
                    new XElement("song",
                        new XElement("title", "Song 2 in album 3"),
                        new XElement("duration", "23")
                            )
                    )
                )
            );

        Console.WriteLine(catalogXml);

        catalogXml.Save("../../../6. CatalogByLINQ.xml");
    }
}


text:
import api from '../index.js'
export default {
  getDraftList (tag) {
    let queryObj
    if (undefined !== tag) {
      queryObj = {tag}
    }
    return api.get('drafts', queryObj)
  },
  getDraft (id) {
    return api.get('drafts/' + id)
  },
  modifyDraftContent (id, content) {
    return api.patch('drafts/' + id, {content})
  },
  modifyDraftTitle (id, title) {
    return api.patch('drafts/' + id, {title})
  },
  modifyDraftTags (id, tags) {
    return api.patch('drafts/' + id, {tags})
  },
  createTags (tagName) {
    return api.post('tags', {name: tagName})
  },
  getAllTags () {
    return api.get('tags')
  },
  createDraft (title) {
    return api.post('drafts', {title: title})
  },
  publish (id) {
    return api.post('publications', {draftId: id})
  },
  deleteDraft (id) {
    return api.delete('drafts/' + id)
  },
  searchTagWithWord (keyword) {
    return api.get('tags', {'start-with': keyword})
  }
}


text:
from __future__ import absolute_import, division, print_function

import paramiko
from contextlib import contextmanager
from toolz import keyfilter, memoize, take
from datashape import discover
import re
from ..directory import _Directory, Directory

from ..utils import keywords, tmpfile, sample
from ..resource import resource
from ..append import append
from ..drop import drop

@contextmanager
def connect(**auth):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(**auth)

    try:
        yield ssh
    finally:
        ssh.close()

@contextmanager
def sftp(**auth):
    with connect(**auth) as ssh:
        sftp = ssh.open_sftp()

        yield sftp

class _SSH(object):
    """ Parent class for data accessed through ``ssh``

    See ``paramiko.SSHClient.connect`` for authentication keyword arguments

    Examples
    --------

    >>> from into import SSH, CSV
    >>> s = SSH(CSV)('/path/to/file.csv', hostname='hostname', username='alice')

    Normally create through resource uris

    >>> data = resource('ssh://alice@host:/path/to/file.csv', password='pass')
    >>> data.path
    '/path/to/file.csv'
    >>> data.auth['hostname']
    'host'
    """
    def __init__(self, *args, **kwargs):
        self.auth = keyfilter(keywords(paramiko.SSHClient.connect).__contains__,
                              kwargs)
        self.subtype.__init__(self, *args, **kwargs)

    def lines(self):
        with sftp(**self.auth) as conn:
            for line in conn.file(self.path, 'r'):
                yield line

def SSH(cls):
    return type('SSH(%s)' % cls.__name__, (_SSH, cls), {'subtype':  cls})

SSH.__doc__ = _SSH.__doc__

SSH = memoize(SSH)

from .csv import CSV
from .json import JSON, JSONLines
types_by_extension = {'csv': CSV, 'json': JSONLines}

ssh_pattern = '((?P<username>[a-zA-Z]\w*)@)?(?P<hostname>[\w.-]*)(:(?P<port>\d+))?:(?P<path>[/\w.*-]+)'

@resource.register('ssh://.+', priority=16)
def resource_ssh(uri, **kwargs):
    if 'ssh://' in uri:
        uri = uri[len('ssh://'):]

    d = re.match(ssh_pattern, uri).groupdict()
    d = dict((k, v) for k, v in d.items() if v is not None)
    path = d.pop('path')

    kwargs.update(d)

    try:
        subtype = types_by_extension[path.split('.')[-1]]
        if '*' in path:
            subtype = Directory(subtype)
            path = path.rsplit('/', 1)[0] + '/'
    except KeyError:
        subtype = type(resource(path))

    return SSH(subtype)(path, **kwargs)

@sample.register(SSH(CSV))
@contextmanager
def sample_ssh(data, lines=500):
    """ Grab a few lines from the remote file """
    with tmpfile('csv') as fn:
        with open(fn, 'w') as f:
            for line in take(lines, data.lines()):
                f.write(line)
                f.write('\n')
        yield fn

@sample.register(SSH(Directory(CSV)))
@contextmanager
def sample_ssh(data, **kwargs):
    """ Grab a few lines from a file in a remote directory """
    with sftp(**data.auth) as conn:
        fn = data.path + '/' + conn.listdir(data.path)[0]
        one_file = SSH(data.container)(fn, **data.auth)
        with sample(one_file, **kwargs) as result:
            yield result

@discover.register(_SSH)
def discover_ssh(data, **kwargs):
    with sample(data) as fn:
        o = data.subtype(fn)
        result = discover(o)
    return result

@discover.register(SSH(CSV))
def discover_ssh_csv(data, **kwargs):
    with sample(data) as fn:
        o = CSV(fn, encoding=data.encoding, has_header=data.has_header, **data.dialect)
        result = discover(o)
    return result

@discover.register(SSH(Directory(CSV)))
def discover_ssh_directory(data, **kwargs):
    with sftp(**data.auth) as conn:
        fn = data.path + '/' + conn.listdir(data.path)[0]
        one_file = SSH(data.container)(fn, **data.auth)
        result = discover(one_file)
    return result

@drop.register(_SSH)
def drop_ssh(data, **kwargs):
    with sftp(**data.auth) as conn:
        conn.remove(data.path)

@append.register(_SSH, object)
def append_anything_to_ssh(target, source, **kwargs):
    if not isinstance(source, target.subtype):
        raise NotImplementedError() # TODO: create local temp
    # TODO: handle overwrite case
    with sftp(**target.auth) as conn:
        conn.put(source.path, target.path)
    return target

@append.register(JSONLines, SSH(JSONLines))
@append.register(JSON, SSH(JSON))
@append.register(CSV, SSH(CSV))
def append_sshX_to_X(target, source, **kwargs):
    # TODO: handle overwrite case
    with sftp(**source.auth) as conn:
        conn.get(source.path, target.path)
    return target


text:
import { animate, stop } from 'liquid-fire';

// arguments are passed directly from use statements in transition rules, e.g.
// this.use('myTransition', arg1, arg2)

export default function (/* arg1, arg2 */) {
  // Stop any currently running animation on oldElement
  stop(this.oldElement);

  // Fade out the old element
  return animate(this.oldElement, { opacity: 0 })
    // And then fade in the new element, from opacity 0 to 1
    .then( () =>
      animate(this.newElement, { opacity: [1, 0] })
    );
}