text:
import os
import subprocess
import sys
from collections import defaultdict
from typing import Any, ClassVar, Dict, Type
from urllib.parse import urljoin

from .wptmanifest.parser import atoms

atom_reset = atoms["Reset"]
enabled_tests = {"testharness", "reftest", "wdspec", "crashtest", "print-reftest"}

class Result:
    def __init__(self,
                 status,
                 message,
                 expected=None,
                 extra=None,
                 stack=None,
                 known_intermittent=None):
        if status not in self.statuses:
            raise ValueError("Unrecognised status %s" % status)
        self.status = status
        self.message = message
        self.expected = expected
        self.known_intermittent = known_intermittent if known_intermittent is not None else []
        self.extra = extra if extra is not None else {}
        self.stack = stack

    def __repr__(self):
        return f"<{self.__module__}.{self.__class__.__name__} {self.status}>"

class SubtestResult:
    def __init__(self, name, status, message, stack=None, expected=None, known_intermittent=None):
        self.name = name
        if status not in self.statuses:
            raise ValueError("Unrecognised status %s" % status)
        self.status = status
        self.message = message
        self.stack = stack
        self.expected = expected
        self.known_intermittent = known_intermittent if known_intermittent is not None else []

    def __repr__(self):
        return f"<{self.__module__}.{self.__class__.__name__} {self.name} {self.status}>"

class TestharnessResult(Result):
    default_expected = "OK"
    statuses = {"OK", "ERROR", "INTERNAL-ERROR", "TIMEOUT", "EXTERNAL-TIMEOUT", "CRASH", "PRECONDITION_FAILED"}

class TestharnessSubtestResult(SubtestResult):
    default_expected = "PASS"
    statuses = {"PASS", "FAIL", "TIMEOUT", "NOTRUN", "PRECONDITION_FAILED"}

class ReftestResult(Result):
    default_expected = "PASS"
    statuses = {"PASS", "FAIL", "ERROR", "INTERNAL-ERROR", "TIMEOUT", "EXTERNAL-TIMEOUT",
                "CRASH"}

class WdspecResult(Result):
    default_expected = "OK"
    statuses = {"OK", "ERROR", "INTERNAL-ERROR", "TIMEOUT", "EXTERNAL-TIMEOUT", "CRASH"}

class WdspecSubtestResult(SubtestResult):
    default_expected = "PASS"
    statuses = {"PASS", "FAIL", "ERROR"}

class CrashtestResult(Result):
    default_expected = "PASS"
    statuses = {"PASS", "ERROR", "INTERNAL-ERROR", "TIMEOUT", "EXTERNAL-TIMEOUT",
                "CRASH"}

def get_run_info(metadata_root, product, **kwargs):
    return RunInfo(metadata_root, product, **kwargs)

class RunInfo(Dict[str, Any]):
    def __init__(self, metadata_root, product, debug,
                 browser_version=None,
                 browser_channel=None,
                 verify=None,
                 extras=None,
                 device_serials=None,
                 adb_binary=None):
        import mozinfo
        self._update_mozinfo(metadata_root)
        self.update(mozinfo.info)

        from .update.tree import GitTree
        try:
            # GitTree.__init__ throws if we are not in a git tree.
            rev = GitTree(log_error=False).rev
        except (OSError, subprocess.CalledProcessError):
            rev = None
        if rev:
            self["revision"] = rev.decode("utf-8")

        self["python_version"] = sys.version_info.major
        self["product"] = product
        if debug is not None:
            self["debug"] = debug
        elif "debug" not in self:
            # Default to release
            self["debug"] = False
        if browser_version:
            self["browser_version"] = browser_version
        if browser_channel:
            self["browser_channel"] = browser_channel

        self["verify"] = verify
        if "wasm" not in self:
            self["wasm"] = False
        if extras is not None:
            self.update(extras)
        if "headless" not in self:
            self["headless"] = False

        if adb_binary:
            self["adb_binary"] = adb_binary
        if device_serials:
            # Assume all emulators are identical, so query an arbitrary one.
            self._update_with_emulator_info(device_serials[0])
            self.pop("linux_distro", None)

    def _adb_run(self, device_serial, args, **kwargs):
        adb_binary = self.get("adb_binary", "adb")
        cmd = [adb_binary, "-s", device_serial, *args]
        return subprocess.check_output(cmd, **kwargs)

    def _adb_get_property(self, device_serial, prop, **kwargs):
        args = ["shell", "getprop", prop]
        value = self._adb_run(device_serial, args, **kwargs)
        return value.strip()

    def _update_with_emulator_info(self, device_serial):
        """Override system info taken from the host if using an Android
        emulator."""
        try:
            self._adb_run(device_serial, ["wait-for-device"])
            emulator_info = {
                "os": "android",
                "os_version": self._adb_get_property(
                    device_serial,
                    "ro.build.version.release",
                    encoding="utf-8",
                ),
            }
            emulator_info["version"] = emulator_info["os_version"]

            # Detect CPU info (https://developer.android.com/ndk/guides/abis#sa)
            abi64, *_ = self._adb_get_property(
                device_serial,
                "ro.product.cpu.abilist64",
                encoding="utf-8",
            ).split(',')
            if abi64:
                emulator_info["processor"] = abi64
                emulator_info["bits"] = 64
            else:
                emulator_info["processor"], *_ = self._adb_get_property(
                    device_serial,
                    "ro.product.cpu.abilist32",
                    encoding="utf-8",
                ).split(',')
                emulator_info["bits"] = 32

            self.update(emulator_info)
        except (OSError, subprocess.CalledProcessError):
            pass

    def _update_mozinfo(self, metadata_root):
        """Add extra build information from a mozinfo.json file in a parent
        directory"""
        import mozinfo

        path = metadata_root
        dirs = set()
        while path != os.path.expanduser('~'):
            if path in dirs:
                break
            dirs.add(str(path))
            path = os.path.dirname(path)

        mozinfo.find_and_update_from_json(*dirs)

def server_protocol(manifest_item):
    if hasattr(manifest_item, "h2") and manifest_item.h2:
        return "h2"
    if hasattr(manifest_item, "https") and manifest_item.https:
        return "https"
    return "http"

class Test:

    result_cls = None  # type: ClassVar[Type[Result]]
    subtest_result_cls = None  # type: ClassVar[Type[SubtestResult]]
    test_type = None  # type: ClassVar[str]
    pac = None

    default_timeout = 10  # seconds
    long_timeout = 60  # seconds

    def __init__(self, url_base, tests_root, url, inherit_metadata, test_metadata,
                 timeout=None, path=None, protocol="http", subdomain=False, pac=None):
        self.url_base = url_base
        self.tests_root = tests_root
        self.url = url
        self._inherit_metadata = inherit_metadata
        self._test_metadata = test_metadata
        self.timeout = timeout if timeout is not None else self.default_timeout
        self.path = path
        self.subdomain = subdomain
        self.environment = {"url_base": url_base,
                            "protocol": protocol,
                            "prefs": self.prefs}

        if pac is not None:
            self.environment["pac"] = urljoin(self.url, pac)

    def __eq__(self, other):
        if not isinstance(other, Test):
            return False
        return self.id == other.id

    # Python 2 does not have this delegation, while Python 3 does.
    def __ne__(self, other):
        return not self.__eq__(other)

    def update_metadata(self, metadata=None):
        if metadata is None:
            metadata = {}
        return metadata

    @classmethod
    def from_manifest(cls, manifest_file, manifest_item, inherit_metadata, test_metadata):
        timeout = cls.long_timeout if manifest_item.timeout == "long" else cls.default_timeout
        return cls(manifest_file.url_base,
                   manifest_file.tests_root,
                   manifest_item.url,
                   inherit_metadata,
                   test_metadata,
                   timeout=timeout,
                   path=os.path.join(manifest_file.tests_root, manifest_item.path),
                   protocol=server_protocol(manifest_item),
                   subdomain=manifest_item.subdomain)

    @property
    def id(self):
        return self.url

    @property
    def keys(self):
        return tuple()

    @property
    def abs_path(self):
        return os.path.join(self.tests_root, self.path)

    def _get_metadata(self, subtest=None):
        if self._test_metadata is not None and subtest is not None:
            return self._test_metadata.get_subtest(subtest)
        else:
            return self._test_metadata

    def itermeta(self, subtest=None):
        if self._test_metadata is not None:
            if subtest is not None:
                subtest_meta = self._get_metadata(subtest)
                if subtest_meta is not None:
                    yield subtest_meta
            yield self._get_metadata()
        yield from reversed(self._inherit_metadata)

    def disabled(self, subtest=None):
        for meta in self.itermeta(subtest):
            disabled = meta.disabled
            if disabled is not None:
                return disabled
        return None

    @property
    def restart_after(self):
        for meta in self.itermeta(None):
            restart_after = meta.restart_after
            if restart_after is not None:
                return True
        return False

    @property
    def leaks(self):
        for meta in self.itermeta(None):
            leaks = meta.leaks
            if leaks is not None:
                return leaks
        return False

    @property
    def min_assertion_count(self):
        for meta in self.itermeta(None):
            count = meta.min_assertion_count
            if count is not None:
                return count
        return 0

    @property
    def max_assertion_count(self):
        for meta in self.itermeta(None):
            count = meta.max_assertion_count
            if count is not None:
                return count
        return 0

    @property
    def lsan_disabled(self):
        for meta in self.itermeta():
            if meta.lsan_disabled is not None:
                return meta.lsan_disabled
        return False

    @property
    def lsan_allowed(self):
        lsan_allowed = set()
        for meta in self.itermeta():
            lsan_allowed |= meta.lsan_allowed
            if atom_reset in lsan_allowed:
                lsan_allowed.remove(atom_reset)
                break
        return lsan_allowed

    @property
    def lsan_max_stack_depth(self):
        for meta in self.itermeta(None):
            depth = meta.lsan_max_stack_depth
            if depth is not None:
                return depth
        return None

    @property
    def mozleak_allowed(self):
        mozleak_allowed = set()
        for meta in self.itermeta():
            mozleak_allowed |= meta.leak_allowed
            if atom_reset in mozleak_allowed:
                mozleak_allowed.remove(atom_reset)
                break
        return mozleak_allowed

    @property
    def mozleak_threshold(self):
        rv = {}
        for meta in self.itermeta(None):
            threshold = meta.leak_threshold
            for key, value in threshold.items():
                if key not in rv:
                    rv[key] = value
        return rv

    @property
    def tags(self):
        tags = set()
        for meta in self.itermeta():
            meta_tags = meta.tags
            tags |= meta_tags
            if atom_reset in meta_tags:
                tags.remove(atom_reset)
                break

        tags.add("dir:%s" % self.id.lstrip("/").split("/")[0])

        return tags

    @property
    def prefs(self):
        prefs = {}
        for meta in reversed(list(self.itermeta())):
            meta_prefs = meta.prefs
            if atom_reset in meta_prefs:
                del meta_prefs[atom_reset]
                prefs = {}
            prefs.update(meta_prefs)
        return prefs

    def expected(self, subtest=None):
        if subtest is None:
            default = self.result_cls.default_expected
        else:
            default = self.subtest_result_cls.default_expected

        metadata = self._get_metadata(subtest)
        if metadata is None:
            return default

        try:
            expected = metadata.get("expected")
            if isinstance(expected, str):
                return expected
            elif isinstance(expected, list):
                return expected[0]
            elif expected is None:
                return default
        except KeyError:
            return default

    def implementation_status(self):
        implementation_status = None
        for meta in self.itermeta():
            implementation_status = meta.implementation_status
            if implementation_status:
                return implementation_status

        # assuming no specific case, we are implementing it
        return "implementing"

    def known_intermittent(self, subtest=None):
        metadata = self._get_metadata(subtest)
        if metadata is None:
            return []

        try:
            expected = metadata.get("expected")
            if isinstance(expected, list):
                return expected[1:]
            return []
        except KeyError:
            return []

    def __repr__(self):
        return f"<{self.__module__}.{self.__class__.__name__} {self.id}>"

class TestharnessTest(Test):
    result_cls = TestharnessResult
    subtest_result_cls = TestharnessSubtestResult
    test_type = "testharness"

    def __init__(self, url_base, tests_root, url, inherit_metadata, test_metadata,
                 timeout=None, path=None, protocol="http", testdriver=False,
                 jsshell=False, scripts=None, subdomain=False, pac=None):
        Test.__init__(self, url_base, tests_root, url, inherit_metadata, test_metadata, timeout,
                      path, protocol, subdomain, pac)

        self.testdriver = testdriver
        self.jsshell = jsshell
        self.scripts = scripts or []

    @classmethod
    def from_manifest(cls, manifest_file, manifest_item, inherit_metadata, test_metadata):
        timeout = cls.long_timeout if manifest_item.timeout == "long" else cls.default_timeout
        pac = manifest_item.pac
        testdriver = manifest_item.testdriver if hasattr(manifest_item, "testdriver") else False
        jsshell = manifest_item.jsshell if hasattr(manifest_item, "jsshell") else False
        script_metadata = manifest_item.script_metadata or []
        scripts = [v for (k, v) in script_metadata
                   if k == "script"]
        return cls(manifest_file.url_base,
                   manifest_file.tests_root,
                   manifest_item.url,
                   inherit_metadata,
                   test_metadata,
                   timeout=timeout,
                   pac=pac,
                   path=os.path.join(manifest_file.tests_root, manifest_item.path),
                   protocol=server_protocol(manifest_item),
                   testdriver=testdriver,
                   jsshell=jsshell,
                   scripts=scripts,
                   subdomain=manifest_item.subdomain)

    @property
    def id(self):
        return self.url

class ManualTest(Test):
    test_type = "manual"

    @property
    def id(self):
        return self.url

class ReftestTest(Test):
    """A reftest

    A reftest should be considered to pass if one of its references matches (see below) *and* the
    reference passes if it has any references recursively.

    Attributes:
        references (List[Tuple[str, str]]): a list of alternate references, where one must match for the test to pass
        viewport_size (Optional[Tuple[int, int]]): size of the viewport for this test, if not default
        dpi (Optional[int]): dpi to use when rendering this test, if not default

    """
    result_cls = ReftestResult
    test_type = "reftest"

    def __init__(self, url_base, tests_root, url, inherit_metadata, test_metadata, references,
                 timeout=None, path=None, viewport_size=None, dpi=None, fuzzy=None,
                 protocol="http", subdomain=False):
        Test.__init__(self, url_base, tests_root, url, inherit_metadata, test_metadata, timeout,
                      path, protocol, subdomain)

        for _, ref_type in references:
            if ref_type not in ("==", "!="):
                raise ValueError

        self.references = references
        self.viewport_size = self.get_viewport_size(viewport_size)
        self.dpi = dpi
        self._fuzzy = fuzzy or {}

    @classmethod
    def cls_kwargs(cls, manifest_test):
        return {"viewport_size": manifest_test.viewport_size,
                "dpi": manifest_test.dpi,
                "protocol": server_protocol(manifest_test),
                "fuzzy": manifest_test.fuzzy}

    @classmethod
    def from_manifest(cls,
                      manifest_file,
                      manifest_test,
                      inherit_metadata,
                      test_metadata):

        timeout = cls.long_timeout if manifest_test.timeout == "long" else cls.default_timeout

        url = manifest_test.url

        node = cls(manifest_file.url_base,
                   manifest_file.tests_root,
                   manifest_test.url,
                   inherit_metadata,
                   test_metadata,
                   [],
                   timeout=timeout,
                   path=manifest_test.path,
                   subdomain=manifest_test.subdomain,
                   **cls.cls_kwargs(manifest_test))

        refs_by_type = defaultdict(list)

        for ref_url, ref_type in manifest_test.references:
            refs_by_type[ref_type].append(ref_url)

        # Construct a list of all the mismatches, where we end up with mismatch_1 != url !=
        # mismatch_2 != url != mismatch_3 etc.
        #
        # Per the logic documented above, this means that none of the mismatches provided match,
        mismatch_walk = None
        if refs_by_type["!="]:
            mismatch_walk = ReftestTest(manifest_file.url_base,
                                        manifest_file.tests_root,
                                        refs_by_type["!="][0],
                                        [],
                                        None,
                                        [])
            cmp_ref = mismatch_walk
            for ref_url in refs_by_type["!="][1:]:
                cmp_self = ReftestTest(manifest_file.url_base,
                                       manifest_file.tests_root,
                                       url,
                                       [],
                                       None,
                                       [])
                cmp_ref.references.append((cmp_self, "!="))
                cmp_ref = ReftestTest(manifest_file.url_base,
                                      manifest_file.tests_root,
                                      ref_url,
                                      [],
                                      None,
                                      [])
                cmp_self.references.append((cmp_ref, "!="))

        if mismatch_walk is None:
            mismatch_refs = []
        else:
            mismatch_refs = [(mismatch_walk, "!=")]

        if refs_by_type["=="]:
            # For each == ref, add a reference to this node whose tail is the mismatch list.
            # Per the logic documented above, this means any one of the matches must pass plus all the mismatches.
            for ref_url in refs_by_type["=="]:
                ref = ReftestTest(manifest_file.url_base,
                                  manifest_file.tests_root,
                                  ref_url,
                                  [],
                                  None,
                                  mismatch_refs)
                node.references.append((ref, "=="))
        else:
            # Otherwise, we just add the mismatches directly as we are immediately into the
            # mismatch chain with no alternates.
            node.references.extend(mismatch_refs)

        return node

    def update_metadata(self, metadata):
        if "url_count" not in metadata:
            metadata["url_count"] = defaultdict(int)
        for reference, _ in self.references:
            # We assume a naive implementation in which a url with multiple
            # possible screenshots will need to take both the lhs and rhs screenshots
            # for each possible match
            metadata["url_count"][(self.environment["protocol"], reference.url)] += 1
            reference.update_metadata(metadata)
        return metadata

    def get_viewport_size(self, override):
        return override

    @property
    def id(self):
        return self.url

    @property
    def keys(self):
        return ("reftype", "refurl")

    @property
    def fuzzy(self):
        return self._fuzzy

    @property
    def fuzzy_override(self):
        values = {}
        for meta in reversed(list(self.itermeta(None))):
            value = meta.fuzzy
            if not value:
                continue
            if atom_reset in value:
                value.remove(atom_reset)
                values = {}
            for key, data in value:
                if isinstance(key, (tuple, list)):
                    key = list(key)
                    key[0] = urljoin(self.url, key[0])
                    key[1] = urljoin(self.url, key[1])
                    key = tuple(key)
                elif key:
                    # Key is just a relative url to a ref
                    key = urljoin(self.url, key)
                values[key] = data
        return values

    @property
    def page_ranges(self):
        return {}

class PrintReftestTest(ReftestTest):
    test_type = "print-reftest"

    def __init__(self, url_base, tests_root, url, inherit_metadata, test_metadata, references,
                 timeout=None, path=None, viewport_size=None, dpi=None, fuzzy=None,
                 page_ranges=None, protocol="http", subdomain=False):
        super().__init__(url_base, tests_root, url, inherit_metadata, test_metadata,
                         references, timeout, path, viewport_size, dpi,
                         fuzzy, protocol, subdomain=subdomain)
        self._page_ranges = page_ranges

    @classmethod
    def cls_kwargs(cls, manifest_test):
        rv = super().cls_kwargs(manifest_test)
        rv["page_ranges"] = manifest_test.page_ranges
        return rv

    def get_viewport_size(self, override):
        assert override is None
        return (5*2.54, 3*2.54)

    @property
    def page_ranges(self):
        return self._page_ranges

class WdspecTest(Test):
    result_cls = WdspecResult
    subtest_result_cls = WdspecSubtestResult
    test_type = "wdspec"

    default_timeout = 25
    long_timeout = 180  # 3 minutes

class CrashTest(Test):
    result_cls = CrashtestResult
    test_type = "crashtest"

manifest_test_cls = {"reftest": ReftestTest,
                     "print-reftest": PrintReftestTest,
                     "testharness": TestharnessTest,
                     "manual": ManualTest,
                     "wdspec": WdspecTest,
                     "crashtest": CrashTest}

def from_manifest(manifest_file, manifest_test, inherit_metadata, test_metadata):
    test_cls = manifest_test_cls[manifest_test.item_type]
    return test_cls.from_manifest(manifest_file, manifest_test, inherit_metadata, test_metadata)


text:
/** @module resolve */ /** for typedoc */
export * from "./interface";
export * from "./resolvable";
export * from "./resolveContext";
//# sourceMappingURL=index.js.map

redpajama_set_name: RedPajamaGithub


text:
package org.jbpm.workbench.cm.client.util;

import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.jbpm.workbench.cm.client.events.CaseRefreshEvent;
import org.jbpm.workbench.cm.model.CaseInstanceSummary;
import org.jbpm.workbench.cm.service.CaseManagementService;
import org.uberfire.client.mvp.UberElement;
import org.uberfire.lifecycle.OnStartup;
import org.uberfire.mvp.PlaceRequest;

import static com.google.common.base.Strings.isNullOrEmpty;

public abstract class AbstractCaseInstancePresenter<V extends UberElement> extends AbstractPresenter<V> {

    public static final String PARAMETER_CASE_ID = "caseId";
    public static final String PARAMETER_CONTAINER_ID = "containerId";

    protected PlaceRequest place;

    protected String caseId;

    protected String containerId;

    @Inject
    protected TranslationService translationService;

    protected Caller<CaseManagementService> caseService;

    @OnStartup
    public void onStartup(final PlaceRequest place) {
        this.place = place;
        this.caseId = place.getParameter(PARAMETER_CASE_ID,
                                         null);
        this.containerId = place.getParameter(PARAMETER_CONTAINER_ID,
                                              null);
        findCaseInstance();
    }

    protected abstract void loadCaseInstance(CaseInstanceSummary cis);

    protected abstract void clearCaseInstance();

    public void findCaseInstance() {
        clearCaseInstance();
        if (isCaseInstanceValid()) {
            caseService.call((CaseInstanceSummary cis) -> loadCaseInstance(cis)).getCaseInstance(containerId, caseId);
        }
    }

    protected boolean isCaseInstanceValid() {
        return  /* !isNullOrEmpty(serverTemplateId) //TODO: include this check when serverTemplateId starts to be used*/
                !isNullOrEmpty(containerId) && !isNullOrEmpty(caseId);
    }

    public void onCaseRefreshEvent(@Observes CaseRefreshEvent caseRefreshEvent) {
        findCaseInstance();
    }

    @Inject
    public void setCaseService(final Caller<CaseManagementService> caseService) {
        this.caseService = caseService;
    }
}


text:
module Algs4ruby
  class Stack
    class ResizingArray
      include Enumerable

      attr_accessor :size, :array

      def initialize(capacity = 2)
        @size = 0
        @array = Array.new(capacity)
      end

      def push(item)
        resize(2*array.length) if size == array.length

        array[size] = item
        self.size += 1

        nil
      end

      def pop
        raise 'Pop on empty stack' if empty?

        resize(array.length/2) if size == array.length/4

        self.size -= 1
        item = array[size]

        return item
      end

      def empty?
        size.zero?
      end

      def each
        return to_enum(:each) unless block_given?

        pos = size - 1
        while pos >= 0
          yield array[pos]
          pos -= 1
        end
      end

      private

        def resize(capacity)
          # puts "--> Resized. before: #{array.count}, after: #{capacity}"
          self.array = Array.new(capacity){|i| array[i]}
        end

    end
  end
end


text:
package xin.keepmoving.netty.discard;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author: Zhourl
 * @Description: myapp
 * @Date: Create in 2017/11/19 21:49
 */
public class TimeClient {
    public static void main(String[] args) throws Exception {
        // 处理I/O操作的多线程事件循环器
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 新建一个辅助类
            Bootstrap b = new Bootstrap();
            b.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            // 开始一个客户端
            ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();

            // 等待连接关闭
            cf.channel().closeFuture().sync();

        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}


text:
==========================================
``construct.core`` -- entire module
==========================================

.. automodule:: construct.core


text:
(function() {
	//Add string.startsWith
	String.prototype.startsWith = function (str){
		return this.slice(0, str.length) == str;
	};

	function getVisibleRegion() {
		var split = window.location.href.split(/[/#/?]/);
		for (var i = 0; i < split.length; i++) {
			if (split[i].startsWith("region=")) {
				return split[i].substring(7).toLowerCase().split(" ").join("_");
			}
		}
		return "";
	}

	function isDarkTheme() {
		return $("link[href^='/ns.dark']").length > 0;
	}

	function getVisibleNation() {
		if ($(".bannernation a").length > 0) {
			return $(".bannernation a").attr("href").trim().substring(8);
		}
		return $(".nationname > a").attr("href") ? $(".nationname > a").attr("href").trim().substring(8) : "";
	}

	checkUpdates();
	function checkUpdates() {
		if ($("#highcharts_graph").length > 0) {
			chart = {};
			chart.type = $("#highcharts_graph").attr("graph");
			chart.region = $("#highcharts_graph").attr("region");
			chart.title = $("#highcharts_graph").attr("title");
			chart.width = $("#highcharts_graph").attr("width");
			chart.height = $("#highcharts_graph").attr("height");
			chart.visibleNation = $("#highcharts_graph").attr("visible_nation");
			chart.showInfluence = $("#highcharts_graph").attr("show_influence") == "true";
			$("#highcharts_graph").remove();

			if (chart.type == "region_chart" && getVisibleRegion() == chart.region) {
				drawRegionPopulationChart(chart.region, chart.title);
			} else if (chart.type == "set_chart_size") {
				updateChartSize(chart.width, chart.height);
			} else if (chart.type == "national_power" && getVisibleNation() == chart.visibleNation) {
				drawNationalPowerChart(chart.region, chart.title, chart.visibleNation, chart.showInfluence);
			}
		}

		if ($("div[name='save_file']").length > 0) {
			$("div[name='save_file']").each(function() {
				console.log("Attempting to save: " + $(this).attr("file"));
				var html = $(this).html();
				var data = JSON.parse(html);
				var blob = new Blob(data, {type: "text/plain;charset=utf-8"});
				saveAs(blob, $(this).attr("file"));
				$(this).remove();
			});
		}

		setTimeout(checkUpdates, 100);
	}

	var activeChart = null;
	function drawNationalPowerChart(region, title, visibleNation, showInfluence) {
		$.get("https://nationstatesplusplus.net/api/region/wa/?region=" + region, function(data) {
			var categoryTitles = [];
			var endorsements = [];
			var influence = [];
			var playerIndex = -1;
			for (var nation in data) {
				categoryTitles.push(nation);
			}
			if (showInfluence) {
				var sortNames = function(a, b) {
					return data[b].influence - data[a].influence;
				};
				categoryTitles.sort(sortNames);
			} else {
				var sortNames = function(a, b) {
					return data[b].endorsements - data[a].endorsements;
				};
				categoryTitles.sort(sortNames);
			}
			for (var i = 0; i < categoryTitles.length; i++) {
				var nation = data[categoryTitles[i]];
				endorsements.push(nation.endorsements);
				influence.push(nation.influence);
				if (playerIndex == -1 && categoryTitles[i].toLowerCase().split(" ").join("_") == visibleNation) {
					playerIndex = i;
				}
				categoryTitles[i] = "<b>" + categoryTitles[i] + "</b>";
			}
			if (activeChart != null) {
				activeChart.destroy();
			}
			var series;
			if (showInfluence) {
				series = [{	name: 'Influence', data: influence, color: '#AA4643' },{
							name: 'Endorsements', data: endorsements, color: '#4572A7' }]
			} else {
				series = [{ name: 'Endorsements', data: endorsements, color: '#4572A7' }]
			}
			var container = $('<div>');
			chart = new Highcharts.Chart({
				chart: {
					type: 'bar',
					renderTo: container[0],
					width: $("#" + (showInfluence ? 'influence' : 'power')).width(),
					height: Math.max(300, 100 + (categoryTitles.length * 26 * (showInfluence ? 2 : 1))),
					backgroundColor: 'rgba(255, 255, 255, ' + (isDarkTheme() ? '0.1' : '1.0') + ')'
				},
				title: {
					text: 'World Assembly Endorsements',
					color: (isDarkTheme() ? '#D0D0D0' : '#000000')
				},
				subtitle: {
					text: 'Region: ' + title,
					color: (isDarkTheme() ? '#D0D0D0' : '#000000')
				},
				xAxis: {
					categories: categoryTitles,
					title: {
						text: null
					}
				},
				yAxis: {
					min: 0,
					title: {
						text: 'Endorsements',
						align: 'high'
					},
					labels: {
						overflow: 'justify',
						useHTML: true
					},
				},
				plotOptions: {
					bar: {
						dataLabels: {
							enabled: true
						},
						animation: false
					},
					series: {
						cursor: 'pointer',
						point: {
							events: {
								click: function() {
									var nation = this.category.substring(3, this.category.length - 4);
									var prefix = (window.location.href.startsWith("https://") ? "https:" : "http:");
									window.location.href = prefix + "//www.nationstates.net/nation=" + nation.toLowerCase().split(" ").join("_") + "/detail=wa_stats/stats=" + (showInfluence ? 'influence' : 'power');
								}
							}
						}
					}
				},
				credits: {
					enabled: false
				},
				series: series
			});
			activeChart = chart;
			if (playerIndex > -1) {
				for (var i = 0; i < chart.series.length; i++) {
					chart.series[i].data[playerIndex].update({
						color: "#FF0000"
					});
				}
			}
			setTimeout(function() { $("#snark").remove(); container.appendTo($("#" + (showInfluence ? 'influence' : 'power')));}, 500);
		});
	}

	function updateChartSize(width, height) {
		for (var i = 0; i < Highcharts.charts.length; i++) {
			if (Highcharts.charts[i] != null)
				Highcharts.charts[i].setSize(width, height, true);
		}
	}

	function drawRegionPopulationChart(region, title) {
		$.get("https://nationstatesplusplus.net/api/region/population/?region=" + region, function(data) {
			var populations = [];
			for (var i = data.region.length - 1; i >= 0; i--) {
				var element = [];
				element.push(data.region[i].timestamp);
				element.push(data.region[i].population);
				populations.push(element);
			}
			chart = new Highcharts.Chart({
				chart: {
					type: 'line',
					renderTo: 'regional-pop',
					backgroundColor: 'rgba(255, 255, 255, ' + (isDarkTheme() ? '0.1' : '1.0') + ')'
				},
				title: {
					text: 'Regional Population',
					color: (isDarkTheme() ? '#D0D0D0' : '#000000')
				},
				subtitle: {
					text: title,
					color: (isDarkTheme() ? '#D0D0D0' : '#000000')
				},
				xAxis: {
					dateTimeLabelFormats: {
						month: '%e. %b',
						year: '%b'
					},
					type: 'datetime',
					title: {
						text: null
					}
				},
				yAxis: {
					min: 0,
					title: {
						text: 'Population',
						align: 'high'
					},
					labels: {
						overflow: 'justify',
						useHTML: true
					}
				},
				credits: {
					enabled: false
				},
				series:  [{ name: 'Population', data: populations, color: '#4572A7' }]
			});
		});
	}
})();


text:
#include "defs.h"
#include "mi-common.h"

static const char * const async_reason_string_lookup[] =
{
  "breakpoint-hit",
  "watchpoint-trigger",
  "read-watchpoint-trigger",
  "access-watchpoint-trigger",
  "function-finished",
  "location-reached",
  "watchpoint-scope",
  "end-stepping-range",
  "exited-signalled",
  "exited",
  "exited-normally",
  "signal-received",
  "solib-event",
  "fork",
  "vfork",
  "syscall-entry",
  "syscall-return",
  "exec",
  NULL
};

gdb_static_assert (ARRAY_SIZE (async_reason_string_lookup)
		   == EXEC_ASYNC_LAST + 1);

const char *
async_reason_lookup (enum async_reply_reason reason)
{
  return async_reason_string_lookup[reason];
}


text:
const express = require("express");
const app = express();

app.set("port", process.env.PORT || 3000);

//home page
app.get("/", (req, res) => {
  res.type("text/plain");
  res.send("Hello World!");
});

//custom 404 page
app.use((req, res) => {
  res.type("text/plain");
  res.status(404);
  res.send("404 - Not Found");
});

//custom 500 page
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.type("text/plain");
    res.status(500);
    res.send("500 - Server error");
});

app.listen(app.get("port"), () => {
    console.log("Server started on http://localhost:" + app.get("port"));
});


text:
SoundCloudSwift provides tools for authentication that you can use within your apps.

### iOS & OSX

1. Create an `Oauth2` object *(handler)* passing the `Oauth2Config` which includes *(client id, client secret and redirect uri)* provided by the API.
```swift
let oauth2: Oauth2 = Oauth2(config: Oauth2Config(clientId: clientId, clientSecret: clientSecret, redirectUri: redirect), scope: .All)
```
2. Subscribe to the Oauth2 signal to listen for status changes during the Oauth2 flow:
```swift
oauth2.signal.observeNext { (next) -> () in
  switch next {
    case .OpenUrl(let url): // Open url
    case .NewSession(let session): // Authentication completed
  }
  // Status events
}
```
Notice the kind of events that are sent:
  - **OpenUrl**: When this event is sent you have to open the provided link in your webview.
  - **NewSession**: When this event is received we have a new user session that we can use to authenticate API requests.

3. Connect your webview with `Oauth2` sending redirect URLs from the browser:
```swift
oauth2.validate(url: newUrl)
```

4. Start the Oauth2 flow with `oauth2.start()`

#### Oauth2WebView and Oauth2WebViewController

If you're going to use the native Webkit we provide you with a class, `Oauth2WebView` that automatizes the process. This class is initialized with the Oauth2 object and internally connects the Webview delegate with that object.

Your only responsibility in that case is listening to next events. *That's all!*

```swift
let viewController: Oauth2WebViewController = Oauth2WebViewController(oauth2: oauth2, scope: .All)
oauth2.signal.observeNext { (next) -> () in
    print(next)
}
```

### tvOS & watchOS

These systems don't support Webview, thus we cannot execute the authentication flow in these platforms. What we can do instead if sharing the authentication information from an iOS device or from OSX.

**watchOS**
- [WatchKit: Best practices sharing data between your watch an iOS app](http://www.kristinathai.com/watchkit-best-practices-for-sharing-data-between-your-watch-and-ios-app/)
- [Watch 2 transition guide](https://developer.apple.com/library/watchos/documentation/General/Conceptual/AppleWatch2TransitionGuide/UpdatetheAppCode.html)

**tvOS**

Apple doesn't provide any Connectivity framework to share data between iOS and tvOS. To solve this problem you can go to HTTP/TCP/Bluetooth custom solutions that you'll have to implement on your own

> We thought about implementing a custom sharing component for SoundCloudSwift but due to the fact that tvOS is in its early versions we preferred to wait for next version to see Apple's strategy around this topic.

### Recommended articles
- [Oauth Authentication on tvOS](http://stephenradford.me/oauth-login-on-tvos/)


text:
require 'test_helper'

require 'execjs'
require 'pathname'

class RequirejsRailsTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Requirejs
    assert_kind_of Module, Requirejs::Rails
    assert_kind_of Class, Requirejs::Rails::Engine
  end

  test "require.js version" do
    require_js = Pathname.new(__FILE__+'/../../vendor/assets/javascripts/require.js').cleanpath.read
    context = ExecJS.compile(require_js)
    assert_equal Requirejs::Rails::LibVersion, context.eval("require.version")
  end

  test "CHANGELOG up to date" do
    changelog_match = (/^# v#{Requirejs::Rails::Version}/ =~ Pathname.new(__FILE__+'/../../CHANGELOG.md').cleanpath.read)
    assert changelog_match, "CHANGELOG has no section for v#{Requirejs::Rails::Version}"
  end
end

class RequirejsRailsConfigTest < ActiveSupport::TestCase
  def setup
    @cfg = Requirejs::Rails::Config.new
  end

  test "config accepts known loaders" do
    @cfg.loader = :almond
    assert_equal :almond, @cfg.loader
  end

  test "config rejects bad loaders" do
    assert_raises Requirejs::ConfigError do
      @cfg.loader = :wombat
    end
  end

  test "matches configured logical assets" do
    assert_equal true, @cfg.asset_allowed?('foo.js')
    assert_equal false, @cfg.asset_allowed?('bar.frobnitz')
    @cfg.logical_asset_filter += [/\.frobnitz$/]
    assert_equal true, @cfg.asset_allowed?('bar.frobnitz')
  end

  test "should have a default empty user_config" do
    assert_kind_of Hash, @cfg.user_config
  end

  test "user_config should reject baseUrl" do
    exc = assert_raises Requirejs::ConfigError do
      @cfg.user_config = { 'baseUrl' => '/frobnitz' }
    end
    assert_match /baseUrl is not needed/, exc.message
  end

  test "run_config should inherit user_config settings" do
    @cfg.user_config = { 'paths' => { 'jquery' => 'lib/jquery-1.7.2.min' } }
    refute_nil @cfg.run_config['paths']
    assert_kind_of Hash, @cfg.run_config['paths']
    assert_equal 'lib/jquery-1.7.2.min', @cfg.run_config['paths']['jquery']
  end

  test "run_config should allow settings to be overridden" do
    @cfg.run_config['baseUrl'] = 'http://cdn.example.com/assets'
    assert_equal 'http://cdn.example.com/assets', @cfg.run_config['baseUrl']
  end

  test "build_config should inherit user_config settings" do
    @cfg.user_config = { 'paths' => { 'jquery' => 'lib/jquery-1.7.2.min' } }
    refute_nil @cfg.build_config['paths']
    assert_kind_of Hash, @cfg.build_config['paths']
    assert_equal 'lib/jquery-1.7.2.min', @cfg.build_config['paths']['jquery']
  end

  test "run_config should reject irrelevant settings" do
    @cfg.user_config = { 'optimize' => 'none' }
    assert_nil @cfg.run_config['optimize']
  end

  test "build_config should reject irrelevant settings" do
    @cfg.user_config = { 'priority' => %w{ foo bar baz } }
    assert_nil @cfg.build_config['priority']
  end

  ## Almond tests
  test "build_config with almond should accept one module" do
    @cfg.loader = :almond
    @cfg.user_config = { 'modules' => [ { 'name' => 'foo' } ] }
    assert_match 'almond', @cfg.build_config['modules'][0]['name']
  end

  test "build_config with almond must reject more than one module" do
    @cfg.loader = :almond
    @cfg.user_config = { 'modules' => [ { 'name' => 'foo' }, { 'name' => 'bar' } ] }
    exc = assert_raises Requirejs::ConfigError do
      @cfg.build_config
    end
    assert_match /requires exactly one module/, exc.message
  end
end

class RequirejsHelperTest < ActionView::TestCase

  def setup
    controller.requirejs_included = false
    Rails.application.config.requirejs.user_config = {}
    Rails.application.config.requirejs.delete(:run_config)
    Rails.application.config.requirejs.delete(:build_config)
  end

  def with_cdn
    Rails.application.config.requirejs.user_config = { 'paths' =>
      { 'jquery' => 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' }
    }
  end

  def wrap(tag)
    "#{tag}"
  end

  test "requirejs_include_tag" do
    render :text => wrap(requirejs_include_tag)
    assert_select "script:first-of-type", :text => /var require =/
    assert_select "script:last-of-type[src^=/javascripts/require.js]", :count => 1
  end

  test "requirejs_include_tag_with_param" do
    render :text => wrap(requirejs_include_tag("application"))
    assert_select "script:last-of-type[src^=/javascripts/require.js][data-main^=/javascripts/application]", :count => 1
  end

  test "requirejs_include_tag_with_block" do
    test_block = Proc.new do |controller|
      { 'class' => controller.class.to_s.demodulize }
    end

    render :text => wrap(requirejs_include_tag("application", &test_block))
    assert_select "script:last-of-type[src^=/javascripts/require.js][data-main^=/javascripts/application]", :count => 1
    assert_select "script:last-of-type[src^=/javascripts/require.js][data-class^=TestController]", :count => 1
  end

  test "requirejs_include_tag can appear only once" do
    assert_raises Requirejs::MultipleIncludeError do
      render :text => "#{requirejs_include_tag}\n#{requirejs_include_tag}"
    end
  end

  test "requirejs_include_tag with digested asset paths" do
    begin
      saved_digest = Rails.application.config.assets.digest
      Rails.application.config.assets.digest = true
      Rails.application.config.requirejs.user_config = { 'modules' => [{'name' => 'foo'}] }
      render :text => wrap(requirejs_include_tag)
      assert_select "script:first-of-type", :text => %r[var require =.*"paths":{"foo":"/javascripts/foo"}]
    ensure
      Rails.application.config.assets.digest = saved_digest
    end
  end

  test "requirejs_include_tag with CDN asset in paths" do
    with_cdn
    render :text => wrap(requirejs_include_tag)
    assert_select "script:first-of-type", :text => %r{var require =.*paths.*http://ajax}
  end

  test "requirejs_include_tag with CDN asset and digested asset paths" do
    begin
      with_cdn
      saved_digest = Rails.application.config.assets.digest
      Rails.application.config.assets.digest = true
      render :text => wrap(requirejs_include_tag)
      assert_select "script:first-of-type", :text => %r{var require =.*paths.*http://ajax}
    ensure
      Rails.application.config.assets.digest = saved_digest
    end
  end
end


text:
identifier: MIR:00000540
name: GWAS Central Study
description: GWAS Central (previously the Human Genome Variation database of Genotype-to-Phenotype information) is a database of summary level findings from genetic association studies, both large and small. It gathers datasets from public domain projects, and accepts direct data submission. It is based upon Marker information encompassing SNP and variant information from public databases, to which allele and genotype frequency data, and genetic association findings are additionally added. A Study (most generic level) contains one or more Experiments, one or more Sample Panels of test subjects, and one or more Phenotypes. This collection references a GWAS Central Study.
prefix: gwascentral.study
pattern: ^HGVST\d+$
prefixed: 0
local_id: HGVST1828
resources:
 - identifier: MIR:00100717
   accessurl: http://www.gwascentral.org/study/${lid}
   keyword: GWAS of Colorectal cancer
   description: GWAS Central Study at University of Leicester
   homepage: http://www.gwascentral.org/studies
   institution: Department of Genetics, University of Leicester, Leicester
   location: UK
   official: false
---


text:
var picker = require('picker');

picker.render();


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ParseStarterProjectActivity!</string>
    <string name="app_name">ParseStarterProject</string>

    <string name="action_settings">Settings</string>
    <string name="action_new">New Note</string>
    <string name="action_refresh">Refresh</string>
    <string name="title_activity_edit_note">Add/Edit</string>
    <string name="note_title_hint">Title</string>
    <string name="note_content_hint">Content</string>
    <string name="save_button">Save</string>
    <string name="edit_error_title">Error!</string>
    <string name="edit_error_message">You cannot save a note without a title</string>
    <string name="title_activity_login">Login</string>
    <string name="username_hint">Username</string>
    <string name="password_hint">Password</string>
    <string name="email_hint">Email</string>
    <string name="sign_up_button_label">Sign Up</string>
    <string name="signup_error_message">Please make sure you enter a username, password, and email address!</string>
    <string name="signup_error_title">Error!</string>
    <string name="login_error_message">Please make sure you enter a username and password!</string>
    <string name="login_error_title">Error!</string>
    <string name="login_button_label">Login</string>
    <string name="sign_up_text">Sign Up!</string>
    <string name="title_activity_sign_up">Sign Up</string>
    <string name="logout_label">Logout</string>

</resources>


text:
package com.goodrobots;

/**
 * Created with IntelliJ IDEA.
 * User: scott
 * Date: 8/16/14
 * Time: 3:26 PM
 * To change this template use File | Settings | File Templates.
 */
public class Log {

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}


text:
package service

import (
	"context"
	"fmt"
	"sort"
	"strings"
	"time"

	"go-common/app/interface/main/tag/model"
	account "go-common/app/service/main/account/model"
	"go-common/app/service/main/archive/api"
	taGrpcModel "go-common/app/service/main/tag/api"
	rpcModel "go-common/app/service/main/tag/model"
	"go-common/library/ecode"
	"go-common/library/net/metadata"
)

const (
	_adminFace = "http://static.hdslb.com/images/member/noface.gif"
	_adminName = "管理员"
)

func keySingle(oid int64, tp int32) string {
	return fmt.Sprintf("%d_%d", oid, tp)
}

// ArcTags .
func (s *Service) ArcTags(c context.Context, aid, mid int64) (reTs []*model.Tag, err error) {
	reTs = make([]*model.Tag, 0)
	v, err, _ := s.singleGroup.Do(keySingle(aid, rpcModel.ResTypeArchive), func() (res interface{}, err error) {
		return s.dao.ResTagMap(c, aid, rpcModel.ResTypeArchive)
	})
	if err != nil {
		return
	}
	arcTags := v.(map[int64]*taGrpcModel.Resource)
	var (
		tids    []int64
		allTids []int64
	)
	for _, v := range arcTags {
		if v.State != model.ResTagStateNormal && v.State != model.ResTagStateRegion {
			continue
		}
		allTids = append(allTids, v.Tid)
		if v.State == model.ResTagStateNormal {
			tids = append(tids, v.Tid)
		}
	}
	if len(tids) == 0 {
		return
	}
	_, channelIDs := s.resourceChannel(allTids, model.ManagerNo)
	channelMap := make(map[int64]struct{}, len(channelIDs))
	for _, tid := range channelIDs {
		channelMap[tid] = struct{}{}
		allTids = append(allTids, tid)
	}
	tagMap, err := s.dao.TagMap(c, allTids, mid)
	if err != nil {
		return
	}
	actionMap, _ := s.resAction(c, mid, aid, rpcModel.ResTypeArchive, tids)
	resTags := make([]*model.Tag, 0, len(channelIDs)+len(tids))
	for _, tid := range channelIDs {
		if tag, ok := tagMap[tid]; ok && tag.State == model.TagStateNormal {
			t := &model.Tag{
				ID:           tag.Id,
				Name:         tag.Name,
				Cover:        tag.Cover,
				Content:      tag.Content,
				ShortContent: tag.ShortContent,
				HeadCover:    tag.HeadCover,
				Type:         int8(tag.Type),
				State:        int8(tag.State),
				CTime:        tag.Ctime,
				MTime:        tag.Mtime,
				IsAtten:      int8(tag.Attention),
				Attribute:    int8(tag.Attr),
			}
			t.Count.Use = int(tag.Bind)
			t.Count.Atten = int(tag.Sub)
			resTags = append(resTags, t)
		}
	}
	for _, tid := range tids {
		if _, ok := channelMap[tid]; ok {
			continue
		}
		resource, ok := arcTags[tid]
		if !ok {
			continue
		}
		tag, ok := tagMap[tid]
		if !ok || tag.State != model.TagStateNormal {
			continue
		}
		t := &model.Tag{
			ID:           tag.Id,
			Name:         tag.Name,
			Cover:        tag.Cover,
			Content:      tag.Content,
			ShortContent: tag.ShortContent,
			HeadCover:    tag.HeadCover,
			Type:         int8(tag.Type),
			State:        int8(tag.State),
			CTime:        tag.Ctime,
			MTime:        tag.Mtime,
			IsAtten:      int8(tag.Attention),
			Role:         int8(resource.Role),
			Likes:        int64(resource.Like),
			Hates:        int64(resource.Hate),
			Attribute:    int8(resource.Attr),
		}
		t.Count.Use = int(tag.Bind)
		t.Count.Atten = int(tag.Sub)
		if action, ok := actionMap[tid]; ok {
			switch action {
			case rpcModel.UserActionLike:
				t.Liked = 1
			case rpcModel.UserActionHate:
				t.Hated = 1
			}
		}
		reTs = append(reTs, t)
	}
	sort.Sort(model.Tags(reTs))
	resTags = append(resTags, reTs...)
	return resTags, err
}

// MutiArcTags muti archive tags.
func (s *Service) MutiArcTags(c context.Context, mid int64, oids []int64) (res map[int64][]*model.Tag, err error) {
	res = make(map[int64][]*model.Tag, len(oids))
	resouceMap, err := s.dao.ResTags(c, oids, rpcModel.ResTypeArchive)
	if err != nil {
		return
	}
	var (
		tids          = make([]int64, 0)
		arcTidsMap    = make(map[int64][]int64, len(oids))
		allArcTidsMap = make(map[int64][]int64, len(oids))
	)
	for oid, arcTags := range resouceMap {
		var (
			arcTids    = make([]int64, 0, len(arcTags))
			allArcTids = make([]int64, 0, len(arcTags))
		)
		for _, v := range arcTags {
			if v.State != model.ResTagStateNormal && v.State != model.ResTagStateRegion {
				continue
			}
			allArcTids = append(allArcTids, v.Tid)
			tids = append(tids, v.Tid)
			if v.State == model.ResTagStateNormal {
				arcTids = append(arcTids, v.Tid)
			}
		}
		arcTidsMap[oid] = arcTids
		allArcTidsMap[oid] = allArcTids
	}
	channelMap, channelIDs := s.resourceChannels(c, model.ManagerNo, allArcTidsMap)
	tids = append(tids, channelIDs...)
	tagMap, err := s.dao.TagMap(c, tids, mid)
	if err != nil {
		return
	}
	for oid, v := range arcTidsMap {
		k, ok := channelMap[oid]
		var arcTags = make([]*model.Tag, 0, len(v)+len(k))
		for channelID := range k {
			if tag, exist := tagMap[channelID]; exist && tag.State == model.TagStateNormal {
				t := &model.Tag{
					ID:           tag.Id,
					Name:         tag.Name,
					Cover:        tag.Cover,
					Content:      tag.Content,
					ShortContent: tag.ShortContent,
					HeadCover:    tag.HeadCover,
					Type:         int8(tag.Type),
					State:        int8(tag.State),
					CTime:        tag.Ctime,
					MTime:        tag.Mtime,
					IsAtten:      int8(tag.Attention),
					Attribute:    int8(tag.Attr),
				}
				t.Count.Use = int(tag.Bind)
				t.Count.Atten = int(tag.Sub)
				arcTags = append(arcTags, t)
			}
		}
		for _, tid := range v {
			if ok {
				if _, b := k[tid]; b {
					continue
				}
			}
			if tag, exist := tagMap[tid]; exist && tag.State == model.TagStateNormal {
				t := &model.Tag{
					ID:           tag.Id,
					Name:         tag.Name,
					Cover:        tag.Cover,
					Content:      tag.Content,
					ShortContent: tag.ShortContent,
					HeadCover:    tag.HeadCover,
					Type:         int8(tag.Type),
					State:        int8(tag.State),
					CTime:        tag.Ctime,
					MTime:        tag.Mtime,
					IsAtten:      int8(tag.Attention),
					Attribute:    int8(tag.Attr),
				}
				t.Count.Use = int(tag.Bind)
				t.Count.Atten = int(tag.Sub)
				arcTags = append(arcTags, t)
			}
		}
		res[oid] = arcTags
	}
	return
}

// Logs .
func (s *Service) Logs(c context.Context, aid, mid int64, pn, ps int) (atls []*model.ArcTagLog, err error) {
	var (
		mids []int64
		mm   map[int64]*account.Card
		tagm = make(map[int64]string)
	)
	if _, err = s.normalArchive(c, aid); err != nil {
		atls = []*model.ArcTagLog{}
		return
	}
	var rls []*rpcModel.ResourceLog
	rls, err = s.resTagLog(c, mid, aid, rpcModel.ResTypeArchive, pn, ps)
	if err != nil {
		return
	}
	if len(rls) == 0 {
		atls = []*model.ArcTagLog{}
		return
	}
	var (
		tids []int64
		ts   []*rpcModel.Tag
	)
	for _, v := range rls {
		atl := &model.ArcTagLog{
			Lid:    v.ID,
			Aid:    v.Oid,
			Tid:    v.Tid,
			Mid:    v.Mid,
			Role:   int8(v.Role),
			Action: int8(v.Action),
			CTime:  v.CTime,
		}
		if v.State == 1 {
			atl.IsDeal = 1
		}
		if v.State == 2 {
			atl.IsReport = 1
		}
		atls = append(atls, atl)
		tids = append(tids, v.Tid)
	}
	ts, err = s.tags(c, tids, mid)
	if err != nil {
		return
	}
	for _, v := range ts {
		if v != nil {
			tagm[v.ID] = v.Name
		}
	}
	for _, atl := range atls {
		if len(tagm) > 0 {
			if name, ok := tagm[atl.Tid]; ok {
				atl.Tname = name
			}
		}
		if atl.Role != 2 {
			mids = append(mids, atl.Mid)
		}
	}
	if mm, err = s.dao.UserCards(c, mids); err != nil {
		return
	}
	for _, atl := range atls {
		if atl.Role == 2 {
			atl.Face = _adminFace
			atl.UName = _adminName
			continue
		}
		if _, ok := mm[atl.Mid]; ok {
			atl.Face = mm[atl.Mid].Face
			atl.UName = mm[atl.Mid].Name
		}
	}
	return
}

// Add .
func (s *Service) Add(c context.Context, aid, mid int64, name string, now time.Time) (tid int64, err error) {
	var arc *api.Arc
	if arc, err = s.normalArchive(c, aid); err != nil {
		return
	}
	if err = s.policy(c, arc.Author.Mid, mid, now); err != nil {
		return
	}
	if mid != arc.Author.Mid {
		err = ecode.TagOnlyUpAdd
		return
	}
	if err = s.realName(c, mid); err != nil {
		return
	}
	if err = s.filter(c, name, now); err != nil {
		return
	}
	var (
		atm                  map[int64]*model.ArcTag
		tag                  *model.Tag
		tagType, userRole, _ = s.checkTypeRole(mid, arc.Author.Mid) // get tag type and user role
	)
	if tag, err = s.resCheckTag(c, mid, name, tagType, now); err != nil {
		return
	}
	// 活动tag不可外部加
	if tag.Type == model.OfficailActiveTag {
		err = ecode.TagIsOfficailTag
		return
	}
	tid = tag.ID
	if atm, err = s.checkArcTag(c, aid, tid, model.ArcTagAdd); err != nil {
		return
	}
	count, err := s.dao.SpamCache(c, mid, model.SpamAdd)
	if err != nil {
		return
	}
	if count >= s.c.Tag.ArcTagAddMaxNum {
		err = ecode.TagArcTagAddMaxFre
		return
	}
	if err = s.checkUser(c, aid, arc.Author.Mid, mid, tid, now, model.ArcTagAdd); err != nil {
		return
	}
	var rem map[string]*rpcModel.ResourceLog
	rem, err = s.resTagLogMap(c, mid, aid, rpcModel.ResTypeArchive, 1, 20)
	if err != nil {
		return
	}
	if len(rem) > 0 {
		k := fmt.Sprintf("%d_%d_%d_%d_%d", aid, rpcModel.ResTypeArchive, tid, mid, rpcModel.ResTagLogAdd)
		if rl, ok := rem[k]; ok && rl.State == 1 {
			return 0, ecode.TagAddNotRptPassed
		}
	}
	err = s.platformUserBind(c, aid, mid, tag.ID, rpcModel.ResTypeArchive, int32(userRole), rpcModel.ResTagLogAdd)
	if err != nil {
		return
	}
	s.dao.IncrSpamCache(c, mid, model.SpamAdd)
	var tids []int64
	for _, at := range atm {
		tids = append(tids, at.Tid)
	}
	tids = append(tids, tid)
	s.setArchiveTag(c, aid, tids)
	return
}

// Del .
func (s *Service) Del(c context.Context, aid, mid, tid int64, now time.Time) (err error) {
	if _, ok := s.channelMap[tid]; ok {
		return ecode.ChannelNotAllowDel
	}
	var arc *api.Arc
	if arc, err = s.normalArchive(c, aid); err != nil {
		return
	}
	if err = s.policy(c, arc.Author.Mid, mid, now); err != nil {
		return
	}
	if mid != arc.Author.Mid {
		return ecode.TagOnlyUpDel
	}
	if err = s.realName(c, mid); err != nil {
		return
	}
	count, err := s.dao.SpamCache(c, mid, model.SpamDel)
	if err != nil {
		return
	}
	if count >= s.c.Tag.ArcTagDelMaxNum {
		return ecode.TagArcTagDelMaxFre
	}
	if err = s.checkUser(c, aid, arc.Author.Mid, mid, tid, now, model.ArcTagDel); err != nil {
		return
	}
	var (
		_, _, opRole = s.checkTypeRole(mid, arc.Author.Mid)
		atm          map[int64]*model.ArcTag
	)
	if atm, err = s.checkArcTag(c, aid, tid, model.ArcTagDel); err != nil {
		return
	}
	var rem map[string]*rpcModel.ResourceLog
	rem, err = s.resTagLogMap(c, mid, aid, rpcModel.ResTypeArchive, 1, 20)
	if err != nil {
		return
	}
	if len(rem) > 0 {
		k := fmt.Sprintf("%d_%d_%d_%d_%d", aid, rpcModel.ResTypeArchive, tid, mid, rpcModel.ResTagLogDel)
		if rl, ok := rem[k]; ok && rl.State == 1 {
			return ecode.TagDelNotRptPassed
		}
	}
	err = s.platformUserBind(c, aid, mid, tid, rpcModel.ResTypeArchive, int32(opRole), rpcModel.ResTagLogDel)
	if err != nil {
		return
	}
	s.dao.IncrSpamCache(c, mid, model.SpamDel)
	var tids []int64
	delete(atm, tid)
	for _, at := range atm {
		tids = append(tids, at.Tid)
	}
	s.setArchiveTag(c, aid, tids)
	return
}

// AddReport .
func (s *Service) AddReport(c context.Context, aid, tid, rptMid int64, reason int8, now time.Time) (err error) {
	if err = s.checkReportUser(c, rptMid); err != nil {
		return
	}
	var arc *api.Arc
	if arc, err = s.normalArchive(c, aid); err != nil {
		return
	}
	score, _ := s.userFigure(c, rptMid)
	var rtm map[int64]*rpcModel.Resource
	if rtm, err = s.resTagMap(c, rptMid, aid, rpcModel.ResTypeArchive); err != nil {
		return
	}
	if _, ok := rtm[tid]; !ok {
		if k, ok := s.channelMap[tid]; ok {
			appealInfo := &model.WorkflowAppealInfo{
				Business: model.WorkflowBusinessChannel,
				FID:      model.WorkflowFIDChannel,
				RID:      model.WorkflowRIDChannel,
				Score:    score,
				Oid:      aid,
				EID:      tid,
				RptMid:   rptMid,
				Mid:      arc.Author.Mid,
				RegionID: arc.TypeID,
				ReasonID: reason,
				TName:    k.Name,
				RealIP:   metadata.String(c, metadata.RemoteIP),
			}
			return s.workflowAppeal(c, appealInfo)
		}
		return ecode.TagResTagNotExist
	}
	err = s.dao.AddReport(c, aid, tid, rptMid, rpcModel.ResTypeArchive, arc.TypeID, int32(reason), int32(score))
	if err == nil {
		s.cacheCh.Do(c, func(ctx context.Context) {
			s.dao.IncrSpamCache(ctx, rptMid, model.SpamReport)
		})
	}
	return
}

// LogReport .
func (s *Service) LogReport(c context.Context, aid, logID, rptMid int64, reason int8, now time.Time) (err error) {
	if err = s.checkReportUser(c, rptMid); err != nil {
		return
	}
	var arc *api.Arc
	if arc, err = s.normalArchive(c, aid); err != nil {
		return
	}
	score, _ := s.userFigure(c, rptMid)
	err = s.reportAction(c, aid, logID, rptMid, rpcModel.ResTypeArchive, arc.TypeID, int32(reason), int32(score))
	if err == nil {
		s.cacheCh.Do(c, func(ctx context.Context) {
			s.dao.IncrSpamCache(ctx, rptMid, model.SpamReport)
		})
	}
	return
}

func (s *Service) setArchiveTag(c context.Context, aid int64, tids []int64) (err error) {
	var (
		names   []string
		nameStr string
		tags    []*model.Tag
	)
	if tags, err = s.infos(c, 0, tids); err != nil {
		return
	}
	for _, tag := range tags {
		names = append(names, tag.Name)
	}
	nameStr = strings.Join(names, ",")
	// up archive tag
	s.setArcTag(c, aid, nameStr)
	return
}

func (s *Service) workflowAppeal(c context.Context, appeal *model.WorkflowAppealInfo) (err error) {
	var state int32
	if state, err = s.workflowAppealState(c, appeal); err != nil {
		return
	}
	if state == model.AppealStatEffective || state == model.AppealStateInvalid {
		return ecode.TagRptNotRptPassed
	}
	appeals, err := s.workflowAppeaList(c, appeal)
	if err != nil {
		return
	}
	for _, rpt := range appeals {
		if rpt.Business == model.WorkflowBusinessChannel && rpt.Oid == appeal.Oid && rpt.Eid == appeal.EID && rpt.Mid == appeal.RptMid {
			return ecode.TagArcTagRpted
		}
	}
	return s.addWorkflowAppeal(c, appeal)
}

func (s *Service) checkReportUser(c context.Context, mid int64) (err error) {
	card, err := s.dao.UserCard(c, mid)
	if err != nil {
		return
	}
	if card.Level < int32(s.c.Tag.ArcTagRptLevel) { // 等级限制
		return ecode.TagArcRptLevelLower
	}
	if card.Silence != model.UserBannedNone {
		return ecode.TagArcAccountBlocked
	}
	count, err := s.dao.SpamCache(c, mid, model.SpamReport)
	if err != nil {
		return
	}
	if count >= s.c.Tag.ArcTagRptMaxNum {
		err = ecode.TagArcTagRptMaxFre
	}
	return
}


text:
package io.aeron.logbuffer;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import io.aeron.protocol.DataHeaderFlyweight;
import org.agrona.ErrorHandler;
import org.agrona.concurrent.UnsafeBuffer;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static io.aeron.logbuffer.FrameDescriptor.*;
import static io.aeron.protocol.HeaderFlyweight.HDR_TYPE_DATA;
import static org.agrona.BitUtil.align;

public class TermReaderTest
{
    private static final int TERM_BUFFER_CAPACITY = LogBufferDescriptor.TERM_MIN_LENGTH;
    private static final int HEADER_LENGTH = DataHeaderFlyweight.HEADER_LENGTH;
    private static final int INITIAL_TERM_ID = 7;

    private final Header header = new Header(INITIAL_TERM_ID, TERM_BUFFER_CAPACITY);
    private final UnsafeBuffer termBuffer = mock(UnsafeBuffer.class);
    private final ErrorHandler errorHandler = mock(ErrorHandler.class);
    private final FragmentHandler handler = Mockito.mock(FragmentHandler.class);

    @Before
    public void setUp()
    {
        when(termBuffer.capacity()).thenReturn(TERM_BUFFER_CAPACITY);
    }

    @Test
    public void shouldPackPaddingAndOffsetIntoResultingStatus()
    {
        final int offset = 77;
        final int fragmentsRead = 999;

        final long scanOutcome = TermReader.pack(offset, fragmentsRead);

        assertThat(TermReader.offset(scanOutcome), is(offset));
        assertThat(TermReader.fragmentsRead(scanOutcome), is(fragmentsRead));
    }

    @Test
    public void shouldReadFirstMessage()
    {
        final int msgLength = 1;
        final int frameLength = HEADER_LENGTH + msgLength;
        final int termOffset = 0;

        when(termBuffer.getIntVolatile(0)).thenReturn(frameLength);
        when(termBuffer.getShort(typeOffset(0))).thenReturn((short)HDR_TYPE_DATA);

        final long readOutcome = TermReader.read(
            termBuffer, termOffset, handler, Integer.MAX_VALUE, header, errorHandler);
        assertThat(TermReader.fragmentsRead(readOutcome), is(1));

        final InOrder inOrder = inOrder(termBuffer);
        inOrder.verify(termBuffer).getIntVolatile(0);
        verify(handler).onFragment(eq(termBuffer), eq(HEADER_LENGTH), eq(msgLength), any(Header.class));
    }

    @Test
    public void shouldNotReadPastTail()
    {
        final int termOffset = 0;

        final long readOutcome = TermReader.read(
            termBuffer, termOffset, handler, Integer.MAX_VALUE, header, errorHandler);
        assertThat(TermReader.fragmentsRead(readOutcome), is(0));
        assertThat(TermReader.offset(readOutcome), is(termOffset));

        verify(termBuffer).getIntVolatile(0);
        verify(handler, never()).onFragment(any(), anyInt(), anyInt(), any());
    }

    @Test
    public void shouldReadOneLimitedMessage()
    {
        final int msgLength = 1;
        final int frameLength = HEADER_LENGTH + msgLength;
        final int termOffset = 0;

        when(termBuffer.getIntVolatile(anyInt())).thenReturn(frameLength);
        when(termBuffer.getShort(anyInt())).thenReturn((short)HDR_TYPE_DATA);

        final long readOutcome = TermReader.read(termBuffer, termOffset, handler, 1, header, errorHandler);
        assertThat(TermReader.fragmentsRead(readOutcome), is(1));

        final InOrder inOrder = inOrder(termBuffer, handler);
        inOrder.verify(termBuffer).getIntVolatile(0);
        inOrder.verify(handler).onFragment(eq(termBuffer), eq(HEADER_LENGTH), eq(msgLength), any(Header.class));
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void shouldReadMultipleMessages()
    {
        final int msgLength = 1;
        final int frameLength = HEADER_LENGTH + msgLength;
        final int alignedFrameLength = align(frameLength, FRAME_ALIGNMENT);
        final int termOffset = 0;

        when(termBuffer.getIntVolatile(0)).thenReturn(frameLength);
        when(termBuffer.getIntVolatile(alignedFrameLength)).thenReturn(frameLength);
        when(termBuffer.getShort(anyInt())).thenReturn((short)HDR_TYPE_DATA);

        final long readOutcome = TermReader.read(
            termBuffer, termOffset, handler, Integer.MAX_VALUE, header, errorHandler);
        assertThat(TermReader.fragmentsRead(readOutcome), is(2));
        assertThat(TermReader.offset(readOutcome), is(alignedFrameLength * 2));

        final InOrder inOrder = inOrder(termBuffer, handler);
        inOrder.verify(termBuffer).getIntVolatile(0);
        inOrder.verify(handler).onFragment(eq(termBuffer), eq(HEADER_LENGTH), eq(msgLength), any(Header.class));

        inOrder.verify(termBuffer).getIntVolatile(alignedFrameLength);
        inOrder
            .verify(handler)
            .onFragment(eq(termBuffer), eq(alignedFrameLength + HEADER_LENGTH), eq(msgLength), any(Header.class));
    }

    @Test
    public void shouldReadLastMessage()
    {
        final int msgLength = 1;
        final int frameLength = HEADER_LENGTH + msgLength;
        final int alignedFrameLength = align(frameLength, FRAME_ALIGNMENT);
        final int frameOffset = TERM_BUFFER_CAPACITY - alignedFrameLength;

        when(termBuffer.getIntVolatile(frameOffset)).thenReturn(frameLength);
        when(termBuffer.getShort(typeOffset(frameOffset))).thenReturn((short)HDR_TYPE_DATA);

        final long readOutcome = TermReader.read(
            termBuffer, frameOffset, handler, Integer.MAX_VALUE, header, errorHandler);
        assertThat(TermReader.fragmentsRead(readOutcome), is(1));
        assertThat(TermReader.offset(readOutcome), is(TERM_BUFFER_CAPACITY));

        final InOrder inOrder = inOrder(termBuffer, handler);
        inOrder.verify(termBuffer).getIntVolatile(frameOffset);
        inOrder.verify(handler).onFragment(
            eq(termBuffer), eq(frameOffset + HEADER_LENGTH), eq(msgLength), any(Header.class));
    }

    @Test
    public void shouldNotReadLastMessageWhenPadding()
    {
        final int msgLength = 1;
        final int frameLength = HEADER_LENGTH + msgLength;
        final int alignedFrameLength = align(frameLength, FRAME_ALIGNMENT);
        final int frameOffset = TERM_BUFFER_CAPACITY - alignedFrameLength;

        when(termBuffer.getIntVolatile(frameOffset)).thenReturn(frameLength);
        when(termBuffer.getShort(typeOffset(frameOffset))).thenReturn((short)PADDING_FRAME_TYPE);

        final long readOutcome = TermReader.read(
            termBuffer, frameOffset, handler, Integer.MAX_VALUE, header, errorHandler);
        assertThat(TermReader.fragmentsRead(readOutcome), is(0));
        assertThat(TermReader.offset(readOutcome), is(TERM_BUFFER_CAPACITY));

        final InOrder inOrder = inOrder(termBuffer);
        inOrder.verify(termBuffer).getIntVolatile(frameOffset);
        verify(handler, never()).onFragment(any(), anyInt(), anyInt(), any());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/fblandroidhack.persontracker"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:gravity="center_vertical">

    <CheckBox
        android:id="@+id/toggleAcceleroDisabled"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>

    <CheckBox
        android:id="@+id/toggleLeftHanded"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/toggleAcceleroDisabled"
        android:layout_below="@+id/toggleAcceleroDisabled"
        android:layout_marginTop="@dimen/settings_vertical_gap"/>

    <com.parrot.freeflight.ui.controls.ParrotSeekBar
        android:id="@+id/seekDeviceTiltMax"
        android:layout_width="@dimen/settings_seek_width"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/toggleLeftHanded"
        android:layout_below="@+id/toggleLeftHanded" android:textSize="@dimen/settings_text_small_size"
        app:lowerBoundText="5"
        app:upperBoundText="50"
    	app:lowerValuePaddingLeft="@dimen/settings_seek_bounds_value_padding"
    	app:upperValuePaddingRight="@dimen/settings_seek_bounds_value_padding"
        android:layout_marginTop="@dimen/settings_vertical_gap" android:layout_marginRight="@dimen/settings_pager_button_width"/>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/toggleAcceleroDisabled"
        android:text="@string/JOYPAD_MODE" android:layout_marginRight="@dimen/settings_hor_gap"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/toggleLeftHanded"
        android:text="@string/left_handed" android:layout_marginRight="@dimen/settings_hor_gap" android:layout_alignTop="@+id/toggleLeftHanded"/>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/seekDeviceTiltMax"
        android:layout_toLeftOf="@+id/seekDeviceTiltMax"
        android:text="@string/tilt_max" android:layout_marginRight="@dimen/settings_hor_gap"/>

    <TextView
        android:id="@+id/txtDeviceTiltMax"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_alignRight="@+id/textView4"
        android:layout_below="@+id/textView4"
        android:text="27.5" style="@style/SettingsTextView.Value" android:layout_marginTop="-5dp"/>

</RelativeLayout>


text:
package cd.go.contrib.elasticagents.marathon.executors;

import cd.go.contrib.elasticagents.marathon.RequestExecutor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;

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

public class GetProfileMetadataExecutor implements RequestExecutor {
    private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

    private static final Metadata IMAGE = new Metadata("Image", true, false);
    private static final Metadata MAX_MEMORY = new MemoryMetadata("Memory", true);
    private static final Metadata CPUS = new Metadata("CPUs", true, false);
    private static final Metadata COMMAND = new Metadata("Command", false, false);
    private static final Metadata ENVIRONMENT = new Metadata("Environment", false, false);
    private static final Metadata USER = new Metadata("User", false, false);
    private static final Metadata CONSTRAINTS = new ArrayMetadata("Constraints", false);
    private static final Metadata URIS = new Metadata("URIs", false, false);
    private static final Metadata VOLUMES = new Metadata("Volumes", false, false);

    static final List<Metadata> FIELDS = new ArrayList<>();

    static {
        FIELDS.add(IMAGE);
        FIELDS.add(MAX_MEMORY);
        FIELDS.add(CPUS);
        FIELDS.add(COMMAND);
        FIELDS.add(ENVIRONMENT);
        FIELDS.add(USER);
        FIELDS.add(CONSTRAINTS);
        FIELDS.add(URIS);
        FIELDS.add(VOLUMES);
    }

    @Override

    public GoPluginApiResponse execute() throws Exception {
        return new DefaultGoPluginApiResponse(200, GSON.toJson(FIELDS));
    }
}


text:
<title>ESRI File Geodatabase (FileGDB)</title>

ESRI File Geodatabase (FileGDB)

The FileGDB driver provides read and write access to File Geodatabases (.gdb directories) created by ArcGIS 10 and above.

Requirements

FileGDB API SDK

OGR >= 1.9.0

Bulk feature loading (OGR >= 1.9.2)

The FGDB_BULK_LOAD configuration option can be set to YES to speed-up feature insertion (or sometimes solve problems
when inserting a lot of features (see http://trac.osgeo.org/gdal/ticket/4420). The effect of this configuration option
is to cause a write lock to be taken and a temporary disabling of the indexes. Those are restored when the datasource is
closed or when a read operation is done.

SQL support (OGR >= 1.10)

Starting with OGR 1.10, SQL statements are run through the SQL engine of the FileGDB SDK API. This holds for non-SELECT
statements. However, due to partial/inaccurate support for SELECT statements in current FileGDB SDK API versions (v1.2),
SELECT statements will be run by default by the OGR SQL engine. This can be changed by specifying the
-dialect FileGDB option to ogrinfo or ogr2ogr.

Special SQL requests

"GetLayerDefinition a_layer_name" and "GetLayerMetadata a_layer_name" can be used as special SQL requests to get
respectively the definition and metadata of a FileGDB table as XML content.

Dataset Creation Options

None.

Layer Creation Options

FEATURE_DATASET: When this option is set, the new layer will be created inside the named FeatureDataset folder. If the folder does not already exist, it will be created.

GEOMETRY_NAME: Set name of geometry column in new layer. Defaults to "SHAPE".

OID_NAME: Name of the OID column to create. Defaults to "OBJECTID".

XYTOLERANCE, ZTOLERANCE: These parameters control the snapping tolerance used for advanced ArcGIS features like network and topology rules. They won't effect any 	OGR operations, but they will by used by ArcGIS. The units of the parameters are the units of the coordinate reference system.

ArcMap 10.0 and OGR defaults for XYTOLERANCE are 0.001m (or equivalent) for projected coordinate systems, and 0.000000008983153° for geographic coordinate systems.

XORIGIN, YORIGIN, ZORIGIN, XYSCALE, ZSCALE: These parameters control the coordinate precision grid  inside the file geodatabase. The dimensions of the grid are determined by the origin, and the scale. The origin defines the location of a reference grid point in space. The scale is the reciprocal of the resolution. So, to get a grid with an origin at 0 and a resolution of 0.001 on all axes, you would set all the origins to 0 and all the scales to 1000.

Important: The domain specified by (xmin=XORIGIN, ymin=YORIGIN, xmax=(XORIGIN + 9E+15 / XYSCALE), ymax=(YORIGIN + 9E+15 / XYSCALE)) needs to encompass every possible coordinate value for the feature class. If features are added with coordinates that fall outside the domain, errors will occur in ArcGIS with spatial indexing, feature selection, and exporting data.

ArcMap 10.0 and OGR defaults:

For geographic coordinate systems: XORIGIN=-400, YORIGIN=-400, XYSCALE=1000000000

For projected coordinate systems: XYSCALE=10000 for the default XYTOLERANCE of 0.001m. XORIGIN and YORIGIN change based on the coordinate system, but the OGR default of -2147483647 is suitable with the default XYSCALE for all coordinate systems.

XML_DEFINITION : (GDAL >= 1.10) When this option is set, its value will be used as the XML definition to create the new table. The root node of such a XML definition must be a <esri:DataElement> element conformant to FileGDBAPI.xsd

Examples

Read layer from FileGDB and load into PostGIS:

	ogr2ogr -overwrite -skipfailures -f "PostgreSQL" PG:"host=myhost user=myuser dbname=mydb password=mypass" "C:\somefolder\BigFileGDB.gdb" "MyFeatureClass"

Get detailed info for FileGDB:

	ogrinfo -al "C:\somefolder\MyGDB.gdb"

Building Notes

 Read the GDAL Windows Building example for Plugins. You will find a similar section in nmake.opt for FileGDB. After you are done, go to the $gdal_source_root\ogr\ogrsf_frmts\filegdb folder and execute:

		nmake /f makefile.vc plugin
		nmake /f makefile.vc plugin-install

Known Issues

Blob fields have not been implemented.

FGDB coordinate snapping will cause geometries to be altered during writing. Use the origin and scale layer creation options to control the snapping behavior.

Links

ESRI File Geodatabase API Page


text:
Tomas Fernandez

National Insurance Number
QQ 53 12 35 C

Date of birth
15 October 1994


text:
"""
===============================================
Feature transformations with ensembles of trees
===============================================

Transform your features into a higher dimensional, sparse space. Then train a
linear model on these features.

First fit an ensemble of trees (totally random trees, a random forest, or
gradient boosted trees) on the training set. Then each leaf of each tree in the
ensemble is assigned a fixed arbitrary feature index in a new feature space.
These leaf indices are then encoded in a one-hot fashion.

Each sample goes through the decisions of each tree of the ensemble and ends up
in one leaf per tree. The sample is encoded by setting feature values for these
leaves to 1 and the other feature values to 0.

The resulting transformer has then learned a supervised, sparse,
high-dimensional categorical embedding of the data.

"""

# Author: Tim Head <betatim@gmail.com>
#
# License: BSD 3 clause

# %%
# First, we will create a large dataset and split it into three sets:
#
# - a set to train the ensemble methods which are later used to as a feature
#   engineering transformer;
# - a set to train the linear model;
# - a set to test the linear model.
#
# It is important to split the data in such way to avoid overfitting by leaking
# data.

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=80_000, random_state=10)

X_full_train, X_test, y_full_train, y_test = train_test_split(
    X, y, test_size=0.5, random_state=10
)
X_train_ensemble, X_train_linear, y_train_ensemble, y_train_linear = train_test_split(
    X_full_train, y_full_train, test_size=0.5, random_state=10
)

# %%
# For each of the ensemble methods, we will use 10 estimators and a maximum
# depth of 3 levels.

n_estimators = 10
max_depth = 3

# %%
# First, we will start by training the random forest and gradient boosting on
# the separated training set

from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier

random_forest = RandomForestClassifier(
    n_estimators=n_estimators, max_depth=max_depth, random_state=10
)
random_forest.fit(X_train_ensemble, y_train_ensemble)

gradient_boosting = GradientBoostingClassifier(
    n_estimators=n_estimators, max_depth=max_depth, random_state=10
)
_ = gradient_boosting.fit(X_train_ensemble, y_train_ensemble)

# %%
# Notice that :class:`~sklearn.ensemble.HistGradientBoostingClassifier` is much
# faster than :class:`~sklearn.ensemble.GradientBoostingClassifier` starting
# with intermediate datasets (`n_samples >= 10_000`), which is not the case of
# the present example.
#
# The :class:`~sklearn.ensemble.RandomTreesEmbedding` is an unsupervised method
# and thus does not required to be trained independently.

from sklearn.ensemble import RandomTreesEmbedding

random_tree_embedding = RandomTreesEmbedding(
    n_estimators=n_estimators, max_depth=max_depth, random_state=0
)

# %%
# Now, we will create three pipelines that will use the above embedding as
# a preprocessing stage.
#
# The random trees embedding can be directly pipelined with the logistic
# regression because it is a standard scikit-learn transformer.

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

rt_model = make_pipeline(random_tree_embedding, LogisticRegression(max_iter=1000))
rt_model.fit(X_train_linear, y_train_linear)

# %%
# Then, we can pipeline random forest or gradient boosting with a logistic
# regression. However, the feature transformation will happen by calling the
# method `apply`. The pipeline in scikit-learn expects a call to `transform`.
# Therefore, we wrapped the call to `apply` within a `FunctionTransformer`.

from sklearn.preprocessing import FunctionTransformer
from sklearn.preprocessing import OneHotEncoder

def rf_apply(X, model):
    return model.apply(X)

rf_leaves_yielder = FunctionTransformer(rf_apply, kw_args={"model": random_forest})

rf_model = make_pipeline(
    rf_leaves_yielder,
    OneHotEncoder(handle_unknown="ignore"),
    LogisticRegression(max_iter=1000),
)
rf_model.fit(X_train_linear, y_train_linear)

# %%
def gbdt_apply(X, model):
    return model.apply(X)[:, :, 0]

gbdt_leaves_yielder = FunctionTransformer(
    gbdt_apply, kw_args={"model": gradient_boosting}
)

gbdt_model = make_pipeline(
    gbdt_leaves_yielder,
    OneHotEncoder(handle_unknown="ignore"),
    LogisticRegression(max_iter=1000),
)
gbdt_model.fit(X_train_linear, y_train_linear)

# %%
# We can finally show the different ROC curves for all the models.

import matplotlib.pyplot as plt
from sklearn.metrics import RocCurveDisplay

fig, ax = plt.subplots()

models = [
    ("RT embedding -> LR", rt_model),
    ("RF", random_forest),
    ("RF embedding -> LR", rf_model),
    ("GBDT", gradient_boosting),
    ("GBDT embedding -> LR", gbdt_model),
]

model_displays = {}
for name, pipeline in models:
    model_displays[name] = RocCurveDisplay.from_estimator(
        pipeline, X_test, y_test, ax=ax, name=name
    )
_ = ax.set_title("ROC curve")

# %%
fig, ax = plt.subplots()
for name, pipeline in models:
    model_displays[name].plot(ax=ax)

ax.set_xlim(0, 0.2)
ax.set_ylim(0.8, 1)
_ = ax.set_title("ROC curve (zoomed in at top left)")


text:
module PackRat
  module CacheHelper
    module Cacher
      def cache(key='', options={}, &block)
        unless options[:overwrite_key] # if overwrite_key was set, we skip creating our own key
          calling_method = caller[0][/`([^']*)'/, 1] # Hack to get the method that called cache
          key << calling_method << '/'
          key << self.cache_key << '/'

          # Since this same method is used in both class and instance contexts, we need to check that here
          if self.is_a? Class
            key << self.file_digest
          else
            key << self.class.file_digest
          end
        end

        puts key if options[:debug] # Output the generated cache key to the console if debug is set
        filtered_options = options.except(:debug, :overwrite_key) # Remove PackRat related options so we can pass to Rails.cache

        # Make the actual Rails.cache call
        Rails.cache.fetch key, filtered_options do
          block.call
        end

      end
    end
  end
end