text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.analytics.synapse.artifacts.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Pipeline reference type. */
@Fluent
public final class PipelineReference {
    /*
     * Pipeline reference type.
     */
    @JsonProperty(value = "type", required = true)
    private PipelineReferenceType type;

    /*
     * Reference pipeline name.
     */
    @JsonProperty(value = "referenceName", required = true)
    private String referenceName;

    /*
     * Reference name.
     */
    @JsonProperty(value = "name")
    private String name;

    /**
     * Get the type property: Pipeline reference type.
     *
     * @return the type value.
     */
    public PipelineReferenceType getType() {
        return this.type;
    }

    /**
     * Set the type property: Pipeline reference type.
     *
     * @param type the type value to set.
     * @return the PipelineReference object itself.
     */
    public PipelineReference setType(PipelineReferenceType type) {
        this.type = type;
        return this;
    }

    /**
     * Get the referenceName property: Reference pipeline name.
     *
     * @return the referenceName value.
     */
    public String getReferenceName() {
        return this.referenceName;
    }

    /**
     * Set the referenceName property: Reference pipeline name.
     *
     * @param referenceName the referenceName value to set.
     * @return the PipelineReference object itself.
     */
    public PipelineReference setReferenceName(String referenceName) {
        this.referenceName = referenceName;
        return this;
    }

    /**
     * Get the name property: Reference name.
     *
     * @return the name value.
     */
    public String getName() {
        return this.name;
    }

    /**
     * Set the name property: Reference name.
     *
     * @param name the name value to set.
     * @return the PipelineReference object itself.
     */
    public PipelineReference setName(String name) {
        this.name = name;
        return this;
    }
}


text:
package at.jku.se.eatemup.core.json;

public abstract class OutgoingMessage extends Message {

	@Override
	public DirectionType getDirection() {
		return DirectionType.Outgoing;
	}
}

redpajama_set_name: RedPajamaGithub


text:
/** Notice of modification as required by the LGPL
 *  This file was modified by Gemstone Systems Inc. on
 *  $Date$
 **/
// changes made by mandar

// Added .* imports
// replacing SecretKey with SecretKey

// $Id: ENCRYPT1_4.java,v 1.8 2005/08/08 12:45:42 belaban Exp $

package com.gemstone.org.jgroups.protocols;

import com.gemstone.org.jgroups.Address;
import com.gemstone.org.jgroups.Event;
import com.gemstone.org.jgroups.Message;
import com.gemstone.org.jgroups.View;
import com.gemstone.org.jgroups.stack.Protocol;
import com.gemstone.org.jgroups.util.ExternalStrings;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;

import java.io.IOException;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.util.Properties;
import java.util.Vector;

/**
 * ENCRYPT1_4 layer. Encrypt and decrypt the group communication in JGroups
 */
public class ENCRYPT1_4 extends Protocol  {

public static class EncryptHeader extends com.gemstone.org.jgroups.Header  {
    int type;
    static final int ENCRYPT=0;
    static final int KEY_REQUEST=1;
    static final int SERVER_PUBKEY=2;
    static final int SECRETKEY=3;
    static final int SECRETKEY_READY=4;

    // adding key for Message object purpose
    static final String KEY="encrypt";

    public EncryptHeader(){}

    public EncryptHeader(int type) {
        this.type=type;
    }

    public void writeExternal(java.io.ObjectOutput out) throws IOException {
        out.writeInt(type);
    }

    public void readExternal(java.io.ObjectInput in) throws IOException, ClassNotFoundException {
        type=in.readInt();
    }

    @Override // GemStoneAddition
    public String toString() {
        return "[ENCTYPT: <variables> ]";
    }
}

    Address local_addr=null;
    Address keyServerAddr=null;
    boolean keyServer=false;
    String asymAlgorithm="RSA";
    String symAlgorithm="DES/ECB/PKCS5Padding";
    int asymInit=512;					// initial public/private key length
    int symInit=56;					// initial shared key length
    // for public/private Key
    KeyPair Kpair;			// to store own's public/private Key
    SecretKey desKey=null;
    final PublicKey pubKey=null;               // for server to store the temporary client public key
//    PublicKey serverPubKey=null;         // for client to store server's public Key GemStoneAddition(omitted)
    Cipher cipher;
    Cipher rsa;
    final Vector members=new Vector();
    final Vector notReady=new Vector();

    public ENCRYPT1_4() {
        //Provider prov = Security.getProvider("SUN");
        //Security.addProvider(prov);
    }

    @Override // GemStoneAddition
    public String getName() {
        return "ENCRYPT1_4";
    }

    /*
     * GetAlgorithm: Get the algorithm name from "algorithm/mode/padding"
     */
    private static String getAlgorithm(String s) {
        int index=s.indexOf("/");
        if(index == -1)
            return s;

        return s.substring(0, index);
    }

    @Override // GemStoneAddition
    public boolean setProperties(Properties props) {
        String str;

        super.setProperties(props);
        // asymmetric key length
        str=props.getProperty("asymInit");
        if(str != null) {
            asymInit=Integer.parseInt(str);
            props.remove("asymInit");

		if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_ASYM_ALGO_BITS_USED_IS__0, asymInit);
        }

        // symmetric key length
        str=props.getProperty("symInit");
        if(str != null) {
            symInit=Integer.parseInt(str);
            props.remove("symInit");

		if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_SYM_ALGO_BITS_USED_IS__0, symInit);
        }

        // asymmetric algorithm name
        str=props.getProperty("asymAlgorithm");
        if(str != null) {
            asymAlgorithm=str;
            props.remove("asymAlgorithm");

		if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_ASYM_ALGO_USED_IS__0, asymAlgorithm);
        }

        // symmetric algorithm name
        str=props.getProperty("symAlgorithm");
        if(str != null) {
            symAlgorithm=str;
            props.remove("symAlgorithm");

		if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_SYM_ALGO_USED_IS__0, symAlgorithm);
        }
        if(props.size() > 0) {

		if(log.isErrorEnabled()) log.error(ExternalStrings.ENCRYPT1_4_THESE_PROPERTIES_ARE_NOT_RECOGNIZED__0, props);
            return false;
        }

        return true;
    }

    @Override // GemStoneAddition
    public void init() throws Exception {
        // generate keys according to the specified algorithms
        // generate publicKey and Private Key using RSA
        KeyPairGenerator KpairGen=KeyPairGenerator.getInstance(getAlgorithm(asymAlgorithm));
        KpairGen.initialize(asymInit, new SecureRandom());
        Kpair=KpairGen.generateKeyPair();

        // generate secret key
        KeyGenerator keyGen=KeyGenerator.getInstance(getAlgorithm(symAlgorithm));
        keyGen.init(symInit);
        desKey=keyGen.generateKey();

        // initialize for rsa, cipher encryption/decryption
        rsa=Cipher.getInstance(asymAlgorithm);
        cipher=Cipher.getInstance(symAlgorithm);

	    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_BOTH_ASYM_AND_SYM_ALGO_INITIALIZED_WITH_THE_SINGLE_SHARED_KEY);
    }

    /** Just remove if you don't need to reset any state */
    public static void reset() {
    }

    @Override // GemStoneAddition
    public void up(Event evt) {
        Message msg;
        Message newMsg;
        EncryptHeader hdr;

	    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_EVENT_GOING_UP_IS__0, evt);

        switch(evt.getType()) {
            case Event.SET_LOCAL_ADDRESS:

		    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_SET_ADDRESS_CALL);
                local_addr=(Address)evt.getArg();
                break;
            case Event.FIND_INITIAL_MBRS_OK:
                Vector member=(Vector)evt.getArg();

		    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_FIND_INIT_MEMBERS_CALL_LEFT_MEMBERS_ARE__0, member.size());

		// this check is required, to prevent keyServer= false when adding itself
		if (!keyServer)
		    keyServer=member.size() <= 0;

                if(member != null && member.size() > 0)
                    keyServerAddr=((PingRsp) member.firstElement()).coord_addr;
                else
                    keyServerAddr=local_addr;

                if(!keyServer)
		    {

			desKey=null;

			    if(log.isDebugEnabled()) log.debug("This is not keyserver, deskey set to null");
			// client send clien's public key to server and request server's public key
			newMsg=new Message(keyServerAddr, local_addr, Kpair.getPublic().getEncoded());
			// making changes (MANDAR)
			newMsg.putHeader(EncryptHeader.KEY, new EncryptHeader(EncryptHeader.KEY_REQUEST));
			passDown(new Event(Event.MSG, newMsg));
		    }

		    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_DONE_PARSING_FOR_ENCRYPT_HEADERS_SENDING_UPWARDS_0, evt);
		passUp(evt);
                return;

            case Event.MSG:
                msg=(Message) evt.getArg();

		    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_THIS_IS_A_MESSAGE_FROM_PEER_NOT_CONTROL_HEADER_0, msg);

                // making changes (MANDAR)
                if(msg == null) {

			if(log.isDebugEnabled()) log.debug("Null message");
                    passUp(evt);
                    return;
                }

                // making changes (MANDAR)
                //Object obj=msg.peekHeader();
                Object obj=msg.removeHeader(EncryptHeader.KEY);

		    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_STRIPPING_THE_REQUIRED_PROTOCOL_HEADER);

                // if not encrypted message, pass up
                if(obj == null || !(obj instanceof EncryptHeader)) {

			if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_DROPPING_PACKAGE_AS_ENCRYPT1_4_PROTOCOL_IS_NOT_BEEN_RECOGNIZED_MSG_WILL_NOT_BE_PASSED_UP);

		    // BELA comment this out in case U think otherwise
                    //passUp(evt);
                    return;
                }

                // making changes (MANDAR)
                //hdr = (EncryptHeader)msg.removeHeader();
                hdr=(EncryptHeader) obj;

		    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_HEADER_RECEIVED_0_1, new Object[] {hdr, Integer.valueOf(hdr.type)});
                switch(hdr.type) {
                    // key request from client and send server's public key to client
                    case EncryptHeader.KEY_REQUEST:
                        try {

				if(log.isDebugEnabled()) log.debug("Request for key");
                            // store the this client to notReady list using client's address
                            notReady.addElement(msg.getSrc());
                            // store the client's public key for temporary
                            PublicKey tmpPubKey=generatePubKey(msg.getBuffer());

				if(log.isDebugEnabled()) log.debug("Generated requestors public key");

                            // send server's publicKey
                            newMsg=new Message(msg.getSrc(), local_addr, Kpair.getPublic().getEncoded());
                            // making changes (MANDAR)
                            newMsg.putHeader(EncryptHeader.KEY, new EncryptHeader(EncryptHeader.SERVER_PUBKEY));

				if(log.isDebugEnabled()) log.debug("Encoded servers public key using clients public key, only client can debug it using its private key and sending it back");
                            passDown(new Event(Event.MSG, newMsg));

			    // my changes (MANDAR)
			    rsa.init(Cipher.ENCRYPT_MODE, tmpPubKey);
			    byte[] encryptedKey = rsa.doFinal(desKey.getEncoded());

				if(log.isDebugEnabled()) log.debug(" Generated encoded key which only client can decode");

                            // send shared DesKey to client
                            //   1. Decrypt desKey with server's own private Key
                            //   2. Encrypt decrypted desKey with client's own public Key
                            // encrypt encoded desKey using server's private key
			    /*
                            rsa.init(Cipher.ENCRYPT_MODE, Kpair.getPrivate());
                            byte[] decryptedKey=rsa.doFinal(desKey.getEncoded());

                            // encrypt decrypted key using client's public key
                            rsa.init(Cipher.ENCRYPT_MODE, pubKey);
                            byte[] encryptedKey=rsa.doFinal(decryptedKey);
			    */
                            //send encrypted deskey to client
                            newMsg=new Message(msg.getSrc(), local_addr, encryptedKey);
                            // making changes (MANDAR)
                            newMsg.putHeader(EncryptHeader.KEY, new EncryptHeader(EncryptHeader.SECRETKEY));

				if(log.isDebugEnabled()) log.debug(" Sending encoded key to client");
                            passDown(new Event(Event.MSG, newMsg));
                        }
                        catch(Exception e) {
                            e.printStackTrace();
                            System.out.println(e + "0");
                        }
                        return;
                    case EncryptHeader.SECRETKEY_READY:
                        //server get client's public key and generate the secret key
                        notReady.removeElement(msg.getSrc());

			    if(log.isDebugEnabled()) log.debug("Removed client " + msg.getSrc() + "from notready list");
                        return;
                    case EncryptHeader.SERVER_PUBKEY:
                        /*serverPubKey=GemStoneAddition*/generatePubKey(msg.getBuffer());

			    if(log.isDebugEnabled()) log.debug(" Obtained the servers public key");
                        return;

                    case EncryptHeader.SECRETKEY:
                        try {
                            // decrypt using client's private Key
                            rsa.init(Cipher.DECRYPT_MODE, Kpair.getPrivate());
			    // my changes (MANDAR)
			    byte[] encodedKey = rsa.doFinal(msg.getBuffer());

				if(log.isDebugEnabled()) log.debug("generating encoded key obtained from server-admin");

			    /* Piece commented out by MANDAR
                            byte[] decryptedKey=rsa.doFinal(msg.getBuffer());
                            // decrypt using server's public Key
                            rsa.init(Cipher.DECRYPT_MODE, serverPubKey);
                            byte[] encodedKey=rsa.doFinal(decryptedKey);
			    */

                            // decode secretKey
                            desKey=decodedKey(encodedKey);
                            if(desKey == null)
                                log.error(ExternalStrings.ENCRYPT1_4_OHH_OH__DES_KEY_IS_NULL);

                            // send ready message (MANDAR) null -> ""
                            newMsg=new Message(msg.getSrc(), local_addr, null);
                            // making changes (MANDAR)
                            newMsg.putHeader(EncryptHeader.KEY, new EncryptHeader(EncryptHeader.SECRETKEY_READY));
                            passDown(new Event(Event.MSG, newMsg));

				if(log.isDebugEnabled()) log.debug("Got the deskey, sending down sec_Ready header");
                        }
                        catch(Exception e) {
                            e.printStackTrace();
                            System.out.println(e + "5");
                        }
                        return;

                    default:
                        break;
                }

                if (hdr.type != 0)
                    log.error(ExternalStrings.ENCRYPT1_4_ERROR__HEADER_IS_NOT_0);

                // not have shared key yet
                // this encrypted message is of no use, drop it
                if(desKey == null) return;

		    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_STARTING_TO_DECYPHER_MESSAGES);

                // if both the shared key and incoming message are not null
                // decrypt the message
                if(msg.getBuffer() != null) {
                    try {
                        cipher.init(Cipher.DECRYPT_MODE, desKey);
                        msg.setBuffer(cipher.doFinal(msg.getBuffer()));
                    }
                    catch(Exception e) {
			e.printStackTrace();
                    }
                }
                break;
        }

	    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_PASSING_UP_EVENT);
        passUp(evt);            // Pass up to the layer above us
    }

    @Override // GemStoneAddition
    public void down(Event evt) {
        Message msg;
        Message newMsg;
        boolean leave=false;

        if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_DOWNEVT_IS_0_1, new Object[] {evt, Integer.valueOf(evt.getType())});

        switch(evt.getType()) {

        case Event.VIEW_CHANGE:

            if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_VIEW_CHANGE_CALL_NEW_MEMBER_COMING_IN);
            Vector new_members=((View)evt.getArg()).getMembers();

            // member size decreases: member leaves, need a new key
            if(members.size() > new_members.size()) leave=true;

            // copy member list
            synchronized(members) {
                members.removeAllElements();
                if(/*new_members != null && GemStoneAddition (cannot be null) */ new_members.size() > 0)
                    for(int i=0; i < new_members.size(); i++)
                        members.addElement(new_members.elementAt(i));
            }// end of sync

            // redistribute/regain the new key because old member leaves
            if(leave) {
                // get coordinator address
                Object obj=members.firstElement();

                // if I'm the coordinator/key-server
                if(obj.equals(local_addr)) {
                    //create the new shared key and distribute
                    keyServer=true;
                    keyServerAddr=local_addr;

                    // reset shared key
                    desKey=null;

                    if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_LEAVE_CAUSED_DESKEY_TO_BE_NULL);

                    try {
                        //generate new shared key
                        KeyGenerator keyGen=KeyGenerator.getInstance(getAlgorithm(symAlgorithm));
                        keyGen.init(symInit);
                        desKey=keyGen.generateKey();
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }//end of local_addr == obj
                // if I'm not the coordinator/key-server
                else {
                    keyServer=false;
                    keyServerAddr=(Address)obj;

                    // reset shared key
                    desKey=null;

                    // client send clien's public key to server and request server's public key
                    newMsg=new Message(keyServerAddr, local_addr, Kpair.getPublic().getEncoded());
                    // making changes (MANDAR)
                    newMsg.putHeader(EncryptHeader.KEY, new EncryptHeader(EncryptHeader.KEY_REQUEST));
                    passDown(new Event(Event.MSG, newMsg));

                    if(log.isDebugEnabled()) log.debug("Requesting new key to be part of group");
                } // end of else
            }
            break;

        case Event.MSG:
            msg= (Message) evt.getArg();

            if(log.isDebugEnabled()) log.debug("Its a message call " + msg);
            int i;

            // For Server:
            // if some members don't have the shared key yet
            if(!notReady.isEmpty())
            {
                System.out.println("not Ready list  :" + notReady.toString());
                if(msg.getDest() == null) {
                    for(i=0; i < notReady.size(); i++) {
                        // making changes (MANDAR)
                        newMsg=new Message((Address)notReady.elementAt(i), local_addr, msg.getBuffer());
                        passDown(new Event(Event.MSG, newMsg));
                    }
                    break;
                }
                else
                {
                    for(i=0; i < notReady.size(); i++) {
                        if(msg.getDest().equals(notReady.elementAt(i))) {
                            passDown(evt);
                            return;
                        }// end of if..
                    }// end of for..
                }// end of else
            }

            // I already know the shared key
            if(desKey != null)
            {

                if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_DESKEY_IS_NOT_NULL_I_KNOW_IT);
                try
                {
                    // if the message is not empty, encrypt it
                    if(msg.getBuffer() != null)
                    {
                        cipher.init(Cipher.ENCRYPT_MODE, desKey);
                        msg.setBuffer(cipher.doFinal(msg.getBuffer()));
                        msg.putHeader(EncryptHeader.KEY, new EncryptHeader(0));

                        if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_HAVE_DES_KEY__PACKAGE_SENT);
                    }
                    else
                    {
                        msg.setBuffer(null);
                        msg.putHeader(EncryptHeader.KEY, new EncryptHeader(0));

                        if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_BUFFER_NULL_ADDED_HEADER);
                    }
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
            break;
        }// check des key..

        if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_PASS_DOWN__0, evt.toString());
        passDown(evt);          // Pass on to the layer below us
    }

    private SecretKey decodedKey(byte[] encodedKey) {
        SecretKey key=null;
        try {
            //change needed mandar
            SecretKeyFactory KeyFac=SecretKeyFactory.getInstance(getAlgorithm(symAlgorithm));
            SecretKeySpec desKeySpec=new SecretKeySpec(encodedKey, getAlgorithm(symAlgorithm));
            key=KeyFac.generateSecret(desKeySpec);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return key;
    }

    private PublicKey generatePubKey(byte[] encodedKey) {
        PublicKey tmpPubKey=null;
        try {
            KeyFactory KeyFac=KeyFactory.getInstance(getAlgorithm(asymAlgorithm));
            X509EncodedKeySpec x509KeySpec=new X509EncodedKeySpec(encodedKey);
            tmpPubKey=KeyFac.generatePublic(x509KeySpec);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return tmpPubKey;
    }
}


text:
'use strict'
var obj = require('../src/basic.30.arrays');

describe("basic.30.arrays.general" , function(){

  it("fruits should be of an Instance of Array and have a length of 3", function(){
    obj.fruits.should.be.eql(["Apple", "Banana", "Kiwi"]);
    obj.v1_value.should.be.exactly("3");
	});

  it('v2 should be equal to "Apple" and of type string', function(){
    obj.v2.should.be.exactly("Apple");
    obj.v2_value.should.be.exactly("Apple");
    obj.v2_type.should.be.exactly("string");
	});

  it('v3 should be equal to undefined' , function(){
    (typeof(obj.v3) === 'undefined').should.be.true;
    obj.v3_value.should.be.exactly("undefined");
    obj.v3_type.should.be.exactly("undefined");
	});

  it('v4 should be equal to "Kiwi" and of type string', function(){
    obj.v4.should.be.exactly("Kiwi");
    obj.v4_value.should.be.exactly("Kiwi");
    obj.v4_type.should.be.exactly("string");
	});

  it('v5 should be equal to 3  ', function(){
    obj.veggies.should.be.eql(["Cabbage","Celery","Potato"]);
    obj.v5.should.be.exactly(3);
    obj.v5_value.should.be.exactly("3");
	});

  it('v6 should be equal to "Cabbage"  ', function(){
    obj.v6.should.be.exactly("Cabbage");
    obj.v6_value.should.be.exactly("Cabbage");
	});

  it('v7 should be equal to "Celery"  ', function(){
    obj.v7.should.be.exactly("Celery");
    obj.v7_value.should.be.exactly("Celery");
	});

  it('v8 should be equal to "Potato"  ', function(){
    obj.v8.should.be.exactly("Potato");
    obj.v8_value.should.be.exactly("Potato");
	});

  it('v9 should be undefined  ', function(){
    (typeof(obj.v9) === "undefined").should.be.true;
    obj.v9_value.should.be.exactly("undefined");
	});

  it('v10 should be 10  ', function(){
    obj.v10.should.be.exactly(10);
    obj.v10_value.should.be.exactly("10");
	});

   it('v11 should be undefined  ', function(){
    (typeof(obj.v11) === "undefined").should.be.true;
    obj.v11_value.should.be.exactly("undefined");
	});

}); //end of describe

describe ("basic.30.arrays.add" , function(){

  it(' v12 should be 2 ', function(){
    obj.dairy.should.be.eql(["Milk","Cheese"]);
    obj.v12_value.should.be.exactly("2");
	});

  it('v14 should be 3 , v15 should be "rye" ', function(){
    obj.breads.should.be.eql(["white","wheat","rye"]);
    obj.v14.should.be.exactly(3);
    obj.v14_value.should.be.exactly("3");
    obj.v15.should.be.exactly("rye");
    obj.v15_value.should.be.exactly("rye");
	});

   it('v16 should be 3 , v17 should be "corn" ', function(){
    obj.grains.should.be.eql(["rice","barley","corn"]);
    obj.v16.should.be.exactly(3);
    obj.v16_value.should.be.exactly("3");
    obj.v17.should.be.exactly("corn");
    obj.v17_value.should.be.exactly("corn");
  });

});// end of describe

describe ("basic.30.arrays.remove" , function(){

 it('v18 should be "basmati" , v19 should be undefined ', function(){
    obj.rice.should.be.eql(["white","brown"]);
    obj.v18.should.be.exactly("basmati");
    obj.v18_value.should.be.exactly("basmati");
    (typeof(obj.v19) === 'undefined').should.be.exactly(true);
    obj.v19_value.should.be.exactly("undefined");
  });

 it('v20 should be "fusilli" , v21 should be "spaghetti" ', function(){
    obj.pasta.should.be.eql(["spaghetti","fettuccine"]);
    obj.v20.should.be.exactly("fusilli");
    obj.v20_value.should.be.exactly("fusilli");
    obj.v21.should.be.exactly("spaghetti");
    obj.v21_value.should.be.exactly("spaghetti");
  });

});// end of describe

//arrays.find

describe ("basic.30.arrays.find" , function(){

 it('v23 should be true ', function(){
    obj.pizzas.should.be.eql(["New York" , "Chicago" , "Sicilian"]);
    obj.v22.should.be.exactly("Chicago");
    obj.v23.should.be.exactly(obj.pizzas.includes(obj.v22));
    obj.v23_value.should.be.exactly(obj.v23.toString());
  });

 it('v25 should be 2 ', function(){
    obj.sushi.should.be.eql(["nigri" , "sashimi" , "maki"]);
    obj.v24.should.be.exactly("maki");
    obj.v25.should.be.exactly(obj.sushi.indexOf(obj.v24));
    obj.v25_value.should.be.exactly(obj.v25.toString());
  });

});// end of describe

//arrays.misc

describe ("basic.30.arrays.misc" , function(){

 it('v26 should be "chicago" ', function(){
    obj.sushiPizza.should.be.eql(["nigri","maki","chicago"]);
    obj.v26.should.be.exactly("chicago");
    obj.v26_value.should.be.exactly(obj.v26.toString());
  });

	it('v27 should be "asian" ', function(){
    obj.apples.should.be.eql(["gala","fuji","asian"]);
    obj.v27.should.be.exactly("asian");
    obj.v27_value.should.be.exactly(obj.v27.toString());
  });

	it('v28 should be \'undefined\' and v29 should be \'latte\' ', function(){
    obj.coffee.should.be.eql(["espresso" , "cappuccino"]);;
    obj.moreCoffee.should.be.eql(["espresso" , "cappuccino",'latte']);;
		(typeof (v28) === 'undefined').should.be.eql(true);
    obj.v29_value.should.be.eql(obj.moreCoffee[2]);
		obj.v29_value.should.be.exactly(obj.v29.toString());
  });

});// end of describe

describe ("basic.30.arrays.bonus.isGrapeFruit" , function(){

  it("isGrapeFruit() should throw an Exception", function(){
    (() => obj.isGrapeFruit()).should.throw();
  });

  it("isGrapeFruit('grape fruit') should throw an Exception", function(){
    (() => obj.isGrapeFruit('grape fruit')).should.throw();
  });

  it('isGrapeFruit(["Apple",1,true]) should return false', function(){
    obj.isGrapeFruit(["Apple",1,true]).should.be.exactly(false);
  });

  it('isGrapeFruit(["Apple","grape fruit"]) should return true', function(){
    obj.isGrapeFruit(["Apple", "grape fruit"]).should.be.exactly(true);

  });
  it('isGrapeFruit(["Apple","grape fruit","b"]) should return true', function(){
    obj.isGrapeFruit(["Apple", "grape fruit","b"]).should.be.exactly(true);

  });

}); //end of describe

describe ("basic.30.arrays.bonus.swapify" , function(){

	it("swapify() should throw an Exception", function(){
    (() => obj.swapify()).should.throw();
  });

  it("swapify('grape fruit') should throw an Exception", function(){
    (() => obj.swapify('grape fruit')).should.throw();
  });

	it('swapify(["A"]) should throw an Exception', function(){
    (() => obj.swapify(["a"])).should.throw();
  });

//	it('swapify(["A",,"B"]) should throw an Exception', function(){
//    (() => obj.swapify(["a","b"])).should.throw();
//  });

  it('swapify(["A", "B"]) should return ["B", "A"]', function(){
    let arr = ["A","B"];
    obj.swapify(arr);
    arr.should.be.eql(["B","A"]);
  });

}); //end of describe

describe ("basic.30.arrays.bonus.stringify" , function(){

  it("stringify() should return []", function(){
    obj.stringify().should.be.eql([]);
  });

  it('stringify(["Apple",1,true]) should return ["Apple"]', function(){
    obj.stringify(["Apple",1,true]).should.be.eql(["Apple"]);
  });

}); //end of describe

describe ("basic.30.arrays.bonus.numberify" , function(){

  it("numberify() should return []", function(){
    obj.numberify().should.be.eql([]);
  });

  it("numberify([Infinity]) should return [Infinity]", function(){
    obj.numberify([Infinity]).should.be.eql([Infinity]);
  });

  it('numberify([NaN,undefined,null,\'\',,false])should return []', function(){
    obj.numberify([NaN,undefined,null,'',,false]).should.be.eql([]);
  });

  it('numberify([\'0\',1,2,true,\'Orange\',\'3\',NaN]) should return [1,2]', function(){
    obj.numberify(['0',1,2,true,"Orange","3",NaN]).should.be.eql([1,2]);
  });

}); //end of describe

describe("basic.30.arrays.bonus.countVowels" , function(){

  it('countVowels("abc def") should return 2" ', function(){
    obj.countVowels("abc def").should.be.eql(2);
	});

  it('countVowels("abc def ghi") should return 3 ', function(){
    obj.countVowels("abc def ghi").should.be.eql(3);
	});

  it('countVowels("aeiou") should return 5 ', function(){
    obj.countVowels("aeiou").should.be.eql(5);
	});

  it('countVowels("The Jean Genie") should return 6 ', function(){
    obj.countVowels("The Jean Genie").should.be.eql(6);
	});

  it('countVowels() should throw an Exception ', function(){
    (() => obj.countVowels()).should.throw();
	});
}); //end of describe

describe ("basic.30.arrays.bonus.maxNumber" , function(){

  it("maxNumber() should throw an Exception", function(){
    (() => obj.maxNumber()).should.throw();
  });

  it('maxNumber(["1","2","3"]) should throw an Exception', function(){
    (() => obj.maxNumber(["1","2","3"])).should.throw();
  });

  it("maxNumber([1,Infinity,3]) should return Infinity", function(){
    obj.maxNumber([1,Infinity,3]).should.be.eql(Infinity);
  });

   it('maxNumber([5,"80",70,20,55]) should return 70', function(){
    obj.maxNumber([5,"80",70,20,55]).should.be.eql(70);
  });

}); //end of describe


text:
package org.sagebionetworks.web.client.widget.accessrequirements.createaccessrequirement;

import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.html.Div;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class CreateManagedACTAccessRequirementStep2ViewImpl implements CreateManagedACTAccessRequirementStep2View {

	public interface Binder extends UiBinder<Widget, CreateManagedACTAccessRequirementStep2ViewImpl> {
	}

	Widget widget;
	@UiField
	Div wikiPageContainer;
	@UiField
	Button editWikiButton;
	@UiField
	CheckBox certifiedCheckbox;
	@UiField
	CheckBox validatedCheckbox;
	@UiField
	CheckBox ducCheckbox;
	@UiField
	Div ducTemplateFileContainer;
	@UiField
	Div ducTemplateFileUploadContainer;
	@UiField
	CheckBox irbCheckbox;
	@UiField
	CheckBox iduCheckbox;
	@UiField
	CheckBox otherAttachmentsCheckbox;
	@UiField
	TextBox expirationPeriodTextbox;
	@UiField
	CheckBox intendedDataUsePublicCheckbox;

	Presenter presenter;

	@Inject
	public CreateManagedACTAccessRequirementStep2ViewImpl(Binder binder) {
		widget = binder.createAndBindUi(this);
		editWikiButton.addClickHandler(event -> {
			presenter.onEditWiki();
		});
		iduCheckbox.addValueChangeHandler(event -> {
			intendedDataUsePublicCheckbox.setEnabled(event.getValue());
			// SWC-5319: if IDU is optional (required==false), clear the IDU public checkbox
			if (!event.getValue() ) {
				intendedDataUsePublicCheckbox.setValue(false);
			}
		});
	}

	@Override
	public Widget asWidget() {
		return widget;
	}

	@Override
	public void setPresenter(Presenter p) {
		this.presenter = p;
	}

	@Override
	public void setAreOtherAttachmentsRequired(boolean value) {
		otherAttachmentsCheckbox.setValue(value);
	}

	@Override
	public void setExpirationPeriod(String value) {
		expirationPeriodTextbox.setValue(value);
	}

	@Override
	public String getExpirationPeriod() {
		return expirationPeriodTextbox.getValue();
	}

	@Override
	public void setIsCertifiedUserRequired(boolean value) {
		certifiedCheckbox.setValue(value);
	}

	@Override
	public void setIsDUCRequired(boolean value) {
		ducCheckbox.setValue(value);
	}

	@Override
	public void setIsIDUPublic(boolean value) {
		intendedDataUsePublicCheckbox.setValue(value);
	}

	@Override
	public void setIsIDURequired(boolean value) {
		iduCheckbox.setValue(value);
		intendedDataUsePublicCheckbox.setEnabled(value);
	}

	@Override
	public void setIsIRBApprovalRequired(boolean value) {
		irbCheckbox.setValue(value);
	}

	@Override
	public void setIsValidatedProfileRequired(boolean value) {
		validatedCheckbox.setValue(value);
	}

	@Override
	public boolean areOtherAttachmentsRequired() {
		return otherAttachmentsCheckbox.getValue();
	}

	@Override
	public boolean isCertifiedUserRequired() {
		return certifiedCheckbox.getValue();
	}

	@Override
	public boolean isDUCRequired() {
		return ducCheckbox.getValue();
	}

	@Override
	public boolean isIDURequired() {
		return iduCheckbox.getValue();
	}

	@Override
	public boolean isIDUPublic() {
		return intendedDataUsePublicCheckbox.getValue();
	}

	@Override
	public boolean isIRBApprovalRequired() {
		return irbCheckbox.getValue();
	}

	@Override
	public boolean isValidatedProfileRequired() {
		return validatedCheckbox.getValue();
	}

	@Override
	public void setWikiPageRenderer(IsWidget w) {
		wikiPageContainer.clear();
		wikiPageContainer.add(w);
	}

	@Override
	public void setDUCTemplateUploadWidget(IsWidget w) {
		ducTemplateFileUploadContainer.clear();
		ducTemplateFileUploadContainer.add(w);
	}

	@Override
	public void setDUCTemplateWidget(IsWidget w) {
		ducTemplateFileContainer.clear();
		ducTemplateFileContainer.add(w);
	}

}


text:
namespace spvtools {
namespace reduce {
namespace {

TEST(OperandToConstantReductionPassTest, BasicCheck) {
  std::string prologue = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main" %37
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
               OpName %4 "main"
               OpName %9 "buf1"
               OpMemberName %9 0 "f"
               OpName %11 ""
               OpName %24 "buf2"
               OpMemberName %24 0 "i"
               OpName %26 ""
               OpName %37 "_GLF_color"
               OpMemberDecorate %9 0 Offset 0
               OpDecorate %9 Block
               OpDecorate %11 DescriptorSet 0
               OpDecorate %11 Binding 1
               OpMemberDecorate %24 0 Offset 0
               OpDecorate %24 Block
               OpDecorate %26 DescriptorSet 0
               OpDecorate %26 Binding 2
               OpDecorate %37 Location 0
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeFloat 32
          %9 = OpTypeStruct %6
         %10 = OpTypePointer Uniform %9
         %11 = OpVariable %10 Uniform
         %12 = OpTypeInt 32 1
         %13 = OpConstant %12 0
         %14 = OpTypePointer Uniform %6
         %20 = OpConstant %6 2
         %24 = OpTypeStruct %12
         %25 = OpTypePointer Uniform %24
         %26 = OpVariable %25 Uniform
         %27 = OpTypePointer Uniform %12
         %33 = OpConstant %12 3
         %35 = OpTypeVector %6 4
         %36 = OpTypePointer Output %35
         %37 = OpVariable %36 Output
          %4 = OpFunction %2 None %3
          %5 = OpLabel
         %15 = OpAccessChain %14 %11 %13
         %16 = OpLoad %6 %15
         %19 = OpFAdd %6 %16 %16
         %21 = OpFAdd %6 %19 %20
         %28 = OpAccessChain %27 %26 %13
         %29 = OpLoad %12 %28
  )";

  std::string epilogue = R"(
         %45 = OpConvertSToF %6 %34
         %46 = OpCompositeConstruct %35 %16 %21 %43 %45
               OpStore %37 %46
               OpReturn
               OpFunctionEnd
  )";

  std::string original = prologue + R"(
         %32 = OpIAdd %12 %29 %29
         %34 = OpIAdd %12 %32 %33
         %43 = OpConvertSToF %6 %29
  )" + epilogue;

  std::string expected = prologue + R"(
         %32 = OpIAdd %12 %13 %13 ; %29 -> %13 x 2
         %34 = OpIAdd %12 %13 %33 ; %32 -> %13
         %43 = OpConvertSToF %6 %13 ; %29 -> %13
  )" + epilogue;

  const auto env = SPV_ENV_UNIVERSAL_1_3;
  const auto consumer = nullptr;
  const auto context =
      BuildModule(env, consumer, original, kReduceAssembleOption);
  const auto ops =
      OperandToConstReductionOpportunityFinder().GetAvailableOpportunities(
          context.get(), 0);
  ASSERT_EQ(17, ops.size());
  ASSERT_TRUE(ops[0]->PreconditionHolds());
  ops[0]->TryToApply();
  ASSERT_TRUE(ops[1]->PreconditionHolds());
  ops[1]->TryToApply();
  ASSERT_TRUE(ops[2]->PreconditionHolds());
  ops[2]->TryToApply();
  ASSERT_TRUE(ops[3]->PreconditionHolds());
  ops[3]->TryToApply();

  CheckEqual(env, expected, context.get());
}

TEST(OperandToConstantReductionPassTest, WithCalledFunction) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main" %10 %12
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeFloat 32
          %7 = OpTypeVector %6 4
          %8 = OpTypeFunction %7
          %9 = OpTypePointer Output %7
         %10 = OpVariable %9 Output
         %11 = OpTypePointer Input %7
         %12 = OpVariable %11 Input
         %13 = OpConstant %6 0
         %14 = OpConstantComposite %7 %13 %13 %13 %13
          %4 = OpFunction %2 None %3
          %5 = OpLabel
         %15 = OpFunctionCall %7 %16
               OpReturn
               OpFunctionEnd
         %16 = OpFunction %7 None %8
         %17 = OpLabel
               OpReturnValue %14
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_3;
  const auto consumer = nullptr;
  const auto context =
      BuildModule(env, consumer, shader, kReduceAssembleOption);
  const auto ops =
      OperandToConstReductionOpportunityFinder().GetAvailableOpportunities(
          context.get(), 0);
  ASSERT_EQ(0, ops.size());
}

TEST(OperandToConstantReductionPassTest, TargetSpecificFunction) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 320
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeInt 32 1
          %7 = OpTypePointer Function %6
          %8 = OpTypeFunction %6 %7
         %17 = OpConstant %6 1
         %20 = OpConstant %6 2
         %23 = OpConstant %6 0
         %24 = OpTypeBool
         %35 = OpConstant %6 3
         %53 = OpConstant %6 10
          %4 = OpFunction %2 None %3
          %5 = OpLabel
         %65 = OpVariable %7 Function
         %68 = OpVariable %7 Function
         %73 = OpVariable %7 Function
               OpStore %65 %35
         %66 = OpLoad %6 %65
         %67 = OpIAdd %6 %66 %17
               OpStore %65 %67
         %69 = OpLoad %6 %65
               OpStore %68 %69
         %70 = OpFunctionCall %6 %13 %68
         %71 = OpLoad %6 %65
         %72 = OpIAdd %6 %71 %70
               OpStore %65 %72
         %74 = OpLoad %6 %65
               OpStore %73 %74
         %75 = OpFunctionCall %6 %10 %73
         %76 = OpLoad %6 %65
         %77 = OpIAdd %6 %76 %75
               OpStore %65 %77
               OpReturn
               OpFunctionEnd
         %10 = OpFunction %6 None %8
          %9 = OpFunctionParameter %7
         %11 = OpLabel
         %15 = OpVariable %7 Function
         %16 = OpLoad %6 %9
         %18 = OpIAdd %6 %16 %17
               OpStore %15 %18
         %19 = OpLoad %6 %15
         %21 = OpIAdd %6 %19 %20
               OpStore %15 %21
         %22 = OpLoad %6 %15
         %25 = OpSGreaterThan %24 %22 %23
               OpSelectionMerge %27 None
               OpBranchConditional %25 %26 %27
         %26 = OpLabel
         %28 = OpLoad %6 %9
               OpReturnValue %28
         %27 = OpLabel
         %30 = OpLoad %6 %9
         %31 = OpIAdd %6 %30 %17
               OpReturnValue %31
               OpFunctionEnd
         %13 = OpFunction %6 None %8
         %12 = OpFunctionParameter %7
         %14 = OpLabel
         %41 = OpVariable %7 Function
         %46 = OpVariable %7 Function
         %55 = OpVariable %7 Function
         %34 = OpLoad %6 %12
         %36 = OpIEqual %24 %34 %35
               OpSelectionMerge %38 None
               OpBranchConditional %36 %37 %38
         %37 = OpLabel
         %39 = OpLoad %6 %12
         %40 = OpIMul %6 %20 %39
               OpStore %41 %40
         %42 = OpFunctionCall %6 %10 %41
               OpReturnValue %42
         %38 = OpLabel
         %44 = OpLoad %6 %12
         %45 = OpIAdd %6 %44 %17
               OpStore %12 %45
               OpStore %46 %23
               OpBranch %47
         %47 = OpLabel
               OpLoopMerge %49 %50 None
               OpBranch %51
         %51 = OpLabel
         %52 = OpLoad %6 %46
         %54 = OpSLessThan %24 %52 %53
               OpBranchConditional %54 %48 %49
         %48 = OpLabel
         %56 = OpLoad %6 %12
               OpStore %55 %56
         %57 = OpFunctionCall %6 %10 %55
         %58 = OpLoad %6 %12
         %59 = OpIAdd %6 %58 %57
               OpStore %12 %59
               OpBranch %50
         %50 = OpLabel
         %60 = OpLoad %6 %46
         %61 = OpIAdd %6 %60 %17
               OpStore %46 %61
               OpBranch %47
         %49 = OpLabel
         %62 = OpLoad %6 %12
               OpReturnValue %62
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_3;
  const auto consumer = nullptr;
  const auto context =
      BuildModule(env, consumer, shader, kReduceAssembleOption);

  // Targeting all functions, there are quite a few opportunities.  To avoid
  // making the test too sensitive, we check that there are more than a number
  // somewhat lower than the real number.
  const auto all_ops =
      OperandToConstReductionOpportunityFinder().GetAvailableOpportunities(
          context.get(), 0);
  ASSERT_TRUE(all_ops.size() > 100);

  // Targeting individual functions, there are fewer opportunities.  Again, we
  // avoid checking against an exact number so that the test is not too
  // sensitive.
  const auto ops_for_function_4 =
      OperandToConstReductionOpportunityFinder().GetAvailableOpportunities(
          context.get(), 4);
  const auto ops_for_function_10 =
      OperandToConstReductionOpportunityFinder().GetAvailableOpportunities(
          context.get(), 10);
  const auto ops_for_function_13 =
      OperandToConstReductionOpportunityFinder().GetAvailableOpportunities(
          context.get(), 13);
  ASSERT_TRUE(ops_for_function_4.size() < 60);
  ASSERT_TRUE(ops_for_function_10.size() < 50);
  ASSERT_TRUE(ops_for_function_13.size() < 80);

  // The total number of opportunities should be the sum of the per-function
  // opportunities.
  ASSERT_EQ(all_ops.size(), ops_for_function_4.size() +
                                ops_for_function_10.size() +
                                ops_for_function_13.size());
}

}  // namespace
}  // namespace reduce
}  // namespace spvtools


text:
package com.azure.cosmos.implementation

import org.apache.spark.sql.Row

private[cosmos] case class SparkRowItem
(
  row: Row
)


text:
/* global Log, Module, moment */

/* Magic Mirror
 * Module: Compliments
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */
Module.register("compliments", {

	// Module config defaults.
	defaults: {
		compliments: {
			anytime: [
				"Hey there sexy!"
			],
			morning: [
				"Good morning, handsome!",
				"Enjoy your day!",
				"How was your sleep?"
			],
			afternoon: [
				"Hello, beauty!",
				"You look sexy!",
				"Looking good today!"
			],
			evening: [
				"Wow, you look hot!",
				"You look nice!",
				"Hi, sexy!"
			]
		},
		updateInterval: 30000,
		remoteFile: null,
		fadeSpeed: 4000,
		morningStartTime: 3,
		morningEndTime: 12,
		afternoonStartTime: 12,
		afternoonEndTime: 17
	},

	// Set currentweather from module
	currentWeatherType: "",

	// Define required scripts.
	getScripts: function() {
		return ["moment.js"];
	},

	// Define start sequence.
	start: function() {
		Log.info("Starting module: " + this.name);

		this.lastComplimentIndex = -1;

		var self = this;
		if (this.config.remoteFile !== null) {
			this.complimentFile(function(response) {
				self.config.compliments = JSON.parse(response);
				self.updateDom();
			});
		}

		// Schedule update timer.
		setInterval(function() {
			self.updateDom(self.config.fadeSpeed);
		}, this.config.updateInterval);
	},

	/* randomIndex(compliments)
	 * Generate a random index for a list of compliments.
	 *
	 * argument compliments Array<String> - Array with compliments.
	 *
	 * return Number - Random index.
	 */
	randomIndex: function(compliments) {
		if (compliments.length === 1) {
			return 0;
		}

		var generate = function() {
			return Math.floor(Math.random() * compliments.length);
		};

		var complimentIndex = generate();

		while (complimentIndex === this.lastComplimentIndex) {
			complimentIndex = generate();
		}

		this.lastComplimentIndex = complimentIndex;

		return complimentIndex;
	},

	/* complimentArray()
	 * Retrieve an array of compliments for the time of the day.
	 *
	 * return compliments Array<String> - Array with compliments for the time of the day.
	 */
	complimentArray: function() {
		var hour = moment().hour();
		var compliments;

		if (hour >= this.config.morningStartTime && hour < this.config.morningEndTime && this.config.compliments.hasOwnProperty("morning")) {
			compliments = this.config.compliments.morning.slice(0);
		} else if (hour >= this.config.afternoonStartTime && hour < this.config.afternoonEndTime && this.config.compliments.hasOwnProperty("afternoon")) {
			compliments = this.config.compliments.afternoon.slice(0);
		} else if(this.config.compliments.hasOwnProperty("evening")) {
			compliments = this.config.compliments.evening.slice(0);
		}

		if (typeof compliments === "undefined") {
			compliments = new Array();
		}

		if (this.currentWeatherType in this.config.compliments) {
			compliments.push.apply(compliments, this.config.compliments[this.currentWeatherType]);
		}

		compliments.push.apply(compliments, this.config.compliments.anytime);

		return compliments;
	},

	/* complimentFile(callback)
	 * Retrieve a file from the local filesystem
	 */
	complimentFile: function(callback) {
		var xobj = new XMLHttpRequest(),
			isRemote = this.config.remoteFile.indexOf("http://") === 0 || this.config.remoteFile.indexOf("https://") === 0,
			path = isRemote ? this.config.remoteFile : this.file(this.config.remoteFile);
		xobj.overrideMimeType("application/json");
		xobj.open("GET", path, true);
		xobj.onreadystatechange = function() {
			if (xobj.readyState === 4 && xobj.status === 200) {
				callback(xobj.responseText);
			}
		};
		xobj.send(null);
	},

	/* complimentArray()
	 * Retrieve a random compliment.
	 *
	 * return compliment string - A compliment.
	 */
	randomCompliment: function() {
		var compliments = this.complimentArray();
		var index = this.randomIndex(compliments);

		return compliments[index];
	},

	// Override dom generator.
	getDom: function() {
		var complimentText = this.randomCompliment();

		var compliment = document.createTextNode(complimentText);
		var wrapper = document.createElement("div");
		wrapper.className = this.config.classes ? this.config.classes : "thin xlarge bright pre-line";
		wrapper.appendChild(compliment);

		return wrapper;
	},

	// From data currentweather set weather type
	setCurrentWeatherType: function(data) {
		var weatherIconTable = {
			"01d": "day_sunny",
			"02d": "day_cloudy",
			"03d": "cloudy",
			"04d": "cloudy_windy",
			"09d": "showers",
			"10d": "rain",
			"11d": "thunderstorm",
			"13d": "snow",
			"50d": "fog",
			"01n": "night_clear",
			"02n": "night_cloudy",
			"03n": "night_cloudy",
			"04n": "night_cloudy",
			"09n": "night_showers",
			"10n": "night_rain",
			"11n": "night_thunderstorm",
			"13n": "night_snow",
			"50n": "night_alt_cloudy_windy"
		};
		this.currentWeatherType = weatherIconTable[data.weather[0].icon];
	},

	// Override notification handler.
	notificationReceived: function(notification, payload, sender) {
		if (notification === "CURRENTWEATHER_DATA") {
			this.setCurrentWeatherType(payload.data);
		}
	},

});


text:
layout: post
title: Docker Workflow
description: TODO description
---

I have a my little routine with docker, i have few scripts so i don't have to type the same things over and over, and it just works, and i have i little things that might be useful to you
My workflow changed i lot since i started with docker, at the begining i aws using docker-compose and loving it, but since we stated deployning containers docker-compose was not the best aprroach
Docker Compose
"Compose is a tool for defining and running multi-container Docker applications"
It works finne
Simple tip:
At the top of the, declare things that wont likely change
Keep the middle for things that will change often with the build
Things that will happend everytime you run a buiild

Docker compose doesn't play well with deploying containers
Docker compose makes links containers easy, it simplifies orcastration

https://github.com/yurifrl/boilerplate
{% highlight shell %}
./q
./production.yml
./Dockerfile
./work.log
./TODO.md
./init.sh
./deploy.sh
./kube.yaml
./VERSION
{% endhighlight %}

Let's take a look at my work environment,  this is basically every one of my projects, i will go through every file.

{% highlight shell %}
# ./docker-compose.yml
version: '2'
services:
  web:
    image: mhart/alpine-node
    ports:
      - 81:81
    working_dir: /web
    command: npm run start
    volumes:
      - ./:/web
      - node_modules:/app/node_modules

volumes:
  node_modules:
    driver: local
{% endhighlight %}

This is probably my favorite file, here i use a alpine image to run my node apps, i just run a `docker-compose run --rm web npm install`, and that will fetch my dependencies, at the first run it will ask to create the volumes and you simply run `docker volume create --name=node_modules`

{% highlight shell %}
# ./init.sh
#!/bin/bash

# Use deploy directory as working directory
parent_path=$( cd "$(dirname "${BASH_SOURCE}")" ; pwd -P )
cd "$parent_path"

# halt on any error
set -e

dg() {
  docker run --rm -ti -w /current \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v $HOME/.ssh:/.ssh \
    -v $(pwd):/current \
    --volumes-from gcloud-config yurifl/gcloud $@
}

/usr/bin/vim ../VERSION

VERSION=$(cat ../VERSION)

Docker-compose -f production.yml build

docker tag docker-workflow "gcr.io/yebo-project/docker-workflow:latest"
dg gcloud docker push "gcr.io/yebo-project/docker-workflow:latest"

echo "dg kubectl create -f ./config/kube.yaml"
echo "dg kubectl delete -f ./config/kube.yaml"

dg kubectl get svc
dg kubectl get rc
{% endhighlight %}


text:
"use strict";

module.exports = Pointer;

const $Ref = require("./ref");
const url = require("./util/url");
const { JSONParserError, InvalidPointerError, MissingPointerError, isHandledError } = require("./util/errors");
const slashes = /\//g;
const tildes = /~/g;
const escapedSlash = /~1/g;
const escapedTilde = /~0/g;

/**
 * This class represents a single JSON pointer and its resolved value.
 *
 * @param {$Ref} $ref
 * @param {string} path
 * @param {string} [friendlyPath] - The original user-specified path (used for error messages)
 * @constructor
 */
function Pointer ($ref, path, friendlyPath) {
  /**
   * The {@link $Ref} object that contains this {@link Pointer} object.
   * @type {$Ref}
   */
  this.$ref = $ref;

  /**
   * The file path or URL, containing the JSON pointer in the hash.
   * This path is relative to the path of the main JSON schema file.
   * @type {string}
   */
  this.path = path;

  /**
   * The original path or URL, used for error messages.
   * @type {string}
   */
  this.originalPath = friendlyPath || path;

  /**
   * The value of the JSON pointer.
   * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
   * @type {?*}
   */
  this.value = undefined;

  /**
   * Indicates whether the pointer references itself.
   * @type {boolean}
   */
  this.circular = false;

  /**
   * The number of indirect references that were traversed to resolve the value.
   * Resolving a single pointer may require resolving multiple $Refs.
   * @type {number}
   */
  this.indirections = 0;
}

/**
 * Resolves the value of a nested property within the given object.
 *
 * @param {*} obj - The object that will be crawled
 * @param {$RefParserOptions} options
 * @param {string} pathFromRoot - the path of place that initiated resolving
 *
 * @returns {Pointer}
 * Returns a JSON pointer whose {@link Pointer#value} is the resolved value.
 * If resolving this value required resolving other JSON references, then
 * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path
 * of the resolved value.
 */
Pointer.prototype.resolve = function (obj, options, pathFromRoot) {
  let tokens = Pointer.parse(this.path, this.originalPath);

  // Crawl the object, one token at a time
  this.value = unwrapOrThrow(obj);

  for (let i = 0; i < tokens.length; i++) {
    if (resolveIf$Ref(this, options)) {
      // The $ref path has changed, so append the remaining tokens to the path
      this.path = Pointer.join(this.path, tokens.slice(i));
    }

    if (typeof this.value === "object" && this.value !== null && "$ref" in this.value) {
      return this;
    }

    let token = tokens[i];
    if (this.value[token] === undefined || this.value[token] === null) {
      this.value = null;
      throw new MissingPointerError(token, decodeURI(this.originalPath));
    }
    else {
      this.value = this.value[token];
    }
  }

  // Resolve the final value
  if (!this.value || this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot) {
    resolveIf$Ref(this, options);
  }

  return this;
};

/**
 * Sets the value of a nested property within the given object.
 *
 * @param {*} obj - The object that will be crawled
 * @param {*} value - the value to assign
 * @param {$RefParserOptions} options
 *
 * @returns {*}
 * Returns the modified object, or an entirely new object if the entire object is overwritten.
 */
Pointer.prototype.set = function (obj, value, options) {
  let tokens = Pointer.parse(this.path);
  let token;

  if (tokens.length === 0) {
    // There are no tokens, replace the entire object with the new value
    this.value = value;
    return value;
  }

  // Crawl the object, one token at a time
  this.value = unwrapOrThrow(obj);

  for (let i = 0; i < tokens.length - 1; i++) {
    resolveIf$Ref(this, options);

    token = tokens[i];
    if (this.value && this.value[token] !== undefined) {
      // The token exists
      this.value = this.value[token];
    }
    else {
      // The token doesn't exist, so create it
      this.value = setValue(this, token, {});
    }
  }

  // Set the value of the final token
  resolveIf$Ref(this, options);
  token = tokens[tokens.length - 1];
  setValue(this, token, value);

  // Return the updated object
  return obj;
};

/**
 * Parses a JSON pointer (or a path containing a JSON pointer in the hash)
 * and returns an array of the pointer's tokens.
 * (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"])
 *
 * The pointer is parsed according to RFC 6901
 * {@link https://tools.ietf.org/html/rfc6901#section-3}
 *
 * @param {string} path
 * @param {string} [originalPath]
 * @returns {string[]}
 */
Pointer.parse = function (path, originalPath) {
  // Get the JSON pointer from the path's hash
  let pointer = url.getHash(path).substr(1);

  // If there's no pointer, then there are no tokens,
  // so return an empty array
  if (!pointer) {
    return [];
  }

  // Split into an array
  pointer = pointer.split("/");

  // Decode each part, according to RFC 6901
  for (let i = 0; i < pointer.length; i++) {
    pointer[i] = decodeURIComponent(pointer[i].replace(escapedSlash, "/").replace(escapedTilde, "~"));
  }

  if (pointer[0] !== "") {
    throw new InvalidPointerError(pointer, originalPath === undefined ? path : originalPath);
  }

  return pointer.slice(1);
};

/**
 * Creates a JSON pointer path, by joining one or more tokens to a base path.
 *
 * @param {string} base - The base path (e.g. "schema.json#/definitions/person")
 * @param {string|string[]} tokens - The token(s) to append (e.g. ["name", "first"])
 * @returns {string}
 */
Pointer.join = function (base, tokens) {
  // Ensure that the base path contains a hash
  if (base.indexOf("#") === -1) {
    base += "#";
  }

  // Append each token to the base path
  tokens = Array.isArray(tokens) ? tokens : [tokens];
  for (let i = 0; i < tokens.length; i++) {
    let token = tokens[i];
    // Encode the token, according to RFC 6901
    base += "/" + encodeURIComponent(token.replace(tildes, "~0").replace(slashes, "~1"));
  }

  return base;
};

/**
 * If the given pointer's {@link Pointer#value} is a JSON reference,
 * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value.
 * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the
 * resolution path of the new value.
 *
 * @param {Pointer} pointer
 * @param {$RefParserOptions} options
 * @returns {boolean} - Returns `true` if the resolution path changed
 */
function resolveIf$Ref (pointer, options) {
  // Is the value a JSON reference? (and allowed?)

  if ($Ref.isAllowed$Ref(pointer.value, options)) {
    let $refPath = url.resolve(pointer.path, pointer.value.$ref);

    if ($refPath === pointer.path) {
      // The value is a reference to itself, so there's nothing to do.
      pointer.circular = true;
    }
    else {
      let resolved = pointer.$ref.$refs._resolve($refPath, pointer.path, options);
      if (resolved === null) {
        return false;
      }

      pointer.indirections += resolved.indirections + 1;

      if ($Ref.isExtended$Ref(pointer.value)) {
        // This JSON reference "extends" the resolved value, rather than simply pointing to it.
        // So the resolved path does NOT change.  Just the value does.
        pointer.value = $Ref.dereference(pointer.value, resolved.value);
        return false;
      }
      else {
        // Resolve the reference
        pointer.$ref = resolved.$ref;
        pointer.path = resolved.path;
        pointer.value = resolved.value;
      }

      return true;
    }
  }
}

/**
 * Sets the specified token value of the {@link Pointer#value}.
 *
 * The token is evaluated according to RFC 6901.
 * {@link https://tools.ietf.org/html/rfc6901#section-4}
 *
 * @param {Pointer} pointer - The JSON Pointer whose value will be modified
 * @param {string} token - A JSON Pointer token that indicates how to modify `obj`
 * @param {*} value - The value to assign
 * @returns {*} - Returns the assigned value
 */
function setValue (pointer, token, value) {
  if (pointer.value && typeof pointer.value === "object") {
    if (token === "-" && Array.isArray(pointer.value)) {
      pointer.value.push(value);
    }
    else {
      pointer.value[token] = value;
    }
  }
  else {
    throw new JSONParserError(`Error assigning $ref pointer "${pointer.path}". \nCannot set "${token}" of a non-object.`);
  }
  return value;
}

function unwrapOrThrow (value) {
  if (isHandledError(value)) {
    throw value;
  }

  return value;
}


text:
<?php

namespace Dizda\Bundle\AppBundle\Consumer;

use Dizda\Bundle\AppBundle\Exception\IncorrectCallbackResponseException;
use Dizda\Bundle\AppBundle\Service\CallbackService;
use Dizda\Bundle\AppBundle\Traits\MessageQueuingInterface;
use Doctrine\ORM\EntityManager;
use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * Dispatch correct callback to the application
 *
 * Class CallbackConsumer
 */
class CallbackConsumer implements ConsumerInterface
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    /**
     * @var \Dizda\Bundle\AppBundle\Service\CallbackService
     */
    private $callbackService;

    /**
     * @param EntityManager   $em
     * @param CallbackService $callbackService
     */
    public function __construct(EntityManager $em, CallbackService $callbackService)
    {
        $this->em = $em;
        $this->callbackService = $callbackService;
    }

    /**
     * @param AMQPMessage $msg
     *
     * @throws IncorrectCallbackResponseException
     *
     * @return bool
     */
    public function execute(AMQPMessage $msg)
    {
        /**
         * @var integer
         */
        $entityId = unserialize($msg->body);

        $entity = $this->em->getRepository($this->guessRepository($msg->delivery_info['exchange']))->find($entityId);
        $method = $this->guessServiceMethod($msg->delivery_info['exchange']);

        // call HTTP service callback now
        if (!$this->callbackService->$method($entity)) {
            // TODO: add a logger there

            throw new IncorrectCallbackResponseException();
        }

        $entity->setQueueStatus(MessageQueuingInterface::QUEUE_STATUS_PROCESSED);

        $this->em->flush();

        return true;
    }

    /**
     * Return appropriate repository according to the exchange type
     *
     * @param string $exchange
     *
     * @return string
     */
    private function guessRepository($exchange)
    {
        switch ($exchange) {
            case 'deposit-callback':
                return 'DizdaAppBundle:Deposit';
                break;
            case 'deposit-topup-callback':
                return 'DizdaAppBundle:DepositTopup';
                break;
            case 'withdraw-output-callback':
                return 'DizdaAppBundle:WithdrawOutput';
                break;
        }

        return false;
    }

    /**
     * @param string $exchange
     *
     * @return string
     */
    private function guessServiceMethod($exchange)
    {
        switch ($exchange) {
            case 'deposit-callback':
                return 'depositExpectedFilling';
                break;
            case 'deposit-topup-callback':
                return 'depositTopupFilling';
                break;
            case 'withdraw-output-callback':
                return 'withdrawOutputWithdrawn';
                break;
        }

        return false;
    }
}


text:
<!doctype html>

<meta charset="utf-8">
<title>upload</title>

Upload Demo

<form id="f" method="post" enctype="multipart/form-data">

<input type="file" name="upfile" id="upfile">

<input type="submit" value="submit">

</form>

<?php bs::out( bs::data('file') ); ?>


text:
<?php
namespace tests\domain\access\FileAccess;
use vsc\domain\access\FileAccess;

/**
 * @covers \vsc\domain\access\FileAccess::__construct()
 */
class __construct extends \BaseUnitTest
{
	public function testBasicInitialization()
	{
		$o = new FileAccess(__FILE__);
		$this->assertEquals(__FILE__, $o->getUri());
	}
}


text:
"""
Based entirely on Django's own ``setup.py``.
"""
import os
from distutils.command.install import INSTALL_SCHEMES
from distutils.core import setup

def fullsplit(path, result=None):
    """
    Split a pathname into components (the opposite of os.path.join) in a
    platform-neutral way.
    """
    if result is None:
        result = []
    head, tail = os.path.split(path)
    if head == '':
        return [tail] + result
    if head == path:
        return result
    return fullsplit(head, [tail] + result)

# Tell distutils to put the data_files in platform-specific installation
# locations. See here for an explanation:
# http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb
for scheme in INSTALL_SCHEMES.values():
    scheme['data'] = scheme['purelib']

# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
extensions_dir = os.path.join(root_dir, 'django_extensions')
pieces = fullsplit(root_dir)
if pieces[-1] == '':
    len_root_dir = len(pieces) - 1
else:
    len_root_dir = len(pieces)

for dirpath, dirnames, filenames in os.walk(extensions_dir):
    # Ignore dirnames that start with '.'
    for i, dirname in enumerate(dirnames):
        if dirname.startswith('.'):
            del dirnames[i]
    #if 'conf' in dirpath:
    #    print dirpath
    if '__init__.py' in filenames and not 'conf' in dirpath:
        packages.append('.'.join(fullsplit(dirpath)[len_root_dir:]))
    elif filenames:
        data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]])

version = __import__('django_extensions').__version__

setup(
    name = 'django-extensions',
    version = version,
    description = "Extensions for Django",
    long_description = """django-extensions bundles several useful
additions for Django projects. See the project page for more information:
  http://code.google.com/p/django-command-extensions/""",
    author = 'Michael Trier',
    author_email = 'mtrier@gmail.com',
    url = 'http://code.google.com/p/django-command-extensions/',
    license = 'New BSD License',
    platforms = ['any'],
    packages = packages,
    data_files = data_files,
    classifiers = ['Development Status :: 4 - Beta',
                   'Environment :: Web Environment',
                   'Framework :: Django',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: BSD License',
                   'Operating System :: OS Independent',
                   'Programming Language :: Python',
                   'Topic :: Utilities'],
)


text:
package clientv3

import (
	"io/ioutil"
	"log"
	"sync"

	"google.golang.org/grpc/grpclog"
)

// Logger is the logger used by client library.
// It implements grpclog.Logger interface.
type Logger grpclog.Logger

var (
	logger settableLogger
)

type settableLogger struct {
	l  grpclog.Logger
	mu sync.RWMutex
}

func init() {
	// disable client side logs by default
	logger.mu.Lock()
	logger.l = log.New(ioutil.Discard, "", 0)

	// logger has to override the grpclog at initialization so that
	// any changes to the grpclog go through logger with locking
	// instead of through SetLogger
	//
	// now updates only happen through settableLogger.set
	grpclog.SetLogger(&logger)
	logger.mu.Unlock()
}

// SetLogger sets client-side Logger. By default, logs are disabled.
func SetLogger(l Logger) {
	logger.set(l)
}

// GetLogger returns the current logger.
func GetLogger() Logger {
	return logger.get()
}

func (s *settableLogger) set(l Logger) {
	s.mu.Lock()
	logger.l = l
	s.mu.Unlock()
}

func (s *settableLogger) get() Logger {
	s.mu.RLock()
	l := logger.l
	s.mu.RUnlock()
	return l
}

// implement the grpclog.Logger interface

func (s *settableLogger) Fatal(args ...interface{})                 { s.get().Fatal(args...) }
func (s *settableLogger) Fatalf(format string, args ...interface{}) { s.get().Fatalf(format, args...) }
func (s *settableLogger) Fatalln(args ...interface{})               { s.get().Fatalln(args...) }
func (s *settableLogger) Print(args ...interface{})                 { s.get().Print(args...) }
func (s *settableLogger) Printf(format string, args ...interface{}) { s.get().Printf(format, args...) }
func (s *settableLogger) Println(args ...interface{})               { s.get().Println(args...) }


text:
package trust

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"os"
	"testing"

	"github.com/docker/cli/cli/config"
	"github.com/docker/cli/cli/trust"
	"github.com/docker/cli/internal/test"
	"github.com/docker/cli/internal/test/testutil"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/theupdateframework/notary"
	"github.com/theupdateframework/notary/client"
	"github.com/theupdateframework/notary/client/changelist"
	"github.com/theupdateframework/notary/passphrase"
	"github.com/theupdateframework/notary/trustpinning"
	"github.com/theupdateframework/notary/tuf/data"
)

const passwd = "password"

func TestTrustSignCommandErrors(t *testing.T) {
	testCases := []struct {
		name          string
		args          []string
		expectedError string
	}{
		{
			name:          "not-enough-args",
			expectedError: "requires exactly 1 argument",
		},
		{
			name:          "too-many-args",
			args:          []string{"image", "tag"},
			expectedError: "requires exactly 1 argument",
		},
		{
			name:          "sha-reference",
			args:          []string{"870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd"},
			expectedError: "invalid repository name",
		},
		{
			name:          "invalid-img-reference",
			args:          []string{"ALPINE:latest"},
			expectedError: "invalid reference format",
		},
		{
			name:          "no-tag",
			args:          []string{"reg/img"},
			expectedError: "No tag specified for reg/img",
		},
		{
			name:          "digest-reference",
			args:          []string{"ubuntu@sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2"},
			expectedError: "cannot use a digest reference for IMAGE:TAG",
		},
	}
	// change to a tmpdir
	tmpDir, err := ioutil.TempDir("", "docker-sign-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tmpDir)
	config.SetDir(tmpDir)
	for _, tc := range testCases {
		cmd := newSignCommand(
			test.NewFakeCli(&fakeClient{}))
		cmd.SetArgs(tc.args)
		cmd.SetOutput(ioutil.Discard)
		testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
	}
}

func TestTrustSignCommandOfflineErrors(t *testing.T) {
	cli := test.NewFakeCli(&fakeClient{})
	cli.SetNotaryClient(getOfflineNotaryRepository)
	cmd := newSignCommand(cli)
	cmd.SetArgs([]string{"reg-name.io/image:tag"})
	cmd.SetOutput(ioutil.Discard)
	assert.Error(t, cmd.Execute())
	testutil.ErrorContains(t, cmd.Execute(), "client is offline")
}

func TestGetOrGenerateNotaryKey(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "notary-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
	assert.NoError(t, err)

	// repo is empty, try making a root key
	rootKeyA, err := getOrGenerateNotaryKey(notaryRepo, data.CanonicalRootRole)
	assert.NoError(t, err)
	assert.NotNil(t, rootKeyA)

	// we should only have one newly generated key
	allKeys := notaryRepo.GetCryptoService().ListAllKeys()
	assert.Len(t, allKeys, 1)
	assert.NotNil(t, notaryRepo.GetCryptoService().GetKey(rootKeyA.ID()))

	// this time we should get back the same key if we ask for another root key
	rootKeyB, err := getOrGenerateNotaryKey(notaryRepo, data.CanonicalRootRole)
	assert.NoError(t, err)
	assert.NotNil(t, rootKeyB)

	// we should only have one newly generated key
	allKeys = notaryRepo.GetCryptoService().ListAllKeys()
	assert.Len(t, allKeys, 1)
	assert.NotNil(t, notaryRepo.GetCryptoService().GetKey(rootKeyB.ID()))

	// The key we retrieved should be identical to the one we generated
	assert.Equal(t, rootKeyA, rootKeyB)

	// Now also try with a delegation key
	releasesKey, err := getOrGenerateNotaryKey(notaryRepo, data.RoleName(trust.ReleasesRole))
	assert.NoError(t, err)
	assert.NotNil(t, releasesKey)

	// we should now have two keys
	allKeys = notaryRepo.GetCryptoService().ListAllKeys()
	assert.Len(t, allKeys, 2)
	assert.NotNil(t, notaryRepo.GetCryptoService().GetKey(releasesKey.ID()))
	// The key we retrieved should be identical to the one we generated
	assert.NotEqual(t, releasesKey, rootKeyA)
	assert.NotEqual(t, releasesKey, rootKeyB)
}

func TestAddStageSigners(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "notary-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
	assert.NoError(t, err)

	// stage targets/user
	userRole := data.RoleName("targets/user")
	userKey := data.NewPublicKey("algoA", []byte("a"))
	err = addStagedSigner(notaryRepo, userRole, []data.PublicKey{userKey})
	assert.NoError(t, err)
	// check the changelist for four total changes: two on targets/releases and two on targets/user
	cl, err := notaryRepo.GetChangelist()
	assert.NoError(t, err)
	changeList := cl.List()
	assert.Len(t, changeList, 4)
	// ordering is determinstic:

	// first change is for targets/user key creation
	newSignerKeyChange := changeList[0]
	expectedJSON, err := json.Marshal(&changelist.TUFDelegation{
		NewThreshold: notary.MinThreshold,
		AddKeys:      data.KeyList([]data.PublicKey{userKey}),
	})
	require.NoError(t, err)
	expectedChange := changelist.NewTUFChange(
		changelist.ActionCreate,
		userRole,
		changelist.TypeTargetsDelegation,
		"", // no path for delegations
		expectedJSON,
	)
	assert.Equal(t, expectedChange, newSignerKeyChange)

	// second change is for targets/user getting all paths
	newSignerPathsChange := changeList[1]
	expectedJSON, err = json.Marshal(&changelist.TUFDelegation{
		AddPaths: []string{""},
	})
	require.NoError(t, err)
	expectedChange = changelist.NewTUFChange(
		changelist.ActionCreate,
		userRole,
		changelist.TypeTargetsDelegation,
		"", // no path for delegations
		expectedJSON,
	)
	assert.Equal(t, expectedChange, newSignerPathsChange)

	releasesRole := data.RoleName("targets/releases")

	// third change is for targets/releases key creation
	releasesKeyChange := changeList[2]
	expectedJSON, err = json.Marshal(&changelist.TUFDelegation{
		NewThreshold: notary.MinThreshold,
		AddKeys:      data.KeyList([]data.PublicKey{userKey}),
	})
	require.NoError(t, err)
	expectedChange = changelist.NewTUFChange(
		changelist.ActionCreate,
		releasesRole,
		changelist.TypeTargetsDelegation,
		"", // no path for delegations
		expectedJSON,
	)
	assert.Equal(t, expectedChange, releasesKeyChange)

	// fourth change is for targets/releases getting all paths
	releasesPathsChange := changeList[3]
	expectedJSON, err = json.Marshal(&changelist.TUFDelegation{
		AddPaths: []string{""},
	})
	require.NoError(t, err)
	expectedChange = changelist.NewTUFChange(
		changelist.ActionCreate,
		releasesRole,
		changelist.TypeTargetsDelegation,
		"", // no path for delegations
		expectedJSON,
	)
	assert.Equal(t, expectedChange, releasesPathsChange)
}

func TestGetSignedManifestHashAndSize(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "notary-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
	assert.NoError(t, err)
	target := &client.Target{}
	target.Hashes, target.Length, err = getSignedManifestHashAndSize(notaryRepo, "test")
	assert.EqualError(t, err, "client is offline")
}

func TestGetReleasedTargetHashAndSize(t *testing.T) {
	oneReleasedTgt := []client.TargetSignedStruct{}
	// make and append 3 non-released signatures on the "unreleased" target
	unreleasedTgt := client.Target{Name: "unreleased", Hashes: data.Hashes{notary.SHA256: []byte("hash")}}
	for _, unreleasedRole := range []string{"targets/a", "targets/b", "targets/c"} {
		oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: unreleasedTgt})
	}
	_, _, err := getReleasedTargetHashAndSize(oneReleasedTgt, "unreleased")
	assert.EqualError(t, err, "No valid trust data for unreleased")
	releasedTgt := client.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}}
	oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt})
	hash, _, _ := getReleasedTargetHashAndSize(oneReleasedTgt, "unreleased")
	assert.Equal(t, data.Hashes{notary.SHA256: []byte("released-hash")}, hash)

}

func TestCreateTarget(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "notary-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
	assert.NoError(t, err)
	_, err = createTarget(notaryRepo, "")
	assert.EqualError(t, err, "No tag specified")
	_, err = createTarget(notaryRepo, "1")
	assert.EqualError(t, err, "client is offline")
}

func TestGetExistingSignatureInfoForReleasedTag(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "notary-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
	assert.NoError(t, err)
	_, err = getExistingSignatureInfoForReleasedTag(notaryRepo, "test")
	assert.EqualError(t, err, "client is offline")
}

func TestPrettyPrintExistingSignatureInfo(t *testing.T) {
	buf := bytes.NewBuffer(nil)
	signers := []string{"Bob", "Alice", "Carol"}
	existingSig := trustTagRow{trustTagKey{"tagName", "abc123"}, signers}
	prettyPrintExistingSignatureInfo(buf, existingSig)

	assert.Contains(t, buf.String(), "Existing signatures for tag tagName digest abc123 from:\nAlice, Bob, Carol")
}

func TestSignCommandChangeListIsCleanedOnError(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "docker-sign-test-")
	assert.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	config.SetDir(tmpDir)
	cli := test.NewFakeCli(&fakeClient{})
	cli.SetNotaryClient(getLoadedNotaryRepository)
	cmd := newSignCommand(cli)
	cmd.SetArgs([]string{"ubuntu:latest"})
	cmd.SetOutput(ioutil.Discard)

	err = cmd.Execute()
	require.Error(t, err)

	notaryRepo, err := client.NewFileCachedRepository(tmpDir, "docker.io/library/ubuntu", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
	assert.NoError(t, err)
	cl, err := notaryRepo.GetChangelist()
	require.NoError(t, err)
	assert.Equal(t, len(cl.List()), 0)
}

func TestSignCommandLocalFlag(t *testing.T) {
	cli := test.NewFakeCli(&fakeClient{})
	cli.SetNotaryClient(getEmptyTargetsNotaryRepository)
	cmd := newSignCommand(cli)
	cmd.SetArgs([]string{"--local", "reg-name.io/image:red"})
	cmd.SetOutput(ioutil.Discard)
	testutil.ErrorContains(t, cmd.Execute(), "error during connect: Get /images/reg-name.io/image:red/json: unsupported protocol scheme")

}


text:
'use strict';

var express    = require('express')
  , methodOverride = require('method-override')
  , routes     = require('./routes')
  , play       = require('./routes/play')
  , stream     = require('./routes/stream')
  , http       = require('http')
  , path       = require('path')
  , util       = require('util')

var stylus = require('stylus')

var app = express()

// all environments
app.set('port', process.env.PORT || 3000)
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')

app.set('title', "LLeo's Video Server")
console.log("Title:", app.get('title'))

app.set('video directory', path.resolve(process.cwd(), 'videos'))
console.log("Using 'video directory' = %s", app.get('video directory'))

app.use(express.logger('dev'))
app.use(express.favicon()) //currently switched places with express.logger()

//app.use(function(req, res, next){
//  console.log(JSON.stringify(req.headers, " "))
//  next()
//})

app.use(express.json())
app.use(express.urlencoded())
//app.use(express.methodOverride())
app.use(methodOverride())
app.use(app.router)
app.use(stylus.middleware(path.join(__dirname, 'static')))
app.use(express.static(path.join(__dirname, 'static')))

// development only
if ('development' == app.get('env')) {
  app.locals.pretty = true
  app.use(express.errorHandler())
}

app.get('/', routes.index)
app.get('/play', play)
app.get('/stream/:video', stream)

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'))
})


text:
def verbing(s):
    if len(s) >= 3:
        if s[-3:] == 'ing':
            ending = 'ly'
        else:
            ending = 'ing'
    else:
        ending = ''

    return s + ending

# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
    # http://docs.python.org/library/stdtypes.html#string-methods
    if 'not' in s and 'bad' in s:
        not_index = s.find('not')
        bad_index = s.find('bad')

        if not_index < bad_index:
            good_string_start = s[:not_index]
            good_string_end_index = bad_index + len('bad')
            good_string_end = s[good_string_end_index:]
            good_string = good_string_start + 'good' + good_string_end
        else:
            good_string = s
    else:
        good_string = s

    return good_string

# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back
def front_back(a, b):
    # integer division truncates, so a_back may be shorter than a_front
    a_back_desired_length = len(a) / 2
    a_front = a[:-a_back_desired_length]
    a_back = a[-a_back_desired_length:]

    b_back_desired_length = len(b) / 2
    b_front = b[:-b_back_desired_length]
    b_back = b[-b_back_desired_length:]

    return a_front + b_front + a_back + b_back

# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
    if got == expected:
        prefix = ' OK '
    else:
        prefix = '  X '
    print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))

# main() calls the above functions with interesting inputs,
# using the above test() to check if the result is correct or not.
def main():
    print 'verbing'
    test(verbing('hail'), 'hailing')
    test(verbing('swiming'), 'swimingly')
    test(verbing('do'), 'do')

    print
    print 'not_bad'
    test(not_bad('This movie is not so bad'), 'This movie is good')
    test(not_bad('This dinner is not that bad!'), 'This dinner is good!')
    test(not_bad('This tea is not hot'), 'This tea is not hot')
    test(not_bad("It's bad yet not"), "It's bad yet not")

    print
    print 'front_back'
    test(front_back('abcd', 'xy'), 'abxcdy')
    test(front_back('abcde', 'xyz'), 'abcxydez')
    test(front_back('Kitten', 'Donut'), 'KitDontenut')

if __name__ == '__main__':
    main()


text:
@interface JCWeatherAnimation : NSObject
#pragma mark 创建下雨动画
+(void)creatRainForLayer:(CALayer *)layer;

#pragma mark 创建下雪动画
+(void)creatSnowForLayer:(CALayer *)layer;

#pragma mark 创建晴天动画
+(void)creatSunnyForLayer:(CALayer *)layer;

#pragma mark 创建阴天动画
+(void)creatCloudForLayer:(CALayer *)layer;

#pragma mark 创建雷雨动画
+(void)creatEletranicForLayer:(CALayer *)layer;
@end


text:
<!doctype html>

  <meta charset="utf-8">
  <title>jQuery Analytics</title>

		<button data-track='{ "category" : "search", "action" : "button", "label" : "Search" }'>Search</button>

		Link


text:
package com.karasiq.bittorrent.protocol.extensions

import java.net.{InetAddress, InetSocketAddress}
import java.nio.ByteBuffer

import akka.util.ByteString

import com.karasiq.bittorrent.format.{BEncode, BEncodedDictionary, BEncodedNumber, BEncodedString}
import com.karasiq.bittorrent.protocol.{BitTorrentTcpProtocol, TcpMessageProtocol}

// TODO: Map(1 -> ut_pex, 6 -> ut_comment, 2 -> ut_metadata, 7 -> lt_donthave, 3 -> upload_only, 4 -> ut_holepunch)
object ExtensionProtocol {
  val defaultMessages: Map[Int, String] = Map(
    1 → "ut_pex"
  )
}

trait ExtensionProtocol extends ExtensionProtocolMessages with ExtensionProtocolTcp

trait ExtensionProtocolMessageIds {
  val EXTENDED_MESSAGE = 20
}

trait ExtensionProtocolMessages {
  case class EPHandshake(messages: Map[Int, String], version: Option[String] = None, requests: Option[Int] = None, address: Option[InetSocketAddress] = None)

  case class ExtendedMessage(id: Int, payload: ByteString)
}

trait ExtensionProtocolTcp { self: ExtensionProtocolMessages ⇒
  implicit object EpHandshakeTcpProtocol extends TcpMessageProtocol[EPHandshake] {
    override def toBytes(value: EPHandshake): ByteString = {
      val messageIds = BEncodedDictionary(value.messages.toSeq.map {
        case (id, key) ⇒
          key → BEncodedNumber(id)
      })
      val values = Vector(
        "m" → Some(messageIds),
        "v" → value.version.map(v ⇒ BEncodedString(ByteString(v))),
        "ipv6" → value.address.collect {
          case address if !address.isUnresolved && address.getAddress.getAddress.length == 16 ⇒
            BEncodedString(ByteString(address.getAddress.getAddress))
        },
        "ipv4" → value.address.collect {
          case address if !address.isUnresolved && address.getAddress.getAddress.length == 4 ⇒
            BEncodedString(ByteString(address.getAddress.getAddress))
        },
        "p" → value.address.map(a ⇒ BEncodedNumber(a.getPort)),
        "reqq" → value.requests.map(r ⇒ BEncodedNumber(r))
      )
      BEncodedDictionary(values.collect { case (k, Some(v)) ⇒ k → v })
        .toBytes
    }

    override def fromBytes(bs: ByteString): Option[EPHandshake] = {
      import com.karasiq.bittorrent.format.BEncodeImplicits._
      BEncode.parse(bs.toArray[Byte]).collectFirst {
        case BEncodedDictionary(values) ⇒
          val map = values.toMap
          val messageIds = map.get("m") match {
            case Some(BEncodedDictionary(messages)) ⇒
              messages.collect {
                case (key, BEncodedNumber(id)) ⇒
                  id.toInt → key
              }

            case _ ⇒
              Nil
          }
          val address = for {
            a <- map.bytes("ipv6").filter(_.length == 16)
              .orElse(map.bytes("ipv4").filter(_.length == 4))
              .map(a ⇒ InetAddress.getByAddress(a.toArray))
            p <- map.int("p")
          } yield new InetSocketAddress(a, p)
          EPHandshake(messageIds.toMap, map.string("v"), map.int("reqq"), address)
      }
    }
  }

  implicit object ExtendedMessageTcpProtocol extends TcpMessageProtocol[ExtendedMessage] {
    override def toBytes(value: ExtendedMessage): ByteString = {
      val buffer = ByteBuffer.allocate(1 + value.payload.length)
      buffer.put(value.id.toByte)
      buffer.put(value.payload.toArray)
      buffer.flip()
      ByteString(buffer)
    }

    override def fromBytes(bs: ByteString): Option[ExtendedMessage] = {
      if (bs.length > 1) {
        Some(ExtendedMessage(BitTorrentTcpProtocol.int32FromBytes(bs.take(1)), bs.drop(1)))
      } else {
        None
      }
    }
  }
}


text:
Sample application Spring-boot - data-rest - scala

## Architecture

## License
This library is licensed under the Apache License, Version 2.0.

## Starting


text:
function Square(game, size, x, y, color) {
  var _x = x || 0;
  var _y = y || 0;
  var _size = size;

  this.sprite = new createjs.Shape();
  this.sprite.graphics.beginFill(color).drawRect(0, 0, _size, _size).endFill();
  this.sprite.x = _x;
  this.sprite.y = _y;

  game.screen.addChild(this.sprite);

  this.changeColor = function(color) {
    this.sprite.graphics.clear().beginFill(color).drawRect(0, 0, _size, _size).endFill();
    this.sprite.x = _x;
    this.sprite.y = _y;
  }
};

Square.prototype.x = function(x) {
  if( typeof x === "undefined" )
    return this.sprite.x;
  this.sprite.x = x;
};
Square.prototype.y = function(y) {
  if( typeof y === "undefined" )
    return this.sprite.y;
  this.sprite.y = y;
};

Square.prototype.init = function() {};
Square.prototype.update = function(delta) {};
Square.prototype.render = function(delta) {};