text:
package jaakko.jaaska.apptycoon.console;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

/**
 * Purpose of the console is to provide an interface for manual testing of the engine through
 * commandline on the PC. This will not be accessible from the Android game.
 *
 * Created by jaakko on 27.3.2017.
 */

public class Console {

    private List<MenuPage> mPages;
    private Stack<MenuPage> mNavStack;

    private void startConsole() {
        System.out.println("SoftwareTycoon Dev Console\n");
        initPages();
        printCurrentMenuPage();
    }

    private void quitConsole() {
        // Gracefully stop and exit the console.
    }

    private void initPages() {

        mNavStack = new Stack<>();
        mPages = new ArrayList<>();

        //
        //
        // Random Generators
        final MenuPage randomGens = new MenuPage("Random Generators");
        randomGens.addAction(new Action("person", "Generate a random Employee.") {
            @Override
            public void doAction(Object... params) {
                //System.out.println(Employee.generateRandomPerson(500));
            }
        });

        //
        //
        // Main Menu
        MenuPage mainMenu = new MenuPage("Main Menu");
        mainMenu.addAction(new Action("r", "Run random generators.") {
            @Override
            public void doAction(Object[] params) {
                navigateToMenuPage(randomGens);
            }
        });

        // Set mainMenu as the current page.
        mNavStack.push(mainMenu);

    }

    private void printCurrentMenuPage() {
        System.out.println(mNavStack.peek());
        readCommand();
    }

    private void readCommand() {
        String cmd = "";
        Scanner sc = new Scanner(System.in);
        MenuPage currentPage = mNavStack.peek();

        while (currentPage.getAction(cmd) == null) {
            System.out.print("> ");
            cmd = sc.nextLine();

            // "back" is a universal command to navigate back one level in the menu.
            if (cmd.equals("back")) {
                goBack();
                return;
            }
        }

        currentPage.getAction(cmd).doAction();
        printCurrentMenuPage();
    }

    private void goBack() {

        mNavStack.pop();

        if (!mNavStack.empty()) {
            printCurrentMenuPage();
        } else {
            quitConsole();
        }

    }

    private void navigateToMenuPage(MenuPage newPage) {
        mNavStack.push(newPage);
        printCurrentMenuPage();
    }

    public static void main(String[] args) {
        Console console = new Console();
        console.startConsole();
    }

    public static void printError(String error) {
        System.out.println("ERROR: " + error);
    }
}


text:
package com.danikula.videocache;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.concurrent.atomic.AtomicInteger;

import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.LOG_TAG;

/**
 * Proxy for {@link Source} with caching support ({@link Cache}).
 * <p/>
 * Can be used only for sources with persistent data (that doesn't change with time).
 * Method {@link #read(byte[], long, int)} will be blocked while fetching data from source.
 * Useful for streaming something with caching e.g. streaming video/audio etc.
 *
 * @author Alexey Danilov (danikula@gmail.com).
 */
public class ProxyCache {

    private static final int MAX_READ_SOURCE_ATTEMPTS = 1;

    private final Source source;
    private final Cache cache;
    private final Object wc;
    private final Handler handler;
    private volatile Thread sourceReaderThread;
    private volatile boolean stopped;
    private final AtomicInteger readSourceErrorsCount;
    private CacheListener cacheListener;
    private final boolean logEnabled;

    public ProxyCache(Source source, Cache cache, boolean logEnabled) {
        this.source = checkNotNull(source);
        this.cache = checkNotNull(cache);
        this.logEnabled = logEnabled;
        this.wc = new Object();
        this.handler = new Handler(Looper.getMainLooper());
        this.readSourceErrorsCount = new AtomicInteger();
    }

    public ProxyCache(Source source, Cache cache) {
        this(source, cache, false);
    }

    public void setCacheListener(CacheListener cacheListener) {
        this.cacheListener = cacheListener;
    }

    public int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
        ProxyCacheUtils.assertBuffer(buffer, offset, length);

        while (!cache.isCompleted() && cache.available() < (offset + length) && !stopped) {
            readSourceAsync();
            waitForSourceData();
            checkIsCacheValid();
            checkReadSourceErrorsCount();
        }
        int read = cache.read(buffer, offset, length);
        if (isLogEnabled()) {
            Log.d(LOG_TAG, "Read data[" + read + " bytes] from cache with offset " + offset + ": " + ProxyCacheUtils.preview(buffer, read));
        }
        return read;
    }

    private void checkIsCacheValid() throws ProxyCacheException {
        int sourceAvailable = source.available();
        if (sourceAvailable > 0 && cache.available() > sourceAvailable) {
            throw new ProxyCacheException("Unexpected cache: cache [" + cache.available() + " bytes] > source[" + sourceAvailable + " bytes]");
        }
    }

    private void checkReadSourceErrorsCount() throws ProxyCacheException {
        int errorsCount = readSourceErrorsCount.get();
        if (errorsCount >= MAX_READ_SOURCE_ATTEMPTS) {
            readSourceErrorsCount.set(0);
            throw new ProxyCacheException("Error reading source " + errorsCount + " times");
        }
    }

    public void shutdown() {
        try {
            stopped = true;
            if (sourceReaderThread != null) {
                sourceReaderThread.interrupt();
            }
            cache.close();
        } catch (ProxyCacheException e) {
            onError(e);
        }
    }

    private void readSourceAsync() throws ProxyCacheException {

        boolean readingInProgress = sourceReaderThread != null && sourceReaderThread.getState() != Thread.State.TERMINATED;
        if (!stopped && !cache.isCompleted() && !readingInProgress) {
            sourceReaderThread = new Thread(new SourceReaderRunnable(), "Source reader for ProxyCache");
            sourceReaderThread.start();
        }
    }

    private void waitForSourceData() throws ProxyCacheException {
        synchronized (wc) {
            try {
                wc.wait(1000);
            } catch (InterruptedException e) {
                throw new ProxyCacheException("Waiting source data is interrupted!", e);
            }
        }
    }

    private void notifyNewCacheDataAvailable(final int cachePercentage) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (cacheListener != null) {
                    cacheListener.onCacheDataAvailable(cachePercentage);
                }
            }
        });

        synchronized (wc) {
            wc.notifyAll();
        }
    }

    private void readSource() {
        int cachePercentage = 0;
        try {
            int offset = cache.available();
            source.open(offset);
            byte[] buffer = new byte[ProxyCacheUtils.DEFAULT_BUFFER_SIZE];
            int readBytes;
            while ((readBytes = source.read(buffer)) != -1 && !Thread.currentThread().isInterrupted() && !stopped) {
                if (isLogEnabled()) {
                    Log.d(LOG_TAG, "Write data[" + readBytes + " bytes] to cache from source with offset " + offset + ": " + ProxyCacheUtils.preview(buffer, readBytes));
                }
                cache.append(buffer, readBytes);
                offset += readBytes;
                cachePercentage = offset * 100 / source.available();

                notifyNewCacheDataAvailable(cachePercentage);
            }
            if (cache.available() == source.available()) {
                cache.complete();
            }
        } catch (Throwable e) {
            readSourceErrorsCount.incrementAndGet();
            onError(e);
        } finally {
            closeSource();
            notifyNewCacheDataAvailable(cachePercentage);
        }
    }

    private void closeSource() {
        try {
            source.close();
        } catch (ProxyCacheException e) {
            onError(new ProxyCacheException("Error closing source " + source, e));
        }
    }

    protected final void onError(final Throwable e) {
        Log.e(LOG_TAG, "ProxyCache error", e);
        handler.post(new ErrorDeliverer(e));
    }

    protected boolean isLogEnabled() {
        return logEnabled;
    }

    private class SourceReaderRunnable implements Runnable {

        @Override
        public void run() {
            readSource();
        }
    }

    private class ErrorDeliverer implements Runnable {

        private final Throwable error;

        public ErrorDeliverer(Throwable error) {
            this.error = error;
        }

        @Override
        public void run() {
            if (error instanceof ProxyCacheException) {
                if (cacheListener != null) {
                    cacheListener.onError((ProxyCacheException) error);
                }
            } else {
                throw new RuntimeException("Unexpected error!", error);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.gamefreezer.galaga;

public class GunHud {

    private Animation hudAnimation;
    private CartesianInt topLeft;

    public GunHud(CartesianInt topLeft) {
	this.topLeft = topLeft;
    }

    public void draw(AbstractGraphics graphics) {
	if (hudAnimation != null) {
	    hudAnimation.draw(graphics, topLeft.x, topLeft.y);
	    if (hudAnimation.isFinished()) {
		hudAnimation = null;
	    }
	}
    }

    public void setAnimation(Animation newHudAnimation) {
	hudAnimation = newHudAnimation;
	hudAnimation.reset();
    }

}


text:
#pragma once
#include <aws/location/LocationService_EXPORTS.h>
#include <aws/location/LocationServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/location/model/DataSourceConfiguration.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>

namespace Aws
{
namespace LocationService
{
namespace Model
{

  /**
   */
  class AWS_LOCATIONSERVICE_API CreatePlaceIndexRequest : public LocationServiceRequest
  {
  public:
    CreatePlaceIndexRequest();

    // 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 "CreatePlaceIndex"; }

    Aws::String SerializePayload() const override;

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline const Aws::String& GetDataSource() const{ return m_dataSource; }

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline bool DataSourceHasBeenSet() const { return m_dataSourceHasBeenSet; }

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline void SetDataSource(const Aws::String& value) { m_dataSourceHasBeenSet = true; m_dataSource = value; }

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline void SetDataSource(Aws::String&& value) { m_dataSourceHasBeenSet = true; m_dataSource = std::move(value); }

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline void SetDataSource(const char* value) { m_dataSourceHasBeenSet = true; m_dataSource.assign(value); }

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline CreatePlaceIndexRequest& WithDataSource(const Aws::String& value) { SetDataSource(value); return *this;}

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline CreatePlaceIndexRequest& WithDataSource(Aws::String&& value) { SetDataSource(std::move(value)); return *this;}

    /**
     *
Specifies the geospatial data provider for the new place index.

     *
This field is case-sensitive. Enter the valid values as shown. For example,
     * entering HERE returns an error.

Valid values
     * include:

 Esri – For additional information about
     * Esri's
     * coverage in your region of interest, see Esri
     * details on geocoding coverage.

 Here – For
     * additional information about HERE
     * Technologies' coverage in your region of interest, see HERE
     * details on goecoding coverage.

If you specify HERE
     * Technologies (Here) as the data provider, you may not store
     * results for locations in Japan. For more information, see the AWS Service Terms for Amazon
     * Location Service.

For additional information ,
     * see Data
     * providers on the Amazon Location Service Developer Guide.

     */
    inline CreatePlaceIndexRequest& WithDataSource(const char* value) { SetDataSource(value); return *this;}

    /**
     *
Specifies the data storage option requesting Places.

     */
    inline const DataSourceConfiguration& GetDataSourceConfiguration() const{ return m_dataSourceConfiguration; }

    /**
     *
Specifies the data storage option requesting Places.

     */
    inline bool DataSourceConfigurationHasBeenSet() const { return m_dataSourceConfigurationHasBeenSet; }

    /**
     *
Specifies the data storage option requesting Places.

     */
    inline void SetDataSourceConfiguration(const DataSourceConfiguration& value) { m_dataSourceConfigurationHasBeenSet = true; m_dataSourceConfiguration = value; }

    /**
     *
Specifies the data storage option requesting Places.

     */
    inline void SetDataSourceConfiguration(DataSourceConfiguration&& value) { m_dataSourceConfigurationHasBeenSet = true; m_dataSourceConfiguration = std::move(value); }

    /**
     *
Specifies the data storage option requesting Places.

     */
    inline CreatePlaceIndexRequest& WithDataSourceConfiguration(const DataSourceConfiguration& value) { SetDataSourceConfiguration(value); return *this;}

    /**
     *
Specifies the data storage option requesting Places.

     */
    inline CreatePlaceIndexRequest& WithDataSourceConfiguration(DataSourceConfiguration&& value) { SetDataSourceConfiguration(std::move(value)); return *this;}

    /**
     *
The optional description for the place index resource.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
The optional description for the place index resource.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
The optional description for the place index resource.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
The optional description for the place index resource.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
The optional description for the place index resource.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
The optional description for the place index resource.

     */
    inline CreatePlaceIndexRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
The optional description for the place index resource.

     */
    inline CreatePlaceIndexRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
The optional description for the place index resource.

     */
    inline CreatePlaceIndexRequest& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline const Aws::String& GetIndexName() const{ return m_indexName; }

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline bool IndexNameHasBeenSet() const { return m_indexNameHasBeenSet; }

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline void SetIndexName(const Aws::String& value) { m_indexNameHasBeenSet = true; m_indexName = value; }

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline void SetIndexName(Aws::String&& value) { m_indexNameHasBeenSet = true; m_indexName = std::move(value); }

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline void SetIndexName(const char* value) { m_indexNameHasBeenSet = true; m_indexName.assign(value); }

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline CreatePlaceIndexRequest& WithIndexName(const Aws::String& value) { SetIndexName(value); return *this;}

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline CreatePlaceIndexRequest& WithIndexName(Aws::String&& value) { SetIndexName(std::move(value)); return *this;}

    /**
     *
The name of the place index resource.

Requirements:

     *
Contain only alphanumeric characters (A–Z, a–z, 0–9), hyphens (-), periods
     * (.), and underscores (_).

Must be a unique place index
     * resource name.

No spaces allowed. For example,
     * ExamplePlaceIndex.

     */
    inline CreatePlaceIndexRequest& WithIndexName(const char* value) { SetIndexName(value); return *this;}

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;}

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
Applies one or more tags to the place index resource. A tag is a key-value
     * pair that helps you manage, identify, search, and filter your resources.

     *
Format: "key" : "value"

Restrictions:

     *
Maximum 50 tags per resource.

Each tag key must be unique
     * and must have exactly one associated value.

Maximum key
     * length: 128 Unicode characters in UTF-8.

Maximum value length:
     * 256 Unicode characters in UTF-8.

Can use alphanumeric
     * characters (A–Z, a–z, 0–9), and the following characters: + - = . _ : / @

     *

Cannot use "aws:" as a prefix for a key.

     */
    inline CreatePlaceIndexRequest& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }

  private:

    Aws::String m_dataSource;
    bool m_dataSourceHasBeenSet = false;

    DataSourceConfiguration m_dataSourceConfiguration;
    bool m_dataSourceConfigurationHasBeenSet = false;

    Aws::String m_description;
    bool m_descriptionHasBeenSet = false;

    Aws::String m_indexName;
    bool m_indexNameHasBeenSet = false;

    Aws::Map<Aws::String, Aws::String> m_tags;
    bool m_tagsHasBeenSet = false;
  };

} // namespace Model
} // namespace LocationService
} // namespace Aws


text:
/*
 * Doctor Appointment
 * Appointment
 *
 * OpenAPI spec version: 1.0.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package io.swagger.client.model;

import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;

/**
 * Payload
 */
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-22T11:51:09.190Z")
public class Payload {
  @SerializedName("doctorId")
  private Long doctorId = null;

  @SerializedName("doctorName")
  private String doctorName = null;

  @SerializedName("visitingCharge")
  private Long visitingCharge = null;

  @SerializedName("availability")
  private Long availability = null;

  @SerializedName("speciality")
  private String speciality = null;

  public Payload doctorId(Long doctorId) {
    this.doctorId = doctorId;
    return this;
  }

   /**
   * Get doctorId
   * @return doctorId
  **/
  @ApiModelProperty(value = "")
  public Long getDoctorId() {
    return doctorId;
  }

  public void setDoctorId(Long doctorId) {
    this.doctorId = doctorId;
  }

  public Payload doctorName(String doctorName) {
    this.doctorName = doctorName;
    return this;
  }

   /**
   * Get doctorName
   * @return doctorName
  **/
  @ApiModelProperty(value = "")
  public String getDoctorName() {
    return doctorName;
  }

  public void setDoctorName(String doctorName) {
    this.doctorName = doctorName;
  }

  public Payload visitingCharge(Long visitingCharge) {
    this.visitingCharge = visitingCharge;
    return this;
  }

   /**
   * Get visitingCharge
   * @return visitingCharge
  **/
  @ApiModelProperty(value = "")
  public Long getVisitingCharge() {
    return visitingCharge;
  }

  public void setVisitingCharge(Long visitingCharge) {
    this.visitingCharge = visitingCharge;
  }

  public Payload availability(Long availability) {
    this.availability = availability;
    return this;
  }

   /**
   * Get availability
   * @return availability
  **/
  @ApiModelProperty(value = "")
  public Long getAvailability() {
    return availability;
  }

  public void setAvailability(Long availability) {
    this.availability = availability;
  }

  public Payload speciality(String speciality) {
    this.speciality = speciality;
    return this;
  }

   /**
   * Get speciality
   * @return speciality
  **/
  @ApiModelProperty(value = "")
  public String getSpeciality() {
    return speciality;
  }

  public void setSpeciality(String speciality) {
    this.speciality = speciality;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Payload payload = (Payload) o;
    return Objects.equals(this.doctorId, payload.doctorId) &&
        Objects.equals(this.doctorName, payload.doctorName) &&
        Objects.equals(this.visitingCharge, payload.visitingCharge) &&
        Objects.equals(this.availability, payload.availability) &&
        Objects.equals(this.speciality, payload.speciality);
  }

  @Override
  public int hashCode() {
    return Objects.hash(doctorId, doctorName, visitingCharge, availability, speciality);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class Payload {\n");

    sb.append("    doctorId: ").append(toIndentedString(doctorId)).append("\n");
    sb.append("    doctorName: ").append(toIndentedString(doctorName)).append("\n");
    sb.append("    visitingCharge: ").append(toIndentedString(visitingCharge)).append("\n");
    sb.append("    availability: ").append(toIndentedString(availability)).append("\n");
    sb.append("    speciality: ").append(toIndentedString(speciality)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


text:
function mask = rois2mask(v,t,m)
%rois2mask  Create an image mask from the ROI verticies
%
%   MASK = rois2mask(VERTS,TYPE,M) generates MASK, a binary image of size M,
%   using the verticies specified by VERTS from one of the ROI constructors
%   (imrect, impoly, etc.) as specified by the string TYPE.

    switch t
        case 'imrect'
            mask = rect2mask(v,m);
        case 'imellipse'
            mask = ellipse2mask(v,m);
        otherwise
            mask = poly2mask(v(:,1),v(:,2),m(1),m(2));
    end

end %rois2mask


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- <item
    	android:state_pressed="true" android:drawable="@drawable/appnew_install_btn_hover"/>
    <item
    	android:state_pressed="false" android:drawable="@drawable/appnew_install_btn"/> -->
</selector>


text:
<?php

include('../connect_db.php');

include("pode_nao_pode.php");

$id = $_GET["eventoid"];

mysqli_query($dbi, "DELETE FROM eventos WHERE id='$id'");

header("location:comunicados.php");

mysqli_close($dbi);

?>


text:
var ms = require('ms');
var s = require('../s');

var TYPE_ERROR = 'should be a duration string (e.g. \"10s\")';

module.exports = function (opts) {

  if (!opts) opts = {};

  var minValue = (opts.min != null) ? ms(opts.min) : 0;
  var maxValue = (opts.max != null) ? ms(opts.max) : Number.MAX_VALUE;

  if (typeof minValue !== 'number') {
    throw new Error('Invalid minimum duration: ' + opts.min);
  }

  if (typeof maxValue !== 'number') {
    throw new Error('Invalid maximum duration: ' + opts.max);
  }

  return s(function(value) {

    if (typeof value !== 'string') return TYPE_ERROR;

    var duration = ms(value);
    if (typeof duration !== 'number') return TYPE_ERROR;

    if (opts.min && opts.max && (duration < minValue || duration > maxValue)) {
      return 'should be a duration between ' + opts.min + ' and ' + opts.max;
    }
    if (opts.min && (duration < minValue)) {
      return 'should be a duration >= ' + opts.min;
    }
    if (opts.max && (duration > maxValue)) {
      return 'should be a duration <= ' + opts.max;
    }

    return null;

  });

};


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;

namespace UserAndCustomControls
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Scenario1 : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;

        public Scenario1()
        {
            this.InitializeComponent();
        }
    }
}


text:
require 'pp'

class ClaimsController < ApplicationController
  def home
    render 'claims/demo/social_start', :layout => 'application-rebuild'
  end

  def templates
    render 'claims/claimant/templates', :layout => 'application-rebuild-templates'
  end

  # stuff for demo only
  def demo_handler
    render 'claims/demo/' + params[:page], :layout => 'application-rebuild'
  end
  # /stuff for demo only

  def before
    render "claims/claimant/before"
  end

  def delete
    Claim.find(params[:id]).delete
    redirect_to root_path
  end

  def show
    @claim = Claim.find(params[:id])
    redirect_to personal_details_claim_path @claim
  end

  def create
    @user = @user || Person.find(session[:user])
    @claim = Claim.create(:owner => @user, :claimants => [@user])

    redirect_to personal_details_claim_path @claim
  end

  def login
    hide_user_nav
    render 'claims/claimant/login'
  end

  def update
    @claim = Claim.find(params[:id])
    params.permit!
    @claim.update_attributes params[:claim]

    case params[:commit]
    when 'save-and-continue'
      redirect_to next_navigation_path
    when 'close'
      redirect_to root_path
    end
  end

  def post_personal_details

    if params.has_key? 'destroy'
      Person.delete(params[:destroy])
      @claim = Claim.find(params[:id])
      redirect_to personal_details_claim_path @claim
      return
    end

    @claim = Claim.find(params[:id])

    params.permit!

    # why doesn't it work normally?
    @claim.address.update_attributes params[:claim][:address]
    params[:claim].except!(:address)
    @claim.update_attributes params[:claim]

    if params.has_key? 'same-address-as-first-tenant'
      a = Address.find(params['same-address-as-first-tenant'])
      a.copy_from @claim.primary_defendant.address
      a.save
      @claim.reload
    elsif params.has_key? 'same-address-as-first-landlord'
      a = Address.find(params['same-address-as-first-landlord'])
      a.copy_from @claim.primary_claimant.address
      a.save
      @claim.reload
    end

    case params[:commit]
    when 'save-and-continue'
      redirect_to next_navigation_path
    when 'close'
      redirect_to root_path
    when 'Add another landlord'
      @claim.claimants.create(:address => Address.create)
      redirect_to personal_details_claim_path @claim
    when 'Add another tenant'
      @claim.defendants.create(:address => Address.create)
      redirect_to personal_details_claim_path @claim
    else
      redirect_to personal_details_claim_path @claim
    end

  end

  def personal_details
    @claim = Claim.find(params[:id])
    @editors = session['editors'] || {}
    if @claim.defendants.empty?
      defendant = @claim.defendants.new(address: Address.new)
    end
    if @claim.address.nil?
      @claim.build_address
      @claim.save
    end
    session[:referer] = 'personal_details'
    render 'claims/claimant/personal_details'
  end

  def case_details
    @claim = Claim.find(params[:id])
    session[:referer] = 'case_details'
    render 'claims/claimant/case_details'
  end

  def court_booking
    @claim = Claim.find(params[:id])
    session[:referer] = 'court_booking'
    render 'claims/claimant/court_booking'
  end

  def statement
    @claim = Claim.find(params[:id], :include => [{:claimants => :address}, {:defendants => :address}])
    session[:referer] = 'statement'
    render 'claims/claimant/statement'
  end

  def fees
    @claim = Claim.find(params[:id])
    session[:referer] = 'fees'
    render 'claims/claimant/fees'
  end

  def confirmation
    @claim = Claim.find(params[:id])
    session[:referer] = 'confirmation'
    render 'claims/claimant/confirmation'
  end

  def case
    render 'claims/staff/case', :layout => 'staff'
  end

  def before
    render 'claims/claimant/before'
  end

  private

    def hide_user_nav
      @hide_user_nav = true
    end

    def page_title
      @page_title = "Repossess a property:<br />make a possession claim".html_safe
    end

    def page_links
      @linkdata = linkdata
    end

    def linkdata
      [
        { :text => 'Personal details', :path => 'personal_details' },
        { :text => 'Case details', :path => 'case_details' },
        { :text => 'County Court', :path => 'court_booking' },
        { :text => 'Confirm details', :path => 'statement' },
        { :text => 'Pay court fee', :path => 'fees' },
        { :text => 'Confirmation', :path => 'confirmation' }
      ]
    end

end


text:
#  ________      ______
#  ___  __/_____ ___  /__________________
#  __  /_ _  __ `/_  /_  ___/  __ \_  __ \
#  _  __/ / /_/ /_  / / /__ / /_/ /  / / /
#  /_/    \__,_/ /_/  \___/ \____//_/ /_/
#
# Author : Shine Xu
# License: The MIT License (MIT)

# -*- coding: utf-8 -*-

from .utils import *
from .entry import Entry

class Answer(Entry):
    """ Tool class for getting answer info. """

    def __init__(self, session, eid):
        Entry.__init__(self, session, eid)

    def get_author(self):
        """ Return author eid or None. """
        author = self.soup.find('a', class_ = 'zm-item-link-avatar')
        if author:
            return author['href']
        return None # for anonymous user

    def get_question(self):
        """ Return the eid of question where this answer in. """
        l = self.eid.split('/')
        return '/{0}/{1}'.format(l[1], l[2])

    @return_int
    def get_num_upvotes(self):
        """ Return number of upvotes int.  """
        num = self.soup.find('div', class_ = 'answer-head').find_all('div')[1]['data-votecount']
        return num

    @return_int
    def get_num_comments(self):
        """ Return number of comments int. """
        return self.soup.find('a', class_ = ' meta-item toggle-comment')\
                        .get_text(strip = True).encode(CODE)

    @return_int
    def get_num_collects(self):
        """ Return number of being collected int. """
        num = self.soup.find('a', href = self.eid + '/collections');
        if num:
            return num.get_text(strip = True).encode(CODE)
        return ''

    def get_voters(self):
        """ A generator yields a voted user eid per next().  """
        aid = self.soup.find('div', class_='zm-item-answer')['data-aid']
        url = HOST_URL + "/answer/{0}/voters_profile".format(aid)
        while url:
            rsp = self.session.get(url)
            voters = rsp.json()['payload']
            for voter in voters:
                voter = self.getSoup(voter).a
                if voter: # for anonymous user
                    yield voter['href']
            url = HOST_URL + rsp.json()['paging']['next']

    def get_all_voters(self):
        """ Return a [list] of voted user eids. """
        return get_all_(self.get_voters)

    def vote_neutral(self, action = 'vote_neutral'):
        """ Vote neutral this answer. Return status code. """
        data = {
            'params' : json.dumps({
                'answer_id' : self.soup.find('div', class_='zm-item-answer')['data-aid']
                }),
            '_xsrf'  : self.session.getCookie()['_xsrf'],
            'method' : action
            }
        rsp = self.session.post(Vote_Neutral_Answer_URL, data)
        if rsp.status_code == requests.codes.ok:
            return SUCCESS
        else:
            return FAILURE

    def vote_up(self):
        """ Vote up this answer. Return status code. """
        return self.vote_neutral('vote_up')

    def vote_down(self):
        """ Vote down this answer. Return status code. """
        return self.vote_neutral('vote_down')

    def thanks(self, url = Thanks_Answer_URL):
        """ Thanks this answer. Return status code. """
        data = {
            'aid' : self.soup.find('div', class_='zm-item-answer')['data-aid'],
            '_xsrf'  : self.session.getCookie()['_xsrf'],
            }
        rsp = self.session.post(url, data)
        if rsp.status_code == requests.codes.ok:
            return SUCCESS
        else:
            return FAILURE

    def cancel_thanks(self):
        """ Cancel thanks this answer. Return status code. """
        return self.thanks(Cancel_Thanks_Answer_URL)

    def helpful(self, url = Helpful_Answer_URL):
        """ This answer is helpful to me. Return status code. """
        return self.thanks(Helpful_Answer_URL)

    def not_helpful(self):
        """ This answer is not helpful to me. Return status code. """
        return self.thanks(Not_Helpful_Answer_URL)

    def get_content(self):
        """ Return answer content in pretty soup format. """
        content = self.soup.find('div', class_ = ' zm-editable-content clearfix')
        soup = BeautifulSoup('<!DOCTYPE html><meta charset="utf-8">')
        soup.body.append(content)

        for noscript in soup.find_all('noscript'):
            noscript.extract()
        for icon in soup.find_all("i", class_='icon-external'):
            icon.extract()
        for img in soup.find_all('img'):
            if img.has_attr('data-actualsrc'):
                img['src'] = "http://" + img['data-actualsrc'][2:]
            elif img.has_attr('eeimg'):
                img['src'] = "http://" + img['src'][2:]

        return soup.prettify()

    def save_content(self):
        """ Save answer content into local files, only support html currently. """
        filename = self.eid.split('/')[-1] + ".html"
        with open(filename, 'wb') as f:
            f.write(self.get_content().encode('utf-8'))

    # TODO #

    def get_comments(sefl):
        """ """


text:
[![Build Status](https://travis-ci.org/phossa/phossa-query.svg?branch=master)](https://travis-ci.org/phossa/phossa-query)
[![HHVM](https://img.shields.io/hhvm/phossa/phossa-query.svg?style=flat)](http://hhvm.h4cc.de/package/phossa/phossa-query)
[![Latest Stable Version](https://img.shields.io/packagist/vpre/phossa/phossa-query.svg?style=flat)](https://packagist.org/packages/phossa/phossa-query)
[![License](https://poser.pugx.org/phossa/phossa-query/license)](http://mit-license.org/)

**phossa-query** is a SQL query builder library with concise syntax for PHP.
It supports Mysql, SQLite, Postgres, Sql server, Oracle etc.

It requires PHP 5.4 and supports PHP 7.0+, HHVM. It is compliant with
[PSR-1][PSR-1], [PSR-2][PSR-2], [PSR-4][PSR-4].

[PSR-1]: http://www.php-fig.org/psr/psr-1/ "PSR-1: Basic Coding Standard"
[PSR-2]: http://www.php-fig.org/psr/psr-2/ "PSR-2: Coding Style Guide"
[PSR-4]: http://www.php-fig.org/psr/psr-4/ "PSR-4: Autoloader"

Features
--

- Support [SELECT](#select), [INSERT](#insert), [UPDATE](#update),
  [REPLACE](#replace), [DELETE](#delete), [CREATE TABLE](#create).

- Complex sql building with [expr()](#expr), [raw()](#raw), [before()](#before),
  [after()](#before) etc.

- Statement with positioned or named [parameters](#param).

- Beautiful output with different [settings](#settings).

- Ongoing support for different dialects like [`Mysql`](#mysql), `Sqlite` and
  more.

Installation
---

Install via the [`composer`](https://getcomposer.org/) utility.

```
composer require "phossa/phossa-query=1.*"
```

or add the following lines to your `composer.json`

```json
{
    "require": {
        "phossa/phossa-query": "^1.0.0"
    }
}
```

Usage
---

- Getting started

  Start with a query builder first, then the query.

  ```php
  use Phossa\Query\Builder;
  use Phossa\Query\Dialect\Mysql;

  // a builder with mysql dialect,default 'users' table
  $users = new Builder(new Mysql(), 'users');

  // SELECT * FROM `users` LIMIT 10
  $sql = $users->select()->limit(10)->getStatement();

  // INSERT INTO `users` (`usr_name`) VALUES ('phossa')
  $sql = $users->insert(['usr_name' => 'phossa'])->getStatement();

  // A new builder (cloned) with default table 'sales'
  $sales = $users->table(['sales' => 's']);
  $query = $sales->select()->where('user_id', 12);

  // SELECT * FROM `sales` AS `s` WHERE `user_id` = ?
  $sql = $query->getStatement(['positionedParam' => true]);

  // value bindings: [12]
  $val = $query->getBindings();
  ```

- `SELECT`

  - Columns

    Columns can be specified in the `select()` or in `col()` (or with its
    alias `field()`).

    Column with optional alias name,

    ```php
    // SELECT `user_name` AS `n` FROM `users`
    $query = $users->select('user_name', 'n');
    ```

    Multiple columns,

    ```php
    // SELECT `id`, `user_name` AS `n` FROM `users`
    $query = $users->select()->col(['id', 'user_name' => 'n']);

    // same as above
    $query = $users->select()->col('id')->field('user_name', 'n');
    ```

    Raw mode,

    ```php
    // SELECT COUNT(user_id) AS `cnt` FROM `users`
    $query = $users->select()->colRaw(['COUNT(user_id)' => 'cnt']);
    ```

    Common functions like `count()`, `min()`, `max()`, `avg()`, `sum()` and
    `sumDistinct()` can be used in the columns.

    ```php
    // SELECT COUNT(`user_id`) AS `cnt`, MAX(`user_id`) AS `max_id` FROM `users`
    $query = $users->select()->count('user_id', 'cnt')->max('user_id', 'max_id');
    ```

    Generic functions by using `func($template, $colName, $colAlias)`,

    ```php
    // SELECT CONCAT(`user_name`, "XXX") AS `new_name` FROM `users`
    $query = $users->select()->func('CONCAT(%s, "XXX")', 'user_name', 'new_name');
    ```

  - Distinct

    `DISTINCT` can be specified with `distinct()`

    ```php
    // SELECT DISTINCT `user_alias` FROM `users`
    $query = $users->select('user_alias')->distinct();
    ```

  - From

    `FROM` can used with builder object or select object.

    Use `select(false)` to ignore default table from the builder,

    ```php
    // SELECT * FROM `sales` AS `s`
    $query = $users->select(false)->from('sales', 's');
  ```

    Builder tables are carried over,

    ```php
    // SELECT * FROM `users`, `sales`
    $query = $users->select()->from('sales');
    ```

    Multiple tables (with aliases) supported,

    ```php
    // SELECT * FROM `users` AS `u`, `accounts` AS `a`
    $query = $users->select()->from(['users' => 'u', 'accounts' => 'a']);
    ```

    Subqueries can be used in `from()`,

    ```php
    // builder without default table[s]
    $builder = $users->table(false);

    // SELECT * FROM (SELECT `user_id` FROM `oldusers`) AS `u`
    $query = $builder->select()->from(
        $builder->select('user_id')->from('oldusers'), 'u'
    );
    ```

  - Group by

    Single `GROUP BY`,

    ```php
    // SELECT `group_id`, COUNT(*) AS `cnt` FROM `users` GROUP BY `group_id`
    $query = $users->select()->col('group_id')->count('*', 'cnt')->groupBy('group_id');
    ```

    Multiple `groupBy()` and raw mode can be used,

    ```php
    // SELECT `group_id`, `age`, COUNT(*) AS `cnt` FROM `users` GROUP BY `group_id`, age ASC
    $query = $users->select()->col('group_id')->col('age')->count('*', 'cnt')
        ->groupBy('group_id')->groupByRaw('age ASC');
    ```

  - Join

    Join with another table with same column name

    ```php
    // SELECT * FROM `users` INNER JOIN `accounts` ON `users`.`id` = `accounts`.`id`
    $query = $users->select()->join('accounts', 'id');
    ```

    Specify alias for the join table,

    ```php
    // SELECT * FROM `users` INNER JOIN `accounts` AS `a` ON `users`.`id` = `a`.`id`
    $query = $users->select()->join('accounts a', 'id');
    ```

    Join table with different column name,

    ```php
    // SELECT * FROM `users` INNER JOIN `accounts` AS `a` ON `users`.`id` = `a`.`user_id`
    $query = $users->select()->join('accounts a', 'id', 'user_id');
    ```

    Join with operator specified,

    ```php
    // SELECT * FROM `users` INNER JOIN `accounts` AS `a` ON `users`.`id` <> `a`.`user_id`
    $query = $users->select()->join('accounts a', 'id', '<>', 'user_id');
    ```

    Multiple joins,

    ```php
    // SELECT * FROM `users`
    // INNER JOIN `sales` AS `s` ON `users`.`uid` = `s`.`uid`
    // INNER JOIN `order` AS `o` ON `users`.`uid` = `o`.`o_uid`
    $query = $users->select()
                ->join('sales s', 'uid', '=', 'uid')
                ->join('order o', 'uid', 'o_uid')
                ->getStatement();
    ```

    Subqueries in join,

    ```php
    // SELECT * FROM `users` INNER JOIN (SELECT `uid` FROM `oldusers`) AS `x`
    // ON `users`.`uid` = `x`.`uid`
    $query = $users->select()->join(
        $builder->select('uid')->from('oldusers')->alias('x'),
        'uid'
    );
    ```

    Other joins `outerJoin()`, `leftJoin()`, `leftOuterJoin()`, `rightJoin()`,
    `rightOuterJoin()`, `fullOuterJoin()`, `crossJoin()` are supported. If want
    to use your own join, `realJoin()` is handy.

    ```php
    // SELECT * FROM `users` OUTER JOIN `accounts` AS `a` ON `users`.`id` = `a`.`id`
    $query = $users->select()->outerJoin('accounts a', 'id');

    // SELECT * FROM `users` NATURAL JOIN `accounts` AS `a` ON `users`.`id` = `a`.`id`
    $query = $users->select()->realJoin('NATURAL', 'accounts a', 'id');
    ```

  - Limit

    `LIMIT` and `OFFSET` are supported,

    ```php
    // SELECT * FROM `users` LIMIT 30 OFFSET 10
    $query = $users->select()->limit(30, 10);

    // SELECT * FROM `users` LIMIT 20 OFFSET 15
    $query = $users->select()->limit(20)->offset(15);
    ```

    Or use `page($pageNum, $pageLength)`,

    ```php
    // SELECT * FROM `users` LIMIT 30 OFFSET 60
    $query = $users->select()->page(3, 30);
    ```

  - Order by

    Order by ASC or DESC

    ```php
    // SELECT * FROM `users` ORDER BY `age` ASC, `score` DESC
    $query = $users->select()->orderByAsc('age')->orderByDesc('score');
    ```

    Or raw mode

    ```php
    // SELECT * FROM `users` ORDER BY age ASC, score DESC
    $query = $users->select()->orderByRaw('age ASC, score DESC');
    ```

  - Where

    Simple wheres,

    ```php
    // SELECT * FROM `users` WHERE age > 18
    $query = $users->select()->where('age > 18');

    // SELECT * FROM `users` WHERE `age` = 18
    $query = $users->select()->where('age', 18);

    // SELECT * FROM `users` WHERE `age` < 18
    $query = $users->select()->where('age', '<', 18);
    ```

    Multiple wheres,

    ```php
    // SELECT * FROM `users` WHERE `age` > 18 AND `gender` = 'male'
    $query = $users->select()->where(['age' => ['>', 18], 'gender' => 'male']);

    // same as above
    $query = $users->select()->where('age', '>', 18)->where('gender','male');
    ```

    Complex where,

    ```php
    // SELECT * FROM `users` WHERE (`id` = 1 OR (`id` < 20 OR `id` > 100))
    // OR `name` = 'Tester'
    $query = $users->select()->where(
                $builder->expr()->where('id', 1)->orWhere(
                    $builder->expr()->where('id', '<', 20)->orWhere('id', '>', 100)
                )
             )->orWhere('name', 'Tester');
    ```

    Raw mode,

    ```php
    // SELECT * FROM `users` WHERE age = 18 OR score > 90
    $query = $users->select()->whereRaw('age = 18')->orWhereRaw('score > 90');
    ```

    with `NOT`,

    ```php
    // SELECT * FROM `users` WHERE NOT `age` = 18 OR NOT `score` > 90
    $query = $users->select()->whereNot('age', 18)->orWhereNot('score', '>', 90);
    ```

    Where `IN` and `BETWEEN`

    ```php
    // SELECT * FROM `users` WHERE `age` IN (10,12,15,18,20) OR `score` NOT BETWEEN 90 AND 100
    $query = $users->select()->whereIn('age', [10,12,15,18,20])
            ->orWhereNotBetween('score', 90, 100);
    ```

    Where `IS NULL` and `IS NOT NULL`

    ```php
    // SELECT * FROM `users` WHERE `age` IS NULL OR `score` IS NOT NULL
    $query = $users->select()->whereNull('age')->orWhereNotNull('score');
    ```

    Exists,

    ```php
    $qry1  = $users->select('user_id')->where('age', '>', 60);
    $sales = $users->table('sales');

    // SELECT * FROM `sales` WHERE EXISTS (SELECT `user_id` FROM `users`
    // WHERE `age` > 60)
    $sql = $sales->select()->whereExists($qry1)->getStatement();
    ```

  - Having

    Similar to `WHERE` clause,

    ```php
    // SELECT * FROM `users` HAVING `age` = 10 OR `level` > 20
    $query = $users->select()->having('age', 10)->orHaving('level', '>', 20);
    ```

  - Union

    ```php
    // SELECT * FROM `users` UNION SELECT * FROM `oldusers1`
    // UNION ALL SELECT `user_id` FROM `oldusers2`
    $sql = $users->select()
            ->union()
                ->select()->from('oldusers1')
            ->unionAll()
                ->select('user_id')->from('oldusers2')
                ->getStatement()
    ```

- `INSERT`

  Single insert statement,

  ```php
  // INSERT INTO `users` (`uid`, `uname`) VALUES (2, 'phossa')
  $sql = $users->insert()->set('uid', 2)->set('uname', 'phossa')
      ->getStatement();

  // same as above, with array notation
  $sql = $users->insert()->set(['uid' => 2, 'uname' => 'phossa'])
      ->getStatement();
  ```

  Multiple data rows,

  ```php
  // INSERT INTO `users` (`uid`, `uname`) VALUES (2, 'phossa'), (3, 'test')
  $query = $users->insert()
            ->set(['uid' => 2, 'uname' => 'phossa'])
            ->set(['uid' => 3, 'uname' => 'test']);
  ```

  Insert with `DEFAULT` values

  ```php
  // INSERT INTO `users` (`uid`, `uname`, `phone`)
  // VALUES (2, 'phossa', DEFAULT), (3, 'test', '1234')
  $query = $users->insert([
      ['uid' => 2, 'uname' => 'phossa'],
      ['uid' => 3, 'uname' => 'test', 'phone' => '1234']
  ]);
  ```

  Insert `NULL` instead of default values,

  ```php
  // INSERT INTO `users` (`uid`, `uname`, `phone`)
  // VALUES (2, 'phossa', NULL), (3, 'test', '1234')
  $sql = $query->getStatement(['useNullAsDefault' => true]);
  ```

  Insert with `SELECT` subquery,

  ```php
  // INSERT INTO `users` (`uid`, `uname`)
  // SELECT `user_id`, `user_name` FROM `oldusers`
  $query = $users->insert()->set(['uid', 'uname'])
               ->select(['user_id', 'user_name'])
               ->from('oldusers');
  ```

- `UPDATE`

  Common update statement,

  ```php
  // UPDATE `users` SET `user_name` = 'phossa' WHERE `user_id` = 3
  $query = $users->update(['user_name' => 'phossa'])->where('user_id', 3);

  // UPDATE `users` SET `user_name` = 'phossa', `user_addr` = 'xxx'
  // WHERE `user_id` = 3
  $query = $users->update()->set('user_name','phossa')
      ->set('user_addr', 'xxx')->where('user_id', 3);
  ```

  With `Mysql` extensions,

  ```php
  // UPDATE IGNORE `users` SET `user_id` = user_id + 10 ORDER BY `user_id` ASC LIMIT 10
  $query = $users->update()->addHint('IGNORE')->set('user_id', $builder->raw('user_id + 10'))
      ->orderByASC('user_id')->limit(10);
  ```

- `REPLACE`

  Mysql version of replace,

  ```php
  // REPLACE LOW_PRIORITY INTO `users` (`user_id`, `user_name`) VALUES (3, 'phossa')
  $query = $users->replace(['user_id' => 3, 'user_name' => 'phossa'])
      ->addHint('low_priority');
  ```

  Sqlite version of replace,

  ```php
  // INSERT INTO `users` (`user_id`, `user_name`) VALUES (3, 'phossa')
  // ON CONFLICT REPLACE
  $query = $users->replace(['user_id' => 3, 'user_name' => 'phossa']);
  ```

- `DELETE`

  Single table deletion,

  ```php
  // DELETE FROM `users` WHERE `user_id` > 10 ORDER BY `user_id` ASC LIMIT 10
  $query = $users->delete()->where('user_id', '>', 10)
      ->orderByAsc('user_id')->limit(10);
  ```

  Multiple tables deletion

  ```php
  // DELETE `users`.* FROM `users` AS `u` INNER JOIN `accounts` AS `a`
  // ON `u`.`user_id` = `a`.`user_id` WHERE `a`.`total_amount` < 0
  $query = $users->delete('users')->from('users', 'u')
      ->join('accounts a', 'user_id')->where('a.total_amount', '<', 0);
  ```

- `CREATE TABLE`

  Create table is used by most of the ORM libraries.

  ```php
  $builder = new Builder();

  $builder->create()->table('new_table')
      ->temp()
      ->ifNotExists()
      ->addCol('id', 'INT')
          ->notNull()
          ->autoIncrement()
      ->addCol('name', 'VARCHAR(20)')
          ->notNull()
          ->unique()
          ->defaultValue('NONAME')
      ->addCol('alias', 'VARCHAR(10)')
          ->colConstraint('CHECK ()')
      ->primaryKey(['id'])
      ->uniqueKey(['name(4) ASC', 'alias'], 'ON CONFLICT REPLACE')
      ->uniqueKey(['id', 'alias'], 'ON CONFLICT ROLLBACK')
      ->constraint('FOREIGN KEY (...)')
      ->tblOption('DELAY_KEY_WRITE=1')
      ->tblOption('MAX_ROWS=100')
      ->getStatement([
          'seperator' => "\n",
          'indent'    => "  ",
      ]);
  ```

  With the following output,

  ```sql
  CREATE TEMPORARY TABLE IF NOT EXISTS "new_table"
  (
    "id" INT NOT NULL AUTO_INCREMENT,
    "name" VARCHAR(20) NOT NULL DEFAULT 'NONAME' UNIQUE,
    "alias" VARCHAR(10) CHECK (),
    PRIMARY KEY ("id"),
    UNIQUE ("name"(4) ASC, "alias") ON CONFLICT REPLACE,
    UNIQUE ("id", "alias") ON CONFLICT ROLLBACK,
    FOREIGN KEY (...)
  )
    DELAY_KEY_WRITE=1,
    MAX_ROWS=100
  ```

Advanced topics
---
- `expr()`

  Expression can be used to construct complex `WHERE`

  ```php
  // SELECT
  //     *
  // FROM
  //     "Users"
  // WHERE
  //    ("age" < 18 OR "gender" = 'female')
  //    OR ("age" > 60 OR ("age" > 55 AND "gender" = 'female'))
  $query = $builder->select()->from('Users')->where(
      $builder->expr()->where('age', '<', 18)->orWhere('gender', 'female')
  )->orWhere(
      $builder->expr()->where('age', '>' , 60)->orWhere(
          $builder->expr()->where('age', '>', 55)->where('gender', 'female')
      )
  );
  ```

  Join with complex `ON`,

  ```php
  $builder = $users->table(false);

  // SELECT * FROM `users` INNER JOIN `sales`
  // (ON `users`.`uid` = `sales`.`s_uid` OR `users`.`uid` = `sales`.`puid`)
  $sql = $users->select()->join('sales',
      $builder->expr()->on('users.uid', 'sales.s_uid')->orOn('users.uid', 'sales.puid')
  )->getStatement();
  ```

- `raw()`

  Raw string bypass the quoting and escaping,

  ```php
  // SELECT id FROM "students" WHERE "time" = NOW()
  $query = $builder->select()->field($builder->raw("id"))
      ->from("students")->where("time", $builder->raw('NOW()'));
  ```

  Raw string with parameters,

  ```php
  // SELECT * FROM "students" WHERE "age" IN RANGE(1, 1.2)
  $query = $builder->select()->from("students")->where("age", "IN",
      $builder->raw('RANGE(?, ?)', 1, 1.2));
  ```

- `before()` and `after()`

  Sometimes, non-standard SQL wanted and no methods found. `before()` and
  `after()` will come to rescue.

  ```php
  // INSERT IGNORE INTO "users" ("id", "name") VALUES (3, 'phossa')
  // ON DUPLICATE KEY UPDATE id=id+10
  $query = $users->insert()->set('id', 3)->set('name', 'phossa')
      ->before('INTO', 'IGNORE')
      ->after('VALUES', 'ON DUPLICATE KEY UPDATE id=id+?', 10);
  ```

- Parameters

  *phossa-query* can return statement for driver to prepare and use the
  `getBindings()` to get the values to bind.

  ```php
  $query = $users->select()->where("user_id", 10);

  // SELECT * FROM "users" WHERE "user_id" = ?
  $sql = $query->getPositionedStatement();

  // values to bind: [10]
  $val = $query->getBindings();
  ```

  Or named parameters,

  ```php
  $query = $users->select()->where("user_name", ':name');

  // SELECT * FROM "users" WHERE "user_name" = :name
  $sql = $query->getNamedStatement();
  ```

- Settings

  Settings can be applied to `$builder` at instantiation,

  ```php
  $users = new Builder(new Mysql(), 'users', ['autoQuote' => false]);
  ```

  Or applied when output with `getStatement()`,

  ```php
  $sql = $users->select()->getStatement(['autoQuote' => false]);
  ```

  List of settings,

  - `autoQuote`: boolean. Quote db identifier or not.

  - `positionedParam`: boolean. Output with positioned parameter or not.

  - `namedParam`: boolean. Output with named parameter or not.

  - `seperator`: string, default to ' '. Seperator between clauses.

  - `indent`: string, default to ''. Indent prefix for clauses.

  - `escapeFunction`: callabel, default to `null`. Function used to quote and
    escape values.

  - `useNullAsDefault`: boolean.

Dialects
---

- Mysql

Dependencies
---

- PHP >= 5.4.0

- phossa/phossa-shared 1.*

License
---

[MIT License](http://mit-license.org/)


text:
<template name="notVerified">
	<h2> You need to verify your email before you can view or upload models </h2>
</template>