text:
/* First created by JCasGen Sat Mar 07 22:05:57 CET 2015 */
package de.julielab.jules.types;

import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.jcas.cas.TOP_Type;

/** Penn Treebank constituent annotation (see Penn Treebank)
 * Updated by JCasGen Sat Mar 07 22:05:57 CET 2015
 * XML source: /Users/richarde/dev/bluebrain/git/Bluima/modules/bluima_typesystem/target/jcasgen/typesystem.xml
 * @generated */
public class PTBConstituent extends Constituent {
  /** @generated
   * @ordered
   */
  @SuppressWarnings ("hiding")
  public final static int typeIndexID = JCasRegistry.register(PTBConstituent.class);
  /** @generated
   * @ordered
   */
  @SuppressWarnings ("hiding")
  public final static int type = typeIndexID;
  /** @generated
   * @return index of the type
   */
  @Override
  public              int getTypeIndexID() {return typeIndexID;}

  /** Never called.  Disable default constructor
   * @generated */
  protected PTBConstituent() {/* intentionally empty block */}

  /** Internal - constructor used by generator
   * @generated
   * @param addr low level Feature Structure reference
   * @param type the type of this Feature Structure
   */
  public PTBConstituent(int addr, TOP_Type type) {
    super(addr, type);
    readObject();
  }

  /** @generated
   * @param jcas JCas to which this Feature Structure belongs
   */
  public PTBConstituent(JCas jcas) {
    super(jcas);
    readObject();
  }

  /** @generated
   * @param jcas JCas to which this Feature Structure belongs
   * @param begin offset to the begin spot in the SofA
   * @param end offset to the end spot in the SofA
  */
  public PTBConstituent(JCas jcas, int begin, int end) {
    super(jcas);
    setBegin(begin);
    setEnd(end);
    readObject();
  }

  /**
   * <!-- begin-user-doc -->
   * Write your own initialization here
   * <!-- end-user-doc -->
   *
   * @generated modifiable
   */
  private void readObject() {/*default - does nothing empty block */}

  //*--------------*
  //* Feature: formFuncDisc

  /** getter for formFuncDisc - gets Form/function discrepancies, O
   * @generated
   * @return value of the feature
   */
  public String getFormFuncDisc() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_formFuncDisc == null)
      jcasType.jcas.throwFeatMissing("formFuncDisc", "de.julielab.jules.types.PTBConstituent");
    return jcasType.ll_cas.ll_getStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_formFuncDisc);}

  /** setter for formFuncDisc - sets Form/function discrepancies, O
   * @generated
   * @param v value to set into the feature
   */
  public void setFormFuncDisc(String v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_formFuncDisc == null)
      jcasType.jcas.throwFeatMissing("formFuncDisc", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_formFuncDisc, v);}

  //*--------------*
  //* Feature: gramRole

  /** getter for gramRole - gets Grammatical role, O
   * @generated
   * @return value of the feature
   */
  public String getGramRole() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_gramRole == null)
      jcasType.jcas.throwFeatMissing("gramRole", "de.julielab.jules.types.PTBConstituent");
    return jcasType.ll_cas.ll_getStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_gramRole);}

  /** setter for gramRole - sets Grammatical role, O
   * @generated
   * @param v value to set into the feature
   */
  public void setGramRole(String v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_gramRole == null)
      jcasType.jcas.throwFeatMissing("gramRole", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_gramRole, v);}

  //*--------------*
  //* Feature: adv

  /** getter for adv - gets Adverbials are generally VP adjuncts.
   * @generated
   * @return value of the feature
   */
  public String getAdv() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_adv == null)
      jcasType.jcas.throwFeatMissing("adv", "de.julielab.jules.types.PTBConstituent");
    return jcasType.ll_cas.ll_getStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_adv);}

  /** setter for adv - sets Adverbials are generally VP adjuncts.
   * @generated
   * @param v value to set into the feature
   */
  public void setAdv(String v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_adv == null)
      jcasType.jcas.throwFeatMissing("adv", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_adv, v);}

  //*--------------*
  //* Feature: misc

  /** getter for misc - gets Miscellaneous
   * @generated
   * @return value of the feature
   */
  public String getMisc() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_misc == null)
      jcasType.jcas.throwFeatMissing("misc", "de.julielab.jules.types.PTBConstituent");
    return jcasType.ll_cas.ll_getStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_misc);}

  /** setter for misc - sets Miscellaneous
   * @generated
   * @param v value to set into the feature
   */
  public void setMisc(String v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_misc == null)
      jcasType.jcas.throwFeatMissing("misc", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_misc, v);}

  //*--------------*
  //* Feature: nullElement

  /** getter for nullElement - gets
   * @generated
   * @return value of the feature
   */
  public String getNullElement() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_nullElement == null)
      jcasType.jcas.throwFeatMissing("nullElement", "de.julielab.jules.types.PTBConstituent");
    return jcasType.ll_cas.ll_getStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_nullElement);}

  /** setter for nullElement - sets
   * @generated
   * @param v value to set into the feature
   */
  public void setNullElement(String v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_nullElement == null)
      jcasType.jcas.throwFeatMissing("nullElement", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setStringValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_nullElement, v);}

  //*--------------*
  //* Feature: ref

  /** getter for ref - gets Th reference from the null constituent to the corresponding lexicalized constituent, O
   * @generated
   * @return value of the feature
   */
  public Constituent getRef() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_ref == null)
      jcasType.jcas.throwFeatMissing("ref", "de.julielab.jules.types.PTBConstituent");
    return (Constituent)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_ref)));}

  /** setter for ref - sets Th reference from the null constituent to the corresponding lexicalized constituent, O
   * @generated
   * @param v value to set into the feature
   */
  public void setRef(Constituent v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_ref == null)
      jcasType.jcas.throwFeatMissing("ref", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setRefValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_ref, jcasType.ll_cas.ll_getFSRef(v));}

  //*--------------*
  //* Feature: map

  /** getter for map - gets In the case of gapping the reference to the corresponding constituent, O
   * @generated
   * @return value of the feature
   */
  public Constituent getMap() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_map == null)
      jcasType.jcas.throwFeatMissing("map", "de.julielab.jules.types.PTBConstituent");
    return (Constituent)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_map)));}

  /** setter for map - sets In the case of gapping the reference to the corresponding constituent, O
   * @generated
   * @param v value to set into the feature
   */
  public void setMap(Constituent v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_map == null)
      jcasType.jcas.throwFeatMissing("map", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setRefValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_map, jcasType.ll_cas.ll_getFSRef(v));}

  //*--------------*
  //* Feature: tpc

  /** getter for tpc - gets Marks elements that appear before the subject in a declarative sentence, O
   * @generated
   * @return value of the feature
   */
  public boolean getTpc() {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_tpc == null)
      jcasType.jcas.throwFeatMissing("tpc", "de.julielab.jules.types.PTBConstituent");
    return jcasType.ll_cas.ll_getBooleanValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_tpc);}

  /** setter for tpc - sets Marks elements that appear before the subject in a declarative sentence, O
   * @generated
   * @param v value to set into the feature
   */
  public void setTpc(boolean v) {
    if (PTBConstituent_Type.featOkTst && ((PTBConstituent_Type)jcasType).casFeat_tpc == null)
      jcasType.jcas.throwFeatMissing("tpc", "de.julielab.jules.types.PTBConstituent");
    jcasType.ll_cas.ll_setBooleanValue(addr, ((PTBConstituent_Type)jcasType).casFeatCode_tpc, v);}
  }


text:
package org.apache.river.test.spec.jeri.mux;

import java.util.logging.Level;

//harness imports
import org.apache.river.qa.harness.TestException;

//utility classes
import org.apache.river.test.spec.jeri.mux.util.AbortMessage;
import org.apache.river.test.spec.jeri.mux.util.AbstractMuxTest;
import org.apache.river.test.spec.jeri.mux.util.AcknowledgementMessage;
import org.apache.river.test.spec.jeri.mux.util.ClientConnectionHeader;
import org.apache.river.test.spec.jeri.mux.util.DataMessage;
import org.apache.river.test.spec.jeri.mux.util.IncrementRationMessage;
import org.apache.river.test.spec.jeri.mux.util.PingAckMessage;
import org.apache.river.test.spec.jeri.mux.util.PingMessage;
import org.apache.river.test.spec.jeri.mux.util.ProtocolException;
import org.apache.river.test.spec.jeri.mux.util.Redirector;
import org.apache.river.test.spec.jeri.mux.util.ServerConnectionHeader;
import org.apache.river.test.spec.jeri.mux.util.TestServerEndpoint;
import org.apache.river.test.spec.jeri.mux.util.TestService;
import org.apache.river.test.spec.jeri.mux.util.TestServiceImpl;
import org.apache.river.test.spec.jeri.mux.util.Util;

//jeri imports
import net.jini.core.constraint.InvocationConstraints;
import net.jini.jeri.BasicILFactory;
import net.jini.jeri.BasicJeriExporter;
import net.jini.jeri.Endpoint;
import net.jini.jeri.OutboundRequest;
import net.jini.jeri.OutboundRequestIterator;
import net.jini.jeri.ServerEndpoint;

//java.io
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

//java.net
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

//java.util
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

/**
 * Purpose: This test verifies that a protocol server stops sending data
 * to a client after the client sends an Abort message.
 *
 * Test:
 * 1. Establish a Jini ERI Multiplexing Protocol connection using an
 * instrumented client.
 * 2. In the client, specify the inbound ration as 256 bytes.
 * 3. From the server, write 800 bytes to the mux connection.
 * 4. After the first message from the server is received, send an Abort
 * message from the client.
 * 5. Verify that and Abort message is sent by the server.
 */
public class ServerAbortTest extends AbstractMuxTest {

    public void run() throws Exception {
        //Setup server side mux connection
        ServerEndpoint se = getServerEndpoint();
        Redirector rd = new Redirector(InetAddress.getLocalHost()
            .getHostAddress(), getPort(), getPort() + 1);
        Thread t = new Thread(rd);
        t.start();
        ((TestServerEndpoint) se).redirect(getPort() + 1);
        TestService service = new TestServiceImpl();
        BasicJeriExporter exporter = new BasicJeriExporter(se,
            new BasicILFactory());
        TestService stub = (TestService) exporter.export(service);
        //Obtain a message to send for the test
        byte[] ball = new byte[800];
        Arrays.fill(ball, (byte)0x88);
        stub.bounce(ball);
        rd.stop();
        byte[] data = extractDataMessage(rd.getClientConversation());
        byte[] serverData = extractDataMessage(rd.getServerConversation());
        int size = (serverData[2]<<8) + serverData[3];
        //Establish a connection to the mux server
        Socket s = new Socket(InetAddress.getLocalHost(),getPort());
        InputStream is = s.getInputStream();
        OutputStream os = s.getOutputStream();
        //Set the client ration to 256 bytes
        ClientConnectionHeader cHeader = new ClientConnectionHeader()
            .setRation((short)0x0001);
        cHeader.send(os);
        //receive the ServerConnection header
        ServerConnectionHeader sHeader = new ServerConnectionHeader();
        sHeader.receive(is,getTimeout());
        //Play back the request obtained before
        os.write(data);
        os.flush();
        int received = 0;
        int sessionId = 0;
        //Receive message fragment
        DataMessage dm = new DataMessage().suppressFormatCheck();
        dm.receive(is,getTimeout());
        if (dm.getSize()>256) {
            throw new TestException("Message fragment size"
                + " over 256 bytes: " + dm);
        }
        AbortMessage am = new AbortMessage();
        am.send(os);
        if (!abortReceived(is)) {
            throw new TestException("Abort message was not"
                + " received from the server");
        }
    }

    /**
     * Extracts a Jini ERI mux protocol data message from an array of bytes.
     *
     * @param conversation Array from which to extract data message.
     * @return An array of bytes that that represents a single data message.
     */
    private byte[] extractDataMessage(ArrayList conversation) {
        Iterator it = conversation.iterator();
        byte[] data = new byte[conversation.size()-8];
        int index = 0;
        while (it.hasNext()) {
            byte[] bytes = (byte[]) it.next();
            //skip the client connection header
            if (index>7) {
                data[index-8] = bytes[0];
            }
            index++;
        }
        return data;
    }

    /**
     * Blocks until a Jini ERI mux protocol Abort message is received or until
     * a timeout expires.
     *
     * @param is Input stream from which to read Jini ERI mux messages
     * @return true if an Abort message is received, false otherwise
     */
    private boolean abortReceived(InputStream is)
        throws IOException, InterruptedException {
        long stopTime = System.currentTimeMillis() + (getTimeout());
        boolean abortReceived = false;
        while (System.currentTimeMillis() < stopTime) {
            if (!waitForInput(is,1,stopTime)) {
                return false;
            }
            byte[] msb = new byte[1];
            is.read(msb);
            if ((msb[0]|(byte)0x22)==0x22) {
                abortReceived = true;
                break;
            } else if ((msb[0]&(byte)0x80)==0x80){
                byte[] header = new byte[3];
                if (!waitForInput(is,3,stopTime)) {
                    return false;
                }
                is.read(header);
                int size =  (header[1]<<8) + header[2];
                if (!waitForInput(is,size,stopTime)) {
                    return false;
                }
                byte[] data = new byte[size];
                is.read(data);
            }
        }
        return abortReceived;
    }

    /**
     * Blocks until a given number of bytes are available from the input
     * stream or until a timeout expires.
     *
     * @param is The input stream to read bytes from
     * @param bytes The number of bytes to wait for
     * @param stop The number of ms to wait for the bytes to be available
     */
    private boolean waitForInput(InputStream is, int bytes, long stop)
        throws IOException, InterruptedException {
        while((is.available()<bytes)&&(System.currentTimeMillis() < stop)){
            Thread.sleep(100);
        }
        return (is.available()>=bytes);
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace TimeZones
{
    /// <summary>
    ///
    /// </summary>
    internal interface ITimeZoneServiceAdapter
    {
        /// <summary>
        ///     All available time zones
        /// </summary>
        IReadOnlyList<string> SystemTimeZoneIds { get; }

        /// <summary>
        /// Gets a TimeZoneEx by id.
        /// </summary>
        /// <param name="id">Invariant Time Zone name. See SystemTimeZoneIds property for full list.</param>
        /// <returns></returns>
        ITimeZoneEx FindSystemTimeZoneById(string id);

        /// <summary>
        /// The Local Time Zone
        /// </summary>
        ITimeZoneEx Local { get; }

        /// <summary>
        /// All Time Zones
        /// </summary>
        /// <returns></returns>
        IEnumerable<ITimeZoneEx> GetAllTimeZones();
    }

    /// <summary>
    /// Represents a time zone
    /// </summary>
    public interface ITimeZoneEx
    {
        /// <summary>
        /// Determines if the current datetime value is in daylight time or not
        /// </summary>
        /// <param name="dateTimeOffset"></param>
        /// <returns></returns>
        bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset);

        /// <summary>
        ///  Gets a DateTimeOffset for this time zone
        /// </summary>
        /// <param name="dateTimeOffset"></param>
        /// <returns></returns>
        DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset);

        /// <summary>
        /// Normal offset from UTC
        /// </summary>
        TimeSpan BaseUtcOffset { get; }

        /// <summary>
        /// Localized name for standard time
        /// </summary>
        string StandardName
        {
            get;
        }

        /// <summary>
        /// Localized name for daylight time
        /// </summary>
        string DaylightName { get; }

        /// <summary>
        /// System Id for this time zone
        /// </summary>
        string Id { get; }
    }
}


text:
        <hp-date-picker
                model="vm.filterData.dateFrom"
                name="dateFrom"
                is-required="true"
                on-change="vm.executeSearch()">
        </hp-date-picker>

đến

            <hp-date-picker
                    model="vm.filterData.dateTo"
                    name="dateTo"
                    is-required="true"
                    on-change="vm.executeSearch()">
            </hp-date-picker>

                <button class="btn btn-default dropdown-toggle"
                        type="button"
                        data-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false"
                        style="box-shadow: none; padding-left: 3px; padding-right: 3px; background: transparent;">

                    Toggle Dropdown
                </button>

Tìm tháng hiện tại

Tìm tháng trước

Tìm tháng tới

Tìm năm hiện tại


text:
dojo.provide("plugins.workflow.StageRow");

dojo.require("plugins.core.Common");

dojo.declare( "plugins.workflow.StageRow",
	[ dijit._Widget, dijit._Templated, plugins.core.Common ],
{
//Path to the template of this widget.
templatePath: dojo.moduleUrl("plugins", "workflow/templates/stagerow.html"),

// Calls dijit._Templated.widgetsInTemplate
widgetsInTemplate : true,

// OR USE @import IN HTML TEMPLATE
cssFiles : [ dojo.moduleUrl("plugins") + "/workflow/css/stagerow.css" ],

// PARENT plugins.workflow.Apps WIDGET
parentWidget : null,

// APPLICATION OBJECT
application : null,

// CORE WORKFLOW OBJECTS
core : null,

/////}}}}}
constructor : function(args) {
	////console.log("StageRow.constructor    " + this.id);

	this.loadCSS();

	this.core = args.core;
	this.parentWidget = args.parentWidget;

	this.application = new Object;
	for ( var key in args )
	{
		if ( key != "parentWidget" )
		{
			this.application[key] = args[key];
		}
	}
	//////////console.log("StageRow.constructor    this.application: " + dojo.toJson(this.application));

	//this.inherited(arguments);
},
postCreate : function() {
	this.startup();
},
startup : function () {
/* SET this.name.parentWidget = this

	FOR RETRIEVAL OF this.application WHEN MENU IS CLICKED

	REM: remove ONCLICK BUBBLES ON stageRow.name NODE RATHER THAN ON node.

	I.E., CONTRARY TO DESIRED, this.name IS THE TARGET INSTEAD OF THE node.

	ALSO ADDED node.parentWidget = stageRow IN Workflows.updateDropTarget()

*/
	//console.group("stageRow-" + this.id + "    startup");
	//console.dir({application:this.application});
	//////////console.log("StageRow.startup    this.parentWidget: " + this.parentWidget);

	this.inherited(arguments);

	this.name.parentWidget = this;
	//////////console.log("StageRow.startup    this.name.parentWidget: " + this.name.parentWidget);

	this.setNumber(this.application.number);

	this.setSubmitStyle(this.application.submit);

	//console.groupEnd("stageRow-" + this.id + "    startup");
},
setSubmitStyle : function (submit) {
	//console.log("StageRow.setSubmitStyle     submit: " + submit)
	if ( submit == 1 ) {
		//console.log("StageRow.setSubmitStyle     DOING dojo.addClass(this.domNode, 'submit')")
		dojo.addClass(this.domNode, "submit");
	}
	else {
		//console.log("StageRow.setSubmitStyle     DOING dojo.removeClass(this.domNode, 'submit')")
		dojo.removeClass(this.domNode, "submit");
	}

},
checkValidParameters : function (force) {
	//console.group("stageRow-" + this.id + "    checkValidParameters");
	//console.log("StageRow.checkValidParameters    caller: " + this.checkValidParameters.caller.nom);

	// CHECK ALL PARAMETERS. COLLECT FILES IN this.fileStageParameters
	this.checkAllParameters(force);

	//console.log("StageRow.checkValidParameters    AFTER this.checkAllParameters(force)");
	//console.log("StageRow.checkValidParameters    this.fileStageParameters.length: " + this.fileStageParameters.length);

	if ( this.fileStageParameters.length != 0 )
		this.checkFiles();
	else
		this.checkRunStatus();

	//console.groupEnd("stageRow-" + this.id + "    checkValidParameters");
},
checkRunStatus : function() {
	//console.log("StageRow.checkRunStatus    plugins.workflow.StageRow.checkRunStatus");

	// DEBUG:
	if ( this.core.runStatus == null )	return;

	// CHECK IF STAGES ARE RUNNING
	//console.log("Parameters.load     BEFORE this.core.userWorkflows.indexOfRunningStage()");
	var indexOfRunningStage = this.core.userWorkflows.indexOfRunningStage();
	//console.log("Parameters.load     indexOfRunningStage: " + indexOfRunningStage);
	var runner = this.core.runStatus.createRunner(indexOfRunningStage);
	var singleton = true;
	var selectTab = false;
	//console.log("Parameters.load     DOING runStatus.getStatus");
	this.core.runStatus.getStatus(runner, singleton, selectTab);
},
checkAllParameters : function (force) {
/*	CHECK ALL THE PARAMETERS HAVE VALID INPUTS AND CHANGE CSS ACCORDINGLY.

 	RETURN VALUE OF validInputs AS true IF ALL PARAMETERS ARE SATISFIED.

 	OTHERWISE, RETURN false.

	PROCESS FOR CHECKING VALIDITY FOR EACH PARAMETER

		1. SET this.validInputs TO TRUE, UPDATE ALONG THE WAY

		2. CHECK ONLY inputs (IGNORE outputs AND resources).

		3. FOR EACH INPUT:

			3.1 CHECK IF VALIDITY HAS ALREADY BEEN COMPUTED AND STORED

				IN Agua.getParameterValidity BOOLEAN. USE IF AVAILABLE AND NEXT

			3.2 OTHERWISE, SET Agua.setParameterValidity FOR EACH

				PARAMETER AS FOLLOWS:

				a. IF FILE/DIR, IGNORE IF OPTIONAL UNLESS FILEPATH SPECIFIED

				b. IF NON-OPTIONAL FILE/DIR, ADD TO ARRAY OF FILES TO BE

					PASSED TO checkFiles

				c. IGNORE FLAGS, CHECK INTS AND NON-OPTIONAL TEXT

			3.3 RUN checkFiles FOR UNKNOWN FILES/DIRS:

				a. DO A BATCH FILE CHECK ON THE REMOTE SERVER.

				b. SET validInputs TO FALSE IF ANY FILES/DIRS ARE MISSING

		4. ADJUST CSS CLASS OF StageRow ACCORDING TO VALUE OF validInputs

		5. RETURN BOOLEAN VALUE OF validInputs

*/

	//console.group("stageRow-" + this.id + "    checkAllParameters");
	//console.log("StageRow.checkAllParameters    caller: " + this.checkAllParameters.caller.nom);
	//console.log("StageRow.checkAllParameters    this.force: " + this.force);

	// SET this.isValid TO DEFAULT true
	this.isValid = true;

	// GET STAGE PARAMETERS
	var parameterRows = new Array;
	var stageParameters = new Array;
	//console.log("StageRow.checkAllParameters    this.application: ");
	//console.dir({application:this.application});
	//console.log("StageRow.checkAllParameters    this.core.parameters.application:");
	//console.dir({parameters_application:this.core.parameters.application});

	if ( this.core.parameters != null
		&& this.core.parameters.isCurrentApplication(this.application) ) {
		parameterRows = this.core.parameters.childWidgets;
		//console.log("StageRow.checkAllParameters    APPLICATIONS IS CURRENT APPLICATION [" + this.application.name + "].     parameterRows.length: " + parameterRows.length);
		for ( var i = 0; i < this.core.parameters.childWidgets.length; i++ )
		{
			stageParameters.push(this.core.parameters.childWidgets[i].parameterObject);
		}
	}
	else {
		//console.log("StageRow.checkAllParameters    APPLICATION IS NOT CURRENT APPLICATION");
		stageParameters = Agua.getStageParameters(this.application);
	}
	//console.log("StageRow.checkAllParameters    stageParameters.length: " + stageParameters.length);

	if ( stageParameters == null ) {
		//console.groupEnd("stageRow-" + this.id + "    checkAllParameters");
		return false;
	}

	// GET ALL REQUIRED/ESSENTIAL INPUT FILE/DIRECTORY PARAMETERS
	this.fileStageParameters = new Array;
	this.fileParameterRows = new Array;
	for ( var i = 0; i < stageParameters.length; i++ )
	{
		//console.log("StageRow.checkAllParameters    Processing parameter: " + stageParameters[i].name + " (discretion: " + stageParameters[i].discretion + ")");

		// ADD SYSTEM VARIABLES
		stageParameters[i].value = this.systemVariables(stageParameters[i].value, stageParameters[i]);

		// UNLESS force SPECIFIED, GET VALIDITY IF EXISTS
		// AND MOVE ON TO NEXT STAGE PARAMETER
		var isValid = Agua.getParameterValidity(stageParameters[i]);
		if ( force != true && isValid != null && isValid != false )
		{
			//console.log("StageRow.checkAllParameters   inside required/essential isValid: " + isValid);

			//console.log("StageRow.checkAllParameters    isValid IS DEFINED and force != true");
			if ( parameterRows[i] != null )
			{
				//console.log("StageRow.checkValidFile    DOING parameterRow.setValid(node)");
				if ( isValid == true )
					parameterRows[i].setValid(parameterRows[i].containerNode);
				else {
					parameterRows[i].setInvalid(parameterRows[i].containerNode);
					this.isValid = false;
				}
			}
			//console.log("StageRow.checkAllParameters    End of processing parameter: " + stageParameters[i].name);

			continue;
		}

		// FLAGS ARE AUTOMATICALLY VALID
		else if ( stageParameters[i].valuetype == "flag" )
			continue;

		// SAVE UNKNOWN FILE/DIRECTORY FOR checkFiles LATER ON
		if ( stageParameters[i].valuetype == "file"
			||  stageParameters[i].valuetype == "directory" )
			this.checkValidFile(stageParameters[i], parameterRows[i]);

		// CHECK INTEGERS
		else if ( stageParameters[i].valuetype == "integer" )
			this.checkValidInteger(stageParameters[i], parameterRows[i]);

		// CHECK TEXT INPUTS
		else
			this.checkValidText(stageParameters[i], parameterRows[i]);
	}

	if ( this.fileStageParameters.length == 0 )
	{
		//console.log("StageRow.checkAllParameters    'this.fileStageParameters' is empty. Returning");
		//console.log("StageRow.checkAllParameters    No filecheck required. FINAL this.isValid: " + this.isValid);

		if ( this.isValid == false || this.isValid == null )
			this.setInvalid();
		else this.setValid();

		//console.groupEnd("stageRow-" + this.id + "    checkFileParameters");
		return this.isValid;
	}

	//console.log("StageRow.checkAllParameters    this.fileStageParameters.length: " + this.fileStageParameters.length);
	//console.log("StageRow.checkAllParameters    this.fileParameterRows.length: " + this.fileParameterRows.length);
	//console.log("StageRow.checkAllParameters    END. this.fileParameterRows:");
	//console.dir({fileParameterRows:this.fileParameterRows});
	//console.log("StageRow.checkAllParameters    END. this.fileStageParameters:");
	//console.dir({fileStageParameters:this.fileStageParameters});

	//console.groupEnd("stageRow-" + this.id + "    checkAllParameters");
},
currentParametersApplication : function (application) {
	////console.log("StageRow.currentParametersApplication    StageRow.currentParametersApplication(application)");

	var keys = ["project", "workflow", "workflownumber", "name", "number"];
	return this._objectsMatchByKey(application, this.core.parameters.application, keys);
},
checkFiles : function (files) {
	//console.group("stageRow-" + this.id + "    checkFiles");
	////console.log("StageRow.checkFiles    caller: " + this.checkFiles.caller.nom);
	////console.log("StageRow.checkFiles    StageRow.checkFiles(files)");
	////console.log("StageRow.checkFiles    this.checkFiles.caller.nom: " + this.checkFiles.caller.nom);
	////console.dir({caller: this.checkFiles.caller});
	////console.log("StageRow.checkFiles    this.fileStageParameters.length: " + this.fileStageParameters.length);
	////console.log("StageRow.checkFiles    this.fileParameterRows.length: " + this.fileParameterRows.length);

	if ( files == null )	files = this.fileStageParameters;
	////console.log("StageRow.checkFiles    this.fileStageParameters: " + this.fileStageParameters.length);
	//////console.log("StageRow.checkFiles    'this.fileStageParameters': " + dojo.toJson(this.fileStageParameters, true));
	////console.log("StageRow.checkFiles    BEFORE xhrPut this.isValid: " + this.isValid);

	// GET FILEINFO FROM REMOTE FILE SYSTEM
	var url = Agua.cgiUrl + "agua.cgi";
	var query 			= 	new Object;
	query.username = Agua.cookie('username');
	query.sessionid = Agua.cookie('sessionid');
	query.project 		= 	this.application.project;
	query.workflow 		= 	this.application.workflow;
	query.mode = "checkFiles";
	query.module = "Agua::Sharing";
	query.files 		= 	files;
	//console.log("StageRow.checkFiles    query: ");
	//console.dir({query:query});

	// SEND TO SERVER
	var thisObject = this;
	var xhrputReturn = dojo.xhrPut({
		url				: url,
		contentType		: "text",
		sync 			: false,
		handleAs		: "json",
		putData			: dojo.toJson(query),
		handle			: function(fileinfos, ioArgs) {
			thisObject.validateFiles(files, fileinfos);
			//console.log("StageRow.checkFiles    fileinfos: ");
			//console.dir({fileinfos:fileinfos});

			if ( thisObject.core.parameters != null
				&& thisObject.core.parameters.isCurrentApplication(thisObject.application) ) {
				//console.log("StageRow.checkFiles    Doing checkRunStatus()");
				thisObject.checkRunStatus();
			}

			//console.groupEnd("stageRow-" + thisObject.id + "    checkFiles");
		}
	});

	////console.log("StageRow.checkFiles    BEFORE setting stageRow CSS, FINAL this.isValid: " + this.isValid);
	if ( this.isValid == false || this.isValid == null ) this.setInvalid();
	else this.setValid();

	return this.isValid;
},
validateFiles : function (fileinfos) {
	//console.group("stageRow-" + this.id + "    validateFiles");
	//console.log("StageRow.validateFiles    caller: " + this.validateFiles.caller.nom);
	//console.log("StageRow.validateFiles    fileinfos: ");
	//console.dir({fileinfos:fileinfos});
	//console.log("StageRow.validateFiles    this.fileParameterRows:");
	//console.dir({parameterRows:this.parameterRows});
	//console.log("StageRow.validateFiles    this.fileParameterRows:");
	//console.dir({fileParameterRows:this.fileParameterRows});

	if ( fileinfos == null
		|| fileinfos.length == null
		|| ! fileinfos.length )
		return;

	for ( var i = 0; i < fileinfos.length; i++ )
	{
		//console.log("StageRow.validateFiles    fileinfos[" + i + "]: ");
		//console.dir({fileinfo:fileinfos[0]});
		var parameterRow = this.fileParameterRows[i];
		//console.log("StageRow.validateFiles    parameterRow: " + parameterRow);
//		if ( ! parameterRow || ! this.fileStageParameters )	return;

		// SET FILE INFO
		if ( this.fileStageParameters && this.fileStageParameters[i])
			Agua.setFileInfo(this.fileStageParameters[i], fileinfos[i]);

		if ( fileinfos[i].exists == "true" )
		{
			if ( fileinfos[i].type != this.fileStageParameters[i].valuetype )
			{
				// SET PARAMETER VALIDITY AS FALSE
				//console.log("StageRow.validateFiles    File/dir mismatch. Setting parameter validity as FALSE");
				Agua.setParameterValidity(this.fileStageParameters[i], false);
				this.isValid = false;
				if ( parameterRow != null )
				{
					//console.log("StageRow.validateFiles    DOING parameterRow.setInvalid(node)");
					parameterRow.setInvalid(parameterRow.containerNode);
				}
			}
			else {
				// SET PARAMETER VALIDITY AS TRUE
				//console.log("StageRow.validateFiles    paramtype matches. Setting parameter validity as TRUE");
				Agua.setParameterValidity(this.fileStageParameters[i], true);
				if ( parameterRow != null )
				{
					//console.log("StageRow.validateFiles    DOING parameterRow.setValid(containerNode)");
					//console.dir({containerNode:parameterRow.containerNode});
					parameterRow.setValid(parameterRow.containerNode);
				}
			}
		}
		else
		{
			if ( this.fileStageParameters[i].discretion == "essential" )
			{
				//console.log("StageRow.validateFiles    file '" + this.fileStageParameters[i].name + "' (discretion: " + this.fileStageParameters[i].discretion + ") does not exist. Setting stageParameter.isValid to FALSE");

				this.isValid = false;

				// DO Agua.setParameterValidity
				Agua.setParameterValidity(this.fileStageParameters[i], false);
				if ( parameterRow != null )
				{
					//console.log("StageRow.validateFiles    DOING parameterRow.setInvalid(node)");
					//console.dir({containerNode:parameterRow.containerNode});
					parameterRow.setInvalid(parameterRow.containerNode);
				}
			}
			else
			{
				// DO Agua.setParameterValidity
				Agua.setParameterValidity(this.fileStageParameters[i], true);
				if ( parameterRow != null )
				{
					//console.log("StageRow.validateFiles    DOING parameterRow.setValid(node)");
					//console.dir({containerNode:parameterRow.containerNode});
					parameterRow.setValid(parameterRow.containerNode);
				}
			}
		}
	}
	//console.log("StageRow.validateFiles    FINAL (w/o fileCheck) this.isValid: " + this.isValid);

	if ( this.isValid == false )
		this.setInvalid();
	else
		this.setValid();

	//console.groupEnd("stageRow-" + this.id + "    validateFiles");
},
checkValidFile : function (stageParameter, parameterRow) {
// LOAD UNKNOWN FILES INTO this.fileStageParameters AND this.fileParameterRows

	////console.group("StageRow-" + this.id + "    checkValidFile");
	//console.log("StageRow.checkValidFile     StageRow.checkValidFile(stageParameter)");
	//console.log("StageRow.checkValidFile     stageParameter: ");
	//console.dir({stageParameter:stageParameter});
	//console.log("StageRow.checkValidFile    stageParameter.name: " + stageParameter.name);

	var filepath = stageParameter.value;
	//console.log("StageRow.checkValidFile     Checking files/dirs");

	// CHECK NON-OPTIONAL FILEPATHS
	// required: FILE PATH MUST BE NON-EMPTY
	// essential: FILE/DIRECTORY MUST BE PHYSICALLY PRESENT
	if ( stageParameter.discretion == "required"
		|| stageParameter.discretion == "essential" )
	{
		//console.log("StageRow.checkValidFile     Parameter is required/essential");

		// SET this.isValid = false IF FILE/DIR IS NULL OR EMPTY
		if ( filepath == null || filepath == '' )
		{
			//console.log("StageRow.checkValidFile    Non-optional file/dir is null or empty.");
			//console.log("StageRow.checkValidFile    Setting stageParameter.parameterIsValid to FALSE.");
			this.setInvalidParameter(stageParameter, parameterRow);
		}

		// ADD TO this.fileStageParameters ARRAY IF NO fileinfo
		else if ( stageParameter.fileinfo == null )
		{
			//console.log("StageRow.checkValidFile    stageParameter.fileinfo is null. Pushing to fileStageParameters");
			//console.log("StageRow.checkValidFile    stageParameter: ");
			//console.dir({stageParameter:stageParameter});
			//console.log("StageRow.checkValidFile    parameterRow: ");
			//console.dir({parameterRow:parameterRow});

			this.fileStageParameters.push(stageParameter);
			this.fileParameterRows.push(parameterRow);
		}

		// FILE/DIR IS SPECIFIED BUT KNOWN TO NOT EXIST
		else if ( stageParameter.fileinfo.exists == "false" )
		{
			//console.log("StageRow.checkValidFile    Non-optional file/dir stageParameter.fileinfo.exists: " + stageParameter.fileinfo.exists);

			// PUSH ONTO this.fileStageParameters IF CHAINED = 0
			if ( stageParameter.chained == null
				|| stageParameter.chained == 0 )
			{
				//console.log("StageRow.checkValidFile    stageParameter.chained is 0 or null");
	 			//console.log("StageRow.checkValidFile    Pushing onto this.fileStageParameters");
				//console.log("StageRow.checkValidFile    stageParameter: ");
				//console.dir({stageParameter:stageParameter});
				//console.log("StageRow.checkValidFile    parameterRow: ");
				//console.dir({parameterRow:parameterRow});
				this.fileStageParameters.push(stageParameter);
				this.fileParameterRows.push(parameterRow);
			}

			// OTHERWISE, USE EXISTING PARAMETER VALIDITY INFO
			// TO SET THE VALIDITY OF THE PARAMETER ROW AND IGNORE
			// WHETHER OR NOT IT EXISTS (CHAINING IS THE PROMISE
			// THAT IT WILL EXIST ONCE THE PREVIOUS STAGE IS DONE.)
			else {
				//console.log("StageRow.checkValidFile    stageParameter.chained: " + stageParameter.chained);
				//console.log("StageRow.checkValidFile    Doing this.setValidParameter()");
				this.setValidParameter(stageParameter, parameterRow);
			}
		}

		// FILE/DIR IS SPECIFIED AND KNOWN TO EXIST
		else {
			//console.log("StageRow.checkValidFile    File/dir exists.");
			if ( stageParameter.fileinfo.type != stageParameter.valuetype )
			{
				// SET PARAMETER VALIDITY AS FALSE
				//console.log("StageRow.checkValidFile    File/dir mismatch. Setting parameter validity as FALSE");
				this.setInvalidParameter(stageParameter, parameterRow);
			}
			else {
				// SET PARAMETER VALIDITY AS TRUE
				//console.log("StageRow.checkValidFile    Paramtype matches. Setting parameter validity as TRUE");
				this.setValidParameter(stageParameter, parameterRow);
			}
		}
	}

	// IT'S AN OPTIONAL PARAMETER SO IT'S VALID IF EMPTY.
	// BUT IF ITS NOT EMPTY, CHECK IT EXISTS.
	else
	{
		// IF EMPTY
		if ( stageParameter.value == null
			|| stageParameter.value == '' )
		{
			//console.log("StageRow.checkValidFile    Ignoring empty optional file/dir parameter");
			this.setValidParameter(stageParameter, parameterRow);
		}
		else
		{
			//console.log("StageRow.checkValidFile    Optional file/dir parameter is specified. Pushing onto this.fileStageParameters array");
			//console.log("StageRow.checkValidFile    stageParameter: ");
			//console.dir({stageParameter:stageParameter});
			//console.log("StageRow.checkValidFile    parameterRow: ");
			//console.dir({parameterRow:parameterRow});
			this.fileStageParameters.push(stageParameter);
			this.fileParameterRows.push(parameterRow);
		}
	}

	////console.log("StageRow.checkValidFile    END. this.fileParameterRows:");
	////console.dir({fileParameterRows:this.fileParameterRows});
	////console.log("StageRow.checkValidFile    END. this.fileStageParameters:");
	////console.dir({fileStageParameters:this.fileStageParameters});

	//console.groupEnd("StageRow-" + this.id + "    checkValidFile");
},
checkValidInteger : function (stageParameter, parameterRow) {
	//console.log("StageRow.checkValidInteger     StageRow.checkValidInteger(stageParameter)");
	////console.log("StageRow.checkValidInteger     stageParameter: " + dojo.toJson(stageParameter));
	if ( stageParameter.discretion != "optional" )
	{
		// SET EMPTY NON-OPTIONAL INTEGER AS FALSE
		if ( stageParameter.value == null
				|| stageParameter.value == '' )
		{
			////console.log("StageRow.checkValidParameters      '" + stageParameter.name + "' Non-optional INTEGER input is empty. Setting this.isValid to FALSE");
			this.setInvalidParameter(stageParameter, parameterRow);
		}
		// NON-OPTIONAL INTEGER BUT IS NOT A PROPER NUMBER
		// ////SO SET TO false
		else if (! stageParameter.value.match(/^\s*[\d\.]+\s*$/) )
		{
			////console.log("StageRow.checkValidParameters      '" + stageParameter.name + "' Non-optional INTEGER input not valid. Setting this.isValid to FALSE");
			this.isValid = false;
			Agua.setParameterValidity(stageParameter, false);
		}
		// OTHERWISE, ITS A CORRECT OPTIONAL INTEGER SO SET TO true
		else
		{
			this.setValidParameter(stageParameter, parameterRow);
		}
	}
	else
	{
		// SET OPTIONAL INTEGER TO false IF ITS NON-EMPTY BUT NOT
		// AN INTEGER
		if ( stageParameter.value != null
				&& stageParameter.value != ''
				&& ! stageParameter.value.match(/^\s*[\d\.]+\s*$/) )
		{
			////console.log("StageRow.checkValidParameters      '" + stageParameter.name + "' Optional INTEGER input not valid. Setting this.isValid to FALSE");
			this.setInvalidParameter(stageParameter, parameterRow);
		}

		// OTHERWISE, ITS EITHER EMPTY OR AN INTEGER SO SET TO true
		else
		{
			////console.log("StageRow.checkValidParameters      '" + stageParameter.name + "' Optional INTEGER input is empty. Setting this.isValid to TRUE");
			this.setValidParameter(stageParameter, parameterRow);
		}
	}
},
checkValidText : function (stageParameter, parameterRow) {
	////console.log("StageRow.checkValidText     StageRow.checkValidText(stageParameter)");
	////console.log("StageRow.checkValidText     stageParameter: " + dojo.toJson(stageParameter));
	if ( stageParameter.discretion != "optional" )
	{
		if ( stageParameter.value == null
			|| stageParameter.value == '' )
		{
			////console.log("StageRow.checkValidText      '" + stageParameter.name + "' Required text input is null or empty. Setting this.isValid to FALSE");
			this.setInvalidParameter(stageParameter, parameterRow);
		}
		else
		{
			////console.log("StageRow.checkValidText      '" + stageParameter.name + "' Required text input is satisfied. Setting this.isValid to TRUE");
			this.setValidParameter(stageParameter, parameterRow);
		}
	}
	else
	{
		// THIS IS AN OPTIONAL PARAMETER SO, EMPTY OR NOT, ITS VALID
		////console.log("StageRow.checkValidText      '" + stageParameter.name + "' Optional text parameter. Setting stageParameter.isValid to TRUE");
		this.setValidParameter(stageParameter, parameterRow);
	}
},
toggle : function () {
	//////console.log("StageRow.toggle    plugins.workflow.StageRow.toggle()");
	//////console.log("StageRow.toggle    this.description: " + this.description);

	var array = [ "executor", "localonly", "location", "description", "notes" ];
	for ( var i in array )
	{
		if ( this[array[i]].style.display == 'table-cell' ) this[array[i]].style.display='none';
		else this[array[i]].style.display = 'table-cell';
	}
},
setInvalidParameter : function (stageParameter, parameterRow) {
	//console.log("StageRow.setInvalidParameter    stageParameter.name: " + stageParameter.name);
	//console.log("StageRow.setInvalidParameter    parameterRow: " + parameterRow);

	this.isValid = false;
	Agua.setParameterValidity(stageParameter, false);
	if ( parameterRow != null)
		parameterRow.setInvalid(parameterRow.containerNode);
},
setValidParameter : function (stageParameter, parameterRow) {
	////console.log("StageRow.setValidParameter    stageParameter.name: " + stageParameter.name);
	Agua.setParameterValidity(stageParameter, true);
	if ( parameterRow != null)
		parameterRow.setValid(parameterRow.containerNode);
},
setValid : function () {
	//console.log("StageRow.setValid    SETTING node to SATISFIED: " + this.id);
	//console.log("StageRow.setValid    this.setValid.caller.nom: " + this.setValid.caller.nom);

	dojo.removeClass(this.domNode, 'unsatisfied');
	dojo.addClass(this.domNode, 'satisfied');

	this.isValid = true;
	var stagesWidget = this.core.userWorkflows;
	//console.log("StageRow.setValid    this.stagesWidget: " + this.stagesWidget);
	stagesWidget.updateRunButton();
},
setInvalid : function () {
	//console.log("StageRow.setInvalid    SETTING node to UNSATISFIED: " + this.id);
	//console.log("StageRow.setInvalid    this.setInvalid.caller.nom: " + this.setInvalid.caller.nom);

	dojo.removeClass(this.domNode, 'satisfied');
	dojo.addClass(this.domNode, 'unsatisfied');

	this.isValid = false;
	var stagesWidget = this.core.userWorkflows;
	//console.log("StageRow.setInvalid    this.stagesWidget: " + this.stagesWidget);
	stagesWidget.updateRunButton();
},
getApplication : function () {
// RETURN A COPY OF this.application
	return dojo.clone(this.application);
},
setApplication : function (application) {
// SET this.application TO THE SUPPLIED APPLICATION OBJECT
	this.application = application;

	return this.application;
},
setNumber : function (number) {
// SET THE NUMBER NODE TO THE stage.number
	//console.log("StageRow.setNumber    plugins.workflow.StageRow.setNumber(" + number + ")");
	this.application.number = number;
	this.application.appnumber = number;
	this.numberNode.innerHTML = number;
}

});


text:
import { AssetCredentials } from "./gemini/getGeminiCredentialsForEnvironment"

export { getGeminiCredentialsForEnvironment } from "./gemini/getGeminiCredentialsForEnvironment"
export { createGeminiAssetWithS3Credentials } from "./gemini/createGeminiAssetWithS3Credentials"
export { getConvectionGeminiKey } from "./gemini/getConvectionGeminiKey"

export interface S3UploadResponse {
  key: string
}

// These are in RN, but not declared in the RN types:
// https://github.com/facebook/react-native/blob/master/Libraries/Network/FormData.js
// https://github.com/facebook/react-native/blob/master/Libraries/Network/XMLHttpRequest.js
declare var FormData: any
declare var XMLHttpRequest: any

interface Props {
  filePath: string
  acl: string
  assetCredentials: AssetCredentials
  updateProgress?: (progress: number) => void
  filename?: string
}
export const uploadFileToS3 = ({
  filePath,
  acl,
  assetCredentials,
  updateProgress,
  filename,
}: Props) =>
  new Promise<S3UploadResponse>((resolve, reject) => {
    const formData = new FormData()
    const geminiKey = assetCredentials.policyDocument.conditions.geminiKey
    const bucket = assetCredentials.policyDocument.conditions.bucket
    const uploadURL = `https://${bucket}.s3.amazonaws.com`

    const data = {
      acl,
      "Content-Type": "image/jpg",
      key: geminiKey + "/${filename}", // NOTE: This form (which _looks_ like ES6 interpolation) is required by AWS
      AWSAccessKeyId: assetCredentials.credentials,
      success_action_status: assetCredentials.policyDocument.conditions.successActionStatus,
      policy: assetCredentials.policyEncoded,
      signature: assetCredentials.signature,
    }

    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
        formData.append(key, data[key])
      }
    }

    formData.append("file", {
      uri: filePath,
      type: "image/jpeg",
      name: filename ?? "photo.jpg",
    })

    // Fetch didn't seem to work, so I had to move to a lower
    // level abstraction. Note that this request will fail if you are using a debugger.
    //
    // Kinda sucks, but https://github.com/jhen0409/react-native-debugger/issues/38
    const request = new XMLHttpRequest()
    // @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
    request.onload = (e) => {
      if (
        e.target.status.toString() ===
        assetCredentials.policyDocument.conditions.successActionStatus
      ) {
        // e.g. https://artsy-media-uploads.s3.amazonaws.com/A3tfuXp0t5OuUKv07XaBOw%2F%24%7Bfilename%7D
        const url = e.target.responseHeaders.Location
        resolve({
          key: url.split("/").pop().replace("%2F", "/"),
        })
      } else {
        reject(new Error("S3 upload failed"))
      }
    }
    request.upload.onprogress = ({ loaded, total }: { loaded: number; total: number }) => {
      if (updateProgress) {
        updateProgress(loaded / total)
      }
    }

    request.open("POST", uploadURL, true)
    request.onerror = () => {
      reject(new Error("Network error: Something went wrong"))
      return
    }

    request.setRequestHeader("Content-type", "multipart/form-data")
    request.send(formData)
  })


text:
"""
#Created on Tue Jul 29 10:12:58 2014

#@author: mcollado
"""

import Adafruit_DHT
import time
import sqlite3 as lite
import sys
import ConfigParser
import os

# If ConfigParser code fails this values are hardcoded
# To be removed when code works
sensor = Adafruit_DHT.AM2302
pin = 4

config = ConfigParser.RawConfigParser()
config.read(os.path.join(os.curdir,'tempsensor.cfg'))

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
sensor = config.get('Sensor', 'sensor')
pin = config.getint('Sensor', 'pin')

# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
     #print  time.strftime("%Y-%m-%d %H:%M:%S") + ' Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity)
     try:
        con = lite.connect('temps.db')

        cur = con.cursor()
        # insert into temps(data, temp,uum) values("2014-08-01 11:10:00",'27,4','40,3');
        data = "INSERT INTO temps(data, temp, hum) VALUES (\"" + time.strftime("%Y-%m-%d %H:%M:%S") + "\",'{0:0.1f}','{1:0.1f}')".format(temperature, humidity)
        print data
        cur.execute(data)

        con.commit()
     except lite.Error, e:
        if con:
            con.rollback()

        print "Error %s:" % e.args[0]
        sys.exit(1)
     finally:
        if con:
            con.close()

else:
     print 'Failed to get reading. Try again!'


text:
//! Random definition.
/*!
  \file     Random.h
  \author   Tody
  \date     2016/03/18
*/

#ifndef RANDOM_H
#define RANDOM_H

#include <Eigen/Dense>

//! Random implementation.
namespace Random
{
    void rand ( int size, Eigen::VectorXd& x, double low = 0.0, double high = 1.0 );

    void rand ( int rows, int cols, Eigen::MatrixXd& X, double low = 0.0, double high = 1.0 );

    void randint ( int size, Eigen::VectorXi& x, int low = 0, int high = 256 );

    void randint ( int rows, int cols, Eigen::MatrixXi& X, int low = 0, int high = 256 );

};

#endif


text:
PEGASUS_USING_STD;

PEGASUS_NAMESPACE_BEGIN

CIMDateTime CIMDateTime::getCurrentDateTime()
{
    // ATTN: Implement this method to get the current time as CIMDateTime.
    //       This is used in IndicationService.cpp.
    CIMDateTime currentTime;

    return currentTime;
}

PEGASUS_NAMESPACE_END


text:
from __future__ import absolute_import

import sys
import re

from .exceptions import SignatureError, RouteMissingError, RouteEndpointError
from .utils import to_bytes_2and3, constant_time_compare

class AlgorithmBase(object):
    """Base for algorithm support classes."""
    pass

class HasherBase(AlgorithmBase):
    """
    Base for algos which need a hash function. The ``bits`` param can be
    passed in from the capturing group of the routing regexp
    """
    supported_bits = (256, 384, 512)
    def __init__(self, bits):
        """
        Determine if the algorithm supports the requested bit depth and set up
        matching hash method from ``hashlib`` if necessary.
        """
        self.bits = int(bits)
        if self.bits not in self.supported_bits:
            raise NotImplementedError("%s implements %s bit algorithms (given %d)" %
                                      (self.__class__, ', '.join(self.supported_bits), self.bits))
        if not getattr(self, 'hasher', None):
            import hashlib
            self.hasher = getattr(hashlib, 'sha%d' % self.bits)

class HMAC(HasherBase):
    """
    Support for HMAC signing.
    """
    def sign(self, msg, key):
        import hmac
        if sys.version < '3':
            utfkey = unicode(key).encode('utf8')
        else:
            utfkey = to_bytes_2and3(key)
            msg = to_bytes_2and3(msg)
        return hmac.new(utfkey, msg, self.hasher).digest()

    def verify(self, msg, crypto, key):
        if not constant_time_compare(self.sign(msg, key), crypto):
            raise SignatureError("Could not validate signature")
        return True

class RSABase(HasherBase):
    """
    Support for RSA signing.

    The ``Crypto`` package >= 2.5 is required.

    """
    supported_bits = (256,384,512,) #:Seems to worka > 256

    def __init__(self, padder, bits):
        super(RSABase,self).__init__(bits)
        self.padder = padder
        from Crypto.Hash import SHA256,SHA384,SHA512
        self.hashm = __import__('Crypto.Hash.SHA%d'%self.bits, globals(), locals(), ['*']).new()

    def sign(self, msg, key):
        """
        Signs a message with an RSA PrivateKey and hash method
        """
        import Crypto.PublicKey.RSA as RSA

        self.hashm.update(msg.encode('UTF-8'))
        ## assume we are dealing with a real key
        # private_key = RSA.importKey(key)
        return self.padder.new(key).sign(self.hashm)             # pycrypto 2.5

    def verify(self, msg, crypto, key):
        """
        Verifies a message using RSA cryptographic signature and key.

        ``crypto`` is the cryptographic signature
        ``key`` is the verifying key. Can be a real key object or a string.
        """
        import Crypto.PublicKey.RSA as RSA

        self.hashm.update(msg.encode('UTF-8'))
        private_key = key
        if not isinstance(key, RSA._RSAobj):
            private_key = RSA.importKey(key)
        if not self.padder.new( private_key ).verify(self.hashm,  crypto):  #:pycrypto 2.5
            raise SignatureError("Could not validate signature")
        return True

class RSA_PKCS1_5(RSABase):
    def __init__(self, bits):
        import Crypto.Signature.PKCS1_v1_5 as PKCS
        super(RSA_PKCS1_5,self).__init__(PKCS, bits)

class RSA_PSS(RSABase):
    def __init__(self, bits):
        import Crypto.Signature.PKCS1_PSS as PSS
        super(RSA_PSS,self).__init__(PSS, bits)

class ECDSA(HasherBase):
    """
    Support for ECDSA signing. This is the preferred algorithm for private/public key
    verification.

    The ``ecdsa`` package is required. ``pip install ecdsa``
    """
    bits_to_curve = {
        256: 'NIST256p',
        384: 'NIST384p',
        512: 'NIST521p',
    }
    def sign(self, msg, key):
        """
        Signs a message with an ECDSA SigningKey and hash method matching the
        bit depth of curve algorithm.
        """
        import ecdsa
        ##  assume the signing key is already a real key
        # curve = getattr(ecdsa, self.bits_to_curve[self.bits])
        # signing_key = ecdsa.SigningKey.from_string(key, curve=curve)
        msg = to_bytes_2and3(msg)
        return key.sign(msg, hashfunc=self.hasher)

    def verify(self, msg, crypto, key):
        """
        Verifies a message using ECDSA cryptographic signature and key.

        ``crypto`` is the cryptographic signature
        ``key`` is the verifying key. Can be a real key object or a string.
        """
        import ecdsa
        curve = getattr(ecdsa, self.bits_to_curve[self.bits])
        vk = key
        if not isinstance(vk, ecdsa.VerifyingKey):
            vk = ecdsa.VerifyingKey.from_string(key, curve=curve)
        try:
            vk.verify(crypto, to_bytes_2and3(msg), hashfunc=self.hasher)
        except ecdsa.BadSignatureError:
            raise SignatureError("Could not validate signature")
        except AssertionError:
            raise SignatureError("Could not validate signature")
        return True

# algorithm routing
def route(name):
    return resolve(*find(name))

def find(name):
    # TODO: more error checking around custom algorithms
    algorithms = CUSTOM + list(DEFAULT)
    for (route, endpoint) in algorithms:
        match = re.match(route, name)
        if match:
            return (endpoint, match)
    raise RouteMissingError('endpoint matching %s could not be found' % name)

def resolve(endpoint, match):
    if callable(endpoint):
        # send result back through
        return resolve(endpoint(**match.groupdict()), match)

    # get the sign and verify methods from dict or obj
    try:
        crypt = { 'sign': endpoint['sign'], 'verify': endpoint['verify'] }
    except TypeError:
        try:
            crypt = { 'sign': endpoint.sign, 'verify': endpoint.verify }
        except AttributeError as e:
            raise RouteEndpointError('route enpoint must have sign, verify as attributes or items of dict')
    # verify callability
    try:
        assert callable(crypt['sign'])
        assert callable(crypt['verify'])
    except AssertionError as e:
        raise RouteEndpointError('sign, verify of endpoint must be callable')
    return crypt

DEFAULT = (
    (r'^HS(?P<bits>256|384|512)$', HMAC),
    (r'^RS(?P<bits>256|384|512)$', RSA_PKCS1_5),
    (r'^PS(?P<bits>256|384|512)$', RSA_PSS),
    (r'^ES(?P<bits>256|384|512)$', ECDSA),
)
CUSTOM = []


text:
<?php

class Google_Service_AndroidManagement_StatusReportingSettings extends Google_Model
{
  protected $applicationReportingSettingsType = 'Google_Service_AndroidManagement_ApplicationReportingSettings';
  protected $applicationReportingSettingsDataType = '';
  public $applicationReportsEnabled;
  public $commonCriteriaModeEnabled;
  public $deviceSettingsEnabled;
  public $displayInfoEnabled;
  public $hardwareStatusEnabled;
  public $memoryInfoEnabled;
  public $networkInfoEnabled;
  public $powerManagementEventsEnabled;
  public $softwareInfoEnabled;
  public $systemPropertiesEnabled;

  /**
   * @param Google_Service_AndroidManagement_ApplicationReportingSettings
   */
  public function setApplicationReportingSettings(Google_Service_AndroidManagement_ApplicationReportingSettings $applicationReportingSettings)
  {
    $this->applicationReportingSettings = $applicationReportingSettings;
  }
  /**
   * @return Google_Service_AndroidManagement_ApplicationReportingSettings
   */
  public function getApplicationReportingSettings()
  {
    return $this->applicationReportingSettings;
  }
  public function setApplicationReportsEnabled($applicationReportsEnabled)
  {
    $this->applicationReportsEnabled = $applicationReportsEnabled;
  }
  public function getApplicationReportsEnabled()
  {
    return $this->applicationReportsEnabled;
  }
  public function setCommonCriteriaModeEnabled($commonCriteriaModeEnabled)
  {
    $this->commonCriteriaModeEnabled = $commonCriteriaModeEnabled;
  }
  public function getCommonCriteriaModeEnabled()
  {
    return $this->commonCriteriaModeEnabled;
  }
  public function setDeviceSettingsEnabled($deviceSettingsEnabled)
  {
    $this->deviceSettingsEnabled = $deviceSettingsEnabled;
  }
  public function getDeviceSettingsEnabled()
  {
    return $this->deviceSettingsEnabled;
  }
  public function setDisplayInfoEnabled($displayInfoEnabled)
  {
    $this->displayInfoEnabled = $displayInfoEnabled;
  }
  public function getDisplayInfoEnabled()
  {
    return $this->displayInfoEnabled;
  }
  public function setHardwareStatusEnabled($hardwareStatusEnabled)
  {
    $this->hardwareStatusEnabled = $hardwareStatusEnabled;
  }
  public function getHardwareStatusEnabled()
  {
    return $this->hardwareStatusEnabled;
  }
  public function setMemoryInfoEnabled($memoryInfoEnabled)
  {
    $this->memoryInfoEnabled = $memoryInfoEnabled;
  }
  public function getMemoryInfoEnabled()
  {
    return $this->memoryInfoEnabled;
  }
  public function setNetworkInfoEnabled($networkInfoEnabled)
  {
    $this->networkInfoEnabled = $networkInfoEnabled;
  }
  public function getNetworkInfoEnabled()
  {
    return $this->networkInfoEnabled;
  }
  public function setPowerManagementEventsEnabled($powerManagementEventsEnabled)
  {
    $this->powerManagementEventsEnabled = $powerManagementEventsEnabled;
  }
  public function getPowerManagementEventsEnabled()
  {
    return $this->powerManagementEventsEnabled;
  }
  public function setSoftwareInfoEnabled($softwareInfoEnabled)
  {
    $this->softwareInfoEnabled = $softwareInfoEnabled;
  }
  public function getSoftwareInfoEnabled()
  {
    return $this->softwareInfoEnabled;
  }
  public function setSystemPropertiesEnabled($systemPropertiesEnabled)
  {
    $this->systemPropertiesEnabled = $systemPropertiesEnabled;
  }
  public function getSystemPropertiesEnabled()
  {
    return $this->systemPropertiesEnabled;
  }
}


text:
import Listener from 'appkit/lib/routes/nav/listener';

export default Listener.extend({

});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Kamilimu</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/main.css" rel="stylesheet">

        Kamilimu Git Exercise
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home
                (current)

              Peer Mentees

              Mentees

Kamilimu Git + GitHub Exercise rules

Rule #1: Task

Follow my example in the peer mentor menu

Add your mini profile respective to your role as a mentee or peer mentor in Kamilimu

Once you are done, post your reply to the G+Group topic I created to confirm your pull request.

It is your absolute responsibility to ensure that the page is clean and works correctly before your pull request, so that others do not face a challenge.

Rule #2: Technologies

Use Git (duuh): Fork the repository, work on your profile the send a pull request

 PS: You can totally edit the page directly on GitHub if you are not conversant with Git

 Play around with Git

Reference Book

Use BootStrap3 or 4, for a guide, follow the link below

Here's the resource

Rule #3: Submission

Submission deadline is on Saturday Midnight

Remember to post a reply to the Google groups topics, when you are done

Copyright © Kamilimu 2017


text:
package study.pmoreira.project5.ui;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import study.pmoreira.project5.R;
import study.pmoreira.project5.entity.Hotel;
import study.pmoreira.project5.entity.Place;

public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<CustomRecyclerViewAdapter.ViewHolder> {

    private LayoutInflater mInflater;

    private List<Place> mPlaces;

    public CustomRecyclerViewAdapter(Context context, List<Place> places) {
        mInflater = LayoutInflater.from(context);

        mPlaces = places;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(mInflater.inflate(R.layout.recycler_row, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final Place place = mPlaces.get(position);

        holder.nameTextView.setText(place.getName());
        holder.descriptionTextView.setText(place.getDescription());

        if (place instanceof Hotel) {
            holder.pictureImageview.setImageResource(((Hotel) place).getImageId());
            holder.pictureImageview.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        return mPlaces.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.picture_imageview)
        ImageView pictureImageview;

        @BindView(R.id.name_textview)
        TextView nameTextView;

        @BindView(R.id.description_textview)
        TextView descriptionTextView;

        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}


text:
vacuum full;
vacuum analyze;


text:
package fi.aalto.ssg.opentee.exception;

import fi.aalto.ssg.opentee.ITEEClient;

/**
 * The requested data item is not found. This exception can be threw by underlying library when CA
 * tries to refer a shared memory which has already been released.
 */
public class ItemNotFoundException extends TEEClientException {
    public ItemNotFoundException(String msg){
        super(msg);
    }

    public ItemNotFoundException(String msg, ITEEClient.ReturnOriginCode retOrigin){
        super(msg, retOrigin);
    }
}


text:
import sys
import time
from datetime import datetime, timedelta, timezone

from libqtile.log_utils import logger
from libqtile.widget import base

try:
    import pytz
except ImportError:
    pass

try:
    import dateutil.tz
except ImportError:
    pass

class Clock(base.InLoopPollText):
    """A simple but flexible text-based clock"""
    orientations = base.ORIENTATION_HORIZONTAL
    defaults = [
        ('format', '%H:%M', 'A Python datetime format string'),
        ('update_interval', 1., 'Update interval for the clock'),
        ('timezone', None, 'The timezone to use for this clock, either as'
         ' string if pytz or dateutil is installed (e.g. "US/Central" or'
         ' anything in /usr/share/zoneinfo), or as tzinfo (e.g.'
         ' datetime.timezone.utc). None means the system local timezone and is'
         ' the default.')
    ]
    DELTA = timedelta(seconds=0.5)

    def __init__(self, **config):
        base.InLoopPollText.__init__(self, **config)
        self.add_defaults(Clock.defaults)
        if isinstance(self.timezone, str):
            if "pytz" in sys.modules:
                self.timezone = pytz.timezone(self.timezone)
            elif "dateutil" in sys.modules:
                self.timezone = dateutil.tz.gettz(self.timezone)
            else:
                logger.warning('Clock widget can not infer its timezone from a'
                               ' string without pytz or dateutil. Install one'
                               ' of these libraries, or give it a'
                               ' datetime.tzinfo instance.')
        if self.timezone is None:
            logger.info('Defaulting to the system local timezone.')

    def tick(self):
        self.update(self.poll())
        return self.update_interval - time.time() % self.update_interval

    # adding .5 to get a proper seconds value because glib could
    # theoreticaly call our method too early and we could get something
    # like (x-1).999 instead of x.000
    def poll(self):
        if self.timezone:
            now = datetime.now(timezone.utc).astimezone(self.timezone)
        else:
            now = datetime.now(timezone.utc).astimezone()
        return (now + self.DELTA).strftime(self.format)


text:
#ifndef _VKREFUTIL_HPP
#define _VKREFUTIL_HPP
/*!
 * \file
 * \brief Vulkan object reference holder utilities.
 *//*--------------------------------------------------------------------*/

#include "vkDefs.hpp"
#include "vkRef.hpp"

namespace vk
{

#include "vkRefUtil.inl"

Move<VkPipeline>		createGraphicsPipeline	(const DeviceInterface&					vk,
												 VkDevice								device,
												 VkPipelineCache						pipelineCache,
												 const VkGraphicsPipelineCreateInfo*	pCreateInfo,
												 const VkAllocationCallbacks*			pAllocator = DE_NULL);
Move<VkPipeline>		createComputePipeline	(const DeviceInterface&					vk,
												 VkDevice								device,
												 VkPipelineCache						pipelineCache,
												 const VkComputePipelineCreateInfo*		pCreateInfo,
												 const VkAllocationCallbacks*			pAllocator = DE_NULL);
#ifndef CTS_USES_VULKANSC
Move<VkPipeline>		createRayTracingPipelineNV(const DeviceInterface&					vk,
												 VkDevice								device,
												 VkPipelineCache						pipelineCache,
												 const VkRayTracingPipelineCreateInfoNV*	pCreateInfo,
												 const VkAllocationCallbacks*			pAllocator = DE_NULL);
Move<VkPipeline>		createRayTracingPipelineKHR	(const DeviceInterface&					vk,
												 VkDevice									device,
												 VkDeferredOperationKHR						deferredOperation,
												 VkPipelineCache							pipelineCache,
												 const VkRayTracingPipelineCreateInfoKHR*	pCreateInfo,
												 const VkAllocationCallbacks*				pAllocator = DE_NULL);
#endif // CTS_USES_VULKANSC

Move<VkCommandBuffer>	allocateCommandBuffer	(const DeviceInterface& vk, VkDevice device, const VkCommandBufferAllocateInfo* pAllocateInfo);
void allocateCommandBuffers	(const DeviceInterface& vk, VkDevice device, const VkCommandBufferAllocateInfo* pAllocateInfo, Move<VkCommandBuffer> *pCommandBuffers);
Move<VkDescriptorSet>	allocateDescriptorSet	(const DeviceInterface& vk, VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo);

Move<VkSemaphore>		createSemaphore			(const DeviceInterface&			vk,
												 VkDevice						device,
												 VkSemaphoreCreateFlags			flags		= (VkSemaphoreCreateFlags)0,
												 const VkAllocationCallbacks*	pAllocator	= DE_NULL);

Move<VkSemaphore>		createSemaphoreType		(const DeviceInterface&			vk,
												 VkDevice						device,
												 VkSemaphoreType				type,
												 VkSemaphoreCreateFlags			flags			= (VkSemaphoreCreateFlags)0,
												 const deUint64					initialValue	= 0,
												 const VkAllocationCallbacks*	pAllocator		= DE_NULL);

Move<VkFence>			createFence				(const DeviceInterface&			vk,
												 VkDevice						device,
												 VkFenceCreateFlags				flags		= (VkFenceCreateFlags)0,
												 const VkAllocationCallbacks*	pAllocator	= DE_NULL);

Move<VkCommandPool>		createCommandPool		(const DeviceInterface&			vk,
												 VkDevice						device,
												 VkCommandPoolCreateFlags		flags,
												 deUint32						queueFamilyIndex,
												 const VkAllocationCallbacks*	pAllocator	= DE_NULL);

Move<VkCommandBuffer>	allocateCommandBuffer	(const DeviceInterface&			vk,
												 VkDevice						device,
												 VkCommandPool					commandPool,
												 VkCommandBufferLevel			level);

Move<VkEvent>			createEvent				(const DeviceInterface&			vk,
												 VkDevice						device,
												 VkEventCreateFlags				flags = (VkEventCreateFlags)0u,
												 const VkAllocationCallbacks*	pAllocateInfo = DE_NULL);

#ifdef CTS_USES_VULKANSC
Move<VkShaderModule>	createShaderModule		(const DeviceInterface&			vk,
												 VkDevice						device,
												 const VkShaderModuleCreateInfo*	pCreateInfo,
												 const VkAllocationCallbacks*	pAllocator = DE_NULL);
#endif // CTS_USES_VULKANSC

} // vk

#endif // _VKREFUTIL_HPP


text:
:- module(man_topic, []).

:- use_module(library(pce)).
:- require([ get_chain/3
           , member/2
           , send_list/3
           ]).

:- pce_begin_class(man_topic_browser, man_frame,
                   "Topic browser").

variable(topics,        man_module,             get, "`Topic' manual module").
variable(selection,     man_topic_card*,        get, "Selected topic").

initialise(TB, Manual:man_manual) :->
    "Create from Manual"::
    send(TB, send_super, initialise, Manual, 'Topic Browser'),

    get(Manual, module, topics, @on, Module),
    send(TB, slot, topics, Module),

    picture(Picture, Module),
    dialog(Dialog),

    send(TB, append, Picture),
    send(Dialog, below, Picture),
    send(TB, edit_mode, Manual?edit_mode),
    send(TB, expand_node, TB?tree?root),

    send(TB, open).

                /********************************
                *            DIALOG             *
                ********************************/

dialog(D) :-
    new(D, dialog),
    new(TB, D?frame),

    send(D, append, new(TN, text_item(name,    '', @nil))),
    send(D, append, new(TS, text_item(summary, '',
                                      if(TN?selection \== '',
                                         message(D?create_member,
                                                 execute))))),
    send(TN, length, 15),
    send(TS, length, 40),
    send(D, append, button(create, block(message(TB, create_topic,
                                                 TN?selection,
                                                 TS?selection),
                                         message(TN, clear),
                                         message(TS, clear),
                                         message(TN, caret)))),
    send(D, append, button(help,   message(TB, help))),
    send(D, append, button(quit,   message(TB, quit))).

                /********************************
                *          COMMUNICATION        *
                ********************************/

edit_mode(TB, Val:bool) :->
    "Switch edit mode on/off"::
    get(TB, dialog_member, Dialog),
    send_list([ Dialog?create_member
              , Dialog?name_member
              , Dialog?summary_member
              ],
              active, Val).

node(TB, Card:man_topic_card, Node) :<-
    "Find node displaying card"::
    get(TB?tree, find, @arg1?card == Card, Node).

selected(TB, Obj:object*) :->
    "Set the selection"::
    get(TB, tree, Tree),
    send(Tree, for_all, message(@arg1, inverted, @off)),
    (   Obj \== @nil,
        send(Obj, instance_of, man_topic_card)
    ->  send(TB, slot, selection, Obj),
        (   get(TB, node, Obj, Node)
        ->  send(Node, inverted, @on)
        ;   true
        )
    ;   send(TB, slot, selection, @nil)
    ).

release_selection(TB) :->
    send(TB, selected, @nil).

unrelated(TB, From:object*, Rel:name, To:object*) :->
    "Trap delated relations"::
    send(TB, related, From, Rel, To).

related(TB, From:object*, Rel:name, _To:object*) :->
    "Trap added relations"::
    Rel == see_also,
    get(TB, current, From),
    send(TB, update_related).

                /********************************
                *            EDITING            *
                ********************************/

create_topic(TB, Name:string, Summary:string, Super:[man_topic_card]) :->
    "Add a new topic from name and summary"::
    (   Super == @default
    ->  get(TB, selection, SuperTopic),
        (   SuperTopic == @nil
        ->  send(@display, inform, 'Please first select a super-topic'),
            fail
        ;   true
        )
    ;   SuperTopic = Super
    ),
    send(Name, strip),
    (   get(Name, size, 0)
    ->  send(@display, inform, 'Please enter a topic name first')
    ;   new(Topic, man_topic_card(TB?topics, Name)),
        send(Topic, store, summary, Summary),
        send(SuperTopic, relate, subs, Topic),
        send(Topic, relate, super, SuperTopic),
        get(TB, node, SuperTopic, SuperNode),
        send(SuperNode, font, font(helvetica, bold, 12)),
        add_card(SuperNode, Topic)
    ).

rename_node(TB, Node:node) :->
    "Rename node to name in dialog"::
    get(TB?dialog_member?name_member, selection, NewName),
    (   NewName == ''
    ->  send(@display, inform, 'First type a name in ''Name''')
    ;   send(Node?card, store, name, NewName),
        send(Node, string, NewName),
        send(TB?dialog_member?name_member, clear)
    ),
    get(TB?dialog_member?summary_member, selection, NewName),
    (   NewSumm == ''
    ->  true
    ;   send(Node?card, store, summary, NewSumm),
        send(TB?dialog_member?summary_member, clear)
    ).

delete_card(_TB, Node:node) :->
    "Destroy a card"::
    get(Node, card, Card),
    send(@display, confirm, 'Really delete card `%s''', Card?name),
    (   get(Card, related, subs, Subs),
        \+ send(Subs, empty)
    ->  send(@display, inform, 'Only leaf-nodes can be deleted')
    ;   send(Node, delete_tree),
        send(Card, free)
    ).

son_node(TB, Node:node) :->
    "Relate node to selection"::
    get(TB, selection, Selection), Selection \== @nil,
    send(Selection, relate, subs, Node?card),
    send(Node?card, relate, super, Selection),
    send(?(TB, node, Selection), son, Node).

remove_son_node(TB, Node:node) :->
    "Unrelate a node from selection"::
    get(TB, selection, Selection), Selection \== @nil,
    send(Selection, unrelate, subs, Node?card),
    send(Node?card, unrelate, super, Selection),
    send(?(TB, node, Selection), unrelate, Node).

below_node(TB, Node:node) :->
    "Move node below selection or to be the first"::
    get_chain(Node, parents, Parents),
    (   get(TB, selection, Selection),
        Selection \== @nil,
        get(TB, node, Selection, SelectedNode),
        member(Parent, Parents),
        send(Parent?sons, member, SelectedNode)
    ->  send(Parent?card, move_relation_after, subs, Node?card, Selection),
        send(Node, move_after, SelectedNode)
    ;   member(Parent, Parents)
    ->  send(Parent?card, move_relation_after, subs, Node?card),
        send(Node, move_after)
    ),
    send(TB, request_selection, Node?card, @off).

                /********************************
                *            PICTURE            *
                ********************************/

:- pce_global(@man_topic_node_handler, make_man_topic_node_handler).

make_man_topic_node_handler(H) :-
    new(TB, @arg1?frame),
    new(Manual, TB?manual),
    new(CanEdit, Manual?edit_mode == @on),
    new(Selection, Manual?selection),
    Node = @arg1,
    new(Card, Node?card),

    new(P, popup),
    send_list(P, append,
              [ menu_item(select,
                          message(TB, request_selection, Card, @on),
                          @default, @on,
                          Selection \== Card)
              , menu_item(expand,
                          message(TB, expand_node, Node),
                          @default, @off,
                          and(message(Node?sons, empty),
                              ?(Card, man_related, subs)))
              , menu_item(expand_tree,
                          message(TB, expand_tree, Node),
                          @default, @off,
                          ?(Card, man_related, subs))
              , menu_item(collapse_node,
                          message(TB, collapse_node, Node),
                          @default, @on,
                          not(message(Node?sons, empty)))
              , menu_item(relate,
                          message(TB, request_relate, Card),
                          @default, @off,
                          and(CanEdit,
                              Selection \== @nil,
                              Selection \== Card,
                              not(message(Card, man_related,
                                          see_also, Selection))))
              , menu_item(rename,
                          message(TB, rename_node, Node),
                          @default, @on,
                          and(CanEdit,
                              TB?dialog_member?name_member?selection \== ''))
              , menu_item(move_below,
                          message(TB, below_node, Node),
                          @default, @off,
                          CanEdit)
              , menu_item(make_daughter,
                          message(TB, son_node, Node),
                          @default, @off,
                          CanEdit)
              , menu_item(remove_daughter,
                          message(TB, remove_son_node, Node),
                          @default, @on,
                          CanEdit)
              , menu_item(delete_card,
                          message(TB, delete_card, Node),
                          @default, @off,
                          CanEdit)
              ]),

    HNode = @receiver,
    new(HTool, HNode?frame),

    new(H, handler_group(popup_gesture(P),
                         click_gesture(left, c, single,
                                       message(HTool, below_node, HNode)),
                         click_gesture(left, '', single,
                                       message(HTool, request_selection,
                                               HNode?card, @off)),
                         click_gesture(left, '', double,
                                       message(HTool, request_selection,
                                               HNode?card, @on)))).

picture(P, Topics) :-
    new(P, picture),
    (   get(Topics, card, root, Root)
    ->  true
    ;   new(Root, man_topic_card(Topics, 'Contents', root)),
        send(Root, store, summary, string("Root of the topic index"))
    ),
    create_node(Root, Node),
    send(P, display, new(T, tree(Node))),
    send(T, level_gap, 25),
    send(T, node_handler, @man_topic_node_handler).

create_node(Card, Node) :-
    (   get(Card, related, subs, Subs),
        Subs \== @nil,
        \+ send(Subs, empty)
    ->  Font = font(helvetica, bold,  12)
    ;   Font = font(helvetica, roman, 12)
    ),
    new(Node, node(text(Card?name, left, Font))),
    send(Node, attribute, attribute(card, Card)).

tree(TB, Tree) :<-
    "Get the associated tree object"::
    get(TB?picture_member, tree_member, Tree).

expand_node(_TB, Node:node) :->
    "Make all sub-topics visible"::
    (   get(Node?card, related, subs, SubCards)
    ->  send(SubCards, for_all, message(@prolog, add_card, Node, @arg1))
    ;   true
    ).

add_card(Node, Card) :-
    (   get(Node?sons, find, @arg1?card == Card, _)
    ->  true
    ;   create_node(Card, Sub),
        send(Node, son, Sub)
    ).

expand_tree(TB, Node:node) :->
    "Expand all nodes below this one"::
    send(TB, expand_node, Node),
    send(Node?sons, for_all, message(TB, expand_tree, @arg1)).

collapse_node(_TB, Node:node) :->
    "Undisplay all subnodes"::
    send(Node?sons, for_all, message(@arg1, delete_tree)).

:- pce_end_class.


text:
Tooltips for any element using any html in AngularJS with no requirements.

**Why another tooltip library?**

There are other libraries out there like https://github.com/720kb/angular-tooltips or https://angular-ui.github.io/bootstrap/#/tooltip
but they either have requirements on other libraries or are overly convoluted in their approach (which can break other things).

This is a very small (8 kB) library that keeps things simple. It also cleans up after itself and doesn't leave rouge elements all over the window.

## Installation

Install through bower

```
bower install tooltips-angular
```

or npm

```
npm install angularjs-tooltips
```

Include the library files

```html
<link rel="stylesheet" href="bower_components/dist/angular-tooltips.css" />
<script src="bower_components/dist/angular-tooltips.js"></script>
```

Add the angular model ```tooltips```

```js
angular.module('app', ['tooltips'])
```

## Usage

Just add a normal title attribute and it will be overridden.

```html
<i class="fa fa-star" title="This is a star!"></i>
```

The direction of the tooltip can be specified using ```title-direction``` with the options: top, top-right, right-top, right, right-bottom, bottom-right, bottom, bottom-left, left-bottom, left, left-top, top-left

```html
<i class="fa fa-star" title="This is a star!" title-direction="right"></i>
```

The direction of the tooltip will automatically swap if the tooltip will sit outside of the window bounds.
To stop this happening and force the direction set the ```fixed-position``` option

```html
<i class="fa fa-star" title="This is a star!" title-direction="right" fixed-position="true"></i>
```

## Demo

http://intellipharm.github.io/angular-tooltips/

## Requrements

**None!!**


text:
class D3ObyTCPServer::Logger

  def log(msg, type)
  end

  def info(msg)
    log msg, :info
  end

  def err(msg)
    log msg, :err
  end
end


text:
/*

Azure Media Services REST API v2 Function

This function delete AMS entities (job(s) and/or asset(s)).

Input:
{
    "jobID": "nb:jid:UUID:7f566f5e-be9c-434f-bb7b-101b2e24f27e,nb:jid:UUID:58f9e85a-a889-4205-baa1-ecf729f9c753",     // job(s) id. Coma delimited if several job ids
    "assetId" : "nb:cid:UUID:61926f1d-69ba-4386-a90e-e27803104853,nb:cid:UUID:b4668bc4-2899-4247-b339-429025153ab9"   // asset(s) id.
}

Output:
{

}
*/

using System;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.MediaServices.Client;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;

namespace media_functions_for_logic_app
{
    public static class delete_entity
    {
        // Field for service context.
        private static CloudMediaContext _context = null;

        [FunctionName("delete-entity")]
        public static async Task<object> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"Webhook was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();
            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            log.Info(jsonContent);

            if (data.jobId == null && data.assetId == null)
            {
                return req.CreateResponse(HttpStatusCode.BadRequest, new
                {
                    error = "Please pass job Id and/or asset Id of the objects to delete"
                });
            }

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
            log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");

            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);
            }
            catch (Exception ex)
            {
                log.Info($"Exception {ex}");
                return req.CreateResponse(HttpStatusCode.InternalServerError, new
                {
                    Error = ex.ToString()
                });
            }

            try
            {
                if (data.jobId != null)
                {
                    var jobids = (string)data.jobId;
                    foreach (string jobi in jobids.Split(','))
                    {
                        log.Info($"Using job Id : {jobi}");
                        var job = _context.Jobs.Where(j => j.Id == jobi).FirstOrDefault();
                        if (job != null)
                        {
                            job.Delete();
                            log.Info("Job deleted.");
                        }
                        else
                        {
                            log.Info("Job not found!");
                        }
                    }
                }

                if (data.assetId != null)
                {
                    var assetids = (string)data.assetId;
                    foreach (string asseti in assetids.Split(','))
                    {
                        log.Info($"Using asset Id : {asseti}");
                        var asset = _context.Assets.Where(a => a.Id == asseti).FirstOrDefault();
                        if (asset != null)
                        {
                            asset.Delete();
                            log.Info("Asset deleted.");
                        }
                        else
                        {
                            log.Info("Asset not found!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
                log.Info($"ERROR: Exception {message}");
                return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message });
            }

            return req.CreateResponse(HttpStatusCode.OK, new
            {

            });
        }
    }
}


text:
FROM java:8
ENV VERSION 0.1-SNAPSHOT
VOLUME /tmp
ADD agent-gateway-${VERSION}.jar app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]


text:
import os
import time
import pytz
import datetime
import requests
import threading
import matplotlib.pyplot  as plt
import matplotlib.patches as mpatches
import matplotlib.dates   as mdates

SECOND =   1
MINUTE =  60 * SECOND
HOUR   =  60 * MINUTE
DAY    =  24 * HOUR
WEEK   =   7 * DAY
MONTH  =  31 * DAY
YEAR   = 365 * DAY

WORKING   = 0
REQUESTED = 1
DONE      = 2

class ChartThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self._CLOUDANT_HOST      = os.environ.get("CLOUDANT_HOST",     "localhost")
        self._CLOUDANT_USERNAME  = os.environ.get("CLOUDANT_USERNAME", "admin"    )
        self._CLOUDANT_PASSWORD  = os.environ.get("CLOUDANT_PASSWORD", "admin"    )
        self._CLOUDANT_DB        = os.environ.get("CLOUDANT_DB",       "defaultdb")
        self._state              = REQUESTED
        self.start()

    def _draw_chart(self):
        smooth                 = 20
        filtersize             = 8000
        myFmt                  = mdates.DateFormatter('%d.%b %H:%M')
        watertemp_patch        = mpatches.Patch(color='blue',   label='Water')
        airtemp_patch          = mpatches.Patch(color='green',  label='Air')
        heater_patch           = mpatches.Patch(color='red',    label='Heater')
        humidity_patch         = mpatches.Patch(color='blue',   label='Humidity')
        heaterpercentage_patch = mpatches.Patch(color='red',    label='Heater Percentage')
        sun_patch              = mpatches.Patch(color='orange', label='Sun')
        moon_patch             = mpatches.Patch(color='blue',   label='Moon')
        data                   = self._get_cloudant_data()
        timeval                = self._get_keys(data)
        timedt                 = self._get_date_time(data)
        watertemp              = self._get_value(data, "watertemp")
        airtemp                = self._get_value(data, "airtemp"  )
        heater                 = self._get_value(data, "heater"   )
        heaterspecial          = self._get_modified(heater, 0.2, 23)
        heaterBoolean          = self._get_boolean(heater)
        humidity               = self._get_value(data, "humidity")
        moon                   = self._get_value(data, "moon")
        sun                    = self._get_value(data, "sun")
        smoothairtemp          = [0] * len(timeval)
        smoothhum              = [0] * len(timeval)
        heaterPercentage       = [0] * len(timeval)

        # smooth the raw values
        for i in range(smooth, len(timeval) - smooth):
            airdummy = 0.0
            humdummy = 0.0
            for j in range(i - smooth, i + smooth):
                airdummy += airtemp[j]
                humdummy += humidity[j]
            airdummy /= (2.0 * smooth)
            humdummy /= (2.0 * smooth)
            smoothairtemp[i] = airdummy
            smoothhum[i] = humdummy

        for i in range(len(timeval) - smooth, len(timeval)):
            smoothairtemp[i] = smoothairtemp[len(timeval) - smooth - 1]
            smoothhum[i] = smoothhum[len(timeval) - smooth - 1]

        # Calculate heater percentage
        for i in range(filtersize, len(timeval)):
            timeOn = 0.0
            for m in range(i - filtersize, i):
                if heaterBoolean[m]:
                    timeOn += timeval[m] - timeval[m - 1]
            heaterPercentage[i] = (timeOn / (timeval[i] - timeval[i - filtersize])) * 100

        # Temp
        with plt.xkcd():
            duration = 12000
            fig = plt.figure(figsize=(20, 15), dpi=256)
            ax  = fig.add_axes((0.035, 0.068, 0.93, 0.93))
            ax.spines['right'].set_color('none')
            ax.spines['top'].set_color('none')
            ax.plot(timedt[-duration:], watertemp[-duration:],     'blue',
                    timedt[-duration:], smoothairtemp[-duration:], 'green',
                    timedt[-duration:], heaterspecial[-duration:], 'red'
                   )
            ax.legend(handles=[watertemp_patch, airtemp_patch, heater_patch])
            ax.xaxis.set_major_formatter(myFmt)
            fig.autofmt_xdate()
            fig.savefig("temperature.png")

        # Percentage
        with plt.xkcd():
            duration = 20000
            fig = plt.figure(figsize=(20, 15), dpi=256)
            ax  = fig.add_axes((0.035, 0.068, 0.93, 0.93))
            ax.spines['right'].set_color('none')
            ax.spines['top'].set_color('none')
            ax.plot(timedt[-duration:], heaterPercentage[-duration:], 'red',
                    timedt[-duration:], smoothairtemp[-duration:], 'green',
                    timedt[-duration:], smoothhum[-duration:], 'blue')
            ax.legend(handles=[heaterpercentage_patch, airtemp_patch, humidity_patch])
            ax.xaxis.set_major_formatter(myFmt)
            fig.autofmt_xdate()
            fig.savefig("percentage.png")

        # sun moon
        with plt.xkcd():
            duration = 70000
            fig = plt.figure(figsize=(20, 15), dpi=256)
            ax  = fig.add_axes((0.035, 0.068, 0.93, 0.93))
            ax.spines['right'].set_color('none')
            ax.spines['top'].set_color('none')
            ax.plot(timedt[-duration:], sun[-duration:], 'orange',
                    timedt[-duration:], moon[-duration:], 'blue')
            ax.legend(handles=[sun_patch, moon_patch])
            ax.xaxis.set_major_formatter(myFmt)
            fig.autofmt_xdate()
            fig.savefig("sunmoon.png")

    def trigger(self):
        self._state = REQUESTED

    def is_done(self):
        if self._state == DONE:
            return True
        else:
            return False

    def run(self):
        while True:

            if self._state == REQUESTED:
                self._state = WORKING
                self._draw_chart()
                self._state = DONE
                print("DONE")

            time.sleep(1)

    def _get_keys(self, data):
        keys = []
        for i in data:
            keys.append(float(i['key']))
        return keys

    def _get_date_time(self, data):
        keys = []
        for i in data:
            keys.append(datetime.datetime.fromtimestamp(i['key'], tz=pytz.timezone('Europe/Berlin')))
        return keys

    def _get_value(self, data, name):
        values = []
        for i in data:
            if isinstance(i['value'][name], str):
                values.append(float(i['value'][name]))
            elif isinstance(i['value'][name], int) or isinstance(i['value'][name], float):
                values.append(i['value'][name])
            elif i['value'][name] is None:
                values.append(0)
            else:
                print(type(i['value'][name]))
                print(i)
        return values

    def _get_modified(self, data, mulval, addval):
        d = []
        for i in data:
            d.append(addval + (float(i) * mulval))
        return d

    def _get_boolean(self, data):
        d = [False] * len(data)
        for i in range(len(data)):
            if float(data[i]) == 1:
                d[i] = True
        return d

    def _get_cloudant_data(self):
        URL  = "https://%s/%s/_design/livingroom/_view/tank?descending=false&startkey=%f&endkey=%f" % (
               self._CLOUDANT_HOST, self._CLOUDANT_DB, time.time() - (10 * DAY), time.time())
        AUTH = (self._CLOUDANT_USERNAME, self._CLOUDANT_PASSWORD)

        try:
            result = requests.get(URL, headers={"Content-Type": "application/json"}, auth=AUTH)

            if result.status_code == 200:
                return result.json()['rows']

            else:
                print("DB Access result code not ok")
                print(result.status_code)
                print(result.content)

        except Exception as e:
            print("Error accessing db")
            print(e)