text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>
JembossParams (Jemboss API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.emboss.jemboss

Class  JembossParams

java.lang.Object
  |
  +--org.emboss.jemboss.JembossParams

public class JembossParams
extends java.lang.Object

Field Summary

private  java.lang.String
acdDirToParse

private  java.lang.String
acdDirToParseName

private  java.lang.String
browserProxyHost

private  java.lang.String
browserProxyHostName

private  int
browserProxyPort

private  java.lang.String
browserProxyPortName

private  java.lang.String
currentMode

private  java.lang.String
currentModeName

private  boolean
debug

private  java.lang.String
debugName

private  java.lang.String
embossBin

private  java.lang.String
embossBinName

private  java.lang.String
embossData

private  java.lang.String
embossDataName

private  java.lang.String
embossEnvironment

private  java.lang.String
embossEnvironmentName

private  java.lang.String
embossPath

private  java.lang.String
embossPathName

private  java.lang.String
embossURL

private  java.lang.String
embURL

private  boolean
hasBatchMode

private  java.lang.String
hasBatchModeName

private  boolean
hasInteractiveMode

private  java.lang.String
hasInteractiveModeName

private  java.lang.String
javaNoProxy

private  java.util.Vector
javaNoProxyEntries

private  java.lang.String
javaProxyHost

private  java.lang.String
javaProxyPort

private  int
javaProxyPortNum

private static boolean
jembossServer

          Jemboss java server

private  java.lang.String
jembossServerName

(package private)  java.util.Properties
jembossSettings

private  java.lang.String
plplot

private  java.lang.String
plplotName

private  boolean
privateServerFailOver

private  java.util.Vector
privateServers

private  java.lang.String
privateSoapService

private  java.lang.String
privateSoapServiceName

private  java.lang.String
privateSoapURL

private  java.lang.String
privateSoapURLName

private  java.lang.String
proxyAuthPasswd

private  java.lang.String
proxyAuthPasswdName

private  java.lang.String
proxyAuthUser

private  java.lang.String
proxyAuthUserName

private  java.lang.String
proxyHost

private  java.lang.String
proxyHostName

private  boolean
proxyOverride

private  java.lang.String
proxyOverrideName

private  int
proxyPortNum

private  java.lang.String
proxyPortNumName

private  boolean
publicServerFailOver

private  java.util.Vector
publicServers

private  java.lang.String
publicSoapService

private  java.lang.String
publicSoapServiceName

private  java.lang.String
publicSoapURL

private  java.lang.String
publicSoapURLName

static int
SERVER_DOWN

static int
SERVER_ERR

static int
SERVER_OK

private  java.lang.String
serverPrivateList

private  java.lang.String
serverPrivateListName

private  java.lang.String
serverPublicList

private  java.lang.String
serverPublicListName

private  java.util.Hashtable
serverStatusHash

private  char[]
servicePasswd

private  byte[]
servicePasswdByte

private  java.lang.String
serviceUserName

private  java.lang.String
serviceUserNameName

private  java.lang.String
soapService

private  java.lang.String
soapServiceName

private  boolean
useAuth

private  java.lang.String
useAuthName

private  boolean
useBrowserProxy

private  java.lang.String
useBrowserProxyName

private  boolean
useJavaNoProxy

private  boolean
useJavaProxy

private  boolean
useProxy

private  boolean
useProxyAuth

private  java.lang.String
useProxyAuthName

private  java.lang.String
useProxyName

private  java.lang.String
userHome

private  java.lang.String
userHomeName

private  boolean
useTFM

private  java.lang.String
useTFMName

Constructor Summary

JembossParams()

          Loads and holds the properties

Method Summary

 java.lang.String
getAcdDirToParse()

 java.lang.String
getBrowserProxyHost()

          The name of the proxy server for the browser

 int
getBrowserProxyPort()

          The port number of the proxy server for the browser

 java.lang.String
getCurrentMode()

          The current mode (interactive or batch).

 boolean
getDebug()

          Whether to show debugging information

 java.lang.String
getEmbossBin()

 java.lang.String
getEmbossData()

 java.lang.String
getEmbossEnvironment()

 java.lang.String[]
getEmbossEnvironmentArray(java.lang.String[] envp)

 java.lang.String
getEmbossPath()

 java.lang.String
getembURL()

 boolean
getHasBatchMode()

          Whether this service supports batch mode

 boolean
getHasInteractiveMode()

          Whether this service supports interactive mode

 java.lang.String
getPlplot()

 boolean
getPrivateServerFailover()

          Return whether we have failover on the private server

 java.util.Vector
getPrivateServers()

          Return a vector containing the list of private servers

 java.lang.String
getPrivateSoapService()

          Get the name of the private soap service we're using

 java.lang.String
getPrivateSoapURL()

          Returns the URL of the private soap server

 java.lang.String
getProxyAuthPasswd()

          password needed to use for the proxy server

 java.lang.String
getProxyAuthUser()

          username needed to use for the proxy server

 java.lang.String
getProxyHost()

          The name of the proxy server

 int
getProxyPortNum()

          The port the proxy server listens on

 boolean
getPublicServerFailover()

          Return whether we have failover on the public server

 java.util.Vector
getPublicServers()

          Return a vector containing the list of public servers

 java.lang.String
getPublicSoapService()

          Get the name of the public soap service we're using

 java.lang.String
getPublicSoapURL()

          Returns the URL of the public soap server

 char[]
getServicePasswd()

          Return the password needed for the remote service

 byte[]
getServicePasswdByte()

 java.lang.String
getServiceUserName()

          Return the username needed for the remote service

 java.lang.String
getSoapService()

          Get the name of the soap service we're using

 boolean
getUseAuth()

          Whether the main service requires authentication

 boolean
getUseProxy()

          If using a proxy server

 boolean
getUseProxy(java.lang.String s)

          If using a proxy server for a given URL

 boolean
getUseProxyAuth()

          If using authenticate with the proxy

 java.lang.String
getUserHome()

 boolean
isBrowserProxy()

          True is using a proxy server for the browser

static boolean
isJembossServer()

 boolean
isUseTFM()

private  void
loadIn(java.lang.String folder)

 java.util.Vector
modeVector()

          Return the mode list as a vector, suitable for loading into
 a combobox.

 java.lang.String
proxyDescription()

          A description of the proxy settings

 java.lang.String
serverDescription()

          A description of the server settings

 void
setCurrentMode(java.lang.String newMode)

          Set the current mode (interactive or batch).

 void
setPrivateSoapService(java.lang.String s)

          Set the name of the private soap service we're using

 void
setPrivateSoapURL(java.lang.String s)

          Set the URL of the private soap server

 void
setPublicSoapService(java.lang.String s)

          Set the name of the public soap service we're using

 void
setPublicSoapURL(java.lang.String s)

          Set the URL of the public soap server

 void
setServerStatus(java.lang.String server,
                int i)

          Mark a server as bad

 void
setServicePasswd(char[] newPasswd)

          Save the password needed for the remote service

 void
setServiceUserName(java.lang.String newUserName)

          Save the username needed for the remote service

protected  void
setupServerRedundancy()

          Initialize the server redundancy data.

 void
setUserHome(java.lang.String s)

private static byte[]
toByteArr(char[] ch)

          Return the password as byte array

 void
updateJembossProperty(java.lang.String name,
                      java.lang.String newvalue)

          Update the properties structure.

 void
updateJembossPropHash(java.util.Hashtable hash)

          Update properties from a Hashtable

 void
updateJembossPropString(java.lang.String entry)

          Parse a key=value string to update the properties structure

 void
updateJembossPropStrings(java.lang.String[] entries)

          Parse an array of key=value strings to update the properties structure

protected  void
updateSettingsFromProperties()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

SERVER_OK

public static final int SERVER_OK

See Also:
Constant Field Values

SERVER_ERR

public static final int SERVER_ERR

See Also:
Constant Field Values

SERVER_DOWN

public static final int SERVER_DOWN

See Also:
Constant Field Values

useProxy

private boolean useProxy

useProxyName

private java.lang.String useProxyName

proxyHost

private java.lang.String proxyHost

proxyHostName

private java.lang.String proxyHostName

proxyPortNum

private int proxyPortNum

proxyPortNumName

private java.lang.String proxyPortNumName

useBrowserProxy

private boolean useBrowserProxy

useBrowserProxyName

private java.lang.String useBrowserProxyName

browserProxyHost

private java.lang.String browserProxyHost

browserProxyHostName

private java.lang.String browserProxyHostName

browserProxyPort

private int browserProxyPort

browserProxyPortName

private java.lang.String browserProxyPortName

useTFM

private boolean useTFM

useTFMName

private java.lang.String useTFMName

useProxyAuth

private boolean useProxyAuth

useProxyAuthName

private java.lang.String useProxyAuthName

proxyAuthUser

private java.lang.String proxyAuthUser

proxyAuthUserName

private java.lang.String proxyAuthUserName

proxyAuthPasswd

private java.lang.String proxyAuthPasswd

proxyAuthPasswdName

private java.lang.String proxyAuthPasswdName

proxyOverride

private boolean proxyOverride

proxyOverrideName

private java.lang.String proxyOverrideName

useAuth

private boolean useAuth

useAuthName

private java.lang.String useAuthName

publicSoapURL

private java.lang.String publicSoapURL

publicSoapURLName

private java.lang.String publicSoapURLName

privateSoapURL

private java.lang.String privateSoapURL

privateSoapURLName

private java.lang.String privateSoapURLName

soapService

private java.lang.String soapService

soapServiceName

private java.lang.String soapServiceName

privateSoapService

private java.lang.String privateSoapService

privateSoapServiceName

private java.lang.String privateSoapServiceName

publicSoapService

private java.lang.String publicSoapService

publicSoapServiceName

private java.lang.String publicSoapServiceName

debug

private boolean debug

debugName

private java.lang.String debugName

hasBatchMode

private boolean hasBatchMode

hasBatchModeName

private java.lang.String hasBatchModeName

hasInteractiveMode

private boolean hasInteractiveMode

hasInteractiveModeName

private java.lang.String hasInteractiveModeName

currentMode

private java.lang.String currentMode

currentModeName

private java.lang.String currentModeName

serverPublicList

private java.lang.String serverPublicList

serverPublicListName

private java.lang.String serverPublicListName

serverPrivateList

private java.lang.String serverPrivateList

serverPrivateListName

private java.lang.String serverPrivateListName

serviceUserName

private java.lang.String serviceUserName

serviceUserNameName

private java.lang.String serviceUserNameName

servicePasswd

private char[] servicePasswd

servicePasswdByte

private byte[] servicePasswdByte

jembossSettings

java.util.Properties jembossSettings

useJavaProxy

private boolean useJavaProxy

javaProxyPort

private java.lang.String javaProxyPort

javaProxyHost

private java.lang.String javaProxyHost

useJavaNoProxy

private boolean useJavaNoProxy

javaNoProxy

private java.lang.String javaNoProxy

javaNoProxyEntries

private java.util.Vector javaNoProxyEntries

javaProxyPortNum

private int javaProxyPortNum

publicServerFailOver

private boolean publicServerFailOver

privateServerFailOver

private boolean privateServerFailOver

serverStatusHash

private java.util.Hashtable serverStatusHash

publicServers

private java.util.Vector publicServers

privateServers

private java.util.Vector privateServers

jembossServer

private static boolean jembossServer

Jemboss java server

jembossServerName

private java.lang.String jembossServerName

plplot

private java.lang.String plplot

plplotName

private java.lang.String plplotName

embossData

private java.lang.String embossData

embossDataName

private java.lang.String embossDataName

embossBin

private java.lang.String embossBin

embossBinName

private java.lang.String embossBinName

embossPath

private java.lang.String embossPath

embossPathName

private java.lang.String embossPathName

embossEnvironment

private java.lang.String embossEnvironment

embossEnvironmentName

private java.lang.String embossEnvironmentName

acdDirToParse

private java.lang.String acdDirToParse

acdDirToParseName

private java.lang.String acdDirToParseName

embURL

private java.lang.String embURL

embossURL

private java.lang.String embossURL

userHome

private java.lang.String userHome

userHomeName

private java.lang.String userHomeName

Constructor Detail

JembossParams

public JembossParams()

Loads and holds the properties

Method Detail

loadIn

private void loadIn(java.lang.String folder)

updateSettingsFromProperties

protected void updateSettingsFromProperties()

setupServerRedundancy

protected void setupServerRedundancy()

Initialize the server redundancy data. This is a separate
 method because the server info might not be initialized in
 the constructor, but may be imported later from the command line.

getUseProxy

public boolean getUseProxy()

If using a proxy server

getUseProxy

public boolean getUseProxy(java.lang.String s)

If using a proxy server for a given URL

Parameters:
s - The URL we wish to connect to

getProxyHost

public java.lang.String getProxyHost()

The name of the proxy server

getProxyPortNum

public int getProxyPortNum()

The port the proxy server listens on

isBrowserProxy

public boolean isBrowserProxy()

True is using a proxy server for the browser

getBrowserProxyHost

public java.lang.String getBrowserProxyHost()

The name of the proxy server for the browser

getBrowserProxyPort

public int getBrowserProxyPort()

The port number of the proxy server for the browser

isUseTFM

public boolean isUseTFM()

getUseProxyAuth

public boolean getUseProxyAuth()

If using authenticate with the proxy

getProxyAuthUser

public java.lang.String getProxyAuthUser()

username needed to use for the proxy server

getProxyAuthPasswd

public java.lang.String getProxyAuthPasswd()

password needed to use for the proxy server

proxyDescription

public java.lang.String proxyDescription()

A description of the proxy settings

getUseAuth

public boolean getUseAuth()

Whether the main service requires authentication

getPublicSoapURL

public java.lang.String getPublicSoapURL()

Returns the URL of the public soap server

isJembossServer

public static boolean isJembossServer()

getPlplot

public java.lang.String getPlplot()

getUserHome

public java.lang.String getUserHome()

setUserHome

public void setUserHome(java.lang.String s)

getembURL

public java.lang.String getembURL()

getEmbossData

public java.lang.String getEmbossData()

getEmbossBin

public java.lang.String getEmbossBin()

getEmbossPath

public java.lang.String getEmbossPath()

getEmbossEnvironment

public java.lang.String getEmbossEnvironment()

getEmbossEnvironmentArray

public java.lang.String[] getEmbossEnvironmentArray(java.lang.String[] envp)

getAcdDirToParse

public java.lang.String getAcdDirToParse()

setPublicSoapURL

public void setPublicSoapURL(java.lang.String s)

Set the URL of the public soap server

getPrivateSoapURL

public java.lang.String getPrivateSoapURL()

Returns the URL of the private soap server

setPrivateSoapURL

public void setPrivateSoapURL(java.lang.String s)

Set the URL of the private soap server

getPublicServerFailover

public boolean getPublicServerFailover()

Return whether we have failover on the public server

getPrivateServerFailover

public boolean getPrivateServerFailover()

Return whether we have failover on the private server

getPublicServers

public java.util.Vector getPublicServers()

Return a vector containing the list of public servers

getPrivateServers

public java.util.Vector getPrivateServers()

Return a vector containing the list of private servers

setServerStatus

public void setServerStatus(java.lang.String server,
                            int i)

Mark a server as bad

getServiceUserName

public java.lang.String getServiceUserName()

Return the username needed for the remote service

setServiceUserName

public void setServiceUserName(java.lang.String newUserName)

Save the username needed for the remote service

Parameters:
newUserName - The username

getServicePasswd

public char[] getServicePasswd()

Return the password needed for the remote service

getServicePasswdByte

public byte[] getServicePasswdByte()

toByteArr

private static byte[] toByteArr(char[] ch)

Return the password as byte array

setServicePasswd

public void setServicePasswd(char[] newPasswd)

Save the password needed for the remote service

Parameters:
newPasswd - The username

getSoapService

public java.lang.String getSoapService()

Get the name of the soap service we're using

getPrivateSoapService

public java.lang.String getPrivateSoapService()

Get the name of the private soap service we're using

setPrivateSoapService

public void setPrivateSoapService(java.lang.String s)

Set the name of the private soap service we're using

Parameters:
s - The name of the service

getPublicSoapService

public java.lang.String getPublicSoapService()

Get the name of the public soap service we're using

setPublicSoapService

public void setPublicSoapService(java.lang.String s)

Set the name of the public soap service we're using

Parameters:
s - The name of the service

serverDescription

public java.lang.String serverDescription()

A description of the server settings

getDebug

public boolean getDebug()

Whether to show debugging information

getHasBatchMode

public boolean getHasBatchMode()

Whether this service supports batch mode

getHasInteractiveMode

public boolean getHasInteractiveMode()

Whether this service supports interactive mode

getCurrentMode

public java.lang.String getCurrentMode()

The current mode (interactive or batch).

Returns:
a String containing the current mode

setCurrentMode

public void setCurrentMode(java.lang.String newMode)

Set the current mode (interactive or batch).

Parameters:
newMode - The new execution mode

modeVector

public java.util.Vector modeVector()

Return the mode list as a vector, suitable for loading into
 a combobox.

updateJembossProperty

public void updateJembossProperty(java.lang.String name,
                                  java.lang.String newvalue)

Update the properties structure.
 This doesn't update the actual properties, just the Properties object
 so you must call updateSettingsFromProperties yoursefl

Parameters:
name - A String naming the property to be updated
newvalue - A String containing the new value of the property

updateJembossPropString

public void updateJembossPropString(java.lang.String entry)

Parse a key=value string to update the properties structure

Parameters:
entry - String containing a key=value message

updateJembossPropStrings

public void updateJembossPropStrings(java.lang.String[] entries)

Parse an array of key=value strings to update the properties structure

Parameters:
entries - Array of Strings containing key=value messages

updateJembossPropHash

public void updateJembossPropHash(java.util.Hashtable hash)

Update properties from a Hashtable

Parameters:
hash - Hashtable containg properties

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?php

namespace LiddleDev\LiddleForum\Controllers\Admin;

use Validator;
use Illuminate\Http\Request;
use LiddleDev\LiddleForum\Models\Category;
use LiddleDev\LiddleForum\Models\Moderator;

class ModeratorsController extends BaseAdminController
{
    public function getIndex()
    {
        $moderators = Moderator::with('user')->with('category')->get();

        $categories = Category::orderBy('parent_id')->get();

        return view('liddleforum::admin.moderators', [
            'moderators' => $moderators,
            'categories' => $categories,
        ]);
    }

    public function postCreate(Request $request)
    {
        $userClass = config('liddleforum.user.model');
        $userObject = new $userClass();

        $validator = Validator::make($request->all(), [
            'user_id' => 'required|exists:' . $userObject->getTable() . ',' . $userObject->getKeyName(),
        ]);

        if ($validator->fails()) {
            return redirect()->route('liddleforum.admin.moderators.index')
                ->withErrors($validator, 'liddleforum')
                ->withInput();
        }

        $userId = $request->input('user_id');

        // Check if user/category pair already exists
        $categoryId = $request->input('category_id') ? $request->input('category_id') : null;
        if ($categoryId) {
            if ( ! $category = Category::where('id', '=', $categoryId)->first()) {
                $request->session()->flash('liddleforum_error', 'Invalid category');
                return redirect()->route('liddleforum.admin.moderators.index');
            }

            if (Moderator::where('user_id', '=', $userId)->where('category_id', '=', $categoryId)->first()) {
                $request->session()->flash('liddleforum_error', 'User is already a moderator of category: ' . $category->name);
                return redirect()->route('liddleforum.admin.moderators.index');
            }
        } else {
            if (Moderator::where('user_id', '=', $userId)->whereNull('category_id')->first()) {
                $request->session()->flash('liddleforum_error', 'User is already a global moderator');
                return redirect()->route('liddleforum.admin.moderators.index');
            }
        }

        $moderator = Moderator::create([
            'user_id' => $userId,
            'category_id' => $categoryId,
        ]);

        $request->session()->flash('liddleforum_success', $moderator->user->{config('liddleforum.user.name_column')} . ' is now a moderator.');
        return redirect()->route('liddleforum.admin.moderators.index');
    }

    public function deleteModerator(Request $request, $moderator_id)
    {
        if ( ! $moderator = $this->fetchModerator($moderator_id)) {
            abort(404);
        }

        $moderator->delete();

        $request->session()->flash('liddleforum_success', 'Moderator privileges have been revoked');
        return redirect()->route('liddleforum.admin.moderators.index');
    }

    /**
     * @param $moderator_id
     * @return Moderator|null
     */
    protected function fetchModerator($moderator_id)
    {
        return Moderator::where('id', '=', $moderator_id)->first();
    }

}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/f4bien/generator-jahia.svg?branch=master)](https://travis-ci.org/f4bien/generator-jahia)

[![Dependency Status](https://david-dm.org/f4bien/generator-jahia.svg)](https://david-dm.org/f4bien/generator-jahia)
[![devDependency Status](https://david-dm.org/f4bien/generator-jahia/dev-status.svg)](https://david-dm.org/f4bien/generator-jahia#info=devDependencies)
[![peerDependency Status](https://david-dm.org/f4bien/generator-jahia/peer-status.svg)](https://david-dm.org/f4bien/generator-jahia#info=peerDependencies)

Yeoman generator for [Digital Factory 7.1 from Jahia](https://www.jahia.com/products/digital-factory)

## Install

```sh
$ npm install -g generator-jahia
```

## Usage

```sh
$ yo jahia
```

*Note that this template will generate files in the current directory, so be sure to change to a new directory first if you don't want to overwrite existing files.*

## Deploy

Deploy on Digital Factory 7.1

```sh
$ mvn clean package jahia:deploy -Pdev
```

## Browsersync

[Browsersync](http://www.browsersync.io/) feature is embedded.

```sh
$ gulp serve
```

## License

MIT


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package de.comci.aggregator.service.representation;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;

/**
 *
 * @author Sebastian Maier (sebastian.maier@comci.de)
 */
public class Dimension {

    @JsonProperty
    String name;

    @JsonProperty
    Class type;

    @JsonProperty
    long cardinality;

    public Dimension() {
        // jackson
    }

    public Dimension(String name, long cardinality, Class type) {
        this.name = name;
        this.cardinality = cardinality;
        this.type = type;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 67 * hash + Objects.hashCode(this.name);
        hash = 67 * hash + (int) (this.cardinality ^ (this.cardinality >>> 32));
        hash = 67 * hash + Objects.hashCode(this.type);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Dimension other = (Dimension) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        if (this.cardinality != other.cardinality) {
            return false;
        }
        if (!Objects.equals(this.type, other.type)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return String.format("%s:%s(%d)", type.getSimpleName(), name, cardinality);
    }

}


text:
function [foundPath, sequence, dirs, partColoredArray,partXY]=FindBuildPathErodeAndDecompose(partXY)
% FINDBUILDPATHERODEANDDECOMPOSE given a polyomino part, searches for a valid build path described by
% order sequence and move direcions dirs.
% Finds the build path by iteratively removing tiles.
%Decomposition : Worst case is 1/2 n (1 + n), best base is n
% Composition Worst case is n!, best case is n
% returns foundPath == true if a path is found, false else.
%Initialize a part with yx
% positions Passes the part and start node to Depth_firstsearch function to
% find possible sequence of joining the items The output is then passed to
% CheckPath function to check if the item can join the assembly from
% l,r,u,d direction
% Outputs: sequence of coordinates (sequence), directions from which each
% tile will be added (dirs) and labelled matrix (partColoredArray)
%
%Authors: Sheryl Manzoor, smanzoor2@uh.edu and Aaron T. Becker, atbecker@uh.edu
clc
format compact
if nargin <1
       %Test inputs if no arguments are provided
%        partXY = [5 3;4 3;4 2;3 2;2 2;1 2];
%        partXY =[6 11;4 8;3 8;3 7;3 6;4 6;5 6;6 6;7 6;7 7;7 8;7 9;6 9;6 10;6 12;6 13;6 14;6 15;7 15;8 15;9 15;9 14;9 13;8 13;5 10;5 11;5 12];
%        partXY=[5 11;7 8;8 8;8 7;8 6;7 6;6 6;5 6;4 6;4 7;4 8;4 9;5 9;5 10;6 10;6 11;5 12;6 12;5 13;5 14;5 15;4 15;3 15;2 15;2 14;2 13;3 13];
 %      partXY=[6 10;8 8;9 8;9 7;9 6;8 6;7 6;6 6;6 7;6 8;6 9;5 9;5 10;5 11;6 11;6 12;7 13;7 14;7 15;6 15;5 15;4 15;3 15;3 14;3 13;4 13;7 12];
       partXY=[4 4;4 3;3 3;2 3;2 4;2 5;2 6;2 7;3 7;4 7;5 7;5 6;6 5;6 6;7 5;7 6;8 5;8 6;9 6;10 6;11 6;11 7;11 8;11 9;10 9;9 9;9 8];
%      partXY=ConvertBinaryMatrixToIndices();
end

% color the part
IND = sub2ind(max(partXY),partXY(:,1),partXY(:,2));
partAr = zeros(max(partXY));
partAr(IND) = 1;
%ensure the part has 0 on all sides
partAr = padarray(partAr,[1 1]); %adds zeros on all sides
partColoredArray = LabelColor(partAr); %label color to each item in part
[x,y] = find(partAr==1);
partXY = [x,y];
% Call the recursive function
[foundPath, sequence, dirs]=FindBuildPath(partXY,partAr,partColoredArray);
%%% Draw the polyomino
G.fig = figure(51);clf;
set(gcf,'color','w');
set(G.fig,'Name',['Colored Part, n = ',num2str(size(partXY,1)),' tiles'])
G.colormap = [  1,1,1; %Empty = white
    0,0,0; %obstacle
    0,0,1;
    1,0,0;
    ];
colormap(G.colormap);
% set(G.fig, 'MenuBar', 'none');
% set(G.fig, 'ToolBar', 'none');
set(G.fig,'numbertitle','off');
set(gca,'Ydir','reverse');

axis equal
axis tight
set(gca,'xcolor','w','ycolor','w');
set(gca,'xtick',[],'ytick',[]);
axes('position', [0 0 1 1])
set(gca,'Ydir','reverse');
axis equal
set(gca,'xtick',[],'ytick',[]);
set(gca,'xcolor','w','ycolor','w');
if ~foundPath
    sequence = partXY;
end

    for k = 1:size(partXY,1)
        x = sequence(k,1);
        y = sequence(k,2);
        clr = partColoredArray(x,y);
        rectangle('Position',[y-1/2,x-1/2,1,1],...
            'FaceColor',G.colormap(clr+2,:),'linewidth',1);
        if foundPath
        if k > 1
            ht = text(y,x,[num2str(k),textarrow( dirs(k-1) )],'HorizontalAlignment','center');
        else
            ht = text(y,x,num2str(k) ,'HorizontalAlignment','center');
        end
        set(ht, 'color','w','fontsize',28,'FontWeight','bold')
        end
    end
if ~foundPath
    text(1/2*(max(partXY(:,2))-min(partXY(:,2))),1/2*(max(partXY(:,1))-min(partXY(:,1))), 'No path found')
end
end

function [remPartXY,partAr,sequence, dirs,foundPath,loops]=ErodePoly(remPartXY,partAr,partColoredArray)
sequence = zeros(size(remPartXY));  % the order to build the part (computed in reverse )
dirs = char(zeros(1,size(remPartXY,1)-1));      % the directions to compose the part
foundPath = false;
loops = false;
dirs2 = ['d';'l';'u';'r'];
p = bwconncomp(1-partAr,8); %the number of white connected components
initwhiteObj = p.NumObjects;
%remPartXY=SortPartXY(remPartXY);
while size(remPartXY,1) > 1
    successfulRemove = false;
    remPartXY=SortPartXY(remPartXY);
    for m = 1:size(remPartXY,1)%check each remaining tile to find a removeable one
        remPartXY=SortPartXY(remPartXY);
        startPart = remPartXY(m,:);%try removing each particle
        restXY = [remPartXY(1:m-1,:);remPartXY(m+1:end,:)];
        partAr(startPart(1),startPart(2)) = 0; % remove this tile from BW array
        for j=1:4 %try taking this particle out in all 4 directions
            % find a particle that can be successfully removed
            if CheckPath1Tile(partAr,startPart,dirs2(j),partColoredArray)
                n = bwconncomp(partAr,4); %TODO: SLOWEST PART OF ALGORITHM
                if n.NumObjects == 1
                    p = bwconncomp(1-partAr,8); %the number of white connected components
                    if p.NumObjects ~= initwhiteObj
                        loops = true;
                    else
                        %ensure it does not generate 2 components & no loops are broken
                        % remove the particle from remPartXY, and add it to revSequence & revDirs
                        remPartXY = restXY;
                        sequence(size(remPartXY,1)+1,:) = startPart; %store removal order in reverse
                        dirs(size(remPartXY,1)) = dirs2(j);%store directions in reverse
                        successfulRemove = true;
                        if size(remPartXY,1) == 1
                            foundPath = true;
                            sequence(1,:) = remPartXY;
                        end
                        break %exit FOR loop
                    end
                end %endif
            end %end if
        end %endfor (try moving in each direction)
        if ~successfulRemove
            partAr(startPart(1),startPart(2)) = 1; % replace this tile
        else
            break
        end
    end %endfor (try removing each existing tile until you can remove one)
    if successfulRemove == false
        display(['no way to remove tile ==> the shape is eroded, size =',num2str(size(remPartXY,1)), ' loops = ',num2str(loops)])
        break
    end
end  %endwhile (repeat until all tiles removed)

end

function [foundPath, sequence, dirs]=FindBuildPath(partXY,partAr,partColoredArray)
% Returned variables
dirs2 = ['d';'l';'u';'r'];
% call ERODE
[remPartXY,remPartAr,sequence, dirs,foundPath,loops]=ErodePoly(partXY,partAr,partColoredArray);
if foundPath
    return
end
% Else, now only loops remain.  We must break the loops, but order matters.
if loops
    for m = 1:size(remPartXY,1)%check each remaining tile to find a removeable one
        display(['Try removing tile ',num2str(m),' of ',num2str(size(remPartXY,1))] )
        startPart = remPartXY(m,:);%try removing each particle
        restXY = [remPartXY(1:m-1,:);remPartXY(m+1:end,:)];
        remPartAr(startPart(1),startPart(2)) = 0; % remove this tile from BW array
        for j=1:4 %try taking this particle out in all 4 directions
            % find a particle that can be successfully removed
            if CheckPath1Tile(remPartAr,startPart,dirs2(j),partColoredArray)
                n = bwconncomp(remPartAr,4); %TODO: SLOWEST PART OF ALGORITHM
                if n.NumObjects == 1  %ensure it does not generate 2 components
                    % add Tile & dir to revSequence & revDirs
                    sequence(size(restXY,1)+1,:) = startPart; %store removal order in reverse
                    dirs(size(restXY,1)) = dirs2(j);%store directions in reverse
                    [foundPath, sequenceS, dirsS]=FindBuildPath(restXY,remPartAr,partColoredArray);
                    if  foundPath == true
                        sequence(1:size(sequenceS,1),:) = sequenceS;
                        dirs(1:numel(dirsS)) = dirsS;
                        return
                    end
                    break %exit FOR loop
                end %endif
            end %end if
        end %endfor (try moving in each direction)
        remPartAr(startPart(1),startPart(2)) = 1; % replace this tile
    end %endfor (try removing each existing tile until you can remove one)
end
display('no way to remove a tile ==> there is no solution')
end  %endfunction

function dirText = textarrow(dir)
if dir == 'd'
    dirText = '\downarrow';
elseif dir == 'u'
    dirText = '\uparrow';
elseif dir == 'r'
    dirText = '\rightarrow';
else
    dirText = '\leftarrow';
end
end


text:
(function () {
  'use strict';
  // socketService

  angular.module('xyz.socket')

  .factory('SocketWrapper', function SocketWrapper($window, $timeout) {

    function asyncAngularify(context, callback) {
      return callback ? function () {
        var args = arguments;
        $timeout(function executeInAngular() {
          callback.apply(context, args);
        }, 0);
      } : angular.noop;
    }

    return function socketWrapper(socket, options) {

      if (!socket && (!_.isString(options.source) && !(socket instanceof $window.io.Socket))) {
        throw new Error('Impossible initialize a socketWrapper without a valid socket instance or a socket URL');
      }

      if (_.isString(options.source)) {
        socket = $window.io.connect(options.source);
      }

      // ---------------------------------------------
      // WRAPPER API
      // ---------------------------------------------

      function addListener(eventName, callback) {
        socket.on(eventName, callback.__ref = asyncAngularify(socket, callback));
      }

      function addOnceListener(eventName, callback) {
        socket.once(eventName, callback.__ref = asyncAngularify(socket, callback));
      }

      function removeListener(ev, fn) {
        if (fn && fn.__ref) {
          arguments[1] = fn.__ref;
        }
        return socket.removeListener.apply(socket, arguments);
      }

      function disconnect() {
        return socket.disconnect();
      }

      function emit(eventName, data, callback) {
        var lastIndex = arguments.length - 1;
        var callbackRef = arguments[lastIndex];

        if (_.isFunction(callbackRef)) {
          callbackRef = asyncAngularify(socket, callbackRef);
          arguments[lastIndex] = callbackRef;
        }

        return socket.emit.apply(socket, arguments);
      }

      function removeAllListeners() {
        return socket.removeAllListeners.apply(socket, arguments);
      }

      function connect() {
        return socket.connect();
      }

      // ---------------------------------------------
      // ADDITIONAL API
      // ---------------------------------------------

      function destroy() {
        removeAllListeners();
        disconnect();
        socket = undefined;
      }

      // ---------------------------------------------
      // EVENT LISTENERS
      // ---------------------------------------------

      addListener('connect', function onConnect() {
        console.log('connected');
        wrappedSocket.connected = socket.connected;
        wrappedSocket.connecting = false;
        wrappedSocket.error = false;
      });
      addListener('connecting', function onConnecting() {
        console.log('connecting');
        wrappedSocket.connecting = true;
      });
      addListener('disconnect', function onDisconnect() {
        wrappedSocket.connected = socket.connected;
        wrappedSocket.connecting = false;
        wrappedSocket.error = false;
      });
      addListener('reconnect', function onConnect() {
        wrappedSocket.connected = socket.connected;
        wrappedSocket.connecting = false;
        wrappedSocket.error = false;
      });
      addListener('reconnecting', function onReconnecting() {
        wrappedSocket.connecting = true;
      });
      addListener('error', function onError() {
        wrappedSocket.error = true;
        wrappedSocket.connecting = false;
      });
      addListener('connect_failed', function onConnectionFailed() {
        wrappedSocket.error = true;
        wrappedSocket.connecting = false;
      });

      // ---------------------------------------------
      // EXPOSED API OBJECT
      // ---------------------------------------------

      var wrappedSocket = {
        /* socket reference*/
        socket: socket,

        /* socket API*/
        on: addListener,
        addListener: addListener,
        addEventListener: addListener,
        once: addOnceListener,
        emit: emit,
        removeListener: removeListener,
        removeEventListener: removeListener,
        removeAllListeners: removeAllListeners,
        disconnect: disconnect,
        close: disconnect,
        connect: connect,

        /* exposed statuses */
        connected: false,
        connecting: false,
        error: false,

        /* additional API */
        destroy: destroy
      };

      return wrappedSocket;
    };
  });

})();


text:
/**
 * Flotr Graph class that plots a graph on creation.
 */
(function () {

var
  D     = Flotr.DOM,
  E     = Flotr.EventAdapter,
  _     = Flotr._,
  flotr = Flotr;
/**
 * Flotr Graph constructor.
 * @param {Element} el - element to insert the graph into
 * @param {Object} data - an array or object of dataseries
 * @param {Object} options - an object containing options
 */
Graph = function(el, data, options){
// Let's see if we can get away with out this [JS]
//  try {
    this._setEl(el);
    this._initMembers();
    this._initPlugins();

    E.fire(this.el, 'flotr:beforeinit', [this]);

    this.data = data;
    this.series = flotr.Series.getSeries(data);
    this._initOptions(options);
    this._initGraphTypes();
    this._initCanvas();
    this._text = new flotr.Text({
      element : this.el,
      ctx : this.ctx,
      html : this.options.HtmlText,
      textEnabled : this.textEnabled
    });
    E.fire(this.el, 'flotr:afterconstruct', [this]);
    this._initEvents();

    this.findDataRanges();
    this.calculateSpacing();

    this.draw(_.bind(function() {
      E.fire(this.el, 'flotr:afterinit', [this]);
    }, this));
/*
    try {
  } catch (e) {
    try {
      console.error(e);
    } catch (e2) {}
  }*/
};

function observe (object, name, callback) {
  E.observe.apply(this, arguments);
  this._handles.push(arguments);
  return this;
}

Graph.prototype = {

  destroy: function () {
    E.fire(this.el, 'flotr:destroy');
    _.each(this._handles, function (handle) {
      E.stopObserving.apply(this, handle);
    });
    this._handles = [];
    this.el.graph = null;
  },

  observe : observe,

  /**
   * @deprecated
   */
  _observe : observe,

  processColor: function(color, options){
    var o = { x1: 0, y1: 0, x2: this.plotWidth, y2: this.plotHeight, opacity: 1, ctx: this.ctx };
    _.extend(o, options);
    return flotr.Color.processColor(color, o);
  },
  /**
   * Function determines the min and max values for the xaxis and yaxis.
   *
   * TODO logarithmic range validation (consideration of 0)
   */
  findDataRanges: function(){
    var a = this.axes,
      xaxis, yaxis, range;

    _.each(this.series, function (series) {
      range = series.getRange();
      if (range) {
        xaxis = series.xaxis;
        yaxis = series.yaxis;
        xaxis.datamin = Math.min(range.xmin, xaxis.datamin);
        xaxis.datamax = Math.max(range.xmax, xaxis.datamax);
        yaxis.datamin = Math.min(range.ymin, yaxis.datamin);
        yaxis.datamax = Math.max(range.ymax, yaxis.datamax);
        xaxis.used = (xaxis.used || range.xused);
        yaxis.used = (yaxis.used || range.yused);
      }
    }, this);

    // Check for empty data, no data case (none used)
    if (!a.x.used && !a.x2.used) a.x.used = true;
    if (!a.y.used && !a.y2.used) a.y.used = true;

    _.each(a, function (axis) {
      axis.calculateRange();
    });

    var
      types = _.keys(flotr.graphTypes),
      drawn = false;

    _.each(this.series, function (series) {
      if (series.hide) return;
      _.each(types, function (type) {
        if (series[type] && series[type].show) {
          this.extendRange(type, series);
          drawn = true;
        }
      }, this);
      if (!drawn) {
        this.extendRange(this.options.defaultType, series);
      }
    }, this);
  },

  extendRange : function (type, series) {
    if (this[type].extendRange) this[type].extendRange(series, series.data, series[type], this[type]);
    if (this[type].extendYRange) this[type].extendYRange(series.yaxis, series.data, series[type], this[type]);
    if (this[type].extendXRange) this[type].extendXRange(series.xaxis, series.data, series[type], this[type]);
  },

  /**
   * Calculates axis label sizes.
   */
  calculateSpacing: function(){

    var a = this.axes,
        options = this.options,
        series = this.series,
        margin = options.grid.labelMargin,
        T = this._text,
        x = a.x,
        x2 = a.x2,
        y = a.y,
        y2 = a.y2,
        maxOutset = options.grid.outlineWidth,
        i, j, l, dim;

    // TODO post refactor, fix this
    _.each(a, function (axis) {
      axis.calculateTicks();
      axis.calculateTextDimensions(T, options);
    });

    // Title height
    dim = T.dimensions(
      options.title,
      {size: options.fontSize*1.5},
      'font-size:1em;font-weight:bold;',
      'flotr-title'
    );
    this.titleHeight = dim.height;

    // Subtitle height
    dim = T.dimensions(
      options.subtitle,
      {size: options.fontSize},
      'font-size:smaller;',
      'flotr-subtitle'
    );
    this.subtitleHeight = dim.height;

    for(j = 0; j < options.length; ++j){
      if (series[j].points.show){
        maxOutset = Math.max(maxOutset, series[j].points.radius + series[j].points.lineWidth/2);
      }
    }

    var p = this.plotOffset;
    if (x.options.margin === false) {
      p.bottom = 0;
      p.top    = 0;
    } else
    if (x.options.margin === true) {
      p.bottom += (options.grid.circular ? 0 : (x.used && x.options.showLabels ?  (x.maxLabel.height + margin) : 0)) +
                  (x.used && x.options.title ? (x.titleSize.height + margin) : 0) + maxOutset;

      p.top    += (options.grid.circular ? 0 : (x2.used && x2.options.showLabels ? (x2.maxLabel.height + margin) : 0)) +
                  (x2.used && x2.options.title ? (x2.titleSize.height + margin) : 0) + this.subtitleHeight + this.titleHeight + maxOutset;
    } else {
      p.bottom = x.options.margin;
      p.top = x.options.margin;
    }
    if (y.options.margin === false) {
      p.left  = 0;
      p.right = 0;
    } else
    if (y.options.margin === true) {
      p.left   += (options.grid.circular ? 0 : (y.used && y.options.showLabels ?  (y.maxLabel.width + margin) : 0)) +
                  (y.used && y.options.title ? (y.titleSize.width + margin) : 0) + maxOutset;

      p.right  += (options.grid.circular ? 0 : (y2.used && y2.options.showLabels ? (y2.maxLabel.width + margin) : 0)) +
                  (y2.used && y2.options.title ? (y2.titleSize.width + margin) : 0) + maxOutset;
    } else {
      p.left = y.options.margin;
      p.right = y.options.margin;
    }

    p.top = Math.floor(p.top); // In order the outline not to be blured

    this.plotWidth  = this.canvasWidth - p.left - p.right;
    this.plotHeight = this.canvasHeight - p.bottom - p.top;

    // TODO post refactor, fix this
    x.length = x2.length = this.plotWidth;
    y.length = y2.length = this.plotHeight;
    y.offset = y2.offset = this.plotHeight;
    x.setScale();
    x2.setScale();
    y.setScale();
    y2.setScale();
  },
  /**
   * Draws grid, labels, series and outline.
   */
  draw: function(after) {

    var
      context = this.ctx,
      i;

    E.fire(this.el, 'flotr:beforedraw', [this.series, this]);

    if (this.series.length) {

      context.save();
      context.translate(this.plotOffset.left, this.plotOffset.top);

      for (i = 0; i < this.series.length; i++) {
        if (!this.series[i].hide) this.drawSeries(this.series[i]);
      }

      context.restore();
      this.clip();
    }

    E.fire(this.el, 'flotr:afterdraw', [this.series, this]);
    if (after) after();
  },
  /**
   * Actually draws the graph.
   * @param {Object} series - series to draw
   */
  drawSeries: function(series){

    function drawChart (series, typeKey) {
      var options = this.getOptions(series, typeKey);
      this[typeKey].draw(options);
    }

    var drawn = false;
    series = series || this.series;

    _.each(flotr.graphTypes, function (type, typeKey) {
      if (series[typeKey] && series[typeKey].show && this[typeKey]) {
        drawn = true;
        drawChart.call(this, series, typeKey);
      }
    }, this);

    if (!drawn) drawChart.call(this, series, this.options.defaultType);
  },

  getOptions : function (series, typeKey) {
    var
      type = series[typeKey],
      graphType = this[typeKey],
      xaxis = series.xaxis,
      yaxis = series.yaxis,
      options = {
        context     : this.ctx,
        width       : this.plotWidth,
        height      : this.plotHeight,
        fontSize    : this.options.fontSize,
        fontColor   : this.options.fontColor,
        textEnabled : this.textEnabled,
        htmlText    : this.options.HtmlText,
        text        : this._text, // TODO Is this necessary?
        element     : this.el,
        data        : series.data,
        color       : series.color,
        shadowSize  : series.shadowSize,
        xScale      : xaxis.d2p,
        yScale      : yaxis.d2p,
        xInverse    : xaxis.p2d,
        yInverse    : yaxis.p2d
      };

    options = flotr.merge(type, options);

    // Fill
    options.fillStyle = this.processColor(
      type.fillColor || series.color,
      {opacity: type.fillOpacity}
    );

    return options;
  },
  /**
   * Calculates the coordinates from a mouse event object.
   * @param {Event} event - Mouse Event object.
   * @return {Object} Object with coordinates of the mouse.
   */
  getEventPosition: function (e){

    var
      d = document,
      b = d.body,
      de = d.documentElement,
      axes = this.axes,
      plotOffset = this.plotOffset,
      lastMousePos = this.lastMousePos,
      pointer = E.eventPointer(e),
      dx = pointer.x - lastMousePos.pageX,
      dy = pointer.y - lastMousePos.pageY,
      r, rx, ry;

    if ('ontouchstart' in this.el) {
      r = D.position(this.overlay);
      rx = pointer.x - r.left - plotOffset.left;
      ry = pointer.y - r.top - plotOffset.top;
    } else {
      r = this.overlay.getBoundingClientRect();
      rx = e.clientX - r.left - plotOffset.left - b.scrollLeft - de.scrollLeft;
      ry = e.clientY - r.top - plotOffset.top - b.scrollTop - de.scrollTop;
    }

    return {
      x:  axes.x.p2d(rx),
      x2: axes.x2.p2d(rx),
      y:  axes.y.p2d(ry),
      y2: axes.y2.p2d(ry),
      relX: rx,
      relY: ry,
      dX: dx,
      dY: dy,
      absX: pointer.x,
      absY: pointer.y,
      pageX: pointer.x,
      pageY: pointer.y
    };
  },
  /**
   * Observes the 'click' event and fires the 'flotr:click' event.
   * @param {Event} event - 'click' Event object.
   */
  clickHandler: function(event){
    if(this.ignoreClick){
      this.ignoreClick = false;
      return this.ignoreClick;
    }
    E.fire(this.el, 'flotr:click', [this.getEventPosition(event), this]);
  },
  /**
   * Observes mouse movement over the graph area. Fires the 'flotr:mousemove' event.
   * @param {Event} event - 'mousemove' Event object.
   */
  mouseMoveHandler: function(event){
    if (this.mouseDownMoveHandler) return;
    var pos = this.getEventPosition(event);
    E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
    this.lastMousePos = pos;
  },
  /**
   * Observes the 'mousedown' event.
   * @param {Event} event - 'mousedown' Event object.
   */
  mouseDownHandler: function (event){

    /*
    // @TODO Context menu?
    if(event.isRightClick()) {
      event.stop();

      var overlay = this.overlay;
      overlay.hide();

      function cancelContextMenu () {
        overlay.show();
        E.stopObserving(document, 'mousemove', cancelContextMenu);
      }
      E.observe(document, 'mousemove', cancelContextMenu);
      return;
    }
    */

    if (this.mouseUpHandler) return;
    this.mouseUpHandler = _.bind(function (e) {
      E.stopObserving(document, 'mouseup', this.mouseUpHandler);
      E.stopObserving(document, 'mousemove', this.mouseDownMoveHandler);
      this.mouseDownMoveHandler = null;
      this.mouseUpHandler = null;
      // @TODO why?
      //e.stop();
      E.fire(this.el, 'flotr:mouseup', [e, this]);
    }, this);
    this.mouseDownMoveHandler = _.bind(function (e) {
        var pos = this.getEventPosition(e);
        E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
        this.lastMousePos = pos;
    }, this);
    E.observe(document, 'mouseup', this.mouseUpHandler);
    E.observe(document, 'mousemove', this.mouseDownMoveHandler);
    E.fire(this.el, 'flotr:mousedown', [event, this]);
    this.ignoreClick = false;
  },
  drawTooltip: function(content, x, y, options) {
    var mt = this.getMouseTrack(),
        style = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;',
        p = options.position,
        m = options.margin,
        plotOffset = this.plotOffset;

    if(x !== null && y !== null){
      if (!options.relative) { // absolute to the canvas
             if(p.charAt(0) == 'n') style += 'top:' + (m + plotOffset.top) + 'px;bottom:auto;';
        else if(p.charAt(0) == 's') style += 'bottom:' + (m + plotOffset.bottom) + 'px;top:auto;';
             if(p.charAt(1) == 'e') style += 'right:' + (m + plotOffset.right) + 'px;left:auto;';
        else if(p.charAt(1) == 'w') style += 'left:' + (m + plotOffset.left) + 'px;right:auto;';
      }
      else { // relative to the mouse
             if(p.charAt(0) == 'n') style += 'bottom:' + (m - plotOffset.top - y + this.canvasHeight) + 'px;top:auto;';
        else if(p.charAt(0) == 's') style += 'top:' + (m + plotOffset.top + y) + 'px;bottom:auto;';
             if(p.charAt(1) == 'e') style += 'left:' + (m + plotOffset.left + x) + 'px;right:auto;';
        else if(p.charAt(1) == 'w') style += 'right:' + (m - plotOffset.left - x + this.canvasWidth) + 'px;left:auto;';
      }

      mt.style.cssText = style;
      D.empty(mt);
      D.insert(mt, content);
      D.show(mt);
    }
    else {
      D.hide(mt);
    }
  },

  clip: function (ctx) {

    var
      o   = this.plotOffset,
      w   = this.canvasWidth,
      h   = this.canvasHeight;

    ctx = ctx || this.ctx;

    if (
      flotr.isIE && flotr.isIE < 9 && // IE w/o canvas
      !flotr.isFlashCanvas // But not flash canvas
    ) {

      // Do not clip excanvas on overlay context
      // Allow hits to overflow.
      if (ctx === this.octx) {
        return;
      }

      // Clipping for excanvas :-(
      ctx.save();
      ctx.fillStyle = this.processColor(this.options.ieBackgroundColor);
      ctx.fillRect(0, 0, w, o.top);
      ctx.fillRect(0, 0, o.left, h);
      ctx.fillRect(0, h - o.bottom, w, o.bottom);
      ctx.fillRect(w - o.right, 0, o.right,h);
      ctx.restore();
    } else {
      ctx.clearRect(0, 0, w, o.top);
      ctx.clearRect(0, 0, o.left, h);
      ctx.clearRect(0, h - o.bottom, w, o.bottom);
      ctx.clearRect(w - o.right, 0, o.right,h);
    }
  },

  _initMembers: function() {
    this._handles = [];
    this.lastMousePos = {pageX: null, pageY: null };
    this.plotOffset = {left: 0, right: 0, top: 0, bottom: 0};
    this.ignoreClick = true;
    this.prevHit = null;
  },

  _initGraphTypes: function() {
    _.each(flotr.graphTypes, function(handler, graphType){
      this[graphType] = flotr.clone(handler);
    }, this);
  },

  _initEvents: function () {

    var
      el = this.el,
      touchendHandler, movement, touchend;

    if ('ontouchstart' in el) {

      touchendHandler = _.bind(function (e) {
        touchend = true;
        E.stopObserving(document, 'touchend', touchendHandler);
        E.fire(el, 'flotr:mouseup', [e, this]);
        this.multitouches = null;

        if (!movement) {
          this.clickHandler(e);
        }
      }, this);

      this.observe(this.overlay, 'touchstart', _.bind(function (e) {
        movement = false;
        touchend = false;
        this.ignoreClick = false;

        if (e.touches && e.touches.length > 1) {
          this.multitouches = e.touches;
        }

        E.fire(el, 'flotr:mousedown', [e, this]);
        this.observe(document, 'touchend', touchendHandler);
      }, this));

      this.observe(this.overlay, 'touchmove', _.bind(function (e) {

        var pos = this.getEventPosition(e);

        if (this.options.preventDefault) {
          e.preventDefault();
        }

        movement = true;

        if (this.multitouches || (e.touches && e.touches.length > 1)) {
          this.multitouches = e.touches;
        } else {
          if (!touchend) {
            E.fire(el, 'flotr:mousemove', [e, pos, this]);
          }
        }
        this.lastMousePos = pos;
      }, this));

    } else {
      this.
        observe(this.overlay, 'mousedown', _.bind(this.mouseDownHandler, this)).
        observe(el, 'mousemove', _.bind(this.mouseMoveHandler, this)).
        observe(this.overlay, 'click', _.bind(this.clickHandler, this)).
        observe(el, 'mouseout', function (e) {
          E.fire(el, 'flotr:mouseout', e);
        });
    }
  },

  /**
   * Initializes the canvas and it's overlay canvas element. When the browser is IE, this makes use
   * of excanvas. The overlay canvas is inserted for displaying interactions. After the canvas elements
   * are created, the elements are inserted into the container element.
   */
  _initCanvas: function(){
    var el = this.el,
      o = this.options,
      children = el.children,
      removedChildren = [],
      child, i,
      size, style;

    // Empty the el
    for (i = children.length; i--;) {
      child = children[i];
      if (!this.canvas && child.className === 'flotr-canvas') {
        this.canvas = child;
      } else if (!this.overlay && child.className === 'flotr-overlay') {
        this.overlay = child;
      } else {
        removedChildren.push(child);
      }
    }
    for (i = removedChildren.length; i--;) {
      el.removeChild(removedChildren[i]);
    }

    D.setStyles(el, {position: 'relative'}); // For positioning labels and overlay.
    size = {};
    size.width = el.clientWidth;
    size.height = el.clientHeight;

    if(size.width <= 0 || size.height <= 0 || o.resolution <= 0){
      throw 'Invalid dimensions for plot, width = ' + size.width + ', height = ' + size.height + ', resolution = ' + o.resolution;
    }

    // Main canvas for drawing graph types
    this.canvas = getCanvas(this.canvas, 'canvas');
    // Overlay canvas for interactive features
    this.overlay = getCanvas(this.overlay, 'overlay');
    this.ctx = getContext(this.canvas);
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.octx = getContext(this.overlay);
    this.octx.clearRect(0, 0, this.overlay.width, this.overlay.height);
    this.canvasHeight = size.height;
    this.canvasWidth = size.width;
    this.textEnabled = !!this.ctx.drawText || !!this.ctx.fillText; // Enable text functions

    function getCanvas(canvas, name){
      if(!canvas){
        canvas = D.create('canvas');
        if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
          FlashCanvas.initElement(canvas);
          this.isFlashCanvas = true;
        }
        canvas.className = 'flotr-'+name;
        canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
        D.insert(el, canvas);
      }
      _.each(size, function(size, attribute){
        D.show(canvas);
        if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
          return;
        }
        canvas.setAttribute(attribute, size * o.resolution);
        canvas.style[attribute] = size + 'px';
      });
      canvas.context_ = null; // Reset the ExCanvas context
      return canvas;
    }

    function getContext(canvas){
      if(window.G_vmlCanvasManager) window.G_vmlCanvasManager.initElement(canvas); // For ExCanvas
      var context = canvas.getContext('2d');
      if(!window.G_vmlCanvasManager) context.scale(o.resolution, o.resolution);
      return context;
    }
  },

  _initPlugins: function(){
    // TODO Should be moved to flotr and mixed in.
    _.each(flotr.plugins, function(plugin, name){
      _.each(plugin.callbacks, function(fn, c){
        this.observe(this.el, c, _.bind(fn, this));
      }, this);
      this[name] = flotr.clone(plugin);
      _.each(this[name], function(fn, p){
        if (_.isFunction(fn))
          this[name][p] = _.bind(fn, this);
      }, this);
    }, this);
  },

  /**
   * Sets options and initializes some variables and color specific values, used by the constructor.
   * @param {Object} opts - options object
   */
  _initOptions: function(opts){
    var options = flotr.clone(flotr.defaultOptions);
    options.x2axis = _.extend(_.clone(options.xaxis), options.x2axis);
    options.y2axis = _.extend(_.clone(options.yaxis), options.y2axis);
    this.options = flotr.merge(opts || {}, options);

    if (this.options.grid.minorVerticalLines === null &&
      this.options.xaxis.scaling === 'logarithmic') {
      this.options.grid.minorVerticalLines = true;
    }
    if (this.options.grid.minorHorizontalLines === null &&
      this.options.yaxis.scaling === 'logarithmic') {
      this.options.grid.minorHorizontalLines = true;
    }

    E.fire(this.el, 'flotr:afterinitoptions', [this]);

    this.axes = flotr.Axis.getAxes(this.options);

    // Initialize some variables used throughout this function.
    var assignedColors = [],
        colors = [],
        ln = this.series.length,
        neededColors = this.series.length,
        oc = this.options.colors,
        usedColors = [],
        variation = 0,
        c, i, j, s;

    // Collect user-defined colors from series.
    for(i = neededColors - 1; i > -1; --i){
      c = this.series[i].color;
      if(c){
        --neededColors;
        if(_.isNumber(c)) assignedColors.push(c);
        else usedColors.push(flotr.Color.parse(c));
      }
    }

    // Calculate the number of colors that need to be generated.
    for(i = assignedColors.length - 1; i > -1; --i)
      neededColors = Math.max(neededColors, assignedColors[i] + 1);

    // Generate needed number of colors.
    for(i = 0; colors.length < neededColors;){
      c = (oc.length == i) ? new flotr.Color(100, 100, 100) : flotr.Color.parse(oc[i]);

      // Make sure each serie gets a different color.
      var sign = variation % 2 == 1 ? -1 : 1,
          factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
      c.scale(factor, factor, factor);

      /**
       * @todo if we're getting too close to something else, we should probably skip this one
       */
      colors.push(c);

      if(++i >= oc.length){
        i = 0;
        ++variation;
      }
    }

    // Fill the options with the generated colors.
    for(i = 0, j = 0; i < ln; ++i){
      s = this.series[i];

      // Assign the color.
      if (!s.color){
        s.color = colors[j++].toString();
      }else if(_.isNumber(s.color)){
        s.color = colors[s.color].toString();
      }

      // Every series needs an axis
      if (!s.xaxis) s.xaxis = this.axes.x;
           if (s.xaxis == 1) s.xaxis = this.axes.x;
      else if (s.xaxis == 2) s.xaxis = this.axes.x2;

      if (!s.yaxis) s.yaxis = this.axes.y;
           if (s.yaxis == 1) s.yaxis = this.axes.y;
      else if (s.yaxis == 2) s.yaxis = this.axes.y2;

      // Apply missing options to the series.
      for (var t in flotr.graphTypes){
        s[t] = _.extend(_.clone(this.options[t]), s[t]);
      }
      s.mouse = _.extend(_.clone(this.options.mouse), s.mouse);

      if (_.isUndefined(s.shadowSize)) s.shadowSize = this.options.shadowSize;
    }
  },

  _setEl: function(el) {
    if (!el) throw 'The target container doesn\'t exist';
    else if (el.graph instanceof Graph) el.graph.destroy();
    else if (!el.clientWidth) throw 'The target container must be visible';

    el.graph = this;
    this.el = el;
  }
};

Flotr.Graph = Graph;

})();


text:
var Siren = function() {
  this.name = 'csv';
  this.mediaTypes = ['text/csv'];
  this.extension = '.csv.js';
  this.subdirectory = '/csv';
};

Siren.prototype.format = function(filename, locals, cb) {
  var template = require(filename);
  cb(null, template(locals));
};

module.exports = new Siren();


text:
/**
 * Main application routes
 */

'use strict';

var errors = require('./components/errors');
var rss = require('./components/rss');

module.exports = function(app) {

  // All undefined asset or api routes should return a 404
  app.route('/:url(api|auth|components|app|bower_components|assets)/*')
   .get(errors[404]);

  // All other routes should redirect to the index.html
  app.route('/')
  .get(function(req, res) {
      res.sendfile(app.get('appPath') + '/index.html');
    });

  app.route('/feed/:id').get(function (req, res) {
    var id = req.params.id;
    console.log('ID = ' + id);
    var feed = new RSS({
        "title": "ID=>" + id + "Lorem ipsum feed for an interval of #{interval} #{unit}s",
        "description": 'This is a constantly updating lorem ipsum feed',
        "site_url": 'http://example.com/',
        "copyright": 'Michael Bertolacci, licensed under a Creative Commons Attribution 3.0 Unported License.',
        "author": 'John Smith'
    });

    res.set('Content-Type', 'application/rss+xml');
    // res.set('ETag', "\"#{crypto.createHash('md5').update(etagString).digest("hex");}\"");
    res.send(feed.xml());
  });

  // All other routes should redirect to the index.html
  app.route('/')
    .get(function(req, res) {
      console.log("Route " + req.url + " not implemented.")
      res.sendfile(app.get('appPath') + '/index.html');
    });

  // All other routes should redirect to the index.html
  app.route('/*').get(errors[404]);
};


text:
===============
teracy-tutorial
===============

The adaptation of tutorial at https://docs.djangoproject.com/en/1.5/
to https://github.com/teracy-official/teracy project layout.


text:
package org.loon.framework.android.game.core.resource;

import org.loon.framework.android.game.utils.NumberUtils;

public class LPKHeader {

	public static final int LF_PAK_ID = (('L' << 24) + ('G' << 16) + ('P' << 8) + 'K');

	public static final int LF_PASSWORD_LENGTH = 10;

	public static final int LF_FILE_LENGTH = 30;

	private int identity;

	private byte[] password;

	private float version = 1.0F;

	private long tables = 0;

	public LPKHeader() {
		this.password = new byte[LPKHeader.LF_PASSWORD_LENGTH];
	}

	public LPKHeader(byte[] password, float version, long tables) {
		this.password = new byte[LPKHeader.LF_PASSWORD_LENGTH];
		for (int i = 0; i < LPKHeader.LF_PASSWORD_LENGTH; this.password[i] = password[i], i++)
			;
		this.version = version;
		this.tables = tables;
	}

	public long getTables() {
		return tables;
	}

	public void setTables(long tables) {
		this.tables = tables;
	}

	public float getVersion() {
		return version;
	}

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

	public int getPAKIdentity() {
		return LPKHeader.LF_PAK_ID;
	}

	public void setPAKIdentity(int id) {
		this.identity = id;
	}

	public boolean validatePAK() {
		return identity == LPKHeader.LF_PAK_ID;
	}

	public byte[] getPassword() {
		return password;
	}

	public void setPassword(long pass) {
		this.password = NumberUtils.addZeros(pass, LPKHeader.LF_PASSWORD_LENGTH)
				.getBytes();
	}

	public void setPassword(byte[] password) {
		for (int i = 0; i < LPKHeader.LF_PASSWORD_LENGTH; password[i] = password[i], i++)
			;
	}

	public static int size() {
		return 4 + LPKHeader.LF_PASSWORD_LENGTH + 4 + 4 + 1;
	}

}


text:
package com.navercorp.pinpoint.profiler.sender.planer;

import com.navercorp.pinpoint.profiler.sender.PartitionedByteBufferLocator;
import com.navercorp.pinpoint.profiler.sender.SpanStreamSendData;
import com.navercorp.pinpoint.profiler.sender.SpanStreamSendDataFactory;
import com.navercorp.pinpoint.profiler.sender.SpanStreamSendDataMode;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author Taejin Koo
 */
public abstract class AbstractSpanStreamSendDataPlaner implements SendDataPlaner {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    protected PartitionedByteBufferLocator partitionedByteBufferLocator;

    private final SpanStreamSendDataFactory spanStreamSendDataFactory;

    public AbstractSpanStreamSendDataPlaner(PartitionedByteBufferLocator partitionedByteBufferLocator, SpanStreamSendDataFactory spanStreamSendDataFactory) {
        this.partitionedByteBufferLocator = partitionedByteBufferLocator;
        this.spanStreamSendDataFactory = spanStreamSendDataFactory;
    }

    @Override
    public Iterator<SpanStreamSendData> getSendDataIterator() throws IOException {
        return getSendDataIterator(spanStreamSendDataFactory.create());
    }

    @Override
    public Iterator<SpanStreamSendData> getSendDataIterator(SpanStreamSendData spanStreamSendData) throws IOException {
        return getSendDataIterator(spanStreamSendData, null);
    }

    @Override
    public Iterator<SpanStreamSendData> getSendDataIterator(SpanStreamSendData spanStreamSendData, HeaderTBaseSerializer serializer) throws IOException {
        logger.info("process");

        List<SpanStreamSendData> spanStreamSendDataList = new ArrayList<SpanStreamSendData>();
        SpanStreamSendData currentSpanStreamSendData = spanStreamSendData;

        FlushMode mode = plan(spanStreamSendData);
        if (mode == FlushMode.FLUSH_FIRST) {
            spanStreamSendDataList.add(currentSpanStreamSendData);
            currentSpanStreamSendData.setFlushMode(SpanStreamSendDataMode.WAIT_BUFFER_AND_FLUSH);
            currentSpanStreamSendData = spanStreamSendDataFactory.create();
        }

        int byteBufferCapacity = partitionedByteBufferLocator.getTotalByteBufferCapacity();
        if (currentSpanStreamSendData.isAvailableBufferCapacity(byteBufferCapacity)) {
            if (currentSpanStreamSendData.getAvailableGatheringComponentsCount() < 2) {
                currentSpanStreamSendData.setFlushMode();
            }

            currentSpanStreamSendData.addBuffer(partitionedByteBufferLocator.getByteBuffer(), serializer);

            spanStreamSendDataList.add(currentSpanStreamSendData);
        } else {
            int markFromPartitionIndex = 0;
            int markToPartitionIndex = -1;

            int flushBufferCapacity = 0;
            for (int i = 0; i < partitionedByteBufferLocator.getPartitionedCount(); i++) {

                int appendBufferSize = 0;
                if (!partitionedByteBufferLocator.isLastPartitionIndex(i)) {
                    appendBufferSize = getSpanChunkLength();
                }

                flushBufferCapacity += partitionedByteBufferLocator.getByteBufferCapacity(i);
                if (needFlush(currentSpanStreamSendData, flushBufferCapacity, appendBufferSize)) {
                    ByteBuffer addBuffer = getByteBuffer(partitionedByteBufferLocator, markFromPartitionIndex, markToPartitionIndex);
                    if (addBuffer != null) {
                        ByteBuffer[] byteBufferArray = new ByteBuffer[2];
                        byteBufferArray[0] = addBuffer;
                        byteBufferArray[1] = getSpanChunkBuffer();

                        currentSpanStreamSendData.addBuffer(byteBufferArray);
                    }

                    currentSpanStreamSendData.setFlushMode();
                    spanStreamSendDataList.add(currentSpanStreamSendData);

                    currentSpanStreamSendData = spanStreamSendDataFactory.create();

                    markFromPartitionIndex = i;
                    flushBufferCapacity = partitionedByteBufferLocator.getByteBufferCapacity(i);
                }

                markToPartitionIndex = i;

                if (partitionedByteBufferLocator.isLastPartitionIndex(i)) {
                    ByteBuffer addBuffer = getByteBuffer(partitionedByteBufferLocator, markFromPartitionIndex, markToPartitionIndex);
                    currentSpanStreamSendData.addBuffer(addBuffer, serializer);

                    spanStreamSendDataList.add(currentSpanStreamSendData);
                }
            }
        }

        return spanStreamSendDataList.iterator();
    }

    private FlushMode plan(SpanStreamSendData spanStreamSendData) {
        int byteBufferCapacity = partitionedByteBufferLocator.getTotalByteBufferCapacity();

        if (byteBufferCapacity < spanStreamSendData.getAvailableBufferCapacity()) {
            return FlushMode.NORMAL;
        } else if (byteBufferCapacity < spanStreamSendData.getMaxBufferCapacity()) {
            return FlushMode.FLUSH_FIRST;
        } else {
            ByteBuffer spanChunkBuffer = getSpanChunkBuffer();

            for (int i = 0; i < partitionedByteBufferLocator.getPartitionedCount(); i++) {
                int currentBufferCapacity = partitionedByteBufferLocator.getByteBufferCapacity(i);

                if (partitionedByteBufferLocator.isLastPartitionIndex(i)) {
                    if (currentBufferCapacity > spanStreamSendData.getMaxBufferCapacity()) {
                        throw new IllegalStateException("BufferList has over size buffer. buffer length:" + currentBufferCapacity);
                    }
                } else {
                    if (currentBufferCapacity + spanChunkBuffer.remaining() > spanStreamSendData.getMaxBufferCapacity()) {
                        throw new IllegalStateException("BufferList has over size buffer. buffer length:" + currentBufferCapacity + ", maxCapacity:" + spanStreamSendData.getMaxBufferCapacity());
                    }
                }
            }

            return plan0(spanStreamSendData);
        }
    }

    private FlushMode plan0(SpanStreamSendData spanStreamSendData) {
        int normalModeChunkSize = calculateWithUsingCurrentSendData(spanStreamSendData);
        int flushFirstModeChunkSize = calculateWithoutUsingCurrentSendData(spanStreamSendData);

        if (normalModeChunkSize > flushFirstModeChunkSize) {
            return FlushMode.FLUSH_FIRST;
        } else {
            return FlushMode.NORMAL;
        }
    }

    private int calculateWithUsingCurrentSendData(SpanStreamSendData spanStreamSendData) {
        int chunkCount = 0;
        int availableBufferCapacity = spanStreamSendData.getAvailableBufferCapacity();

        return chunkCount + getNeedsChunkCount(spanStreamSendData, availableBufferCapacity);
    }

    private int calculateWithoutUsingCurrentSendData(SpanStreamSendData spanStreamSendData) {
        int chunkCount = 1;
        int availableBufferCapacity = spanStreamSendData.getMaxBufferCapacity();

        return chunkCount + getNeedsChunkCount(spanStreamSendData, availableBufferCapacity);
    }

    private int getNeedsChunkCount(SpanStreamSendData spanStreamSendData, int availableCurrentBufferCapacity) {
        int chunkCount = 1;
        int availableBufferCapacity = availableCurrentBufferCapacity;

        for (int i = 0; i < partitionedByteBufferLocator.getPartitionedCount(); i++) {
            int partitionByteBufferCapacity = partitionedByteBufferLocator.getByteBufferCapacity(i);

            if (partitionedByteBufferLocator.isLastPartitionIndex(i)) {
                if (partitionByteBufferCapacity > availableBufferCapacity) {
                    chunkCount++;
                }
            } else {
                if (partitionByteBufferCapacity + getSpanChunkLength() < availableBufferCapacity) {
                    availableBufferCapacity -= partitionByteBufferCapacity;
                } else {
                    chunkCount++;
                    availableBufferCapacity = spanStreamSendData.getMaxBufferCapacity();
                    availableBufferCapacity -= partitionByteBufferCapacity;
                }
            }
        }
        return chunkCount;
    }

    private boolean needFlush(SpanStreamSendData spanStreamSendData, int length, int delemeterBufferSize) {
        if (!spanStreamSendData.isAvailableBufferCapacity(length + delemeterBufferSize)) {
            return true;
        }

        int availableComponentsCount = 1;
        if (delemeterBufferSize > 0) {
            availableComponentsCount++;
        }

        if (!spanStreamSendData.isAvailableComponentsCount(availableComponentsCount)) {
            return true;
        }

        return false;
    }

    private ByteBuffer getByteBuffer(PartitionedByteBufferLocator partitionedByteBufferLocator, int fromPartitionIndex, int toPartitionIndex) {
        if (toPartitionIndex == -1) {
            return null;
        }

        return partitionedByteBufferLocator.getByteBuffer(fromPartitionIndex, toPartitionIndex);
    }

    abstract protected int getSpanChunkLength();

    abstract protected ByteBuffer getSpanChunkBuffer();

    private enum FlushMode {
        FLUSH_FIRST, NORMAL
    }

}


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace Elasticsearch.Net.Integration.Yaml.IndicesGetMapping4
{
	public partial class IndicesGetMapping4YamlTests
	{

		[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
		public class GettingMappingForAliasesShouldReturnTheRealIndexAsKey1Tests : YamlTestsBase
		{
			[Test]
			public void GettingMappingForAliasesShouldReturnTheRealIndexAsKey1Test()
			{

				//do indices.create
				_body = new {
					mappings= new {
						test_type= new {
							properties= new {
								text= new {
									type= "string",
									analyzer= "whitespace"
								}
							}
						}
					}
				};
				this.Do(()=> _client.IndicesCreate("test_index", _body));

				//do indices.put_alias
				this.Do(()=> _client.IndicesPutAlias("test_index", "test_alias", null));

				//do indices.get_mapping
				this.Do(()=> _client.IndicesGetMapping("test_alias"));

				//match _response.test_index.mappings.test_type.properties.text.type:
				this.IsMatch(_response.test_index.mappings.test_type.properties.text.type, @"string");

				//match _response.test_index.mappings.test_type.properties.text.analyzer:
				this.IsMatch(_response.test_index.mappings.test_type.properties.text.analyzer, @"whitespace");

			}
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MultipleApps1</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="btnText">Start another</string>

</resources>


text:
package v1

//go:generate swagger-doc

/*
 ATTENTION: Rerun code generators when comments on structs or fields are modified.
*/

type DomainSpec struct {
	Memory  Memory   `json:"memory"`
	Type    string   `json:"type"`
	OS      OS       `json:"os"`
	SysInfo *SysInfo `json:"sysInfo,omitempty"`
	Devices Devices  `json:"devices"`
	Clock   *Clock   `json:"clock,omitempty"`
}

type Memory struct {
	Value uint   `json:"value"`
	Unit  string `json:"unit"`
}

type Devices struct {
	Emulator   string      `json:"emulator,omitempty"`
	Interfaces []Interface `json:"interfaces,omitempty"`
	Channels   []Channel   `json:"channels,omitempty"`
	Video      []Video     `json:"video,omitempty"`
	Graphics   []Graphics  `json:"graphics,omitempty"`
	Ballooning *Ballooning `json:"memballoon,omitempty"`
	Disks      []Disk      `json:"disks,omitempty"`
	Serials    []Serial    `json:"serials,omitempty"`
	Consoles   []Console   `json:"consoles,omitempty"`
}

// BEGIN Disk -----------------------------

type Disk struct {
	Device   string      `json:"device"`
	Snapshot string      `json:"snapshot,omitempty"`
	Type     string      `json:"type"`
	Source   DiskSource  `json:"source"`
	Target   DiskTarget  `json:"target"`
	Serial   string      `json:"serial,omitempty"`
	Driver   *DiskDriver `json:"driver,omitempty"`
	ReadOnly *ReadOnly   `json:"readOnly,omitempty"`
}

type ReadOnly struct{}

type DiskSource struct {
	File          string          `json:"file,omitempty"`
	StartupPolicy string          `json:"startupPolicy,omitempty"`
	Protocol      string          `json:"protocol,omitempty"`
	Name          string          `json:"name,omitempty"`
	Host          *DiskSourceHost `json:"host,omitempty"`
}

type DiskTarget struct {
	Bus    string `json:"bus,omitempty"`
	Device string `json:"dev"`
}

type DiskDriver struct {
	Cache       string `json:"cache,omitempty"`
	ErrorPolicy string `json:"errorPolicy,omitempty"`
	IO          string `json:"io,omitempty"`
	Name        string `json:"name,omitempty"`
	Type        string `json:"type,omitempty"`
}

type DiskSourceHost struct {
	Name string `json:"name"`
	Port string `json:"port,omitempty"`
}

// END Disk -----------------------------

// BEGIN Serial -----------------------------

type Serial struct {
	Type   string        `json:"type"`
	Target *SerialTarget `json:"target,omitempty"`
}

type SerialTarget struct {
	Port *uint `json:"port,omitempty"`
}

// END Serial -----------------------------

// BEGIN Console -----------------------------

type Console struct {
	Type   string         `json:"type"`
	Target *ConsoleTarget `json:"target,omitempty"`
}

type ConsoleTarget struct {
	Type *string `json:"type,omitempty"`
	Port *uint   `json:"port,omitempty"`
}

// END Serial -----------------------------

// BEGIN Inteface -----------------------------

type Interface struct {
	Address   *Address         `json:"address,omitempty"`
	Type      string           `json:"type"`
	Source    InterfaceSource  `json:"source"`
	Target    *InterfaceTarget `json:"target,omitempty"`
	Model     *Model           `json:"model,omitempty"`
	MAC       *MAC             `json:"mac,omitempty"`
	BandWidth *BandWidth       `json:"bandwidth,omitempty"`
	BootOrder *BootOrder       `json:"boot,omitempty"`
	LinkState *LinkState       `json:"link,omitempty"`
	FilterRef *FilterRef       `json:"filterRef,omitempty"`
	Alias     *Alias           `json:"alias,omitempty"`
}

type LinkState struct {
	State string `json:"state"`
}

type BandWidth struct {
}

type BootOrder struct {
	Order uint `json:"order"`
}

type MAC struct {
	MAC string `json:"address"`
}

type FilterRef struct {
	Filter string `json:"filter"`
}

type InterfaceSource struct {
	Network string `json:"network,omitempty"`
	Device  string `json:"device,omitempty"`
	Bridge  string `json:"bridge,omitempty"`
}

type Model struct {
	Type string `json:"type"`
}

type InterfaceTarget struct {
	Device string `json:"dev"`
}

type Alias struct {
	Name string `json:"name"`
}

// END Inteface -----------------------------
//BEGIN OS --------------------

type OS struct {
	Type      OSType    `json:"type"`
	SMBios    *SMBios   `json:"smBIOS,omitempty"`
	BootOrder []Boot    `json:"bootOrder"`
	BootMenu  *BootMenu `json:"bootMenu,omitempty"`
	BIOS      *BIOS     `json:"bios,omitempty"`
}

type OSType struct {
	OS      string `json:"os"`
	Arch    string `json:"arch,omitempty"`
	Machine string `json:"machine,omitempty"`
}

type SMBios struct {
	Mode string `json:"mode"`
}

type NVRam struct {
	NVRam    string `json:"nvRam,omitempty"`
	Template string `json:"template,omitempty"`
}

type Boot struct {
	Dev string `json:"dev"`
}

type BootMenu struct {
	Enabled bool  `json:"enabled,omitempty"`
	Timeout *uint `json:"timeout,omitempty"`
}

// TODO <loader readonly='yes' secure='no' type='rom'>/usr/lib/xen/boot/hvmloader</loader>
type BIOS struct {
}

// TODO <bios useserial='yes' rebootTimeout='0'/>
type Loader struct {
}

type SysInfo struct {
	Type      string  `json:"type"`
	System    []Entry `json:"system"`
	BIOS      []Entry `json:"bios"`
	BaseBoard []Entry `json:"baseBoard"`
}

type Entry struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

//END OS --------------------

//BEGIN Clock --------------------

type Clock struct {
}

type Timer struct {
	Name       string `json:"name"`
	TickPolicy string `json:"tickPolicy,omitempty"`
	Present    string `json:"present,omitempty"`
}

//END Clock --------------------

//BEGIN Channel --------------------

type Channel struct {
	Type   string         `json:"type"`
	Source ChannelSource  `json:"source,omitempty"`
	Target *ChannelTarget `json:"target,omitempty"`
}

type ChannelTarget struct {
	Name    string `json:"name,omitempty"`
	Type    string `json:"type"`
	Address string `json:"address,omitempty"`
	Port    uint   `json:"port,omitempty"`
}

type ChannelSource struct {
	Mode string `json:"mode"`
	Path string `json:"path"`
}

//END Channel --------------------

//BEGIN Video -------------------
/*
<graphics autoport="yes" defaultMode="secure" listen="0" passwd="*****" passwdValidTo="1970-01-01T00:00:01" port="-1" tlsPort="-1" type="spice" />
*/

type Video struct {
	Type   string `json:"type"`
	Heads  *uint  `json:"heads,omitempty"`
	Ram    *uint  `json:"ram,omitempty"`
	VRam   *uint  `json:"vRam,omitempty"`
	VGAMem *uint  `json:"vgaMem,omitempty"`
}

type Graphics struct {
	AutoPort      string `json:"autoPort,omitempty"`
	DefaultMode   string `json:"defaultMode,omitempty"`
	Listen        Listen `json:"listen,omitempty"`
	PasswdValidTo string `json:"passwdValidTo,omitempty"`
	Port          int32  `json:"port,omitempty"`
	TLSPort       int    `json:"tlsPort,omitempty"`
	Type          string `json:"type"`
}

type Listen struct {
	Type    string `json:"type"`
	Address string `json:"address,omitempty"`
	Network string `json:"network,omitempty"`
}

type Address struct {
	Type     string `json:"type"`
	Domain   string `json:"domain"`
	Bus      string `json:"bus"`
	Slot     string `json:"slot"`
	Function string `json:"function"`
}

//END Video -------------------

type Ballooning struct {
	Model string `json:"model"`
}

type RandomGenerator struct {
}

// TODO ballooning, rng, cpu ...

func NewMinimalDomainSpec() *DomainSpec {
	domain := DomainSpec{OS: OS{Type: OSType{OS: "hvm"}}, Type: "qemu"}
	domain.Memory = Memory{Unit: "KiB", Value: 8192}
	domain.Devices = Devices{}
	domain.Devices.Interfaces = []Interface{
		{Type: "network", Source: InterfaceSource{Network: "default"}},
	}
	return &domain
}


text:
package edu.neu.ccs.pyramid.application;

import edu.neu.ccs.pyramid.configuration.Config;
import edu.neu.ccs.pyramid.dataset.*;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * merge two datasets into one
 * Created by chengli on 5/18/16.
 */
public class Merger {
    public static void main(String[] args) throws Exception{
        Config config = new Config(args[0]);
        System.out.println(config);
        String dataType = config.getString("dataSetType");
        switch (dataType) {
            case "clf":
                mergeClfData(config);
                break;
            case "reg":
                //todo
                break;
            case "mlclf":
                mergeMLClfData(config);
        }

    }

    private static void mergeClfData(Config config) throws Exception{
        String input1 = config.getString("input.data1");
        String input2 = config.getString("input.data2");
        String output= config.getString("output.data");
        ClfDataSet dataSet1 = TRECFormat.loadClfDataSet(input1,DataSetType.CLF_DENSE,true);
        ClfDataSet dataSet2 = TRECFormat.loadClfDataSet(input2,DataSetType.CLF_DENSE,true);
        ClfDataSet merged = DataSetUtil.concatenateByRow(dataSet1,dataSet2);
        TRECFormat.save(merged,output);

    }

    private static void mergeMLClfData(Config config) throws Exception{
        List<String> inputs = config.getStrings("input.dataSets");
        String output= config.getString("output.dataSet");
        List<MultiLabelClfDataSet> dataSets = new ArrayList<>();
        for (String input: inputs){
            MultiLabelClfDataSet dataSet = TRECFormat.loadMultiLabelClfDataSet(input,DataSetType.ML_CLF_SPARSE,true);
            dataSets.add(dataSet);
        }
        MultiLabelClfDataSet merged = DataSetUtil.concatenateByRow(dataSets);
        TRECFormat.save(merged,output);

    }
}


text:
"""
    Difficulty: *
    Code:       *

    Ref: https://www.hackerrank.com/challenges/minimum-distances
"""
import unittest

def find_min_distance(arr):
    found = {}
    min_distance = float('inf')
    for i, val in enumerate(arr):
        if val in found:
            if min_distance > abs(found[val] - i):
                min_distance = abs(found[val] - i)
                found[val] = i
        else:
            found[val] = i
    min_distance = min_distance if min_distance != float('inf') else -1
    return min_distance

class MyTestCases(unittest.TestCase):
    def test_find_min_distance(self):
        arr = [7, 1, 3, 4, 1, 7]
        self.assertEqual(find_min_distance(arr), 3)

if __name__ == '__main__':
    n = int(input().strip())
    A = [int(A_temp) for A_temp in input().strip().split(' ')]
    print(find_min_distance(A))


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.google.zxing.client.android"
          android:versionCode="1"
          android:versionName="1.0"
          android:installLocation="auto">

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.FLASHLIGHT"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <uses-sdk android:minSdkVersion="15"/>

    <application android:icon="@drawable/launcher_icon"
                 android:logo="@drawable/launcher_icon"
                 android:label="@string/app_name"
                 android:allowBackup="true">
        <activity
                android:name=".CaptureActivity"
                android:clearTaskOnLaunch="true"
                android:stateNotNeeded="true"
                android:screenOrientation="portrait"
                android:theme="@style/CaptureTheme"
                android:windowSoftInputMode="stateAlwaysHidden">
        </activity>
    </application>

</manifest>


text:
<?php

namespace Doctrine\ORM\Tools\Console\Command\SchemaTool;

use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Base class for CreateCommand, DropCommand and UpdateCommand.
 *
 * @link    www.doctrine-project.org
 * @since   2.0
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
abstract class AbstractCommand extends Command
{

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $emHelper = $this->getHelper('em');

        /* @var $em \Doctrine\ORM\EntityManager */
        $em = $emHelper->getEntityManager();

        $metadatas = $em->getMetadataFactory()->getAllMetadata();

        if (!empty( $metadatas )) {
            // Create SchemaTool
            $tool = new SchemaTool($em);

            return $this->executeSchemaCommand($input, $output, $tool, $metadatas);
        } else {
            $output->writeln('No Metadata Classes to process.');
            return 0;
        }
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     * @param SchemaTool      $schemaTool
     * @param array           $metadatas
     *
     * @return null|int Null or 0 if everything went fine, or an error code.
     */
    abstract protected function executeSchemaCommand(
        InputInterface $input,
        OutputInterface $output,
        SchemaTool $schemaTool,
        array $metadatas
    );
}


text:
package com.ztiany.filter.filters;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class SetAllCharacterEncodingFilter implements Filter {

    private FilterConfig filterConfig;
    private ServletContext mServletContext;

    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        mServletContext = filterConfig.getServletContext();
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) resp;
        } catch (Exception e) {
            throw new RuntimeException("non http request");
        }

        //hwo to get runtime information
        System.out.println(mServletContext.getMajorVersion());//服务器支持的Servlet主版本号
        System.out.println(mServletContext.getMinorVersion());//服务器支持的Servlet次版本号
        Enumeration attributeNames = mServletContext.getAttributeNames();

        while (attributeNames.hasMoreElements()) {
            Object name = attributeNames.nextElement();
            System.out.println(name + " = " + mServletContext.getAttribute((String) name));
        }

        String encoding = filterConfig.getInitParameter("encoding");

        if (encoding == null) {
            encoding = "UTF-8";
        }

        request.setCharacterEncoding(encoding);//POST方式,同时也可以给后面过滤器或Servlet使用
        response.setCharacterEncoding(encoding);//给后面过滤器或Servlet使用
        response.setContentType("text/html;charset=" + encoding);//输出字符流使用的编码,告知客户端用什么编码解码

        CodeFixHttpServletRequest codeFixHttpServletRequest = new CodeFixHttpServletRequest(request);

        chain.doFilter(codeFixHttpServletRequest, response);
    }

    public void destroy() {

    }

    private class CodeFixHttpServletRequest extends HttpServletRequestWrapper {

        CodeFixHttpServletRequest(HttpServletRequest request) {
            super(request);
        }

        public String getParameter(String name) {
            String value = super.getParameter(name);
            if (value == null) {
                return null;
            }

            //只管get方式
            String method = super.getMethod();

            if ("get".equalsIgnoreCase(method)) {
                value = fixGetEncoding(value);
            }
            return value;
        }

        private String fixGetEncoding(String value) {

            try {
                //for tomcat 6/7
                value = new String(value.getBytes("ISO-8859-1"), super.getCharacterEncoding());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return value;
        }

    }

}


text:
require 'spec_helper'

module Arel
  describe SqlLiteral do
    before do
      @relation = Table.new(:users)
    end

    describe '#to_sql' do
      it "manufactures sql with a literal SQL fragment" do
        sql = @relation.project(Count.new(SqlLiteral.new("*"))).to_sql

        adapter_is :mysql do
          sql.should be_like(%Q{SELECT COUNT(*) AS count_id FROM `users`})
        end

        adapter_is :oracle do
          sql.should be_like(%Q{SELECT COUNT(*) AS count_id FROM "USERS"})
        end

        adapter_is_not :mysql, :oracle do
          sql.should be_like(%Q{SELECT COUNT(*) AS count_id FROM "users"})
        end
      end

      it "manufactures expressions on literal SQL fragment" do
        sql = @relation.project(SqlLiteral.new("2 * credit_limit").sum).to_sql

        adapter_is :mysql do
          sql.should be_like(%Q{SELECT SUM(2 * credit_limit) AS sum_id FROM `users`})
        end

        adapter_is :oracle do
          sql.should be_like(%Q{SELECT SUM(2 * credit_limit) AS sum_id FROM "USERS"})
        end

        adapter_is_not :mysql, :oracle do
          sql.should be_like(%Q{SELECT SUM(2 * credit_limit) AS sum_id FROM "users"})
        end
      end
    end
  end
end


text:
package gate.compound.impl;

import gate.ProcessingResource;
import gate.Resource;
import gate.compound.CompoundDocument;
import gate.creole.AbstractLanguageAnalyser;
import gate.creole.ExecutionException;
import gate.creole.ResourceInstantiationException;

/**
 * This PR deletes a member document from the compound document.
 *
 * @author niraj
 */
public class DeleteMemberPR extends AbstractLanguageAnalyser implements
		ProcessingResource {

	private static final long serialVersionUID = 2001251690576486313L;

	private String documentID;

	/*
	 * this method gets called whenever an object of this class is created
	 * either from GATE GUI or if initiated using Factory.createResource()
	 * method.
	 */
	public Resource init() throws ResourceInstantiationException {
		// here initialize all required variables, and may
		// be throw an exception if the value for any of the
		// mandatory parameters is not provided
		return this;
	}

	/* this method is called to reinitialize the resource */
	public void reInit() throws ResourceInstantiationException {
		// reinitialization code
		init();
	}

	public void execute() throws ExecutionException {
		if (document == null) {
			throw new ExecutionException("Document is null!");
		}

		if (document instanceof CompoundDocument)
			((CompoundDocument) document).removeDocument(documentID);
		else
			System.err
					.println("Since the document is not an instance of CompoundDocument, No changes made for the document :"
							+ document.getName());
	}

	public String getDocumentID() {
		return documentID;
	}

	public void setDocumentID(String documentID) {
		this.documentID = documentID;
	}
}