text:
package tests.api.javax.net.ssl;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.security.Principal;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

import org.apache.harmony.security.tests.support.cert.TestUtils;

import junit.framework.TestCase;

/**
 * Tests for HttpsURLConnection class constructors and methods.
 *
 */
public class HttpsURLConnectionTest extends TestCase {

    /**
     * javax.net.ssl.HttpsURLConnection#HttpsURLConnection(java_net_URL)
     */
    public final void test_Constructor() throws Exception {
        new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
        new MyHttpsURLConnection(null);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getCipherSuite()
     */
    public final void test_getCipherSuite() throws Exception {
        URL url = new URL("https://localhost:55555");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        try {
            connection.getCipherSuite();
            fail("IllegalStateException wasn't thrown");
        } catch (IllegalStateException expected) {
        }

        HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
        assertEquals("CipherSuite", con.getCipherSuite());
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getLocalCertificates()
     */
    public final void test_getLocalCertificates() throws Exception {
        URL url = new URL("https://localhost:55555");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        try {
            connection.getLocalCertificates();
            fail("IllegalStateException wasn't thrown");
        } catch (IllegalStateException expected) {
        }

        HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
        assertNull(con.getLocalCertificates());
        con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
        Certificate[] cert = con.getLocalCertificates();
        assertNotNull(cert);
        assertEquals(1, cert.length);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getDefaultHostnameVerifier()
     */
    public final void test_getDefaultHostnameVerifier() {
        HostnameVerifier verifyer =
            HttpsURLConnection.getDefaultHostnameVerifier();
        assertNotNull("Default hostname verifyer is null", verifyer);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getDefaultSSLSocketFactory()
     */
    public final void test_getDefaultSSLSocketFactory() {
        SSLSocketFactory sf = HttpsURLConnection.getDefaultSSLSocketFactory();
        if (!sf.equals(SSLSocketFactory.getDefault())) {
            fail("incorrect DefaultSSLSocketFactory");
        }
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getHostnameVerifier()
     */
    public final void test_getHostnameVerifier()
        throws Exception {
        HttpsURLConnection con = new MyHttpsURLConnection(
                new URL("https://www.fortify.net/"));
        HostnameVerifier verifyer = con.getHostnameVerifier();
        assertNotNull("Hostname verifyer is null", verifyer);
        assertEquals("Incorrect value of hostname verirfyer",
                HttpsURLConnection.getDefaultHostnameVerifier(), verifyer);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getLocalPrincipal()
     */
    public final void test_getLocalPrincipal() throws Exception {
        URL url = new URL("https://localhost:55555");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        try {
            connection.getLocalPrincipal();
            fail("IllegalStateException wasn't thrown");
        } catch (IllegalStateException expected) {
        }

        HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
        assertNull(con.getLocalPrincipal());
        con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
        assertNotNull("Local principal is null", con.getLocalPrincipal());
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getPeerPrincipal()
     */
    public final void test_getPeerPrincipal() throws Exception {
        URL url = new URL("https://localhost:55555");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        try {
            connection.getPeerPrincipal();
            fail("IllegalStateException wasn't thrown");
        } catch (IllegalStateException expected) {
        }
        HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
        try {
            Principal p = con.getPeerPrincipal();
            fail("SSLPeerUnverifiedException wasn't thrown");
        } catch (SSLPeerUnverifiedException expected) {
        }

        con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
        Principal p = con.getPeerPrincipal();
        assertNotNull(p);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getServerCertificates()
     */
    public final void test_getServerCertificates() throws Exception {
        URL url = new URL("https://localhost:55555");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        try {
            connection.getServerCertificates();
            fail("IllegalStateException wasn't thrown");
        } catch (IllegalStateException expected) {
        }

        HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
        try {
            con.getServerCertificates();
            fail("SSLPeerUnverifiedException wasn't thrown");
        } catch (SSLPeerUnverifiedException expected) {
        }

        con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
        Certificate[] cert = con.getServerCertificates();
        assertNotNull(cert);
        assertEquals(1, cert.length);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#getSSLSocketFactory()
     */
    public final void test_getSSLSocketFactory() {
        HttpsURLConnection con = new MyHttpsURLConnection(null);
        SSLSocketFactory sf = con.getSSLSocketFactory();
        if (!sf.equals(SSLSocketFactory.getDefault())) {
            fail("incorrect DefaultSSLSocketFactory");
        }
    }

    /**
     * javax.net.ssl.HttpsURLConnection#setDefaultHostnameVerifier()
     */
    public final void test_setDefaultHostnameVerifier() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(null);
            fail("No expected IllegalArgumentException");
        } catch (IllegalArgumentException expected) {
        }
        HostnameVerifier def = HttpsURLConnection.getDefaultHostnameVerifier();
        try {
            myHostnameVerifier hnv = new myHostnameVerifier();
            HttpsURLConnection.setDefaultHostnameVerifier(hnv);
            assertEquals(hnv, HttpsURLConnection.getDefaultHostnameVerifier());
        } finally {
            HttpsURLConnection.setDefaultHostnameVerifier(def);
        }
    }

    /**
     * javax.net.ssl.HttpsURLConnection#setHostnameVerifier()
     */
    public final void test_setHostnameVerifier() {
        HttpsURLConnection con = new MyHttpsURLConnection(null);
        try {
            con.setHostnameVerifier(null);
            fail("No expected IllegalArgumentException");
        } catch (IllegalArgumentException expected) {
        }
        myHostnameVerifier hnv = new myHostnameVerifier();
        con.setHostnameVerifier(hnv);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#setDefaultSSLSocketFactory()
     */
    public final void test_setDefaultSSLSocketFactory() {
        try {
            HttpsURLConnection.setDefaultSSLSocketFactory(null);
            fail("No expected IllegalArgumentException");
        } catch (IllegalArgumentException expected) {
        }
        SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
                .getDefault();
        HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
    }

    /**
     * javax.net.ssl.HttpsURLConnection#setSSLSocketFactory()
     */
    public final void test_setSSLSocketFactory() {
        HttpsURLConnection con = new MyHttpsURLConnection(null);
        try {
            con.setSSLSocketFactory(null);
            fail("No expected IllegalArgumentException");
        } catch (IllegalArgumentException expected) {
        }
        SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
                .getDefault();
        con.setSSLSocketFactory(ssf);
    }
}

class MyHttpsURLConnection extends javax.net.ssl.HttpsURLConnection {

    private String typeDone;

    public MyHttpsURLConnection(URL url) {
        super(url);
    }

    public MyHttpsURLConnection(URL url, String type) {
        super(url);
        typeDone = type;
    }

    /*
     * @see javax.net.ssl.HttpsURLConnection#getCipherSuite()
     */
    public String getCipherSuite() {
        return "CipherSuite";
    }

    /*
     * @see javax.net.ssl.HttpsURLConnection#getLocalCertificates()
     */
    public Certificate[] getLocalCertificates() {
        try {
            CertificateFactory cf = CertificateFactory.getInstance(typeDone);
            byte[] barr = TestUtils.getX509Certificate_v1();
            ByteArrayInputStream bis = new ByteArrayInputStream(barr);
            Certificate cert = cf.generateCertificate(bis);
            return new Certificate[] { cert };
        } catch (CertificateException se) {
            return null;
        }
    }

    /*
     * @see javax.net.ssl.HttpsURLConnection#getServerCertificates()
     */
    public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
        try {
            CertificateFactory cf = CertificateFactory.getInstance(typeDone);
            byte[] barr = TestUtils.getX509Certificate_v3();
            ByteArrayInputStream bis = new ByteArrayInputStream(barr);
            Certificate cert = cf.generateCertificate(bis);
            return new Certificate[] { cert };
        } catch (CertificateException se) {
            throw new SSLPeerUnverifiedException("No server's end-entity certificate");
        }
    }

    /*
     * @see java.net.HttpURLConnection#disconnect()
     */
    public void disconnect() {
    }

    /*
     * @see java.net.HttpURLConnection#usingProxy()
     */
    public boolean usingProxy() {
        return false;
    }

    public void connect() {
    }

}

class myHostnameVerifier implements HostnameVerifier {

    myHostnameVerifier() {
    }

    public boolean verify(String hostname, SSLSession session) {
        if (hostname == session.getPeerHost()) {
            return true;
        } else return false;
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.Text;

namespace WcfService
{
    public class HttpSoap12WSA2004TestServiceHostFactory : ServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            HttpSoap12WSA2004TestServiceHost serviceHost = new HttpSoap12WSA2004TestServiceHost(serviceType, baseAddresses);
            return serviceHost;
        }
    }
    public class HttpSoap12WSA2004TestServiceHost : TestServiceHostBase<IWcfService>
    {
        protected override string Address { get { return "http-soap12WSA2004"; } }

        protected override Binding GetBinding()
        {
            return new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressingAugust2004, Encoding.UTF8), new HttpTransportBindingElement());
        }

        public HttpSoap12WSA2004TestServiceHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
description: Learn how to install Docker Universal Control Plane on production
keywords: Universal Control Plane, UCP, install
redirect_from:
- /ucp/production-install/
- /ucp/installation/install-production/
title: Install UCP for production
---

Docker Universal Control Plane (UCP) is a containerized application that can be
installed on-premises or on a cloud infrastructure.

If you're installing Docker Datacenter on Azure, [follow this guide](https://success.docker.com/?cid=ddc-on-azure).

## Step 1: Validate the system requirements

The first step in installing UCP, is ensuring your
infrastructure has all the [requirements UCP needs to run](system-requirements.md).

## Step 2: Install CS Docker on all nodes

UCP is a containerized application that requires CS Docker Engine 1.10.0 or
above to run. It is recommended to install the exact same version of the
CS Docker Engine on all nodes.

So on each host that you want to be part of the UCP cluster,
[install CS Docker Engine 1.10.0 or above](/docker-trusted-registry/cs-engine/install/).
In the case where you are creating a VM template with CS Engine already
installed, make sure that `/etc/docker/key.json` is not included in the image.
You can do this by simply removing `/etc/docker/key.json`. You can then restart
Docker on each node, which will generate new `/etc/docker/key.json` files.

## Step 3: Customize named volumes

Docker UCP uses [named volumes](../architecture.md) to persist data. If you want
to customize the volume drivers and flags of these volumes, you can create the
volumes before installing UCP.

If the volumes don't exist, when installing UCP they are created with the
default volume driver and flags.

## Step 4: Customize the server certificates

The UCP cluster uses TLS to secure all communications. Two Certificate
Authorities (CA) are used for this:

* Cluster root CA: generates certificates for new nodes joining the cluster and
admin user bundles.
* Client root CA: generates non-admin user bundles.

You can customize UCP to use certificates signed by an external Certificate
Authority. These certificates are used instead of the ones generated by the
client root CA. That way you can use a certificate from a CA that your
browsers and client tools already trust.

If you want to use your own certificates:

1. Log into the host where you intend to instal UCP.

2. Create a volume with the name `ucp-controller-server-certs`.

3. Add the following files to `/var/lib/docker/volumes/ucp-controller-server-certs/_data/`:

    | File     | Description                                                                       |
    |:---------|:----------------------------------------------------------------------------------|
    | ca.pem   | Your root CA certificate.                                                         |
    | cert.pem | Your signed UCP controller certificate followed by any intermediate certificates. |
    | key.pem  | Your UCP controller private key.                                                  |

## Step 5: Install the UCP controller

To install UCP you use the `docker/ucp` image. This image has commands to
install, configure, and backup UCP. To find what commands and options are
available, check the [reference documentation](../reference/install.md).

To install UCP:

1.  Log in to the machine where you want to install UCP.

2.  Use the `docker/ucp install` command to install UCP.

    In this example we'll be running the install command interactively, so that
    the command prompts for the necessary configuration values.
    You can also use flags to pass values to the install command.

    ```none
    $ docker run --rm -it --name ucp \
      -v /var/run/docker.sock:/var/run/docker.sock \
      docker/ucp install -i \
      --host-address <$UCP_PUBLIC_IP>
    ```

    Where:

    * i, specify to run the install command interactively,
    * host-address, is the public IP where users or a load balancer can access
    UCP,
    * Also, include the `--external-server-cert` flag if you're using server
    certificates signed by an external CA.

    When installing Docker UCP, overlay networking is automatically configured
    for you. If you are running Docker CS Engine 1.10, or have custom
    configurations on your Docker CS Engine, you need to restart the Docker
    daemon at this point.

3.  Check that the UCP web application is running.

    In your browser, navigate to the address where you've installed UCP.

    If you're not using an external CA, your browser warns that UCP is
    an unsafe site. This happens because you're accessing UCP using HTTPS
    but the certificates used by UCP are not trusted by your browser.

    ![](../images/login.png)

## Step 6: License your installation

Now that your UCP controller is installed, you need to license it.
[Learn how to license your installation](license.md).

## Step 7: Backup the controller CAs

For a highly available installation, you can add more controller nodes to
the UCP cluster. The controller nodes are replicas of each other.

For this, you need to make the CAs on each controller node use the same
root certificates and keys.

To create a backup of the CAs used on the controller node:

1. Log into the controller node using ssh.
2.  Run the docker/ucp backup command.

    ```none
    $ docker run --rm -i --name ucp \
        -v /var/run/docker.sock:/var/run/docker.sock \
        docker/ucp backup \
        --interactive \
        --root-ca-only \
        --passphrase "secret" > /tmp/backup.tar
    ```

[Learn more about the backup command](../high-availability/replicate-cas.md).

## Step 8: Add controller replicas to the UCP cluster

This step is optional.

For a highly available installation, you can add more controller nodes to
the UCP cluster. For that, use the `docker/ucp join --replica` command.
[Learn more about the join command](../reference/join.md).

For each node that you want to install as a controller replica:

1. Log into that node using ssh.

2. Make sure you transfer the backup.tar from the previous step to this node.

3.  Use the join command with the replica option:

    In this example we'll be running the join command interactively, so that
    the command prompts for the necessary configuration values. We'll also
    be passing the backup.tar file from the previous step in order to ensure
    that the CAs are replicated to the new controller node.

    ```none
    $ docker run --rm -it --name ucp \
      -v /var/run/docker.sock:/var/run/docker.sock \
      -v $BACKUP_PATH/backup.tar:/backup.tar \
      docker/ucp join \
      --interactive \
      --replica \
      --passphrase "secret"
    ```

4. Since UCP configures your Docker Engine for multi-host networking, it might
prompt you to restart the Docker daemon. To make the installation faster, join
all replica nodes first, and only then restart the Docker daemon on those nodes.

5. Repeat steps 1 and 2 on the other nodes you want to set up as replicas.
Make sure you set up 3, 5, or 7 controllers.

6. Check the cluster state.

    The Dashboard page of UCP should list all your controller nodes.

    ![UCP nodes page](../images/replica-nodes.png)

## Step 9: Ensure controllers know about each other

Internally, each controller node has a key-value store that keeps track of
the controllers that are part of the cluster.
When you installed and joined replica controllers, the Docker daemon on that
host was configured to use that key-value store.

To make the cluster fault-tolerant and be able to recover faster with less
downtime, you need to configure the Docker daemon on each controller node to
know about the key-value store that is running on the other nodes.

For each controller node:

1. Log into that node using ssh.

2.  Run the engine-discovery command.

    ```none
    $ docker run --rm -it \
        --name ucp \
        -v /var/run/docker.sock:/var/run/docker.sock \
        docker/ucp engine-discovery \
        --update
    ```

## Step 10: Add more nodes to the UCP cluster

Now you can add additional nodes to your UCP cluster. These are the nodes that
will be running your containers.

For each node that you want to add to your UCP cluster:

1. Log into that node.

2.  Use the join command, to join the node to the cluster:

    ```none
    $ docker run --rm -it --name ucp \
      -v /var/run/docker.sock:/var/run/docker.sock \
      docker/ucp join -i
    ```

3. Repeat steps 1 and 2 on the other nodes you want to add to your UCP cluster.

4. Check the cluster state.

    The Dashboard page of UCP should list all your controller nodes.

    ![UCP nodes page](../images/nodes-page.png)

## Step 11. Download a client certificate bundle

To validate that your cluster is correctly configured, you should try accessing
the cluster with the Docker CLI client. For this, you'll need to get a client
certificate bundle.
[Learn more about user bundles](../access-ucp/cli-based-access.md).

## Where to go next

* [Deploy an app from the UI](../applications/deploy-app-ui.md)
* [Monitor a UCP cluster](../monitor/monitor-ucp.md)


text:
<?php

use Eloquent\Phony\Test\Phony;

// setup
$stub = Phony::stub()->setUseIterableSpies(true)->setLabel('label');
$stub->with('aardvark')->generates();
$stub->with('bonobo', '*')->does(
    function ($animal, $verify, $depth = 0) use (&$stub) {
        if ($depth < 1) {
            iterator_to_array($stub($animal, $verify, $depth + 1));
        } else {
            $verify();
        }

        return [];
    }
);
iterator_to_array($stub('aardvark'));

// verification
iterator_to_array(
    $stub(
        'bonobo',
        function () use ($stub) {
            $stub->generated()->threw('InvalidArgumentException');
        }
    )
);


text:
/**
@method Seemple.Array#METHOD
@importance 1
@summary Any method from ``Array.prototype``
@desc {@link Seemple.Array} includes all the methods existing in the native JavaScript Array:

- [join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
- [pop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)
- [push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
- [reverse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)
- [shift](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)
- [unshift](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift)
- [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
- [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)
- [sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
- [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
- [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
- [some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
- [every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)
- [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
- [indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
- [lastIndexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf)
- [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
- [reduceRight](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight)
- [copyWithin](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin)
- [find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
- [findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)
- [fill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill)
- [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
- [entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries)
- [keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys)
- [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)

Yet they work the same as the ``Array.prototype``. There are only a few remarks:
- The ``forEach`` method returns an array itself instead of ``undefined``
- The methods which should return a new array (``splice``, ``slice``, ``filter``, ``map``...) return a new ``Seemple.Array`` instance.
- The ``keys``, ``values`` and ``entries`` methods return an array instead of an iterator.

Moreover, the methods generate events which are fired on any array modification. For more detailed information look at {@link Seemple.Array}.

@see {@link Seemple.Array#METHOD_}
@example
this.push(1, 2, 3);
@example
const seempleArray = this
	.forEach((value, index) => {
		//...
	})
	.map((value, index) => {
		//...
	});

console.log(seempleArray.isSeempleArray); // true
@example
this.reverse();
*/


text:
package org.apache.uima.jcas.cas;

import org.apache.uima.cas.ArrayFS;
import org.apache.uima.cas.FeatureStructure;

/**
 * For backwards compatibility with V2, only Only has methods not in ArrayFS or CommonArrayFSImpl
 *
 * @deprecated use FSArray instead
 */
@Deprecated
public interface ArrayFSImpl<E extends FeatureStructure> extends ArrayFS<E> {

}


text:
                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

                Science has not yet mastered prophecy

                We predict too much for the next year and yet far too little for the next ten.

Posted by Start Bootstrap on August 24, 2014

                Failure is not an option

                Many say exploration is part of our destiny, but it's actually our duty to future generations.

Posted by Start Bootstrap on July 8, 2014

            Older Posts →


text:
$(document).ready(function() {

	var $fadeIn = $('.scroll-fade-in');

	//set opacity of all elements with the 'scroll-fade-in' class
	$fadeIn.css({"opacity":"0"});

	$(window).scroll( function(){

        //for every element with 'scroll fade in' we calculate viewport and element dimensions
        $fadeIn.each( function(){

            var bottomElement = $(this).position().top + $(this).outerHeight() - $(this).data('offset');
            var bottomWindow = $(window).scrollTop() + $(window).height();

	        // if we can see the whole element, fade in
	        if( bottomWindow > bottomElement ){

	            $(this).animate({'opacity':'1'},1500);

	        }

        });

    });
});


text:
def sum_times_tables(table,a,b):
    return sum(sum(i*j for j in table) for i in range(a,b+1))


text:
package iso20022

// Specifies rates.
type CorporateActionRate74 struct {

	// Cash dividend amount per equity before deductions or allowances have been made.
	GrossDividendRate []*GrossDividendRateFormat23Choice `xml:"GrssDvddRate,omitempty"`

	// Cash dividend amount per equity after deductions or allowances have been made.
	NetDividendRate []*NetDividendRateFormat25Choice `xml:"NetDvddRate,omitempty"`

	// Public index rate applied to the amount paid to adjust it to inflation.
	IndexFactor *RateAndAmountFormat43Choice `xml:"IndxFctr,omitempty"`

	// Actual interest rate used for the payment of the interest for the specified interest period.
	InterestRateUsedForPayment []*InterestRateUsedForPaymentFormat9Choice `xml:"IntrstRateUsdForPmt,omitempty"`

	// A maximum percentage of shares available through the over subscription privilege, usually a percentage of the basic subscription shares, for example, an account owner subscribing to 100 shares may over subscribe to a maximum of 50 additional shares when the over subscription maximum is 50 percent.
	MaximumAllowedOversubscriptionRate *PercentageRate `xml:"MaxAllwdOvrsbcptRate,omitempty"`

	// Proportionate allocation used for the offer.
	ProrationRate *PercentageRate `xml:"PrratnRate,omitempty"`

	// Percentage of a cash distribution that will be withheld by the tax authorities of the jurisdiction of the issuer, for which a relief at source and/or reclaim may be possible.
	WithholdingTaxRate []*RateAndAmountFormat45Choice `xml:"WhldgTaxRate,omitempty"`

	// Rate at which the income will be withheld by a jurisdiction other than the jurisdiction of the issuer's country of tax incorporation, for which a relief at source and/or reclaim may be possible. It is levied in complement or offset of the withholding tax rate (TAXR) levied by the jurisdiction of the issuer's tax domicile.
	SecondLevelTax []*RateAndAmountFormat45Choice `xml:"ScndLvlTax,omitempty"`

	// Rate used for additional tax that cannot be categorised.
	AdditionalTax *RateAndAmountFormat43Choice `xml:"AddtlTax,omitempty"`

	// Amount included in the dividend/NAV that is identified as gains directly or indirectly derived from interest payments, for example, in the context of the EU Savings directive.
	TaxableIncomePerDividendShare []*RateTypeAndAmountAndStatus33 `xml:"TaxblIncmPerDvddShr,omitempty"`
}

func (c *CorporateActionRate74) AddGrossDividendRate() *GrossDividendRateFormat23Choice {
	newValue := new(GrossDividendRateFormat23Choice)
	c.GrossDividendRate = append(c.GrossDividendRate, newValue)
	return newValue
}

func (c *CorporateActionRate74) AddNetDividendRate() *NetDividendRateFormat25Choice {
	newValue := new(NetDividendRateFormat25Choice)
	c.NetDividendRate = append(c.NetDividendRate, newValue)
	return newValue
}

func (c *CorporateActionRate74) AddIndexFactor() *RateAndAmountFormat43Choice {
	c.IndexFactor = new(RateAndAmountFormat43Choice)
	return c.IndexFactor
}

func (c *CorporateActionRate74) AddInterestRateUsedForPayment() *InterestRateUsedForPaymentFormat9Choice {
	newValue := new(InterestRateUsedForPaymentFormat9Choice)
	c.InterestRateUsedForPayment = append(c.InterestRateUsedForPayment, newValue)
	return newValue
}

func (c *CorporateActionRate74) SetMaximumAllowedOversubscriptionRate(value string) {
	c.MaximumAllowedOversubscriptionRate = (*PercentageRate)(&value)
}

func (c *CorporateActionRate74) SetProrationRate(value string) {
	c.ProrationRate = (*PercentageRate)(&value)
}

func (c *CorporateActionRate74) AddWithholdingTaxRate() *RateAndAmountFormat45Choice {
	newValue := new(RateAndAmountFormat45Choice)
	c.WithholdingTaxRate = append(c.WithholdingTaxRate, newValue)
	return newValue
}

func (c *CorporateActionRate74) AddSecondLevelTax() *RateAndAmountFormat45Choice {
	newValue := new(RateAndAmountFormat45Choice)
	c.SecondLevelTax = append(c.SecondLevelTax, newValue)
	return newValue
}

func (c *CorporateActionRate74) AddAdditionalTax() *RateAndAmountFormat43Choice {
	c.AdditionalTax = new(RateAndAmountFormat43Choice)
	return c.AdditionalTax
}

func (c *CorporateActionRate74) AddTaxableIncomePerDividendShare() *RateTypeAndAmountAndStatus33 {
	newValue := new(RateTypeAndAmountAndStatus33)
	c.TaxableIncomePerDividendShare = append(c.TaxableIncomePerDividendShare, newValue)
	return newValue
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>service.tests</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Trees

         Indices

         Help

Jisc Publications Router

        Package service ::
        Package tests

[hide private]

[frames] | no frames]

Package tests

source code

This module contains all of the system tests and associated fixtures

        Submodules
        [hide private]

 service.tests.fixtures: This module contains all of the fixtures that are used throughout the testing.

 service.tests.fixtures.api: Fixtures for testing the API

 service.tests.fixtures.notifications: Fixtures for testing notifications

 service.tests.fixtures.packages: Fixtures for testing packages

 service.tests.fixtures.repository: Fixtures for testing repository features

 service.tests.functional: Module which contains tests and scripts for functional system testing

 service.tests.functional.harness: Script which can be used to drive all aspects of the JPER API in order to test its behaviour at scale

 service.tests.functional.load_test_data: Script which can load repository configs and user accounts into an empty test system, to prime it for the test harness

 service.tests.functional.test_api: Functional tests for the API.

 service.tests.unit: System unit tests

 service.tests.unit.test_api: Unit tests for the JPER API class

 service.tests.unit.test_dao: Unit tests for the Data Access Objects

 service.tests.unit.test_models: Unit tests for the core system objects

 service.tests.unit.test_packager: Unit tests for the packaging system

 service.tests.unit.test_routing: Unit tests for the routing system

        Variables
        [hide private]

        __package__ = None

         Trees

         Indices

         Help

Jisc Publications Router

    Generated by Epydoc 3.0.1 on Tue Dec  1 17:26:35 2015

      http://epydoc.sourceforge.net


text:
<?php

namespace backend\modules\bdk\execution\controllers;

use Yii;
use backend\models\Student;
use backend\modules\bdk\execution\models\StudentSearch;
use backend\models\Person;
use backend\modules\bdk\execution\models\PersonSearch;
use backend\models\ObjectReference;
use backend\models\ObjectFile;
use backend\models\File;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use hscstudio\heart\helpers\Heart;

/**
 * StudentController implements the CRUD actions for Student model.
 */
class StudentController extends Controller
{
    public $layout = '@hscstudio/heart/views/layouts/column2';
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Student models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new StudentSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Student model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

   /**
     * Creates a new Trainer model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateX($person_id)
    {
		$person = Person::findOne($person_id);
		if (null==$person){
			throw new NotFoundHttpException(Yii::t('app','SYSTEM_TEXT_PAGE_NOT_FOUND'));
		}

        $model = new Student([
			'person_id'=>$person_id,
		]);

        if ($model->load(Yii::$app->request->post())){
			if(strlen($person->nip)>3){
				$model->username = $person->nip;
				$model->password = $person->nip;
				if($model->save()) {
					Yii::$app->getSession()->setFlash('success', 'New data have saved.');
				}
				else{
					Yii::$app->getSession()->setFlash('error', 'New data is not saved.');
				}
			}
			else{
				Yii::$app->getSession()->setFlash('error', 'NIP tidak boleh kosong.');
			}
            return $this->redirect(['person']);
        } else {
			if (Yii::$app->request->isAjax){
				return $this->renderAjax('create', [
					'model' => $model,
				]);
			}
			else{
				return $this->render('create', [
					'model' => $model,
				]);
			}
        }
    }

    /**
     * Updates an existing Student model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateX($id)
    {
        $model = $this->findModel($id);
		$person = Person::findOne($model->person_id);
		if (null==$person){
			throw new NotFoundHttpException(Yii::t('app','SYSTEM_TEXT_PAGE_NOT_FOUND'));
		}
		$renders = [];
		$renders['model'] = $model;
		$renders['person'] = $person;
		$object_references_array = [
			'unit'=>'Unit','religion'=>'Religion','rank_class'=>'Rank Class','graduate'=>'Graduate'];
		$renders['object_references_array'] = $object_references_array;
		foreach($object_references_array as $object_reference=>$label){
			$object_references[$object_reference] = ObjectReference::find()
				->where([
					'object'=>'person',
					'object_id' => $person->id,
					'type' => $object_reference,
				])
				->one();
			if($object_references[$object_reference]==null){
				$object_references[$object_reference]= new ObjectReference();
			}
			$renders[$object_reference] = $object_references[$object_reference];
		}

		$currentFiles=[];
		$object_file_array = [
			'photo'=>'Photo 4x6','sk_cpns'=>'SK CPNS','sk_pangkat'=>'SK Pangkat'];
		$renders['object_file_array'] = $object_file_array;
		foreach($object_file_array as $object_file=>$label){
			$currentFiles[$object_file] = '';
			$object_files[$object_file] = ObjectFile::find()
				->where([
					'object'=>($object_file=='photo')?'person':'person',
					'object_id' => $person->id,
					'type' => $object_file,
				])
				->one();

			if($object_files[$object_file]!=null){
				$files[$object_file] = File::find()
					->where([
						'id'=>$object_files[$object_file]->file_id,
					])
					->one();
				$currentFiles[$object_file]=$files[$object_file]->file_name;
			}
			else{
				$object_files[$object_file]= new ObjectFile();
				$files[$object_file] = new File();
			}
			$renders[$object_file] = $object_files[$object_file];
			$renders[$object_file.'_file'] = $files[$object_file];
		}

        if ($model->load(Yii::$app->request->post())) {
            if($model->save()) {
				Yii::$app->getSession()->setFlash('success', 'Data student have updated.');
				$person->load(Yii::$app->request->post());

				//$person->scenario = 'profile';
				if($person->save()) {
					Yii::$app->getSession()->setFlash('success', 'Data student & person have updated.');
					foreach($object_references_array as $object_reference=>$label){
						$reference_id = Yii::$app->request->post('ObjectReference')[$object_reference]['reference_id'];
						Heart::objectReference($object_references[$object_reference],$reference_id,'person',$person->id,$object_reference);
					}

					$uploaded_files = [];
					foreach($object_file_array as $object_file=>$label){
						$uploaded_files[$object_file] = \yii\web\UploadedFile::getInstance($files[$object_file], 'file_name['.$object_file.']');
						if(null!=$uploaded_files[$object_file]){
							//upload(
								//$instance_file, $object='person', $object_id, $file, $object_file,
								//$type='photo', $resize=false,$current_file='',$thumb = false){
							Heart::upload(
								$uploaded_files[$object_file],
								'person',
								$person->id,
								$files[$object_file],
								$object_files[$object_file],
								$object_file,
								($object_file=='photo')?true:false,
								$currentFiles[$object_file],
								($object_file=='photo')?true:false
							);
						}
					}
				}
				return $this->redirect(['index']);
			}
			else{
				Yii::$app->getSession()->setFlash('error', 'Data is not updated.');
			}
			return $this->redirect(['view', 'id' => $model->person_id]);
        } else {
            return $this->render('update', $renders);
        }
    }

    /**
     * Deletes an existing Student model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteX($id)
    {
		if($this->findModel($id)->delete()) {
			Yii::$app->getSession()->setFlash('success', 'Data have deleted.');
		}
		else{
			Yii::$app->getSession()->setFlash('error', 'Data is not deleted.');
		}
        return $this->redirect(['index']);
    }

    /**
     * Finds the Student model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Student the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Student::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException(Yii::t('app','SYSTEM_TEXT_PAGE_NOT_FOUND'));
        }
    }

	/**
     * Lists all Person models.
     * @return mixed
     */
    public function actionPerson()
    {
        $searchModel = new PersonSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('person', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

	/**
     * Creates a new Person model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreatePerson()
    {
        $model = new Person();
		$student = new Student();
		$renders = [];
		$renders['model'] = $model;
		$renders['student'] = $student;

		$object_references_array = [
			'religion'=>'Religion','rank_class'=>'Rank Class','graduate'=>'Graduate'];
		$renders['object_references_array'] = $object_references_array;
		foreach($object_references_array as $object_reference=>$label){
			$object_references[$object_reference]= new ObjectReference();
			$renders[$object_reference] = $object_references[$object_reference];
		}

		$currentFiles=[];
		$object_file_array = [
			'photo'=>'Photo 4x6','sk_cpns'=>'SK CPNS','sk_pangkat'=>'SK Pangkat'];
		$renders['object_file_array'] = $object_file_array;
		foreach($object_file_array as $object_file=>$label){
			$currentFiles[$object_file] = '';
			$object_files[$object_file]= new ObjectFile();
			$files[$object_file] = new File();
			if($object_file=='photo'){
				$files[$object_file]->scenario = 'filetype-image';
			}
			else{
				$files[$object_file]->scenario = 'filetype-document';
			}
			$renders[$object_file] = $object_files[$object_file];
			$renders[$object_file.'_file'] = $files[$object_file];
		}

        if ($model->load(Yii::$app->request->post())){
			$model->status = 1;
			if($model->save()) {
				$student->person_id = $model->id;
				$student->save();
				Yii::$app->getSession()->setFlash('success', 'New data have saved.');
				foreach($object_references_array as $object_reference=>$label){
					$reference_id = Yii::$app->request->post('ObjectReference')[$object_reference]['reference_id'];
					Heart::objectReference($object_references[$object_reference],$reference_id,'person',$model->id,$object_reference);
				}

				$uploaded_files = [];
				foreach($object_file_array as $object_file=>$label){
					$uploaded_files[$object_file] = \yii\web\UploadedFile::getInstance($files[$object_file], 'file_name['.$object_file.']');
					if(null!=$uploaded_files[$object_file]){
						//upload(
							//$instance_file, $object='person', $object_id, $file, $object_file,
							//$type='photo', $resize=false,$current_file='',$thumb = false){
						Heart::upload(
							$uploaded_files[$object_file],
							'person',
							$model->id,
							$files[$object_file],
							$object_files[$object_file],
							$object_file,
							($object_file=='photo')?true:false,
							$currentFiles[$object_file],
							($object_file=='photo')?true:false
						);
					}
				}

				return $this->redirect(['view-person', 'id' => $model->id]);
			}
			else{
				Yii::$app->getSession()->setFlash('error', 'New data is not saved.');
				return $this->render('create_person', $renders);
			}

        } else {
            return $this->render('create_person', $renders);
        }
    }

	/**
     * Updates an existing Person model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModelPerson($id);
		$student = $this->findModel($id);
		$renders = [];
		$renders['model'] = $model;
		$renders['student'] = $student;
		$object_references_array = [
			'religion'=>'Religion','rank_class'=>'Rank Class','graduate'=>'Graduate'];
		$renders['object_references_array'] = $object_references_array;
		foreach($object_references_array as $object_reference=>$label){
			$object_references[$object_reference] = ObjectReference::find()
				->where([
					'object'=>'person',
					'object_id' => $id,
					'type' => $object_reference,
				])
				->one();
			if($object_references[$object_reference]==null){
				$object_references[$object_reference]= new ObjectReference();
			}
			$renders[$object_reference] = $object_references[$object_reference];
		}

		$currentFiles=[];
		$object_file_array = [
			'photo'=>'Photo 4x6','sk_cpns'=>'SK CPNS','sk_pangkat'=>'SK Pangkat'];
		$renders['object_file_array'] = $object_file_array;
		foreach($object_file_array as $object_file=>$label){
			$currentFiles[$object_file] = '';
			$object_files[$object_file] = ObjectFile::find()
				->where([
					'object'=>($object_file=='photo')?'person':'person',
					'object_id' => $model->id,
					'type' => $object_file,
				])
				->one();

			if($object_files[$object_file]!=null){
				$files[$object_file] = File::find()
					->where([
						'id'=>$object_files[$object_file]->file_id,
					])
					->one();
				$currentFiles[$object_file]=$files[$object_file]->file_name;
			}
			else{
				$object_files[$object_file]= new ObjectFile();
				$files[$object_file] = new File();
			}
			$renders[$object_file] = $object_files[$object_file];
			$renders[$object_file.'_file'] = $files[$object_file];
		}

        if ($model->load(Yii::$app->request->post())) {
            if($model->save()) {
				Yii::$app->getSession()->setFlash('success', 'Data Person telah diupdate.');
				if ($student->load(Yii::$app->request->post())) {
					if($student->save()){
						Yii::$app->getSession()->setFlash('success', 'Data Pengajar telah diupdate.');
					}
				}

				foreach($object_references_array as $object_reference=>$label){
					$reference_id = Yii::$app->request->post('ObjectReference')[$object_reference]['reference_id'];
					Heart::objectReference($object_references[$object_reference],$reference_id,'person',$model->id,$object_reference);
				}

				$uploaded_files = [];
				foreach($object_file_array as $object_file=>$label){
					$uploaded_files[$object_file] = \yii\web\UploadedFile::getInstance($files[$object_file], 'file_name['.$object_file.']');
					if(null!=$uploaded_files[$object_file]){
						//upload(
							//$instance_file, $object='person', $object_id, $file, $object_file,
							//$type='photo', $resize=false,$current_file='',$thumb = false){
						Heart::upload(
							$uploaded_files[$object_file],
							'person',
							$model->id,
							$files[$object_file],
							$object_files[$object_file],
							$object_file,
							($object_file=='photo')?true:false,
							$currentFiles[$object_file],
							($object_file=='photo')?true:false
						);
					}
				}
				return $this->redirect(['view-person', 'id' => $model->id]);
			}
			else{
				Yii::$app->getSession()->setFlash('error', 'Data is not updated.');
				return $this->render('update_person', $renders);
			}

        } else {
            return $this->render('update_person', $renders);
        }
    }

    /**
     * Deletes an existing Person model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
		$model = $this->findModelPerson($id);
		// delete object_reference
		ObjectReference::deleteAll(
			'object = :object AND object_id = :object_id',
			[':object' => 'person', ':object_id' => $id]
		);
		// find all object_file
		$object_files = ObjectFile::find()
			->where([
				'object' => 'person',
				'object_id' => $id,
			])
			->all();
		foreach($object_files as $object_file){
			$files = File::find()
			->where([
				'id' => $object_file->file_id,
			])
			->one();
			if($files!=null){
				$path = '';
				if(isset(Yii::$app->params['uploadPath'])){
					$path = Yii::$app->params['uploadPath'].'/'.$object_file->object.'/'.$object_file->object_id.'/';
				}
				else{
					$path = Yii::getAlias('@file').'/'.$object_file->object.'/'.$object_file->object_id.'/';
				}
				$filename = $files->file_name;
				@mkdir($path, 0755, true);
				@chmod($path, 0755);
				@unlink($path . $filename);
				@unlink($path . 'thumb_'. $filename);
				File::find(
					'id = :id',
					[':id' => $files->id]
				)
				->one()
				->delete();
			}
		}
		ObjectFile::deleteAll(
			'object = :object AND object_id = :object_id',
			[':object' => 'person', ':object_id' => $id]
		);

		if($model->delete()) {
			Yii::$app->getSession()->setFlash('success', 'Data have deleted.');
		}
		else{
			Yii::$app->getSession()->setFlash('error', 'Data is not deleted.');
		}
        return $this->redirect(['index']);
    }

	/**
     * Displays a single Person model.
     * @param integer $id
     * @return mixed
     */
    public function actionViewPerson($id)
    {
        return $this->render('view_person', [
            'model' => $this->findModelPerson($id),
        ]);
    }

    /**
     * Finds the Person model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Person the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelPerson($id)
    {
        if (($model = Person::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException(Yii::t('app','SYSTEM_TEXT_PAGE_NOT_FOUND'));
        }
    }

	public function actionPasswordStudent($id)
    {
        $model = $this->findModel($id);

		//echo $new_password;
        if(!empty(Yii::$app->request->post()['password_hash'])) {

			$model->password_hash = Yii::$app->security->generatePasswordHash(Yii::$app->request->post()['password_hash']);
            if($model->save()) {
				Yii::$app->getSession()->setFlash('success', 'Data have updated.');
			}
			else{
				Yii::$app->getSession()->setFlash('error', 'Data is not updated.');
			}
			return $this->redirect(['index']);

        } else {

			if (Yii::$app->request->isAjax)
				{return $this->renderAjax('change_password_student', [
                'model' => $model,]);}
            else
            	{return $this->render('change_password_student', [
                'model' => $model,]);}
        }
    }
}


text:
BUILD_DIR="_build"
PREVIEW_DIR="${BUILD_DIR}/preview"
WEB_DIR="${BUILD_DIR}/web"

makeAll() {
  makeClean
  makeSphinxPreview
  makeSphinxWeb
}

makeSphinxWeb() {
  echo "Building Sphinx files for website..."
  sphinx-build -b html . ${WEB_DIR}
  # Delete intermediary/unused files:
  find ${WEB_DIR} -mindepth 1 -not -name "*.md" -delete
  rm ${WEB_DIR}/search.md ${WEB_DIR}/genindex.md ${WEB_DIR}/py-modindex.md
  # Some custom tweaks to the output:
  python postprocess.py -f ${WEB_DIR}/
  echo "All done. Web pages are in ${WEB_DIR}."
}

makeSphinxPreview() {
  echo "Building Sphinx files for local preview..."
  # Build the docs for local viewing (in "read the docs" style):
  sphinx-build -b html . ${PREVIEW_DIR} \
    -D html_theme="sphinx_rtd_theme" \
    -D html_file_suffix=".html" \
    -D html_link_suffix=".html"
  echo "All done. Preview pages are in ${PREVIEW_DIR}."
}

makeClean() {
  rm -rf ${BUILD_DIR}
  echo "Deleted ${BUILD_DIR}."
}

usage() {
  echo -n "Usage:
 makedocs.sh [-a|-w|-p|-c]

 Options (only one allowed):
  -a   Clean and make all docs (default)
  -w   Make Sphinx for website
  -p   Make Sphinx for local preview
  -c   Clean
"
}

if [[ "$#" -gt 1 ]]; then
  usage
elif [[ "$#" -eq 1 ]]; then
  if [[ "$1" == "-a" ]]; then
    makeAll
  elif [[ "$1" == "-w" ]]; then
    makeSphinxWeb
  elif [[ "$1" == "-p" ]]; then
    makeSphinxPreview
  elif [[ "$1" == "-c" ]]; then
    makeClean
  else
    usage
  fi
else
  makeAll
fi


text:
<!DOCTYPE html>

	<title> correctness:   JSON.parse() and non-ASCII input  </title>

FAILED (This TC requires JavaScript enabled)


text:
package model

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
)

/*ICMPInfo i c m p info

swagger:model ICMPInfo
*/
type ICMPInfo struct {

	/* code
	 */
	Code int64 `json:"code,omitempty"`

	/* type
	 */
	Type int64 `json:"type,omitempty"`
}

// Validate validates this i c m p info
func (m *ICMPInfo) Validate(formats strfmt.Registry) error {
	var res []error

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
$packageName = 'mzcv'
$url = 'http://www.nirsoft.net/utils/mzcv.zip'
$checksum = 'a0cd6b7cf8fa0c9dae133d37b411c7a14f77a341'
$checksumType = 'sha1'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$installFile = Join-Path $toolsDir "$($packageName).exe"

Install-ChocolateyZipPackage -PackageName "$packageName" `
                             -Url "$url" `
                             -UnzipLocation "$toolsDir" `
                             -Url64bit "" `
                             -Checksum "$checksum" `
                             -ChecksumType "$checksumType"

Set-Content -Path ("$installFile.gui") `
            -Value $null


text:
require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'sqlite3',
  database: ':memory:'
)

ActiveRecord::Migration.create_table :cars do |t|
  t.string :make
  t.string :model
end

ActiveRecord::Migration.create_table :doors do |t|
  t.references  :car
  t.string      :position
end

# :nodoc:
class Car < ActiveRecord::Base
  has_many :doors, autosave: true
end

# :nodoc:
class Door < ActiveRecord::Base
  belongs_to :car

  validates_inclusion_of :position, in: %w(left right)
end


text:
module Crypto.Gpgme (
      -- * Context
      Ctx
    , newCtx
    , freeCtx
    , withCtx
    , setArmor
    , setKeyListingMode
      -- ** Passphrase callbacks
    , isPassphraseCbSupported
    , PassphraseCb
    , setPassphraseCallback
      -- ** Progress callbacks
    , progressCb
    , setProgressCallback

    -- * Keys
    , Key
    , importKeyFromFile
    , getKey
    , listKeys
    , removeKey
    , RemoveKeyFlags(..)

    , searchKeys
    -- * Information about keys
    , Validity (..)
    , PubKeyAlgo (..)
    , KeySignature (..)
    , UserId (..)
    , KeyUserId (..)
    , keyUserIds
    , keyUserIds'
    , SubKey (..)
    , keySubKeys
    , keySubKeys'

    -- * Encryption
    , Signature
    , SignatureSummary(..)
    , VerificationResult
    , encrypt
    , encryptSign
    , encryptFd
    , encryptSignFd
    , encrypt'
    , encryptSign'
    , decrypt
    , decryptFd
    , decryptVerifyFd
    , decrypt'
    , decryptVerify
    , decryptVerify'
    , verify
    , verify'
    , verifyDetached
    , verifyDetached'
    , verifyPlain
    , verifyPlain'
    , sign

    -- * Error handling
    , GpgmeError
    , errorString
    , sourceString

    -- * Other Types
    , KeyListingMode(..)
    , SignMode(..)

    , Fpr
    , Encrypted
    , Plain

    , Protocol(..)

    , InvalidKey

    , IncludeSecret(..)

    , Flag(..)

    , DecryptError(..)

    , HgpgmeException(..)

) where

import Crypto.Gpgme.Ctx
import Crypto.Gpgme.Crypto
import Crypto.Gpgme.Types
import Crypto.Gpgme.Key


text:
class AddAssessmentIndexToSubmissions < ActiveRecord::Migration
  def self.up
    add_index :submissions, :assessment_id
  end

  def self.down
    remove_index :submissions, assessment_id
  end
end


text:
import armor
import weapons
import potions
import spells
import scrolls
import bombs
import rangedWeapons


text:
package org.datanucleus.samples.jdo.tutorial;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import java.util.ArrayList;
import java.util.List;

/**
 * Definition of a Product
 * Represents a product, and contains the key aspects of the item.
 */
@PersistenceCapable
public class Product
{
    @PrimaryKey
    @Persistent(valueStrategy=IdGeneratorStrategy.NATIVE)
    protected long id;

    protected String name=null;

    protected String description=null;

    protected double price=0.0;

    private List<User> owners;

    public Product(String name, String description, double price)
    {
        this.name = name;
        this.description = description;
        this.price = price;
        owners=new ArrayList<User>();
    }

    public long getId()
    {
        return id;
    }

    public String getName()
    {
        return name;
    }

    public String getDescription()
    {
        return description;
    }

    public double getPrice()
    {
        return price;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public void setPrice(double price)
    {
        this.price = price;
    }

    public List<User> getOwners() {
        return owners;
    }

    public void setOwners(List<User> owners) {
        this.owners = owners;
    }

    @Override
    public String toString() {
        return "Product{" +
                ", price=" + price +
                ", description='" + description + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}


text:
package org.waveprotocol.wave.client.paging;

import com.google.common.base.Preconditions;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Simple block tree for testing.
 *
 */
public final class FakeBlock extends AbstractTreeNode<FakeBlock> implements Block {

  interface Factory {
    FakeBlock create(String name, Dimensions size);
  }

  static class Dimensions {
    /** Maximum margin size. */
    private final static int MAX_MARGIN = 40;
    /** Maximum padding size. */
    private final static int MAX_PADDING = 40;
    /** Probability that a block will be an offset parent. */
    private final static double PARENT_PROBABILITY = 0.3;

    /** Randomizer for wobbling. */
    private final Random random;

    /** External space before and after this block. */
    int margin;
    /** Internal space at each end of this block. */
    int padding;
    /** True iff this block acts as a new origin for descendant positions. */
    boolean isOffsetParent;

    private Dimensions(Random random) {
      this.random = random;
    }

    /** @return a specification for an empty block. */
    static Dimensions zero() {
      return new Dimensions(null);
    }

    /** @return a specification for block of random size. */
    static Dimensions create(Random random) {
      Dimensions dimensions = new Dimensions(random);
      dimensions.wobble();
      return dimensions;
    }

    /**
     * Randomly adjusts this size specification.
     */
    void wobble() {
      if (random != null) {
        margin = random.nextInt(MAX_MARGIN);
        padding = random.nextInt(MAX_PADDING);
        isOffsetParent = random.nextDouble() < PARENT_PROBABILITY;
      }
    }
  }

  private final String name;
  private final Dimensions layout;

  private boolean pagedIn;

  private static final Factory ROOT = new Factory() {
    @Override
    public FakeBlock create(String name, Dimensions size) {
      return new FakeBlock(name, size);
    }
  };

  private FakeBlock(String name, Dimensions size) {
    this.name = name;
    this.layout = size;
  }

  @Override
  protected FakeBlock self() {
    return this;
  }

  public static FakeBlock.Factory root() {
    return ROOT;
  }

  private boolean hasParent() {
    return getParent() != null;
  }

  //
  // Covariant mutation.
  //

  public FakeBlock.Factory prepend() {
    return new FakeBlock.Factory() {
      @Override
      public FakeBlock create(String name, Dimensions size) {
        return prepend(new FakeBlock(name, size));
      }
    };
  }

  public FakeBlock.Factory append() {
    return new FakeBlock.Factory() {
      @Override
      public FakeBlock create(String name, Dimensions size) {
        return append(new FakeBlock(name, size));
      }
    };
  }

  public FakeBlock.Factory insertBefore(final FakeBlock reference) {
    return new FakeBlock.Factory() {
      @Override
      public FakeBlock create(String name, Dimensions size) {
        return insertBefore(reference, new FakeBlock(name, size));
      }
    };
  }

  public FakeBlock.Factory insertAfter(final FakeBlock reference) {
    return new FakeBlock.Factory() {
      @Override
      public FakeBlock create(String name, Dimensions size) {
        return insertAfter(reference, new FakeBlock(name, size));
      }
    };
  }

  public void removeFomParent() {
    Preconditions.checkState(hasParent());
    remove();
  }

  //
  // Paging state.
  //

  @Override
  public void pageIn() {
    Preconditions.checkState(!pagedIn);
    Preconditions.checkState(!hasParent() || getParent().isPagedIn());
    pagedIn = true;
    layout.wobble();
  }

  @Override
  public void pageOut() {
    Preconditions.checkState(pagedIn);
    Preconditions.checkState(hasParent() || getParent().isPagedIn());
    pagedIn = false;
    layout.wobble();
  }

  public boolean isPagedIn() {
    return pagedIn;
  }

  //
  // Dimensions.
  //

  /** @return the start of this block's margin box. */
  private double getOuterStart() {
    if (getPreviousSibling() != null) {
      return getPreviousSibling().getOuterEnd();
    } else if (getParent() != null) {
      return getParent().getInnerStart() - getParent().getChildrenOrigin();
    } else {
      return 0;
    }
  }

  /** @return the end of this block's margin box. */
  private double getOuterEnd() {
    return getEnd() + layout.margin;
  }

  private double getInnerStart() {
    return getStart() + layout.padding;
  }

  private double getInnerEnd() {
    if (getLastChild() != null) {
      return getLastChild().getOuterEnd() + getChildrenOrigin();
    } else {
      return getInnerStart();
    }
  }

  @Override
  public double getStart() {
    return getOuterStart() + layout.margin;
  }

  @Override
  public double getEnd() {
    return getInnerEnd() + layout.padding;
  }

  @Override
  public double getChildrenOrigin() {
    return layout.isOffsetParent ? getInnerStart() : 0;
  }

  //
  // Naming.
  //

  public String getName() {
    return name;
  }

  //
  // Random.
  //

  public List<FakeBlock> collect() {
    List<FakeBlock> all = new ArrayList<FakeBlock>();
    collectInto(all);
    return all;
  }

  private void collectInto(List<FakeBlock> all) {
    all.add(this);
    for (FakeBlock child = getFirstChild(); child != null; child = child.getNextSibling()) {
      child.collectInto(all);
    }
  }

  public String render() {
    return render(new StringBuffer()).toString();
  }

  public String renderWithNames() {
    return renderWithNames(new StringBuffer()).toString();
  }

  private StringBuffer render(StringBuffer sb) {
    sb.append(pagedIn ? "[" : "(");
    for (FakeBlock child = getFirstChild(); child != null; child = child.getNextSibling()) {
      child.render(sb);
    }
    sb.append(pagedIn ? "]" : ")");
    return sb;
  }

  private StringBuffer renderWithNames(StringBuffer sb) {
    sb.append(pagedIn ? "[ " : "( ");
    sb.append(name);
    for (FakeBlock child = getFirstChild(); child != null; child = child.getNextSibling()) {
      sb.append(" ");
      child.renderWithNames(sb);
    }
    sb.append(pagedIn ? " ]" : " )");
    return sb;
  }

  @Override
  public String toString() {
    return render();
  }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>psidev.psi.mi.jami.bridges.exception (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)</title>
<meta name="date" content="2021-08-20">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

psidev.psi.mi.jami.bridges.exception

Exceptions

BridgeFailedException


text:
springies
=========

Authors:
Thanh-ha Nguyen (tn32)
Dennis Park (djp28)

##Project details
Start date: Jan 18 2014

End date: Feb 08 2014

Time spent: 40-50 hrs

[Github repo] (https://github.com/duke-compsci308-spring2014/springies_team24.git)

##What is Springies?
A sandbox simulation manipulating spring-mass assemblies.  Objects are enacted by various forces; affected by user input.  XML docs are parsed and processed, its products loaded into the environment.  The Springies engine contains the list of assemblies, initializes JGame settings, environment, forces, and listeners.

Based off of [Sodaplay Constructor] (http://sodaplay.com/creators/soda/items/constructor).

##Primary roles
Thanh-ha : debugging, xml (Parsers package), forces package, Mass, Walls, setup for Environment

Dennis   : physics, forces package, Assembly, AssemblyFactory, Spring, Muscle, toggling Environment

Both     : extensive refactoring, listeners

##Resources
* Kevin Oh (TA)
* Robert Duvall
* Javadocs
* Stackoverflow
* Stackexchange
* Piazza
* [Sodaplay] (http://sodaplay.com/)

##Starter files
* Main.java
* PhysicalObject.java
* PhysicalObjectCircle.java
* PhysicalObjectRect.java
* WorldManager.java
* JGame Engine
* JBox2D Engine

##How to play
Keystroke : Behavior

'g'       : toggles gravity force

'v'       : toggles viscosity force

'm'       : toggles center of mass force
'1'-'4'   : toggle wall repulsion forces

'c'       : clear all loaded assemblies

'n'       : load new assembly

'Up'      : increase walled canvas

'Down'    : decrease walled canvas

'Leftclick: drag and release assembly (exert spring force)

##Known bugs
* Masses may get stuck in walls due to bounds limitations of JBox and JGEngine
* JFileChooser returns NullPointerException when called (temporary fix: place cursor over top-right corner, then press 'n'). Sometimes works. Sometimes doesn't. Might have to do with calling file only when Springies is fully loaded.
* The direction that forces act upon are calculated in radians but environment.xml gives the direction in degrees. This is never converted so gravity will be at a strange angle (90 radians = 156.6 degrees) when using reading in the given environment.xml file. A simple fix is to change the direction in the XML file to 1.57 (90 degrees = 1.57 radians).
* If you move the walls 2-3 clicks outside of the game window, they become stuck there (some kind of collision) and will never go back to the game window. If you don't go too far out, walls will toggle in and out as expected.
* If you move the walls too quickly, they will move too quickly to exert repulsion forces on the masses.


text:
{{ partial "head.html" . }}

{{ if eq .Site.Params.sidebar "default" }}
  {{ partial "sidebars/sidebar-base--default.html" . }}
{{ end }}

        {{if .Params.excerpt_image.post}}{{end}}

{{ .Title }}

                <time datetime="{{ .Date.Format .Site.Params.date_format }}">
                  {{ .Date.Format .Site.Params.date_format }} /
                </time>
                {{ .Site.Params.author.name }} {{if .Site.Params.disqus_shortname}}/
                 Comments{{end}}

              {{.Content}}

                Share on:

                  Twitter
                 /

                  Facebook
                 /

                  Google+

Author: {{ .Site.Params.author.name }}

                {{ .Site.Params.author.bio }}

                {{ .Site.Params.author.website }}

        {{ with .Site.DisqusShortname }}

        {{ end }}

{{ partial "foot.html" . }}


text:
package ssh

import (
	"errors"
	"fmt"
	"io"
	"math/rand"
	"net"
	"strconv"
	"strings"
	"sync"
	"time"
)

// Listen requests the remote peer open a listening socket on
// addr. Incoming connections will be available by calling Accept on
// the returned net.Listener. The listener must be serviced, or the
// SSH connection may hang.
func (c *Client) Listen(n, addr string) (net.Listener, error) {
	laddr, err := net.ResolveTCPAddr(n, addr)
	if err != nil {
		return nil, err
	}
	return c.ListenTCP(laddr)
}

// Automatic port allocation is broken with OpenSSH before 6.0. See
// also https://bugzilla.mindrot.org/show_bug.cgi?id=2017.  In
// particular, OpenSSH 5.9 sends a channelOpenMsg with port number 0,
// rather than the actual port number. This means you can never open
// two different listeners with auto allocated ports. We work around
// this by trying explicit ports until we succeed.

const openSSHPrefix = "OpenSSH_"

var portRandomizer = rand.New(rand.NewSource(time.Now().UnixNano()))

// isBrokenOpenSSHVersion returns true if the given version string
// specifies a version of OpenSSH that is known to have a bug in port
// forwarding.
func isBrokenOpenSSHVersion(versionStr string) bool {
	i := strings.Index(versionStr, openSSHPrefix)
	if i < 0 {
		return false
	}
	i += len(openSSHPrefix)
	j := i
	for ; j < len(versionStr); j++ {
		if versionStr[j] < '0' || versionStr[j] > '9' {
			break
		}
	}
	version, _ := strconv.Atoi(versionStr[i:j])
	return version < 6
}

// autoPortListenWorkaround simulates automatic port allocation by
// trying random ports repeatedly.
func (c *Client) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) {
	var sshListener net.Listener
	var err error
	const tries = 10
	for i := 0; i < tries; i++ {
		addr := *laddr
		addr.Port = 1024 + portRandomizer.Intn(60000)
		sshListener, err = c.ListenTCP(&addr)
		if err == nil {
			laddr.Port = addr.Port
			return sshListener, err
		}
	}
	return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err)
}

// RFC 4254 7.1
struct channelForwardMsg {
	addr  string
	rport uint32
}

// ListenTCP requests the remote peer open a listening socket
// on laddr. Incoming connections will be available by calling
// Accept on the returned net.Listener.
func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) {
	if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) {
		return c.autoPortListenWorkaround(laddr)
	}

	m := channelForwardMsg{
		laddr.IP.String(),
		uint32(laddr.Port),
	}
	// send message
	ok, resp, err := c.SendRequest("tcpip-forward", true, Marshal(&m))
	if err != nil {
		return nil, err
	}
	if !ok {
		return nil, errors.New("ssh: tcpip-forward request denied by peer")
	}

	// If the original port was 0, then the remote side will
	// supply a real port number in the response.
	if laddr.Port == 0 {
		var p struct {
			Port uint32
		}
		if err := Unmarshal(resp, &p); err != nil {
			return nil, err
		}
		laddr.Port = int(p.Port)
	}

	// Register this forward, using the port number we obtained.
	ch := c.forwards.add(*laddr)

	return &tcpListener{laddr, c, ch}, nil
}

// forwardList stores a mapping between remote
// forward requests and the tcpListeners.
struct forwardList {
	sync.Mutex
	entries []forwardEntry
}

// forwardEntry represents an established mapping of a laddr on a
// remote ssh server to a channel connected to a tcpListener.
struct forwardEntry {
	laddr net.TCPAddr
	c     chan forward
}

// forward represents an incoming forwarded tcpip connection. The
// arguments to add/remove/lookup should be address as specified in
// the original forward-request.
struct forward {
	newCh NewChannel   // the ssh client channel underlying this forward
	raddr *net.TCPAddr // the raddr of the incoming connection
}

func (l *forwardList) add(addr net.TCPAddr) chan forward {
	l.Lock()
	defer l.Unlock()
	f := forwardEntry{
		addr,
		make(chan forward, 1),
	}
	l.entries = append(l.entries, f)
	return f.c
}

func (l *forwardList) handleChannels(in <-chan NewChannel) {
	for ch := range in {
		laddr, rest, ok := parseTCPAddr(ch.ExtraData())
		if !ok {
			// invalid request
			ch.Reject(ConnectionFailed, "could not parse TCP address")
			continue
		}

		raddr, rest, ok := parseTCPAddr(rest)
		if !ok {
			// invalid request
			ch.Reject(ConnectionFailed, "could not parse TCP address")
			continue
		}

		if ok := l.forward(*laddr, *raddr, ch); !ok {
			// Section 7.2, implementations MUST reject spurious incoming
			// connections.
			ch.Reject(Prohibited, "no forward for address")
			continue
		}
	}
}

// remove removes the forward entry, and the channel feeding its
// listener.
func (l *forwardList) remove(addr net.TCPAddr) {
	l.Lock()
	defer l.Unlock()
	for i, f := range l.entries {
		if addr.IP.Equal(f.laddr.IP) && addr.Port == f.laddr.Port {
			l.entries = append(l.entries[:i], l.entries[i+1:]...)
			close(f.c)
			return
		}
	}
}

// closeAll closes and clears all forwards.
func (l *forwardList) closeAll() {
	l.Lock()
	defer l.Unlock()
	for _, f := range l.entries {
		close(f.c)
	}
	l.entries = nil
}

func (l *forwardList) forward(laddr, raddr net.TCPAddr, ch NewChannel) bool {
	l.Lock()
	defer l.Unlock()
	for _, f := range l.entries {
		if laddr.IP.Equal(f.laddr.IP) && laddr.Port == f.laddr.Port {
			f.c <- forward{ch, &raddr}
			return true
		}
	}
	return false
}

struct tcpListener {
	laddr *net.TCPAddr

	conn *Client
	in   <-chan forward
}

// Accept waits for and returns the next connection to the listener.
func (l *tcpListener) Accept() (net.Conn, error) {
	s, ok := <-l.in
	if !ok {
		return nil, io.EOF
	}
	ch, incoming, err := s.newCh.Accept()
	if err != nil {
		return nil, err
	}
	go DiscardRequests(incoming)

	return &tcpChanConn{
		Channel: ch,
		laddr:   l.laddr,
		raddr:   s.raddr,
	}, nil
}

// Close closes the listener.
func (l *tcpListener) Close() error {
	m := channelForwardMsg{
		l.laddr.IP.String(),
		uint32(l.laddr.Port),
	}

	// this also closes the listener.
	l.conn.forwards.remove(*l.laddr)
	ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m))
	if err == nil && !ok {
		err = errors.New("ssh: cancel-tcpip-forward failed")
	}
	return err
}

// Addr returns the listener's network address.
func (l *tcpListener) Addr() net.Addr {
	return l.laddr
}

// Dial initiates a connection to the addr from the remote host.
// The resulting connection has a zero LocalAddr() and RemoteAddr().
func (c *Client) Dial(n, addr string) (net.Conn, error) {
	// Parse the address into host and numeric port.
	host, portString, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}
	port, err := strconv.ParseUint(portString, 10, 16)
	if err != nil {
		return nil, err
	}
	// Use a zero address for local and remote address.
	zeroAddr := &net.TCPAddr{
		IP:   net.IPv4zero,
		Port: 0,
	}
	ch, err := c.dial(net.IPv4zero.String(), 0, host, int(port))
	if err != nil {
		return nil, err
	}
	return &tcpChanConn{
		Channel: ch,
		laddr:   zeroAddr,
		raddr:   zeroAddr,
	}, nil
}

// DialTCP connects to the remote address raddr on the network net,
// which must be "tcp", "tcp4", or "tcp6".  If laddr is not nil, it is used
// as the local address for the connection.
func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
	if laddr == nil {
		laddr = &net.TCPAddr{
			IP:   net.IPv4zero,
			Port: 0,
		}
	}
	ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port)
	if err != nil {
		return nil, err
	}
	return &tcpChanConn{
		Channel: ch,
		laddr:   laddr,
		raddr:   raddr,
	}, nil
}

// RFC 4254 7.2
struct channelOpenDirectMsg {
	raddr string
	rport uint32
	laddr string
	lport uint32
}

func (c *Client) dial(laddr string, lport int, raddr string, rport int) (Channel, error) {
	msg := channelOpenDirectMsg{
		raddr: raddr,
		rport: uint32(rport),
		laddr: laddr,
		lport: uint32(lport),
	}
	ch, in, err := c.OpenChannel("direct-tcpip", Marshal(&msg))
	go DiscardRequests(in)
	return ch, err
}

struct tcpChan {
	Channel // the backing channel
}

// tcpChanConn fulfills the net.Conn interface without
// the tcpChan having to hold laddr or raddr directly.
struct tcpChanConn {
	Channel
	laddr, raddr net.Addr
}

// LocalAddr returns the local network address.
func (t *tcpChanConn) LocalAddr() net.Addr {
	return t.laddr
}

// RemoteAddr returns the remote network address.
func (t *tcpChanConn) RemoteAddr() net.Addr {
	return t.raddr
}

// SetDeadline sets the read and write deadlines associated
// with the connection.
func (t *tcpChanConn) SetDeadline(deadline time.Time) error {
	if err := t.SetReadDeadline(deadline); err != nil {
		return err
	}
	return t.SetWriteDeadline(deadline)
}

// SetReadDeadline sets the read deadline.
// A zero value for t means Read will not time out.
// After the deadline, the error from Read will implement net.Error
// with Timeout() == true.
func (t *tcpChanConn) SetReadDeadline(deadline time.Time) error {
	return errors.New("ssh: tcpChan: deadline not supported")
}

// SetWriteDeadline exists to satisfy the net.Conn interface
// but is not implemented by this type.  It always returns an error.
func (t *tcpChanConn) SetWriteDeadline(deadline time.Time) error {
	return errors.New("ssh: tcpChan: deadline not supported")
}


text:
package com.castelijns.mmdemo.user_detail;

import com.castelijns.mmdemo.models.User;

public class UserDetailPresenter implements UserDetailContract.Presenter {

    private UserDetailContract.View view;
    private User user;

    UserDetailPresenter(UserDetailContract.View view, User user) {
        this.view = view;
        this.user = user;
    }

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void onDirectionsClicked() {
        view.showNavigationTo(user.getAddress().getGeo().get("lat"),
                user.getAddress().getGeo().get("lon"));
    }
}


text:
<!DOCTYPE <!DOCTYPE html>

	<title>Get-It Adventures</title>
	<link rel="stylesheet" href="style.css" media="screen" charset="utf-8">
	<link href='https://fonts.googleapis.com/css?family=Asap' rel='stylesheet' type='text/css'>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

Home

About

Application

Contact

Video

Get It Adventures

Mission Statement: Providing a place where individuals and families can  create new memories through shared experiences of adventure and thrills is what Get-It Adventures aims to do with each participant through helping  people transition into healthy lifestyles and uniting them with others in the pursuit of life.

A life of addiction is isolating. The focus of our adventures is to increase the ability of those who participate to enjoy and create relationships with others. All of our adventures are done in various sized groups, and those who qualify are welcome to bring friends and family.

To begin your Intake, select from the following images the ones you find most interesting:

<button id="intake-button">Click to begin intake!</button>

    <button id="btnVote">Vote</button>

<button id="btnNew">New pair</button>

    <canvas id="myChart" width="600" height="300"> </canvas>

Git It © Follow us on  Twitter and Facebook


text:
use strict;
use warnings;
# use IO::File;
# use File::Basename; # enable maipulating of the full path
# use File::Slurp;
# use List::Util qw(max);
# use List::Util qw(sum);
use Getopt::Long;
use Pod::Usage;
###############################################################################
##############         Print informative message             ##################
###############################################################################
print "###########################################################\n";
print "#  xmap_stats.pl Version 1.0                              #\n";
print "#                                                         #\n";
print "#  Created by Jennifer Shelton 08/26/14                   #\n";
print "#  github.com/i5K-KINBRE-script-share                     #\n";
print "#  perl xmap_stats.pl -help # for usage/options           #\n";
print "#  perl xmap_stats.pl -man # for more details             #\n";
print "###########################################################\n";
###############################################################################
##############                get arguments                  ##################
###############################################################################
my ($input_xmap);
my $con = 0;
my $man = 0;
my $help = 0;
GetOptions (
    'help|?' => \$help,
    'man' => \$man,
    'x|input_xmap:s' => \$input_xmap,
    'c|con:i' => \$con

)
or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
die "Option -x or --input_xmap not specified.\n" unless $input_xmap; # report missing required variables

###############################################################################
##############              run                              ##################
###############################################################################
#h XmapEntryID  QryContigID     RefContigID     QryStartPos     QryEndPos       RefStartPos     RefEndPos       Orientation     Confidence      HitEnum

my ($breadth,$total_length,%refs);
open (my $xmap, "<", $input_xmap) or die "Can't open $input_xmap: $!";
my $start_cov = -1;
my $end_cov = 0;

while (<$xmap>)
{
    unless (/^#/)
    {
        unless (/^\s+$/) # unless the line is blank
        {
            my ($RefContigID, $start, $end, $Confidence) = (split(/\t/))[2,5,6,8];
            if ($Confidence >= $con)
            {
                $total_length += $end - $start;
                unless ($refs{$RefContigID})#if (new contig)
                {
                    $refs{$RefContigID} = 1;
                    $breadth += $end_cov - $start_cov;
                    $start_cov = $start;
                    $end_cov = $end;
                }
                elsif ((($start >= $start_cov) && ($start <= $end_cov)) && ($end > $end_cov))# if alignment overlaps and extends coverage
                {
                    $end_cov = $end;
                }
                elsif ($start > $end_cov) # if next alignment on same reference but not overlapping
                {
                    $breadth += $end_cov - $start_cov;
                    $start_cov = $start;
                    $end_cov = $end;
                }
            }
        }
        if (eof)
        {
            $breadth += $end_cov - $start_cov;
        }
    }
}
if (!$breadth)
{
    $breadth = 0;
}
if (!$total_length)
{
    $total_length = 0;
}
$breadth = $breadth/1000000;
$total_length = $total_length/1000000;
print "Breadth of alignment coverage = $breadth (Mb)\n";
print "Total alignment length = $total_length (Mb)\n";
print "done\n";
###############################################################################
##############                  Documentation                ##################
###############################################################################
## style adapted from http://www.perlmonks.org/?node_id=489861
__END__

=head1 NAME

xmap_stats.pl - Script outputs breadth of alignment coverage and total aligned length from an xmap.

"Breadth of alignment coverage" is the number of bases covered by aligned maps. This is equivalent to "Total Unique Aligned Len(Mb)".

"Total alignment length is the total length of the alignment. This is equivalent to "Total Aligned Len(Mb)".

=head1 USAGE

perl xmap_stats.pl [options]

Documentation options:

    -help    brief help message
    -man	    full documentation

Required parameters:

    -x	    xmap to summarize

Filtering parameters:

    -c	    minimum confidence score

=head1 OPTIONS

=over 8

=item B<-help>

Print a brief help message and exits.

=item B<-man>

Prints the more detailed manual page with output details and examples and exits.

=item B<-x, --input_xmap>

The fullpath for the xmap file. This will be summarized.

=item B<-c, --con>

The minimum alignment confidence score (default = 0).

=back

=head1 DESCRIPTION

B<OUTPUT DETAILS:>

Script has no unusual dependencies.

=cut


text:
class MetaCallback(object):
    definition = ('MetaCallback', 'addCallback', 'removeCallback')

    def __init__(self, meta):
        self.meta = meta

    def started(self, server):
        """Called when a server is started. The server is up and running when this event is sent,
        so all methods that need a running server will work."""
        pass

    def stopped(self, server):
        """Called when a server is stopped. The server is  already stopped when this event is sent,
        so no methods that need a running server will work."""
        pass

class ServerCallback(object):
    definition = ('ServerCallback', 'addCallback', 'removeCallback')

    def __init__(self, server_id):
        self.id = server_id

    def user_connected(self, state):
        """Called when a user connects to the server. """
        pass

    def user_disconnected(self, state):
        """Called when a user disconnects from the server."""
        pass

    def user_state_changed(self, state):
        """Called when a user state changes. This is called if the user moves, is renamed, is muted,
        deafened etc."""
        pass

    def user_text_message(self, state, message):
        """Called when user writes a text message."""
        pass

    def channel_created(self, state):
        """Called when a new channel is created."""
        pass

    def channel_removed(self, state):
        """Called when a channel is removed."""
        pass

    def channel_state_changed(self, state):
        """Called when a new channel state changes. This is called if the channel is moved, renamed
        or if new links are added."""
        pass

class ServerContextCallback(object):
    definition = ('ServerContextCallback', 'addContextCallback', 'removeContextCallback')

    def __init__(self, server_id):
        self.id = server_id

    def context_action(self, action, user, session, channelid):
        pass

class ServerAuthenticator(object):
    definition = ('ServerAuthenticator', 'setAuthenticator', None)
    fallthrough_values = dict(
        authenticate=(-2, None, None),
        get_info=(False, None,),
        name_to_id=-2,
        id_to_name='',
        id_to_texture=None,
    )

    def __init__(self, server_id):
        self.id = server_id

    def authenticate(self, name, password, certificates, certhash, certstrong):
        raise NotImplementedError

    def get_info(self, user_id):
        raise NotImplementedError

    def name_to_id(self, name):
        raise NotImplementedError

    def id_to_name(self, user_id):
        raise NotImplementedError

    def id_to_texture(self, user_id):
        raise NotImplementedError

class ServerUpdatingAuthenticator(ServerAuthenticator):
    definition = ('ServerUpdatingAuthenticator', 'setAuthenticator', None)
    fallthrough_values = dict(
        register_user=-2,
        unregister_user=-1,
        get_registered_users={},
        set_info=-1,
        set_texture=-1,
    )

    def register_user(self, info):
        raise NotImplementedError

    def unregister_user(self, user_id):
        raise NotImplementedError

    def get_registered_users(self, filter):
        raise NotImplementedError

    def set_info(self, user_id, info):
        raise NotImplementedError

    def set_texture(self, user_id, texture):
        raise NotImplementedError


text: This repository holds my learning journal entries.


text:
%% Gray-Level Appearance Model
function AppearanceData=ASM_MakeAppearanceModel3D(TrainingData,Faces,options)

% Number of TrainingData sets
s=length(TrainingData);

% Number of landmarks
nl = size(TrainingData(1).Vertices,1);

% Calculate the normals of the contours of all training data
for i=1:s
    [TrainingData(i).normalsV]=ASM_GetContourNormals3D(TrainingData(i).Vertices,Faces);
end

% Inverse of covariance matrix sometimes badly scaled
warning('off','MATLAB:nearlySingularMatrix');

AppearanceData=struct;
% Get the landmark profiles for 3 image scales (for multiscale ASM)
for itt_res=1:options.nscales
    scale=1 / (2^(itt_res-1));
    if(options.verbose), disp(['Processing Data Scale : ' num2str(scale)]); drawnow; end
    % Get the pixel profiles of every landmark perpendicular to the contour
    if(options.verbose), disp('Get Intensity profiles'); drawnow; end
    for i=1:s
        pV = (TrainingData(i).Vertices)*scale;

        Ismall=imresize3d(TrainingData(i).I,scale,[],'linear','bound');
        nV = TrainingData(i).normalsV;

        [TrainingData(i).GrayProfiles,TrainingData(i).DerivativeGrayProfiles]=ASM_getProfileAndDerivatives3D(Ismall,pV,nV,options.k);
    end

    if(options.verbose),
        disp('Process Intensity profiles');
        figure, hold on;
        for i=1:s
            plot(mean(TrainingData(i).GrayProfiles,2),'Color',rand(1,3));
        end
        legend('1','2','3','4','5','6')
        title('Mean intensity profiles');
        drawnow;
    end

    % Profile length
    pl=options.k*2+1;

    % Calculate a covariance matrix for all landmarks
    PCAData=struct;
    for j=1:nl
        %% The orginal search method using Mahanobis distance with
        % edge gradient information
        dg=zeros(pl,s);
        for i=1:s, dg(:,i)=TrainingData(i).DerivativeGrayProfiles(:,j); end
        dg_mean=mean(dg,2);
        dg=dg-repmat(dg_mean,1,s);
        % Calculate the coveriance matrix and its inverse
        AppearanceData(itt_res).Landmarks(j).S = cov(dg');
        AppearanceData(itt_res).Landmarks(j).Sinv = inv(AppearanceData(itt_res).Landmarks(j).S);
        AppearanceData(itt_res).Landmarks(j).dg_mean = dg_mean;

        %% The new search method using PCA on intensities, and minimizing
        % parameters / the distance to the mean during the search.
        % Make a matrix with all intensities
        g=zeros(pl,s);
        for i=1:s, g(:,i)=TrainingData(i).GrayProfiles(:,j); end

        [Evalues, Evectors, Emean]=PCA(g);
        % Keep only 98% of all eigen vectors, (remove contour noise)
		i=find(cumsum(Evalues)>sum(Evalues)*0.98,1,'first');
        PCAData(j).Evectors= Evectors(:,1:i);
        PCAData(j).Evalues = Evalues(1:i);
        PCAData(j).Emean = Emean;

    end
    AppearanceData(itt_res).PCAData=PCAData;
end