text:
package com.mygdx.game.entites.systems;

import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.mygdx.game.Factory.EntityFactory;
import com.mygdx.game.entites.entitiycomponents.HealthComponent;
import com.mygdx.game.entites.entitiycomponents.Mappers;
import com.mygdx.game.entites.entitiycomponents.PositionComponent;
import com.mygdx.game.entites.entitiycomponents.enemy.EnemyComponent;
import com.mygdx.game.managers.WaveTimeManager;
import com.mygdx.game.states.PlayState;
import com.mygdx.game.utils.Assets;

public class HealthSystem extends IteratingSystem {
	private SpriteBatch _batch;
	private EntityFactory _entityFactory;

	public HealthSystem(SpriteBatch batch, EntityFactory factory) {
		super(Family.all(HealthComponent.class, PositionComponent.class).get());
		_entityFactory = factory;
		_batch = batch;
	}

	@Override
	protected void processEntity(Entity entity, float deltaTime) {
		HealthComponent hpComp = Mappers.HEALTH_M.get(entity);
		PositionComponent posComp = Mappers.POSITION_M.get(entity);
		EnemyComponent enemyComp = Mappers.ENEMY_M.get(entity);
		if (hpComp.isDead) {
			float deathX = posComp.position.x;
			float deathY = posComp.position.y;
			entity.removeAll();
			getEngine().removeEntity(entity);
			if(enemyComp != null){
				PlayState.CURRENT_LIVING_ENEMIES --;
			}
			_entityFactory.createCoinEntity(deathX, deathY, WaveTimeManager.WAVE + MathUtils.random(1));
		}
		if(enemyComp != null){
			drawHealthBar(hpComp, posComp);
		}
	}

	private void drawHealthBar(HealthComponent healthComp, PositionComponent pos) {
		final float healthBarHeight = Assets.enemyRedHealthbarBG.getHeight();
		final float healthBarWidth = Assets.enemyRedHealthbarBG.getWidth();
		// getting the scale ratio
		final double ratio = healthBarWidth / healthComp.maxHealth;
		Sprite spriteBg = Assets.enemyRedHealthbarBG;
		Sprite sprite = Assets.enemyGreenHealthbarBG;
		// todo center hp bar
		sprite.setPosition(pos.position.x, pos.position.y);
		spriteBg.setPosition(pos.position.x, pos.position.y);
		if(healthComp.health > 0)
			sprite.setSize((float) (ratio * healthComp.health), healthBarHeight);
		// 100 %
		if (healthComp.health <= healthComp.maxHealth)
			sprite.setColor(0, 0.75f, 0, 1f);
		// 75 %
		if (healthComp.health <= 0.75 * healthComp.maxHealth)
			sprite.setColor(Color.YELLOW);
		// 50%
		if (healthComp.health <= 0.50 * healthComp.maxHealth)
			sprite.setColor(Color.ORANGE);
		// 25%
		if (healthComp.health <= 0.25 * healthComp.maxHealth)
			sprite.setColor(Color.BROWN);
		// if enemy isn't hurt don't draw health.
		if (healthComp.health != healthComp.maxHealth) {
			_batch.begin();
			spriteBg.draw(_batch);
			sprite.draw(_batch);
			_batch.end();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
const stubComponent = require("./stubComponent");
const mockComponent = require("./mockComponents");

const _ = require('lodash');

module.exports = function(mocks, rewiredModule){
  let mockComponents = [];
  let stubs          = {};
  _.forEach(mocks, (mock)=>{
    let mc   = mockComponent(mock.fn, mock.title);
    mc.title = mock.title;
    mockComponents.push(mc);
    stubs[mock.title] = mc.mock;
  });

  stubComponent(rewiredModule, stubs);

  return mockComponents;
};


text:
using System;
using System.Security;
using System.Runtime.InteropServices;
#if SYSTEM_XAML
using MS.Internal.Xaml;
#else
using MS.Utility;
#endif

namespace MS.Win32
{
    //
    // ETW Tracing native methods
    //

    ///<SecurityNote>
    /// Critical as this code performs an elevation.
    ///</SecurityNote>
    [SecurityCritical(SecurityCriticalScope.Everything)]
    [SuppressUnmanagedCodeSecurity]
    internal static unsafe class ManifestEtw
    {
        //
        // ETW Methods
        //
        //
        // Callback
        //
        ///<SecurityNote>
        /// Critical - Accepts untrusted pointer argument
        ///</SecurityNote>
        [SecurityCritical]
        internal unsafe delegate void EtwEnableCallback(
            [In] ref Guid sourceId,
            [In] int isEnabled,
            [In] byte level,
            [In] long matchAnyKeywords,
            [In] long matchAllKeywords,
            [In] EVENT_FILTER_DESCRIPTOR* filterData,
            [In] void* callbackContext
            );

        //
        // Registration APIs
        //
        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll", ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
        internal static extern unsafe uint EventRegister(
                    [In] ref Guid providerId,
                    [In]EtwEnableCallback enableCallback,
                    [In]void* callbackContext,
                    [In][Out]ref ulong registrationHandle
                    );

        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll", ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
        internal static extern uint EventUnregister([In] ulong registrationHandle);

        //
        // Writing (Publishing/Logging) APIs
        //
        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll", ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
        internal static extern unsafe uint EventWrite(
                [In] ulong registrationHandle,
                [In] ref EventDescriptor eventDescriptor,
                [In] uint userDataCount,
                [In] EventData* userData
                );

        [StructLayout(LayoutKind.Sequential)]
        unsafe internal struct EVENT_FILTER_DESCRIPTOR
        {
            public long Ptr;
            public int Size;
            public int Type;
        };

        [StructLayout(LayoutKind.Explicit, Size = 16)]
        internal struct EventDescriptor
        {
            [FieldOffset(0)]
            internal ushort Id;
            [FieldOffset(2)]
            internal byte Version;
            [FieldOffset(3)]
            internal byte Channel;
            [FieldOffset(4)]
            internal byte Level;
            [FieldOffset(5)]
            internal byte Opcode;
            [FieldOffset(6)]
            internal ushort Task;
            [FieldOffset(8)]
            internal long Keywords;
        }
    }

    [SuppressUnmanagedCodeSecurity]
    internal static unsafe class ClassicEtw
    {
        #region RegisterTraceGuidsW()
        // Support structs for RegisterTraceGuidsW
        [StructLayout(LayoutKind.Sequential)]
        internal struct TRACE_GUID_REGISTRATION
        {
            ///<SecurityNote>
            /// Critical:  Pointer field
            ///</SecurityNote>
            [SecurityCritical]
            internal unsafe Guid* Guid;

            ///<SecurityNote>
            /// Critical:  Pointer field
            ///</SecurityNote>
            [SecurityCritical]
            internal unsafe void* RegHandle;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct WNODE_HEADER
        {
            public UInt32 BufferSize;
            public UInt32 ProviderId;
            public UInt64 HistoricalContext;
            public UInt64 TimeStamp;
            public Guid Guid;
            public UInt32 ClientContext;
            public UInt32 Flags;
        };

        internal enum WMIDPREQUESTCODE
        {
            GetAllData = 0,
            GetSingleInstance = 1,
            SetSingleInstance = 2,
            SetSingleItem = 3,
            EnableEvents = 4,
            DisableEvents = 5,
            EnableCollection = 6,
            DisableCollection = 7,
            RegInfo = 8,
            ExecuteMethod = 9,
        };

         ///<SecurityNote>
        /// Critical:  Delegate that takes an unsafe pointer argument
        ///</SecurityNote>
        [SecurityCritical]
        internal unsafe delegate uint ControlCallback(WMIDPREQUESTCODE requestCode, IntPtr requestContext, IntPtr reserved, WNODE_HEADER* data);

        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll", CharSet = CharSet.Unicode)]
        internal static extern uint RegisterTraceGuidsW([In] ControlCallback cbFunc, [In] IntPtr context, [In] ref Guid providerGuid, [In] int taskGuidCount, [In, Out] ref TRACE_GUID_REGISTRATION taskGuids, [In] string mofImagePath, [In] string mofResourceName, out ulong regHandle);
        #endregion // RegisterTraceGuidsW

        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll")]
        internal static extern uint UnregisterTraceGuids(ulong regHandle);

        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll")]
        internal static extern int GetTraceEnableFlags(ulong traceHandle);

        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll")]
        internal static extern byte GetTraceEnableLevel(ulong traceHandle);

        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll")]
        internal static extern long GetTraceLoggerHandle(WNODE_HEADER* data);

        #region TraceEvent()
        // Structures for TraceEvent API.

        // Constants for flags field.
        internal const int WNODE_FLAG_TRACED_GUID = 0x00020000;
        internal const int WNODE_FLAG_USE_MOF_PTR = 0x00100000;

        // Size is 48 = 0x30 bytes;
        [StructLayout(LayoutKind.Sequential)]
        internal struct EVENT_TRACE_HEADER
        {
            public ushort Size;
            public ushort FieldTypeFlags;   // holds our MarkerFlags too
            public byte Type;               // This is now called opcode.
            public byte Level;
            public ushort Version;
            public int ThreadId;
            public int ProcessId;
            public long TimeStamp;          // Offset 0x10
            public Guid Guid;               // Offset 0x18
            public uint ClientContext;      // Offset 0x28
            public uint Flags;              // Offset 0x2C
        }

        internal const int MAX_MOF_FIELDS = 16;
        [StructLayout(LayoutKind.Explicit, Size = 48 + 16 * MAX_MOF_FIELDS)]
        internal struct EVENT_HEADER
        {
            [FieldOffset(0)]
            public EVENT_TRACE_HEADER Header;
            [FieldOffset(48)]
            public EventData Data;         // Actually variable sized;
        }

        ///<SecurityNote>
        /// Critical as this code performs an elevation.
        ///</SecurityNote>
        [SecurityCritical]
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Advapi32.dll")]
        internal static extern unsafe uint TraceEvent(ulong traceHandle, EVENT_HEADER* header);
        #endregion // TraceEvent()
    }
}

#endif //!SILVERLIGHTXAML


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>in.katty</groupId>
	<artifactId>helloworldbenchmark</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>helloworldbenchmark Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>helloworldbenchmark</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<path>/</path>
					<charset>UTF-8</charset>
					<uriEncoding>UTF-8</uriEncoding>
					<port>8080</port>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
for fileExist in fileList tiempos newTiempos nueva
        do
        if [ -f $fileExist ]; then
                rm $fileExist
        fi
        done

# listamos los ficheros con un hand en su nombre
ls -lash *.txt | awk '{print $10}' | grep "_Hand" >> fileList
outcome=0

# listamos los ficheros que nos interesan
for i in $(cat fileList)
do
# i=20140403_1331_HandoverTest.txt
        rm tiempos newTiempos
        ((outcome++))
 #poner titulo
 #echo $i >> tiempos

 #obtenemos solo la columnas de identificacion del mensaje y el tiempo. Eliminamos las lineas en blanco
awk '{print $5, $7}' "$i" | awk -F '=' '{print $2, $3}' | awk -F 'time' '{print $1, $2}' | awk 'NF' >> tiempos

 #cambiamos el separador decimal de puntos a comas
 cat tiempos | sed -e 's/\./,/g' > newTiempos$outcome.tp

count=1
lost=0
FILE=newTiempos$outcome.tp
OUTFILE=outcome$outcome.xls
VAR_OLD=0

while read line;
        do
                #echo "$line"
                tempVar=$(echo $line | awk '{print $1}')
                timesaved=$(echo $line | awk '{print $2}')

                echo $tempVar $timesaved $count

                if [ $count = $tempVar ]; then
                        #echo "iguales"
                        echo $tempVar $timesaved >> $OUTFILE
                else
                        echo $count "n/a" >> $OUTFILE

                        while [ $count -lt $tempVar ]
                        do
                                ((count++))
                                ((lost++))
                                echo $count "n/a" >> $OUTFILE
                                #((count++))
                        done
                        #echo "distintos"

                #Buscamos valores duplicados en los mensajes trasmitidos
                if [ $tempVar = $VAR_OLD ]; then
                        echo "duplicated message identification"
                else
                        ((count++))
                fi
                VAR_OLD=$tempVar

        done < $FILE
done


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps JavaScript API Example</title>

    <form action="#" onsubmit="showAddress(this.address.value); return false">

        <input type="text" size="50" id="addressInput" name="address" value="London, UK" />
        <input type="submit" value="Go!" />

    </form>


text:
package com.amazonaws.services.groundstation.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListSatellitesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * Next token that can be supplied in the next call to get the next page of satellites.
     *

     */
    private String nextToken;
    /**
     *

     * List of satellites.
     *

     */
    private java.util.List<SatelliteListItem> satellites;

    /**
     *

     * Next token that can be supplied in the next call to get the next page of satellites.
     *

     *
     * @param nextToken
     *        Next token that can be supplied in the next call to get the next page of satellites.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * Next token that can be supplied in the next call to get the next page of satellites.
     *

     *
     * @return Next token that can be supplied in the next call to get the next page of satellites.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * Next token that can be supplied in the next call to get the next page of satellites.
     *

     *
     * @param nextToken
     *        Next token that can be supplied in the next call to get the next page of satellites.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListSatellitesResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * List of satellites.
     *

     *
     * @return List of satellites.
     */

    public java.util.List<SatelliteListItem> getSatellites() {
        return satellites;
    }

    /**
     *

     * List of satellites.
     *

     *
     * @param satellites
     *        List of satellites.
     */

    public void setSatellites(java.util.Collection<SatelliteListItem> satellites) {
        if (satellites == null) {
            this.satellites = null;
            return;
        }

        this.satellites = new java.util.ArrayList<SatelliteListItem>(satellites);
    }

    /**
     *

     * List of satellites.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setSatellites(java.util.Collection)} or {@link #withSatellites(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param satellites
     *        List of satellites.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListSatellitesResult withSatellites(SatelliteListItem... satellites) {
        if (this.satellites == null) {
            setSatellites(new java.util.ArrayList<SatelliteListItem>(satellites.length));
        }
        for (SatelliteListItem ele : satellites) {
            this.satellites.add(ele);
        }
        return this;
    }

    /**
     *

     * List of satellites.
     *

     *
     * @param satellites
     *        List of satellites.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListSatellitesResult withSatellites(java.util.Collection<SatelliteListItem> satellites) {
        setSatellites(satellites);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken()).append(",");
        if (getSatellites() != null)
            sb.append("Satellites: ").append(getSatellites());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListSatellitesResult == false)
            return false;
        ListSatellitesResult other = (ListSatellitesResult) obj;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getSatellites() == null ^ this.getSatellites() == null)
            return false;
        if (other.getSatellites() != null && other.getSatellites().equals(this.getSatellites()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getSatellites() == null) ? 0 : getSatellites().hashCode());
        return hashCode;
    }

    @Override
    public ListSatellitesResult clone() {
        try {
            return (ListSatellitesResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package org.opensmartgridplatform.adapter.domain.shared;

import org.opensmartgridplatform.domain.core.valueobjects.DeviceStatusMapped;
import org.opensmartgridplatform.shared.exceptionhandling.OsgpException;
import org.opensmartgridplatform.shared.infra.jms.ResponseMessageResultType;

public class GetStatusResponse {
    ResponseMessageResultType result;
    OsgpException osgpException;
    DeviceStatusMapped deviceStatusMapped;

    public GetStatusResponse() {
        // Empty constructor.
    }

    public ResponseMessageResultType getResult() {
        return this.result;
    }

    public void setResult(final ResponseMessageResultType result) {
        this.result = result;
    }

    public OsgpException getOsgpException() {
        return this.osgpException;
    }

    public void setOsgpException(final OsgpException osgpException) {
        this.osgpException = osgpException;
    }

    public DeviceStatusMapped getDeviceStatusMapped() {
        return this.deviceStatusMapped;
    }

    public void setDeviceStatusMapped(final DeviceStatusMapped deviceStatusMapped) {
        this.deviceStatusMapped = deviceStatusMapped;
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/video_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <SurfaceView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:fitsSystemWindows="true" />

    <LinearLayout
        android:id="@+id/video_loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="visible"
        android:gravity="center_vertical" >

        <ProgressBar
            android:id="@+id/video_loading_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/video_loading_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="7.0dip"
            android:text="@string/video_layout_loading"
            android:textColor="@android:color/white"
            android:textSize="20.0sp" />
    </LinearLayout>

</RelativeLayout>


text:
package controller

import skinny._
import skinny.controller.AssetsController

object Controllers {

  def mount(ctx: ServletContext): Unit = {

    ErrorController.mount(ctx)

    fileUpload.mount(ctx)
    fileDownload.mount(ctx)

    root.mount(ctx)
    companies.mount(ctx)
    customLayout.mount(ctx)
    mail.mount(ctx)
    mustache.mount(ctx)
    programmers.mount(ctx)
    thymeleaf.mount(ctx)
    freemarker.mount(ctx)
    velocity.mount(ctx)
    sampleApi.mount(ctx)
    sampleTxApi.mount(ctx)
    scaldi.mount(ctx)
    dashboard.mount(ctx)

    SkillsController.mount(ctx)
    CommentsController.mount(ctx)
    SnakeCaseKeyExamplesController.mount(ctx)

    AngularXHRProgrammersController.mount(ctx)
    angularApp.mount(ctx)

    facebook.mount(ctx)
    github.mount(ctx)
    google.mount(ctx)
    twitter.mount(ctx)
    typetalk.mount(ctx)
    dropbox.mount(ctx)
    backlog.mount(ctx)
    backlogJp.mount(ctx)

    AssetsController.mount(ctx)
  }

  object companies extends CompaniesController {
  }

  object root extends RootController with Routes {
    val indexUrl = get("/")(index).as('index)
    val sessionRenewUrl = get("/session/renew")(renewSessionAttributes).as('sessionRenew)
    val errorUrl = get("/error")(errorExample).as('error)
    val reactUrl = get("/react")(reactExample).as('react)
    val nestedI18nUrl = get("/nested-i18n")(nestedI18nExample).as('nestedI18n)
    val invalidateUrl = get("/invalidate")(invalidateExample).as('invalidate)
  }

  object programmers extends ProgrammersController with Routes {
    val joinCompanyUrl = post("/programmers/:programmerId/company/:companyId")(joinCompany).as('joinCompany)
    val leaveCompanyUrl = delete("/programmers/:programmerId/company")(leaveCompany).as('leaveCompany)
    val addSkillUrl = post("/programmers/:programmerId/skills/:skillId")(addSkill).as('addSkill)
    val deleteSkillUrl = delete("/programmers/:programmerId/skills/:skillId")(deleteSkill).as('deleteSkill)
  }

  object customLayout extends CustomLayoutController with Routes {
    val indexUrl = get("/custom-layout/?".r)(index).as('index)
    val defaultUrl = get("/custom-layout/default")(default).as('default)
    val barUrl = get("/custom-layout/bar")(bar).as('bar)
  }

  object mail extends MailController with Routes {
    val indexUrl = get("/mail/")(index).as('index)
    val sspUrl = get("/mail/ssp")(ssp).as('ssp)
  }

  object mustache extends MustacheController with Routes {
    val indexUrl = get("/mustache/?".r)(index).as('index)
  }

  object thymeleaf extends ThymeleafController with Routes {
    val indexUrl = get("/thymeleaf/?".r)(index).as('index)
  }
  object freemarker extends FreeMarkerController with Routes {
    val indexUrl = get("/freemarker/?".r)(index).as('index)
  }
  object velocity extends VelocityController with Routes {
    val indexUrl = get("/velocity/?".r)(index).as('index)
  }

  object sampleApi extends SampleApiController with Routes {
    val createCompanyUrl = post("/api/companies")(createCompany).as('createCompany)
    val companiesUrl = get("/api/companies")(companiesJson).as('companies)
  }
  object sampleTxApi extends SampleTxApiController with Routes {
    get("/api/error")(index).as('index)
  }

  object fileUpload extends FileUploadController with Routes {
    val formUrl = get("/fileupload")(form).as('form)
    val submitUrl = post("/fileupload/submit")(submit).as('submit)
  }
  object fileDownload extends FileDownloadController with Routes {
    val indexUrl = get("/filedownload")(index).as('index)
    val smallUrl = get("/filedownload/small")(small).as('small)
    val nullUrl = get("/filedownload/null")(nullValue).as('null)
    val errorUrl = get("/filedownload/error")(error).as('error)
  }

  object scaldi extends ScaldiController with Routes {
    val indexUrl = get("/scaldi/")(index).as('index)
  }

  object dashboard extends DashboardController with Routes {
    val indexUrl = get("/dashboard/")(index).as('index)
  }

  object angularApp extends AngularAppController with Routes {
    val indexUrl = get("/angular/app")(index).as('index)
    val programmersUrl = get("/angular/programmers/")(programmers).as('programmers)
  }

  object facebook extends FacebookController with Routes {
    val loginUrl = get("/facebook")(loginRedirect).as('login)
    val callbackUrl = get("/facebook/callback")(callback).as('callback)
    val okUrl = get("/facebook/ok")(ok).as('ok)
  }

  object github extends GitHubController with Routes {
    val loginUrl = get("/github")(loginRedirect).as('login)
    val callbackUrl = get("/github/callback")(callback).as('callback)
    val okUrl = get("/github/ok")(ok).as('ok)
  }

  object google extends GoogleController with Routes {
    val loginUrl = get("/google")(loginRedirect).as('login)
    val callbackUrl = get("/google/callback")(callback).as('callback)
    val okUrl = get("/google/ok")(ok).as('ok)
  }

  object twitter extends TwitterController with Routes {
    val loginUrl = get("/twitter")(loginRedirect).as('login)
    val callbackUrl = get("/twitter/callback")(callback).as('callback)
    val okUrl = get("/twitter/ok")(ok).as('ok)
  }

  object typetalk extends TypetalkController with Routes {
    val loginUrl = get("/typetalk")(loginRedirect).as('login)
    val callbackUrl = get("/typetalk/callback")(callback).as('callback)
    val okUrl = get("/typetalk/ok")(ok).as('ok)
  }

  object dropbox extends DropboxController with Routes {
    val loginUrl = get("/dropbox")(loginRedirect).as('login)
    val callbackUrl = get("/dropbox/callback")(callback).as('callback)
    val okUrl = get("/dropbox/ok")(ok).as('ok)
  }

  object backlog extends BacklogController with Routes {
    val loginUrl = get("/backlog")(loginRedirect).as('login)
    val callbackUrl = get("/backlog/callback")(callback).as('callback)
    val okUrl = get("/backlog/ok")(ok).as('ok)
  }
  object backlogJp extends BacklogJPController with Routes {
    val loginUrl = get("/backlogjp")(loginRedirect).as('login)
    val callbackUrl = get("/backlogjp/callback")(callback).as('callback)
    val okUrl = get("/backlogjp/ok")(ok).as('ok)
  }

}


text:
module QME
  class QualityReport

    # Removes the cached results for the patient with the supplied id and
    # recalculates as necessary
    def self.update_patient_results(id)
      # TODO: need to wait for any outstanding calculations to complete and then prevent
      # any new ones from starting until we are done.

      # drop any cached measure result calculations for the modified patient
      QME::PatientCache.where('value.medical_record_id' => id).destroy()

      # get a list of cached measure results for a single patient
      sample_patient =  QME::PatientCache.where({}).first
      if sample_patient
        cached_results =  QME::PatientCache.where({'value.patient_id' => sample_patient['value']['patient_id']})

        # for each cached result (a combination of measure_id, sub_id, effective_date and test_id)
        cached_results.each do |measure|
          # recalculate patient_cache value for modified patient
          value = measure['value']
          measure_model = QME::QualityMeasure.new(value['measure_id'], value['sub_id'])
          oid_dictionary = OidHelper.generate_oid_dictionary(measure_model)
          map = QME::MapReduce::Executor.new(value['measure_id'], value['sub_id'],
            'effective_date' => value['effective_date'], 'test_id' => value['test_id'],
            'oid_dictionary' => oid_dictionary)
          map.map_record_into_measure_groups(id)
        end
      end

      # remove the query totals so they will be recalculated using the new results for
      # the modified patient

      QME::QualityReport.where({}).each do |qr|
        measure_model = QME::QualityMeasure.new(qr['measure_id'], qr['sub_id'])
        oid_dictionary = OidHelper.generate_oid_dictionary(measure_model)
        qr.calculate({"recalculate"=>true, "oid_dictionary" =>oid_dc},true)
      end
    end
  end
end


text:
layout: post
title:  "188FourQuadrantManagement Support Page"
date:   2017-10-22
desc: "188FourQuadrantManagement is comming"
keywords: "188,time,management,task,support"
categories: [HTML]
tags: [TimeManagement,188]
icon: icon-html
---

# Descrption

Four quadrant time management

A person's life is very limited time, how to make these limited time to play a more effective role, it involves a time of planning and management issues. Time
"four quadrant" method is a time management tool. He divided the work according to two important levels of importance and urgency, basically divided into four "quadrants".

Any Question with the app you can email me with support.

# Support

email: ziyiyang1993@gmail.com


text:
ACCEPTED

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

#### Published in
in Braun & Takamatsu, Schlechtendalia 4: 31 (2000)

#### Original name
Erysiphe xanthii Castagne, 1845

### Remarks
null


text:
// Authors: Juyong Zhang, Bailin Deng, Zishun Liu, Giuseppe Patane, Sofien Bouaziz, Kai Hormann, and Ligang Liu, https://github.com/bldeng/LBC
// Updated by: Dmitry Anisimov danston@ymail.com.
// Copyright Juyong Zhang, Bailin Deng, Zishun Liu, Giuseppe Patane, Sofien Bouaziz, Kai Hormann, Ligang Liu, and Dmitry Anisimov (c) 2016-2017.

// README:
/*

    Local barycentric coordinates.

    This class depends on:
    1. BarycentricCoordinatesR2.hpp
    2. SegmentCoordinatesR2.hpp
    3. VertexExpressionsR2.hpp
    4. VertexR2.hpp
    5. TriangleCoordinatesR2.hpp

    This code also depends on the external triangulation library:
    Triangle, https://www.cs.cmu.edu/~quake/triangle.html
    I use the wrapper TriangulatorR2.hpp to include the library in the code.

    and it depends on the external linear algebra library: Eigen http://eigen.tuxfamily.org!

    The solver is provided by the authors: see extra/libs/lbcsolver.

*/

#ifndef GBC_LOCALR2_HPP
#define GBC_LOCALR2_HPP

// STL includes.
#include <vector>
#include <cassert>
#include <iostream>
#include <cmath>

// Local includes.
#include "../extra/VertexR2.hpp"
#include "../extra/BarycentricCoordinatesR2.hpp"
#include "../extra/TriangleCoordinatesR2.hpp"

// Libs.
#include "../extra/libs/eigen/Eigen/Core"
#include "../extra/libs/eigen/Eigen/Dense"

#include "../extra/TriangulatorR2.hpp"

#include "../extra/libs/lbcsolver/DataTypes.hpp"
#include "../extra/libs/lbcsolver/LbcSolver.hpp"

namespace gbc {

    // Local barycentric coordinates in R2.
    // May give slightly negative values, but this is numerical instability of the solver.
    class LocalR2 : public BarycentricCoordinatesR2 {

    public:
        // Constructor.
        LocalR2(const std::vector<VertexR2> &v, const double tol = 1.0e-10)
        : super(v, tol), _edgeLength(-1.0),
        _isPolyLoaded(false),
        _isMeshGiven(false),
        _isMeshCreated(false),
        _areCoordinatesComputed(false),
        _isEdgeLengthSet(false),
        _verbose(false) {

            setPolygon();
        }

        // Return name of the coordinate function.
        inline std::string name() const {
            return "LocalR2";
        }

        // Function that computes coordinates bb at all points p.
        // Here the set of points p must exclude the polygon's vertices _v.
        void compute(const std::vector<VertexR2> &p, std::vector<std::vector<double> > &bb) {

            // Create internal triangle mesh.
            createMesh(p);

            // Compute coordinates.
            lbc_solver();

            // Wrap computed coordinates in the vector bb.
            wrapCoordinates(bb);
        }

        // Compute coordinates bb at the vertices of the internal mesh with the given edgeLength
        // of the average triangle in this mesh. The number of returned coordinates is the number of the polygon's vertices
        // + the number of the points p generated by the TriangulatorR2.hpp. All the coordinates are ordered as
        // _v[0].b(), ..., _v[n-1].b(), p[0].b(), ..., p[N-1].b(), where n = _v.size() and N = p.size().
        void compute(const double edgeLength, std::vector<std::vector<double> > &bb) {

            // Create internal triangle mesh.
            createMesh(edgeLength);

            // Compute coordinates.
            lbc_solver();

            // Wrap computed coordinates in the vector bb.
            wrapCoordinates(bb);
        }

        // Compute coordinates at all points p in the vector using the internal storage from the VertexR2 class.
        // Note that here the function returns a slightly different set of points p from the given one.
        // Here the set of points p must exclude the polygon's vertices _v.
        void compute(std::vector<VertexR2> &p) {

            // Create internal triangle mesh.
            createMesh(p);

            // Compute coordinates.
            lbc_solver();

            // Wrap vertices with coordinates.
            wrapVertices(p);
        }

        // Implementation of the virtual function to compute all coordinates.
        // Here the set of points p must exclude the polygon's vertices _v
        // apart from the case when the given mesh is used.
        inline void bc(std::vector<VertexR2> &p) {

            // Create internal triangle mesh.
            if (!_isMeshGiven) createMesh(p);

            // Compute coordinates.
            lbc_solver();

            // Wrap vertices with coordinates.
            wrapVertices(p);
        }

        // Evaluate coordinates b at any point p.
        void evaluate(const VertexR2 &p, std::vector<double> &b) const {

            assert(_isPolyLoaded);
            assert(_isMeshCreated);
            assert(_areCoordinatesComputed);

            std::vector<double> lambda;

            const size_t numF = _meshFaces.cols();
            for (size_t i = 0; i < numF; ++i) {

                const int i0 = _meshFaces(0, i);
                const int i1 = _meshFaces(1, i);
                const int i2 = _meshFaces(2, i);

                const VertexR2 v0 = VertexR2(_meshVertices(0, i0), _meshVertices(1, i0));
                const VertexR2 v1 = VertexR2(_meshVertices(0, i1), _meshVertices(1, i1));
                const VertexR2 v2 = VertexR2(_meshVertices(0, i2), _meshVertices(1, i2));

                TriangleCoordinatesR2 tc(v0, v1, v2);
                tc.compute(p, lambda);

                assert(lambda.size() == 3);

                if (lambda[0] >= 0.0 &&
                    lambda[1] >= 0.0 &&
                    lambda[2] >= 0.0) {

                    b.clear();

                    const size_t n = _v.size();
                    b.resize(n, 0.0);

                    assert(_meshVertices.cols() == _b.rows());
                    assert(_v.size()  ==  (size_t) _b.cols());

                    for (size_t j = 0; j < n; ++j)
                        b[j] = lambda[0] * _b(i0, j) + lambda[1] * _b(i1, j) + lambda[2] * _b(i2, j);

                    return;
                }
            }
            assert(false);
        }

        // Evalaute coordinates at p using the internal storage from the VertexR2 class.
        inline void evaluate(VertexR2 &p) const {
            evaluate(p, p.b());
        }

        // Evaluate coordinates bb at all points p in the vector.
        void evaluate(const std::vector<VertexR2> &p, std::vector<std::vector<double> > &bb) const {

            const size_t numP = p.size();

            bb.resize(numP);
            for (size_t i = 0; i < numP; ++i) evaluate(p[i], bb[i]);
        }

        // Evaluate coordinates at all points p in the vector using
        // the internal storage from the VertexR2 class.
        void evaluate(std::vector<VertexR2> &p) const {

            const size_t numP = p.size();
            for (size_t i = 0; i < numP; ++i) evaluate(p[i], p[i].b());
        }

        // Set mesh if any.
        void setMesh(const std::vector<VertexR2> &tp, const std::vector<Face> &tf) {

            setTriangulation(tp, tf);

            _isMeshGiven = true;
            _isMeshCreated = false;
        }

        // Set the average edge length for the boundary refinement.
        inline void setEdgeLength(const double newEdgeLength) {

            assert(newEdgeLength > 0.0);

            _edgeLength = newEdgeLength;
            _isEdgeLengthSet = true;
        }

        // Indicate if we want to output the solver progress or not.
        // The default is false.
        inline void showOutput(const bool verbose) {
            _verbose = verbose;
        }

        // Clear all internal data structures.
        void clear() {

            _poly.resize(3, 0);
            _meshFaces.resize(0, 0);
            _meshVertices.resize(3, 0);
            _b.resize(0, 0);

            _isPolyLoaded = false;
            _isMeshGiven = false;
            _isMeshCreated = false;
            _areCoordinatesComputed = false;
            _isEdgeLengthSet = false;
        }

    private:
        // Some typedefs.
        typedef BarycentricCoordinatesR2 super;

        // Mesh.
        Eigen::MatrixXi  _meshFaces;
        Eigen::Matrix3Xd _meshVertices;

        // Polygon.
        Eigen::Matrix3Xd _poly;

        // Coordinates.
        Eigen::MatrixXd  _b;

        // Edge length of the average triangle in the internal triangulation.
        double _edgeLength;

        // Flags.
        bool _isPolyLoaded;
        bool _isMeshGiven;
        bool _isMeshCreated;
        bool _areCoordinatesComputed;
        bool _isEdgeLengthSet;
        bool _verbose;

        // Return the obtained coordinates.
        void wrapCoordinates(std::vector<std::vector<double> > &bb) const {

            const long rows = _b.rows();
            const long cols = _b.cols();

            bb.clear();
            bb.resize(rows);

            assert(_v.size() == (size_t) cols);
            for (long i = 0; i < rows; ++i) {

                bb[i].resize((size_t) cols);
                for (long j = 0; j < cols; ++j) bb[i][j] = _b(i, j);
            }
        }

        // Return new set of vertices with the corresponding coordinates
        // using the internal coordinate storage from the class VertexR2.
        void wrapVertices(std::vector<VertexR2> &p) const {

            const size_t n = _v.size();
            const size_t N = _meshVertices.cols();

            p.clear();
            p.resize(N);

            assert(N == (size_t) _b.rows());
            assert(_v.size() == (size_t) _b.cols());

            for (size_t i = 0; i < N; ++i) {

                p[i].x() = _meshVertices(0, i);
                p[i].y() = _meshVertices(1, i);

                p[i].b().resize(n, 0.0);
                for (size_t j = 0; j < n; ++j) p[i].b()[j] = _b(i, j);
            }
        }

        // Set vertices of the given polygon.
        void setPolygon() {

            const size_t numV = _v.size();
            _poly.resize(3, numV);

            for (size_t i = 0; i < numV; ++i) {

                _poly(0, i) = _v[i].x();
                _poly(1, i) = _v[i].y();
                _poly(2, i) = 0.0;
            }

            _isPolyLoaded = true;
        }

        // Given a set of points p, create the internal triangle mesh.
        // For this code the prefered edge length for the boundary
        // refinement is also necessary!
        void createMesh(const std::vector<VertexR2> &p) {

            assert(_isEdgeLengthSet);
            assert(_edgeLength > 0.0);

            std::vector<VertexR2> poly;
            refinePolygon(poly);

            assert(!p.empty());

            std::vector<VertexR2> tp;
            std::vector<Face> tf;

            TriangulatorR2 tri(poly);

            tri.setPlanarGraph(true);

            tri.allowBoundaryRefinement(false);
            tri.allowEdgeRefinement(false);

            tri.setPoints(p);
            tri.generate(tp, tf);

            setTriangulation(tp, tf);

            _isMeshGiven = false;
            _isMeshCreated = true;
        }

        // Given the edgeLength of the average triangle, create the internal triangle mesh.
        void createMesh(const double edgeLength) {

            _edgeLength = edgeLength;
            _isEdgeLengthSet = true;

            assert(_edgeLength > 0.0);

            std::vector<VertexR2> poly;
            refinePolygon(poly);

            std::vector<VertexR2> tp;
            std::vector<Face> tf;

            TriangulatorR2 tri(poly, _edgeLength, true);
            tri.setPlanarGraph(true);

            tri.generate(tp, tf);

            setTriangulation(tp, tf);

            _isMeshGiven = false;
            _isMeshCreated = true;
        }

        // Refine boundary of the given polygon _v with respect to the given _edgeLength.
        void refinePolygon(std::vector<VertexR2> &poly) const {

            assert(poly.empty());
            const size_t numV = _v.size();

            for (size_t i = 0; i < numV; ++i) {
                poly.push_back(_v[i]);

                const size_t ip = (i + 1) % numV;
                const size_t numS = ceil((_v[ip] - _v[i]).length() / _edgeLength);

                for (size_t j = 1; j < numS; ++j) {

                    VertexR2 vert = _v[i] + (double(j) / double(numS)) * (_v[ip] - _v[i]);
                    poly.push_back(vert);
                }
            }
        }

        // Set vertices and faces of the given triangulation.
        void setTriangulation(const std::vector<VertexR2> &tp, const std::vector<Face> &tf) {

            const size_t numP = tp.size();
            const size_t numF = tf.size();

            _meshVertices.resize(3, numP);

            for (size_t i = 0; i < numP; ++i) {

                _meshVertices(0, i) = tp[i].x();
                _meshVertices(1, i) = tp[i].y();
                _meshVertices(2, i) = 0.0;
            }

            _meshFaces.resize(3, numF);

            for (size_t i = 0; i < numF; ++i) {

                _meshFaces(0, i) = tf[i].v[0];
                _meshFaces(1, i) = tf[i].v[1];
                _meshFaces(2, i) = tf[i].v[2];
            }
        }

        // Compute coordinates. This implementation is based on the following paper:
        // J. Zhang, B. Deng, Z. Liu, G. Patane, S. Bouaziz, K. Hormann, and L. Liu. Local barycentric coordinates.
        // ACM Transactions on Graphics, 33(6):188:1-12, 2014.
        void lbc_solver(const int weighting_scheme = 2, // 0 - Constant, 1 - Linear, 2 - Quadratic, 3 - Sqrt
                        const int max_iter = 10000, // default is 10000
                        const double relaxation_alpha = 1.65, // default is 1.65
                        const double penalty_weight = 10.0, // default is 10.0
                        const double primal_residual_tolerance = 0.0000001, // default is 0.0000001
                        const double dual_residual_tolerance = 0.000001) { // default is 0.000001

            assert(_isPolyLoaded);
            assert(_isMeshCreated || _isMeshGiven);

            if (_verbose) std::cout << "Setting up input data..." << std::endl;

            LBC::DenseMatrix sample_points = _meshVertices.block(0, 0, 2, _meshVertices.cols());
            LBC::DenseIndexMatrix &cell_vertices = _meshFaces;

            // Control_point_idx.
            LBC::IndexVector control_point_idx(_poly.cols());
            for (int i = 0; i < _poly.cols(); ++i) {

                Eigen::Vector2d ctrl_pt = _poly.block(0, i, 2, 1);
                LBC::DenseMatrix candidate_points = sample_points;

                int min_idx = -1;
                (candidate_points.colwise() - ctrl_pt).colwise().norm().minCoeff(&min_idx);
                control_point_idx[i] = min_idx;
            }

            // Boundary_facet_info.
            std::vector<LBC::DataSetup::CageBoundaryFacetInfo> boundary_facet_info;
            int n_control_pt = (int) _poly.cols();
            for (int i = 0; i < n_control_pt; ++i) {

                int next_i = (i + 1) % n_control_pt;

                LBC::IndexVector facet_vertices(2);
                facet_vertices(0) = i;
                facet_vertices(1) = next_i;
                int n_segments = std::ceil((_poly.col(i) - _poly.col(next_i)).norm() / _edgeLength);

                LBC::IndexVector boundary_points(n_segments - 1);
                for (int k = 1; k < n_segments; ++k) {

                    Eigen::Vector3d pt_3d = _poly.col(i) + k * (_poly.col(next_i) - _poly.col(i)) / n_segments;
                    Eigen::Vector2d pt = pt_3d.head(2);

                    LBC::DenseMatrix candidate_points = sample_points;

                    int min_idx = -1;
                    (candidate_points.colwise() - pt).colwise().norm().minCoeff(&min_idx);
                    boundary_points[k - 1] = min_idx;
                }

                LBC::DataSetup::CageBoundaryFacetInfo edge(facet_vertices, boundary_points);
                boundary_facet_info.push_back(edge);
            }

            LBC::DataSetup::WeightingScheme scheme = static_cast<LBC::DataSetup::WeightingScheme>(weighting_scheme);
            LBC::DataSetup ds(sample_points, control_point_idx, cell_vertices, boundary_facet_info, scheme);

            LBC::Param param;

            param.max_iterations = max_iter;
            param.relaxation_alpha = relaxation_alpha;
            param.rel_primal_eps = primal_residual_tolerance;
            param.rel_dual_eps = dual_residual_tolerance;
            param.penalty_weight = penalty_weight;

            param.convergence_check_frequency = 10;

            if (_verbose) param.output_frequency_ratio = 10;
            else param.output_frequency_ratio = max_iter;

            param.use_timer = false;

            // Interior.
            LBC::LBCSolver solver(param, ds);
            solver.showOutput(_verbose);

            if (_verbose) std::cout << "LBC Solver started:\n" << std::endl;

            solver.solve();

            if (_verbose) std::cout << "Computation finished!\n" << std::endl;

            _b = ds.get_full_coordinate_values(solver.get_coordinates());
            _areCoordinatesComputed = true;
        }
    };

} // namespace gbc

#endif // GBC_LOCALR2_HPP


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tekle.oss.android.flipviewtransition"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="7" />

</manifest>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

//[RequireComponent(typeof(AudioSource))]
public class newScreen : MonoBehaviour {

	public GameObject Screen1;
	public GameObject Screen3;
	public GameObject Screen2;
	public GameObject smoke;

	public void secondScreen() {
		Screen1.SetActive (false);
		Screen2.SetActive (true);
	}

	public void visualize() {
//		if visualize button is clicked, hide second screen, show the third
		Screen2.SetActive (false);
		Screen3.SetActive (true);
		smoke.SetActive (true);
	}

}

//	attempt to get next audio clip to play once previous clip ends
//		public AudioClip otherClip;
//		AudioSource audioSource;
//
//		void Start()
//		{
//			audioSource = GetComponent<AudioSource>();
//		}
//
//		void Update()
//		{
//			if (audioSource.isPlaying == false)
//			{
//				audioSource.clip = otherClip;
//				audioSource.Play();
//			}
//		}

//		public AudioClip engineStartClip;
//		public AudioClip engineLoopClip;
//		void Start()
//		{
//			GetComponent<AudioSource> ().loop = true;
//			StartCoroutine(playEngineSound());
//		}
//
//		IEnumerator playEngineSound()
//		{
//			audio.clip = engineStartClip;
//			audio.Play();
//			yield return new WaitForSeconds(audio.clip.length);
//			audio.clip = engineLoopClip;
//			audio.Play();
//		}

//	attempt to get screens to change when audio clip ended
//	public AudioClip audio;
//	private AudioSource audiosource;
//
//	void Start()
//	{
//		audiosource = GetComponent<AudioSource>();
//		audiosource.clip = audio;
//		audiosource.Play();
//		StartCoroutine(WaitForSound(audio));
//	}
//
//	public IEnumerator WaitForSound(AudioClip Sound)
//	{
//		yield return new WaitUntil(() => audiosource.isPlaying == false);
//		// or yield return new WaitWhile(() => audiosource.isPlaying == true);
//		if(Screen1 != null)
//			Screen1.SetActive(false); //Do something
//	}


text:
layout: post
title:      "React and state flow"
date:       2018-07-30 17:07:27 +0000
permalink:  react_and_state_flow
---

React is tough. Having built a few apps using it, I enjoy it. But it can be tricky to get a feel for how it all fits together.

React is a library that allows you to compose complex user interface from smaller components. This makes React convenient for its reusability and customization. However, once you start passing around actual data, it becomes a real juggling act.

If you are new to React, I'd like to go over a library for managing the state of your app called Redux. Redux essentially takes all of your data and stores it in one place, passing it around as needed. However, it is critical that you understand the flow of data when using Redux in order to ensure your data is going where you need it to go.

To get started using [Redux](http://redux.js.org), let's go over some of the vocabulary you'll need to understand.

Store: holds the state of the application
Dispatcher: store method for dispatching actions
Action: payloads of data sent from application to store
Action creator: functions that create actions
Reducer: specify how the application state changes in response to an action

Using Redux, the basic flow is as follows:

- The store passes state to React components.
- React components can manipulate data
- Data from components is passed via the dispatch method into an action creator
- Action creators do the heavy lifting (think API calls, persistence)
- Action creators send newly fetched/persisted data as action payload to a reducer
- Reducers take the new data and combine them with the current store and replace the current store with the newly updated store

Okay, okay, I understand that may not make a lot of sense if you have never used it. Once you put it into action, you will start to see how the flow works.

One method I learned that helped me understand state flow using Redux was to insert a trail of console.logs into my code and then try to predict the order in which they would log before I triggered an update to state.

As you dive into React/Redux, I hope this helps you wrap your head around all the moving parts that make up this fascinating pattern.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:paddingTop="5dip"
  android:paddingBottom="5dip">

  <ImageView android:id="@+id/image_item_1" android:layout_width="wrap_content" android:layout_centerVertical="true"
  android:layout_height="wrap_content" android:src="@drawable/icon_360"/>

  <LinearLayout android:id="@+id/linearlayout_out_1" android:layout_width="wrap_content" android:layout_marginLeft="5dip" android:layout_centerVertical="true"
  android:layout_height="wrap_content" android:orientation="vertical" android:layout_toRightOf="@id/image_item_1">
    <TextView android:id="@+id/text_item_1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_centerHorizontal="true"
  android:textSize="16sp" android:textStyle="bold" android:text="360安全卫士" android:textColor="#000000"
   />
  <LinearLayout android:id="@+id/linearlayout_in_1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="5dip">
   <TextView android:id="@+id/text_item_2" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_centerHorizontal="true"
  android:textSize="12sp" android:textStyle="italic" android:text="应用 > 安全"
  />

   <TextView android:id="@+id/text_item_3" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_centerHorizontal="true"
  android:layout_marginLeft="100dip"
  android:textSize="12sp" android:textStyle="italic" android:text="2.56M"/>
  </LinearLayout>
    </LinearLayout>

  <ImageView android:id="@+id/image_item_2" android:layout_width="1dip" android:src="@drawable/tab_divider" android:layout_centerVertical="true"
  android:layout_height="wrap_content" android:layout_toRightOf="@id/linearlayout_out_1"  android:layout_marginLeft="15dip"/>

  <LinearLayout android:id="@+id/linearlayout_out_2" android:layout_width="wrap_content" android:layout_marginLeft="10dip" android:layout_centerVertical="true"
  android:layout_height="wrap_content" android:orientation="vertical" android:layout_toRightOf="@id/image_item_2">
   <ImageView android:id="@+id/image_item_3" android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>

   <TextView android:id="@+id/text_item_4" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="免费"
  android:textSize="14sp" android:textStyle="italic"
  />
  </LinearLayout>

</RelativeLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fieldiana, Bot. 21: 89 (1989)

#### Original name
Dermoloma pataguae Singer

### Remarks
null


text:
package com.markzhai.library.widget.slider.Transformers;

import android.view.View;

import com.nineoldandroids.view.ViewHelper;

public class RotateDownTransformer extends BaseTransformer {

	private static final float ROT_MOD = -15f;

	@Override
	protected void onTransform(View view, float position) {
		final float width = view.getWidth();
		final float height = view.getHeight();
		final float rotation = ROT_MOD * position * -1.25f;

		ViewHelper.setPivotX(view,width * 0.5f);
        ViewHelper.setPivotY(view,height);
        ViewHelper.setRotation(view,rotation);
	}

	@Override
	protected boolean isPagingEnabled() {
		return true;
	}

}


text:
package org.jetbrains.plugins.groovy.lang.surroundWith;

import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrTryCatchStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrCatchClause;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;

/**
 * User: Dmitry.Krasilschikov
 * Date: 22.05.2007
 */
public abstract class TrySurrounder extends GroovyManyStatementsSurrounder {
  protected TextRange getSurroundSelectionRange(GroovyPsiElement element) {
    assert element instanceof GrTryCatchStatement;
    int endOffset = element.getTextRange().getEndOffset();
    GrTryCatchStatement tryCatchStatement = (GrTryCatchStatement) element;

    GrCatchClause[] catchClauses = tryCatchStatement.getCatchClauses();
    if (catchClauses != null && catchClauses.length > 0) {
      GrParameter parameter = catchClauses[0].getParameter();
      if (parameter == null) {
        GrOpenBlock block = catchClauses[0].getBody();
        assert block != null;
        endOffset = block.getTextRange().getEndOffset();
      } else {
        endOffset = parameter.getTextRange().getStartOffset();
        parameter.getParent().getNode().removeChild(parameter.getNode());
      }
    } else {
      GrOpenBlock block = tryCatchStatement.getTryBlock();
      if (block != null) {
        GrStatement[] statements = block.getStatements();
        if (statements.length > 0) {
          endOffset = statements[0].getTextRange().getStartOffset();
        }
      }
    }

    return new TextRange(endOffset, endOffset);
  }

  public String getTemplateDescription() {
    return "try";
  }
}


text:
export class Constants {
  public static readonly INVALID_MESSAGE_STRING: string = "Invalid Command";

  public static readonly ERROR_STRING: string =
    "There was an error in your request";

  public static readonly NO_RESTAURANTS_FOUND_STRING: string =
    "No Restaurants Found";

  public static readonly APP_NAME: string = "10bis.slackbot";

  public static readonly TOTAL_KEYWORD: string = "total";

  public static readonly DATE_FORMAT: string = "DD/MM/YYYY";

  public static readonly TIME_FORMAT: string = "HH:mm:ss";

  public static readonly TIMEZONE: string = "Asia/Jerusalem";

  public static readonly RESTAURANT_BASE_URL: string =
    "https://www.10bis.co.il/Restaurants/Menu/Delivery?ResId=";

  public static readonly DEFAULT_RESPONSE: string =
    "Hi, I'm a 10bis bot, searching for restaurants\n" +
    "To use me - enter /10bis Restaurant, e.g. '/10bis דיקסי'";
}


text:
@implementation NSSet (PrintModelProperty)

- (NSString *)readableDescription {
    return [NSString stringWithFormat:@"{%@}", [[self allObjects] readableDescription]];
}

@end


text:
module Azure::MixedReality::Mgmt::V2020_04_06_preview
  module Models
    #
    # The resource model definition representing SKU
    #
    class Sku

      include MsRestAzure

      # @return [String] The name of the SKU. Ex - P3. It is typically a
      # letter+number code
      attr_accessor :name

      # @return [SkuTier] This field is required to be implemented by the
      # Resource Provider if the service has more than one tier, but is not
      # required on a PUT. Possible values include: 'Free', 'Basic',
      # 'Standard', 'Premium'
      attr_accessor :tier

      # @return [String] The SKU size. When the name field is the combination
      # of tier and some other value, this would be the standalone code.
      attr_accessor :size

      # @return [String] If the service has different generations of hardware,
      # for the same SKU, then that can be captured here.
      attr_accessor :family

      # @return [Integer] If the SKU supports scale out/in then the capacity
      # integer should be included. If scale out/in is not possible for the
      # resource this may be omitted.
      attr_accessor :capacity

      #
      # Mapper for Sku class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Sku',
          type: {
            name: 'Composite',
            class_name: 'Sku',
            model_properties: {
              name: {
                client_side_validation: true,
                required: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              tier: {
                client_side_validation: true,
                required: false,
                serialized_name: 'tier',
                type: {
                  name: 'Enum',
                  module: 'SkuTier'
                }
              },
              size: {
                client_side_validation: true,
                required: false,
                serialized_name: 'size',
                type: {
                  name: 'String'
                }
              },
              family: {
                client_side_validation: true,
                required: false,
                serialized_name: 'family',
                type: {
                  name: 'String'
                }
              },
              capacity: {
                client_side_validation: true,
                required: false,
                serialized_name: 'capacity',
                type: {
                  name: 'Number'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package com.microsoft.applicationinsights.internal.channel.common;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

import com.microsoft.applicationinsights.internal.logger.InternalLogger;

import com.google.common.primitives.Longs;

/**
 * The class is responsible for managing the back-offs of Sender Threads.
 *
 * Sending threads are expected to:
 * 1. Call 'backOffCurrentSenderThread' when they need to suspend their work with a Transmission.
 *    A typical scenario is when the thread was given a 'Throttled' response from the server.
 * 2. Call 'onDoneSending' when the thread doesn't need to re-send the Transmission. This might
 *    happen when the Transmission was successfully sent, or when there are errors that lead to this decision.
 *
 * In either way, each send activity must be followed by calling one of those methods. Failing to do so, might result in undefined behavior.
 *
 * Created by gupele on 2/9/2015.
 */
final class SenderThreadsBackOffManager extends ThreadLocal<SenderThreadLocalBackOffData> {
    // The back-off timeouts that will be used by sender threads when need to back-off.
    private long[] backOffTimeoutsInMilliseconds = null;

    // All the thread local data
    private final ArrayList<SenderThreadLocalBackOffData> allSendersData;

    // A way to distinct
    private final AtomicInteger threadsSecondsDifference = new AtomicInteger(-1);

    private SenderThreadLocalBackOffData senderThreadLocalData;
    private boolean stopped;

    public SenderThreadsBackOffManager(BackOffTimesPolicy backOffTimesContainer) {
        allSendersData = new ArrayList<SenderThreadLocalBackOffData>();
        initializeBackOffTimeouts(backOffTimesContainer);
    }

    public void onDoneSending() {
        SenderThreadLocalBackOffData currentThreadData = this.get();
        currentThreadData.onDoneSending();
    }

    public boolean backOffCurrentSenderThread() {
        SenderThreadLocalBackOffData currentThreadData = this.get();
        return currentThreadData.backOff();
    }

    public synchronized void stopAllSendersBackOffActivities() {
        for (SenderThreadLocalBackOffData sender : allSendersData) {
            sender.stop();
        }
        stopped = true;
    }

    @Override
    protected SenderThreadLocalBackOffData initialValue() {
        int addSeconds = threadsSecondsDifference.incrementAndGet();
        senderThreadLocalData = new SenderThreadLocalBackOffData(backOffTimeoutsInMilliseconds, addSeconds * 1000);
        registerSenderData(senderThreadLocalData);
        return senderThreadLocalData;
    }

    private synchronized void registerSenderData(SenderThreadLocalBackOffData senderData) {
        if (stopped) {
            senderData.stop();
        }

        allSendersData.add(senderData);
    }

    /**
     * Initialize the 'backOffTimeoutsInSeconds' container, which should be done only once.
     * @param container The container that supplies the back-off timeouts in seconds.
     *                  Note that if the container returns null, an exception (NullPointerException) will be thrown.
     */
    private synchronized void initializeBackOffTimeouts(BackOffTimesPolicy container) {
        if (backOffTimeoutsInMilliseconds != null) {
            return;
        }

        if (container == null) {
            backOffTimeoutsInMilliseconds = new ExponentialBackOffTimesPolicy().getBackOffTimeoutsInMillis();
            InternalLogger.INSTANCE.trace("No BackOffTimesContainer, using default values.");
            return;
        }

        long[] injectedBackOffTimeoutsInSeconds = container.getBackOffTimeoutsInMillis();
        ArrayList<Long> validBackOffTimeoutsInSeconds = new ArrayList<Long>();
        if (injectedBackOffTimeoutsInSeconds != null) {
            for (long backOffValue : injectedBackOffTimeoutsInSeconds) {
                if (backOffValue <= 0) {
                    continue;
                }

                validBackOffTimeoutsInSeconds.add(backOffValue);
            }
        }

        if (validBackOffTimeoutsInSeconds.isEmpty()) {
            backOffTimeoutsInMilliseconds = new ExponentialBackOffTimesPolicy().getBackOffTimeoutsInMillis();
            InternalLogger.INSTANCE.trace("BackOff timeouts are not supplied or not valid, using default values.");
            return;
        }

        backOffTimeoutsInMilliseconds = Longs.toArray(validBackOffTimeoutsInSeconds);
    }
}


text:
layout: doc
title: "Label.setDisplayFormat"
position: 37
---

Устанавливает [функцию](../../Core/Script/) форматирования [значения](../EditorBase/EditorBase.getValue/) для отображения.

# Syntax

```js
Label.setDisplayFormat(format)
```

## Parameters

|Name|Type|Description|
|----|----------|---------|
|format|[функция](../../Core/Script/)|[Функция](../../Core/Script/) форматирования [значения](../EditorBase/EditorBase.getValue/) для отображения.|

## Returns

нет

# Examples

```js
//js-demo
var label = new Label();
var formaToLowerCase = function (context, args) {
    return String(args.value).toLowerCase();
}
label.setDisplayFormat(formaToLowerCase);
label.setValue('sOmEcAsE');

$elementForExample.prepend(label.render());
```

# See Also

* [`getDisplayFormat()`](../Label.getDisplayFormat/)


text:
"""
Prefetches images into the Image Cache
"""

import eventlet

import glance_store

from glance.common import exception
from glance import context
from glance.image_cache import base
from glance.openstack.common import gettextutils
import glance.openstack.common.log as logging
import glance.registry.client.v1.api as registry

LOG = logging.getLogger(__name__)
_LI = gettextutils._LI
_LW = gettextutils._LW

class Prefetcher(base.CacheApp):

    def __init__(self):
        super(Prefetcher, self).__init__()
        registry.configure_registry_client()
        registry.configure_registry_admin_creds()

    def fetch_image_into_cache(self, image_id):
        ctx = context.RequestContext(is_admin=True, show_deleted=True)

        try:
            image_meta = registry.get_image_metadata(ctx, image_id)
            if image_meta['status'] != 'active':
                LOG.warn(_LW("Image '%s' is not active. Not caching.") %
                         image_id)
                return False

        except exception.NotFound:
            LOG.warn(_LW("No metadata found for image '%s'") % image_id)
            return False

        location = image_meta['location']
        image_data, image_size = glance_store.get_from_backend(location,
                                                               context=ctx)
        LOG.debug("Caching image '%s'", image_id)
        cache_tee_iter = self.cache.cache_tee_iter(image_id, image_data,
                                                   image_meta['checksum'])
        # Image is tee'd into cache and checksum verified
        # as we iterate
        list(cache_tee_iter)
        return True

    def run(self):

        images = self.cache.get_queued_images()
        if not images:
            LOG.debug("Nothing to prefetch.")
            return True

        num_images = len(images)
        LOG.debug("Found %d images to prefetch", num_images)

        pool = eventlet.GreenPool(num_images)
        results = pool.imap(self.fetch_image_into_cache, images)
        successes = sum([1 for r in results if r is True])
        if successes != num_images:
            LOG.warn(_LW("Failed to successfully cache all "
                         "images in queue."))
            return False

        LOG.info(_LI("Successfully cached all %d images") % num_images)
        return True


text:
<Customer CustomerID="LINOD">
	<CompanyName>LINO-Delicateses</CompanyName>
	<ContactName>Felipe Izquierdo</ContactName>
	<ContactTitle>Owner</ContactTitle>
	<Address>Ave. 5 de Mayo Porlamar</Address>
	<City>I. de Margarita</City>
	<Region>Nueva Esparta</Region>
	<PostalCode>4980</PostalCode>
	<Country>Venezuela</Country>
	<Phone>(8) 34-56-12</Phone>
	<Fax>(8) 34-93-93</Fax>
</Customer>


text:
package de.lessvoid.nifty.builder;

import de.lessvoid.nifty.controls.dynamic.CustomControlCreator;

import javax.annotation.Nonnull;

public class ControlBuilder extends ElementBuilder {
  @Nonnull
  private final CustomControlCreator creator;

  private ControlBuilder(@Nonnull final CustomControlCreator creator) {
    super(creator);
    this.creator = creator;
  }

  public ControlBuilder(@Nonnull final String name) {
    this(new CustomControlCreator(name));
  }

  public ControlBuilder(@Nonnull final String id, @Nonnull final String name) {
    this(new CustomControlCreator(id, name));
  }

  public ControlBuilder parameter(@Nonnull final String name, @Nonnull final String value) {
    creator.parameter(name, value);
    return this;
  }
}


text:
#include "ml_metadata/metadata_store/metadata_source_test_suite.h"

#include <memory>

#include <gmock/gmock.h>
#include "absl/status/status.h"
#include "absl/strings/substitute.h"
#include "ml_metadata/metadata_store/constants.h"
#include "ml_metadata/metadata_store/test_util.h"

namespace ml_metadata {
namespace testing {
namespace {

using ::testing::HasSubstr;
using ::testing::IsEmpty;
using ::testing::Not;

// Test Insert execution.
// Initialization: creates an empty table t1 (c1 INT, c2 VARCHAR(255)) with test
// schema.
// Execution: Insert a new row (1,'v1') into t1.
// Expectation: all the retrieved rows in t1 are (1, 'v1').
TEST_P(MetadataSourceTestSuite, TestInsert) {
  metadata_source_container_->InitTestSchema();
  ASSERT_EQ(absl::OkStatus(), metadata_source_->Begin());
  ASSERT_EQ(absl::OkStatus(), metadata_source_->ExecuteQuery(
                                  "INSERT INTO t1 VALUES (1, 'v1')", nullptr));
  RecordSet expected_results;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(
      R"(column_names: "c1"
         column_names: "c2"
         records: {
            values: "1"
            values: "v1"
         })",
      &expected_results));

  RecordSet query_results;
  ASSERT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("SELECT * FROM t1", &query_results));
  ASSERT_EQ(absl::OkStatus(), metadata_source_->Commit());

  EXPECT_EQ(1, query_results.records().size());
  EXPECT_THAT(query_results, EqualsProto(expected_results));
}

// Test Insert execution with escaped string value.
// Initialization: creates an empty table t1 (c1 INT, c2 VARCHAR(255)) with test
// schema.
// Execution: Insert a new row (1,'') into the table.
// Expectation: all the retrieved rows in t1 are (1, '').
TEST_P(MetadataSourceTestSuite, TestInsertWithEscapedStringValue) {
  metadata_source_container_->InitTestSchema();
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Begin());
  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery(
                absl::StrCat("INSERT INTO t1 VALUES (1, '",
                             metadata_source_->EscapeString("''"), "')"),
                nullptr));
  RecordSet expected_results = ParseTextProtoOrDie<RecordSet>(
      R"(column_names: "c1"
         column_names: "c2"
         records: { values: "1" values: "''" })");

  RecordSet query_results;
  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("SELECT * FROM t1", &query_results));
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Commit());
  EXPECT_EQ(1, query_results.records().size());
  EXPECT_THAT(query_results, EqualsProto(expected_results));
}

// Test Delete execution.
// Initialization: creates an empty table t1 (c1 INT, c2 VARCHAR(255)) with test
// schema and adds 3 rows to this table: (1,'v1'), (2,'v2'), (3, 'v3').
// Execution: Delete all the rows in the table.
// Expectation: query results are empty.
TEST_P(MetadataSourceTestSuite, TestDelete) {
  metadata_source_container_->InitSchemaAndPopulateRows();
  RecordSet query_results;
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Begin());
  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("SELECT * FROM t1", &query_results));
  EXPECT_THAT(query_results.records(), Not(IsEmpty()));

  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("DELETE FROM t1", nullptr));

  query_results.Clear();
  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("SELECT * FROM t1", &query_results));
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Commit());
  EXPECT_THAT(query_results.records(), IsEmpty());
}

// Test Update execution.
// Initialization: creates an empty table t1 (c1 INT, c2 VARCHAR(255)) with test
// schema and adds 3 rows to t1: (1,'v1'), (2,'v2'), (3, 'v3').
// Execution: Update c2 to 'v100' in rows where c1 = 1 in table t1.
// Expectation: c2 was updated to 'v100' in rows where c1 = 1 in query results.
TEST_P(MetadataSourceTestSuite, TestUpdate) {
  metadata_source_container_->InitSchemaAndPopulateRows();
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Begin());
  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery(
                "UPDATE t1 SET c2 = 'v100' WHERE c1 = 1", nullptr));

  RecordSet expected_results = ParseTextProtoOrDie<RecordSet>(
      R"(column_names: "c1"
         column_names: "c2"
         records: { values: "1" values: "v100" })");

  RecordSet query_results;
  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("SELECT * FROM t1 WHERE c1 = 1",
                                           &query_results));
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Commit());
  EXPECT_THAT(query_results, EqualsProto(expected_results));
}

// Test query execution without open connection to metadata source.
// Expectation: returns FAILED_PRECONDITION status.
TEST_P(MetadataSourceTestSuite, TestQueryWithoutConnect) {
  absl::Status s =
      metadata_source_->ExecuteQuery("CREATE TABLE foo(bar INT)", nullptr);
  EXPECT_TRUE(absl::IsFailedPrecondition(s));
  EXPECT_THAT(std::string(s.message()), HasSubstr("No opened connection"));
}

// Test multiple queries, and rollback. Nothing should happen.
// Initialization: creates an empty table t1 (c1 INT, c2 VARCHAR(255)) with test
// schema and adds 3 rows to this table: (1,'v1'), (2,'v2'), (3, 'v3').
// Execution 1: Delete all the rows in t1 and then Rollback.
// Expectation 1: the retrieved rows remain the same.
// Execution 2: Insert 2 new rows into t1: (1, 'v1'), (2, 'v2').
// Expectation 2: 2 more rows were added in the original query results.
TEST_P(MetadataSourceTestSuite, TestMultiQueryTransaction) {
  metadata_source_container_->InitSchemaAndPopulateRows();
  RecordSet expected_results;
  ASSERT_EQ(absl::OkStatus(), metadata_source_->Begin());
  ASSERT_EQ(absl::OkStatus(), metadata_source_->ExecuteQuery(
                                  "SELECT * FROM t1", &expected_results));
  ASSERT_EQ(absl::OkStatus(), metadata_source_->Commit());

  ASSERT_EQ(absl::OkStatus(), metadata_source_->Begin());
  ASSERT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("DELETE FROM t1", nullptr));
  ASSERT_EQ(absl::OkStatus(), metadata_source_->Rollback());

  // rollback the Delete query, there should be no change in the database.
  {
    RecordSet query_results;
    ASSERT_EQ(absl::OkStatus(), metadata_source_->Begin());
    ASSERT_EQ(absl::OkStatus(), metadata_source_->ExecuteQuery(
                                    "SELECT * FROM t1", &query_results));
    ASSERT_EQ(absl::OkStatus(), metadata_source_->Commit());
    EXPECT_THAT(query_results, EqualsProto(expected_results));
  }

  // now it is in a new transaction, insert two records, then commit
  ASSERT_EQ(absl::OkStatus(), metadata_source_->Begin());
  ASSERT_EQ(absl::OkStatus(), metadata_source_->ExecuteQuery(
                                  "INSERT INTO t1 VALUES (1, 'v1')", nullptr));
  ASSERT_EQ(absl::OkStatus(), metadata_source_->ExecuteQuery(
                                  "INSERT INTO t1 VALUES (2, 'v2')", nullptr));
  ASSERT_EQ(absl::OkStatus(), metadata_source_->Commit());

  {
    RecordSet query_results;
    ASSERT_EQ(absl::OkStatus(), metadata_source_->Begin());
    EXPECT_EQ(absl::OkStatus(), metadata_source_->ExecuteQuery(
                                    "SELECT * FROM t1", &query_results));
    ASSERT_EQ(absl::OkStatus(), metadata_source_->Commit());
    int expected_num_rows = expected_results.records().size() + 2;
    EXPECT_EQ(expected_num_rows, query_results.records().size());
  }
}

// Test Insert execution with NULL values.
// Initialization: creates an empty table t1 (c1 INT, c2 VARCHAR(255)) with test
// schema.
// Execution: Insert a new row (1, NULL) into t1.
// Expectation: all the retrieved rows in t1 are (1, kMetadataSourceNull).
TEST_P(MetadataSourceTestSuite, TestNull) {
  metadata_source_container_->InitTestSchema();
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Begin());
  EXPECT_EQ(absl::OkStatus(), metadata_source_->ExecuteQuery(
                                  "INSERT INTO t1 VALUES (1, NULL)", nullptr));
  RecordSet expected_results = ParseTextProtoOrDie<RecordSet>(absl::Substitute(
      R"(column_names: "c1"
           column_names: "c2"
           records: { values: "1" values: "$0" })",
      kMetadataSourceNull));

  RecordSet query_results;
  EXPECT_EQ(absl::OkStatus(),
            metadata_source_->ExecuteQuery("SELECT * FROM t1", &query_results));
  EXPECT_EQ(absl::OkStatus(), metadata_source_->Commit());
  EXPECT_EQ(1, query_results.records().size());
  EXPECT_THAT(query_results, EqualsProto(expected_results));
}

}  // namespace
}  // namespace testing
}  // namespace ml_metadata


text:
const AdapterFactoryProvider = require('../../providers').AdapterFactoryProvider
const MongodbAdapter = require('./mongodb')
const MongooseAdapter = require('./mongoose')

module.exports = AdapterFactoryProvider({
  mongodb: MongodbAdapter,
  mongoose: MongooseAdapter
})


text:
package com.squareup.wire.schema;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.squareup.wire.ProtoAdapter;
import java.io.EOFException;
import java.io.IOException;
import java.net.ProtocolException;
import okio.Buffer;
import okio.ByteString;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;

public final class SchemaProtoAdapterTest {
  final Schema coffeeSchema = new SchemaBuilder()
      .add("coffee.proto", ""
          + "message CafeDrink {\n"
          + "  optional string customer_name = 1;\n"
          + "  repeated EspressoShot shots = 2;\n"
          + "  optional Foam foam = 3;\n"
          + "  optional int32 size_ounces = 14;\n"
          + "  optional Dairy dairy = 15;\n"
          + "\n"
          + "  enum Foam {\n"
          + "    NOT_FOAMY_AND_QUITE_BORING = 1;\n"
          + "    ZOMG_SO_FOAMY = 3;\n"
          + "  }\n"
          + "}\n"
          + "\n"
          + "message Dairy {\n"
          + "  optional int32 count = 2;\n"
          + "  optional string type = 1;\n"
          + "}\n"
          + "\n"
          + "message EspressoShot {\n"
          + "  optional string bean_type = 1;\n"
          + "  optional double caffeine_level = 2;\n"
          + "}\n")
      .build();

  // Golden data emitted by protoc using the schema above.
  final ImmutableMap<String, Object> dansCoffee = ImmutableMap.<String, Object>of(
      "customer_name", "Dan",
      "shots", ImmutableList.of(
          ImmutableMap.of("caffeine_level", 0.5d)
      ),
      "size_ounces", 16,
      "dairy", ImmutableMap.of("count", 1));
  final ByteString dansCoffeeEncoded = ByteString.decodeHex(
      "0a0344616e120911000000000000e03f70107a021001");

  final ImmutableMap<String, Object> jessesCoffee = ImmutableMap.<String, Object>of(
      "customer_name", "Jesse",
      "shots", ImmutableList.of(
          ImmutableMap.of("bean_type", "colombian", "caffeine_level", 1.0d),
          ImmutableMap.of("bean_type", "colombian", "caffeine_level", 1.0d)
      ),
      "foam", "ZOMG_SO_FOAMY",
      "size_ounces", 24);
  final ByteString jessesCoffeeEncoded = ByteString.decodeHex("0a054a6573736512140a09636f6c"
      + "6f6d6269616e11000000000000f03f12140a09636f6c6f6d6269616e11000000000000f03f18037018");

  @Test public void decode() throws Exception {
    ProtoAdapter<Object> adapter = coffeeSchema.protoAdapter("CafeDrink", true);
    assertThat(adapter.decode(new Buffer().write(dansCoffeeEncoded))).isEqualTo(dansCoffee);
    assertThat(adapter.decode(new Buffer().write(jessesCoffeeEncoded))).isEqualTo(jessesCoffee);
  }

  @Test public void encode() throws IOException {
    ProtoAdapter<Object> adapter = coffeeSchema.protoAdapter("CafeDrink", true);
    assertThat(ByteString.of(adapter.encode(dansCoffee))).isEqualTo(dansCoffeeEncoded);
    assertThat(ByteString.of(adapter.encode(jessesCoffee))).isEqualTo(jessesCoffeeEncoded);
  }

  @Test public void groupsIgnored() throws IOException {
    ProtoAdapter<Object> adapter = new SchemaBuilder()
        .add("message.proto", ""
            + "message Message {\n"
            + "  optional string a = 1;\n"
            + "  // repeated group Group1 = 2 {\n"
            + "  //   optional SomeMessage a = 11;\n"
            + "  // }\n"
            + "  // repeated group Group2 = 3 {\n"
            + "  //   optional SomeMessage b = 21;\n"
            + "  // }\n"
            + "  optional string b = 4;\n"
            + "}\n")
        .buildProtoAdapter("Message");
    ByteString encoded = ByteString.decodeHex("0a0161135a02080114135a02100214135a090803720568656c6c"
        + "6f141baa010208011c1baa010210021c1baa01090803720568656c6c6f1c220162");
    ImmutableMap<String, Object> expected = ImmutableMap.<String, Object>of(
        "a", "a",
        "b", "b");
    assertThat(adapter.decode(new Buffer().write(encoded))).isEqualTo(expected);
  }

  @Test public void startGroupWithoutEndGroup() throws IOException {
    ProtoAdapter<Object> adapter = new SchemaBuilder()
        .add("message.proto", ""
            + "message Message {\n"
            + "  optional string a = 1;\n"
            + "}\n")
        .buildProtoAdapter("Message");
    ByteString encoded = ByteString.decodeHex("130a0161");
    try {
      adapter.decode(new Buffer().write(encoded));
      fail();
    } catch (EOFException expected) {
    }
  }

  @Test public void unexpectedEndGroup() throws IOException {
    ProtoAdapter<Object> adapter = new SchemaBuilder()
        .add("message.proto", ""
            + "message Message {\n"
            + "  optional string a = 1;\n"
            + "}\n")
        .buildProtoAdapter("Message");
    ByteString encoded = ByteString.decodeHex("0a01611c");
    try {
      adapter.decode(new Buffer().write(encoded));
      fail();
    } catch (ProtocolException expected) {
      assertThat(expected).hasMessage("Unexpected end group");
    }
  }

  @Test public void endGroupDoesntMatchStartGroup() throws IOException {
    ProtoAdapter<Object> adapter = new SchemaBuilder()
        .add("message.proto", ""
            + "message Message {\n"
            + "  optional string a = 1;\n"
            + "}\n")
        .buildProtoAdapter("Message");
    ByteString encoded = ByteString.decodeHex("130a01611c");
    try {
      adapter.decode(new Buffer().write(encoded));
      fail();
    } catch (ProtocolException expected) {
      assertThat(expected).hasMessage("Unexpected end group");
    }
  }

  @Test public void decodeToUnpacked() throws IOException {
    ProtoAdapter<Object> adapter = new SchemaBuilder()
        .add("message.proto", ""
            + "message Message {\n"
            + "  repeated int32 a = 90 [packed = false];\n"
            + "}\n")
        .buildProtoAdapter("Message");
    ImmutableMap<String, Object> expected = ImmutableMap.<String, Object>of(
        "a", ImmutableList.of(601, 701));
    ByteString packedEncoded = ByteString.decodeHex("d20504d904bd05");
    assertThat(adapter.decode(new Buffer().write(packedEncoded))).isEqualTo(expected);
    ByteString unpackedEncoded = ByteString.decodeHex("d005d904d005bd05");
    assertThat(adapter.decode(new Buffer().write(unpackedEncoded))).isEqualTo(expected);
  }

  @Test public void decodeToPacked() throws IOException {
    ProtoAdapter<Object> adapter = new SchemaBuilder()
        .add("message.proto", ""
            + "message Message {\n"
            + "  repeated int32 a = 90 [packed = true];\n"
            + "}\n")
        .buildProtoAdapter("Message");
    ImmutableMap<String, Object> expected = ImmutableMap.<String, Object>of(
        "a", ImmutableList.of(601, 701));
    ByteString unpackedEncoded = ByteString.decodeHex("d005d904d005bd05");
    assertThat(adapter.decode(new Buffer().write(unpackedEncoded))).isEqualTo(expected);
    ByteString packedEncoded = ByteString.decodeHex("d20504d904bd05");
    assertThat(adapter.decode(new Buffer().write(packedEncoded))).isEqualTo(expected);
  }

  @Test public void recursiveMessage() throws IOException {
    ProtoAdapter<Object> adapter = new SchemaBuilder()
        .add("tree.proto", ""
            + "message BinaryTreeNode {\n"
            + "  optional BinaryTreeNode left = 1;\n"
            + "  optional BinaryTreeNode right = 2;\n"
            + "  optional string value = 3;\n"
            + "}\n")
        .buildProtoAdapter("BinaryTreeNode");
    ImmutableMap<String, Object> value = ImmutableMap.<String, Object>of(
        "value", "D",
        "left", ImmutableMap.of(
            "value", "B",
            "left", ImmutableMap.of("value", "A"),
            "right", ImmutableMap.of("value", "C")),
        "right", ImmutableMap.of(
            "value", "F",
            "left", ImmutableMap.of("value", "E"),
            "right", ImmutableMap.of("value", "G")));
    ByteString encoded = ByteString.decodeHex(
        "1a01440a0d1a01420a031a014112031a0143120d1a01460a031a014512031a0147");
    assertThat(ByteString.of(adapter.encode(value))).isEqualTo(encoded);
    assertThat(adapter.decode(new Buffer().write(encoded))).isEqualTo(value);
  }

  @Test public void includeUnknowns() throws Exception {
    Schema schema = new SchemaBuilder()
        .add("coffee.proto", ""
            + "message CafeDrink {\n"
            + "  optional string customer_name = 1;\n"
            + "  optional int32 size_ounces = 14;\n"
            + "}\n")
        .build();

    ImmutableMap<String, Object> dansCoffeeWithUnknowns = ImmutableMap.<String, Object>of(
        "customer_name", "Dan",
        "2", ImmutableList.of(ByteString.decodeHex("11000000000000e03f")),
        "size_ounces", 16,
        "15", ImmutableList.of(ByteString.decodeHex("1001")));

    ProtoAdapter<Object> adapter = schema.protoAdapter("CafeDrink", true);
    assertThat(adapter.decode(new Buffer().write(dansCoffeeEncoded)))
        .isEqualTo(dansCoffeeWithUnknowns);
  }

  @Test public void omitUnknowns() throws Exception {
    Schema schema = new SchemaBuilder()
        .add("coffee.proto", ""
            + "message CafeDrink {\n"
            + "  optional string customer_name = 1;\n"
            + "  optional int32 size_ounces = 14;\n"
            + "}\n")
        .build();

    ImmutableMap<String, Object> dansCoffeeWithoutUnknowns = ImmutableMap.<String, Object>of(
        "customer_name", "Dan",
        "size_ounces", 16);

    ProtoAdapter<Object> adapter = schema.protoAdapter("CafeDrink", false);
    assertThat(adapter.decode(new Buffer().write(dansCoffeeEncoded)))
        .isEqualTo(dansCoffeeWithoutUnknowns);
  }
}