text:
package lighthouse.protocol;

import com.google.common.collect.*;
import com.google.protobuf.*;
import lighthouse.wallet.*;
import org.bitcoinj.core.*;
import org.bitcoinj.crypto.*;
import org.bitcoinj.params.*;
import org.bitcoinj.script.*;
import org.bitcoinj.utils.*;
import org.junit.*;

import java.security.*;
import java.util.*;

import static java.util.concurrent.CompletableFuture.*;
import static lighthouse.protocol.LHUtils.*;
import static org.bitcoinj.testing.FakeTxBuilder.*;
import static org.junit.Assert.*;

public class ProjectTest {
    private List<TransactionOutput> EMPTY_LIST = ImmutableList.of();

    private Address toAddress;
    private LHProtos.ProjectDetails.Builder details;
    private NetworkParameters params = UnitTestParams.get();
    private LHProtos.Project.Builder projectBuilder;
    private PledgingWallet wallet;

    private static class TxData {
        Transaction pledge;
        Transaction fakeStub;
        ECKey key;
    }

    private TxData makePledge(LHProtos.ProjectDetails.Builder details, double percentage) {
        TxData txData = new TxData();
        txData.pledge = new Transaction(params);
        long total = 0;
        for (LHProtos.Output output : details.getOutputsList()) {
            txData.pledge.addOutput(Coin.valueOf(output.getAmount()), new Script(output.getScript().toByteArray()));
            total += output.getAmount();
        }
        txData.key = new ECKey();
        final long pledgeSatoshis = (long) (total * percentage);
        txData.fakeStub = createFakeTx(params, Coin.valueOf(pledgeSatoshis), txData.key.toAddress(params));
        txData.pledge.addSignedInput(txData.fakeStub.getOutput(0), txData.key, Transaction.SigHash.ALL, true);
        txData.pledge = roundTripTransaction(params, txData.pledge);
        return txData;
    }

    @Before
    public void setUp() throws Exception {
        BriefLogFormatter.init();
        // Some constant key to make tests faster and deterministic.
        wallet = new PledgingWallet(params);
        toAddress = wallet.freshReceiveAddress();
        details = Project.makeDetails(
                wallet.getParams(), "My cool project", "A project to make awesome things ... out of Lego!",
                toAddress, Coin.COIN, wallet.freshAuthKey(), wallet.getKeychainLookaheadSize());
        projectBuilder = LHProtos.Project.newBuilder();
        projectBuilder.setSerializedPaymentDetails(details.build().toByteString());
    }

    @Test
    public void accessors() throws Exception {
        Project project = new Project(projectBuilder.build());
        assertEquals("My cool project", project.getTitle());
        assertEquals("A project to make awesome things ... out of Lego!", project.getMemo());
        assertEquals(Coin.COIN, project.getGoalAmount());
    }

    @Test(expected = Ex.NoTransactionData.class)
    public void badPledgeNoTx() throws Exception {
        LHProtos.Pledge.Builder pledge = LHProtos.Pledge.newBuilder();
        pledge.getPledgeDetailsBuilder().setTotalInputValue(0);
        pledge.getPledgeDetailsBuilder().setProjectId("abc");
        pledge.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge.getPledgeDetailsBuilder();
        Project project = new Project(projectBuilder.build());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(EMPTY_LIST), pledge.build()));
    }

    @Test(expected = Ex.TxWrongNumberOfOutputs.class)
    public void badPledgeInsufficientOutputs() throws Exception {
        TxData pledgeTX = makePledge(details, 0.5);
        // Add an output to the contract and verify the pledge fails with the right exception.
        details.addOutputsBuilder().setScript(details.getOutputs(0).getScript()).setAmount(100);
        projectBuilder.setSerializedPaymentDetails(details.build().toByteString());
        LHProtos.Pledge.Builder pledge = LHProtos.Pledge.newBuilder();
        pledge.addTransactions(ByteString.copyFrom(pledgeTX.pledge.bitcoinSerialize()));
        pledge.getPledgeDetailsBuilder().setTotalInputValue(0);
        pledge.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge.getPledgeDetailsBuilder().setProjectId("abc");
        pledge.getPledgeDetailsBuilder();
        Project project = new Project(projectBuilder.build());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(EMPTY_LIST), pledge.build()));
    }

    @Test(expected = Ex.OutputMismatch.class)
    public void badPledgeWrongOutput() throws Exception {
        TxData pledgeTX = makePledge(details, 0.5);
        pledgeTX.pledge.getOutput(0).setValue(Coin.valueOf(100));
        LHProtos.Pledge.Builder pledge = LHProtos.Pledge.newBuilder();
        pledge.addTransactions(ByteString.copyFrom(pledgeTX.pledge.bitcoinSerialize()));
        pledge.getPledgeDetailsBuilder().setTotalInputValue(0);
        pledge.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge.getPledgeDetailsBuilder().setProjectId("abc");
        pledge.getPledgeDetailsBuilder();
        Project project = new Project(projectBuilder.build());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(EMPTY_LIST), pledge.build()));
    }

    @Test(expected = Ex.PledgeTooSmall.class)
    public void badPledgeTooSmall() throws Exception {
        TxData pledgeTX = makePledge(details, 0.00001);
        LHProtos.Pledge.Builder pledge = pledgeToBuilder(pledgeTX, false);
        details.getExtraDetailsBuilder().setMinPledgeSize(2000);
        projectBuilder.setSerializedPaymentDetails(details.build().toByteString());
        Project project = new Project(projectBuilder.build());
        pledge.getPledgeDetailsBuilder().setTotalInputValue(project.getGoalAmount().divide(100000).value);
        pledge.getPledgeDetailsBuilder();
        List<TransactionOutput> outputs = ImmutableList.of(pledgeTX.fakeStub.getOutput(0).duplicateDetached());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(outputs), pledge.build()));
    }

    @Test(expected = Ex.UnknownUTXO.class)
    public void missingUTXO() throws Exception {
        // Check the exception thrown if the pledge seems to be double spent away or is just invalid.
        TxData pledgeTX = makePledge(details, 0.5);
        LHProtos.Pledge.Builder pledge = LHProtos.Pledge.newBuilder();
        pledge.addTransactions(ByteString.copyFrom(pledgeTX.pledge.bitcoinSerialize()));
        pledge.getPledgeDetailsBuilder().setTotalInputValue(0);
        pledge.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge.getPledgeDetailsBuilder().setProjectId("abc");
        pledge.getPledgeDetailsBuilder();
        Project project = new Project(projectBuilder.build());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(EMPTY_LIST), pledge.build()));
    }

    @Test(expected = ScriptException.class)
    public void badSignature() throws Exception {
        TxData pledgeTX = makePledge(details, 0.1);
        pledgeTX.pledge.getInput(0).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy(), pledgeTX.key));
        LHProtos.Pledge.Builder pledge = pledgeToBuilder(pledgeTX, false);
        Project project = new Project(projectBuilder.build());
        List<TransactionOutput> outputs = ImmutableList.of(pledgeTX.fakeStub.getOutput(0).duplicateDetached());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(outputs), pledge.build()));
    }

    @Test(expected = VerificationException.class)
    public void badOutputScript() throws Exception {
        TxData pledgeTX = makePledge(details, 0.1);
        LHProtos.Pledge.Builder pledge = LHProtos.Pledge.newBuilder();
        pledge.addTransactions(ByteString.copyFrom(pledgeTX.pledge.bitcoinSerialize()));
        final Coin val = Coin.COIN.divide(10);
        pledge.getPledgeDetailsBuilder().setTotalInputValue(val.value);
        pledge.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge.getPledgeDetailsBuilder().setProjectId("abc");
        Project project = new Project(projectBuilder.build());
        TransactionOutput badOutput = new TransactionOutput(params, null, val,
                new ScriptBuilder().op(ScriptOpCodes.OP_TRUE).build().getProgram());
        List<TransactionOutput> outputs = ImmutableList.of(badOutput);
        checkedGet(project.verifyPledge(outPoints -> completedFuture(outputs), pledge.build()));
    }

    @Test(expected = Ex.CachedValueMismatch.class)
    public void badTotalValueField() throws Exception {
        // We require the pledge to (redundantly) specify the total value of all inputs, even though we check it
        // and calculate it by requesting the UTXOs, because that way once checked we can just save the pledge
        // message in a way that says it was validated and not have to look up UTXOs again in future, or wrap it
        // with extra data.
        TxData pledgeTX = makePledge(details, 0.1);
        LHProtos.Pledge.Builder pledge = pledgeToBuilder(pledgeTX, true);
        Project project = new Project(projectBuilder.build());
        List<TransactionOutput> outputs = ImmutableList.of(pledgeTX.fakeStub.getOutput(0).duplicateDetached());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(outputs), pledge.build()));
    }

    private LHProtos.Pledge.Builder pledgeToBuilder(TxData pledgeTX, boolean valueMismatch) {
        LHProtos.Pledge.Builder pledge = LHProtos.Pledge.newBuilder();
        pledge.addTransactions(ByteString.copyFrom(pledgeTX.pledge.bitcoinSerialize()));
        pledge.getPledgeDetailsBuilder().setTotalInputValue((long) (Coin.COIN.longValue() * (valueMismatch ? 0.2 : 0.1)));  // Mismatch.
        pledge.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge.getPledgeDetailsBuilder().setProjectId("abc");
        return pledge;
    }

    @Test(expected = VerificationException.DuplicatedOutPoint.class)
    public void duplicatedOutpoints() throws Exception {
        // Verify that the pledge we've been given doesn't contain multiple inputs that connect to the same output.
        // This would represent a malicious attempt to make us think we received more pledges than we really did.
        TxData pledgeTX = makePledge(details, 0.1);
        pledgeTX.pledge.addInput(pledgeTX.pledge.getInput(0).duplicateDetached());
        Project project = new Project(projectBuilder.build());
        project.fastSanityCheck(pledgeToBuilder(pledgeTX, true).build());
    }

    @Test(expected = Ex.NonStandardInput.class)
    public void nonStandardInputRegularOutput() throws Exception {
        // Unconsumed stack items are not allowed.
        TxData pledgeTX = makePledge(details, 0.1);
        TransactionInput input = pledgeTX.pledge.getInput(0);
        input.setScriptSig(
                new ScriptBuilder(input.getScriptSig())
                        .data(0, new byte[]{})
                        .build()
        );
        LHProtos.Pledge.Builder pledge = pledgeToBuilder(pledgeTX, false);
        Project project = new Project(projectBuilder.build());
        List<TransactionOutput> outputs = ImmutableList.of(pledgeTX.fakeStub.getOutput(0).duplicateDetached());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(outputs), pledge.build()));
    }

    @Test(expected = Ex.NonStandardInput.class)
    public void nonStandardInputP2SHOutput() throws Exception {
        // Unconsumed stack items are not allowed.
        TxData pledgeTX = makePledge(details, 0.1);
        TransactionInput input = pledgeTX.pledge.getInput(0);
        TransactionOutput origOutput = pledgeTX.fakeStub.getOutput(0);
        Script p2shPK = ScriptBuilder.createP2SHOutputScript(origOutput.getScriptPubKey());
        Script p2shSS = new ScriptBuilder(input.getScriptSig()).data(origOutput.getScriptBytes()).data(0, new byte[]{}).build();
        input.setScriptSig(p2shSS);
        pledgeTX.fakeStub.clearOutputs();
        pledgeTX.fakeStub.addOutput(origOutput.getValue(), p2shPK);
        LHProtos.Pledge.Builder pledge = pledgeToBuilder(pledgeTX, false);
        Project project = new Project(projectBuilder.build());
        List<TransactionOutput> outputs = ImmutableList.of(pledgeTX.fakeStub.getOutput(0).duplicateDetached());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(outputs), pledge.build()));
    }

    @Test
    public void okPledge() throws Exception {
        TxData pledgeTX = makePledge(details, 0.1);
        LHProtos.Pledge.Builder pledge = pledgeToBuilder(pledgeTX, false);
        Project project = new Project(projectBuilder.build());
        List<TransactionOutput> outputs = ImmutableList.of(pledgeTX.fakeStub.getOutput(0).duplicateDetached());
        checkedGet(project.verifyPledge(outPoints -> completedFuture(outputs), pledge.build()));
    }

    @Test(expected = Ex.ValueMismatch.class)
    public void incompleteContract() throws Exception {
        TxData pledgeTX1 = makePledge(details, 0.1);
        TxData pledgeTX2 = makePledge(details, 0.7);
        LHProtos.Pledge.Builder pledge1 = LHProtos.Pledge.newBuilder();
        pledge1.addTransactions(ByteString.copyFrom(pledgeTX1.pledge.bitcoinSerialize()));
        pledge1.getPledgeDetailsBuilder().setTotalInputValue((long) (Coin.COIN.longValue() * 0.1));
        pledge1.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge1.getPledgeDetailsBuilder().setProjectId("abc");
        LHProtos.Pledge.Builder pledge2 = LHProtos.Pledge.newBuilder();
        pledge2.addTransactions(ByteString.copyFrom(pledgeTX2.pledge.bitcoinSerialize()));
        pledge2.getPledgeDetailsBuilder().setTotalInputValue((long) (Coin.COIN.longValue() * 0.7));
        pledge2.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge2.getPledgeDetailsBuilder().setProjectId("abc");
        pledge2.getPledgeDetailsBuilder();

        Project project = new Project(projectBuilder.build());
        Transaction contract = project.completeContract(ImmutableSet.of(pledge1.build(), pledge2.build()));
        assertEquals(2, contract.getInputs().size());
    }

    @Test
    public void completeContract() throws Exception {
        TxData pledgeTX1 = makePledge(details, 0.1);
        TxData pledgeTX2 = makePledge(details, 0.9);
        LHProtos.Pledge.Builder pledge1 = LHProtos.Pledge.newBuilder();
        pledge1.addTransactions(ByteString.copyFrom(pledgeTX1.pledge.bitcoinSerialize()));
        pledge1.getPledgeDetailsBuilder().setTotalInputValue((long) (Coin.COIN.longValue() * 0.1));
        pledge1.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge1.getPledgeDetailsBuilder().setProjectId("abc");
        pledge1.getPledgeDetailsBuilder();
        LHProtos.Pledge.Builder pledge2 = LHProtos.Pledge.newBuilder();
        pledge2.addTransactions(ByteString.copyFrom(pledgeTX2.pledge.bitcoinSerialize()));
        pledge2.getPledgeDetailsBuilder().setTotalInputValue((long) (Coin.COIN.longValue() * 0.9));
        pledge2.getPledgeDetailsBuilder().setTimestamp(Utils.currentTimeSeconds());
        pledge2.getPledgeDetailsBuilder().setProjectId("abc");
        pledge2.getPledgeDetailsBuilder();

        Project project = new Project(projectBuilder.build());
        Transaction contract = project.completeContract(ImmutableSet.of(pledge1.build(), pledge2.build()));
        assertEquals(2, contract.getInputs().size());
    }

    @Test
    public void authKeys() throws Exception {
        details = Project.makeDetails(
                wallet.getParams(), "My cool project", "A project to make awesome things ... out of Lego!",
                toAddress, Coin.COIN, wallet.freshAuthKey(), wallet.getKeychainLookaheadSize());
        Project project = new Project(details.build());
        String signature = project.signAsOwner(wallet, "legolegolego", null);
        project.authenticateOwner("legolegolego", signature);
        try {
            project.authenticateOwner("duplo!duplo!duplo!", signature);
            fail();
        } catch (SignatureException e) {
            // Expected.
        }
    }

    @Test
    public void titleToPath() {
        assertEquals("bbc-14-01-2015-eu-lawyer-approves-ecb-bond-buying-programme", titleToUrlString("BBC 14/01/2015 EU lawyer approves ECB bond-buying programme"));
        assertEquals("bob-http-example-com-1378-foo-bar", titleToUrlString("Bob http://example.com:1378/?foo=bar"));
        assertEquals("a-really-cool-20-title-with-lots-asdf-of-weird-chars", titleToUrlString("A really $cool %20 Title with ;;lots asdf\n of weird // chars"));
        assertEquals("български-език", titleToUrlString("български език"));
        assertEquals("a-test-with-quotes-yeah", titleToUrlString("a test with \"quotes\" 'yeah'"));
    }
}


text:
package follower

import (
	"time"

	"github.com/bahadley/mgc/common"
	"github.com/bahadley/mgc/config"
	"github.com/bahadley/mgc/log"
)

var (
	// Invariant:  Heartbeats are in descending order by event.seqNo.
	hbWindow []*common.Heartbeat

	// Used to calculate next freshness points.
	dlCalc deadline
	// Used to determine the trust/suspect verdict for the leader.
	vCalc verdict
)

func manageObservations() {
	for {
		switch event := <-eventChan; event.EventType {
		// Heartbeat received from network interface.  Set the arrival time in
		// matching shell record in the observation window
		case common.HeartbeatEvent:
			if updated, delay := update(event.SeqNo, event.EventTime); !updated {
				log.Warning.Printf("Heartbeat from %s with seqNo %d not registered",
					event.Src, event.SeqNo)
			} else {
				verdictChan <- &common.Event{
					EventType: common.Verdict,
					EventTime: event.EventTime,
					SeqNo:     event.SeqNo,
					Suspect:   false}
				outputChan <- &common.Event{
					EventType:      common.HeartbeatEvent,
					EventTime:      event.EventTime,
					SeqNo:          event.SeqNo,
					Suspect:        false,
					HeartbeatDelay: delay}
			}
		// Leader will be sending a heartbeat now.  Calculate a deadline and
		// create a shell record in the observation window.
		case common.Query:
			reportChan <- &common.Event{
				EventType:      common.Query,
				EventTime:      event.EventTime,
				SeqNo:          event.SeqNo,
				FreshnessPoint: dlCalc.nextDeadline(event.EventTime)}
			if !insert(&common.Heartbeat{
				SeqNo:    event.SeqNo,
				SendTime: event.EventTime}) {
				log.Warning.Printf("Heartbeat initialization with seqNo %d not inserted",
					event.SeqNo)
			}
		// Deadline has expired.  Determine if a heartbeat has arrived for
		// this period.
		case common.FreshnessEvent:
			verdictChan <- &common.Event{
				EventType: common.Verdict,
				EventTime: time.Now(),
				SeqNo:     event.SeqNo,
				Suspect:   vCalc.check(event.SeqNo)}
		default:
			log.Error.Println("Invalid event type encountered")
		}
	}
}

func insert(tmp *common.Heartbeat) bool {
	var inserted bool

	for idx, hb := range hbWindow {
		if inserted ||
			(!inserted && hb != nil && tmp.SeqNo > hb.SeqNo) {
			// Insert the new heartbeat and shift the subsequent heartbeats towards
			// the back of the window.  The last heartbeat will fall off if the
			// window is full.
			hbWindow[idx] = tmp
			tmp = hb
			inserted = true
		} else if !inserted && hb == nil {
			// Window is currently empty and this is the first arriving heartbeat.
			hbWindow[idx] = tmp
			inserted = true
			break
		}
	}

	return inserted
}

func update(seqNo common.SeqNoType, arrivalTime time.Time) (bool, time.Duration) {
	var updated bool
	var delay time.Duration

	// Search for heartbeat with same sequence number.
	for _, hb := range hbWindow {
		if hb != nil && hb.SeqNo == seqNo {
			hb.ArrivalTime = arrivalTime
			hb.TransDelay = arrivalTime.Sub(hb.SendTime)
			updated = true
			delay = hb.TransDelay
			break
		}
	}

	return updated, delay
}

func init() {
	hbWindow = make([]*common.Heartbeat, config.DefaultWindowSz())

	dlCalc = &last{}
	vCalc = &basic{}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>tdh-collection</artifactId>
        <groupId>io.transwarp.collection</groupId>
        <version>0.4v</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>kafkaDecoder</artifactId>

    <dependencies>
        <dependency>
            <!-- use kafka_2.10(Kafka core) 0.8.0 and 0.8.2.2 often-->
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.10</artifactId>
            <version>0.8.0</version>
        </dependency>
        <dependency>
            <!-- Caution! Pick up the right version of inceptor_2.10-->
            <groupId>io.transwarp</groupId>
            <artifactId>inceptor_2.10</artifactId>
            <version>1.1.0-transwarp-tdh463</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

</project>


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('idc', '0001_initial'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Network',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('name', models.CharField(max_length=128, verbose_name='Network Name')),
                ('network_id', models.CharField(max_length=128, null=True, verbose_name='OS Network UUID', blank=True)),
                ('status', models.IntegerField(default=0, verbose_name='Status', choices=[(0, 'BUILD'), (1, 'ACTIVE'), (2, 'DOWN'), (3, 'ERROR'), (4, 'CREATING'), (5, 'DELETING'), (6, 'UPDATING')])),
                ('is_default', models.BooleanField(default=False, verbose_name='Default')),
                ('deleted', models.BooleanField(default=False, verbose_name='Deleted')),
                ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='Create Date')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
                ('user_data_center', models.ForeignKey(to='idc.UserDataCenter')),
            ],
            options={
                'db_table': 'network',
                'verbose_name': 'Network',
                'verbose_name_plural': 'Network',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Router',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('name', models.CharField(max_length=128, verbose_name='Router Name')),
                ('router_id', models.CharField(max_length=128, null=True, verbose_name='OS Router UUID', blank=True)),
                ('gateway', models.CharField(max_length=128, null=True, verbose_name='OS Router UUID', blank=True)),
                ('is_gateway', models.BooleanField(default=False, verbose_name='Deleted')),
                ('status', models.IntegerField(default=0, verbose_name='Status', choices=[(0, 'BUILD'), (1, 'ACTIVE'), (2, 'DOWN'), (3, 'ERROR'), (4, 'CREATING'), (5, 'DELETING'), (6, 'UPDATING')])),
                ('deleted', models.BooleanField(default=False, verbose_name='Deleted')),
                ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='Create Date')),
                ('is_default', models.BooleanField(default=False, verbose_name='Default')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
                ('user_data_center', models.ForeignKey(to='idc.UserDataCenter')),
            ],
            options={
                'db_table': 'router',
                'verbose_name': 'Router',
                'verbose_name_plural': 'Router',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='RouterInterface',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('os_port_id', models.CharField(max_length=128, null=True, verbose_name='Port', blank=True)),
                ('network_id', models.IntegerField(verbose_name='Network')),
                ('deleted', models.BooleanField(default=False, verbose_name='Deleted')),
                ('router', models.ForeignKey(to='network.Router')),
            ],
            options={
                'db_table': 'router_interface',
                'verbose_name': 'RouterInterface',
                'verbose_name_plural': 'RouterInterface',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Subnet',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('name', models.CharField(max_length=128, verbose_name='Network Name')),
                ('subnet_id', models.CharField(max_length=128, null=True, verbose_name='OS Subnet UUID', blank=True)),
                ('address', models.CharField(max_length=128, verbose_name='IPv4 CIDR')),
                ('ip_version', models.IntegerField(default=4, verbose_name='IP Version', choices=[(4, b'IP V4'), (6, b'IP V6')])),
                ('status', models.IntegerField(default=0, verbose_name='Status', choices=[(0, 'BUILD'), (1, 'ACTIVE'), (2, 'DOWN'), (3, 'ERROR'), (4, 'CREATING'), (5, 'DELETING'), (6, 'UPDATING')])),
                ('deleted', models.BooleanField(default=False, verbose_name='Deleted')),
                ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='Create Date')),
                ('network', models.ForeignKey(to='network.Network')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
                ('user_data_center', models.ForeignKey(to='idc.UserDataCenter')),
            ],
            options={
                'db_table': 'subnet',
                'verbose_name': 'Subnet',
                'verbose_name_plural': 'Subnet',
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='routerinterface',
            name='subnet',
            field=models.ForeignKey(to='network.Subnet'),
            preserve_default=True,
        ),
    ]


text:
. scripts/common/main.sh
. scripts/common/build.sh

prepare_build fish/fish --url git://github.com/fish-shell/fish-shell

export CC=gcc-6
export CXX=g++-6
cd "${BUILD_DIRECTORY}"
if cd pcre2* ; then
	autoreconf
	cd ..
fi
sed -r -i -e '/AC_CONFIG_MACRO_DIRS/d' ./configure.ac
for f in m4/*.m4 ; do
	sed -r -i -e "1i m4_include($f)" ./configure.ac
done
$CC --version
$CXX --version
autoreconf --version
autoreconf --no-recursive
./configure --prefix="$OPT_DIRECTORY"
make
./fish --version
make install

save_exe ./fish

commit_opt_archive "$OPT_DIRECTORY" "$TARGET" \
"Update fish
$COMMIT_MESSAGE_FOOTER"


text:
package com.blinkfox.myioc.tools;

import com.blinkfox.myioc.exception.NewInstanceException;
import java.util.HashMap;
import java.util.Map;

/**
 * 根据class生成该class对应策略的实例,使用枚举实现
 * Created by blinkfox on 2017/1/10.
 */
public enum ClassStrategy {

    /**
     * 根据类的class得到该类的唯一实例
     */
    SINGLETON {
        @Override
        public Object getInstance(Class cls) {
            // 先判断map中是否存在此变量,如果存在就直接返回该类的实例,否则生成新的类实例并存入全局的Map中
            String clsName = cls.getName();
            if (clsObjMap.containsKey(clsName)) {
                return clsObjMap.get(clsName);
            }

            try {
                Object obj = cls.newInstance();
                clsObjMap.put(clsName, obj);
                return obj;
            }catch (Exception e) {
                throw new NewInstanceException("实例化类" + clsName + "出错!", e);
            }
        }
    };

    // 存放类class和对应类实例的全局Map,其中key是className,value是类的实例
    private static Map<String, Object> clsObjMap = new HashMap<String, Object>();

    /**
     * 根据类的class获取该类的实例
     * @param cls 类的class
     * @return 类的实例
     */
    public abstract Object getInstance(Class cls);

}


text:
package samplesyscc

import (
	"errors"
	"fmt"
	"testing"

	"github.com/golang/protobuf/ptypes/timestamp"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/protos/peer"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func TestSampleSysCC_Init(t *testing.T) {
	assert.Equal(t, shim.Success(nil), (&SampleSysCC{}).Init(&mockStub{}))
}

type testCase struct {
	expected peer.Response
	mockStub
}

func TestSampleSysCC_Invoke(t *testing.T) {
	putvalIncorrectArgNum := &testCase{
		mockStub: mockStub{
			f:    "putval",
			args: []string{},
		},
		expected: shim.Error("need 2 args (key and a value)"),
	}

	putvalKeyNotFound := &testCase{
		mockStub: mockStub{
			f:    "putval",
			args: []string{"key", "value"},
		},
		expected: shim.Error(fmt.Sprintf("{\"Error\":\"Failed to get val for %s\"}", "key")),
	}
	putvalKeyNotFound.On("GetState", mock.Anything).Return(nil, errors.New("key not found"))

	putvalKeyKeyFoundButPutStateFailed := &testCase{
		mockStub: mockStub{
			f:    "putval",
			args: []string{"key", "value"},
		},
		expected: shim.Error("PutState failed"),
	}
	putvalKeyKeyFoundButPutStateFailed.On("GetState", mock.Anything).Return([]byte{}, nil)
	putvalKeyKeyFoundButPutStateFailed.On("PutState", mock.Anything).Return(errors.New("PutState failed"))

	putvalKeyKeyFoundAndPutStateSucceeded := &testCase{
		mockStub: mockStub{
			f:    "putval",
			args: []string{"key", "value"},
		},
		expected: shim.Success(nil),
	}
	putvalKeyKeyFoundAndPutStateSucceeded.On("GetState", mock.Anything).Return([]byte{}, nil)
	putvalKeyKeyFoundAndPutStateSucceeded.On("PutState", mock.Anything).Return(nil)

	getvalIncorrectArgNum := &testCase{
		mockStub: mockStub{
			f:    "getval",
			args: []string{},
		},
		expected: shim.Error("Incorrect number of arguments. Expecting key to query"),
	}

	getvalGetStateFails := &testCase{
		mockStub: mockStub{
			f:    "getval",
			args: []string{"key"},
		},
		expected: shim.Error(fmt.Sprintf("{\"Error\":\"Failed to get state for %s\"}", "key")),
	}
	getvalGetStateFails.On("GetState", mock.Anything).Return(nil, errors.New("GetState failed"))

	getvalGetStateSucceedsButNoData := &testCase{
		mockStub: mockStub{
			f:    "getval",
			args: []string{"key"},
		},
		expected: shim.Error(fmt.Sprintf("{\"Error\":\"Nil val for %s\"}", "key")),
	}
	var nilSlice []byte
	getvalGetStateSucceedsButNoData.On("GetState", mock.Anything).Return(nilSlice, nil)

	getvalGetStateSucceeds := &testCase{
		mockStub: mockStub{
			f:    "getval",
			args: []string{"key"},
		},
		expected: shim.Success([]byte("value")),
	}
	getvalGetStateSucceeds.On("GetState", mock.Anything).Return([]byte("value"), nil)

	unknownFunction := &testCase{
		mockStub: mockStub{
			f:    "default",
			args: []string{},
		},
		expected: shim.Error("{\"Error\":\"Unknown function default\"}"),
	}

	for _, tc := range []*testCase{
		putvalIncorrectArgNum,
		putvalKeyNotFound,
		putvalKeyKeyFoundButPutStateFailed,
		putvalKeyKeyFoundAndPutStateSucceeded,
		getvalIncorrectArgNum,
		getvalGetStateFails,
		getvalGetStateSucceedsButNoData,
		getvalGetStateSucceeds,
		unknownFunction,
	} {
		resp := (&SampleSysCC{}).Invoke(tc)
		assert.Equal(t, tc.expected, resp)
	}
}

type mockStub struct {
	f    string
	args []string
	mock.Mock
}

func (*mockStub) GetArgs() [][]byte {
	panic("implement me")
}

func (*mockStub) GetStringArgs() []string {
	panic("implement me")
}

func (s *mockStub) GetFunctionAndParameters() (string, []string) {
	return s.f, s.args
}

func (*mockStub) GetTxID() string {
	panic("implement me")
}

func (*mockStub) InvokeChaincode(chaincodeName string, args [][]byte, channel string) peer.Response {
	panic("implement me")
}

func (s *mockStub) GetState(key string) ([]byte, error) {
	args := s.Called(key)
	if args.Get(1) == nil {
		return args.Get(0).([]byte), nil
	}
	return nil, args.Get(1).(error)
}

func (s *mockStub) PutState(key string, value []byte) error {
	args := s.Called(key)
	if args.Get(0) == nil {
		return nil
	}
	return args.Get(0).(error)
}

func (*mockStub) DelState(key string) error {
	panic("implement me")
}

func (*mockStub) GetStateByRange(startKey, endKey string) (shim.StateQueryIteratorInterface, error) {
	panic("implement me")
}

func (*mockStub) GetStateByPartialCompositeKey(objectType string, keys []string) (shim.StateQueryIteratorInterface, error) {
	panic("implement me")
}

func (*mockStub) CreateCompositeKey(objectType string, attributes []string) (string, error) {
	panic("implement me")
}

func (*mockStub) SplitCompositeKey(compositeKey string) (string, []string, error) {
	panic("implement me")
}

func (*mockStub) GetQueryResult(query string) (shim.StateQueryIteratorInterface, error) {
	panic("implement me")
}

func (*mockStub) GetHistoryForKey(key string) (shim.HistoryQueryIteratorInterface, error) {
	panic("implement me")
}

func (*mockStub) GetCreator() ([]byte, error) {
	panic("implement me")
}

func (*mockStub) GetTransient() (map[string][]byte, error) {
	panic("implement me")
}

func (*mockStub) GetBinding() ([]byte, error) {
	panic("implement me")
}

func (*mockStub) GetSignedProposal() (*peer.SignedProposal, error) {
	panic("implement me")
}

func (*mockStub) GetArgsSlice() ([]byte, error) {
	panic("implement me")
}

func (*mockStub) GetTxTimestamp() (*timestamp.Timestamp, error) {
	panic("implement me")
}

func (*mockStub) SetEvent(name string, payload []byte) error {
	panic("implement me")
}
func (*mockStub) GetDecorations() map[string][]byte {
	panic("implement me")
}
func (stub *mockStub) GetPrivateData(collection string, key string) ([]byte, error) {
	panic("implement me")
}

func (stub *mockStub) PutPrivateData(collection string, key string, value []byte) error {
	panic("implement me")
}

func (stub *mockStub) DelPrivateData(collection string, key string) error {
	panic("implement me")
}

func (stub *mockStub) GetPrivateDataByRange(collection, startKey, endKey string) (shim.StateQueryIteratorInterface, error) {
	panic("implement me")
}

func (stub *mockStub) GetPrivateDataByPartialCompositeKey(collection, objectType string, attributes []string) (shim.StateQueryIteratorInterface, error) {
	panic("implement me")
}

func (stub *mockStub) GetPrivateDataQueryResult(collection, query string) (shim.StateQueryIteratorInterface, error) {
	panic("implement me")
}
func (stub *mockStub) GetChannelID() string {
	panic("implement me")
}


text:
/* @flow */
function foo(x?: string): string {
    if (x == null) { return 'foo'; }
    return x;
}

function bar(obj: {x?: string}): string {
    if (obj.x == null) { return 'foo'; }
    return obj.x;
}

function baz(bar?: {duck: mixed}) {
    if (!bar) { return 1; }
    return bar.duck
}

function testOptionalNullable(x?: ?string): string {
    if (x == null) { return 'foo'; }
    return x;
}

function testOptionalNullableDefault(x?: ?string = "hi"): string {
    if (x == null) { return 'foo'; }
    return x;
}

function testOptionalNullableProperty(obj: {x?: ?string}): string {
    if (obj.x == null) { return 'foo'; }
    return obj.x;
}

function testOptionalNullableFlowingToNullable(x?: ?string): ?string {
  var f = function(y: ?string) {};
  f(x);
}


text:
package org.openhubframework.openhub.core.common.version;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Class for printing version info when application starts.
 *
 * @author Petr Juza
 */
@Component
public class VersionPrinter {

    private static final Logger LOG = LoggerFactory.getLogger(VersionPrinter.class);

    @Autowired
    private VersionInfoSource versionInfoSource;

    /**
     * Application name, must correspond with {@code <name>} element from root pom.xml.
     */
    public static final String APPLICATION_NAME = "OpenHub Core";

    @PostConstruct
    public void printVersion() {
        VersionInfo filter = new VersionInfo(APPLICATION_NAME, null, null, null, null);
        final VersionInfo[] versions = versionInfoSource.getVersionInformation(filter);

        String versionStr = "N/A";
        if (versions.length > 0) {
            versionStr = versions[0].getFullVersion() + " (" + versions[0].getDate() + ")";
        }

        LOG.info("\n\nOpenHub version: " + versionStr + "\n");
    }
}


text:
package uk.co.samicemalone.libtv.matcher.tv;

import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
import uk.co.samicemalone.libtv.matcher.TVMatcher;
import uk.co.samicemalone.libtv.model.EpisodeMatch;
import uk.co.samicemalone.libtv.model.TVMatcherOptions;
import static uk.co.samicemalone.libtv.util.EpisodeTestUtil.assertEpisodeMatchEquals;

/**
 *
 * @author Sam Malone
 */
public class WordDelimitedMatcherTest {

    private final String path = "C:\\TV\\The League\\Season 1\\";

    /**
     * Test of match method, of class XDelimitedMatcher.
     */
    @Test
    public void testMatch() {
        String[] fileNames = new String[] {
            "the.league ep2 name.mkv",
            "the_league - e2 - name.mkv",
            "the_league_e02_name.mkv",
            "the.league ep02 name.mkv",
            "the.league.ep.02.name.mkv",
        };
        WordDelimitedMatcher instance = new WordDelimitedMatcher(new TVMatcherOptions());
        for(String fileName : fileNames) {
            EpisodeMatch expResult = new EpisodeMatch("The League", EpisodeMatch.NO_SEASON, 2);
            Path p = Paths.get(path, fileName);
            EpisodeMatch result = instance.match(p, TVMatcher.stripCommonTags(fileName));
            assertEpisodeMatchEquals(expResult, result);
        }
    }

    /**
     * Test of match method, of class XDelimitedMatcher.
     */
    @Test
    public void testMatchWithSeason() {
        String[] fileNames = new String[] {
            "the_league - season 1 - e2 - name.mkv",
            "the_league_season_1_e02_name.mkv",
            "the league season 1 ep 2 name.mkv",
            "the.league.season.1.ep02.name.mkv",
            "the league season 1 episode 2 name.mkv",
        };
        WordDelimitedMatcher instance = new WordDelimitedMatcher(new TVMatcherOptions());
        for(String fileName : fileNames) {
            EpisodeMatch expResult = new EpisodeMatch("The League", 1, 2);
            Path p = Paths.get(path, fileName);
            EpisodeMatch result = instance.match(p, TVMatcher.stripCommonTags(fileName));
            assertEpisodeMatchEquals(expResult, result);
        }
    }

    /**
     * Test of match method, of class XDelimitedMatcher.
     */
    @Test
    public void testMatchDouble() {
        String[] fileNames = new String[] {
            "the_league - e1e2 - name.mkv",
            "the_league_e01_e02_name.mkv",
            "the_league_e01_name_e02_name.mkv",
            "the.league ep01ep02 pilot.mkv",
            "the.league ep1ep2 pilot.mkv",
            "the_league_ep01_ep02_pilot.mkv",
            "the_league_ep1_ep2_pilot.mkv",
            "the.league.ep_01_ep_02.pilot.mkv",
            "the.league.ep_1_ep_2.pilot.mkv",
            "the.league.ep_01_name_ep_02_name.mkv",
        };
        WordDelimitedMatcher instance = new WordDelimitedMatcher(new TVMatcherOptions());
        for(String fileName : fileNames) {
            EpisodeMatch expResult = new EpisodeMatch("The League", EpisodeMatch.NO_SEASON, 1);
            expResult.addEpisodeNo(2);
            Path p = Paths.get(path, fileName);
            EpisodeMatch result = instance.match(p, TVMatcher.stripCommonTags(fileName));
            assertEpisodeMatchEquals(expResult, result);
        }
    }

    /**
     * Test of match method, of class XDelimitedMatcher.
     */
    @Test
    public void testMatchDoubleWithSeason() {
        String[] fileNames = new String[] {
            "the_league - season 1 - e2e3 - name.mkv",
            "the_league_season_1_e02_e03_name.mkv",
            "the_league_season_1_e02_name_e03_name.mkv",
            "the league season 1 ep 2 ep 3 name.mkv",
            "the league season1 ep2 ep3 name.mkv",
            "the league season1 ep2ep3 name.mkv",
            "the.league.season.1.ep02.ep03.name.mkv",
            "the league season 1 episode 2 episode 3 name.mkv",
            "the league season 01 episode 02 episode 03 name.mkv",
            "the_league_season_1_episode_02_name_episode_03_name.mkv",
            "the_league_season_1_ep_02_name_ep_03_name.mkv",
            "the league season 1 ep 2 name ep 3 name.mkv",
        };
        WordDelimitedMatcher instance = new WordDelimitedMatcher(new TVMatcherOptions());
        for(String fileName : fileNames) {
            EpisodeMatch expResult = new EpisodeMatch("The League", 1, 2);
            expResult.addEpisodeNo(3);
            Path p = Paths.get(path, fileName);
            EpisodeMatch result = instance.match(p, TVMatcher.stripCommonTags(fileName));
            assertEpisodeMatchEquals(expResult, result);
        }
    }

    /**
     * Test of match method, of class XDelimitedMatcher.
     */
    @Test
    public void testMatchQuad() {
        String[] fileNames = new String[] {
            "the_league - e1e2e3e4 - name.mkv",
            "the_league_e01_e02_e03_e04_name.mkv",
            "the_league_e01_name_e02_name_e03_name_e04_name.mkv",
            "the.league ep01ep02ep03ep04 pilot.mkv",
            "the.league ep1ep2ep3ep4 pilot.mkv",
            "the_league_ep01_ep02_ep03_ep04_pilot.mkv",
            "the_league_ep1_ep2_ep3_ep4_pilot.mkv",
            "the.league.ep_01_ep_02_ep_03_ep_04.pilot.mkv",
            "the.league.ep_01_name_ep_02_name_ep_03_name_ep_04_name.mkv",
            "the.league.ep_1_ep_2_ep_3_ep_4.pilot.mkv",
        };
        WordDelimitedMatcher instance = new WordDelimitedMatcher(new TVMatcherOptions());
        for(String fileName : fileNames) {
            EpisodeMatch expResult = new EpisodeMatch("The League", EpisodeMatch.NO_SEASON, 1);
            expResult.addEpisodeNo(2, 3, 4);
            Path p = Paths.get(path, fileName);
            EpisodeMatch result = instance.match(p, TVMatcher.stripCommonTags(fileName));
            assertEpisodeMatchEquals(expResult, result);
        }
    }

    /**
     * Test of match method, of class XDelimitedMatcher.
     */
    @Test
    public void testMatchQuadWithSeason() {
        String[] fileNames = new String[] {
            "the_league - season 1 - e2e3e4e5 - name.mkv",
            "the_league_season_1_e02_e03_e04_e05_name.mkv",
            "the_league_season_1_e02_name_e03_name_e04_name_e05_name.mkv",
            "the league season 1 ep 2 ep 3 ep 4 ep 5 name.mkv",
            "the league season1 ep2 ep3 ep4 ep5 name.mkv",
            "the league season1 ep2ep3ep4ep5 name.mkv",
            "the.league.season.1.ep02.ep03.ep04.ep05.name.mkv",
            "the league season 1 episode 2 episode 3 episode 4 episode 5 name.mkv",
            "the league season 01 episode 02 episode 03 episode 04 episode 05 name.mkv",
            "the_league_season_1_episode_02_name_episode_03_name_episode_04_name_episode_05_name.mkv",
            "the_league_season_1_ep_02_name_ep_03_name_ep_04_name_ep_05_name.mkv",
            "the league season 1 ep 2 name ep 3 name ep 4 name ep5 name.mkv",
        };
        WordDelimitedMatcher instance = new WordDelimitedMatcher(new TVMatcherOptions());
        for(String fileName : fileNames) {
            EpisodeMatch expResult = new EpisodeMatch("The League", 1, 2);
            expResult.addEpisodeNo(3, 4, 5);
            Path p = Paths.get(path, fileName);
            EpisodeMatch result = instance.match(p, TVMatcher.stripCommonTags(fileName));
            assertEpisodeMatchEquals(expResult, result);
        }
    }

}


text:
namespace GoogleARCore
{
    using System;
    using System.Runtime.InteropServices;
    using UnityEngine;

    /// <summary>
    /// Double precision vector in 4D.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct DVector4
    {
        [MarshalAs(UnmanagedType.R8)]
        public double x;
        [MarshalAs(UnmanagedType.R8)]
        public double y;
        [MarshalAs(UnmanagedType.R8)]
        public double z;
        [MarshalAs(UnmanagedType.R8)]
        public double w;

        /// <summary>
        /// Creates a new double-precision vector with given x, y, z, w components.
        /// </summary>
        /// <param name="x">The x component.</param>
        /// <param name="y">The y component.</param>
        /// <param name="z">The z component.</param>
        /// <param name="w">The w component.</param>
        public DVector4(double x, double y, double z, double w)
        {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
        }

        /// <summary>
        /// Creates a new double-precision vector with given Vector4.
        /// </summary>
        /// <param name="copy">The Vector4 to copy.</param>
        public DVector4(UnityEngine.Vector4 copy)
        {
            this.x = copy.x;
            this.y = copy.y;
            this.z = copy.z;
            this.w = copy.w;
        }

        /// <summary>
        /// Gets identity quaternion in DVector4 format.
        /// </summary>
        /// <value>Identity quaternion.</value>
        public static DVector4 IdentityQuaternion
        {
            get { return new DVector4(0.0, 0.0, 0.0, 1.0); }
        }

        /// <summary>
        /// Gets the length of this vector (Read Only).
        /// </summary>
        /// <value>The length.</value>
        public double Magnitude
        {
            get { return Math.Sqrt(SqrMagnitude); }
        }

        /// <summary>
        /// Gets the squared length of this vector (Read Only).
        /// </summary>
        /// <value>The squared length.</value>
        public double SqrMagnitude
        {
            get { return (x * x) + (y * y) + (z * z) + (w * w); }
        }

        /// <summary>
        /// Get or set x,y,z,w components (double) as 0,1,2,3 - other values throw an IndexOutOfRange exception.
        /// </summary>
        /// <param name="index">Set a component of the quaternion by int index.</param>
        /// <returns>
        /// A <see cref="System.Double"/> in the quaternion.
        /// </returns>
        public double this[int index]
        {
            get
            {
                switch (index)
                {
                    case 0:
                        return x;
                    case 1:
                        return y;
                    case 2:
                        return z;
                    case 3:
                        return w;
                    default:
                        throw new System.IndexOutOfRangeException();
                }
            }

            set
            {
                switch (index)
                {
                    case 0:
                        x = value;
                        return;
                    case 1:
                        y = value;
                        return;
                    case 2:
                        z = value;
                        return;
                    case 3:
                        w = value;
                        return;
                    default:
                        throw new System.IndexOutOfRangeException();
                }
            }
        }

        /// <summary>
        /// Returns the distance between a and b.
        /// </summary>
        /// <returns>Euclidean distance as a double.</returns>
        /// <param name="a">First vector.</param>
        /// <param name="b">Second vector.</param>
        public static double Distance(DVector4 a, DVector4 b)
        {
            return (a - b).Magnitude;
        }

        /// <summary>
        /// Dot Product of two vectors.
        /// </summary>
        /// <returns>Dot product as a double.</returns>
        /// <param name="a">First vector.</param>
        /// <param name="b">Second vector.</param>
        public static double Dot(DVector4 a, DVector4 b)
        {
            return (a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w);
        }

        /// <summary>
        /// Subtracts one vector from another.
        ///
        /// Subtracts each component of b from a.
        /// </summary>
        /// <returns>Subtraction result.</returns>
        /// <param name="a">First vector.</param>
        /// <param name="b">Second vector.</param>
        public static DVector4 operator -(DVector4 a, DVector4 b)
        {
            return new DVector4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
        }

        /// <summary>
        /// Adds two vectors.
        ///
        /// Adds corresponding components together.
        /// </summary>
        /// <returns>Addition result.</returns>
        /// <param name="a">First vector.</param>
        /// <param name="b">Second vector.</param>
        public static DVector4 operator +(DVector4 a, DVector4 b)
        {
            return new DVector4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
        }

        /// <summary>
        /// Returns a single-precision quaternion representation of this
        /// double-precision vector.
        /// </summary>
        /// <returns>A single-precision vector.</returns>
        public Quaternion ToQuaternion()
        {
            return new Quaternion((float)x, (float)y, (float)z, (float)w);
        }

        /// <summary>
        /// Overrided ToString function to formatted DVector4 string output.
        /// </summary>
        /// <returns>Formatted string of this DVector4.</returns>
        public override string ToString()
        {
            return string.Format("{0}, {1}, {2}, {3}", x, y, z, w);
        }
    }
}


text:
echo Creating new user: $3
curl -i -XPOST $5/query -u $1:$2 --data-urlencode "q=CREATE USER $3 WITH PASSWORD '$4'"


text:
<form class='dcontrols' action=''>
    <button class="drefresh"></button>
    <button class="dfilter"></button>

        {{ form.as_p }}

            <input type="submit" value="Update">
            <input type='reset' value='Reset' />

</form>


text:
import MySQLdb
import urllib
import re
import pygments.console
from BeautifulSoup import BeautifulStoneSoup
from ldaptools import LDAPTools
import json

# Load configuration
with open("config.json") as fh:
	config=json.loads(fh.read())
assert(config)

# Set up all classes

skillstripper = re.compile('.*typeid="(\d+)".* level="(\d)".*')

class SkillIndexer():
	def __init__(self, config):
		self.ldaptools = LDAPTools(config)
		self.config = config["skillindexer"]
		self.authconfig = config

	def getSkills(self, db, name, id, vCode):
		accountCharacters = "http://api.eveonline.com/account/Characters.xml.aspx"
		charSheet = "http://api.eveonline.com/char/CharacterSheet.xml.aspx"

		print "Processing %s" % name
		params = urllib.urlencode({"keyID": id, "vCode": vCode})
		f = urllib.urlopen(accountCharacters+"?"+params)
		data = f.read()
		f.close()
		soup = BeautifulStoneSoup(data)
		r = soup.findAll("row", {"name":unicode(name)})
		if len(r)==0:
			return (1, "Character not found")
		corp = r[0]["corporationname"]
		charid = r[0]["characterid"]
		params = urllib.urlencode({"keyID": id, "vCode": vCode, "characterID":charid})
		f = urllib.urlopen(charSheet+"?"+params)
		data = f.read()
		f.close()
		soup = BeautifulStoneSoup(data)
		error = soup.findAll("error")
		if len(error):
			print "Error"

		skills = str(soup.findAll("rowset", {"name": "skills"})[0]).split("\n")
		skills = map(lambda x:x.replace("</row>", ""), skills)
		skills = filter(lambda x:x.startswith("<row "), skills)
		skills = map(lambda x: skillstripper.match(x).groups(), skills)
		print len(skills)
		for t, l in skills:
			t=int(t)
			l=int(l)
			r = db.execute('INSERT INTO skills (name, typeid, level) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE level=%s', (name, t, l, l) )

	def main(self):
		#ldap
		everyone = self.ldaptools.getusers("alliance=" + self.authconfig["auth"]["alliance"])

		#database server
		db = MySQLdb.connect(self.config["server"], self.config["user"], self.config["password"], self.config["database"])
		c = db.cursor()
		c.execute('truncate skills;')
		for user in everyone:
			try:
				self.getSkills(c, user.characterName[0], user.keyID[0], user.vCode[0])
			except Exception as e:
				print e
		db.commit()

if __name__ == "__main__":
	s = SkillIndexer(config)
	s.main()


text:
from Queue import Queue
import pika
import ssl
from threading import Thread
import time

from beaver.transports.base_transport import BaseTransport
from beaver.transports.exception import TransportException

class RabbitmqTransport(BaseTransport):

    def __init__(self, beaver_config, logger=None):
        super(RabbitmqTransport, self).__init__(beaver_config, logger=logger)

        self._rabbitmq_config = {}
        config_to_store = [
            'key', 'exchange', 'username', 'password', 'host', 'port', 'vhost',
            'queue', 'queue_durable', 'ha_queue', 'exchange_type', 'exchange_durable',
            'ssl', 'ssl_key', 'ssl_cert', 'ssl_cacert', 'timeout', 'delivery_mode'
        ]

        for key in config_to_store:
            self._rabbitmq_config[key] = beaver_config.get('rabbitmq_' + key)

        self._connection = None
        self._channel = None
        self._count = 0
        self._lines = Queue()
        self._connection_ok = False
        self._thread = None
        self._is_valid = True
        self._connect()

    def _on_connection_open(self,connection):
        self._logger.debug("RabbitMQ: Connection Created")
        self._channel = connection.channel(self._on_channel_open)

    def _on_channel_open(self,unused):
        self._logger.debug("RabbitMQ: Channel Created")
        self._channel.exchange_declare(self._on_exchange_declareok,
                                       exchange=self._rabbitmq_config['exchange'],
                                       exchange_type=self._rabbitmq_config['exchange_type'],
                                       durable=self._rabbitmq_config['exchange_durable'])

    def _on_exchange_declareok(self,unused):
        self._logger.debug("RabbitMQ: Exchange Declared")
        self._channel.queue_declare(self._on_queue_declareok,
                                    queue=self._rabbitmq_config['queue'],
                                    durable=self._rabbitmq_config['queue_durable'],
                                    arguments={'x-ha-policy': 'all'} if self._rabbitmq_config['ha_queue'] else {})

    def _on_queue_declareok(self,unused):
        self._logger.debug("RabbitMQ: Queue Declared")
        self._channel.queue_bind(self._on_bindok,
                                 exchange=self._rabbitmq_config['exchange'],
                                 queue=self._rabbitmq_config['queue'],
                                 routing_key=self._rabbitmq_config['key'])

    def _on_bindok(self,unused):
        self._logger.info("RabbitMQ: Connection OK.")
        self._connection_ok = True
        self._logger.debug("RabbitMQ: Scheduling regular message transport.")
        self._connection.add_timeout(1, self._publish_message)

    def _publish_message(self):
        self._logger.debug("RabbitMQ: Looking for messages to transport...")
        while self._connection_ok and not self._lines.empty():
            line = self._lines.get()
            if self._count == 10000:
                self._logger.debug("RabbitMQ: Transport queue size: %s", self._lines.qsize())
                self._count = 0
            else:
                self._count += 1
            self._channel.basic_publish(
                exchange=self._rabbitmq_config['exchange'],
                routing_key=self._rabbitmq_config['key'],
                body=line,
                properties=pika.BasicProperties(
                    content_type='text/json',
                    delivery_mode=self._rabbitmq_config['delivery_mode']
                ))
        if self._connection_ok:
            self._logger.debug("RabbitMQ: No messages to transport. Sleeping.")
            self._connection.add_timeout(1, self._publish_message)
        else:
            self._logger.info('RabbitMQ: Message publisher stopped.')

    def _on_connection_open_error(self, non_used_connection=None, error=None):
        self._connection_ok = False
        self._logger.error('RabbitMQ: Could not open connection: %s', error)

    def _on_connection_closed(self, connection, reply_code, reply_text):
        self._connection_ok = False
        self._logger.warning('RabbitMQ: Connection closed: %s %s', reply_code, reply_text)

    def reconnect(self):
        self._logger.debug("RabbitMQ: Reconnecting...")
        self.interrupt()

        self._thread = Thread(target=self._connection_start)
        self._thread.start()
        while self._thread.is_alive() and not self._connection_ok:
            time.sleep(1)
        if self._connection_ok:
            self._is_valid = True
            self._logger.info('RabbitMQ: Reconnect successful.')
        else:
            self._logger.warning('RabbitMQ: Reconnect failed!')
            self.interrupt()

    def _connection_start(self):
        self._logger.debug("RabbitMQ: Connecting...")
        try:
            self._connection_ok = False
            self._connection = pika.adapters.SelectConnection(
                parameters=self._parameters,
                on_open_callback=self._on_connection_open,
                on_open_error_callback=self._on_connection_open_error,
                on_close_callback=self._on_connection_closed
            )
            if not self._connection.is_closed:
                self._connection.ioloop.start()
        except Exception as e:
            self._logger.error('RabbitMQ: Failed to connect: %s', e)

    def _connect(self):
        credentials = pika.PlainCredentials(
            self._rabbitmq_config['username'],
            self._rabbitmq_config['password']
        )
        ssl_options = {
            'keyfile': self._rabbitmq_config['ssl_key'],
            'certfile': self._rabbitmq_config['ssl_cert'],
            'ca_certs': self._rabbitmq_config['ssl_cacert'],
            'ssl_version': ssl.PROTOCOL_TLSv1
        }
        self._parameters = pika.connection.ConnectionParameters(
            credentials=credentials,
            host=self._rabbitmq_config['host'],
            port=self._rabbitmq_config['port'],
            ssl=self._rabbitmq_config['ssl'],
            ssl_options=ssl_options,
            virtual_host=self._rabbitmq_config['vhost'],
            socket_timeout=self._rabbitmq_config['timeout']
        )
        self._thread = Thread(target=self._connection_start)
        self._thread.start()

    def callback(self, filename, lines, **kwargs):
        if not self._connection_ok:
            raise TransportException('RabbitMQ: Not connected or connection not OK')
        timestamp = self.get_timestamp(**kwargs)
        if kwargs.get('timestamp', False):
            del kwargs['timestamp']
        for line in lines:
            try:
                import warnings
                with warnings.catch_warnings():
                    warnings.simplefilter('error')
                    body = self.format(filename, line, timestamp, **kwargs)
                    self._lines.put(body)
            except UserWarning:
                raise TransportException('Connection appears to have been lost')
            except Exception as e:
                try:
                    raise TransportException(e.strerror)
                except AttributeError:
                    raise TransportException('Unspecified exception encountered')

    def interrupt(self):
        self._connection_ok = False
        if self._connection:
            self._connection.close()
            self._connection = None
        if self._thread:
            self._thread.join()
            self._thread = None

    def unhandled(self):
        return True


text:
<?php
if(isset($_GET['url'])) {
  $pincount = json_decode( file_get_contents( 'http://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url='.$_GET['url'] ) );
  echo isset($pincount->count)?intval($pincount->count):0;
} else {
  echo 'not set';
}
?>


text:
    <md-content class="messages-content">

        <messages-section theme="md-accent" title="New Orders" messages="vm.messages"></messages-section>
        <messages-section theme="md-primary" title="Delivered" messages="vm.messages"></messages-section>
        <messages-section theme="md-warn" title="Problems reported" messages="vm.messages"></messages-section>

        <md-divider></md-divider>
    </md-content>


text:
@implementation MLDrawing

- (id)initWithFrame:(CGRect)frame andDiameter:(double)dmeter andLineWidth:(double)lWidth andColor:(UIColor *)color
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        diameter = dmeter;
        lineWidth = lWidth;
        colorRef = color;

        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    const float* colors = CGColorGetComponents(colorRef.CGColor);

    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(contextRef, 2.0);
    CGContextSetRGBFillColor(contextRef, colors[0], colors[1], colors[2], colors[3]);
    CGRect circlePoint = (CGRectMake(0, 0, diameter, diameter));
    CGContextFillEllipseInRect(contextRef, circlePoint);

}

@end


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ProfessionalsComponent, ProfessionalComponent } from './index';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { InfiniteScrollModule } from 'angular2-infinite-scroll/angular2-infinite-scroll';

@NgModule({
    declarations: [
        ProfessionalsComponent,
        ProfessionalComponent
    ],
    imports: [
        FormsModule,
        BrowserModule,
        RouterModule,
        InfiniteScrollModule,
        HttpModule
    ],
    exports: [
        ProfessionalsComponent,
        ProfessionalComponent
    ],
    providers: [
    ]
})
export class ProfessionalsModule {
}


text:
package com.evolveum.midpoint.web.page.admin.server.handlers;

import com.evolveum.midpoint.web.component.data.column.LinkIconPanel;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.page.admin.server.PageTaskEdit;
import com.evolveum.midpoint.web.page.admin.server.handlers.dto.LiveSyncHandlerDto;
import com.evolveum.midpoint.web.page.admin.server.handlers.dto.ResourceRelatedHandlerDto;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

/**
 * @author mederly
 */
public class LiveSyncHandlerPanel extends ResourceRelatedHandlerPanel<LiveSyncHandlerDto> {

    private static final long serialVersionUID = 1L;

    private static final String ID_TOKEN_CONTAINER = "tokenContainer";
    private static final String ID_TOKEN = "token";
    private static final String ID_DELETE_TOKEN = "deleteToken";

        private static final String ID_TOKEN_RETRY_CONTAINER = "retryUnhandledErrContainer";
    private static final String ID_TOKEN_RETRY_CHECKBOX_CONTAINER = "retryUnhandledErrCheckboxContainer";
    private static final String ID_TOKEN_RETRY_CHECKBOX = "retryUnhandledErrCheckbox";

    public LiveSyncHandlerPanel(String id, IModel<LiveSyncHandlerDto> handlerDtoModel, PageTaskEdit parentPage) {
        super(id, handlerDtoModel, parentPage);
        initLayout(parentPage);
    }

    private void initLayout(final PageTaskEdit parentPage) {
        WebMarkupContainer tokenContainer = new WebMarkupContainer(ID_TOKEN_CONTAINER);
        tokenContainer.add(new VisibleEnableBehaviour() {
            @Override
            public boolean isVisible() {
                return true;    //TODO
            }
        });
        tokenContainer.add(new Label(ID_TOKEN, new PropertyModel<>(getModel(), LiveSyncHandlerDto.F_TOKEN)));

        LinkIconPanel deleteTokenPanel = new LinkIconPanel(ID_DELETE_TOKEN, new Model("fa fa-fw fa-trash-o fa-lg text-danger"), createStringResource("LiveSyncHandlerPanel.deleteToken")) {
            @Override
            protected void onClickPerformed(AjaxRequestTarget target) {
                parentPage.getController().deleteSyncTokenPerformed(target);
            }
        };
        deleteTokenPanel.add(new VisibleEnableBehaviour() {
            @Override
            public boolean isVisible() {
                return !parentPage.isEdit() && getModelObject().hasToken();        // TODO ... and security
            }
        });
        deleteTokenPanel.setRenderBodyOnly(true);
        tokenContainer.add(deleteTokenPanel);
        add(tokenContainer);

                WebMarkupContainer retryContainer = new WebMarkupContainer(ID_TOKEN_RETRY_CONTAINER);
        add(retryContainer);
        WebMarkupContainer retryCheckboxContainer = new WebMarkupContainer(ID_TOKEN_RETRY_CHECKBOX_CONTAINER);
        retryContainer.add(retryCheckboxContainer);
        CheckBox retryCheckbox = new CheckBox(ID_TOKEN_RETRY_CHECKBOX, new PropertyModel<>(getModel(), ResourceRelatedHandlerDto.F_TOKEN_RETRY_UNHANDLED_ERR));
        retryCheckbox.add(enabledIfEdit);
        retryCheckboxContainer.add(retryCheckbox);
    }

}


text:
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;

namespace FluentMigrator.Runner.Processors
{
#pragma warning disable 612
    public abstract class DbFactoryBase : IDbFactory
#pragma warning restore 612
    {
        private readonly object _lock = new object();
        private volatile DbProviderFactory _factory;

        protected DbFactoryBase(DbProviderFactory factory)
        {
            _factory = factory;
        }

        protected DbFactoryBase()
        {
        }

        /// <summary>
        /// Gets the DB provider factory
        /// </summary>
        public virtual DbProviderFactory Factory
        {
            get
            {
                if (_factory == null)
                {
                    lock (_lock)
                    {
                        if (_factory == null)
                        {
                            _factory = CreateFactory();
                        }
                    }
                }
                return _factory;
            }
        }

        protected abstract DbProviderFactory CreateFactory();

        [Obsolete]
        public IDbConnection CreateConnection(string connectionString)
        {
            var connection = Factory.CreateConnection();
            Debug.Assert(connection != null, nameof(connection) + " != null");
            connection.ConnectionString = connectionString;
            return connection;
        }

        [Obsolete]
        public virtual IDbCommand CreateCommand(string commandText, IDbConnection connection, IDbTransaction transaction, IMigrationProcessorOptions options)
        {
            var command = connection.CreateCommand();
            command.CommandText = commandText;
            if (options?.Timeout != null) command.CommandTimeout = options.Timeout.Value;
            if (transaction != null) command.Transaction = transaction;
            return command;
        }
    }
}


text:
"""Test the Z-Wave JS update entities."""
import asyncio
from datetime import timedelta

import pytest
from zwave_js_server.event import Event
from zwave_js_server.exceptions import FailedZWaveCommand
from zwave_js_server.model.firmware import FirmwareUpdateStatus

from homeassistant.components.update import (
    ATTR_AUTO_UPDATE,
    ATTR_IN_PROGRESS,
    ATTR_INSTALLED_VERSION,
    ATTR_LATEST_VERSION,
    ATTR_RELEASE_URL,
    ATTR_SKIPPED_VERSION,
    DOMAIN as UPDATE_DOMAIN,
    SERVICE_INSTALL,
    SERVICE_SKIP,
)
from homeassistant.components.zwave_js.const import DOMAIN, SERVICE_REFRESH_VALUE
from homeassistant.components.zwave_js.helpers import get_valueless_base_unique_id
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_registry import async_get
from homeassistant.util import dt as dt_util

from tests.common import MockConfigEntry, async_fire_time_changed

UPDATE_ENTITY = "update.z_wave_thermostat_firmware"
FIRMWARE_UPDATES = {
    "updates": [
        {
            "version": "10.11.1",
            "changelog": "blah 1",
            "files": [
                {"target": 0, "url": "https://example1.com", "integrity": "sha1"}
            ],
        },
        {
            "version": "11.2.4",
            "changelog": "blah 2",
            "files": [
                {"target": 0, "url": "https://example2.com", "integrity": "sha2"}
            ],
        },
        {
            "version": "11.1.5",
            "changelog": "blah 3",
            "files": [
                {"target": 0, "url": "https://example3.com", "integrity": "sha3"}
            ],
        },
    ]
}

FIRMWARE_UPDATE_MULTIPLE_FILES = {
    "updates": [
        {
            "version": "11.2.4",
            "changelog": "blah 2",
            "files": [
                {"target": 0, "url": "https://example2.com", "integrity": "sha2"},
                {"target": 1, "url": "https://example4.com", "integrity": "sha4"},
            ],
        },
    ]
}

async def test_update_entity_states(
    hass,
    client,
    climate_radio_thermostat_ct100_plus_different_endpoints,
    controller_node,
    integration,
    caplog,
    hass_ws_client,
):
    """Test update entity states."""
    ws_client = await hass_ws_client(hass)

    assert hass.states.get(UPDATE_ENTITY).state == STATE_OFF

    client.async_send_command.return_value = {"updates": []}

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_OFF

    await ws_client.send_json(
        {
            "id": 1,
            "type": "update/release_notes",
            "entity_id": UPDATE_ENTITY,
        }
    )
    result = await ws_client.receive_json()
    assert result["result"] is None

    client.async_send_command.return_value = FIRMWARE_UPDATES

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=2))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_ON
    attrs = state.attributes
    assert not attrs[ATTR_AUTO_UPDATE]
    assert attrs[ATTR_INSTALLED_VERSION] == "10.7"
    assert not attrs[ATTR_IN_PROGRESS]
    assert attrs[ATTR_LATEST_VERSION] == "11.2.4"
    assert attrs[ATTR_RELEASE_URL] is None

    await ws_client.send_json(
        {
            "id": 2,
            "type": "update/release_notes",
            "entity_id": UPDATE_ENTITY,
        }
    )
    result = await ws_client.receive_json()
    assert result["result"] == "blah 2"

    # Refresh value should not be supported by this entity
    await hass.services.async_call(
        DOMAIN,
        SERVICE_REFRESH_VALUE,
        {
            ATTR_ENTITY_ID: UPDATE_ENTITY,
        },
        blocking=True,
    )

    assert "There is no value to refresh for this entity" in caplog.text

    # Assert a node firmware update entity is not created for the controller
    driver = client.driver
    node = driver.controller.nodes[1]
    assert node.is_controller_node
    assert (
        async_get(hass).async_get_entity_id(
            DOMAIN,
            "sensor",
            f"{get_valueless_base_unique_id(driver, node)}.firmware_update",
        )
        is None
    )

    client.async_send_command.reset_mock()

async def test_update_entity_install_raises(
    hass,
    client,
    climate_radio_thermostat_ct100_plus_different_endpoints,
    integration,
):
    """Test update entity install raises exception."""
    client.async_send_command.return_value = FIRMWARE_UPDATES

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    # Test failed installation by driver
    client.async_send_command.side_effect = FailedZWaveCommand("test", 12, "test")

    with pytest.raises(HomeAssistantError):
        await hass.services.async_call(
            UPDATE_DOMAIN,
            SERVICE_INSTALL,
            {
                ATTR_ENTITY_ID: UPDATE_ENTITY,
            },
            blocking=True,
        )

async def test_update_entity_sleep(
    hass,
    client,
    zen_31,
    integration,
):
    """Test update occurs when device is asleep after it wakes up."""
    event = Event(
        "sleep",
        data={"source": "node", "event": "sleep", "nodeId": zen_31.node_id},
    )
    zen_31.receive_event(event)
    client.async_send_command.reset_mock()

    client.async_send_command.return_value = FIRMWARE_UPDATES

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    # Because node is asleep we shouldn't attempt to check for firmware updates
    assert len(client.async_send_command.call_args_list) == 0

    event = Event(
        "wake up",
        data={"source": "node", "event": "wake up", "nodeId": zen_31.node_id},
    )
    zen_31.receive_event(event)
    await hass.async_block_till_done()

    # Now that the node is up we can check for updates
    assert len(client.async_send_command.call_args_list) > 0

    args = client.async_send_command.call_args_list[0][0][0]
    assert args["command"] == "controller.get_available_firmware_updates"
    assert args["nodeId"] == zen_31.node_id

async def test_update_entity_dead(
    hass,
    client,
    zen_31,
    integration,
):
    """Test update occurs when device is dead after it becomes alive."""
    event = Event(
        "dead",
        data={"source": "node", "event": "dead", "nodeId": zen_31.node_id},
    )
    zen_31.receive_event(event)
    client.async_send_command.reset_mock()

    client.async_send_command.return_value = FIRMWARE_UPDATES

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    # Because node is asleep we shouldn't attempt to check for firmware updates
    assert len(client.async_send_command.call_args_list) == 0

    event = Event(
        "alive",
        data={"source": "node", "event": "alive", "nodeId": zen_31.node_id},
    )
    zen_31.receive_event(event)
    await hass.async_block_till_done()

    # Now that the node is up we can check for updates
    assert len(client.async_send_command.call_args_list) > 0

    args = client.async_send_command.call_args_list[0][0][0]
    assert args["command"] == "controller.get_available_firmware_updates"
    assert args["nodeId"] == zen_31.node_id

async def test_update_entity_ha_not_running(
    hass,
    client,
    zen_31,
    hass_ws_client,
):
    """Test update occurs after HA starts."""
    await hass.async_stop()

    entry = MockConfigEntry(domain="zwave_js", data={"url": "ws://test.org"})
    entry.add_to_hass(hass)
    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    assert len(client.async_send_command.call_args_list) == 0

    await hass.async_start()

    assert len(client.async_send_command.call_args_list) == 1
    args = client.async_send_command.call_args_list[0][0][0]
    assert args["command"] == "controller.get_available_firmware_updates"
    assert args["nodeId"] == zen_31.node_id

async def test_update_entity_update_failure(
    hass,
    client,
    climate_radio_thermostat_ct100_plus_different_endpoints,
    integration,
):
    """Test update entity update failed."""
    assert len(client.async_send_command.call_args_list) == 0
    client.async_send_command.side_effect = FailedZWaveCommand("test", 260, "test")

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_OFF
    assert len(client.async_send_command.call_args_list) == 1
    args = client.async_send_command.call_args_list[0][0][0]
    assert args["command"] == "controller.get_available_firmware_updates"
    assert (
        args["nodeId"]
        == climate_radio_thermostat_ct100_plus_different_endpoints.node_id
    )

async def test_update_entity_progress(
    hass,
    client,
    climate_radio_thermostat_ct100_plus_different_endpoints,
    integration,
):
    """Test update entity progress."""
    node = climate_radio_thermostat_ct100_plus_different_endpoints
    client.async_send_command.return_value = FIRMWARE_UPDATES

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_ON
    attrs = state.attributes
    assert attrs[ATTR_INSTALLED_VERSION] == "10.7"
    assert attrs[ATTR_LATEST_VERSION] == "11.2.4"

    client.async_send_command.reset_mock()
    client.async_send_command.return_value = {"success": False}

    # Test successful install call without a version
    install_task = hass.async_create_task(
        hass.services.async_call(
            UPDATE_DOMAIN,
            SERVICE_INSTALL,
            {
                ATTR_ENTITY_ID: UPDATE_ENTITY,
            },
            blocking=True,
        )
    )

    # Sleep so that task starts
    await asyncio.sleep(0.1)

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    attrs = state.attributes
    assert attrs[ATTR_IN_PROGRESS] is True

    event = Event(
        type="firmware update progress",
        data={
            "source": "node",
            "event": "firmware update progress",
            "nodeId": node.node_id,
            "progress": {
                "currentFile": 1,
                "totalFiles": 1,
                "sentFragments": 1,
                "totalFragments": 20,
                "progress": 5.0,
            },
        },
    )
    node.receive_event(event)

    # Validate that the progress is updated
    state = hass.states.get(UPDATE_ENTITY)
    assert state
    attrs = state.attributes
    assert attrs[ATTR_IN_PROGRESS] == 5

    event = Event(
        type="firmware update finished",
        data={
            "source": "node",
            "event": "firmware update finished",
            "nodeId": node.node_id,
            "result": {
                "status": FirmwareUpdateStatus.OK_NO_RESTART,
                "success": True,
                "reInterview": False,
            },
        },
    )

    node.receive_event(event)
    await hass.async_block_till_done()

    # Validate that progress is reset and entity reflects new version
    state = hass.states.get(UPDATE_ENTITY)
    assert state
    attrs = state.attributes
    assert attrs[ATTR_IN_PROGRESS] is False
    assert attrs[ATTR_INSTALLED_VERSION] == "11.2.4"
    assert attrs[ATTR_LATEST_VERSION] == "11.2.4"
    assert state.state == STATE_OFF

    await install_task

async def test_update_entity_install_failed(
    hass,
    client,
    climate_radio_thermostat_ct100_plus_different_endpoints,
    integration,
    caplog,
):
    """Test update entity install returns error status."""
    node = climate_radio_thermostat_ct100_plus_different_endpoints
    client.async_send_command.return_value = FIRMWARE_UPDATES

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_ON
    attrs = state.attributes
    assert attrs[ATTR_INSTALLED_VERSION] == "10.7"
    assert attrs[ATTR_LATEST_VERSION] == "11.2.4"

    client.async_send_command.reset_mock()
    client.async_send_command.return_value = {"success": False}

    # Test install call - we expect it to finish fail
    install_task = hass.async_create_task(
        hass.services.async_call(
            UPDATE_DOMAIN,
            SERVICE_INSTALL,
            {
                ATTR_ENTITY_ID: UPDATE_ENTITY,
            },
            blocking=True,
        )
    )

    # Sleep so that task starts
    await asyncio.sleep(0.1)

    event = Event(
        type="firmware update progress",
        data={
            "source": "node",
            "event": "firmware update progress",
            "nodeId": node.node_id,
            "progress": {
                "currentFile": 1,
                "totalFiles": 1,
                "sentFragments": 1,
                "totalFragments": 20,
                "progress": 5.0,
            },
        },
    )
    node.receive_event(event)

    # Validate that the progress is updated
    state = hass.states.get(UPDATE_ENTITY)
    assert state
    attrs = state.attributes
    assert attrs[ATTR_IN_PROGRESS] == 5

    event = Event(
        type="firmware update finished",
        data={
            "source": "node",
            "event": "firmware update finished",
            "nodeId": node.node_id,
            "result": {
                "status": FirmwareUpdateStatus.ERROR_TIMEOUT,
                "success": False,
                "reInterview": False,
            },
        },
    )

    node.receive_event(event)
    await hass.async_block_till_done()

    # Validate that progress is reset and entity reflects old version
    state = hass.states.get(UPDATE_ENTITY)
    assert state
    attrs = state.attributes
    assert attrs[ATTR_IN_PROGRESS] is False
    assert attrs[ATTR_INSTALLED_VERSION] == "10.7"
    assert attrs[ATTR_LATEST_VERSION] == "11.2.4"
    assert state.state == STATE_ON

    # validate that the install task failed
    with pytest.raises(HomeAssistantError):
        await install_task

async def test_update_entity_reload(
    hass,
    client,
    climate_radio_thermostat_ct100_plus_different_endpoints,
    integration,
):
    """Test update entity maintains state after reload."""
    assert hass.states.get(UPDATE_ENTITY).state == STATE_OFF

    client.async_send_command.return_value = {"updates": []}

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=1))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_OFF

    client.async_send_command.return_value = FIRMWARE_UPDATES

    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=2))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_ON
    attrs = state.attributes
    assert not attrs[ATTR_AUTO_UPDATE]
    assert attrs[ATTR_INSTALLED_VERSION] == "10.7"
    assert not attrs[ATTR_IN_PROGRESS]
    assert attrs[ATTR_LATEST_VERSION] == "11.2.4"
    assert attrs[ATTR_RELEASE_URL] is None

    await hass.services.async_call(
        UPDATE_DOMAIN,
        SERVICE_SKIP,
        {
            ATTR_ENTITY_ID: UPDATE_ENTITY,
        },
        blocking=True,
    )

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_OFF
    assert state.attributes[ATTR_SKIPPED_VERSION] == "11.2.4"

    await hass.config_entries.async_reload(integration.entry_id)
    await hass.async_block_till_done()

    # Trigger another update and make sure the skipped version is still skipped
    async_fire_time_changed(hass, dt_util.utcnow() + timedelta(days=4))
    await hass.async_block_till_done()

    state = hass.states.get(UPDATE_ENTITY)
    assert state
    assert state.state == STATE_OFF
    assert state.attributes[ATTR_SKIPPED_VERSION] == "11.2.4"


text:
<?php

namespace Lib\Router;

use Symfony\Component\HttpFoundation\Response;

use Lib\Request\RequestSecurity,
    Lib\Router\RouterUtils,
    Lib\Router\RouteParser,
    Lib\File\Resource as FileResource,
    Lib\Router\Exception\NotFoundException,
    Lib\Event\Dispatcher\RouteFoundDispatcher,
    Lib\Event\Dispatcher\ControllerCompleteDispatcher;

class Router implements RoutingInterface
{
    /**
     * Event Dispatcher
     * @var EventDispatcher
     */
    private $dispatcher;

    /**
     * Symfony's Request object (already checked)
     * @var Request
     */
    private $request;

    /**
     * Symfony's Response object (already checked)
     * @var Response
     */
    private $response;

    /**
     * The configuration
     * @var StdClass
     */
    private $config;

    /**
     * The current URL
     */
    private $url;

    /**
     * Injector
     */
    private $injector;

    /**
     * Constructor.
     *
     * @param Request  $request
     * @param Response $response
     * @param StdClass $config
     */
    public function __construct($dispatcher,$request,$response,$config,$dependencyInjector)
    {
        $this->processVariables($dispatcher,$request,$response,$config,$dependencyInjector);
    }

    /**
     * Variable procession
     *
     * @param Request  $request
     * @param Response $response
     * @param StdClass $config
     */
    public function processVariables($dispatcher,$request,$response,$config,$dependencyInjector)
    {
        $this->dispatcher = $dispatcher;
        $this->request = $request;
        $this->response = $response;
        $this->config = $config;
        $this->injector = $dependencyInjector;
    }

    /**
     * main routing function. Manages the routing
     *
     * /bla/bla/bla to /src/Core/Controller/AbcController.php
     *
     * @see \Lib\Router\RoutingInterface::route()
     */
    public function route()
    {
        $utils = new RouterUtils("/");
        $parser = new RouteParser(new FileResource($this->config->router->global_router));
        $parsed = $parser->parse();
        $found = false;
        $result = new \stdClass();
        foreach ($parsed as $name => $route) {
            $this->url = $utils->cutWebRoot(
                        $utils->getRequestPath(
                                $this->request->getRequestUri()
                        ),
                        $this->config->web->root
                    );

            $route->match = preg_replace("#\{\w+\}#i","(\w+|\_|\_+|\-|\-+|\+|\++|\%|\%+)",$route->match);

            if (preg_match("#^{$route->match}$#",$this->url)) {
                if (in_array($this->request->getMethod(),(array) $route->via)) {
                    $routeFoundDispatcher = new RouteFoundDispatcher($name,$route);
                    $this->dispatcher->dispatch("route.found",$routeFoundDispatcher);
                    $found = true;
                    break;
                }
            }
        }
        if ($found === false) {
            $this->dispatcher->dispatch("route.notfound");
        }
    }

    /**
     * The same as route() but solves AbcController.php to /bla/bla/bla
     *
     * @see \Lib\Router\RoutingInterface::reverseRoute()
     */
    public function reverseRoute()
    {
        //print_r();
    }

    /**
     * processes the request
     *
     */
    public function process()
    {
        $utils = new RouterUtils("/");
        if((strpos($utils->cutWebRoot($utils->getRequestPath($this->request->getRequestUri()),$this->config->web->root),
                ".".$this->config->general->phpext) === false) && $this->request->get('format') !== $this->config->general->phpext){
             $this->route();
        } else {
             $this->reverseRoute();
        }

    }

    public function returnResponse(Response $response)
    {
        $response->send();
    }
}


text:
package aurora;

import java.io.IOException;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import jssc.SerialPortException;

@org.springframework.stereotype.Controller
public class WeatherController {

  @RequestMapping(value = "/weather", method = RequestMethod.GET)
  public String getWeather(Model model) throws IOException, SerialPortException {
    model.addAttribute("weather", new WeatherWrapper(100, 0));

    return "weather";
  }

  @RequestMapping(value = "/weather", method = RequestMethod.POST)
  public String weatherSubmit(@ModelAttribute WeatherWrapper weather, Model model) throws IOException, SerialPortException {
    try {
      DeviceCommunication deviceCommunication = new DeviceCommunication();
      deviceCommunication.setWeatherType(new WeatherTypeWrapper(weather.getWeatherType()));
      deviceCommunication.setTemperature(new TemperatureWrapper(weather.getTemperature()));
      model.addAttribute("status", "Success!");
    } catch (Exception ex) {
      model.addAttribute("status", ex.getMessage());
    }

    model.addAttribute("weather", weather);

    return "weather";
  }
}


text:
package libvirt

import (
	"os"
	"testing"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/terraform"
)

var testAccProviders map[string]terraform.ResourceProvider
var testAccProvider *schema.Provider

func init() {
	testAccProvider = Provider().(*schema.Provider)
	testAccProviders = map[string]terraform.ResourceProvider{
		"libvirt": testAccProvider,
	}
}

func TestProvider(t *testing.T) {
	if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
		t.Fatalf("err: %s", err)
	}
}

func TestProvider_impl(t *testing.T) {
	var _ terraform.ResourceProvider = Provider()
}

func testAccPreCheck(t *testing.T) {
	if v := os.Getenv("LIBVIRT_DEFAULT_URI"); v == "" {
		t.Fatal("LIBVIRT_DEFAULT_URI must be set for acceptance tests")
	}
}