text:
<?php

namespace Settings\Test\TestCase\Core;

use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;
use Settings\Core\Setting;

/**
 * Settings\Core\Setting Test Case
 */
class SettingTest extends TestCase
{
    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'Configurations' => 'plugin.settings.settings_configurations'
    ];

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();

        $this->Settings = TableRegistry::get('Settings.Configurations');

        Setting::model($this->Settings);
    }

    /**
     * tearDown method
     *
     * @return void
     */
    public function tearDown()
    {
        unset($this->Settings);

        Setting::clear();

        parent::tearDown();
    }

    /**
     * Test model-method
     *
     * @return void
     */
    public function testModel()
    {
        $model = Setting::model();

        $this->assertEquals($this->Settings, $model);

        $this->assertEquals('settings_configurations', $model->table());
        $this->assertEquals('Configurations', $model->alias());

        $_model = "Test";

        Setting::model($_model);

        $this->assertEquals($_model, "Test");
    }

    /**
     * Test clear
     *
     * @return void
     */
    public function testClear()
    {
        Setting::write('App.test1', 1);
        Setting::write('App.test2', 2);
        Setting::write('App.test3', 3);

        $data = [
            'App.test1' => 1,
            'App.test2' => 2,
            'App.test3' => 3,
        ];

        $this->assertEquals($data, Setting::read());

        $this->assertEquals(3, $this->Settings->find('all')->count());

        Setting::clear();

        $this->assertEquals([], Setting::read());

        $this->assertEquals(3, $this->Settings->find('all')->count());
    }

    /**
     * Test check-method
     */
    public function testCheck()
    {
        $this->assertFalse(Setting::check('App.UniqueName'));

        Setting::write('App.UniqueName', 'Test');

        $this->assertTrue(Setting::check('App.UniqueName'));
    }

    public function testRead()
    {
        $data = [
            'name' => 'App.UniqueReadvalue',
            'value' => 'UniqueValue'
        ];

        $this->Settings->save($this->Settings->newEntity($data));

        $this->assertEquals('UniqueValue', Setting::read('App.UniqueReadvalue'));
        $this->assertTrue(Setting::read('App.UniqueReadvalue', 'bool'));
        $this->assertEquals(0, Setting::read('App.UniqueReadvalue', 'integer'));
        $this->assertEquals('UniqueValue', Setting::read('App.UniqueReadvalue', 'string'));

        Setting::write('App.UniqueReadvalue', false);
        $this->assertFalse(Setting::read('App.UniqueReadvalue'));
        $this->assertFalse(Setting::read('App.UniqueReadvalue', 'bool'));
        $this->assertEquals(0, Setting::read('App.UniqueReadvalue'));
        $this->assertEquals(0, Setting::read('App.UniqueReadvalue', 'integer'));
        $this->assertEquals('', Setting::read('App.UniqueReadvalue', 'string'));

        Setting::write('App.UniqueReadvalue', true);
        $this->assertTrue(Setting::read('App.UniqueReadvalue'));
        $this->assertTrue(Setting::read('App.UniqueReadvalue', 'bool'));
        $this->assertEquals(1, Setting::read('App.UniqueReadvalue'));
        $this->assertEquals(1, Setting::read('App.UniqueReadvalue', 'integer'));
        $this->assertEquals('1', Setting::read('App.UniqueReadvalue', 'string'));
    }

    /**
     * Test write-method
     *
     * @return void
     */
    public function testWrite()
    {
        $count = $this->Settings->find('all')->count();

        $this->assertEquals(0, $count);

        Setting::write('App.WriteSimple', 'SimpleValue');

        $this->assertEquals(1, $this->Settings->find('all')->count());
        $value = $this->Settings->get(1);
        $this->assertEquals('App.WriteSimple', $value->name);
        $this->assertEquals('App.WriteSimple', $value->key);
        $this->assertEquals('SimpleValue', $value->value);
        $this->assertEmpty($value->description);
        $this->assertEmpty($value->type);
        $this->assertEquals(1, $value->editable);
        $this->assertEmpty($value->options);
        $this->assertEquals(0, $value->weight);

        Setting::write('App.WriteAdvanced', 'AdvancedValue', [
            'description' => 'Short description',
            'type' => 'text',
            'editable' => true,
            'options' => [
                1 => 'One',
                2 => 'Two'
            ],
            'weight' => 20,
            'autoload' => true,
        ]);

        $this->assertEquals(2, $this->Settings->find('all')->count());

        $value = $this->Settings->get(2);
        $this->assertEquals('App.WriteAdvanced', $value->name);
        $this->assertEquals('App.WriteAdvanced', $value->key);
        $this->assertEquals('AdvancedValue', $value->value);
        $this->assertEquals('Short description', $value->description);
        $this->assertEquals('text', $value->type);
        $this->assertEquals(1, $value->editable);
        $this->assertEquals(20, $value->weight);
        $this->assertEquals(1, $value->autoload);
    }

    /**
     * Test register-method
     *
     * @return void
     */
    public function testRegister()
    {
        $count = $this->Settings->find('all')->count();

        $this->assertEquals(0, $count);

        Setting::register('App.WriteSimple', 'SimpleValue');

        $this->assertEquals(1, $this->Settings->find('all')->count());
        $value = $this->Settings->get(1);
        $this->assertEquals('App.WriteSimple', $value->name);
        $this->assertEquals('App.WriteSimple', $value->key);
        $this->assertEquals('SimpleValue', $value->value);
        $this->assertEmpty($value->description);
        $this->assertEmpty($value->type);
        $this->assertEquals(1, $value->editable);
        $this->assertEmpty($value->options);
        $this->assertEquals(0, $value->weight);

        Setting::write('App.WriteSimple', 'SecondValue');

        $this->assertEquals('SecondValue', Setting::read('App.WriteSimple'));
        $this->assertEquals('SecondValue', $this->Settings->get(1)->value);

        Setting::register('App.WriteSimple', 'SimpleValue');

        $this->assertEquals(1, $this->Settings->find('all')->count());
        $this->assertEquals('SecondValue', Setting::read('App.WriteSimple'));
        $this->assertEquals('SecondValue', $this->Settings->get(1)->value);

        Setting::register('App.WriteAdvanced', 'AdvancedValue', [
            'description' => 'Short description',
            'type' => 'text',
            'editable' => true,
            'weight' => 20,
            'autoload' => true,
        ]);

        $this->assertEquals(2, $this->Settings->find('all')->count());

        $value = $this->Settings->get(2);
        $this->assertEquals('App.WriteAdvanced', $value->name);
        $this->assertEquals('App.WriteAdvanced', $value->key);
        $this->assertEquals('AdvancedValue', $value->value);
        $this->assertEquals('Short description', $value->description);
        $this->assertEquals('text', $value->type);
        $this->assertEquals(1, $value->editable);
        $this->assertEquals(20, $value->weight);
        $this->assertEquals(1, $value->autoload);
    }

    /**
     * Test options-method
     */
    public function testOptions()
    {
        Setting::register('App.Key', 1, [
            'options' => [
                0 => 'One',
                1 => 'Two',
            ]
        ]);

        $expected = [
            0 => 'One',
            1 => 'Two',
        ];

        $this->assertEquals($expected, Setting::options('App.Key'));

        Setting::options('App.Second', [
            0 => 'One',
            1 => 'Two',
        ]);
    }

    /**
     * Test autoload-method
     *
     * @return void
     */
    public function testAutoload()
    {
        Setting::write('App.Test1', 'Test1');
        Setting::write('App.Test2', 'Test2');

        Setting::clear();

        $this->assertEmpty(Setting::read());

        Setting::clear(true);
        Setting::autoLoad();

        $_array = [
            'App.Test1' => 'Test1',
            'App.Test2' => 'Test2',
        ];

        $this->assertEquals($_array, Setting::read());
    }
}


text:
USING_NS_CC;

int main(int argc, char **argv)
{
    // create the application instance
    AppDelegate app;
    EGLView eglView;
    eglView.init("SimpleGame",900,640);
    return Application::getInstance()->run();
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Canny+Watershed failed
category: Reports
tags:
  - algorithm
  - failure
  - JUK
comments: true
share: true
published: true
mathjax: false
featured: false
---

Unforuntately, the currently used combination of algorithms does not seem to work well when putting markers inside the lumina on the dark regions, that are very similar to other vessel parts by colour.
So I have to decide whether to change the tactics and try model-based strategy or to go on with canny and watershed and add the vessel contour to the image and see what happens.


text:
/**
 * Default.ts
 *
 * @package  vrkd/src/list
 * @author  Fernando Salazar
 */
export declare type Storage<V> = {
    [k: string]: V;
};
/**
 * List class adds a CRUD wrapper to an object.
 */
export declare class List<V> {
    /**
     * List storage
     */
    private _storage;
    /**
     * Unique identifier for appending keyless values.
     */
    private _count;
    /**
     * Class constructor
     */
    constructor($storage?: Storage<V>);
    /**
     * Assign a `$val` to a `$key`
     */
    set($key: string, $val: V): void;
    /**
     * Get a value by `$key`
     */
    get($key: string): V;
    /**
     * Does storage have `$key`
     */
    has($key: string): boolean;
    /**
     * Add value to storage with no key provided.
     * It will generate and return the key it was assigned to.
     *
     * @param  {V} $value to be added.
     * @return {int} The `$key` index of the value.
     */
    append($value: V): string;
    /**
     * Remove value by `$key`.
     *
     * @param  {string} $key
     * @return {void}
     */
    remove($key: string): void;
    /**
     * Get all keys from storage
     */
    keys(): string[];
    /**
     * Get storage in a json string.
     *
     * @return {string} JSON string
     */
    toJSON(): string;
}


text:
package net.ypresto.miniguava.compare;

import static net.ypresto.miniguava.base.Preconditions.checkNotNull;

import javax.annotation.Nullable;

/** An ordering that uses the reverse of a given order. */
// miniguava: Removed serialization support.
final class ReverseOrdering<T> extends Ordering<T> {
  final Ordering<? super T> forwardOrder;

  ReverseOrdering(Ordering<? super T> forwardOrder) {
    this.forwardOrder = checkNotNull(forwardOrder);
  }

  @Override
  public int compare(T a, T b) {
    return forwardOrder.compare(b, a);
  }

  @SuppressWarnings("unchecked") // how to explain?
  @Override
  public <S extends T> Ordering<S> reverse() {
    return (Ordering<S>) forwardOrder;
  }

  // Override the min/max methods to "hoist" delegation outside loops

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

  @Override
  public boolean equals(@Nullable Object object) {
    if (object == this) {
      return true;
    }
    if (object instanceof ReverseOrdering) {
      ReverseOrdering<?> that = (ReverseOrdering<?>) object;
      return this.forwardOrder.equals(that.forwardOrder);
    }
    return false;
  }

  @Override
  public String toString() {
    return forwardOrder + ".reverse()";
  }
}


text:
<?php
echo 'start from hellp.test2.php<br>';


text:
package swift.application.test;

import static org.junit.Assert.assertEquals;
import static swift.application.test.TestsUtil.compareValue;
import static swift.application.test.TestsUtil.decrement;
import static swift.application.test.TestsUtil.getValue;
import static swift.application.test.TestsUtil.increment;
import static sys.Context.Networking;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import swift.api.CRDTIdentifier;
import swift.exceptions.SwiftException;
import swift.indigo.Indigo;
import swift.indigo.remote.IndigoImpossibleException;
import swift.indigo.remote.RemoteIndigo;

public class CounterUnitTests {

	static Indigo stub11, stub12;
	static String serversAdresses = "localhost";
	static String table = "COUNTER";
	static char key = '@';

	static Random random = new Random();

	static String DC_A = "DC_A";
	static String DC_B = "DC_B";
	static boolean started;

	@Before
	public void init1DC() {
		if (!started) {
			TestsUtil.startSequencer(DC_A, DC_A, 31001, new String[]{"tcp://*:33001/"}, new String[]{});
			TestsUtil.startServer(DC_A, DC_A, 32001, 34001, 35001, 36001, 33001, "tcp://*:31001/", new String[]{});
			started = true;
			stub11 = RemoteIndigo.getInstance(Networking.resolve("tcp://*/36001/DC_A/"));
			stub12 = RemoteIndigo.getInstance(Networking.resolve("tcp://*/36001/DC_A/"));
		}
	}

	@Before
	public void init() throws InterruptedException, SwiftException {
		key++;
		init1DC();
	}

	@Test
	public void incrementAndRead() throws SwiftException {
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, 10, stub11, DC_A);
		compareValue(id, 10, stub11);
	}
	@Test
	public void twoIncrementAndRead() throws SwiftException {
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, 10, stub11, DC_A);
		increment(id, 10, stub11, DC_A);
		compareValue(id, 20, stub11);
	}
	@Test
	public void decrementAborts() throws SwiftException, InterruptedException {
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, 10, stub11, DC_A);
		assertEquals(true, decrement(id, 10, stub11, DC_A));
		Thread.sleep(5000);
		assertEquals(false, decrement(id, 10, stub11, DC_A));
	}

	@Test
	public void decrementStillAborts() throws SwiftException {
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, 9, stub11, DC_A);
		assertEquals(false, decrement(id, 10, stub11, DC_A));
	}

	@Test
	public void decrementNoResources() throws SwiftException {
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, 0, stub11, DC_A);
		assertEquals(false, decrement(id, 10, stub11, DC_A));
		increment(id, 0, stub11, DC_A);
		increment(id, 0, stub11, DC_A);
	}

	@Test
	public void decrementSucceeds() throws SwiftException, InterruptedException {
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, 10, stub11, DC_A);
		assertEquals(true, decrement(id, 10, stub11, DC_A));
		Thread.sleep(1000);
		assertEquals(0, getValue(id, stub11));
	}

	@Test
	public void decrementCycle1Threads1DC() throws SwiftException, InterruptedException, BrokenBarrierException {
		decrementCycleNThreads1DC(100, 1);
	}

	@Test
	public void decrementCycle2Threads1DC() throws SwiftException, InterruptedException, BrokenBarrierException {
		decrementCycleNThreads1DC(200, 2);
	}

	@Test
	public void decrementCycle10Threads1DC() throws SwiftException, InterruptedException, BrokenBarrierException {
		decrementCycleNThreads1DC(1000, 10);
	}

	@Test
	public void decrementCycle100Threads1DC() throws SwiftException, InterruptedException, BrokenBarrierException {
		decrementCycleNThreads1DC(10000, 100);
	}

	public void decrementCycleNThreads1DC(int initValue, int nThreads) throws SwiftException, InterruptedException, BrokenBarrierException {
		int count = initValue;
		final AtomicInteger sum = new AtomicInteger();
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, count, stub11, DC_A);
		Semaphore sem = new Semaphore(nThreads);
		sem.acquire(nThreads);
		for (int i = 0; i < nThreads; i++) {
			final Indigo stub = RemoteIndigo.getInstance(Networking.resolve("tcp://*/36001/" + DC_A + "/"));

			new Thread(new Runnable() {
				public void run() {
					try {
						for (;;) {
							if (getValue(id, stub) > 0) {
								if (decrement(id, 1, stub, DC_A))
									sum.incrementAndGet();
								Thread.sleep(random.nextInt(200));
							} else {
								break;
							}
						}
					} catch (IndigoImpossibleException e) {
					} catch (SwiftException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						sem.release();
					}
				}
			}).start();
		}

		Thread.sleep(2000);
		sem.acquire(nThreads);
		Thread.sleep(1000);
		compareValue(id, 0, stub11);
		assertEquals(count, sum.get());
	}

	@Test
	public void waitAndSucceed() throws SwiftException, InterruptedException {
		CRDTIdentifier id = new CRDTIdentifier(table, "" + key);
		increment(id, 10, stub11, DC_A);

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					decrement(id, 10, stub11, DC_A);
					System.out.println("Decrement and sleep");
					Thread.sleep(500);
					increment(id, 10, stub11, DC_A);
					System.out.println("First thread increments and finish");
				} catch (SwiftException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}).start();

		Thread.sleep(500);

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					decrement(id, 8, stub12, DC_A);
					System.out.println("Second thread succeeded");
				} catch (SwiftException e) {
					e.printStackTrace();
				}

			}
		}).start();

		Thread.sleep(2000);
	}

	@After
	public void close() {
		// Should Stop the nodes.
	}

}


text:
package pl.msitko.xml.dsl

import pl.msitko.xml.entities.XmlDocument

trait ToDocumentOps {
  implicit def toDocumentOps(xmlDocument: XmlDocument): XmlDocumentOps =
    new XmlDocumentOps(xmlDocument)
}


text:
package org.mengyun.tcctransaction.sample.dubbo.order.web.controller;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.mengyun.tcctransaction.sample.dubbo.order.service.AccountServiceImpl;
import org.mengyun.tcctransaction.sample.dubbo.order.service.PlaceOrderServiceImpl;
import org.mengyun.tcctransaction.sample.dubbo.order.web.controller.vo.PlaceOrderRequest;
import org.mengyun.tcctransaction.sample.order.domain.entity.Order;
import org.mengyun.tcctransaction.sample.order.domain.entity.Product;
import org.mengyun.tcctransaction.sample.order.domain.repository.ProductRepository;
import org.mengyun.tcctransaction.sample.order.domain.service.OrderServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.math.BigDecimal;
import java.security.InvalidParameterException;
import java.util.List;

/**
 * Created by changming.xie on 4/1/16.
 */
@Controller
@RequestMapping("")
public class OrderController {

    @Autowired
    PlaceOrderServiceImpl placeOrderService;

    @Autowired
    ProductRepository productRepository;

    @Autowired
    AccountServiceImpl accountService;

    @Autowired
    OrderServiceImpl orderService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("/index");
        return mv;
    }

    @RequestMapping(value = "/user/{userId}/shop/{shopId}", method = RequestMethod.GET)
    public ModelAndView getProductsInShop(@PathVariable long userId,
                                          @PathVariable long shopId) {
        List<Product> products = productRepository.findByShopId(shopId);

        ModelAndView mv = new ModelAndView("/shop");

        mv.addObject("products", products);
        mv.addObject("userId", userId);
        mv.addObject("shopId", shopId);

        return mv;
    }

    @RequestMapping(value = "/user/{userId}/shop/{shopId}/product/{productId}/confirm", method = RequestMethod.GET)
    public ModelAndView productDetail(@PathVariable long userId,
                                      @PathVariable long shopId,
                                      @PathVariable long productId) {

        ModelAndView mv = new ModelAndView("product_detail");

        mv.addObject("capitalAmount", accountService.getCapitalAccountByUserId(userId));
        mv.addObject("redPacketAmount", accountService.getRedPacketAccountByUserId(userId));

        mv.addObject("product", productRepository.findById(productId));

        mv.addObject("userId", userId);
        mv.addObject("shopId", shopId);

        return mv;
    }

    @RequestMapping(value = "/placeorder", method = RequestMethod.POST)
    public RedirectView placeOrder(@RequestParam String redPacketPayAmount,
                                   @RequestParam long shopId,
                                   @RequestParam long payerUserId,
                                   @RequestParam long productId) {

        PlaceOrderRequest request = buildRequest(redPacketPayAmount, shopId, payerUserId, productId);

        String merchantOrderNo = placeOrderService.placeOrder(request.getPayerUserId(), request.getShopId(),
                request.getProductQuantities(), request.getRedPacketPayAmount());

        return new RedirectView("/payresult/" + merchantOrderNo);
    }

    @RequestMapping(value = "/payresult/{merchantOrderNo}", method = RequestMethod.GET)
    public ModelAndView getPayResult(@PathVariable String merchantOrderNo) {

        ModelAndView mv = new ModelAndView("pay_success");

        String payResultTip = null;
        Order foundOrder = orderService.findOrderByMerchantOrderNo(merchantOrderNo);

        if ("CONFIRMED".equals(foundOrder.getStatus()))
            payResultTip = "Success";
        else if ("PAY_FAILED".equals(foundOrder.getStatus()))
            payResultTip = "Failed, please see log";
        else
            payResultTip = "Unknown";

        mv.addObject("payResult", payResultTip);

        mv.addObject("capitalAmount", accountService.getCapitalAccountByUserId(foundOrder.getPayerUserId()));
        mv.addObject("redPacketAmount", accountService.getRedPacketAccountByUserId(foundOrder.getPayerUserId()));

        return mv;
    }

    private PlaceOrderRequest buildRequest(String redPacketPayAmount, long shopId, long payerUserId, long productId) {
        BigDecimal redPacketPayAmountInBigDecimal = new BigDecimal(redPacketPayAmount);
        if (redPacketPayAmountInBigDecimal.compareTo(BigDecimal.ZERO) < 0)
            throw new InvalidParameterException("invalid red packet amount :" + redPacketPayAmount);

        PlaceOrderRequest request = new PlaceOrderRequest();
        request.setPayerUserId(payerUserId);
        request.setShopId(shopId);
        request.setRedPacketPayAmount(new BigDecimal(redPacketPayAmount));
        request.getProductQuantities().add(new ImmutablePair<Long, Integer>(productId, 1));
        return request;
    }
}


text:
package com.google.common.hash;

import com.google.common.primitives.Longs;
import sun.misc.Unsafe;
import java.nio.ByteOrder;

/**
 * Utility functions for loading and storing values from a byte array.
 *
 * @author Kevin Damm
 * @author Kyle Maddison
 */

final class LittleEndianByteArray {

  /** The instance that actually does the work; delegates to Unsafe or a pure-Java fallback. */
  private static final LittleEndianBytes byteArray;

  /**
   * Load 8 bytes into long in a little endian manner, from the substring between position and
   * position + 8. The array must have at least 8 bytes from offset (inclusive).
   *
   * @param input the input bytes
   * @param offset the offset into the array at which to start
   * @return a long of a concatenated 8 bytes
   */

  static long load64(byte[] input, int offset) {
    // We don't want this in production code as this is the most critical part of the loop.
           assert input.length >= offset + 8;
    // Delegates to the fast (unsafe) version or the fallback.
           return byteArray.getLongLittleEndian(input, offset);
  }

  /**
   * Similar to load64, but allows offset + 8 > input.length, padding the result with zeroes. This
   * has to explicitly reverse the order of the bytes as it packs them into the result which makes
   * it slower than the native version.
   *
   * @param input the input bytes
   * @param offset the offset into the array at which to start reading
   * @param length the number of bytes from the input to read
   * @return a long of a concatenated 8 bytes
   */

  static long load64Safely(byte[] input, int offset, int length) {
    long result = 0;
    // Due to the way we shift, we can stop iterating once we've run out of data, the rest
    // of the result already being filled with zeros.

    // This loop is critical to performance, so please check HashBenchmark if altering it.
    int limit = Math.min(length, 8);
    for (int i = 0; i < limit; i++) {
      // Shift value left while iterating logically through the array.
      result |= (input[offset + i] & 0xFFL) << (i * 8);
    }
    return result;
  }

  /**
   * Store 8 bytes into the provided array at the indicated offset, using the value provided.
   *
   * @param sink the output byte array
   * @param offset the offset into the array at which to start writing
   * @param value the value to write
   */

  static void store64(byte[] sink, int offset, long value) {
    // We don't want to assert in production code.
           assert offset >= 0 && offset + 8 <= sink.length;
    // Delegates to the fast (unsafe)version or the fallback.
           byteArray.putLongLittleEndian(sink, offset, value);
  }

  /**
   * Load 4 bytes from the provided array at the indicated offset.
   *
   * @param input the input bytes
   * @param offset the offset into the array at which to start
   * @return the value found in the array in the form of a long
   */

  static int load32(byte[] source, int offset) {
    // TODO(user): Measure the benefit of delegating this to LittleEndianBytes also.
    return (source[offset] & 0xFF) | ((source[offset + 1] & 0xFF) << 8)
    | ((source[offset + 2] & 0xFF) << 16)
      | ((source[offset + 3] & 0xFF) << 24);
  }

  /**
   * Indicates that the loading of Unsafe was successful and the load and store operations will be
   * very efficient. May be useful for calling code to fall back on an alternative implementation
   * that is slower than Unsafe.get/store but faster than the pure-Java mask-and-shift.
   */

  static boolean usingUnsafe() {
    return (byteArray instanceof UnsafeByteArray);
  }

  /**
   * Common interface for retrieving a 64-bit long from a little-endian byte array.
   *
   * This abstraction allows us to use single-instruction load and put when available, or fall back
   * on the slower approach of using Longs.fromBytes(byte...).
   */

  private interface LittleEndianBytes {

    long getLongLittleEndian(byte[] array, int offset);

    void putLongLittleEndian(byte[] array, int offset, long value);
  }

  /**
   * The only reference to Unsafe is in this nested class. We set things up so that if
   * Unsafe.theUnsafe is inaccessible, the attempt to load the nested class fails, and the outer
   * class's static initializer can fall back on a non-Unsafe version.
   */

  private enum UnsafeByteArray implements LittleEndianBytes {
    // Do *not* change the order of these constants!

    UNSAFE_LITTLE_ENDIAN {
      @Override
      public long getLongLittleEndian(byte[] array, int offset) {
        return theUnsafe.getLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET);
      }

      @Override
      public void putLongLittleEndian(byte[] array, int offset, long value) {
        theUnsafe.putLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET, value);
      }
    },

    UNSAFE_BIG_ENDIAN {
      @Override
      public long getLongLittleEndian(byte[] array, int offset) {
        long bigEndian = theUnsafe.getLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET);
        // The hardware is big-endian, so we need to reverse the order of the bytes.
        return Long.reverseBytes(bigEndian);
      }

      @Override
      public void putLongLittleEndian(byte[] array, int offset, long value) {
        // Reverse the order of the bytes before storing, since we're on big-endian hardware.
        long littleEndianValue = Long.reverseBytes(value);
        theUnsafe.putLong(array, (long) offset + BYTE_ARRAY_BASE_OFFSET, littleEndianValue);
      }
    };

    // Provides load and store operations that use native instructions to get better performance.

    private static final Unsafe theUnsafe;

    // The offset to the first element in a byte array.

    private static final int BYTE_ARRAY_BASE_OFFSET;

    /**
     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple
     * call to Unsafe.getUnsafe when integrating into a jdk.
     *
     * @return a sun.misc.Unsafe instance if successful
     */

    private static sun.misc.Unsafe getUnsafe() {
      try {
        return sun.misc.Unsafe.getUnsafe();
      } catch (SecurityException tryReflectionInstead) {
        // We'll try reflection instead.
      }
      try {
        return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
                                                             @Override
                                                             public sun.misc.Unsafe run() throws Exception {
                                                               Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
                                                               for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                                                                 f.setAccessible(true);
                                                                 Object x = f.get(null);
                                                                 if (k.isInstance(x)) {
                                                                   return k.cast(x);
                                                                 }
                                                               }
                                                               throw new NoSuchFieldError("the Unsafe");
                                                             }
                                                           });
      } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
      }
    }

    static {
      theUnsafe = getUnsafe();
      BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);

      // sanity check - this should never fail
      if (theUnsafe.arrayIndexScale(byte[].class) != 1) {
        throw new AssertionError();
      }
    }
  }

  /**
   * Fallback implementation for when Unsafe is not available in our current environment.
   */

  private enum JavaLittleEndianBytes implements LittleEndianBytes {
    INSTANCE {
      @Override
      public long getLongLittleEndian(byte[] source, int offset) {
        return Longs.fromBytes(source[offset + 7], source[offset + 6], source[offset + 5], source[offset + 4], source[offset + 3], source[offset + 2], source[offset + 1], source[offset]);
      }

      @Override
      public void putLongLittleEndian(byte[] sink, int offset, long value) {
        long mask = 0xFFL;
        for (int i = 0; i < 8; mask <<= 8, i++) {
          sink[offset + i] = (byte) ((value & mask) >> (i * 8));
        }
      }
    };
  }

  static {
    LittleEndianBytes theGetter;
    try {
      theGetter =
        ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)
          ? UnsafeByteArray.UNSAFE_LITTLE_ENDIAN
          : UnsafeByteArray.UNSAFE_BIG_ENDIAN;
    } catch (Throwable t) { // ensure we really catch *everything*
      theGetter = JavaLittleEndianBytes.INSTANCE;
    }
    byteArray = theGetter;
  }

  /** Deter instantiation of this class. */

  private LittleEndianByteArray() {}
}


text:
OAuth 2.0 Google Provider Changelog

## 3.0.3 - 2020-07-24

### Fixed

- Remove the `approval_prompt` from default parameters, #90

## 3.0.2 - 2019-11-16

### Fixed

- Allow for `family_name` to be undefined in user information, #79 by @majkel89

## 3.0.1 - 2018-12-28

### Fixed

- Correct conflict handling for prompt option, #69 by @mxdpeep

## 3.0.0 - 2018-12-23

### Changed

- Update to latest version of Google OAuth
- Use only OpenID Connect for user details

### Fixed

- Correct handling of selecting from multiple user accounts, #45
- Prevent conflict when using prompt option, #42

### Added

- Add "locale" to user details, #60
- Support additional scopes at construction

### Removed

- Dropped support for Google+ user details, #34 and #63

## 2.2.0 - 2018-03-19

### Added

- Hosted domain validation, #54 by @pradtke

## 2.1.0 - 2018-03-09

### Added

- OpenID Connect support, #48 by @pradtke

## 2.0.0 - 2017-01-24

### Added

- PHP 7.1 support

### Removed

- Dropped PHP 5.5 support

## 1.0.0 - 2015-08-12

- Initial release


text:
Metaclasses
-----------

Python 3 and Python 2 syntax for metaclasses are incompatible.
``future`` provides a function (from ``jinja2/_compat.py``) called
:func:`with_metaclass` that can assist with specifying metaclasses
portably across Py3 and Py2. Use it like this::

    from future.utils import with_metaclass

    class BaseForm(object):
        pass

    class FormType(type):
        pass

    class Form(with_metaclass(FormType, BaseForm)):
        pass


text:
if defined?(Facter::Core::Execution.which) && Facter::Core::Execution.which('haproxy')
  Facter.add('haproxy_version') do
    haproxy_version_cmd = 'haproxy -v 2>&1'
    haproxy_version_result = Facter::Core::Execution.execute(haproxy_version_cmd)
    setcode do
      haproxy_version_result.to_s.lines.first.strip.split(%r{HA?.Proxy})[1].strip.split(%r{version})[1].strip.split(%r{((\d+\.){2,}\d+).*})[1]
    end
  end
end


text:
class Band
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic
  field :name, type: String
  field :active, type: Mongoid::Boolean, default: true
  field :origin, type: String
  field :genres, type: Array
  field :member_count, type: Integer
  field :mems, as: :members, type: Array
  field :likes, type: Integer
  field :views, type: Integer
  field :rating, type: Float
  field :upserted, type: Mongoid::Boolean, default: false
  field :created, type: DateTime
  field :sales, type: BigDecimal
  field :y, as: :years, type: Integer
  field :founded, type: Date

  embeds_many :records, cascade_callbacks: true
  embeds_many :notes, as: :noteable, cascade_callbacks: true, validate: false
  embeds_one :label, cascade_callbacks: true

  after_upsert do |doc|
    doc.upserted = true
  end
end


text:
package io.probedock.rt.client;

import io.probedock.client.common.model.v1.TestResult;

import java.io.Serializable;

/**
 * Probe Dock RT listener to gather information and forward to the agent
 *
 * @author Laurent Prevost <laurent.prevost@probedock.io>
 */
public class Listener implements Serializable {
	public static final long serialVersionUID = 1L;

	/**
	 * The connector to communicate with the agent
	 */
	private static final Connector connector = Connector.getInstance();

	/**
	 * Notify that a test run started
	 *
	 * @param projectApiId Project API ID
	 * @param version Project version
	 * @param category Category of tests
	 */
	public void testRunStart(String projectApiId, String version, String category) {
		connector.notifyStart(projectApiId, version, category);
	}

	/**
	 * Notify that a test run ended
	 *
	 * @param projectApiId Project API ID
	 * @param version Project version
	 * @param category Category of tests
	 * @param duration Duration of the whole test run
	 */
	public void testRunEnd(String projectApiId, String version, String category, Long duration) {
		connector.notifyEnd(projectApiId, version, category, duration);
	}

	/**
	 * Notify a test result
	 *
	 * @param test The test data
	 * @param projectApidId The project API ID
	 * @param version The project version
	 * @param category The catory of tests
	 */
	public void testResult(TestResult test, String projectApidId, String version, String category) {
		connector.notifyTestResult(test, projectApidId, version, category);
	}
}


text:
/*
 * Created on Aug 5, 2005
 *
 */
package aima.learning.framework;

/**
 * @author Ravi Mohan
 *
 */
public interface Attribute {
	public String valueAsString();

	public String name();

}


text:
paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                     egr::kSlotSmallVectorSize>
fused_feedforwardGradNodeCompat::operator()(
    paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                         egr::kSlotSmallVectorSize>& grads,
    bool create_graph,
    bool is_new_grad) {
  VLOG(3) << "Running Eager Backward Node: fused_feedforwardGradNodeCompat";
  const auto& out_metas = OutputMeta();
  paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                       egr::kSlotSmallVectorSize>
      outputs(11);

  paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                       egr::kSlotSmallVectorSize>
      hooked_grads0 =
          fused_feedforwardGradNodeCompat::ApplyGradientHooks(grads);

  bool pre_layer_norm = false;
  if (attr_map_.count("pre_layer_norm")) {
    pre_layer_norm = PADDLE_GET_CONST(bool, attr_map_.at("pre_layer_norm"));
  }

  std::map<std::string, std::vector<std::shared_ptr<egr::EagerVariable>>> ins0 =
      {{"Dropout1Mask",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->Dropout1Mask_))},
       {"Dropout1Out",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->Dropout1Out_))},
       {"Dropout2Mask",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->Dropout2Mask_))},
       {"Dropout2Out",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->Dropout2Out_))},
       {"Linear1Out",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->Linear1Out_))},
       {"Linear1Weight",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->Linear1Weight_))},
       {"Linear2Weight",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->Linear2Weight_))},
       {"Out@GRAD", egr::EagerUtils::TrySyncToVars(hooked_grads0[0])},
       {"X",
        egr::EagerUtils::TrySyncToVars(
            egr::EagerUtils::RecoverTensorWrapper(&this->X_))}};

  std::map<std::string, std::vector<std::shared_ptr<egr::EagerVariable>>> outs0;

  auto Linear1Bias = egr::EagerUtils::RecoverTensorWrapper(&this->Linear1Bias_);
  if (Linear1Bias.defined())
    ins0["Linear1Bias"] = egr::EagerUtils::TrySyncToVars(Linear1Bias);

  if ((!out_metas[3].empty()) && (!(out_metas[3][0].IsStopGradient()))) {
    outs0.insert({"Linear1Weight@GRAD",
                  {std::make_shared<egr::EagerVariable>(
                      egr::Controller::Instance().GenerateUniqueName())}});
  }
  if ((!out_metas[5].empty()) && (!(out_metas[5][0].IsStopGradient()))) {
    outs0.insert({"Linear2Weight@GRAD",
                  {std::make_shared<egr::EagerVariable>(
                      egr::Controller::Instance().GenerateUniqueName())}});
  }
  if ((!out_metas[0].empty()) && (!(out_metas[0][0].IsStopGradient()))) {
    outs0.insert({"X@GRAD",
                  {std::make_shared<egr::EagerVariable>(
                      egr::Controller::Instance().GenerateUniqueName())}});
  }
  if (Linear1Bias.defined() && (!out_metas[4].empty()) &&
      (!out_metas[4][0].IsStopGradient()))
    outs0["Linear1Bias@GRAD"] = {std::make_shared<egr::EagerVariable>(
        egr::Controller::Instance().GenerateUniqueName())};

  if (pre_layer_norm) {
    auto Ln1Scale = egr::EagerUtils::RecoverTensorWrapper(&this->Ln1Scale_);
    if (Ln1Scale.defined())
      ins0["Ln1Scale"] = egr::EagerUtils::TrySyncToVars(Ln1Scale);
    auto Ln1Bias = egr::EagerUtils::RecoverTensorWrapper(&this->Ln1Bias_);
    if (Ln1Bias.defined())
      ins0["Ln1Bias"] = egr::EagerUtils::TrySyncToVars(Ln1Bias);
    auto Ln1Out = egr::EagerUtils::RecoverTensorWrapper(&this->Ln1Out_);
    if (Ln1Out.defined())
      ins0["Ln1Out"] = egr::EagerUtils::TrySyncToVars(Ln1Out);
    auto Ln1Mean = egr::EagerUtils::RecoverTensorWrapper(&this->Ln1Mean_);
    if (Ln1Mean.defined())
      ins0["Ln1Mean"] = egr::EagerUtils::TrySyncToVars(Ln1Mean);
    auto Ln1Variance =
        egr::EagerUtils::RecoverTensorWrapper(&this->Ln1Variance_);
    if (Ln1Variance.defined())
      ins0["Ln1Variance"] = egr::EagerUtils::TrySyncToVars(Ln1Variance);
    if (Ln1Scale.defined() && (!out_metas[7].empty()) &&
        (!out_metas[7][0].IsStopGradient()))
      outs0["Ln1Scale@GRAD"] = {std::make_shared<egr::EagerVariable>(
          egr::Controller::Instance().GenerateUniqueName())};
    if (Ln1Bias.defined() && (!out_metas[8].empty()) &&
        (!out_metas[8][0].IsStopGradient()))
      outs0["Ln1Bias@GRAD"] = {std::make_shared<egr::EagerVariable>(
          egr::Controller::Instance().GenerateUniqueName())};

  } else {
    auto Ln2Scale = egr::EagerUtils::RecoverTensorWrapper(&this->Ln2Scale_);
    if (Ln2Scale.defined())
      ins0["Ln2Scale"] = egr::EagerUtils::TrySyncToVars(Ln2Scale);
    auto Ln2Bias = egr::EagerUtils::RecoverTensorWrapper(&this->Ln2Bias_);
    if (Ln2Bias.defined())
      ins0["Ln2Bias"] = egr::EagerUtils::TrySyncToVars(Ln2Bias);
    auto Ln2Mean = egr::EagerUtils::RecoverTensorWrapper(&this->Ln2Mean_);
    if (Ln2Mean.defined())
      ins0["Ln2Mean"] = egr::EagerUtils::TrySyncToVars(Ln2Mean);
    auto Ln2Variance =
        egr::EagerUtils::RecoverTensorWrapper(&this->Ln2Variance_);
    if (Ln2Variance.defined())
      ins0["Ln2Variance"] = egr::EagerUtils::TrySyncToVars(Ln2Variance);
    if (Ln2Scale.defined() && (!out_metas[9].empty()) &&
        (!out_metas[9][0].IsStopGradient()))
      outs0["Ln2Scale@GRAD"] = {std::make_shared<egr::EagerVariable>(
          egr::Controller::Instance().GenerateUniqueName())};
    if (Ln2Bias.defined() && (!out_metas[10].empty()) &&
        (!out_metas[10][0].IsStopGradient()))
      outs0["Ln2Bias@GRAD"] = {std::make_shared<egr::EagerVariable>(
          egr::Controller::Instance().GenerateUniqueName())};
  }

  auto Linear2Bias = egr::EagerUtils::RecoverTensorWrapper(&this->Linear2Bias_);
  if (Linear2Bias.defined()) {
    ins0["Linear2Bias"] = egr::EagerUtils::TrySyncToVars(Linear2Bias);
    if ((!out_metas[6].empty()) && (!out_metas[6][0].IsStopGradient()))
      outs0["Linear2Bias@GRAD"] = {std::make_shared<egr::EagerVariable>(
          egr::Controller::Instance().GenerateUniqueName())};
  }

  auto& attrs_map0 = this->attr_map_;
  // Pass the entire attribute map to TraceOp
  // The underlying kernel will pickup whatever attribute they need at runtime
  egr::Controller::Instance().GetCurrentTracer()->TraceOp(
      "fused_feedforward_grad",
      ins0,
      outs0,
      attrs_map0,
      egr::Controller::Instance().GetExpectedPlace(),
      &this->default_attr_map_,
      false,
      {});

  if (outs0.find("Linear1Weight@GRAD") != outs0.end()) {
    outputs[3] = egr::EagerUtils::GetOutputs(outs0["Linear1Weight@GRAD"]);
  }
  if (outs0.find("Linear2Weight@GRAD") != outs0.end()) {
    outputs[5] = egr::EagerUtils::GetOutputs(outs0["Linear2Weight@GRAD"]);
  }
  if (outs0.find("X@GRAD") != outs0.end()) {
    outputs[0] = egr::EagerUtils::GetOutputs(outs0["X@GRAD"]);
  }
  if (outs0.find("Linear1Bias@GRAD") != outs0.end()) {
    outputs[4] = egr::EagerUtils::GetOutputs(outs0["Linear1Bias@GRAD"]);
  }

  if (pre_layer_norm) {
    if (outs0.find("Ln1Scale@GRAD") != outs0.end()) {
      outputs[7] = egr::EagerUtils::GetOutputs(outs0["Ln1Scale@GRAD"]);
    }
    if (outs0.find("Ln1Bias@GRAD") != outs0.end()) {
      outputs[8] = egr::EagerUtils::GetOutputs(outs0["Ln1Bias@GRAD"]);
    }

  } else {
    if (outs0.find("Ln2Bias@GRAD") != outs0.end()) {
      outputs[10] = egr::EagerUtils::GetOutputs(outs0["Ln2Bias@GRAD"]);
    }
    if (outs0.find("Ln2Scale@GRAD") != outs0.end()) {
      outputs[9] = egr::EagerUtils::GetOutputs(outs0["Ln2Scale@GRAD"]);
    }
  }

  if (Linear2Bias.defined()) {
    if (outs0.find("Linear2Bias@GRAD") != outs0.end()) {
      outputs[6] = egr::EagerUtils::GetOutputs(outs0["Linear2Bias@GRAD"]);
    }
  }

  if (NeedComplexToRealConversion()) HandleComplexGradToRealGrad(&outputs);
  return outputs;
}


text:
#define __CORDOVA_0_9_6 906
#define __CORDOVA_1_0_0 10000
#define __CORDOVA_1_1_0 10100
#define __CORDOVA_1_2_0 10200
#define __CORDOVA_1_3_0 10300
#define __CORDOVA_1_4_0 10400
#define __CORDOVA_1_4_1 10401
#define __CORDOVA_1_5_0 10500
#define __CORDOVA_1_6_0 10600
#define __CORDOVA_1_6_1 10601
#define __CORDOVA_1_7_0 10700
#define __CORDOVA_1_8_0 10800
#define __CORDOVA_1_8_1 10801
#define __CORDOVA_1_9_0 10900
#define __CORDOVA_2_0_0 20000
#define __CORDOVA_2_1_0 20100
#define __CORDOVA_2_2_0 20200
#define __CORDOVA_NA 99999      /* not available */

/*
 #if CORDOVA_VERSION_MIN_REQUIRED >= __CORDOVA_1_7_0
    // do something when its at least 1.7.0
 #else
    // do something else (non 1.7.0)
 #endif
 */
#ifndef CORDOVA_VERSION_MIN_REQUIRED
    #define CORDOVA_VERSION_MIN_REQUIRED __CORDOVA_2_2_0
#endif

/*
 Returns YES if it is at least version specified as NSString(X)
 Usage:
     if (IsAtLeastiOSVersion(@"5.1")) {
         // do something for iOS 5.1 or greater
     }
 */
#define IsAtLeastiOSVersion(X) ([[[UIDevice currentDevice] systemVersion] compare:X options:NSNumericSearch] != NSOrderedAscending)

#define CDV_IsIPad() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] && ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad))

#define CDV_IsIPhone5() ([[UIScreen mainScreen] bounds].size.height == 568 && [[UIScreen mainScreen] bounds].size.width == 320)

/* Return the string version of the decimal version */
#define CDV_VERSION [NSString stringWithFormat:@"%d.%d.%d", \
        (CORDOVA_VERSION_MIN_REQUIRED / 10000),             \
        (CORDOVA_VERSION_MIN_REQUIRED % 10000) / 100,       \
        (CORDOVA_VERSION_MIN_REQUIRED % 10000) % 100]

#ifdef __clang__
    #define CDV_DEPRECATED(version, msg) __attribute__((deprecated("Deprecated in Cordova " #version ". " msg)))
#else
    #define CDV_DEPRECATED(version, msg) __attribute__((deprecated()))
#endif


text:
apetools.connections.lineproducer
=================================

.. automodule:: apetools.connections.lineproducer


text:
<?php

class Bert_Rpc_Service
{
	public $host;
	public $port;
	public $timeout;

	public function __construct($host, $port, $timeout = null)
	{
		$this->host = $host;
		$this->port = $port;
		$this->timeout = $timeout;
	}

	public function call($options = null)
	{
		$this->_verifyOptions($options);
		return new Bert_Rpc_Request($this, Bert::a('call'), $options);
	}

	public function cast($options = null)
	{
		$this->_verifyOptions($options);
		return new Bert_Rpc_Request($this, Bert::a('cast'), $options);
	}

	// --

	private function _verifyOptions($options)
	{
		if (isset($options))
		{
			if ($cache = $options['cache'])
			{
				if ($cache[0] != 'validation' || !is_string($cache[1]))
				{
					throw new Exception('Valid :cache args are ["validation", String]');
				}
			}
			else
			{
				throw new Exception('Valid options are "cache"');
			}
		}
	}
}


text:
#include "pch.h"

namespace net { namespace http { namespace client {
	std::string os_client_info()
	{
		static const char* platform =  "Linux "
#if defined (__arm__)
			"ARM"
#elif defined (__aarch64__)
			"ARM64"
#elif defined (__i386__)
			"x86"
#elif defined (__x86_64__)
			"x86_64"
#else
#error Unknown architecture
#endif
			;
		return platform;
	}
}}}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_marginBottom="2dp"
    android:background="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="150dp">
    <TextView
        android:textSize="20dp"
        android:textStyle="bold"
        android:gravity="center"
        android:text="头部布局"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


text:
"""Tests for Keras Vis utils."""

from tensorflow.python import keras
from tensorflow.python.keras.utils import vis_utils
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test

class ModelToDotFormatTest(test.TestCase):

  def test_plot_model_cnn(self):
    model = keras.Sequential()
    model.add(
        keras.layers.Conv2D(
            filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
    model.add(keras.layers.Flatten(name='flat'))
    model.add(keras.layers.Dense(5, name='dense'))
    dot_img_file = 'model_1.png'
    try:
      vis_utils.plot_model(
          model, to_file=dot_img_file, show_shapes=True, show_dtype=True)
      self.assertTrue(file_io.file_exists_v2(dot_img_file))
      file_io.delete_file_v2(dot_img_file)
    except ImportError:
      pass

  def test_plot_model_with_wrapped_layers_and_models(self):
    inputs = keras.Input(shape=(None, 3))
    lstm = keras.layers.LSTM(6, return_sequences=True, name='lstm')
    x = lstm(inputs)
    # Add layer inside a Wrapper
    bilstm = keras.layers.Bidirectional(
        keras.layers.LSTM(16, return_sequences=True, name='bilstm'))
    x = bilstm(x)
    # Add model inside a Wrapper
    submodel = keras.Sequential(
        [keras.layers.Dense(32, name='dense', input_shape=(None, 32))]
    )
    wrapped_dense = keras.layers.TimeDistributed(submodel)
    x = wrapped_dense(x)
    # Add shared submodel
    outputs = submodel(x)
    model = keras.Model(inputs, outputs)
    dot_img_file = 'model_2.png'
    try:
      vis_utils.plot_model(
          model,
          to_file=dot_img_file,
          show_shapes=True,
          show_dtype=True,
          expand_nested=True)
      self.assertTrue(file_io.file_exists_v2(dot_img_file))
      file_io.delete_file_v2(dot_img_file)
    except ImportError:
      pass

  def test_plot_model_with_add_loss(self):
    inputs = keras.Input(shape=(None, 3))
    outputs = keras.layers.Dense(1)(inputs)
    model = keras.Model(inputs, outputs)
    model.add_loss(math_ops.reduce_mean(outputs))
    dot_img_file = 'model_3.png'
    try:
      vis_utils.plot_model(
          model,
          to_file=dot_img_file,
          show_shapes=True,
          show_dtype=True,
          expand_nested=True)
      self.assertTrue(file_io.file_exists_v2(dot_img_file))
      file_io.delete_file_v2(dot_img_file)
    except ImportError:
      pass

    model = keras.Sequential([
        keras.Input(shape=(None, 3)), keras.layers.Dense(1)])
    model.add_loss(math_ops.reduce_mean(model.output))
    dot_img_file = 'model_4.png'
    try:
      vis_utils.plot_model(
          model,
          to_file=dot_img_file,
          show_shapes=True,
          show_dtype=True,
          expand_nested=True)
      self.assertTrue(file_io.file_exists_v2(dot_img_file))
      file_io.delete_file_v2(dot_img_file)
    except ImportError:
      pass

if __name__ == '__main__':
  test.main()


text:
// A simple sky box rendering class for OpenGL 2.0 contexts
// Renders an infinitely distant sky box suitable for rendering
// as the last thing in the frame.
class SkyBox
{
public:
    SkyBox();

    // Frees up the skybox's resources
    ~SkyBox();

    // Creates the skybox's resources
    bool Create();

    // Draw the skybox using the view/projection matrix passed in
    // (which should include the camera rotation but not the camera
    // translation in order to position the skybox at the camera)
    void Draw(const GLdouble *viewProj);

    // Retrieves the underlying cube map, useful for environment mapping
    GLuint GetCubemap() const {
        return cubeMap;
    }

    bool SetCubeMap(const char* cubeMap);
private:
    bool CreateBuffers();
    bool LoadShader();

    GLuint cubeMap;
    GLuint vboID, idxID;
    GLhandleARB vertexShader, fragmentShader, shaderProgram;
    GLint viewProjLoc, cubeMapLoc;
};


text:
<?php

define('HOSTNAME', 'http://localhost:8123/up/');

session_start();

// Change these configuration options if needed, see above descriptions for info.
$enable_jsonp    = false;
$enable_native   = false;
$valid_url_regex = '/.*/';

// ############################################################################

$path = $_GET['path'];
$url = HOSTNAME . $path;

$ch = curl_init($url);

$client_headers = array();
$client_headers[] = 'X-Forwarded-For: ' . $_SERVER['REMOTE_ADDR'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $client_headers);

if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
    $postText = trim(file_get_contents('php://input'));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postText);
}

$cookie = array();
foreach ($_COOKIE as $key => $value) {
    $cookie[] = $key . '=' . $value;
}
$cookie[] = SID;
$cookie = implode('; ', $cookie);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);

//curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);

list($header, $contents) = preg_split('/([\r\n][\r\n])\\1/', curl_exec($ch), 2);

$status = curl_getinfo($ch);

curl_close($ch);

// Split header text into an array.
$header_text = preg_split('/[\r\n]+/', $header);

// Propagate headers to response.
foreach ($header_text as $header) {
    if (preg_match('/^(?:Content-Type|Content-Language|Set-Cookie):/i', $header)) {
        header($header);
    }
}

print $contents;


text:
<?php
namespace Styde\Providers;

use Styde\SessionArrayDriver;
use Styde\SessionManager;
use Styde\Container\Provider;

class SessionProvider extends Provider
{

    public function register()
    {
        $this->container->singleton('session', function () {
            $data = [
                'user_data' => [
                    'name' => 'Duilio',
                    'role' => 'teacher'
                ]
            ];

            $driver = new SessionArrayDriver($data);
            return new SessionManager($driver);
        });
    }
}


text:
package at.ac.uibk.fiba.wang.spring4uli.rest.web;

import at.ac.uibk.fiba.wang.spring4uli.rest.H2TestBase;
import at.ac.uibk.fiba.wang.spring4uli.rest.web.message.PersonFW;
import at.ac.uibk.fiba.wang.spring4uli.rest.web.message.ProjectFull;
import at.ac.uibk.fiba.wang.spring4uli.rest.web.message.ProjectFullMsg;
import at.ac.uibk.fiba.wang.spring4uli.rest.web.message.ProjectListMsg;
import at.ac.uibk.fiba.wang.spring4uli.testhelper.TestData;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ProjectControllerTest extends H2TestBase {

    @Autowired
    private ProjectController controller;

    @Test
    public void t01_writeData() throws Exception {
        TestData.writeData(personRepo, projectRepo);
    }

    private static Long adamId, bertaId, chrisId, danaId;

    @Test
    public void t02_listProjects() {
        ResponseEntity<ProjectListMsg> resp = controller.listAll();
        Assert.assertEquals(2, resp.getBody().projectList.size());
        adamId = personRepo.findByName("Adam").getId();
        bertaId = personRepo.findByName("Berta").getId();
        chrisId = personRepo.findByName("Chris").getId();
        danaId = personRepo.findByName("Dana").getId();
    }

    private static Long projectId;

    @Test
    public void t03_createNew() {
        PersonFW leader = new PersonFW(adamId, null, null, null);
        List<PersonFW> labors = Arrays.asList(
                new PersonFW(bertaId, null, null,  null),
                new PersonFW(danaId, null, null,  null)
        );
        ProjectFull full = new ProjectFull(null, "Project three", "Destroy the universe",
                leader, labors, Collections.emptyList());
        ResponseEntity<ProjectFullMsg> resp = controller.create(full);
        Assert.assertEquals(HttpStatus.OK, resp.getStatusCode());
        Assert.assertEquals(2, resp.getBody().project.laborators.size());
        Assert.assertTrue(resp.getBody().project.leader.name!=null);
        projectId = resp.getBody().project.id;
//        Assert.assertEquals(Long.valueOf(3L), resp.getBody().project.id);
    }

    @Test
    public void t04_createNewFail() {
        ProjectFull full = new ProjectFull(null, "Project three", "blah", null, null, null);
        ResponseEntity<ProjectFullMsg> resp = controller.create(full);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, resp.getStatusCode());
    }

    @Test
    public void t05_update() {
        PersonFW leader = new PersonFW(bertaId, null, null, null);
        List<PersonFW> labors = Arrays.asList(
                new PersonFW(chrisId, null, null,  null),
                new PersonFW(danaId, null, null,  null)
        );
        ProjectFull full = new ProjectFull(projectId, "Project three", "Destroy the universe",
                leader, labors, Collections.emptyList());
        ResponseEntity<ProjectFullMsg> resp = controller.update(full, projectId);
        ProjectFull result = resp.getBody().project;
        Assert.assertEquals("Berta", result.leader.name);
        Assert.assertTrue(result.laborators.stream().map(x -> x.name).collect(Collectors.toSet()).contains("Chris"));
    }

    @Test
    public void t06_delete() {
        ResponseEntity<ProjectListMsg> resp = controller.delete(projectId);
        Assert.assertEquals(2, resp.getBody().projectList.size());
    }

    @Test
    public void t99_clearData() throws Exception {
        TestData.clearData(personRepo, projectRepo);
    }

}


text:
import React from 'react';
import Cmd from './Cmd';

export const path = '/cmd';
export const action = async (state) => {
   const title = 'Command Prompt';
   state.context.onSetTitle(title);
   return <Cmd title={title} />;
};


text:
package de.fakeller.palladio.builder.repository.impl;

import de.fakeller.palladio.builder.repository.InterfaceBuilder;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

public class ComponentBuilderTest {

    private RepositoryBuilderImpl repo;
    private ComponentBuilderImpl booking;

    private InterfaceBuilder i_payment;
    private InterfaceBuilder i_reservation;

    @Before
    public void setup() {
        this.repo = new RepositoryBuilderImpl();
        this.booking = (ComponentBuilderImpl) this.repo.withComponent("Booking");
        this.i_payment = this.repo.withInterface("IPaymentGateway");
        this.i_reservation = this.repo.withInterface("IRoomReservation");
    }

    @Test
    public void testProvideInterface() {
        assertEquals(0, this.booking.getReference().getProvidedRoles_InterfaceProvidingEntity().size());
        this.booking.provides(this.i_reservation);
        assertEquals(1, this.booking.getReference().getProvidedRoles_InterfaceProvidingEntity().size());
        assertSame(this.booking.getReference(), this.booking.getReference().getProvidedRoles_InterfaceProvidingEntity().get(0).getProvidingEntity_ProvidedRole());
    }

    @Test
    public void testRequireInterface() {
        assertEquals(0, this.booking.getReference().getRequiredRoles_InterfaceRequiringEntity().size());
        this.booking.requires(this.i_payment);
        assertEquals(1, this.booking.getReference().getRequiredRoles_InterfaceRequiringEntity().size());
        assertSame(this.booking.getReference(), this.booking.getReference().getRequiredRoles_InterfaceRequiringEntity().get(0).getRequiringEntity_RequiredRole());
    }
}


text:
ACCEPTED

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

#### Published in
Dansk bot. Ark. 19(no. 2): 167 (1960)

#### Original name
Corticium lacteolum Bourdot, 1922

### Remarks
null


text:
#ifndef L_STDLIB_H
#define L_STDLIB_H 1

#include <sys/cdefs.h>

#include <stdint.h>

#include "liballoc/liballoc.h"

//#define malloc kmalloc
//#define free kfree

#ifdef __cplusplus
extern "C" {
#endif

__attribute__((__noreturn__))
void abort_impl(const char* file, size_t line, const char* fun);

__attribute__((__noreturn__))
void _abort();

#define abort() abort_impl(__FILE__, __LINE__, __PRETTY_FUNCTION__)

int atoi (const char *);
long atol (const char *);
long long atoll (const char *);
double atof (const char *);

float strtof (const char *__restrict, char **__restrict);
double strtod (const char *__restrict, char **__restrict);
long double strtold (const char *__restrict, char **__restrict);

long strtol (const char *__restrict, char **__restrict, int);
unsigned long strtoul (const char *__restrict, char **__restrict, int);
long long strtoll (const char *__restrict, char **__restrict, int);
unsigned long long strtoull (const char *__restrict, char **__restrict, int);

int rand (void);
void srand (unsigned);

int atexit (void (*) (void));
void _Exit (int);
int at_quick_exit (void (*) (void));
void quick_exit (int);

char *getenv (const char *);

int system (const char *);

void *bsearch (const void *, const void *, size_t, size_t, int (*)(const void *, const void *));
void qsort (void *, size_t, size_t, int (*)(const void *, const void *));

//int abs (int);
long labs (long);
long long llabs (long long);

typedef struct { int quot, rem; } div_t;
typedef struct { long quot, rem; } ldiv_t;
typedef struct { long long quot, rem; } lldiv_t;

div_t div (int, int);
ldiv_t ldiv (long, long);
lldiv_t lldiv (long long, long long);

int mblen (const char *, size_t);
int mbtowc (wchar_t *__restrict, const char *__restrict, size_t);
int wctomb (char *, wchar_t);
size_t mbstowcs (wchar_t *__restrict, const char *__restrict, size_t);
size_t wcstombs (char *__restrict, const wchar_t *__restrict, size_t);

#ifdef __cplusplus
}
#endif

#endif


text:
package org.estatio.module.capex.integtests.app.taskreminder;

import java.net.URI;

import javax.inject.Inject;

import org.joda.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;

import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.services.repository.RepositoryService;

import org.estatio.module.asset.fixtures.person.enums.Person_enum;
import org.estatio.module.capex.app.taskreminder.TaskReminderService;
import org.estatio.module.capex.integtests.CapexModuleIntegTestAbstract;
import org.estatio.module.party.dom.role.PartyRoleTypeEnum;
import org.estatio.module.party.dom.role.PartyRoleTypeRepository;
import org.estatio.module.task.dom.task.Task;
import org.estatio.module.task.dom.task.TaskRepository;

import static org.assertj.core.api.Assertions.assertThat;

public class TaskReminderService_IntegTest extends CapexModuleIntegTestAbstract {

    @Before
    public void setupData() {

        runFixtureScript(new FixtureScript() {
            @Override
            protected void execute(final FixtureScript.ExecutionContext ec) {
                ec.executeChildren(this,
                        Person_enum.OlivePropertyManagerFr);
            }
        });

    }

    @Test
    public void deeplink_for_test() throws Exception {

        // given
        assertThat(taskRepository.listAll()).isEmpty();
        Task task = new Task(partyRoleTypeRepository.findByKey(PartyRoleTypeEnum.INCOMING_INVOICE_MANAGER.getKey()), null, "x", LocalDateTime
                .now(), "x", null);
        repositoryService.persistAndFlush(task);
        transactionService.nextTransaction();
        assertThat(taskRepository.listAll()).hasSize(1);

        // when

        final URI uri = taskReminderService.deepLinkFor(task);

        // then
        assertThat(uri.toString()).startsWith("https://estatio.int.ecpnv.com/wicket/entity/task.Task:");
        final String oidString = uri.toString().replace("https://estatio.int.ecpnv.com/wicket/entity/task.Task:", "");
        assertThat(oidString.length()).isGreaterThanOrEqualTo(1);
        assertThat(oidString.matches("\\d*"));

    }

    @Inject TaskReminderService taskReminderService;
    @Inject PartyRoleTypeRepository partyRoleTypeRepository;
    @Inject RepositoryService repositoryService;
    @Inject TaskRepository taskRepository;

}


text:
package edu.cmu.lti.oaqa.baseqa.providers.kb;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.resource.Resource;

/**
 * An implementation of this interface can identify the list of synonyms for a given concept ID.
 * It should also override the {@link #accept(String)} method to filter the ID that is supported
 * by the particular synonym expansion provider.
 *
 * @author Zi Yang created on 4/20/15
 */
public interface SynonymExpansionProvider extends Resource {

  boolean accept(String id);

  Set<String> getSynonyms(String id) throws AnalysisEngineProcessException;

  Map<String, Set<String>> getSynonyms(Collection<String> ids)
          throws AnalysisEngineProcessException;

}


text:
abstract class Num<T> {
  static final Num<Long> longNum = new Num<Long>() {
    public Long zero() {
      return 0L;
    }

    public Long increment(Long t) {
      return t + 1;
    }

    public Long fromInt(int x) {
      return (long)x;
    }

    public Long sqrt(Long t) {
      return (long)Math.sqrt(t);
    }

    public Long add(Long a, Long b) {
      return a + b;
    }

    public Long min(Long a, Long b) {
      return Math.min(a, b);
    }

    public boolean lessThan(Long a, Long b) {
      return a < b;
    }

    public Long modulo(Long a, Long b) {
      return a % b;
    }

    public boolean eq(Long a, Long b) {
      return a.equals(b);
    }
  };

  abstract T zero();
  abstract T increment(T t);
  abstract T fromInt(int x);
  abstract T sqrt(T t);
  abstract T add(T a, T b);
  abstract T min(T a, T b);
  abstract boolean lessThan(T a, T b);
  abstract T modulo(T a, T b);
  abstract boolean eq(T a, T b);
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: FileIO</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Module
          FileIO

            In:

                lib/svengali/file_io.rb

Methods

      get_contents_remote
      is_exist
      pull_a_file
      pull_dir
      pull_files
      push_a_file
      push_dir
      push_files
      write_contents_remote

Constants

          BUFFER_SIZE
          =
          1024

Public Instance methods

          get_contents_remote(remote_filepath_str)

[Source]

# File lib/svengali/file_io.rb, line 84
  def get_contents_remote(remote_filepath_str)
    debug_p("get_contents_remote from #{remote_filepath_str}")
    handle = @sftp_session.open!(remote_filepath_str)
    contents = String.new()
    offset = 0
    while (data = @sftp_session.read!(handle, offset, BUFFER_SIZE)) != nil
      contents += data
      offset += BUFFER_SIZE
    end
    @sftp_session.close!(handle)

    return contents
  end

          is_exist(remote_path)

return -> boolean :

[Source]

# File lib/svengali/file_io.rb, line 72
  def is_exist(remote_path)
    begin
      @sftp_session.stat!(remote_path) { |response|
        #returns whether exists or not
        next response.ok?
      }
    rescue => e
      return false
    end
  end

          pull_a_file(remote_path,local_path)

[Source]

# File lib/svengali/file_io.rb, line 14
  def pull_a_file(remote_path,local_path)
    debug_p("pull_a_file from #{remote_path} to #{local_path}")

    begin
      @sftp_session.download!(remote_path,local_path)
    rescue
      debug_p remote_path + " is not found on remote!!"
      return nil
    end
  end

          pull_dir(remote_path,local_path)

[Source]

# File lib/svengali/file_io.rb, line 61
  def pull_dir(remote_path,local_path)
    debug_p("pull_dir from #{remote_path} to #{local_path}")
    begin
      @sftp_session.download!(remote_path,local_path,:recursive => true)
    rescue
      debug_p remote_path + " is not found on remote!!"
      return nil
    end
  end

          pull_files(remote_path,local_path)

pull files on specified dir. only one level.

[Source]

# File lib/svengali/file_io.rb, line 38
  def pull_files(remote_path,local_path)
    debug_p("pull_files from #{remote_path} to #{local_path}")
    @sftp_session.dir.foreach(remote_path){ |path|
      #unless path.name == "." || path.name == ".."
      #not directory
      unless /^d/ =~ path.longname
          @sftp_session.download!(remote_path + "/" + path.name,local_path + "/" + path.name)
      end
      #end
    }
  end

          push_a_file(local_path,remote_path)

[Source]

# File lib/svengali/file_io.rb, line 9
  def push_a_file(local_path,remote_path)
    debug_p("push_a_file from #{local_path} to #{remote_path}")
    @sftp_session.upload!(local_path,remote_path)
  end

          push_dir(local_path,remote_path)

Note: if there is a directory which has same name with local_path,
remote_directory is removed before coping directory

[Source]

# File lib/svengali/file_io.rb, line 51
  def push_dir(local_path,remote_path)
    debug_p("push_dir from #{local_path} to #{remote_path}")
    begin
      @sftp_session.upload!(local_path,remote_path)
    rescue
      @ssh.exec!("rm -rf #{remote_path}")
      retry
    end
  end

          push_files(local_path,remote_path)

push files on specified dir. only one level. directories are not copied.

[Source]

# File lib/svengali/file_io.rb, line 27
  def push_files(local_path,remote_path)
    debug_p("push_files from #{local_path} to #{remote_path}")
    local_dir = Dir.new(local_path)
    local_dir.each{ |path|
      unless File::ftype(local_path + "/" + path) == "directory"
        @sftp_session.upload!(local_path + "/" + path,remote_path + "/" + path)
      end
    }
  end

          write_contents_remote(remote_filepath_str,contents_str)

over writes contens from the start

[Source]

# File lib/svengali/file_io.rb, line 99
  def write_contents_remote(remote_filepath_str,contents_str)
    debug_p("write_contents_remote to #{remote_filepath_str}")
    handle = @sftp_session.open!(remote_filepath_str,"w")
    @sftp_session.write!(handle, 0, contents_str)
    @sftp_session.close!(handle)
  end

[Validate]


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.croogster.metbzr" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" android-versionCode="1">
  <name>MetBazaar</name>
  <description>Platform for Metal Traders</description>
  <author email="developer@metbazaar.com" href="http://metbazaar.com/">Croogster</author>
  <content src="index.html" />
  <access origin="*" />
  <allow-navigation href="http://*/*" />
  <allow-navigation href="https://*/*" />
  <allow-intent href="http://*/*" />
  <allow-intent href="https://*/*" />
  <allow-intent href="tel:*" />
  <allow-intent href="sms:*" />
  <allow-intent href="mailto:*" />
  <allow-intent href="geo:*" />
  <platform name="android">
    <allow-intent href="market:*" />
    <icon src="resources\android\icon\drawable-ldpi-icon.png" density="ldpi" />
    <icon src="resources\android\icon\drawable-mdpi-icon.png" density="mdpi" />
    <icon src="resources\android\icon\drawable-hdpi-icon.png" density="hdpi" />
    <icon src="resources\android\icon\drawable-xhdpi-icon.png" density="xhdpi" />
    <icon src="resources\android\icon\drawable-xxhdpi-icon.png" density="xxhdpi" />
    <icon src="resources\android\icon\drawable-xxxhdpi-icon.png" density="xxxhdpi" />
    <splash src="resources\android\splash\drawable-land-ldpi-screen.png" density="land-ldpi" />
    <splash src="resources\android\splash\drawable-land-mdpi-screen.png" density="land-mdpi" />
    <splash src="resources\android\splash\drawable-land-hdpi-screen.png" density="land-hdpi" />
    <splash src="resources\android\splash\drawable-land-xhdpi-screen.png" density="land-xhdpi" />
    <splash src="resources\android\splash\drawable-land-xxhdpi-screen.png" density="land-xxhdpi" />
    <splash src="resources\android\splash\drawable-land-xxxhdpi-screen.png" density="land-xxxhdpi" />
    <splash src="resources\android\splash\drawable-port-ldpi-screen.png" density="port-ldpi" />
    <splash src="resources\android\splash\drawable-port-mdpi-screen.png" density="port-mdpi" />
    <splash src="resources\android\splash\drawable-port-hdpi-screen.png" density="port-hdpi" />
    <splash src="resources\android\splash\drawable-port-xhdpi-screen.png" density="port-xhdpi" />
    <splash src="resources\android\splash\drawable-port-xxhdpi-screen.png" density="port-xxhdpi" />
    <splash src="resources\android\splash\drawable-port-xxxhdpi-screen.png" density="port-xxxhdpi" />
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
  </platform>
  <preference name="webviewbounce" value="false" />
  <preference name="UIWebViewBounce" value="false" />
  <preference name="DisallowOverscroll" value="true" />
  <preference name="android-minSdkVersion" value="16" />
  <preference name="BackupWebStorage" value="none" />
  <preference name="SplashMaintainAspectRatio" value="true" />
  <preference name="ShowSplashScreenSpinner" value="false" />
  <preference name="FadeSplashScreen" value="true" />
  <preference name="FadeSplashScreenDuration" value="1000" />
  <preference name="AutoHideSplashScreen" value="false" />
  <preference name="SplashShowOnlyFirstTime" value="false" />
  <preference name="SplashScreen" value="screen" />
  <preference name="SplashScreenDelay" value="30000" />
  <preference name="android-targetSdkVersion" value="25" />
  <feature name="StatusBar">
    <param name="ios-package" onload="true" value="CDVStatusBar" />
  </feature>
  <plugin name="ionic-plugin-keyboard" spec="~2.2.1" />
  <plugin name="cordova-plugin-whitelist" spec="1.3.1" />
  <plugin name="cordova-plugin-console" spec="1.0.5" />
  <plugin name="cordova-plugin-statusbar" spec="2.2.1" />
  <plugin name="cordova-plugin-device" spec="1.1.4" />
  <plugin name="cordova-plugin-splashscreen" spec="~4.0.1" />
  <plugin name="cordova-plugin-camera" version="2.3.1" />
  <plugin name="cordova-plugin-compat" version="1.1.0" />
  <plugin name="mx.ferreyra.callnumber" version="0.0.2" />
  <plugin name="cordova-plugin-googleplus" spec="~5.1.1">
    <variable name="REVERSED_CLIENT_ID" value="468979984175-ercgmvtfdla9n21e8dqu46gn7fp94msl.apps.googleusercontent.com" />
  </plugin>
  <plugin name="cordova-sqlite-storage" spec="~2.0.2" />
  <plugin name="cordova-plugin-x-socialsharing" version="5.1.7" />
  <plugin name="phonegap-plugin-push" spec="1.8.2">
    <variable name="SENDER_ID" value="79899062384" />
  </plugin>
  <plugin name="cordova-plugin-facebook4" spec="~1.7.4">
    <variable name="APP_ID" value="123456789" />
    <variable name="APP_NAME" value="myApplication" />
  </plugin>
  <plugin name="com.xmartlabs.cordova.market" version="1.1" />
  <icon src="resources\android\icon\drawable-xhdpi-icon.png" />

</widget>


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 com.facebook.presto.cost;

import com.facebook.presto.Session;
import com.facebook.presto.spi.plan.PlanNode;
import com.facebook.presto.sql.planner.TypeProvider;
import com.facebook.presto.sql.planner.iterative.IterativeOptimizer;
import com.facebook.presto.sql.planner.iterative.Lookup;

public interface StatsCalculator
{
    /**
     * Calculate stats for the {@code node}.
     *
     * @param node The node to compute stats for.
     * @param sourceStats The stats provider for any child nodes' stats, if needed to compute stats for the {@code node}
     * @param lookup Lookup to be used when resolving source nodes, allowing stats calculation to work within {@link IterativeOptimizer}
     * @param types
     */
    PlanNodeStatsEstimate calculateStats(
            PlanNode node,
            StatsProvider sourceStats,
            Lookup lookup,
            Session session,
            TypeProvider types);
}


text:
<div id="<?php print $params['id']; ?>" class="media-player" style="width:<?php print $params['width']; ?>; height:<?php print $params['height']; ?>;">

  <?php if ($params['showController']): ?>

00:00

  <?php endif; ?>


text:
var botBuilder = require('claudia-bot-builder');
var excuse = require('huh');

module.exports = botBuilder(function(request) {
    console.log(request);
    return 'Thanks for sending ' + request.text  +
      '. Your message is very important to us, but ' +
      excuse.get();
});


text:
create table ACT_RU_VARIABLE (
    ID_ NVARCHAR2(64) not null,
    REV_ INTEGER,
    TYPE_ NVARCHAR2(255) not null,
    NAME_ NVARCHAR2(255) not null,
    EXECUTION_ID_ NVARCHAR2(64),
    PROC_INST_ID_ NVARCHAR2(64),
    TASK_ID_ NVARCHAR2(64),
    SCOPE_ID_ NVARCHAR2(255),
    SUB_SCOPE_ID_ NVARCHAR2(255),
    SCOPE_TYPE_ NVARCHAR2(255),
    BYTEARRAY_ID_ NVARCHAR2(64),
    DOUBLE_ NUMBER(*,10),
    LONG_ NUMBER(19,0),
    TEXT_ NVARCHAR2(2000),
    TEXT2_ NVARCHAR2(2000),
    primary key (ID_)
);

create index ACT_IDX_RU_VAR_SCOPE_ID_TYPE on ACT_RU_VARIABLE(SCOPE_ID_, SCOPE_TYPE_);
create index ACT_IDX_RU_VAR_SUB_ID_TYPE on ACT_RU_VARIABLE(SUB_SCOPE_ID_, SCOPE_TYPE_);

create index ACT_IDX_VAR_BYTEARRAY on ACT_RU_VARIABLE(BYTEARRAY_ID_);
alter table ACT_RU_VARIABLE
    add constraint ACT_FK_VAR_BYTEARRAY
    foreign key (BYTEARRAY_ID_)
    references ACT_GE_BYTEARRAY (ID_);

insert into ACT_GE_PROPERTY values ('variable.schema.version', '6.7.2.3', 1);


text:
export const JSXSyntax = {
    JSXAttribute: 'JSXAttribute',
    JSXClosingElement: 'JSXClosingElement',
    JSXElement: 'JSXElement',
    JSXEmptyExpression: 'JSXEmptyExpression',
    JSXExpressionContainer: 'JSXExpressionContainer',
    JSXIdentifier: 'JSXIdentifier',
    JSXMemberExpression: 'JSXMemberExpression',
    JSXNamespacedName: 'JSXNamespacedName',
    JSXOpeningElement: 'JSXOpeningElement',
    JSXSpreadAttribute: 'JSXSpreadAttribute',
    JSXText: 'JSXText'
};


text:
.user_profile_link_span a {
	/* font-weight: bold; */
	/* color: #3B5998!important; */
}

.username_listing a {
	font-weight: bold;
	color: #3B5998!important;
}

.listing_rate {
	width: 130px;
	background: none;
}

.listing_rate_detail {
	width: 180px;
	background: none;
}

div.row_title_image_header_body {
    margin-left: 138px;
    min-height: 128px !important;
}

a.advlink {
	font-weight: bold;
}

.content .row_title_info .extra_info {
	margin: 0px!important;
	padding-top: 0px!important;
	padding-bottom: 0px!important;
}


text:
package com.gmail.thelimeglass.Npcs;

import org.bukkit.entity.EntityType;
import org.bukkit.event.Event;
import org.eclipse.jdt.annotation.Nullable;

import com.gmail.thelimeglass.Utils.Annotations.Config;
import com.gmail.thelimeglass.Utils.Annotations.FullConfig;
import com.gmail.thelimeglass.Utils.Annotations.MainConfig;
import com.gmail.thelimeglass.Utils.Annotations.PropertyType;
import com.gmail.thelimeglass.Utils.Annotations.Syntax;

import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.npc.NPCRegistry;

@Syntax({"[a] [new] (npc|citizen) [with] (name[d]|id|string) %string% [and] [with] [entity [type]] %string%", "[a] [new] npc [with] [entity [type]] %string% [and] [with] (name[d]|id|string) %string%"})
@Config("PluginHooks.Npc")
@FullConfig
@MainConfig
@PropertyType(ExpressionType.SIMPLE)
public class ExprNewNpc extends SimpleExpression<NPC>{

	private Expression<String> name, type;
	@Override
	public Class<? extends NPC> getReturnType() {
		return NPC.class;
	}
	@Override
	public boolean isSingle() {
		return true;
	}
	@SuppressWarnings("unchecked")
	@Override
	public boolean init(Expression<?>[] e, int matchedPattern, Kleenean isDelayed, ParseResult parser) {
		if (matchedPattern == 0) {
			name = (Expression<String>) e[0];
			type = (Expression<String>) e[1];
		} else {
			type = (Expression<String>) e[0];
			name = (Expression<String>) e[1];
		}
		return true;
	}
	@Override
	public String toString(@Nullable Event e, boolean arg1) {
		return "[a] [new] npc [with] (name[d]|id|string) %string% [and] [with] [entity [type]] %string%";
	}
	@Override
	@Nullable
	protected NPC[] get(Event e) {
		NPCRegistry registry = CitizensAPI.getNPCRegistry();
		return new NPC[]{registry.createNPC(EntityType.valueOf(type.getSingle(e)), name.getSingle(e))};
	}
}


text:
package org.apache.druid.timeline;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;

/**
 * DataSegment object plus the overshadowed status for the segment. An immutable object.
 *
 * SegmentWithOvershadowedStatus's {@link #compareTo} method considers only the {@link SegmentId}
 * of the DataSegment object.
 */
public class SegmentWithOvershadowedStatus implements Comparable<SegmentWithOvershadowedStatus>
{
  private final boolean overshadowed;
  /**
   * dataSegment is serialized "unwrapped", i.e. it's properties are included as properties of
   * enclosing class. If in future, if {@Code SegmentWithOvershadowedStatus} were to extend {@link DataSegment},
   * there will be no change in the serialized format.
   */
  @JsonUnwrapped
  private final DataSegment dataSegment;

  @JsonCreator
  public SegmentWithOvershadowedStatus(
      @JsonProperty("dataSegment") DataSegment dataSegment,
      @JsonProperty("overshadowed") boolean overshadowed
  )
  {
    this.dataSegment = dataSegment;
    this.overshadowed = overshadowed;
  }

  @JsonProperty
  public boolean isOvershadowed()
  {
    return overshadowed;
  }

  @JsonProperty
  public DataSegment getDataSegment()
  {
    return dataSegment;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (!(o instanceof SegmentWithOvershadowedStatus)) {
      return false;
    }
    final SegmentWithOvershadowedStatus that = (SegmentWithOvershadowedStatus) o;
    if (!dataSegment.equals(that.dataSegment)) {
      return false;
    }
    if (overshadowed != (that.overshadowed)) {
      return false;
    }
    return true;
  }

  @Override
  public int hashCode()
  {
    int result = dataSegment.hashCode();
    result = 31 * result + Boolean.hashCode(overshadowed);
    return result;
  }

  @Override
  public int compareTo(SegmentWithOvershadowedStatus o)
  {
    return dataSegment.getId().compareTo(o.dataSegment.getId());
  }
}


text:
// -----------------------------------------------------------------------
// <copyright file="Selector.cs" company="Steven Kirk">
// Copyright 2014 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace Perspex.Styling
{
    using System;
    using System.Collections.Generic;

    public class Selector
    {
        private Func<IStyleable, SelectorMatch> evaluate;

        private bool inTemplate;

        private bool stopTraversal;

        private string description;

        public Selector()
        {
            this.evaluate = _ => SelectorMatch.True;
        }

        public Selector(
            Selector previous,
            Func<IStyleable, SelectorMatch> evaluate,
            string selectorString,
            bool inTemplate = false,
            bool stopTraversal = false)
            : this()
        {
            Contract.Requires<ArgumentNullException>(previous != null);

            this.Previous = previous;
            this.evaluate = evaluate;
            this.SelectorString = selectorString;
            this.inTemplate = inTemplate || previous.inTemplate;
            this.stopTraversal = stopTraversal;
        }

        public Selector Previous
        {
            get;
            private set;
        }

        public string SelectorString
        {
            get;
            set;
        }

        public Selector MovePrevious()
        {
            return this.stopTraversal ? null : this.Previous;
        }

        public SelectorMatch Match(IStyleable control)
        {
            List<IObservable<bool>> inputs = new List<IObservable<bool>>();
            Selector selector = this;

            while (selector != null)
            {
                if (selector.inTemplate && control.TemplatedParent == null)
                {
                    return SelectorMatch.False;
                }

                var match = selector.evaluate(control);

                if (match.ImmediateResult == false)
                {
                    return match;
                }
                else if (match.ObservableResult != null)
                {
                    inputs.Add(match.ObservableResult);
                }

                selector = selector.MovePrevious();
            }

            if (inputs.Count > 0)
            {
                return new SelectorMatch(new StyleActivator(inputs));
            }
            else
            {
                return SelectorMatch.True;
            }
        }

        public override string ToString()
        {
            if (this.description == null)
            {
                string result = string.Empty;

                if (this.Previous != null)
                {
                    result = this.Previous.ToString();
                }

                this.description = result + this.SelectorString;
            }

            return this.description;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="grid_item_width">180dp</dimen>
    <dimen name="grid_item_height">244dp</dimen>
</resources>


text:
<?php

namespace Magento\Catalog\Test\Fixture;

use Mtf\Fixture\InjectableFixture;

/**
 * Class CatalogAttributeSet
 * Catalog Attribute Set fixture
 */
class CatalogAttributeSet extends InjectableFixture
{
    /**
     * @var string
     */
    protected $repositoryClass = 'Magento\Catalog\Test\Repository\CatalogAttributeSet';

    /**
     * @var string
     */
    protected $handlerInterface = 'Magento\Catalog\Test\Handler\CatalogAttributeSet\CatalogAttributeSetInterface';

    protected $defaultDataSet = [
        'attribute_set_name' => 'Default_attribute_set_%isolation%',
        'skeleton_set' => ['dataSet' => 'default'],
    ];

    protected $attribute_set_id = [
        'attribute_code' => 'attribute_set_id',
        'backend_type' => 'smallint',
        'is_required' => '1',
        'default_value' => '',
        'input' => '',
    ];

    protected $entity_type_id = [
        'attribute_code' => 'entity_type_id',
        'backend_type' => 'smallint',
        'is_required' => '',
        'default_value' => '0',
        'input' => '',
    ];

    protected $attribute_set_name = [
        'attribute_code' => 'attribute_set_name',
        'backend_type' => 'varchar',
        'is_required' => '',
        'default_value' => '',
        'input' => '',
    ];

    protected $sort_order = [
        'attribute_code' => 'sort_order',
        'backend_type' => 'smallint',
        'is_required' => '',
        'default_value' => '0',
        'input' => '',
    ];

    protected $skeleton_set = [
        'attribute_code' => 'skeleton_set',
        'backend_type' => 'varchar',
        'is_required' => '',
        'default_value' => '',
        'input' => '',
        'source' => 'Magento\Catalog\Test\Fixture\CatalogAttributeSet\SkeletonSet',
    ];

    protected $assigned_attributes = [
        'attribute_code' => 'assigned_attributes',
        'backend_type' => 'virtual',
        'source' => 'Magento\Catalog\Test\Fixture\CatalogAttributeSet\AssignedAttributes',
    ];

    protected $group = [
        'attribute_code' => 'group',
        'backend_type' => 'virtual',
    ];

    public function getAttributeSetId()
    {
        return $this->getData('attribute_set_id');
    }

    public function getEntityTypeId()
    {
        return $this->getData('entity_type_id');
    }

    public function getAttributeSetName()
    {
        return $this->getData('attribute_set_name');
    }

    public function getSortOrder()
    {
        return $this->getData('sort_order');
    }

    public function getSkeletonSet()
    {
        return $this->getData('skeleton_set');
    }

    public function getAssignedAttributes()
    {
        return $this->getData('assigned_attributes');
    }

    public function getGroup()
    {
        return $this->getData('group');
    }
}


text:
package com.amazonaws.services.glacier.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.glacier.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * AbortVaultLockResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AbortVaultLockResultJsonUnmarshaller implements Unmarshaller<AbortVaultLockResult, JsonUnmarshallerContext> {

    public AbortVaultLockResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        AbortVaultLockResult abortVaultLockResult = new AbortVaultLockResult();

        return abortVaultLockResult;
    }

    private static AbortVaultLockResultJsonUnmarshaller instance;

    public static AbortVaultLockResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new AbortVaultLockResultJsonUnmarshaller();
        return instance;
    }
}


text:
require 'spec_helper'

describe Fundraiser::Contribution do
  describe ".create_from_amazon_ipn" do
    it "creates the contribution" do
      Fundraiser::Contribution.should_receive(:create).
          with(:email => "aws@crowdint.com", :reference => "3",
               :request_params => success_ipn_params, :amount => 12500 )

      Fundraiser::Contribution.create_from_amazon_ipn success_ipn_params
    end
  end

  describe ".amazon_amount_to_cents" do
    it "returns the amount as cents integer" do
      Fundraiser::Contribution.
          amazon_amount_to_cents("USD 125.000000").should eq 12500
    end
  end

  describe ".total_contributed" do
    it "returns the sums of the amounts divided by 100" do
      Fundraiser::Contribution.should_receive(:sum).and_return 1000
      Fundraiser::Contribution.total_contributed.should eq 10
    end
  end
end


text:
while [[ $# > 0 ]]
do
	key="$1"

	case $key in
    	--stage-schema)
			STAGE_SCHEMA="$2"
		    shift
		    ;;
    	--target-schema)
			TARGET_SCHEMA="$2"
		    shift
		    ;;
	    *)
    		echo "Usage: `basename $0` --stage-schema [stage schema] --target-schema [target schema]"
			exit 1
		    ;;
	esac
	shift
done

if [ "a$STAGE_SCHEMA" == "a" ]
then
	echo "Stage schema is not set."
	exit 1
fi

if [ "a$TARGET_SCHEMA" == "a" ]
then
	echo "Target schema is not set."
	exit 2
fi
# /Input parameters

cat <<END | psql
	BEGIN;

	TRUNCATE ${TARGET_SCHEMA}.parcel CASCADE;

	DROP INDEX IF EXISTS ${TARGET_SCHEMA}.parcel_geom_idx;
	ALTER TABLE ${TARGET_SCHEMA}.parcel DROP CONSTRAINT parcel_pkey;

	INSERT INTO ${TARGET_SCHEMA}.parcel (
		id,
		label,
		area,
		geom,
		area_code
	)
	SELECT
		replace(cp.gml_id, 'CP.', '')::bigint,
		cp.label,
		cp.areavalue::integer,
		ST_Multi(cp.wkb_geometry),
        substring(cp.nationalcadastralreference from 0 for 7)::integer
	FROM ${STAGE_SCHEMA}.cadastralparcel cp
    JOIN ${TARGET_SCHEMA}.area a ON (substring(cp.nationalcadastralreference from 0 for 7)::integer = a.code);

	CREATE INDEX ON ${TARGET_SCHEMA}.parcel USING gist (geom);
	ALTER TABLE ${TARGET_SCHEMA}.parcel ADD PRIMARY KEY (id);

	COMMIT;
END


text:
package org.mafagafogigante.dungeon.entity.items;

import org.mafagafogigante.dungeon.date.DungeonTimeParser;
import org.mafagafogigante.dungeon.entity.Integrity;
import org.mafagafogigante.dungeon.entity.Luminosity;
import org.mafagafogigante.dungeon.entity.TagSet.InvalidTagException;
import org.mafagafogigante.dungeon.entity.Weight;
import org.mafagafogigante.dungeon.game.Id;
import org.mafagafogigante.dungeon.game.NameFactory;
import org.mafagafogigante.dungeon.io.JsonObjectFactory;
import org.mafagafogigante.dungeon.logging.DungeonLogger;
import org.mafagafogigante.dungeon.util.Percentage;

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Set;

/**
 * An ItemPresetFactory based on JSON files.
 */
public class JsonItemPresetFactory implements ItemPresetFactory {

  private final String filename;

  public JsonItemPresetFactory(String filename) {
    this.filename = filename;
  }

  /**
   * Creates a Set of tags from an array of Strings.
   *
   * @param enumClass the Class of the enum
   * @param array a JSON array of strings
   * @param <E> an Enum type
   * @return a Set of Item.Tag
   */
  private static <E extends Enum<E>> Set<E> tagSetFromArray(Class<E> enumClass, JsonArray array) {
    Set<E> set = EnumSet.noneOf(enumClass);
    for (JsonValue value : array) {
      String tag = value.asString();
      try {
        set.add(Enum.valueOf(enumClass, tag));
      } catch (IllegalArgumentException fatal) {
        // Guarantee that bugged resource files are not going to make it to a release.
        String message = "invalid tag '" + tag + "' found.";
        throw new InvalidTagException(message, fatal);
      }
    }
    return set;
  }

  @Override
  public Collection<ItemPreset> getItemPresets() {
    JsonObject objects = JsonObjectFactory.makeJsonObject(filename);
    Collection<ItemPreset> itemPresets = new ArrayList<>();
    for (JsonValue value : objects.get("items").asArray()) {
      JsonObject itemObject = value.asObject();
      ItemPreset preset = new ItemPreset();
      Id id = new Id(itemObject.get("id").asString());
      preset.setId(id);
      preset.setType(itemObject.get("type").asString());
      preset.setName(NameFactory.fromJsonObject(itemObject.get("name").asObject()));
      for (Item.Tag tag : tagSetFromArray(Item.Tag.class, itemObject.get("tags").asArray())) {
        preset.addTag(tag);
      }
      preset.setUnique(itemObject.getBoolean("unique", false));
      if (itemObject.get("decompositionPeriod") != null) {
        long seconds = DungeonTimeParser.parsePeriod(itemObject.get("decompositionPeriod").asString()).getSeconds();
        preset.setPutrefactionPeriod(seconds);
      }
      JsonObject integrity = itemObject.get("integrity").asObject();
      preset.setIntegrity(new Integrity(integrity.get("current").asInt(), integrity.get("maximum").asInt()));
      preset.setVisibility(Percentage.fromString(itemObject.get("visibility").asString()));
      if (itemObject.get("luminosity") != null) {
        preset.setLuminosity(new Luminosity(Percentage.fromString(itemObject.get("luminosity").asString())));
      }
      preset.setWeight(Weight.newInstance(itemObject.get("weight").asDouble()));
      preset.setDamage(itemObject.get("damage").asInt());
      preset.setHitRate(Percentage.fromString(itemObject.get("hitRate").asString()));
      preset.setIntegrityDecrementOnHit(itemObject.get("integrityDecrementOnHit").asInt());
      if (itemObject.get("nutrition") != null) {
        preset.setNutrition(itemObject.get("nutrition").asInt());
      }
      if (itemObject.get("integrityDecrementOnEat") != null) {
        preset.setIntegrityDecrementOnEat(itemObject.get("integrityDecrementOnEat").asInt());
      }
      if (preset.hasTag(Item.Tag.BOOK)) {
        preset.setText(itemObject.get("text").asString());
      }
      if (preset.hasTag(Item.Tag.DRINKABLE)) {
        preset.setDrinkableDoses(itemObject.get("drinkableDoses").asInt());
        preset.setDrinkableHealing(itemObject.get("drinkableHealing").asInt());
        preset.setIntegrityDecrementPerDose(itemObject.get("integrityDecrementPerDose").asInt());
        preset.setEffectTime(itemObject.get("effectTime").asInt());
      }
      if (itemObject.get("spell") != null) {
        preset.setSpellId(itemObject.get("spell").asString());
      }
      itemPresets.add(preset);
    }
    DungeonLogger.info("Loaded " + itemPresets.size() + " item presets.");
    return itemPresets;
  }

}