text:
"""
Hyperparameter tuning with Ray Tune
===================================

Hyperparameter tuning can make the difference between an average model and a highly
accurate one. Often simple things like choosing a different learning rate or changing
a network layer size can have a dramatic impact on your model performance.

Fortunately, there are tools that help with finding the best combination of parameters.
`Ray Tune <https://docs.ray.io/en/master/tune.html>`_ is an industry standard tool for
distributed hyperparameter tuning. Ray Tune includes the latest hyperparameter search
algorithms, integrates with TensorBoard and other analysis libraries, and natively
supports distributed training through `Ray's distributed machine learning engine
<https://ray.io/>`_.

In this tutorial, we will show you how to integrate Ray Tune into your PyTorch
training workflow. We will extend `this tutorial from the PyTorch documentation
<https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html>`_ for training
a CIFAR10 image classifier.

As you will see, we only need to add some slight modifications. In particular, we
need to

1. wrap data loading and training in functions,
2. make some network parameters configurable,
3. add checkpointing (optional),
4. and define the search space for the model tuning

|

To run this tutorial, please make sure the following packages are
installed:

-  ``ray[tune]``: Distributed hyperparameter tuning library
-  ``torchvision``: For the data transformers

Setup / Imports
---------------
Let's start with the imports:
"""
from functools import partial
import numpy as np
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import random_split
import torchvision
import torchvision.transforms as transforms
import ray
from ray import tune
from ray.tune import CLIReporter
from ray.tune.schedulers import ASHAScheduler

######################################################################
# Most of the imports are needed for building the PyTorch model. Only the last three
# imports are for Ray Tune.
#
# Data loaders
# ------------
# We wrap the data loaders in their own function and pass a global data directory.
# This way we can share a data directory between different trials.

def load_data(data_dir="./data"):
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])

    trainset = torchvision.datasets.CIFAR10(
        root=data_dir, train=True, download=True, transform=transform)

    testset = torchvision.datasets.CIFAR10(
        root=data_dir, train=False, download=True, transform=transform)

    return trainset, testset

######################################################################
# Configurable neural network
# ---------------------------
# We can only tune those parameters that are configurable. In this example, we can specify
# the layer sizes of the fully connected layers:

class Net(nn.Module):
    def __init__(self, l1=120, l2=84):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, l1)
        self.fc2 = nn.Linear(l1, l2)
        self.fc3 = nn.Linear(l2, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

######################################################################
# The train function
# ------------------
# Now it gets interesting, because we introduce some changes to the example `from the PyTorch
# documentation <https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html>`_.
#
# We wrap the training script in a function ``train_cifar(config, checkpoint_dir=None, data_dir=None)``.
# As you can guess, the ``config`` parameter will receive the hyperparameters we would like to
# train with. The ``checkpoint_dir`` parameter is used to restore checkpoints. The ``data_dir`` specifies
# the directory where we load and store the data, so multiple runs can share the same data source.
#
# .. code-block:: python
#
#     net = Net(config["l1"], config["l2"])
#
#     if checkpoint_dir:
#         model_state, optimizer_state = torch.load(
#             os.path.join(checkpoint_dir, "checkpoint"))
#         net.load_state_dict(model_state)
#         optimizer.load_state_dict(optimizer_state)
#
# The learning rate of the optimizer is made configurable, too:
#
# .. code-block:: python
#
#     optimizer = optim.SGD(net.parameters(), lr=config["lr"], momentum=0.9)
#
# We also split the training data into a training and validation subset. We thus train on
# 80% of the data and calculate the validation loss on the remaining 20%. The batch sizes
# with which we iterate through the training and test sets are configurable as well.
#
# Adding (multi) GPU support with DataParallel
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Image classification benefits largely from GPUs. Luckily, we can continue to use
# PyTorch's abstractions in Ray Tune. Thus, we can wrap our model in ``nn.DataParallel``
# to support data parallel training on multiple GPUs:
#
# .. code-block:: python
#
#     device = "cpu"
#     if torch.cuda.is_available():
#         device = "cuda:0"
#         if torch.cuda.device_count() > 1:
#             net = nn.DataParallel(net)
#     net.to(device)
#
# By using a ``device`` variable we make sure that training also works when we have
# no GPUs available. PyTorch requires us to send our data to the GPU memory explicitly,
# like this:
#
# .. code-block:: python
#
#     for i, data in enumerate(trainloader, 0):
#         inputs, labels = data
#         inputs, labels = inputs.to(device), labels.to(device)
#
# The code now supports training on CPUs, on a single GPU, and on multiple GPUs. Notably, Ray
# also supports `fractional GPUs <https://docs.ray.io/en/master/using-ray-with-gpus.html#fractional-gpus>`_
# so we can share GPUs among trials, as long as the model still fits on the GPU memory. We'll come back
# to that later.
#
# Communicating with Ray Tune
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# The most interesting part is the communication with Ray Tune:
#
# .. code-block:: python
#
#     with tune.checkpoint_dir(epoch) as checkpoint_dir:
#         path = os.path.join(checkpoint_dir, "checkpoint")
#         torch.save((net.state_dict(), optimizer.state_dict()), path)
#
#     tune.report(loss=(val_loss / val_steps), accuracy=correct / total)
#
# Here we first save a checkpoint and then report some metrics back to Ray Tune. Specifically,
# we send the validation loss and accuracy back to Ray Tune. Ray Tune can then use these metrics
# to decide which hyperparameter configuration lead to the best results. These metrics
# can also be used to stop bad performing trials early in order to avoid wasting
# resources on those trials.
#
# The checkpoint saving is optional, however, it is necessary if we wanted to use advanced
# schedulers like
# `Population Based Training <https://docs.ray.io/en/master/tune/tutorials/tune-advanced-tutorial.html>`_.
# Also, by saving the checkpoint we can later load the trained models and validate them
# on a test set.
#
# Full training function
# ~~~~~~~~~~~~~~~~~~~~~~
#
# The full code example looks like this:

def train_cifar(config, checkpoint_dir=None, data_dir=None):
    net = Net(config["l1"], config["l2"])

    device = "cpu"
    if torch.cuda.is_available():
        device = "cuda:0"
        if torch.cuda.device_count() > 1:
            net = nn.DataParallel(net)
    net.to(device)

    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(net.parameters(), lr=config["lr"], momentum=0.9)

    if checkpoint_dir:
        model_state, optimizer_state = torch.load(
            os.path.join(checkpoint_dir, "checkpoint"))
        net.load_state_dict(model_state)
        optimizer.load_state_dict(optimizer_state)

    trainset, testset = load_data(data_dir)

    test_abs = int(len(trainset) * 0.8)
    train_subset, val_subset = random_split(
        trainset, [test_abs, len(trainset) - test_abs])

    trainloader = torch.utils.data.DataLoader(
        train_subset,
        batch_size=int(config["batch_size"]),
        shuffle=True,
        num_workers=8)
    valloader = torch.utils.data.DataLoader(
        val_subset,
        batch_size=int(config["batch_size"]),
        shuffle=True,
        num_workers=8)

    for epoch in range(10):  # loop over the dataset multiple times
        running_loss = 0.0
        epoch_steps = 0
        for i, data in enumerate(trainloader, 0):
            # get the inputs; data is a list of [inputs, labels]
            inputs, labels = data
            inputs, labels = inputs.to(device), labels.to(device)

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            outputs = net(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            # print statistics
            running_loss += loss.item()
            epoch_steps += 1
            if i % 2000 == 1999:  # print every 2000 mini-batches
                print("[%d, %5d] loss: %.3f" % (epoch + 1, i + 1,
                                                running_loss / epoch_steps))
                running_loss = 0.0

        # Validation loss
        val_loss = 0.0
        val_steps = 0
        total = 0
        correct = 0
        for i, data in enumerate(valloader, 0):
            with torch.no_grad():
                inputs, labels = data
                inputs, labels = inputs.to(device), labels.to(device)

                outputs = net(inputs)
                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()

                loss = criterion(outputs, labels)
                val_loss += loss.cpu().numpy()
                val_steps += 1

        with tune.checkpoint_dir(epoch) as checkpoint_dir:
            path = os.path.join(checkpoint_dir, "checkpoint")
            torch.save((net.state_dict(), optimizer.state_dict()), path)

        tune.report(loss=(val_loss / val_steps), accuracy=correct / total)
    print("Finished Training")

######################################################################
# As you can see, most of the code is adapted directly from the original example.
#
# Test set accuracy
# -----------------
# Commonly the performance of a machine learning model is tested on a hold-out test
# set with data that has not been used for training the model. We also wrap this in a
# function:

def test_accuracy(net, device="cpu"):
    trainset, testset = load_data()

    testloader = torch.utils.data.DataLoader(
        testset, batch_size=4, shuffle=False, num_workers=2)

    correct = 0
    total = 0
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = net(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    return correct / total

######################################################################
# The function also expects a ``device`` parameter, so we can do the
# test set validation on a GPU.
#
# Configuring the search space
# ----------------------------
# Lastly, we need to define Ray Tune's search space. Here is an example:
#
# .. code-block:: python
#
#     config = {
#         "l1": tune.sample_from(lambda _: 2**np.random.randint(2, 9)),
#         "l2": tune.sample_from(lambda _: 2**np.random.randint(2, 9)),
#         "lr": tune.loguniform(1e-4, 1e-1),
#         "batch_size": tune.choice([2, 4, 8, 16])
#     }
#
# The ``tune.sample_from()`` function makes it possible to define your own sample
# methods to obtain hyperparameters. In this example, the ``l1`` and ``l2`` parameters
# should be powers of 2 between 4 and 256, so either 4, 8, 16, 32, 64, 128, or 256.
# The ``lr`` (learning rate) should be uniformly sampled between 0.0001 and 0.1. Lastly,
# the batch size is a choice between 2, 4, 8, and 16.
#
# At each trial, Ray Tune will now randomly sample a combination of parameters from these
# search spaces. It will then train a number of models in parallel and find the best
# performing one among these. We also use the ``ASHAScheduler`` which will terminate bad
# performing trials early.
#
# We wrap the ``train_cifar`` function with ``functools.partial`` to set the constant
# ``data_dir`` parameter. We can also tell Ray Tune what resources should be
# available for each trial:
#
# .. code-block:: python
#
#     gpus_per_trial = 2
#     # ...
#     result = tune.run(
#         partial(train_cifar, data_dir=data_dir),
#         resources_per_trial={"cpu": 8, "gpu": gpus_per_trial},
#         config=config,
#         num_samples=num_samples,
#         scheduler=scheduler,
#         progress_reporter=reporter,
#         checkpoint_at_end=True)
#
# You can specify the number of CPUs, which are then available e.g.
# to increase the ``num_workers`` of the PyTorch ``DataLoader`` instances. The selected
# number of GPUs are made visible to PyTorch in each trial. Trials do not have access to
# GPUs that haven't been requested for them - so you don't have to care about two trials
# using the same set of resources.
#
# Here we can also specify fractional GPUs, so something like ``gpus_per_trial=0.5`` is
# completely valid. The trials will then share GPUs among each other.
# You just have to make sure that the models still fit in the GPU memory.
#
# After training the models, we will find the best performing one and load the trained
# network from the checkpoint file. We then obtain the test set accuracy and report
# everything by printing.
#
# The full main function looks like this:

def main(num_samples=10, max_num_epochs=10, gpus_per_trial=2):
    data_dir = os.path.abspath("./data")
    load_data(data_dir)
    config = {
        "l1": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)),
        "l2": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)),
        "lr": tune.loguniform(1e-4, 1e-1),
        "batch_size": tune.choice([2, 4, 8, 16])
    }
    scheduler = ASHAScheduler(
        metric="loss",
        mode="min",
        max_t=max_num_epochs,
        grace_period=1,
        reduction_factor=2)
    reporter = CLIReporter(
        # parameter_columns=["l1", "l2", "lr", "batch_size"],
        metric_columns=["loss", "accuracy", "training_iteration"])
    result = tune.run(
        partial(train_cifar, data_dir=data_dir),
        resources_per_trial={"cpu": 2, "gpu": gpus_per_trial},
        config=config,
        num_samples=num_samples,
        scheduler=scheduler,
        progress_reporter=reporter)

    best_trial = result.get_best_trial("loss", "min", "last")
    print("Best trial config: {}".format(best_trial.config))
    print("Best trial final validation loss: {}".format(
        best_trial.last_result["loss"]))
    print("Best trial final validation accuracy: {}".format(
        best_trial.last_result["accuracy"]))

    best_trained_model = Net(best_trial.config["l1"], best_trial.config["l2"])
    device = "cpu"
    if torch.cuda.is_available():
        device = "cuda:0"
        if gpus_per_trial > 1:
            best_trained_model = nn.DataParallel(best_trained_model)
    best_trained_model.to(device)

    best_checkpoint_dir = best_trial.checkpoint.value
    model_state, optimizer_state = torch.load(os.path.join(
        best_checkpoint_dir, "checkpoint"))
    best_trained_model.load_state_dict(model_state)

    test_acc = test_accuracy(best_trained_model, device)
    print("Best trial test set accuracy: {}".format(test_acc))

if __name__ == "__main__":
    # You can change the number of GPUs per trial here:
    ray.init(num_cpus=2)  # for testing purposes only
    main(num_samples=2, max_num_epochs=2, gpus_per_trial=0)

######################################################################
# If you run the code, an example output could look like this:
#
# .. code-block::
#
#     Number of trials: 10 (10 TERMINATED)
#     +-----+------+------+-------------+--------------+---------+------------+--------------------+
#     | ... |   l1 |   l2 |          lr |   batch_size |    loss |   accuracy | training_iteration |
#     |-----+------+------+-------------+--------------+---------+------------+--------------------|
#     | ... |   64 |    4 | 0.00011629  |            2 | 1.87273 |     0.244  |                  2 |
#     | ... |   32 |   64 | 0.000339763 |            8 | 1.23603 |     0.567  |                  8 |
#     | ... |    8 |   16 | 0.00276249  |           16 | 1.1815  |     0.5836 |                 10 |
#     | ... |    4 |   64 | 0.000648721 |            4 | 1.31131 |     0.5224 |                  8 |
#     | ... |   32 |   16 | 0.000340753 |            8 | 1.26454 |     0.5444 |                  8 |
#     | ... |    8 |    4 | 0.000699775 |            8 | 1.99594 |     0.1983 |                  2 |
#     | ... |  256 |    8 | 0.0839654   |           16 | 2.3119  |     0.0993 |                  1 |
#     | ... |   16 |  128 | 0.0758154   |           16 | 2.33575 |     0.1327 |                  1 |
#     | ... |   16 |    8 | 0.0763312   |           16 | 2.31129 |     0.1042 |                  4 |
#     | ... |  128 |   16 | 0.000124903 |            4 | 2.26917 |     0.1945 |                  1 |
#     +-----+------+------+-------------+--------------+---------+------------+--------------------+
#
#
#     Best trial config: {'l1': 8, 'l2': 16, 'lr': 0.00276249, 'batch_size': 16, 'data_dir': '...'}
#     Best trial final validation loss: 1.181501
#     Best trial final validation accuracy: 0.5836
#     Best trial test set accuracy: 0.5806
#
# Most trials have been stopped early in order to avoid wasting resources.
# The best performing trial achieved a validation accuracy of about 58%, which could
# be confirmed on the test set.
#
# So that's it! You can now tune the parameters of your PyTorch models.


text:
// https://github.com/electron/electron/blob/master/docs/api/desktop-capturer.md

declare namespace Electron {
	/**
	 * This module can be used to get available sources that can be used to be captured with getUserMedia.
	 */
	interface DesktopCapturer {
		/**
		 * Starts a request to get all desktop sources.
		 *
		 * Note: There is no guarantee that the size of source.thumbnail is always
		 * the same as the thumnbailSize in options. It also depends on the scale of the screen or window.
		 */
		getSources(options: DesktopCapturerOptions, callback: (error: Error, sources: DesktopCapturerSource[]) => any): void;
	}

	interface DesktopCapturerOptions {
		/**
		 * The types of desktop sources to be captured.
		 */
		types?: ('screen' | 'window')[];
		/**
		 * The suggested size that thumbnail should be scaled.
		 * Default: {width: 150, height: 150}
		 */
		thumbnailSize?: Dimension;
	}

	interface DesktopCapturerSource {
		/**
		 * The id of the captured window or screen used in navigator.webkitGetUserMedia.
		 * The format looks like window:XX or screen:XX where XX is a random generated number.
		 */
		id: string;
		/**
		 * The described name of the capturing screen or window.
		 * If the source is a screen, the name will be Entire Screen or Screen <index>;
		 * if it is a window, the name will be the window's title.
		 */
		name: string;
		/**
		 * A thumbnail image.
		 */
		thumbnail: NativeImage;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package sudokucf;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;

/**
 * Represents a sudoku square. Mainly dealing with the possible choices still available. This class does not deal with the position of the square.
 */
public class Square {

  /**
   * All the possible values (i.e. [1;9]). It is a SortedSet for displaying purpose: I like the squares to be in the correct order.
   */
  public static final SortedSet<Integer> RANGE_1_9 = new TreeSet<>();
  public static final SortedSet<Integer> RANGE_1_3 = new TreeSet<>(); // FIXME Should be somewhere else

  static {
    IntStream.rangeClosed(1, 9).forEach(RANGE_1_9::add);
    IntStream.rangeClosed(1, 3).forEach(RANGE_1_3::add);
  }

  /**
   * The current possible choices for the square. It starts being the full [1;9] range, and hopefully ends with a single value: the result!
   */
  private final Set<Integer> possibilities = new HashSet<>();

  /**
   * A mapping between integer values and some CF. These CF will be triggered when it appears that an integer value cannot be the resolved value of this Square. While it may sound redundant, the CF
   * will return the impossible Integer in order to ease the job downstream.
   */
  private final Map<Integer, CompletableFuture<Integer>> impossibilities = new HashMap<>();

  /**
   * A CF that triggers when the Square is resolved. The future value is the Integer value of the Square.
   */
  private final CompletableFuture<Integer> resolved = new CompletableFuture<>();

  /**
   * Horizontal coordinate
   */
  private Integer i;

  /**
   * Vertical coordinate
   */
  private Integer j;

  public Integer getI() {
    return this.i;
  }

  public Integer getJ() {
    return this.j;
  }

  public Square(Integer i, Integer j) {
    this.i = i;
    this.j = j;
    IntStream.rangeClosed(1, 9).forEach(this.possibilities::add);
    IntStream.rangeClosed(1, 9).forEach(k -> this.impossibilities.put(k, new CompletableFuture<>()));
  }

  /**
   * Getter to {@link #resolved}.
   */
  public CompletableFuture<Integer> getResolved() {
    return this.resolved;
  }

  /**
   * Is the square resolved.
   *
   * @return See description.
   */
  public boolean isResolved() {
    return this.possibilities.size() == 1;
  }

  /**
   * Returns the trigger associated to impossible that will fire when impossible becomes impossible.
   *
   * @param impossible
   *          The integer for which we want the impossibility trigger.
   * @return The CF trigger.
   */
  public CompletableFuture<Integer> getImpossible(Integer impossible) {
    assert (RANGE_1_9.contains(impossible));
    return this.impossibilities.get(impossible);
  }

  /**
   * Checks that one unique value remains in {@link #possibilities} and returns this value.
   *
   * @return The solution for this square.
   */
  private Integer getResolvedValue() {
    assert (this.possibilities.size() == 1);
    Integer resolvedValue = this.possibilities.iterator().next();
    return resolvedValue;
  }

  /**
   * Completes the {@link #resolved} CF with the unique remaining values from the {@link #possibilities}.
   */
  private void completeResolved() {
    if (!this.resolved.isDone()) {
      this.resolved.complete(this.getResolvedValue());
    }
  }

  /**
   * Checks if the square is resolved before completing {@link #resolved}.
   */
  private void completeResolvedIfNeeded() {
    if (this.possibilities.size() == 1) {
      this.completeResolved();
    }
  }

  /**
   * Defines the solution for the square.
   *
   * @param solution
   *          The solution of the square in the sudoku.
   */
  public void resolve(Integer solution) {
    assert (!this.resolved.isDone()); // FIXME I shall check that value is the same and log a possible error...
    assert (this.possibilities.contains(solution));

    RANGE_1_9.stream().filter(i -> !i.equals(solution)).forEach(this::remove);

    assert (this.getResolvedValue().equals(solution));
  }

  /**
   * Removes the impossible choice from the possibilities of this square. Fires the {@link #resolved} if it has to.
   *
   * @param impossible
   *          The integer that cannot be part of the solution in this square.
   */
  public void remove(Integer impossible) {
    if (this.possibilities.size() != 1) {
      this.possibilities.remove(impossible);
      this.impossibilities.get(impossible).complete(impossible);
      this.completeResolvedIfNeeded();
    }
  }

  /**
   * Checks if the integer i is still possible for the square.
   *
   * @param i
   *          The integer we want to check.
   * @return See description.
   */
  public boolean isPossible(Integer i) {
    return this.possibilities.contains(i);
  }
}


text:
Deface::Override.new(virtual_path: 'spree/users/show',
  name: 'add_loyalty_points_balance_to_account_page',
  insert_after: "#user-info",
  text: "

<%= Spree.t(:loyalty_points_balance) %>

<%= @user.loyalty_points_balance %> (<%= link_to Spree.t(:details), spree.loyalty_points_path %>)

  ")


text:
<!DOCTYPE html>
<!--
Copyright (C) 2017 The Android Open Source Project

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.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-project-api</title>

<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../../test/common-test-setup.html"/>
<link rel="import" href="../gr-endpoint-decorator/gr-endpoint-decorator.html">
<link rel="import" href="gr-project-api.html">

<script>void(0);</script>

<test-fixture id="basic">
  <template>
    <gr-endpoint-decorator name="project-command">
    </gr-endpoint-decorator>
  </template>
</test-fixture>

<script>
  suite('gr-project-api tests', () => {
    let sandbox;
    let projectApi;

    setup(() => {
      sandbox = sinon.sandbox.create();
      let plugin;
      Gerrit.install(p => { plugin = p; }, '0.1',
          'http://test.com/plugins/testplugin/static/test.js');
      sandbox.stub(Gerrit, '_arePluginsLoaded').returns(true);
      projectApi = plugin.project();
    });

    teardown(() => {
      projectApi = null;
      sandbox.restore();
    });

    test('exists', () => {
      assert.isOk(projectApi);
    });

    test('works', done => {
      const attachedStub = sandbox.stub();
      const tapStub = sandbox.stub();
      projectApi
          .createCommand('foo', attachedStub)
          .onTap(tapStub);
      const element = fixture('basic');
      flush(() => {
        assert.isTrue(attachedStub.called);
        const pluginCommand = element.$$('gr-plugin-project-command');
        assert.isOk(pluginCommand);
        const command = pluginCommand.$$('gr-project-command');
        assert.isOk(command);
        assert.equal(command.title, 'foo');
        assert.isFalse(tapStub.called);
        MockInteractions.tap(command.$$('gr-button'));
        assert.isTrue(tapStub.called);
        done();
      });
    });
  });
</script>


text:
lang:   NL
title:  Elementair
answer: ^(12|35|47)$
load:   kaart = [12, 47, 35]
ok:     Ok
error:  Bijna
---

We hebben ons lijstje met bingo getallen in variabele kaart staan. Hoe krijgen we
de getallen er weer één voor één uit?

We hebben __max__ al gebruikt om het hoogste getal te bepalen. Je kunt ook __first__
of __last__ gebruiken voor het eerste en laatste element van de lijst.
Maar hoe haal je er één specifiek element uit?

### [ ]
Ruby gebruikt hiervoor de vierkant teksthaken.
Deze worden trouwens heel vaak gebruikt in Ruby.

Ok, we halen de bingo getallen één voor één op:

    puts kaart[0]
    puts kaart[1]
    puts kaart[2]

Maar waarom [0], [1], [2] ? En niet [1], [2] and [3] ?

Heeft dat met dat Japanse Zen gedoe te maken?
Nee hoor, computer programmeurs beginnen nou eenmaal graag met tellen vanaf
nul. En niet alleen Ruby programmeurs maar alle programmeurs. Het heeft
zelfs een naam: _zero based indexing_.

> Tip: mocht je het vergeten zijn, je kunt de __Copy__ knop gebruiken om de
> voorbeeldcode over te nemen in de editor.


text:
Create New contact

        <form class="form-horizontal" data-ng-submit="create()" novalidate>
            <fieldset>

                    Name

                        <input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>

                  Zip Code

                    <input type="text" data-ng-model="zip_code" id="zip_code" class="form-control" placeholder="Zip Code" required>

                  County

                    <input type="text" data-ng-model="county" id="county" class="form-control" placeholder="County" required>

                  Email

                    <input type="text" data-ng-model="email" id="email" class="form-control" placeholder="Email" required>

                  Phone Number

                    <input type="text" data-ng-model="phone_number" id="phone_number" class="form-control" placeholder="Phone Number" required>

                  <input ng-model="Submit_Button" type="submit" value="Submit" class="btn btn-default">

            </fieldset>
        </form>


text:
---
author: mc
layout: post
cover: 'assets/images/mc_cover6.jpg'
title: 'FabGL PCEmulator on TTGO VGA32 v1.4'
date: 2021-09-02 00:00:01
tags: electronics
subclass: 'post tag-test tag-content'
categories: mc
navigation: True
logo: 'assets/images/home.png'
disqus: true
---

After waiting about 3 weeks I finally got my TTGO VGA32 v1.4 from Aliexpress.
Immediately, after getting my hands on the device I wanted to test it with [FabGL library](https://github.com/fdivitto/FabGL).
![TTGO VGA32](assets/images/2021-09-02/ttgo.png)

NOTE: While powering the board using a USB 2.0 port, my 20+ year old PS/2 keyboard refused to work. Probably the USB port was
not able to source enough current. In the end I used a power supply designed for Raspbarry PI 3B. With that setup everything worked
correctly. USB 3.0 can source much more current than USB 2.0, but I did not test that setup.

It must be admitted that FabGL is compatible with TTGO VGA32 board, but only with version `v1.2`.
Version `v1.4` has slightly different pinout (`MISO` and `MOSI` connections to SDCARD use different IO ports).
![Pinout of VGA32](assets/images/2021-09-02/pinout.webp)

To run PCEmulator example we must edit PCEmulator source code:
{% highlight c %}
 /* SIGNATURE:
      bool mountSDCard  ( bool  formatOnFail,
      char const *  mountPath,
      size_t  maxFiles = 4,
      int   allocationUnitSize = 16 * 1024,
      int   MISO = 16,
      int   MOSI = 17,
      int   CLK = 14,
      int   CS = 13
      )
   */

  // original: if (!FileBrowser::mountSDCard(false, "/SD", 8))
  // changed:
  if (!FileBrowser::mountSDCard(false, "/SD", 8, 16*1024, 2, 12, 14, 13))
    ibox.message("Error!", "This app requires a SD-CARD!", nullptr, nullptr);
{% endhighlight %}
Notice that now we will use ports 2 and 12 for `MISO` and `MOSI` lines.

After this change PCEmulator starts without any troubles.
I could run Windows 3.11 and use all the provided programs:
![Windows 3.11 on TTGO VGA32](assets/images/2021-09-02/win.png)

Although Windows 3.11 works as intended, it is working quite slow.
It can take several seconds to e.g. open Excel, on the other hand you can comfortably play Reversi.
When it comes to provided DOS games, I had less luck. Most of them either froze the emulator or simply refuse to start.
Looks like there is still much work to be done on this project.

Anyway having a cheap, compatible, and ready to use board is very nice.
With FabGL on top of it, I am sure I will have no troubles finding some good use of it.

Resources:
* [TTGO VGA32 v1.4 Schematic](https://github.com/LilyGO/FabGL/blob/master/Schematic/vga32_v1.4.pdf)
* [TTGO VGA32 Product Page](http://www.lilygo.cn/prod_view.aspx?TypeId=50033&Id=1083&FId=t3:50033:3)


text:
describe 'mysql::server::mysqltuner' do

  it { should contain_file('/usr/local/bin/mysqltuner') }

end


text:
Given /^there is no project$/ do
  system "rm -rf tmp/cluster"
end

When /^I generate a project$/ do
  system("INTEGRATION_TEST=true bin/testbot_cloud new tmp/cluster 1> /dev/null") || raise
end

Then /^there should be a project folder$/ do
  File.exists?("tmp/cluster") || raise
end

Then /^the project folder should contain a config file$/ do
  File.exists?("tmp/cluster/config.yml") || raise
end

Then /^the project folder should contain bootstrap files$/ do
  File.exists?("tmp/cluster/bootstrap/runner.sh") || raise
end

Given /^I start the testbot cluster$/ do
  @results = `cd tmp/cluster; INTEGRATION_TEST=true ../../bin/testbot_cloud start 2>&1`
end

Then /^I should see "([^"]*)"$/ do |text|
  @results.include?(text) || raise("Did not see '#{text}' in #{@results}")
end

Then /^I should not see any errors$/ do
  if @results.include?("testbot_cloud/lib")
    puts @results
    raise
  end
end


text:
#ifndef CCBRIGHTNESS_FILTER
#define CCBRIGHTNESS_FILTER

#include "CCFilter.h"

NS_CC_EXT_BEGIN
//================== BrightnessFilter

class BrightnessFilter : public SingleFloatParamFilter
{

public:
	static BrightnessFilter* create();
	static BrightnessFilter* create(float brightness);

	BrightnessFilter();

	virtual void setParameter(float brightness);
protected:
	virtual GLProgram* loadShader();
	virtual void setAttributes(GLProgram* glp);
	virtual void setUniforms(GLProgram* glp);
};

NS_CC_EXT_END

#endif //CCBRIGHTNESS_FILTER


text:
package config

import (
	"context"

	"github.com/rancher/norman/controller"
	"github.com/rancher/norman/signal"
	appsv1beta2 "github.com/rancher/types/apis/apps/v1beta2"
	corev1 "github.com/rancher/types/apis/core/v1"
	managementv3 "github.com/rancher/types/apis/management.cattle.io/v3"
	projectv3 "github.com/rancher/types/apis/project.cattle.io/v3"
	"github.com/sirupsen/logrus"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

type ManagementContext struct {
	RESTConfig        rest.Config
	UnversionedClient rest.Interface

	Management managementv3.Interface
}

func (c *ManagementContext) controllers() []controller.Starter {
	return []controller.Starter{
		c.Management,
	}
}

type ClusterContext struct {
	Management        *ManagementContext
	ClusterName       string
	RESTConfig        rest.Config
	UnversionedClient rest.Interface
	K8sClient         kubernetes.Interface

	Apps    appsv1beta2.Interface
	Project projectv3.Interface
	Core    corev1.Interface
}

func (w *ClusterContext) controllers() []controller.Starter {
	return []controller.Starter{
		w.Apps,
		w.Project,
		w.Core,
	}
}

func NewManagementContext(config rest.Config) (*ManagementContext, error) {
	var err error

	context := &ManagementContext{
		RESTConfig: config,
	}

	context.Management, err = managementv3.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	dynamicConfig := config
	if dynamicConfig.NegotiatedSerializer == nil {
		configConfig := dynamic.ContentConfig()
		dynamicConfig.NegotiatedSerializer = configConfig.NegotiatedSerializer
	}

	context.UnversionedClient, err = rest.UnversionedRESTClientFor(&dynamicConfig)
	if err != nil {
		return nil, err
	}

	return context, err
}

func (c *ManagementContext) Start(ctx context.Context) error {
	logrus.Info("Starting management controllers")
	return controller.SyncThenSync(ctx, 5, c.controllers()...)
}

func (c *ManagementContext) StartAndWait() error {
	ctx := signal.SigTermCancelContext(context.Background())
	c.Start(ctx)
	<-ctx.Done()
	return ctx.Err()
}

func NewClusterContext(clusterConfig, config rest.Config, clusterName string) (*ClusterContext, error) {
	var err error
	context := &ClusterContext{
		RESTConfig:  config,
		ClusterName: clusterName,
	}

	context.Management, err = NewManagementContext(clusterConfig)
	if err != nil {
		return nil, err
	}

	context.K8sClient, err = kubernetes.NewForConfig(&config)
	if err != nil {
		return nil, err
	}

	context.Apps, err = appsv1beta2.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	context.Core, err = corev1.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	context.Project, err = projectv3.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	dynamicConfig := config
	if dynamicConfig.NegotiatedSerializer == nil {
		configConfig := dynamic.ContentConfig()
		dynamicConfig.NegotiatedSerializer = configConfig.NegotiatedSerializer
	}

	context.UnversionedClient, err = rest.UnversionedRESTClientFor(&dynamicConfig)
	if err != nil {
		return nil, err
	}

	return context, err
}

func (w *ClusterContext) Start(ctx context.Context) error {
	logrus.Info("Starting cluster controllers")
	controllers := w.Management.controllers()
	controllers = append(controllers, w.controllers()...)
	return controller.SyncThenSync(ctx, 5, controllers...)
}

func (w *ClusterContext) StartAndWait() error {
	ctx := signal.SigTermCancelContext(context.Background())
	w.Start(ctx)
	<-ctx.Done()
	return ctx.Err()
}


text:
using NUnit.Framework;

namespace Selenium.Tests
{
    [TestFixture]
    public class TestCheckUncheck : SeleniumTestCaseBase
    {
        [Test]
        public void ShouldBeAbleToCheckAndUncheck()
        {
            selenium.Open("/html/test_check_uncheck.html");
            Assert.IsTrue(selenium.IsChecked("base-spud"));
            Assert.IsFalse(selenium.IsChecked("base-rice"));
            Assert.IsTrue(selenium.IsChecked("option-cheese"));
            Assert.IsFalse(selenium.IsChecked("option-onions"));
            selenium.Check("base-rice");
            Assert.IsFalse(selenium.IsChecked("base-spud"));
            Assert.IsTrue(selenium.IsChecked("base-rice"));
            selenium.Uncheck("option-cheese");
            Assert.IsFalse(selenium.IsChecked("option-cheese"));
            selenium.Check("option-onions");
            Assert.IsTrue(selenium.IsChecked("option-onions"));
            Assert.IsFalse(selenium.IsChecked("option-chilli"));
            selenium.Check("option chilli");
            Assert.IsTrue(selenium.IsChecked("option-chilli"));
            selenium.Uncheck("option index=3");
            Assert.IsFalse(selenium.IsChecked("option-chilli"));
        }
    }
}


text:
<?
	require_once('database.php');

	class Template
	{
		private $db;
		function __construct()
		{
			$this->db = new Database();
		}
		function AddTemplate($name, $content)
		{
			$v = $this->db->query(
				"INSERT INTO templates VALUES(?,?,?)",
				array(NULL, $name, $content)
			);
			if(!$v)
			{
				throw new Exception('Could not add template: '.
					$this->db->error);
			}
		}
		function GetTemplateRaw($id)
		{
			$v = $this->db->query(
				"SELECT * FROM templates WHERE id = ?",
				array($id)
			);
			if(!$v[0]['id'])
			{
				throw new Exception('No such template.');
			}
			return $v[0]['content'];
		}
		function GetTemplate($id, $vars)
		{
			//check if $vars is associative
			if (is_array($vars) &&
				array_diff_key($vars, array_fill(
					0, count($vars), null)))
			{
				throw new Exception('GetTemplate expects assoc array');
			}
			$template = $this->GetTemplateRaw($id);
			foreach($vars as $token => $value)
			{
				$template = str_replace($token, $value, $template);
			}
			return $template;
		}
		function EditTemplate($id, $name, $content)
		{
			if(!($id && $name && $content))
			{
				throw new Exception('All fields are required for edit.');
			}
			$v = $this->db->query(
				"UPDATE templates SET name = ?, content = ? WHERE id = ?".
				array($name, $content, $id)
			);
			if(!$v)
			{
				throw new Exception('Could not edit template: '.
					$this->db->error);
			}
		}
		function DeleteTemplate($id)
		{
			if(!$id)
			{
				throw new Exception('All fields are required for delete.');
			}
			$v = $this->db->query(
				"DELETE FROM templates WHERE id = ?",
				array($id)
			);
		}
	}


text:
#include <aws/iam/model/DeleteSigningCertificateRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::IAM::Model;
using namespace Aws::Utils;

DeleteSigningCertificateRequest::DeleteSigningCertificateRequest() :
    m_userNameHasBeenSet(false),
    m_certificateIdHasBeenSet(false)
{
}

Aws::String DeleteSigningCertificateRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DeleteSigningCertificate&";
  if(m_userNameHasBeenSet)
  {
    ss << "UserName=" << StringUtils::URLEncode(m_userName.c_str()) << "&";
  }

  if(m_certificateIdHasBeenSet)
  {
    ss << "CertificateId=" << StringUtils::URLEncode(m_certificateId.c_str()) << "&";
  }

  ss << "Version=2010-05-08";
  return ss.str();
}

void  DeleteSigningCertificateRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
import unittest
import transaction

from pyramid import testing

from .models import DBSession

class TestMyView(unittest.TestCase):
    def setUp(self):
        self.config = testing.setUp()
        from sqlalchemy import create_engine
        engine = create_engine('sqlite://')
        from .models import (
            Base,
            MyModel,
            )
        DBSession.configure(bind=engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            model = MyModel(name='one', value=55)
            DBSession.add(model)

    def tearDown(self):
        DBSession.remove()
        testing.tearDown()

    def test_it(self):
        from .views import my_view
        request = testing.DummyRequest()
        info = my_view(request)
        self.assertEqual(info['one'].name, 'one')
        self.assertEqual(info['project'], 'MyApp')


text:
from openstack_horizon.test.integration_tests.pages import basepage

class AdminPage(basepage.BasePage):
    def __init__(self, driver, conf):
        super(AdminPage, self).__init__(driver, conf)
        self._page_title = "Usage Overview"


text:
namespace horizon{

#define HORIZON_LOG_FUNCTION "  [" <<  __FILE__ << "(" << __LINE__ << ")" << ": " <<  __FUNCTION__ << "]  "

#define HORIZON_TRACE     BOOST_LOG_TRIVIAL(trace) << HORIZON_LOG_FUNCTION
#define HORIZON_DEBUG     BOOST_LOG_TRIVIAL(debug) << HORIZON_LOG_FUNCTION
#define HORIZON_INFO      BOOST_LOG_TRIVIAL(info) << HORIZON_LOG_FUNCTION
#define HORIZON_WARNING   BOOST_LOG_TRIVIAL(warning) << HORIZON_LOG_FUNCTION
#define HORIZON_ERROR     BOOST_LOG_TRIVIAL(error) << HORIZON_LOG_FUNCTION
#define HORIZON_FATAL     BOOST_LOG_TRIVIAL(fatal) << HORIZON_LOG_FUNCTION

//#define HORIZON_TRACE_ASYNC     BOOST_LOG_TRIVIAL(trace) << HORIZON_LOG_FUNCTION
//#define HORIZON_DEBUG_ASYNC     BOOST_LOG_TRIVIAL(debug) << HORIZON_LOG_FUNCTION
//#define HORIZON_INFO_ASYNC      BOOST_LOG_TRIVIAL(info) << HORIZON_LOG_FUNCTION
//#define HORIZON_WARNING_ASYNC   BOOST_LOG_TRIVIAL(warning) << HORIZON_LOG_FUNCTION
//#define HORIZON_ERROR_ASYNC     BOOST_LOG_TRIVIAL(error) << HORIZON_LOG_FUNCTION
//#define HORIZON_FATAL_ASYNC     BOOST_LOG_TRIVIAL(fatal) << HORIZON_LOG_FUNCTION

    class LogBackend : public boost::log::sinks::basic_formatted_sink_backend < char > {
    public:
        virtual void consume(const boost::log::record_view& rec, string_type const& msg);
    private:
        void logMessage(const boost::log::record_view& rec, const std::string& msg);
        void logMessageImplement(const std::string& msg);

    };

} //namespace horizon

#endif //_HORIZON_HORIZON_LOG_H_


text:
var async = require('async');
var express = require('express');
var bodyParser = require('body-parser');
var r = require('rethinkdb');

var config = require(__dirname + '/config.js');

var app = express();

//For serving the index.html and all the other front-end assets.
app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json());

//The REST routes for "todos".
app.route('/users')
  .get(listUsers)
  .post(createUser);

app.route('/todos/:id')
  .get(getUserById)
  .put(updateUser)
  .delete(deleteUser);

//If we reach this middleware the route could not be handled and must be unknown.
app.use(handle404);

//Generic error handling middleware.
app.use(handleError);

/*
 * Retrieve all users.
 */
function listUsers(req, res, next) {
  r.table('users').orderBy({index: 'createdAt'}).run(req.app._rdbConn, function(err, cursor) {
    if(err) {
      return next(err);
    }

    //Retrieve all the users in an array.
    cursor.toArray(function(err, result) {
      if(err) {
        return next(err);
      }

      res.json(result);
    });
  });
}

/*
 * Insert a new user.
 */
function createUser(req, res, next) {
  var user = req.body;
  user.createdAt = r.now();

  console.log(req);

  r.table('users').insert(user, {returnChanges: true}).run(req.app._rdbConn, function(err, result) {
    if(err) {
      return next(err);
    }

    res.json(result.changes[0].new_val);
  });
}

/*
 * Get a specific user.
 */
function getUserById(req, res, next) {
  var userID = req.params.id;

  r.table('users').get(userID).run(req.app._rdbConn, function(err, result) {
    if(err) {
      return next(err);
    }

    res.json(result);
  });
}

/*
 * Update a user.
 */
function updateUser(req, res, next) {
  var user = req.body;
  var userID = req.params.id;

  r.table('users').get(userID).update(user, {returnChanges: true}).run(req.app._rdbConn, function(err, result) {
    if(err) {
      return next(err);
    }

    res.json(result.changes[0].new_val);
  });
}

/*
 * Delete a user.
 */
function deleteUser(req, res, next) {
  var userID = req.params.id;

  r.table('users').get(userID).delete().run(req.app._rdbConn, function(err, result) {
    if(err) {
      return next(err);
    }

    res.json({success: true});
  });
}

/*
 * Page-not-found middleware.
 */
function handle404(req, res, next) {
  res.status(404).end('not found');
}

/*
 * Generic error handling middleware.
 * Send back a 500 page and log the error to the console.
 */
function handleError(err, req, res, next) {
  console.error(err.stack);
  res.status(500).json({err: err.message});
}

/*
 * Store the db connection and start listening on a port.
 */
function startExpress(connection) {
  app._rdbConn = connection;
  app.listen(config.express.port);
  console.log('Listening on port ' + config.express.port);
}

/*
 * Connect to rethinkdb, create the needed tables/indexes and then start express.
 * Create tables/indexes then start express
 */
async.waterfall([
  function connect(callback) {
    r.connect(config.rethinkdb, callback);
  },
  function createDatabase(connection, callback) {
    //Create the database if needed.
    r.dbList().contains(config.rethinkdb.db).do(function(containsDb) {
      return r.branch(
        containsDb,
        {created: 0},
        r.dbCreate(config.rethinkdb.db)
      );
    }).run(connection, function(err) {
      callback(err, connection);
    });
  },
  function createTable(connection, callback) {
    //Create the table if needed.
    r.tableList().contains('users').do(function(containsTable) {
      return r.branch(
        containsTable,
        {created: 0},
        r.tableCreate('users')
      );
    }).run(connection, function(err) {
      callback(err, connection);
    });
  },
  function createIndex(connection, callback) {
    //Create the index if needed.
    r.table('users').indexList().contains('createdAt').do(function(hasIndex) {
      return r.branch(
        hasIndex,
        {created: 0},
        r.table('users').indexCreate('createdAt')
      );
    }).run(connection, function(err) {
      callback(err, connection);
    });
  },
  function waitForIndex(connection, callback) {
    //Wait for the index to be ready.
    r.table('users').indexWait('createdAt').run(connection, function(err, result) {
      callback(err, connection);
    });
  }
], function(err, connection) {
  if(err) {
    console.error(err);
    process.exit(1);
    return;
  }

  startExpress(connection);
});


text:
__version__ = '0.1 alpha'

from customtags.core import Options, Tag


text:
package com.example.carlcastello.dosomethingapp.Dialog;

import android.app.Dialog;
import android.content.Context;
import android.support.v4.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.carlcastello.dosomethingapp.Listeners.DialogListener;
import com.example.carlcastello.dosomethingapp.R;

import java.util.ArrayList;

/**
 * Created by carlcastello on 27/05/17.
 */

public class RadiusDialog extends DialogFragment implements SeekBar.OnSeekBarChangeListener {
    private View view;
    private TextView radiusText;
    private ArrayList mSelectedItems;
    private DialogListener dialogListener;

    public RadiusDialog() {
        // Empty constructor is required for DialogFragment
        // Make sure not to add arguments to the constructor
        // Use `newInstance` instead as shown below
    }

    public static RadiusDialog newInstance(String title, int radius, DialogListener dialogListener) {
        RadiusDialog frag = new RadiusDialog();
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putInt("radius",radius);
        args.putSerializable("dialogListener",dialogListener);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        this.mSelectedItems = new ArrayList();

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();
        this.view = inflater.inflate(R.layout.dialog_radius, null);

//        https://stackoverflow.com/questions/14640397/dialogfragment-throws-classcastexception-if-called-from-fragment
        this.dialogListener = (DialogListener) getArguments().getSerializable("dialogListener");
        this.radiusText = (TextView) this.view.findViewById(R.id.radius_edit_2);

        int progress = getArguments().getInt("radius");
        this.radiusText.setText(""+progress);
        // Seek bar
        SeekBar seekBar = (SeekBar) view.findViewById(R.id.radius_seekbar);
        seekBar.setMax(100);
        seekBar.setProgress(progress);
        seekBar.setOnSeekBarChangeListener(this);

        String title = getArguments().getString("title");
        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        // Use the Builder class for convenient dialog construction
        builder.setTitle(title)
                .setView(view)
                // Add action buttons
                .setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        RadiusDialog.this.getDialog().cancel();
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }

    // http://stackoverflow.com/questions/13746412/prevent-dialogfragment-from-dismissing-when-button-is-clicked
    @Override
    public void onStart() {
        //super.onStart() is where dialog.show() is actually called on the underlying dialog, so we have to do it after this point
        super.onStart();

        final AlertDialog dialog = (AlertDialog) getDialog();
        if(dialog != null) {
            Button positiveButton = (Button) dialog.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String param = radiusText.getText().toString();
                    dialogListener.radiusDialogResponse(param);
                    dismiss();
                }
            });
        }
    }

    // https://stackoverflow.com/questions/8956218/android-seekbar-setonseekbarchangelistener
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {
        //set textView's text
        this.radiusText.setText(""+progress);
    }

    public void onStartTrackingTouch(SeekBar seekBar) {}

    public void onStopTrackingTouch(SeekBar seekBar) {}
}


text:
namespace test
{
    template <typename T>
    using List = std::list<T, typename std::allocator_traits<arena>::template rebind_alloc<T> >;

    template <typename T>
    using Vector = std::vector<T, typename std::allocator_traits<arena>::template rebind_alloc<T> >;

    template <typename T>
    using Set = std::set<T, std::less<T>, typename std::allocator_traits<arena>::template rebind_alloc<T> >;

    template <typename K, typename T>
    using Map = std::map<K, T, std::less<K>, typename std::allocator_traits<arena>::template rebind_alloc<std::pair<const K, T> > >;

    using String = std::basic_string<char, std::char_traits<char>, typename std::allocator_traits<arena>::template rebind_alloc<char> >;

    using NestedAliases = ::test::Set< ::test::List< ::test::Map<int32_t, ::test::String> > >;

    using TheFoo = ::test::foo;

    struct foo
    {
        using allocator_type = arena;

        ::test::List<bool> l;
        ::test::Vector<bool> v;
        ::test::Set<bool> s;
        ::test::Map< ::test::String, bool> m;
        ::test::String st;
        ::test::String d;
        ::bond::maybe< ::test::List<bool> > l1;
        ::bond::maybe< ::test::Vector<bool> > v1;
        ::bond::maybe< ::test::Set<bool> > s1;
        ::bond::maybe< ::test::Map< ::test::String, bool> > m1;
        ::bond::maybe< ::test::String> st1;
        ::test::NestedAliases na;

        template <int = 0> // Workaround to avoid compilation if not used
        foo()
          : d("foo")
        {
        }

        // Compiler generated copy ctor OK
        foo(const foo&) = default;

        foo(foo&&) = default;

        explicit
        foo(const arena& allocator)
          : l(allocator),
            v(allocator),
            s(allocator),
            m(allocator),
            st(allocator),
            d("foo", allocator),
            l1(allocator),
            v1(allocator),
            s1(allocator),
            m1(allocator),
            st1(allocator),
            na(allocator)
        {
        }

        // Compiler generated operator= OK
        foo& operator=(const foo&) = default;
        foo& operator=(foo&&) = default;

        bool operator==(const foo& other) const
        {
            return true
                && (l == other.l)
                && (v == other.v)
                && (s == other.s)
                && (m == other.m)
                && (st == other.st)
                && (d == other.d)
                && (l1 == other.l1)
                && (v1 == other.v1)
                && (s1 == other.s1)
                && (m1 == other.m1)
                && (st1 == other.st1)
                && (na == other.na);
        }

        bool operator!=(const foo& other) const
        {
            return !(*this == other);
        }

        void swap(foo& other)
        {
            using std::swap;
            swap(l, other.l);
            swap(v, other.v);
            swap(s, other.s);
            swap(m, other.m);
            swap(st, other.st);
            swap(d, other.d);
            swap(l1, other.l1);
            swap(v1, other.v1);
            swap(s1, other.s1);
            swap(m1, other.m1);
            swap(st1, other.st1);
            swap(na, other.na);
        }

        struct Schema;

    protected:
        void InitMetadata(const char*, const char*)
        {
        }
    };

    inline void swap(::test::foo& left, ::test::foo& right)
    {
        left.swap(right);
    }

    struct withFoo
    {
        using allocator_type = arena;

        ::test::TheFoo f;
        ::test::foo f1;

        template <int = 0> // Workaround to avoid compilation if not used
        withFoo()
        {
        }

        // Compiler generated copy ctor OK
        withFoo(const withFoo&) = default;

        withFoo(withFoo&&) = default;

        explicit
        withFoo(const arena& allocator)
          : f(allocator),
            f1(allocator)
        {
        }

        // Compiler generated operator= OK
        withFoo& operator=(const withFoo&) = default;
        withFoo& operator=(withFoo&&) = default;

        bool operator==(const withFoo& other) const
        {
            return true
                && (f == other.f)
                && (f1 == other.f1);
        }

        bool operator!=(const withFoo& other) const
        {
            return !(*this == other);
        }

        void swap(withFoo& other)
        {
            using std::swap;
            swap(f, other.f);
            swap(f1, other.f1);
        }

        struct Schema;

    protected:
        void InitMetadata(const char*, const char*)
        {
        }
    };

    inline void swap(::test::withFoo& left, ::test::withFoo& right)
    {
        left.swap(right);
    }
} // namespace test


text:
/*jslint node: true, nomen: true, stupid: true */
/*global YUI: true, YUITest: true */

YUI.add('addon-rs-hotswap-yui-tests', function (Y, NAME) {
    'use strict';

    var libfs = require('fs'),
        libpath = require('path'),

        A = YUITest.Assert,

        fixtures = libpath.join(__dirname, 'fixtures/store'),

        hotswapMojitControllerResourcePath = libpath.join(fixtures, 'mojits/HotswapMojit/controller.server.js'),

        oldControllerContent =
            "YUI.add('HotswapMojit', function (Y, NAME) {\n" +
            "    'use strict';\n" +
            "    Y.hotswap = 'originalValue';\n" +
            "});",

        newControllerContent =
            "YUI.add('HotswapMojit', function (Y, NAME) {\n" +
            "    'use strict';\n" +
            "    Y.hotswap = 'modifiedValue';\n" +
            "});",

        suite = new YUITest.TestSuite(NAME),

        store;

    Y.applyConfig({
        modules: {
            'addon-rs-hotswap-yui': {
                requires: ['plugin', 'oop'],
                fullpath: libpath.join(__dirname, '../addons/rs/hotswap-yui.js')
            }
        }
    });

    Y.applyConfig({ useSync: true });
    Y.use('addon-rs-hotswap-yui');
    Y.applyConfig({ useSync: false });

    function MockRS(config) {
        MockRS.superclass.constructor.apply(this, arguments);
    }

    MockRS.NAME = 'MockResourceStore';

    MockRS.ATTRS = {};

    Y.extend(MockRS, Y.Base, {

        initializer: function (cfg) {
            this._config = cfg || {};
        },

        blendStaticContext: function (ctx) {
            return Y.mojito.util.blend(this._config.context, ctx);
        },

        getStaticAppConfig: function () {
            return {
                resourceStore: {
                    hotswap: true
                }
            };
        },

        listAllMojits: function () {
            return ['HotswapMojit'];
        },

        addResourceVersion: function (res) {
            return;
        },

        getResourceVersions: function () {
            return [{
                yui: {
                    name: 'HotswapMojit'
                },
                affinity: {
                    affinity: 'server'
                },
                source: {
                    pkg: {
                        name: 'mojito'
                    }
                }
            }];
        }
    });

    suite.add(new YUITest.TestCase({

        name: 'hotswap yui rs addon tests',

        setUp: function () {

            libfs.writeFileSync(hotswapMojitControllerResourcePath, oldControllerContent);

            store = new MockRS({ root: fixtures });

            // Plug in mocked config addon
            store.plug(Y.mojito.addons.rs.config, {
                appRoot: fixtures,
                mojitoRoot: ''
            });

            // Plug in hotswap YUI addon
            store.plug(Y.mojito.addons.rs['hotswap-yui'], {
                appRoot: fixtures,
                mojitoRoot: ''
            });

            // Give the store a reference to the runtime YUI instance
            store.Y = Y;

            // Add a fake YUI resource to the runtime YUI instance
            Y.applyConfig({
                modules: {
                    HotswapMojit: {
                        fullpath: hotswapMojitControllerResourcePath,
                        requires: []
                    }
                }
            });

            // Execute the original module
            Y.applyConfig({ useSync: true });
            Y.use('HotswapMojit');
            Y.applyConfig({ useSync: false });

            // Trigger the addon hook on this method so the file is watched
            store.addResourceVersion({
                type: 'controller',
                yui: {
                    name: 'HotswapMojit'
                },
                source: {
                    fs: {
                        isFile: true,
                        fullPath: hotswapMojitControllerResourcePath
                    }
                }
            });
        },

        tearDown: function () {
            store = null;

            // Reset the fixture to the original content
            libfs.writeFile(hotswapMojitControllerResourcePath, oldControllerContent);
        },

        'disk change is propagated to live YUI module': function () {
            var test = this;

            A.areEqual('originalValue', Y.hotswap);

            // Modify the resource on the filesystem
            libfs.writeFile(hotswapMojitControllerResourcePath, newControllerContent,
                function (err) {
                    setTimeout(function () {
                        test.resume();

                        if (err) {
                            throw err;
                        }

                        A.areEqual('modifiedValue', Y.hotswap);
                    }, 101);
                });

            test.wait();
        }
    }));

    YUITest.TestRunner.add(suite);

}, '1.0.0', {
    requires: [
        'base',
        'oop'
    ]
});


text:
require 'hyrax/ingest/ingester/active_fedora_base_ingester'
require 'hyrax/ingest/ingester/active_fedora_file_ingester'

module Hyrax
  module Ingest
    module Ingester
      class PreservationEventIngester < ActiveFedoraBaseIngester

        attr_reader :premis_event_related_object

        def initialize(config={})
          config[:af_model_class_name] ||= 'Hyrax::Preservation::Event'
          @premis_event_related_object = config.delete(:premis_event_related_object)
          super(config)
        end

        def run!
          assign_properties!
          af_model.premis_event_related_object = premis_event_related_object
          save_model!
          # return the new instance of the ActiveFedora model
          af_model
        end
      end
    end
  end
end


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['pluginname'] = '安全考試瀏覽器/ 測驗存取規則';
$string['requiresafeexambrowser'] = '安全考試瀏覽器/ 測驗存取規則';
$string['safebrowsererror'] = '這一測驗已經被設定,因此它只能使用安全瀏覽器作答。你不能使用這一瀏覽器作答。';
$string['safebrowsernotice'] = '這一測驗已經被設定,因此學生只能使用安全瀏覽器作答。';


text:
"""
http://community.topcoder.com/stat?c=problem_statement&pm=1741

Single Round Match 148 Round 1 - Division II, Level One
Single Round Match 215 Round 1 - Division II, Level One
"""

class DivisorDigits:
    def howMany(self, number):
        digits = [0] * 11
        n = number
        while n:
            digits[n % 10] += 1
            n /= 10
        result = 0
        for digit, count in enumerate(digits):
            if digit > 0 and number % digit == 0:
                result += count
        return result


text:
	<link href="//gmpg.org/xfn/11" rel="profile">
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<title>没吃药的七叔 · blog</title>
	<meta name="mobile-web-app-capable" content="yes">
	<meta name="HandheldFriendly" content="True" />
	<meta name="MobileOptimized" content="320" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<link rel="stylesheet" type="text/css" media="only screen and (min-width: 900px)" href="/assets/css/desktop.css" />
	<link rel="stylesheet" type="text/css" media="only screen and (max-width: 899px)" href="/assets/css/mobile.css" />
	<link href="/assets/css/genericons.css" type="text/css" rel="stylesheet" />
	<link href="/assets/css/syntax.css" type="text/css" rel="stylesheet" />
	<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Fenix:400,400italic">
	<link rel="apple-touch-icon" href="http://7heaven.github.io/assets/images/icon.png">
	<link rel="shortcut icon" href="http://7heaven.github.io/assets/images/favicon.ico">
	<link rel="alternate" type="application/rss+xml" title="RSS" href="http://7heaven.github.io/atom.xml">

	<meta name="theme-color" content="#7E9576">

<input id="_1" type="checkbox">

没吃药的七叔

		Home

		About

			02 December 2015

Hola

test, test, test

			27 February 2014

Hello, Cosette

Thinny reaches a new version, with mobile support and some other cool features.

			22 January 2014

Thinny 2: a Jekyll theme

The Infinite's Nymphet has a new look, a new codename, and a new platform!

	Page 1 of 1

©2015, 7Heaven. Some rights reserved.


text:
package com.powerknights.dashboard.lib.typeadapters;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.powerknights.dashboard.lib.config.Config;

import java.lang.reflect.Type;

/**
 * <p>
 * Info about this class goes HERE!
 * </p>
 *
 * @author Bret 'Horfius' Dusseault
 * @version ${VERSION}
 */
public class ConfigSerializer implements JsonSerializer<Config> {
    @Override
    public JsonElement serialize(Config src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject o = new JsonObject();
        o.addProperty("name", src.getUnlocalizedName());
        o.addProperty("value", src.serializeString());

        return o;
    }
}


text:
namespace GMap.NET.CacheProviders
{
#if SQLite

   using System.Collections.Generic;
   using System.Data.Common;
   using System.IO;
   using System.Text;
   using System;
   using System.Diagnostics;
   using System.Globalization;
   using GMap.NET.MapProviders;
   using System.Threading;

#if !MONO
   using System.Data.SQLite;
#else
   using SQLiteConnection=Mono.Data.SqliteClient.SqliteConnection;
   using SQLiteTransaction=Mono.Data.SqliteClient.SqliteTransaction;
   using SQLiteCommand=Mono.Data.SqliteClient.SqliteCommand;
   using SQLiteDataReader=Mono.Data.SqliteClient.SqliteDataReader;
   using SQLiteParameter=Mono.Data.SqliteClient.SqliteParameter;
#endif

   /// <summary>
   /// ultra fast cache system for tiles
   /// </summary>
   internal class SQLitePureImageCache : PureImageCache
   {
#if !PocketPC
#if !MONO
      static SQLitePureImageCache()
      {
         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
      }

      static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
      {
         if(args.Name.StartsWith("System.Data.SQLite", StringComparison.OrdinalIgnoreCase))
         {
            string rootDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "GMap.NET" + Path.DirectorySeparatorChar;
            string dllDir = rootDir + "DllCache" + Path.DirectorySeparatorChar;
            string dll = dllDir + "SQLite_v79_NET" + Environment.Version.Major + "_" + (IntPtr.Size == 8 ? "x64" : "x86") + Path.DirectorySeparatorChar + "System.Data.SQLite.DLL";
            if(!File.Exists(dll))
            {
               string dir = Path.GetDirectoryName(dll);
               if(!Directory.Exists(dir))
               {
                  Directory.CreateDirectory(dir);
               }

               Debug.WriteLine("Saving to DllCache: " + dll);

               if(Environment.Version.Major == 2)
               {
                  using(MemoryStream gzipDll = new MemoryStream((IntPtr.Size == 8 ? Properties.Resources.System_Data_SQLite_x64_NET2_dll : Properties.Resources.System_Data_SQLite_x86_NET2_dll)))
                  {
                     using(var gs = new System.IO.Compression.GZipStream(gzipDll, System.IO.Compression.CompressionMode.Decompress))
                     {
                        using(MemoryStream exctDll = new MemoryStream())
                        {
                           byte[] tmp = new byte[1024 * 256];
                           int r = 0;
                           while((r = gs.Read(tmp, 0, tmp.Length)) > 0)
                           {
                              exctDll.Write(tmp, 0, r);
                           }
                           File.WriteAllBytes(dll, exctDll.ToArray());
                        }
                     }
                  }
               }
               else if(Environment.Version.Major == 4)
               {
                  using(MemoryStream gzipDll = new MemoryStream((IntPtr.Size == 8 ? Properties.Resources.System_Data_SQLite_x64_NET4_dll : Properties.Resources.System_Data_SQLite_x86_NET4_dll)))
                  {
                     using(var gs = new System.IO.Compression.GZipStream(gzipDll, System.IO.Compression.CompressionMode.Decompress))
                     {
                        using(MemoryStream exctDll = new MemoryStream())
                        {
                           byte[] tmp = new byte[1024 * 256];
                           int r = 0;
                           while((r = gs.Read(tmp, 0, tmp.Length)) > 0)
                           {
                              exctDll.Write(tmp, 0, r);
                           }
                           File.WriteAllBytes(dll, exctDll.ToArray());
                        }
                     }
                  }
               }
            }

            Debug.WriteLine("Assembly.LoadFile: " + dll);

            return System.Reflection.Assembly.LoadFile(dll);
         }
         return null;
      }

      static int ping = 0;

      /// <summary>
      /// triggers dynamic sqlite loading
      /// </summary>
      public static void Ping()
      {
         ping++;
      }
#endif
#endif

      string cache;
      string gtileCache;
      string dir;
      string db;
      bool Created = false;

      public string GtileCache
      {
         get
         {
            return gtileCache;
         }
      }

      /// <summary>
      /// local cache location
      /// </summary>
      public string CacheLocation
      {
         get
         {
            return cache;
         }
         set
         {
            cache = value;

            gtileCache = Path.Combine(cache, "TileDBv5") + Path.DirectorySeparatorChar;

            dir = gtileCache + GMapProvider.LanguageStr + Path.DirectorySeparatorChar;

            // precreate dir
            if(!Directory.Exists(dir))
            {
               Directory.CreateDirectory(dir);
            }

            // make empty db
            {
               db = dir + "Data.gmdb";

               if(!File.Exists(db))
               {
                  Created = CreateEmptyDB(db);
               }
               else
               {
                  Created = AlterDBAddTimeColumn(db);
               }

               CheckPreAllocation();
#if !MONO
               ConnectionString = string.Format("Data Source=\"{0}\";Page Size=32768;Pooling=True", db);
#else
               ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768,Pooling=True", db);
#endif
            }

            // clear old attachments
            AttachedCaches.Clear();
            RebuildFinnalSelect();

            // attach all databases from main cache location
#if !PocketPC
            var dbs = Directory.GetFiles(dir, "*.gmdb", SearchOption.AllDirectories);
#else
            var dbs = Directory.GetFiles(dir, "*.gmdb");
#endif
            foreach(var d in dbs)
            {
               if(d != db)
               {
                  Attach(d);
               }
            }
         }
      }

      /// <summary>
      /// pre-allocate 32MB free space 'ahead' if needed,
      /// decreases fragmentation
      /// </summary>
      void CheckPreAllocation()
      {
         {
            byte[] pageSizeBytes = new byte[2];
            byte[] freePagesBytes = new byte[4];

            lock(this)
            {
               using(var dbf = File.Open(db, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
               {
                  dbf.Seek(16, SeekOrigin.Begin);

#if (!PocketPC && !MONO)
                  dbf.Lock(16, 2);
                  dbf.Read(pageSizeBytes, 0, 2);
                  dbf.Unlock(16, 2);

                  dbf.Seek(36, SeekOrigin.Begin);

                  dbf.Lock(36, 4);
                  dbf.Read(freePagesBytes, 0, 4);
                  dbf.Unlock(36, 4);
#else
                  dbf.Read(pageSizeBytes, 0, 2);
                  dbf.Seek(36, SeekOrigin.Begin);
                  dbf.Read(freePagesBytes, 0, 4);
#endif

                  dbf.Close();
               }
            }

            if(BitConverter.IsLittleEndian)
            {
               Array.Reverse(pageSizeBytes);
               Array.Reverse(freePagesBytes);
            }
            UInt16 pageSize = BitConverter.ToUInt16(pageSizeBytes, 0);
            UInt32 freePages = BitConverter.ToUInt32(freePagesBytes, 0);

            var freeMB = (pageSize * freePages) / (1024.0 * 1024.0);

#if !PocketPC
            int addSizeMB = 32;
            int waitUntilMB = 4;
#else
            int addSizeMB = 4; // reduce due to test in emulator
            int waitUntilMB = 2;
#endif

            Debug.WriteLine("FreePageSpace in cache: " + freeMB + "MB | " + freePages + " pages");

            if(freeMB <= waitUntilMB)
            {
               PreAllocateDB(db, addSizeMB);
            }
         }
      }

      #region -- import / export --
      public static bool CreateEmptyDB(string file)
      {
         bool ret = true;

         try
         {
            string dir = Path.GetDirectoryName(file);
            if(!Directory.Exists(dir))
            {
               Directory.CreateDirectory(dir);
            }

            using(SQLiteConnection cn = new SQLiteConnection())
            {
#if !MONO
               cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=False;Page Size=32768", file);
#else
               cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=False,Page Size=32768", file);
#endif
               cn.Open();
               {
                  using(DbTransaction tr = cn.BeginTransaction())
                  {
                     try
                     {
                        using(DbCommand cmd = cn.CreateCommand())
                        {
                           cmd.Transaction = tr;
#if !PocketPC
                           cmd.CommandText = Properties.Resources.CreateTileDb;
#else
                           cmd.CommandText = GMap.NET.WindowsMobile.Properties.Resources.CreateTileDb;
#endif
                           cmd.ExecuteNonQuery();
                        }
                        tr.Commit();
                     }
                     catch(Exception exx)
                     {
#if MONO
                        Console.WriteLine("CreateEmptyDB: " + exx.ToString());
#endif
                        Debug.WriteLine("CreateEmptyDB: " + exx.ToString());

                        tr.Rollback();
                        ret = false;
                     }
                  }
                  cn.Close();
               }
            }
         }
         catch(Exception ex)
         {
#if MONO
            Console.WriteLine("CreateEmptyDB: " + ex.ToString());
#endif
            Debug.WriteLine("CreateEmptyDB: " + ex.ToString());
            ret = false;
         }
         return ret;
      }

      public static bool PreAllocateDB(string file, int addSizeInMBytes)
      {
         bool ret = true;

         try
         {
            Debug.WriteLine("PreAllocateDB: " + file + ", +" + addSizeInMBytes + "MB");

            using(SQLiteConnection cn = new SQLiteConnection())
            {
#if !MONO
               cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=False;Page Size=32768", file);
#else
               cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=False,Page Size=32768", file);
#endif
               cn.Open();
               {
                  using(DbTransaction tr = cn.BeginTransaction())
                  {
                     try
                     {
                        using(DbCommand cmd = cn.CreateCommand())
                        {
                           cmd.Transaction = tr;
                           cmd.CommandText = string.Format("create table large (a); insert into large values (zeroblob({0})); drop table large;", addSizeInMBytes * 1024 * 1024);
                           cmd.ExecuteNonQuery();
                        }
                        tr.Commit();
                     }
                     catch(Exception exx)
                     {
#if MONO
                        Console.WriteLine("PreAllocateDB: " + exx.ToString());
#endif
                        Debug.WriteLine("PreAllocateDB: " + exx.ToString());

                        tr.Rollback();
                        ret = false;
                     }
                  }
                  cn.Close();
               }
            }
         }
         catch(Exception ex)
         {
#if MONO
            Console.WriteLine("PreAllocateDB: " + ex.ToString());
#endif
            Debug.WriteLine("PreAllocateDB: " + ex.ToString());
            ret = false;
         }
         return ret;
      }

      private static bool AlterDBAddTimeColumn(string file)
      {
         bool ret = true;

         try
         {
            if(File.Exists(file))
            {
               using(SQLiteConnection cn = new SQLiteConnection())
               {
#if !MONO
                  cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=False;Page Size=32768;Pooling=True", file);
#else
                  cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=False,Page Size=32768,Pooling=True", file);
#endif
                  cn.Open();
                  {
                     using(DbTransaction tr = cn.BeginTransaction())
                     {
                        bool? NoCacheTimeColumn = null;

                        try
                        {
                           using(DbCommand cmd = new SQLiteCommand("SELECT CacheTime FROM Tiles", cn))
                           {
                              cmd.Transaction = tr;

                              using(DbDataReader rd = cmd.ExecuteReader())
                              {
                                 rd.Close();
                              }
                              NoCacheTimeColumn = false;
                           }
                        }
                        catch(Exception ex)
                        {
                           if(ex.Message.Contains("no such column: CacheTime"))
                           {
                              NoCacheTimeColumn = true;
                           }
                           else
                           {
                              throw ex;
                           }
                        }

                        try
                        {
                           if(NoCacheTimeColumn.HasValue && NoCacheTimeColumn.Value)
                           {
                              using(DbCommand cmd = cn.CreateCommand())
                              {
                                 cmd.Transaction = tr;

                                 cmd.CommandText = "ALTER TABLE Tiles ADD CacheTime DATETIME";

                                 cmd.ExecuteNonQuery();
                              }
                              tr.Commit();
                              NoCacheTimeColumn = false;
                           }
                        }
                        catch(Exception exx)
                        {
#if MONO
                           Console.WriteLine("AlterDBAddTimeColumn: " + exx.ToString());
#endif
                           Debug.WriteLine("AlterDBAddTimeColumn: " + exx.ToString());

                           tr.Rollback();
                           ret = false;
                        }
                     }
                     cn.Close();
                  }
               }
            }
            else
            {
               ret = false;
            }
         }
         catch(Exception ex)
         {
#if MONO
            Console.WriteLine("AlterDBAddTimeColumn: " + ex.ToString());
#endif
            Debug.WriteLine("AlterDBAddTimeColumn: " + ex.ToString());
            ret = false;
         }
         return ret;
      }

      public static bool VacuumDb(string file)
      {
         bool ret = true;

         try
         {
            using(SQLiteConnection cn = new SQLiteConnection())
            {
#if !MONO
               cn.ConnectionString = string.Format("Data Source=\"{0}\";FailIfMissing=True;Page Size=32768", file);
#else
               cn.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768", file);
#endif
               cn.Open();
               {
                  using(DbCommand cmd = cn.CreateCommand())
                  {
                     cmd.CommandText = "vacuum;";
                     cmd.ExecuteNonQuery();
                  }
                  cn.Close();
               }
            }
         }
         catch(Exception ex)
         {
            Debug.WriteLine("VacuumDb: " + ex.ToString());
            ret = false;
         }
         return ret;
      }

      public static bool ExportMapDataToDB(string sourceFile, string destFile)
      {
         bool ret = true;

         try
         {
            if(!File.Exists(destFile))
            {
               ret = CreateEmptyDB(destFile);
            }

            if(ret)
            {
               using(SQLiteConnection cn1 = new SQLiteConnection())
               {
#if !MONO
                  cn1.ConnectionString = string.Format("Data Source=\"{0}\";Page Size=32768", sourceFile);
#else
                  cn1.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768", sourceFile);
#endif

                  cn1.Open();
                  if(cn1.State == System.Data.ConnectionState.Open)
                  {
                     using(SQLiteConnection cn2 = new SQLiteConnection())
                     {
#if !MONO
                        cn2.ConnectionString = string.Format("Data Source=\"{0}\";Page Size=32768", destFile);
#else
                        cn2.ConnectionString = string.Format("Version=3,URI=file://{0},FailIfMissing=True,Page Size=32768", destFile);
#endif
                        cn2.Open();
                        if(cn2.State == System.Data.ConnectionState.Open)
                        {
                           using(SQLiteCommand cmd = new SQLiteCommand(string.Format("ATTACH DATABASE \"{0}\" AS Source", sourceFile), cn2))
                           {
                              cmd.ExecuteNonQuery();
                           }

#if !MONO
                           using(SQLiteTransaction tr = cn2.BeginTransaction())
#else
                           using(DbTransaction tr = cn2.BeginTransaction())
#endif
                           {
                              try
                              {
                                 List<long> add = new List<long>();
                                 using(SQLiteCommand cmd = new SQLiteCommand("SELECT id, X, Y, Zoom, Type FROM Tiles;", cn1))
                                 {
                                    using(SQLiteDataReader rd = cmd.ExecuteReader())
                                    {
                                       while(rd.Read())
                                       {
                                          long id = rd.GetInt64(0);
                                          using(SQLiteCommand cmd2 = new SQLiteCommand(string.Format("SELECT id FROM Tiles WHERE X={0} AND Y={1} AND Zoom={2} AND Type={3};", rd.GetInt32(1), rd.GetInt32(2), rd.GetInt32(3), rd.GetInt32(4)), cn2))
                                          {
                                             using(SQLiteDataReader rd2 = cmd2.ExecuteReader())
                                             {
                                                if(!rd2.Read())
                                                {
                                                   add.Add(id);
                                                }
                                             }
                                          }
                                       }
                                    }
                                 }

                                 foreach(long id in add)
                                 {
                                    using(SQLiteCommand cmd = new SQLiteCommand(string.Format("INSERT INTO Tiles(X, Y, Zoom, Type, CacheTime) SELECT X, Y, Zoom, Type, CacheTime FROM Source.Tiles WHERE id={0}; INSERT INTO TilesData(id, Tile) Values((SELECT last_insert_rowid()), (SELECT Tile FROM Source.TilesData WHERE id={0}));", id), cn2))
                                    {
                                       cmd.Transaction = tr;
                                       cmd.ExecuteNonQuery();
                                    }
                                 }
                                 add.Clear();

                                 tr.Commit();
                              }
                              catch(Exception exx)
                              {
                                 Debug.WriteLine("ExportMapDataToDB: " + exx.ToString());
                                 tr.Rollback();
                                 ret = false;
                              }
                           }

                           using(SQLiteCommand cmd = new SQLiteCommand("DETACH DATABASE Source;", cn2))
                           {
                              cmd.ExecuteNonQuery();
                           }
                        }
                     }
                  }
               }
            }
         }
         catch(Exception ex)
         {
            Debug.WriteLine("ExportMapDataToDB: " + ex.ToString());
            ret = false;
         }
         return ret;
      }
      #endregion

      static readonly string singleSqlSelect = "SELECT Tile FROM main.TilesData WHERE id = (SELECT id FROM main.Tiles WHERE X={0} AND Y={1} AND Zoom={2} AND Type={3})";
      static readonly string singleSqlInsert = "INSERT INTO main.Tiles(X, Y, Zoom, Type, CacheTime) VALUES(@p1, @p2, @p3, @p4, @p5)";
      static readonly string singleSqlInsertLast = "INSERT INTO main.TilesData(id, Tile) VALUES((SELECT last_insert_rowid()), @p1)";

      string ConnectionString;

      readonly List<string> AttachedCaches = new List<string>();
      string finnalSqlSelect = singleSqlSelect;
      string attachSqlQuery = string.Empty;
      string detachSqlQuery = string.Empty;

      void RebuildFinnalSelect()
      {
         finnalSqlSelect = null;
         finnalSqlSelect = singleSqlSelect;

         attachSqlQuery = null;
         attachSqlQuery = string.Empty;

         detachSqlQuery = null;
         detachSqlQuery = string.Empty;

         int i = 1;
         foreach(var c in AttachedCaches)
         {
            finnalSqlSelect += string.Format("\nUNION SELECT Tile FROM db{0}.TilesData WHERE id = (SELECT id FROM db{0}.Tiles WHERE X={{0}} AND Y={{1}} AND Zoom={{2}} AND Type={{3}})", i);
            attachSqlQuery += string.Format("\nATTACH '{0}' as db{1};", c, i);
            detachSqlQuery += string.Format("\nDETACH DATABASE db{0};", i);

            i++;
         }
      }

      public void Attach(string db)
      {
         if(!AttachedCaches.Contains(db))
         {
            AttachedCaches.Add(db);
            RebuildFinnalSelect();
         }
      }

      public void Detach(string db)
      {
         if(AttachedCaches.Contains(db))
         {
            AttachedCaches.Remove(db);
            RebuildFinnalSelect();
         }
      }

      #region PureImageCache Members

      int preAllocationPing = 0;

      bool PureImageCache.PutImageToCache(byte[] tile, int type, GPoint pos, int zoom)
      {
         bool ret = true;
         if(Created)
         {
            try
            {
               using(SQLiteConnection cn = new SQLiteConnection())
               {
                  cn.ConnectionString = ConnectionString;
                  cn.Open();
                  {
                     using(DbTransaction tr = cn.BeginTransaction())
                     {
                        try
                        {
                           using(DbCommand cmd = cn.CreateCommand())
                           {
                              cmd.Transaction = tr;
                              cmd.CommandText = singleSqlInsert;

                              cmd.Parameters.Add(new SQLiteParameter("@p1", pos.X));
                              cmd.Parameters.Add(new SQLiteParameter("@p2", pos.Y));
                              cmd.Parameters.Add(new SQLiteParameter("@p3", zoom));
                              cmd.Parameters.Add(new SQLiteParameter("@p4", type));
                              cmd.Parameters.Add(new SQLiteParameter("@p5", DateTime.Now));

                              cmd.ExecuteNonQuery();
                           }

                           using(DbCommand cmd = cn.CreateCommand())
                           {
                              cmd.Transaction = tr;

                              cmd.CommandText = singleSqlInsertLast;
                              cmd.Parameters.Add(new SQLiteParameter("@p1", tile));

                              cmd.ExecuteNonQuery();
                           }
                           tr.Commit();
                        }
                        catch(Exception ex)
                        {
#if MONO
                           Console.WriteLine("PutImageToCache: " + ex.ToString());
#endif
                           Debug.WriteLine("PutImageToCache: " + ex.ToString());

                           tr.Rollback();
                           ret = false;
                        }
                     }
                  }
                  cn.Close();
               }

               if(Interlocked.Increment(ref preAllocationPing) % 22 == 0)
               {
                  CheckPreAllocation();
               }
            }
            catch(Exception ex)
            {
#if MONO
               Console.WriteLine("PutImageToCache: " + ex.ToString());
#endif
               Debug.WriteLine("PutImageToCache: " + ex.ToString());
               ret = false;
            }
         }
         return ret;
      }

      PureImage PureImageCache.GetImageFromCache(int type, GPoint pos, int zoom)
      {
         PureImage ret = null;
         try
         {
            using(SQLiteConnection cn = new SQLiteConnection())
            {
               cn.ConnectionString = ConnectionString;
               cn.Open();
               {
                  if(!string.IsNullOrEmpty(attachSqlQuery))
                  {
                     using(DbCommand com = cn.CreateCommand())
                     {
                        com.CommandText = attachSqlQuery;
                        int x = com.ExecuteNonQuery();
                        //Debug.WriteLine("Attach: " + x);
                     }
                  }

                  using(DbCommand com = cn.CreateCommand())
                  {
                     com.CommandText = string.Format(finnalSqlSelect, pos.X, pos.Y, zoom, type);

                     using(DbDataReader rd = com.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
                     {
                        if(rd.Read())
                        {
                           long length = rd.GetBytes(0, 0, null, 0, 0);
                           byte[] tile = new byte[length];
                           rd.GetBytes(0, 0, tile, 0, tile.Length);
                           {
                              if(GMapProvider.TileImageProxy != null)
                              {
                                 ret = GMapProvider.TileImageProxy.FromArray(tile);
                              }
                           }
                           tile = null;
                        }
                        rd.Close();
                     }
                  }

                  if(!string.IsNullOrEmpty(detachSqlQuery))
                  {
                     using(DbCommand com = cn.CreateCommand())
                     {
                        com.CommandText = detachSqlQuery;
                        int x = com.ExecuteNonQuery();
                        //Debug.WriteLine("Detach: " + x);
                     }
                  }
               }
               cn.Close();
            }
         }
         catch(Exception ex)
         {
#if MONO
            Console.WriteLine("GetImageFromCache: " + ex.ToString());
#endif
            Debug.WriteLine("GetImageFromCache: " + ex.ToString());
            ret = null;
         }

         return ret;
      }

      int PureImageCache.DeleteOlderThan(DateTime date, int? type)
      {
         int affectedRows = 0;

         try
         {
            using(SQLiteConnection cn = new SQLiteConnection())
            {
               cn.ConnectionString = ConnectionString;
               cn.Open();
               {
                  using(DbCommand com = cn.CreateCommand())
                  {
                     com.CommandText = string.Format("DELETE FROM Tiles WHERE CacheTime is not NULL and CacheTime < datetime('{0}')", date.ToString("s"));
                     if(type.HasValue)
                     {
                        com.CommandText += " and Type = " + type;
                     }
                     affectedRows = com.ExecuteNonQuery();
                  }
               }
            }
         }
         catch(Exception ex)
         {
#if MONO
            Console.WriteLine("DeleteOlderThan: " + ex);
#endif
            Debug.WriteLine("DeleteOlderThan: " + ex);
         }

         return affectedRows;
      }

      #endregion
   }
#endif
}


text:
export interface Logger {
  error: (...args: any[]) => void;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/FacebookSDK/FacebookSDK.iml" filepath="$PROJECT_DIR$/FacebookSDK/FacebookSDK.iml" />
      <module fileurl="file://$PROJECT_DIR$/FacebookSDK/Firebase/Firebase.iml" filepath="$PROJECT_DIR$/FacebookSDK/Firebase/Firebase.iml" />
      <module fileurl="file://$PROJECT_DIR$/Model/MVP/MVP.iml" filepath="$PROJECT_DIR$/Model/MVP/MVP.iml" />
      <module fileurl="file://$PROJECT_DIR$/Model/Model.iml" filepath="$PROJECT_DIR$/Model/Model.iml" />
      <module fileurl="file://$PROJECT_DIR$/Model/ModelParser/ModelParser.iml" filepath="$PROJECT_DIR$/Model/ModelParser/ModelParser.iml" />
      <module fileurl="file://$PROJECT_DIR$/helper-android.iml" filepath="$PROJECT_DIR$/helper-android.iml" />
    </modules>
  </component>
</project>


text:
package com.custom.domain;

public enum Currency implements DomainEnum{
	INR("INR"),
	Euro("Euro"),
	Pound("Pound"),
	Dollar("Dollar");

	private String forName;
	private boolean uiHidden = false;
	@Override
	public boolean uiHidden() {
		return uiHidden;
	}
	private Currency(String forName){
		this.forName=forName;
	}

	public String getName(){
		return forName;
	}
}