text:
'''
Created 08/18/2014

@authors: Yifan Ning

@summary: Read csv file, which contains preferred term, UNII, NUI, preferredNameAndRole, Drug bank URI, ChEBI URI, rxnorm URI, OMOP id, DrOn id. To create rdf graph to represents active moieties.

'''

import sys
import time
sys.path = sys.path + ['.']

import re, codecs, uuid, datetime
import urllib2
import urllib
import traceback
import csv
import difflib
from rdflib import Graph, BNode, Literal, Namespace, URIRef, RDF, RDFS
from sets import Set

OUT_FILE = "activeMoietySub-in-rdf.xml"
ACTIVEMOIETY_BASE = "http://bio2rdf.org/linkedspls:"

CHEBI_BASE = "http://purl.obolibrary.org/obo/"
RXNORM_BASE = "http://purl.bioontology.org/ontology/RXNORM/"
DRUGBANK_CA = "http://www.drugbank.ca/drugs/"
DRUGBANK_BIO2RDF = "http://bio2rdf.org/drugbank:"
DRON_BASE = "http://purl.obolibrary.org/obo/"
NDFRT_BASE = "http://purl.bioontology.org/ontology/NDFRT/"
OHDSI_BASE = "http://purl.org/net/ohdsi#"

class DictItem:

   def __init__(self, pt, db_uri1, db_uri2, rxcui, omopid, chebi, dron, nui, nameAndRole):
      self.pt = str(pt)
      self.db_uri1 = str(db_uri1)
      self.db_uri2 = str(db_uri2)
      self.rxcui = str(rxcui)
      self.omopid = str(omopid)
      self.chebi = str(chebi)
      self.dron = str(dron)

      if nui and nameAndRole:
         self.drugClass = Set([str(nui)+'|'+str(nameAndRole)])
      else:
         self.drugClass = Set()

data_set = csv.DictReader(open("mergedActiveMoiety.csv","rb"), delimiter='\t')
dict_moieties = {}

## convert data from csv to dict (unii, items-object)

for item in data_set:

   if item["unii"] not in dict_moieties:
      moiety = DictItem(item["pt"], item["db_uri1"], item["db_uri2"], item["rxcui"], item["omopid"], item["chebi"], item["dron"], item["nui"], item["nameAndRole"])
      dict_moieties[item["unii"]]=moiety
      #print str(dict_moieties[item["unii"]].drugClass)

   else:
      if not dict_moieties[item["unii"]].pt and item["pt"]:
         dict_moieties[item["unii"]].pt = item["pt"]
      if not dict_moieties[item["unii"]].db_uri1 and item["db_uri1"]:
         dict_moieties[item["unii"]].db_uri1 = item["db_uri1"]
      if not dict_moieties[item["unii"]].db_uri2 and item["db_uri2"]:
         dict_moieties[item["unii"]].db_uri2 = item["db_uri2"]
      if not dict_moieties[item["unii"]].rxcui:
         dict_moieties[item["unii"]].rxcui = item["rxcui"]
      if not dict_moieties[item["unii"]].omopid:
         dict_moieties[item["unii"]].omopid = item["omopid"]
      if not dict_moieties[item["unii"]].chebi:
         dict_moieties[item["unii"]].chebi = item["chebi"]
      if not dict_moieties[item["unii"]].dron:
         dict_moieties[item["unii"]].dron = item["dron"]

      #print item['nui']+'|'+item['nameAndRole']

      if item['nui'] and item['nameAndRole']:
         if dict_moieties[item["unii"]].drugClass:
            dict_moieties[item["unii"]].drugClass.add(item['nui']+'|'+item['nameAndRole'])
         else:
            dict_moieties[item["unii"]].drugClass = Set(item['nui']+'|'+item['nameAndRole'])

## set up RDF graph
# identify namespaces for other ontologies to be used
dcterms = Namespace("http://purl.org/dc/terms/")
pav = Namespace("http://purl.org/pav")
dctypes = Namespace("http://purl.org/dc/dcmitype/")
linkedspls_vocabulary = Namespace('http://bio2rdf.org/linkedspls_vocabulary:')
sio = Namespace('http://semanticscience.org/resource/')
oa = Namespace('http://www.w3.org/ns/oa#')
cnt = Namespace('http://www.w3.org/2011/content#')
gcds = Namespace('http://www.genomic-cds.org/ont/genomic-cds.owl#')

siocns = Namespace('http://rdfs.org/sioc/ns#')
swande = Namespace('http://purl.org/swan/1.2/discourse-elements#')
dikbD2R = Namespace('http://dbmi-icode-01.dbmi.pitt.edu/dikb/vocab/resource/')
linkedspls = Namespace('file:///home/rdb20/Downloads/d2rq-0.8.1/linkedspls-dump.nt#structuredProductLabelMetadata/')
ncbit = Namespace('http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#')
dikbEvidence = Namespace('http://dbmi-icode-01.dbmi.pitt.edu/dikb-evidence/DIKB_evidence_ontology_v1.3.owl#')
ndfrt = Namespace('http://purl.bioontology.org/ontology/NDFRT/')
activemoiety = Namespace('http://purl.org/net/nlprepository/spl-active-moiety')

graph = Graph()

graph.namespace_manager.reset()
graph.namespace_manager.bind("dcterms", "http://purl.org/dc/terms/")
graph.namespace_manager.bind("pav",  "http://purl.org/pav");
graph.namespace_manager.bind("dctypes", "http://purl.org/dc/dcmitype/")

graph.namespace_manager.bind('linkedspls_vocabulary', 'http://bio2rdf.org/linkedspls_vocabulary:')

graph.namespace_manager.bind('sio', 'http://semanticscience.org/resource/')
graph.namespace_manager.bind('oa', 'http://www.w3.org/ns/oa#')
graph.namespace_manager.bind('cnt', 'http://www.w3.org/2011/content#')
graph.namespace_manager.bind('gcds','http://www.genomic-cds.org/ont/genomic-cds.owl#')

graph.namespace_manager.bind('siocns','http://rdfs.org/sioc/ns#')
graph.namespace_manager.bind('swande','http://purl.org/swan/1.2/discourse-elements#')
graph.namespace_manager.bind('dikbD2R','http://dbmi-icode-01.dbmi.pitt.edu/dikb/vocab/resource/')

graph.namespace_manager.bind('linkedspls','file:///home/rdb20/Downloads/d2rq-0.8.1/linkedspls-dump.nt#structuredProductLabelMetadata/')
graph.namespace_manager.bind('ncbit','http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#')
graph.namespace_manager.bind('dikbEvidence','http://dbmi-icode-01.dbmi.pitt.edu/dikb-evidence/DIKB_evidence_ontology_v1.3.owl#')
graph.namespace_manager.bind('ndfrt','http://purl.bioontology.org/ontology/NDFRT/')

graph.namespace_manager.bind('activemoiety','http://purl.org/net/nlprepository/spl-active-moiety')

## metadata

graph.add((URIRef(activemoiety), pav["createdBy"], Literal('Richard D. Boyce, PhD')))
graph.add((URIRef(activemoiety), pav["contributedBy"], Literal('Yifan Ning, MS')))
graph.add((URIRef(activemoiety), pav["createdOn"], Literal(time.strftime("%m/%d/%Y-%H:%M"))))
graph.add((URIRef(activemoiety), dcterms['publisher'], Literal("Department of Biomedical Informatics, University of Pittsburgh")))
graph.add((URIRef(activemoiety), dcterms['license'], URIRef("http://www.opendatacommons.org/licenses/by/1.0")))

index =1

for k,v in dict_moieties.items():

   # pt, unii, db_uri1, db_uri2, rxcui, omopid, chebi, dron, nui, nameAndRole

   graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), linkedspls_vocabulary["UNII"], Literal(k)))
   graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), RDFS.label, Literal(v.pt.strip())))
   graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), RDF.type, linkedspls_vocabulary["ActiveMoietyUNII"]))
   if v.rxcui:
      graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), linkedspls_vocabulary["RxCUI"], URIRef(RXNORM_BASE + str(int(float(v.rxcui))))))

   if v.chebi:
      graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), linkedspls_vocabulary["ChEBI"], URIRef(CHEBI_BASE + v.chebi)))

   if v.db_uri1:
      graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), linkedspls_vocabulary["x-drugbank"], URIRef(v.db_uri1)))
      graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), linkedspls_vocabulary["x-drugbank"], URIRef(v.db_uri2)))

   if v.omopid:
      graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), linkedspls_vocabulary["OMOPConceptId"], Literal(OHDSI_BASE + str(int(float(v.omopid))))))

   if v.dron:
      graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), linkedspls_vocabulary["DrOnId"], URIRef(DRON_BASE + v.dron)))

   if v.drugClass:

      for dc in v.drugClass:
         idx = dc.find('|')
         nui = dc[0:idx]
         dcStr = dc[idx+1:]

         dcGroup = None

         if '[PE]' in dcStr:
            dcGroup = "N0000009802"
         elif '[MoA]' in dcStr:
            dcGroup = "N0000000223"
         elif '[Chemical/Ingredient]' in dcStr:
            dcGroup = "N0000000002"
         elif '[EPC]' in dcStr:
            dcGroup = "N0000182631"

         if dcGroup:
            graph.add((URIRef(ACTIVEMOIETY_BASE + str(k)), ndfrt[dcGroup], ndfrt[nui]))

##display the graph
f = codecs.open(OUT_FILE,"w","utf8")
s = graph.serialize(format="xml",encoding="utf8")
f.write(unicode(s,errors='replace'))
print graph.serialize(format="xml")
f.close
graph.close()


text:
Image trimming tool for Machine Learning.

For trimming numerous, fixed size images from one image.

Xcode11 / Swift5.1 / macOS

Currently, it's specialized for binary classification.

## Usage

### Common
![Main Window](./Resources/main.png)

1. Drag and drop image onto the upper box.
1. Set output directories and file numbers to start from.
1. Set trim width and height.

### Trim manually
1. [Common](#common)
1. Set x and y(Input value, or just click image).
1. Trimming preview will be shown on the right box.
1. Press "Trim(P)" or "Trim(N)" button to trim and save positive/negative image.

Can zoom, scroll.

### Trim randomly
![Random trimming](./Resources/random.png)

1. [Common](#common)
1. Press "Random" button, then new window will open.
1. Randomly trimmed image will be shown, Press "Positive"/"Negative" button to save image.

## License
[MIT License](./LICENSE)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <fragment
            android:id="@+id/fragment_feedintelligenceselector"
            android:name="com.newsblur.fragment.FeedIntelligenceSelectorFragment"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:tag="feedIntelligenceSelector" />

        <fragment
            android:id="@+id/fragment_folderfeedlist"
            android:name="com.newsblur.fragment.FolderListFragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_above="@id/fragment_feedintelligenceselector"
            android:layout_alignParentTop="true"
            android:tag="folderFeedListFragment" />

        <View
            android:id="@+id/feedintelligenceselector_border"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:background="@color/midgray"
            android:layout_below="@id/fragment_folderfeedlist" />

        <TextView
            android:id="@+id/main_sync_status"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/fragment_feedintelligenceselector"
            android:padding="3dp"
            android:textSize="14sp"
            android:gravity="center"
            android:textColor="@color/status_overlay_text"
            android:background="@color/status_overlay_background"
            android:text="SYNC STATUS" />

    </RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>


text:
package org.me.PrivateSpark

import java.io.File

import org.apache.spark.launcher.SparkLauncher

class SparkRunner(_jar : String, _main : String, _outputPath : String) {

  def jar = _jar
  def main = _main
  def outputPath = _outputPath

  def start(): Unit = {
    val file = new File(outputPath)
    var launcher = new SparkLauncher()
      .setAppResource(jar)
      .setMainClass(main)
      .addJar("/Users/aheifetz/Dropbox/MIT Classes/Thesis/impl/code/spark-wrapper/target/scala-2.11/wrapper-2_2.11-1.0.jar")
      .setMaster("local")
      .setSparkHome("/Users/aheifetz/Dropbox/MIT Classes/Thesis/impl/code/spark-bin")
      .setAppName("DemoApp")
      .redirectOutput(file)
      .setConf(SparkLauncher.DRIVER_MEMORY, "2g")
      .startApplication()
  }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<link type="text/css" rel="stylesheet" href="../../page.css" />

[name]

		Use an array of [page:Bone bones] to create a skeleton that can be used by a [page:SkinnedMesh].
		WebGL only.

Example

		// Create a simple "arm"

		var bones = [];

		var shoulder = new THREE.Bone();
		var elbow = new THREE.Bone();
		var hand = new THREE.Bone();

		shoulder.add( elbow );
		elbow.add( hand );

		bones.push( shoulder );
		bones.push( elbow );
		bones.push( hand );

		shoulder.position.y = -5;
		elbow.position.y = 0;
		hand.position.y = 5;

		var armSkeleton = THREE.Skeleton( bones );

		// See THREE.SkinnedMesh for an example of usage with a mesh

Constructor

[name]( [page:Array bones], [page:Array boneInverses], [page:Boolean useVertexTexture]  )

		bones — The array of [page:bone bones]

		boneInverses — (optional) An array of [page:Matrix4 Matrix4s]

		useVertexTexture — (optional) Whether or not to use a vertex texture in the shader.

		The constructor automatically sets up all of the properties below.

Properties

[property:Array bones]

		The array of [page:bone bones]

[property:Boolean useVertexTexture]

		Whether or not to use a vertex texture in the shader, set in the constructor. Not all devices
		support floating point pixel textures. If this option is set then the bone matrices will be packed into
		a texture and sent to the shader. This method allows a much larger set of bones to be used. Otherwise
		the vertex shader will use uniforms, which do not allow for as many bones to be used. The exact
		numbers vary between devices.

[property:Array boneInverses]

		An array of [page:Matrix4 Matrix4s] that represent the inverse of the matrixWorld of the individual bones.

[property:Integer boneTextureWidth]

		The width of the vertex data texture.

[property:Integer boneTextureHeight]

		The height of the vertex data texture.

[property:Float32Array boneMatrices]

		The array buffer holding the bone data when using a vertex texture.

[property:DataTexture boneTexture]

		The [page:DataTexture] holding the bone data when using a vertex texture.

Methods

[method:null calculateInverses]()

Generates the boneInverses.

[method:null pose]()

Returns the skeleton to the base pose.

[method:null update]()

		Updates the [page:Float32Array boneMatrices] and [page:DataTexture boneTexture] after changing the bones.
		This is called automatically by the [page:WebGLRenderer] if the skeleton is used with a [page:SkinnedMesh].

[method:Skeleton clone]()

		Clone a Skeleton Object.

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
from simplexml import dumps
from flask import make_response, Flask
from flask_restplus import Api, Resource, fields

def output_xml(data, code, headers=None):
    """Makes a Flask response with a XML encoded body"""
    resp = make_response(dumps({'response': data}), code)
    resp.headers.extend(headers or {})
    return resp

app = Flask(__name__)
api = Api(app, default_mediatype='application/xml')
api.representations['application/xml'] = output_xml

hello_fields = api.model('Hello', {'entry': fields.String})

@api.route('/<string:entry>')
class Hello(Resource):
    """
        # you need requests
        >>> from requests import get
        >>> get('http://localhost:5000/me').content # default_mediatype
        '<?xml version="1.0" ?><response><hello>me</hello></response>'
        >>> get('http://localhost:5000/me', headers={"accept":"application/json"}).content
        '{"hello": "me"}'
        >>> get('http://localhost:5000/me', headers={"accept":"application/xml"}).content
        '<?xml version="1.0" ?><response><hello>me</hello></response>'
    """
    @api.doc(model=hello_fields, params={'entry': 'The entry to wrap'})
    def get(self, entry):
        '''Get a wrapped entry'''
        return {'hello': entry}

if __name__ == '__main__':
    app.run(debug=True)


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.07.24 at 05:36:05 PM EEST
//

package lt.registrucentras.esaskaita.service.invoice.ubl.sig;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import com.google.common.base.Objects;

/**
 *
Java class for SignatureMethodType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SignatureMethodType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="HMACOutputLength" type="{http://www.w3.org/2000/09/xmldsig#}HMACOutputLengthType" minOccurs="0"/>
 *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SignatureMethodType", propOrder = {
    "content"
})
public class SignatureMethodType implements Serializable
{

    private final static long serialVersionUID = 1L;
    @XmlElementRef(name = "HMACOutputLength", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class)
    @XmlMixed
    @XmlAnyElement(lax = true)
    protected List<Object> content;
    @XmlAttribute(name = "Algorithm", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String algorithm;

    /**
     * Default no-arg constructor
     *
     */
    public SignatureMethodType() {
        super();
    }

    /**
     * Fully-initialising value constructor
     *
     */
    public SignatureMethodType(final List<Object> content, final String algorithm) {
        this.content = content;
        this.algorithm = algorithm;
    }

    /**
     * Gets the value of the content property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the content property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getContent().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link JAXBElement }{@code <}{@link BigInteger }{@code >}
     * {@link Object }
     * {@link String }
     *
     *
     */
    public List<Object> getContent() {
        if (content == null) {
            content = new ArrayList<Object>();
        }
        return this.content;
    }

    /**
     * Gets the value of the algorithm property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAlgorithm() {
        return algorithm;
    }

    /**
     * Sets the value of the algorithm property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAlgorithm(String value) {
        this.algorithm = value;
    }

    public SignatureMethodType withContent(Object... values) {
        if (values!= null) {
            for (Object value: values) {
                getContent().add(value);
            }
        }
        return this;
    }

    public SignatureMethodType withContent(Collection<Object> values) {
        if (values!= null) {
            getContent().addAll(values);
        }
        return this;
    }

    public SignatureMethodType withAlgorithm(String value) {
        setAlgorithm(value);
        return this;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this).add("content", content).add("algorithm", algorithm).toString();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(content, algorithm);
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null) {
            return false;
        }
        if (getClass()!= other.getClass()) {
            return false;
        }
        final SignatureMethodType o = ((SignatureMethodType) other);
        return (Objects.equal(content, o.content)&&Objects.equal(algorithm, o.algorithm));
    }

}


text:
package org.onosproject.workflow.api;

import org.onosproject.event.Event;

/**
 * Functional interface for delivering event hint supplier.
 */
@FunctionalInterface
public interface EventHintSupplier {
    String apply(Event event);
}


text:
package grpc

import (
	"errors"
	"fmt"
	"net"
	"strings"
	"sync"
	"time"

	"golang.org/x/net/context"
	"golang.org/x/net/trace"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/transport"
)

var (
	// ErrClientConnClosing indicates that the operation is illegal because
	// the ClientConn is closing.
	ErrClientConnClosing = errors.New("grpc: the client connection is closing")
	// ErrClientConnTimeout indicates that the ClientConn cannot establish the
	// underlying connections within the specified timeout.
	ErrClientConnTimeout = errors.New("grpc: timed out when dialing")

	// errNoTransportSecurity indicates that there is no transport security
	// being set for ClientConn. Users should either set one or explicitly
	// call WithInsecure DialOption to disable security.
	errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)")
	// errTransportCredentialsMissing indicates that users want to transmit security
	// information (e.g., oauth2 token) which requires secure connection on an insecure
	// connection.
	errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)")
	// errCredentialsConflict indicates that grpc.WithTransportCredentials()
	// and grpc.WithInsecure() are both called for a connection.
	errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)")
	// errNetworkIP indicates that the connection is down due to some network I/O error.
	errNetworkIO = errors.New("grpc: failed with network I/O error")
	// errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs.
	errConnDrain = errors.New("grpc: the connection is drained")
	// errConnClosing indicates that the connection is closing.
	errConnClosing = errors.New("grpc: the connection is closing")
	errNoAddr      = errors.New("grpc: there is no address available to dial")
	// minimum time to give a connection to complete
	minConnectTimeout = 20 * time.Second
)

// dialOptions configure a Dial call. dialOptions are set by the DialOption
// values passed to Dial.
type dialOptions struct {
	codec    Codec
	cp       Compressor
	dc       Decompressor
	bs       backoffStrategy
	balancer Balancer
	block    bool
	insecure bool
	timeout  time.Duration
	copts    transport.ConnectOptions
}

// DialOption configures how we set up the connection.
type DialOption func(*dialOptions)

// WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
func WithCodec(c Codec) DialOption {
	return func(o *dialOptions) {
		o.codec = c
	}
}

// WithCompressor returns a DialOption which sets a CompressorGenerator for generating message
// compressor.
func WithCompressor(cp Compressor) DialOption {
	return func(o *dialOptions) {
		o.cp = cp
	}
}

// WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating
// message decompressor.
func WithDecompressor(dc Decompressor) DialOption {
	return func(o *dialOptions) {
		o.dc = dc
	}
}

// WithBalancer returns a DialOption which sets a load balancer.
func WithBalancer(b Balancer) DialOption {
	return func(o *dialOptions) {
		o.balancer = b
	}
}

// WithBackoffMaxDelay configures the dialer to use the provided maximum delay
// when backing off after failed connection attempts.
func WithBackoffMaxDelay(md time.Duration) DialOption {
	return WithBackoffConfig(BackoffConfig{MaxDelay: md})
}

// WithBackoffConfig configures the dialer to use the provided backoff
// parameters after connection failures.
//
// Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up
// for use.
func WithBackoffConfig(b BackoffConfig) DialOption {
	// Set defaults to ensure that provided BackoffConfig is valid and
	// unexported fields get default values.
	setDefaults(&b)
	return withBackoff(b)
}

// withBackoff sets the backoff strategy used for retries after a
// failed connection attempt.
//
// This can be exported if arbitrary backoff strategies are allowed by gRPC.
func withBackoff(bs backoffStrategy) DialOption {
	return func(o *dialOptions) {
		o.bs = bs
	}
}

// WithBlock returns a DialOption which makes caller of Dial blocks until the underlying
// connection is up. Without this, Dial returns immediately and connecting the server
// happens in background.
func WithBlock() DialOption {
	return func(o *dialOptions) {
		o.block = true
	}
}

// WithInsecure returns a DialOption which disables transport security for this ClientConn.
// Note that transport security is required unless WithInsecure is set.
func WithInsecure() DialOption {
	return func(o *dialOptions) {
		o.insecure = true
	}
}

// WithTransportCredentials returns a DialOption which configures a
// connection level security credentials (e.g., TLS/SSL).
func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
	return func(o *dialOptions) {
		o.copts.TransportCredentials = creds
	}
}

// WithPerRPCCredentials returns a DialOption which sets
// credentials which will place auth state on each outbound RPC.
func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
	return func(o *dialOptions) {
		o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
	}
}

// WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn
// initially. This is valid if and only if WithBlock() is present.
func WithTimeout(d time.Duration) DialOption {
	return func(o *dialOptions) {
		o.timeout = d
	}
}

// WithDialer returns a DialOption that specifies a function to use for dialing network addresses.
func WithDialer(f func(addr string, timeout time.Duration) (net.Conn, error)) DialOption {
	return func(o *dialOptions) {
		o.copts.Dialer = f
	}
}

// WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.
func WithUserAgent(s string) DialOption {
	return func(o *dialOptions) {
		o.copts.UserAgent = s
	}
}

// Dial creates a client connection the given target.
func Dial(target string, opts ...DialOption) (*ClientConn, error) {
	cc := &ClientConn{
		target: target,
		conns:  make(map[Address]*addrConn),
	}
	for _, opt := range opts {
		opt(&cc.dopts)
	}
	if cc.dopts.codec == nil {
		// Set the default codec.
		cc.dopts.codec = protoCodec{}
	}

	if cc.dopts.bs == nil {
		cc.dopts.bs = DefaultBackoffConfig
	}

	cc.balancer = cc.dopts.balancer
	if cc.balancer == nil {
		cc.balancer = RoundRobin(nil)
	}
	if err := cc.balancer.Start(target); err != nil {
		return nil, err
	}
	var (
		ok    bool
		addrs []Address
	)
	ch := cc.balancer.Notify()
	if ch == nil {
		// There is no name resolver installed.
		addrs = append(addrs, Address{Addr: target})
	} else {
		addrs, ok = <-ch
		if !ok || len(addrs) == 0 {
			return nil, errNoAddr
		}
	}
	waitC := make(chan error, 1)
	go func() {
		for _, a := range addrs {
			if err := cc.newAddrConn(a, false); err != nil {
				waitC <- err
				return
			}
		}
		close(waitC)
	}()
	var timeoutCh <-chan time.Time
	if cc.dopts.timeout > 0 {
		timeoutCh = time.After(cc.dopts.timeout)
	}
	select {
	case err := <-waitC:
		if err != nil {
			cc.Close()
			return nil, err
		}
	case <-timeoutCh:
		cc.Close()
		return nil, ErrClientConnTimeout
	}
	if ok {
		go cc.lbWatcher()
	}
	colonPos := strings.LastIndex(target, ":")
	if colonPos == -1 {
		colonPos = len(target)
	}
	cc.authority = target[:colonPos]
	return cc, nil
}

// ConnectivityState indicates the state of a client connection.
type ConnectivityState int

const (
	// Idle indicates the ClientConn is idle.
	Idle ConnectivityState = iota
	// Connecting indicates the ClienConn is connecting.
	Connecting
	// Ready indicates the ClientConn is ready for work.
	Ready
	// TransientFailure indicates the ClientConn has seen a failure but expects to recover.
	TransientFailure
	// Shutdown indicates the ClientConn has started shutting down.
	Shutdown
)

func (s ConnectivityState) String() string {
	switch s {
	case Idle:
		return "IDLE"
	case Connecting:
		return "CONNECTING"
	case Ready:
		return "READY"
	case TransientFailure:
		return "TRANSIENT_FAILURE"
	case Shutdown:
		return "SHUTDOWN"
	default:
		panic(fmt.Sprintf("unknown connectivity state: %d", s))
	}
}

// ClientConn represents a client connection to an RPC server.
type ClientConn struct {
	target    string
	balancer  Balancer
	authority string
	dopts     dialOptions

	mu    sync.RWMutex
	conns map[Address]*addrConn
}

func (cc *ClientConn) lbWatcher() {
	for addrs := range cc.balancer.Notify() {
		var (
			add []Address   // Addresses need to setup connections.
			del []*addrConn // Connections need to tear down.
		)
		cc.mu.Lock()
		for _, a := range addrs {
			if _, ok := cc.conns[a]; !ok {
				add = append(add, a)
			}
		}
		for k, c := range cc.conns {
			var keep bool
			for _, a := range addrs {
				if k == a {
					keep = true
					break
				}
			}
			if !keep {
				del = append(del, c)
			}
		}
		cc.mu.Unlock()
		for _, a := range add {
			cc.newAddrConn(a, true)
		}
		for _, c := range del {
			c.tearDown(errConnDrain)
		}
	}
}

func (cc *ClientConn) newAddrConn(addr Address, skipWait bool) error {
	ac := &addrConn{
		cc:           cc,
		addr:         addr,
		dopts:        cc.dopts,
		shutdownChan: make(chan struct{}),
	}
	if EnableTracing {
		ac.events = trace.NewEventLog("grpc.ClientConn", ac.addr.Addr)
	}
	if !ac.dopts.insecure {
		if ac.dopts.copts.TransportCredentials == nil {
			return errNoTransportSecurity
		}
	} else {
		if ac.dopts.copts.TransportCredentials != nil {
			return errCredentialsConflict
		}
		for _, cd := range ac.dopts.copts.PerRPCCredentials {
			if cd.RequireTransportSecurity() {
				return errTransportCredentialsMissing
			}
		}
	}
	// Insert ac into ac.cc.conns. This needs to be done before any getTransport(...) is called.
	ac.cc.mu.Lock()
	if ac.cc.conns == nil {
		ac.cc.mu.Unlock()
		return ErrClientConnClosing
	}
	stale := ac.cc.conns[ac.addr]
	ac.cc.conns[ac.addr] = ac
	ac.cc.mu.Unlock()
	if stale != nil {
		// There is an addrConn alive on ac.addr already. This could be due to
		// i) stale's Close is undergoing;
		// ii) a buggy Balancer notifies duplicated Addresses.
		stale.tearDown(errConnDrain)
	}
	ac.stateCV = sync.NewCond(&ac.mu)
	// skipWait may overwrite the decision in ac.dopts.block.
	if ac.dopts.block && !skipWait {
		if err := ac.resetTransport(false); err != nil {
			ac.tearDown(err)
			return err
		}
		// Start to monitor the error status of transport.
		go ac.transportMonitor()
	} else {
		// Start a goroutine connecting to the server asynchronously.
		go func() {
			if err := ac.resetTransport(false); err != nil {
				grpclog.Printf("Failed to dial %s: %v; please retry.", ac.addr.Addr, err)
				ac.tearDown(err)
				return
			}
			ac.transportMonitor()
		}()
	}
	return nil
}

func (cc *ClientConn) getTransport(ctx context.Context, opts BalancerGetOptions) (transport.ClientTransport, func(), error) {
	// TODO(zhaoq): Implement fail-fast logic.
	addr, put, err := cc.balancer.Get(ctx, opts)
	if err != nil {
		return nil, nil, err
	}
	cc.mu.RLock()
	if cc.conns == nil {
		cc.mu.RUnlock()
		return nil, nil, ErrClientConnClosing
	}
	ac, ok := cc.conns[addr]
	cc.mu.RUnlock()
	if !ok {
		if put != nil {
			put()
		}
		return nil, nil, transport.StreamErrorf(codes.Internal, "grpc: failed to find the transport to send the rpc")
	}
	t, err := ac.wait(ctx)
	if err != nil {
		if put != nil {
			put()
		}
		return nil, nil, err
	}
	return t, put, nil
}

// Close tears down the ClientConn and all underlying connections.
func (cc *ClientConn) Close() error {
	cc.mu.Lock()
	if cc.conns == nil {
		cc.mu.Unlock()
		return ErrClientConnClosing
	}
	conns := cc.conns
	cc.conns = nil
	cc.mu.Unlock()
	cc.balancer.Close()
	for _, ac := range conns {
		ac.tearDown(ErrClientConnClosing)
	}
	return nil
}

// addrConn is a network connection to a given address.
type addrConn struct {
	cc           *ClientConn
	addr         Address
	dopts        dialOptions
	shutdownChan chan struct{}
	events       trace.EventLog

	mu      sync.Mutex
	state   ConnectivityState
	stateCV *sync.Cond
	down    func(error) // the handler called when a connection is down.
	// ready is closed and becomes nil when a new transport is up or failed
	// due to timeout.
	ready     chan struct{}
	transport transport.ClientTransport
}

// printf records an event in ac's event log, unless ac has been closed.
// REQUIRES ac.mu is held.
func (ac *addrConn) printf(format string, a ...interface{}) {
	if ac.events != nil {
		ac.events.Printf(format, a...)
	}
}

// errorf records an error in ac's event log, unless ac has been closed.
// REQUIRES ac.mu is held.
func (ac *addrConn) errorf(format string, a ...interface{}) {
	if ac.events != nil {
		ac.events.Errorf(format, a...)
	}
}

// getState returns the connectivity state of the Conn
func (ac *addrConn) getState() ConnectivityState {
	ac.mu.Lock()
	defer ac.mu.Unlock()
	return ac.state
}

// waitForStateChange blocks until the state changes to something other than the sourceState.
func (ac *addrConn) waitForStateChange(ctx context.Context, sourceState ConnectivityState) (ConnectivityState, error) {
	ac.mu.Lock()
	defer ac.mu.Unlock()
	if sourceState != ac.state {
		return ac.state, nil
	}
	done := make(chan struct{})
	var err error
	go func() {
		select {
		case <-ctx.Done():
			ac.mu.Lock()
			err = ctx.Err()
			ac.stateCV.Broadcast()
			ac.mu.Unlock()
		case <-done:
		}
	}()
	defer close(done)
	for sourceState == ac.state {
		ac.stateCV.Wait()
		if err != nil {
			return ac.state, err
		}
	}
	return ac.state, nil
}

func (ac *addrConn) resetTransport(closeTransport bool) error {
	var retries int
	for {
		ac.mu.Lock()
		ac.printf("connecting")
		if ac.state == Shutdown {
			// ac.tearDown(...) has been invoked.
			ac.mu.Unlock()
			return errConnClosing
		}
		if ac.down != nil {
			ac.down(downErrorf(false, true, "%v", errNetworkIO))
			ac.down = nil
		}
		ac.state = Connecting
		ac.stateCV.Broadcast()
		t := ac.transport
		ac.mu.Unlock()
		if closeTransport && t != nil {
			t.Close()
		}
		sleepTime := ac.dopts.bs.backoff(retries)
		ac.dopts.copts.Timeout = sleepTime
		if sleepTime < minConnectTimeout {
			ac.dopts.copts.Timeout = minConnectTimeout
		}
		connectTime := time.Now()
		newTransport, err := transport.NewClientTransport(ac.addr.Addr, &ac.dopts.copts)
		if err != nil {
			ac.mu.Lock()
			if ac.state == Shutdown {
				// ac.tearDown(...) has been invoked.
				ac.mu.Unlock()
				return errConnClosing
			}
			ac.errorf("transient failure: %v", err)
			ac.state = TransientFailure
			ac.stateCV.Broadcast()
			if ac.ready != nil {
				close(ac.ready)
				ac.ready = nil
			}
			ac.mu.Unlock()
			sleepTime -= time.Since(connectTime)
			if sleepTime < 0 {
				sleepTime = 0
			}
			closeTransport = false
			select {
			case <-time.After(sleepTime):
			case <-ac.shutdownChan:
			}
			retries++
			grpclog.Printf("grpc: addrConn.resetTransport failed to create client transport: %v; Reconnecting to %q", err, ac.addr)
			continue
		}
		ac.mu.Lock()
		ac.printf("ready")
		if ac.state == Shutdown {
			// ac.tearDown(...) has been invoked.
			ac.mu.Unlock()
			newTransport.Close()
			return errConnClosing
		}
		ac.state = Ready
		ac.stateCV.Broadcast()
		ac.transport = newTransport
		if ac.ready != nil {
			close(ac.ready)
			ac.ready = nil
		}
		ac.down = ac.cc.balancer.Up(ac.addr)
		ac.mu.Unlock()
		return nil
	}
}

// Run in a goroutine to track the error in transport and create the
// new transport if an error happens. It returns when the channel is closing.
func (ac *addrConn) transportMonitor() {
	for {
		ac.mu.Lock()
		t := ac.transport
		ac.mu.Unlock()
		select {
		// shutdownChan is needed to detect the teardown when
		// the addrConn is idle (i.e., no RPC in flight).
		case <-ac.shutdownChan:
			return
		case <-t.Error():
			ac.mu.Lock()
			if ac.state == Shutdown {
				// ac.tearDown(...) has been invoked.
				ac.mu.Unlock()
				return
			}
			ac.state = TransientFailure
			ac.stateCV.Broadcast()
			ac.mu.Unlock()
			if err := ac.resetTransport(true); err != nil {
				ac.mu.Lock()
				ac.printf("transport exiting: %v", err)
				ac.mu.Unlock()
				grpclog.Printf("grpc: addrConn.transportMonitor exits due to: %v", err)
				return
			}
		}
	}
}

// wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed.
func (ac *addrConn) wait(ctx context.Context) (transport.ClientTransport, error) {
	for {
		ac.mu.Lock()
		switch {
		case ac.state == Shutdown:
			ac.mu.Unlock()
			return nil, errConnClosing
		case ac.state == Ready:
			ct := ac.transport
			ac.mu.Unlock()
			return ct, nil
		default:
			ready := ac.ready
			if ready == nil {
				ready = make(chan struct{})
				ac.ready = ready
			}
			ac.mu.Unlock()
			select {
			case <-ctx.Done():
				return nil, transport.ContextErr(ctx.Err())
			// Wait until the new transport is ready or failed.
			case <-ready:
			}
		}
	}
}

// tearDown starts to tear down the addrConn.
// TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in
// some edge cases (e.g., the caller opens and closes many addrConn's in a
// tight loop.
func (ac *addrConn) tearDown(err error) {
	ac.mu.Lock()
	defer func() {
		ac.mu.Unlock()
		ac.cc.mu.Lock()
		if ac.cc.conns != nil {
			delete(ac.cc.conns, ac.addr)
		}
		ac.cc.mu.Unlock()
	}()
	if ac.state == Shutdown {
		return
	}
	ac.state = Shutdown
	if ac.down != nil {
		ac.down(downErrorf(false, false, "%v", err))
		ac.down = nil
	}
	ac.stateCV.Broadcast()
	if ac.events != nil {
		ac.events.Finish()
		ac.events = nil
	}
	if ac.ready != nil {
		close(ac.ready)
		ac.ready = nil
	}
	if ac.transport != nil {
		if err == errConnDrain {
			ac.transport.GracefulClose()
		} else {
			ac.transport.Close()
		}
	}
	if ac.shutdownChan != nil {
		close(ac.shutdownChan)
	}
	return
}


text:
import requests
import sys
import argparse
from os import remove, mkdir, rename, listdir, getcwd
from shutil import rmtree

cwd = getcwd()
documentsIndex = cwd.index("Documents")
documentsIndex += len("Documents")
ROOT = cwd[:documentsIndex]

class stansi: # Collection of Stash's ANSI escape codes.
	bold = u"\x9b1m"
	underscore = u"\x9b4m"
	attr_end = u"\x9b0m"

	fore_red = u"\x9b31m"
	fore_green = u"\x9b32m"
	fore_brown = u"\x9b33m"
	fore_blue = u"\x9b34m"
	fore_pink = u"\x9b35m"
	fore_cyan = u"\x9b36m"
	fore_white = u"\x9b37m"
	fore_end = u"\x9b39m"

	back_red = u"\x9b41m"
	back_green = u"\x9b42m"
	back_brown = u"\x9b43m"
	back_blue = u"\x9b44m"
	back_pink = u"\x9b45m"
	back_cyan = u"\x9b46m"
	back_white = u"\x9b47m"
	back_end = u"\x9b49m"

def Red(text):
	return stansi.fore_red+text+stansi.fore_end
def Blue(text):
	return stansi.fore_blue+text+stansi.fore_end
def Green(text):
	return stansi.fore_green+text+stansi.fore_end
def Cyan(text):
	return stansi.fore_cyan+text+stansi.fore_end

class SWConfig (object): # Parser for the config files such as the repository listing.
	def __init__(self, content):
		self.data = {}
		for line in content.splitlines():
			key = line.split("=")[0]
			value = line.split("=")[1]
			self.data[key] = value

	def __getitem__(self, key):
		return self.data[key]

	def keys(self):
		return self.data.keys()

def download_package(url, package_name): # Handles the installation of packages directories (since they're no longer tarfiles)
	content_listing = ["bin.py", "meta.latte"]
	mkdir(ROOT+"/"+package_name)
	for item in content_listing:
		requested = requests.get(url+"/"+package_name+"/"+item)
		content = requested.text
		requested.close()
		if content == "404: Not Found\n":
			print(Red("ERROR") + ": Package not found.")
			sys.exit()
		opened = open(ROOT+"/"+package_name+"/"+item, "w")
		opened.write(content)
		opened.close()

def main(sargs):
	parser = argparse.ArgumentParser()
	parser.add_argument("method", help="What action to perform (install, remove, etc)", type=str)
	parser.add_argument("package", help="Name of package", type=str)
	args = parser.parse_args(sargs)

	try:
		opened = open(".latte-repos.swconf", "r")
		opened.close()
	except:
		opened = open(".latte-repos.swconf", "w")
		print(Red("WARNING") + ": Repository listing doesn't exist, rebuilding to default...")
		opened.write("universe=https://raw.githubusercontent.com/Seanld/latte-universe/master")
		opened.close()

	repo_listing_opened = open(".latte-repos.swconf", "r")
	listing_content = repo_listing_opened.read()
	repo_listing_opened.close()
	REPOSITORIES = SWConfig(listing_content)

	if args.method == "install":
		packageSplitted = args.package.split("/")
		try:
			package_name = packageSplitted[1]
			repo_to_use = REPOSITORIES[packageSplitted[0]]
		except IndexError:

			repo_to_use = REPOSITORIES["universe"]
			package_name = packageSplitted[0]
		print(Red("WARNING") + ": No repository specified, using universe by default...")
		try:
			download_package(repo_to_use, package_name)
		except:
			stoutput("ERROR", "Couldn't find package", "error")
			sys.exit()
		# Move to correct locations
		print("Installing")
		try:
			rename(ROOT+"/"+package_name+"/meta.latte", ROOT+"/stash_extensions/latte/"+package_name+".latte")
		except:
			mkdir(ROOT+"/stash_extensions/latte")
			rename(ROOT+"/"+package_name+"/meta.latte", ROOT+"/stash_extensions/latte/"+package_name+".latte")
		rename(ROOT+"/"+package_name+"/bin.py", ROOT+"/stash_extensions/bin/"+package_name+".py")
		rmtree(ROOT+"/"+package_name)
		print(Green("SUCCESS") + ": Package '"+package_name+"' successfully installed!")
	elif args.method == "remove":
		try:
			remove(ROOT+"/stash_extensions/bin/"+args.package+".py")
			remove(ROOT+"/stash_extensions/latte/"+args.package+".latte")
		except:
			print(Red("ERROR") + ": Couldn't remove package; not found in resources.")
			sys.exit()
		print(Green("SUCCESS") + ": '"+args.package+"' removed!")
	elif args.method == "update":
		print("Jeez! Sorry, but we are currently working on self-update capabilities. For now, just redo the install process to update.")
	elif args.method == "new":
		try:
			mkdir(args.package)
			config = open(args.package+"/meta.latte", "w")
			config.write("developer=Your name here\ndescription=Enter description of your app here\nversion=0.1")
			config.close()
			index = open(args.package+"/bin.py", "w")
			index.write("# This is just an example template. You can change this all you like.\n\nimport sys\nimport argparse\n\ndef main(sargs):\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('echo', help='What you want the command to echo back.')\n\targs = parser.parse_args(sargs)\n\t\n\tprint('Echoing back: '+args.echo)\n\nif __name__ == '__main__':\n\tmain(sys.argv[1:])")
			index.close()
			print(Green("SUCCESS") + ": Package '"+args.package+"' generated, check current working directory!")
		except:
			print(Red("ERROR") + ": Couldn't generate package; directory may already exist.")
	elif args.method == "add-repo":
		try:
			request = requests.get(args.package+"/init.latte")
			data = request.text
			request.close()
			data_org = SWConfig(data)
			nickname = data_org["NICKNAME"]
			repo_listing = open(".latte-repos.swconf", "a")
			repo_listing.write("\n"+nickname+"="+args.package)
			repo_listing.close()
			print(Green("SUCCESS") + ": '"+nickname+"' added to repositories!")
		except:
			print(Red("ERROR") + ": Either repository doesn't exist, or does not contain an 'init.latte' file.")
	elif args.method == "list-repos":
		if args.package == "all":
			opened = open(".latte-repos.swconf")
			content = opened.read()
			opened.close()
			as_config = SWConfig(content)
			for repo in as_config.keys():
				print(Cyan(repo) + ": " + Green(as_config[repo]))
	else:
		print(Red("ERROR") + ": Unknown command '"+args.method+"'!")

if __name__ == "__main__":
	main(sys.argv[1:])


text:
var Notification = Dialog.extend({
  className: 'dialog dialog--notification',

  events: {
    click: 'dismiss'
  }
});


text:
package net.sf.esfinge.metadata.locate.conventions.annotations;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(ANNOTATION_TYPE)
public @interface ContainsParameterTypeConvention {

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Login - COLL MZ</title>
    {{template "header"}}
    <link rel="stylesheet" type="text/css" href="/assets/css/login.css">

            Coll MZ System

            <form class="ui large form" action="/action-login" method="post">

                            <input type="text" name="email" placeholder="用户名(email)">

                            <input type="password" name="password" placeholder="密码">

登录

            </form>

    {{template "footer"}}


text:
/**
 * An index contains the built index of all documents and provides a query interface
 * to the index.
 *
 * Usually instances of lunr.Index will not be created using this constructor, instead
 * lunr.Builder should be used to construct new indexes, or lunr.Index.load should be
 * used to load previously built and serialized indexes.
 *
 * @constructor
 * @param {Object} attrs - The attributes of the built search index.
 * @param {Object} attrs.invertedIndex - An index of term/field to document reference.
 * @param {Object<string, lunr.Vector>} attrs.fieldVectors - Field vectors
 * @param {lunr.TokenSet} attrs.tokenSet - An set of all corpus tokens.
 * @param {string[]} attrs.fields - The names of indexed document fields.
 * @param {lunr.Pipeline} attrs.pipeline - The pipeline to use for search terms.
 */
lunr.Index = function (attrs) {
  this.invertedIndex = attrs.invertedIndex
  this.fieldVectors = attrs.fieldVectors
  this.tokenSet = attrs.tokenSet
  this.fields = attrs.fields
  this.pipeline = attrs.pipeline
}

/**
 * A result contains details of a document matching a search query.
 * @typedef {Object} lunr.Index~Result
 * @property {string} ref - The reference of the document this result represents.
 * @property {number} score - A number between 0 and 1 representing how similar this document is to the query.
 * @property {lunr.MatchData} matchData - Contains metadata about this match including which term(s) caused the match.
 */

/**
 * Although lunr provides the ability to create queries using lunr.Query, it also provides a simple
 * query language which itself is parsed into an instance of lunr.Query.
 *
 * For programmatically building queries it is advised to directly use lunr.Query, the query language
 * is best used for human entered text rather than program generated text.
 *
 * At its simplest queries can just be a single term, e.g. `hello`, multiple terms are also supported
 * and will be combined with OR, e.g `hello world` will match documents that contain either 'hello'
 * or 'world', though those that contain both will rank higher in the results.
 *
 * Wildcards can be included in terms to match one or more unspecified characters, these wildcards can
 * be inserted anywhere within the term, and more than one wildcard can exist in a single term. Adding
 * wildcards will increase the number of documents that will be found but can also have a negative
 * impact on query performance, especially with wildcards at the beginning of a term.
 *
 * Terms can be restricted to specific fields, e.g. `title:hello`, only documents with the term
 * hello in the title field will match this query. Using a field not present in the index will lead
 * to an error being thrown.
 *
 * Modifiers can also be added to terms, lunr supports edit distance and boost modifiers on terms. A term
 * boost will make documents matching that term score higher, e.g. `foo^5`. Edit distance is also supported
 * to provide fuzzy matching, e.g. 'hello~2' will match documents with hello with an edit distance of 2.
 * Avoid large values for edit distance to improve query performance.
 *
 * Each term also supports a presence modifier. By default a term's presence in document is optional, however
 * this can be changed to either required or prohibited. For a term's presence to be required in a document the
 * term should be prefixed with a '+', e.g. `+foo bar` is a search for documents that must contain 'foo' and
 * optionally contain 'bar'. Conversely a leading '-' sets the terms presence to prohibited, i.e. it must not
 * appear in a document, e.g. `-foo bar` is a search for documents that do not contain 'foo' but may contain 'bar'.
 *
 * To escape special characters the backslash character '\' can be used, this allows searches to include
 * characters that would normally be considered modifiers, e.g. `foo\~2` will search for a term "foo~2" instead
 * of attempting to apply a boost of 2 to the search term "foo".
 *
 * @typedef {string} lunr.Index~QueryString
 * @example
Simple single term query

 * hello
 * @example
Multiple term query

 * hello world
 * @example
term scoped to a field

 * title:hello
 * @example
term with a boost of 10

 * hello^10
 * @example
term with an edit distance of 2

 * hello~2
 * @example
terms with presence modifiers

 * -foo +bar baz
 */

/**
 * Performs a search against the index using lunr query syntax.
 *
 * Results will be returned sorted by their score, the most relevant results
 * will be returned first.  For details on how the score is calculated, please see
 * the {@link https://lunrjs.com/guides/searching.html#scoring|guide}.
 *
 * For more programmatic querying use lunr.Index#query.
 *
 * @param {lunr.Index~QueryString} queryString - A string containing a lunr query.
 * @throws {lunr.QueryParseError} If the passed query string cannot be parsed.
 * @returns {lunr.Index~Result[]}
 */
lunr.Index.prototype.search = function (queryString) {
  return this.query(function (query) {
    var parser = new lunr.QueryParser(queryString, query)
    parser.parse()
  })
}

/**
 * A query builder callback provides a query object to be used to express
 * the query to perform on the index.
 *
 * @callback lunr.Index~queryBuilder
 * @param {lunr.Query} query - The query object to build up.
 * @this lunr.Query
 */

/**
 * Performs a query against the index using the yielded lunr.Query object.
 *
 * If performing programmatic queries against the index, this method is preferred
 * over lunr.Index#search so as to avoid the additional query parsing overhead.
 *
 * A query object is yielded to the supplied function which should be used to
 * express the query to be run against the index.
 *
 * Note that although this function takes a callback parameter it is _not_ an
 * asynchronous operation, the callback is just yielded a query object to be
 * customized.
 *
 * @param {lunr.Index~queryBuilder} fn - A function that is used to build the query.
 * @returns {lunr.Index~Result[]}
 */
lunr.Index.prototype.query = function (fn) {
  // for each query clause
  // * process terms
  // * expand terms from token set
  // * find matching documents and metadata
  // * get document vectors
  // * score documents

  var query = new lunr.Query(this.fields),
      matchingFields = Object.create(null),
      queryVectors = Object.create(null),
      termFieldCache = Object.create(null),
      requiredMatches = Object.create(null),
      prohibitedMatches = Object.create(null)

  /*
   * To support field level boosts a query vector is created per
   * field. An empty vector is eagerly created to support negated
   * queries.
   */
  for (var i = 0; i < this.fields.length; i++) {
    queryVectors[this.fields[i]] = new lunr.Vector
  }

  fn.call(query, query)

  for (var i = 0; i < query.clauses.length; i++) {
    /*
     * Unless the pipeline has been disabled for this term, which is
     * the case for terms with wildcards, we need to pass the clause
     * term through the search pipeline. A pipeline returns an array
     * of processed terms. Pipeline functions may expand the passed
     * term, which means we may end up performing multiple index lookups
     * for a single query term.
     */
    var clause = query.clauses[i],
        terms = null,
        clauseMatches = lunr.Set.complete

    if (clause.usePipeline) {
      terms = this.pipeline.runString(clause.term, {
        fields: clause.fields
      })
    } else {
      terms = [clause.term]
    }

    for (var m = 0; m < terms.length; m++) {
      var term = terms[m]

      /*
       * Each term returned from the pipeline needs to use the same query
       * clause object, e.g. the same boost and or edit distance. The
       * simplest way to do this is to re-use the clause object but mutate
       * its term property.
       */
      clause.term = term

      /*
       * From the term in the clause we create a token set which will then
       * be used to intersect the indexes token set to get a list of terms
       * to lookup in the inverted index
       */
      var termTokenSet = lunr.TokenSet.fromClause(clause),
          expandedTerms = this.tokenSet.intersect(termTokenSet).toArray()

      /*
       * If a term marked as required does not exist in the tokenSet it is
       * impossible for the search to return any matches. We set all the field
       * scoped required matches set to empty and stop examining any further
       * clauses.
       */
      if (expandedTerms.length === 0 && clause.presence === lunr.Query.presence.REQUIRED) {
        for (var k = 0; k < clause.fields.length; k++) {
          var field = clause.fields[k]
          requiredMatches[field] = lunr.Set.empty
        }

        break
      }

      for (var j = 0; j < expandedTerms.length; j++) {
        /*
         * For each term get the posting and termIndex, this is required for
         * building the query vector.
         */
        var expandedTerm = expandedTerms[j],
            posting = this.invertedIndex[expandedTerm],
            termIndex = posting._index

        for (var k = 0; k < clause.fields.length; k++) {
          /*
           * For each field that this query term is scoped by (by default
           * all fields are in scope) we need to get all the document refs
           * that have this term in that field.
           *
           * The posting is the entry in the invertedIndex for the matching
           * term from above.
           */
          var field = clause.fields[k],
              fieldPosting = posting[field],
              matchingDocumentRefs = Object.keys(fieldPosting),
              termField = expandedTerm + "/" + field,
              matchingDocumentsSet = new lunr.Set(matchingDocumentRefs)

          /*
           * if the presence of this term is required ensure that the matching
           * documents are added to the set of required matches for this clause.
           *
           */
          if (clause.presence == lunr.Query.presence.REQUIRED) {
            clauseMatches = clauseMatches.union(matchingDocumentsSet)

            if (requiredMatches[field] === undefined) {
              requiredMatches[field] = lunr.Set.complete
            }
          }

          /*
           * if the presence of this term is prohibited ensure that the matching
           * documents are added to the set of prohibited matches for this field,
           * creating that set if it does not yet exist.
           */
          if (clause.presence == lunr.Query.presence.PROHIBITED) {
            if (prohibitedMatches[field] === undefined) {
              prohibitedMatches[field] = lunr.Set.empty
            }

            prohibitedMatches[field] = prohibitedMatches[field].union(matchingDocumentsSet)

            /*
             * Prohibited matches should not be part of the query vector used for
             * similarity scoring and no metadata should be extracted so we continue
             * to the next field
             */
            continue
          }

          /*
           * The query field vector is populated using the termIndex found for
           * the term and a unit value with the appropriate boost applied.
           * Using upsert because there could already be an entry in the vector
           * for the term we are working with. In that case we just add the scores
           * together.
           */
          queryVectors[field].upsert(termIndex, clause.boost, function (a, b) { return a + b })

          /**
           * If we've already seen this term, field combo then we've already collected
           * the matching documents and metadata, no need to go through all that again
           */
          if (termFieldCache[termField]) {
            continue
          }

          for (var l = 0; l < matchingDocumentRefs.length; l++) {
            /*
             * All metadata for this term/field/document triple
             * are then extracted and collected into an instance
             * of lunr.MatchData ready to be returned in the query
             * results
             */
            var matchingDocumentRef = matchingDocumentRefs[l],
                matchingFieldRef = new lunr.FieldRef (matchingDocumentRef, field),
                metadata = fieldPosting[matchingDocumentRef],
                fieldMatch

            if ((fieldMatch = matchingFields[matchingFieldRef]) === undefined) {
              matchingFields[matchingFieldRef] = new lunr.MatchData (expandedTerm, field, metadata)
            } else {
              fieldMatch.add(expandedTerm, field, metadata)
            }

          }

          termFieldCache[termField] = true
        }
      }
    }

    /**
     * If the presence was required we need to update the requiredMatches field sets.
     * We do this after all fields for the term have collected their matches because
     * the clause terms presence is required in _any_ of the fields not _all_ of the
     * fields.
     */
    if (clause.presence === lunr.Query.presence.REQUIRED) {
      for (var k = 0; k < clause.fields.length; k++) {
        var field = clause.fields[k]
        requiredMatches[field] = requiredMatches[field].intersect(clauseMatches)
      }
    }
  }

  /**
   * Need to combine the field scoped required and prohibited
   * matching documents into a global set of required and prohibited
   * matches
   */
  var allRequiredMatches = lunr.Set.complete,
      allProhibitedMatches = lunr.Set.empty

  for (var i = 0; i < this.fields.length; i++) {
    var field = this.fields[i]

    if (requiredMatches[field]) {
      allRequiredMatches = allRequiredMatches.intersect(requiredMatches[field])
    }

    if (prohibitedMatches[field]) {
      allProhibitedMatches = allProhibitedMatches.union(prohibitedMatches[field])
    }
  }

  var matchingFieldRefs = Object.keys(matchingFields),
      results = [],
      matches = Object.create(null)

  /*
   * If the query is negated (contains only prohibited terms)
   * we need to get _all_ fieldRefs currently existing in the
   * index. This is only done when we know that the query is
   * entirely prohibited terms to avoid any cost of getting all
   * fieldRefs unnecessarily.
   *
   * Additionally, blank MatchData must be created to correctly
   * populate the results.
   */
  if (query.isNegated()) {
    matchingFieldRefs = Object.keys(this.fieldVectors)

    for (var i = 0; i < matchingFieldRefs.length; i++) {
      var matchingFieldRef = matchingFieldRefs[i]
      var fieldRef = lunr.FieldRef.fromString(matchingFieldRef)
      matchingFields[matchingFieldRef] = new lunr.MatchData
    }
  }

  for (var i = 0; i < matchingFieldRefs.length; i++) {
    /*
     * Currently we have document fields that match the query, but we
     * need to return documents. The matchData and scores are combined
     * from multiple fields belonging to the same document.
     *
     * Scores are calculated by field, using the query vectors created
     * above, and combined into a final document score using addition.
     */
    var fieldRef = lunr.FieldRef.fromString(matchingFieldRefs[i]),
        docRef = fieldRef.docRef

    if (!allRequiredMatches.contains(docRef)) {
      continue
    }

    if (allProhibitedMatches.contains(docRef)) {
      continue
    }

    var fieldVector = this.fieldVectors[fieldRef],
        score = queryVectors[fieldRef.fieldName].similarity(fieldVector),
        docMatch

    if ((docMatch = matches[docRef]) !== undefined) {
      docMatch.score += score
      docMatch.matchData.combine(matchingFields[fieldRef])
    } else {
      var match = {
        ref: docRef,
        score: score,
        matchData: matchingFields[fieldRef]
      }
      matches[docRef] = match
      results.push(match)
    }
  }

  /*
   * Sort the results objects by score, highest first.
   */
  return results.sort(function (a, b) {
    return b.score - a.score
  })
}

/**
 * Prepares the index for JSON serialization.
 *
 * The schema for this JSON blob will be described in a
 * separate JSON schema file.
 *
 * @returns {Object}
 */
lunr.Index.prototype.toJSON = function () {
  var invertedIndex = Object.keys(this.invertedIndex)
    .sort()
    .map(function (term) {
      return [term, this.invertedIndex[term]]
    }, this)

  var fieldVectors = Object.keys(this.fieldVectors)
    .map(function (ref) {
      return [ref, this.fieldVectors[ref].toJSON()]
    }, this)

  return {
    version: lunr.version,
    fields: this.fields,
    fieldVectors: fieldVectors,
    invertedIndex: invertedIndex,
    pipeline: this.pipeline.toJSON()
  }
}

/**
 * Loads a previously serialized lunr.Index
 *
 * @param {Object} serializedIndex - A previously serialized lunr.Index
 * @returns {lunr.Index}
 */
lunr.Index.load = function (serializedIndex) {
  var attrs = {},
      fieldVectors = {},
      serializedVectors = serializedIndex.fieldVectors,
      invertedIndex = Object.create(null),
      serializedInvertedIndex = serializedIndex.invertedIndex,
      tokenSetBuilder = new lunr.TokenSet.Builder,
      pipeline = lunr.Pipeline.load(serializedIndex.pipeline)

  if (serializedIndex.version != lunr.version) {
    lunr.utils.warn("Version mismatch when loading serialised index. Current version of lunr '" + lunr.version + "' does not match serialized index '" + serializedIndex.version + "'")
  }

  for (var i = 0; i < serializedVectors.length; i++) {
    var tuple = serializedVectors[i],
        ref = tuple[0],
        elements = tuple[1]

    fieldVectors[ref] = new lunr.Vector(elements)
  }

  for (var i = 0; i < serializedInvertedIndex.length; i++) {
    var tuple = serializedInvertedIndex[i],
        term = tuple[0],
        posting = tuple[1]

    tokenSetBuilder.insert(term)
    invertedIndex[term] = posting
  }

  tokenSetBuilder.finish()

  attrs.fields = serializedIndex.fields

  attrs.fieldVectors = fieldVectors
  attrs.invertedIndex = invertedIndex
  attrs.tokenSet = tokenSetBuilder.root
  attrs.pipeline = pipeline

  return new lunr.Index(attrs)
}


text:
<?php

/**
 * Author: imsamurai <im.samuray@gmail.com>
 * Date: 10.10.2013
 * Time: 18:00:00
 */
App::uses("HttpSourceTestFixture", "HttpSource.TestSuite/Fixture");

/**
 * Alias fixture
 *
 * @package ElasticsearchSourceTest
 * @subpackage Test.Fixture
 */
class ElasticsearchAliasFixture extends HttpSourceTestFixture {

	/**
	 * Fixture Datasource
	 *
	 * @var string
	 */
	public $useDbConfig = "elasticsearchTest";

	/**
	 * {@inheritdoc}
	 *
	 * @var string
	 */
	public $model = "ElasticsearchSource.ElasticsearchAlias";

	/**
	 * Records
	 *
	 * @var array
	 */
	public $records = array(
		array("name" => 'test_alias1', "index" => "test_index", "filter" => array('query' => array("term" => array("title" => "guratabaata"))), "routing" => 1),
		array("name" => 'test_alias2', "index" => "test_index", "filter" => array('query' => array("term" => array("title" => "guratabaata"))), "routing" => 2),
		array("name" => 'test_alias3', "index" => "test_index", "filter" => array('query' => array("term" => array("title" => "guratabaata"))), "routing" => 3)
	);

	/**
	 * {@inheritdoc}
	 *
	 * @return void
	 * @throws MissingModelException Whe importing from a model that does not exist.
	 */
	public function init() {
		ElasticsearchTest::setConfig();
		parent::init();
		$this->_Model->setSource('aliases');
	}

}


text:
Contributing
======================

To contribute to the Showoff project:

* Fork `puppetlabs/showoff`

* Use the presentations in the `example/` subdirectory to make sure you haven't broken
  existing functionality. These presentations are used as simple integration tests.

* Add an example presentation to validate any new features you add.

* Push your contribution to a branch named after your change:
    * Example: `git push origin master:fixed-static-links`

* Send me a pull request through GitHub with a description of what you are contributing.


text:
#include <linux/ieee80211.h>
#include <linux/export.h>
#include <net/cfg80211.h>
#include "nl80211.h"
#include "core.h"
#include "rdev-ops.h"

/* Default values, timeouts in ms */
#define MESH_TTL 		31
#define MESH_DEFAULT_ELEMENT_TTL 31
#define MESH_MAX_RETR	 	3
#define MESH_RET_T 		100
#define MESH_CONF_T 		100
#define MESH_HOLD_T 		100

#define MESH_PATH_TIMEOUT	5000
#define MESH_RANN_INTERVAL      5000
#define MESH_PATH_TO_ROOT_TIMEOUT      6000
#define MESH_ROOT_INTERVAL     5000
#define MESH_ROOT_CONFIRMATION_INTERVAL 2000

/*
 * Minimum interval between two consecutive PREQs originated by the same
 * interface
 */
#define MESH_PREQ_MIN_INT	10
#define MESH_PERR_MIN_INT	100
#define MESH_DIAM_TRAVERSAL_TIME 50

#define MESH_RSSI_THRESHOLD	0

/*
 * A path will be refreshed if it is used PATH_REFRESH_TIME milliseconds
 * before timing out.  This way it will remain ACTIVE and no data frames
 * will be unnecessarily held in the pending queue.
 */
#define MESH_PATH_REFRESH_TIME			1000
#define MESH_MIN_DISCOVERY_TIMEOUT (2 * MESH_DIAM_TRAVERSAL_TIME)

/* Default maximum number of established plinks per interface */
#define MESH_MAX_ESTAB_PLINKS	32

#define MESH_MAX_PREQ_RETRIES	4

#define MESH_SYNC_NEIGHBOR_OFFSET_MAX 50

#define MESH_DEFAULT_BEACON_INTERVAL	1000	/* in 1024 us units (=TUs) */
#define MESH_DEFAULT_DTIM_PERIOD	2
#define MESH_DEFAULT_AWAKE_WINDOW	10	/* in 1024 us units (=TUs) */

const struct mesh_config default_mesh_config = {
	.dot11MeshRetryTimeout = MESH_RET_T,
	.dot11MeshConfirmTimeout = MESH_CONF_T,
	.dot11MeshHoldingTimeout = MESH_HOLD_T,
	.dot11MeshMaxRetries = MESH_MAX_RETR,
	.dot11MeshTTL = MESH_TTL,
	.element_ttl = MESH_DEFAULT_ELEMENT_TTL,
	.auto_open_plinks = true,
	.dot11MeshMaxPeerLinks = MESH_MAX_ESTAB_PLINKS,
	.dot11MeshNbrOffsetMaxNeighbor = MESH_SYNC_NEIGHBOR_OFFSET_MAX,
	.dot11MeshHWMPactivePathTimeout = MESH_PATH_TIMEOUT,
	.dot11MeshHWMPpreqMinInterval = MESH_PREQ_MIN_INT,
	.dot11MeshHWMPperrMinInterval = MESH_PERR_MIN_INT,
	.dot11MeshHWMPnetDiameterTraversalTime = MESH_DIAM_TRAVERSAL_TIME,
	.dot11MeshHWMPmaxPREQretries = MESH_MAX_PREQ_RETRIES,
	.path_refresh_time = MESH_PATH_REFRESH_TIME,
	.min_discovery_timeout = MESH_MIN_DISCOVERY_TIMEOUT,
	.dot11MeshHWMPRannInterval = MESH_RANN_INTERVAL,
	.dot11MeshGateAnnouncementProtocol = false,
	.dot11MeshForwarding = true,
	.rssi_threshold = MESH_RSSI_THRESHOLD,
	.ht_opmode = IEEE80211_HT_OP_MODE_PROTECTION_NONHT_MIXED,
	.dot11MeshHWMPactivePathToRootTimeout = MESH_PATH_TO_ROOT_TIMEOUT,
	.dot11MeshHWMProotInterval = MESH_ROOT_INTERVAL,
	.dot11MeshHWMPconfirmationInterval = MESH_ROOT_CONFIRMATION_INTERVAL,
	.power_mode = NL80211_MESH_POWER_ACTIVE,
	.dot11MeshAwakeWindowDuration = MESH_DEFAULT_AWAKE_WINDOW,
};

const struct mesh_setup default_mesh_setup = {
	/* cfg80211_join_mesh() will pick a channel if needed */
	.sync_method = IEEE80211_SYNC_METHOD_NEIGHBOR_OFFSET,
	.path_sel_proto = IEEE80211_PATH_PROTOCOL_HWMP,
	.path_metric = IEEE80211_PATH_METRIC_AIRTIME,
	.ie = NULL,
	.ie_len = 0,
	.is_secure = false,
	.user_mpm = false,
	.beacon_interval = MESH_DEFAULT_BEACON_INTERVAL,
	.dtim_period = MESH_DEFAULT_DTIM_PERIOD,
};

int __cfg80211_join_mesh(struct cfg80211_registered_device *rdev,
			 struct net_device *dev,
			 struct mesh_setup *setup,
			 const struct mesh_config *conf)
{
	struct wireless_dev *wdev = dev->ieee80211_ptr;
	int err;

	BUILD_BUG_ON(IEEE80211_MAX_SSID_LEN != IEEE80211_MAX_MESH_ID_LEN);

	ASSERT_WDEV_LOCK(wdev);

	if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
		return -EOPNOTSUPP;

	if (!(rdev->wiphy.flags & WIPHY_FLAG_MESH_AUTH) &&
	      setup->is_secure)
		return -EOPNOTSUPP;

	if (wdev->mesh_id_len)
		return -EALREADY;

	if (!setup->mesh_id_len)
		return -EINVAL;

	if (!rdev->ops->join_mesh)
		return -EOPNOTSUPP;

	if (!setup->chandef.chan) {
		/* if no channel explicitly given, use preset channel */
		setup->chandef = wdev->preset_chandef;
	}

	if (!setup->chandef.chan) {
		/* if we don't have that either, use the first usable channel */
		enum ieee80211_band band;

		for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
			struct ieee80211_supported_band *sband;
			struct ieee80211_channel *chan;
			int i;

			sband = rdev->wiphy.bands[band];
			if (!sband)
				continue;

			for (i = 0; i < sband->n_channels; i++) {
				chan = &sband->channels[i];
				if (chan->flags & (IEEE80211_CHAN_NO_IBSS |
						   IEEE80211_CHAN_PASSIVE_SCAN |
						   IEEE80211_CHAN_DISABLED |
						   IEEE80211_CHAN_RADAR))
					continue;
				setup->chandef.chan = chan;
				break;
			}

			if (setup->chandef.chan)
				break;
		}

		/* no usable channel ... */
		if (!setup->chandef.chan)
			return -EINVAL;

		setup->chandef.width = NL80211_CHAN_WIDTH_20_NOHT;
		setup->chandef.center_freq1 = setup->chandef.chan->center_freq;
	}

	if (!cfg80211_reg_can_beacon(&rdev->wiphy, &setup->chandef))
		return -EINVAL;

	err = cfg80211_can_use_chan(rdev, wdev, setup->chandef.chan,
				    CHAN_MODE_SHARED);
	if (err)
		return err;

	err = rdev_join_mesh(rdev, dev, conf, setup);
	if (!err) {
		memcpy(wdev->ssid, setup->mesh_id, setup->mesh_id_len);
		wdev->mesh_id_len = setup->mesh_id_len;
		wdev->channel = setup->chandef.chan;
	}

	return err;
}

int cfg80211_join_mesh(struct cfg80211_registered_device *rdev,
		       struct net_device *dev,
		       struct mesh_setup *setup,
		       const struct mesh_config *conf)
{
	struct wireless_dev *wdev = dev->ieee80211_ptr;
	int err;

	mutex_lock(&rdev->devlist_mtx);
	wdev_lock(wdev);
	err = __cfg80211_join_mesh(rdev, dev, setup, conf);
	wdev_unlock(wdev);
	mutex_unlock(&rdev->devlist_mtx);

	return err;
}

int cfg80211_set_mesh_channel(struct cfg80211_registered_device *rdev,
			      struct wireless_dev *wdev,
			      struct cfg80211_chan_def *chandef)
{
	int err;

	/*
	 * Workaround for libertas (only!), it puts the interface
	 * into mesh mode but doesn't implement join_mesh. Instead,
	 * it is configured via sysfs and then joins the mesh when
	 * you set the channel. Note that the libertas mesh isn't
	 * compatible with 802.11 mesh.
	 */
	if (rdev->ops->libertas_set_mesh_channel) {
		if (chandef->width != NL80211_CHAN_WIDTH_20_NOHT)
			return -EINVAL;

		if (!netif_running(wdev->netdev))
			return -ENETDOWN;

		err = cfg80211_can_use_chan(rdev, wdev, chandef->chan,
					    CHAN_MODE_SHARED);
		if (err)
			return err;

		err = rdev_libertas_set_mesh_channel(rdev, wdev->netdev,
						     chandef->chan);
		if (!err)
			wdev->channel = chandef->chan;

		return err;
	}

	if (wdev->mesh_id_len)
		return -EBUSY;

	wdev->preset_chandef = *chandef;
	return 0;
}

static int __cfg80211_leave_mesh(struct cfg80211_registered_device *rdev,
				 struct net_device *dev)
{
	struct wireless_dev *wdev = dev->ieee80211_ptr;
	int err;

	ASSERT_WDEV_LOCK(wdev);

	if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
		return -EOPNOTSUPP;

	if (!rdev->ops->leave_mesh)
		return -EOPNOTSUPP;

	if (!wdev->mesh_id_len)
		return -ENOTCONN;

	err = rdev_leave_mesh(rdev, dev);
	if (!err) {
		wdev->mesh_id_len = 0;
		wdev->channel = NULL;
		rdev_set_qos_map(rdev, dev, NULL);
	}

	return err;
}

int cfg80211_leave_mesh(struct cfg80211_registered_device *rdev,
			struct net_device *dev)
{
	struct wireless_dev *wdev = dev->ieee80211_ptr;
	int err;

	wdev_lock(wdev);
	err = __cfg80211_leave_mesh(rdev, dev);
	wdev_unlock(wdev);

	return err;
}


text:
'use strict';
var getBuiltIn = require('../internals/get-built-in');
var anObject = require('../internals/an-object');
var aFunction = require('../internals/a-function');
var speciesConstructor = require('../internals/species-constructor');
var iterate = require('../internals/iterate');

// `Set.prototype.intersection` method
// https://github.com/tc39/proposal-set-methods
require('../internals/export')({ target: 'Set', proto: true, real: true, forced: require('../internals/is-pure') }, {
  intersection: function intersection(iterable) {
    var set = anObject(this);
    var newSet = new (speciesConstructor(set, getBuiltIn('Set')))();
    var hasCheck = aFunction(set.has);
    var adder = aFunction(newSet.add);
    iterate(iterable, function (value) {
      if (hasCheck.call(set, value)) adder.call(newSet, value);
    });
    return newSet;
  }
});


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#ifndef NDN_BINARYXMLENCODER_HPP
#define NDN_BINARYXMLENCODER_HPP

#include <vector>
#include <ndn-cpp/common.hpp>
#include "../util/dynamic-uint8-vector.hpp"
#include "../c/encoding/binary-xml-encoder.h"

namespace ndn {

/**
 * A BinaryXmlEncoder extends a C ndn_BinaryXmlEncoder struct and wraps related functions.
 */
class BinaryXmlEncoder : public ndn_BinaryXmlEncoder {
public:
  /**
   * Initialize the base ndn_BinaryXmlEncoder struct with an initial array of 16 bytes.  Use simpleRealloc.
   */
  BinaryXmlEncoder()
  : output_(16)
  {
    ndn_BinaryXmlEncoder_initialize(this, &output_);
  }

  /**
   * Resize the output vector to the correct encoding length and return.
   * @return The encoding as a shared_ptr.  Assume that the caller now owns the vector.
   */
  const ptr_lib::shared_ptr<std::vector<uint8_t> >&
  getOutput()
  {
    output_.get()->resize(offset);
    return output_.get();
  }

  DynamicUInt8Vector output_;
};

}

#endif


text:
package org.schoellerfamily.gedbrowser.controller;

import org.schoellerfamily.gedbrowser.analytics.calendar.CalendarProvider;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Dick Schoeller
 */
@SuppressWarnings("PMD.AbstractClassWithoutAbstractMethod")
public abstract class DatedDataController extends AbstractController {
    /** */
    @Autowired
    private transient CalendarProvider provider;

    /**
     * Return the calendar provider.
     *
     * @return the provider
     */
    protected final CalendarProvider calendarProvider() {
        return provider;
    }
}


text:
package com.elastisys.scale.cloudpool.aws.autoscaling.driver.client;

import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.autoscaling.model.AutoScalingGroup;
import com.amazonaws.services.autoscaling.model.LaunchConfiguration;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Tag;
import com.elastisys.scale.cloudpool.api.NotFoundException;
import com.elastisys.scale.cloudpool.aws.autoscaling.driver.AwsAsPoolDriver;
import com.elastisys.scale.cloudpool.aws.autoscaling.driver.config.CloudApiSettings;

/**
 * A simplified client interface towards the AWS Auto Scaling API that only
 * provides the functionality needed by the {@link AwsAsPoolDriver}.
 *

 * The {@link #configure} method must be called before calling any other
 * methods.
 *
 *
 *
 */
public interface AutoScalingClient {

    /**
     * Configures this {@link AutoScalingClient} with API access credentials and
     * settings to allow it to access the AWS Auto Scaling API.
     *
     * @param configuration
     *            API access credentials and settings.
     */
    void configure(CloudApiSettings configuration);

    /**
     * Retrieves a particular {@link AutoScalingGroup}.
     *
     * @param autoScalingGroupName
     *            The name of the Auto Scaling Group.
     * @return
     * @throws AmazonClientException
     */
    AutoScalingGroup getAutoScalingGroup(String autoScalingGroupName) throws AmazonClientException;

    /**
     * Retrieves a particular {@link LaunchConfiguration} (describing how to
     * launch on-demand or spot instances for an Auto Scaling Group).
     *
     * @param launchConfigurationName
     *            The name of the Launch configuration.
     * @return
     * @throws AmazonClientException
     */
    LaunchConfiguration getLaunchConfiguration(String launchConfigurationName) throws AmazonClientException;

    /**
     * Retrieves all members of a particular {@link AutoScalingGroup}.
     *
     * @param autoScalingGroupName
     *            The name of the Auto Scaling Group.
     * @return
     * @throws AmazonClientException
     */
    List<Instance> getAutoScalingGroupMembers(String autoScalingGroupName) throws AmazonClientException;

    /**
     * Sets the desired capacity of a particular Auto Scaling Group.
     *

     * Note that this method will not block until the group has reached the
     * desired size, which may be a time-consuming process.
     *
     * @param autoScalingGroupName
     *            The name of the Auto Scaling Group.
     * @param desiredSize
     *            The desired capacity of the group to set.
     * @throws AmazonClientException
     */
    void setDesiredSize(String autoScalingGroupName, int desiredSize) throws AmazonClientException;

    /**
     * Terminates a particular Auto Scaling Group member instance. As a
     * side-effect, the desired capacity of the Auto Scaling Group is
     * decremented.
     *
     * @param autoScalingGroupName
     *            The name of the Auto Scaling Group.
     * @param instanceId
     *            An instance identifier of a member in the Auto Scaling Group.
     * @throws NotFoundException
     *             if the instance does not exist
     * @throws AmazonClientException
     */
    void terminateInstance(String autoScalingGroupName, String instanceId)
            throws NotFoundException, AmazonClientException;

    /**
     * Adds a machine instance to the scaling group. As a side-effect, the
     * desired capacity of the Auto Scaling Group is incremented.
     *
     * @param machineId
     *            The identifier of the instance to attach to the pool.
     * @throws NotFoundException
     *             if the instance does not exist
     * @throws AmazonClientException
     */
    void attachInstance(String autoScalingGroupName, String instanceId) throws NotFoundException, AmazonClientException;

    /**
     * Removes a member from the scaling group without terminating it. As a
     * side-effect, the desired capacity of the Auto Scaling Group is
     * decremented.
     *
     * @param machineId
     *            The identifier of the instance to detach from the pool.
     * @throws NotFoundException
     *             if the instance does not exist
     * @throws AmazonClientException
     */
    void detachInstance(String autoScalingGroupName, String instanceId) throws NotFoundException, AmazonClientException;

    /**
     * Sets a collection of tags on an EC2 instance.
     *
     * @param instanceId
     *            An instance identifier.
     * @param tags
     *            The {@link Tag}s to set on the {@link Instance}.
     * @throws NotFoundException
     *             if the instance does not exist
     * @throws AmazonClientException
     */
    void tagInstance(String instanceId, List<Tag> tags) throws NotFoundException, AmazonClientException;

}


text:
<?php

class SmartyTagHelper {
	public static function cdata(array $params, $content, Smarty $smarty, &$repeat){
		if (!$repeat) {
			return "//<![CDATA[\n$content\n//]]>";
		}
	}
}

sfSmartyView::registerBlock('cdata', array('SmartyTagHelper', 'cdata'));
?>


text:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

  if (request.autoPassUniversal) {

    var host = window.location.hostname.split(".").slice(-2).join(".");
    var hash = md5(host + request.secret);
    document.activeElement.value = hash.substring(5, 15) + "!,Az";
    return;

  }

  if (request.autoPassName) {

    document.activeElement.value = request.userName
    return;

  }

  if (request.autoPass) {

    var host = window.location.hostname.split(".").slice(-2).join(".");
    var hash = md5(request.userName + host + request.secret);
    document.activeElement.value = hash.substring(5, 15) + "!,Az";
    return;

  }

  var elem = document.activeElement;

  var editable = elem.getAttribute("contenteditable") ?
    elem.getAttribute("contenteditable").toLowerCase() :
    "false";

  if (elem.tagName.toLowerCase() == "input") {

    document.activeElement.value += request.word;

  } else if (

      (elem.tagName.toLowerCase() == "div" && editable == "true") ||
      elem.tagName.toLowerCase() == "textarea"

    ) {

    document.activeElement.textContent += request.word;

  } else {

    alert("Word '" + request.word + "' was put in the clipboard.\n\n" +
      "You can paste if from there in a usual way, like Control+V");

  }

  placeCaretAtEnd(elem);

});

function placeCaretAtEnd(el) {
  el.focus();
  if (typeof window.getSelection != "undefined"
        && typeof document.createRange != "undefined") {
      var range = document.createRange();
      range.selectNodeContents(el);
      range.collapse(false);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
  } else if (typeof document.body.createTextRange != "undefined") {
      var textRange = document.body.createTextRange();
      textRange.moveToElementText(el);
      textRange.collapse(false);
      textRange.select();
  }
}


text:
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";

class HistoryTester : public UITest {
 protected:
  HistoryTester() : UITest() { }

  virtual void SetUp() {
    show_window_ = true;
    UITest::SetUp();
  }
};

// TODO(yuzo): Fix the following flaky (hence disabled) tests.
// These tests are flaky because automatic and user-initiated transitions are
// distinguished based on the interval between page load and redirect.

TEST_F(HistoryTester, DISABLED_VerifyHistoryLength) {
  // Test the history length for the following page transitions.
  //
  // Test case 1:
  //   -open-> Page 1.
  // Test case 2:
  //   -open-> Page 2 -redirect-> Page 3.
  // Test case 3:
  //   -open-> Page 4 -navigate_backward-> Page 3 -navigate_backward->Page 1
  //   -navigate_forward-> Page 3 -navigate_forward-> Page 4
  //
  // Note that Page 2 is not visited on navigating backward/forward.

  // Test case 1
  std::wstring test_case_1 = L"history_length_test_page_1.html";
  GURL url_1 = GetTestUrl(L"History", test_case_1);
  NavigateToURL(url_1);
  WaitForFinish("History_Length_Test_1", "1", url_1, kTestCompleteCookie,
                  kTestCompleteSuccess, action_max_timeout_ms());

  // Test case 2
  std::wstring test_case_2 = L"history_length_test_page_2.html";
  GURL url_2 = GetTestUrl(L"History", test_case_2);
  NavigateToURL(url_2);
  WaitForFinish("History_Length_Test_2", "1", url_2, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());

  // Test case 3
  std::wstring test_case_3 = L"history_length_test_page_4.html";
  GURL url_3 = GetTestUrl(L"History", test_case_3);
  NavigateToURL(url_3);
  WaitForFinish("History_Length_Test_3", "1", url_3, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}

#if defined(OS_WIN) || defined(OS_NIX)
TEST_F(HistoryTester, DISABLED_ConsiderRedirectAfterGestureAsUserInitiated) {
  // Test the history length for the following page transition.
  //
  // -open-> Page 11 -slow_redirect-> Page 12.
  //
  // If redirect occurs after a user gesture, e.g., mouse click, the
  // redirect is more likely to be user-initiated rather than automatic.
  // Therefore, Page 11 should be in the history in addition to Page 12.

  std::wstring test_case = L"history_length_test_page_11.html";
  GURL url = GetTestUrl(L"History", test_case);
  NavigateToURL(url);
  WaitForFinish("History_Length_Test_11", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());

  // Simulate click. This only works for Windows.
  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  scoped_refptr<WindowProxy> window = browser->GetWindow();
  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
                                    true));
  ASSERT_TRUE(
      window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                              views::Event::EF_LEFT_BUTTON_DOWN));

  NavigateToURL(GURL("javascript:redirectToPage12()"));
  WaitForFinish("History_Length_Test_12", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}
#endif  // defined(OS_WIN) || defined(OS_NIX)

TEST_F(HistoryTester, DISABLED_ConsiderSlowRedirectAsUserInitiated) {
  // Test the history length for the following page transition.
  //
  // -open-> Page 21 -redirect-> Page 22.
  //
  // If redirect occurs more than 5 seconds later after the page is loaded,
  // the redirect is likely to be user-initiated.
  // Therefore, Page 21 should be in the history in addition to Page 22.

  std::wstring test_case = L"history_length_test_page_21.html";
  GURL url = GetTestUrl(L"History", test_case);
  NavigateToURL(url);
  WaitForFinish("History_Length_Test_21", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}