text:
// Copyright (c) 2019-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <compressor.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <script/interpreter.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <univalue.h>

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>

void initialize_script()
{
    // Fuzzers using pubkey must hold an ECCVerifyHandle.
    static const ECCVerifyHandle verify_handle;

    SelectParams(CBaseChainParams::REGTEST);
}

FUZZ_TARGET_INIT(script, initialize_script)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const std::optional<CScript> script_opt = ConsumeDeserializable<CScript>(fuzzed_data_provider);
    if (!script_opt) return;
    const CScript script{*script_opt};

    CompressedScript compressed;
    if (CompressScript(script, compressed)) {
        const unsigned int size = compressed[0];
        compressed.erase(compressed.begin());
        assert(size <= 5);
        CScript decompressed_script;
        const bool ok = DecompressScript(decompressed_script, size, compressed);
        assert(ok);
        assert(script == decompressed_script);
    }

    CTxDestination address;
    TxoutType type_ret;
    std::vector<CTxDestination> addresses;
    int required_ret;
    bool extract_destinations_ret = ExtractDestinations(script, type_ret, addresses, required_ret);
    bool extract_destination_ret = ExtractDestination(script, address);
    if (!extract_destinations_ret) {
        assert(!extract_destination_ret);
        if (type_ret == TxoutType::MULTISIG) {
            assert(addresses.empty() && required_ret == 0);
        } else {
            assert(type_ret == TxoutType::PUBKEY ||
                   type_ret == TxoutType::NONSTANDARD ||
                   type_ret == TxoutType::NULL_DATA);
        }
    } else {
        assert(required_ret >= 1 && required_ret <= 16);
        assert((unsigned long)required_ret == addresses.size());
        assert(type_ret == TxoutType::MULTISIG || required_ret == 1);
    }
    if (type_ret == TxoutType::NONSTANDARD || type_ret == TxoutType::NULL_DATA) {
        assert(!extract_destinations_ret);
    }
    if (!extract_destination_ret) {
        assert(type_ret == TxoutType::PUBKEY ||
               type_ret == TxoutType::NONSTANDARD ||
               type_ret == TxoutType::NULL_DATA ||
               type_ret == TxoutType::MULTISIG);
    } else {
        assert(address == addresses[0]);
    }
    if (type_ret == TxoutType::NONSTANDARD ||
        type_ret == TxoutType::NULL_DATA ||
        type_ret == TxoutType::MULTISIG) {
        assert(!extract_destination_ret);
    }

    TxoutType which_type;
    bool is_standard_ret = IsStandard(script, which_type);
    assert(type_ret == which_type);
    if (!is_standard_ret) {
        assert(which_type == TxoutType::NONSTANDARD ||
               which_type == TxoutType::NULL_DATA ||
               which_type == TxoutType::MULTISIG);
    }
    if (which_type == TxoutType::NONSTANDARD) {
        assert(!is_standard_ret);
    }
    if (which_type == TxoutType::NULL_DATA) {
        assert(script.IsUnspendable());
    }
    if (script.IsUnspendable()) {
        assert(which_type == TxoutType::NULL_DATA ||
               which_type == TxoutType::NONSTANDARD);
    }

    const FlatSigningProvider signing_provider;
    (void)InferDescriptor(script, signing_provider);
    (void)IsSegWitOutput(signing_provider, script);
    (void)IsSolvable(signing_provider, script);

    (void)RecursiveDynamicUsage(script);

    std::vector<std::vector<unsigned char>> solutions;
    (void)Solver(script, solutions);

    (void)script.HasValidOps();
    (void)script.IsPayToScriptHash();
    (void)script.IsPayToWitnessScriptHash();
    (void)script.IsPushOnly();
    (void)script.GetSigOpCount(/* fAccurate= */ false);

    (void)FormatScript(script);
    (void)ScriptToAsmStr(script, false);
    (void)ScriptToAsmStr(script, true);

    UniValue o1(UniValue::VOBJ);
    ScriptPubKeyToUniv(script, o1, true, true);
    ScriptPubKeyToUniv(script, o1, true, false);
    UniValue o2(UniValue::VOBJ);
    ScriptPubKeyToUniv(script, o2, false, true);
    ScriptPubKeyToUniv(script, o2, false, false);
    UniValue o3(UniValue::VOBJ);
    ScriptToUniv(script, o3, true);
    UniValue o4(UniValue::VOBJ);
    ScriptToUniv(script, o4, false);

    {
        const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
        CompressedScript compressed_script;
        compressed_script.assign(bytes.begin(), bytes.end());
        // DecompressScript(..., ..., bytes) is not guaranteed to be defined if the bytes vector is too short
        if (compressed_script.size() >= 32) {
            CScript decompressed_script;
            DecompressScript(decompressed_script, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), compressed_script);
        }
    }

    const std::optional<CScript> other_script = ConsumeDeserializable<CScript>(fuzzed_data_provider);
    if (other_script) {
        {
            CScript script_mut{script};
            (void)FindAndDelete(script_mut, *other_script);
        }
        const std::vector<std::string> random_string_vector = ConsumeRandomLengthStringVector(fuzzed_data_provider);
        const uint32_t u32{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
        const uint32_t flags{u32 | SCRIPT_VERIFY_P2SH};
        {
            CScriptWitness wit;
            for (const auto& s : random_string_vector) {
                wit.stack.emplace_back(s.begin(), s.end());
            }
            (void)CountWitnessSigOps(script, *other_script, &wit, flags);
            wit.SetNull();
        }
    }

    (void)GetOpName(ConsumeOpcodeType(fuzzed_data_provider));
    (void)ScriptErrorString(static_cast<ScriptError>(fuzzed_data_provider.ConsumeIntegralInRange<int>(0, SCRIPT_ERR_ERROR_COUNT)));

    {
        const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
        CScript append_script{bytes.begin(), bytes.end()};
        append_script << fuzzed_data_provider.ConsumeIntegral<int64_t>();
        append_script << ConsumeOpcodeType(fuzzed_data_provider);
        append_script << CScriptNum{fuzzed_data_provider.ConsumeIntegral<int64_t>()};
        append_script << ConsumeRandomLengthByteVector(fuzzed_data_provider);
    }

    {
        WitnessUnknown witness_unknown_1{};
        witness_unknown_1.version = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
        const std::vector<uint8_t> witness_unknown_program_1 = fuzzed_data_provider.ConsumeBytes<uint8_t>(40);
        witness_unknown_1.length = witness_unknown_program_1.size();
        std::copy(witness_unknown_program_1.begin(), witness_unknown_program_1.end(), witness_unknown_1.program);

        WitnessUnknown witness_unknown_2{};
        witness_unknown_2.version = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
        const std::vector<uint8_t> witness_unknown_program_2 = fuzzed_data_provider.ConsumeBytes<uint8_t>(40);
        witness_unknown_2.length = witness_unknown_program_2.size();
        std::copy(witness_unknown_program_2.begin(), witness_unknown_program_2.end(), witness_unknown_2.program);

        (void)(witness_unknown_1 == witness_unknown_2);
        (void)(witness_unknown_1 < witness_unknown_2);
    }

    {
        const CTxDestination tx_destination_1 = ConsumeTxDestination(fuzzed_data_provider);
        const CTxDestination tx_destination_2 = ConsumeTxDestination(fuzzed_data_provider);
        (void)(tx_destination_1 == tx_destination_2);
        (void)(tx_destination_1 < tx_destination_2);
    }
}


text:
import 'whatwg-fetch';
import 'es6-promise';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    throw new Error(response.statusText);
  }
}

function parseJSON(response) {
  return response.json();
}

export function loadLinks(){
  return (dispatch, getState) => {
    dispatch(toggleLoading(true));
    fetch('assets/json/db.json')
      .then(checkStatus)
      .then(parseJSON)
      .then( data => {
        dispatch(linksLoaded(data));
        dispatch(toggleLoading(false));
      })
      .catch( error => {
        dispatch(tempErrorMessage(`Bad response from server: ${error.message}`));
        dispatch(toggleLoading(false));
      });

  };
}

function linksLoaded(tasks){
  return {type:'LINKS_LOADED', data:tasks};
}

export function loadCubieStatus(){
  return (dispatch, getState) => {
    dispatch(toggleLoadingCubie(true));
    fetch('http://cubie.stanzani.com.br:8800/ping/')
      .then(checkStatus)
      .then(parseJSON)
      .then( pong => {
        dispatch(toggleLoadingCubie(false));
        dispatch(cubieStatusLoaded(pong));
      })
      .catch( error => {
        dispatch(cubieStatusLoaded({"pong":"Offline"}));
        dispatch(toggleLoadingCubie(false));
      });
  };
}

function cubieStatusLoaded(pong){
  return {type:'CUBIE_STATUS', data:pong};
}

function toggleLoading(isLoading){
  return {type:'TOGGLE_LOADING', data:isLoading};
}
function toggleLoadingCubie(isLoadingCubie){
  return {type:'TOGGLE_LOADING_CUBIE', data:isLoadingCubie};
}

function showError(message){
  return {type:'SHOW_ERROR', data:message};
}

export function hideError(){
  return {type:'HIDE_ERROR'};
}

function tempErrorMessage(message){
  return (dispatch, getState) => {
    dispatch(showError(message));
    setTimeout( ( t => dispatch(hideError()) ), 3000);
  };
}

redpajama_set_name: RedPajamaGithub


text:
import os
import dj_database_url

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

SECRET_KEY = os.environ.get(
    'SECRET_KEY',
    'i+acxn5(akgsn!sr4^qgf(^m&*@+g1@u^t@=8s@axc41ml*f=s'
)

DEBUG = bool(os.environ.get('DEBUG', True))
# Because test settings will trigger KEEN.io hits
KEEN_DEBUG = bool(os.environ.get('DEBUG', True))

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = []

CUSTOM_APPS = (
    'resources',
    'rest_framework',
    'markdown_deux',
    'corsheaders',
    'clear_cache',
)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.humanize',
    'django.contrib.staticfiles',
) + CUSTOM_APPS

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'swapi.urls'

WSGI_APPLICATION = 'swapi.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_ETAGS = True
USE_I18N = True
USE_L10N = True
USE_TZ = True

if not DEBUG:
    DATABASES['default'] =  dj_database_url.config()

    DATABASES['default']['ENGINE'] = 'django_postgrespool'

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

ALLOWED_HOSTS = ['*']

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
        'TIMEOUT': 60
    }
}

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

# Markdown

MARKDOWN_DEUX_STYLES = {
    "default": {
        "extras": {
            "code-friendly": None,
        },
        "safe_mode": False,
    },
}

# REST Framework

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'resources.renderers.WookieeRenderer'
    ),
    'PAGINATE_BY': 10,
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '10000/day',
    },
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.SearchFilter',
    )
}

# Keen.io

KEEN_PROJECT_ID = os.environ.get('KEEN_PROJECT_ID', '')
KEEN_WRITE_KEY = os.environ.get('KEEN_WRITE_KEY', '')
KEEN_READ_KEY = os.environ.get('KEEN_READ_KEY', '')
KEEN_CELERY = False

# Stripe

STRIPE_TEST_SECRET_KEY = os.environ.get('STRIPE_TEST_SECRET_KEY', '')
STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY', '')
STRIPE_PUBLISHABLE_KEY = os.environ.get('STRIPE_PUBLISHABLE_KEY', '')
STRIPE_TEST_PUBLISHABLE_KEY = os.environ.get('STRIPE_TEST_PUBLISHABLE_KEY', '')

if DEBUG:
    STRIPE_KEYS = {
        "secret" :STRIPE_TEST_SECRET_KEY,
        "publishable": STRIPE_TEST_PUBLISHABLE_KEY
    }
else:
    STRIPE_KEYS = {
        "secret" :STRIPE_SECRET_KEY,
        "publishable": STRIPE_PUBLISHABLE_KEY
    }

# Cors

CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/.*$'
CORS_ALLOW_METHODS = (
        'GET',
    )

# Memcache

from memcacheify import memcacheify

CACHES = memcacheify()

APPEND_SLASH = True


text:
/**
 * @file
 * @brief
 *
 * @author  Anton Kozlov
 * @date    30.10.2013
 */

#ifndef DRIVERS_USB_HID_H_
#define DRIVERS_USB_HID_H_

#define USB_HID_MAX_DEVS         2

#define USB_CLASS_HID 		 3

#define USB_CLASS_HID_SUB	 0
#define USB_CLASS_HID_SUB_BOOT	 1

#define USB_CLASS_HID_PROT_NONE  0
#define USB_CLASS_HID_PROT_KBD   1
#define USB_CLASS_HID_PROT_MOUSE 2

#include <drivers/usb/usb.h>

struct input_dev;

struct usb_desc_hid {
	uint8_t b_length;
	uint8_t b_desc_type;
	uint16_t bcd_hid;
	uint8_t b_country_code;
	uint8_t b_num_descriptors;
	uint8_t b_descriptor_type;
	uint16_t w_descriptor_len;
} __attribute__((packed));

struct usb_class_hid {
	struct input_dev *indev;
};

static inline struct usb_class_hid *usb2hiddata(struct usb_interface *dev) {
	return dev->driver_data;
}

extern int usb_hid_found(struct usb_interface *dev);

#endif /* DRIVERS_USB_HID_H_ */


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Nuova Notarisia 18: 38.

#### Original name
null

### Remarks
null


text: CREATE TRIGGER dt_ins BEFORE INSERT ON dt FOR EACH ROW UPDATE dt SET col2='ins' WHERE id = NEW.id


text:
using namespace std;

namespace puppet { namespace runtime { namespace types {

    regexp::regexp(string pattern) :
        _pattern(rvalue_cast(pattern))
    {
    }

    string const& regexp::pattern() const
    {
        return _pattern;
    }

    const char* regexp::name()
    {
        return "Regexp";
    }

    ostream& operator<<(ostream& os, regexp const& type)
    {
        os << regexp::name();
        if (type.pattern().empty()) {
            return os;
        }
        os << "[/" << type.pattern() << "/]";
        return os;
    }

    bool operator==(regexp const& left, regexp const& right)
    {
        return left.pattern() == right.pattern();
    }

}}}  // namespace puppet::runtime::types


text:
package api;

import com.google.common.base.Preconditions;
import datamanagement.XMLReader;
import datamanagement.XMLWriter;

import java.io.File;
import java.io.Serializable;

/**
 * Interface for serializable objects.
 * Indicates that an object may be read and written from a file, and allows a few methods to do so.
 *
 * @author Rhondu Smithwick, Tom Wu
 */
public interface ISerializable extends Serializable {

    /**
     * Serializes this object to a File
     *
     * @return File representing the serialized form of this object
     */
    default File serialize (String fileName) {
        return new XMLWriter<>().writeToFile(fileName, this);
    }

    /**
     * Serializes this object to a String
     *
     * @return String representing the serialized form of this object
     */
    default String serializeToString () {
        return new XMLWriter<>().writeToString(this);
    }

    /**
     * Clones this object to the provided class. Must be the same class.
     *
     * @param objectClass the class to clone to (must be same class)
     * @param <T>         the type
     * @return a cloned object
     * @throws IllegalArgumentException if objectClass snot same class
     */
    default <T extends ISerializable> T clone (Class<T> objectClass) {
        boolean sameClass = getClass().isAssignableFrom(objectClass);
        Preconditions.checkArgument(sameClass, "Not the same class so cannot clone.");
        String clonedString = serializeToString();
        Object obj = new XMLReader<T>().readSingleFromString(clonedString);
        return objectClass.cast(obj);
    }

}


text:
package controller;

/**
 * DWZ的callback json对象
 *
 * @author weiwei
 *
 */
public class DWZCallback {

	private String statusCode = "200";
	private String errorCode = "login_required";//错误代码
	private String message = "";
	private String navTabId = "";
	private String forwardUrl = "";
	private String callbackType = "reloadTab";//closeCurrent
	private String title = "";

	public static DWZCallback me(){
		return new DWZCallback();
	}

	public DWZCallback success(){
		return status("200").msg("操作成功");
	}

	public DWZCallback fail(){
		return status("300").msg("操作失败");
	}

	public DWZCallback errorCode(String code){
		this.errorCode = code;
		return this;
	}

	public DWZCallback login_required(String msg){
		return status("301").errorCode("login_required").msg(msg);
	}

	public DWZCallback status(String code){
		this.statusCode = code;
		return this;
	}

	public DWZCallback msg(String message){
		this.message = message;
		return this;
	}

	public DWZCallback tab(String tabID){
		this.navTabId = tabID;
		return this;
	}

	public DWZCallback reload(String url) {
		return type("reloadTab").url(url).tab(url);
	}

	public DWZCallback close() {
		return type("closeCurrent");
	}

	public DWZCallback url(String forwardUrl) {
		this.forwardUrl = forwardUrl;
		return this;
	}

	public DWZCallback type(String callbackType) {
		this.callbackType = callbackType;
		return this;
	}

	public DWZCallback title(String title) {
		this.title = title;
		return this;
	}

	public DWZCallback() {
	}

	public DWZCallback(String error) {
		init("300", error, "", "", "reloadTab", "");
	}

	public DWZCallback(String statusCode, String message, String navTabId,
			String forwardUrl, String callbackType, String title) {
		this.init(statusCode, message, navTabId, forwardUrl, callbackType,
				title);
	}

	public void init(String statusCode, String message, String navTabId,
			String forwardUrl, String callbackType, String title) {
		if (statusCode == null) {
			statusCode = "200";
		} else {
			this.statusCode = statusCode;
		}
		if (message == null) {
			if ("200".equals(statusCode)) {
				message = "操作成功";
			} else if ("300".equals(statusCode)) {
				message = "操作失败";
			}
		} else {
			this.message = message;
		}
		this.navTabId = navTabId;
		this.forwardUrl = forwardUrl;
		this.title = title;

		this.callbackType = callbackType;
	}

	public String getStatusCode() {
		return statusCode;
	}

	public void setStatusCode(String statusCode) {
		this.statusCode = statusCode;
	}

	public String getMessage() {
		return message;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

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

	public String getForwardUrl() {
		return forwardUrl;
	}

	public void setForwardUrl(String forwardUrl) {
		this.forwardUrl = forwardUrl;
	}

	public String getCallbackType() {
		return callbackType;
	}

	public void setCallbackType(String callbackType) {
		this.callbackType = callbackType;
	}

	public String getNavTabId() {
		return navTabId;
	}

	public void setNavTabId(String navTabId) {
		this.navTabId = navTabId;
	}

	public String getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(String errorCode) {
		this.errorCode = errorCode;
	}

	@Override
	public String toString() {
		return "{\"statusCode\":\""+statusCode + "\", \"errorCode\":\""
				+ errorCode + "\", \"message\":\"" + message + "\", \"navTabId:\"" + navTabId
				+ "\", \"forwardUrl\":\"" + forwardUrl + "\", \"callbackType\":\""
				+ callbackType + "\", \"title\":\"" + title + "\"}";
	}

}


text:
package com.llmaps.dm.core.storage.entities;

/**
 *
 * @author Vojtech Krizek
 */
public class QuotaEntity {

	public static final long UNLIMITED_QUOTA = -1;
	public static final long READ_ONLY_QUOTA = 0;

	private String name;
	private long quota;

	public QuotaEntity() {
	}

	public QuotaEntity(String name, long quota) {
		this.name = name;
		this.quota = quota;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getQuota() {
		return quota;
	}

	public void setQuota(long quota) {
		this.quota = quota;
	}

}


text:
var MetaYaml = require('./lib/MetaYaml');
module.exports = MetaYaml;


text:
import removeClasses from "../../src/fn/remove-classes";

describe("fn/remove-classes", () => {
  afterEach(clearFixtures);

  it("adds classes from given list which added to element early", () => {
    useFixture(`<div class="root foo"></div>`);

    const subject = document.querySelector(".root");

    expect(subject.classList.contains("foo")).toBe(true);
    expect(subject.classList.contains("bar")).toBe(false);

    removeClasses(subject, "foo", "bar");

    expect(subject.classList.contains("foo")).toBe(false);
    expect(subject.classList.contains("bar")).toBe(false);
  });

  it("returns `true` if all given classes has been removed from element", () => {
    useFixture(`<div class="root foo bar"></div>`);

    const subject = document.querySelector(".root");

    expect(subject.classList.contains("foo")).toBe(true);
    expect(subject.classList.contains("bar")).toBe(true);

    expect(removeClasses(subject, "foo", "bar")).toBe(true);

    expect(subject.classList.contains("foo")).toBe(false);
    expect(subject.classList.contains("bar")).toBe(false);
  });

  it("returns `true` if any given class has been removed from element", () => {
    useFixture(`<div class="root foo"></div>`);

    const subject = document.querySelector(".root");

    expect(subject.classList.contains("foo")).toBe(true);
    expect(subject.classList.contains("bar")).toBe(false);

    expect(removeClasses(subject, "foo", "bar")).toBe(true);

    expect(subject.classList.contains("foo")).toBe(false);
    expect(subject.classList.contains("bar")).toBe(false);
  });

  it("returns `false` if all given class hasn't been removed from element", () => {
    useFixture(`<div class="root"></div>`);

    const subject = document.querySelector(".root");

    expect(subject.classList.contains("foo")).toBe(false);
    expect(subject.classList.contains("bar")).toBe(false);

    expect(removeClasses(subject, "foo", "bar")).toBe(false);

    expect(subject.classList.contains("foo")).toBe(false);
    expect(subject.classList.contains("bar")).toBe(false);
  });
});


text:
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace Plainion.Composition
{
    /// <summary>
    /// Simplify usage of MEF or plain vanilla usages of it.
    /// </summary>
    public class Composer : IComposer, IDisposable
    {
        private AggregateCatalog myCatalog;
        private CompositionBatch myBatch;
        private CompositionContainer myContainer;

        public Composer()
        {
            myCatalog = new AggregateCatalog();
            myBatch = new CompositionBatch();
            myContainer = new CompositionContainer( myCatalog, CompositionOptions.DisableSilentRejection );
        }

        public void Compose()
        {
            myContainer.Compose( myBatch );
        }

        public void Add( ComposablePartCatalog catalog )
        {
            myCatalog.Catalogs.Add( catalog );
        }

        public void Register( params Type[] types )
        {
            myCatalog.Catalogs.Add( new TypeCatalog( types ) );
        }

        public T Resolve<T>()
        {
            return myContainer.GetExportedValue<T>();
        }

        public T Resolve<T>( string contractName )
        {
            return myContainer.GetExportedValue<T>( contractName );
        }

        public void RegisterInstance<T>( T instance )
        {
            myBatch.AddExportedValue<T>( instance );
        }

        public void RegisterInstance<T>( string contractName, T instance )
        {
            myBatch.AddExportedValue<T>( contractName, instance );
        }

        public void Dispose()
        {
            if ( myContainer != null )
            {
                myContainer.Dispose();
                myContainer = null;
            }
        }
    }
}


text:
import { DataModelIDbTaskConfiguration } from '../DataModel/DataModelIDbTaskConfiguration';
import { IEasyLogger } from '../Logger/EasyLogger';
import { ITaskConfiguration } from '../Tasking/ITaskConfiguration';
import { ITaskConfigurations } from '../Tasking/ITaskConfigurations';
import { FoxfmIndexedDb } from './FoxfmIndexedDb';
import { TaskConfigurationIDb } from './TaskConfigurationIDb';
import { TaskNamesIDb } from './TaskNamesIDb';
import { TaskStatusesIDb } from './TaskStatusesIDb';

export class TaskConfigurationsIDb implements ITaskConfigurations {
  constructor(
    private dataBase: FoxfmIndexedDb,
    private logger: IEasyLogger,
  ) { }

  public all(): Promise<ITaskConfiguration[]> {
    let vals: ITaskConfiguration[] = [];
    return this.dataBase
      .taskConfigurations
      .toCollection()
      .eachPrimaryKey((pk: Number) => vals.push(new TaskConfigurationIDb(this.dataBase, pk, this.logger)))
      .then(() => vals);
  }

  public byTaskName(taskName: String): Promise<ITaskConfiguration[]> {
    return this.dataBase
      .transaction(
        "rw",
        this.dataBase.taskConfigurations,
        this.dataBase.taskNames,
        async () => {
          let taskNameInDb = await new TaskNamesIDb(this.dataBase, this.logger).getOrAdd(taskName);
          return this.dataBase
            .taskConfigurations
            .filter(tc => tc.taskNameId === taskNameInDb.id())
            .toArray(tc => tc.map(tc => new TaskConfigurationIDb(this.dataBase, tc.id!, this.logger)));
        });
  }

  public async add(
    taskName: String,
    activated: Boolean,
    intervalSeconds: Number,
    lastExecutionsToKeep: Number,
  ): Promise<ITaskConfiguration> {
    try {
      this.logger.debug(`will add new task configuration to IDb: name='${taskName}', activated='${activated}', interval[sec]='${intervalSeconds}'`);
      return this.dataBase
        .transaction(
          "rw",
          this.dataBase.taskConfigurations,
          this.dataBase.taskStatuses,
          this.dataBase.taskNames,
          async () => {
            let taskNameInDb = await new TaskNamesIDb(this.dataBase, this.logger).getOrAdd(taskName);
            let id = await this.dataBase
              .taskConfigurations
              .add(new DataModelIDbTaskConfiguration(
                activated,
                taskNameInDb.id(),
                intervalSeconds,
                lastExecutionsToKeep,
              ));
            this.logger.debug(`added to IDb: new task configuration: name='${taskName}', activated='${activated}', interval[sec]='${intervalSeconds}'`);
            return new TaskConfigurationIDb(
              this.dataBase,
              id,
              this.logger,
            );
          });
    } catch (e) {
      throw new Error(`Could not add new task configuration to IDb name='${taskName}', activated='${activated}', interval[sec]='${intervalSeconds}': ${e}`);
    }
  }

  public async getOrAdd(
    taskName: String,
    activated: Boolean,
    intervalSeconds: Number,
    lastExecutionsToKeep,
  ): Promise<ITaskConfiguration> {
    return this.dataBase
      .transaction(
        "rw",
        this.dataBase.taskConfigurations,
        this.dataBase.taskStatuses,
        this.dataBase.taskNames,
        async () => {
          let taskConfigInDb: ITaskConfiguration;
          let taskConfigsInDb = await this.byTaskName(taskName);
          if (await taskConfigsInDb.length === 1) {
            taskConfigInDb = await taskConfigsInDb[0];
            this.logger.debug(`already in IDb: task configuration for task: '${await (await taskConfigInDb.taskName()).name()}'`);
          } else {
            taskConfigInDb = await this.add(
              taskName,
              activated,
              intervalSeconds,
              lastExecutionsToKeep,
            );
          }
          return taskConfigInDb;
        });
  }
}


text:
{% extends 'layouts/master.html' %}

{% set page = 'issues' %}

{% block title %}Gitamin{% endblock %}

{% block breadcrumb %}
    {% include 'partials/breadcrumb.html' with {breadcrumbs: [{dir: 'Issues', path:''}]} %}
{% endblock %}

{% block content %}

                       Issues

             Recent

             Unanswered

            {% if issues.total > 0 %}

{% for issue in issues %}

             {{ issue.comment_count }}

                {{ issue.title }}

				回复

                  {{ issue.author.username }}

                 •
                {{ issue.updated_at }}

    {% endfor %}

    {% else %}

There aren't issues.

    {% endif %}

                {{ issues.appends(input.all()).render() | raw }}

Gitamin

        new issue

{% endblock %}


text:
package com.aldebaran.qi;

/**
 * Type that conveys no information.
 *
 * It can be used in place of `Void`, with the benefit of being instantiable.
 *
 * Theoretically, it corresponds to the terminal object in the category of
 * sets and functions, which is the set with a single element.
 *
 * See <https://en.wikipedia.org/wiki/Unit_type>
 */
final class Unit {
    // Unique value of `Unit`.
    private static final Unit UNIT = new Unit();

    private Unit(){}

    public static Unit value() {
        return UNIT;
    }
}


text:
package org.apache.jackrabbit.oak.plugins.index.elastic;

import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.index.search.util.IndexDefinitionBuilder;
import org.apache.jackrabbit.oak.plugins.nodetype.write.NodeTypeRegistry;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

import static org.apache.jackrabbit.JcrConstants.NT_UNSTRUCTURED;

public class ElasticDynamicBoostQueryTest extends ElasticAbstractQueryTest {

    public static final String ASSET_NODE_TYPE =
            "[dam:Asset]\n" +
                    " - * (UNDEFINED) multiple\n" +
                    " - * (UNDEFINED)\n" +
                    " + * (nt:base) = oak:TestNode VERSION";

    @Test
    public void dynamicBoost() throws CommitFailedException {
        configureIndex();

        Tree test = createNodeWithType(root.getTree("/"), "test", NT_UNSTRUCTURED);
        Tree item1Metadata = createNodeWithMetadata(test, "item1", "flower with a lot of red and a bit of blue");
        Tree item1Color1 = createNodeWithType(item1Metadata,"color1", NT_UNSTRUCTURED);
        item1Color1.setProperty("name", "red");
        item1Color1.setProperty("confidence", 9.0);
        Tree item1Color2 = createNodeWithType(item1Metadata,"color2", NT_UNSTRUCTURED);
        item1Color2.setProperty("name", "blue");
        item1Color2.setProperty("confidence", 1.0);

        Tree item2Metadata = createNodeWithMetadata(test, "item2", "flower with a lot of blue and a bit of red");
        Tree item2Color1 = createNodeWithType(item2Metadata,"color1", NT_UNSTRUCTURED);
        item2Color1.setProperty("name", "blue");
        item2Color1.setProperty("confidence", 9.0);
        Tree item2Color2 = createNodeWithType(item2Metadata,"color2", NT_UNSTRUCTURED);
        item2Color2.setProperty("name", "red");
        item2Color2.setProperty("confidence", 1.0);
        root.commit();

        assertEventually(() -> {
            assertQuery("//element(*, dam:Asset)[jcr:contains(@title, 'flower')]",
                    XPATH, Arrays.asList("/test/item1", "/test/item2"));
            assertOrderedQuery("select [jcr:path] from [dam:Asset] where contains(title, 'red flower')",
                    Arrays.asList("/test/item1", "/test/item2"));
            assertOrderedQuery("select [jcr:path] from [dam:Asset] where contains(title, 'blue flower')",
                    Arrays.asList("/test/item2", "/test/item1"));
        });
    }

    @Test
    public void dynamicBoostAnalyzed() throws CommitFailedException {
        configureIndex();

        Tree test = createNodeWithType(root.getTree("/"), "test", NT_UNSTRUCTURED);
        Tree item1Metadata = createNodeWithMetadata(test, "item1", "flower with a lot of red and a bit of blue");
        item1Metadata.setProperty("foo", "bar");
        Tree item1Color1 = createNodeWithType(item1Metadata,"color1", NT_UNSTRUCTURED);
        item1Color1.setProperty("name", "red");
        item1Color1.setProperty("confidence", 9.0);
        Tree item1Color2 = createNodeWithType(item1Metadata,"color2", NT_UNSTRUCTURED);
        item1Color2.setProperty("name", "blue");
        item1Color2.setProperty("confidence", 1.0);

        Tree item2Metadata = createNodeWithMetadata(test, "item2", "flower with a lot of blue and a bit of red");
        Tree item2Color1 = createNodeWithType(item2Metadata,"color1", NT_UNSTRUCTURED);
        item2Color1.setProperty("name", "blue");
        item2Color1.setProperty("confidence", 9.0);
        Tree item2Color2 = createNodeWithType(item2Metadata,"color2", NT_UNSTRUCTURED);
        item2Color2.setProperty("name", "red");
        item2Color2.setProperty("confidence", 1.0);
        root.commit();

        assertEventually(() -> {
            assertQuery("//element(*, dam:Asset)[jcr:contains(@title, 'flower')]",
                    XPATH, Arrays.asList("/test/item1", "/test/item2"));
            assertOrderedQuery("select [jcr:path] from [dam:Asset] where contains(title, 'red-flower')",
                    Arrays.asList("/test/item1", "/test/item2"));
            assertOrderedQuery("select [jcr:path] from [dam:Asset] where contains(title, 'blue-flower')",
                    Arrays.asList("/test/item2", "/test/item1"));
        });
    }

    private void configureIndex() throws CommitFailedException {
        NodeTypeRegistry.register(root, toInputStream(ASSET_NODE_TYPE), "test nodeType");
        IndexDefinitionBuilder builder = createIndex(true, "dam:Asset", "title", "dynamicBoost");
        IndexDefinitionBuilder.PropertyRule title = builder.indexRule("dam:Asset")
                .property("title")
                .analyzed();
        title.getBuilderTree().setProperty(JcrConstants.JCR_PRIMARYTYPE, NT_UNSTRUCTURED, Type.NAME);
        IndexDefinitionBuilder.PropertyRule db = builder.indexRule("dam:Asset").property("dynamicBoost");
        Tree dbTree = db.getBuilderTree();
        dbTree.setProperty(JcrConstants.JCR_PRIMARYTYPE, NT_UNSTRUCTURED, Type.NAME);
        dbTree.setProperty("name", "jcr:content/metadata/.*");
        dbTree.setProperty("isRegexp", true);
        dbTree.setProperty("dynamicBoost", true);
        setIndex("damAsset_" + UUID.randomUUID(), builder);
        root.commit();
    }

    private Tree createNodeWithMetadata(Tree parent, String nodeName, String title) {
        Tree item = createNodeWithType(parent, nodeName, "dam:Asset");
        item.setProperty("title", title);

        return createNodeWithType(
                createNodeWithType(item, JcrConstants.JCR_CONTENT, NT_UNSTRUCTURED),
                "metadata", NT_UNSTRUCTURED);
    }

    private static Tree createNodeWithType(Tree t, String nodeName, String typeName){
        t = t.addChild(nodeName);
        t.setProperty(JcrConstants.JCR_PRIMARYTYPE, typeName, Type.NAME);
        return t;
    }

    private static InputStream toInputStream(String x) {
        return new ByteArrayInputStream(x.getBytes());
    }
}


text:
- [x] Create a page with a list of all users
  - [x] Add search
  - [x] Add pagination

- [x] Create user detail page
  - [x] Add block with albums/photos

- [X] Create albums list
  - [x] Add search
  - [x] Add pagination

- [x] Create album detail page

- [x] Create photos list
  - [x] Add search
  - [x] Add pagination

- [x] Create search page

- [x] Add unit tests
- [x] Add e2e tests

- [x] Lighthouse optimization

- [ ] SEO optimization

- [ ] Add share support

- [ ] Add sentry

- [ ] Add documentation

- [ ] Add server and full REST support

- [ ] Add CI support


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Öst. Z. Pilzk. 7: 244 (1998)

#### Original name
Entoloma pseudosericeoides Noordel. & Hauskn.

### Remarks
null


text:
package org.arquillian.cube.docker.impl.client.config;

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

public class ExposedPort {
    private int exposed;
    private String type = "tcp";

    public ExposedPort(int exposed, String type) {
        this.exposed = exposed;
        if (type != null) {
            this.type = type;
        }
    }

    public static ExposedPort valueOf(String exp) {
        int exposed;
        String type = null;
        String[] parts = exp.split("/");
        exposed = Integer.parseInt(parts[0].trim());
        if (parts.length > 1) {
            type = parts[1].trim();
        }
        return new ExposedPort(exposed, type);
    }

    public static ExposedPort valueOf(int port) {
        return new ExposedPort(port, null);
    }

    public static Collection<ExposedPort> valuesOf(Collection<String> ports) {
        if (ports == null) {
            return null;
        }
        List<ExposedPort> result = new ArrayList<ExposedPort>();
        for (String port : ports) {
            result.add(valueOf(port));
        }
        return result;
    }

    public int getExposed() {
        return exposed;
    }

    public void setExposed(int exposed) {
        this.exposed = exposed;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return exposed + "/" + type;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + exposed;
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        ExposedPort other = (ExposedPort) obj;
        if (exposed != other.exposed) {
            return false;
        }
        if (type == null) {
            if (other.type != null) {
                return false;
            }
        } else if (!type.equals(other.type)) {
            return false;
        }
        return true;
    }
}


text:
#pragma once

#ifdef SAIGA_USE_EIGEN
#include <Eigen/Geometry>
#else
#include "tiny-eigen/matrix.h"
#endif

namespace Saiga
{
// All vector types are formed from this typedef.
// -> A vector is a Nx1 Eigen::Matrix.
template <typename Scalar, int Size>
using Vector = Eigen::Matrix<Scalar, Size, 1, Eigen::ColMajor>;

// All 2D fixed size matrices are formed from this typedef.
// They are all stored in column major order.
template <typename Scalar, int Rows, int Cols>
using Matrix = Eigen::Matrix<Scalar, Rows, Cols, Eigen::ColMajor>;

// ===== Double Precision (Capital Letter) ======
using Vec2 = Vector<double, 2>;
using Vec3 = Vector<double, 3>;
using Vec4 = Vector<double, 4>;
using Vec5 = Vector<double, 5>;
using Vec6 = Vector<double, 6>;
using Vec7 = Vector<double, 7>;
using Vec8 = Vector<double, 8>;
using Vec9 = Vector<double, 9>;

using Mat2 = Matrix<double, 2, 2>;
using Mat3 = Matrix<double, 3, 3>;
using Mat4 = Matrix<double, 4, 4>;

// ===== Single Precision  ======

using vec2 = Vector<float, 2>;
using vec3 = Vector<float, 3>;
using vec4 = Vector<float, 4>;
using vec5 = Vector<float, 5>;
using vec6 = Vector<float, 6>;
using vec7 = Vector<float, 7>;
using vec8 = Vector<float, 8>;
using vec9 = Vector<float, 9>;

using mat2 = Matrix<float, 2, 2>;
using mat3 = Matrix<float, 3, 3>;
using mat4 = Matrix<float, 4, 4>;

// ===== Non-floating point types. Used for example in image processing  ======

using uvec2 = Vector<unsigned int, 2>;
using uvec3 = Vector<unsigned int, 3>;
using uvec4 = Vector<unsigned int, 4>;

using ivec2 = Vector<int, 2>;
using ivec3 = Vector<int, 3>;
using ivec4 = Vector<int, 4>;

using cvec2 = Vector<char, 2>;
using cvec3 = Vector<char, 3>;
using cvec4 = Vector<char, 4>;

using ucvec2 = Vector<unsigned char, 2>;
using ucvec3 = Vector<unsigned char, 3>;
using ucvec4 = Vector<unsigned char, 4>;

using svec2 = Vector<short, 2>;
using svec3 = Vector<short, 3>;
using svec4 = Vector<short, 4>;

using usvec2 = Vector<unsigned short, 2>;
using usvec3 = Vector<unsigned short, 3>;
using usvec4 = Vector<unsigned short, 4>;

}  // namespace Saiga


text:
#pragma once
#include <aws/iotfleetwise/IoTFleetWise_EXPORTS.h>
#include <aws/iotfleetwise/IoTFleetWiseRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/iotfleetwise/model/VehicleAssociationBehavior.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/iotfleetwise/model/Tag.h>
#include <utility>

namespace Aws
{
namespace IoTFleetWise
{
namespace Model
{

  /**
   */
  class AWS_IOTFLEETWISE_API CreateVehicleRequest : public IoTFleetWiseRequest
  {
  public:
    CreateVehicleRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateVehicle"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline const Aws::String& GetVehicleName() const{ return m_vehicleName; }

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline bool VehicleNameHasBeenSet() const { return m_vehicleNameHasBeenSet; }

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline void SetVehicleName(const Aws::String& value) { m_vehicleNameHasBeenSet = true; m_vehicleName = value; }

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline void SetVehicleName(Aws::String&& value) { m_vehicleNameHasBeenSet = true; m_vehicleName = std::move(value); }

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline void SetVehicleName(const char* value) { m_vehicleNameHasBeenSet = true; m_vehicleName.assign(value); }

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline CreateVehicleRequest& WithVehicleName(const Aws::String& value) { SetVehicleName(value); return *this;}

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline CreateVehicleRequest& WithVehicleName(Aws::String&& value) { SetVehicleName(std::move(value)); return *this;}

    /**
     *
 The unique ID of the vehicle to create.

     */
    inline CreateVehicleRequest& WithVehicleName(const char* value) { SetVehicleName(value); return *this;}

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline const Aws::String& GetModelManifestArn() const{ return m_modelManifestArn; }

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline bool ModelManifestArnHasBeenSet() const { return m_modelManifestArnHasBeenSet; }

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline void SetModelManifestArn(const Aws::String& value) { m_modelManifestArnHasBeenSet = true; m_modelManifestArn = value; }

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline void SetModelManifestArn(Aws::String&& value) { m_modelManifestArnHasBeenSet = true; m_modelManifestArn = std::move(value); }

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline void SetModelManifestArn(const char* value) { m_modelManifestArnHasBeenSet = true; m_modelManifestArn.assign(value); }

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline CreateVehicleRequest& WithModelManifestArn(const Aws::String& value) { SetModelManifestArn(value); return *this;}

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline CreateVehicleRequest& WithModelManifestArn(Aws::String&& value) { SetModelManifestArn(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Name ARN of a vehicle model.

     */
    inline CreateVehicleRequest& WithModelManifestArn(const char* value) { SetModelManifestArn(value); return *this;}

    /**
     *
 The ARN of a decoder manifest.

     */
    inline const Aws::String& GetDecoderManifestArn() const{ return m_decoderManifestArn; }

    /**
     *
 The ARN of a decoder manifest.

     */
    inline bool DecoderManifestArnHasBeenSet() const { return m_decoderManifestArnHasBeenSet; }

    /**
     *
 The ARN of a decoder manifest.

     */
    inline void SetDecoderManifestArn(const Aws::String& value) { m_decoderManifestArnHasBeenSet = true; m_decoderManifestArn = value; }

    /**
     *
 The ARN of a decoder manifest.

     */
    inline void SetDecoderManifestArn(Aws::String&& value) { m_decoderManifestArnHasBeenSet = true; m_decoderManifestArn = std::move(value); }

    /**
     *
 The ARN of a decoder manifest.

     */
    inline void SetDecoderManifestArn(const char* value) { m_decoderManifestArnHasBeenSet = true; m_decoderManifestArn.assign(value); }

    /**
     *
 The ARN of a decoder manifest.

     */
    inline CreateVehicleRequest& WithDecoderManifestArn(const Aws::String& value) { SetDecoderManifestArn(value); return *this;}

    /**
     *
 The ARN of a decoder manifest.

     */
    inline CreateVehicleRequest& WithDecoderManifestArn(Aws::String&& value) { SetDecoderManifestArn(std::move(value)); return *this;}

    /**
     *
 The ARN of a decoder manifest.

     */
    inline CreateVehicleRequest& WithDecoderManifestArn(const char* value) { SetDecoderManifestArn(value); return *this;}

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetAttributes() const{ return m_attributes; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline bool AttributesHasBeenSet() const { return m_attributesHasBeenSet; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline void SetAttributes(const Aws::Map<Aws::String, Aws::String>& value) { m_attributesHasBeenSet = true; m_attributes = value; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline void SetAttributes(Aws::Map<Aws::String, Aws::String>&& value) { m_attributesHasBeenSet = true; m_attributes = std::move(value); }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& WithAttributes(const Aws::Map<Aws::String, Aws::String>& value) { SetAttributes(value); return *this;}

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& WithAttributes(Aws::Map<Aws::String, Aws::String>&& value) { SetAttributes(std::move(value)); return *this;}

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& AddAttributes(const Aws::String& key, const Aws::String& value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, value); return *this; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& AddAttributes(Aws::String&& key, const Aws::String& value) { m_attributesHasBeenSet = true; m_attributes.emplace(std::move(key), value); return *this; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& AddAttributes(const Aws::String& key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, std::move(value)); return *this; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& AddAttributes(Aws::String&& key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& AddAttributes(const char* key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, std::move(value)); return *this; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& AddAttributes(Aws::String&& key, const char* value) { m_attributesHasBeenSet = true; m_attributes.emplace(std::move(key), value); return *this; }

    /**
     *
Static information about a vehicle in a key-value pair. For example:
     * "engineType" : "1.3 L R2"

     */
    inline CreateVehicleRequest& AddAttributes(const char* key, const char* value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, value); return *this; }

    /**
     *
 An option to create a new Amazon Web Services IoT thing when creating a
     * vehicle, or to validate an existing Amazon Web Services IoT thing as a vehicle.
     *

Default:

     */
    inline const VehicleAssociationBehavior& GetAssociationBehavior() const{ return m_associationBehavior; }

    /**
     *
 An option to create a new Amazon Web Services IoT thing when creating a
     * vehicle, or to validate an existing Amazon Web Services IoT thing as a vehicle.
     *

Default:

     */
    inline bool AssociationBehaviorHasBeenSet() const { return m_associationBehaviorHasBeenSet; }

    /**
     *
 An option to create a new Amazon Web Services IoT thing when creating a
     * vehicle, or to validate an existing Amazon Web Services IoT thing as a vehicle.
     *

Default:

     */
    inline void SetAssociationBehavior(const VehicleAssociationBehavior& value) { m_associationBehaviorHasBeenSet = true; m_associationBehavior = value; }

    /**
     *
 An option to create a new Amazon Web Services IoT thing when creating a
     * vehicle, or to validate an existing Amazon Web Services IoT thing as a vehicle.
     *

Default:

     */
    inline void SetAssociationBehavior(VehicleAssociationBehavior&& value) { m_associationBehaviorHasBeenSet = true; m_associationBehavior = std::move(value); }

    /**
     *
 An option to create a new Amazon Web Services IoT thing when creating a
     * vehicle, or to validate an existing Amazon Web Services IoT thing as a vehicle.
     *

Default:

     */
    inline CreateVehicleRequest& WithAssociationBehavior(const VehicleAssociationBehavior& value) { SetAssociationBehavior(value); return *this;}

    /**
     *
 An option to create a new Amazon Web Services IoT thing when creating a
     * vehicle, or to validate an existing Amazon Web Services IoT thing as a vehicle.
     *

Default:

     */
    inline CreateVehicleRequest& WithAssociationBehavior(VehicleAssociationBehavior&& value) { SetAssociationBehavior(std::move(value)); return *this;}

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline CreateVehicleRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline CreateVehicleRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline CreateVehicleRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
Metadata that can be used to manage the vehicle.

     */
    inline CreateVehicleRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_vehicleName;
    bool m_vehicleNameHasBeenSet = false;

    Aws::String m_modelManifestArn;
    bool m_modelManifestArnHasBeenSet = false;

    Aws::String m_decoderManifestArn;
    bool m_decoderManifestArnHasBeenSet = false;

    Aws::Map<Aws::String, Aws::String> m_attributes;
    bool m_attributesHasBeenSet = false;

    VehicleAssociationBehavior m_associationBehavior;
    bool m_associationBehaviorHasBeenSet = false;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet = false;
  };

} // namespace Model
} // namespace IoTFleetWise
} // namespace Aws


text:
class Task < Hanami::Entity
  attributes do
    attribute :id,                Types::Int
    attribute :count,             Types::Int
    attribute :user_id,           Types::String
    attribute :body,              Types::String
    attribute :title,             Types::String
    attribute :lang,              Types::String
    attribute :md_body,           Types::String
    attribute :issue_url,         Types::String
    attribute :status,            Types::String
    attribute :complexity,        Types::String
    attribute :repository_name,   Types::String
    attribute :time_estimate,     Types::String
    attribute :assignee_username, Types::String
    attribute :approved,          Types::Bool
    attribute :first_pr,          Types::Bool
    attribute :created_at,        Types::Time
    attribute :updated_at,        Types::Time
    attribute :created_at_day,    Types::Date
  end

  VALID_STATUSES = {
    in_progress: 'in progress',
    assigned: 'assigned',
    closed: 'closed',
    done: 'done',
    moderation: 'moderation',
  }.freeze

  VALID_LANGUAGES = {
    unknown: 'unknown',
    ruby: 'ruby',
    javascript: 'javascript',
    typescript: 'typescript',
    java: 'java',
    python: 'python',
    go: 'go',
    csharp: 'csharp',
    fsharp: 'fsharp',
    vbnet: 'vbnet',
    c: 'c',
    cplusplus: 'cplusplus',
    haskell: 'haskell',
    lua: 'lua',
    scala: 'scala',
    elixir: 'elixir',
    rust: 'rust',
    clojure: 'clojure',
    php: 'php',
    crystal: 'crystal'
  }.freeze

  def author
    UserRepository.new.find(user_id)
  end

  def opened?
    status == Task::VALID_STATUSES[:in_progress] || status == Task::VALID_STATUSES[:assigned]
  end
end


text:
var assert = require('assert')
  , core = require('../../lib');

describe('global service', function() {
    it('can run migrations', function(done) {
        core.services.global.migrate(function(err) {
            assert.ifError(err);
            done();
        });
    });

    it('can run janitor iteration', function(done) {
        core.services.global.janitor(function(err) {
            assert.ifError(err);
            done();
        });
    });
});


text:
/* -----------------
 * EdmondsKarpMaximumFlowTest.java
 * -----------------
 * (C) Copyright 2008-2008, by Ilya Razenshteyn and Contributors.
 *
 * Original Author:  Ilya Razenshteyn
 * Contributor(s):   -
 *
 * $Id: EdmondsKarpMaximumFlowTest.java 628 2008-08-17 12:00:59Z ilyaraz $
 *
 * Changes
 * -------
 */
package org.jgrapht.alg;

import java.util.*;

import junit.framework.*;

import org.jgrapht.graph.*;

public final class EdmondsKarpMaximumFlowTest
    extends TestCase
{
    //~ Methods ----------------------------------------------------------------

    /**
     * .
     */
    public void testCornerCases()
    {
        DirectedWeightedMultigraph<Integer, DefaultWeightedEdge> simple =
            new DirectedWeightedMultigraph<Integer, DefaultWeightedEdge>(
                DefaultWeightedEdge.class);
        simple.addVertex(0);
        simple.addVertex(1);
        DefaultWeightedEdge e = simple.addEdge(0, 1);
        try {
            new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(null);
            fail();
        } catch (NullPointerException ex) {
        }
        try {
            new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(
                simple,
                -0.1);
            fail();
        } catch (IllegalArgumentException ex) {
        }
        try {
            simple.setEdgeWeight(e, -1.0);
            new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(simple);
            fail();
        } catch (IllegalArgumentException ex) {
        }
        try {
            simple.setEdgeWeight(e, 1.0);
            EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge> solver =
                new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(
                    simple);
            solver.calculateMaximumFlow(0, 1);
            Map<DefaultWeightedEdge, Double> flow = solver.getMaximumFlow();
            flow.put(e, 25.0);
            fail();
        } catch (UnsupportedOperationException ex) {
        }
        try {
            EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge> solver =
                new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(
                    simple);
            solver.calculateMaximumFlow(2, 0);
            fail();
        } catch (IllegalArgumentException ex) {
        }
        try {
            EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge> solver =
                new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(
                    simple);
            solver.calculateMaximumFlow(1, 2);
            fail();
        } catch (IllegalArgumentException ex) {
        }
        try {
            EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge> solver =
                new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(
                    simple);
            solver.calculateMaximumFlow(0, 0);
            fail();
        } catch (IllegalArgumentException ex) {
        }
        try {
            EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge> solver =
                new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(
                    simple);
            solver.calculateMaximumFlow(null, 0);
            fail();
        } catch (IllegalArgumentException ex) {
        }
        try {
            EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge> solver =
                new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(
                    simple);
            solver.calculateMaximumFlow(0, null);
            fail();
        } catch (IllegalArgumentException ex) {
        }
    }

    /**
     * .
     */
    public void testLogic()
    {
        runTest(
            new int[] {},
            new int[] {},
            new double[] {},
            new int[] { 1 },
            new int[] { 4057218 },
            new double[] { 0.0 });
        runTest(
            new int[] { 3, 1, 4, 3, 2, 8, 2, 5, 7 },
            new int[] { 1, 4, 8, 2, 8, 6, 5, 7, 6 },
            new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
            new int[] { 3 },
            new int[] { 6 },
            new double[] { 2 });
        runTest(
            new int[] { 5, 5, 5, 1, 1, 4, 2, 7, 8, 3 },
            new int[] { 1, 4, 2, 7, 8, 3, 8, 6, 6, 6 },
            new double[] { 7, 8, 573146, 31337, 1, 1, 1, 1, 2391717, 170239 },
            new int[] { 5 },
            new int[] { 6 },
            new double[] { 4.0 });
        runTest(
            new int[] { 1, 1, 2, 2, 3 },
            new int[] { 2, 3, 3, 4, 4 },
            new double[] {
                1000000000.0, 1000000000.0, 1.0, 1000000000.0, 1000000000.0
            },
            new int[] { 1 },
            new int[] { 4 },
            new double[] { 2000000000.0 });
    }

    private void runTest(
        int [] tails,
        int [] heads,
        double [] capacities,
        int [] sources,
        int [] sinks,
        double [] expectedResults)
    {
        assertTrue(tails.length == heads.length);
        assertTrue(tails.length == capacities.length);
        DirectedWeightedMultigraph<Integer, DefaultWeightedEdge> network =
            new DirectedWeightedMultigraph<Integer, DefaultWeightedEdge>(
                DefaultWeightedEdge.class);
        int m = tails.length;
        for (int i = 0; i < m; i++) {
            network.addVertex(tails[i]);
            network.addVertex(heads[i]);
            DefaultWeightedEdge e = network.addEdge(tails[i], heads[i]);
            network.setEdgeWeight(e, capacities[i]);
        }
        assertTrue(sources.length == sinks.length);
        int q = sources.length;
        for (int i = 0; i < q; i++) {
            network.addVertex(sources[i]);
            network.addVertex(sinks[i]);
        }
        EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge> solver =
            new EdmondsKarpMaximumFlow<Integer, DefaultWeightedEdge>(network);
        assertTrue(solver.getCurrentSource() == null);
        assertTrue(solver.getCurrentSink() == null);
        assertTrue(solver.getMaximumFlowValue() == null);
        assertTrue(solver.getMaximumFlow() == null);
        for (int i = 0; i < q; i++) {
            solver.calculateMaximumFlow(sources[i], sinks[i]);
            assertTrue(solver.getCurrentSource().equals(sources[i]));
            assertTrue(solver.getCurrentSink().equals(sinks[i]));
            double flowValue = solver.getMaximumFlowValue();
            Map<DefaultWeightedEdge, Double> flow = solver.getMaximumFlow();
            assertEquals(
                expectedResults[i],
                flowValue,
                EdmondsKarpMaximumFlow.DEFAULT_EPSILON);
            for (DefaultWeightedEdge e : network.edgeSet()) {
                assertTrue(flow.containsKey(e));
            }
            for (DefaultWeightedEdge e : flow.keySet()) {
                assertTrue(network.containsEdge(e));
                assertTrue(
                    flow.get(e) >= -EdmondsKarpMaximumFlow.DEFAULT_EPSILON);
                assertTrue(
                    flow.get(e)
                    <= (network.getEdgeWeight(e)
                        + EdmondsKarpMaximumFlow.DEFAULT_EPSILON));
            }
            for (Integer v : network.vertexSet()) {
                double balance = 0.0;
                for (DefaultWeightedEdge e : network.outgoingEdgesOf(v)) {
                    balance -= flow.get(e);
                }
                for (DefaultWeightedEdge e : network.incomingEdgesOf(v)) {
                    balance += flow.get(e);
                }
                if (v.equals(sources[i])) {
                    assertEquals(
                        -flowValue,
                        balance,
                        EdmondsKarpMaximumFlow.DEFAULT_EPSILON);
                } else if (v.equals(sinks[i])) {
                    assertEquals(
                        flowValue,
                        balance,
                        EdmondsKarpMaximumFlow.DEFAULT_EPSILON);
                } else {
                    assertEquals(
                        0.0,
                        balance,
                        EdmondsKarpMaximumFlow.DEFAULT_EPSILON);
                }
            }
        }
    }
}

// End EdmondsKarpMaximumFlowTest.java


text:
require 'spec_helper'

module Application
  describe Dispatcher do

    before do
      @dispatcher = Dispatcher.new
    end

    describe '#handle_command' do
      before do
        @command_line = 'help'
      end

      it 'should match handler.' do
        expect(@dispatcher.instance_variable_get(:@commands)[:help]).to receive(:handle)
        @dispatcher.handle_command(@command_line)
      end
    end
  end
end


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.offlinepages.prefetch;

import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.profiles.ProfileKey;

/**
 * Allows the querying and setting of Offline Prefetch related configurations.
 */
@JNINamespace("offline_pages::android")
public class PrefetchConfiguration {
    /**
     * Returns true if the Offline Prefetch feature flag is enabled. This can be used to determine
     * if any evidence of this feature should be presented to the user (like its respective user
     * settings entries).
     */
    public static boolean isPrefetchingFlagEnabled() {
        return ChromeFeatureList.isEnabled(ChromeFeatureList.OFFLINE_PAGES_PREFETCHING);
    }

    /**
     * Returns true if Offline Prefetch is allowed to run, requiring both the feature flag and the
     * user setting to be true. If the current browser Profile is null this method returns false.
     */
    public static boolean isPrefetchingEnabled(ProfileKey profileKey) {
        return PrefetchConfigurationJni.get().isPrefetchingEnabled(profileKey);
    }

    /**
     * Return the value of offline_pages.enabled_by_server pref.
     */
    public static boolean isPrefetchingEnabledByServer(ProfileKey profileKey) {
        return PrefetchConfigurationJni.get().isEnabledByServer(profileKey);
    }

    /**
     * Returns true if it's time for a GeneratePageBundle-forbidden check. This could be the case
     * if the check has never run before or we are forbidden and it's been more than seven days
     * since the last check.
     */
    public static boolean isForbiddenCheckDue(ProfileKey profileKey) {
        return PrefetchConfigurationJni.get().isForbiddenCheckDue(profileKey);
    }

    /**
     * Returns true if the GeneratePageBundle-forbidden check has never run and is due to run.
     */
    public static boolean isEnabledByServerUnknown(ProfileKey profileKey) {
        return PrefetchConfigurationJni.get().isEnabledByServerUnknown(profileKey);
    }

    /**
     * Sets the value of the user controlled setting that controls whether Offline Prefetch is
     * enabled or disabled. If the current browser Profile is null the setting will not be changed.
     */
    public static void setPrefetchingEnabledInSettings(ProfileKey profileKey, boolean enabled) {
        PrefetchConfigurationJni.get().setPrefetchingEnabledInSettings(profileKey, enabled);
    }

    /**
     * Gets the value of the user controlled setting that controls whether Offline Prefetch is
     * enabled or disabled.
     */
    public static boolean isPrefetchingEnabledInSettings(ProfileKey profileKey) {
        return PrefetchConfigurationJni.get().isPrefetchingEnabledInSettings(profileKey);
    }

    @NativeMethods
    interface Natives {
        boolean isPrefetchingEnabled(ProfileKey key);
        boolean isEnabledByServer(ProfileKey key);
        boolean isForbiddenCheckDue(ProfileKey key);
        boolean isEnabledByServerUnknown(ProfileKey key);
        void setPrefetchingEnabledInSettings(ProfileKey key, boolean enabled);
        boolean isPrefetchingEnabledInSettings(ProfileKey key);
    }
}


text:
package aerospike

import (
	"fmt"
	"sync/atomic"

	"github.com/aerospike/aerospike-client-go/types"
)

// Partition encapsulates partition information.
type Partition struct {
	// Namespace of the partition
	Namespace string
	// PartitionId of the partition
	PartitionId int
	partitions  *Partitions
	replica     ReplicaPolicy
	sequence    int
	linearize   bool
}

// NewPartition returns a partition representation
func NewPartition(partitions *Partitions, key *Key, replica ReplicaPolicy, linearize bool) *Partition {
	return &Partition{
		partitions:  partitions,
		Namespace:   key.Namespace(),
		replica:     replica,
		linearize:   linearize,
		PartitionId: key.PartitionId(),
	}
}

// PartitionForWrite returns a partition for write purposes
func PartitionForWrite(cluster *Cluster, policy *BasePolicy, key *Key) (*Partition, error) {
	// Must copy hashmap reference for copy on write semantics to work.
	pmap := cluster.getPartitions()
	partitions := pmap[key.namespace]

	if partitions == nil {
		return nil, newInvalidNamespaceError(key.namespace, len(pmap))
	}

	return NewPartition(partitions, key, policy.ReplicaPolicy, false), nil
}

// PartitionForRead returns a partition for read purposes
func PartitionForRead(cluster *Cluster, policy *BasePolicy, key *Key) (*Partition, error) {
	// Must copy hashmap reference for copy on write semantics to work.
	pmap := cluster.getPartitions()
	partitions := pmap[key.namespace]

	if partitions == nil {
		return nil, newInvalidNamespaceError(key.namespace, len(pmap))
	}

	var replica ReplicaPolicy
	var linearize bool

	if partitions.SCMode {
		switch policy.ReadModeSC {
		case ReadModeSCSession:
			replica = MASTER
			linearize = false

		case ReadModeSCLinearize:
			replica = policy.ReplicaPolicy
			if policy.ReplicaPolicy == PREFER_RACK {
				replica = SEQUENCE
			}
			linearize = true

		default:
			replica = policy.ReplicaPolicy
			linearize = false
		}
	} else {
		replica = policy.ReplicaPolicy
		linearize = false
	}
	return NewPartition(partitions, key, replica, linearize), nil
}

// GetReplicaPolicySC returns a ReplicaPolicy based on different variables in SC mode
func GetReplicaPolicySC(policy *BasePolicy) ReplicaPolicy {
	switch policy.ReadModeSC {
	case ReadModeSCSession:
		return MASTER

	case ReadModeSCLinearize:
		if policy.ReplicaPolicy == PREFER_RACK {
			return SEQUENCE
		}
		return policy.ReplicaPolicy

	default:
		return policy.ReplicaPolicy
	}
}

// GetNodeBatchRead returns a node for batch reads
func GetNodeBatchRead(cluster *Cluster, key *Key, replica ReplicaPolicy, replicaSC ReplicaPolicy, sequence int, sequenceSC int) (*Node, error) {
	// Must copy hashmap reference for copy on write semantics to work.
	pmap := cluster.getPartitions()
	partitions := pmap[key.namespace]

	if partitions == nil {
		return nil, newInvalidNamespaceError(key.namespace, len(pmap))
	}

	if partitions.SCMode {
		replica = replicaSC
		sequence = sequenceSC
	}

	p := NewPartition(partitions, key, replica, false)
	p.sequence = sequence
	return p.GetNodeRead(cluster)
}

// GetNodeRead returns a node for read operations
func (ptn *Partition) GetNodeRead(cluster *Cluster) (*Node, error) {
	switch ptn.replica {
	default:
		fallthrough
	case SEQUENCE:
		return ptn.getSequenceNode(cluster)

	case PREFER_RACK:
		return ptn.getRackNode(cluster)

	case MASTER:
		return ptn.getMasterNode(cluster)

	case MASTER_PROLES:
		return ptn.getMasterProlesNode(cluster)

	case RANDOM:
		return cluster.GetRandomNode()
	}
}

// GetNodeWrite returns a node for write operations
func (ptn *Partition) GetNodeWrite(cluster *Cluster) (*Node, error) {
	switch ptn.replica {
	default:
		fallthrough
	case SEQUENCE:
		fallthrough
	case PREFER_RACK:
		return ptn.getSequenceNode(cluster)

	case MASTER:
		fallthrough
	case MASTER_PROLES:
		fallthrough
	case RANDOM:
		return ptn.getMasterNode(cluster)
	}
}

// PrepareRetryRead increases sequence number before read retries
func (ptn *Partition) PrepareRetryRead(isClientTimeout bool) {
	if !isClientTimeout || !ptn.linearize {
		ptn.sequence++
	}
}

// PrepareRetryWrite increases sequence number before write retries
func (ptn *Partition) PrepareRetryWrite(isClientTimeout bool) {
	if !isClientTimeout {
		ptn.sequence++
	}
}

func (ptn *Partition) getSequenceNode(cluster *Cluster) (*Node, error) {
	replicas := ptn.partitions.Replicas

	for range replicas {
		index := ptn.sequence % len(replicas)
		node := replicas[index][ptn.PartitionId]

		if node != nil && node.IsActive() {
			return node, nil
		}
		ptn.sequence++
	}
	nodeArray := cluster.GetNodes()
	return nil, newInvalidNodeError(len(nodeArray), ptn)
}

func (ptn *Partition) getRackNode(cluster *Cluster) (*Node, error) {
	replicas := ptn.partitions.Replicas
	var fallback *Node

	for range replicas {
		index := ptn.sequence % len(replicas)
		node := replicas[index][ptn.PartitionId]

		if node != nil && node.IsActive() {
			if node.hasRack(ptn.Namespace, cluster.clientPolicy.RackId) {
				return node, nil
			}

			if fallback == nil {
				fallback = node
			}
		}
		ptn.sequence++
	}

	if fallback != nil {
		return fallback, nil
	}

	nodeArray := cluster.GetNodes()
	return nil, newInvalidNodeError(len(nodeArray), ptn)
}

func (ptn *Partition) getMasterNode(cluster *Cluster) (*Node, error) {
	node := ptn.partitions.Replicas[0][ptn.PartitionId]

	if node != nil && node.IsActive() {
		return node, nil
	}
	nodeArray := cluster.GetNodes()
	return nil, newInvalidNodeError(len(nodeArray), ptn)
}

func (ptn *Partition) getMasterProlesNode(cluster *Cluster) (*Node, error) {
	replicas := ptn.partitions.Replicas

	for range replicas {
		index := int(atomic.AddUint64(&cluster.replicaIndex, 1) % uint64(len(replicas)))
		node := replicas[index][ptn.PartitionId]

		if node != nil && node.IsActive() {
			return node, nil
		}
	}
	nodeArray := cluster.GetNodes()
	return nil, newInvalidNodeError(len(nodeArray), ptn)
}

// String implements the Stringer interface.
func (ptn *Partition) String() string {
	return fmt.Sprintf("%s:%d", ptn.Namespace, ptn.PartitionId)
}

// Equals checks equality of two partitions.
func (ptn *Partition) Equals(other *Partition) bool {
	return ptn.PartitionId == other.PartitionId && ptn.Namespace == other.Namespace
}

// newnewInvalidNamespaceError creates an AerospikeError with Resultcode INVALID_NAMESPACE
// and a corresponding message.
func newInvalidNamespaceError(ns string, mapSize int) error {
	s := "Partition map empty"
	if mapSize != 0 {
		s = "Namespace not found in partition map: " + ns
	}
	return types.NewAerospikeError(types.INVALID_NAMESPACE, s)
}


text:
[![Codeship Status for naXa777/file-tree](https://app.codeship.com/projects/17e4d940-9903-0136-b15a-3601fc6081f4/status?branch=master)](https://app.codeship.com/projects/305398)

## Description

### Task

Implement a web-based file manager that observes file changes. The work has been done in the framework of a practice-based research in computer science that took place in Exadel, 2013.

### Steps

- [x] Implement a file indexing console application
  _Implement console application which takes directory path as argument._
  The application should:
  - [x] Create an index for each file in the target directory. Index should contain file name, file size and last update fields.
  - [x] Collection of indexes should be serialised as XML on disc.
  - [x] Before serialisation application should check if previously serialised data for target directory already exists.
  - [x] Application should print complete report about file changes based on their previous and current index data.
  - [x] After report old serialised data should be rewritten by actual.

- [x] Provide choice to use DB file indexes storage
  _Make application more flexible: provide choice to store file indexes in DB._
  - [x] Develop interface for required directory and file indexes operations. Refactor existed code to make it an implementation of the interface.
  - [x] Develop another implementation of the interface which will use DB as file indexes storage. Write SQL script for DB creation. Store DB settings in application properties file. Use Spring framework JDBC data access abstraction for the implementation.
  - [x] Use Inversion of Control (IoC) pattern to choose between two implementations. Create Spring context for the application. Select an implementation depending on key from application properties.

- [ ] Create WEB application
  _Create WEB application based on existed functionality._
  - [x] Use Servlets/JSP technology to develop WEB application. Use Tomcat as J2EE web container.
  - [x] The application should allow file tree navigation providing list of subdirectories as well as file changes indexes.
  - [ ] Provide user control for directory file indexes update.
  - [x] _(Optional)_ Use Spring Web MVC for the implementation.

**Technologies**: Maven, J2EE, Servlets/JSP, Tomcat, MVC, Spring Framework.

## Configuration

You can choose to store index either in DB or XML.

### MySQL Database

1. Create database. Find and execute `src/main/resources/DB create.sql`.
2. Tweak JDBC connection in `jdbc connection.properties` file.
3. Set `app.use.implementation` to either `springDBService` or `dbService` in `application.properties` file if you want to use database as a storage.

### XML

Set `app.use.implementation` to `xmlService` in `application.properties` file if you want to use XML-based storage.

## Quick Start

### Build web app

    mvn clean package

Output: /target/file-tree.war

### Build console app

    mvn clean jar:jar

Output: /target/file-tree.jar

### Run web app

1. Deploy the application to Tomcat;
2. Open [http://localhost:8080/<deploy-path>](http://localhost:8080/file-tree) in a browser;
3. Guess credentials!
4. And browse your `D:\` drive from the browser!

### Run console app

    java -jar ./file-tree.jar "D:/example"

The first argument is a root folder for indexing.

## Screenshots

State 1
![File Tree](/screenshots/filetree_1.png)

_Make changes... Refresh page_

State 2
![File Tree](/screenshots/filetree_2.png)


text:
Use this playbook to create or use existing Inventa ticket in order to obtain information on the PII entities for
the Data Subject as well as file or database storages which contain information about the Data Subject.
The incident will be automatically closed if no such datasubject is found within Inventa system.

####Triggers
The Inventa's DSAR engine will report all the PII categories and info storages containing information about Data Subject.
This playbook is automatically triggered by the Incident creation and is used for enrichment of the Incident information

####Configuration
No extra configuration required. However, in case of disruptions or connectivity issues some tasks, involving
Inventa's API call may fail and will require to be manually restarted.

####Best practices and suggestions
In case where the incident is automatically closed due to the fact that requested datasubject is not present within Inventa system, it's recommended to recheck whether the inputs have any mistakes and reopen the Incident if the inputs were incorrect.

#Dependencies
* Builtin

##Sub-playbooks
This playbook does not use sub-playbooks.

##Integrations
This playbook is designed to be used in Inventa integration.

##Scripts
* Set
* SearchIncidentsV2
* linkIncidents
* SetGridField
* closeInvestigation

#Playbook inputs
| **Name** | **Description** | **Default Value** | **Required** |
| --- | --- | --- | --- |
| National ID | National ID of a Data Subject. Used as a part of a constraint. | - | Optional |
| Passport Number | Passport Number of a Data Subject. Used as a part of a constraint. | - | Optional |
| Driver License | Driver License of a Data Subject. Used as a part of a constraint. | - | Optional |
| Tax ID | Tax ID of a Data Subject. Used as a part of a constraint. | - | Optional |
| Credit Card Number | Credit Card Number of a Data Subject. Used as a part of a constraint. | - | Optional |
| First Name | First Name of a Data Subject. Used as a part of a constraint. | - | Optional |
| Surname | Surname of a Data Subject. Used as a part of a constraint. | - | Optional |
| Full Name | Full Name of a Data Subject. Used as a part of a constraint. | - | Optional |
| Vehicle Number | Vehicle Number of a Data Subject. Used as a part of a constraint. | - | Optional |
| Phone Number | Phone Number of a Data Subject. Used as a part of a constraint. | - | Optional |
| Birthday | Birthday of a Data Subject. Used as a part of a constraint. | - | Optional |
| City | City of a Data Subject. Used as a part of a constraint. | - | Optional |
| Street Address | Street Address of a Data Subject. Used as a part of a constraint. | - | Optional |
| Reason | Reason of a Data Subject. Required by Inventa DSAR Engine for creating a ticket. | - | Required |
| Ticket | Ticket of a Data Subject. Used to obtain all relevant information on the ticket and data stored in it from Inventa. | - | Optional |

#Playbook outputs
There are no outputs for this playbook.

#Playbook Image


text:
import React from 'react';
import ReactDOM from 'react-dom';

class Page1 extends React.Component{
	render(){
		return ( < div >
					This is page1
					<button onClick={this.goHome.bind(this)}>Go to Home Page</button>
					<input type="text" ref="username" />
					<button onClick={this.findGithub.bind(this)}>Get Github Details</button>
			< /div>);
	}
	findGithub(){
		var username = ReactDOM.findDOMNode(this.refs.username).value.trim();
		this.props.history.pushState(null,'/github/'+username);
	}
	goHome(){
		this.props.history.pushState(null,'/');
	}
}

export default Page1;


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.trellisldp.rosid.file;

import static java.io.File.separator;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.isNull;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.stream.IntStream.range;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import static org.apache.commons.rdf.jena.JenaRDF.asQuad;
import static org.apache.jena.riot.Lang.NQUADS;
import static org.apache.jena.riot.RDFParser.fromString;
import static org.apache.jena.sparql.core.DatasetGraphFactory.create;
import static org.slf4j.LoggerFactory.getLogger;

import java.io.File;
import java.net.URI;
import java.util.Iterator;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.zip.CRC32;

import org.apache.commons.rdf.api.IRI;
import org.apache.commons.rdf.api.Quad;
import org.apache.commons.rdf.api.RDF;
import org.apache.jena.riot.RiotException;
import org.apache.jena.sparql.core.DatasetGraph;
import org.slf4j.Logger;

/**
 * @author acoburn
 */
public final class FileUtils {

    private static final Logger LOGGER = getLogger(FileUtils.class);

    // The length of the CRC directory partition
    public static final int LENGTH = 2;
    public static final int MAX = 3;

    /**
     * Partition an identifier into a directory structure
     * @param identifier the identifier
     * @return a string usable as a directory path
     */
    public static String partition(final IRI identifier) {
        return partition(identifier.getIRIString());
    }

    /**
     * Partition an identifier into a directory structure
     * @param identifier the identifier
     * @return a string usable as a directory path
     */
    public static String partition(final String identifier) {
        requireNonNull(identifier, "identifier must not be null!");

        final StringJoiner joiner = new StringJoiner(separator);
        final CRC32 hasher = new CRC32();
        hasher.update(identifier.getBytes(UTF_8));
        final String intermediate = Long.toHexString(hasher.getValue());

        range(0, intermediate.length() / LENGTH).limit(MAX)
            .forEach(i -> joiner.add(intermediate.substring(i * LENGTH, (i + 1) * LENGTH)));

        joiner.add(md5Hex(identifier));
        return joiner.toString();
    }

    /**
     * Parse a string into a Quad
     * @param rdf the RDF object
     * @param line the line of text
     * @return the Quad
     */
    public static Optional<Quad> stringToQuad(final RDF rdf, final String line) {
        final DatasetGraph dataset = create();
        try {
            fromString(line).lang(NQUADS).parse(dataset);
        } catch (final RiotException ex) {
            LOGGER.warn("Skipping invalid data value: {}", line);
            return empty();
        }
        final Iterator<org.apache.jena.sparql.core.Quad> i = dataset.find();
        if (i.hasNext()) {
            return of(i.next()).map(x -> asQuad(rdf, x));
        }
        return empty();
    }

    /**
     * Get the resource directory for a given identifier
     * @param dataLocation the data location
     * @param identifier the identifier
     * @return the file
     */
    public static File resourceDirectory(final String dataLocation, final IRI identifier) {
        return resourceDirectory(dataLocation, identifier.getIRIString());
    }

    /**
     * Get the resource directory for a given identifier
     * @param dataLocation the dataLocation
     * @param identifier the identifier
     * @return the file
     */
    public static File resourceDirectory(final String dataLocation, final String identifier) {
        if (isNull(dataLocation)) {
            return null;
        }

        final File root;
        if (dataLocation.startsWith("file:")) {
            root = new File(URI.create(dataLocation));
        } else {
            root = new File(dataLocation);
        }
        final File directory = new File(root, partition(identifier));
        directory.mkdirs();
        return directory;
    }

    private FileUtils() {
        // prevent instantiation
    }
}


text:
'use strict';

import * as os from 'os';

import uri from 'vs/base/common/uri';
import * as ipc from 'vs/base/parts/ipc/common/ipc';
import { Client } from 'vs/base/parts/ipc/node/ipc.cp';

import { ISearchWorker, ISearchWorkerChannel, SearchWorkerChannelClient } from './worker/searchWorkerIpc';

export interface ITextSearchWorkerProvider {
	getWorkers(): ISearchWorker[];
}

export class TextSearchWorkerProvider implements ITextSearchWorkerProvider {
	private workers: ISearchWorker[] = [];

	getWorkers(): ISearchWorker[] {
		const numWorkers = os.cpus().length;
		while (this.workers.length < numWorkers) {
			this.createWorker();
		}

		return this.workers;
	}

	private createWorker(): void {
		let client = new Client(
			uri.parse(require.toUrl('bootstrap')).fsPath,
			{
				serverName: 'Search Worker ' + this.workers.length,
				args: ['--type=searchWorker'],
				timeout: 30 * 1000,
				env: {
					AMD_ENTRYPOINT: 'vs/workbench/services/search/node/worker/searchWorkerApp',
					PIPE_LOGGING: 'true',
					VERBOSE_LOGGING: process.env.VERBOSE_LOGGING
				},
				useQueue: true
			});

		const channel = ipc.getNextTickChannel(client.getChannel<ISearchWorkerChannel>('searchWorker'));
		const channelClient = new SearchWorkerChannelClient(channel);

		this.workers.push(channelClient);
	}
}


text:
<title>Most important options - ECB - the Emacs Code Browser</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="ECB - the Emacs Code Browser">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="ecb.html#Top">
<link rel="up" href="Customizing.html#Customizing" title="Customizing">
<link rel="prev" href="General-aspects.html#General-aspects" title="General aspects">
<link rel="next" href="Customizable-options.html#Customizable-options" title="Customizable options">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<meta http-equiv="Content-Style-Type" content="text/css">

Next: Customizable options,
Previous: General aspects,
Up: Customizing

7.2 The most important options of ECB

Here are the most important options (it is recommended to check at
least the following options before working with ECB). You can
customize them via the customize-group “ecb-most-important” or via
the command ecb-customize-most-important.

ecb-source-path
Where ECB can find your sources. You must set this option!

ecb-show-help-format
Should the online help of ECB be displayed in the standard Info format
or in HTML format in a web-browser.

ecb-auto-activate

ecb-major-modes-show-or-hide
Auto. activation of ECB after start (see Automatic activation) or
major-mode-based showing or hiding the ecb-windows.

ecb-winman-escreen-number
ecb-winman-winring-name
Support of several window-managers (see Window-managers and ECB).

ecb-key-map
All ECB-keybindings incl. a common prefix-key (see Using the keyboard).

ecb-new-ecb-frame
Should ECB create a new frame at activation time.

ecb-primary-secondary-mouse-buttons
ecb-mouse-click-destination
Define how to use the mouse (see Using the mouse).

ecb-tree-buffer-style
ecb-tree-expand-symbol-before
ecb-tree-indent
ecb-truncate-lines
The look&feel of the trees in the tree-buffers. The former option
defines the general style of the tree-buffers and the latter ones
allow to customize the ascii-style tree-buffers (maybe you like a
value of 4 for the latter one if you display the expand-symbol before
(see Tree-buffer styles).

ecb-source-file-regexps
Which files will (not) be shown in ECB.

ecb-layout-name
ecb-compile-window-height
ecb-compile-window-width
ecb-other-window-behavior
The ECB layout, means which windows you want to be displayed in the
ECB-frame and also the location of these windows (see Changing the ECB-layout).

ecb-compilation-buffer-names
Which buffers should be treaten as “compilation-buffers” and
therefore displayed in the compile-window of ECB - if there is any.

ecb-tag-display-function
ecb-type-tag-display
ecb-type-tag-expansion
ecb-show-tags
How to display the entries in the ECB-method window for semantic
supported sources (see Customizing the display). These options
take only effect for semantic-sources (see Definition of semantic- and non-semantic-sources).

ecb-process-non-semantic-files
Displaying file-contents for not by semantic supported files too, e.g.
for LaTeX- and perl-sources (see Non-semantic sources).

But to make ECB working best for you it is also recommended to have a
look at Customizable options!