text:
package org.apache.nifi.processors.standard;

import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class TestCompressContent {

    @Test
    public void testSnappyCompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_COMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_SNAPPY);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertAttributeEquals(CoreAttributes.MIME_TYPE.key(), "application/x-snappy");
        flowFile.assertAttributeEquals("filename", "SampleFile.txt.snappy");
    }

    @Test
    public void testSnappyDecompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_DECOMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_SNAPPY);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.snappy"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");
    }

    @Test
    public void testSnappyHadoopCompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_COMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_SNAPPY_HADOOP);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertAttributeEquals(CoreAttributes.MIME_TYPE.key(), "application/x-snappy-hadoop");
        flowFile.assertAttributeEquals("filename", "SampleFile.txt.snappy");
    }

    @Test
    public void testSnappyHadoopDecompress() {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_DECOMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_SNAPPY_HADOOP);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.assertNotValid();
    }

    @Test
    public void testSnappyFramedCompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_COMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_SNAPPY_FRAMED);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertAttributeEquals(CoreAttributes.MIME_TYPE.key(), "application/x-snappy-framed");
        flowFile.assertAttributeEquals("filename", "SampleFile.txt.sz");
    }

    @Test
    public void testSnappyFramedDecompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_DECOMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_SNAPPY_FRAMED);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.sz"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");
    }

    @Test
    public void testBzip2DecompressConcatenated() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "decompress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "bzip2");
        runner.setProperty(CompressContent.UPDATE_FILENAME, "false");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFileConcat.txt.bz2"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFileConcat.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFileConcat.txt.bz2"); // not updating filename
    }

    @Test
    public void testBzip2Decompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "decompress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "bzip2");
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.bz2"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");

        runner.clearTransferState();
        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile1.txt.bz2"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile1.txt");
    }

    @Test
    public void testProperMimeTypeFromBzip2() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "compress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "bzip2");
        runner.setProperty(CompressContent.UPDATE_FILENAME, "false");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertAttributeEquals("mime.type", "application/x-bzip2");
    }

    @Test
    public void testBzip2DecompressWithBothMimeTypes() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "decompress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_ATTRIBUTE);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        // ensure that we can decompress with a mime type of application/x-bzip2
        final Map<String, String> attributes = new HashMap<>();
        attributes.put("mime.type", "application/x-bzip2");
        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.bz2"), attributes);
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");

        // ensure that we can decompress with a mime type of application/bzip2. The appropriate mime type is
        // application/x-bzip2, but we used to use application/bzip2. We want to ensure that we are still
        // backward compatible.
        runner.clearTransferState();
        attributes.put("mime.type", "application/bzip2");
        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile1.txt.bz2"), attributes);
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile1.txt");
    }

    @Test
    public void testGzipDecompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "decompress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "gzip");
        assertTrue(runner.setProperty(CompressContent.UPDATE_FILENAME, "true").isValid());

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.gz"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");

        runner.clearTransferState();
        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile1.txt.gz"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile1.txt");

        runner.clearTransferState();
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_ATTRIBUTE);
        Map<String, String> attributes = new HashMap<>();
        attributes.put(CoreAttributes.MIME_TYPE.key(), "application/x-gzip");
        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.gz"), attributes);
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");
    }

    @Test
    public void testDeflateDecompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "decompress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "deflate");
        assertTrue(runner.setProperty(CompressContent.UPDATE_FILENAME, "true").isValid());

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.zlib"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        System.err.println(new String(flowFile.toByteArray()));
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");
    }

    @Test
    public void testDeflateCompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "compress");
        runner.setProperty(CompressContent.COMPRESSION_LEVEL, "6");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "deflate");
        assertTrue(runner.setProperty(CompressContent.UPDATE_FILENAME, "true").isValid());

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt.zlib"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt.zlib");
    }

    @Test
    public void testFilenameUpdatedOnCompress() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "compress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "gzip");
        assertTrue(runner.setProperty(CompressContent.UPDATE_FILENAME, "true").isValid());

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertAttributeEquals("filename", "SampleFile.txt.gz");

    }

    @Test
    public void testDecompressFailure() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, "decompress");
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, "gzip");

        byte[] data = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        runner.enqueue(data);

        assertTrue(runner.setProperty(CompressContent.UPDATE_FILENAME, "true").isValid());
        runner.run();
        runner.assertQueueEmpty();
        runner.assertAllFlowFilesTransferred(CompressContent.REL_FAILURE, 1);

        runner.getFlowFilesForRelationship(CompressContent.REL_FAILURE).get(0).assertContentEquals(data);
    }

    @Test
    public void testLz4FramedCompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_COMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_LZ4_FRAMED);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertAttributeEquals(CoreAttributes.MIME_TYPE.key(), "application/x-lz4-framed");
        flowFile.assertAttributeEquals("filename", "SampleFile.txt.lz4");
    }

    @Test
    public void testLz4FramedDecompress() throws Exception {
        final TestRunner runner = TestRunners.newTestRunner(CompressContent.class);
        runner.setProperty(CompressContent.MODE, CompressContent.MODE_DECOMPRESS);
        runner.setProperty(CompressContent.COMPRESSION_FORMAT, CompressContent.COMPRESSION_FORMAT_LZ4_FRAMED);
        runner.setProperty(CompressContent.UPDATE_FILENAME, "true");

        runner.enqueue(Paths.get("src/test/resources/CompressedData/SampleFile.txt.lz4"));
        runner.run();

        runner.assertAllFlowFilesTransferred(CompressContent.REL_SUCCESS, 1);
        MockFlowFile flowFile = runner.getFlowFilesForRelationship(CompressContent.REL_SUCCESS).get(0);
        flowFile.assertContentEquals(Paths.get("src/test/resources/CompressedData/SampleFile.txt"));
        flowFile.assertAttributeEquals("filename", "SampleFile.txt");
    }
}


text:
Keshif
======

**Keshif** is a visual data browser that makes it easier to browse and understand your data. It presents visual summaries of your data properties, such as who, what, when and where, in its facets and timeline. You can discover relations between attributes through exploration. Filtering follows a consistent design within and across facets. After each step of exploration, the most relevant results and data properties are shown first, as they are dynamically and smoothly re-ordered.

To start using Keshif
* Get the source code from github.
* Check out the [wiki](https://github.com/adilyalcin/Keshif/wiki).
* Explore the demos and source codes.

[![Demo](https://github.com/adilyalcin/Keshif/blob/master/demo/demo_img/demo.png)](http://keshif.me)

### License

BSD 3 clause (c) University of Maryland

### Author

Mehmet Adil Yalcin @ HCIL, University of Maryland, College Park

Funded in part by Huawei.

redpajama_set_name: RedPajamaGithub


text:
id: if-else-in-JSX
title: If-Else in JSX
layout: tips
permalink: tips/if-else-in-JSX.html
prev: inline-styles.html
next: self-closing-tag.html
---

`if-else` statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:

```js
// This JSX:
ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);

// Is transformed to this JS:
ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);
```

This means that `if` statements don't fit in. Take this example:

```js
// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>

// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
```

That's not valid JS. You probably want to make use of a ternary expression:

```js
ReactDOM.render(<div id={condition ? 'msg' : null}>Hello World!</div>, mountNode);
```

If a ternary expression isn't robust enough, you can use `if` statements outside of your JSX to determine which components should be used:

```js
var loginButton;
if (loggedIn) {
  loginButton = <LogoutButton />;
} else {
  loginButton = <LoginButton />;
}

return (
  <nav>
    <Home />
    {loginButton}
  </nav>
);
```

Or if you prefer a more "inline" aesthetic, define [immediately-invoked function expressions](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) _inside_ your JSX:

```js
return (
  <section>
    <h1>Color</h1>
    <h3>Name</h3>
    <p>{this.state.color || "white"}</p>
    <h3>Hex</h3>
    <p>
      {(() => {
        switch (this.state.color) {
          case "red":   return "#FF0000";
          case "green": return "#00FF00";
          case "blue":  return "#0000FF";
          default:      return "#FFFFFF";
        }
      })()}
    </p>
  </section>
);
```

> Note:
>
> In the example above, an ES6 [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is utilized to lexically bind the value of `this`.

Try using it today with the [Babel REPL](https://babeljs.io/repl/).


text:
docker build -t travis-ci https://goo.gl/vS7ep1

docker run -v $(pwd):/usr/src/app -it travis-ci encrypt var=var --add


text:
#pragma once

// namespace tokenizer
namespace tokenizer {
	/**
	 * Definition of All Token-types
	 */
	enum class TokenType : int {
		// Special Tokens
		UNDEFINED  = -1,
		EOFTOK     =  0,

		// Identifier
		IDENTIFIER =  1,

		// Stack Expressions
		STACK_START,
		STACK_END,

		// Data Types
		INTEGER,
		FLOAT,
		STRING,
		NIL,
		BOOLEAN_TRUE,
		BOOLEAN_FALSE,
		SYMBOL,

		// Instructions
		// - Basic Arithmec Operations
		INST_PLUS,
		INST_MINUS,
		INST_MULTIPLICATION,
		INST_DIVISION,
		// - Basic Stack Operations
		INST_DROP,
		// - Environment Operation
		INST_BIND,
		// - Control Operation
		INST_IF,
	};
} // namespace tokenizer


text:
package com.linecorp.armeria.server.docs;

import static com.google.common.collect.ImmutableMap.toImmutableMap;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.reflections.Configuration;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.io.Resources;

/**
 * A supporting base class for implementing the standard pattern of extracting docstrings
 * from arbitrary files in a particular classpath location.
 */
public abstract class DocStringExtractor {

    private static final Logger logger = LoggerFactory.getLogger(DocStringExtractor.class);

    private static final Map<ClassLoader, Map<String, String>> cached = new ConcurrentHashMap<>();

    private final String path;

    protected DocStringExtractor(String defaultPath, String pathPropertyName) {
        path = computePath(defaultPath, pathPropertyName);
    }

    /**
     * Extract all docstrings from files at the configured path, delegating to
     * {@link #getDocStringsFromFiles(Map)} for actual processing.
     */
    public Map<String, String> getAllDocStrings(ClassLoader classLoader) {
        return cached.computeIfAbsent(classLoader, this::getAllDocStrings0);
    }

    private Map<String, String> getAllDocStrings0(ClassLoader classLoader) {
        final Configuration configuration = new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder().includePackage(path))
                .setUrls(ClasspathHelper.forPackage(path))
                .addClassLoader(classLoader)
                .setScanners(new ResourcesScanner());
        if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) {
            return Collections.emptyMap();
        }
        final Map<String, byte[]> files = new Reflections(configuration)
                .getResources(this::acceptFile).stream()
                .map(f -> {
                    try {
                        URL url = classLoader.getResource(f);
                        if (url == null) {
                            throw new IllegalStateException("not found: " + f);
                        }
                        return new SimpleImmutableEntry<>(f, Resources.toByteArray(url));
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                })
                .collect(toImmutableMap(Entry::getKey, Entry::getValue));
        return getDocStringsFromFiles(files);
    }

    /**
     * Determine whether the file at {@code filename} should be processed by the {@link DocStringExtractor}.
     * This will usually look at the file extension, but the default implementation can be used to check all
     * files at a particular path.
     */
    protected boolean acceptFile(String filename) {
        return true;
    }

    /**
     * Extracts a {@link Map} of docstrings from the given {@link Map} of path to file contents. The result will
     * generally be used within a {@link DocServicePlugin} for finding docstrings of items.
     */
    protected abstract Map<String, String> getDocStringsFromFiles(Map<String, byte[]> files);

    private static String computePath(String defaultPath, String pathPropertyName) {
        String dir = System.getProperty(pathPropertyName, defaultPath);
        if (dir.startsWith("/") || dir.startsWith("\\")) {
            dir = dir.substring(1);
        }
        if (dir.endsWith("/") || dir.endsWith("\\")) {
            dir = dir.substring(0, dir.length() - 1);
        }
        logger.info("Using {}: {}", pathPropertyName, dir);
        return dir;
    }
}


text:
module SlimFormObject
  class Validator
    include ::HelperMethods

    attr_reader :form_object, :data_objects_arr

    def initialize(form_object)
      @form_object                          = form_object
      @data_objects_arr                     = form_object.data_objects_arr
    end

    def validate_form_object
      validation_objects(data_objects_arr)
      form_object.after_validation_form_block.call(form_object)
    end

    def allow_to_save_object?(object)
      form_object.allow_to_save_object_block.call(object)
    end

    def allow_to_validate_object?(data_object)
      form_object.allow_to_validate_object_block.call(data_object)
    end

    def empty_attributes?(attributes)
      attributes.empty?
    end

    def only_blank_strings_in_attributes?(attributes)
      return false if empty_attributes?(attributes)
      attributes.each { |key, value| return false if value&.to_s&.strip != '' }
      true
    end

    def only_blank_or_empty_attributes(attributes)
      empty_attributes?(attributes) or only_blank_strings_in_attributes?(attributes)
    end

    def blank_or_empty_object?(data_object, except_fileds: [])
      attributes = data_object.attributes.reject { |key| except_fileds.map{|name| name.to_s }.include?(key.to_s) }
      only_blank_or_empty_attributes(attributes) and data_object.nested.empty?
    end

    def allow_object_processing?(data_object)
      form_object.allow_object_processing_block.call(data_object)
    end

    private

    def validation_objects(objects)
      objects.each do |data_object|
        next unless allow_to_validate_object?(data_object)
        set_errors( snake(data_object.model), data_object.object.errors ) unless data_object.object.valid?
        validation_objects(data_object.nested)
      end
    end

    def set_errors(object_name, object_errors)
      object_errors.each do |attribute, message|
        form_object.errors.add(object_name, { attribute => message})
      end
    end
  end
end


text:
namespace ewok {

  Application::Application()
    : delegate_(NULL)
  {
  }

  void Application::init(IAppDelegate &del, IResourceManager &res)
  {
    LogInfo << "Application::init";
    resManager_ = &res;

    Random::init();

    renderer_.init();

    delegate_ = &del;
    delegate_->init(*this);
  }

  void Application::deinit()
  {
    delegate_->deinit();
    renderer_.deinit();
  }

  void Application::pause()
  {
    delegate_->pause();
  }

  void Application::resume()
  {
    delegate_->resume();
  }

  void Application::update(float duration)
  {
    delegate_->update(duration);

    animations_.update(duration);
    physics_.update(duration);
  }

  void Application::render()
  {
    renderer_.render();
  }

  void Application::touchBegin(const Touch &t)
  {
    LogInfo << "App touch begin: " << t.x << " / " << t.y;
    delegate_->touchBegin(t);
  }

  void Application::touchEnd(const Touch &t)
  {
    LogInfo << "App touch end: " << t.x << " / " << t.y;
    delegate_->touchEnd(t);
  }

  Animations &Application::animations()
  {
    return animations_;
  }

  Physics &Application::physics()
  {
    return physics_;
  }

  Renderer &Application::renderer()
  {
    return renderer_;
  }

  IResourceManager &Application::resources()
  {
    return *resManager_;
  }

} // namespace ewok


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ServiceFabric.Mocks.NetCoreTests.Services;

namespace ServiceFabric.Mocks.NetCoreTests.ServiceProxyTests
{
    [TestClass]
    public class MockServiceProxyTests
    {
        [TestMethod]
        public void TestNetStandardCompatibility()
        {
            var proxy = new MockServiceProxy<MyStatelessService>();
            Assert.IsNotNull(proxy);
            Assert.IsNull(proxy.GetType().GetProperty("ServicePartitionClient"));
            Assert.IsNotNull(proxy.GetType().GetProperty("ServicePartitionClient2"));
        }
    }
}


text:
Function.bind || (Function.prototype.bind = new function () {

    function newApply(Constructor, args) {
        var argNames = [],
            len = args.length,
            i = 0;
        while (i < len) {
            argNames.push('arg' + i);
            i++;
        }
        argNames = argNames.join(',');
        return new Function(
            'Constructor',
            argNames,
            'return new Constructor(' + argNames + ')'
        ).apply(window, [Constructor].concat(args));
    }

    return function (boundThis) {
        var boundArgs = Array.slice(arguments, 1),
            targetFunc = this;
        function boundFunc() {
            var proto,
                args,
                len;
            function NOP() {}
            if (boundFunc._protoMagic) {
                boundFunc._protoMagic = false;
                NOP.prototype = this;
                NOP.prototype.constructor = targetFunc;
                return new NOP;
            } else {
                args = boundArgs.concat(Array.from(arguments));
                len = args.length;
            }
            if (this instanceof boundFunc) {
                boundFunc._protoMagic = true;
                switch (len) {
                    case 0:
                        proto = new targetFunc;
                        break;
                    case 1:
                        proto = new targetFunc(args[0]);
                        break;
                    case 2:
                        proto = new targetFunc(args[0], args[1]);
                        break;
                    default:
                        proto = newApply(targetFunc, args);
                }
                NOP.prototype = proto;
                boundFunc.prototype = new NOP;
                boundFunc.prototype.constructor = boundFunc;
                return new boundFunc;
            }
            switch (len) {
                case 0:
                    return targetFunc.call(boundThis);
                case 1:
                    return targetFunc.call(boundThis, args[0]);
                case 2:
                    return targetFunc.call(boundThis, args[0], args[1]);
            }
            return targetFunc.apply(boundThis, args);
        }
        if ('function' != typeof targetFunc) {
            throw new TypeError('Function.prototype.bind ' +
                                'called on non-function');
        }
        boundFunc._protoMagic = false;
        return boundFunc;
    };

});


text:
#pragma once

#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC

#import <OpenAL/al.h>
#import <AudioToolbox/AudioToolbox.h>

#include <string>
#include <mutex>
#include <vector>

#include "platform/CCPlatformMacros.h"

#define QUEUEBUFFER_NUM 3
#define QUEUEBUFFER_TIME_STEP 0.1

#define QUOTEME_(x) #x
#define QUOTEME(x) QUOTEME_(x)

#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
#define ALOGV(fmt, ...) printf("V/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
#else
#define ALOGV(fmt, ...) do {} while(false)
#endif
#define ALOGD(fmt, ...) printf("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
#define ALOGI(fmt, ...) printf("I/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
#define ALOGW(fmt, ...) printf("W/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
#define ALOGE(fmt, ...) printf("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)

#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
#define CHECK_AL_ERROR_DEBUG() \
do { \
    GLenum __error = alGetError(); \
    if (__error) { \
        ALOGE("OpenAL error 0x%04X in %s %s %d\n", __error, __FILE__, __FUNCTION__, __LINE__); \
    } \
} while (false)
#else
#define CHECK_AL_ERROR_DEBUG()
#endif

NS_CC_BEGIN
namespace experimental{

class AudioEngineImpl;
class AudioPlayer;

class AudioCache
{
public:

    enum class State
    {
        INITIAL,
        LOADING,
        READY,
        FAILED
    };

    AudioCache();
    ~AudioCache();

    void addPlayCallback(const std::function<void()>& callback);

    void addLoadCallback(const std::function<void(bool)>& callback);

protected:
    void setSkipReadDataTask(bool isSkip) { _isSkipReadDataTask = isSkip; };
    void readDataTask(unsigned int selfId);

    void invokingPlayCallbacks();

    void invokingLoadCallbacks();

    //pcm data related stuff
    ALsizei _dataSize;
    ALenum _format;
    ALsizei _sampleRate;
    float _duration;
    int _bytesPerFrame;
    AudioStreamBasicDescription _outputFormat;

    /*Cache related stuff;
     * Cache pcm data when sizeInBytes less than PCMDATA_CACHEMAXSIZE
     */
    ALuint _alBufferId;
    char* _pcmData;
    SInt64 _bytesOfRead;

    /*Queue buffer related stuff
     *  Streaming in openal when sizeInBytes greater then PCMDATA_CACHEMAXSIZE
     */
    char* _queBuffers[QUEUEBUFFER_NUM];
    ALsizei _queBufferSize[QUEUEBUFFER_NUM];
    UInt32 _queBufferFrames;
    UInt32 _queBufferBytes;

    std::mutex _playCallbackMutex;
    std::vector< std::function<void()> > _playCallbacks;

    // loadCallbacks doesn't need mutex since it's invoked only in Cocos thread.
    std::vector< std::function<void(bool)> > _loadCallbacks;

    std::mutex _readDataTaskMutex;

    State _state;

    std::shared_ptr<bool> _isDestroyed;
    std::string _fileFullPath;
    unsigned int _id;
    bool _isLoadingFinished;
    bool _isSkipReadDataTask;

    friend class AudioEngineImpl;
    friend class AudioPlayer;
} ;

}
NS_CC_END

#endif


text:
<!DOCTYPE html>

    <title>Хватит писать // Marat Sharifullin</title>

        <meta charset="utf-8">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <meta name="author" content="">
        <meta property="og:title" content="Хватит писать" />
    <meta property="og:description" content="" />
    <meta property="og:type" content="website" />
    <meta property="og:locale" content="en_US" />
    <meta property="og:url" content="//sharifmarat.github.io/mabsurdation/enough-writing/" />

    <link href="" rel="alternate" type="application/rss+xml" title="Marat Sharifullin" />
    <link rel="shortcut icon" href="/favicon.ico">

    <link href="//sharifmarat.github.io/webfonts/ptserif/main.css" rel='stylesheet' type='text/css'>
    <link href="//sharifmarat.github.io/webfonts/source-code-pro/main.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" href="//sharifmarat.github.io/css/style.css">

    <link href="http://gmpg.org/xfn/11" rel="profile">

    <meta name="generator" content="Hugo 0.92.1" />

        This is a copy or a backup of ifnull.org.

            Marat Sharifullin

                Blog

                Projects

                Archive

                Mabsurdation

                Gallery

                Contact

Хватит писать

                    <time datetime='2019-05-08T00:00:00.000+00:00' itemprop="datePublished">2019-05-08</time>

                Comments

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

            © 2022 Marat Sharifullin
            Powered by Hugo with theme Minos

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/tomorrow-night.min.css" integrity="sha256-2wL88NKUqvJi/ExflDzkzUumjUM73mcK2gBvBBeLvTk=" crossorigin="anonymous" />


text:
package io.coala.guice.config;

import io.coala.config.InjectConfig;

import java.lang.reflect.Field;

import javax.inject.Inject;

import org.apache.commons.configuration.Configuration;

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

/**
 * {@link ConfigTypeListener} inspired by here
 *
 * @version $Revision: 300 $
 * @author Rick
 *
 */
public class ConfigTypeListener implements TypeListener
{

	/** */
	private final Configuration configuration;

	/**
	 * {@link ConfigTypeListener} constructor
	 *
	 * @param configuration
	 */
	@Inject
	public ConfigTypeListener(final Configuration configuration)
	{
		this.configuration = configuration;
	}

	@Override
	public <T> void hear(final TypeLiteral<T> type,
			final TypeEncounter<T> encounter)
	{
		for (Field field : type.getRawType().getDeclaredFields())
		{
			if (field.isAnnotationPresent(InjectConfig.class))
			{
				encounter.register(new ConfigMembersInjector<T>(field,
						configuration));
			}
		}
	}
}


text:
This modules allows you to set seed points in a given field and interactively change their location.

**Detailed Description**

The **input** is a field containing a mesh.

The **Geometry** output connects directly to the ViewScene module and produces points that can be interactively moved by holding shift while dragging them. This will update the points output to the Field port.

The **Field** output the points as a point cloud field.


text:
<?php
/**
 * A special form element which allows the user to enter arbitrary HTML code
 * in a form.
 * @author ekow
 * @ingroup Forms
 */
class HTMLBox extends Container
{
    public $content;

    /**
     * Creates a new HTML box
     * @code
     * $box = new HTMLBox("
Hello World!
");
     * @endcode
     * @param string $content
     */
    public function __construct($content)
    {
        $this->content  = $content;
    }

    public function setContent($content)
    {
        $this->content = $content;
        return $this;
    }

    public function render()
    {
        return $this->content;
    }

    public function hasLabel()
    {
    	return true;
    }
}


text:
package org.springframework.orm.jpa.support;

import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.PersistenceProperty;
import javax.persistence.PersistenceUnit;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.InjectionMetadata;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.jndi.JndiLocatorDelegate;
import org.springframework.jndi.JndiTemplate;
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.orm.jpa.EntityManagerProxy;
import org.springframework.orm.jpa.ExtendedEntityManagerCreator;
import org.springframework.orm.jpa.SharedEntityManagerCreator;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

/**
 * BeanPostProcessor that processes {@link javax.persistence.PersistenceUnit}
 * and {@link javax.persistence.PersistenceContext} annotations, for injection of
 * the corresponding JPA resources {@link javax.persistence.EntityManagerFactory}
 * and {@link javax.persistence.EntityManager}. Any such annotated fields or methods
 * in any Spring-managed object will automatically be injected.
 *
 *
This post-processor will inject sub-interfaces of {@code EntityManagerFactory}
 * and {@code EntityManager} if the annotated fields or methods are declared as such.
 * The actual type will be verified early, with the exception of a shared ("transactional")
 * {@code EntityManager} reference, where type mismatches might be detected as late
 * as on the first actual invocation.
 *
 *
Note: In the present implementation, PersistenceAnnotationBeanPostProcessor
 * only supports {@code @PersistenceUnit} and {@code @PersistenceContext}
 * with the "unitName" attribute, or no attribute at all (for the default unit).
 * If those annotations are present with the "name" attribute at the class level,
 * they will simply be ignored, since those only serve as deployment hint
 * (as per the Java EE specification).
 *
 *
This post-processor can either obtain EntityManagerFactory beans defined
 * in the Spring application context (the default), or obtain EntityManagerFactory
 * references from JNDI ("persistence unit references"). In the bean case,
 * the persistence unit name will be matched against the actual deployed unit,
 * with the bean name used as fallback unit name if no deployed name found.
 * Typically, Spring's {@link org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean}
 * will be used for setting up such EntityManagerFactory beans. Alternatively,
 * such beans may also be obtained from JNDI, e.g. using the {@code jee:jndi-lookup}
 * XML configuration element (with the bean name matching the requested unit name).
 * In both cases, the post-processor definition will look as simple as this:
 *
 *

 * <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

 *
 * In the JNDI case, specify the corresponding JNDI names in this post-processor's
 * {@link #setPersistenceUnits "persistenceUnits" map}, typically with matching
 * {@code persistence-unit-ref} entries in the Java EE deployment descriptor.
 * By default, those names are considered as resource references (according to the
 * Java EE resource-ref convention), located underneath the "java:comp/env/" namespace.
 * For example:
 *
 *

 * <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
 *   <property name="persistenceUnits">
 *     <map/gt;
 *       <entry key="unit1" value="persistence/unit1"/>
 *       <entry key="unit2" value="persistence/unit2"/>
 *     </map/gt;
 *   </property>
 * </bean>

 *
 * In this case, the specified persistence units will always be resolved in JNDI
 * rather than as Spring-defined beans. The entire persistence unit deployment,
 * including the weaving of persistent classes, is then up to the Java EE server.
 * Persistence contexts (i.e. EntityManager references) will be built based on
 * those server-provided EntityManagerFactory references, using Spring's own
 * transaction synchronization facilities for transactional EntityManager handling
 * (typically with Spring's {@code @Transactional} annotation for demarcation
 * and {@link org.springframework.transaction.jta.JtaTransactionManager} as backend).
 *
 *
If you prefer the Java EE server's own EntityManager handling, specify entries
 * in this post-processor's {@link #setPersistenceContexts "persistenceContexts" map}
 * (or {@link #setExtendedPersistenceContexts "extendedPersistenceContexts" map},
 * typically with matching {@code persistence-context-ref} entries in the
 * Java EE deployment descriptor. For example:
 *
 *

 * <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
 *   <property name="persistenceContexts">
 *     <map/gt;
 *       <entry key="unit1" value="persistence/context1"/>
 *       <entry key="unit2" value="persistence/context2"/>
 *     </map/gt;
 *   </property>
 * </bean>

 *
 * If the application only obtains EntityManager references in the first place,
 * this is all you need to specify. If you need EntityManagerFactory references
 * as well, specify entries for both "persistenceUnits" and "persistenceContexts",
 * pointing to matching JNDI locations.
 *
 *
NOTE: In general, do not inject EXTENDED EntityManagers into STATELESS beans,
 * i.e. do not use {@code @PersistenceContext} with type {@code EXTENDED} in
 * Spring beans defined with scope 'singleton' (Spring's default scope).
 * Extended EntityManagers are not thread-safe, hence they must not be used
 * in concurrently accessed beans (which Spring-managed singletons usually are).
 *
 *
Note: A default PersistenceAnnotationBeanPostProcessor will be registered
 * by the "context:annotation-config" and "context:component-scan" XML tags.
 * Remove or turn off the default annotation configuration there if you intend
 * to specify a custom PersistenceAnnotationBeanPostProcessor bean definition.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 2.0
 * @see javax.persistence.PersistenceUnit
 * @see javax.persistence.PersistenceContext
 */
@SuppressWarnings("serial")
public class PersistenceAnnotationBeanPostProcessor
		implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor,
		MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware, Serializable {

	/* Check JPA 2.1 PersistenceContext.synchronization() attribute */
	private static final Method synchronizationAttribute =
			ClassUtils.getMethodIfAvailable(PersistenceContext.class, "synchronization");

	private Object jndiEnvironment;

	private boolean resourceRef = true;

	private transient Map<String, String> persistenceUnits;

	private transient Map<String, String> persistenceContexts;

	private transient Map<String, String> extendedPersistenceContexts;

	private transient String defaultPersistenceUnitName = "";

	private int order = Ordered.LOWEST_PRECEDENCE - 4;

	private transient ListableBeanFactory beanFactory;

	private transient final Map<String, InjectionMetadata> injectionMetadataCache =
			new ConcurrentHashMap<String, InjectionMetadata>(64);

	private final Map<Object, EntityManager> extendedEntityManagersToClose =
			new ConcurrentHashMap<Object, EntityManager>(16);

	/**
	 * Set the JNDI template to use for JNDI lookups.
	 * @see org.springframework.jndi.JndiAccessor#setJndiTemplate
	 */
	public void setJndiTemplate(Object jndiTemplate) {
		this.jndiEnvironment = jndiTemplate;
	}

	/**
	 * Set the JNDI environment to use for JNDI lookups.
	 * @see org.springframework.jndi.JndiAccessor#setJndiEnvironment
	 */
	public void setJndiEnvironment(Properties jndiEnvironment) {
		this.jndiEnvironment = jndiEnvironment;
	}

	/**
	 * Set whether the lookup occurs in a J2EE container, i.e. if the prefix
	 * "java:comp/env/" needs to be added if the JNDI name doesn't already
	 * contain it. PersistenceAnnotationBeanPostProcessor's default is "true".
	 * @see org.springframework.jndi.JndiLocatorSupport#setResourceRef
	 */
	public void setResourceRef(boolean resourceRef) {
		this.resourceRef = resourceRef;
	}

	/**
	 * Specify the persistence units for EntityManagerFactory lookups,
	 * as a Map from persistence unit name to persistence unit JNDI name
	 * (which needs to resolve to an EntityManagerFactory instance).
	 *
JNDI names specified here should refer to {@code persistence-unit-ref}
	 * entries in the Java EE deployment descriptor, matching the target persistence unit.
	 *
In case of no unit name specified in the annotation, the specified value
	 * for the {@link #setDefaultPersistenceUnitName default persistence unit}
	 * will be taken (by default, the value mapped to the empty String),
	 * or simply the single persistence unit if there is only one.
	 *
This is mainly intended for use in a Java EE environment, with all lookup
	 * driven by the standard JPA annotations, and all EntityManagerFactory
	 * references obtained from JNDI. No separate EntityManagerFactory bean
	 * definitions are necessary in such a scenario.
	 *
If no corresponding "persistenceContexts"/"extendedPersistenceContexts"
	 * are specified, {@code @PersistenceContext} will be resolved to
	 * EntityManagers built on top of the EntityManagerFactory defined here.
	 * Note that those will be Spring-managed EntityManagers, which implement
	 * transaction synchronization based on Spring's facilities.
	 * If you prefer the Java EE server's own EntityManager handling,
	 * specify corresponding "persistenceContexts"/"extendedPersistenceContexts".
	 */
	public void setPersistenceUnits(Map<String, String> persistenceUnits) {
		this.persistenceUnits = persistenceUnits;
	}

	/**
	 * Specify the transactional persistence contexts for EntityManager lookups,
	 * as a Map from persistence unit name to persistence context JNDI name
	 * (which needs to resolve to an EntityManager instance).
	 *
JNDI names specified here should refer to {@code persistence-context-ref}
	 * entries in the Java EE deployment descriptors, matching the target persistence unit
	 * and being set up with persistence context type {@code Transaction}.
	 *
In case of no unit name specified in the annotation, the specified value
	 * for the {@link #setDefaultPersistenceUnitName default persistence unit}
	 * will be taken (by default, the value mapped to the empty String),
	 * or simply the single persistence unit if there is only one.
	 *
This is mainly intended for use in a Java EE environment, with all
	 * lookup driven by the standard JPA annotations, and all EntityManager
	 * references obtained from JNDI. No separate EntityManagerFactory bean
	 * definitions are necessary in such a scenario, and all EntityManager
	 * handling is done by the Java EE server itself.
	 */
	public void setPersistenceContexts(Map<String, String> persistenceContexts) {
		this.persistenceContexts = persistenceContexts;
	}

	/**
	 * Specify the extended persistence contexts for EntityManager lookups,
	 * as a Map from persistence unit name to persistence context JNDI name
	 * (which needs to resolve to an EntityManager instance).
	 *
JNDI names specified here should refer to {@code persistence-context-ref}
	 * entries in the Java EE deployment descriptors, matching the target persistence unit
	 * and being set up with persistence context type {@code Extended}.
	 *
In case of no unit name specified in the annotation, the specified value
	 * for the {@link #setDefaultPersistenceUnitName default persistence unit}
	 * will be taken (by default, the value mapped to the empty String),
	 * or simply the single persistence unit if there is only one.
	 *
This is mainly intended for use in a Java EE environment, with all
	 * lookup driven by the standard JPA annotations, and all EntityManager
	 * references obtained from JNDI. No separate EntityManagerFactory bean
	 * definitions are necessary in such a scenario, and all EntityManager
	 * handling is done by the Java EE server itself.
	 */
	public void setExtendedPersistenceContexts(Map<String, String> extendedPersistenceContexts) {
		this.extendedPersistenceContexts = extendedPersistenceContexts;
	}

	/**
	 * Specify the default persistence unit name, to be used in case
	 * of no unit name specified in an {@code @PersistenceUnit} /
	 * {@code @PersistenceContext} annotation.
	 *
This is mainly intended for lookups in the application context,
	 * indicating the target persistence unit name (typically matching
	 * the bean name), but also applies to lookups in the
	 * {@link #setPersistenceUnits "persistenceUnits"} /
	 * {@link #setPersistenceContexts "persistenceContexts"} /
	 * {@link #setExtendedPersistenceContexts "extendedPersistenceContexts"} map,
	 * avoiding the need for duplicated mappings for the empty String there.
	 *
Default is to check for a single EntityManagerFactory bean
	 * in the Spring application context, if any. If there are multiple
	 * such factories, either specify this default persistence unit name
	 * or explicitly refer to named persistence units in your annotations.
	 */
	public void setDefaultPersistenceUnitName(String unitName) {
		this.defaultPersistenceUnitName = (unitName != null ? unitName : "");
	}

	public void setOrder(int order) {
	  this.order = order;
	}

	@Override
	public int getOrder() {
	  return this.order;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		if (beanFactory instanceof ListableBeanFactory) {
			this.beanFactory = (ListableBeanFactory) beanFactory;
		}
	}

	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		if (beanType != null) {
			InjectionMetadata metadata = findPersistenceMetadata(beanName, beanType, null);
			metadata.checkConfigMembers(beanDefinition);
		}
	}

	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}

	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		return true;
	}

	@Override
	public PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

		InjectionMetadata metadata = findPersistenceMetadata(beanName, bean.getClass(), pvs);
		try {
			metadata.inject(bean, beanName, pvs);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of persistence dependencies failed", ex);
		}
		return pvs;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Override
	public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
		EntityManager emToClose = this.extendedEntityManagersToClose.remove(bean);
		EntityManagerFactoryUtils.closeEntityManager(emToClose);
	}

	private InjectionMetadata findPersistenceMetadata(String beanName, final Class<?> clazz, PropertyValues pvs) {
		// Fall back to class name as cache key, for backwards compatibility with custom callers.
		String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
		// Quick check on the concurrent map first, with minimal locking.
		InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
		if (InjectionMetadata.needsRefresh(metadata, clazz)) {
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey);
				if (InjectionMetadata.needsRefresh(metadata, clazz)) {
					if (metadata != null) {
						metadata.clear(pvs);
					}
					try {
						metadata = buildPersistenceMetadata(clazz);
						this.injectionMetadataCache.put(cacheKey, metadata);
					}
					catch (NoClassDefFoundError err) {
						throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() +
								"] for persistence metadata: could not find class that it depends on", err);
					}
				}
			}
		}
		return metadata;
	}

	private InjectionMetadata buildPersistenceMetadata(final Class<?> clazz) {
		LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
		Class<?> targetClass = clazz;

		do {
			final LinkedList<InjectionMetadata.InjectedElement> currElements =
					new LinkedList<InjectionMetadata.InjectedElement>();

			ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
				@Override
				public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
					if (field.isAnnotationPresent(PersistenceContext.class) ||
							field.isAnnotationPresent(PersistenceUnit.class)) {
						if (Modifier.isStatic(field.getModifiers())) {
							throw new IllegalStateException("Persistence annotations are not supported on static fields");
						}
						currElements.add(new PersistenceElement(field, field, null));
					}
				}
			});

			ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
				@Override
				public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
					Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
					if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
						return;
					}
					if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) ||
							bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) &&
							method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
						if (Modifier.isStatic(method.getModifiers())) {
							throw new IllegalStateException("Persistence annotations are not supported on static methods");
						}
						if (method.getParameterTypes().length != 1) {
							throw new IllegalStateException("Persistence annotation requires a single-arg method: " + method);
						}
						PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
						currElements.add(new PersistenceElement(method, bridgedMethod, pd));
					}
				}
			});

			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		return new InjectionMetadata(clazz, elements);
	}

	/**
	 * Return a specified persistence unit for the given unit name,
	 * as defined through the "persistenceUnits" map.
	 * @param unitName the name of the persistence unit
	 * @return the corresponding EntityManagerFactory,
	 * or {@code null} if none found
	 * @see #setPersistenceUnits
	 */
	protected EntityManagerFactory getPersistenceUnit(String unitName) {
		if (this.persistenceUnits != null) {
			String unitNameForLookup = (unitName != null ? unitName : "");
			if ("".equals(unitNameForLookup)) {
				unitNameForLookup = this.defaultPersistenceUnitName;
			}
			String jndiName = this.persistenceUnits.get(unitNameForLookup);
			if (jndiName == null && "".equals(unitNameForLookup) && this.persistenceUnits.size() == 1) {
				jndiName = this.persistenceUnits.values().iterator().next();
			}
			if (jndiName != null) {
				try {
					return lookup(jndiName, EntityManagerFactory.class);
				}
				catch (Exception ex) {
					throw new IllegalStateException("Could not obtain EntityManagerFactory [" + jndiName + "] from JNDI", ex);
				}
			}
		}
		return null;
	}

	/**
	 * Return a specified persistence context for the given unit name, as defined
	 * through the "persistenceContexts" (or "extendedPersistenceContexts") map.
	 * @param unitName the name of the persistence unit
	 * @param extended whether to obtain an extended persistence context
	 * @return the corresponding EntityManager, or {@code null} if none found
	 * @see #setPersistenceContexts
	 * @see #setExtendedPersistenceContexts
	 */
	protected EntityManager getPersistenceContext(String unitName, boolean extended) {
		Map<String, String> contexts = (extended ? this.extendedPersistenceContexts : this.persistenceContexts);
		if (contexts != null) {
			String unitNameForLookup = (unitName != null ? unitName : "");
			if ("".equals(unitNameForLookup)) {
				unitNameForLookup = this.defaultPersistenceUnitName;
			}
			String jndiName = contexts.get(unitNameForLookup);
			if (jndiName == null && "".equals(unitNameForLookup) && contexts.size() == 1) {
				jndiName = contexts.values().iterator().next();
			}
			if (jndiName != null) {
				try {
					return lookup(jndiName, EntityManager.class);
				}
				catch (Exception ex) {
					throw new IllegalStateException("Could not obtain EntityManager [" + jndiName + "] from JNDI", ex);
				}
			}
		}
		return null;
	}

	/**
	 * Find an EntityManagerFactory with the given name in the current Spring
	 * application context, falling back to a single default EntityManagerFactory
	 * (if any) in case of no unit name specified.
	 * @param unitName the name of the persistence unit (may be {@code null} or empty)
	 * @param requestingBeanName the name of the requesting bean
	 * @return the EntityManagerFactory
	 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
	 */
	protected EntityManagerFactory findEntityManagerFactory(String unitName, String requestingBeanName)
			throws NoSuchBeanDefinitionException {

		if (this.beanFactory == null) {
			throw new IllegalStateException("ListableBeanFactory required for EntityManagerFactory bean lookup");
		}
		String unitNameForLookup = (unitName != null ? unitName : "");
		if ("".equals(unitNameForLookup)) {
			unitNameForLookup = this.defaultPersistenceUnitName;
		}
		if (!"".equals(unitNameForLookup)) {
			return findNamedEntityManagerFactory(unitNameForLookup, requestingBeanName);
		}
		else {
			return findDefaultEntityManagerFactory(requestingBeanName);
		}
	}

	/**
	 * Find an EntityManagerFactory with the given name in the current
	 * Spring application context.
	 * @param unitName the name of the persistence unit (never empty)
	 * @param requestingBeanName the name of the requesting bean
	 * @return the EntityManagerFactory
	 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
	 */
	protected EntityManagerFactory findNamedEntityManagerFactory(String unitName, String requestingBeanName)
			throws NoSuchBeanDefinitionException {

		EntityManagerFactory emf = EntityManagerFactoryUtils.findEntityManagerFactory(this.beanFactory, unitName);
		if (this.beanFactory instanceof ConfigurableBeanFactory) {
			((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
		}
		return emf;
	}

	/**
	 * Find a single default EntityManagerFactory in the Spring application context.
	 * @return the default EntityManagerFactory
	 * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
	 */
	protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
			throws NoSuchBeanDefinitionException {

		String[] beanNames =
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
		if (beanNames.length == 1) {
			String unitName = beanNames[0];
			EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
			if (this.beanFactory instanceof ConfigurableBeanFactory) {
				((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
			}
			return emf;
		}
		else if (beanNames.length > 1) {
			throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
		}
		else {
			throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
		}
	}

	/**
	 * Perform a JNDI lookup for the given resource by name.
	 *
Called for EntityManagerFactory and EntityManager lookup
	 * when JNDI names are mapped for specific persistence units.
	 * @param jndiName the JNDI name to look up
	 * @param requiredType the required type of the object
	 * @return the obtained object
	 * @throws Exception if the JNDI lookup failed
	 */
	protected <T> T lookup(String jndiName, Class<T> requiredType) throws Exception {
		return new LocatorDelegate().lookup(jndiName, requiredType);
	}

	/**
	 * Separate inner class to isolate the JNDI API dependency
	 * (for compatibility with Google App Engine's API white list).
	 */
	private class LocatorDelegate {

		public <T> T lookup(String jndiName, Class<T> requiredType) throws Exception {
			JndiLocatorDelegate locator = new JndiLocatorDelegate();
			if (jndiEnvironment instanceof JndiTemplate) {
				locator.setJndiTemplate((JndiTemplate) jndiEnvironment);
			}
			else if (jndiEnvironment instanceof Properties) {
				locator.setJndiEnvironment((Properties) jndiEnvironment);
			}
			else if (jndiEnvironment != null) {
				throw new IllegalStateException("Illegal 'jndiEnvironment' type: " + jndiEnvironment.getClass());
			}
			locator.setResourceRef(resourceRef);
			return locator.lookup(jndiName, requiredType);
		}
	}

	/**
	 * Class representing injection information about an annotated field
	 * or setter method.
	 */
	private class PersistenceElement extends InjectionMetadata.InjectedElement {

		private final String unitName;

		private PersistenceContextType type;

		private boolean synchronizedWithTransaction = false;

		private Properties properties;

		public PersistenceElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) {
			super(member, pd);
			PersistenceContext pc = ae.getAnnotation(PersistenceContext.class);
			PersistenceUnit pu = ae.getAnnotation(PersistenceUnit.class);
			Class<?> resourceType = EntityManager.class;
			if (pc != null) {
				if (pu != null) {
					throw new IllegalStateException("Member may only be annotated with either " +
							"@PersistenceContext or @PersistenceUnit, not both: " + member);
				}
				Properties properties = null;
				PersistenceProperty[] pps = pc.properties();
				if (!ObjectUtils.isEmpty(pps)) {
					properties = new Properties();
					for (PersistenceProperty pp : pps) {
						properties.setProperty(pp.name(), pp.value());
					}
				}
				this.unitName = pc.unitName();
				this.type = pc.type();
				this.synchronizedWithTransaction = (synchronizationAttribute == null ||
						"SYNCHRONIZED".equals(ReflectionUtils.invokeMethod(synchronizationAttribute, pc).toString()));
				this.properties = properties;
			}
			else {
				resourceType = EntityManagerFactory.class;
				this.unitName = pu.unitName();
			}
			checkResourceType(resourceType);
		}

		/**
		 * Resolve the object against the application context.
		 */
		@Override
		protected Object getResourceToInject(Object target, String requestingBeanName) {
			// Resolves to EntityManagerFactory or EntityManager.
			if (this.type != null) {
				return (this.type == PersistenceContextType.EXTENDED ?
						resolveExtendedEntityManager(target, requestingBeanName) :
						resolveEntityManager(requestingBeanName));
			}
			else {
				// OK, so we need an EntityManagerFactory...
				return resolveEntityManagerFactory(requestingBeanName);
			}
		}

		private EntityManagerFactory resolveEntityManagerFactory(String requestingBeanName) {
			// Obtain EntityManagerFactory from JNDI?
			EntityManagerFactory emf = getPersistenceUnit(this.unitName);
			if (emf == null) {
				// Need to search for EntityManagerFactory beans.
				emf = findEntityManagerFactory(this.unitName, requestingBeanName);
			}
			return emf;
		}

		private EntityManager resolveEntityManager(String requestingBeanName) {
			// Obtain EntityManager reference from JNDI?
			EntityManager em = getPersistenceContext(this.unitName, false);
			if (em == null) {
				// No pre-built EntityManager found -> build one based on factory.
				// Obtain EntityManagerFactory from JNDI?
				EntityManagerFactory emf = getPersistenceUnit(this.unitName);
				if (emf == null) {
					// Need to search for EntityManagerFactory beans.
					emf = findEntityManagerFactory(this.unitName, requestingBeanName);
				}
				// Inject a shared transactional EntityManager proxy.
				if (emf instanceof EntityManagerFactoryInfo &&
						((EntityManagerFactoryInfo) emf).getEntityManagerInterface() != null) {
					// Create EntityManager based on the info's vendor-specific type
					// (which might be more specific than the field's type).
					em = SharedEntityManagerCreator.createSharedEntityManager(
							emf, this.properties, this.synchronizedWithTransaction);
				}
				else {
					// Create EntityManager based on the field's type.
					em = SharedEntityManagerCreator.createSharedEntityManager(
							emf, this.properties, this.synchronizedWithTransaction, getResourceType());
				}
			}
			return em;
		}

		private EntityManager resolveExtendedEntityManager(Object target, String requestingBeanName) {
			// Obtain EntityManager reference from JNDI?
			EntityManager em = getPersistenceContext(this.unitName, true);
			if (em == null) {
				// No pre-built EntityManager found -> build one based on factory.
				// Obtain EntityManagerFactory from JNDI?
				EntityManagerFactory emf = getPersistenceUnit(this.unitName);
				if (emf == null) {
					// Need to search for EntityManagerFactory beans.
					emf = findEntityManagerFactory(this.unitName, requestingBeanName);
				}
				// Inject a container-managed extended EntityManager.
				em = ExtendedEntityManagerCreator.createContainerManagedEntityManager(
						emf, this.properties, this.synchronizedWithTransaction);
			}
			if (em instanceof EntityManagerProxy && beanFactory != null &&
					beanFactory.containsBean(requestingBeanName) && !beanFactory.isPrototype(requestingBeanName)) {
				extendedEntityManagersToClose.put(target, ((EntityManagerProxy) em).getTargetEntityManager());
			}
			return em;
		}
	}

}


text:
using AutoDI.AssemblyGenerator;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;

namespace AutoDI.Build.Tests
{
    [TestClass]
    public class SetupMethodTests
    {
        private static Assembly _publicAssembly;
        private static Assembly _internalAssembly;
        private static Assembly _manualAssembly;

        [ClassInitialize]
        public static async Task Initialize(TestContext context)
        {
            var gen = new Generator();
            Dictionary<string, AssemblyInfo> result = await gen.Execute();
            _publicAssembly = result["public"].Assembly;
            _internalAssembly = result["internal"].Assembly;
            _manualAssembly = result["manual"].Assembly;
        }

        [TestMethod]
        [Description("Issue 23")]
        public void PublicSetupMethodIsInvoked()
        {
            ContainerMap GetInitMap()
            {
                // ReSharper disable once PossibleNullReferenceException
                return (ContainerMap)_publicAssembly.GetStaticProperty<SetupMethodPublicTests.Program>(
                    nameof(SetupMethodPublicTests.Program.InitMap));
            }

            Assert.IsNull(GetInitMap());
            _publicAssembly.InvokeEntryPoint();
            Assert.IsNotNull(GetInitMap());
        }

        [TestMethod]
        [Description("Issue 38")]
        public void InternalSetupMethodIsInvoked()
        {
            ContainerMap GetInitMap()
            {
                // ReSharper disable once PossibleNullReferenceException
                return (ContainerMap)_internalAssembly.GetStaticProperty<SetupMethodInternalTests.Program>(
                    nameof(SetupMethodInternalTests.Program.InitMap));
            }

            Assert.IsNull(GetInitMap());
            _internalAssembly.InvokeEntryPoint();
            Assert.IsNotNull(GetInitMap());
        }

        [TestMethod]
        [Description("Issue 49")]
        public void SetupMethodIsNotInvokedUntilTheContainerIsInjected()
        {
            ContainerMap GetInitMap()
            {
                // ReSharper disable once PossibleNullReferenceException
                return (ContainerMap)_manualAssembly.GetStaticProperty<SetupMethodManualInjectionTests.TestClass>(
                    nameof(SetupMethodManualInjectionTests.TestClass.InitMap));
            }

            Assert.IsNull(GetInitMap());
            DI.Init(_manualAssembly);
            Assert.IsNotNull(GetInitMap());

        }
    }
}
//<assembly:public />
//<type: ConsoleApplication />
//<ref: AutoDI />
//<weaver: AutoDI.Build.ProcessAssemblyTask />
namespace SetupMethodPublicTests
{
    using AutoDI;

    public class Program
    {
        public static IContainer InitMap { get; set; }

        public static void Main(string[] args)
        {

        }

        [SetupMethod]
        public static void Setup(IApplicationBuilder builder)
        {
            builder.ConfigureContainer<IContainer>(map =>
            {
                InitMap = map;
            });
        }
    }
}
//</assembly>

//<assembly:internal />
//<type: ConsoleApplication />
//<ref: AutoDI />
//<weaver: AutoDI.Build.ProcessAssemblyTask />
namespace SetupMethodInternalTests
{
    using AutoDI;

    public class Program
    {
        public static IContainer InitMap { get; set; }

        public static void Main(string[] args)
        {

        }

        [SetupMethod]
        internal static void Setup(IApplicationBuilder builder)
        {
            builder.ConfigureContainer<IContainer>(map =>
            {
                InitMap = map;
            });
        }
    }
}
//</assembly>

//<assembly:manual />
//<ref: AutoDI />
//<weaver: AutoDI.Build.ProcessAssemblyTask />
namespace SetupMethodManualInjectionTests
{
    using AutoDI;
    using System;

    public class TestClass
    {
        public static IContainer InitMap { get; set; }

        [SetupMethod]
        internal static void InitializeContainer(IApplicationBuilder builder)
        {
            builder.ConfigureContainer<IContainer>(map =>
            {
                InitMap = map;
            });
        }
    }

    public interface IManager { }

    public class Manager : IManager
    {
        public IService Service { get; }
        public Manager([Dependency] IService service = null)
        {
            Service = service ?? throw new ArgumentNullException(nameof(service));
        }
    }

    public interface IService { }

    public class Service : IService { }
}
//</assembly>


text:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
    <msapplication>
        <tile>
            <square150x150logo src="/mstile-150x150.png"/>
            <TileColor>#292b2c</TileColor>
        </tile>
    </msapplication>
</browserconfig>


text:
import domready = require('domready');
import { Calculator } from './calculator';

domready(() => {
    let container = document.body.querySelector('#calculator') as HTMLElement;

    let calculator = new Calculator(container);
});


text:
/**
 * @author: nthienan
 */

package agu.thesis2015.controller.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import agu.thesis2015.controller.SongController;
import agu.thesis2015.domain.Song;
import agu.thesis2015.model.Response;
import agu.thesis2015.service.SongService;

@RestController
@RequestMapping(value = "/api/song")
public class SongControllerImpl implements SongController {

	@Autowired
	private SongService service;

	// get all
	@Override
	@RequestMapping(value = "/{username}/all", method = RequestMethod.GET, produces = "application/json")
	public Response getAll(@PathVariable String username) {
		return service.getAll(username);
	}

	// get by id
	@Override
	@RequestMapping(value = "/{username}/{id}", method = RequestMethod.GET, produces = "application/json")
	public Response getById(@PathVariable String username, @PathVariable String id) {
		return service.getById(username, id);
	}

	// insert
	@Override
	@RequestMapping(value = "/{username}", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
	public Response insert(@PathVariable String username, @RequestBody Song song) {
		return service.insert(username, song);
	}

	// update
	@Override
	@RequestMapping(value = "/{username}", method = RequestMethod.PUT, produces = "application/json", consumes = "application/json")
	public Response update(@PathVariable String username, @RequestBody Song song) {
		return service.update(username, song);
	}

	// delete all
	@Override
	@RequestMapping(value = "/{username}/all", method = RequestMethod.DELETE, produces = "application/json")
	public Response deleteAll(@PathVariable String username, HttpServletRequest request) {
		return service.deleteAll(username, request);
	}

	// delete one
	@Override
	@RequestMapping(value = "/{username}/{id}", method = RequestMethod.DELETE, produces = "application/json")
	public Response deleteOne(@PathVariable String username, @PathVariable String id, HttpServletRequest request) {
		return service.deleteOne(username, id, request);
	}

	// delete multi
	@Override
	@RequestMapping(value = "/{username}", method = RequestMethod.DELETE, produces = "application/json", consumes = "application/json")
	public Response deleteMulti(@PathVariable String username, @RequestBody List<String> ids, HttpServletRequest request) {
		return service.deleteMulti(username, ids, request);
	}

	// paging
	@Override
	@RequestMapping(value = "/{username}", method = RequestMethod.GET, produces = "application/json")
	public Response paging(@PathVariable String username, @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size,
			@RequestParam(defaultValue = "asc") String sort, @RequestParam(defaultValue = "_id") String field) {
		return service.paging(username, page, size, sort, field);
	}

	// search
	@Override
	@RequestMapping(value = "/{username}/search", method = RequestMethod.GET, produces = "application/json")
	public Response search(@PathVariable String username, @RequestParam(defaultValue = "") String keyword, @RequestParam(defaultValue = "0") int page,
			@RequestParam(defaultValue = "10") int size, @RequestParam(defaultValue = "asc") String sort, @RequestParam(defaultValue = "_id") String field) {
		return service.search(username, keyword, page, size, sort, field);
	}

	// upload
	@Override
	@RequestMapping(value = "/{username}/upload", method = RequestMethod.POST, produces = "application/json")
	public Response upload(@PathVariable String username, @RequestParam String name, @RequestParam String gener, @RequestParam String artist,
			@RequestParam String musician, @RequestParam boolean shared, @RequestParam MultipartFile file, HttpServletRequest request) {
		return service.upload(username, name, gener, artist, musician, shared, file, request);
	}

	// update view
	@Override
	@RequestMapping(value = "/{songId}/view", method = RequestMethod.PUT, produces = "application/json")
	public Response updateView(@PathVariable String songId) {
		return service.updateView(songId);
	}

	// update download
	@Override
	@RequestMapping(value = "/{songId}/download", method = RequestMethod.PUT, produces = "application/json")
	public Response updateDownload(@PathVariable String songId) {
		return service.updateDownload(songId);
	}

	// download file
	@Override
	@RequestMapping(value = "/{songId}/download", method = RequestMethod.GET)
	public void downloadFile(@PathVariable String songId, HttpServletRequest request, HttpServletResponse response) {
		service.downloadFile(songId, request, response);
	}

	// share
	@Override
	@RequestMapping(value = "/{username}/{songId}/share", method = RequestMethod.PUT, produces = "application/json")
	public Response shared(@PathVariable String username, @PathVariable String songId) {
		return service.shared(username, songId);
	}

	// unshare
	@Override
	@RequestMapping(value = "/{username}/{songId}/unshare", method = RequestMethod.PUT, produces = "application/json")
	public Response unShare(@PathVariable String username, @PathVariable String songId) {
		return service.unShared(username, songId);
	}

	// get share
	@Override
	@RequestMapping(value = "/share", method = RequestMethod.GET, produces = "application/json")
	public Response getShare(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size,
			@RequestParam(defaultValue = "asc") String sort, @RequestParam(defaultValue = "_id") String field) {
		return service.getShare(page, size, sort, field);
	}
}


text:
module Main where

import Crypto.Scrypt
import Data.ByteString.Char8 (pack)
import Data.Maybe (catMaybes)
import Database.Persist.Postgresql
import Seneschall.Config (readConfig)
import Seneschall.Database
import Seneschall.Types
import System.Environment (getArgs)

main :: IO ()
main = do
    args <- getArgs
    case args of
        ("adduser":u:p:r) -> addUser u p r
        ("initdb":_)      -> initDb
        _                 -> printUsage

printUsage :: IO ()
printUsage = do
    putStrLn "seneadmin [command] ..."
    putStrLn "  adduser [username] [password] roles"
    putStrLn "  initdb"

addUser :: String -> String -> [String] -> IO ()
addUser u p r = do
    conf <- readConfig "seneschall.conf"
    case conf of
         Left  e -> putStrLn $ "config error: " ++ e
         Right c -> do
             enc <- encryptPassIO defaultParams (Pass $ pack p)
             let dbString = dbFromConfig c
             withPostgresqlConn (pack dbString) $ runSqlPersistM (do
                 u' <- insert $ WebUser u "" (getEncryptedPass enc) UserActive
                 mapM_ (insert . UserRole u') $ readRole r
                 )
             putStrLn "user added"

readRole :: [String] -> [Role]
readRole = concatMap (fmap fst . reads)

initDb :: IO ()
initDb = do
    conf <- readConfig "seneschall.conf"
    case conf of
         Left  e -> putStrLn $ "config error: " ++ e
         Right c -> do
             let dbString = dbFromConfig c
             withPostgresqlConn (pack dbString) $ runSqlPersistM
                $ runMigration migrateAll
             print "db initialized"


text:
package edu.upenn.cis.ppod.dto;

import java.util.List;

public interface IHasOtuSets extends ILabeled {

	/**
	 * Return a list of the composing OTU sets. Modification of the returned
	 * list is undefined.
	 *
	 * @return a list of the composing OTU sets
	 */
	List<PPodOtuSet> getOtuSets();

}


text:
Following is a layout of the various directories that make up the pachyderm
repo, and their purpose.

```
build
debian
doc - the Pachyderm documentation built with mkdocs
├── pachctl - cobra auto-generated docs on command-line usage
etc - everything else
├── build - scripts for building releases
├── compile - scripts to facilitate compiling and building docker images
├── contributing - contains helper scripts/assets for contributors
├── deploy - scripts/assets for pachyderm deployments
│   ├── cloudfront
│   ├── gpu - scripts to help enable GPU resources on k8s/pachyderm
│   └── tracing - k8s manifests for enabling Jaeger tracing of pachyderm
├── helm - Pachyderm helm chart
├── kube - internal scripts for working with k8s
├── kubernetes-kafka
├── kubernetes-prometheus
├── netcat
├── proto - scripts for compiling protobufs
├── testing - scripts/assets used for testing
│   ├── artifacts - static assets used in testing/mocking
│   ├── loads
│   ├── migration - sample data used in testing pachyderm migrations
│   ├── s3gateway - scripts for running conformance tests on the s3gateway
│   └── spout
└── worker
examples - example projects; see readme for details of each one
src - source code
├── client - contains protobufs and the source code for pachyderm's go client
│   ├── admin - admin-related functionality
│   │   └── 1_7 - old, v1.7-compatible protobufs
│   ├── auth - auth-related functionality
│   ├── debug - debug-related functionality
│   ├── deploy - deployment-related functionality
│   ├── enterprise - enterprise-related functionality
│   ├── health - health check-related functionality
│   ├── limit - limit-related functionality
│   ├── pfs - PFS-related functionality
│   ├── pkg - utility packages
│   │   ├── config - pachyderm config file reading/writing
│   │   ├── discovery
│   │   ├── grpcutil - utilities for working with gRPC clients/servers
│   │   ├── pbutil - utilities for working with protobufs
│   │   ├── require - utilities for making unit tests terser
│   │   ├── shard
│   │   └── tracing - facilitates pachyderm cluster Jaeger tracing
│   ├── pps - PPS-related functionality
│   └── version - version check-related functionality
├── plugin
│   └── vault
│       ├── etc
│       ├── pachyderm
│       ├── pachyderm-plugin
│       └── vendor - vendored libraries for the vault plugin
├── server - contains server-side logic and CLI
│   ├── admin - cluster admin functionality
│   │   ├── cmds - cluster admin CLI
│   │   └── server - cluster admin server
│   ├── auth - auth functionality
│   │   ├── cmds - auth CLI
│   │   ├── server - auth server
│   │   └── testing - a mock auth server used for testing
│   ├── cmd - contains the various pachyderm entrypoints
│   │   ├── pachctl - the CLI entrypoint
│   │   ├── pachctl-doc - helps generate docs for the CLI
│   │   ├── pachd - the server entrypoint
│   │   └── worker - the worker entrypoint
│   ├── debug - debug functionality
│   │   ├── cmds - debug CLI
│   │   └── server - debug server
│   ├── enterprise - enterprise functionality
│   │   ├── cmds - enterprise CLI
│   │   └── server - enterprise server
│   ├── pfs - PFS functionality
│   │   ├── cmds - PFS CLI
│   │   ├── fuse - support mounting PFS repos via FUSE
│   │   ├── pretty - pretty-printing of PFS metadata in the CLI
│   │   ├── s3 - the s3gateway, an s3-like HTTP API for serving PFS content
│   │   └── server - PFS server
│   ├── pkg - utility packages
│   │   ├── ancestry - parses git ancestry reference strings
│   │   ├── backoff - backoff algorithms for retrying operations
│   │   ├── cache - a gRPC server for serving cached content
│   │   ├── cert - functionality for generating x509 certificates
│   │   ├── cmdutil - functionality for helping creating CLIs
│   │   ├── collection - etcd collection management
│   │   ├── dag - a simple in-memory directed acyclic graph data structure
│   │   ├── deploy - functionality for deploying pachyderm
│   │   │   ├── assets - generates k8s manifests and other assets used in deployment
│   │   │   ├── cmds - deployment CLI
│   │   │   └── images - handling of docker images
│   │   ├── dlock - distributed lock on etcd
│   │   ├── errutil - utility functions for error handling
│   │   ├── exec - utilities for running external commands
│   │   ├── hashtree - a Merkle tree library
│   │   ├── lease - utility for managing resources with expirable leases
│   │   ├── localcache - a concurrency-safe local disk cache
│   │   ├── log - logging utilities
│   │   ├── metrics - cluster metrics service using segment.io
│   │   ├── migration
│   │   ├── netutil - networking utilities
│   │   ├── obj - tools for working with various object stores (e.g. S3)
│   │   ├── pfsdb - the etcd database schema that PFS uses
│   │   ├── pool - gRPC connection pooling
│   │   ├── ppsconsts - PPS-related constants
│   │   ├── ppsdb - the etcd database schema that PPS uses
│   │   ├── ppsutil - PPS-related utility functions
│   │   ├── pretty - function for pretty printing values
│   │   ├── serviceenv - management of connections to pach services
│   │   ├── sql - tools for working with postgres database dumps
│   │   ├── sync - tools for syncing PFS content
│   │   ├── tabwriter - tool for writing tab-delimited content
│   │   ├── testutil - test-related utilities
│   │   ├── uuid - UUID generation
│   │   ├── watch - tool for watching etcd databases for changes
│   │   └── workload
│   ├── pps - PPS functionality
│   │   ├── cmds - - PPS CLI
│   │   ├── example - example PPS requests
│   │   ├── pretty - pretty printing of PPS output to the CLI
│   │   └── server - PPS server
│   │       └── githook - support for github PPS sources
│   ├── vendor - vendored packages
│   └── worker - pachd master and sidecar
└── testing - testing tools
    ├── loadtest - load tests for pachyderm
    │   └── split - stress tests of PFS merge functionality
    ├── match - a grep-like tool used in testing
    ├── saml-idp
    └── vendor - vendored packages
```


text:
/* eslint camelcase: [0] */

import {oneFlight, whileInFlight} from '@ciscospark/common';
import {grantErrors, SparkPlugin} from '@ciscospark/spark-core';

/**
 * NodeJS support for OAuth2
 * @class
 * @variation 2
 */
const Authorization = SparkPlugin.extend({
  derived: {
    /**
     * Alias of {@link Authorization(2)#isAuthorizing}
     * @instance
     * @memberof Authorization(2)
     * @type {boolean}
     */
    isAuthenticating: {
      deps: [`isAuthorizing`],
      fn() {
        return this.isAuthorizing;
      }
    }
  },

  session: {
    /**
     * Indicates if an Authorization Code exchange is inflight
     * @instance
     * @memberof Authorization(2)
     * @type {boolean}
     */
    isAuthorizing: {
      default: false,
      type: `boolean`
    }
  },

  namespace: `Credentials`,

  @whileInFlight(`isAuthorizing`)
  @oneFlight
  /**
   * Exchanges an authorization code for an access token
   * @instance
   * @memberof Authorization(2)
   * @param {Object} options
   * @param {Object} options.code
   * @returns {Promise}
   */
  requestAuthorizationCodeGrant(options = {}) {
    this.logger.info(`credentials: requesting authorization code grant`);

    if (!options.code) {
      return Promise.reject(new Error(`\`options.code\` is required`));
    }

    return this.spark.request({
      method: `POST`,
      uri: this.config.tokenUrl,
      form: {
        grant_type: `authorization_code`,
        redirect_uri: this.config.redirect_uri,
        code: options.code,
        self_contained_token: true
      },
      auth: {
        user: this.config.client_id,
        pass: this.config.client_secret,
        sendImmediately: true
      },
      shouldRefreshAccessToken: false
    })
      .then((res) => {
        this.spark.credentials.set({supertoken: res.body});
      })
      .catch((res) => {
        if (res.statusCode !== 400) {
          return Promise.reject(res);
        }

        const ErrorConstructor = grantErrors.select(res.body.error);
        return Promise.reject(new ErrorConstructor(res._res || res));
      });
  },

  @oneFlight
  /**
   * Requests a Cisco Spark access token for a user already authenticated into
   * your product.
   *
   * Note: You'll need to supply a jwtRefreshCallback of the form
   * `Promise<jwt> = jwtRefreshCallback(spark)` for automatic token refresh to
   * work.
   *
   * @param {Object} options
   * @param {Object} options.jwt This is a jwt generated by your backend that
   * identifies a user in your system
   * @returns {Promise}
   */
  requestAccessTokenFromJwt({jwt}) {
    return this.spark.request({
      method: `POST`,
      service: `hydra`,
      resource: `jwt/login`,
      headers: {
        authorization: jwt
      }
    })
      .then(({body}) => ({
        access_token: body.token,
        token_type: `Bearer`,
        expires_in: body.expiresIn
      }))
      .then((token) => {
        this.spark.credentials.set({
          supertoken: token
        });
      });
  }
});

export default Authorization;


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using IDI.Central.Common.Enums;
using IDI.Core.Domain;

namespace IDI.Central.Domain.Modules.Sales.AggregateRoots
{
    [Table("Orders")]
    public class Order : AggregateRoot
    {
        [Required]
        [StringLength(30)]
        public string SN { get; set; }

        public DocumentCategory Category { get; set; }

        public DateTime Date { get; set; }

        public SaleStatus Status { get; set; }

        [StringLength(200)]
        public string Remark { get; set; }

        public Guid? CustomerId { get; set; }

        public Customer Customer { get; set; }

        public ShippingAddress Shipping { get; set; }

        public List<OrderItem> Items { get; set; } = new List<OrderItem>();
    }
}


text:
the Java API for Microsoft Documents
: http://poi.apache.org/

## Links

- [Overview (POI API Documentation)](http://poi.apache.org/apidocs/overview-summary.html)
- [POIのHSSFを使ってExcelに画像を挿入 - No Programming, No Life](http://npnl.hatenablog.jp/entry/20081122/1227337357)
- [Javaでの画像ファイルをリサイズしてExcelに一括貼り付け(POI) - Qiita](http://qiita.com/mojaie/items/ace880e817e80f7746c0)
- [POI Cellメモ(Hishidama's Java POI Cell Memo)](http://www.ne.jp/asahi/hishidama/home/tech/apache/poi/cell.html)
- [java - How to know number of sheets in a workbook? - Stack Overflow](http://stackoverflow.com/questions/2077566/how-to-know-number-of-sheets-in-a-workbook)

## Code samples

#### テンプレートExcelファイルを用意してデータを埋め込んでダウンロードするサンプル
```java
FileInputStream fis = new FileInputStream( "C:\\TemplateBook.xlsx" );
Workbook workbook = WorkbookFactory.create( fis );
Sheet sheet = workbook.getSheet( "Sheet1" );
int i = 0;
for (Row row : sheet) {
	for (Cell cell : row) {
		cell.setCellValue( "_" + i + "_" );
		i++;
	}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write( baos );
response.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" );
response.setHeader( "Content-Disposition", "attachment; filename=\"YourBook.xlsx\"" );
// :
// :
response.flushBuffer();
```
MIME type of `.xlsx` - [Description of the default settings for the MimeMap property and for the ScriptMaps property in IIS](http://support.microsoft.com/kb/936496/en-us)


text:
package info.knigoed.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mark
 */
public class UrlGenerator {
    private final static Logger LOGGER = LoggerFactory.getLogger(UrlGenerator.class);
    private final static String DEFAULT_ENCODING_URL = "UTF-8";

    private final URL address;
    private final Map<String, String> map = new LinkedHashMap<>();

    public UrlGenerator() {
        address = null;
    }

    /**
     * Определяет параметры из URL и сохраняет в Map.
     *
     * @param address url адрес
     */
    public UrlGenerator(URL address) {
        this.address = address;

        if (null != address.getQuery()) {
            String[] query = StringUtils.split(address.getQuery(), "&");
            for (String params : query) {
                String[] param = StringUtils.split(params, "=");
                map.put(param[0], param.length > 1 ? param[1] : "");
            }
        }
    }

    public String getParameter(String param) {
        return map.get(param);
    }

    public void setParameter(String param, Object value) {
        if (value != null) {
            map.put(param, value.toString());
        } else {
            unsetParameter(param);
        }
    }

    /**
     * Добавляет новый параметр вместе со значением, пример:
     *
     * @param parVal "param=value"
     */
    public void setParameter(String parVal) {
        if (null != parVal) {
            String[] p = parVal.split("=");
            map.put(p[0], p[1]);
        }
    }

    private void unsetParameter(String param) {
        map.remove(param);
    }

    public void setParameters(Map<String, String> map) {
        this.map.putAll(map);
    }

    public Map<String, String> getParameters() {
        return map;
    }

    public String getURL(boolean isEncode) {
        String uri = "";
        if (null != address) {
            uri = address.getProtocol() + "://"
                + address.getHost()
                + address.getPath();
        }

        StringBuilder sb = new StringBuilder(uri);
        List<String> listOfParams = new ArrayList<>();
        for (String param : map.keySet()) {
            listOfParams.add(param + "=" + (isEncode ? encodeString(map.get(param)) : map.get(param)));
        }

        if (!listOfParams.isEmpty()) {
            String query = StringUtils.join(listOfParams, "&");
            sb.append("?");
            sb.append(query);
        }

        return sb.toString();
    }

    private static String encodeString(String name) throws NullPointerException {
        String tmp = null;

        if (name == null) {
            return null;
        }

        try {
            tmp = java.net.URLEncoder.encode(name, DEFAULT_ENCODING_URL);
        } catch (UnsupportedEncodingException ex) {
            LOGGER.error("", ex);
        }

        if (tmp == null) {
            throw new NullPointerException();
        }

        return tmp;
    }

    /**
     * Возвращает полный URL адрес страницы
     * *
     *
     * @param request HttpServletRequest
     * @return url
     */
    public static String getURI(HttpServletRequest request) {
        return request.getScheme() + "://"
            + request.getServerName()
            + ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort())
            + request.getRequestURI()
            + (request.getQueryString() != null ? "?" + request.getQueryString() : "");
    }

}