text:
Following the success of our simple [WunderBar-sensors-based weather station](https://github.com/relayr/blog/tree/master/weatherstation_part1), we wanted to give the option to obtain additional readings from the surrounding environment and take our little weather station to new heights.

In this stage of the weather station we provide the option of connecting external sensors via the Particle.io [Photon](https://docs.particle.io/guide/getting-started/intro/photon/)

This stage includes two tutorials, one for a [webpage](https://github.com/relayr/blog/tree/master/weatherstation_part2/webpage), essentially the dashboard which displays the data and another for  the [hardware](https://github.com/relayr/blog/tree/master/weatherstation_part2/hardwarecode)- which explains how to connect the Grove sensors to the Photon and then define the newly created device as a prototype on the relayr platform.

In our example we've added three additional sensors:

5. A [Gas sensor](http://www.seeedstudio.com/wiki/Grove_-_Gas_Sensor)
6. A [UV Sensor](http://www.seeedstudio.com/wiki/Grove_-_UV_Sensor)
7. A [Barometer](http://www.seeedstudio.com/wiki/Grove_-_Barometer_Sensor)

You are more than welcome to extend this project even further and add other sensors as you see fit.

redpajama_set_name: RedPajamaGithub


text:
package org.apache.catalina.startup;

import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.util.ServerInfo;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;

/**
 * Logs version information on startup.
 */
public class VersionLoggerListener implements LifecycleListener {

    private static final Log log = LogFactory.getLog(VersionLoggerListener.class);

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(Constants.Package);

    private boolean logArgs = true;
    private boolean logEnv = false;

    public boolean getLogArgs() {
        return logArgs;
    }

    public void setLogArgs(boolean logArgs) {
        this.logArgs = logArgs;
    }

    public boolean getLogEnv() {
        return logEnv;
    }

    public void setLogEnv(boolean logEnv) {
        this.logEnv = logEnv;
    }

    @Override
    public void lifecycleEvent(LifecycleEvent event) {
        if (Lifecycle.BEFORE_INIT_EVENT.equals(event.getType())) {
            log();
        }
    }

    private void log() {
        log.info(sm.getString("versionLoggerListener.serverInfo.server.version",
                ServerInfo.getServerInfo()));
        log.info(sm.getString("versionLoggerListener.serverInfo.server.built",
                ServerInfo.getServerBuilt()));
        log.info(sm.getString("versionLoggerListener.serverInfo.server.number",
                ServerInfo.getServerNumber()));
        log.info(sm.getString("versionLoggerListener.os.name",
                System.getProperty("os.name")));
        log.info(sm.getString("versionLoggerListener.os.version",
                System.getProperty("os.version")));
        log.info(sm.getString("versionLoggerListener.os.arch",
                System.getProperty("os.arch")));
        log.info(sm.getString("versionLoggerListener.java.home",
                System.getProperty("java.home")));
        log.info(sm.getString("versionLoggerListener.vm.version",
                System.getProperty("java.runtime.version")));
        log.info(sm.getString("versionLoggerListener.vm.vendor",
                System.getProperty("java.vm.vendor")));
        log.info(sm.getString("versionLoggerListener.catalina.base",
                System.getProperty("catalina.base")));
        log.info(sm.getString("versionLoggerListener.catalina.home",
                System.getProperty("catalina.home")));

        if (logArgs) {
            List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments();
            for (String arg : args) {
                log.info(sm.getString("versionLoggerListener.arg", arg));
            }
        }

        if (logEnv) {
            Map<String,String> envs = System.getenv();
            SortedSet<String> keys = new TreeSet<String>(envs.keySet());
            for (String key : keys) {
                log.info(sm.getString("versionLoggerListener.env", key, envs.get(key)));
            }
        }
    }
}


text:
/* Example from https://www.w3.org/TR/CSS2/syndata.html#rule-sets */
q[example="public class foo\
{\
    private int x;\
\
    foo(int x) {\
        this.x = x;\
    }\
\
}"] { color: red }

/* A pseudo selector with essential whitespace wrapped in quotes. */
q[style*="quotes: none"] {
    quotes: none;
}

q[style*='quotes: none'] {
    quotes: none;
}

q:after {
    content: ": colon & escaped double \" quotes \".";
}

q:after {
    content: ' (brackets & escaped single \' quotes \') ';
}

q:after {
    content: "I'm Quote";
}


text:
@interface OSPMapCSSUnaryTest : OSPMapCSSTest

@property (readwrite, assign, getter=isNegated) BOOL negated;
@property (readwrite, strong) NSString *tagName;

- (id)initWithTagName:(NSString *)tagName negated:(BOOL)negated;

@end


text:
> Unicode symbols with Windows CMD fallbacks

[![](screenshot.png)](index.js)

[*and more...*](index.js)

Windows CMD only supports a [limited character set](http://en.wikipedia.org/wiki/Code_page_437).

## Install

```
$ npm install --save figures
```

## Usage

See the [source](index.js) for supported symbols.

```js
var figures = require('figures');

console.log(figures.tick);
// On real OSes:  ✔
// On Windows:    √
```

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)


text:
<?php

abstract class AbstractHTTPHandler
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function GetName()
    {
        return $this->name;
    }

    public abstract function Render(Renderer $renderer);
}


text:
<?xml version="1.0"?>
<package>
  <name>strands_karl</name>
  <version>0.0.0</version>
  <description>The strands_karl package</description>

  <maintainer email="beyer@vision.rwth-aachen.de">Lucas Beyer</maintainer>

  <license>MIT</license>

  <buildtool_depend>catkin</buildtool_depend>
  <!-- From `karl_robot.launch` -->
  <run_depend>scitos_mira</run_depend>
  <run_depend>sicks300</run_depend>
  <run_depend>flir_pantilt_d46</run_depend>
  <run_depend>diagnostic_aggregator</run_depend>
  <run_depend>scitos_description</run_depend>
  <run_depend>scitos_cmd_vel_mux</run_depend>
  <run_depend>scitos_teleop</run_depend>

  <!-- From `karl_cams.launch` -->
  <run_depend>openni_wrapper</run_depend>

  <!-- From `karl_navigation.launch` -->
  <run_depend>strands_recovery_behaviours</run_depend>
  <run_depend>strands_bringup</run_depend>

  <!-- For the marathon routines. -->
  <run_depend>strands_executive_msgs</run_depend>
  <run_depend>scitos_msgs</run_depend>
  <run_depend>std_srvs</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>strands_navigation_msgs</run_depend>
  <run_depend>dynamic_reconfigure</run_depend>
  <run_depend>task_executor</run_depend>
  <run_depend>mongodb_store</run_depend>
</package>


text:
//
// Copyright (C) 2014 OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//

#include "inet/common/geometry/shape/polyhedron/PolyhedronEdge.h"

namespace inet {

PolyhedronPoint PolyhedronEdge::getEdgeVector() const
{
    return *point2 - *point1;
}

bool PolyhedronEdge::operator ==(const PolyhedronEdge& rhs) const
{
    return (point1 == rhs.point1 && point2 == rhs.point2) ||
           (point1 == rhs.point2 && point2 == rhs.point1);
}

} /* namespace inet */


text:
package com.netflix.curator.framework.recipes.cache;

import com.google.common.io.Closeables;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.retry.RetryOneTime;
import com.netflix.curator.test.InstanceSpec;
import com.netflix.curator.test.TestingCluster;
import com.netflix.curator.test.Timing;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class TestPathChildrenCacheInCluster
{
    @Test
    public void     testServerLoss() throws Exception
    {
        Timing                  timing = new Timing();

        CuratorFramework client = null;
        PathChildrenCache cache = null;
        TestingCluster cluster = new TestingCluster(3);
        try
        {
            cluster.start();

            client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
            client.start();
            client.create().creatingParentsIfNeeded().forPath("/test");

            cache = new PathChildrenCache(client, "/test", false);
            cache.start();

            final CountDownLatch                    resetLatch = new CountDownLatch(1);
            final CountDownLatch                    reconnectLatch = new CountDownLatch(1);
            final AtomicReference<CountDownLatch>   latch = new AtomicReference<CountDownLatch>(new CountDownLatch(3));
            cache.getListenable().addListener
                (
                    new PathChildrenCacheListener()
                    {
                        @Override
                        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
                        {
                            if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED )
                            {
                                resetLatch.countDown();
                            }
                            else if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED )
                            {
                                reconnectLatch.countDown();
                            }
                            else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED )
                            {
                                latch.get().countDown();
                            }
                        }
                    }
                );

            client.create().forPath("/test/one");
            client.create().forPath("/test/two");
            client.create().forPath("/test/three");

            Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS));

            InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper());
            cluster.killServer(connectionInstance);

            Assert.assertTrue(timing.awaitLatch(reconnectLatch));

            Assert.assertEquals(cache.getCurrentData().size(), 3);
        }
        finally
        {
            Closeables.closeQuietly(cache);
            Closeables.closeQuietly(client);
            Closeables.closeQuietly(cluster);
        }
    }
}


text:
package org.elasticsearch.repositories.blobstore;

import org.apache.lucene.util.SetOnce;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotRequestBuilder;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequestBuilder;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.blobstore.BlobContainer;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.seqno.RetentionLeases;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.repositories.IndexId;
import org.elasticsearch.repositories.RepositoriesService;
import org.elasticsearch.repositories.Repository;
import org.elasticsearch.repositories.RepositoryData;
import org.elasticsearch.snapshots.SnapshotMissingException;
import org.elasticsearch.snapshots.SnapshotRestoreException;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

//import static org.elasticsearch.index.seqno.RetentionLeaseActions.RETAIN_ALL;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

/**
 * Basic integration tests for blob-based repository validation.
 */
public abstract class ESBlobStoreRepositoryIntegTestCase extends ESIntegTestCase {

    protected abstract void createTestRepository(String name, boolean verify);

    protected void afterCreationCheck(Repository repository) {

    }

    protected void createAndCheckTestRepository(String name) {
        final boolean verify = randomBoolean();
        createTestRepository(name, verify);

        final Iterable<RepositoriesService> repositoriesServices =
            internalCluster().getDataOrMasterNodeInstances(RepositoriesService.class);

        for (RepositoriesService repositoriesService : repositoriesServices) {
            final BlobStoreRepository repository = (BlobStoreRepository) repositoriesService.repository(name);

            afterCreationCheck(repository);
            assertThat("blob store has to be lazy initialized",
                repository.getBlobStore(), verify ? is(notNullValue()) : is(nullValue()));
        }

    }

    public void testSnapshotAndRestore() throws Exception {
        final String repoName = randomAsciiName();
        logger.info("-->  creating repository {}", repoName);
        createAndCheckTestRepository(repoName);
        int indexCount = randomIntBetween(1, 5);
        int[] docCounts = new int[indexCount];
        String[] indexNames = generateRandomNames(indexCount);
        for (int i = 0; i < indexCount; i++) {
            docCounts[i] = iterations(10, 1000);
            logger.info("-->  create random index {} with {} records", indexNames[i], docCounts[i]);
            addRandomDocuments(indexNames[i], docCounts[i]);
            assertHitCount(client().prepareSearch(indexNames[i]).setSize(0).get(), docCounts[i]);
        }

        final String snapshotName = randomAsciiName();
        logger.info("-->  create snapshot {}:{}", repoName, snapshotName);
        assertSuccessfulSnapshot(client().admin().cluster().prepareCreateSnapshot(repoName, snapshotName)
                .setWaitForCompletion(true).setIndices(indexNames));

        List<String> deleteIndices = randomSubsetOf(randomIntBetween(0, indexCount), indexNames);
        if (deleteIndices.size() > 0) {
            logger.info("-->  delete indices {}", deleteIndices);
            assertAcked(client().admin().indices().prepareDelete(deleteIndices.toArray(new String[deleteIndices.size()])));
        }

        Set<String> closeIndices = new HashSet<>(Arrays.asList(indexNames));
        closeIndices.removeAll(deleteIndices);

        if (closeIndices.size() > 0) {
            for (String index : closeIndices) {
                if (randomBoolean()) {
                    logger.info("--> add random documents to {}", index);
                    addRandomDocuments(index, randomIntBetween(10, 1000));
                } else {
                    int docCount = (int) client().prepareSearch(index).setSize(0).get().getHits().getTotalHits();
                    int deleteCount = randomIntBetween(1, docCount);
                    logger.info("--> delete {} random documents from {}", deleteCount, index);
                    for (int i = 0; i < deleteCount; i++) {
                        int doc = randomIntBetween(0, docCount - 1);
                        client().prepareDelete(index, index, Integer.toString(doc)).get();
                    }
                    client().admin().indices().prepareRefresh(index).get();
                }
            }

            logger.info("-->  close indices {}", closeIndices);
            assertAcked(client().admin().indices().prepareClose(closeIndices.toArray(new String[closeIndices.size()])));
        }

        logger.info("--> restore all indices from the snapshot");
        assertSuccessfulRestore(client().admin().cluster().prepareRestoreSnapshot(repoName, snapshotName).setWaitForCompletion(true));

        ensureGreen();

        for (int i = 0; i < indexCount; i++) {
            assertHitCount(client().prepareSearch(indexNames[i]).setSize(0).get(), docCounts[i]);
        }

        logger.info("-->  delete snapshot {}:{}", repoName, snapshotName);
        assertAcked(client().admin().cluster().prepareDeleteSnapshot(repoName, snapshotName).get());

        expectThrows(SnapshotMissingException.class, () ->
            client().admin().cluster().prepareGetSnapshots(repoName).setSnapshots(snapshotName).get());

        expectThrows(SnapshotMissingException.class, () ->
            client().admin().cluster().prepareDeleteSnapshot(repoName, snapshotName).get());

        expectThrows(SnapshotRestoreException.class, () ->
            client().admin().cluster().prepareRestoreSnapshot(repoName, snapshotName).setWaitForCompletion(randomBoolean()).get());
    }

    public void testMultipleSnapshotAndRollback() throws Exception {
        String repoName = randomAsciiName();
        logger.info("-->  creating repository {}", repoName);
        createAndCheckTestRepository(repoName);
        int iterationCount = randomIntBetween(2, 5);
        int[] docCounts = new int[iterationCount];
        String indexName = randomAsciiName();
        String snapshotName = randomAsciiName();
        assertAcked(client().admin().indices().prepareCreate(indexName).get());
        for (int i = 0; i < iterationCount; i++) {
            if (randomBoolean() && i > 0) { // don't delete on the first iteration
                int docCount = docCounts[i - 1];
                if (docCount > 0) {
                    int deleteCount = randomIntBetween(1, docCount);
                    logger.info("--> delete {} random documents from {}", deleteCount, indexName);
                    for (int j = 0; j < deleteCount; j++) {
                        int doc = randomIntBetween(0, docCount - 1);
                        client().prepareDelete(indexName, indexName, Integer.toString(doc)).get();
                    }
                    client().admin().indices().prepareRefresh(indexName).get();
                }
            } else {
                int docCount = randomIntBetween(10, 1000);
                logger.info("--> add {} random documents to {}", docCount, indexName);
                addRandomDocuments(indexName, docCount);
            }
            // Check number of documents in this iteration
            docCounts[i] = (int) client().prepareSearch(indexName).setSize(0).get().getHits().getTotalHits();
            logger.info("-->  create snapshot {}:{} with {} documents", repoName, snapshotName + "-" + i, docCounts[i]);
            assertSuccessfulSnapshot(client().admin().cluster().prepareCreateSnapshot(repoName, snapshotName + "-" + i)
                    .setWaitForCompletion(true).setIndices(indexName));
        }

        int restoreOperations = randomIntBetween(1, 3);
        for (int i = 0; i < restoreOperations; i++) {
            int iterationToRestore = randomIntBetween(0, iterationCount - 1);
            logger.info("-->  performing restore of the iteration {}", iterationToRestore);

            logger.info("-->  close index");
            assertAcked(client().admin().indices().prepareClose(indexName));

            logger.info("--> restore index from the snapshot");
            assertSuccessfulRestore(client().admin().cluster().prepareRestoreSnapshot(repoName, snapshotName + "-" + iterationToRestore)
                    .setWaitForCompletion(true));

            ensureGreen();
            assertHitCount(client().prepareSearch(indexName).setSize(0).get(), docCounts[iterationToRestore]);
        }

        for (int i = 0; i < iterationCount; i++) {
            logger.info("-->  delete snapshot {}:{}", repoName, snapshotName + "-" + i);
            assertAcked(client().admin().cluster().prepareDeleteSnapshot(repoName, snapshotName + "-" + i).get());
        }
    }

    public void testIndicesDeletedFromRepository() throws Exception {
        Client client = client();

        logger.info("-->  creating repository");
        final String repoName = "test-repo";
        createAndCheckTestRepository(repoName);

        createIndex("test-idx-1", "test-idx-2", "test-idx-3");
        ensureGreen();

        logger.info("--> indexing some data");
        for (int i = 0; i < 20; i++) {
            index("test-idx-1", "doc", Integer.toString(i), "foo", "bar" + i);
            index("test-idx-2", "doc", Integer.toString(i), "foo", "baz" + i);
            index("test-idx-3", "doc", Integer.toString(i), "foo", "baz" + i);
        }
        refresh();

        logger.info("--> take a snapshot");
        CreateSnapshotResponse createSnapshotResponse =
            client.admin().cluster().prepareCreateSnapshot(repoName, "test-snap").setWaitForCompletion(true).get();
        assertEquals(createSnapshotResponse.getSnapshotInfo().successfulShards(), createSnapshotResponse.getSnapshotInfo().totalShards());

        logger.info("--> indexing more data");
        for (int i = 20; i < 40; i++) {
            index("test-idx-1", "doc", Integer.toString(i), "foo", "bar" + i);
            index("test-idx-2", "doc", Integer.toString(i), "foo", "baz" + i);
            index("test-idx-3", "doc", Integer.toString(i), "foo", "baz" + i);
        }

        logger.info("--> take another snapshot with only 2 of the 3 indices");
        createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(repoName, "test-snap2")
                                     .setWaitForCompletion(true)
                                     .setIndices("test-idx-1", "test-idx-2")
                                     .get();
        assertEquals(createSnapshotResponse.getSnapshotInfo().successfulShards(), createSnapshotResponse.getSnapshotInfo().totalShards());

        logger.info("--> delete a snapshot");
        assertAcked(client().admin().cluster().prepareDeleteSnapshot(repoName, "test-snap").get());

        logger.info("--> verify index folder deleted from blob container");
        RepositoriesService repositoriesSvc = internalCluster().getInstance(RepositoriesService.class, internalCluster().getMasterName());
        ThreadPool threadPool = internalCluster().getInstance(ThreadPool.class, internalCluster().getMasterName());
        @SuppressWarnings("unchecked") BlobStoreRepository repository = (BlobStoreRepository) repositoriesSvc.repository(repoName);

        final SetOnce<BlobContainer> indicesBlobContainer = new SetOnce<>();
        final SetOnce<RepositoryData> repositoryData = new SetOnce<>();
        final CountDownLatch latch = new CountDownLatch(1);
        threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(() -> {
            indicesBlobContainer.set(repository.blobStore().blobContainer(repository.basePath().add("indices")));
            repositoryData.set(repository.getRepositoryData());
            latch.countDown();
        });

        latch.await();
        for (IndexId indexId : repositoryData.get().getIndices().values()) {
            if (indexId.getName().equals("test-idx-3")) {
                assertFalse(indicesBlobContainer.get().blobExists(indexId.getId())); // deleted index
            }
        }
    }

    /*
    public void testRetentionLeasesClearedOnRestore() throws Exception {
        final String repoName = randomAsciiName();
        logger.info("-->  creating repository {}", repoName);
        createAndCheckTestRepository(repoName);

        final String indexName = randomAsciiName();
        final int shardCount = randomIntBetween(1, 5);
        assertAcked(client().admin().indices().prepareCreate(indexName).setSettings(Settings.builder()
            .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, shardCount)
            .put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true)).get());
        final ShardId shardId = new ShardId(resolveIndex(indexName), randomIntBetween(0, shardCount - 1));

        final int snapshotDocCount = iterations(10, 1000);
        logger.info("--> indexing {} docs into {}", snapshotDocCount, indexName);
        addRandomDocuments(indexName, snapshotDocCount);
        assertHitCount(client().prepareSearch(indexName).setSize(0).get(), snapshotDocCount);

        final String leaseId = randomAsciiName();
        logger.info("--> adding retention lease with id {} to {}", leaseId, shardId);
        client().execute(RetentionLeaseActions.Add.INSTANCE, new RetentionLeaseActions.AddRequest(
            shardId, leaseId, RETAIN_ALL, "test")).actionGet();

        final ShardStats shardStats = Arrays.stream(client().admin().indices().prepareStats(indexName).get().getShards())
            .filter(s -> s.getShardRouting().shardId().equals(shardId)).findFirst().get();
        final RetentionLeases retentionLeases = shardStats.getRetentionLeaseStats().retentionLeases();
        assertTrue(shardStats + ": " + retentionLeases, retentionLeases.contains(leaseId));

        final String snapshotName = randomAsciiName();
        logger.info("-->  create snapshot {}:{}", repoName, snapshotName);
        assertSuccessfulSnapshot(client().admin().cluster().prepareCreateSnapshot(repoName, snapshotName)
            .setWaitForCompletion(true).setIndices(indexName));

        if (randomBoolean()) {
            final int extraDocCount = iterations(10, 1000);
            logger.info("--> indexing {} extra docs into {}", extraDocCount, indexName);
            addRandomDocuments(indexName, extraDocCount);
        }

        logger.info("-->  close index {}", indexName);
        assertAcked(client().admin().indices().prepareClose(indexName));

        logger.info("--> restore index {} from snapshot", indexName);
        assertSuccessfulRestore(client().admin().cluster().prepareRestoreSnapshot(repoName, snapshotName).setWaitForCompletion(true));

        ensureGreen();
        assertHitCount(client().prepareSearch(indexName).setSize(0).get(), snapshotDocCount);

        final RetentionLeases restoredRetentionLeases = Arrays.stream(client().admin().indices().prepareStats(indexName).get()
            .getShards()).filter(s -> s.getShardRouting().shardId().equals(shardId)).findFirst().get()
            .getRetentionLeaseStats().retentionLeases();
        assertFalse(restoredRetentionLeases.toString() + " has no " + leaseId, restoredRetentionLeases.contains(leaseId));
    }
    */

    protected void addRandomDocuments(String name, int numDocs) throws ExecutionException, InterruptedException {
        IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs; i++) {
            indexRequestBuilders[i] = client().prepareIndex(name, name, Integer.toString(i))
                .setRouting(randomAlphaOfLength(randomIntBetween(1, 10))).setSource("field", "value");
        }
        indexRandom(true, indexRequestBuilders);
    }

    protected String[] generateRandomNames(int num) {
        Set<String> names = new HashSet<>();
        for (int i = 0; i < num; i++) {
            String name;
            do {
                name = randomAsciiName();
            } while (names.contains(name));
            names.add(name);
        }
        return names.toArray(new String[num]);
    }

    public static CreateSnapshotResponse assertSuccessfulSnapshot(CreateSnapshotRequestBuilder requestBuilder) {
        CreateSnapshotResponse response = requestBuilder.get();
        assertSuccessfulSnapshot(response);
        return response;
    }

    public static void assertSuccessfulSnapshot(CreateSnapshotResponse response) {
        assertThat(response.getSnapshotInfo().successfulShards(), greaterThan(0));
        assertThat(response.getSnapshotInfo().successfulShards(), equalTo(response.getSnapshotInfo().totalShards()));
    }

    public static RestoreSnapshotResponse assertSuccessfulRestore(RestoreSnapshotRequestBuilder requestBuilder) {
        RestoreSnapshotResponse response = requestBuilder.get();
        assertSuccessfulRestore(response);
        return response;
    }

    public static void assertSuccessfulRestore(RestoreSnapshotResponse response) {
        assertThat(response.getRestoreInfo().successfulShards(), greaterThan(0));
        assertThat(response.getRestoreInfo().successfulShards(), equalTo(response.getRestoreInfo().totalShards()));
    }

    public static String randomAsciiName() {
        return randomAlphaOfLength(randomIntBetween(1, 10)).toLowerCase(Locale.ROOT);
    }
}


text:
class ValLambda {
	public void easyLambda() {
		lombok.val foo = (Runnable)()-> {};
	}

	public void easyIntersectionLambda() {
		lombok.val foo = (Runnable & java.io.Serializable)()-> {};
		lombok.val bar = (java.io.Serializable & Runnable)()-> {};
	}

	public void easyLubLambda() {
		lombok.val foo = (System.currentTimeMillis() > 0) ? (Runnable)()-> {} : (Runnable)System.out::println;
	}

//	public void castLubLambda() {
//		Runnable foo = (Runnable) ((System.currentTimeMillis() > 0) ? () -> {} : System.out::println);
//		lombok.val foo = (Runnable) ((System.currentTimeMillis() > 0) ? () -> {} : System.out::println);
//	}
}


text:
package com.wql.nettyhttpxml;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;

import java.net.InetSocketAddress;

import com.wql.nettyhttpxml.base.HttpXmlRequest;
import com.wql.nettyhttpxml.base.HttpXmlRequestEncoder;
import com.wql.nettyhttpxml.base.HttpXmlResponse;
import com.wql.nettyhttpxml.base.HttpXmlResponseDecoder;
import com.wql.nettyhttpxml.base.Order;
import com.wql.nettyhttpxml.base.OrderFactory;

/**
 * @author wuqinglong
 * @date 2015年7月16日 下午2:30:09
 */
public class HttpXmlClient {

	public static void main(String[] args) {
		if (null == args || args.length != 2)
			args = new String[] { "127.0.0.1", "8000" };
		new HttpXmlClient().connect(Integer.valueOf(args[1]), args[0]);
	}

	public void connect(int port, String host) {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap boot = new Bootstrap();
			boot.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast("http-decoder", new HttpResponseDecoder());
					ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
					ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
					ch.pipeline().addLast("http-encoder", new HttpRequestEncoder());
					ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
					ch.pipeline().addLast("xmlClientHandler", new SimpleChannelInboundHandler<HttpXmlResponse>() {

						public void channelActive(ChannelHandlerContext ctx) {
							HttpXmlRequest request = new HttpXmlRequest(null, OrderFactory.create(123L));
							ctx.writeAndFlush(request);
						}

						public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
							cause.printStackTrace();
							ctx.close();
						}

						@Override
						protected void messageReceived(ChannelHandlerContext ctx, HttpXmlResponse msg) throws Exception {
							System.out.println("The client receive response of http header is : " + msg.getResponse().headers().names());
							System.out.println("The client receive response of http body is : " + msg.getResult());
						}
					});
				}
			});
			boot.connect(new InetSocketAddress(port)).sync().channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
}


text:
import Adapter from '../../../../src/core/adapters/refinements';
import Search from '../../../../src/core/adapters/search';
import Selectors from '../../../../src/core/selectors';
import suite from '../../_suite';

suite('Refinements Adapter', ({ expect, stub }) => {

  describe('mergeRefinements()', () => {
    it('should merge refinements', () => {
      const name = 'brand';
      const refinements = ['a', 'b', 'c', 'd'];
      const state: any = { e: 'f' };
      const navigation = { range: false, refinements: ['g', 'h', 'i', 'j'], selected: [1, 3] };
      const navigationSelector = stub(Selectors, 'navigation').returns(navigation);
      const extractRefinement = stub(Search, 'extractRefinement').returns('x');
      const refinementsMatch = stub(Search, 'refinementsMatch').returns(true);

      const merged = Adapter.mergeRefinements(<any>{ navigation: { name, refinements } }, state);

      expect(merged).to.eql({
        navigationId: name,
        refinements: ['x', 'x', 'x', 'x'],
        selected: [0, 1, 2, 3]
      });
      expect(navigationSelector).to.be.calledWith(state, name);
      expect(extractRefinement).to.have.callCount(4)
        .and.calledWith('a')
        .and.calledWith('b')
        .and.calledWith('d')
        .and.calledWith('c');
      expect(refinementsMatch).to.have.callCount(4)
        .and.calledWith('x', 'h', 'Value');
    });

    it('should not select non-matching refinements', () => {
      const name = 'brand';
      const refinements = ['a', 'b', 'c', 'd'];
      const state: any = { e: 'f' };
      const navigation = { range: false, refinements: ['g', 'h', 'i', 'j'], selected: [1, 3] };
      const navigationSelector = stub(Selectors, 'navigation').returns(navigation);
      const extractRefinement = stub(Search, 'extractRefinement').returns('x');
      const refinementsMatch = stub(Search, 'refinementsMatch').returns(false);

      const merged = Adapter.mergeRefinements(<any>{ navigation: { name, refinements } }, state);

      expect(merged).to.eql({
        navigationId: name,
        refinements: ['x', 'x', 'x', 'x'],
        selected: []
      });
      expect(navigationSelector).to.be.calledWith(state, name);
      expect(extractRefinement).to.have.callCount(4)
        .and.calledWith('a')
        .and.calledWith('b')
        .and.calledWith('d')
        .and.calledWith('c');
      expect(refinementsMatch).to.have.callCount(8)
        .and.calledWith('x', 'h', 'Value');
    });

    it('should merge range refinements', () => {
      const name = 'brand';
      const refinements = ['a', 'b', 'c', 'd'];
      const state: any = { e: 'f' };
      const navigation = { range: true, refinements: ['g', 'h', 'i', 'j'], selected: [1, 3] };
      const navigationSelector = stub(Selectors, 'navigation').returns(navigation);
      const extractRefinement = stub(Search, 'extractRefinement').returns('x');
      const refinementsMatch = stub(Search, 'refinementsMatch').returns(true);

      const merged = Adapter.mergeRefinements(<any>{ navigation: { name, refinements } }, state);

      expect(merged).to.eql({
        navigationId: name,
        refinements: ['x', 'x', 'x', 'x'],
        selected: [0, 1, 2, 3]
      });
      expect(navigationSelector).to.be.calledWith(state, name);
      expect(extractRefinement).to.have.callCount(4)
        .and.calledWith('a')
        .and.calledWith('b')
        .and.calledWith('d')
        .and.calledWith('c');
      expect(refinementsMatch).to.have.callCount(4)
        .and.calledWith('x', 'h', 'Range');
    });
  });
});


text:
try:
    from bashmu.dist import DistBase
except ImportError:
    from .dist import DistBase

from multiprocessing import Pool, RLock
import dill

class DistThreadPool(DistBase):
    def __init__(self, start=True, threads=8):
        super().__init__(start=start)
        self.pool = Pool(threads)
        self.poollock = RLock()

    def dispatch(self,f,args,kwargs,deferobj,callback,ecallback,addjobargs):
        with self.poollock:
            fcode = dill.dumps(f)
            def makecallback(dobj):
                def customcallback(result):
                    callback(result)
                    dobj.__setvalue__(result)
                return customcallback
            self.pool.apply_async(undillfunc, [fcode] + list(args), kwargs,
                                  makecallback(deferobj), ecallback)

class DeferredException(Exception):
    def __init__(self, message):
        super(DeferredException, self).__init__(message)

    @staticmethod
    def make_error_message(f,args,kwargs,error):
        errortype = str(type(error).__name__)
        fname = str(f.__name__)
        total_args = list(str(arg) for arg in args) + list(str(key)+"="+str(kwargs[key]) for key in kwargs.keys())
        argsstring = ", ".join(total_args)
        return "[{errortype}] {fname}({argstring}): {errormessage}".format(errortype=errortype,fname=fname,
                                                                           argstring=argsstring,
                                                                           errormessage=str(error))

def undillfunc(fcode, *args, **kwargs):
    newf = dill.loads(fcode)
    try:
        return newf(*args, **kwargs)
    except Exception as error:
        message = DeferredException.make_error_message(newf,args,kwargs,error)
        raise DeferredException(message)


text:
typedef struct _param
{
    strBuf name;
    unsigned char value;
} Param;

extern tcp_streamer* streamsOut;
extern tcp_streamer* streamsInp;

static const unsigned short m1=(unsigned short int)(-1);

void answer500(struct espconn * conn, const size_t code);

bool unpackParams(const strBuf* params, Param* ret, const unsigned short int count);

unsigned short int findParam(const strBuf* name, const Param* params, const unsigned short int count);

bool doReply(const strBuf* inputMessageAll,struct espconn *conn);

void sendStatus(char status, strBuf *send);

void makeHTTPReply(const strBuf* statusString, const size_t contentSize, const strBuf *etag, strBuf *out);

#endif // WEBSRVR_H


text:
/* Richard Meadows 2013 */

/* Generates the valiation function for our CouchDB */

exports = module.exports = function() {
  /* ======== Main ======== */

  return function(new_doc, old_doc, user_context, security) {

  };
}();


text:
DEBUG = True

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
    }
}

INSTALLED_APPS = ('django.contrib.auth',
                  'django.contrib.admin',
                  'django.contrib.contenttypes',
                  'django.contrib.sessions',
                  'django.contrib.sites',

                  'cms',
                  'mptt',

                  'djangocms_picture')

SECRET_KEY = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',)


text:
.Bounceable {
  width: 100%;
  overflow-y: hidden;
  display: flex;
  align-items: center;
}

.Bounceable-spring {
  position: relative;
  width: 100%;
  display: flex;
}


text:
package sias.model.pojo;

import sias.model.base.BasePOJO;

public class DeficienciaPessoa extends BasePOJO{

    private String descricao;
    private TipoDeficiencia tipoDeficiencia;
    private Pessoa pessoa;

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public TipoDeficiencia getTipoDeficiencia() {
        return tipoDeficiencia;
    }

    public void setTipoDeficiencia(TipoDeficiencia tipoDeficiencia) {
        this.tipoDeficiencia = tipoDeficiencia;
    }

    public Pessoa getPessoa() {
        return pessoa;
    }

    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }

}


text:
package leap.web.json;

import leap.lang.enums.Bool;

import java.lang.annotation.*;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface JsonSerialize {

	String settings() default "";

	Bool keyQuoted() default Bool.NONE;

	Bool ignoreNull() default Bool.NONE;

	Bool ignoreEmpty() default Bool.NONE;

	Bool nullToEmptyString() default Bool.FALSE;

	Bool htmlEscape() default Bool.FALSE;

	String namingStyle() default "";

    String dateFormat() default "";

    /**
     * Formats the {@link java.util.Date} with gmt time zone.
     */
    boolean gmt() default false;
}


text:
import re
import time
import asyncio

from . import filters

class Remote:
	def __init__(self, master):
		self.master = master

	def __getattr__(self, name):
		def _fun(*args, **kwds):
			return self.master.call_remote_method(name, *args, **kwds)

		return _fun

class Client(asyncio.Protocol):
	def __init__(self, delegate, options, send_service, receive_service):
		self.delegate = delegate
		self.send_service = send_service
		self.receive_service = receive_service

		self.parse_options(options)

		self.transport = None
		self.ip = ''
		self.port = 0

		self.setup_data_filter()

	def setup_data_filter(self):
		self.send_filter, self.receive_filter = filters.gen_filters(self.options)

	def call_remote_method(self, name, *args, **kwds):
		data = self.send_service.pack(name, *args, **kwds)

		data = self.send_filter.filter(data)

		self.transport.write(data)

	def raw_send(self, data):
		self.transport.write(self.send_filter.filter(data))

	def parse_options(self, options):
		self.options = set()
		for token in re.split('[ ,]', options):
			token = token.strip()
			self.options.add(token)

	def connect(self, ip, port, callback = None, timeout = 0):
		self.ip = ip
		self.port = port

		loop = asyncio.get_event_loop()
		routine = loop.create_connection(lambda : self, self.ip, self.port)

		if not callback:
			loop.run_until_complete(routine)
			return

		# await time out
		begin_time = time.time()
		def done_callback(future):
			exception = future.exception()
			if timeout > 0 and (time.time() - begin_time > timeout):
				callback and callback(False)
				return

			# reconnect
			if exception: # re connected
				routine = loop.create_connection(lambda : self, self.ip, self.port)
				future = asyncio.ensure_future(routine)
				future.add_done_callback(done_callback)
			else:
				callback(True)

		future = asyncio.ensure_future(routine)
		future.add_done_callback(done_callback)

	def connection_made(self, transport):
		self.transport = transport

		self.remote = Remote(self)
		self.delegate.remote = self.remote

		self.delegate.connection_made()
		# to do: check the signature
		self.delegate.connection_ready()

	def connection_lost(self, exc):
		self.delegate.connection_lost()

		# break the recycyle reference
		self.__dict__.clear()

	def data_received(self, data):
		for package in self.receive_filter.feed(data):
			name, args = self.receive_service.unpack(package)

			getattr(self.delegate, name)(*args)

	def eof_received(self):
		pass

if __name__ == '__main__':
	import service

	import signal
	signal.signal(signal.SIGINT, signal.SIG_DFL)

	s = service.Service()
	s.build_protocols()

	class Delegate:
		def connection_made(self):
			print('client connection made!')

		def connection_lost(self):
			print('client connection lost!!!')

		def connection_ready(self):
			print('client connection ready')

	c = Client(Delegate(), 'zip pack,big', s)

	def _connected(ok):
		print('client connected!!!!', ok)

	c.connect('127.0.0.1', 999, _connected)

	print('client started!!!')
	asyncio.get_event_loop().run_forever()


text:
package ledis

type Object struct {
	Id      string   `json:"id"`      //
	Created int64    `json:"created"` //
	Updated int64    `json:"updated"` //
	Memo    []string `json:"memo"`    //
}

func (o *Object) Create() error {
	return nil
}

func (o *Object) Read() (Object, error) {
	return nil, nil
}

func (o *Object) Update() error {
	return nil
}

func (o *Object) Delete() error {
	return nil
}


text:
namespace storage
{
	class TextureDataStorage
	{
	private:
		storage::Array2DSquareTextureBuffer array_2d_square_texture_buffer;

	public:
		//------------------------------ Constructors
		TextureDataStorage();
		TextureDataStorage(GLuint mip_level, GLenum sized_internal_format, GLenum base_internal_format, GLuint width, GLuint height, GLuint min_texture_size, GLuint layers);

		storage::Array2DSquareTextureBuffer getArray2DSquareTextureBuffer();
		void addModelTexture(model::ModelFormat* model);
	};
}


text:
@interface PodsDummy_Pods_ShakeNBake_YFoundationSDK_sConnectionMonitor : NSObject
@end
@implementation PodsDummy_Pods_ShakeNBake_YFoundationSDK_sConnectionMonitor
@end


text:
package org.onosproject.net;

import com.google.common.annotations.Beta;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.onlab.util.Identifier;
import org.onosproject.net.resource.ResourceConsumer;
import org.onosproject.net.resource.ResourceConsumerId;

import java.nio.charset.StandardCharsets;

/**
 * Intent identifier suitable as an external key.
 *
This class is immutable.

 */
@Beta
public final class ResourceGroup extends Identifier<Long> implements ResourceConsumer {

    private static final String HEX_PREFIX = "0x";
    private static final HashFunction HASH_FN = Hashing.md5();

    /**
     * Creates a resource group identifier from the specified long
     * representation.
     *
     * @param value long value
     * @return resource group identifier
     */
    public static ResourceGroup of(long value) {
        return new ResourceGroup(value);
    }

    /**
     * Creates a resource group identifier from the specified string
     * representation.
     * Warning: it is caller responsibility to make sure the hashed value of
     * {@code value} is unique.
     *
     * @param value string value
     * @return resource group identifier
     */
    public static ResourceGroup of(String value) {
        return new ResourceGroup(HASH_FN.newHasher()
                                        .putString(value, StandardCharsets.UTF_8)
                                        .hash()
                                        .asLong());
    }

    /**
     * Constructor for serializer.
     */
    protected ResourceGroup() {
        super(0L);
    }

    /**
     * Constructs the ID corresponding to a given long value.
     *
     * @param value the underlying value of this ID
     */
    protected ResourceGroup(long value) {
        super(value);
    }

    /**
     * Returns the backing value.
     *
     * @return the value
     */
    public long fingerprint() {
        return identifier;
    }

    @Override
    public String toString() {
        return HEX_PREFIX + Long.toHexString(identifier);
    }

    @Override
    public ResourceConsumerId consumerId() {
        return ResourceConsumerId.of(this);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        final ResourceGroup other = (ResourceGroup) obj;
        if (this.fingerprint() != other.fingerprint()) {
            return false;
        }
        return true;
    }
}


text:
{{announcements}}

                  <button  ng-click="onClickCreate()" class="btn btn-primary">Create Announcement</button>

                Title
                Public
                POC Name
                POC Contact
                Action

 {{message}}

{{title}}

                  <button  ng-click="backNav()" class="btn btn-primary">View Announcements</button>

	<form class="form-horizontal" name="announcementForm" role="form" ng-submit="announcementForm.$valid && saveAnnouncement()"
		novalidate>

			Title*

				<input type="text" class="form-control" ng-model="data.title" name="title" required="required"
					id="title" placeholder="Enter Announcement Title">

Title is required.

			Description*

				<textarea id="description" class="form-control" required="required"
					ng-model="data.description" name="description"
					placeholder="Enter Announcement Description"></textarea>

Description is required.

			Public

				<input type="checkbox" class="form-control" ng-model="data.public" name="public" id="public">

			Point Of Contact *

				<input type="text" class="form-control" ng-model="data.contacts_list[0].name" name="name" placeholder="Name" id="name" required="required">

Name is required

				<input type="text" class="form-control" type="number" class="form-control" maxlength="10"
					   ng-model="data.contacts_list[0].phone" placeholder="Phone" name="phone" id="phone" required="required">

Contact number is required

				Created By
				{{created_by_name}}

				Created Date
				{{data.created_date}}

				Last Updated By
				{{updated_by_name}}

				Last Updated Date
				{{data.last_updated_date}}

				<button type="submit" ng-click="submitted=true" class="btn btn-primary">Save</button>

	</form>


text:
var redis = require('redis'),
    subscribeStream = require('../');

var stream = subscribeStream({ subscription: 'hithere' });

var client = redis.createClient();

var testObj = {
  test: 'value',
  other: 'otherValue'
};

stream.on('readable', function () {
  var obj = stream.read();
  console.log('obj', obj);
});

client.publish('hithere', JSON.stringify(testObj));


text:
<?php

namespace PommProject\Foundation\Exception;

/**
 * ConverterException
 *
 * Exceptions dedicated to the converters.
 *
 * @package Foundation
 * @copyright 2014 Grégoire HUBERT
 * @author Grégoire HUBERT
 * @license X11 {@link http://opensource.org/licenses/mit-license.php}
 * @see FoundationException
 */
class ConverterException extends FoundationException
{
}


text:
using System.Linq;
using System.Text;
using PatientManagement.DAL;

namespace Edi835._835Segments
{
    public class Clp : SegmentBase
    {
        public Clp(ServiceDescription serviceDescription)
        {
            this.SegmentIdentifier = "CLP";

            this.ClaimSubmittersIdentifier = serviceDescription.BillId;
            this.ClaimStatusCode = serviceDescription.ClaimStatus.Code;
            this.TotalClaimChargeAmount = serviceDescription.ChargeCost +
                                          serviceDescription.AdditionalServiceDescriptions.Sum(s => s.ChargeCost);
            this.TotalClaimPaymentAmount = serviceDescription.PaymentAmount +
                                           serviceDescription.AdditionalServiceDescriptions.Sum(s => s.SumOfChargePaid);
            this.PatientResponsibility = serviceDescription.Copay +
                                         serviceDescription.AdditionalServiceDescriptions.Sum(s => s.Copay);
            this.ClaimFilingIndicatorCode = "12";
            this.PayerClaimControlNumber = "EMC5841338";
            this.FacilityTypeCode = serviceDescription.PlaceOfService.ServiceLocation;
            this.ClaimFrequencyCode = string.Empty;
            this.DrgCode = string.Empty;
            this.DrgWeight = 0;
            this.Dischargefractionpercentage = 0;
        }

        private string ClaimSubmittersIdentifier { get; }
        private string ClaimStatusCode { get; }
        private decimal TotalClaimChargeAmount { get; }
        private decimal TotalClaimPaymentAmount { get; }
        private decimal PatientResponsibility { get; }
        private string ClaimFilingIndicatorCode { get; }
        private string PayerClaimControlNumber { get; }
        private string FacilityTypeCode { get; }
        private string ClaimFrequencyCode { get; }
        private string DrgCode { get; }
        private int DrgWeight { get; }
        private int Dischargefractionpercentage { get; }

        public string BuildClp()
        {
            var buildClp = new StringBuilder();

            buildClp.Append(this.SegmentIdentifier);
            buildClp.Append(this.DataElementTerminator);
            buildClp.Append(this.ClaimSubmittersIdentifier);
            buildClp.Append(this.DataElementTerminator);
            buildClp.Append(this.ClaimStatusCode);
            buildClp.Append(this.DataElementTerminator);
            buildClp.Append(this.TotalClaimChargeAmount);
            buildClp.Append(this.DataElementTerminator);
            buildClp.Append(this.TotalClaimPaymentAmount);
            buildClp.Append(this.DataElementTerminator);

            if (this.PatientResponsibility > 0) buildClp.Append(this.PatientResponsibility);
            buildClp.Append(this.DataElementTerminator);
            buildClp.Append(this.ClaimFilingIndicatorCode);
            buildClp.Append(this.DataElementTerminator);
            buildClp.Append(this.PayerClaimControlNumber);

            if (!string.IsNullOrEmpty(this.FacilityTypeCode))
            {
                buildClp.Append(this.DataElementTerminator);
                buildClp.Append(this.FacilityTypeCode);
            }

            if (!string.IsNullOrEmpty(this.ClaimFrequencyCode))
            {
                buildClp.Append(this.DataElementTerminator);
                buildClp.Append(this.ClaimFrequencyCode);
            }

            if (!string.IsNullOrEmpty(this.DrgCode))
            {
                buildClp.Append(this.DataElementTerminator);
                buildClp.Append(this.DrgCode);
                buildClp.Append(this.DataElementTerminator);
                buildClp.Append(this.DrgWeight);
            }

            if (this.Dischargefractionpercentage > 0)
            {
                buildClp.Append(this.DataElementTerminator);
                buildClp.Append(this.Dischargefractionpercentage);
            }

            buildClp.Append(this.SegmentTerminator);
            return buildClp.ToString();
        }
    }
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />

This room doesn't use the room's state. It just broadcast messages through "broadcast" method.

    Messages

    <form id="form">
      <input type="text" id="input" value="" autofocus/>
      <input type="submit" value="send" />
    </form>


text:
package mesosphere.marathon
package core.base

import mesosphere.marathon.state.Timestamp
import org.joda.time.DateTime

import scala.concurrent.duration.FiniteDuration

case class ConstantClock(var now_ : Timestamp = Timestamp(new DateTime(2015, 4, 9, 12, 30))) extends Clock {
  def now(): Timestamp = now_

  def +=(duration: FiniteDuration): Unit = now_ += duration
}


text:
#if !defined(PROTO_AMISSL_H) && !defined(AMISSL_COMPILE)
# include <proto/amissl.h>
#endif

#ifndef OPENSSL_OPENSSLV_H
# define OPENSSL_OPENSSLV_H
# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3))
#  pragma once
# endif

# ifdef  __cplusplus
extern "C" {
# endif

/*
 * SECTION 1: VERSION DATA.  These will change for each release
 */

/*
 * Base version macros
 *
 * These macros express version number MAJOR.MINOR.PATCH exactly
 */
# define OPENSSL_VERSION_MAJOR  3
# define OPENSSL_VERSION_MINOR  0
# define OPENSSL_VERSION_PATCH  7

/*
 * Additional version information
 *
 * These are also part of the new version scheme, but aren't part
 * of the version number itself.
 */

/* Could be: #define OPENSSL_VERSION_PRE_RELEASE "-alpha.1" */
# define OPENSSL_VERSION_PRE_RELEASE ""
/* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+fips" */
/* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+vendor.1" */
# define OPENSSL_VERSION_BUILD_METADATA ""

/*
 * Note: The OpenSSL Project will never define OPENSSL_VERSION_BUILD_METADATA
 * to be anything but the empty string.  Its use is entirely reserved for
 * others
 */

/*
 * Shared library version
 *
 * This is strictly to express ABI version, which may or may not
 * be related to the API version expressed with the macros above.
 * This is defined in free form.
 */
# define OPENSSL_SHLIB_VERSION 3

/*
 * SECTION 2: USEFUL MACROS
 */

/* For checking general API compatibility when preprocessing */
# define OPENSSL_VERSION_PREREQ(maj,min)                                \
    ((OPENSSL_VERSION_MAJOR << 16) + OPENSSL_VERSION_MINOR >= ((maj) << 16) + (min))

/*
 * Macros to get the version in easily digested string form, both the short
 * "MAJOR.MINOR.PATCH" variant (where MAJOR, MINOR and PATCH are replaced
 * with the values from the corresponding OPENSSL_VERSION_ macros) and the
 * longer variant with OPENSSL_VERSION_PRE_RELEASE_STR and
 * OPENSSL_VERSION_BUILD_METADATA_STR appended.
 */
# define OPENSSL_VERSION_STR "3.0.7"
# define OPENSSL_FULL_VERSION_STR "3.0.7"

/*
 * SECTION 3: ADDITIONAL METADATA
 *
 * These strings are defined separately to allow them to be parsable.
 */
# define OPENSSL_RELEASE_DATE "1 Nov 2022"

/*
 * SECTION 4: BACKWARD COMPATIBILITY
 */

# define OPENSSL_VERSION_TEXT "OpenSSL 3.0.7 1 Nov 2022"

/* Synthesize OPENSSL_VERSION_NUMBER with the layout 0xMNN00PPSL */
# ifdef OPENSSL_VERSION_PRE_RELEASE
#  define _OPENSSL_VERSION_PRE_RELEASE 0x0L
# else
#  define _OPENSSL_VERSION_PRE_RELEASE 0xfL
# endif
# define OPENSSL_VERSION_NUMBER          \
    ( (OPENSSL_VERSION_MAJOR<<28)        \
      |(OPENSSL_VERSION_MINOR<<20)       \
      |(OPENSSL_VERSION_PATCH<<4)        \
      |_OPENSSL_VERSION_PRE_RELEASE )

# ifdef  __cplusplus
}
# endif

# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  define HEADER_OPENSSLV_H
# endif

#endif                          /* OPENSSL_OPENSSLV_H */


text:
title=API Release 1.0.2
date=2018-04-10
type=post
tags=blog
status=published
~~~~~~

Service Release 2

API Release 1.0.2

		A new service release of JSR 354 API was released today.

		The major improvement was embracing the Java 9 module system. As usual This patch release 1.0.2 of JSR 354 was be made available on popular Maven repositories.

		There are no structural API changes nor JavaDoc, etc. therefore no MR was necessary for this and jcp.org won't be updated. Check the 1.0.2 release tag.

	Thanks everyone who helped publish this release.


text:
package au.id.cxd.math.count

import breeze.linalg.DenseMatrix

import scala.math.Ordering

/**
  * given two vectors of two equal lengths
  * create a table with vector a length cols and vector b length rows
  * this table becomes a count matrix where value of row label i is equal to value of col label j
  */
class CrossTabulate[A] {

  def op(a:Seq[A], b:Seq[A])(implicit ord: Ordering[A]) = {

    val uniqueA = a.sorted.distinct
    val uniqueB = b.sorted.distinct

    val merged = (uniqueA ++ uniqueB).sorted.distinct

    val m = DenseMatrix.tabulate[Double](uniqueA.length, uniqueB.length) {
      case (i,j) => {
        val testA = uniqueA(i)
        val testB = uniqueB(j)

        // count the number of times testA index value equals test index value
        val bcount = b.foldLeft((0,0)) {
          (accum, bi) => {
            val ai = a(accum._1)
            bi.equals(testA) && ai.equals(bi) && bi.equals(testB) match {
              case true => (accum._1 + 1, accum._2 + 1)
              case _ =>
                ai.equals(testA) && bi.equals(testB) match {
                  case true => (accum._1 + 1, accum._2 + 1)
                  case _ => (accum._1 + 1, accum._2)
                }

            }
          }
        }
        bcount._2.toDouble
      }
    }

    val m2 = DenseMatrix.tabulate[Double](merged.length, merged.length) {
      case (i,j) => {
        val iIdx = uniqueA.indexOf(merged(i))
        val jIdx = uniqueB.indexOf(merged(j))
        if (iIdx < 0 || jIdx < 0) {
          0.0
        } else {
          m(iIdx,jIdx)
        }
      }
    }

    m2
  }

}
object CrossTabulate {
  def apply[A](a:Seq[A], b:Seq[A])(implicit ord: Ordering[A]) = new CrossTabulate[A]().op(a,b)

  def metrics(m:DenseMatrix[Double]) = {
    val total = m.toArray.sum.toDouble
    val (posTotal, falseTotal) = (for (i<-0 until m.rows) yield i).foldLeft((0.0,0.0)) {
      (accum, i) => (for (j<-0 until m.cols) yield j).foldLeft(accum) {
        (accum1, j) => if (i == j) (accum1._1+m(i,j), accum1._2) else (accum1._1, accum1._2+m(i,j))
      }
    }
    val odds = (posTotal/total)/(falseTotal/total)
    val posPc = (posTotal/total)
    val falsePc = (falseTotal/total)
    (total, posTotal, falseTotal, posPc, falsePc, odds)
  }

  def printMetrics(m:DenseMatrix[Double]) = {
    val (total, posTotal, falseTotal, posPc, falsePc, odds) = metrics(m)
    println(s"Total Records: $total")
    println(s"Total Match: $posTotal")
    println(s"Total Mismatch: $falseTotal")
    println(s"Positive Percent: $posPc")
    println(s"False percent: $falsePc")
    println(s"Odds: $odds")
  }
}


text:
{{ site.title }} is a collection of bits from inspiring pieces.

{{ site.posts.size }} bits, and counting.


text:
// Copyright (c) 2019 Andrew Vardeman.  Published under the MIT license.
// See license.txt in the FileSharper distribution or repository for the
// full text of the license.

using System.IO;
using System.Threading;
using FileSharperCore.Processors;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FileSharperCore.Tests.Processors
{
    [TestClass]
    public class DoNothingProcessorTests: TestBase
    {
        [TestMethod]
        public void Succeeds()
        {
            DoNothingProcessor p = new DoNothingProcessor();
            p.Init(RunInfo);
            FileInfo file = GetTestFile("BasicTextFile.txt");
            ProcessingResult result = p.Process(file, MatchResultType.Yes, new string[0], new FileInfo[0],
                ProcessInput.OriginalFile, CancellationToken.None);
            Assert.AreEqual(ProcessingResultType.Success, result.Type);
            p.Cleanup();
        }
    }
}


text:
module RailsEventLogger
  class User
    class << self
      def current
        Thread.current[:user]
      end

      def current=(user)
        Thread.current[:user] = user
      end
    end # class << self
  end
end # module RailsEventLogger


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<context:component-scan base-package="com.xiaogua.web.control,com.baidu.fsg.uid" />

	<mvc:default-servlet-handler />

</beans>


text:
// This file is automatically generated.

package adila.db;

/*
 * Alcatel Pixo 7
 *
 * DEVICE: PIXO7
 * MODEL: I212
 */
final class pixo7_i212 {
    public static final String DATA = "Alcatel|Pixo 7|";
}


text:
package org.hisp.dhis.dataapproval;

/**
 * Created by jim on 9/24/14.
 */
public class DataApprovalAndPermissions
    extends DataApproval
{
    private boolean mayApprove;

    private boolean mayUnapprove;

    private boolean mayAccept;

    private boolean mayUnaccept;

    private boolean mayReadData;

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    public DataApprovalAndPermissions()
    {
    }

    public DataApprovalAndPermissions( DataApproval d )
    {
        super( d );
    }

    // -------------------------------------------------------------------------
    // Getters and Setters
    // -------------------------------------------------------------------------

    public boolean isMayApprove()
    {
        return mayApprove;
    }

    public void setMayApprove( boolean mayApprove )
    {
        this.mayApprove = mayApprove;
    }

    public boolean isMayUnapprove()
    {
        return mayUnapprove;
    }

    public void setMayUnapprove( boolean mayUnapprove )
    {
        this.mayUnapprove = mayUnapprove;
    }

    public boolean isMayAccept()
    {
        return mayAccept;
    }

    public void setMayAccept( boolean mayAccept )
    {
        this.mayAccept = mayAccept;
    }

    public boolean isMayUnaccept()
    {
        return mayUnaccept;
    }

    public void setMayUnaccept( boolean mayUnaccept )
    {
        this.mayUnaccept = mayUnaccept;
    }

    public boolean isMayReadData()
    {
        return mayReadData;
    }

    public void setMayReadData( boolean mayReadData )
    {
        this.mayReadData = mayReadData;
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.utils.timezone
import clarityv2.accounts.managers

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0008_alter_user_username_max_length'),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer.', max_length=150, unique=True, verbose_name='username')),
                ('first_name', models.CharField(blank=True, max_length=255, verbose_name='first name')),
                ('last_name', models.CharField(blank=True, max_length=255, verbose_name='last name')),
                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
            ],
            options={
                'verbose_name': 'user',
                'verbose_name_plural': 'users',
            },
            managers=[
                ('objects', clarityv2.accounts.managers.UserManager()),
            ],
        ),
    ]


text:
from __future__ import print_function, division, absolute_import

from doto.logger import log

import requests
from doto.event import Event

class Droplet(object):

    def __repr__(self):
        return "Droplet(id=%s, image=%s, name=%s, ip=%s, status=%s, mem=%s, disk=%s, regions=%s)" % (self.id, self.image_id, self.name, self.ip_address, self.status, self.size_id, "NotImplemented", self.region_id)

    __str__ = __repr__

    def __init__(self, conn=None, **kwds):
        self._conn = conn
        self.__dict__.update(kwds)

    def update(self):
        """
        Method to update Droplet (primarily used to update ip information and state changes)

        https://api.digitalocean.com/events/[event_id]/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        data = self._conn.request("/droplets/"+str(self.id))

        self.__dict__.update(**data['droplet'])

    def event_update(self):
        """
        Method to update Droplet

        https://api.digitalocean.com/events/[event_id]/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/events/%s" % (str(self.event_id))
        data = self._conn.request(url)
        log.debug("Updating Event")
        log.debug(data)

        data['event']['event_id'] = data['event']['id']
        data['event']['id'] = data['event']['droplet_id']

        self.__dict__.update(**data['event'])

    def percentage_update(self):
        """
        Convenience method to return the percentage of event completion

        """

        #needed to grab ip_address
        self.update()

        self.event_update()
        return self.percentage

    def rename(self,name=None):
        """
        This method renames the droplet to the specified name.

        :type name: str
        :param name: Name of the new droplet

        https://api.digitalocean.com/droplets/[droplet_id]/rename/?
        client_id=[your_client_id]&api_key=[your_api_key]&name=[name]
        """

        url = "/droplets/%s/rename" % (str(self.id))

        data = self._conn.request(url,name=name)

        self.event_id = data['event_id']

        log.debug("Renaming: %d To: %s Event: %d" % (self.id, name, self.event_id))
        self.update()

    def rebuild(self, image_id=None, use_current=False):

        """
        This method allows you to reinstall a droplet with a default image.
        This is useful if you want to start again but retain the same IP address for your droplet.

        :type image_id: int
        :param image_id: ID of the image you would like to use to rebuild your droplet with

        :type use_current: BOOL
        :param use_current: Use the current image_id of the droplet during rebuild process

        https://api.digitalocean.com/droplets/[droplet_id]/rebuild/?image_id=[image_id]&
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        if use_current:
            image_id = self.image_id

        url = "/droplets/%s/rebuild" % (str(self.id))

        data = self._conn.request(url,image_id=image_id)

        self.event_id = data['event_id']

        self.update()
        log.debug("Rebuild: %d With: %d Event: %d" % (self.id, image_id, self.event_id))

        return Event(self._conn,self.event_id)

    def restore(self, image_id=None):

        """
        This method allows you to restore a droplet with a previous image or snapshot.
        This will be a mirror copy of the image or snapshot to your droplet.
        Be sure you have backed up any necessary information prior to restore.

        :type image_id: int
        :param image_id: ID of the image you would like to use to rebuild your droplet with

        https://api.digitalocean.com/droplets/[droplet_id]/restore/?image_id=[image_id]&
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/restore" % (str(self.id))

        data = self._conn.request(url,image_id=image_id)

        self.event_id = data['event_id']

        log.debug("Restoring: %d With: %d Event: %d" % (self.id, image_id, self.event_id))
        self.update()

    def set_backups(self,flag=True):
        """
        This method enables/disables automatic backups
        which run in the background daily to backup your droplet's data.

        :type flag: bool
        :param scrub_data: A bool which enables/disables backups

        https://api.digitalocean.com/droplets/[droplet_id]/enable_backups/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        backup_setting = "enable_backups" if flag else "disable_backups"

        url = "/droplets/%s/%s" % (str(self.id), backup_setting)

        data = self._conn.request(url)

        self.event_id = data['event_id']

        log.debug("Destroying: %d, Event: %d" % (self.id, self.event_id))

    def destroy(self, scrub_data=1):
        """
        This method destroys one of your droplets - this is irreversible.

        :type scrub_data: bool
        :param scrub_data: An optional bool which will strictly write 0s to your prior
        partition to ensure that all data is completely erased. True by default

        https://api.digitalocean.com/droplets/[droplet_id]/destroy/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/destroy" % (str(self.id))

        data = self._conn.request(url,scrub_data=scrub_data)

        self.event_id = data['event_id']

        log.debug("Destroying: %d, Event: %d" % (self.id, self.event_id))

    def reboot(self):
        """
        This method allows you to reboot a droplet.
        This is the preferred method to use if a server is not responding.

        https://api.digitalocean.com/droplets/[droplet_id]/reboot/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/reboot" % (str(self.id))

        data = self._conn.request(url)

        self.event_id = data['event_id']

        log.debug("Rebooting: %d, Event: %d" % (self.id, self.event_id))

    def shutdown(self):
        """
        This method allows you to shutdown a droplet.
        The droplet will remain in your account.

        https://api.digitalocean.com/droplets/[droplet_id]/shutdown/
        ?client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/shutdown" % (str(self.id))

        data = self._conn.request(url)

        self.event_id = data['event_id']

        log.debug("Shutting Down: %d, Event: %d" % (self.id, self.event_id))
        log.debug("Droplet remains active in your account")

    def power_cycle(self):
        """
        This method allows you to power cycle a droplet.
        This will turn off the droplet and then turn it back on.

        https://api.digitalocean.com/droplets/[droplet_id]/power_cycle/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/power_cycle" % (str(self.id))

        data = self._conn.request(url)

        self.event_id = data['event_id']

        log.debug("Power Cycle: %d, Event: %d" % (self.id, self.event_id))

    def power_off(self):
        """
        This method allows you to power off a droplet.
        This will turn off the droplet and then turn it back on.

        https://api.digitalocean.com/droplets/[droplet_id]/power_off/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/power_off" % (str(self.id))

        data = self._conn.request(url)

        self.event_id = data['event_id']

        log.debug("Powering Off: %d, Event: %d" % (self.id, self.event_id))

        return Event(self._conn, self.event_id)

    def power_on(self):
        """
        This method allows you to power on a previously powered off droplet.

        https://api.digitalocean.com/droplets/[droplet_id]/power_on/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/power_on" % (str(self.id))

        data = self._conn.request(url)

        self.event_id = data['event_id']

        log.debug("Powering On: %d, Event: %d" % (self.id, self.event_id))

        return Event(self._conn, self.event_id)

    def password_reset(self):
        """
        This method will reset the root password for a droplet.
        Please be aware that this will reboot the droplet to allow resetting the password.

        https://api.digitalocean.com/droplets/[droplet_id]/password_reset/?
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/password_reset" % (str(self.id))

        data = self._conn.request(url)

        self.event_id = data['event_id']

        log.debug("Resetting Password: %d, Event: %d" % (self.id, self.event_id))
        log.debug("Rebooting Droplet")

    def resize(self,size=None):
        """
        This method allows you to resize a specific droplet to a different size.
        This will affect the number of processors and memory allocated to the droplet.

        REQUIRES SNAPSHOT OF DROPLET

        :type size: int
        :param size: The new SIZE id of the droplet

        https://api.digitalocean.com/droplets/[droplet_id]/resize/?size_id=[size_id]&
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/resize" % (str(self.id))

        data = self._conn.request(url,size=size)

        self.event_id = data['event_id']

        log.debug("Resizing Droplet: %d, Event: %d" % (self.id, self.event_id))
        log.debug("Rebooting Droplet")

    def create_snapshot(self,name=None):
        """
        This method allows you to take a snapshot of the droplet once it has been powered off,
        which can later be restored or used to create a new droplet from the same image.
        Please be aware this may cause a reboot.

        :type name: string
        :param size: The NAME of the snapshot

        https://api.digitalocean.com/droplets/[droplet_id]/snapshot/?name=[snapshot_name]&
        client_id=[your_client_id]&api_key=[your_api_key]
        """

        url = "/droplets/%s/snapshot" % (str(self.id))

        data = self._conn.request(url,name=name)

        self.event_id = data['event_id']

        log.debug("Taking Snapshot: %d, Event: %d" % (self.id, self.event_id))

        return Event(self._conn, self.event_id)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFEFEFEF"
    android:orientation="vertical">

    <com.wa.sdk.cn.demo.widget.TitleBar
        android:id="@+id/tb_csc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#AA000000" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!--<ImageView-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent"-->
        <!--android:scaleType="fitCenter"-->
        <!--android:src="@drawable/ic_launcher" />-->

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="15dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/btn_show_elva"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginEnd="5dp"
                        android:layout_marginRight="5dp"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/showElva" />

                    <Button
                        android:id="@+id/btn_show_elva_op"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_marginEnd="5dp"
                        android:layout_marginRight="5dp"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/showElvaOP" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal"
                    android:weightSum="2">

                    <Button
                        android:id="@+id/btn_show_faqs"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_marginEnd="5dp"
                        android:layout_marginRight="5dp"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/showFAQs" />

                    <Button
                        android:id="@+id/btn_show_conversation"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/showConversation" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:gravity="center_vertical"
                    android:orientation="horizontal">

                    <EditText
                        android:id="@+id/et_show_single_faq"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="2"
                        android:hint="@string/input_faqId"
                        android:inputType="number"
                        android:maxLines="1" />

                    <Button
                        android:id="@+id/btn_show_single_faq"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginEnd="5dp"
                        android:layout_marginRight="5dp"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/showSingleFAQ" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:gravity="center_vertical"
                    android:orientation="horizontal">

                    <EditText
                        android:id="@+id/et_show_faq_section"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="2"
                        android:hint="@string/input_sectionPublishId"
                        android:inputType="number"
                        android:maxLines="1" />

                    <Button
                        android:id="@+id/btn_show_faq_section"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginEnd="5dp"
                        android:layout_marginRight="5dp"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/showFAQSection" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal"
                    android:visibility="gone"
                    android:weightSum="2">

                    <Button
                        android:id="@+id/btn_set_sdk_language"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_marginEnd="5dp"
                        android:layout_marginRight="5dp"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/setSDKLanguage" />

                    <View
                        android:layout_width="0dp"
                        android:layout_height="wrap_content" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/btn_isOpenAiHelp"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/isOpenAiHelp" />

                    <Button
                        android:id="@+id/btn_switchAiHelpVip"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/switchAiHelpVip" />

                </LinearLayout>

                <TextView
                    android:id="@+id/tv_openAiHelp_config"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:visibility="gone"
                    android:padding="8dp"
                    android:gravity="center_vertical"
                    android:hint="AiHelp 本地配置" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:orientation="horizontal"
                    android:layout_height="wrap_content">

                    <Button
                        android:id="@+id/btn_switchConfig"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:visibility="gone"
                        android:onClick="onClick"
                        android:text="切换openAiHelp配置" />
                    <Button
                        android:id="@+id/btn_openAiHelp"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="@string/openAiHelp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:orientation="horizontal"
                    android:visibility="gone"
                    android:layout_height="wrap_content">
                    <EditText
                        android:id="@+id/edt_custom_key"
                        android:inputType="number"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:hint="key"
                        android:maxLines="1" />

                    <EditText
                        android:id="@+id/edt_custom_value"
                        android:inputType="number"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:hint="value"
                        android:maxLines="1" />

                    <Button
                        android:id="@+id/btn_add_custom_data"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="添加参数" />
                   <Button
                        android:id="@+id/btn_reset_custom_data"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="重置" />

                </LinearLayout>
                <TextView
                    android:id="@+id/tv_custom_data"
                    android:visibility="gone"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="8dp"
                    android:gravity="center_vertical"
                    android:hint="当前自定义参数:空" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/btn_enable_log"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:visibility="gone"
                        android:onClick="onClick"
                        android:text="日志:关闭" />

                    <Button
                        android:id="@+id/btn_switch_language"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:onClick="onClick"
                        android:text="切换语言" />

                    <TextView
                        android:id="@+id/tv_language"
                        android:layout_width="0dp"
                        android:padding="8dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:hint="当前语言:默认"
                        android:textColor="@color/wa_sdk_color_black_alpha_66"
                        />

                </LinearLayout>
            </LinearLayout>
        </ScrollView>

    </FrameLayout>

</LinearLayout>


text:
StateInfinite::Scalar moment_generating_function(const StateInfinite &state_original, std::vector<Eigen::Tensor<StateInfinite::Scalar, 2>> &Op_vec) {
    using Scalar                = StateInfinite::Scalar;
    StateInfinite state_evolved = state_original;

    long bond_lim = 5 * state_evolved.chiC();
    for(auto &Op : Op_vec) {
        // Evolve
        Eigen::Tensor<Scalar, 3> mps_evo = Op.contract(state_evolved.get_2site_mps(), tenx::idx({0}, {0}));
        state_evolved.set_mps(mps_evo, bond_lim);
        if(&Op != &Op_vec.back()) { state_evolved.swap_AB(); }
    }

    long sizeLB = state_evolved.chiB() * state_evolved.chiB();
    // Normalize
    Eigen::Tensor<Scalar, 2> transfer_matrix_theta_evn =
        tools::common::views::get_transfer_matrix_theta_evn(state_evolved).reshape(tenx::array2{sizeLB, sizeLB});
    using namespace settings::precision;
    eig::solver solver;
    auto        nev = static_cast<eig::size_type>(1);
    auto        ncv = static_cast<eig::size_type>(eigs_default_ncv);

    solver.eigs(transfer_matrix_theta_evn.data(), sizeLB, nev, ncv, eig::Ritz::LM, eig::Form::NSYM, eig::Side::R, std::nullopt, eig::Shinv::OFF, eig::Vecs::OFF,
                eig::Dephase::OFF);
    auto eigval                   = eig::view::get_eigval<eig::cplx>(solver.result, 0);
    auto new_theta_evn_normalized = tools::common::views::get_theta_evn(state_evolved, sqrt(eigval));
    auto old_theta_evn_normalized = tools::common::views::get_theta_evn(state_original);
    long sizeL                    = new_theta_evn_normalized.dimension(1) * state_original.chiA();
    long sizeR                    = new_theta_evn_normalized.dimension(3) * state_original.chiB();

    Eigen::Tensor<Scalar, 2> transfer_matrix_G = new_theta_evn_normalized.contract(old_theta_evn_normalized.conjugate(), tenx::idx({0, 2}, {0, 2}))
                                                     .shuffle(tenx::array4{0, 2, 1, 3})
                                                     .reshape(tenx::array2{sizeL, sizeR});
    // Compute the characteristic function G(a).
    solver.eigs(transfer_matrix_G.data(), transfer_matrix_G.dimension(0), nev, ncv, eig::Ritz::LM, eig::Form::NSYM, eig::Side::R, std::nullopt, eig::Shinv::OFF,
                eig::Vecs::OFF, eig::Dephase::OFF);
    //    solver.eig(transfer_matrix_G.data(),(int)transfer_matrix_G.dimension(0), 1, eigs_default_ncv, Ritz::LM, Side::R, false);
    auto lambdaG = eig::view::get_eigval<eig::cplx>(solver.result, 0);
    return lambdaG;
}

double tools::infinite::measure::energy_per_site_mom(const TensorsInfinite &tensors) {
    if(tensors.measurements.energy_per_site_mom) return tensors.measurements.energy_per_site_mom.value();
    const auto &state = *tensors.state;
    const auto &model = *tensors.model;
    if(state.chiC() <= 2) {
        tensors.measurements.energy_per_site_mom          = std::numeric_limits<double>::quiet_NaN();
        tensors.measurements.energy_variance_per_site_mom = std::numeric_limits<double>::quiet_NaN();
        return tensors.measurements.energy_per_site_mom.value();
    }
    tools::log->trace("Measuring energy mom");
    auto t_ene_mom = tid::tic_scope("ene_mom");

    Scalar a      = Scalar(0.0, 1.0) * 5e-3;
    auto  &h_evn  = model.get_2site_ham_AB();
    auto  &h_odd  = model.get_2site_ham_BA();
    auto   Op_vec = qm::time::compute_G(a, 4, h_evn, h_odd);

    // The following only works if state.MPS has been normalized! I.e, you have to have run MPS->compute_mps_components() prior.
    Scalar lambdaG                                    = moment_generating_function(state, Op_vec);
    Scalar l                                          = 2.0; // Number of sites in unit cell
    Scalar G                                          = pow(lambdaG, 1.0 / l);
    Scalar logG                                       = std::log(lambdaG) * 1.0 / l;
    Scalar logGc                                      = std::log(conj(lambdaG)) * 1.0 / l;
    Scalar O                                          = (logG - logGc) / (2.0 * a);
    Scalar VarO                                       = 2.0 * std::log(abs(G)) / (a * a);
    tensors.measurements.energy_per_site_mom          = std::real(O);
    tensors.measurements.energy_variance_per_site_mom = std::real(VarO);
    return tensors.measurements.energy_per_site_mom.value();
}

double tools::infinite::measure::energy_variance_per_site_mom(const TensorsInfinite &tensors) {
    if(tensors.measurements.energy_variance_per_site_mom) return tensors.measurements.energy_variance_per_site_mom.value();
    tensors.measurements.energy_per_site_mom = tools::infinite::measure::energy_per_site_mom(tensors);
    return tensors.measurements.energy_variance_per_site_mom.value();
}


text:
layout: data_model
title: DestinationOptionsType
this_version: 1.1
---

  Heads up! These docs are for STIX 1.1, which is not the latest version (1.2). View the latest!

DestinationOptionsTypeNetwork Packet Object Schema

Defines fields for the IPv6 Destination Options header which is used to carry optional information that needs to be examined only by a packet's destination node(s).

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" selected="selected">STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" >STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      Next_Header0..1

          IANAAssignedIPNumbersType

Identifies the type of header immediately following the Destination_Options options header. Uses the same values as the IPv4 Protocol field.

      Header_Ext_Len0..1

          HexBinaryObjectPropertyType

Length of the Destination Options header in 8-octet units, not including the first 8 octets.

      Option_Data0..n

          OptionDataType

Variable-length field, of length such that the complete Destinations Options header is an integer multiple of 8 octets long. Contains one or more type-length-value (TLV)-encoded options.