text:
require 'pathname'

# Deps
# -----------------------------------------------------------------------
require 'nrser'
require 'nrser/refinements/types'
require 'nrser/props/immutable/instance_variables'

# Package
# -----------------------------------------------------------------------
require 'qb/repo/git'

# Refinements
# =======================================================================

using NRSER::Types

# Definitions
# =======================================================================

# An extension of {Pathname} that implements the facts we want about paths
# as {NRSER::Meta::Props}.
#
class QB::Path < Pathname

  # Mixins
  # =====================================================================

  include NRSER::Props::Immutable::InstanceVariables

  # Props
  # ======================================================================

  # Principle path properties
  # ---------------------------------------------------------------------
  #
  # Values stored as variables on the instance.
  #

  # The current working directory *relevant* to the path - basically, when
  # and where the instance was created, which may be on a totally different
  # system if the instance was loaded from data.
  #
  # TODO  Not totally flushed out yet, could imagine a lot of problems and
  #       weirdness, but it seems like we need something like this to make
  #       instances transportable. Issues with relative paths come to mind...
  #
  prop  :cwd,
        type: t.pathname,
        to_data: :to_s

  # The raw path argument used to instantiate the path object.
  #
  # NOTE  Because we reduce {Pathname} instances to {String} when converting
  #       to data, there is some lossy-ness. I guess it's similar to how
  #       symbols and strings all become strings when run through {JSON}
  #       dump and load.
  #
  prop  :raw,
        type: t.path,
        to_data: :to_s

  # Derived path properties
  # ---------------------------------------------------------------------
  #
  # On-demand values computed via method calls.
  #

  prop  :expanded,
        type: t.path,
        source: ->() { expand_path.to_s }

  prop  :exists,
        type: t.bool,
        source: :exist?

  prop  :is_expanded,
        type: t.bool,
        source: :expanded?

  prop  :is_absolute,
        type: t.bool,
        source: :absolute?

  prop  :is_relative,
        type: t.bool,
        source: :relative?

  prop  :is_dir,
        type: t.bool,
        source: :directory?

  prop  :is_file,
        type: t.bool,
        source: :file?

  prop  :is_cwd,
        type: t.bool,
        source: :cwd?

  prop  :is_symlink,
        type: t.bool,
        source: :symlink?

  prop  :relative,
        type: t.maybe( t.path ),
        source: :relative,
        to_data: :to_s

  prop  :realpath,
        type: t.maybe( t.path ),
        source: :try_realpath,
        to_data: :to_s

  prop  :is_realpath,
        type: t.bool,
        source: :realpath?

  # Composed properties
  # ---------------------------------------------------------------------
  #
  # On-demand values that point to other {NRSER::Meta::Props} instances.
  #

  prop  :git,
        type: QB::Repo::Git,
        source: :git

  # # Value would be *loadable* via init
  # prop  :packages,
  #       type: t.map( keys: t.sym, values: QB::Package ),
  #       default: ->() { QB::Package.all_from_path self }
  #
  #
  # # Value would be ignored by init and re-computed
  # prop  :packages,
  #       type: t.map( keys: t.sym, values: QB::Package ),
  #       source: ->() { QB::Package.all_from_path self },
  #       cache: true

  # Constructor
  # ======================================================================

  # @overload initialize path
  #   Initialize in the same way as you would a {Pathname}. {#cwd} is set to
  #   the current directory (via {Pathname#getwd}) and the `path` argument is
  #   assigned to {#raw}.
  #
  #   @param [String | Pathname] path
  #     Target path.
  #
  # @overload initialize **values
  #   Initialize by invoking {NRSER::Meta::Props#initialize_props}.
  #
  #   The {#raw} value is passed up to {Pathname#initialize}.
  #
  #   {#cwd} is accepted in `values`, allowing a re-instantiated object to
  #   "make sense" when the process' current directory may no longer be the
  #   one that data was constructed against.
  #
  #   {#cwd} defaults to the current directory (via {Pathname.getwd}) if not
  #   provided.
  #
  # @param **values see {NRSER::Meta::Props#initialize_props}
  #
  def initialize arg
    case arg
    when Hash
      super arg[:raw]
      initialize_props cwd: Pathname.getwd, **arg
    else
      super arg
      initialize_props raw: arg, cwd: Pathname.getwd
    end
  end # #initialize

  # Instance Methods
  # ======================================================================

  # @return [Boolean]
  #   `true` if `self` is equal to {#expand_path}.
  #
  def expanded?
    self == expand_path
  end

  # @return [Boolean]
  #   `true` if `self` is equal to {#cwd}.
  #
  def cwd?
    self == cwd
  end

  # Relative path from {#cwd} to `self`, if one exists.
  #
  # @return [QB::Path]
  #   If a relative path from {#cwd} to `self` exists.
  #
  # @return [nil]
  #   If no relative path from {#cwd} to `self` exists. Can't recall exactly
  #   how this happens, but I guess it can...
  #
  def relative
    begin
      relative_path_from cwd
    rescue ArgumentError => error
      nil
    end
  end

  # Like {Pathname#realpath} but returns {nil} instead of raising if there
  # isn't one.
  #
  # @return [nil]
  #   If there is no real path.
  #
  # @return [Pathname]
  #   If there is a real path.
  #
  def try_realpath
    begin
      realpath
    rescue SystemCallError => error
      nil
    end
  end

  # Is `self` already it's real path?
  #
  # @return [Boolean]
  #   `true` if `self` and {#try_realpath} are equal.
  #
  def realpath?
    self == try_realpath
  end # #realpath?

  # @return [Pathname]
  #   A regular (non-{QB::Path}) {Pathname} version of `self`.
  def path
    Pathname.new self
  end

  alias_method :pathname, :path

  # Composed Sub-Instances
  # ---------------------------------------------------------------------

  # {QB::Repo::Git} resource for the Git repo {#path} is in one, or {nil} if
  # it isn't.
  #
  # @return [QB::Repo::Git]
  #   If {#path} is in a Git repo.
  #
  # @return [nil]
  #   If {#path} is not in a Git repo.
  #
  def git
    unless instance_variable_defined? :@git
      @git = QB::Repo::Git.from_path path
    end

    @git
  end

  def gem
    unless instance_variable_defined? :@gem
      @gem = QB::Package::Gem.from_root_path path, repo: git
    end

    @gem
  end

end # class QB::Path


text:
title: Hello Rest Service
description: "Hello Rest Service - Tutorial showing how Knot.x can be used to transform a static website into a dynamic one. The tutorial uses the Google Books API to fetch data about books and Knot.x to inject it into an HTML template"
author: tomaszmichalak
keywords: tutorial
order: 2
date: 2017-02-23
layout: tutorial
knotxVersions:
  - 1.2.0
---
## Overview

In this tutorial, we're going to show how Knot.x can be used to quickly transform your
static website into a dynamic one. Instead of a manually coded HTML document presenting available books,
we're going to use an HTML template and populate it with data loaded from an external service.

This article concentrates on the steps required to integrate with a service using Knot.x, instead of client side JavaScript.
In the next article we are going to compare that solution with a frontend integration.

What you're going to learn:

- How to transform static HTML into dynamic content
- How to configure Knot.x to use simple REST services to get data
- How to use data from such services to dynamically populate HTML

If you want to skip the configuration part and simply run the demo, please checkout
[Github/hello-rest-service](https://github.com/Knotx/knotx-tutorials/tree/master/hello-rest-service) and follow the `README.md` to see how to run it.

## Book service – the service we're going to integrate with

We're going to use the [Google Books API](https://developers.google.com/books/) as a service feed with books.
To make the tutorial easy to follow, we use a very simple endpoint that [searches for all volumes](https://developers.google.com/books/docs/v1/using#WorkingVolumes) for the given query.

The goal is to display all volumes related to **java**
([https://www.googleapis.com/books/v1/volumes?q=java](https://www.googleapis.com/books/v1/volumes?q=java)).

A sample JSON response of the service looks like this:

``` json
{
  "kind":"books#volumes",
  "totalItems":605,
  "items":[
    {
      "kind":"books#volume",
      "id":"87totx4p3ZcC",
      "etag":"mviM5CD/Vg8",
      "selfLink":"https://www.googleapis.com/books/v1/volumes/87totx4p3ZcC",
      "volumeInfo":{
        "title":"Java in a Time of Revolution",
        "subtitle":"Occupation and Resistance, 1944-1946",
        "authors":[
          "Benedict Anderson"
        ],
        "publisher":"Equinox Publishing",
        "publishedDate":"2005-12-01",
        "description":"With remarkable scope and in scrupulous detail...",
        "pageCount":494,
        "imageLinks":{
          "smallThumbnail":"...",
           "thumbnail":"..."
         },
         "language":"en"
       }
    },
    ...
  ]
}
```

## Our application
Knot.x has the ability to combine service data with HTML in a very efficient manner.
It can get a JSON response from a service and then, using the Handlebars engine, render the dynamic part.
This can be achieved without any custom code – it is only a matter of configuration.

The diagram below depicts how a request from a user is handled by the Knot.x application.

![Books service diagram](/img/blog/hello-rest-service/books-service-diagram.jpg)

As soon as a request comes to Knot.x, it causes an HTML template to be fetched from the repository.
In real cases, the repository is usually an external system, like a CMS, that is available over HTTP.
However, for the purpose of demonstration, we simply get those HTML pages from the local filesystem using
the Knot.x File system repository connector.

At this point, Knot.x detects all services required to render your dynamic page. Actual service
endpoints are defined in Knot.x configuration, on the HTML level, each dynamic part simply specifies
which endpoint it requires (by name). The unique set of services required, initiates process of
querying services for the data, followed by an invocation of the Handlebars engine. The Handlebars engine
combines the markup and the data obtained form the services to produce the final markup of the dynamic HTML snippet.

Finally, the rendered HTML is returned to the requesting user.

## Start with Knot.x

Now it's the time to prepare the environment required to run Knot.x.
First, let's download all required files from the Nexus repository and create the folder structure that we're going to use in this tutorial.

Download the following files:
1. [Knot.x standalone fat jar](https://oss.sonatype.org/content/groups/public/io/knotx/knotx-standalone/1.2.0/knotx-standalone-1.2.0.fat.jar)
2. [JSON configuration file](https://oss.sonatype.org/content/groups/public/io/knotx/knotx-standalone/1.2.0/knotx-standalone-1.2.0.json)
3. [Log configuration file](https://oss.sonatype.org/content/groups/public/io/knotx/knotx-standalone/1.2.0/knotx-standalone-1.2.0.logback.xml)

Additionally, download the file `books.html` from GitHub. We're going to transform it into a dynamic one.

The directory tree should look like this:

```
├── knotx-config.json  (download from nexus knotx-standalone-1.2.0.json)
├── logback.xml (download from nexus knotx-standalone-1.2.0.logback.xml)
├── app
│   ├── knotx-standalone-1.2.0.fat.jar (download from nexus)
├── library
│   ├── html
│       ├── books.html (Taken from Knot.x tutorials Github)
```

To simplify Knot.x execution, create a `run.sh` script with the following content in the root folder:

```
#!/bin/bash
java -Dvertx.disableDnsResolver=true -Dlogback.configurationFile=logback.xml -cp "app/*" io.knotx.launcher.LogbackLauncher -conf knotx-config.json
```

You can try running Knot.x application with `./run.sh` command. But for now stop it and follow next steps to configure it to do something useful.
More details about Knot.x deployment and setup can be found [here](https://github.com/Cognifide/knotx/wiki/KnotxDeployment).

## Configure Knot.x

> All the configurations used in this tutorial are available on [Github/knotx-tutorials](https://github.com/Knotx/knotx-tutorials/tree/master/hello-rest-service)

As we already have a base Knot.x setup, let's start adapting it to our needs.
If you open the `knotx-config.json` file in a text editor, you wil see that it contains an array
containing a list of modules. These are the [Knot.x modules](https://github.com/Cognifide/knotx/wiki/KnotxModules)
that are going to be started.

```json
{
  "modules":[
    "knotx:io.knotx.KnotxServer",
    "knotx:io.knotx.HttpRepositoryConnector",
    "knotx:io.knotx.FilesystemRepositoryConnector",
    "knotx:io.knotx.FragmentSplitter",
    "knotx:io.knotx.FragmentAssembler",
    "knotx:io.knotx.ServiceKnot",
    "knotx:io.knotx.ActionKnot",
    "knotx:io.knotx.HandlebarsKnot",
    "knotx:io.knotx.HttpServiceAdapter"
  ]
}
```

All of the above modules are explained on the project [Wiki](https://github.com/Cognifide/knotx/wiki).
In this tutorial, we're going to pay attention to but a few of them.

In order to change the default configuration of any of the modules, you need to modify
this configuration JSON by adding a `config` JsonObject for the module(s) you want to modify, e.g.:

```json
{
 "modules": [...],
 "config": {
   "knotx:io.knotx.KnotxServer": {
     "options": {
        "config": {
           ...
        }
      }
    }
  }
}
```

You can find more details on how to configure Knot.x on [Wiki – How to Configure](https://github.com/Cognifide/knotx/wiki/KnotxDeployment#how-to-configure-).

### Repository configuration

As mentioned before, we are going to fetch an HTML template from our local file system.
Knot.x is shipped with a dedicated module called [`FileSystemRepositoryConnector`](https://github.com/Cognifide/knotx/wiki/FilesystemRepositoryConnector) designed
for this very purpose. You need set up the connector to use the `/library` folder from where requested HTML files
(containing Handlebars snippets) will be fetched.

```json
{
  "modules": [...],
  "config": {
    "knotx:io.knotx.FilesystemRepositoryConnector": {
      "options": {
        "config": {
          "catalogue": "./library/"
        }
      }
    }
  }
}
```

Different repository connectors can be used at the same time, so we need to tell Knot.x which one should be used to process a given request.
You can use regular expressions to match request URIs to different repositories.

Our template file (`books.html`) is available in the `html` folder, under the `library` root folder.
It means, that our target is that whenever a user performs a `GET` request for `/html/books.html`,
Knot.x should look for the `/html/books.html` file inside the `/library` folder on the local file system.
In order to achieve that, we need to tell KnotxServer module that:

> Any request to `/html/.*` should fetch a template from the file system repository.

```json
{
  "modules":[...],
  "config": {
    "knotx:io.knotx.FilesystemRepositoryConnector": {...},
    "knotx:io.knotx.KnotxServer": {
      "options": {
        "config": {
          "defaultFlow": {
            "repositories": [
              {
                "path": "/html/.*",
                "address": "knotx.core.repository.filesystem"
              }
            ]
          }
        }
      }
    }
  }
}
```

You might notice the `address` field in the above configuration. This is the internal event bus
address of the Repository Connector, in this case it's the address of our File System Repository Connector.

> All configuration options and default values, such as address fields, for each Knot.x module are described in the [documentation](https://github.com/Cognifide/knotx/wiki).

### Book service configuration
The [Service Knot](https://github.com/Cognifide/knotx/wiki/ServiceKnot) module is responsible for an integration with
external services.
The configuration of this module consists of services which can be used in any template
processed by Knot.x. Each service has an associated `name`, that is actually being used on HTML
level and an address of the Adapter that is handling communication with the outside world.
This kind of mapping makes possible a quick substitution of the acutal service being used.
You can supply multiple Adapter modules for any kind of protocol or interface. And as long as
the data provided by your adapter implementation has the same structure, you can swap it for another implementation.

```json
  "modules": [
    ...
  ],
  "config": {
    "knotx:io.knotx.KnotxServer": {
      ...
    },
    "knotx:io.knotx.FilesystemRepositoryConnector": {
      ...
    }
    "knotx:io.knotx.ServiceKnot": {
      "options": {
        "config": {
          "services": [
            {
              "name": "bookslist",
              "address": "knotx.adapter.service.http",
              "params": {
                "path": "/books/v1/volumes?q=java"
              }
            }
          ]
        }
      }
    }
  }
```

We're saying here, that:
- One service will be used and its name is `bookslist`
- The adapter address for this name is `knotx.adapter.service.http`
- Each service request using this name will be done under the path `/books/v1/volumes?q=java`

> As you see we specified the URI but not the address of the service. The actual endpoint will be
configured on the Adapter level. This configuration approach allows you to have two services
defined, each using the same adapter (and therefore the same endpoint), but have a different name and path.

The adapter address points to the [`HttpServiceAdapter`](https://github.com/Cognifide/knotx/wiki/HttpServiceAdapter)
that is available out of the box. So, as you can suspect, the remaining configuration
will happen in the Adapter module.

So let's do this.

```json
  "modules": [
    ...
  ],
  "config": {
    "knotx:io.knotx.KnotxServer": {
      ...
    },
    "knotx:io.knotx.FilesystemRepositoryConnector": {
      ...
    },
    "knotx:io.knotx.ServiceKnot": {
      ...
    },
    "knotx:io.knotx.HttpServiceAdapter": {
      "options": {
        "config": {
          "clientOptions": {
            "ssl": true
          },
          "services": [
            {
              "path": "/books.*",
              "domain": "www.googleapis.com",
              "port": 443
            }
          ]
        }
      }
    }
  }
```

We're saying here that:
- The HTTP Client making calls to HTTP services should consider using SSL if necessary
- List of services to which we're going to make calls, in our case there's just one
  - If the service URI starts with `/books`, e.g. `/books/v1/volumes?q=java`
  - Then use `www.googleapis.com:443`

At this point, we can say that Knot.x configuration is finished. You can download the final
configuration file from [here](https://github.com/Knotx/knotx-tutorials/blob/master/hello-rest-service/knotx-config.json).

## Template definition

Now it's the time for the markup. You started with `books.html` having only static markup.
Now, you can modify it by removing book items and inserting a new ***dynamic*** snippet.

```html
<script data-knotx-knots="services,handlebars"
   data-knotx-service="bookslist"
   type="text/knotx-snippet">
   {{#each _result.items}}
     <div class="col-sm-3">
     <div class="card">
       <img class="card-img-top"
          src="{{volumeInfo.imageLinks.thumbnail}}"
          alt="{{volumeInfo.title}}">
       <div class="card-block">
         <h4 class="card-title">{{volumeInfo.title}}</h4>
         <p class="card-text">
           {{#each volumeInfo.authors as |author|}}
             {{author}}{{#unless @last}}, {{/unless}}
           {{/each}}<br />
           Published: {{volumeInfo.publishedDate}}
         </p>
       </div>
      </div>
      </div>
   {{/each}}
</script>
```

The most important elements of the above markup are:

- `data-knotx-service="bookslist"` - defines that the service named `bookslist` is required,
- `_result` object in Handlebars expressions is the root of data fetched from service,
- the path to the object under `_result` is actually the path to an object in the JSON document returned by the service `https://www.googleapis.com/books/v1/volumes?q=java`

> Knot.x provides the extensible Handlebars mechanism that allows you to specify very lightweight templates by implementing your own custom Handlebars helpers.

The final HTML markup can be found [here](https://github.com/Knotx/knotx-tutorials/blob/master/hello-rest-service/library/html/books.html).

## Run ***dynamic*** page
So, now it's time to run our new, ***dynamic*** page. Just start Knot.x using the `./run.sh` command
and go to [`http://localhost:8092/html/books.html`](http://localhost:8092/html/books.html) in your favourite browser.

redpajama_set_name: RedPajamaGithub


text:
<?php

abstract class A_DataObject
{
	/**
	 * Instance of db adapter
	 *
	 * @var Zend_Db_Adapter_Abstract
	 */
	protected $oDb;

	/**
	 * Primary Key definition
	 *
	 * @var array
	 */
	private $aPrimaryValue = array();

	/**
	 * The list of modified fields
	 *
	 * @var array
	 */
	private $aModifiedFields = array();

	/**
	 * Name of DB table
	 *
	 * @var string
	 */
	private $sTableName;

	/**
	 * Is object removed
	 *
	 * @var bool
	 */
	private $bDeleted = false;

	/**
	 * Whether the object is modified
	 *
	 * @var bool
	 */
	private $bModified = false;

	/**
	 * Constructor, sets necessary data for the data object
	 * Warning: In child class use this constructor!
	 *
	 * @param	string	$sTableName		name of DB table connected with model
	 * @param	array	$aPrimaryKey	array with prmiary key description (<field name> => <field value>)
	 * @return	A_DataObject
	 */
	public function __construct($sTableName, array $aPrimaryKey)
	{
		$this->oDb = Zend_Registry::get('db');

		$this->sTableName = $sTableName;
		$this->aPrimaryValue = $aPrimaryKey;
	}

	/**
	 * Do not allow serialization of a database object
	 */
	public function __sleep()
	{
		$oReflect = new ReflectionClass($this);
		$aResult = array();

		// analizuję pola klasy i odrzucam pole bazy danych
		foreach($oReflect->getProperties() as $oProperty)
		{
			if($oProperty->getName() != 'oDb')
			{
				$aResult[] = $oProperty->getName();
			}
		}

		return $aResult;
	}

	/**
	 * Loads database object after usnserialize
	 */
	public function __wakeup()
	{
		$this->oDb = Zend_Registry::get('db');
	}

	/**
	 * Delete object from DB
	 *
	 * @return void
	 */
	public function delete()
	{
		$this->oDb->delete($this->sTableName, $this->getWhereString());
		$this->bDeleted = true;
	}

	/**
	 * Save object to DB
	 *
	 * @return	void
	 */
	public function save()
	{
		// is deleted
		if($this->bDeleted)
		{
			throw new A_DataObject_Exception('Object is already deleted, you cannot save it.');
		}

		// check whether any data has been modified
		if($this->bModified)
		{
			$this->oDb->update(
				$this->sTableName,
				$this->aModifiedFields,
				$this->getWhereString()
			);

			$this->aModifiedFields = array();
			$this->bModified = false;
		}
	}

	/**
	 * Returns DB table name
	 *
	 * @return	string
	 */
	protected function getTableName()
	{
		return $this->sTableName;
	}

	/**
	 * Returns true, if object was modified
	 *
	 * @return bool
	 */
	final protected function isModified()
	{
		return $this->bModified;
	}

	/**
	 * Set new DB field value
	 *
	 * @param	string	$sField		DB field name
	 * @param	string	$mValue		new field value
	 * @return	void
	 */
	final protected function setDataValue($sField, $mValue)
	{
		$this->aModifiedFields[$sField] = $mValue;
		$this->bModified = true;
	}

	/**
	 * Returns SQL WHERE code for Primary Key fields
	 *
	 * @return string
	 */
	private function getWhereString()
	{
		$oWhere = new A_DataObject_Where();

		foreach($this->aPrimaryValue as $sField => $sValue)
		{
			$oWhere->addAnd($sField . ' = ?', $sValue);
		}

		return $oWhere->getWhere();
	}
}


text:
<!DOCTYPE html>
<html>
<body>

    <video controls src="video.ogv">Your browser does not support the video tag.</video>

</body>
</html>


text:
import gulp from 'gulp';
import changed from 'gulp-changed';

import config from '../../config';

var imgConfig = config.public.images;

gulp.task('public:images', () => {
  return gulp.src(imgConfig.src)
    .pipe(changed(imgConfig.dest))
    .pipe(gulp.dest(imgConfig.dest));
});


text:
package com.microsoft.azure.management.appservice.v2018_02_01;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;

/**
 * Details about restoring a deleted app.
 */
@JsonFlatten
public class DeletedAppRestoreRequest extends ProxyOnlyResource {
    /**
     * ARM resource ID of the deleted app. Example:
     * /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}.
     */
    @JsonProperty(value = "properties.deletedSiteId")
    private String deletedSiteId;

    /**
     * If true, deleted site configuration, in addition to content, will be
     * restored.
     */
    @JsonProperty(value = "properties.recoverConfiguration")
    private Boolean recoverConfiguration;

    /**
     * Point in time to restore the deleted app from, formatted as a DateTime
     * string.
     * If unspecified, default value is the time that the app was deleted.
     */
    @JsonProperty(value = "properties.snapshotTime")
    private String snapshotTime;

    /**
     * Get aRM resource ID of the deleted app. Example:
     /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}.
     *
     * @return the deletedSiteId value
     */
    public String deletedSiteId() {
        return this.deletedSiteId;
    }

    /**
     * Set aRM resource ID of the deleted app. Example:
     /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}.
     *
     * @param deletedSiteId the deletedSiteId value to set
     * @return the DeletedAppRestoreRequest object itself.
     */
    public DeletedAppRestoreRequest withDeletedSiteId(String deletedSiteId) {
        this.deletedSiteId = deletedSiteId;
        return this;
    }

    /**
     * Get if true, deleted site configuration, in addition to content, will be restored.
     *
     * @return the recoverConfiguration value
     */
    public Boolean recoverConfiguration() {
        return this.recoverConfiguration;
    }

    /**
     * Set if true, deleted site configuration, in addition to content, will be restored.
     *
     * @param recoverConfiguration the recoverConfiguration value to set
     * @return the DeletedAppRestoreRequest object itself.
     */
    public DeletedAppRestoreRequest withRecoverConfiguration(Boolean recoverConfiguration) {
        this.recoverConfiguration = recoverConfiguration;
        return this;
    }

    /**
     * Get point in time to restore the deleted app from, formatted as a DateTime string.
     If unspecified, default value is the time that the app was deleted.
     *
     * @return the snapshotTime value
     */
    public String snapshotTime() {
        return this.snapshotTime;
    }

    /**
     * Set point in time to restore the deleted app from, formatted as a DateTime string.
     If unspecified, default value is the time that the app was deleted.
     *
     * @param snapshotTime the snapshotTime value to set
     * @return the DeletedAppRestoreRequest object itself.
     */
    public DeletedAppRestoreRequest withSnapshotTime(String snapshotTime) {
        this.snapshotTime = snapshotTime;
        return this;
    }

}


text:
#ifndef ONESIDEMERGECONFIGURATION_HPP_
#define ONESIDEMERGECONFIGURATION_HPP_

#include <merging/automergeconfiguration.hpp>

using namespace std;

namespace kdb
{

namespace tools
{

namespace merging
{

// This configuration is like the auto merge configuration except
// that it resolves any unresolved conflicts by using one side only
class OneSideMergeConfiguration : public AutoMergeConfiguration
{

private:
	ConflictResolutionSide winningSide;

public:
	explicit OneSideMergeConfiguration (ConflictResolutionSide _winningSide) : winningSide (_winningSide)
	{
	}
	virtual void configureMerger (ThreeWayMerge & merger) override;
};
} // namespace merging
} // namespace tools
} // namespace kdb

#endif /* ONESIDEMERGECONFIGURATION_HPP_ */


text:
.. _dijit/_Calendar:

===============
dijit/_Calendar
===============

*Deprecated*.   Use :ref:`dijit/Calendar <dijit/Calendar>` instead.


text:
var exec = require('child_process').exec;

function MonitoringTarget(id) {
	this.id = id;
	this.data;
	this.refreshTime;

	this.listener = [];
	this.interval = 0;
	this.cmd = "";

	var reg = new RegExp(/ +/g);
	switch (id) {
		case "all":
			this.cmd = "top -p -n 1 -b";
			break;
		case "sys":
			break;
		default:
			this.cmd = "top -p " + this.id + " -n 1 -b";
			break;
	}

	if (typeof this.tick === "undefined") {
		MonitoringTarget.prototype.addListener = function(client) {
			this.listener.push(client);

			if(this.interval === 0){this.interval = client.intervalList[this.id];return;}
			for(var i = Math.min(client.intervalList[this.id], this.interval); i > 0; i--){
				if(this.interval % i === 0 && client.intervalList[this.id] % i === 0){
					this.interval = client.intervalList[this.id];
					return;
				}
			}
		};
		MonitoringTarget.prototype.removeListener = function(client) {
			var findClient = false;
			for(var i = this.listener.length - 1; i >= 0; i--){
				if(this.listener[i].id === client.id){
					this.listener.splice(i, 1);
					findClient = true;
				}
			}
			if(!findClient){return}

			//重新计算最大公约数
			var intervals = [];
			for(var i = 0; i < this.listener.length; i++){
				intervals.push(this.listener[i].intervalList[this.id]);
			}
			var min = Math.min.apply(Math, intervals);
			if(min === Infinity) {return;}
			for(var i = min; i > 0; i--){
				var find = true;
				for(var j = 0; j < intervals.lenght; j++){
					if(intervals[i] % i !== 0){
						find = false;
						break;
					}
				}
				if(find){
					this.interval = i;
					break;
				}
			}
		};

		MonitoringTarget.prototype.refreshCallback = function(error, stdout, stderr, tock) {
			if(error){console.log("monitoring target error: id[" + this.id + "]  cmd[" + this.cmd + "]" + (new Date() - 0));}
			if(stderr){console.log("monitoring target stderr: id[" + this.id + "]  cmd[" + this.cmd + "]" + (new Date() - 0));}

			this.refreshTime = new Date();
			this.data = this.formateData(stdout);
		};
		MonitoringTarget.prototype.tick = function(tock) {
			if (tock % this.interval !== 0) return;
			var self = this;
			exec(this.cmd, function(error, stdout, stderr){self.refreshCallback(error, stdout, stderr, tock);});
		};
		MonitoringTarget.prototype.formateData  = function(data){
			var tmpData = data.split("\n")[7].trim().replace(reg, ',').split(",");
			return {
				cpu: tmpData[8],
				ram: tmpData[9],
			};
		};
	}
}

exports.MonitoringTarget = MonitoringTarget;


text:
//
//  AEFCrashReporting.h
//  OctoCrash
//
//  Created by Alex Fish on 18/12/2013.
//  Copyright (c) 2013 alexefish. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol AEFCrashReporting <NSObject>

/**
 The Github repository to report crashes to, in the format org/name or user/name
 E.g alexfish/octocrash
 */
@property (nonatomic, copy, readonly) NSString *repo;

/**
 Github OAuth application client ID
 */
@property (nonatomic, copy, readonly) NSString *clientID;

/**
 Githuv OAuth application client secret
 */
@property (nonatomic, copy, readonly) NSString *clientSecret;

@end


text:
package org.hisp.dhis.system;

import java.util.Date;

import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.system.database.DatabaseInfo;
import org.springframework.beans.BeanUtils;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

/**
 * @author Lars Helge Overland
 */
@JacksonXmlRootElement( localName = "systemInfo", namespace = DxfNamespaces.DXF_2_0 )
public class SystemInfo
{
    // -------------------------------------------------------------------------
    // Transient properties
    // -------------------------------------------------------------------------

    private String contextPath;

    private String userAgent;

    // -------------------------------------------------------------------------
    // Volatile properties
    // -------------------------------------------------------------------------

    private String calendar;

    private String dateFormat;

    private Date serverDate;

    private Date lastAnalyticsTableSuccess;

    private String intervalSinceLastAnalyticsTableSuccess;

    // -------------------------------------------------------------------------
    // Stable properties
    // -------------------------------------------------------------------------

    private String version;

    private String revision;

    private Date buildTime;

    private String environmentVariable;

    private String javaVersion;

    private String javaVendor;

    private String javaHome;

    private String javaIoTmpDir;

    private String javaOpts;

    private String osName;

    private String osArchitecture;

    private String osVersion;

    private String externalDirectory;

    private DatabaseInfo databaseInfo;

    private String memoryInfo;

    private Integer cpuCores;

    private String systemId;

    public SystemInfo instance()
    {
        SystemInfo info = new SystemInfo();
        BeanUtils.copyProperties( this, info );
        return info;
    }

    // -------------------------------------------------------------------------
    // Logic
    // -------------------------------------------------------------------------

    public void clearSensitiveInfo()
    {
        this.javaVersion = null;
        this.javaVendor = null;
        this.javaHome = null;
        this.javaIoTmpDir = null;
        this.javaOpts = null;
        this.osName = null;
        this.osArchitecture = null;
        this.osVersion = null;
        this.externalDirectory = null;
        this.databaseInfo = null;
        this.memoryInfo = null;
        this.cpuCores = null;
        this.systemId = null;
    }

    // -------------------------------------------------------------------------
    // Getters and setters
    // -------------------------------------------------------------------------

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getContextPath()
    {
        return contextPath;
    }

    public void setContextPath( String contextPath )
    {
        this.contextPath = contextPath;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getUserAgent()
    {
        return userAgent;
    }

    public void setUserAgent( String userAgent )
    {
        this.userAgent = userAgent;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getCalendar()
    {
        return calendar;
    }

    public void setCalendar( String calendar )
    {
        this.calendar = calendar;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getDateFormat()
    {
        return dateFormat;
    }

    public void setDateFormat( String dateFormat )
    {
        this.dateFormat = dateFormat;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Date getServerDate()
    {
        return serverDate;
    }

    public void setServerDate( Date serverDate )
    {
        this.serverDate = serverDate;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Date getLastAnalyticsTableSuccess()
    {
        return lastAnalyticsTableSuccess;
    }

    public void setLastAnalyticsTableSuccess( Date lastAnalyticsTableSuccess )
    {
        this.lastAnalyticsTableSuccess = lastAnalyticsTableSuccess;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getIntervalSinceLastAnalyticsTableSuccess()
    {
        return intervalSinceLastAnalyticsTableSuccess;
    }

    public void setIntervalSinceLastAnalyticsTableSuccess( String intervalSinceLastAnalyticsTableSuccess )
    {
        this.intervalSinceLastAnalyticsTableSuccess = intervalSinceLastAnalyticsTableSuccess;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getVersion()
    {
        return version;
    }

    public void setVersion( String version )
    {
        this.version = version;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getRevision()
    {
        return revision;
    }

    public void setRevision( String revision )
    {
        this.revision = revision;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Date getBuildTime()
    {
        return buildTime;
    }

    public void setBuildTime( Date buildTime )
    {
        this.buildTime = buildTime;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getEnvironmentVariable()
    {
        return environmentVariable;
    }

    public void setEnvironmentVariable( String environmentVariable )
    {
        this.environmentVariable = environmentVariable;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getJavaVersion()
    {
        return javaVersion;
    }

    public void setJavaVersion( String javaVersion )
    {
        this.javaVersion = javaVersion;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getJavaVendor()
    {
        return javaVendor;
    }

    public void setJavaVendor( String javaVendor )
    {
        this.javaVendor = javaVendor;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getJavaHome()
    {
        return javaHome;
    }

    public void setJavaHome( String javaHome )
    {
        this.javaHome = javaHome;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getJavaIoTmpDir()
    {
        return javaIoTmpDir;
    }

    public void setJavaIoTmpDir( String javaIoTmpDir )
    {
        this.javaIoTmpDir = javaIoTmpDir;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getJavaOpts()
    {
        return javaOpts;
    }

    public void setJavaOpts( String javaOpts )
    {
        this.javaOpts = javaOpts;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getOsName()
    {
        return osName;
    }

    public void setOsName( String osName )
    {
        this.osName = osName;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getOsArchitecture()
    {
        return osArchitecture;
    }

    public void setOsArchitecture( String osArchitecture )
    {
        this.osArchitecture = osArchitecture;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getOsVersion()
    {
        return osVersion;
    }

    public void setOsVersion( String osVersion )
    {
        this.osVersion = osVersion;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getExternalDirectory()
    {
        return externalDirectory;
    }

    public void setExternalDirectory( String externalDirectory )
    {
        this.externalDirectory = externalDirectory;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public DatabaseInfo getDatabaseInfo()
    {
        return databaseInfo;
    }

    public void setDatabaseInfo( DatabaseInfo databaseInfo )
    {
        this.databaseInfo = databaseInfo;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getMemoryInfo()
    {
        return memoryInfo;
    }

    public void setMemoryInfo( String memoryInfo )
    {
        this.memoryInfo = memoryInfo;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Integer getCpuCores()
    {
        return cpuCores;
    }

    public void setCpuCores( Integer cpuCores )
    {
        this.cpuCores = cpuCores;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getSystemId()
    {
        return systemId;
    }

    public void setSystemId( String systemId )
    {
        this.systemId = systemId;
    }
}


text:
alias pu='pushd'
alias po='popd'

# Basic directory operations
alias ...='cd ../..'
alias -- -='cd -'

# Super user
alias _='sudo'
alias please='sudo'

#alias g='grep -in'

# Show history
if [ "$HIST_STAMPS" = "mm/dd/yyyy" ]
then
    alias history='fc -fl 1'
elif [ "$HIST_STAMPS" = "dd.mm.yyyy" ]
then
    alias history='fc -El 1'
elif [ "$HIST_STAMPS" = "yyyy-mm-dd" ]
then
    alias history='fc -il 1'
else
    alias history='fc -l 1'
fi
# List direcory contents
alias lsa='ls -lah'
alias l='ls -lah'
alias ll='ls -lh'
alias la='ls -lAh'

alias afind='ack-grep -il'

# ---------

alias be='bundle exec'
alias sublime2='open -a ~/Applications/Sublime\ Text.app'
alias atom='open -a /Applications/Atom.app'
alias rubymine='open -a /Applications/RubyMine.app'
alias sourcetree='open -a /Applications/SourceTree.app'
alias st='open -a /Applications/SourceTree.app'

# alias eb='source ./.aws_credential; eb'

alias aws_208="export AWS_CREDENTIAL_FILE=/Users/aki_/.elasticbeanstalk/aws_credential_file.208; echo aws_credential_file.208"
alias aws_smilenet="export AWS_CREDENTIAL_FILE=/Users/aki_/.elasticbeanstalk/aws_credential_file.smilenet; echo aws_credential_file.smilenet"
alias aws_smilenet_staging="export AWS_CREDENTIAL_FILE=/Users/aki_/.elasticbeanstalk/aws_credential_file.smilenet_staging; echo aws_credential_file.smilenet_staging"

alias aws_credential_file.fpapp_staging="export AWS_CREDENTIAL_FILE=/Users/aki_/.elasticbeanstalk/aws_credential_file.fpapp_staging; echo aws_credential_file.fpapp_staging"


text:
using namespace std;

int main () {
  int myints[] = { 10, 20, 30 ,40 };
  int * p;
  vector<int> myvector (myints,myints+4);
  vector<int>::iterator it;

  //pointer to array element:
  p = find(myints,myints+4,30);
  ++p;
  cout << "The element following 30 is " << *p << endl;

  // iterator to vector element:
  it = find (myvector.begin(), myvector.end(), 30);
  assert(*it != 30);
  ++it;
  cout << "The element following 30 is " << *it << endl;

  return 0;
}


text:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}

module Network.API.Shopify.Client (
    createF
  , CrudF(..)
  , deleteF
  , httpShopify
  , readF
  , SCrudable(..)
  , updateF
  ) where

import Control.Monad.Free (Free(Free, Pure))
import Control.Monad.Trans (liftIO, MonadIO)
import Control.Monad.Trans.Reader (ask, ReaderT)
import Data.Aeson (decode, encode)
import Data.ByteString.Lazy (ByteString)
import Data.Proxy (Proxy)
import Network.HTTP.Client (httpLbs, Manager, RequestBody (RequestBodyLBS), Response(responseBody, responseStatus), Request(requestBody))
import Network.HTTP.Types.Status (Status(Status))
import Network.API.Shopify.Request (
    authorizeRequest
  , createMetafieldReq
  , createProductReq
  , createVariantReq
  , deleteMetafieldReq
  , deleteProductReq
  , deleteVariantReq
  , readMetafieldReq
  , readProductReq
  , readProductsReq
  , readVariantReq
  , updateMetafieldReq
  , updateProductReq
  , updateVariantReq
  )
import Network.API.Shopify.Types (
    Metafield
  , MetafieldId
  , APICredential
  , Product
  , ProductId
  , ShopifyError(ErrorResponseBodyNotParseable, ErrorHTTPResponseCode)
  , StoreName
  , Variant
  , VariantId
  )

-- | crudable types
data Crudable = MetafieldCRUD
              | ProductCRUD
              | ProductsR
              | VariantCRUD

-- | singleton support
data SCrudable (c :: Crudable) :: * where
    SMetafield :: SCrudable 'MetafieldCRUD
    SProduct   :: SCrudable 'ProductCRUD
    SProducts  :: SCrudable 'ProductsR
    SVariant   :: SCrudable 'VariantCRUD

-- | type family that maps a Crudable type to its type
type family CrudBase (c :: Crudable) :: * where
    CrudBase 'MetafieldCRUD = Metafield
    CrudBase 'ProductCRUD   = Product
    CrudBase 'ProductsR     = [Product]
    CrudBase 'VariantCRUD   = Variant

-- | type family mapping: (Crudable Type) X (Interface) -> required data to create
type family CreateData (c :: Crudable) :: * where
    CreateData 'MetafieldCRUD = Metafield
    CreateData 'ProductCRUD   = Product
    CreateData 'VariantCRUD   = Variant

-- | type family mapping: (Crudable Type) X (Interface) -> required data to create
type family ReadData (c :: Crudable) :: * where
    ReadData 'MetafieldCRUD = MetafieldId
    ReadData 'ProductCRUD   = ProductId
    ReadData 'ProductsR     = Proxy ()
    ReadData 'VariantCRUD   = VariantId

-- | type family mapping: (Crudable Type) X (Interface) -> required data to create
type family UpdateData (c :: Crudable) :: * where
    UpdateData 'MetafieldCRUD = (MetafieldId, Metafield)
    UpdateData 'ProductCRUD   = (ProductId, Product)
    UpdateData 'VariantCRUD   = (VariantId, Variant)

-- | type family mapping: (Crudable Type) X (Interface) -> required data to create
type family DeleteData (c :: Crudable) :: * where
    DeleteData 'MetafieldCRUD = MetafieldId
    DeleteData 'ProductCRUD   = ProductId
    DeleteData 'VariantCRUD   = VariantId

-- | CRUD Algebra
data CrudF a where
    CreateF :: SCrudable c
            -> CreateData c
            -> (Either ShopifyError (CrudBase c) -> a)
            -> CrudF a
    ReadF   :: SCrudable c
            -> ReadData c
            -> (Either ShopifyError (CrudBase c) -> a)
            -> CrudF a
    UpdateF :: SCrudable c
            -> UpdateData c
            -> (Either ShopifyError () -> a)
            -> CrudF a
    DeleteF :: SCrudable c
            -> DeleteData c
            -> (Either ShopifyError () -> a)
            -> CrudF a

instance Functor CrudF where
  fmap f (CreateF c d g) = CreateF c d (f . g)
  fmap f (ReadF   c d g) = ReadF   c d (f . g)
  fmap f (UpdateF c d g) = UpdateF c d (f . g)
  fmap f (DeleteF c d g) = DeleteF c d (f . g)

-- | smart create constructor.
createF :: SCrudable c
        -> CreateData c
        -> Free CrudF (Either ShopifyError (CrudBase c))
createF c d = Free $ CreateF c d Pure

-- | smart read constructor.
readF :: SCrudable c
      -> ReadData c
      -> Free CrudF (Either ShopifyError (CrudBase c))
readF c d = Free $ ReadF c d Pure

-- | smart update constructor.
updateF :: SCrudable c
        -> UpdateData c
        -> Free CrudF (Either ShopifyError ())
updateF c d = Free $ UpdateF c d Pure

-- | smart delete constructor.
deleteF :: SCrudable c
        -> DeleteData c
        -> Free CrudF (Either ShopifyError ())
deleteF c d = Free $ DeleteF c d Pure

-- | Method to create `Request` objects for create requests.
-- purpusefully non-exhuastive as we cannot "create" via the
-- Products endpoint. This is still safe as any attempt to match
-- on SProductsR will yield a type error as CreateData 'ProductsR
-- is not specified.
createRequest :: SCrudable c
              -> CreateData c
              -> StoreName
              -> APICredential
              -> Request
createRequest SMetafield d storeName cred =
    authorizeRequest cred req
      where req = (createMetafieldReq storeName) {
                requestBody = RequestBodyLBS body
            }
            body = encode d
createRequest SProduct d storeName cred =
    authorizeRequest cred req
      where req = (createProductReq storeName) {
                requestBody = RequestBodyLBS body
            }
            body = encode d
createRequest SVariant d storeName cred =
    authorizeRequest cred req
      where req = (createVariantReq storeName) {
                requestBody = RequestBodyLBS body
            }
            body = encode d

-- | method to create `Request` objects for read requests.
readRequest :: SCrudable c
            -> ReadData c
            -> StoreName
            -> APICredential
            -> Request
readRequest SMetafield d storeName cred =
    authorizeRequest cred (readMetafieldReq storeName d)
readRequest SProduct d storeName cred =
    authorizeRequest cred (readProductReq storeName d)
readRequest SProducts _ storeName cred =
    authorizeRequest cred (readProductsReq storeName)
readRequest SVariant d storeName cred =
    authorizeRequest cred (readVariantReq storeName d)

-- | method to create `Request` objects for update requests
updateRequest :: SCrudable c
              -> UpdateData c
              -> StoreName
              -> APICredential
              -> Request
updateRequest SMetafield (metafieldId,d) storeName cred =
    authorizeRequest cred req
      where req = (updateMetafieldReq storeName metafieldId) {
                requestBody = RequestBodyLBS body
            }
            body = encode d
updateRequest SProduct (productId,d) storeName cred =
    authorizeRequest cred req
      where req = (updateProductReq storeName productId) {
                requestBody = RequestBodyLBS body
            }
            body = encode d
updateRequest SVariant (variantId,d) storeName cred =
    authorizeRequest cred req
      where req = (updateVariantReq storeName variantId) {
                requestBody = RequestBodyLBS body
            }
            body = encode d

-- | method to create `Request` objects for delete requests
deleteRequest :: SCrudable c
              -> DeleteData c
              -> StoreName
              -> APICredential
              -> Request
deleteRequest SMetafield d storeName cred =
    authorizeRequest cred (deleteMetafieldReq storeName d)
deleteRequest SProduct d storeName cred =
    authorizeRequest cred (deleteProductReq storeName d)
deleteRequest SVariant d storeName cred =
    authorizeRequest cred (deleteVariantReq storeName d)

-- | handle response codes.
checkResponse :: Response b -> Either ShopifyError ()
checkResponse resp = case responseStatus resp of
    (Status 200 _) -> Right ()
    (Status 201 _) -> Right ()
    (Status 202 _) -> Right ()
    (Status 203 _) -> Right ()
    (Status 204 _) -> Right ()
    (Status 205 _) -> Right ()
    (Status 206 _) -> Right ()
    _              -> Left ErrorHTTPResponseCode

-- | helper method to handle http responses
-- for type inference reasons, we need to pattern match on
-- SCrudable type.
decodeResponse :: SCrudable c
               -> Response ByteString
               -> Either ShopifyError (CrudBase c)
decodeResponse SMetafield resp = checkResponse resp >>= \_ -> case decode (responseBody resp) of
    Nothing  -> Left ErrorResponseBodyNotParseable
    Just val -> Right val
decodeResponse SProduct resp = checkResponse resp >>= \_ -> case decode (responseBody resp) of
    Nothing  -> Left ErrorResponseBodyNotParseable
    Just val -> Right val
decodeResponse SProducts resp = checkResponse resp >>= \_ -> case decode (responseBody resp) of
    Nothing  -> Left ErrorResponseBodyNotParseable
    Just val -> Right val
decodeResponse SVariant resp = checkResponse resp >>= \_ -> case decode (responseBody resp) of
    Nothing  -> Left ErrorResponseBodyNotParseable
    Just val -> Right val

-- | HTTP interpreter
-- TODO: error handling
httpShopify :: (MonadIO m)
            => Free CrudF a
            -> ReaderT (Manager, StoreName, APICredential) m a
httpShopify (Pure a) = return a
httpShopify (Free (CreateF s d g)) = do
    (mgr, storeName, cred) <- ask
    response <- liftIO $ httpLbs (createRequest s d storeName cred) mgr
    httpShopify . g . decodeResponse s $ response
httpShopify (Free (ReadF s d g)) = do
    (mgr, storeName, cred) <- ask
    response <- liftIO $ httpLbs (readRequest s d storeName cred) mgr
    httpShopify . g . decodeResponse s $ response
httpShopify (Free (UpdateF s d g)) = do
    (mgr, storeName, cred) <- ask
    response <- liftIO $ httpLbs (updateRequest s d storeName cred) mgr
    httpShopify . g . checkResponse $ response
httpShopify (Free (DeleteF s d g)) = do
    (mgr, storeName, cred) <- ask
    response <- liftIO $ httpLbs (deleteRequest s d storeName cred) mgr
    httpShopify . g . checkResponse $ response


text:
/*
 * 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.
 */
/**
 * Trellis Rosid: an implementation of the core Trellis API, using file-based persistence
 *
 *
This package implements the core resource and session interfaces of trellis.
 * it provides a persistence layer and read/write operations to that persistence layer.

 *
 * @author acoburn
 */
package org.trellisldp.rosid.file;


text:
package com.skynav.ttv.model.value;

public class TextReserve {

    public enum Position {
        NONE,
        BEFORE,
        AFTER,
        BOTH,
        OUTSIDE,
        AROUND,
        BETWEEN,
        AUTO;
        public static Position fromValue(String v) {
            return Position.valueOf(v.toUpperCase());
        }
    };

    public static final TextReserve NONE       = new TextReserve(Position.NONE, null);

    private Position position;
    private Length reserve;

    public TextReserve(Position position, Length reserve) {
        this.position = position;
        this.reserve = reserve;
    }

    public Position getPosition() {
        return position;
    }

    public Length getReserve() {
        return reserve;
    }

}


text:
Imports GH_IO.Serialization
Imports Grasshopper.Kernel.Types
Imports Owl.Core.Tensors
Imports Owl.Core.IO

Public Class GH_OwlTensorSet
    Inherits GH_Goo(Of TensorSet)

    Sub New()
        MyBase.New
    End Sub

    Sub New(V As TensorSet)
        MyBase.New(V)
    End Sub

    Public Overrides ReadOnly Property IsValid As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides ReadOnly Property TypeDescription As String
        Get
            Return "TensorSet"
        End Get
    End Property

    Public Overrides ReadOnly Property TypeName As String
        Get
            Return "TensorSet"
        End Get
    End Property

    Public Overrides Function Duplicate() As IGH_Goo
        Return New GH_OwlTensorSet(Me.Value.Duplicate)
    End Function

    Public Overrides Function ToString() As String
        Return Me.Value.ToString
    End Function

    Public Overrides Function CastTo(Of Q)(ByRef target As Q) As Boolean

        Select Case GetType(Q)
            Case GetType(TensorSet)
                Dim mev As TensorSet = Me.Value.Duplicate
                Dim obj As Object = mev
                target = obj
                Return True
        End Select

        Return False

    End Function

    Public Overrides Function CastFrom(source As Object) As Boolean
        Select Case source.GetType
            Case GetType(Tensor)
                Dim tens As Tensor = DirectCast(source, Tensor)
                tens = tens.Duplicate
                Me.Value = New TensorSet({tens})
                Return True
            Case GetType(TensorSet)
                Me.Value = DirectCast(source, TensorSet)
                Return True
            Case GetType(GH_String)
                Dim thiss As GH_String = source
                Me.Value = New TensorSet(thiss.Value)
                Return True
            Case GetType(String)
                Dim this As String = source
                Me.Value = New TensorSet(this)
                Return True
        End Select

        Return False
    End Function

    Public Overrides Function Read(reader As GH_IReader) As Boolean
        Dim ts As New TensorSet

        For i As Integer = 0 To reader.GetInt64("TensorSetCount") - 1 Step 1
            ts.Add(ReadOne(reader, i))
        Next

        Me.Value = ts

        Return True
    End Function

    Public Overrides Function Write(writer As GH_IWriter) As Boolean

        writer.SetInt64("TensorSetCount", Me.Value.Count)

        For i As Integer = 0 To Me.Value.Count - 1 Step 1
            WriteOne(Me.Value(i), writer, i)
        Next

        Return True
    End Function

    Public Function ReadOne(reader As GH_IReader, Suffix As String) As Tensor
        Dim shape As New List(Of Integer)
        Dim cnt As Integer = reader.GetInt32("ShapeCount_" & Suffix)

        For i As Integer = 0 To cnt - 1 Step 1
            shape.Add(reader.GetInt32("S" & i & "_" & Suffix))
        Next

        Return New Tensor(shape, reader.GetDoubleArray("Data_" & Suffix))
    End Function

    Public Function WriteOne(tens As Tensor, writer As GH_IWriter, Suffix As String) As Boolean
        writer.SetInt32("ShapeCount_" & Suffix, tens.ShapeCount)
        Dim shape As List(Of Integer) = tens.GetShape

        For i As Integer = 0 To tens.ShapeCount - 1 Step 1
            writer.SetInt32("S" & i & "_" & Suffix, shape(i))
        Next

        writer.SetDoubleArray("Data_" & Suffix, tens.ToArray)
        Return True
    End Function

End Class


text:
import zmq

def main():
    try:
        context = zmq.Context(1)
        # Socket facing clients
        frontend = context.socket(zmq.PULL)
        frontend.bind('tcp://*:5559')

        # Socket facing services
        backend = context.socket(zmq.PUSH)
        backend.bind('tcp://*:5560')

        zmq.device(zmq.STREAMER, frontend, backend)
    except Exception, e:
        print('{}\nbringing down zmq device'.format(e))
    finally:
        frontend.close()
        backend.close()
        context.term()

if __name__ == '__main__':
    main()


text:
package de.jtem.jrworkspace.plugin.sidecontainer.widget;

import static java.awt.GridBagConstraints.BOTH;
import static java.awt.GridBagConstraints.REMAINDER;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

/**
 * A container class which can stack ShrinkPanels and scroll them
 *

 * Copyright 2005 Stefan Sechelmann
 * TU-Berlin
 * @author Stefan Sechelmann
 */
public class ShrinkSlotVertical extends ShrinkSlot implements MouseMotionListener, MouseListener, MouseWheelListener {

	private static final long
		serialVersionUID = 1L;
	protected JPanel
		content = new JPanel();
	protected JScrollPane
		scroller = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
	protected List<ShrinkPanel>
		panels = new LinkedList<ShrinkPanel>();
	private Map<ShrinkPanel, Integer>
		positionMap = new HashMap<ShrinkPanel, Integer>();
	private GridBagLayout
		gbl = new GridBagLayout();
	protected GridBagConstraints
		normalConstraints = new GridBagConstraints(),
		fillConstraints = new GridBagConstraints();
	private JPanel
		fillPanel = new JPanel();
	private int
		lastDrag = 0;
	private boolean
		showInsertHint = false;
	private Point
		insertHintPoint = new Point();
	private int
		width = 200;

	public ShrinkSlotVertical(int width){
		this.width = width;
		content.setLayout(gbl);

		fillConstraints.fill = BOTH;
		fillConstraints.gridheight = 1;
		fillConstraints.gridwidth = REMAINDER;
		fillConstraints.weightx = 1.0;
		fillConstraints.weighty = 1.0;

		normalConstraints.fill = BOTH;
		normalConstraints.gridheight = 1;
		normalConstraints.gridwidth = REMAINDER;
		normalConstraints.weightx = 1.0;
		normalConstraints.weighty = 0.0;

		scroller.setViewportView(content);
		scroller.setBorder(BorderFactory.createEmptyBorder());
		scroller.addMouseWheelListener(this);

		setLayout(new GridLayout());
		super.add(scroller);
		updateLayout();
	}

	protected void updateLayout() {
		content.removeAll();
		boolean fillerNeeded = true;
		for (ShrinkPanel sp : panels) {
			if (sp.isFillSpace()) {
				if (sp.isShrinked()) {
					content.add(sp, normalConstraints);
				} else {
					fillerNeeded = false;
					content.add(sp, fillConstraints);
				}
			} else {
				content.add(sp, normalConstraints);
			}
		}
		if (fillerNeeded) {
			content.add(fillPanel, fillConstraints);
		}
		if (panels.size() == 0) {
			setPreferredSize(new Dimension(10, 10));
			setMinimumSize(new Dimension(10, 10));
		} else {
			setPreferredSize(null);
			setMinimumSize(new Dimension(width, 10));
		}
		content.doLayout();
		revalidate();
		updateUI();
	}

	@Override
    public Component add(Component arg0) {
		throw new UnsupportedOperationException("Use addShrinkPanel()");
    }

	@Override
	public void addShrinkPanel(ShrinkPanel panel){
		addShrinkPanelAt(panel, panel.getPreferredPosition());
	}

	@Override
	public void addShrinkPanelAt(ShrinkPanel panel, Point p) {
		int scroll = scroller.getVerticalScrollBar().getValue();
		Point scrollPoint = new Point(p.x, p.y + scroll);
		Component c = content.getComponentAt(scrollPoint);
		if (c instanceof ShrinkPanel) {
			addShrinkPanelAt(panel, positionMap.get(c));
		} else {
			TreeSet<Integer> posSet = new TreeSet<Integer>(positionMap.values());
			if (posSet.size() != 0) {
				addShrinkPanelAt(panel, posSet.last() + 1);
			} else {
				addShrinkPanelAt(panel, 0);
			}
		}
		positionMap.clear();
		for (ShrinkPanel pl : panels) {
			positionMap.put(pl, panels.lastIndexOf(pl));
		}
	}

	protected void addShrinkPanelAt(ShrinkPanel p, int pos) {
		Collection<Integer> occupied = positionMap.values();
		if (occupied.contains(pos)) {
			List<ShrinkPanel> panelList = new LinkedList<ShrinkPanel>(positionMap.keySet());
			for (ShrinkPanel panel : panelList) {
				int panelPos = positionMap.get(panel);
				if (panelPos >= pos) {
					positionMap.remove(panel);
					positionMap.put(panel, panelPos + 1);
					panel.setPreferredPosition(panelPos + 1);
				}
			}
		}
		positionMap.put(p, pos);
		p.setPreferredPosition(pos);

		TreeSet<Integer> posSet = new TreeSet<Integer>(positionMap.values());
		ShrinkPanel[] panelArray = new ShrinkPanel[posSet.last() + 1];
		for (ShrinkPanel panel : positionMap.keySet()) {
			panelArray[positionMap.get(panel)] = panel;
		}

		panels.clear();
		for (ShrinkPanel panel : panelArray) {
			if (panel != null) {
				panels.add(panel);
			}
		}

		updateMouseListeners(p);
		p.setParentSlot(this);
		updateLayout();
		revalidate();
		repaint();
	}

	@Override
	public void removeShrinkPanel(ShrinkPanel panel){
	    content.remove(panel);
	    panels.remove(panel);
	    positionMap.remove(panel);
	    removeMouseListeners(panel);
	    updateLayout();
	    revalidate();
	}

	private void updateMouseListeners(Container container) {
		if (container instanceof JScrollPane) {
			return;
		}
		container.removeMouseListener(this);
		container.removeMouseMotionListener(this);
		container.removeMouseWheelListener(this);
		container.addMouseListener(this);
		container.addMouseMotionListener(this);
		container.addMouseWheelListener(this);
		for (Component c : container.getComponents()) {
			if (c instanceof Container) {
				updateMouseListeners((Container) c);
			}
		}
	}

	private void removeMouseListeners(Container container) {
		container.removeMouseWheelListener(this);
		container.removeMouseMotionListener(this);
		container.removeMouseListener(this);
		for (Component c : container.getComponents()) {
			if (c instanceof Container) {
				removeMouseListeners((Container) c);
			}
		}
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		JScrollBar vert = scroller.getVerticalScrollBar();
		int schroll_pos = vert.getValue();
		vert.setValue(schroll_pos - (e.getY() - lastDrag));
		lastDrag = e.getY() - (e.getY() - lastDrag);
	}

	@Override
	public void mouseMoved(MouseEvent arg0) {
	}
	@Override
	public void mouseClicked(MouseEvent arg0) {
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		lastDrag = arg0.getY();
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
	}
	@Override
	public void mouseEntered(MouseEvent arg0) {
	}
	@Override
	public void mouseExited(MouseEvent arg0) {
	}

    @Override
	public void mouseWheelMoved(MouseWheelEvent m) {
        int dx = -m.getUnitsToScroll() * 5;
		JScrollBar vert = scroller.getVerticalScrollBar();
		int schroll_pos = vert.getValue();
		vert.setValue(schroll_pos - dx);
		lastDrag = dx;
    }

    @Override
    protected void paintChildren(Graphics g) {
    	scroller.setBorder(null);
    	super.paintChildren(g);
    }

    @Override
    public void showInsertHint(boolean show, Point p) {
    	showInsertHint = show;
    	insertHintPoint = p;
    	repaint();
    }

    @Override
    public void paint(Graphics g) {
    	super.paint(g);
    	if (showInsertHint) {
    		Dimension size = getSize();
    		g.setColor(Color.BLACK);
    		g.drawRect(0, 0, size.width - 1, size.height - 1);

    		int scroll = scroller.getVerticalScrollBar().getValue();
    		Point scrollPoint = new Point(insertHintPoint.x, insertHintPoint.y + scroll);
    		Component c = content.getComponentAt(scrollPoint);
    		if (c != null) {
				Rectangle r = c.getBounds();
				int hint = Math.max(r.y + 1 - scroll, 0);
				g.draw3DRect(0, hint, getSize().width, 2, false);
    		}
    	}
    }

    public int getPreferredWidth() {
    	return width;
    }

    @Override
    public void updateUI() {
    	super.updateUI();
    	if (fillPanel != null) {
    		fillPanel.updateUI();
    	}
    }

}


text:
package ingestevents

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"io"

	"go.skia.org/infra/go/paramtools"
	"go.skia.org/infra/go/skerr"
	"go.skia.org/infra/go/util"
)

// IngestEvent is the PubSub body that is sent from the ingesters each time
// a new file is ingested.
type IngestEvent struct {
	// TraceIDs is a list of all the unencoded trace ids that appeared in the ingested file.
	TraceIDs []string

	// ParamSet is the unencoded ParamSet summary of TraceIDs.
	ParamSet paramtools.ReadOnlyParamSet

	// Filename of the file ingested.
	Filename string
}

// CreatePubSubBody takes an IngestEvent and returns a byte slice that is a
// gzipp'd JSON encoded version of that event. We gzip the to stay below the
// 10MB limit for PubSub data.
func CreatePubSubBody(body *IngestEvent) ([]byte, error) {
	var buf bytes.Buffer
	err := util.WithGzipWriter(&buf, func(w io.Writer) error {
		return json.NewEncoder(w).Encode(body)
	})
	return buf.Bytes(), skerr.Wrap(err)
}

// DecodePubSubBody decodes an IngestEvent encoded by CreatePubSubBody.
func DecodePubSubBody(b []byte) (*IngestEvent, error) {
	var ret IngestEvent
	buf := bytes.NewBuffer(b)
	r, err := gzip.NewReader(buf)
	if err != nil {
		return nil, skerr.Wrapf(err, "Failed to decode gzip'd IngestEvent.")
	}
	if err := json.NewDecoder(r).Decode(&ret); err != nil {
		return nil, skerr.Wrapf(err, "Failed to decode JSON IngestEvent.")
	}
	return &ret, nil
}


text:
#include "config.h"

#if ENABLE(SVG)
#include "SVGPolygonElement.h"

#include "Path.h"

namespace WebCore {

inline SVGPolygonElement::SVGPolygonElement(const QualifiedName& tagName, Document* document)
    : SVGPolyElement(tagName, document)
{
}

PassRefPtr<SVGPolygonElement> SVGPolygonElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new SVGPolygonElement(tagName, document));
}

void SVGPolygonElement::toPathData(Path& path) const
{
    ASSERT(path.isEmpty());

    SVGPointList& points = pointList();
    if (points.isEmpty())
        return;

    path.moveTo(points.first());

    unsigned size = points.size();
    for (unsigned i = 1; i < size; ++i)
        path.addLineTo(points.at(i));

    path.closeSubpath();
}

}

#endif // ENABLE(SVG)


text:
/********************************************************************************
** Form generated from reading UI file 'leveleditor.ui'
**
** Created by: Qt User Interface Compiler version 5.5.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_LEVELEDITOR_H
#define UI_LEVELEDITOR_H

#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QTreeWidget>
#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE

class Ui_LevelEditorClass
{
public:
    QAction *actionCreate_Static_Entity;
    QAction *actionCreate_Dynamic_Entity;
    QAction *actionSaveFile;
    QAction *actionCreate_Gravity_Area;
    QAction *actionCreate_Gravity_Well;
    QAction *actionExit;
    QWidget *centralWidget;
    QTreeWidget *treeWidget;
    QGroupBox *groupBox_Data;
    QMenuBar *menuBar;
    QMenu *menuFile;
    QToolBar *mainToolBar;
    QStatusBar *statusBar;

    void setupUi(QMainWindow *LevelEditorClass)
    {
        if (LevelEditorClass->objectName().isEmpty())
            LevelEditorClass->setObjectName(QStringLiteral("LevelEditorClass"));
        LevelEditorClass->resize(1920, 1080);
        actionCreate_Static_Entity = new QAction(LevelEditorClass);
        actionCreate_Static_Entity->setObjectName(QStringLiteral("actionCreate_Static_Entity"));
        actionCreate_Dynamic_Entity = new QAction(LevelEditorClass);
        actionCreate_Dynamic_Entity->setObjectName(QStringLiteral("actionCreate_Dynamic_Entity"));
        actionSaveFile = new QAction(LevelEditorClass);
        actionSaveFile->setObjectName(QStringLiteral("actionSaveFile"));
        actionCreate_Gravity_Area = new QAction(LevelEditorClass);
        actionCreate_Gravity_Area->setObjectName(QStringLiteral("actionCreate_Gravity_Area"));
        actionCreate_Gravity_Well = new QAction(LevelEditorClass);
        actionCreate_Gravity_Well->setObjectName(QStringLiteral("actionCreate_Gravity_Well"));
        actionExit = new QAction(LevelEditorClass);
        actionExit->setObjectName(QStringLiteral("actionExit"));
        centralWidget = new QWidget(LevelEditorClass);
        centralWidget->setObjectName(QStringLiteral("centralWidget"));
        treeWidget = new QTreeWidget(centralWidget);
        QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
        __qtreewidgetitem->setText(0, QStringLiteral("1"));
        treeWidget->setHeaderItem(__qtreewidgetitem);
        treeWidget->setObjectName(QStringLiteral("treeWidget"));
        treeWidget->setGeometry(QRect(1590, 20, 256, 361));
        groupBox_Data = new QGroupBox(centralWidget);
        groupBox_Data->setObjectName(QStringLiteral("groupBox_Data"));
        groupBox_Data->setGeometry(QRect(1500, 440, 381, 221));
        LevelEditorClass->setCentralWidget(centralWidget);
        menuBar = new QMenuBar(LevelEditorClass);
        menuBar->setObjectName(QStringLiteral("menuBar"));
        menuBar->setGeometry(QRect(0, 0, 1920, 21));
        menuFile = new QMenu(menuBar);
        menuFile->setObjectName(QStringLiteral("menuFile"));
        LevelEditorClass->setMenuBar(menuBar);
        mainToolBar = new QToolBar(LevelEditorClass);
        mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
        LevelEditorClass->addToolBar(Qt::TopToolBarArea, mainToolBar);
        statusBar = new QStatusBar(LevelEditorClass);
        statusBar->setObjectName(QStringLiteral("statusBar"));
        LevelEditorClass->setStatusBar(statusBar);

        menuBar->addAction(menuFile->menuAction());
        menuFile->addAction(actionSaveFile);
        menuFile->addAction(actionExit);
        mainToolBar->addAction(actionCreate_Static_Entity);
        mainToolBar->addAction(actionCreate_Dynamic_Entity);
        mainToolBar->addAction(actionCreate_Gravity_Area);
        mainToolBar->addAction(actionCreate_Gravity_Well);

        retranslateUi(LevelEditorClass);

        QMetaObject::connectSlotsByName(LevelEditorClass);
    } // setupUi

    void retranslateUi(QMainWindow *LevelEditorClass)
    {
        LevelEditorClass->setWindowTitle(QApplication::translate("LevelEditorClass", "LevelEditor", 0));
        actionCreate_Static_Entity->setText(QApplication::translate("LevelEditorClass", "Create Static Entity", 0));
        actionCreate_Dynamic_Entity->setText(QApplication::translate("LevelEditorClass", "Create Dynamic Entity", 0));
        actionSaveFile->setText(QApplication::translate("LevelEditorClass", "Save", 0));
        actionSaveFile->setShortcut(QApplication::translate("LevelEditorClass", "Ctrl+S", 0));
        actionCreate_Gravity_Area->setText(QApplication::translate("LevelEditorClass", "Create Gravity Area", 0));
        actionCreate_Gravity_Well->setText(QApplication::translate("LevelEditorClass", "Create Gravity Well", 0));
        actionExit->setText(QApplication::translate("LevelEditorClass", "Exit", 0));
        groupBox_Data->setTitle(QApplication::translate("LevelEditorClass", "Data", 0));
        menuFile->setTitle(QApplication::translate("LevelEditorClass", "File", 0));
    } // retranslateUi

};

namespace Ui {
    class LevelEditorClass: public Ui_LevelEditorClass {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_LEVELEDITOR_H


text:
<?php

namespace Ivory\GoogleMap\Helper\Controls;

use Ivory\GoogleMap\Controls\ControlPosition;
use Ivory\GoogleMap\Exception\HelperException;

/**
 * Control position helper.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class ControlPositionHelper
{
    /**
     * Renders a control position.
     *
     * @param string $controlPosition The control position.
     *
     * @throws \Ivory\GoogleMap\Exception\HelperException If the control position is not valid.
     *
     * @return The JS output.
     */
    public function render($controlPosition)
    {
        switch ($controlPosition) {
            case ControlPosition::BOTTOM_CENTER:
            case ControlPosition::BOTTOM_LEFT:
            case ControlPosition::BOTTOM_RIGHT:
            case ControlPosition::LEFT_BOTTOM:
            case ControlPosition::LEFT_CENTER:
            case ControlPosition::LEFT_TOP:
            case ControlPosition::RIGHT_BOTTOM:
            case ControlPosition::RIGHT_CENTER:
            case ControlPosition::RIGHT_TOP:
            case ControlPosition::TOP_CENTER:
            case ControlPosition::TOP_LEFT:
            case ControlPosition::TOP_RIGHT:
                return sprintf('google.maps.ControlPosition.%s', strtoupper($controlPosition));
            default:
                throw HelperException::invalidControlPosition();
        }
    }
}


text:
BosSTAN
===================

Aplikasi Pengelolaan dana Bantuan Operasional Sekolah
-------------------
Aplikasi ini adalah aplikasi Pengelolaan dana Bantuan Operasional Sekolah untuk Sekolah. Repositori ini berisi Community Version dari aplikasi bosstan yang dikembangkan oleh [bosstan.id](https://bosstan.id) dan dapat digunakan secara bebas dengan perizinan dari kami.

Silahkan hubungi heru@belajararief.com untuk dapat menggunakan aplikasi ini.

Aplikasi ini merupakan aplikasi yang ditujukan untuk penggunaan akademik sehingga tidak dipungut biaya untuk penggunaannya.

Demo:  [Demo](http://showcase.belajararief.com/bossan)

User Diknas : diknas/diknas

user Sekolah: sekolah/sekolah

Database
------------

Restore database yang tersimpan dalam aplikasi ini.

INSTALLATION
------------

### Install via Composer

If you do not have [Composer](http://getcomposer.org/), you may install it by following the instructions
at [getcomposer.org](http://getcomposer.org/doc/00-intro.md#installation-nix).

Make sure you have fxp-asset-plugin installed. If not, run this following code:
~~~
composer global require "fxp/composer-asset-plugin:~1.3"
~~~

For additional information of fxp-asset-plugin visit this [link](https://github.com/fxpio/composer-asset-plugin/blob/master/Resources/doc/index.md).

You can then install this project template using the following command:

~~~
php composer update
~~~

Then configure your application to connect to database via _protected/config/db.php

Now you should be able to access the application through the following URL

~~~
http://localhost/bossan
~~~


text:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
//session_start();
class Municipio extends MX_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->library('template');
		$this->load->library('menu');
		$this->load->model('municipio_model');
	}

	public function index()
	{
		if($this->session->userdata('id')):
			$session_data=$this->session->userdata();
			$data['usuario']=$session_data['username'];
			$data['iduser']=$session_data['id'];
			$data['idperfil']=$session_data['idperfil'];
			$data['menu']=$this->menu->crea_menu($data['idperfil']);
			$data['css']='';
			$data['js']='<script src="'.base_url('assets/js/res.js').'"></script>';

			$data['municipios'] = $this->municipio_model->desplega_municipios();
			$this->template->load('template','municipio',$data);
		else:
			redirect('login/index','refresh');
		endif;
	}

	public function agrega_municipio()
	{
		$municipio = $this->input->get('municipio');
		$data["result"] = $this->municipio_model->agrega_municipio($municipio);
		$new = $data["result"][0]["mensaje"];
		if($new=="Error"):
			echo '{"msg":"ko"}';
		else:
			echo '{"msg":"'.$new.'"}';
		endif;
	}

	public function modifica_municipio()
	{
		$idmunicipio = $this->input->get('idmunicipio');
		$municipio = $this->input->get('municipio');
		$data["result"] = $this->municipio_model->modifica_municipio($idmunicipio,$municipio);
		$new = $data["result"][0]["mensaje"];
		if($new=="Error"):
			echo '{"msg":"ko"}';
		else:
			echo '{"msg":"'.$new.'"}';
		endif;
	}

	public function carga_localidad()
	{
		$municipio = $this->input->post('municipio');
		$elementos = $this->municipio_model->desplega_municipio($municipio);
		$data["municipio"]=$elementos[0]->nombre_municipio;
		$data["idmunicipio"]=$elementos[0]->idmunicipio;
		$data['localidades'] = $this->municipio_model->desplega_localidades_municipio($municipio);
		$this->load->view('municipio_localidad',$data);
	}

	public function agrega_localidad()
	{
		$idmunicipio = $this->input->get('idmunicipio');
		$localidad = $this->input->get('localidad');
		$data["result"] = $this->municipio_model->agrega_localidad($idmunicipio,$localidad);
		$new = $data["result"][0]["mensaje"];
		if($new=="Error"):
			echo '{"msg":"ko"}';
		else:
			echo '{"msg":"'.$new.'"}';
		endif;
	}

	public function modifica_localidad()
	{
		$idlocalidad = $this->input->get('idlocalidad');
		$localidad = $this->input->get('localidad');
		$data["result"] = $this->municipio_model->modifica_localidad($idlocalidad,$localidad);
		$new = $data["result"][0]["mensaje"];
		if($new=="Error"):
			echo '{"msg":"ko"}';
		else:
			echo '{"msg":"'.$new.'"}';
		endif;
	}
}
?>


text:
import Action, { updateError, resource } from '../../actions'

export function validateProfile({username, email, dob, zipcode, password, pwconf}) {
    if (username) {
        if (!username.match('^[a-zA-Z][a-zA-Z0-9]+')) {
            return 'Invalid username.  Must start with a letter and can only contains letters and numbers.'
        }
    }

    if (email) {
        if (!email.match('^[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z][a-zA-Z]+$')) {
            return 'Invalid email.  Must be like a@b.co'
        }
    }

    if (zipcode) {
        if (!zipcode.match('^[0-9]{5}$')) {
            return 'Invalid zipcode.  Must be 5 digits in length, e.g., 77005'
        }
    }

    if(dob) {
        return 'You cannot change the date of birth'
    }

    if (password || pwconf) {
        if (password !== pwconf) {
            return 'Password do not match'
        }
        // enforce strong passwords!
    }

    return ''
}

export function updateHeadline(headline) {
    return (dispatch) => {
        dispatch(updateField('headline', headline))
    }
}

export function updateProfile({email, dob, zipcode, password, pwconf}) {
    return (dispatch) => {
        const err = validateProfile({email, dob, zipcode, password, pwconf})
        if (err.length > 0) {
            return dispatch(updateError(err))
        }
        dispatch(updateField('email', email))
        dispatch(updateField('zipcode', zipcode))
        dispatch(updateField('password', password))
    }
}

export function fetchProfile() {
    return (dispatch) => {
        dispatch(fetchField('avatars'))
        dispatch(fetchField('zipcode'))
        dispatch(fetchField('email'))
        dispatch(fetchField('dob'))
    }
}

function updateField(field, value) {
    return (dispatch) => {
        if (value) {
            const payload = {}
            payload[field] = value
            resource('PUT', field, payload).then((response) => {
                const action = { type: Action.UPDATE_PROFILE }
                action[field] = response[field]
                if (field == 'password')
                    dispatch(updateError('successfully update the password'))
                else
                    dispatch(action)
            })
        }
    }
}

function fetchField(field) {
    return (dispatch) => {
        resource('GET', field).then((response) => {
            const action = { type: Action.UPDATE_PROFILE }
            switch(field) {
                case 'avatars':
                    action.avatar = response.avatars[0].avatar; break;
                case 'email':
                    action.email = response.email; break;
                case 'zipcode':
                    action.zipcode = response.zipcode; break;
                case 'dob':
                    action.dob = new Date(response.dob).toDateString(); break;
            }
            dispatch(action)
        })
    }
}


text:
/*
 * Created by IntelliJ IDEA.
 * User: Anna.Kozlova
 * Date: 16-Aug-2006
 * Time: 16:56:21
 */
package com.intellij.openapi.roots.ui.configuration;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl;
import com.intellij.openapi.roots.ui.configuration.projectRoot.JdkConfigurable;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel;
import com.intellij.openapi.ui.MasterDetailsComponent;
import com.intellij.openapi.ui.MasterDetailsStateService;
import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Conditions;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.util.Consumer;
import com.intellij.util.Icons;
import com.intellij.util.containers.Convertor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class ProjectJdksConfigurable extends MasterDetailsComponent {

  private final ProjectSdksModel myProjectJdksModel;
  private final Project myProject;
  @NonNls
  private static final String SPLITTER_PROPORTION = "project.jdk.splitter";

  public ProjectJdksConfigurable(Project project) {
    super();
    myProject = project;
    myProjectJdksModel = ProjectStructureConfigurable.getInstance(project).getProjectJdksModel();
    MasterDetailsStateService.getInstance(project).register("ProjectJDKs.UI", this);
    initTree();
  }

  protected void initTree() {
    super.initTree();
    new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
      public String convert(final TreePath treePath) {
        return ((MyNode)treePath.getLastPathComponent()).getDisplayName();
      }
    }, true);

    myTree.setRootVisible(false);
  }

  public void reset() {
    super.reset();

    myProjectJdksModel.reset(myProject);

    myRoot.removeAllChildren();
    final HashMap<Sdk, Sdk> sdks = myProjectJdksModel.getProjectSdks();
    for (Sdk sdk : sdks.keySet()) {
      final JdkConfigurable configurable = new JdkConfigurable((ProjectJdkImpl)sdks.get(sdk), myProjectJdksModel, TREE_UPDATER, myHistory, myProject);
      addNode(new MyNode(configurable), myRoot);
    }
    selectJdk(myProjectJdksModel.getProjectSdk()); //restore selection
    final String value = PropertiesComponent.getInstance().getValue(SPLITTER_PROPORTION);
    if (value != null) {
      try {
        final Splitter splitter = extractSplitter();
        if (splitter != null) {
          (splitter).setProportion(Float.parseFloat(value));
        }
      }
      catch (NumberFormatException e) {
        //do not set proportion
      }
    }
  }

  @Nullable
  private Splitter extractSplitter() {
    final Component[] components = myWholePanel.getComponents();
    if (components.length == 1 && components[0] instanceof Splitter) {
      return (Splitter)components[0];
    }
    return null;
  }

  public void apply() throws ConfigurationException {
    super.apply();
    boolean modifiedJdks = false;
    for (int i = 0; i < myRoot.getChildCount(); i++) {
      final NamedConfigurable configurable = ((MyNode)myRoot.getChildAt(i)).getConfigurable();
      if (configurable.isModified()) {
        configurable.apply();
        modifiedJdks = true;
      }
    }

    if (myProjectJdksModel.isModified() || modifiedJdks) myProjectJdksModel.apply(this);
    myProjectJdksModel.setProjectSdk(getSelectedJdk());
 }

  public boolean isModified() {
    return super.isModified() || myProjectJdksModel.isModified();
  }

  public void disposeUIResources() {
    final Splitter splitter = extractSplitter();
    if (splitter != null) {
      PropertiesComponent.getInstance().setValue(SPLITTER_PROPORTION, String.valueOf(splitter.getProportion()));
    }
    myProjectJdksModel.disposeUIResources();
    super.disposeUIResources();
  }

  @Nullable
  protected ArrayList<AnAction> createActions(final boolean fromPopup) {
    final ArrayList<AnAction> actions = new ArrayList<AnAction>();
    DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("add.new.jdk.text"), true);
    group.getTemplatePresentation().setIcon(Icons.ADD_ICON);
    myProjectJdksModel.createAddActions(group, myTree, new Consumer<Sdk>() {
      public void consume(final Sdk projectJdk) {
        addNode(new MyNode(new JdkConfigurable(((ProjectJdkImpl)projectJdk), myProjectJdksModel, TREE_UPDATER, myHistory, myProject), false), myRoot);
        selectNodeInTree(findNodeByObject(myRoot, projectJdk));
      }
    });
    actions.add(new MyActionGroupWrapper(group));
    actions.add(new MyDeleteAction(Conditions.alwaysTrue()));
    return actions;
  }

  protected void processRemovedItems() {
    final Set<Sdk> jdks = new HashSet<Sdk>();
    for(int i = 0; i < myRoot.getChildCount(); i++){
      final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i);
      final NamedConfigurable namedConfigurable = (NamedConfigurable)node.getUserObject();
      jdks.add(((JdkConfigurable)namedConfigurable).getEditableObject());
    }
    final HashMap<Sdk, Sdk> sdks = new HashMap<Sdk, Sdk>(myProjectJdksModel.getProjectSdks());
    for (Sdk sdk : sdks.values()) {
      if (!jdks.contains(sdk)) {
        myProjectJdksModel.removeSdk(sdk);
      }
    }
  }

  protected boolean wasObjectStored(Object editableObject) {
    //noinspection RedundantCast
    return myProjectJdksModel.getProjectSdks().containsKey((Sdk)editableObject);
  }

  @Nullable
  public Sdk getSelectedJdk() {
    return (Sdk)getSelectedObject();
  }

  public void selectJdk(final Sdk projectJdk) {
    selectNodeInTree(projectJdk);
  }

  @Nullable
  public String getDisplayName() {
    return null;
  }

  @Nullable
  public Icon getIcon() {
    return null;
  }

  @Nullable
  @NonNls
  public String getHelpTopic() {
    return null;
  }

  protected
  @Nullable
  String getEmptySelectionString() {
    return "Select a JDK to view or edit its details here";
  }
}