text:
namespace util
{

void TypedCommandLineParser::updateOptionMap(const StringView& name, const OptionType type, void* data)
{
	auto inserted = optionMap.try_emplace(name, OptionEntry{type, data}).second;
	assert(inserted && "Duplicate entry in optionMap!");
}

void TypedCommandLineParser::addUIntOptionalFlag(const StringView& name, const StringView& desc, unsigned& flag)
{
	parser.addOptionalFlag(name, desc, "");
	updateOptionMap(name, OptionType::UInt, &flag);
}

void TypedCommandLineParser::addBooleanOptionalFlag(const StringView& name, const StringView& desc, bool& flag)
{
	parser.addOptionalFlag(name, desc);
	updateOptionMap(name, OptionType::Bool, &flag);
}

void TypedCommandLineParser::addStringOptionalFlag(const StringView& name, const StringView& desc, StringView& str)
{
	parser.addOptionalFlag(name, desc, "");
	updateOptionMap(name, OptionType::String, &str);
}

void TypedCommandLineParser::addStringPositionalFlag(const StringView& name, const StringView& desc, StringView& str)
{
	parser.addPositionalFlag(name, desc);
	updateOptionMap(name, OptionType::String, &str);
}

void TypedCommandLineParser::parseCommandLineOptions(int argc, char** argv)
{
	auto parseResult = parser.parseCommandLineOptions(argc, argv);

	for (auto& mapping: optionMap)
	{
		auto data = mapping.second.data;
		switch (mapping.second.type)
		{
			case OptionType::Bool:
			{
				*(reinterpret_cast<bool*>(data)) = parseResult.count(mapping.first);
				break;
			}
			case OptionType::UInt:
			{
				auto res = parseResult.lookup(mapping.first);
				assert(res != nullptr);
				if (!res->empty())
					*(reinterpret_cast<unsigned*>(data)) = std::stoul(res->to_string());
				break;
			}
			case OptionType::String:
			{
				auto res = parseResult.lookup(mapping.first);
				assert(res != nullptr);
				if (!res->empty())
					*(reinterpret_cast<StringView*>(data)) = *res;
				break;
			}
		}
	}
}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
/* @var $this AddexpencesController */
/* @var $model addexpences */

$this->breadcrumbs=array(
	'Addexpences'=>array('index'),
	$model->Name,
);

$this->menu=array(
	array('label'=>'List addexpences', 'url'=>array('index')),
	array('label'=>'Create addexpences', 'url'=>array('create')),
	array('label'=>'Update addexpences', 'url'=>array('update', 'id'=>$model->IDExpence)),
	array('label'=>'Delete addexpences', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->IDExpence),'confirm'=>'Are you sure you want to delete this item?')),
	array('label'=>'Manage addexpences', 'url'=>array('admin')),
);
?>

View addexpences #<?php echo $model->IDExpence; ?>

<?php $this->widget('zii.widgets.CDetailView', array(
	'data'=>$model,
	'attributes'=>array(
		'Name',
		array(
			'label' => 'CostHour',
			'type' => 'raw',
			'value' => '$'.$model->CostHour,
		)
		,
	),
)); ?>


text:
# HTTP Client

The `okhttp-client` module provides a `HttpClient` that can be used to make
HTTP requests which is backed by the [okhttp](https://github.com/square/okhttp)
library.

This module uses version 2.5.0 of okhttp.

## Configuration

If a configuration property is not set, the default from okhttp is used.

key | type | required | note
--- | ---- | -------- | ----
`http.client.connectTimeout` | int | optional | milliseconds; defaults to 10000
`http.client.readTimeout` | int | optional | milliseconds; defaults to 10000
`http.client.writeTimeout` | int | optional | milliseconds; defaults to 10000
`http.client.maxIdleConnections` | int | optional | maximum number of idle connections to keep in the connection pool; defaults to system property `http.maxConnections` if set, else 5
`http.client.keepAliveDuration` | int | optional | Time in milliseconds to keep the connection alive in the pool before closing it; defaults to system property `http.keepAliveDuration` if set, else 5 minutes
`http.client.followRedirects` | boolean | optional | Explicitly enable or disable following http redirect responses, default is behavior is to follow redirects (true)
`http.client.async.maxRequests` | int | optional | maximum number of asynchronous requests to execute concurrently; defaults to 64. Above this requests queue in memory, waiting for the running calls to complete.
`http.client.async.maxRequestsPerHost` | int | optional | Set the maximum number of requests for each host to execute concurrently. This limits requests by the URL's host name. Defaults to 5

## Example

```java
public static void main(String[] args) throws Exception {
  Service service = Services.usingName("test")
      .withModule(HttpClientModule.create())
      .build();

  try (Service.Instance instance = service.start(args)) {
    HttpClient httpClient = instance.resolve(HttpClient.class);
    RequestHandler handler = new ProxyHandler(httpClient);
    HttpServer httpServer = HttpServerModule.server(instance);

    httpServer.start(handler);
    instance.waitForShutdown();
  }
}

/** Proxies requests to another service */
public static class ProxyHandler implements RequestHandler {
  private final HttpClient httpClient;

  public Handler(HttpClient httpClient) {
    this.httpClient = httpClient;
  }

  public void handle(OngoingRequest originalRequest) {
    Request req = Request.forUri("http://proxy.example");
    httpClient.send(req, Optional.of(originalRequest))
      .thenAccept(response -> originalRequest.reply(response));
  }
}
```


text:
package com.github.pengrad.recyclerview;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

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

/**
 * stas
 * 7/23/15
 */
public abstract class RecyclerViewListAdapter<T> extends RecyclerView.Adapter<RecyclerViewHolder<T>> {

    private ItemClickListener<T> itemClickListener;
    private List<T> data;

    public RecyclerViewListAdapter() {
        this(null);
    }

    public RecyclerViewListAdapter(@Nullable ItemClickListener<T> itemClickListener) {
        this.itemClickListener = itemClickListener;
        setDataImpl(null);
    }

    private void setDataImpl(@Nullable Collection<T> data) {
        if (data == null) {
            this.data = new ArrayList<>(0);
        } else {
            this.data = new ArrayList<>(data.size());
            this.data.addAll(data);
        }
    }

    public RecyclerViewListAdapter<T> setData(Collection<T> data) {
        setDataImpl(data);
        notifyDataSetChanged();
        return this;
    }

    public RecyclerViewListAdapter<T> add(T item) {
        data.add(item);
        notifyDataSetChanged();
        return this;
    }

    public RecyclerViewListAdapter<T> add(int index, T item) {
        data.add(index, item);
        notifyDataSetChanged();
        return this;
    }

    public RecyclerViewListAdapter<T> addAll(Collection<? extends T> items) {
        data.addAll(items);
        notifyDataSetChanged();
        return this;
    }

    public RecyclerViewListAdapter<T> addAll(T... items) {
        for (T item : items) {
            data.add(item);
        }
        notifyDataSetChanged();
        return this;
    }

    public void clear() {
        data.clear();
        notifyDataSetChanged();
    }

    public void remove(T item) {
        data.remove(item);
    }

    public void remove(int index) {
        data.remove(index);
    }

    public void remove(Collection<T> items) {
        data.remove(items);
    }

    public List<T> getAll() {
        return data;
    }

    public T getItem(int position) {
        return data.get(position);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public abstract RecyclerViewHolder<T> onCreateViewHolder(ViewGroup parent, int viewType);

    @Override
    public void onBindViewHolder(RecyclerViewHolder<T> holder, int position) {
        holder.onBind(data.get(position), itemClickListener);
    }
}


text:
extern zend_class_entry *accelleratii_component_stopwatch_section_ce;

ZEPHIR_INIT_CLASS(Accelleratii_Component_Stopwatch_Section);

PHP_METHOD(Accelleratii_Component_Stopwatch_Section, __construct);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, get);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, open);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, getId);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, setId);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, startEvent);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, isEventStarted);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, stopEvent);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, lap);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, getEvent);
PHP_METHOD(Accelleratii_Component_Stopwatch_Section, getEvents);

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section___construct, 0, 0, 0)
	ZEND_ARG_INFO(0, origin)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_get, 0, 0, 1)
	ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_open, 0, 0, 1)
	ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_setid, 0, 0, 1)
	ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_startevent, 0, 0, 2)
	ZEND_ARG_INFO(0, name)
	ZEND_ARG_INFO(0, category)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_iseventstarted, 0, 0, 1)
	ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_stopevent, 0, 0, 1)
	ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_lap, 0, 0, 1)
	ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_accelleratii_component_stopwatch_section_getevent, 0, 0, 1)
	ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()

ZEPHIR_INIT_FUNCS(accelleratii_component_stopwatch_section_method_entry) {
	PHP_ME(Accelleratii_Component_Stopwatch_Section, __construct, arginfo_accelleratii_component_stopwatch_section___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, get, arginfo_accelleratii_component_stopwatch_section_get, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, open, arginfo_accelleratii_component_stopwatch_section_open, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, getId, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, setId, arginfo_accelleratii_component_stopwatch_section_setid, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, startEvent, arginfo_accelleratii_component_stopwatch_section_startevent, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, isEventStarted, arginfo_accelleratii_component_stopwatch_section_iseventstarted, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, stopEvent, arginfo_accelleratii_component_stopwatch_section_stopevent, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, lap, arginfo_accelleratii_component_stopwatch_section_lap, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, getEvent, arginfo_accelleratii_component_stopwatch_section_getevent, ZEND_ACC_PUBLIC)
	PHP_ME(Accelleratii_Component_Stopwatch_Section, getEvents, NULL, ZEND_ACC_PUBLIC)
  PHP_FE_END
};


text:
Protomak is a template for C projects. It is based on the venerable GNU Make to provide a complete
solution for building C projects. Its features are:

 * Simple project configuration. Simply fill in the required variables at `build_config.mk`.
 * Multi-arch compilations. Architecture specific parameters, as for example the compiler name,
 will have to be configured at `build_rules.mk`.
 * Embedded unit testing and mocking for C based on ThrowTheSwitch Unity and CMock tools.

# Starting a new project with Protomak

Simply fork this repository.

# Directory Layout

Protomak uses the following layout for the project files:

 * `src`. The source code files are expected to be here.
 * `test`. This folder will contain the unit tests and the testing framework files.
   * `test/unit`. Include here the unit tests you want. Each file containing unit tests is expected to have the name `test_*.c`.
   * `test/framework`. The Unity and CMock frameworks source files shall be contained here. You can configure CMock through the
     file `test/framework/cmock_conf.yml`.
 * `bin`. The generated binary file with the compiled application will be placed here.
 * `build/$(ARCH)`. The intermediate build files will be placed in this folder.

# Build Configuration

The build is configured with the file `build_config.mk`. The following variables are available:

 * `NAME`. Name of the application. The name will be used to generate the binary at the directory `bin`.
 * `SOURCE_PATHS`. Non-recursive list of paths where to find the source files.
 * `INCLUDE_PATHS`. Non-recursive list of include directories.
 * `LIBRARIES`. List of libraries with which to link the application. The library names have to be defined using its bare names. For example, use `pthread` in order to link with the pthread library.
 * `LIBRARY_PATHS`. List of search paths for non-standard libraries.
 * `SYMBOLS`. List of symbols to be defined in the application scope (used as `#define`)
 * `EXCLUDED_FILES`. Define the list of files to be excluded from the compilation.
 * Compilation flags for individual files. It's possible to define compilation flags for individual flags simply by defining the file name as a variable and defining the list of flags. For example, `src/main.c = -O0`.

# Unit Test Configuration

Unity and CMock are an integral part of Protomak. A set of compilation rules has been included to provide the simplest configuration of unit tests.

The unit test configuration is performed through the file `test/unit/test_cases.mk`. Each file in `test/unit/test_*.c` is linked only to the relevant sources that it tests. In order to define the file dependencies of a test file, define a variable with the same name in `test/unit/test_cases.mk`. For example, if you have a test file `test/unit/test_unit.c` that will test the functionality of the file `src/module.c`, you'll have to define the variable `test_unit = src/module.c`. It is possible to define more than one file for a single test file. If you have doubts, please take a look at the examples provided in the template.

## Mocks

In order to Mock interfaces, CMock is used. This library provides scripts to parse a header file and automatically create a `Mock%.c` file with the mock implementation. In order to define the set of headers from which to create mocks, please define the `MOCK_HEADERS` variable in `test/unit/test_cases.mk`.

The mock sources will be placed in the folder `test/unit/mocks`. This folder is automatically created and deleted so please do not place any files here that you don't want to loose. The mocks are compiled into a library at `test/unit/mocks/libmocks.a`. Each test case is automatically linked against this library.

# Command Line

## Building the Application

For the basic compilation, simply run make:
```bash
$ make
```

Protomak uses a set of special variables to parametrize the build. They can be placed in the `build_config.mk` file as well, but usually it's preferrable to use them from the command line.

### V

By default, the output of the build is minimalistic. However, if you want to have a verbose compilation, you can define the `V` flag. This is useful when using an IDE like Eclipse, that automatically generates an index from the build output.

```bash
$ make V=1
```

### NOOPT

By default, optimizations are enabled with `-O2`. If you want to disable them, run with the `NOOPT` flag.

```bash
$ make NOOPT=1
```

## Running the Unit Tests

In order to run the unit tests, a `unit` rule is provided:

```bash
$ make unit
```

Verbose compilation is available for unit tests as well:

```bash
$ make unit V=1
```

# Cross Compiling

One of the problems that Protomak attempts to solve is cross compilation. There are many ways to do it through makefiles. Protomak provides one that attempts to be as simple as possible.

In order to configure a compiler for a different architecture, please create a new section in `build_rules.mk`, that contains the definitions for that specific architecture. The template for that section is:

```make
ifeq ($(ARCH), arm)
CROSS_COMPILER := arm-linux-gnueabi-
endif
```

Once this is configured, each time we want to compile for `ARM` architecture you will only have to call make for the proper architecture:

```bash
$ make ARCH=arm
```

The compilation intermediate files are placed in the `build/$(ARCH)` directory.


text:
// *The majorant of an array of size N is a value that occurs in it at least N/2 + 1 times.
namespace Task08.FindMajorant
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class FindMajorant
    {
        public static void Main()
        {
            Console.WriteLine("Enter N integrer numbers separated by space or coma: ");
            List<int> listOfNumbers = Console.ReadLine()
               .Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries)
               .Select(x => int.Parse(x))
               .ToList();

            var result = listOfNumbers
                .GroupBy(x => x)
                .Where(gr => gr.Count() > listOfNumbers.Count / 2)
                .FirstOrDefault();

            Console.WriteLine("The majorant in the array {0}", result == null ? "does not exist" : "is " + result.Key);
        }
    }
}


text:
module Main where

import Criterion.Main
import qualified Functions.Comp as A
import qualified Functions.Standard as S
import DataTypes.Comp as DC
import DataTypes.Standard as DS
import DataTypes.Transform
import Data.Comp
import Data.Comp.DeepSeq ()
import Control.DeepSeq
import Test.QuickCheck.Arbitrary
import Test.QuickCheck.Gen
import Test.QuickCheck.Random
import System.Random

aExpr :: SugarExpr
aExpr = iIf ((iVInt 1 `iGt` (iVInt 2 `iMinus` iVInt 1))
            `iOr` ((iVInt 1 `iGt` (iVInt 2 `iMinus` iVInt 1))))
       ((iVInt 2 `iMinus` iVInt 1))
       (iVInt 3)

sExpr :: PExpr
sExpr = transSugar aExpr

sfCoalg :: Coalg SugarSig Int
sfCoalg 0 = inj $ VInt 1
sfCoalg n = let n' = n-1 in inj $ Plus n' n'

sfGen' :: Int -> SugarExpr
sfGen'  = ana' sfCoalg

sfGen :: Int -> SugarExpr
sfGen  = ana sfCoalg

shortcutFusion :: Benchmark
shortcutFusion = bgroup "shortcut-fusion" [
                  bench "eval without fusion" (nf (A.evalSugar2 . sfGen) depth),
                  bench "eval with fusion" (nf (A.evalSugar2 . sfGen') depth)
                  ]
    where depth = 15

standardBenchmarks :: (PExpr, SugarExpr, String) -> Benchmark
standardBenchmarks  (sExpr,aExpr,n) = rnf aExpr `seq` rnf sExpr `seq` getBench (sExpr, aExpr,n)
    where getBench (sExpr, aExpr,n) = bgroup n paperBenchmarks
          -- these are the benchmarks for evaluation
          evalBenchmarks = [
                 bench "evalDesug" (nf A.desugEval2 aExpr),
                 bench "evalDesug (fusion)" (nf A.desugEval2' aExpr),
                 bench "evalDesug (comparison)" (nf S.desugEval2 sExpr),
                 bench "evalDesugM" (nf A.desugEval aExpr),
                 bench "evalDesugT" (nf A.desugEvalT aExpr),
                 bench "evalDesugM (fusion)" (nf A.desugEval' aExpr),
                 bench "evalDesugT (fusion)" (nf A.desugEvalT' aExpr),
                 bench "evalDesugM (comparison)" (nf S.desugEval sExpr),
                 bench "eval" (nf A.evalSugar2 aExpr),
                 bench "evalDirect" (nf A.evalDirectE2 aExpr),
                 bench "eval[Direct] (comparison)" (nf S.evalSugar2 sExpr),
                 bench "evalM" (nf A.evalSugar aExpr),
                 bench "evalT" (nf A.evalSugarT aExpr),
                 bench "evalDirectM" (nf A.evalDirectE aExpr),
                 bench "eval[Direct]M (comparison)" (nf S.evalSugar sExpr)]
          -- these are the benchmarks from the WGP '11 paper
          paperBenchmarks = [
                 bench "desugHom" (nf A.desugExpr aExpr),
                 bench "desugCata" (nf A.desugExpr2 aExpr),
                 bench "desug[Hom,Cata] (comparison)" (nf S.desug sExpr),
                 bench "inferDesug" (nf A.desugType2 aExpr),
                 bench "inferDesug (fusion)" (nf A.desugType2' aExpr),
                 bench "inferDesug (comparison)" (nf S.desugType2 sExpr),
                 bench "inferDesugM" (nf A.desugType aExpr),
                 bench "inferDesugM (fusion)" (nf A.desugType' aExpr),
                 bench "inferDesugM (comparison)" (nf S.desugType sExpr),
                 bench "infer" (nf A.typeSugar2 aExpr),
                 bench "infer (comparison)" (nf S.typeSugar2 sExpr),
                 bench "inferM" (nf A.typeSugar aExpr),
                 bench "inferM (comparison)" (nf S.typeSugar sExpr),
                 bench "evalDesug" (nf A.desugEval2 aExpr),
                 bench "evalDesug (fusion)" (nf A.desugEval2' aExpr),
                 bench "evalDesug (comparison)" (nf S.desugEval2 sExpr),
                 bench "evalDesugM" (nf A.desugEval aExpr),
                 bench "evalDesugM (fusion)" (nf A.desugEval' aExpr),
                 bench "evalDesugM (comparison)" (nf S.desugEval sExpr),
                 bench "eval" (nf A.evalSugar2 aExpr),
                 bench "evalDirect" (nf A.evalDirectE2 aExpr),
                 bench "eval[Direct] (comparison)" (nf S.evalSugar2 sExpr),
                 bench "evalM" (nf A.evalSugar aExpr),
                 bench "evalDirectM" (nf A.evalDirectE aExpr),
                 bench "eval[Direct]M (comparison)" (nf S.evalSugar sExpr),
                 bench "contVar" (nf (A.contVar' 10) aExpr),
                 bench "contVarG" (nf (A.contVarGen 10) aExpr),
                 bench "contVarU" (nf (S.contVarGen 10) sExpr),
                 bench "contVar (comparison)" (nf (S.contVar 10) sExpr),
                 bench "freeVars" (nf A.freeVars' aExpr),
                 bench "freeVarsG" (nf A.freeVarsGen aExpr),
                 bench "freeVarsU" (nf S.freeVarsGen sExpr),
                 bench "freeVars (comparison)" (nf S.freeVars sExpr)]
          -- these are all the benchmarks
          allBenchmarks = [
                 bench "Comp.desug" (nf A.desugExpr aExpr),
                 bench "Comp.desug'" (nf A.desugExpr' aExpr),
                 bench "Comp.desugAlg" (nf A.desugExpr2 aExpr),
                 bench "Standard.desug" (nf S.desug sExpr),
                 bench "Standard.desug'" (nf S.desug' sExpr),
                 bench "Comp.desugType" (nf A.desugType aExpr),
                 bench "Comp.desugType'" (nf A.desugType' aExpr),
                 bench "Standard.desugType" (nf S.desugType sExpr),
                 bench "Comp.typeSugar" (nf A.typeSugar aExpr),
                 bench "Standard.typeSugar" (nf S.typeSugar sExpr),
                 bench "Comp.desugType2" (nf A.desugType2 aExpr),
                 bench "Comp.desugType2'" (nf A.desugType2' aExpr),
                 bench "Standard.desugType2" (nf S.desugType2 sExpr),
                 bench "Comp.typeSugar2" (nf A.typeSugar2 aExpr),
                 bench "Standard.typeSugar2" (nf S.typeSugar2 sExpr),
                 bench "Comp.desugEval" (nf A.desugEval aExpr),
                 bench "Comp.desugEval'" (nf A.desugEval' aExpr),
                 bench "Standard.desugEval" (nf S.desugEval sExpr),
                 bench "Comp.evalSugar" (nf A.evalSugar aExpr),
                 bench "Comp.evalDirect" (nf A.evalDirectE aExpr),
                 bench "Standard.evalSugar" (nf S.evalSugar sExpr),
                 bench "Comp.desugEval2" (nf A.desugEval2 aExpr),
                 bench "Comp.desugEval2'" (nf A.desugEval2' aExpr),
                 bench "Standard.desugEval2" (nf S.desugEval2 sExpr),
                 bench "Comp.evalSugar2" (nf A.evalSugar2 aExpr),
                 bench "Comp.evalDirect2" (nf A.evalDirectE2 aExpr),
                 bench "Standard.evalSugar2" (nf S.evalSugar2 sExpr),
                 bench "Comp.contVar" (nf (A.contVar 10) aExpr),
                 bench "Comp.contVar'" (nf (A.contVar' 10) aExpr),
                 bench "Comp.contVarGen" (nf (A.contVarGen 10) aExpr),
                 bench "Standard.contVar" (nf (S.contVar 10) sExpr),
                 bench "Standard.contVarGen" (nf (S.contVarGen 10) sExpr),
                 bench "Comp.freeVars" (nf A.freeVars aExpr),
                 bench "Comp.freeVars'" (nf A.freeVars' aExpr),
                 bench "Comp.freeVarsGen" (nf A.freeVarsGen aExpr),
                 bench "Standard.freeVars" (nf S.freeVars sExpr),
                 bench "Standard.freeVarsGen" (nf S.freeVarsGen sExpr)
                                      ]

randStdBenchmarks :: Int -> IO Benchmark
randStdBenchmarks s = do
  rand <- newQCGen
  let ty = unGen arbitrary rand s
  putStr "size of the type term: "
  print $ size ty
  print $ ty
  let aExpr = unGen (genTyped ty) rand s
      sExpr = transSugar aExpr
  putStr "size of the input term: "
  print $ size aExpr
  putStr "does it type check: "
  print (A.desugType aExpr == Right ty)
  return $ standardBenchmarks (sExpr,aExpr, "random (depth: " ++ show s ++ ", size: "++ show (size aExpr) ++ ")")

main = do b1 <- randStdBenchmarks 5
          b2 <- randStdBenchmarks 10
          b3 <- randStdBenchmarks 20
          let b0 = standardBenchmarks (sExpr, aExpr, "hand-written")
          defaultMain $ [b0,b1,b2,b3]


text:
#include <stdbool.h>

/*
 * Queue data type.
 */
struct Queue {
	unsigned int size;
	struct Node *front;
	struct Node *back;
};

struct Node {
	int data;
	struct Node *next;
};

/*
 * Queue prototypes.
 */
void
enqueue(struct Queue *q, int data);

void
dequeue(struct Queue *q);

bool
is_empty(struct Queue *q);

void
free_queue(struct Queue *q);


text:
using BellRichM.Weather.Api.Data;
using BellRichM.Weather.Api.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BellRichM.Weather.Api.Repositories
{
    /// <summary>
    /// The condition repository.
    /// </summary>
    public interface IConditionRepository
    {
        /// <summary>
        /// Get the condition for years.
        /// </summary>
        /// <param name="offset">The starting offset.</param>
        /// <param name="limit">The maximum number of years to return.</param>
        /// <returns>The <see cref="MinMaxCondition"/>.</returns>
        Task<IEnumerable<MinMaxCondition>> GetYear(int offset, int limit);

        /// <summary>
        /// Get the condition for detail for an hour.
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="month">The mont.</param>
        /// <param name="day">The day.</param>
        /// <param name="hour">The hour.</param>
        /// <returns>The <see cref="MinMaxCondition"/>.</returns>
        Task<MinMaxCondition> GetHourDetail(int year, int month, int day, int hour);

        /// <summary>
        /// Gets the total count of year records.
        /// </summary>
        /// <returns>The count.</returns>
        Task<int> GetYearCount();

        /// <summary>
        /// Gets the total count of 'day' records.
        /// </summary>
        /// <returns>The count.</returns>
        Task<int> GetDayCount();

        /// <summary>
        /// Gets the min/max conditions by minute.
        /// </summary>
        /// <param name="dayOfYear">The day of the year to get data for.</param>
        /// <param name="startHour">The hour to start at.</param>
        /// <param name="endHour">The hour to end at.</param>
        /// <param name="offset">The starting offset.</param>
        /// <param name="limit">The maximum number of minutes to return.</param>
        /// <returns>The <see cref="MinMaxGroupPage"/>.</returns>
        Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByMinute(int dayOfYear, int startHour, int endHour, int offset, int limit);

        /// <summary>
        /// Gets the min/max conditions by hour.
        /// </summary>
        /// <param name="startDayOfYear">The hour to start at.</param>
        /// <param name="endDayOfYear">The hour to end at.</param>
        /// <param name="offset">The starting offset.</param>
        /// <param name="limit">The maximum number of hours to return.</param>
        /// <returns>The <see cref="MinMaxGroupPage"/>.</returns>
        Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByHour(int startDayOfYear, int endDayOfYear, int offset, int limit);

        /// <summary>
        /// Gets the min/max conditions by day.
        /// </summary>
        /// <param name="startDayOfYear">The day of the year to start at.</param>
        /// <param name="endDayOfYear">The day of the year to end at.</param>
        /// <param name="offset">The starting offset.</param>
        /// <param name="limit">The maximum number of days to return.</param>
        /// <returns>The <see cref="MinMaxGroup"/>.</returns>
        Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByDay(int startDayOfYear, int endDayOfYear, int offset, int limit);

        /// <summary>
        /// Gets the min/max conditions by week.
        /// </summary>
        /// <param name="startWeekOfYear">The week of the year to start at.</param>
        /// <param name="endWeekOfYear">The week of the year to end at.</param>
        /// <param name="offset">The starting offset.</param>
        /// <param name="limit">The maximum number of weeks to return.</param>
        /// <returns>The <see cref="MinMaxGroupPage"/>.</returns>
        Task<IEnumerable<MinMaxGroup>> GetMinMaxConditionsByWeek(int startWeekOfYear, int endWeekOfYear, int offset, int limit);

        /// <summary>
        /// Gets the conditions grouped (averaged) by day and within a time period.
        /// </summary>
        /// <param name="offset">The starting offset.</param>
        /// <param name="limit">The maximum number of years to return.</param>
        /// <param name="timePeriodModel">The time period.</param>
        /// <returns>The observations.</returns>
        Task<IEnumerable<Condition>> GetConditionsByDay(int offset, int limit, TimePeriodModel timePeriodModel);
    }
}


text:
from datetime import datetime
from flask import Flask, request, jsonify, g, render_template
from werkzeug.exceptions import BadRequest, Unauthorized
import collections
import sqlite3
from db import DB

app = Flask(__name__)

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = DB()
    return db

@app.route("/")
def hello():
    return render_template("index.html")

@app.route("/devices")
def devices():
    db = get_db()
    devices = db.get_device_details()
    for device in devices:
        last_updated = datetime.strptime(device['last_updated'],
                                         "%Y-%m-%d %H:%M:%S.%f")
        seen_ago = datetime.utcnow() - last_updated
        device['seen_ago'] = "Status expires in {}s".format(
            device['holdtime'] - seen_ago.seconds)
        if seen_ago.seconds > device['holdtime']:
            device['status'] = "dead"
        else:
            device['status'] = "alive"
    return render_template("devices.html", devices=devices)

@app.route('/device/<int:dev_id>')
def device(dev_id):
    db = get_db()
    device = db.get_device_details(dev_id)
    print(device)
    return render_template('device.html', device=device[0])

@app.route('/api/register',methods=['POST'])
def register():
    db = get_db()
    data = request.get_json()
    print(data)
    response = db.update_device(data)
    return jsonify(response)

@app.route("/api/devices")
def api_devices():
    db = get_db()
    devices = db.get_device_details()
    return jsonify(devices)

@app.teardown_appcontext
def close_connection(exception):
    db = get_db()
    db.close()

if __name__ == "__main__":
    app.run(host="::", debug=True)


text:
namespace sandbox {

// Operation result codes returned by the sandbox API.
enum ResultCode {
  SBOX_ALL_OK = 0,
  // Error is originating on the win32 layer. Call GetlastError() for more
  // information.
  SBOX_ERROR_GENERIC = 1,
  // An invalid combination of parameters was given to the API.
  SBOX_ERROR_BAD_PARAMS = 2,
  // The desired operation is not supported at this time.
  SBOX_ERROR_UNSUPPORTED = 3,
  // The request requires more memory that allocated or available.
  SBOX_ERROR_NO_SPACE = 4,
  // The ipc service requested does not exist.
  SBOX_ERROR_INVALID_IPC = 5,
  // The ipc service did not complete.
  SBOX_ERROR_FAILED_IPC = 6,
  // The requested handle was not found.
  SBOX_ERROR_NO_HANDLE = 7,
  // This function was not expected to be called at this time.
  SBOX_ERROR_UNEXPECTED_CALL = 8,
  // WaitForAllTargets is already called.
  SBOX_ERROR_WAIT_ALREADY_CALLED = 9,
  // A channel error prevented DoCall from executing.
  SBOX_ERROR_CHANNEL_ERROR = 10,
  // Failed to create the alternate desktop.
  SBOX_ERROR_CANNOT_CREATE_DESKTOP = 11,
  // Failed to create the alternate window station.
  SBOX_ERROR_CANNOT_CREATE_WINSTATION = 12,
  // Failed to switch back to the interactive window station.
  SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION = 13,
  // Placeholder for last item of the enum.
  SBOX_ERROR_LAST
};

// If the sandbox cannot create a secure environment for the target, the
// target will be forcibly terminated. These are the process exit codes.
enum TerminationCodes {
  SBOX_FATAL_INTEGRITY = 7006,       // Could not set the integrity level.
  SBOX_FATAL_DROPTOKEN = 7007,       // Could not lower the token.
  SBOX_FATAL_FLUSHANDLES = 7008,     // Failed to flush registry handles.
  SBOX_FATAL_CACHEDISABLE = 7009     // Failed to forbid HCKU caching.
};

class TargetServices;
class BrokerServices;

// Contains the pointer to a target or broker service. Older code used
// a union so the |legacy| member is there for us to detect we are
// being passed a SandboxInterfaceInfo by old code. If legacy is not
// null it means we are dealing with old code a must copy this value
// into both |broker_services| and |target_services|.
struct SandboxInterfaceInfo {
  void* legacy;
  BrokerServices* broker_services;
  TargetServices* target_services;
};

#if SANDBOX_EXPORTS
#define SANDBOX_INTERCEPT extern "C" __declspec(dllexport)
#else
#define SANDBOX_INTERCEPT extern "C"
#endif

enum InterceptionType {
  INTERCEPTION_INVALID = 0,
  INTERCEPTION_SERVICE_CALL,    // Trampoline of an NT native call
  INTERCEPTION_EAT,
  INTERCEPTION_SIDESTEP,        // Preamble patch
  INTERCEPTION_SMART_SIDESTEP,  // Preamble patch but bypass internal calls
  INTERCEPTION_UNLOAD_MODULE,   // Unload the module (don't patch)
  INTERCEPTION_LAST             // Placeholder for last item in the enumeration
};

}  // namespace sandbox

#endif  // SANDBOX_SRC_SANDBOX_TYPES_H_


text:
struct sl_display {
    struct wegl_display wegl;
};

DEFINE_CONTAINER_CAST_FUNC(sl_display,
                           struct sl_display,
                           struct wegl_display,
                           wegl)

struct wcore_display*
sl_display_connect(struct wcore_platform *wc_plat, const char *name);

bool
sl_display_destroy(struct wcore_display *wc_self);


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for VmDiskFileQueryFlags complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="VmDiskFileQueryFlags">
 *   <complexContent>
 *     <extension base="{urn:vim25}DynamicData">
 *       <sequence>
 *         <element name="diskType" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *         <element name="capacityKb" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *         <element name="hardwareVersion" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *         <element name="controllerType" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="diskExtents" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="thin" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VmDiskFileQueryFlags", propOrder = {
    "diskType",
    "capacityKb",
    "hardwareVersion",
    "controllerType",
    "diskExtents",
    "thin"
})
public class VmDiskFileQueryFlags
    extends DynamicData
{

    protected boolean diskType;
    protected boolean capacityKb;
    protected boolean hardwareVersion;
    protected Boolean controllerType;
    protected Boolean diskExtents;
    protected Boolean thin;

    /**
     * Gets the value of the diskType property.
     *
     */
    public boolean isDiskType() {
        return diskType;
    }

    /**
     * Sets the value of the diskType property.
     *
     */
    public void setDiskType(boolean value) {
        this.diskType = value;
    }

    /**
     * Gets the value of the capacityKb property.
     *
     */
    public boolean isCapacityKb() {
        return capacityKb;
    }

    /**
     * Sets the value of the capacityKb property.
     *
     */
    public void setCapacityKb(boolean value) {
        this.capacityKb = value;
    }

    /**
     * Gets the value of the hardwareVersion property.
     *
     */
    public boolean isHardwareVersion() {
        return hardwareVersion;
    }

    /**
     * Sets the value of the hardwareVersion property.
     *
     */
    public void setHardwareVersion(boolean value) {
        this.hardwareVersion = value;
    }

    /**
     * Gets the value of the controllerType property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isControllerType() {
        return controllerType;
    }

    /**
     * Sets the value of the controllerType property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setControllerType(Boolean value) {
        this.controllerType = value;
    }

    /**
     * Gets the value of the diskExtents property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isDiskExtents() {
        return diskExtents;
    }

    /**
     * Sets the value of the diskExtents property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setDiskExtents(Boolean value) {
        this.diskExtents = value;
    }

    /**
     * Gets the value of the thin property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isThin() {
        return thin;
    }

    /**
     * Sets the value of the thin property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setThin(Boolean value) {
        this.thin = value;
    }

}


text:
package ast

import (
  "fmt"
  "github.com/kedebug/LispEx/scope"
  . "github.com/kedebug/LispEx/value"
)

type Force struct {
  Promise Node
}

func NewForce(promise Node) *Force {
  return &Force{Promise: promise}
}

func (self *Force) Eval(s *scope.Scope) Value {
  val := self.Promise.Eval(s)
  if promise, ok := val.(*Promise); ok {
    if promise.IsVal == false {
      return nil
    } else {
      promise.IsVal = false
      env := promise.Env.(*scope.Scope)
      lazy := promise.Lazy.(Node)
      return lazy.Eval(env)
    }
  } else {
    panic(fmt.Sprintf("force: expected argument of type <promise>, given: %s", val))
  }
}

func (self *Force) String() string {
  return fmt.Sprintf("(force %s)", self.Promise)
}


text:
using System;
using System.IO;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using Fido_Main.Fido_Support.ErrorHandling;
using Fido_Main.Fido_Support.Objects.Fido;
using Fido_Main.Main.Receivers;
//using Fido_Main.Logger;

namespace Fido_Main
{
  public partial class FidoMain : Form
  {
    public FidoMain()
    {
      InitializeComponent();
    }

    //The load will grab configurations for what FIDO is monitoring,
    //then go to each configured external system to parse any alerts.
    //Finally, FIDO is configured to pause per iteration on a
    //configurable timed basis.
    private void Fido_Load(object sender, EventArgs aug)
    {
      //Disabled the current time during current iteration.
      timer1.Enabled = false;
      Hide();

      //Check to see if Fido configurations exists and if not
      //fail with prompt that configurations are not found.
      Console.Clear();
      var sAppStartupPath = Application.StartupPath + @"\data\fido.db";
      if (!File.Exists(sAppStartupPath))
      {
        Console.WriteLine(@"Failed to load FIDO DB.");
        Application.Exit();
      }
      else {Console.WriteLine(@"Loaded FIDO DB successfully.");}

      //Load fido configs from database
      Object_Fido_Configs.LoadConfigFromDb("config");

      //Setup syslog
      var server1 = Object_Fido_Configs.GetAsString("fido.logger.syslog.server", "localhost");
      var port1 = Object_Fido_Configs.GetAsInt("fido.logger.syslog.port", 514);
      var facility1 = Object_Fido_Configs.GetAsString("fido.logger.syslog.facility", "local1");
      var sender1 = Object_Fido_Configs.GetAsString("fido.logger.syslog.sender", "Fido");
      var layout1 = Object_Fido_Configs.GetAsString("fido.logger.syslog.layout", "$(message)");
      //SysLogger.Setup(server1, port1, facility1, sender1, layout1);

      //Beginning of primary area which starts parsing of alerts.
      var isParamTest = Object_Fido_Configs.GetAsBool("fido.application.teststartup", true);
      var sDetectors = Object_Fido_Configs.GetAsString("fido.application.detectors", string.Empty).Split(',');

      try
      {
        Console.WriteLine(isParamTest ? @"Running test configs." : @"Running production configs.");

        foreach (var detect in sDetectors)
        {
          var parseConfigs = Object_Fido_Configs.ParseDetectorConfigs(detect);
          //Get the detector, ie, email, log, web service, etc.
          var sDetectorType = parseConfigs.DetectorType;
          switch (sDetectorType)
          {
            case "api":
              Console.WriteLine(@"Loading webservice receiver.");
              Recieve_API.DirectToEngine(sDetectorType, detect);
              break;

            case "log":
              Console.WriteLine(@"Loaded log receiver.");
              var sDefaultServer = parseConfigs.Server;
              var sDefaultFile = parseConfigs.File;
              var sVendor = parseConfigs.Vendor;
              Receive_Logging.DirectToEngine(detect, sVendor, sDefaultServer, sDefaultFile, isParamTest);
              break;

            case "sql":
              Console.WriteLine(@"Loaded sql receiver.");
              Receive_SQL.DirectToEngine(sDetectorType, detect);
              break;

            case "email":
              Console.WriteLine(@"Loaded email receiver.");
              var sEmailVendor = Object_Fido_Configs.GetAsString("fido.email.vendor", "imap");
              var sDetectorsEmail = parseConfigs.EmailFrom;
              var sDetectorsFolder = parseConfigs.Folder;
              Receive_Email.ReadEmail(sEmailVendor, sDetectorsFolder, null, sDetectorsEmail, isParamTest);
              break;
          }
        }
      }
      catch (Exception e)
      {
        Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught in fidomain area:" + e);
      }

      //Sleep for X # of seconds per iteration specified in Fido configuration
      Application.DoEvents();
      var iSleep = Object_Fido_Configs.GetAsInt("fido.application.sleepiteration", 5);
      Console.WriteLine(@"Fido processing complete... sleeping for " + (iSleep / 1000).ToString(CultureInfo.InvariantCulture) + @" seconds.");
      Thread.Sleep(iSleep);
      timer1.Enabled = true;

    }

    //Configurable timer to run Fido
    private void Timer1Tick(object sender, EventArgs e)
    {
      try
      {
        Application.DoEvents();
        Fido_Load(null, null);

        //todo: make the below integer value configurable
        Thread.Sleep(2000);
      }
      catch (Exception ex)
      {
        Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Exception caught in fidomain area:" + ex);
      }

    }

    //todo: do something with this timer or remove it.
    private void timer2_Tick(object sender, EventArgs e)
    {
      Application.DoEvents();
    }
  }
}


text:
import template from './attachments.htm';

const attachments = {
  replace: true,
  template,
};

export default function() {
  return attachments;
}


text:
package fswatcher

import (
	"github.com/bazelbuild/bazel-watcher/internal/ibazel/fswatcher/common"
	"github.com/bazelbuild/bazel-watcher/internal/ibazel/fswatcher/fsnotify"
)

func NewWatcher() (common.Watcher, error) {
	return fsnotify.NewWatcher()
}


text:
class PapertrailLogHandler : public LogHandler {
    String m_host;
    uint16_t m_port;
    String m_app;
    String m_system;
    UDP m_udp;
    bool m_inited;
    IPAddress m_address;

public:
    /// Initialize the log handler.
    /// \param host Hostname of the Papertrail log server.
    /// \param port Port of the Papertrail log server.
    /// \param app The name of the application in every log entry.
    /// \param system The name of the system in every log entry. Defaults to the deviceID.
    /// \para level Default log level.
    /// \param filters Category filters.
    ///
    /// Each log entry uses RFC 5424 with the following format:
    /// "<22>1 %ISO8601_TIME% %system% %app% - - - [%category%] %log_level%: %text".
    explicit PapertrailLogHandler(String host, uint16_t port, String app, String system = System.deviceID(),
                                  LogLevel level = LOG_LEVEL_INFO, const LogCategoryFilters &filters = {});
    virtual ~PapertrailLogHandler();

private:

    bool lazyInit();
    const char* extractFileName(const char *s);
    const char* extractFuncName(const char *s, size_t *size);
    void log(String message);
    static IPAddress resolve(const char *host);
    static const uint16_t kLocalPort;

protected:
    virtual void logMessage(const char *msg, LogLevel level, const char *category, const LogAttributes &attr) override;
};


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>mPurpose - Multipurpose Feature Rich Bootstrap Template</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/icomoon-social.css">
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600,800' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="css/leaflet.css" />

		<link rel="stylesheet" href="css/main.css">

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

78% Funded

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

84% Funded

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

26% Funded
(Hurry)

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

78% Funded

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

78% Funded

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

38% Funded
(5 days left)

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

78% Funded

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

78% Funded

								    	Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

										Lorem ipsum dolor sit amet

16% Funded
(2 days left)

Previous

1

2

3

4

5

6

7

8

9

10

Next


text:
package kaflib.gui.components;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.swing.JScrollPane;

import kaflib.graphics.Canvas;
import kaflib.graphics.GraphicsUtils;

public class ScrolledImageComponent extends KPanel {

	private static final long serialVersionUID = -163026813414707128L;
	private final JScrollPane scroll;
	private StaticImageComponent image;
	private Dimension preferred_size;

	public ScrolledImageComponent() {
		this(null, null);
	}

	public ScrolledImageComponent(final Integer width, final Integer height) {
		scroll = new JScrollPane();
		image = new StaticImageComponent(3, Color.BLACK, null);
		scroll.setViewportView(image);
		add(scroll);
		if (width != null && height != null) {
			preferred_size = new Dimension(width, height);
		}
	}

	public void set(final File file) throws Exception {
		set(GraphicsUtils.read(file));
	}

	public void set(final BufferedImage image) throws Exception {
		this.image.set(image);
	}

	public void set(final Canvas canvas) throws Exception {
		set(canvas.toBufferedImage());
	}

	public Dimension getPreferredSize() {
		if (preferred_size == null) {
			return super.getPreferredSize();
		}
		else {
			return preferred_size;
		}
	}

	public static void main(String args[]) {
		try {
			File file = new File("data/flag.jpg");
			ScrolledImageComponent image = new ScrolledImageComponent(400, 200);
			image.set(file);
			new KFrame(image);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ECQRS.Commons.Repositories;

namespace ECQRS.SqlServer.Bus.Entities
{
    public class QueueEntity:IEntity
    {
        public Guid Id { get; set; }
        public String QueueId { get; set; }
        public bool IsMultiple { get; set; }
    }
}


text:
layout: default
---

{% include header.html %}
{% include hero.html color=site.data.info.theme_color %}

{%- for section in page.sections -%}

{%- capture background_color -%} {% cycle "#fff", "#fafafa" %} {%- endcapture -%}

{% include section.html background_color=background_color section=section color=site.data.info.theme_color %}

{%- if forloop.last == true -%}
{%- capture background_color -%} {% cycle "#fff", "#fafafa" %} {%- endcapture -%}
{%- endif -%}

{%- endfor -%}

        {{ site.data.info.email_signup_copy | markdownify }}

        {% include forms/email-signup.html %}

{% include footer.html %}


text:
import java.util.Arrays;

/*
 * Computing Normalized edit distance using dynamic programming
 * This algorithm doesn't store an entire table, instead it remember only
 * the last two rows computed in the table.
 */

public class EditDistance {

	public static float findNormalizedEditDistance(String s1, String s2){

		int[] topRow = new int[s1.length()+1];
		int[] bottomRow = new int[s1.length()+1];
		int topDownIndex = 0;
		float normalizedEditDistance = 0.0F;

		// Initialize topRow once
		for (int i = 0; i < topRow.length; i++) {
			topRow[i] = i;
		}

		//Method call to compute the bottomRow - Recursive Method
		computeNextRow(s1.toCharArray(), s2.toCharArray(), topRow, topDownIndex, bottomRow);

		// Print the last row
		//System.out.println(Arrays.toString(bottomRow));

		// Last value of the last row is the edit distance
		// Computing Normalized edit distance using the formula dN = (|s1|+|s2|-d)/(|s1|+|s2|)
		normalizedEditDistance = (float)(s1.length()+s2.length()-bottomRow[bottomRow.length-1])/(float)(s1.length()+s2.length());

		return normalizedEditDistance;
	}

	private static void computeNextRow(char[] s1, char[] s2, int[] topRow, int topDownIndex, int[] bottomRow){

		// Computing the current row using the values of previous row
		bottomRow[0] = topDownIndex+1;
		for (int i = 1; i < bottomRow.length; i++) {

			if (s2[topDownIndex] == s1[i-1]) {
				bottomRow[i] = topRow[i-1];
			}  else {
				bottomRow[i] = (bottomRow[i-1] < topRow[i])? bottomRow[i-1] + 1 : topRow[i] + 1;
			}
		}

		// [***Exit Check***]
		//Check for the 'topDownIndex' reached the last symbol of the top-down string
		if(topDownIndex == s2.length - 1){
			return;
		}

		//Since arrays are passed by reference, copying the bottom row to top row and making bottom row to empty
		for (int i = 0; i < topRow.length; i++) {
			topRow[i] = bottomRow[i];
		}
		Arrays.fill(bottomRow, 0);

		//Tail recursion will takes place until it matched the exit check
		computeNextRow(s1, s2, topRow, topDownIndex+1, bottomRow);
	}

}


text:
from __future__ import unicode_literals

import pytest

from nidhogg.core import NidhoggException
from nidhogg.sevenmode import SevenMode
from nidhogg.clustermode import ClusterMode

pytestmark = pytest.mark.usefixtures(
    "patch_timeout",
)

@pytest.mark.parametrize('mode', [
    (ClusterMode, {'@status': "passed", 'status': "resizing"}),
    (SevenMode, {'@status': "passed", 'status': "resizing"})
], indirect=True)
def test_set_quota_time_out(mode):
    with pytest.raises(NidhoggException):
        mode.set_quota("volume", "qtree", 1000, True)

@pytest.mark.parametrize('mode', [
    (ClusterMode, {'@status': "passed", 'status': "resizing"}),
    (SevenMode, {'@status': "passed", 'status': "resizing"})
], indirect=True)
def test_set_quota_time_out_ignored(mode):
    mode.set_quota("volume", "qtree", 1000, False)


text:
All Notable changes to `client-side-validation` will be documented in this file

## 1.2.0
- Change CSS class naming
- Add CSS class for valid fields

## 1.1.0
- Add/remove CSS class to fields
- Allow jquery 3

## 1.0.0
- Initial release


text:
package com.allanvital.games.quick.battles.gameplay.actor;

import com.allanvital.games.quick.battles.gameplay.Position;
import com.allanvital.games.quick.battles.texture.TexturePathsConstants;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;

public class Peasant extends MovablePrintableSoldier {

	public Peasant(Position position) {
		super(position, new Texture(Gdx.files.internal(TexturePathsConstants.PEASANT_SPRITE)));
	}

	@Override
	public String toString() {
		return "<PEASANT " + super.getPosition() + ">";
	}

	@Override
	public float getSpeed() {
		if (isBattling) {
			return 0.2f;
		}
		return 1.5f;
	}

}


text:
package net.bis5.mattermost.model;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import lombok.Getter;
import net.bis5.mattermost.model.StatusType.StatusTypeDeserializer;
import net.bis5.mattermost.model.serialize.HasCodeSerializer;

/**
 * The type of user status.
 *
 * @author Takayuki Maruyama
 */
@JsonSerialize(using = HasCodeSerializer.class)
@JsonDeserialize(using = StatusTypeDeserializer.class)
@Getter
public enum StatusType implements HasCode<StatusType> {
  OFFLINE("offline"), AWAY("away"), ONLINE("online"), DND("dnd");
  private final String code;

  private StatusType(String code) {
    this.code = code;
  }

  static class StatusTypeDeserializer extends JsonDeserializer<StatusType> {

    @Override
    public StatusType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
      String jsonValue = p.getText();
      return HasCode.of(StatusType::values, jsonValue, OFFLINE);
    }
  }
}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Javanotes 6.0, Solution to Exercise 5, Chapter 13</title>
<link type="text/css" rel="stylesheet" href="../javanotes.css">

        [ Exercises |
        Chapter Index |
        Main Index ]

Solution for Programming Exercise 13.5

<big>T</big>his page contains a sample solution to
           one of the exercises from Introduction to Programming Using Java.

Exercise 13.5:

The sample program PhoneDirectoryFileDemo.java
from Subsection 11.3.2 keeps data for a "phone directory" in a file in the user's
home directory.  Exercise 11.5 asked you to revise that program to
use an XML format for the data.  Both programs have a simple command-line user
interface.  For this exercise, you should provide a GUI interface for the
phone directory data.  You can base your program either on the original sample
program or on the modified version from the exercise.  Use a JTable
to hold the data.  The user should be able to edit all the entries in the
table.  Also, the user should be able to add and delete rows.  Include either
buttons or menu commands that can be used to perform these actions.  The
delete command should delete the selected row, if any.   New rows should be
added at the end of the table.
For this program, you can use a standard DefaultTableModel.

Your program should load data from the file when it starts and save data to the
file when it ends, just as the two previous programs do.  For a GUI program, you can't
simply save the data at the end of the main() routine, since main()
terminates as soon as the window shows up on the screen.  You want to save the
data when the user closes the window and ends the program.  There are several
approaches.  One is to use a WindowListener to detect
the event that occurs when the window closes.  Another is to use a "Quit"
command to end the program; when the user quits, you can save the data and
close the window  (by calling its dispose() method), and end the program.
If you use the "Quit" command approach, you don't want the user to be
able to end the program simply by closing the window.  To accomplish this,
you should call

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

where frame refers to the JFrame that
you have created for the program's user interface.  When using a
WindowListener, you want the close box on the window to
close the window, not end the program.  For this, you need

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

When the listener is notified of a window closed event, it can
save the data and end the program.

Most of the JTable and DefaultTableModel
methods that you need for this exercise are discussed in Subsection 13.4.3,
but there are a few more that you need to know about.  To determine
which row is selected in a JTable, call
table.getSelectedRow().  This method
returns the row number of the selected row, or returns -1 if no
row is selected.  To specify which cell is currently being edited, you can
use:

table.setRowSelectionInterval(rowNum, rowNum);  // Selects row number rowNum.
table.editCellAt( rowNum, colNum ); // Edit cell at position (rowNum,colNum).
phoneTable.getEditorComponent().requestFocus();  // Put input cursor in cell.

One particularly troublesome point is that the data that is in the cell that
is currently being edited is not in the table model.  The value in the edit cell
is not put into the table model until after the editing is finished.  This means
that even though the user sees the data in the cell, it's not really part of the
table data yet.  If you lose that data, the user would be justified in complaining.
To make sure that you get the right data when you save the
data at the end of the program, you have to turn off editing before retrieving
the data from the model.  This can be done with the following method:

private void stopEditing() {
   if (table.getCellEditor() != null)
      table.getCellEditor().stopCellEditing();
}

This method must also be called before modifying the table by adding or
deleting rows; if such modifications are made while editing is in progress,
the effect can be very strange.

<big>Discussion</big>

There are many, many ways to organize the program.  I will
discuss just one. The main GUI class in my program is a subclass of JPanel,
named PhoneDirectoryPanel.  This panel holds the table and
two buttons that are used for adding and deleting rows.
In the main() routine, the data from the file is read
into a variable of type TreeMap<String,String>.
Somehow, that data has to get into the panel.  I decided to pass it as a
parameter to a constructor of the form

public PhoneDirectoryPanel(TreeMap<String,String> initialPhoneBook)

When the program ends, the data has to be gotten back out of the
panel object so it can be saved to the file.  I defined a method in the
PhoneDirectoryPanel class that can be used to get
the data:

public TreeMap<String, String> getPhoneBook()

Aside from the constructor, some instance variables, and the getPhoneBook() method, the only
other thing in the panel class is the stopEditing() method that was mentioned in the
exercise.  While the program is running, the data is managed by the table.

In the command-line version, the code for
saving the data is at the end of the main() routine.  I
moved it into a static method

private static void saveData(TreeMap<String,String> newPhoneBook)

This method has to be called when the program ends.  I decided to use a
WindowListener to save the data when the window is closed.
The main() routine creates the window, puts a PhoneDirectoryPanel
in the window, and adds a listener to the window:

JFrame window = new JFrame("PhoneBook");
final PhoneDirectoryPanel panel = new PhoneDirectoryPanel(phoneBook);
window.setContentPane( panel );
window.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screenSize.width - window.getWidth())/2, 80 );
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
window.addWindowListener( new WindowAdapter() {
      // When the user clicks the close box of the window,
      // the window will be disposed (that is, closed), and the
      // windowClosed method in this WindowListener will be
      // called.  This method saves the phone book data and
      // calls System.exit() to terminate the program.
   public void windowClosed(WindowEvent evt) {
      saveData(panel.getPhoneBook());
      System.exit(0);
   }
});

After it does this, the main() routine ends, and the window takes
over.  The constructor of the panel class has to create a table and a table model
using the data from the TreeMap, initialPhoneBook.
To do this, it copies the data into a two-dimensional array of Strings
that can be used in the constructor for the DefaultTableModel:

int entryCount = initialPhoneBook.size();
String[][] entries;
if (entryCount == 0)
    entries = new String[1][2]; // Represents an empty row.
else {
   entries = new String[entryCount][2];
   int index = 0;
   for (Map.Entry<String, String> entry : initialPhoneBook.entrySet()) {
      entries[index][0] = entry.getKey();
      entries[index][1] = entry.getValue();
      index++;
   }
}
String[] columnHeads = new String[] { "Name", "Number" };

model = new DefaultTableModel(entries,columnHeads);
table = new JTable(model);

Note that if there are no entries in the phone book, I place one empty row
in the table, since the user would have to do that anyway before they could
do anything else with the table.  (Also, I need a real array when I create the model,
since the number of columns is taken from the size of the array.)
I also did some customization of the table's appearance.  The constructor
also creates an "Add Row" button and a "Delete Row" button.  It's worth
looking at the ActionListener for the "Add Row" button:

JButton addRowButton = new JButton("Add Row");
addRowButton.addActionListener( new ActionListener() {
   public void actionPerformed(ActionEvent evt) {
          // Add a row at the end of the table.  Also, select
          // that row and set the first cell in that row to
          // be the cell that is currently being edited.
      stopEditing();
      model.addRow( new String[] { null, null } );
      int newRow = model.getRowCount() - 1;  // Number of the row that was added.
      table.setRowSelectionInterval(newRow, newRow);
      table.editCellAt( newRow, 0 );
      Component c = table.getEditorComponent();
      if (c != null) // (Should not be null.)
         c.requestFocus();
   }
});

The statement model.addRow( new String[] { null, null } ); adds a row
at the end of the table.  The data that is to go into the cells in that row is passed
to the addRow() method as an array.  In this case, the null
values mean that both cells will initially be empty.  Before adding the row,
I call stopEditing(), as suggested in the exercise, and after
adding the row, I select the first cell in the row for editing, again following the
exercise.

The only other thing to do in the panel class is to define the getPhoneBooK() method.
This method has to get the data out of the table model and add it to a TreeMap.
One question was, what to do about empty cells in the table?  A row with one or two empty
rows represents missing or incomplete data.  One possibility is just to ignore all such
rows.  However, I decided that having a name in the phone book with no number attached to
it would be OK.  On the other hand, it doesn't make any sense to have a number without a
name, so my policy is to ignore any row in which the "name" cell is empty.  You can see
how it's done in the solution shown below.

One other issue that came up is what to do if an error occurs while trying to
read or write the data file.  The command-line version of the program simply prints
a message to standard output.  For a GUI program, however, the user probably won't
even see standard output, so sending the output there does no good.  A much
better way to report errors in a GUI program is to use the JOptionPane
class, so I converted error reports from the original program to use
JOptionPane instead of System.out.

<big>The Solution</big>

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import java.io.*;

import java.util.Map;
import java.util.TreeMap;

import javax.xml.parsers.*;
import org.w3c.dom.*;

/**
 * This program lets the user keep a persistent "phone book" that
 * contains names and phone numbers.  The data for the phone book
 * is stored in a file in the user's home directory.  This is
 * a GUI version of the program, with the phonebook displayed
 * in a table that the user can edit.  The data files for this
 * version of the program are in XML format.
 *
 * WARNING:  This program will save a file named ".phone_book_xml_demo"
 * in the home directory of the user who runs it.  On some computers,
 * this will be a "hidden" file.
 */
public class PhoneDirectoryGUI {

   /**
    * The name of the file in which the phone book data is kept.  The
    * file is stored in the user's home directory.  The "." at the
    * beginning of the file name means that the file will be a
    * "hidden" file on Unix-based computers, including Linux and
    * Mac OS X.
    */
   private static String DATA_FILE_NAME = ".phone_book_xml_demo";

   /**
    * A File object created from the absolute path name of the file.
    */
   private static File dataFile;

   /**
    * Holds the phone book data as it was read from the data file
    * when the program started.  The data in this map is not modified
    * after it has been read.
    */
   private static TreeMap<String,String> phoneBook;

   public static void main(String[] args) {

      phoneBook = new TreeMap<String,String>();
      File userHomeDirectory = new File( System.getProperty("user.home") );
      dataFile = new File( userHomeDirectory, DATA_FILE_NAME );

      /* If the data file already exists, then the data in the file is
       * read and is used to initialize the phone directory.  The user
       * is informed before the file is created and is given a chance to
       * exit the program immediately.
       */

      if ( ! dataFile.exists() ) {
         int response = JOptionPane.showConfirmDialog(null,
               "No phone book data file found.  To create a new one,\n"
                    + "click OK.  To exit the program now, click CANCEL.\n\n"
                  + "(The name of the file will be:\n      "
                  + dataFile.getAbsolutePath() + ")",
               "Create phonebook?", JOptionPane.OK_CANCEL_OPTION);
         if (response == JOptionPane.CANCEL_OPTION)
            System.exit(1);
      }
      else {
         System.out.println("Reading phone book data...");
         try {
            DocumentBuilder docReader =
               DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document xmldoc = docReader.parse(dataFile);
            Element root = xmldoc.getDocumentElement();
            if (! root.getTagName().equals("phone_directory"))
               throw new Exception();
            NodeList nodes = root.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
               if ( nodes.item(i) instanceof Element ) {
                  Element entry = (Element)nodes.item(i);
                  if (! entry.getTagName().equals("entry"))
                     throw new Exception();
                  String entryName = entry.getAttribute("name");
                  String entryNumber = entry.getAttribute("number");
                  if (entryName.length() == 0)
                     throw new Exception();
                  phoneBook.put(entryName,entryNumber);
               }
            }
         }
         catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                  "An error occurred while trying to read\n"
                  + "the phone directory from the file:\n   "
                  + dataFile.getAbsolutePath()
                  +"\n\nThis program cannot continue.");
            System.exit(1);
         }
      }

      /* The phone book has been read successfully (if it existed).  Open
       * a window where the user can view and edit the phone directory.
       */

      JFrame window = new JFrame("PhoneBook");
      final PhoneDirectoryPanel panel = new PhoneDirectoryPanel(phoneBook);
      window.setContentPane( panel );
      window.pack();
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation( (screenSize.width - window.getWidth())/2, 80 );
      window.setVisible(true);
      window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      window.addWindowListener( new WindowAdapter() {
            // When the user clicks the close box of the window,
            // the window will be disposed (that is, closed), and the
            // windowClosed method in this WindowListener will be
            // called.  This method saves the phone book data and
            // calls System.exit() to terminate the program.
         public void windowClosed(WindowEvent evt) {
            saveData(panel.getPhoneBook());
            System.exit(0);
         }
      });

   } // end main()

   /**
    * Before ending the program, write the current contents of the
    * phone directory, but only if some changes have been made to
    * the directory.  This is called by a window listener when the
    * window is closed.  If an error occurs while the data is being
    * saved, a pop-up box will inform the user (but this is unlikely).
    * @param newPhoneBook the phone book data that has possibly been
    *    edited by the user.  If this is the same as the data that
    *    was read from the file originally, this method does not
    *    re-save the unchanged data.  If the data has changed, the
    *    new data is written to the file.
    */
   private static void saveData(TreeMap<String,String> newPhoneBook) {
      if (phoneBook.equals(newPhoneBook) )
         System.out.println("No changes to phone book.");
      else{
         System.out.println("Saving phone directory changes to file " +
               dataFile.getAbsolutePath() + " ...");
         PrintWriter out;
         try {
            out = new PrintWriter( new FileWriter(dataFile) );
         }
         catch (IOException e) {
            JOptionPane.showMessageDialog(null,"Whoops!  Some error occurred while\n"
                  + "trying to save your phone book.  Sorry.");
            return;
         }
         out.println("<?xml version=\"1.0\"?>");
         out.println("<phone_directory>");
         for ( Map.Entry<String,String> entry : newPhoneBook.entrySet() ) {
            out.print("  <entry name='");
            out.print(entry.getKey());
            out.print("' number='");
            out.print(entry.getValue());
            out.println("'/>");
         }
         out.println("</phone_directory>");
         out.close();
         if (out.checkError()) {
            JOptionPane.showMessageDialog(null,"Whoops!  Some error occurred while\n"
                  + "trying to save your phone book.  Sorry.");
         }
      }
   }

   /**
    * This class defines the GUI for viewing and editing the phone
    * book.  The main program adds an object of this type to a frame.
    */
   private static class PhoneDirectoryPanel extends JPanel {

      private JTable phoneTable;        // For showing/editing the phone book.
      private DefaultTableModel model;  // The model for the table.  (This is
                                        //   where the data is actually stored.)

      /**
       * Constructor creates the table and shows it with an "Add row"
       * and a "Delete Row" button beneath it.
       * @param initialPhoneBook contains the phone book data that is initially
       *    added to the table.  (This comes from the main program and
       *    contains the data that was read from the file.)
       */
      public PhoneDirectoryPanel(TreeMap<String,String> initialPhoneBook) {

         /* First create the arrays that hold the data for the table
          * and the names of its columns.  These arrays are used to
          * create the table model.
          */

         int entryCount = initialPhoneBook.size();
         String[][] entries;
         if (entryCount == 0)
             entries = new String[1][2];
         else {
            entries = new String[entryCount][2];
            int index = 0;
            for (Map.Entry<String, String> entry : initialPhoneBook.entrySet()) {
               entries[index][0] = entry.getKey();
               entries[index][1] = entry.getValue();
               index++;
            }
         }
         String[] columnHeads = new String[] { "Name", "Number" };

         /* Create the table model from the data and column name arrays,
          * and use it to create the JTable.  After this, the official
          * phone book data is what's in the table, and the arrays and
          * initialPhoneBook are no longer used.
          */

         model = new DefaultTableModel(entries,columnHeads);
         phoneTable = new JTable(model);

         /* Customize the appearance of the table.
          */

         phoneTable.setRowHeight(27);
         phoneTable.setShowGrid(true);
         phoneTable.setGridColor(Color.BLACK);
         phoneTable.getTableHeader().setReorderingAllowed(false);

         /* Create the two buttons, and set up listeners to respond
          * when the user clicks them.
          */

         JButton addRowButton = new JButton("Add Row");
         addRowButton.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                   // Add a row at the end of the table.  Also, select
                   // that row and set the first cell in that row to
                   // be the cell that is currently being edited.
               stopEditing();
               model.addRow( new String[] { null, null } );
               int newRow = model.getRowCount() - 1;
               phoneTable.setRowSelectionInterval(newRow, newRow);
               phoneTable.editCellAt( newRow, 0 );
               Component c = phoneTable.getEditorComponent();
               if (c != null) // (Should not be null.)
                  c.requestFocus();
            }
         });

         JButton deleteRowButton = new JButton("Delete Row");
         deleteRowButton.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                   // Delete the selected row, if there is one.  If more than
                   // one cell is selected, the first selected row is deleted.
               stopEditing();
               int selectedRow = phoneTable.getSelectedRow();
               if (selectedRow >= 0)
                  model.removeRow(selectedRow);
            }
         });

         /* Build the layout for the panel.
          */

         setLayout(new BorderLayout(2,2));
         setBackground(Color.GRAY);
         setBorder(BorderFactory.createLineBorder(Color.GRAY,2));
         add( new JScrollPane(phoneTable), BorderLayout.CENTER );
         JPanel buttonBar = new JPanel();
         buttonBar.add(addRowButton);
         buttonBar.add(deleteRowButton);
         add( buttonBar, BorderLayout.SOUTH );

      } // end constructor

      /**
       * This method is called before modifying the table or getting
       * the data out of the table.  If a cell is currently being
       * edited, it turns off editing of that cell and changes the
       * data model to match the current content of the editor.  (Note
       * that the table model does not change while the cell is being
       * edited.)
       */
      private void stopEditing() {
         if (phoneTable.getCellEditor() != null)
            phoneTable.getCellEditor().stopCellEditing();
      }

      /**
       * This method is called when the program ends to get the phone
       * book data, which might have been edited by the user.  The
       * data is in the table model.  This method gets the data from
       * the table model and puts it into a TreeMap, which is then
       * returned as the value of the method.  Note that if a row in
       * the table contains an empty name, it is ignored.  However,
       * if there is an empty number for a non-empty name, the number
       * is changed to "(unknown)" and the row is added to the TreeMap.
       * Note that by using a TreeMap, we allow only one number for
       * a given name.  If the user has used the same name in more than
       * one row, the first row with that name will be lost;
       * it would probably be better to warn the user about this or to
       * take some other, more reasonable answer (like adding a number
       * to the end of the duplicate name).
       */
      public TreeMap<String, String> getPhoneBook() {
         stopEditing();
         TreeMap<String,String> phoneBook = new TreeMap<String,String>();
         for (int row = 0; row < model.getRowCount(); row++) {
            String name = (String)model.getValueAt(row, 0);
            String number = (String)model.getValueAt(row, 1);
            if (number == null || number.trim().length() == 0)
               number = "(unknown)";
            if (name != null && name.trim().length() > 0)
               phoneBook.put(name,number);
         }
         return phoneBook;
      }

   }

}

        [ Exercises |
        Chapter Index |
        Main Index ]


text:
namespace blink {

MediaValues* MediaValuesDynamic::Create(Document& document) {
  return MediaValuesDynamic::Create(document.GetFrameOfMasterDocument());
}

MediaValues* MediaValuesDynamic::Create(LocalFrame* frame) {
  if (!frame || !frame->View() || !frame->GetDocument() ||
      !frame->GetDocument()->GetLayoutView())
    return MakeGarbageCollected<MediaValuesCached>();
  return MakeGarbageCollected<MediaValuesDynamic>(frame);
}

MediaValuesDynamic::MediaValuesDynamic(LocalFrame* frame)
    : frame_(frame),
      viewport_dimensions_overridden_(false),
      viewport_width_override_(0),
      viewport_height_override_(0) {
  DCHECK(frame_);
}

MediaValuesDynamic::MediaValuesDynamic(LocalFrame* frame,
                                       bool overridden_viewport_dimensions,
                                       double viewport_width,
                                       double viewport_height)
    : frame_(frame),
      viewport_dimensions_overridden_(overridden_viewport_dimensions),
      viewport_width_override_(viewport_width),
      viewport_height_override_(viewport_height) {
  DCHECK(frame_);
}

MediaValues* MediaValuesDynamic::Copy() const {
  return MakeGarbageCollected<MediaValuesDynamic>(
      frame_, viewport_dimensions_overridden_, viewport_width_override_,
      viewport_height_override_);
}

bool MediaValuesDynamic::ComputeLength(double value,
                                       CSSPrimitiveValue::UnitType type,
                                       int& result) const {
  return MediaValues::ComputeLength(value, type,
                                    CalculateDefaultFontSize(frame_),
                                    ViewportWidth(), ViewportHeight(), result);
}

bool MediaValuesDynamic::ComputeLength(double value,
                                       CSSPrimitiveValue::UnitType type,
                                       double& result) const {
  return MediaValues::ComputeLength(value, type,
                                    CalculateDefaultFontSize(frame_),
                                    ViewportWidth(), ViewportHeight(), result);
}

double MediaValuesDynamic::ViewportWidth() const {
  if (viewport_dimensions_overridden_)
    return viewport_width_override_;
  return CalculateViewportWidth(frame_);
}

double MediaValuesDynamic::ViewportHeight() const {
  if (viewport_dimensions_overridden_)
    return viewport_height_override_;
  return CalculateViewportHeight(frame_);
}

int MediaValuesDynamic::DeviceWidth() const {
  return CalculateDeviceWidth(frame_);
}

int MediaValuesDynamic::DeviceHeight() const {
  return CalculateDeviceHeight(frame_);
}

float MediaValuesDynamic::DevicePixelRatio() const {
  return CalculateDevicePixelRatio(frame_);
}

int MediaValuesDynamic::ColorBitsPerComponent() const {
  return CalculateColorBitsPerComponent(frame_);
}

int MediaValuesDynamic::MonochromeBitsPerComponent() const {
  return CalculateMonochromeBitsPerComponent(frame_);
}

PointerType MediaValuesDynamic::PrimaryPointerType() const {
  return CalculatePrimaryPointerType(frame_);
}

int MediaValuesDynamic::AvailablePointerTypes() const {
  return CalculateAvailablePointerTypes(frame_);
}

HoverType MediaValuesDynamic::PrimaryHoverType() const {
  return CalculatePrimaryHoverType(frame_);
}

int MediaValuesDynamic::AvailableHoverTypes() const {
  return CalculateAvailableHoverTypes(frame_);
}

bool MediaValuesDynamic::ThreeDEnabled() const {
  return CalculateThreeDEnabled(frame_);
}

bool MediaValuesDynamic::InImmersiveMode() const {
  return CalculateInImmersiveMode(frame_);
}

const String MediaValuesDynamic::MediaType() const {
  return CalculateMediaType(frame_);
}

blink::mojom::DisplayMode MediaValuesDynamic::DisplayMode() const {
  return CalculateDisplayMode(frame_);
}

bool MediaValuesDynamic::StrictMode() const {
  return CalculateStrictMode(frame_);
}

DisplayShape MediaValuesDynamic::GetDisplayShape() const {
  return CalculateDisplayShape(frame_);
}

ColorSpaceGamut MediaValuesDynamic::ColorGamut() const {
  return CalculateColorGamut(frame_);
}

PreferredColorScheme MediaValuesDynamic::GetPreferredColorScheme() const {
  return CalculatePreferredColorScheme(frame_);
}

bool MediaValuesDynamic::PrefersReducedMotion() const {
  return CalculatePrefersReducedMotion(frame_);
}

ForcedColors MediaValuesDynamic::GetForcedColors() const {
  return CalculateForcedColors();
}

NavigationControls MediaValuesDynamic::GetNavigationControls() const {
  return CalculateNavigationControls(frame_);
}

ScreenSpanning MediaValuesDynamic::GetScreenSpanning() const {
  return CalculateScreenSpanning(frame_);
}

Document* MediaValuesDynamic::GetDocument() const {
  return frame_->GetDocument();
}

bool MediaValuesDynamic::HasValues() const {
  return frame_;
}

void MediaValuesDynamic::Trace(Visitor* visitor) {
  visitor->Trace(frame_);
  MediaValues::Trace(visitor);
}

void MediaValuesDynamic::OverrideViewportDimensions(double width,
                                                    double height) {
  viewport_dimensions_overridden_ = true;
  viewport_width_override_ = width;
  viewport_height_override_ = height;
}

}  // namespace blink


text:
package com.uphyca.testing;

import java.lang.reflect.InvocationTargetException;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import android.app.Instrumentation;
import android.os.Bundle;
import android.test.FlakyTest;
import android.test.RepetitiveTest;
import android.test.UiThreadTest;

class AndroidAnnotatedMethodRule implements TestRule {

    private Instrumentation fInstrumentation;

    public AndroidAnnotatedMethodRule() {
    }

    public AndroidAnnotatedMethodRule(Instrumentation instrumentation) {
        fInstrumentation = instrumentation;
    }

    @Override
    public Statement apply(final Statement statement,
                           final Description description) {
        return new Statement() {

            @Override
            public void evaluate() throws Throwable {
                //String methodName = description.getMethodName();
                //methodName.
                //FIXME How to get annotations via description ?
                //Method method = description.getTestClass().getMethod(methodName);

                //Following code taken from android.test.InstrumentationTestCase.

                int runCount = 1;
                boolean isRepetitive = false;
                if (description.getAnnotation(FlakyTest.class) != null) {
                    runCount = description.getAnnotation(FlakyTest.class).tolerance();
                } else if (description.getAnnotation(RepetitiveTest.class) != null) {
                    runCount = description.getAnnotation(RepetitiveTest.class).numIterations();
                    isRepetitive = true;
                }

                if (fInstrumentation != null && description.getAnnotation(UiThreadTest.class) != null) {
                    final int tolerance = runCount;
                    final boolean repetitive = isRepetitive;
                    final Throwable[] exceptions = new Throwable[1];
                    fInstrumentation.runOnMainSync(new Runnable() {
                        public void run() {
                            try {
                                runMethod(statement,
                                          tolerance,
                                          repetitive);
                            } catch (Throwable throwable) {
                                exceptions[0] = throwable;
                            }
                        }
                    });
                    if (exceptions[0] != null) {
                        throw exceptions[0];
                    }
                } else {
                    runMethod(statement,
                              runCount,
                              isRepetitive);
                }
            }
        };
    }

    //Taken from android.test.InstrumentationTestCase
    private void runMethod(Statement statement,
                           int tolerance,
                           boolean isRepetitive) throws Throwable {
        Throwable exception = null;

        int runCount = 0;
        do {
            try {
                statement.evaluate();
                exception = null;
            } catch (Throwable e) {
                if (e instanceof InvocationTargetException) {
                    e.fillInStackTrace();
                    exception = ((InvocationTargetException)e).getTargetException();
                } else if (e instanceof IllegalAccessException) {
                    e.fillInStackTrace();
                    exception = e;
                } else {
                    exception = e;
                }
            } finally {
                runCount++;
                // Report current iteration number, if test is repetitive
                if (isRepetitive) {
                    Bundle iterations = new Bundle();
                    iterations.putInt("currentiterations",
                                      runCount);
                    fInstrumentation.sendStatus(2,
                                                iterations);
                }
            }
        } while ((runCount < tolerance) && (isRepetitive || exception != null));

        if (exception != null) {
            throw exception;
        }
    }
}


text:
void LoadSprite(SPRITE *pSprite, LPSTR szFileName, int width, int height, int lastFrame)
{
	char szBuffer[255];
	int i = 0;

	// Set the sprites bitmapCount so it knows when to start over when animating
	pSprite->lastFrame = lastFrame - 1;

	// Initialize the currentFrame to 0 (start at the first frame)
	pSprite->currentFrame= 0;

	// Set the sprite animation to the first state (NORTH)
	SetSpriteState(pSprite, NORTH);

	// Set the sprites speed to default
	SetSpriteSpeed(pSprite, 5, 5);

	// Call our load bitmap function and pass in the bitmap to load
	pSprite->hBitmap = LoadABitmap(szFileName);

	// If we didn't receive a valid HBITMAP back, it didn't find the bitmap name
	if(!pSprite->hBitmap)
	{
		// Store the bitmap file name in a buffer with a sentence to display
		sprintf(szBuffer, "Can't find the bitmap: %s!", szFileName);

		// Display a dialog box that says the error message and file name
		MessageBox(NULL, szBuffer, "Error!", MB_OK);

		// Quit the program
		exit(0);
	}

	// Set the width and height of the sprite
	pSprite->width = width;
	pSprite->height = height;
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    SetSpritePosition()
///// DESCRIPTION: This sets the sprite's x and y position
///// INPUT:       x, y    - The x and y position where the sprite is displayed
///// OUTPUT:      pSprite - The sprite that we want to change it's position
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void SetSpritePosition(SPRITE *pSprite, int x, int y)
{
	// Set the x and y position of the sprite to the x and y passed in
	pSprite->position.x = x;
	pSprite->position.y = y;
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    SetSpriteState()
///// DESCRIPTION: This sets the sprite's state such as WEST, NORTH, etc...
///// INPUT:       whichState - This is the state (#define for which animation)
///// OUTPUT:      pSprite - The sprite that we want to change it's position
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void SetSpriteState(SPRITE *pSprite, int whichState)
{
	// Set the sprites state such as WEST, EAST, etc...
	pSprite->state = whichState;
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    SetSpriteSpeed()
///// DESCRIPTION: This sets the sprite's x and y speed (in pixels)
///// INPUT:       xSpeed, ySpeed    - The x and y speed of the sprite
///// OUTPUT:      pSprite - The sprite that we want to change it's position
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void SetSpriteSpeed(SPRITE *pSprite, int xSpeed, int ySpeed)
{
	// Set the X and Y speed of the sprite
	pSprite->speed.x = xSpeed;
	pSprite->speed.y = ySpeed;
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    AnimateNextFrame()
///// DESCRIPTION: This returns TRUE every time we want to display the next
/////			   frame of animation.  Say we wanted 30 frames of animation
/////			   per second, it would return TRUE 30 times every second.
///// INPUT:       desiredFrameRate - The desired frame rate we want (ie. 30 fps)
///// OUTPUT:      nothing
///// RETURN:      TRUE/FALSE - Depending if the time passed is adequate
/////
//////////////////////////////////////////////////////////////////////////

BOOL AnimateNextFrame(int desiredFrameRate)
{
	static float lastTime = GetTickCount() * 0.001f;
	static float elapsedTime = 0.0f;

	float currentTime = GetTickCount() * 0.001f; // Get the time (milliseconds = seconds * .001)
	float deltaTime = currentTime - lastTime; // Get the slice of time
	float desiredFPS = 1.0f / desiredFrameRate; // Store 1 / desiredFrameRate

	elapsedTime += deltaTime; // Add to the elapsed time
	lastTime = currentTime; // Update lastTime

	// Check if the time since we last checked is greater than our desiredFPS
	if( elapsedTime > desiredFPS )
	{
		elapsedTime -= desiredFPS; // Adjust the elapsed time

		// Return true, to animate the next frame of animation
		return TRUE;
	}

	// We don't animate right now.
	return FALSE;
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    CalculateFrameRate()
///// DESCRIPTION: This Calculates the frames per second and stores it in the window title
///// INPUT:       hWnd - The handle to the window to display the result
///// OUTPUT:      nothing
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void CalculateFrameRate(HWND hWnd)
{
	static float fFPS      = 0.0f;
    static float fLastTime = 0.0f;
    static DWORD dwFrames  = 0;
	char strFrameRate[55] = {0};

    // Keep track of the time lapse and frame count
    float fTime = GetTickCount() * 0.001f; // Convert time to seconds
    ++dwFrames;

    // If our current time minus the last recorded time is great than 1 second, start over
    if( fTime - fLastTime > 1.0f)
    {
		// Store the current time to test again
        fLastTime = fTime;

		// Store our Frames Per Second Into a buffer
		sprintf(strFrameRate, "Frames Per Second: %d", dwFrames);

		// Display the Frames Per Second in our window title
		SetWindowText(hWnd, strFrameRate);

		// Reset the frames
		dwFrames  = 0;
    }
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    AnimateSprite()
///// DESCRIPTION: This displays the current frame of animation, then increases it.
///// INPUT:       nothing
///// OUTPUT:      pBuffer - The back buffer to draw to
/////			   pSprite - The sprite to animate
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void AnimateSprite(BUFFER *pBuffer, SPRITE *pSprite)
{
	// This holds the rectangle coordinates we want to display from the bitmap
	RECT rPortion;
	// This gets the y value in which we want to start at.
	// ie. If it's the third frame, we want to go down the file 3 times the height
	int yPos = pSprite->currentFrame * pSprite->height + 1 + pSprite->currentFrame + ((pSprite->lastFrame + 1) * pSprite->state) +
				     (pSprite->state * ((pSprite->lastFrame + 1) * pSprite->height));

	// Fill in the structure with coordinated we need to get from the bitmap
	rPortion.left = 1;
	rPortion.top =  yPos;
	rPortion.right = pSprite->width + 1;
	rPortion.bottom = yPos + pSprite->height;

	// Display the currentBitmap indexed into the hBitmap array.
	// This function calls TransparentBlit() which leaks memory on win98.
	// A future tutorial should fix this by writing our own function for transparency.
	DisplayTransparentBitmap(pBuffer, pSprite->hBitmap,
						   pSprite->position.x, pSprite->position.y, rPortion);

	// Increment to the next frame
	pSprite->currentFrame++;

	// Check if we reached the end of the animation
	if(pSprite->currentFrame > pSprite->lastFrame)
	{
		// Reset the currentBitmap to the beginning
		pSprite->currentFrame = 0;
	}

}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    MoveSprite()
///// DESCRIPTION: This Moves the sprite on screen depending on it's direction and speed
/////              You will most likely want to change this for your games
///// INPUT:       nothing
///// OUTPUT:      pSprite - The sprite to be moved
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void MoveSprite(SPRITE *pSprite)
{
	// Check the sprites direction
	switch(pSprite->state)
	{
		case NORTH:
			// Move the sprite north
			SetSpritePosition(pSprite, pSprite->position.x, pSprite->position.y - pSprite->speed.y);
			break;
		case SOUTH:
			// Move the sprite south
			SetSpritePosition(pSprite, pSprite->position.x, pSprite->position.y + pSprite->speed.y);
			break;
		case EAST:
			// Move the sprite east
			SetSpritePosition(pSprite, pSprite->position.x + pSprite->speed.x, pSprite->position.y);
			break;
		case WEST:
			// Move the sprite west
			SetSpritePosition(pSprite, pSprite->position.x - pSprite->speed.x, pSprite->position.y);
			break;
	}
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    EraseSprite()
///// DESCRIPTION: This replaces the sprite with a potion of the background
///// INPUT:       hBackground - The bitmap that holds the background
///// OUTPUT:      pBuffer - The back buffer to draw to
/////			   pSprite - The sprite to erase
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void EraseSprite(BUFFER *pBuffer, SPRITE *pSprite, HBITMAP hBackground)
{
	// Store the portion of the background that we need to redraw
	// We add and subtract the speed because if we switch states it sometimes moves
	// Without erasing the current position.  Try and see for yourself.  delete the speed from here and below
	RECT Portion= {pSprite->position.x - pSprite->speed.x,
				   pSprite->position.y - pSprite->speed.y,
				   pSprite->position.x + pSprite->width + pSprite->speed.x,
				   pSprite->position.y + pSprite->height + pSprite->speed.y};

	// Display only the portion of the background that needs to be redrawn
	DisplayPortionOfBitmap(pBuffer, hBackground, pSprite->position.x - pSprite->speed.x, pSprite->position.y - pSprite->speed.y, Portion);
}

//////////////////////////////////////////////////////////////////////////
/////
///// FUNCTION:    FreeSprite()
///// DESCRIPTION: This frees the sprite and it's associated hBitmaps
///// INPUT:       nothing
///// OUTPUT:      pSprite - The sprite to free
///// RETURN:      nothing
/////
//////////////////////////////////////////////////////////////////////////

void FreeSprite(SPRITE *pSprite)
{
	// Check if the handle to the bitmap is valid
	if(pSprite->hBitmap)
	{
		// Free the hBitmap
		DeleteObject(pSprite->hBitmap);
	}
}

////////////////////////////////////////////////////////////////////
//
// *Quick Notes*
//
// Most of these functions could remain the same, except the MoveSprite().
// This one is specific to your game, so feel free to change it.
// You will probably want to include this whole .cpp with your other apps.
//
//