text:
package es.tid.ospf.ospfv2.lsa.tlv;

import es.tid.ospf.ospfv2.lsa.tlv.subtlv.AdministrativeGroup;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.AvailableLabels;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.IPv4RemoteASBRID;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.InterfaceSwitchingCapabilityDescriptor;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.LinkID;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.LinkLocalRemoteIdentifiers;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.LinkProtectionType;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.LinkType;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.LocalInterfaceIPAddress;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.MalformedOSPFSubTLVException;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.MaximumBandwidth;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.MaximumReservableBandwidth;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.OSPFSubTLV;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.OSPFSubTLVTypes;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.RemoteASNumber;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.RemoteInterfaceIPAddress;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.SharedRiskLinkGroup;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.TrafficEngineeringMetric;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.UnreservedBandwidth;

/**
 * Link TLV from RFC 3630 (TE Extensions to OSPF Version 2).
 *
 *2.4.2. Link TLV
   The Link TLV describes a single link.  It is constructed of a set of
   sub-TLVs.  There are no ordering requirements for the sub-TLVs.

   Only one Link TLV shall be carried in each LSA, allowing for fine
   granularity changes in topology.

   The Link TLV is type 2, and the length is variable.

   The following sub-TLVs of the Link TLV are defined:

      1 - Link type (1 octet)
      2 - Link ID (4 octets)
      3 - Local interface IP address (4 octets)
      4 - Remote interface IP address (4 octets)
      5 - Traffic engineering metric (4 octets)
      6 - Maximum bandwidth (4 octets)
      7 - Maximum reservable bandwidth (4 octets)
      8 - Unreserved bandwidth (32 octets)
      9 - Administrative group (4 octets)

   This memo defines sub-Types 1 through 9.  See the IANA Considerations
   section for allocation of new sub-Types.

   The Link Type and Link ID sub-TLVs are mandatory, i.e., must appear
   exactly once.  All other sub-TLVs defined here may occur at most
   once.  These restrictions need not apply to future sub-TLVs.
   Unrecognized sub-TLVs are ignored.
   Various values below use the (32 bit) IEEE Floating Point format.
   For quick reference, this format is as follows:
       0                   1                   2                   3
       0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |S|    Exponent   |                  Fraction                   |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

   S is the sign, Exponent is the exponent base 2 in "excess 127"
   notation, and Fraction is the mantissa - 1, with an implied binary
   point in front of it.  Thus, the above represents the value:

      (-1)**(S) * 2**(Exponent-127) * (1 + Fraction)

   For more details, refer to [4].
 *  @author ogondio
 */
public class LinkTLV extends OSPFTLV {

	private LinkType linkType;

	private LinkID linkID;

	private LocalInterfaceIPAddress localInterfaceIPAddress;

	private RemoteInterfaceIPAddress remoteInterfaceIPAddress;

	private TrafficEngineeringMetric trafficEngineeringMetric;

	private MaximumBandwidth maximumBandwidth;

	private MaximumReservableBandwidth maximumReservableBandwidth;

	private UnreservedBandwidth unreservedBandwidth;

	private AdministrativeGroup administrativeGroup;

	private LinkLocalRemoteIdentifiers linkLocalRemoteIdentifiers;

	private LinkProtectionType linkProtectionType;

	//private InterfaceSwitchingCapabilityDescriptor interfaceSwitchingCapabilityDescriptor;

	private SharedRiskLinkGroup sharedRiskLinkGroup;

	private RemoteASNumber remoteASNumber;

	private IPv4RemoteASBRID iPv4RemoteASBRID;

	private AvailableLabels availableLabels;

	public LinkTLV(){
		this.setTLVType(OSPFTLVTypes.LinkTLV);
	}

	public LinkTLV(byte[] bytes, int offset)throws MalformedOSPFTLVException{
		super(bytes,offset);
		decode();
	}

	@Override
	public void encode() {
		int valueLength=0;
		if (linkType!=null){
			linkType.encode();
			valueLength=valueLength+linkType.getTotalTLVLength();
		}
		else {
			//FIXME: THROW EXCEPTION??
		}
		if (linkID!=null){
			linkID.encode();
			valueLength=valueLength+linkID.getTotalTLVLength();

		}
		else {
			//FIXME: THROW EXCEPTION??
		}

		if (localInterfaceIPAddress!=null){
			localInterfaceIPAddress.encode();
			valueLength=valueLength+localInterfaceIPAddress.getTotalTLVLength();
		}
		if (remoteInterfaceIPAddress!=null){
			remoteInterfaceIPAddress.encode();
			valueLength=valueLength+remoteInterfaceIPAddress.getTotalTLVLength();
		}

		if (maximumBandwidth!=null){
			maximumBandwidth.encode();
			valueLength=valueLength+maximumBandwidth.getTotalTLVLength();
		}

		if (maximumReservableBandwidth!=null){
			maximumReservableBandwidth.encode();
			valueLength=valueLength+maximumReservableBandwidth.getTotalTLVLength();
		}

		if (unreservedBandwidth!=null){
			unreservedBandwidth.encode();
			valueLength=valueLength+unreservedBandwidth.getTotalTLVLength();
		}

		if (administrativeGroup!=null){
			try {
				administrativeGroup.encode();
			} catch (MalformedOSPFSubTLVException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			valueLength=valueLength+administrativeGroup.getTotalTLVLength();
		}

		if (linkLocalRemoteIdentifiers!=null){
			linkLocalRemoteIdentifiers.encode();
			valueLength=valueLength+linkLocalRemoteIdentifiers.getTotalTLVLength();
		}

		if (remoteASNumber!=null){
			remoteASNumber.encode();
			valueLength=valueLength+remoteASNumber.getTotalTLVLength();
		}

		if (iPv4RemoteASBRID!=null){
			iPv4RemoteASBRID.encode();
			valueLength=valueLength+iPv4RemoteASBRID.getTotalTLVLength();
		}
		if (availableLabels != null){
			try {
				availableLabels.encode();
			} catch (MalformedOSPFSubTLVException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			valueLength=valueLength+availableLabels.getTotalTLVLength();
		}
		//After encoding, the valueLength is known
		this.setTLVValueLength(valueLength);
		//After calling setTLVValueLength, the total TLV length is computed
		//Then create the byte array
		this.tlv_bytes=new byte[this.getTotalTLVLength()];
		//Encode the header
		this.encodeHeader();
		int offset=4;
		if (linkType!=null){
			System.arraycopy(linkType.getTlv_bytes(),0, this.tlv_bytes,offset, linkType.getTotalTLVLength());
			offset=offset+linkType.getTotalTLVLength();
		}
		if (linkID!=null){
			System.arraycopy(linkID.getTlv_bytes(),0, this.tlv_bytes,offset, linkID.getTotalTLVLength());
			offset=offset+linkID.getTotalTLVLength();
		}
		if (localInterfaceIPAddress!=null){
			System.arraycopy(localInterfaceIPAddress.getTlv_bytes(),0, this.tlv_bytes,offset, localInterfaceIPAddress.getTotalTLVLength());
			offset=offset+localInterfaceIPAddress.getTotalTLVLength();
		}
		if (remoteInterfaceIPAddress!=null){
			System.arraycopy(remoteInterfaceIPAddress.getTlv_bytes(),0, this.tlv_bytes,offset, remoteInterfaceIPAddress.getTotalTLVLength());
			offset=offset+remoteInterfaceIPAddress.getTotalTLVLength();
		}
		if (maximumBandwidth!=null){
			System.arraycopy(maximumBandwidth.getTlv_bytes(),0, this.tlv_bytes,offset, maximumBandwidth.getTotalTLVLength());
			offset=offset+maximumBandwidth.getTotalTLVLength();
		}
		if (maximumReservableBandwidth!=null){
			System.arraycopy(maximumReservableBandwidth.getTlv_bytes(),0, this.tlv_bytes,offset, maximumReservableBandwidth.getTotalTLVLength());
			offset=offset+maximumReservableBandwidth.getTotalTLVLength();
		}
		if (unreservedBandwidth!=null){
			System.arraycopy(unreservedBandwidth.getTlv_bytes(),0, this.tlv_bytes,offset, unreservedBandwidth.getTotalTLVLength());
			offset=offset+unreservedBandwidth.getTotalTLVLength();
		}
		if (administrativeGroup!=null){
			System.arraycopy(administrativeGroup.getTlv_bytes(),0, this.tlv_bytes,offset, administrativeGroup.getTotalTLVLength());
			offset=offset+administrativeGroup.getTotalTLVLength();
		}
		if (linkLocalRemoteIdentifiers!=null){
			System.arraycopy(linkLocalRemoteIdentifiers.getTlv_bytes(),0, this.tlv_bytes,offset, linkLocalRemoteIdentifiers.getTotalTLVLength());
			offset=offset+linkLocalRemoteIdentifiers.getTotalTLVLength();
		}
		if (remoteASNumber!=null){
			System.arraycopy(remoteASNumber.getTlv_bytes(),0, this.tlv_bytes,offset, remoteASNumber.getTotalTLVLength());
			offset=offset+remoteASNumber.getTotalTLVLength();
		}
		if (iPv4RemoteASBRID!=null){
			System.arraycopy(iPv4RemoteASBRID.getTlv_bytes(),0, this.tlv_bytes,offset, iPv4RemoteASBRID.getTotalTLVLength());
			offset=offset+iPv4RemoteASBRID.getTotalTLVLength();
		}
		if (availableLabels != null){
			System.arraycopy(availableLabels.getTlv_bytes(), 0, this.tlv_bytes, offset, availableLabels.getTotalTLVLength());
		}
	}

	private void decode()throws MalformedOSPFTLVException{
		boolean fin=false;
		int offset=4;//Position of the next subobject
		if (this.getTLVValueLength()==0){
			throw new MalformedOSPFTLVException();
		}
		while (!fin) {
			int subTLVType=OSPFSubTLV.getType(this.getTlv_bytes(), offset);
			int subTLVLength=OSPFSubTLV.getTotalTLVLength(this.getTlv_bytes(), offset);
			try {
				switch (subTLVType){
				case OSPFSubTLVTypes.LinkID:
					this.linkID=new LinkID(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.LinkType:
					this.linkType=new LinkType(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.LocalInterfaceIPAddress:
					this.localInterfaceIPAddress=new LocalInterfaceIPAddress(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.RemoteInterfaceIPAddress:
					this.remoteInterfaceIPAddress=new RemoteInterfaceIPAddress(this.getTlv_bytes(), offset);
					break;
				case OSPFSubTLVTypes.TrafficEngineeringMetric:
					this.trafficEngineeringMetric=new TrafficEngineeringMetric(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.MaximumBandwidth:
					this.maximumBandwidth=new MaximumBandwidth(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.MaximumReservableBandwidth:
					this.maximumReservableBandwidth=new MaximumReservableBandwidth(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.UnreservedBandwidth:
					this.unreservedBandwidth=new UnreservedBandwidth(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.AdministrativeGroup:
					this.administrativeGroup=new AdministrativeGroup(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.LinkLocalRemoteIdentifiers:
					this.linkLocalRemoteIdentifiers=new LinkLocalRemoteIdentifiers(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.LinkProtectionType:
					this.linkProtectionType=new LinkProtectionType(this.getTlv_bytes(), offset);
					break;

//				case OSPFSubTLVTypes.InterfaceSwitchingCapabilityDescriptor:
//					this.interfaceSwitchingCapabilityDescriptor=new InterfaceSwitchingCapabilityDescriptor(this.getTlv_bytes(), offset);
//					break;

				case OSPFSubTLVTypes.SharedRiskLinkGroup:
					this.sharedRiskLinkGroup=new SharedRiskLinkGroup(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.RemoteASNumber:
					this.remoteASNumber=new RemoteASNumber(this.getTlv_bytes(), offset);
					break;

				case OSPFSubTLVTypes.IPv4RemoteASBRID:
					this.iPv4RemoteASBRID=new IPv4RemoteASBRID(this.getTlv_bytes(), offset);
					break;
				case OSPFSubTLVTypes.AvailableLabels:
					this.availableLabels = new AvailableLabels(this.getTlv_bytes(), offset);
					break;
				default:
					log.warn("Unknown TLV found: "+subTLVType);

				}
			} catch (MalformedOSPFSubTLVException e) {
				log.warn("Malformed SubTLV found ");
				throw new MalformedOSPFTLVException();
			}
			offset=offset+subTLVLength;
			if (offset>=(this.getTLVValueLength()+4)){
				fin=true;
			}

		}
	}

	public LinkType getLinkType() {
		return linkType;
	}

	public void setLinkType(LinkType linkType) {
		this.linkType = linkType;
	}

	public LinkID getLinkID() {
		return linkID;
	}

	public void setLinkID(LinkID linkID) {
		this.linkID = linkID;
	}

	public LocalInterfaceIPAddress getLocalInterfaceIPAddress() {
		return localInterfaceIPAddress;
	}

	public void setLocalInterfaceIPAddress(
			LocalInterfaceIPAddress localInterfaceIPAddress) {
		this.localInterfaceIPAddress = localInterfaceIPAddress;
	}

	public RemoteInterfaceIPAddress getRemoteInterfaceIPAddress() {
		return remoteInterfaceIPAddress;
	}

	public void setRemoteInterfaceIPAddress(
			RemoteInterfaceIPAddress remoteInterfaceIPAddress) {
		this.remoteInterfaceIPAddress = remoteInterfaceIPAddress;
	}

	public MaximumBandwidth getMaximumBandwidth() {
		return maximumBandwidth;
	}

	public void setMaximumBandwidth(MaximumBandwidth maximumBandwidth) {
		this.maximumBandwidth = maximumBandwidth;
	}

	public MaximumReservableBandwidth getMaximumReservableBandwidth() {
		return maximumReservableBandwidth;
	}

	public void setMaximumReservableBandwidth(
			MaximumReservableBandwidth maximumReservableBandwidth) {
		this.maximumReservableBandwidth = maximumReservableBandwidth;
	}

	public UnreservedBandwidth getUnreservedBandwidth() {
		return unreservedBandwidth;
	}

	public void setUnreservedBandwidth(UnreservedBandwidth unreservedBandwidth) {
		this.unreservedBandwidth = unreservedBandwidth;
	}

	public AvailableLabels getAvailableLabels() {
		return availableLabels;
	}

	public void setAvailableLabels(AvailableLabels availableLabels) {
		//this.availableLabels = availableLabels;//FIXME
	}

	public AdministrativeGroup getAdministrativeGroup() {
		return administrativeGroup;
	}

	public void setAdministrativeGroup(AdministrativeGroup administrativeGroup) {
		this.administrativeGroup = administrativeGroup;
	}

	public TrafficEngineeringMetric getTrafficEngineeringMetric() {
		return trafficEngineeringMetric;
	}

	public void setTrafficEngineeringMetric(
			TrafficEngineeringMetric trafficEngineeringMetric) {
		this.trafficEngineeringMetric = trafficEngineeringMetric;
	}

	public LinkLocalRemoteIdentifiers getLinkLocalRemoteIdentifiers() {
		return linkLocalRemoteIdentifiers;
	}

	public void setLinkLocalRemoteIdentifiers(
			LinkLocalRemoteIdentifiers linkLocalRemoteIdentifiers) {
		this.linkLocalRemoteIdentifiers = linkLocalRemoteIdentifiers;
	}

	public LinkProtectionType getLinkProtectionType() {
		return linkProtectionType;
	}

	public void setLinkProtectionType(LinkProtectionType linkProtectionType) {
		this.linkProtectionType = linkProtectionType;
	}

//	public InterfaceSwitchingCapabilityDescriptor getInterfaceSwitchingCapabilityDescriptor() {
//		return interfaceSwitchingCapabilityDescriptor;
//	}
//
//	public void setInterfaceSwitchingCapabilityDescriptor(
//			InterfaceSwitchingCapabilityDescriptor interfaceSwitchingCapabilityDescriptor) {
//		this.interfaceSwitchingCapabilityDescriptor = interfaceSwitchingCapabilityDescriptor;
//	}

	public SharedRiskLinkGroup getSharedRiskLinkGroup() {
		return sharedRiskLinkGroup;
	}

	public void setSharedRiskLinkGroup(SharedRiskLinkGroup sharedRiskLinkGroup) {
		//this.sharedRiskLinkGroup = sharedRiskLinkGroup;
	}

	public RemoteASNumber getRemoteASNumber() {
		return remoteASNumber;
	}

	public void setRemoteASNumber(RemoteASNumber remoteASNumber) {
		//this.remoteASNumber = remoteASNumber;
	}

	public IPv4RemoteASBRID getIPv4RemoteASBRID() {
		return iPv4RemoteASBRID;
	}

	public void setIPv4RemoteASBRID(IPv4RemoteASBRID iPv4RemoteASBRID) {
		this.iPv4RemoteASBRID = iPv4RemoteASBRID;
	}

	public String toString(){
		StringBuffer sb=new StringBuffer(1000);
		if (linkType!=null){
			sb.append(linkType.toString());
			sb.append("\r\n");
		}
		if (linkID!=null){
			sb.append(linkID.toString());
			sb.append("\r\n");
		}
		if (localInterfaceIPAddress!=null){
			sb.append(localInterfaceIPAddress.toString());
			sb.append("\r\n");
		}
		if (remoteInterfaceIPAddress!=null){
			sb.append(remoteInterfaceIPAddress.toString());
			sb.append("\r\n");
		}

		if (maximumBandwidth!=null){
			sb.append(maximumBandwidth.toString());
			sb.append("\r\n");
		}
		if (maximumReservableBandwidth!=null){
			sb.append(maximumReservableBandwidth.toString());
			sb.append("\r\n");
		}

		if (unreservedBandwidth!=null){
			sb.append(unreservedBandwidth.toString());
			sb.append("\r\n");
		}

		if (administrativeGroup!=null){
			sb.append(administrativeGroup.toString());
			sb.append("\r\n");
		}

		if (remoteASNumber!=null){
			sb.append(remoteASNumber.toString());
			sb.append("\r\n");
		}

		if (iPv4RemoteASBRID!=null){
			sb.append(iPv4RemoteASBRID.toString());
			sb.append("\r\n");
		}

		if (availableLabels!=null){
			sb.append(availableLabels.toString());
			sb.append("\r\n");
		}

//		if (interfaceSwitchingCapabilityDescriptor!=null){
//			sb.append(interfaceSwitchingCapabilityDescriptor.toString());
//			sb.append("\r\n");
//		}
		if (linkLocalRemoteIdentifiers!=null){
			sb.append(linkLocalRemoteIdentifiers.toString());
			sb.append("\r\n");
		}

		return sb.toString();
	}

	public String printShort(){
		StringBuffer sb=new StringBuffer(1000);
		if (linkID!=null){
			sb.append(linkID.toString());
			sb.append("\r\n");
		}
		if (localInterfaceIPAddress!=null){
			sb.append(localInterfaceIPAddress.toString());
			sb.append("\r\n");
		}
		if (remoteInterfaceIPAddress!=null){
			sb.append(remoteInterfaceIPAddress.toString());
			sb.append("\r\n");
		}

		if (remoteASNumber!=null){
			sb.append(remoteASNumber.toString());
			sb.append("\r\n");
		}

		if (iPv4RemoteASBRID!=null){
			sb.append(iPv4RemoteASBRID.toString());
			sb.append("\r\n");
		}

		if (availableLabels!=null){
			sb.append(availableLabels.toString());
			sb.append("\r\n");
		}

		return sb.toString();
	}

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Verh. zool. -bot. Ges. Wien 37: (1887)

#### Original name
Chaetoconidium arachnoideum Zukal, 1887

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
![travis](https://travis-ci.org/evildevel/php-shell.svg?branch=master)

# php-shell
Micro PHP Framework

[https://php-shell.com](https://php-shell.com)

### Requirements

You need at least `PHP 5.6` with extensions:

- [Zip](http://php.net/manual/en/book.zip.php)

### Install

- [Download](https://php-shell.com/public/export/core/php-shell.zip) the latest version
- Upload and unzip the archive to your server
- Set `install = true` in file `conf.php` to activate the module installation
- Set `location` in file `conf.php` to according your domain
- Follow `/import` to import modules via network

Note: You can manually [download](https://php-shell.com/downloads) and copy
modules into the directory `/protected/import` on your server. Follow `/install`
to start installation of imported modules. Best suited if the server cannot
connect to the Internet.

### Configuration
```php
array APP::$conf  // Core config
```

### Modules
```php
object APP::Module(string $classname)                           // Instance of a module class
mixed APP::Module(string $classname)->conf                      // Config of a module

object APP::LoadModule(string $path)                            // Load module
mixed APP::InitModule(object $module [, bool $force = false])   // Init module
```

### Render
Root directory: `/protected/render/`

Default file extension: `.php`
```php
mixed APP::Render(string $src[, string $mode = 'include'[, mixed $data = null[, string $ext = '.php']]])

// Mode
APP::Render('src')              // Include file
APP::Render('src', 'include')   // Same "include src"
APP::Render('src', 'content')   // Return the contents of the output buffer
APP::Render('src', 'return')    // Same "return include src"
APP::Render('src', 'eval')      // Same "return eval($src)"

// Data transfer
APP::Render('src', 'include', ['foo' => 'bar'])

// Return the contents of the src.csv
APP::Render('src', 'content', null, '.csv')

// Return eval content
APP::Render('<?= echo 'data' ?>', 'eval')
```

### Errors
To configure the error logging must be enabled `APP::$conf['logs']`. Set full
path to logs directory or `false` to disable logging. Set write permission for
the logs directory. In the log directory are created files `php-errors-[d-m-Y].log`.

Each call
```php
throw new Exception('message');
```
will be added record to the log file.

### Console
```php
// Example module
class Console {
    public function Test($arg1, $arg2, $arg3) {}
}
```
Run method `Test` in the module `Console` with three args

`php init.php Console Test '[{"x":"y"},1,"test"]'`

### Unit testing
Each module provides a class for testing.
```php
include_once 'init.php';
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase {}
```
Run test of module `Example`

`php phpunit.phar protected/modules/Example/test.php`

### Files
```
/
├── /protected
│   ├── /import                         # Imported modules
│   ├── /modules                        # Installed modules
│   └── /render
│       └── /core
│           ├── /widgets
│           │   ├── css.php
│           │   ├── ie_warning.php
│           │   ├── js.php
│           │   └── page_loader.php
│           ├── error.php
│           ├── import.php
│           └── install.php
├── phpshell.sql                        # Database dump
├── php.ini                             # Custom PHP config
├── app.php                             # Core class
├── conf.php                            # Main config
└── init.php                            # Init script
```

### Credits
Thanks to [Andrey Kosenko](https://github.com/kosenkoandrey) for great ideas and financial support of the project.


text:
<!-- Copyright 2014 SeaClouds Contact: SeaClouds Licensed under the Apache
	License, Version 2.0 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software distributed
	under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
	OR CONDITIONS OF ANY KIND, either express or implied. See the License for
	the specific language governing permissions and limitations under the License. -->

<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>eu.seaclouds-project</groupId>
		<artifactId>optimizer</artifactId>
		<version>0.8.0-SNAPSHOT</version>
	</parent>
	<artifactId>optimizer-service</artifactId>
	<name>optimizer-service</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<pluginRepositories>
		<pluginRepository>
			<id>maven2-repository.dev.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/glassfish/</url>
		</pluginRepository>
	</pluginRepositories>
	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>${maven-war-plugin.version}</version>
				<configuration>
					<webXml>WebContent/WEB-INF/web.xml</webXml>
				</configuration>
			</plugin>

			<plugin>
				<groupId>eu.seaclouds-project</groupId>
				<artifactId>optimizer-core</artifactId>
				<version>0.8.0-SNAPSHOT</version>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-failsafe-plugin</artifactId>
				<version>${maven-failsafe-plugin.version}</version>
				<executions>
					<execution>
						<goals>
							<goal>integration-test</goal>
							<goal>verify</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>${jetty.version}</version>
				<configuration>

					<webApp>
						<contextPath>/</contextPath>
						<descriptor>${project.basedir}/WebContent/WEB-INF/web.xml</descriptor>
					</webApp>
					<scanIntervalSeconds>10</scanIntervalSeconds>
					<stopKey>STOP</stopKey>
					<stopPort>9999</stopPort>
				</configuration>
				<executions>
					<execution>
						<id>start-jetty</id>
						<phase>pre-integration-test</phase>
						<goals>
							<goal>stop</goal>
							<goal>start</goal>

						</goals>
						<configuration>
							<scanIntervalSeconds>0</scanIntervalSeconds>
						</configuration>
					</execution>
					<execution>
						<id>stop-jetty</id>
						<phase>post-integration-test</phase>
						<goals>
							<goal>stop</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>

	</build>
	<dependencies>

		<dependency>
			<groupId>eu.seaclouds-project</groupId>
			<artifactId>optimizer-core</artifactId>
			<version>0.8.0-SNAPSHOT</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-web-api</artifactId>
			<version>6.0</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>2.0.1</version>
		</dependency>

		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>

		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>2.22.1</version>
		</dependency>

	</dependencies>

	<packaging>war</packaging>
</project>


text:
using System;
using System.Collections.Generic;
using System.IO;
using Codestellation.Galaxy.Domain;
using Codestellation.Galaxy.Domain.Notifications;
using Codestellation.Galaxy.ServiceManager.Events;
using Codestellation.Galaxy.ServiceManager.Operations;
using Codestellation.Quarks.DateAndTime;
using Codestellation.Quarks.IO;
using MediatR;
using Nejdb.Bson;

namespace Codestellation.Galaxy.ServiceManager
{
    public class DeploymentTask
    {
        public readonly DeploymentTaskContext Context;

        private readonly List<IOperation> _operations;

        private OperationResult[] _operationResults;

        public IReadOnlyList<IOperation> Operations => _operations;

        public DeploymentTask Add(IOperation operation)
        {
            _operations.Add(operation);
            return this;
        }

        public ObjectId DeploymentId => Context.DeploymentId;

        public string Name => Context.TaskName;

        public IMediator Mediator => Context.Mediator;

        public DeploymentTask(DeploymentTaskContext context)
        {
            _operations = new List<IOperation>();
            Context = context;
        }

        public void Process()
        {
            try
            {
                Context.BuildLog.WriteLine("Task '{0}' started", Name);
                ExecuteOperations();
                Context.BuildLog.WriteLine("Task '{0}' finished", Name);
            }
            finally
            {
                Context.BuildLog.Flush();
                WriteBuildLogToDisk();
                Context.BuildLog.Dispose();
            }

            var deploymentResult = new OperationResult(Name, _operationResults);
            var anEvent = new DeploymentTaskCompletedEvent(this, deploymentResult);
            Mediator.Send(anEvent).Wait();
        }

        private void WriteBuildLogToDisk()
        {
            FullPath? deployLogFolder =
                Context.NewFolders?.DeployLogsFolder
                ?? Context.Folders?.DeployLogsFolder;

            if (deployLogFolder == null)
            {
                return;
            }

            Folder.EnsureExists((string)deployLogFolder);

            var filename = $"{Context.TaskName}.{Clock.UtcNow.ToLocalTime():yyyy-MM-dd_HH.mm.ss}.log";
            var fullPath = Path.Combine((string)deployLogFolder, filename);

            using (var fileStream = File.Open(fullPath, FileMode.Create, FileAccess.Write))
            {
                Context.LogStream.Position = 0;
                Context.LogStream.CopyTo(fileStream);
                fileStream.Flush();
            }
        }

        private void ExecuteOperations()
        {
            _operationResults = new OperationResult[Operations.Count];
            var failureDetected = false;
            for (var index = 0; index < Operations.Count; index++)
            {
                var operation = Operations[index];

                string operationName = operation.GetType().Name;

                var operationIndex = index + 1;

                Context.BuildLog.WriteLine("Operation '{0}' started. ({1}/{2})", operationName, operationIndex, Operations.Count);

                var operationResult = _operationResults[index] =
                    failureDetected
                        ? new OperationResult(operationName, ResultCode.NotRan) //do not execute operation if any previous failed
                        : Execute(operation);

                WriteResult(operationResult, operationIndex);

                failureDetected = operationResult.ResultCode != ResultCode.Succeed;
                PublishProgress(index, operationResult);
            }
        }

        private OperationResult Execute(IOperation operation)
        {
            var operationName = operation.GetType().Name;
            OperationResult result = null;
            try
            {
                operation.Execute(Context);
                result = new OperationResult(operationName, ResultCode.Succeed);
            }
            catch (Exception ex)
            {
                Context.BuildLog.WriteLine(ex.ToString());
                result = new OperationResult(operationName, ResultCode.Failed, ex.Message);
            }
            return result;
        }

        private void WriteResult(OperationResult operationResult, int operationIndex)
        {
            var operationName = operationResult.OperationName;

            string result = DefineResult(operationResult);

            Context.BuildLog.WriteLine("Operation '{0}' {1}. ({2}/{3})", operationName, result, operationIndex, Operations.Count);
        }

        private string DefineResult(OperationResult operationResult)
        {
            switch (operationResult.ResultCode)
            {
                case ResultCode.Succeed:
                    return "succeed";
                case ResultCode.Failed:
                    return "failed";
                case ResultCode.NotRan:
                    return "skipped";
            }
            throw new InvalidOperationException();
        }

        private void PublishProgress(int index, OperationResult result)
        {
            var notification = new OperationProgressNotification(++index, _operations.Count, result);
            Mediator.Publish(notification);
        }

        public override string ToString()
        {
            return Name;
        }
    }
}


text:
export {}
export interface Option<T> {
	zip1<O extends Array<Option<any>>>(...others: O): Option<[T, ...UnzipOptionArray1<O>]>;

	zip2<O extends Array<Option<any>>>(...others: O): Option<[T, ...UnzipOptionArray2<O>]>;

	zip3<O extends Array<Option<any>>>(...others: O): Option<[T, ...UnzipOptionArray3<O>]>;
}

type UnzipOption<T> = T extends Option<infer V> ? V : never;

/// This doesn't work
type UnzipOptionArray1<T> = { [k in keyof T]: T[k] extends Option<any> ? UnzipOption<T[k]> : never };

/// But these work
type UnzipOptionArray2<T> = { [k in keyof T]: UnzipOption<T[k]> };
type UnzipOptionArray3<T> = { [k in keyof T]: T[k] extends Option<infer V> ? V : never };

declare const opt1: Option<number>;
declare const opt2: Option<string>;
declare const opt3: Option<boolean>;

const zipped1 = opt1.zip1(opt2, opt3);
const zipped2 = opt1.zip2(opt2, opt3);
const zipped3 = opt1.zip3(opt2, opt3);

//// [recursiveTypeAliasWithSpreadConditionalReturnNotCircular.js]
"use strict";
exports.__esModule = true;
var zipped1 = opt1.zip1(opt2, opt3);
var zipped2 = opt1.zip2(opt2, opt3);
var zipped3 = opt1.zip3(opt2, opt3);


text:
package play

import sbt._
import java.lang.{ ProcessBuilder => JProcessBuilder }
import java.io.{ File => JFile, BufferedReader, InputStream, InputStreamReader, OutputStream }
import scala.Console.{ GREEN, RESET }

/**
 * based on https://github.com/typesafehub/sbt-multi-jvm
 */
/**
 * trait PlayJvm {
 *
 * case class RunWith(java: File, scala: ScalaInstance)
 * case class JVMOptions(jvm: Seq[String], scala: (String, Option[String]) => Seq[String])
 * def multiSimpleName(name: String) = name.split("\\.").last
 *
 * def javaCommand(javaHome: Option[File], name: String): File = {
 * val home = javaHome.getOrElse(new File(System.getProperty("java.home")))
 * new File(new File(home, "bin"), name)
 * }
 *
 * def fork(name: String, mainClass: String, args: Option[String], runWith: RunWith, options: JVMOptions, srcDir: JFile, log: Logger) {
 * val logName = "* " + name
 * log.info(if (log.ansiCodesSupported) GREEN + logName + RESET else logName)
 * val process = {
 * val jvmLogger = new JvmLogger("info")
 * val scalaOptions = options.scala(mainClass, args)
 * log.debug("Starting %s for %t" format (name, mainClass))
 * log.debug("  with JVM options: %s" format options.jvm.mkString(" "))
 * startJvm(runWith.java, options.jvm, runWith.scala, scalaOptions, jvmLogger, true)
 * }
 * if (process.exitValue > 0) {
 * log.error("JVM Process failed")
 * sys.error(process.exitValue.toString)
 * }
 *
 * }
 *
 * def startJvm(javaBin: JFile, jvmOptions: Seq[String], si: ScalaInstance, scalaOptions: Seq[String], logger: Logger, connectInput: Boolean) = {
 * forkScala(javaBin, jvmOptions, si.jars, scalaOptions, logger, connectInput)
 * }
 *
 * def forkScala(javaBin: JFile, jvmOptions: Seq[String], scalaJars: Iterable[File], arguments: Seq[String], logger: Logger, connectInput: Boolean) = {
 * val scalaClasspath = scalaJars.map(_.getAbsolutePath).mkString(JFile.pathSeparator)
 * val bootClasspath = "-Xbootclasspath/a:" + scalaClasspath
 * val mainScalaClass = "scala.tools.nsc.MainGenericRunner"
 * val options = jvmOptions ++ Seq(bootClasspath, mainScalaClass) ++ arguments
 * forkJava(javaBin, options, logger, connectInput)
 * }
 *
 * def forkJava(javaBin: JFile, options: Seq[String], logger: Logger, connectInput: Boolean) = {
 * val java = javaBin.toString
 * val command = (java :: options.toList).toArray
 * val builder = new JProcessBuilder(command: _*)
 * Process(builder).run(JvmIO(logger, connectInput))
 * }
 * }
 */
final class JvmLogger(name: Option[String] = None) extends BasicLogger {
  def jvm(message: String) = name.map(n => "[%s] %s" format (n, message)).getOrElse(message)

  def log(level: Level.Value, message: => String) = System.out.synchronized {
    System.out.println(jvm(message))
  }

  def trace(t: => Throwable) = System.out.synchronized {
    val traceLevel = getTrace
    if (traceLevel >= 0) System.out.print(StackTrace.trimmed(t, traceLevel))
  }

  def success(message: => String) = log(Level.Info, message)
  def control(event: ControlEvent.Value, message: => String) = log(Level.Info, message)

  def logAll(events: Seq[LogEvent]) = System.out.synchronized { events.foreach(log) }
}

object JvmIO {
  def apply(log: Logger, connectInput: Boolean) =
    new ProcessIO(input(connectInput), processStream(log, Level.Info), processStream(log, Level.Error), (pb: JProcessBuilder) => false)

  final val BufferSize = 8192

  def processStream(log: Logger, level: Level.Value): InputStream => Unit =
    processStream(line => log.log(level, line))

  def processStream(processLine: String => Unit): InputStream => Unit = in => {
    val reader = new BufferedReader(new InputStreamReader(in))
    def process() {
      val line = reader.readLine()
      if (line != null) {
        processLine(line)
        process()
      }
    }
    process()
  }

  def input(connectInput: Boolean): OutputStream => Unit =
    if (connectInput) connectSystemIn else ignoreOutputStream

  def connectSystemIn(out: OutputStream) = transfer(System.in, out)

  def ignoreOutputStream = (out: OutputStream) => ()

  def transfer(in: InputStream, out: OutputStream): Unit = {
    try {
      val buffer = new Array[Byte](BufferSize)
      def read() {
        val byteCount = in.read(buffer)
        if (Thread.interrupted) throw new InterruptedException
        if (byteCount > 0) {
          out.write(buffer, 0, byteCount)
          out.flush()
          read()
        }
      }
      read()
    } catch {
      case _: InterruptedException => ()
    }
  }
}


text:
var RightJS = (function(window, src) {
  // premassaging the source code, swapping the document reference where needed
  src = src
    // the default document to the current one
    .replace(',document,', ',parent.document,')

    // building the inside types conversion methods
    + 'RightJS.$N=function(v){return new Number(v)};'
    + 'RightJS.$S=function(v){return new String(v)}';

  // building the frame sandbox
  var frame_id = '__rightjs_condom', document = window.document;
  if ('attachEvent' in window) {
    document.write('');
  } else {
    var frame  = document.createElement('iframe');
    frame.name = frame_id;
    frame.style.display = 'none';
    document.documentElement.appendChild(frame);
  }

  // puttin the code into the frame
  var win = window.frames[frame_id];

  if ('execScript' in win) {
    win.execScript(src);
  } else {
    var doc = win.document;
    doc.open();doc.write(''); doc.close();

    var script = document.createElement('script');
    script.text = src;
    doc.body.appendChild(script);
  }

  // transferring the object references from the sandbox into local variable
  var RightJS = win.RightJS;
  RightJS.context = win;
  RightJS.safe    = true;

  // building the access and types conversion proxy
  var proxy = function(value) {
    switch (typeof value) {
      case 'number':   return RightJS.$N(value);
      case 'string':   return RightJS.$S(value);
      case 'function': return RightJS.$ext(value, RightJS.Function.Methods);
      case 'object':
        if (RightJS.isArray(value))
          return RightJS.$A(value);
    }

    return value;
  };

  return RightJS.$ext(proxy, RightJS);

})(window, %{source_code});


text:
using System;

namespace pwiz.Common.SystemUtil
{
    public class MustDispose : IDisposable
    {
        private bool _disposed;
        public bool IsDisposed()
        {
            lock(this)
            {
                return _disposed;
            }
        }
        public virtual void Dispose()
        {
            lock(this)
            {
                _disposed = true;
            }
        }
        public void CheckDisposed()
        {
            if (IsDisposed())
            {
                ThrowObjectDisposed();
            }
        }

        protected void ThrowObjectDisposed()
        {
            throw new ObjectDisposedException(GetType().FullName);
        }

        protected void DisposeMember<T>(ref T member) where T : IDisposable
        {
            T localValue;
            lock(this)
            {
                localValue = member;
                member = default(T);
            }
            if (!ReferenceEquals(null, localValue))
            {
                localValue.Dispose();
            }
        }

        protected T DetachMember<T>(ref T member) where T : IDisposable
        {
            T localValue;
            lock(this)
            {
                localValue = member;
                member = default(T);
            }
            return localValue;
        }
        protected void AttachMember<T>(ref T member, T newValue) where T : IDisposable
        {
            lock(this)
            {
                if (!Equals(member, default(T)))
                {
                    throw new InvalidOperationException("Already attached"); // Not L10N
                }
                member = newValue;
            }
        }
        protected TResult DetachAndReturn<TMember, TResult>(ref TMember member, TMember expectedValue, TResult result) where TMember : IDisposable
        {
            if (!ReferenceEquals(expectedValue, DetachMember(ref member)))
            {
                ThrowObjectDisposed();
            }
            return result;
        }
    }
}


text:
from typing import Iterable, Union

from airflow.operators.branch import BaseBranchOperator
from airflow.utils import timezone
from airflow.utils.context import Context
from airflow.utils.weekday import WeekDay

class BranchDayOfWeekOperator(BaseBranchOperator):
    """
    Branches into one of two lists of tasks depending on the current day.
    For more information on how to use this operator, take a look at the guide:
    :ref:`howto/operator:BranchDayOfWeekOperator`

    :param follow_task_ids_if_true: task id or task ids to follow if criteria met
    :type follow_task_ids_if_true: str or list[str]
    :param follow_task_ids_if_false: task id or task ids to follow if criteria does not met
    :type follow_task_ids_if_false: str or list[str]
    :param week_day: Day of the week to check (full name). Optionally, a set
        of days can also be provided using a set.
        Example values:

            * ``"MONDAY"``,
            * ``{"Saturday", "Sunday"}``
            * ``{WeekDay.TUESDAY}``
            * ``{WeekDay.SATURDAY, WeekDay.SUNDAY}``

    :type week_day: iterable or airflow.utils.weekday.WeekDay
    :param use_task_execution_day: If ``True``, uses task's execution day to compare
        with is_today. Execution Date is Useful for backfilling.
        If ``False``, uses system's day of the week.
    :type use_task_execution_day: bool
    """

    def __init__(
        self,
        *,
        follow_task_ids_if_true: Union[str, Iterable[str]],
        follow_task_ids_if_false: Union[str, Iterable[str]],
        week_day: Union[str, Iterable[str]],
        use_task_execution_day: bool = False,
        **kwargs,
    ) -> None:
        super().__init__(**kwargs)
        self.follow_task_ids_if_true = follow_task_ids_if_true
        self.follow_task_ids_if_false = follow_task_ids_if_false
        self.week_day = week_day
        self.use_task_execution_day = use_task_execution_day
        self._week_day_num = WeekDay.validate_week_day(week_day)

    def choose_branch(self, context: Context) -> Union[str, Iterable[str]]:
        if self.use_task_execution_day:
            now = context["logical_date"]
        else:
            now = timezone.make_naive(timezone.utcnow(), self.dag.timezone)

        if now.isoweekday() in self._week_day_num:
            return self.follow_task_ids_if_true
        return self.follow_task_ids_if_false


text:
<DocInternals>
  <AlwaysLoose></AlwaysLoose>
  <FieldSrcTables></FieldSrcTables>
  <TableViewData>
    <Pos></Pos>
    <CtlInfo>
      <InternalView>
        <Tables>
          <TableViewTableWinSaveInfo>
            <Pos>
              <Left>575</Left>
              <Top>224</Top>
              <Width>212</Width>
              <Height>208</Height>
            </Pos>
            <Caption>Contabilidad</Caption>
          </TableViewTableWinSaveInfo>
        </Tables>
        <BroomPoints></BroomPoints>
        <ConnectionPoints></ConnectionPoints>
        <ZoomFactor>3FF0000000000000</ZoomFactor>
      </InternalView>
      <SourceView></SourceView>
    </CtlInfo>
    <Mode>0</Mode>
  </TableViewData>
  <Bookmarks></Bookmarks>
  <SavedByVersion>12.10.20100.0</SavedByVersion>
  <ForceBackEndMacroExecution>false</ForceBackEndMacroExecution>
  <FieldTags>
    <ScriptBased>
      <FieldTagData>
        <Tag>$hidden</Tag>
        <FieldNames>
          <String>$Field</String>
          <String>$Table</String>
          <String>$Rows</String>
          <String>$Fields</String>
          <String>$FieldNo</String>
          <String>$Info</String>
        </FieldNames>
      </FieldTagData>
      <FieldTagData>
        <Tag>$system</Tag>
        <FieldNames>
          <String>$Field</String>
          <String>$Table</String>
          <String>$Rows</String>
          <String>$Fields</String>
          <String>$FieldNo</String>
          <String>$Info</String>
        </FieldNames>
      </FieldTagData>
      <FieldTagData>
        <Tag>$ascii</Tag>
        <FieldNames>
          <String>$Field</String>
          <String>$Table</String>
          <String>$Rows</String>
          <String>$Fields</String>
          <String>$FieldNo</String>
          <String>$Info</String>
        </FieldNames>
      </FieldTagData>
      <FieldTagData>
        <Tag>$text</Tag>
        <FieldNames>
          <String>$Field</String>
          <String>$Table</String>
          <String>$Rows</String>
          <String>$Fields</String>
          <String>$FieldNo</String>
          <String>$Info</String>
        </FieldNames>
      </FieldTagData>
    </ScriptBased>
    <Interactive></Interactive>
  </FieldTags>
  <FieldComments></FieldComments>
  <TableComments></TableComments>
  <CreatePrjFolder>false</CreatePrjFolder>
  <LinkedTables></LinkedTables>
  <AppObjectEntries></AppObjectEntries>
  <GenericDimensions></GenericDimensions>
  <GenericMeasures></GenericMeasures>
  <GenericBookmarks></GenericBookmarks>
  <ConnectionInfo></ConnectionInfo>
  <GenericDerivedDefinitions></GenericDerivedDefinitions>
  <GenericDerivedFields></GenericDerivedFields>
</DocInternals>


text:
/*
 * File:	start.h
 * Purpose:	Kinetis start up routines.
 *
 * Notes:
 * Modified from original Freescale distribution; removed CPU identify and
 * flash identify prototypes.  4 Apr 14 KEL
 */

#ifndef __START_H__
#define __START_H__

#include "common.h"

// Function prototypes
void start(void);

#endif /*__START_H__*/


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.humegatech</groupId>
  <artifactId>car2gosling</artifactId>
  <packaging>jar</packaging>
  <version>1.2-SNAPSHOT</version>
  <name>car2gosling</name>
  <description>Car2Go API v2.1 client in Java</description>
  <url>https://github.com/eebbesen/car2gosling</url>

  <scm>
    <url>git@github.com:eebbesen/car2gosling.git</url>
  </scm>

  <licenses>
    <license>
      <name>MIT License</name>
      <url>https://opensource.org/licenses/MIT</url>
    </license>
  </licenses>

  <developers>
    <developer>
      <name>Eric Ebbesen</name>
      <email>eebbesen.git@gmail.com</email>
      <organization>Humegatech</organization>
      <organizationUrl>http://humegatech.com</organizationUrl>
    </developer>
  </developers>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.glassfish.jersey</groupId>
        <artifactId>jersey-bom</artifactId>
        <version>${jersey.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.glassfish.jersey.core</groupId>
      <artifactId>jersey-common</artifactId>
      <version>2.11</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.9</version>
      <scope>test</scope>
    </dependency>
    <!-- used by Mule 3.7.0 -->
    <dependency>
      <groupId>org.codehaus.jettison</groupId>
      <artifactId>jettison</artifactId>
      <version>1.3.3</version>
    </dependency>

    <!-- because Mule 3.7.0 CE has this as a core resource that can't be overloaded -->
    <dependency>
      <groupId>javax.ws.rs</groupId>
      <artifactId>javax.ws.rs-api</artifactId>
      <version>2.0</version>
    </dependency>
  </dependencies>

  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
    </repository>
  </distributionManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <inherited>true</inherited>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.sonatype.plugins</groupId>
        <artifactId>nexus-staging-maven-plugin</artifactId>
        <version>1.6.8</version>
        <extensions>true</extensions>
        <configuration>
          <serverId>ossrh</serverId>
          <nexusUrl>https://oss.sonatype.org/</nexusUrl>
          <autoReleaseAfterClose>true</autoReleaseAfterClose>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-gpg-plugin</artifactId>
        <version>1.5</version>
        <executions>
          <execution>
            <id>sign-artifacts</id>
            <phase>verify</phase>
            <goals>
              <goal>sign</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.2.1</version>
        <executions>
          <execution>
            <id>attach-sources</id>
            <goals>
              <goal>jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9.1</version>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <properties>
    <jersey.version>2.11</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>


text:
/**
 * The input form to pick genes and experiments, and run coexpression or differential expression searches. This form has
 * three main parts: a search mode chooser, an experiment (group) searcher, and a gene (group) searcher
 *

 * This supports queries that originate from a URL. Example:
 *
 *

 * /home.html?taxon=1&geneList=ARHGAP42P5,TRAV8-5,OR11H12,RNU6-1239P,OR4K1,POTEG,OR11H13P,DUXAP10,POTEM,
 *

 *
 *
 * @requires SessionBoundExpressionExperimentSetValueObject
 * @requires Gemma.ExperimentSearchAndPreview
 * @requires Gemma.GeneSearchAndPreview
 * @author thea
 *
 */
Gemma.AnalysisResultsSearchForm = Ext
    .extend(
        Ext.FormPanel,
        {
            layout: 'table',
            layoutConfig: {
                columns: 5
            },
            width: 900,
            frame: false,
            border: false,
            bodyBorder: false,
            bodyStyle: "backgroundColor:white",
            defaults: {
                border: false
            },
            ctCls: 'titleBorderBox',

            /**
             * @type {Boolean}
             */
            stateful: false,

            stateEvents: ["beforesearch"],

            /**
             * @type {Boolean}
             */
            eeSetReady: false,

            /**
             * @type {Number}
             */
            taxonId: null,

            /**
             * @type {Boolean}
             */
            defaultIsDiffEx: false,

            /**
             *
             */
            searchbBar: null,

            /**
             * @type {Gemma.ExperimentSearchAndPreview}
             */
            experimentSearchAndPreview: null,

            /**
             * @type {Gemma.GeneSearchAndPreview}
             */
            geneSearchAndPreview: null,

            /**
             * @private
             * @param msg
             * @param e
             * @memberOf Gemma.AnalysisResultsSearchForm
             */
            handleWarning: function (msg, e) {
                if (Ext.get("analysis-results-search-form-messages")) {
                    msg = (msg === "") ? "Error retrieving results" : msg;

                    Ext.DomHelper.overwrite("analysis-results-search-form-messages", {
                        tag: 'img',
                        src: ctxBasePath + '/images/icons/warning.png'
                    });

                    Ext.DomHelper.append("analysis-results-search-form-messages", {
                        tag: 'span',
                        html: "  " + msg
                    });
                } else {
                    this.fireEvent("search_error", msg);
                }
            },

            /**
             * @private
             *
             * @param msg
             * @param e
             */
            handleError: function (msg, e) {
                // console.log( e.stack );

                this.handleWarning(msg);

                if (this.loadMask)
                    this.loadMask.hide();

                this.fireEvent('aftersearch', this, e);
                Ext.Msg.alert("Error", e + "/n" + msg);

            },

            /**
             * @private
             */
            clearError: function () {
                if (Ext.get("analysis-results-search-form-messages")) {
                    Ext.DomHelper.overwrite("analysis-results-search-form-messages", "");
                }
            },

            /**
             * @private
             *
             * @return {boolean}
             */
            wereSelectionsModified: function () {

                if (this.geneSearchAndPreview.getSelectedGeneSetValueObject()
                    && this.geneSearchAndPreview.getSelectedGeneSetValueObject().modified) {
                    return true;
                }

                if (this.experimentSearchAndPreview.getSelectedExpressionExperimentSetValueObject()
                    && this.experimentSearchAndPreview.listModified) {
                    return true;
                }

                return false;
            },

            /**
             *
             * @return {Array}
             */
            getGeneSessionGroupQueries: function () {
                return this.geneSearchAndPreview.queryUsedToGetSessionGroup;
            },

            /**
             *
             * @return {Array}
             */
            getExperimentSessionGroupQueries: function () {
                if (this.experimentSearchAndPreview.getSelectedExpressionExperimentSetValueObject()
                    && this.experimentSearchAndPreview.queryUsedToGetSessionGroup !== null) {
                    return this.experimentSearchAndPreview.queryUsedToGetSessionGroup;
                }
            },

            /**
             * Get selections as geneSetValueObjects (selected single genes will be wrapped as single-member geneSets)
             *
             * @return GeneSetValueObject
             */
            getSelectedGeneSetValueObject: function () {
                var selectedVO = this.geneSearchAndPreview.getSelectedGeneSetValueObject();
                // we allow searches without specifying genes in some cases.

                // if ( !selectedVO ) {
                // throw "No genes selected";
                // }

                if (selectedVO instanceof GeneValueObject) {
                    // this should never happen
                    // console.log( "got a single gene" );
                    var gene = selectedVO;
                    // Why do we do it this way? it would be easier to have selected always be a set in the first place.
                    var singleGeneSet = new SessionBoundGeneSetValueObject();
                    singleGeneSet.id = null;
                    singleGeneSet.geneIds = [gene.id];
                    singleGeneSet.name = gene.officialSymbol;
                    singleGeneSet.description = gene.officialName;
                    singleGeneSet.size = gene.size;
                    singleGeneSet.taxonName = gene.taxonCommonName;
                    singleGeneSet.taxonId = gene.taxonId;
                    singleGeneSet.modified = false;
                    return singleGeneSet;
                }
                return selectedVO;

            },

            /**
             * Get selections as expressionExperimentSetValueObjects (selected single genes will be wrapped as
             * single-member experimentSets)
             *
             * @return ExpressionExperimentSetValueObject
             */
            getSelectedExperimentSetValueObject: function () {
                var selectedVO = this.experimentSearchAndPreview.getSelectedExpressionExperimentSetValueObject();

                // we allow searches without specifying experiments in some cases.
                // if ( selectedVO == null ) {
                // throw "No experiment set was selected";
                // }

                if (selectedVO instanceof ExpressionExperimentValueObject) {
                    // we should not let this happen.
                    // console.log( "got a single experiment " );
                    var ee = selectedVO;
                    var singleExperimentSet = new SessionBoundExpressionExperimentSetValueObject();
                    singleExperimentSet.id = null;
                    singleExperimentSet.expressionExperimentIds = [ee.id];
                    singleExperimentSet.name = ee.shortName;
                    singleExperimentSet.description = ee.name;
                    singleExperimentSet.size = 1;
                    singleExperimentSet.taxonName = ee.taxon;
                    singleExperimentSet.taxonId = ee.taxonId;
                    singleExperimentSet.modified = false;
                    singleExperimentSet.numWithCoexpressionAnalysis = ee.hasCoexpressionAnalysis ? 1 : 0;
                    singleExperimentSet.numWithDifferentialExpressionAnalysis = ee.hasDifferentialExpressionAnalysis ? 1 : 0;
                    return singleExperimentSet;
                }

                return selectedVO;
            },

            /**
             *
             * @private
             *
             */
            runSearch: function () {

                this.searchMethods = new Gemma.AnalysisResultsSearchMethods({
                    taxonId: this.getTaxonId(),
                    taxonName: this.getTaxonName()
                });

                this.relayEvents(this.searchMethods, ['beforesearch']);

                this.searchMethods.on('differential_expression_search_query_ready', function (result, data) {
                    Ext.apply(data, {
                        geneSessionGroupQueries: this.getGeneSessionGroupQueries(),
                        experimentSessionGroupQueries: this.getExperimentSessionGroupQueries(),
                        selectionsModified: this.wereSelectionsModified(),
                        showTutorial: this.runningExampleQuery
                    });
                    this.fireEvent('differential_expression_search_query_ready', this, result, data);
                }, this);

                this.searchMethods.on('coexpression_search_query_ready', function (searchCommand) {
                    this.fireEvent('coexpression_search_query_ready', this, searchCommand, this.runningExampleQuery);
                }, this);

                this.searchMethods.on('warning', function (msg, e) {
                    this.handleWarning(msg, e);
                }, this);

                this.searchMethods.on('error', function (msg, e) {
                    this.handleError(msg, e);
                }, this);

                this.searchMethods.on('clearerror', function () {
                    this.clearError();
                }, this);

                this.searchMethods.on('searchAborted', function () {
                    this.loadMask.hide();
                }, this);

                this.collapsePreviews();
                this.collapseExamples();

                if (!this.loadMask) {
                    this.loadMask = new Ext.LoadMask(this.getEl(), {
                        msg: Gemma.StatusText.Searching.analysisResults,
                        msgCls: 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
                    });
                }

                /*
                 * Key entry point.
                 */
                if (this.coexToggle.pressed) {
                    this.searchMethods.searchCoexpression(this.getSelectedGeneSetValueObject(), this
                        .getSelectedExperimentSetValueObject());
                } else {
                    this.searchMethods.searchDifferentialExpression(this.getSelectedGeneSetValueObject(), this
                        .getSelectedExperimentSetValueObject());
                }
            },

            /**
             * @Override
             */
            initComponent: function () {

                // experiment chooser panels. This panel is just a bit of a wrapper.
                this.experimentSearchAndPreviewPanel = new Ext.Panel({
                    // width: 319,
                    frame: false,
                    bodyStyle: 'background-color:transparent',
                    defaults: {
                        border: false,
                        bodyStyle: 'background-color:transparent'
                    },
                    style: 'padding-bottom: 10px',
                    autoDestroy: true
                });

                // gene chooser panels
                this.geneSearchAndPreviewPanel = new Ext.Panel({
                    // width: 319,
                    frame: false,
                    defaults: {
                        border: false
                    },
                    style: 'padding-bottom: 10px;',
                    autoDestroy: true
                });

                /**
                 * ***** BUTTONS ******
                 */
                this.coexToggle = new Ext.Button({
                    text: "Coexpression",
                    cls: 'highlightToggle',
                    scale: 'medium',
                    width: 150,
                    enableToggle: true,
                    pressed: !this.defaultIsDiffEx,
                    tooltip: 'Look for patterns of coexpression between genes of your choosing, across multiple data sets'
                });
                this.coexToggle.on('click', function () {
                    this.coexToggle.toggle(true);
                    this.diffExToggle.toggle(false);
                    this.fireEvent('modechange', 'coex');
                }, this);

                this.diffExToggle = new Ext.Button({
                    text: "Differential Expression",
                    scale: 'medium',
                    cls: 'highlightToggle',
                    width: 150,
                    enableToggle: true,
                    pressed: this.defaultIsDiffEx,
                    tooltip: 'Look for differential experession of genes of your choosing, across multiple conditions'
                });
                this.diffExToggle.on('click', function () {
                    this.diffExToggle.toggle(true);
                    this.coexToggle.toggle(false);
                    this.fireEvent('modechange', 'diffex');
                }, this);

                this.initializeGeneSearchAndPreview();
                this.initializeExperimentSearchAndPreview();

                this.searchBar = new Ext.Panel({

                    border: false,
                    layout: 'table',
                    layoutConfig: {
                        columns: 5
                    },
                    width: 490,
                    style: 'margin: 0 7px',
                    defaults: {
                        border: false
                    },
                    items: [{
                        html: 'Test for ',
                        style: 'white-space: nowrap;text-align:center;vertical-align:middle;font-size:1.7em;margin-top:7px'
                    }, this.coexToggle, {
                        html: 'or',
                        style: 'white-space: nowrap;text-align:center;vertical-align:middle;font-size:1.7em;margin-top:7px'
                    }, this.diffExToggle, {
                        html: 'of:',
                        style: 'white-space: nowrap;text-align:center;vertical-align:middle;font-size:1.7em;margin-top:7px'
                    }]

                });

                /** ************* TEXT ******************** */

                // little areas in the middle.
                this.theseExperimentsPanel = new Ext.Panel({
                    html: 'these experiments',
                    style: 'text-align:center;font-size:1.4em;',
                    tpl: new Ext.XTemplate('these ',
                        '{taxonCommonName}  experiments '),
                    tplWriteMode: 'overwrite'
                });
                this.theseGenesPanel = new Ext.Panel({
                    html: 'these genes',
                    style: 'text-align:center;font-size:1.4em;',
                    tpl: new Ext.XTemplate('these ',
                        '{taxonCommonName} genes '),
                    tplWriteMode: 'overwrite'
                });

                this.searchExamples = new Gemma.AnalysisResultsSearchExamples({
                    ref: 'searchExamples',
                    defaultIsDiffEx: false
                });

                this.searchExamples.on('startingExample', function () {
                    if (!this.loadMask) {
                        this.loadMask = new Ext.LoadMask(this.getEl(), {
                            msg: Gemma.StatusText.Searching.analysisResults,
                            msgCls: 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
                        });
                    }
                    this.loadMask.show();
                }, this);

                this.searchExamples.on('examplesReady', function (taxonId, geneSetExampleRecord,
                                                                  experimentSetExampleRecord) {
                    this.runExampleQuery(taxonId, geneSetExampleRecord, experimentSetExampleRecord);
                }, this);

                this.diffExToggle.on('toggle', function () {
                    if (this.diffExToggle.pressed) {
                        this.searchExamples.showDiffExExamples();
                    } else {
                        this.searchExamples.showCoexExamples();
                    }
                }, this);
                /** ************* PUT ITEMS IN PANEL ******************** */

                Ext.apply(this, {
                    style: '',
                    items: {
                        xtype: 'fieldset',
                        title: ' ',
                        border: true,
                        searchBar: this.searchBar,
                        listeners: {
                            render: function (c) {
                                // Ext bug workaround
                                var floatType = Ext.isIE ? 'styleFloat' : 'cssFloat';
                                c.header.child('span').applyStyles(floatType + ':left;padding:5px 5px 0 0');
                                this.searchBar.render(c.header, 1);
                                // this.searchBar.wrap.applyStyles(floatType + ':left');
                                c.on('destroy', function () {
                                    this.searchBar.destroy();
                                }, c, {
                                    single: true
                                });
                            }.createDelegate(this)
                        },
                        items: [{
                            layout: 'table', // needs to be table so panel stretches with content growth
                            layoutConfig: {
                                columns: 4
                            },
                            width: 850,
                            border: false,
                            defaults: {
                                border: false,
                                bodyStyle: 'padding: 0px;margin:0px'
                            },
                            items: [{
                                defaults: {
                                    border: false
                                },
                                items: [this.theseGenesPanel, this.geneSearchAndPreviewPanel]
                            }, {
                                html: 'in ',
                                style: 'white-space: nowrap;font-size:1.7em;padding-top: 32px;padding-right:5px;'
                            }, {
                                defaults: {
                                    border: false
                                },
                                items: [this.theseExperimentsPanel, this.experimentSearchAndPreviewPanel]
                            }, {
                                style: 'padding:20 0 0 0px;margin:0px;',
                                items: [{
                                    xtype: 'button',
                                    text: "Go!",
                                    width: 55,
                                    tooltip: 'Run the search',
                                    scale: 'medium',
                                    listeners: {
                                        click: function () {
                                            this.runningExampleQuery = false;
                                            this.runSearch();
                                        }.createDelegate(this, [], false)
                                    }

                                }, {
                                    xtype: 'button',
                                    width: 55,
                                    icon: ctxBasePath + '/images/icons/arrow_refresh_small.png',
                                    style: 'margin-top: 8px',
                                    text: 'Reset',
                                    tooltip: 'Clear all selections and reset the taxon mode ',
                                    handler: this.reset.createDelegate(this)
                                }]
                            }, this.searchExamples]
                        }]
                    }
                });

                Gemma.AnalysisResultsSearchForm.superclass.initComponent.call(this);

                this.on('queryUpdateFromCoexpressionViz', function (geneIds) {
                    this.getEl().unmask();

                    if (this.geneSearchAndPreview.preview) {
                        this.geneSearchAndPreview.preview.selectionEditorWindow.hide();
                    }

                    if (this.experimentSearchAndPreviewPanel.preview) {
                        this.experimentSearchAndPreviewPanel.preview.selectionEditorWindow.hide();
                    }

                    this.geneSearchAndPreview.getGenes(geneIds);

                }, this);

                this.addEvents('beforesearch', 'aftersearch', 'differential_expression_search_query_ready',
                    'coexpression_search_query_ready', 'modechange');

                // for events triggered when this page was reached using parameters encoded in the url.
                this.relayEvents(this.experimentSearchAndPreview.experimentCombo,
                    ['experimentGroupUrlSelectionComplete']);
                this.relayEvents(this.geneSearchAndPreview, ['geneListUrlSelectionComplete']);

                this.on('experimentGroupUrlSelectionComplete', function () {
                    this.experimentGroupUrlSelectionComplete = true;
                    this.initiateSearch();
                }, this);

                this.on('geneListUrlSelectionComplete', function () {
                    this.geneListUrlSelectionComplete = true;
                    this.initiateSearch();
                }, this);

                this.doLayout();

                this.fireEvent('modechange', this.defaultIsDiffEx ? 'diffex' : 'coex');
            },

            /**
             * If the URL used to reach this page provides search parameters, immediately do a search. This was initially
             * put in place to support AspireDB queries.
             */
            checkUrlParams: function () {
                var urlparams = Ext.urlDecode(location.search.substring(1));

                // if these parameters are in the URL then do a search.
                if (urlparams.geneList && urlparams.taxon) {

                    this.geneSearchAndPreview.getGenesFromUrl();

                    if (urlparams.type) {

                        if (urlparams.type == 'diff') {
                            this.coexToggle.toggle(false);
                            this.diffExToggle.toggle(true);
                        } else {
                            this.coexToggle.toggle(true);
                            this.diffExToggle.toggle(false);
                        }

                    } else {
                        // backwards compatibility; assume coexpression
                        this.coexToggle.toggle(true);
                        this.diffExToggle.toggle(false);

                    }
                }
            },

            /**
             * Start search if everything is ready.
             *
             * @private
             */
            initiateSearch: function () {
                if (this.experimentGroupUrlSelectionComplete && this.geneListUrlSelectionComplete) {
                    this.runSearch();
                }
            },

            /**
             * Go back to initial state - including resetting the taxon. Behaviour is different if user clicks on reset for
             * just genes or just experiments.
             *
             * @private
             */
            reset: function () {
                // reset experiment and gene choosers
                this.geneSearchAndPreview.reset();
                this.experimentSearchAndPreview.reset();

                // reset taxon
                this.setTaxonId(null);

                // reset taxon id and titles
                Ext.DomHelper.overwrite(this.theseGenesPanel.body, {
                    cn: 'these genes'
                });
                Ext.DomHelper.overwrite(this.theseExperimentsPanel.body, {
                    cn: 'these experiments'
                });
            },

            getTaxonId: function () {
                return this.taxonId;
            },

            setTaxonId: function (taxonId) {
                this.taxonId = taxonId;
                this.geneSearchAndPreview.geneCombo.setTaxonId(taxonId);
                this.experimentSearchAndPreview.taxonId = taxonId;
                this.experimentSearchAndPreview.experimentCombo.setTaxonId(taxonId);
            },

            getTaxonName: function () {
                return this.taxonName;
            },

            setTaxonName: function (taxonName) {
                this.taxonName = taxonName;
                this.theseExperimentsPanel.update({
                    taxonCommonName: taxonName
                });
                this.theseGenesPanel.update({
                    taxonCommonName: taxonName
                });
            },

            /**
             * Check if the taxon needs to be changed, and if so, update the geneAndGroupCombo and reset the gene preivew
             *
             * @param taxonId
             *           {Number}
             *
             * @param taxonName
             *           {String}
             *
             */
            taxonChanged: function (taxonId, taxonName) {

                // if the 'new' taxon is the same as the 'old' taxon for the experiment
                // combo, don't do anything
                if (taxonId && this.getTaxonId() && (this.getTaxonId() === taxonId)) {
                    return;
                }

                // if the 'new' and 'old' taxa are different, reset the gene preview and
                // filter the geneCombo
                else if (taxonId) {
                    this.setTaxonId(taxonId);
                    if (taxonName) {
                        this.setTaxonName(taxonName);
                    }
                }

                // this.fireEvent( "taxonchanged", taxonId );
                Gemma.EVENTBUS.fireEvent('taxonchanged', taxonId);
            },

            // collapse all gene and experiment previews
            collapsePreviews: function () {
                this.collapseGenePreviews();
                this.collapseExperimentPreviews();
            },

            collapseGenePreviews: function () {
                this.geneSearchAndPreview.collapsePreview(false);
            },

            collapseExperimentPreviews: function () {
                this.experimentSearchAndPreview.collapsePreview(false);
            },

            initializeGeneSearchAndPreview: function () {
                this.geneSearchAndPreview = new Gemma.GeneSearchAndPreview({
                    searchForm: this,
                    taxonId: this.getTaxonId(),
                    style: 'padding-top:10px;'
                });

                this.geneSearchAndPreviewPanel.add(this.geneSearchAndPreview);
                if (typeof Ext.getCmp('geneChooser' + (this.geneChooserIndex - 1) + 'Button') !== 'undefined') {
                    Ext.getCmp('geneChooser' + (this.geneChooserIndex - 1) + 'Button').show().setIcon(
                        ctxBasePath + '/images/icons/delete.png').setTooltip('Remove this gene or group from your search')
                        .setHandler(
                            this.removeGeneChooser.createDelegate(this, ['geneChooserPanel' + (this.geneChooserIndex - 1)],
                                false));
                }

                this.geneSearchAndPreviewPanel.doLayout();
            },

            /**
             * Set up the {Gemma.ExperimentSearchAndPreview}
             *
             * @memberOf Gemma.AnalysisResultsSearchForm
             */
            initializeExperimentSearchAndPreview: function () {
                this.experimentSearchAndPreview = new Gemma.ExperimentSearchAndPreview({
                    searchForm: this,
                    taxonId: this.getTaxonId(),
                    style: 'padding-top:10px;',
                    mode: this.diffExToggle.pressed ? 'diffex' : 'coex'
                });

                this.experimentSearchAndPreviewPanel.add(this.experimentSearchAndPreview);
                this.experimentSearchAndPreviewPanel.doLayout();
            },

            /**
             * hide the example queries
             */
            collapseExamples: function () {
                this.searchExamples.collapseExamples(false);
            },

            /**
             * For example queries: set the experiment chooser to have chosen a set and show its preview
             *
             * @private
             * @param record
             */
            setExampleExperimentSet: function (record) {

                var chooser = this.experimentSearchAndPreview;
                chooser.setSelectedExpressionExperimentSetValueObject(record.data);

                var eeCombo = chooser.experimentCombo;

                // insert record into combo's store
                eeCombo.getStore().insert(0, record);
                eeCombo.selectedIndex = 0;

                // tell gene combo the group was selected
                eeCombo.fireEvent('select', eeCombo, record, 0);
            },

            /**
             * For example queries: set the gene chooser to have chosen a go group and show its preview
             *
             * @private
             * @param record
             *
             */
            setExampleGeneSet: function (record) {

                // get the chooser to inject
                var chooser = this.geneSearchAndPreview;

                chooser.setSelectedGeneSetValueObject(record.data);

                // get the chooser's gene combo
                var geneCombo = chooser.geneCombo;
                geneCombo.getStore().insert(0, record);

                // tell gene combo the GO group was selected
                geneCombo.fireEvent('select', geneCombo, record, 0);

            },

            /**
             *
             * @param taxonId
             *           {Number}
             * @param geneSetRecord
             * @param experimentSetRecord
             */
            runExampleQuery: function (taxonId, geneSetRecord, experimentSetRecord) {
                if (!geneSetRecord || !experimentSetRecord) {
                    throw "Need gene set and experiment set";
                }

                // taxon needs to be set before gene group is chosen because otherwise there will be >1 choice provided
                this.setTaxonId(taxonId);

                this.setExampleExperimentSet(experimentSetRecord);
                this.setExampleGeneSet(geneSetRecord);

                this.runningExampleQuery = true;
                this.runSearch();
            }
        });

Ext.reg('analysisResultsSearchForm', Gemma.AnalysisResultsSearchForm);


text:
@implementation NSObject (FXPageControl)

- (UIColor *)pageControl:(FXPageControl *)pageControl colorForDotAtIndex:(NSInteger)index { return nil; }
- (UIColor *)pageControl:(FXPageControl *)pageControl selectedColorForDotAtIndex:(NSInteger)index { return nil; }
- (UIImage *)pageControl:(FXPageControl *)pageControl imageForDotAtIndex:(NSInteger)index { return nil; }
- (UIImage *)pageControl:(FXPageControl *)pageControl selectedImageForDotAtIndex:(NSInteger)index { return nil; }

@end

@implementation FXPageControl

- (void)setUp
{
    //needs redrawing if bounds change
    //this isn't a private method, but this approach avoids having to import <QuartzCore>
    [self setValue:@YES forKeyPath:@"layer.needsDisplayOnBoundsChange"];

	//set defaults
	_dotSpacing = 10.0f;
	_dotSize = 6.0f;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
	{
		[self setUp];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
	if ((self = [super initWithCoder:aDecoder]))
	{
		[self setUp];
	}
	return self;
}

- (CGSize)sizeForNumberOfPages:(NSInteger)pageCount
{
    CGFloat width = _dotSize + (_dotSize + _dotSpacing) * (_numberOfPages - 1);
    return CGSizeMake(width, fmaxf(_dotSize, 36.0f));
}

- (void)updateCurrentPageDisplay
{
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
	if (_numberOfPages > 1 || !_hidesForSinglePage)
	{
		CGFloat width = [self sizeForNumberOfPages:_numberOfPages].width;
		CGFloat offset = (self.frame.size.width - width) / 2.0f;

		for (int i = 0; i < _numberOfPages; i++)
		{
			UIImage *dotImage = nil;
            UIColor *dotColor = nil;
			if (i == _currentPage)
			{
				[_selectedDotColor setFill];
				dotImage = [_delegate pageControl:self selectedImageForDotAtIndex:i] ?: _selectedDotImage;
				dotColor = [_delegate pageControl:self selectedColorForDotAtIndex:i] ?: _selectedDotColor ?: [UIColor blackColor];
			}
			else
			{
				[_dotColor setFill];
                dotImage = [_delegate pageControl:self imageForDotAtIndex:i] ?: _dotImage;
				dotColor = [_delegate pageControl:self colorForDotAtIndex:i] ?: _dotColor;
                if (!dotColor)
                {
                    //fall back to selected dot color with reduced alpha
                    dotColor = [_delegate pageControl:self selectedColorForDotAtIndex:i] ?: _selectedDotColor ?: [UIColor blackColor];
                    dotColor = [dotColor colorWithAlphaComponent:0.25f];
                }
			}
			if (dotImage)
			{
				[dotImage drawInRect:CGRectMake(offset + (_dotSize + _dotSpacing) * i + (_dotSize - dotImage.size.width) / 2.0f, (self.frame.size.height / 2.0f) - (dotImage.size.height / 2.0f), dotImage.size.width, dotImage.size.height)];
			}
			else
			{
                [dotColor setFill];
                CGContextRef context = UIGraphicsGetCurrentContext();
				CGContextFillEllipseInRect(context, CGRectMake(offset + (_dotSize + _dotSpacing) * i, (self.frame.size.height / 2.0f) - (_dotSize / 2.0f), _dotSize, _dotSize));
			}
		}
	}
}

- (NSInteger)clampedPageValue:(NSInteger)page
{
	if (_wrapEnabled)
    {
        return _numberOfPages? (page + _numberOfPages) % _numberOfPages: 0;
    }
    else
    {
        return MIN(MAX(0, page), _numberOfPages - 1);
    }
}

- (void)setDotColor:(UIColor *)dotColor
{
	if (_dotColor != dotColor)
	{
		_dotColor = dotColor;
		[self setNeedsDisplay];
	}
}

- (void)setSelectedDotColor:(UIColor *)dotColor
{
	if (_selectedDotColor != dotColor)
	{
		_selectedDotColor = dotColor;
		[self setNeedsDisplay];
	}
}

- (void)setDotSpacing:(CGFloat)dotSpacing
{
	if (_dotSpacing != dotSpacing)
	{
		_dotSpacing = dotSpacing;
		[self setNeedsDisplay];
	}
}

- (void)setDotSize:(CGFloat)dotSize
{
	if (_dotSize != dotSize)
	{
		_dotSize = dotSize;
		[self setNeedsDisplay];
	}
}

- (void)setDelegate:(id<FXPageControlDelegate>)delegate
{
	if (_delegate != delegate)
	{
		_delegate = delegate;
		[self setNeedsDisplay];
	}
}

- (void)setCurrentPage:(NSInteger)page
{
    _currentPage = [self clampedPageValue:page];
    [self setNeedsDisplay];
}

- (void)setNumberOfPages:(NSInteger)pages
{
	if (_numberOfPages != pages)
    {
        _numberOfPages = pages;
        if (_currentPage >= pages)
        {
            _currentPage = pages - 1;
        }
        [self setNeedsDisplay];
    }
}

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint point = [touch locationInView:self];
	_currentPage = [self clampedPageValue:_currentPage + ((point.x > self.frame.size.width / 2.0f)? 1: -1)];
    if (!_defersCurrentPageDisplay)
    {
        [self setNeedsDisplay];
    }
	[self sendActionsForControlEvents:UIControlEventValueChanged];
	return [super beginTrackingWithTouch:touch withEvent:event];
}

- (CGSize)sizeThatFits:(CGSize)size
{
    return CGSizeMake(self.superview.bounds.size.width, [self sizeForNumberOfPages:1].height);
}

@end


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.editor.views.tree.actions;

import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;

import com.archimatetool.editor.actions.ArchiActionFactory;
import com.archimatetool.editor.views.tree.commands.DuplicateCommandHandler;

/**
 * Duplicate Action
 *
 * @author Phillip Beauvoir
 */
public class DuplicateAction extends ViewerAction {

    public DuplicateAction(ISelectionProvider selectionProvider) {
        super(selectionProvider);
        setText(Messages.DuplicateAction_0);

        setActionDefinitionId(ArchiActionFactory.DUPLICATE.getCommandId()); // Ensures key binding is displayed
        setEnabled(false);
    }

    @Override
    public void run() {
        IStructuredSelection selection = getSelection();
        if(selection == null || selection.isEmpty()) {
            return;
        }

        DuplicateCommandHandler cmdHandler = new DuplicateCommandHandler(selection.toArray());
        cmdHandler.duplicate();
    }

    @Override
    public void update() {
        setEnabled(DuplicateCommandHandler.canDuplicate(getSelection()));
    }

}


text:
CEyebrow::CEyebrow(std::shared_ptr<CTask> task, Float2 pos, int page, Float2 parts_pos) :
CParts(task, pos, parts_pos, Float2(420 / 2.5, 640 / 2.5), utility::GetId<CEyebrow>(), page)
{
}
void CEyebrow::PartsDraw()
{
	TextureAsset(CResource::GetInstance().GetEyebrow(id)).resize(size * 2).draw(pos + parts_pos);
}


text:
package com.graphhopper.routing.util.parsers;

import com.graphhopper.reader.ReaderWay;
import com.graphhopper.routing.ev.Lanes;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.storage.IntsRef;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class OSMLanesParserTest {

    private OSMLanesParser parser;
    private EncodingManager em;

    @BeforeEach
    void setup() {
        parser = new OSMLanesParser();
        em = new EncodingManager.Builder().add(parser).build();
    }

    @Test
    void basic() {
        ReaderWay readerWay = new ReaderWay(1);
        IntsRef intsRef = em.createEdgeFlags();
        readerWay.setTag("lanes", "4");
        parser.handleWayTags(intsRef, readerWay, false, em.createRelationFlags());
        Assertions.assertEquals(4, em.getIntEncodedValue(Lanes.KEY).getInt(false, intsRef));
    }

    @Test
    void notTagged() {
        ReaderWay readerWay = new ReaderWay(1);
        IntsRef intsRef = em.createEdgeFlags();
        parser.handleWayTags(intsRef, readerWay, false, em.createRelationFlags());
        Assertions.assertEquals(1, em.getIntEncodedValue(Lanes.KEY).getInt(false, intsRef));
    }

}


text:
#pragma once

#include <string>
#include <mraa/aio.h>
#include <mraa/gpio.h>

#define MAX_BIT_PER_BLOCK     16
#define CMDMODE               0x0000
#define BIT_HIGH              0x00ff
#define BIT_LOW               0x0000

#define HIGH                  1
#define LOW                   0

namespace upm {

/**
 * @brief my9221 led bar library
 * @defgroup my9221 libupm-9221
 */

/**
 * @brief C++ API for MY9221 led bar module
 *
 * This file defines the MY9221 C++ interface for libmy9221
 *
 * @ingroup my9221 gpio
 * @snippet my9221-ledbar.cxx Interesting
 * @snippet my9221-updown.cxx Interesting
 */
class MY9221 {
    public:
         /**
         * Instanciates a MY9221 object
         *
         * @param di data pin
         * @param dcki clock pin
         */
        MY9221 (uint8_t di, uint8_t dcki);

        /**
         * MY9221 object destructor
         */
        ~MY9221 ();

        /**
         * Set the level bar
         *
         * @param level selected level for the bar (1 - 10)
         * @param direction up or down, true is up and is the default
         */
        mraa_result_t setBarLevel (uint8_t level, bool direction=true);

        /**
         * Return name of the component
         */
        std::string name()
        {
            return m_name;
        }
    private:
        mraa_result_t lockData ();
        mraa_result_t send16bitBlock (short data);

        std::string m_name;
        mraa_gpio_context m_clkPinCtx;
        mraa_gpio_context m_dataPinCtx;
};

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Write your site description here. It will be used as your sites meta description as well!">
    <meta name="author" content="Tianxiang Gao">

    <title>Tianxiang Gao - Tianxiang's Blog</title>

    <link rel="stylesheet" href="/blogs/css/bootstrap.css">
    <link rel="stylesheet" href="/blogs/css/style.css">

    <link rel="stylesheet" href="/blogs/css/clean-blog.css">
    <link rel="stylesheet" href="/blogs/css/main.css">

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

            </button>

Tianxiang Gao

Home

About

News

Contact

              Blogs

Archive

Categories

Tags

Tianxiang Gao

                    There is always a better way.

            Basic Concept of Convex Optimization

            KKT condition and Lagrange dual.

Posted by Tianxiang Gao on April 14, 2015

            Suport vector machine #2 - Maximal margin classifier

            Suport vector machine is an extention of a simple and intuitive classifier called the maximal margin classifier

Posted by Tianxiang Gao on April 13, 2015

            Suport vector machine #1 - Hyperplane and margin

            Hyperplane and margin are the foundation for maximal margin classifiers and suppor vector machines.

Posted by Tianxiang Gao on April 12, 2015

            Man must explore, and this is exploration at its greatest

            Problems look mighty small from 150 miles up

Posted by Start Bootstrap on September 24, 2014

            I believe every human has a finite number of heartbeats. I don't intend to waste any of mine.

Posted by Start Bootstrap on September 18, 2014

        Older Posts →

© 2014- Tianxiang Gao | Hosted by GitHub & Powered by Jekyll.


text:
package org.pitest.mutationtest.execute;

import org.pitest.testapi.MetaData;

public class TimingMetaData implements MetaData {

  private final long expectedTime;

  public TimingMetaData(final long expectedTime) {
    this.expectedTime = expectedTime;
  }

  public long getExpectedTime() {
    return this.expectedTime;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = (prime * result)
        + (int) (this.expectedTime ^ (this.expectedTime >>> 32));
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final TimingMetaData other = (TimingMetaData) obj;
    if (this.expectedTime != other.expectedTime) {
      return false;
    }
    return true;
  }

}


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

#ifndef UI_CIRCLE_H
#define UI_CIRCLE_H

#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QTextEdit>

QT_BEGIN_NAMESPACE

class Ui_Circle
{
public:
    QDialogButtonBox *buttonBox;
    QTextEdit *textEdit;
    QLabel *label;
    QTextEdit *textEdit_2;
    QTextEdit *textEdit_3;
    QLabel *label_2;
    QLabel *label_3;

    void setupUi(QDialog *Circle)
    {
        if (Circle->objectName().isEmpty())
            Circle->setObjectName(QStringLiteral("Circle"));
        Circle->resize(168, 130);
        buttonBox = new QDialogButtonBox(Circle);
        buttonBox->setObjectName(QStringLiteral("buttonBox"));
        buttonBox->setGeometry(QRect(0, 90, 161, 32));
        buttonBox->setOrientation(Qt::Horizontal);
        buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
        textEdit = new QTextEdit(Circle);
        textEdit->setObjectName(QStringLiteral("textEdit"));
        textEdit->setGeometry(QRect(87, 8, 41, 31));
        label = new QLabel(Circle);
        label->setObjectName(QStringLiteral("label"));
        label->setGeometry(QRect(40, 10, 51, 20));
        label->setTextFormat(Qt::AutoText);
        textEdit_2 = new QTextEdit(Circle);
        textEdit_2->setObjectName(QStringLiteral("textEdit_2"));
        textEdit_2->setGeometry(QRect(30, 50, 41, 31));
        textEdit_3 = new QTextEdit(Circle);
        textEdit_3->setObjectName(QStringLiteral("textEdit_3"));
        textEdit_3->setGeometry(QRect(100, 50, 41, 31));
        label_2 = new QLabel(Circle);
        label_2->setObjectName(QStringLiteral("label_2"));
        label_2->setGeometry(QRect(10, 60, 21, 16));
        label_3 = new QLabel(Circle);
        label_3->setObjectName(QStringLiteral("label_3"));
        label_3->setGeometry(QRect(80, 60, 21, 16));

        retranslateUi(Circle);
        QObject::connect(buttonBox, SIGNAL(accepted()), Circle, SLOT(accept()));
        QObject::connect(buttonBox, SIGNAL(rejected()), Circle, SLOT(reject()));

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

    void retranslateUi(QDialog *Circle)
    {
        Circle->setWindowTitle(QApplication::translate("Circle", "Dialog", 0));
        label->setText(QApplication::translate("Circle", "radius", 0));
        label_2->setText(QApplication::translate("Circle", "x", 0));
        label_3->setText(QApplication::translate("Circle", "y", 0));
    } // retranslateUi

};

namespace Ui {
    class Circle: public Ui_Circle {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_CIRCLE_H


text:
@interface LSPEmotionPopView()

@property (weak, nonatomic) IBOutlet LSPEmotionButton *emotionBtn;
@end
@implementation LSPEmotionPopView

+ (instancetype)popView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"LSPEmotionPopView" owner:nil options:nil] lastObject];
}

- (void)showFromButton:(LSPEmotionButton *)button
{

    if(button == nil) return;

    self.emotionBtn.emotion = button.emotion;

    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [window addSubview:self];
    CGRect pageFrame = [button convertRect:button.bounds toView:nil];

    self.y = CGRectGetMidY(pageFrame) - self.height;
    self.centerX = CGRectGetMidX(pageFrame);

}
@end