text:
from warnings import warn
from itertools import combinations

import networkx as nx

from pgmpy.estimators import StructureEstimator
from pgmpy.estimators import K2Score
from pgmpy.utils.mathext import powerset
from pgmpy.models import BayesianModel

class ExhaustiveSearch(StructureEstimator):
    def __init__(self, data, scoring_method=None, **kwargs):
        """
        Search class for exhaustive searches over all BayesianModels with a given set of variables.
        Takes a `StructureScore`-Instance as parameter; `estimate` finds the model with maximal score.

        Parameters
        ----------
        data: pandas DataFrame object
            datafame object where each column represents one variable.
            (If some values in the data are missing the data cells should be set to `numpy.NaN`.
            Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.)

        scoring_method: Instance of a `StructureScore`-subclass (`K2Score` is used as default)
            An instance of `K2Score`, `BdeuScore`, or `BicScore`.
            This score is optimized during structure estimation by the `estimate`-method.

        state_names: dict (optional)
            A dict indicating, for each variable, the discrete set of states (or values)
            that the variable can take. If unspecified, the observed values in the data set
            are taken to be the only possible states.

        complete_samples_only: bool (optional, default `True`)
            Specifies how to deal with missing data, if present. If set to `True` all rows
            that contain `np.Nan` somewhere are ignored. If `False` then, for each variable,
            every row where neither the variable nor its parents are `np.NaN` is used.
            This sets the behavior of the `state_count`-method.
        """
        if scoring_method is not None:
            self.scoring_method = scoring_method
        else:
            self.scoring_method = K2Score(data, **kwargs)

        super(ExhaustiveSearch, self).__init__(data, **kwargs)

    def all_dags(self, nodes=None):
        """
        Computes all possible directed acyclic graphs with a given set of nodes,
        sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes,
        so this is likely not feasible for n>6. This is a generator.

        Parameters
        ----------
        nodes: list of nodes for the DAGs (optional)
            A list of the node names that the generated DAGs should have.
            If not provided, nodes are taken from data.

        Returns
        -------
        dags: Generator object for nx.DiGraphs
            Generator that yields all acyclic nx.DiGraphs, ordered by number of edges. Empty DAG first.

        Examples
        --------
        >>> import pandas as pd
        >>> from pgmpy.estimators import ExhaustiveSearch
        >>> s = ExhaustiveSearch(pd.DataFrame(data={'Temperature': [23, 19],
                                                    'Weather': ['sunny', 'cloudy'],
                                                    'Humidity': [65, 75]}))
        >>> list(s.all_dags())
        [<networkx.classes.digraph.DiGraph object at 0x7f6955216438>,
         <networkx.classes.digraph.DiGraph object at 0x7f6955216518>,
        ....
        >>> [dag.edges() for dag in s.all_dags()]
        [[], [('Humidity', 'Temperature')], [('Humidity', 'Weather')],
        [('Temperature', 'Weather')], [('Temperature', 'Humidity')],
        ....
        [('Weather', 'Humidity'), ('Weather', 'Temperature'), ('Temperature', 'Humidity')]]

        """
        if nodes is None:
            nodes = sorted(self.state_names.keys())
        if len(nodes) > 6:
            warn("Generating all DAGs of n nodes likely not feasible for n>6!")
            warn("Attempting to search through {0} graphs".format(2**(len(nodes)*(len(nodes)-1))))

        edges = list(combinations(nodes, 2))  # n*(n-1) possible directed edges
        edges.extend([(y, x) for x, y in edges])
        all_graphs = powerset(edges)  # 2^(n*(n-1)) graphs

        for graph_edges in all_graphs:
            graph = nx.DiGraph()
            graph.add_nodes_from(nodes)
            graph.add_edges_from(graph_edges)
            if nx.is_directed_acyclic_graph(graph):
                yield graph

    def all_scores(self):
        """
        Computes a list of DAGs and their structure scores, ordered by score.

        Returns
        -------
        list: a list of (score, dag) pairs
            A list of (score, dag)-tuples, where score is a float and model a acyclic nx.DiGraph.
            The list is ordered by score values.

        Examples
        --------
        >>> import pandas as pd
        >>> import numpy as np
        >>> from pgmpy.estimators import ExhaustiveSearch, K2Score
        >>> # create random data sample with 3 variables, where B and C are identical:
        >>> data = pd.DataFrame(np.random.randint(0, 5, size=(5000, 2)), columns=list('AB'))
        >>> data['C'] = data['B']
        >>> searcher = ExhaustiveSearch(data, scoring_method=K2Score(data))
        >>> for score, model in searcher.all_scores():
        ...   print("{0}\t{1}".format(score, model.edges()))
        -24234.44977974726      [('A', 'B'), ('A', 'C')]
        -24234.449760691063     [('A', 'B'), ('C', 'A')]
        -24234.449760691063     [('A', 'C'), ('B', 'A')]
        -24203.700955937973     [('A', 'B')]
        -24203.700955937973     [('A', 'C')]
        -24203.700936881774     [('B', 'A')]
        -24203.700936881774     [('C', 'A')]
        -24203.700936881774     [('B', 'A'), ('C', 'A')]
        -24172.952132128685     []
        -16597.30920265254      [('A', 'B'), ('A', 'C'), ('B', 'C')]
        -16597.30920265254      [('A', 'B'), ('A', 'C'), ('C', 'B')]
        -16597.309183596342     [('A', 'B'), ('C', 'A'), ('C', 'B')]
        -16597.309183596342     [('A', 'C'), ('B', 'A'), ('B', 'C')]
        -16566.560378843253     [('A', 'B'), ('C', 'B')]
        -16566.560378843253     [('A', 'C'), ('B', 'C')]
        -16268.324549347722     [('A', 'B'), ('B', 'C')]
        -16268.324549347722     [('A', 'C'), ('C', 'B')]
        -16268.324530291524     [('B', 'A'), ('B', 'C')]
        -16268.324530291524     [('B', 'C'), ('C', 'A')]
        -16268.324530291524     [('B', 'A'), ('C', 'B')]
        -16268.324530291524     [('C', 'A'), ('C', 'B')]
        -16268.324530291524     [('B', 'A'), ('B', 'C'), ('C', 'A')]
        -16268.324530291524     [('B', 'A'), ('C', 'A'), ('C', 'B')]
        -16237.575725538434     [('B', 'C')]
        -16237.575725538434     [('C', 'B')]
        """

        scored_dags = sorted([(self.scoring_method.score(dag), dag) for dag in self.all_dags()],
                             key=lambda x: x[0])
        return scored_dags

    def estimate(self):
        """
        Estimates the `BayesianModel` structure that fits best to the given data set,
        according to the scoring method supplied in the constructor.
        Exhaustively searches through all models. Only estimates network structure, no parametrization.

        Returns
        -------
        model: `BayesianModel` instance
            A `BayesianModel` with maximal score.

        Examples
        --------
        >>> import pandas as pd
        >>> import numpy as np
        >>> from pgmpy.estimators import ExhaustiveSearch
        >>> # create random data sample with 3 variables, where B and C are identical:
        >>> data = pd.DataFrame(np.random.randint(0, 5, size=(5000, 2)), columns=list('AB'))
        >>> data['C'] = data['B']
        >>> est = ExhaustiveSearch(data)
        >>> best_model = est.estimate()
        >>> best_model
        <pgmpy.models.BayesianModel.BayesianModel object at 0x7f695c535470>
        >>> best_model.edges()
        [('B', 'C')]
        """

        best_dag = max(self.all_dags(), key=self.scoring_method.score)

        best_model = BayesianModel()
        best_model.add_nodes_from(sorted(best_dag.nodes()))
        best_model.add_edges_from(sorted(best_dag.edges()))
        return best_model


text:
package org.elasticsearch.index.mapper;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.RAMDirectory;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor;
import org.elasticsearch.index.mapper.MapperService.MergeReason;
import org.elasticsearch.test.ESSingleNodeTestCase;

import java.util.Set;

import static org.hamcrest.Matchers.equalTo;

public class StoredNumericValuesTests extends ESSingleNodeTestCase {
    public void testBytesAndNumericRepresentation() throws Exception {
        IndexWriter writer = new IndexWriter(new RAMDirectory(), new IndexWriterConfig(Lucene.STANDARD_ANALYZER));

        String mapping = Strings
                .toString(XContentFactory.jsonBuilder()
                        .startObject()
                            .startObject("type")
                                .startObject("properties")
                                    .startObject("field1").field("type", "byte").field("store", true).endObject()
                                    .startObject("field2").field("type", "short").field("store", true).endObject()
                                    .startObject("field3").field("type", "integer").field("store", true).endObject()
                                    .startObject("field4").field("type", "float").field("store", true).endObject()
                                    .startObject("field5").field("type", "long").field("store", true).endObject()
                                    .startObject("field6").field("type", "double").field("store", true).endObject()
                                    .startObject("field7").field("type", "ip").field("store", true).endObject()
                                    .startObject("field8").field("type", "ip").field("store", true).endObject()
                                    .startObject("field9").field("type", "date").field("store", true).endObject()
                                    .startObject("field10").field("type", "boolean").field("store", true).endObject()
                                .endObject()
                            .endObject()
                        .endObject());
        MapperService mapperService = createIndex("test").mapperService();
        DocumentMapper mapper = mapperService.merge("type", new CompressedXContent(mapping), MergeReason.MAPPING_UPDATE);

        ParsedDocument doc = mapper.parse(SourceToParse.source("test", "type", "1", BytesReference
                .bytes(XContentFactory.jsonBuilder()
                        .startObject()
                            .field("field1", 1)
                            .field("field2", 1)
                            .field("field3", 1)
                            .field("field4", 1.1)
                            .startArray("field5").value(1).value(2).value(3).endArray()
                            .field("field6", 1.1)
                            .field("field7", "192.168.1.1")
                            .field("field8", "2001:db8::2:1")
                            .field("field9", "2016-04-05")
                            .field("field10", true)
                        .endObject()),
                XContentType.JSON));

        writer.addDocument(doc.rootDoc());

        DirectoryReader reader = DirectoryReader.open(writer);
        IndexSearcher searcher = new IndexSearcher(reader);

        Set<String> fieldNames = Sets.newHashSet("field1", "field2", "field3", "field4", "field5",
            "field6", "field7", "field8", "field9", "field10");
        CustomFieldsVisitor fieldsVisitor = new CustomFieldsVisitor(fieldNames, false);
        searcher.doc(0, fieldsVisitor);

        fieldsVisitor.postProcess(mapperService);
        assertThat(fieldsVisitor.fields().size(), equalTo(10));
        assertThat(fieldsVisitor.fields().get("field1").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field1").get(0), equalTo((byte) 1));

        assertThat(fieldsVisitor.fields().get("field2").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field2").get(0), equalTo((short) 1));

        assertThat(fieldsVisitor.fields().get("field3").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field3").get(0), equalTo(1));

        assertThat(fieldsVisitor.fields().get("field4").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field4").get(0), equalTo(1.1f));

        assertThat(fieldsVisitor.fields().get("field5").size(), equalTo(3));
        assertThat(fieldsVisitor.fields().get("field5").get(0), equalTo(1L));
        assertThat(fieldsVisitor.fields().get("field5").get(1), equalTo(2L));
        assertThat(fieldsVisitor.fields().get("field5").get(2), equalTo(3L));

        assertThat(fieldsVisitor.fields().get("field6").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field6").get(0), equalTo(1.1));

        assertThat(fieldsVisitor.fields().get("field7").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field7").get(0), equalTo("192.168.1.1"));

        assertThat(fieldsVisitor.fields().get("field8").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field8").get(0), equalTo("2001:db8::2:1"));

        assertThat(fieldsVisitor.fields().get("field9").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field9").get(0), equalTo("2016-04-05T00:00:00.000Z"));

        assertThat(fieldsVisitor.fields().get("field10").size(), equalTo(1));
        assertThat(fieldsVisitor.fields().get("field10").get(0), equalTo(true));

        reader.close();
        writer.close();
    }
}

redpajama_set_name: RedPajamaGithub


text:
// SPDX-License-Identifier: Apache-2.0

#include <benchmark/benchmark.h>
#include <cstdlib>
#include <stumpless.h>
#include "test/helper/fixture.hpp"
#include "test/helper/memory_counter.hpp"

NEW_MEMORY_COUNTER( function );

const int EXPECTED_RETURN_VALUE = 1;

int
stub_log_function( const struct stumpless_target *target,
                   const struct stumpless_entry *entry ) {
  return EXPECTED_RETURN_VALUE;
}

class FunctionFixture : public::benchmark::Fixture {
protected:
  struct stumpless_target *target;
  struct stumpless_entry *entry;

public:
  void SetUp( const ::benchmark::State &state ) {
    target = stumpless_open_function_target( "function-perf",
                                             stub_log_function );
    entry = create_entry(  );
    INIT_MEMORY_COUNTER( function );
  }

  void TearDown( const ::benchmark::State &state ) {
    stumpless_set_malloc( malloc );
    stumpless_set_realloc( realloc );
    stumpless_set_free( free );
    stumpless_destroy_entry_and_contents( entry );
    stumpless_close_function_target( target );
    stumpless_free_all(  );
  }
};

BENCHMARK_F( FunctionFixture, AddEntry )( benchmark::State &state ) {
  for( auto _ : state ) {
    if( stumpless_add_entry( target, entry ) != EXPECTED_RETURN_VALUE ) {
      state.SkipWithError( "could not send an entry" );
    }
  }

  SET_STATE_COUNTERS( state, function );
}


text:
MEDUSA_BEGIN;

class SkeletonBoneModel :public BoneMoveable
{
public:
	SkeletonBoneModel(const StringRef& name, const StringRef& parentName);
	~SkeletonBoneModel();

	StringRef Name() const { return mName; }
	StringRef ParentName() const { return mParentName; }

	SkeletonBoneModel* Parent() const { return mParent; }
	void SetParent(SkeletonBoneModel* val);

	uint Length() const { return mLength; }
	void SetLength(uint val) { mLength = val; }

	Color4F Color() const { return mColor; }
	void SetColor(Color4F val) { mColor = val; }

	void AddChildBone(SkeletonBoneModel* bone);
	void AddSlot(SkeletonSlotModel* slot);
protected:
	SkeletonBoneModel* mParent=nullptr;
	List<SkeletonBoneModel*> mBones;
	List<SkeletonSlotModel*> mSlots;

	HeapString mName;
	HeapString mParentName;

	uint mLength;		//only used to debug draw bone
	Color4F mColor;		//only used to debug draw bone

	Point3F mPosition;
	Rotation3F mRotation;
	Scale3F mScale;
};

MEDUSA_END;


text:
<!--
	Copyright 2019 Hans Dembinski

	Distributed under the Boost Software License, Version 1.0.
	(See accompanying file LICENSE_1_0.txt
	or copy at http://www.boost.org/LICENSE_1_0.txt)
-->

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="17">
<item class_id="0" tracking_level="0" version="1">
	<sum>2.50000000000000000e+00</sum>
	<mean>2.00000000000000000e+00</mean>
	<sum_of_deltas_squared>2.00000000000000000e+00</sum_of_deltas_squared>
</item>
</boost_serialization>


text:
package com.dropbox.djinni.test;

import javax.annotation.Nonnull;

public class BaseObjcJavaInterfaceInheritanceImpl extends BaseObjcJavaInterfaceInheritance {
    @Nonnull
    @Override
    public String baseMethod() {
        return InterfaceInheritanceConstant.BASE_METHOD_RETURN_VALUE;
    }

    @Nonnull
    @Override
    public String overrideMethod() {
        return InterfaceInheritanceConstant.BASE_OVERRIDE_METHOD_RETURN_VALUE;
    }
}


text:
package cn.ieclipse.af.volley.mock;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import cn.ieclipse.af.util.RandomUtils;

/**
 * The is the base response info model of network. Override or extend {@link #mock()} to mock object.
 * All the response info must override {@link #equals(Object)} to indicate the same object.
 *
 * @author Jamling
 */

public class BaseInfo implements java.io.Serializable {

    public int id;
    public String name;
    public float weight;
    public int age;

    public void mock() {
        id = 1;
        name = "Jamling";
        weight = 2f;
    }

    @Override
    public String toString() {
        return String.format("id=%d,name=%s,weight=%s,age=%d", id, name, weight, age);
    }

    public static <T> T mockObject(Class<T> clazz) {
        try {
            T output = clazz.newInstance();
            try {
                Method m = clazz.getDeclaredMethod("mock", (Class<?>[]) null);
                m.invoke(output, (Object[]) null);
            } catch (Exception e) {
                //
            }
            return output;
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> List<T> mockList(int max, Class<T> clazz) {
        int size = RandomUtils.genInt(max);
        List<T> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            try {
                T t = clazz.newInstance();
                clazz.getDeclaredMethod("mock", (Class<?>[]) null).invoke(t);
                list.add(t);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}


text:
pwd = $(CURDIR)
bin = $(pwd)/node_modules/.bin
coffee = "$(bin)/coffee"
githash = `git rev-parse --short HEAD`
gulp = "$(bin)/gulp"

all: build

bootstrap:
	npm install
	cd test/phantomjs; "$(bin)/bower" --config.analytics=false install

unbootstrap:
	rm -Rf node_modules
	rm -Rf test/phantomjs/bower

clean:
	rm -rf build

build: bootstrap clean
	mkdir -p build
	$(gulp) build:release

debug: bootstrap clean
	mkdir -p build
	$(gulp) build:debug

watch: bootstrap
	$(gulp) watch

watcher: bootstrap
	$(gulp) watcher

test: bootstrap
	$(gulp) test

coverage: bootstrap
	$(bin)/coffeeCoverage ./framer ./build/instrumented
	$(gulp) coverage
	cp ./test/coverage-template/* ./build/coverage
	open ./build/coverage/jscoverage.html

studio:
	open -a "Framer Studio" extras/Studio.framer

# Building and uploading the site

dist:
	make build
	mkdir -p build/Framer
	cp -R extras/templates/Project build/Framer/Project
	rm -Rf build/Framer/Project/framer
	mkdir -p build/Framer/Project/framer
	cp build/framer.js build/Framer/Project/framer/framer.js
	cp build/framer.js.map build/Framer/Project/framer/framer.js.map
	find build/Framer -name ".DS_Store" -depth -exec rm {} \;
	cd build; zip -r Framer.zip Framer

site%build:
	make dist
	mkdir -p build/builds.framerjs.com
	$(coffee) scripts/site-deploy.coffee build
	cp -R extras/builds.framerjs.com/static build/builds.framerjs.com/static
	mkdir -p build/builds.framerjs.com/latest
	cp build/*.js build/builds.framerjs.com/latest
	cp build/*.map build/builds.framerjs.com/latest
	cp build/*.zip build/builds.framerjs.com/latest
	cp -R build/builds.framerjs.com/latest build/builds.framerjs.com/$(githash)

site%upload:
	make site:build
	$(coffee) scripts/site-deploy.coffee upload

deploy:
	make site:build
	make site:upload

resources%optimize:
	python scripts/optimize.py

resources%upload:
	cd extras/resources.framerjs.com; cactus deploy

lint:
	./node_modules/.bin/coffeelint -f coffeelint.json -r framer

.PHONY: all build test clean perf watch


text:
<?php

use Bouda\Php7Backport\Printer\DefaultPrinter;

class DefaultPrinterTest extends PHPUnit_Framework_TestCase
{
    private $printer;

    public function setUp()
    {
        $this->printer = new DefaultPrinter();
    }

    public function testPrintNode()
    {
        // random simple node
        $node = $this->getMockBuilder('PhpParser\Node\Scalar\MagicConst\Class_')->getMock();
        $node->method('getType')->willReturn('Scalar_MagicConst_Class');

        $this->assertEquals('__CLASS__', $this->printer->printNode($node));
    }
}


text:
package org.springframework.boot.gradle;

import java.io.File;
import java.util.jar.JarFile;

import org.gradle.tooling.ProjectConnection;
import org.junit.Test;
import org.springframework.boot.dependency.tools.ManagedDependencies;

import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;

/**
 * Integration tests for Gradle repackaging with a multi-project build.
 *
 * @author Andy Wilkinson
 */
public class MultiProjectRepackagingTests {

	private static final String BOOT_VERSION = ManagedDependencies.get()
			.find("spring-boot").getVersion();

	@Test
	public void repackageWithTransitiveFileDependency() throws Exception {
		ProjectConnection project = new ProjectCreator()
				.createProject("multi-project-transitive-file-dependency");
		project.newBuild().forTasks("clean", "build")
				.withArguments("-PbootVersion=" + BOOT_VERSION).run();
		File buildLibs = new File(
				"target/multi-project-transitive-file-dependency/main/build/libs");
		JarFile jarFile = new JarFile(new File(buildLibs, "main.jar"));
		assertThat(jarFile.getEntry("lib/commons-logging-1.1.3.jar"), notNullValue());
		assertThat(jarFile.getEntry("lib/foo.jar"), notNullValue());
		jarFile.close();
	}

	@Test
	public void repackageWithCommonFileDependency() throws Exception {
		ProjectConnection project = new ProjectCreator()
				.createProject("multi-project-common-file-dependency");
		project.newBuild().forTasks("clean", "build")
				.withArguments("-PbootVersion=" + BOOT_VERSION).run();
		File buildLibs = new File(
				"target/multi-project-common-file-dependency/build/libs");
		JarFile jarFile = new JarFile(new File(buildLibs,
				"multi-project-common-file-dependency.jar"));
		assertThat(jarFile.getEntry("lib/foo.jar"), notNullValue());
		jarFile.close();
	}
}


text:
Returns the number of lines of text contained by the string.

```lua
string.lines("str")
```

### Parameters ###

`str` is the string to be tested.

### Return Value ###

The number of lines of text contained by the string.

### Availability ###

Premake 5.0 or later.


text:
<?xml version="1.0" encoding="UTF-8"?>
<response>

<lst name="responseHeader">
  <int name="status">0</int>
  <int name="QTime">258</int>
</lst>
<result name="response" numFound="2" start="0">
  <doc>
    <int name="id">1</int></doc>
  <doc>
    <int name="id">2</int></doc>
</result>
<lst name="debug">
  <str name="rawquerystring">*:*</str>
  <str name="querystring">*:*</str>
  <str name="parsedquery">MatchAllDocsQuery(*:*)</str>
  <str name="parsedquery_toString">*:*</str>
  <lst name="explain">
    <str name="1">
1.0 = (MATCH) MatchAllDocsQuery, product of:
  1.0 = queryNorm
</str>
    <str name="2">
1.0 = (MATCH) MatchAllDocsQuery, product of:
  1.0 = queryNorm
</str>
  </lst>
  <str name="QParser">LuceneQParser</str>
  <arr name="filter_queries">
    <str>{!geofilt sfield=home_gh}</str>
  </arr>
  <arr name="parsed_filter_queries">
    <str>ConstantScore(frange(ghhsin(str(home_gh),literal(djz5ex3ybvu7))):[0 TO 300.0])</str>
  </arr>
  <lst name="timing">
    <double name="time">258.0</double>
    <lst name="prepare">
      <double name="time">190.0</double>
      <lst name="org.apache.solr.handler.component.QueryComponent">
        <double name="time">190.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.FacetComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.MoreLikeThisComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.HighlightComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.StatsComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.DebugComponent">
        <double name="time">0.0</double>
      </lst>
    </lst>
    <lst name="process">
      <double name="time">68.0</double>
      <lst name="org.apache.solr.handler.component.QueryComponent">
        <double name="time">68.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.FacetComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.MoreLikeThisComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.HighlightComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.StatsComponent">
        <double name="time">0.0</double>
      </lst>
      <lst name="org.apache.solr.handler.component.DebugComponent">
        <double name="time">0.0</double>
      </lst>
    </lst>
  </lst>
</lst>
</response>


text:
package uk.ac.rdg.evoportal.data;

import java.io.File;
import org.apache.wicket.model.LoadableDetachableModel;

/**
 *
 * @author david
 */
public class OutputFileLoadableDetachableModel extends LoadableDetachableModel {

    File file;

    public OutputFileLoadableDetachableModel(File f) {
        this.file = f;
    }

    @Override
    protected Object load() {
        OutputFile outputFile = null;
        if (file.exists())
            outputFile = new OutputFile(file);
        return outputFile;
    }

}


text:
__author__ = 'Yuheng Chen'

import time
import json

class Request(object):
    '''
    Client Request class.
    Init with command id and params data.
    '''

    cmdid = 0
    timestamp = 0
    params = dict()

    def __init__(self, cmdid, data):
        '''
        Ensure data is a dict type object.
        :param cmdid: Command id.
        :param data: data dict.
        :return: Request instance.
        '''
        if isinstance(data,dict):
            self.params = data
            self.cmdid = cmdid
            self.timestamp = int(time.time())

        else:
            raise TypeError

    def serialization(self):
        '''
        Serialized request object in order to send through IOStream.
        '''
        serialized_request = {}
        serialized_request['cmdid'] = self.cmdid
        serialized_request['timestamp'] = self.timestamp
        serialized_request['params'] = self.params

        result = json.dumps(serialized_request)+'\n'
        return result


text:
class CreateAdverseEventFiles < ActiveRecord::Migration[4.2]
  def change
    create_table :adverse_event_files do |t|
      t.integer :project_id
      t.integer :adverse_event_id
      t.integer :user_id
      t.string :attachment

      t.timestamps null: false
    end

    add_index :adverse_event_files, :project_id
    add_index :adverse_event_files, :adverse_event_id
    add_index :adverse_event_files, :user_id
  end
end


text:
<?php

namespace KaramanisWeb\FaceRD\Models;

class Face extends AbstractModel
{
    protected $driver;
    protected $token;
    protected $rectangle;
    protected $attributes;
    protected $landmark;

    public function __construct(string $driver, string $token, array $unmapped = [])
    {
        $this->driver = $driver;
        $this->token = $token;
        $this->unmapped = $unmapped;
    }

    public function setAttributes($attributes)
    {
        $this->attributes = $attributes;
    }

    public function setLandmark($landmark)
    {
        $this->landmark = $landmark;
    }

    public function setRectangle(int $left, int $top, int $width, int $height)
    {
        $this->rectangle = [
            'left' => $left,
            'top' => $top,
            'width' => $width,
            'height' => $height,
        ];
    }
}


text:
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="robots" content="index,follow"/>
  <meta name="revisit-after" content="1 days"/>
  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
  <meta name="HandheldFriendly" content="True"/>
  <meta name="MobileOptimized" content="320"/>
  <meta http-equiv="cleartype" content="on"/>
  <meta name="description" content="{% if page.summary %}{{ page.summary | xml_escape }}{% else %}{{ site.description | xml_escape }}{% endif %}">
  <meta name="author" content="{{ site.author.name }}">
  {% if page.tags %}<meta name="keywords" content="{{ page.tags | join: ', ' }}">{% endif %}
  <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>

  <title>
    {% if page.title == "Home" %}
      {{ site.title }} - {{ site.description }}
    {% else %}
      {{ page.title }} - {{ site.title }}
    {% endif %}
  </title>

  <!-- Fonts -->
  <link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
  <link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>
  {% if site.show_social_icons or site.show_sharing_icons %}
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
  {% endif %}

  <!-- Open Graph -->
  <!-- From: https://github.com/mmistakes/hpstr-jekyll-theme/blob/master/_includes/head.html -->
  <meta property="og:locale" content="en_US">
  <meta property="og:type" content="article">
  <meta property="og:title" content="{% if page.title %}{{ page.title | xml_escape }}{% else %}{{ site.title | xml_escape }}{% endif %}">
  <meta property="og:description" content="{% if page.description %}{{ page.description | xml_escape }}{% else %}{{ site.description | xml_escape }}{% endif %}">
  <meta property="og:url" content="{{ site.url }}{{ page.url }}">
  <meta property="og:site_name" content="{{ site.title | xml_escape }}">

  <!-- CSS -->
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/main.css">
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/jekyll.css">
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/animate.css">
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/solarizedDark.css">

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ site.baseurl }}public/favicons/Icon-72%402x.png">
  <link rel="shortcut icon" href="{{ site.baseurl }}public/favicons/favicon.ico">
  <link rel="icon" href="{{ site.baseurl }}public/favicons/Icon.png" />
  <link rel="apple-touch-icon" sizes="57x57" href="{{ site.baseurl }}public/favicons/Icon.png" />
  <link rel="apple-touch-icon" sizes="58x58" href="{{ site.baseurl }}public/favicons/Icon-Small%402x.png" />
  <link rel="apple-touch-icon" sizes="60x60" href="{{ site.baseurl }}public/favicons/Icon-60.png" />
  <link rel="apple-touch-icon" sizes="72x72" href="{{ site.baseurl }}public/favicons/Icon-72.png" />
  <link rel="apple-touch-icon" sizes="76x76" href="{{ site.baseurl }}public/favicons/Icon-76.png" />
  <link rel="apple-touch-icon" sizes="114x114" href="{{ site.baseurl }}public/favicons/Icon%402x.png" />
  <link rel="apple-touch-icon" sizes="120x120" href="{{ site.baseurl }}public/favicons/Icon-60%402x.png" />
  <link rel="apple-touch-icon" sizes="144x144" href="{{ site.baseurl }}public/favicons/Icon-72%402x.png" />
  <link rel="apple-touch-icon" sizes="152x152" href="{{ site.baseurl }}public/favicons/Icon-76%402x.png" />
  <link rel="apple-touch-icon" sizes="180x180" href="{{ site.baseurl }}public/favicons/Icon-60%403x.png" />

  <meta name="msapplication-TileImage" content="{{ site.baseurl }}public/favicons/Icon-72%402x.png"/>
  <meta name="msapplication-TileColor" content="#01778d"/>

  <!-- RSS -->
  <link rel="alternate" type="application/atom+xml" title="{{ site.title }}" href="{{ site.baseurl }}{{ site.rss_feed }}">
</head>


text:
package com.jerzysciechowski.p14164318.golddigger;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
package com.example.hbl.bluetooth;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;

/**
 * Created by hbl on 2017/8/12.
 */

public class MyTextView extends android.support.v7.widget.AppCompatTextView {
    private Paint paint;

    public MyTextView(Context context) {
        super(context);
        init();
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(getResources().getColor(R.color.colorAccent));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRoundRect(new RectF(0, 0, width, height), height / 3f, height / 3f, paint);
        super.onDraw(canvas);

    }

    private int width;
    private int height;

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }
    public void setColor(int color){
        if(color>6){
            paint.setColor(Color.RED);
        }else if(color>3){
            paint.setColor(Color.BLUE);
        }else {
            paint.setColor(Color.GREEN);
        }
        invalidate();
    }
}


text:
/*Generated by KISSY Module Compiler*/
config({
'editor/plugin/dialog-loader': {requires: ['overlay','editor']}
});


text:
module Nanoc3::CLI::Commands

  class CreateSite < Cri::Command

    class << self

    protected

      # Converts the given array to YAML format
      def array_to_yaml(array)
        '[ ' + array.map { |s| "'" + s + "'" }.join(', ') + ' ]'
      end

    end

    DEFAULT_CONFIG = <<EOS
# A list of file extensions that nanoc will consider to be textual rather than
# binary. If an item with an extension not in this list is found,  the file
# will be considered as binary.
text_extensions: #{array_to_yaml(Nanoc3::Site::DEFAULT_CONFIG[:text_extensions])}

# The path to the directory where all generated files will be written to. This
# can be an absolute path starting with a slash, but it can also be path
# relative to the site directory.
output_dir: #{Nanoc3::Site::DEFAULT_CONFIG[:output_dir]}

# A list of index filenames, i.e. names of files that will be served by a web
# server when a directory is requested. Usually, index files are named
# "index.hml", but depending on the web server, this may be something else,
# such as "default.htm". This list is used by nanoc to generate pretty URLs.
index_filenames: #{array_to_yaml(Nanoc3::Site::DEFAULT_CONFIG[:index_filenames])}

# Whether or not to generate a diff of the compiled content when compiling a
# site. The diff will contain the differences between the compiled content
# before and after the last site compilation.
enable_output_diff: false

# The data sources where nanoc loads its data from. This is an array of
# hashes; each array element represents a single data source. By default,
# there is only a single data source that reads data from the "content/" and
# "layout/" directories in the site directory.
data_sources:
  -
    # The type is the identifier of the data source. By default, this will be
    # `filesystem_unified`.
    type: #{Nanoc3::Site::DEFAULT_DATA_SOURCE_CONFIG[:type]}

    # The path where items should be mounted (comparable to mount points in
    # Unix-like systems). This is "/" by default, meaning that items will have
    # "/" prefixed to their identifiers. If the items root were "/en/"
    # instead, an item at content/about.html would have an identifier of
    # "/en/about/" instead of just "/about/".
    items_root: #{Nanoc3::Site::DEFAULT_DATA_SOURCE_CONFIG[:items_root]}

    # The path where layouts should be mounted. The layouts root behaves the
    # same as the items root, but applies to layouts rather than items.
    layouts_root: #{Nanoc3::Site::DEFAULT_DATA_SOURCE_CONFIG[:layouts_root]}

# Configuration for the "watch" command, which watches a site for changes and
# recompiles if necessary.
watcher:
  # A list of directories to watch for changes. When editing this, make sure
  # that the "output/" and "tmp/" directories are _not_ included in this list,
  # because recompiling the site will cause these directories to change, which
  # will cause the site to be recompiled, which will cause these directories
  # to change, which will cause the site to be recompiled again, and so on.
  dirs_to_watch: [ 'content', 'layouts', 'lib' ]

  # A list of single files to watch for changes. As mentioned above, don't put
  # any files from the "output/" or "tmp/" directories in here.
  files_to_watch: [ 'config.yaml', 'Rules' ]

  # When to send notifications (using Growl or notify-send).
  notify_on_compilation_success: true
  notify_on_compilation_failure: true
EOS

    DEFAULT_RULES = <<EOS
#!/usr/bin/env ruby

# A few helpful tips about the Rules file:
#
# * The order of rules is important: for each item, only the first matching
#   rule is applied.
#
# * Item identifiers start and end with a slash (e.g. "/about/" for the file
#   "content/about.html"). To select all children, grandchildren, … of an
#   item, use the pattern "/about/*/"; "/about/*" will also select the parent,
#   because "*" matches zero or more characters.

compile '/stylesheet/' do
  # don't filter or layout
end

compile '*' do
  filter :erb
  layout 'default'
end

route '/stylesheet/' do
  '/style.css'
end

route '*' do
  if item.binary?
    # /foo/ -> /foo.ext
    item.identifier.chop + '.' + item[:extension]
  else
    # /foo/ -> /foo/index.html
    item.identifier + 'index.html'
  end
end

layout '*', :erb
EOS

    DEFAULT_ITEM = <<EOS

A Brand New nanoc Site

You've just created a new nanoc site. The page you are looking at right now is the home page for your site. To get started, consider replacing this default homepage with your own customized homepage. Some pointers on how to do so:

Change this page's content by editing the "index.html" file in the "content" directory. This is the actual page content, and therefore doesn't include the header, sidebar or style information (those are part of the layout).

Change the layout, which is the "default.html" file in the "layouts" directory, and create something unique (and hopefully less bland).

If you need any help with customizing your nanoc web site, be sure to check out the documentation (see sidebar), and be sure to subscribe to the discussion group (also see sidebar). Enjoy!

EOS

    DEFAULT_STYLESHEET = <<EOS
* {
  margin: 0;
  padding: 0;

  font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif;
}

body {
  background: #fff;
}

a {
  text-decoration: none;
}

a:link,
a:visited {
  color: #f30;
}

a:hover {
  color: #f90;
}

#main {
  position: absolute;

  top: 40px;
  left: 280px;

  width: 500px;
}

#main h1 {
  font-size: 40px;
  font-weight: normal;

  line-height: 40px;

  letter-spacing: -1px;
}

#main p {
  margin: 20px 0;

  font-size: 15px;

  line-height: 20px;
}

#main ul {
  margin: 20px;
}

#main li {
  list-style-type: square;

  font-size: 15px;

  line-height: 20px;
}

#sidebar {
  position: absolute;

  top: 40px;
  left: 20px;
  width: 200px;

  padding: 20px 20px 0 0;

  border-right: 1px solid #ccc;

  text-align: right;
}

#sidebar h2 {
  text-transform: uppercase;

  font-size: 13px;

  color: #333;

  letter-spacing: 1px;

  line-height: 20px;
}

#sidebar ul {
  list-style-type: none;

  margin: 20px 0;
}

#sidebar li {
  font-size: 14px;

  line-height: 20px;
}
EOS

    DEFAULT_LAYOUT = <<EOS
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <title>A Brand New nanoc Site - <%= @item[:title] %></title>
    <link rel="stylesheet" type="text/css" href="/style.css" media="screen">
    <meta name="generator" content="nanoc #{Nanoc3::VERSION}">

      <%= yield %>

Documentation

Documentation

Getting Started

Community

Discussion Group

IRC Channel

Wiki

EOS

    def name
      'create_site'
    end

    def aliases
      [ 'cs' ]
    end

    def short_desc
      'create a site'
    end

    def long_desc
      'Create a new site at the given path. The site will use the ' +
      'filesystem_unified data source by default, but this can be ' +
      'changed using the --datasource commandline option.'
    end

    def usage
      "nanoc3 create_site [options] path"
    end

    def option_definitions
      [
        # --datasource
        {
          :long => 'datasource', :short => 'd', :argument => :required,
          :desc => 'specify the data source for the new site'
        }
      ]
    end

    def run(options, arguments)
      # Check arguments
      if arguments.length != 1
        $stderr.puts "usage: #{usage}"
        exit 1
      end

      # Extract arguments and options
      path        = arguments[0]
      data_source = options[:datasource] || 'filesystem_unified'

      # Check whether site exists
      if File.exist?(path)
        $stderr.puts "A site at '#{path}' already exists."
        exit 1
      end

      # Check whether data source exists
      if Nanoc3::DataSource.named(data_source).nil?
        $stderr.puts "Unrecognised data source: #{data_source}"
        exit 1
      end

      # Setup notifications
      Nanoc3::NotificationCenter.on(:file_created) do |file_path|
        Nanoc3::CLI::Logger.instance.file(:high, :create, file_path)
      end

      # Build entire site
      FileUtils.mkdir_p(path)
      FileUtils.cd(File.join(path)) do
        site_create_minimal(data_source)
        site_setup
        site_populate
      end

      puts "Created a blank nanoc site at '#{path}'. Enjoy!"
    end

  protected

    # Creates a configuration file and a output directory for this site, as
    # well as a rakefile that loads the standard nanoc tasks.
    def site_create_minimal(data_source)
      # Create output
      FileUtils.mkdir_p('output')

      # Create config
      File.open('config.yaml', 'w') { |io| io.write(DEFAULT_CONFIG.make_compatible_with_env) }
      Nanoc3::NotificationCenter.post(:file_created, 'config.yaml')

      # Create rakefile
      File.open('Rakefile', 'w') do |io|
        io.write "require 'nanoc3/tasks'"
      end
      Nanoc3::NotificationCenter.post(:file_created, 'Rakefile')

      # Create rules
      File.open('Rules', 'w') do |io|
        io.write DEFAULT_RULES.make_compatible_with_env
      end
      Nanoc3::NotificationCenter.post(:file_created, 'Rules')
    end

    # Sets up the site's data source, i.e. creates the bare essentials for
    # this data source to work.
    def site_setup
      # Get site
      site = Nanoc3::Site.new('.')

      # Set up data sources
      site.data_sources.each do |data_source|
        data_source.loading { data_source.setup }
      end
    end

    # Populates the site with some initial data, such as a root item, a
    # default layout, and so on.
    def site_populate
      # Get site
      site = Nanoc3::Site.new('.')
      data_source = site.data_sources[0]

      # Create home page
      data_source.create_item(
        DEFAULT_ITEM.make_compatible_with_env,
        { :title => "Home" },
        '/'
      )

      # Create stylesheet
      data_source.create_item(
        DEFAULT_STYLESHEET.make_compatible_with_env,
        {},
        '/stylesheet/',
        :extension => '.css'
      )

      # Create layout
      data_source.create_layout(
        DEFAULT_LAYOUT.make_compatible_with_env,
        {},
        '/default/'
      )

      # Create code
      FileUtils.mkdir_p('lib')
      File.open('lib/default.rb', 'w') do |io|
        io.write "\# All files in the 'lib' directory will be loaded\n"
        io.write "\# before nanoc starts compiling.\n"
      end
    end

  end

end


text:
debian-8のOS Imageを明示的に指定してInstanceを作成します。

### debian image 一覧を確認

debian image一覧をから最新のimage nameを確認する

```
gcloud compute images list --regexp ".*debian.*"
```

### debianの指定したversionのimageでInstanceを作成する

```
gcloud compute instances create sample --image debian-8-jessie-v20170110 --image-project debian-cloud --machine-type g1-small --zone us-central1-b
```

### debianの最新versionのimageでInstanceを作成する

imageはimage-familyでグルーピングされています。 `--image-family` optionを指定した場合、そのimage-familyの中で最新のimageが利用されます。
image-familyのversionが変わるとミドルウェアのversionなども変わる可能性があるため、任意のタイミングでversionを上げたい場合は、imageを明示的に指定した方がよいです。

```
gcloud compute instances create latest-debian-8 --image-family debian-8 --image-project debian-cloud --machine-type g1-small --zone us-central1-b
```

## Diskを追加する

Instanceを作成するとBootDiskが1つある状態となります。
アプリケーションやDBのデータのみを入れたDiskを作りたい場合、新しいDiskを作成してInstanceにattachします。

### Diskを作成

```
gcloud compute disks create additional-disk --size 15 --zone us-central1-b --type pd-ssd

Created [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/disks/additional-disk].
NAME             ZONE           SIZE_GB  TYPE    STATUS
additional-disk  us-central1-b  15       pd-ssd  READY
```

### InstanceにDiskをattach

先程作成したsample instanceにdiskをattachします。 `--device-name` を省略するとOSから見たdiskとResouceとしてのdiskの対応が分からなくなってしまうので、明示的に指定するのがおすすめです。

```
gcloud compute instances attach-disk sample --disk additional-disk --device-name additional-disk --zone us-central1-b
```

### Diskをmountする

diskをattachしただけではOSから認識されていないので、sshで接続してmountを行います。

```
# ssh接続を行う

gcloud compute ssh --zone us-central1-b sample
```

```
# diskはgoogle-{device-name}で認識された状態になります。
# `ls /dev/disk/by-id` で確認してみます。

ls /dev/disk/by-id

google-additional-disk    google-persistent-disk-0-part1               scsi-0Google_PersistentDisk_persistent-disk-0
google-persistent-disk-0  scsi-0Google_PersistentDisk_additional-disk  scsi-0Google_PersistentDisk_persistent-disk-0-part1
```

```
# まだ、mountしてないので、いません

df

Filesystem     1K-blocks   Used Available Use% Mounted on
/dev/sda1       10188088 882592   8764928  10% /
udev               10240      0     10240   0% /dev
tmpfs             349068   4576    344492   2% /run
tmpfs             872664      0    872664   0% /dev/shm
tmpfs               5120      0      5120   0% /run/lock
tmpfs             872664      0    872664   0% /sys/fs/cgroup
```

```
# 新規作成してattachしたdiskはblankの状態なので、formatを行います。

sudo mkfs.ext4 -F -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/disk/by-id/google-additional-disk

mke2fs 1.42.12 (29-Aug-2014)
Discarding device blocks: done
Creating filesystem with 3932160 4k blocks and 983040 inodes
Filesystem UUID: 393d9fa9-9ab0-43ea-a80b-dbb59c01fd0d
Superblock backups stored on blocks:
	32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208

Allocating group tables: done
Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done
```

```
# mount用のdiskを作成
sudo mkdir -p /mnt/disks/additional-disk
```

```
# mount
sudo mount -o discard,defaults /dev/disk/by-id/google-additional-disk /mnt/disks/additional-disk
```

```
# diskがmountされて、使えるようになりました。

df

Filesystem     1K-blocks   Used Available Use% Mounted on
/dev/sda1       10188088 882620   8764900  10% /
udev               10240      0     10240   0% /dev
tmpfs             349068   4580    344488   2% /run
tmpfs             872664      0    872664   0% /dev/shm
tmpfs               5120      0      5120   0% /run/lock
tmpfs             872664      0    872664   0% /sys/fs/cgroup
/dev/sdb        15350768  38384  14509568   1% /mnt/disks/additional-disk
```

このままではInstanceを再起動した時にmountが外れてしまうので、自動的にmountされるように設定しておきます。

```
echo UUID=`sudo blkid -s UUID -o value /dev/disk/by-id/google-additional-disk` /mnt/disks/additional-disk ext4 discard,defaults,nofail 0 2 | sudo tee -a /etc/fstab
```

## Custom Imageの利用

### Custom Image作成

Custom Imageから作られていることが分かるように、適当にhome diskにファイルを作っておく

```
gcloud compute ssh sample --zone us-central1-b

touch version-1.txt
```

//gcloud compute disks snapshot sample --snapshot-names sample-snapshot --zone us-central1-b
//Created [https://www.googleapis.com/compute/v1/projects/cpo200demo1/global/snapshots/sample-snapshot].

### Diskを残してInstanceを削除する

Custom Imageは、InstanceにattachされていないDiskを元に作られるので、 `sample` のBoot Diskを残した状態で、Instanceを削除します。

```
# sample diskをInstance削除時に一緒に消さないように設定
gcloud compute instances set-disk-auto-delete sample --no-auto-delete --disk sample --zone us-central1-b

Updated [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample].
```

```
# Diskの状態をきれいに保つためにシャットダウンする
gcloud compute instances stop sample --zone us-central1-b

Updated [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample].
```

```
gcloud compute instances delete sample --zone us-central1-b

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample].
```

```
# Diskが残っていることを確認

gcloud compute disks list

NAME             ZONE           SIZE_GB  TYPE         STATUS
additional-disk  us-central1-b  15       pd-ssd       READY
sample           us-central1-b  10       pd-standard  READY
```

### Custom Imageを作成

```
gcloud compute images create sample-image-20160926v1 --family sample-image --source-disk sample --source-disk-zone us-central1-b
Created [https://www.googleapis.com/compute/v1/projects/cpo200demo1/global/images/sample-image-20160926v1].
NAME                     PROJECT      FAMILY        DEPRECATED  STATUS
sample-image-20160926v1  cpo200demo1  sample-image              READY
```

```
# Custom Imageを確認

gcloud compute images list
NAME                                 PROJECT          FAMILY           DEPRECATED  STATUS
sample-image-20160926v1              cpo200demo1      sample-image                 READY
centos-6-v20160921                   centos-cloud     centos-6                     READY
centos-7-v20160921                   centos-cloud     centos-7                     READY
...
```

```
# Custom Imageを利用してInstaceを作成

gcloud compute instances create sample-20160926v1 --image-family sample-image --zone us-central1-b

Created [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample-20160926v1].
NAME               ZONE           MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP      STATUS
sample-20160926v1  us-central1-b  n1-standard-1               10.128.0.2   104.154.239.117  RUNNING
```

## image-familyの新しいVersionを作成する

image-family `sample-image` に新しいversionのimageを作成してみます

```
# sshで接続してv2用であることが分かるようにファイルを置いておく

gcloud compute ssh sample-20160926v1 --zone us-central1-b

touch v2.txt
```

### Boot Diskを残してInstanceを削除

```
# sample-20160926v1 diskをInstance削除時に一緒に消さないように設定
gcloud compute instances set-disk-auto-delete sample-20160926v1 --no-auto-delete --disk sample-20160926v1 --zone us-central1-b                                                                 1 ↵
Updated [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample-20160926v1].
```

```
# sample-20160926v1 instanceを削除

gcloud compute instances delete sample-20160926v1 --zone us-central1-b

The following instances will be deleted. Attached disks configured to
be auto-deleted will be deleted unless they are attached to any other
instances. Deleting a disk is irreversible and any data on the disk
will be lost.
 - [sample-20160926v1] in [us-central1-b]

Do you want to continue (Y/n)?  Y

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample-20160926v1].
```

### Custom Imageを作成

image-family `sample-image` に新しいimageを作成します。
latest versionの判断はimage nameが最も大きいものになるので、YYYYMMDDやversion idを入れて、名前を大きくしていきます。

```
gcloud compute images create sample-image-20160926v2 --family sample-image --source-disk sample-20160926v1 --source-disk-zone us-central1-b

Created [https://www.googleapis.com/compute/v1/projects/cpo200demo1/global/images/sample-image-20160926v2].
NAME                     PROJECT      FAMILY        DEPRECATED  STATUS
sample-image-20160926v2  cpo200demo1  sample-image              READY
```

```
# image-family `sample-image` で新たにInstanceを作成

gcloud compute instances create sample-v2 --image-family sample-image --zone us-central1-b
Created [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample-v2].
NAME       ZONE           MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
sample-v2  us-central1-b  n1-standard-1               10.128.0.2   104.197.90.222  RUNNING
```

```
# ssh接続して、v2のimageが使われていることを確認

gcloud compute ssh sample-v2
ls

v1.txt  v2.txt
```

image-familyを使えば、imageを利用している側のコードを変えること無く、imageのversion upを行うことができます。

## Clean Up

instanceを削除する

```
gcloud compute instances delete sample-v2 --zone us-central1-b                                                                                2 ↵
The following instances will be deleted. Attached disks configured to
be auto-deleted will be deleted unless they are attached to any other
instances. Deleting a disk is irreversible and any data on the disk
will be lost.
 - [sample-v2] in [us-central1-b]

Do you want to continue (Y/n)?  Y

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/instances/sample-v2].
```

imageを削除する

```
gcloud compute images delete sample-image-20160926v1
The following images will be deleted:
 - [sample-image-20160926v1]

Do you want to continue (Y/n)?  Y

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/global/images/sample-image-20160926v1].
```

```
gcloud compute images delete sample-image-20160926v2
The following images will be deleted:
 - [sample-image-20160926v2]

Do you want to continue (Y/n)?  Y

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/global/images/sample-image-20160926v2].
```

diskを削除する

```
gcloud compute disks delete additional-disk --zone us-central1-b
The following disks will be deleted. Deleting a disk is irreversible
and any data on the disk will be lost.
 - [additional-disk] in [us-central1-b]

Do you want to continue (Y/n)?  Y

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/disks/additional-disk].
```

```
gcloud compute disks delete sample --zone us-central1-b
The following disks will be deleted. Deleting a disk is irreversible
and any data on the disk will be lost.
 - [sample] in [us-central1-b]

Do you want to continue (Y/n)?  Y

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/disks/sample].
```

```
gcloud compute disks delete sample-20160926v1 --zone us-central1-b
The following disks will be deleted. Deleting a disk is irreversible
and any data on the disk will be lost.
 - [sample-20160926v1] in [us-central1-b]

Do you want to continue (Y/n)?  Y

Deleted [https://www.googleapis.com/compute/v1/projects/cpo200demo1/zones/us-central1-b/disks/sample-20160926v1].
```


text:
var defaults = {
	autoAnalyzeHeaders: 0,
	upgradeMessage: 1,
	tracking: 1
};


text:
当你需要在Request请求进入之后,到进入Controller之前,你需要一些操作,比如CSRF token 验证等。这个时候你要用到这个中间件(middleware)

## 使用

### 1、注册Middleware Listener到Appkernel

找到 src/App里面的 `AppKernel` 增加一行代码:

```
$this->registerMiddlewareListener(MiddlewareListener::class, "onMiddlewareAction");
```

```
<?php

namespace TastPHP\App;

use TastPHP\Framework\Event\AppEvent;
use TastPHP\Framework\Kernel;
use TastPHP\FrontBundle\Listener\MiddlewareListener;

class AppKernel extends Kernel
{
    public function __construct(array $values = [])
    {
        $this->registerMiddlewareListener(MiddlewareListener::class, "onMiddlewareAction");
        parent::__construct($values);
    }
}
```

### 2、创建自定义的MiddlewareListener

进入 src/FrontBundle/Listener 目录,创建一个Listener后缀的`MiddlewareListener.php`文件,内容如下:

```
<?php

namespace TastPHP\FrontBundle\Listener;

use TastPHP\Framework\Event\MiddlewareEvent;

class MiddlewareListener
{
    public function onMiddlewareAction(MiddlewareEvent $event)
    {
        echo "onMiddlewareAction ~";
    }
}
```

### 3、开始测试吧

打开浏览器,出现结果类似如下,说明成功:

```
onMiddlewareAction ~
indexAction ~
```


text:
Dir.glob(File.dirname(__FILE__) + '/**/*.rb') { |file| require file }

module UspsCounties
end


text:
package com.mossle.bridge.humantask;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mossle.api.form.FormDTO;
import com.mossle.api.humantask.HumanTaskConnector;
import com.mossle.api.humantask.HumanTaskDTO;
import com.mossle.api.humantask.HumanTaskDefinition;

import com.mossle.bpm.cmd.CompleteTaskWithCommentCmd;
import com.mossle.bpm.cmd.DeleteTaskWithCommentCmd;
import com.mossle.bpm.cmd.FindTaskDefinitionsCmd;
import com.mossle.bpm.persistence.domain.BpmConfForm;
import com.mossle.bpm.persistence.domain.BpmConfOperation;
import com.mossle.bpm.persistence.domain.BpmTaskConf;
import com.mossle.bpm.persistence.manager.BpmConfFormManager;
import com.mossle.bpm.persistence.manager.BpmConfOperationManager;
import com.mossle.bpm.persistence.manager.BpmTaskConfManager;

import com.mossle.form.domain.FormTemplate;
import com.mossle.form.manager.FormTemplateManager;

import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.task.DelegationState;
import org.activiti.engine.task.Task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.jdbc.core.JdbcTemplate;

public class HumanTaskConnectorImpl implements HumanTaskConnector {
    private Logger logger = LoggerFactory
            .getLogger(HumanTaskConnectorImpl.class);
    private ProcessEngine processEngine;
    private BpmConfOperationManager bpmConfOperationManager;
    private BpmConfFormManager bpmConfFormManager;
    private FormTemplateManager formTemplateManager;
    private BpmTaskConfManager bpmTaskConfManager;
    private JdbcTemplate jdbcTemplate;

    public HumanTaskDTO findHumanTask(String taskId) {
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        HumanTaskDTO humanTaskDto = new HumanTaskDTO();
        humanTaskDto.setId(task.getId());
        humanTaskDto.setProcessInstanceId(task.getProcessInstanceId());
        humanTaskDto.setProcessDefinitionId(task.getProcessDefinitionId());
        humanTaskDto.setTaskDefinitionKey(task.getTaskDefinitionKey());

        return humanTaskDto;
    }

    public FormDTO findTaskForm(String taskId) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(taskId);

        FormDTO formDto = new FormDTO();
        formDto.setTaskId(taskId);

        List<BpmConfOperation> bpmConfOperations = bpmConfOperationManager
                .find("from BpmConfOperation where bpmConfNode.bpmConfBase.processDefinitionId=? and bpmConfNode.code=?",
                        humanTaskDto.getProcessDefinitionId(),
                        humanTaskDto.getTaskDefinitionKey());

        for (BpmConfOperation bpmConfOperation : bpmConfOperations) {
            formDto.getButtons().add(bpmConfOperation.getValue());
        }

        String processDefinitionId = humanTaskDto.getProcessDefinitionId();
        String activityId = humanTaskDto.getTaskDefinitionKey();
        formDto.setProcessDefinitionId(processDefinitionId);
        formDto.setActivityId(activityId);

        List<BpmConfForm> bpmConfForms = bpmConfFormManager
                .find("from BpmConfForm where bpmConfNode.bpmConfBase.processDefinitionId=? and bpmConfNode.code=?",
                        processDefinitionId, activityId);

        if (!bpmConfForms.isEmpty()) {
            BpmConfForm bpmConfForm = bpmConfForms.get(0);

            if (!Integer.valueOf(2).equals(bpmConfForm.getStatus())) {
                // 外部表单
                if (Integer.valueOf(1).equals(bpmConfForm.getType())) {
                    formDto.setRedirect(true);
                    formDto.setUrl(bpmConfForm.getValue());
                } else {
                    formDto.setCode(bpmConfForm.getValue());
                }
            }
        }

        FormTemplate formTemplate = formTemplateManager.findUniqueBy("code",
                formDto.getCode());

        if (formTemplate == null) {
            logger.error("cannot find form : {}", formDto.getCode());

            return formDto;
        }

        if (Integer.valueOf(1).equals(formTemplate.getType())) {
            formDto.setRedirect(true);
            formDto.setUrl(formTemplate.getContent());
        }

        return formDto;
    }

    public List<HumanTaskDefinition> findHumanTaskDefinitions(
            String processDefinitionId) {
        FindTaskDefinitionsCmd cmd = new FindTaskDefinitionsCmd(
                processDefinitionId);
        List<TaskDefinition> taskDefinitions = processEngine
                .getManagementService().executeCommand(cmd);

        List<HumanTaskDefinition> humanTaskDefinitions = new ArrayList<HumanTaskDefinition>();

        for (TaskDefinition taskDefinition : taskDefinitions) {
            HumanTaskDefinition humanTaskDefinition = new HumanTaskDefinition();
            humanTaskDefinition.setKey(taskDefinition.getKey());
            humanTaskDefinition.setName(taskDefinition.getNameExpression()
                    .getExpressionText());
            humanTaskDefinition.setAssignee(taskDefinition
                    .getAssigneeExpression().getExpressionText());
            humanTaskDefinitions.add(humanTaskDefinition);
        }

        return humanTaskDefinitions;
    }

    public void configTaskDefinitions(String businessKey,
            List<String> taskDefinitionKeys, List<String> taskAssignees) {
        if (taskDefinitionKeys == null) {
            return;
        }

        // 如果是从配置任务负责人的页面过来,就保存TaskConf,再从草稿中得到数据启动流程
        int index = 0;

        for (String taskDefinitionKey : taskDefinitionKeys) {
            String taskAssignee = taskAssignees.get(index++);
            BpmTaskConf bpmTaskConf = new BpmTaskConf();
            bpmTaskConf.setBusinessKey(businessKey);
            bpmTaskConf.setTaskDefinitionKey(taskDefinitionKey);
            bpmTaskConf.setAssignee(taskAssignee);
            bpmTaskConfManager.save(bpmTaskConf);
        }
    }

    public void completeTask(String taskId, String userId,
            Map<String, Object> taskParameters) {
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        // 处理抄送任务
        if ("copy".equals(task.getCategory())) {
            processEngine.getManagementService().executeCommand(
                    new DeleteTaskWithCommentCmd(taskId, "已阅"));

            return;
        }

        // 先设置登录用户
        IdentityService identityService = processEngine.getIdentityService();
        identityService.setAuthenticatedUserId(userId);

        if (task == null) {
            throw new IllegalStateException("任务不存在");
        }

        // logger.info("{}", task.getDelegationState());

        // 处理委办任务
        if (DelegationState.PENDING == task.getDelegationState()) {
            taskService.resolveTask(taskId);

            return;
        }

        // 处理子任务
        if ("subtask".equals(task.getCategory())) {
            processEngine.getManagementService().executeCommand(
                    new DeleteTaskWithCommentCmd(taskId, "完成"));

            int count = jdbcTemplate.queryForObject(
                    "select count(*) from ACT_RU_TASK where PARENT_TASK_ID_=?",
                    Integer.class, task.getParentTaskId());

            if (count > 1) {
                return;
            }

            taskId = task.getParentTaskId();
        }

        processEngine.getManagementService().executeCommand(
                new CompleteTaskWithCommentCmd(taskId, taskParameters, "完成"));
    }

    @Resource
    public void setProcessEngine(ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Resource
    public void setBpmConfOperationManager(
            BpmConfOperationManager bpmConfOperationManager) {
        this.bpmConfOperationManager = bpmConfOperationManager;
    }

    @Resource
    public void setBpmConfFormManager(BpmConfFormManager bpmConfFormManager) {
        this.bpmConfFormManager = bpmConfFormManager;
    }

    @Resource
    public void setFormTemplateManager(FormTemplateManager formTemplateManager) {
        this.formTemplateManager = formTemplateManager;
    }

    @Resource
    public void setBpmTaskConfManager(BpmTaskConfManager bpmTaskConfManager) {
        this.bpmTaskConfManager = bpmTaskConfManager;
    }

    @Resource
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}


text:
package toolkit.neuralnetwork.operator

import libcog._
import cogdebugger._

/** A debugger test to manually check difference between Fourier approach and
  * backProjectFrame operator
  * @author Matthew Pickett
  */
object ConvBackDebugger extends CogDebuggerApp( new ComputeGraph{
  val inRows = 64
  val inShape = Shape(inRows, inRows)
  val filterSize = 9
  val filterShape = Shape(filterSize, filterSize)
  val filterNum = 32
  val inputLen = 48
  val batchSize = 24

  val inputSetSize = 4
  val batchSetSize = 4

  //generate random inputs and filter bank
  val grad = VectorField.random(inShape, Shape(filterNum * batchSize))
  val f = VectorField.random(filterShape, Shape(filterNum * inputLen)) - 0.5f
  val x = fourierBackProject(grad, f, batchSize, batchSetSize, inputSetSize)
//  val x = backProjectFFT(grad, f, batchSize, filterSetSize, batchSetSize)

  //calculate the difference between the above Fourier approach and backProjectFrame
  val totalDiffBack = IndexedSeq.tabulate(batchSize){i=>{
    val batchN = VectorField(Vector(filterNum, j=>j+i*filterNum))
    val yN = vectorElements(grad, batchN)
    val xN = blockReduceSum(backProjectFrame(yN,f,BorderCyclic),filterNum)

    val outputN = VectorField(Vector(inputLen, j=>j+i*inputLen))
    val singleDiff = xN - vectorElements(x, outputN)
    singleDiff
  }}.reduce(_+_)
  probe(totalDiffBack, "total difference back")
})


text:
title: "MTF Qualifies for Slack NonProfits Program"
tags:
    - memtech
    - slack
    - chat
categories:
    - news
author:
    - Joe
---

We have completed our Slack for nonprofits application and were recently approved. Slack has upgraded us to a standard account for up to 100 users.

This account upgrade is a $3,920 value to Memphis Technology Foundation. We'd like to thank Slack for providing this great service to nonprofit groups!

Come [join us on Slack!](/blog/2015/05/23/join-memtech-on-slack-chat/)


text:
config_file = File.expand_path('../base.rb', __FILE__)
require config_file

Compass.configuration do |config|
    config.output_style = :debug
    config.css_path = File.join($root_path, "css/debug/")
    config.line_comments = true
end


text:
package de.isibboi.agentsim.ui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.font.TextAttribute;
import java.util.Collections;

import javax.swing.JFrame;

import de.isibboi.agentsim.Settings;

/**
 * Renders the default look and feel of the game.
 *
 * @author Sebastian Schmidt
 * @since 0.2.0
 */
public class DefaultRenderer implements Renderer {
	private final Font _font;
	private final Font _buttonFont;
	private final int _textHeight;
	private int _textVerticalOffset;

	private Graphics2D _g;

	/**
	 * Constructs a new default renderer.
	 *
	 * @param frame The JFrame this renderer should draw on.
	 * @param settings The settings.
	 */
	public DefaultRenderer(final JFrame frame, final Settings settings) {
		_font = new Font(settings.get(Settings.UI_FONT_FAMILY), Font.PLAIN, 20);
		_buttonFont = _font.deriveFont(Collections.singletonMap(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON));

		_textHeight = frame.getFontMetrics(_font).getHeight();
		_textVerticalOffset = -frame.getFontMetrics(_font).getDescent();
	}

	@Override
	public void setGraphics(final Graphics2D g) {
		_g = g;
	}

	@Override
	public void drawBox(final int x, final int y, final int width, final int height) {
		_g.setColor(Color.WHITE);
		_g.fillRect(x, y, width, height);
		_g.setColor(Color.BLACK);
		_g.drawRect(x, y, width, height);
	}

	@Override
	public void drawText(final String text, final int x, final int y) {
		_g.setFont(_font);
		_g.setColor(Color.BLACK);
		_g.drawString(text, x, y + _textVerticalOffset);
	}

	@Override
	public int getTextHeight() {
		return _textHeight;
	}

	@Override
	public void drawButtonText(final String text, final int x, final int y) {
		_g.setFont(_buttonFont);
		_g.setColor(Color.BLACK);
		_g.drawString(text, x, y + _textVerticalOffset);
	}

	@Override
	public void drawHoveredBox(final int x, final int y, final int width, final int height) {
		_g.setColor(new Color(230, 230, 230));
		_g.fillRect(x, y, width, height);
		_g.setColor(Color.BLACK);
		_g.drawRect(x, y, width, height);
	}

	@Override
	public void drawClickedBox(final int x, final int y, final int width, final int height) {
		_g.setColor(new Color(230, 230, 230));
		_g.fillRect(x, y, width, height);
		_g.setColor(Color.BLACK);

		Stroke oldStroke = _g.getStroke();
		int additionalThickness = 1;
		_g.setStroke(new BasicStroke(additionalThickness + 1f));
		_g.drawRect(x + (int) Math.ceil(additionalThickness / 2.0f), y + (int) Math.ceil(additionalThickness / 2.0f),
				width - additionalThickness, height - additionalThickness);
		_g.setStroke(oldStroke);
	}

	@Override
	public void drawEntitySelectionRectangle(final Rectangle rectangle) {
		_g.setColor(new Color(230, 20, 20));
		_g.draw(rectangle);
	}
}


text:
/**
 * @file wbxml_tree.h
 * @ingroup wbxml_tree
 *
 * @author Aymerick Jehanne <aymerick@jehanne.org>
 * @date 03/02/16
 *
 * @brief WBXML Tree
 */

#ifndef WBXML_TREE_H
#define WBXML_TREE_H

#include "wbxml.h"
#include "wbxml_elt.h"

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#include "wbxml_config.h"

/** @addtogroup wbxml_tree
 *  @{
 */

/****************************************************
 *	WBXML Tree Structures
 */

/**
 * @brief WBXML Tree Node Type
 */
typedef enum WBXMLTreeNodeType_e
{
    WBXML_TREE_ELEMENT_NODE = 0, /**< Element Node */
    WBXML_TREE_TEXT_NODE,        /**< Text Node */
    WBXML_TREE_CDATA_NODE,       /**< CDATA Node */
    WBXML_TREE_PI_NODE,          /**< PI Node */
    WBXML_TREE_TREE_NODE         /**< WBXML Tree Node */
} WBXMLTreeNodeType;

/**
 * @brief WBXML Tree Node structure
 */
typedef struct WBXMLTreeNode_s
{
    WBXMLTreeNodeType   type;       /**< Node Type */
    WBXMLTag            *name;      /**< Node Name (if type is 'WBXML_TREE_ELEMENT_NODE') */
    WBXMLList           *attrs;     /**< Node Attributes (if type is 'WBXML_TREE_ELEMENT_NODE') */
    WBXMLBuffer         *content;   /**< Node Content (if  type is 'WBXML_TREE_TEXT_NODE')  */
    struct WBXMLTree_s  *tree;      /**< Node Tree (if  type is 'WBXML_TREE_TREE_NODE') */

    struct WBXMLTreeNode_s  *parent;    /**< Parent Node */
    struct WBXMLTreeNode_s  *children;  /**< Children Node */
    struct WBXMLTreeNode_s  *next;      /**< Next sibling Node */
    struct WBXMLTreeNode_s  *prev;      /**< Previous sibling Node */
} WBXMLTreeNode;

/**
 * @brief WBXML Tree structure
 *
 * This structure is created when parsing a WBXML or XML document, thanks to
 * the functions wbxml_tree_from_wbxml() and wbxml_tree_from_xml().
 *
 * It represents the parsed document, and have this fields:
 *   - lang: the language table of the parsed document (in wbxml_tables.c)
 *   - root: the root element of the Tree representing the parsed document
 *   - orig_charset: the original charset encoding of the parsed document
 *
 * @note All the strings inside the WBXML Tree are encoded into UTF-8
 */
typedef struct WBXMLTree_s
{
    const WBXMLLangEntry *lang;         /**< Language Table */
    WBXMLTreeNode        *root;         /**< Root Element */
    WBXMLCharsetMIBEnum   orig_charset; /**< Charset encoding of original document */
    WB_UTINY              cur_code_page;/**< Last seen code page */
} WBXMLTree;

/**
 * WBXML Tree Clb Context Structure
 * @note Used by WBXML Tree Callbacks ('wbxml_tree_clb_wbxml.h' and 'wbxml_tree_clb_xml.h')
 */
typedef struct WBXMLTreeClbCtx_s {
    /* For XML and WBXML Clb */
    WBXMLTree     *tree;          /**< The WBXML Tree we are constructing */
    WBXMLTreeNode *current;       /**< Current Tree Node */
    WBXMLError     error;         /**< Error while parsing Document */
    /* For XML Clb */
    WB_ULONG       skip_lvl;      /**< Used to skip a whole XML node (used for SyncML) */
    WB_LONG        skip_start;    /**< Starting Skipping position in XML Document (used for SyncML) */
    WB_UTINY      *input_buff;    /**< Pointer to Input Buffer */
#if defined( HAVE_EXPAT )
    XML_Parser     xml_parser;    /**< Pointer to Expat XML Parser */
    WB_BOOL        expat_utf16;   /**< Is Expat compiled to output UTF-16 ? */
#endif /* HAVE_EXPAT */
} WBXMLTreeClbCtx;

#if defined ( WBXML_SUPPORT_SYNCML )
/**
 * SyncML Data Type (the type of data inside <Data> element)
 */
typedef enum WBXMLSyncMLDataType_e {
    WBXML_SYNCML_DATA_TYPE_NORMAL = 0,      /**< Not specific Data Type */
    WBXML_SYNCML_DATA_TYPE_WBXML,           /**< application/vnd.syncml-devinf+wbxml (WBXML Document) */
    WBXML_SYNCML_DATA_TYPE_CLEAR,			/**< text/clear */
    WBXML_SYNCML_DATA_TYPE_DIRECTORY_VCARD, /**< text/directory;profile=vCard */
    WBXML_SYNCML_DATA_TYPE_VCARD,           /**< text/x-vcard */
    WBXML_SYNCML_DATA_TYPE_VCALENDAR,       /**< text/x-vcalendar */
    WBXML_SYNCML_DATA_TYPE_VOBJECT          /**< Hack: we assume that any <Data> inside a <Replace> or <Add> Item is a vObjec (vCard / vCal / ...) */
} WBXMLSyncMLDataType;
#endif /* WBXML_SUPPORT_SYNCML */

/****************************************************
 *  WBXML Tree Building Functions
 */

/**
 * @brief Parse a WBXML document, using internal callbacks (in wbxml_tree_clb_wbxml.c), and construct a WBXML Tree
 * @param wbxml     [in]  The WBXML document to parse
 * @param wbxml_len [in]  The WBXML document length
 * @param lang      [in]  Can be used to force parsing of a given Language (set it to WBXML_LANG_UNKNOWN if you don't want to force anything)
 * @param tree      [out] The resulting WBXML Tree
 * @result Return WBXML_OK if no error, an error code otherwise
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_from_wbxml(WB_UTINY *wbxml,
                                                WB_ULONG wbxml_len,
                                                WBXMLLanguage lang,
                                                WBXMLCharsetMIBEnum charset,
                                                WBXMLTree **tree);

/**
 * @brief Convert a WBXML Tree to a WBXML document
 * @param tree      [in]  The WBXML Tree to convert
 * @param wbxml     [out] The resulting WBXML document
 * @param wbxml_len [out] The resulting WBXML document length
 * @param params    [in]  Parameters (if NULL, default values are used)
 * @result Return WBXML_OK if no error, an error code otherwise
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_to_wbxml(WBXMLTree *tree,
                                              WB_UTINY **wbxml,
                                              WB_ULONG  *wbxml_len,
                                              WBXMLGenWBXMLParams *params);

/**
 * @brief Parse an XML document, using internal callbacks (in wbxml_tree_clb_xml.c), and construct a WBXML Tree
 * @param xml     [in]  The XML document to parse
 * @param xml_len [in]  Length of the XML document
 * @param tree    [out] The resulting WBXML Tree
 * @result Return WBXML_OK if no error, an error code otherwise
 * @note Needs 'HAVE_EXPAT' compile flag
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_from_xml(WB_UTINY *xml,
                                              WB_ULONG xml_len,
                                              WBXMLTree **tree);

/**
 * @brief Convert a WBXML Tree to an XML document
 * @param tree    [in]  The WBXML Tree to convert
 * @param xml     [out] The resulting XML document
 * @param xml_len [out] The resulting XML document length
 * @param params  [in]  Parameters (if NULL, default values are used)
 * @result Return WBXML_OK if no error, an error code otherwise
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_to_xml(WBXMLTree *tree,
                                            WB_UTINY **xml,
                                            WB_ULONG  *xml_len,
                                            WBXMLGenXMLParams *params);

/** @todo Libxml support ! */
#if defined( HAVE_LIBXML )

/**
 * @brief Parse a LibXML document, and construct the corresponding WBXML Tree
 * @param libxml_doc [in]  The LibXML document to parse
 * @param tree       [out] The resulting WBXML Tree
 * @result Return WBXML_OK if no error, an error code otherwise
 * @note Needs 'HAVE_LIBXML' compile flag
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_from_libxml_doc(xmlDocPtr libxml_doc,
                                                     WBXMLTree **tree);

/**
 * @brief Parse a WBXML Tree, and construct the corresponding LibXML document
 * @param tree       [in]  The WBXML Tree to parse
 * @param libxml_doc [out] The resulting LibXML document
 * @result Return WBXML_OK if no error, an error code otherwise
 * @note Needs 'HAVE_LIBXML' compile flag
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_to_libxml_doc(WBXMLTree *tree,
                                                   xmlDocPtr *libxml_doc);

#endif /* HAVE_LIBXML */

/****************************************************
 *	WBXML Tree Functions
 */

/**
 * @brief Create a Tree Node structure
 * @param type Node type
 * @return The newly created Tree Node, or NULL if not enough memory
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_node_create(WBXMLTreeNodeType type);

/**
 * @brief Destroy a Tree Node structure
 * @param node The Tree Node structure to destroy
 * @note The Node is freed, but not extracted from its WBXML Tree (use wbxml_tree_extract_node() before)
 */
WBXML_DECLARE(void) wbxml_tree_node_destroy(WBXMLTreeNode *node);

/**
 * @brief Destroy a Tree Node structure (used for wbxml_list_destroy())
 * @param node The Tree Node structure to destroy
 */
WBXML_DECLARE(void) wbxml_tree_node_destroy_item(void *node);

/**
 * @brief Destroy a Tree Node structure, and all its children
 * @param node The Tree Node structure to destroy
 * @note The Node (and its sub-tree) is freed, but not extracted from its WBXML Tree (use wbxml_tree_extract_node() before)
 */
WBXML_DECLARE(void) wbxml_tree_node_destroy_all(WBXMLTreeNode *node);

/**
 * @brief Create a Tree Node structure, given the XML node name
 * @param lang_table Language table
 * @param name       XML node name
 * @return The newly created Tree Node, or NULL if not enough memory
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_node_create_xml_elt(const WBXMLLangEntry *lang_table,
                                                              const WB_UTINY *name);

/**
 * @brief Create a Tree Node structure, given the XML node name and text content
 * @param lang_table Language table
 * @param name       XML node name
 * @param text       Text content
 * @param len        Text content length
 * @return The newly created Tree Node, or NULL if not enough memory
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_node_create_xml_elt_with_text(const WBXMLLangEntry *lang_table,
                                                                        const WB_UTINY *name,
                                                                        const WB_UTINY *text,
                                                                        WB_ULONG len);

/**
 * @brief Create a Text Node structure
 * @param text       Text content
 * @param len        Text content length
 * @return The newly created Tree Node, or NULL if not enough memory
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_node_create_text(const WB_UTINY *text,
                                                           WB_ULONG len);

/**
 * @brief Create a CDATA Node structure
 * @param text       Text content
 * @param len        Text content length
 * @return The newly created Tree Node, or NULL if not enough memory
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_node_create_cdata(const WB_UTINY *text,
                                                            WB_ULONG len);

/**
 * @brief Create a Tree Node structure
 * @param root Root node for this Tree
 * @param lang Language table to use
 * @param orig_charset Original charset
 * @return The newly created Tree Node, or NULL if not enough memory
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_node_create_tree(WBXMLTreeNode *root,
                                                           WBXMLLanguage lang,
                                                           WBXMLCharsetMIBEnum orig_charset);

/**
 * @brief Add a Child node
 * @param parent Parent node
 * @param node   Child node to add
 * @return TRUE if added or FALSE if error
 */
WBXML_DECLARE(WB_BOOL) wbxml_tree_node_add_child(WBXMLTreeNode *parent,
                                                 WBXMLTreeNode *node);

/**
 * @brief Extract a node
 * @param node Node to extract
 * @return TRUE if extracted or FALSE if error
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_node_extract(WBXMLTreeNode *node);

/**
 * @brief Add a WBXML Attribute to a Tree Node structure
 * @param node The Tree Node to modify
 * @param attr The WBXML Attribute to add
 * @return WBXML_OK if no error, an error code otherwise
 * @note This is only meanfull for an element node
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_node_add_attr(WBXMLTreeNode *node,
                                                   WBXMLAttribute *attr);

/**
 * @brief Add a WBXML Attributes list to a Tree Node structure
 * @param node  The Tree Node to modify
 * @param attrs The WBXML Attributes to add
 * @return WBXML_OK if no error, an error code otherwise
 * @note This is only meanfull for an element node
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_node_add_attrs(WBXMLTreeNode *node,
                                                    WBXMLAttribute **attrs);

/**
 * @brief Add an XML Attribute to a Tree Node structure
 * @param lang_table Language table
 * @param node The Tree Node to modify
 * @param name The XML Attribute name
 * @param value The XML Attribute value
 * @return WBXML_OK if no error, an error code otherwise
 * @note This is only meanfull for an element node
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_node_add_xml_attr(const WBXMLLangEntry *lang_table,
                                                       WBXMLTreeNode *node,
                                                       const WB_UTINY *name,
                                                       const WB_UTINY *value);

/**
 * @brief Add an XML Attributes list to a Tree Node structure
 * @param lang_table Language table
 * @param node  The Tree Node to modify
 * @param attrs The XML Attributes to add
 * @return WBXML_OK if no error, an error code otherwise
 * @note This is only meanfull for an element node
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_node_add_xml_attrs(const WBXMLLangEntry *lang_table,
                                                        WBXMLTreeNode *node,
                                                        const WB_UTINY **attrs);

/**
 * @brief Get an Element Node, given the Element Name
 * @param node   The Tree Node where to start searching
 * @param name   The Element Name we are searching
 * @param recurs If FALSE, only search into direct childs of 'node'
 * @return The found Tree Node, or NULL if not found
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_node_elt_get_from_name(WBXMLTreeNode *node,
                                                                 const char *name,
                                                                 WB_BOOL recurs);

#if defined ( WBXML_SUPPORT_SYNCML )

/**
 * @brief Get the SyncML Data Type of this Tree Node
 * @param node The Tree Node
 * @return The SyncML Data Type of this Tree Node (cf: WBXMLSyncMLDataType enum)
 * @note If no specific Data Type is found, this function returns 'WBXML_SYNCML_DATA_TYPE_NORMAL'
 */
WBXML_DECLARE(WBXMLSyncMLDataType) wbxml_tree_node_get_syncml_data_type(WBXMLTreeNode *node);

#endif /* WBXML_SUPPORT_SYNCML */

/**
 * @brief Check if a node have an Element Node in its children list
 * @param node The Tree Node
 * @return YES if one of the node children is an Element, FALSE otherwise
 */
WBXML_DECLARE(WB_BOOL) wbxml_tree_node_have_child_elt(WBXMLTreeNode *node);

/**
 * @brief Get all children from node
 * @param node The Tree Node
 * @return A list of all children belonging to this node, or NULL if no children found
 */
WBXML_DECLARE(WBXMLList*) wbxml_tree_node_get_all_children(WBXMLTreeNode *node);

/**
 * @brief Create a Tree structure
 * @param lang Tree Language
 * @param orig_charset Original tree charset
 * @return The newly created Tree, or NULL if not enough memory
 * @note The 'orig_charset' is used for further Tree encoding, it does NOT set
 *       the internal Tree representation charset (UTF8 is always used).
 */
WBXML_DECLARE(WBXMLTree *) wbxml_tree_create(WBXMLLanguage lang,
                                             WBXMLCharsetMIBEnum orig_charset);

/**
 * @brief Destroy a Tree structure, and all its nodes
 * @param tree The Tree structure to destroy
 */
WBXML_DECLARE(void) wbxml_tree_destroy(WBXMLTree *tree);

/**
 * @brief Add a Node to a Tree
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param node   The new Tree Node to add
 * @return TRUE is added, or FALSE if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns FALSE, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WB_BOOL) wbxml_tree_add_node(WBXMLTree *tree,
                                           WBXMLTreeNode *parent,
                                           WBXMLTreeNode *node);

/**
 * @brief Extract a Tree Node from its WBXML Tree
 * @param tree  The Tree to modify
 * @param node  The Tree Node to extract
 * @return WBXML_OK if no error, an error code otherwise
 * @note The node is extracted but not freed
 */
WBXML_DECLARE(WBXMLError) wbxml_tree_extract_node(WBXMLTree *tree,
                                                  WBXMLTreeNode *node);

/**
 * @brief Add an Element Node to Tree, given its WBXML Tag
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param tag    Element to add
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_elt(WBXMLTree *tree,
                                                  WBXMLTreeNode *parent,
                                                  WBXMLTag *tag);

/**
 * @brief Add a Tag Element Node to Tree, with its WBXML Attributes
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param tag    Element to add
 * @param attrs  Element attributes
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_elt_with_attrs(WBXMLTree *tree,
                                                             WBXMLTreeNode *parent,
                                                             WBXMLTag *tag,
                                                             WBXMLAttribute **attrs);

/**
 * @brief Add an Element Node to a Tree, given its XML Name
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param name   XML element name to add
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_xml_elt(WBXMLTree *tree,
                                                      WBXMLTreeNode *parent,
                                                      WB_UTINY *name);

/**
 * @brief Add an Element Node to Tree, with its WBXML Attributes, given there XML values
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param name   XML element name to add
 * @param attrs  XML element attributes
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_xml_elt_with_attrs(WBXMLTree *tree,
                                                                 WBXMLTreeNode *parent,
                                                                 WB_UTINY *name,
                                                                 const WB_UTINY **attrs);

/**
 * @brief Add a Text Node to Tree
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param text   Text to add
 * @param len    Text length
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_text(WBXMLTree *tree,
                                                   WBXMLTreeNode *parent,
                                                   const WB_UTINY *text,
                                                   WB_ULONG len);

/**
 * @brief Add CDATA Node to Tree
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_cdata(WBXMLTree *tree,
                                                    WBXMLTreeNode *parent);

/** @todo wbxml_tree_add_cdata_with_text() */

/**
 * @brief Add a Tree Node to Tree
 * @param tree     The Tree to modify
 * @param parent   Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param new_tree The new Tree to add (will be freed when destroying the main Tree, so caller must not free it)
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_tree(WBXMLTree *tree,
                                                   WBXMLTreeNode *parent,
                                                   WBXMLTree *new_tree);

/**
 * @brief Add an Element Node to a Tree, given its XML Name, its attributes and a text content
 * @param tree   The Tree to modify
 * @param parent Parent of the new Node (ie: Position where to add the new Node in Tree)
 * @param name   XML element name to add
 * @param attrs  XML element attributes
 * @param text   Text content for this new element
 * @param len    Text content length
 * @return The newly created node, or NULL if error.
 * @note If 'parent' is NULL: if 'tree' already have a Root Element this function returns NULL, else 'node' becomes the Root Element of 'tree'
 */
WBXML_DECLARE(WBXMLTreeNode *) wbxml_tree_add_xml_elt_with_attrs_and_text(WBXMLTree *tree,
                                                                          WBXMLTreeNode *parent,
                                                                          WB_UTINY *name,
                                                                          const WB_UTINY **attrs,
                                                                          const WB_UTINY *text,
                                                                          WB_ULONG len);

/** @} */

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* WBXML_TREE_H */


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates.commands.elevator;

import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.CommandBase;

/**
 *
 * @author eyal
 */
public class OpenDoor extends CommandBase{

    public OpenDoor(){
        requires(door);
    }

    protected void initialize() {
        setTimeout(RobotMap.DOOR_TIMEOUT);
    }

    protected void execute() {
        door.openDoor();
    }

    protected boolean isFinished() {
        if(overriding)
            return isTimedOut();
        return door.isOpen() || isTimedOut();
    }

    protected void end() {
        door.stop();
    }

    protected void interrupted() {
        end();
    }

}


text:
package org.makersoft.web.mvc.mapping.impl;

import org.makersoft.web.mvc.mapping.AbstractMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 */
public class EditMapping extends AbstractMapping {

	private String[] values = new String[] { "/{id}/edit" };

	private RequestMethod[] requestMethods = { RequestMethod.GET };

	public EditMapping() {
		super(METHOD_EDIT_NAME);
	}

	@Override
	public String[] getValues() {
		return values;
	}

	@Override
	public RequestMethod[] getRequestMethods() {
		return requestMethods;
	}

}


text:
<?php
namespace Shop\Model;
use Think\Model;
/**
 * Created by PhpStorm.
 * User: an
 * Date: 2015/9/12
 * Time: 14:44
 */
class HasIdcodeModel extends  Model{

}


text:
from __future__ import absolute_import
# Copyright (c) 2010-2014 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# @license: http://www.opensource.org/licenses/mit-license.php
# @author: see AUTHORS file

"""Write the shared string table."""
from io import BytesIO

# package imports
from openpyxl.xml.functions import start_tag, end_tag, tag, XMLGenerator

def write_string_table(string_table):
    """Write the string table xml."""
    temp_buffer = BytesIO()
    doc = XMLGenerator(out=temp_buffer)
    start_tag(doc, 'sst', {'xmlns':
            'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
            'uniqueCount': '%d' % len(string_table)})
    for key in string_table:
        start_tag(doc, 'si')
        if key.strip() != key:
            attr = {'xml:space': 'preserve'}
        else:
            attr = {}
        tag(doc, 't', attr, key)
        end_tag(doc, 'si')
    end_tag(doc, 'sst')
    string_table_xml = temp_buffer.getvalue()
    temp_buffer.close()
    return string_table_xml