text:
declare module '@horizon/client' {
    import { Observable } from 'rxjs';
    import { WebSocketSubject } from "rxjs/observable/dom/WebSocketSubject";

import * as Horizon from '@horizon/client';
    namespace hz {
        interface Feed {
            watch(options?: { rawChanges: boolean }): Observable<any>;
            fetch(): Observable<any>;
        }

        type Bound = 'open' | 'closed';
        type Direction = 'ascending' | 'descending';
        type Primitive = boolean | number | string | Date;
        type IdValue = Primitive | Primitive[] | { id: Primitive } | any;
        type WriteOp = Object | Object[];

        interface TermBase extends Feed {
            find(value: IdValue): TermBase;
            findAll(...values: IdValue[]): TermBase;

            order(fields: string, direction?: Direction): TermBase;
            limit(size: Number): TermBase;
            above(spec: any, bound?: Bound): TermBase;
            below(spec: any, bound?: Bound): TermBase;
        }

        interface Collection extends TermBase {
            store(docs: WriteOp): Observable<any>;
            upsert(docs: WriteOp): Observable<any>;
            insert(docs: WriteOp): Observable<any>;
            replace(docs: WriteOp): Observable<any>;
            update(docs: WriteOp): Observable<any>;

            remove(docs: IdValue): Observable<any>;
            removeAll(docs: IdValue[]): Observable<any>;
        }

        interface User extends Feed {
            fetch(): WebSocketSubject<any>;
         }

        interface HorizonInstance {
            (name: string): Collection;

            currentUser(): User;

            hasAuthToken(): boolean;
            authEndpoint(name: string): Observable<string>;

            aggregate(aggs: any): TermBase;
            model(fn: Function): TermBase;

            disconnect(): void;
            connect(): void;

            status(): Observable<any>;
            onReady(): Observable<any>;
            onDisconnected(): Observable<any>;
            onSocketError(): Observable<any>;
        }

        interface HorizonOptions {
            host?: string;
            path?: string;
            secure?: boolean;

            authType?: string;
            lazyWrites?: boolean;
            keepalive?: number;

            WebSocketCtor?: any;
        }

        interface Horizon {
            (options: HorizonOptions): HorizonInstance;

            clearAuthTokens(): void;
        }
    }

    export type HorizonOptions = hz.HorizonOptions;
    export type HorizonInstance = hz.HorizonInstance;
    export type TermBase = hz.TermBase;
    export type Collection = hz.Collection;
    export type User = hz.User;
    export type Horizon = hz.Horizon

    export * from '@horizon/client';

}


text:
This folder contains the C++ and JavaScript code for the HTML5/WebAssembly platform port,
compiled using [Emscripten](https://emscripten.org/).

It also contains a ESLint linting setup (see [`package.json`](package.json)).

See also [`misc/dist/html`](/misc/dist/html) folder for files used by this platform
such as the HTML5 shell.

## Artwork license

[`logo.png`](logo.png) and [`run_icon.png`](run_icon.png) are licensed under
[Creative Commons Attribution 3.0 Unported](https://www.w3.org/html/logo/faq.html#how-licenced)
per the HTML5 logo usage guidelines.

redpajama_set_name: RedPajamaGithub


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) > [type](./puppeteer.frameaddscripttagoptions.type.md)

## FrameAddScriptTagOptions.type property

Set the script's `type`<!-- -->. Use `module` in order to load an ES2015 module.

<b>Signature:</b>

```typescript
type?: string;
```


text:
from __future__ import division,print_function,unicode_literals,with_statement

import inspect
import types

# preliminary: two utility functions

def skip_redundant(iterable,skipset=None):
  """
  Redundant items are repeated items or items in the original skipset.
  """
  if skipset is None:
    skipset=set()
  for item in iterable:
    if item not in skipset:
      skipset.add(item)
      yield item

def remove_redundant(metaclasses):
  skipset=set([types.ClassType])
  for meta in metaclasses:  # determines the metaclasses to be skipped
    skipset.update(inspect.getmro(meta)[1:])
  return tuple(skip_redundant(metaclasses,skipset))

# now the core of the module: two mutually recursive functions

memoized_metaclasses_map={}

def get_noconflict_metaclass(bases,left_metas,right_metas):
  """
  Not intended to be used outside of this module, unless you know what you are doing.
  """
  # make tuple of needed metaclasses in specified priority order
  metas=left_metas+tuple(map(type,bases))+right_metas
  needed_metas=remove_redundant(metas)

  # return existing confict-solving meta, if any
  if needed_metas in memoized_metaclasses_map:
    return memoized_metaclasses_map[needed_metas]
  # nope: compute, memoize and return needed conflict-solving meta
  elif not needed_metas:  # wee, a trivial case, happy us
    meta=type
  elif len(needed_metas)==1:  # another trivial case
    meta=needed_metas[0]
  # check for recursion, can happen i.e. for Zope ExtensionClasses
  elif needed_metas==bases:
    raise TypeError("Incompatible root metatypes",needed_metas)
  else:  # gotta work ...
    metaname='_'+''.join([m.__name__ for m in needed_metas])
    meta=classmaker()(metaname,needed_metas,{})
  memoized_metaclasses_map[needed_metas]=meta
  return meta

def classmaker(left_metas=(),right_metas=()):
  def make_class(name,bases,adict):
    metaclass=get_noconflict_metaclass(bases,left_metas,right_metas)
    return metaclass(name,bases,adict)

  return make_class


text:
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"sort"
	"strings"

	"github.com/mibk/dupl/job"
	"github.com/mibk/dupl/printer"
	"github.com/mibk/dupl/syntax"
)

const defaultThreshold = 15

var (
	paths     = []string{"."}
	vendor    = flag.Bool("vendor", false, "")
	verbose   = flag.Bool("verbose", false, "")
	threshold = flag.Int("threshold", defaultThreshold, "")
	files     = flag.Bool("files", false, "")

	html     = flag.Bool("html", false, "")
	plumbing = flag.Bool("plumbing", false, "")
)

const (
	vendorDirPrefix = "vendor" + string(filepath.Separator)
	vendorDirInPath = string(filepath.Separator) + vendorDirPrefix
)

func init() {
	flag.BoolVar(verbose, "v", false, "alias for -verbose")
	flag.IntVar(threshold, "t", defaultThreshold, "alias for -threshold")
}

func main() {
	flag.Usage = usage
	flag.Parse()
	if *html && *plumbing {
		log.Fatal("you can have either plumbing or HTML output")
	}
	if flag.NArg() > 0 {
		paths = flag.Args()
	}

	if *verbose {
		log.Println("Building suffix tree")
	}
	schan := job.Parse(filesFeed())
	t, data, done := job.BuildTree(schan)
	<-done

	// finish stream
	t.Update(&syntax.Node{Type: -1})

	if *verbose {
		log.Println("Searching for clones")
	}
	mchan := t.FindDuplOver(*threshold)
	duplChan := make(chan syntax.Match)
	go func() {
		for m := range mchan {
			match := syntax.FindSyntaxUnits(*data, m, *threshold)
			if len(match.Frags) > 0 {
				duplChan <- match
			}
		}
		close(duplChan)
	}()

	newPrinter := printer.NewText
	if *html {
		newPrinter = printer.NewHTML
	} else if *plumbing {
		newPrinter = printer.NewPlumbing
	}
	p := newPrinter(os.Stdout, ioutil.ReadFile)
	if err := printDupls(p, duplChan); err != nil {
		log.Fatal(err)
	}
}

func filesFeed() chan string {
	if *files {
		fchan := make(chan string)
		go func() {
			s := bufio.NewScanner(os.Stdin)
			for s.Scan() {
				f := s.Text()
				fchan <- strings.TrimPrefix(f, "./")
			}
			close(fchan)
		}()
		return fchan
	}
	return crawlPaths(paths)
}

func crawlPaths(paths []string) chan string {
	fchan := make(chan string)
	go func() {
		for _, path := range paths {
			info, err := os.Lstat(path)
			if err != nil {
				log.Fatal(err)
			}
			if !info.IsDir() {
				fchan <- path
				continue
			}
			err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
				if !*vendor && (strings.HasPrefix(path, vendorDirPrefix) ||
					strings.Contains(path, vendorDirInPath)) {
					return nil
				}
				if !info.IsDir() && strings.HasSuffix(info.Name(), ".go") {
					fchan <- path
				}
				return nil
			})
			if err != nil {
				log.Fatal(err)
			}
		}
		close(fchan)
	}()
	return fchan
}

func printDupls(p printer.Printer, duplChan <-chan syntax.Match) error {
	groups := make(map[string][][]*syntax.Node)
	for dupl := range duplChan {
		groups[dupl.Hash] = append(groups[dupl.Hash], dupl.Frags...)
	}
	keys := make([]string, 0, len(groups))
	for k := range groups {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	if err := p.PrintHeader(); err != nil {
		return err
	}
	for _, k := range keys {
		uniq := unique(groups[k])
		if len(uniq) > 1 {
			if err := p.PrintClones(uniq); err != nil {
				return err
			}
		}
	}
	return p.PrintFooter()
}

func unique(group [][]*syntax.Node) [][]*syntax.Node {
	fileMap := make(map[string]map[int]struct{})

	var newGroup [][]*syntax.Node
	for _, seq := range group {
		node := seq[0]
		file, ok := fileMap[node.Filename]
		if !ok {
			file = make(map[int]struct{})
			fileMap[node.Filename] = file
		}
		if _, ok := file[node.Pos]; !ok {
			file[node.Pos] = struct{}{}
			newGroup = append(newGroup, seq)
		}
	}
	return newGroup
}

func usage() {
	fmt.Fprintln(os.Stderr, `Usage: dupl [flags] [paths]

Paths:
  If the given path is a file, dupl will use it regardless of
  the file extension. If it is a directory, it will recursively
  search for *.go files in that directory.

  If no path is given, dupl will recursively search for *.go
  files in the current directory.

Flags:
  -files
    	read file names from stdin one at each line
  -html
    	output the results as HTML, including duplicate code fragments
  -plumbing
    	plumbing (easy-to-parse) output for consumption by scripts or tools
  -t, -threshold size
    	minimum token sequence size as a clone (default 15)
  -vendor
    	check files in vendor directory
  -v, -verbose
    	explain what is being done

Examples:
  dupl -t 100
    	Search clones in the current directory of size at least
    	100 tokens.
  dupl $(find app/ -name '*_test.go')
    	Search for clones in tests in the app directory.
  find app/ -name '*_test.go' |dupl -files
    	The same as above.`)
	os.Exit(2)
}


text:
'use strict';

const mm = require('egg-mock');
const assert = require('assert');
const innerClient = require('cluster-client/lib/symbol').innerClient;
const utils = require('../../utils');

let app;
describe('test/lib/cluster/cluster-client.test.js', () => {
  describe('common mode', () => {
    before(async () => {
      mm.consoleLevel('NONE');
      app = utils.app('apps/cluster_mod_app');
      await app.ready();
    });
    after(async () => {
      await app.close();
      const agentInnerClient = app.agent.registryClient[innerClient];
      assert(agentInnerClient._realClient.closed === true);
      mm.restore();
    });

    it('should publish & subscribe ok', () => {
      return app.httpRequest()
        .post('/publish')
        .send({ value: '30.20.78.299' })
        .expect('ok')
        .expect(200)
        .then(() => {
          return new Promise(resolve => {
            setTimeout(resolve, 500);
          });
        })
        .then(() => {
          return app.httpRequest()
            .get('/getHosts')
            .expect('30.20.78.299:20880')
            .expect(200);
        });
    });

    it('should get default cluster response timeout', () => {
      return app.httpRequest()
        .get('/getDefaultTimeout')
        .expect(200)
        .then(res => {
          assert(res.text === '60000');
        });
    });

    it('should get overwrite cluster response timeout', () => {
      return app.httpRequest()
        .get('/getOverwriteTimeout')
        .expect(200)
        .then(res => {
          assert(res.text === '1000');
        });
    });
  });

  describe('single process mode', () => {
    before(async () => {
      mm.consoleLevel('NONE');
      app = await utils.singleProcessApp('apps/cluster_mod_app');
    });
    after(async () => {
      await app.close();
      const agentInnerClient = app.agent.registryClient[innerClient];
      assert(agentInnerClient._realClient.closed === true);
      mm.restore();
    });

    it('should publish & subscribe ok', () => {
      return app.httpRequest()
        .post('/publish')
        .send({ value: '30.20.78.299' })
        .expect('ok')
        .expect(200)
        .then(() => {
          return new Promise(resolve => {
            setTimeout(resolve, 500);
          });
        })
        .then(() => {
          return app.httpRequest()
            .get('/getHosts')
            .expect('30.20.78.299:20880')
            .expect(200);
        });
    });

    it('should get default cluster response timeout', () => {
      return app.httpRequest()
        .get('/getDefaultTimeout')
        .expect(200)
        .then(res => {
          assert(res.text === '60000');
        });
    });

    it('should get overwrite cluster response timeout', () => {
      return app.httpRequest()
        .get('/getOverwriteTimeout')
        .expect(200)
        .then(res => {
          assert(res.text === '1000');
        });
    });
  });
});


text:
Models construction, parsing and formatting durations in hh::mm::ss format.

This is an extraction from the [cre-stats](http://github.com/nerab/cre-stats) project.

[![Build Status](https://secure.travis-ci.org/nerab/hms.png?branch=master)](http://travis-ci.org/nerab/hms)

## Installation

Add this line to your application's Gemfile:

    gem 'hms'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install hms

## Usage

    d = HMS::Duration.new(42)
    puts "Podcast episode length is #{d}." # 42

    d = HMS::Duration.new('32:16:08')
    puts "#{d} equals to #{d.to_i} seconds" # 116168

See [tests](/nerab/hms/blob/master/test/unit) for advanced usage.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
u"""
Perform straight-line Wilson plot fit.  Draw the Wilson plot.

Reflection d-spacings are determined from the crystal symmetry (from
indexing) and the Miller indices of the indexed reflections.  The
atomic displacement parameter is assumed isotropic.  Its value is
determined from a fit to the reflection data:
  I = A * exp(-B / (2 * d^2)),
where I is the intensity and the scale factor, A, and isotropic
displacement parameter, B, are the fitted parameters.

An I/σ condition for 'good' diffraction statistics is set by the
instance variable min_i_over_sigma, and the user's desired
resolution is set by the instance variable desired_d.  A crude
error model is assumed, whereby σ² = I, and so the I/σ condition
translates trivially to a threshold I.

The value of the fitted intensity function at the desired
resolution is compared with the threshold I.  The ratio of these
values is used to determine a recommended exposure (flux × exposure time)
for the full data collection.

The Wilson plot of I as a function of d is drawn as the file
'wilson_plot.png'.  The plot can optionally be saved in other formats.

Examples:

    screen19.minimum_exposure integrated.expt integrated.refl

    screen19.minimum_exposure indexed.expt indexed.refl

    screen19.minimum_exposure min_i_over_sigma=2 desired_d=0.84 wilson_fit_max_d=4 \
        integrated.expt integrated.refl

"""

from __future__ import absolute_import, division, print_function

import logging
import time
from typing import Iterable, List, Optional, Sequence, Union

import numpy as np
from scipy.optimize import curve_fit
from six.moves import cStringIO as StringIO
from tabulate import tabulate

import iotbx.phil
from cctbx import miller
from libtbx.phil import scope, scope_extract

from dials.array_family import flex
from dials.util import log
from dials.util.options import OptionParser
from dials.util.version import dials_version
from dxtbx.model import Experiment, ExperimentList

from screen19 import __version__, d_ticks, plot_intensities, terminal_size

# Custom types
FloatSequence = Sequence[float]
Fit = Union[np.ndarray, Iterable, int, float]

help_message = __doc__

phil_scope = iotbx.phil.parse(
    u"""
    verbosity = 0
        .type = int(value_min=0)
        .caption = 'Verbosity level of log output'
        .help = "Possible values:\n"
                "\t• 0: Info log output to stdout/logfile\n"
                "\t• 1: Info & debug log output to stdout/logfile"
    minimum_exposure
        .caption = 'Parameters for the calculation of the lower exposure bound'
        {
        desired_d = None
            .multiple = True
            .type = float
            .caption = u'Desired resolution limit, in Ångströms, of diffraction data'
            .help = 'This is the resolution target for the lower-bound exposure ' \
                    'recommendation.'
        min_i_over_sigma = 2
            .type = float
            .caption = u'Target I/σ value for lower-bound exposure recommendation'
            .help = 'The lower-bound exposure recommendation provides an estimate of ' \
                    u'the exposure (flux × exposure time) required to ensure that the' \
                    'majority of expected reflections at the desired resolution limit' \
                    u'have I/σ greater than or equal to this value.'
        wilson_fit_max_d = 4  # Å
            .type = float
            .caption = u'Maximum d-value (in Ångströms) for displacement parameter fit'
            .help = 'Reflections with lower resolution than this value will be ' \
                    'ignored for the purposes of the Wilson plot.'
        }
    output
        .caption = 'Parameters to control the output'
        {
        log = 'screen19.minimum_exposure.log'
            .type = str
            .caption = 'Location for the info log'
        debug_log = 'screen19.minimum_exposure.debug.log'
            .type = str
            .caption = 'Location for the debug log'
        wilson_plot = 'wilson_plot'
            .type = str
            .caption = 'Filename for the Wilson plot image'
            .help = "By default, the extension '.png' is appended.  If you include " \
                    "a different extension, either '.pdf', '.ps', '.eps' or '.svg', " \
                    "a file of that format will be created instead."
        }
        """,
    process_includes=True,
)

logger_name = "dials.screen19.minimum_exposure"
logger = logging.getLogger(logger_name)
debug, info, warn = logger.debug, logger.info, logger.warning

def scaled_debye_waller(x, b, a):
    # type: (float, float, float) -> float
    u"""
    Calculate a scaled isotropic Debye-Waller factor.

    By assuming a single isotropic disorder parameter, :param:`b`, this factor
    approximates the decay of diffracted X-ray intensity increasing resolution
    (decreasing d, increasing sin(θ)).

    Args:
        x: Equivalent to 1/d².
        b: Isotropic displacement parameter.
        a: A scale factor.

    Returns:
        Estimated value of scaled isotropic Debye-Waller factor.
    """
    return a * np.exp(-b / 2 * x)

def wilson_fit(d_star_sq, intensity, sigma, wilson_fit_max_d):
    # type: (FloatSequence, FloatSequence, FloatSequence, float) -> Fit
    u"""
    Fit a simple Debye-Waller factor, assume isotropic disorder parameter.

    Reflections with d ≥ :param:`wilson_fit_max_d` are ignored.

    Args:
        d_star_sq: 1/d² (equivalently d*²), sequence of values for the observed
            reflections (units of Å⁻² assumed).
        intensity: Sequence of reflection intensities.
        sigma: Sequence of uncertainties in reflection intensity.
        wilson_fit_max_d: The minimum resolution for reflections against which to
            fit.

    Returns:
        - The fitted isotropic displacement parameter (units of Ų assumed);
        - The fitted scale factor.

    """
    # Eliminate reflections with d > wilson_fit_max_d from the fit
    sel = d_star_sq > 1 / wilson_fit_max_d ** 2

    # Perform a weighted Wilson plot fit to the reflection intensities
    fit, cov = curve_fit(
        scaled_debye_waller,
        d_star_sq.select(sel),
        intensity.select(sel),
        sigma=sigma.select(sel),
        bounds=(0, np.inf),
    )

    return fit

def wilson_plot_ascii(miller_array, d_ticks=None):
    # type: (miller.array, Optional[Sequence]) -> None
    u"""
    Print an ASCII-art Wilson plot of reflection intensities.

    Equivalent reflections will be merged according to the crystal symmetry.

    Args:
        miller_array: An array of integrated intensities, bundled with appropriate
                      crystal symmetry and unit cell info.
        d_ticks: d location of ticks on 1/d² axis.
    """
    # Draw the Wilson plot, using existing functionality in cctbx.miller
    columns, rows = terminal_size()
    n_bins = min(columns, miller_array.data().size())
    miller_array.setup_binner_counting_sorted(n_bins=n_bins, reflections_per_bin=1)
    wilson = miller_array.wilson_plot(use_binning=True)
    # Get the relevant plot data from the miller_array:
    binned_intensity = [x if x else 0 for x in wilson.data[1:-1]]
    bins = dict(zip(wilson.binner.bin_centers(1), binned_intensity))
    if d_ticks:
        tick_positions = ", ".join(['"%g" %s' % (d, 1 / d ** 2) for d in d_ticks])
        tick_positions = tick_positions.join(["(", ")"])
    else:
        tick_positions = ""
    # Draw the plot:
    plot_intensities(
        bins,
        1,
        title="'Wilson plot'",
        xlabel="'d (Angstrom) (inverse-square scale)'",
        ylabel="'I (counts)'",
        xticks=tick_positions,
        style="with lines",
    )

def wilson_plot_image(
    d_star_sq,  # type: FloatSequence
    intensity,  # type: FloatSequence
    fit,  # type: Fit
    max_d=None,  # type: Optional[float]
    ticks=None,  # type: Optional[FloatSequence]
    output="wilson_plot",  # type: str
):
    # type: (...) -> None
    u"""
    Generate the Wilson plot as a PNG image.

    :param:`max_d` allows greying out of the reflections not included in the
    isotropic Debye-Waller fit.

    Args:
        d_star_sq: 1/d² values of reflections.
        intensity: Intensities of reflections.
        fit: Fitted parameters (tuple of fitted isotropic displacement parameter and
            fitted scale factor).
        max_d: The minimum resolution for reflections used in the Debye-Waller fit.
        ticks: d location of ticks on 1/d² axis.
        output: Output filename.  The extension `.png` will be added automatically.
    """
    import matplotlib

    matplotlib.use("Agg")
    from matplotlib import pyplot as plt

    plt.xlabel(u"d (Å) (inverse-square scale)")
    plt.ylabel(u"Intensity (counts)")
    if ticks:
        plt.xticks([1 / d ** 2 for d in ticks], ["%g" % d for d in ticks])

    # Matplotlib v3.3.0 includes API change 'nonposy' → 'nonpositive'
    # https://matplotlib.org/api/api_changes.html#log-symlog-scale-base-ticks-and-nonpos-specification
    try:
        plt.yscale("log", nonpositive="clip")
    except ValueError:
        plt.yscale("log", nonposy="clip")

    plt.plot(d_star_sq, intensity, "b.", label=None)
    plt.plot(
        d_star_sq, scaled_debye_waller(d_star_sq, *fit), "r-", label="Debye-Waller fit"
    )
    if max_d:
        plt.fill_betweenx(
            plt.ylim(),
            1 / np.square(max_d),
            color="k",
            alpha=0.5,
            zorder=2.1,
            label="Excluded from fit",
        )
    plt.legend(loc=0)
    plt.savefig(output)
    plt.close()

def suggest_minimum_exposure(expts, refls, params):
    # type: (ExperimentList[Experiment], flex.reflection_table, scope_extract) -> None
    u"""
    Suggest an estimated minimum sufficient exposure to achieve a certain resolution.

    The estimate is based on a fit of a Debye-Waller factor under the assumption that a
    single isotropic displacement parameter can be used to adequately describe the
    decay of intensities with increasing sin(θ).

    An ASCII-art Wilson plot is printed, along with minimum exposure recommendations for
    a number of different resolution targets.  The Wilson plot, including the fitted
    isotropic Debye-Waller factor, is saved as a PNG image.

    Args:
        expts: Experiment list containing a single experiment, from which the crystal
            symmetry will be extracted.
        refls: Reflection table of observed reflections.
        params: Parameters for calculation of minimum exposure estimate.
    """
    # Ignore reflections without an index, since uctbx.unit_cell.d returns spurious
    # d == -1 values, rather than None, for unindexed reflections.
    refls.del_selected(refls["id"] == -1)
    # Ignore all spots flagged as overloaded
    refls.del_selected(refls.get_flags(refls.flags.overloaded).iselection())

    # Work from profile-fitted intensities where possible but if the number of
    # profile-fitted intensities is less than 75% of the number of summed
    # intensities, use summed intensities instead.  This is a very arbitrary heuristic.
    sel_prf = refls.get_flags(refls.flags.integrated_prf).iselection()
    sel_sum = refls.get_flags(refls.flags.integrated_sum).iselection()
    if sel_prf.size() < 0.75 * sel_sum.size():
        refls = refls.select(sel_sum)
        intensity = refls["intensity.sum.value"]
        sigma = flex.sqrt(refls["intensity.sum.variance"])
    else:
        refls = refls.select(sel_prf)
        intensity = refls["intensity.prf.value"]
        sigma = flex.sqrt(refls["intensity.prf.variance"])

    # Apply French-Wilson scaling to ensure positive intensities.
    miller_array = miller.array(
        miller.set(
            expts[0].crystal.get_crystal_symmetry(),
            refls["miller_index"],
            anomalous_flag=False,
        ),
        data=intensity,
        sigmas=sigma,
    )
    miller_array.set_observation_type_xray_intensity()
    miller_array = miller_array.merge_equivalents().array()
    cctbx_log = StringIO()  # Prevent idiosyncratic CCTBX logging from polluting stdout.
    miller_array = miller_array.french_wilson(log=cctbx_log).as_intensity_array()
    logger.debug(cctbx_log.getvalue())

    d_star_sq = miller_array.d_star_sq().data()
    intensity = miller_array.data()
    sigma = miller_array.sigmas()

    # Parameters for the lower-bound exposure estimate:
    min_i_over_sigma = params.minimum_exposure.min_i_over_sigma
    wilson_fit_max_d = params.minimum_exposure.wilson_fit_max_d
    desired_d = params.minimum_exposure.desired_d
    # If no target resolution is given, use the following defaults:
    if not params.minimum_exposure.desired_d:
        desired_d = [
            1,  # Å
            0.84,  # Å (IUCr publication requirement)
            0.6,  # Å
            0.4,  # Å
        ]
    desired_d.sort(reverse=True)

    # Perform the Wilson plot fit
    fit = wilson_fit(d_star_sq, intensity, sigma, wilson_fit_max_d)

    # Get recommended exposure factors
    # Use the fact that σ² = I for indexed data, so I/σ = √̅I
    desired_d_star_sq = [1 / d ** 2 for d in desired_d]
    target_i = min_i_over_sigma ** 2
    recommended_factor = [
        (target_i / scaled_debye_waller(target_d, *fit))
        for target_d in desired_d_star_sq
    ]

    # Get the achievable resolution at the current exposure
    desired_d += [np.sqrt(fit[0] / (2 * np.log(fit[1] / target_i)))]
    recommended_factor += [1]

    # Draw the ASCII art Wilson plot
    wilson_plot_ascii(miller_array, d_ticks)

    recommendations = zip(desired_d, recommended_factor)
    recommendations = sorted(recommendations, key=lambda rec: rec[0], reverse=True)

    # Print a recommendation to the user.
    info(u"\nFitted isotropic displacement parameter, B = %.3g Ų", fit[0])
    for target, recommendation in recommendations:
        if recommendation < 1:
            debug(
                u"\nIt is likely that you can achieve a resolution of %g Å using a "
                "lower exposure (lower transmission and/or shorter exposure time).",
                target,
            )
        elif recommendation > 1:
            debug(
                "\nIt is likely that you need a higher exposure (higher transmission "
                u"and/or longer exposure time to achieve a resolution of %g Å.",
                target,
            )
        debug(
            u"The estimated minimal sufficient exposure (flux × exposure time) to "
            u"achievea resolution of %.2g Å is %.3g times the exposure used for this "
            "data collection.",
            target,
            recommendation,
        )

    summary = "\nRecommendations summarised:\n"
    summary += tabulate(
        recommendations,
        [u"Resolution (Å)", "Suggested\nexposure factor"],
        floatfmt=(".3g", ".3g"),
        tablefmt="rst",
    )
    summary += (
        u"\nExposure is flux × exposure time."
        "\nYou can achieve your desired exposure factor by modifying "
        "transmission and/or exposure time."
    )
    info(summary)

    # Draw the Wilson plot image and save to file
    wilson_plot_image(
        d_star_sq,
        intensity,
        fit,
        max_d=params.minimum_exposure.wilson_fit_max_d,
        ticks=d_ticks,
        output=params.output.wilson_plot,
    )

def run(phil=phil_scope, args=None, set_up_logging=False):
    # type: (scope, Optional[List[str, ...]], bool) -> None
    """
    Parse command-line arguments, run the script.

    Uses the DIALS option parser to extract an experiment list, reflection table and
    parameters, then passes them to :func:`suggest_minimum_exposure`.
    Optionally, sets up the logger.

    Args:
        phil: PHIL scope for option parser.
        args: Arguments to parse. If None, :data:`sys.argv[1:]` will be used.
        set_up_logging: Choose whether to configure :module:`screen19` logging.
    """
    usage = "%prog [options] integrated.expt integrated.refl"

    parser = OptionParser(
        usage=usage,
        phil=phil,
        read_experiments=True,
        read_reflections=True,
        check_format=False,
        epilog=help_message,
    )

    params, options = parser.parse_args(args=args)

    if set_up_logging:
        # Configure the logging
        log.config(params.verbosity, params.output.log)

    if not (params.input.experiments and params.input.reflections):
        version_information = "screen19.minimum_exposure v%s using %s (%s)" % (
            __version__,
            dials_version(),
            time.strftime("%Y-%m-%d %H:%M:%S"),
        )

        print(help_message)
        print(version_information)
        return

    if len(params.input.experiments) > 1:
        warn(
            "You provided more than one experiment list (%s).  Only the "
            "first, %s, will be used.",
            ", ".join([expt.filename for expt in params.input.experiments]),
            params.input.experiments[0].filename,
        )
    if len(params.input.reflections) > 1:
        warn(
            "You provided more than one reflection table (%s).  Only the "
            "first, %s, will be used.",
            ", ".join([refls.filename for refls in params.input.reflections]),
            params.input.reflections[0].filename,
        )

    expts = params.input.experiments[0].data
    refls = params.input.reflections[0].data

    if len(expts) > 1:
        warn(
            "The experiment list you provided, %s, contains more than one "
            "experiment object (perhaps multiple indexing solutions).  Only "
            "the first will be used, all others will be ignored.",
            params.input.experiments[0].filename,
        )

    suggest_minimum_exposure(expts, refls, params)

def main():
    # type: () -> None
    """Dispatcher for command-line call."""
    run(set_up_logging=True)


text:
<meta charset="UTF-8">
<title>QuickMockspresso.PluginPicker.guava - mockspresso-quick</title>
<link rel="stylesheet" href="../../../../style.css">

mockspresso-quick / com.episode6.hackit.mockspresso.quick / QuickMockspresso / PluginPicker / guava

guava

@NotNull abstract fun guava(): QuickMockspresso.Builder

Applies a MockspressoPlugin thats adds special object handling for some of the types provided by guava. * Requires your project have a dependency on 'com.google.guava:guava'

Return

QuickMockspresso.Builder: The QuickMockspresso.Builder for your mockspresso instance


text:
TcpWorker::TcpWorker( QObject *parent )
: QObject( parent )
, mpTcpSocket( new QTcpSocket(this) )
{
   connect( mpTcpSocket, SIGNAL(connected()),
            this, SIGNAL(connected()) );
   connect( mpTcpSocket, SIGNAL(disconnected()),
            this, SIGNAL(disconnected()) );
   connect( mpTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SIGNAL(stateChanged(QAbstractSocket::SocketState)) );
}

TcpWorker::~TcpWorker()
{
}

void TcpWorker::connectToHost( const QString &hostname, int port )
{
   mpTcpSocket->connectToHost( hostname, static_cast<quint16>(port) );
}

void TcpWorker::close()
{
   mpTcpSocket->close();
}

void TcpWorker::send( const QByteArray &data )
{
   if( mpTcpSocket->isOpen() )
   {
      mpTcpSocket->write( data );
      mpTcpSocket->flush();
   }
}

void TcpWorker::readData()
{
   emit received( mpTcpSocket->readAll() );
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DictionaryExtensions.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Extension methods for <see cref="IDictionary{TKey,TValue}" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Collections
{
    using System;
    using System.Collections.Generic;

    using Kephas.Diagnostics.Contracts;

    /// <summary>
    /// Extension methods for <see cref="IDictionary{TKey,TValue}"/>.
    /// </summary>
    public static class DictionaryExtensions
    {
        /// <summary>
        /// Tries to get the value for the provided key. If the requested item cannot be found, the default value is returned.
        /// </summary>
        /// <typeparam name="TKey">The type of the key.</typeparam>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="key">The item's key.</param>
        /// <param name="defaultValue">The default value to return if the item could not be found.</param>
        /// <returns>The found value, or the default value.</returns>
        public static TValue TryGetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue))
        {
            Requires.NotNull(dictionary, nameof(dictionary));
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
        }
    }
}


text:
<bill session="115" type="s" number="269" updated="2017-08-10T13:24:02Z">
  <state datetime="2017-02-08">REPORTED</state>
  <status>
    <unknown datetime="2017-02-08"/>
  </status>
  <introduced datetime="2017-02-01"/>
  <titles>
    <title type="official" as="introduced">A bill to provide for the conveyance of certain property to the Tanana Tribal Council located in Tanana, Alaska, and to the Bristol Bay Area Health Corporation located in  Dillingham, Alaska, and for other purposes.</title>
    <title type="display">A bill to provide for the conveyance of certain property to the Tanana Tribal Council located in Tanana, Alaska, and to the Bristol Bay Area Health Corporation located in  Dillingham, Alaska, and for other purposes.</title>
  </titles>
  <sponsor bioguide_id="M001153"/>
  <cosponsors>
    <cosponsor bioguide_id="S001198" joined="2017-02-01"/>
  </cosponsors>
  <actions>
    <action datetime="2017-02-01">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-02-01" state="REFERRED">
      <text>Read twice and referred to the Committee on Indian Affairs.</text>
    </action>
    <calendar datetime="2017-02-08" state="REPORTED">
      <text>Committee on Indian Affairs. Ordered to be reported favorably.</text>
    </calendar>
    <action datetime="2017-03-27">
      <text>Committee on Indian Affairs. Reported by Senator Hoeven without amendment. With written report No. 115-11.</text>
    </action>
    <calendar datetime="2017-03-27" calendar="Senate Legislative" under="General Orders" number="24">
      <text>Placed on Senate Legislative Calendar under General Orders. Calendar No. 24.</text>
    </calendar>
  </actions>
  <committees>
    <committee subcommittee="" code="SLIA" name="Senate Indian Affairs" activity="Reporting, Referral"/>
  </committees>
  <relatedbills>
    <bill type="h" session="115" relation="identical" number="236"/>
  </relatedbills>
  <subjects>
    <term name="Public lands and natural resources"/>
    <term name="Alaska"/>
    <term name="Alaska Natives and Hawaiians"/>
    <term name="Indian lands and resources rights"/>
    <term name="Indian social and development programs"/>
    <term name="Land transfers"/>
    <term name="Minority health"/>
  </subjects>
  <amendments/>
  <summary date="2017-03-27T15:10:48Z" status="Reported to House without amendment">(This measure has not been amended since it was introduced. The summary has been expanded because action occurred on the measure.)

(Sec. 1) This bill directs the Department of Health and Human Services (HHS) to convey to the Tanana Tribal Council in Tanana, Alaska, all interest of the United States in and to certain property (including all land, improvements, and appurtenances) containing 11.25 acres, in the village of Tanana for use in connection with health and social services programs.

 (Sec. 2) HHS shall convey to the Bristol Bay Area Health Corporation in Dillingham, Alaska, all interest of the United States in and to certain property included in the Dental Annex Subdivision containing 1.474 acres more or less, also for use in connection with health and social services programs.

Such conveyances by warranty deed: (1) shall supersede and render of no future effect any quitclaim deed to the property executed by HHS and the Council or Corporation; and (2) shall not require any consideration from the Council or Corporation for the property, impose any obligation, term, or condition on the Council or Corporation, or allow for any U.S. reversionary interest in the property.

The Council or Corporation shall not be liable for soil, surface water, groundwater, or other contamination resulting from the disposal, release, or presence of environmental contamination.

HHS shall: (1) be accorded any easement or access to the conveyed property as may be necessary to satisfy any retained obligations and liability; and (2) comply with requirements under the Comprehensive Environmental Response, Compensation, and Liability Act of 1980 for certain deeds for the transfer of U.S.-owned real property on which any hazardous substance was stored for one year or more, disposed of, or known to have been released.</summary>
  <committee-reports>
    <report>S. Rept. 115-11</report>
  </committee-reports>
</bill>


text:
package kvstore;

import static kvstore.KVConstants.ERROR_OVERSIZED_KEY;
import static kvstore.KVConstants.ERROR_OVERSIZED_VALUE;
import static kvstore.KVConstants.RESP;

import java.util.concurrent.locks.Lock;

/**
 * This class services all storage logic for an individual key-value server.
 * All KVServer request on keys from different sets must be parallel while
 * requests on keys from the same set should be serial. A write-through
 * policy should be followed when a put request is made.
 */
public class KVServer implements KeyValueInterface {

    private KVStore dataStore;
    private KVCache dataCache;

    private static final int MAX_KEY_SIZE = 256;
    private static final int MAX_VAL_SIZE = 256 * 1024;

    /**
     * Constructs a KVServer backed by a KVCache and KVStore.
     *
     * @param numSets the number of sets in the data cache
     * @param maxElemsPerSet the size of each set in the data cache
     */

    public KVServer(int numSets, int maxElemsPerSet) {
        this.dataCache = new KVCache(numSets, maxElemsPerSet);
        this.dataStore = new KVStore();
    }

    /**
     * Performs put request on cache and store.
     *
     * @param  key String key
     * @param  value String value
     * @throws KVException if key or value is too long
     */
    @Override
    public void put(String key, String value) throws KVException {
        if(key.length() > MAX_KEY_SIZE)
            throw new KVException(ERROR_OVERSIZED_KEY);
        if(value.length() > MAX_VAL_SIZE)
            throw new KVException(ERROR_OVERSIZED_VALUE);
        dataCache.getLock(key).lock();
        try {
            dataCache.put(key, value);
            dataStore.put(key, value);
        } finally {
            dataCache.getLock(key).unlock();
        }
    }

    /**
     * Performs get request.
     * Checks cache first. Updates cache if not in cache but located in store.
     *
     * @param  key String key
     * @return String value associated with key
     * @throws KVException with ERROR_NO_SUCH_KEY if key does not exist in store
     */
    @Override
    public String get(String key) throws KVException {
        dataCache.getLock(key).lock();
        try {
            String value = dataCache.get(key);
            if(value == null) {
                value = dataStore.get(key);
                dataCache.put(key, value);
            }
            return value;
        } finally {
            dataCache.getLock(key).unlock();
        }
    }

    /**
     * Performs del request.
     *
     * @param  key String key
     * @throws KVException with ERROR_NO_SUCH_KEY if key does not exist in store
     */
    @Override
    public void del(String key) throws KVException {
        dataCache.getLock(key).lock();
        try {
            dataCache.del(key);
            dataStore.del(key);
        } finally {
            dataCache.getLock(key).unlock();
        }
    }

    /**
     * Check if the server has a given key. This is used for TPC operations
     * that need to check whether or not a transaction can be performed but
     * you don't want to modify the state of the cache by calling get(). You
     * are allowed to call dataStore.get() for this method.
     *
     * @param key key to check for membership in store
     */
    public boolean hasKey(String key) {
        try {
            dataStore.get(key);
        } catch(KVException e) {
            return false;
        }
        return true;
    }

    /** This method is purely for convenience and will not be tested. */
    @Override
    public String toString() {
        return dataStore.toString() + dataCache.toString();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Drawing.Design;

namespace Tomato.Hardware
{
    public class LEM1802 : Device
    {
        public LEM1802()
        {
            if (DefaultFont == null)
            {
                Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Tomato.Hardware.DefaultFont.dat");
                DefaultFont = new ushort[stream.Length / 2];
                for (int i = 0; i < DefaultFont.Length; i++)
                {
                    byte left = (byte)stream.ReadByte();
                    byte right = (byte)stream.ReadByte();
                    ushort value = (ushort)(right | (left << 8));
                    DefaultFont[i] = value;
                }
            }
            timer = new Timer(ToggleBlinker, null, BlinkRate, BlinkRate);
        }

        Timer timer;
        private void ToggleBlinker(object o)
        {
            BlinkOn = !BlinkOn;
        }

        [Category("Device Information")]
        public const int Width = 128;
        [Category("Device Information")]
        public const int Height = 96;
        [Category("Device Information")]
        public const int CharWidth = 4;
        [Category("Device Information")]
        public const int CharHeight = 8;
        /// <summary>
        /// The rate at which blinking characters should blink
        /// </summary>
        [Browsable(false)]
        public static int BlinkRate = 1000;
        [Browsable(false)]
        private bool BlinkOn = true;

        [Category("Device Status")]
        [TypeConverter(typeof(HexTypeEditor))]
        public ushort ScreenMap { get; set; }

        [Category("Device Status")]
        [TypeConverter(typeof(HexTypeEditor))]
        public ushort FontMap { get; set; }

        [Category("Device Status")]
        [TypeConverter(typeof(HexTypeEditor))]
        public ushort PaletteMap { get; set; }

        [Category("Device Status")]
        public ushort BorderColorValue { get; set; }

        [Browsable(false)]
        public Color BorderColor
        {
            get
            {
                return GetPaletteColor((byte)BorderColorValue);
            }
        }

        /// <summary>
        /// Gets an image of the screen, without the border.
        /// </summary>
        [Browsable(false)]
        public unsafe Bitmap ScreenImage
        {
            get
            {
                UnsafeBitmap screen = new UnsafeBitmap(Width, Height);
                if (ScreenMap == 0)
                    return screen.Bitmap;

                screen.LockBitmap();
                ushort address = 0;
                for (int y = 0; y < 12; y++)
                    for (int x = 0; x < 32; x++)
                    {
                        ushort value = AttachedCPU.Memory[ScreenMap + address];
                        uint fontValue;
                        if (FontMap == 0)
                            fontValue = (uint)((DefaultFont[(value & 0x7F) * 2] << 16) | DefaultFont[(value & 0x7F) * 2 + 1]);
                        else
                            fontValue = (uint)((AttachedCPU.Memory[FontMap + ((value & 0x7F) * 2)] << 16) | AttachedCPU.Memory[FontMap + ((value & 0x7F) * 2) + 1]);
                        fontValue = BitConverter.ToUInt32(BitConverter.GetBytes(fontValue).Reverse().ToArray(), 0);

                        Color background = GetPaletteColor((byte)((value & 0xF00) >> 8));
                        Color foreground = GetPaletteColor((byte)((value & 0xF000) >> 12));
                        for (int i = 0; i < sizeof(uint) * 8; i++)
                        {
                            if ((fontValue & 1) == 0 || (((value & 0x80) == 0x80) && !BlinkOn))
                                screen.SetPixel(i / 8 + (x * CharWidth), i % 8 + (y * CharHeight), PixelData.FromColor(background));
                            else
                                screen.SetPixel(i / 8 + (x * CharWidth), i % 8 + (y * CharHeight), PixelData.FromColor(foreground));
                            fontValue >>= 1;
                        }
                        address++;
                    }

                screen.UnlockBitmap();
                return screen.Bitmap;
            }
        }

        [Category("Device Information")]
        [TypeConverter(typeof(HexTypeEditor))]
        public override uint DeviceID
        {
            get { return 0x7349f615; }
        }

        [Category("Device Information")]
        [TypeConverter(typeof(HexTypeEditor))]
        public override uint ManufacturerID
        {
            get { return 0x1c6c8b36; }
        }

        [Category("Device Information")]
        [TypeConverter(typeof(HexTypeEditor))]
        public override ushort Version
        {
            get { return 0x1802; }
        }

        [Browsable(false)]
        public override string FriendlyName
        {
            get { return "LEM 1802 Screen"; }
        }

        public override int HandleInterrupt()
        {
            switch (AttachedCPU.A)
            {
                case 0x00:
                    ScreenMap = AttachedCPU.B;
                    break;
                case 0x01:
                    FontMap = AttachedCPU.B;
                    break;
                case 0x02:
                    PaletteMap = AttachedCPU.B;
                    break;
                case 0x03:
                    BorderColorValue = (ushort)(AttachedCPU.B & 0xF);
                    break;
                case 0x04:
                    Array.Copy(DefaultFont, 0, AttachedCPU.Memory, AttachedCPU.B, DefaultFont.Length);
                    return 256;
                case 0x05:
                    Array.Copy(DefaultPalette, 0, AttachedCPU.Memory, AttachedCPU.B, DefaultPalette.Length);
                    return 16;
            }
            return 0;
        }

        public Color GetPaletteColor(byte value)
        {
            ushort color;
            if (PaletteMap == 0)
                color = DefaultPalette[value & 0xF];
            else
                color = AttachedCPU.Memory[PaletteMap + (value & 0xF)];

            byte r, g, b;
            b = (byte)(color & 0xF);
            b |= (byte)(b << 4);
            g = (byte)((color & 0xF0) >> 4);
            g |= (byte)(g << 4);
            r = (byte)((color & 0xF00) >> 8);
            r |= (byte)(r << 4);

            return Color.FromArgb(
                255, r, g, b
                );
        }

        public override void Reset()
        {
            ScreenMap = FontMap = PaletteMap = 0;
            BorderColorValue = 0;
        }

        #region Default Values

        private static ushort[] DefaultPalette =
        {
            0x000,0x00A,0x0A0,0x0AA,0xA00,0xA0A,0xA50,0xAAA,0x555,0x55F,0x5F5,0x5FF,0xF55,0xF5F,0xFF5,0xFFF
        };

        private static ushort[] DefaultFont;

        #endregion

        #region Fast Bitmap

        public unsafe class UnsafeBitmap
        {
            Bitmap bitmap;

            // three elements used for MakeGreyUnsafe
            int width;
            BitmapData bitmapData = null;
            Byte* pBase = null;

            public UnsafeBitmap(Bitmap bitmap)
            {
                this.bitmap = new Bitmap(bitmap);
            }

            public UnsafeBitmap(int width, int height)
            {
                this.bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            }

            public void Dispose()
            {
                bitmap.Dispose();
            }

            public Bitmap Bitmap
            {
                get
                {
                    return (bitmap);
                }
            }

            private Point PixelSize
            {
                get
                {
                    GraphicsUnit unit = GraphicsUnit.Pixel;
                    RectangleF bounds = bitmap.GetBounds(ref unit);

                    return new Point((int)bounds.Width, (int)bounds.Height);
                }
            }

            public void LockBitmap()
            {
                GraphicsUnit unit = GraphicsUnit.Pixel;
                RectangleF boundsF = bitmap.GetBounds(ref unit);
                Rectangle bounds = new Rectangle((int)boundsF.X,
               (int)boundsF.Y,
               (int)boundsF.Width,
               (int)boundsF.Height);

                // Figure out the number of bytes in a row
                // This is rounded up to be a multiple of 4
                // bytes, since a scan line in an image must always be a multiple of 4 bytes
                // in length.
                width = (int)boundsF.Width * sizeof(PixelData);
                if (width % 4 != 0)
                {
                    width = 4 * (width / 4 + 1);
                }
                bitmapData =
               bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

                pBase = (Byte*)bitmapData.Scan0.ToPointer();
            }

            public PixelData GetPixel(int x, int y)
            {
                PixelData returnValue = *PixelAt(x, y);
                return returnValue;
            }

            public void SetPixel(int x, int y, PixelData colour)
            {
                PixelData* pixel = PixelAt(x, y);
                *pixel = colour;
            }

            public void UnlockBitmap()
            {
                bitmap.UnlockBits(bitmapData);
                bitmapData = null;
                pBase = null;
            }
            public PixelData* PixelAt(int x, int y)
            {
                return (PixelData*)(pBase + y * width + x * sizeof(PixelData));
            }
        }

        public struct PixelData
        {
            public byte blue;
            public byte green;
            public byte red;

            public static PixelData FromColor(Color color)
            {
                return new PixelData()
                {
                    red = color.R,
                    green = color.G,
                    blue = color.B
                };
            }
        }

        #endregion
    }
}


text:
// ----------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="ConnectionMessageBase.cs" company="David Eiwen">
// Copyright © 2016 by David Eiwen
// </copyright>
// <author>David Eiwen</author>
// <summary>
// This file contians the ConnectionMessageBase class.
// </summary>
// ----------------------------------------------------------------------------------------------------------------------------------------

namespace IndiePortable.Communication.Devices.ConnectionMessages
{
    using System;
    using Formatter;

    /// <summary>
    /// Represents a message that is used for the communication between
    /// two <see cref="IConnection{TAddress}" /> instances.
    /// This class is abstract.
    /// </summary>
    /// <seealso cref="ISerializable" />
    [Serializable]
    public abstract class ConnectionMessageBase
        : ISerializable
    {
        /// <summary>
        /// The backing field for the <see cref="SendTime" /> property.
        /// </summary>
        private readonly DateTime sendTimeBacking;

        /// <summary>
        /// The backing field for the <see cref="MessageIdentifier" /> property.
        /// </summary>
        private readonly Guid messageIdentifierBacking;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionMessageBase" /> class.
        /// </summary>
        protected ConnectionMessageBase()
        {
            this.messageIdentifierBacking = Guid.NewGuid();
            this.sendTimeBacking = DateTime.Now;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionMessageBase" /> class.
        /// </summary>
        /// <param name="data">
        ///
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <para>Thrown if <paramref name="data" /> is <c>null</c>-</para>
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <para>Thrown if <paramref name="data" /> does not contain the necessary information.</para>
        /// </exception>
        protected ConnectionMessageBase(ObjectDataCollection data)
        {
            if (object.ReferenceEquals(data, null))
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (!data.TryGetValue(nameof(this.SendTime), out this.sendTimeBacking) ||
                !data.TryGetValue(nameof(this.MessageIdentifier), out this.messageIdentifierBacking))
            {
                throw new ArgumentException();
            }
        }

        /// <summary>
        /// Gets the send time of the <see cref="ConnectionMessageBase" />.
        /// </summary>
        /// <value>
        ///     Contains the send time of the <see cref="ConnectionMessageBase" />.
        /// </value>
        public DateTime SendTime => this.sendTimeBacking;

        /// <summary>
        /// Gets the unique identifier of the <see cref="ConnectionMessageBase" />.
        /// </summary>
        /// <value>
        ///     Contains the unique identifier of hte <see cref="ConnectionMessageBase" />.
        /// </value>
        public Guid MessageIdentifier => this.messageIdentifierBacking;

        /// <summary>
        /// Populates a specified <see cref="ObjectDataCollection" /> instance with data from the <see cref="ConnectionMessageBase" /> instance.
        /// </summary>
        /// <param name="data">
        ///     The <see cref="ObjectDataCollection" /> that shall be populated.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <para>Thrown if <paramref name="data" /> is <c>null</c>.</para>
        /// </exception>
        public virtual void GetObjectData(ObjectDataCollection data)
        {
            if (object.ReferenceEquals(data, null))
            {
                throw new ArgumentNullException(nameof(data));
            }

            data.AddValue(nameof(this.SendTime), this.sendTimeBacking);
            data.AddValue(nameof(this.MessageIdentifier), this.messageIdentifierBacking);
        }
    }
}


text:
require 'fileutils'
require 'pathname'
require 'uri'
require 'net/http'
require 'json'
require 'digest'
require 'zlib'
require 'securerandom'
require 'archive/tar/minitar'

require 'librarian/source/basic_api'
require 'librarian/chef/manifest_reader'

module Librarian
  module Chef
    module Source
      class Site

        class Line

          attr_accessor :source, :name
          private :source=, :name=

          def initialize(source, name)
            self.source = source
            self.name = name
          end

          def install_version!(version, install_path)
            cache_version_unpacked! version

            if install_path.exist?
              debug { "Deleting #{relative_path_to(install_path)}" }
              install_path.rmtree
            end

            unpacked_path = version_unpacked_cache_path(version)

            debug { "Copying #{relative_path_to(unpacked_path)} to #{relative_path_to(install_path)}" }
            FileUtils.cp_r(unpacked_path, install_path)
          end

          def manifests
            version_uris.map do |version_uri|
              Manifest.new(source, name, version_uri)
            end
          end

          def to_version(version_uri)
            version_uri_metadata(version_uri)["version"]
          end

          def version_dependencies(version)
            version_manifest(version)["dependencies"]
          end

        private

          attr_accessor :metadata_cached
          alias metadata_cached? metadata_cached

          def environment
            source.environment
          end

          def uri
            @uri ||= URI.parse("#{source.uri}/cookbooks/#{name}")
          end

          def version_uris
            metadata["versions"]
          end

          def version_metadata(version)
            version_uri = to_version_uri(version)
            version_uri_metadata(version_uri)
          end

          def version_uri_metadata(version_uri)
            memo(__method__, version_uri.to_s) do
              cache_version_uri_metadata! version_uri
              parse_local_json(version_uri_metadata_cache_path(version_uri))
            end
          end

          def version_manifest(version)
            version_uri = to_version_uri(version)
            version_uri_manifest(version_uri)
          end

          def version_uri_manifest(version_uri)
            memo(__method__, version_uri.to_s) do
              cache_version_uri_unpacked! version_uri
              unpacked_path = version_uri_unpacked_cache_path(version_uri)
              manifest_path = ManifestReader.manifest_path(unpacked_path)
              ManifestReader.read_manifest(name, manifest_path)
            end
          end

          def metadata
            @metadata ||= begin
              cache_metadata!
              parse_local_json(metadata_cache_path)
            end
          end

          def to_version_uri(version)
            memo(__method__, version.to_s) do
              cache_version! version
              version_cache_path(version).read
            end
          end

          def metadata_cached!
            self.metadata_cached = true
          end

          def cache_path
            @cache_path ||= source.cache_path.join(name)
          end

          def metadata_cache_path
            @metadata_cache_path ||= cache_path.join("metadata.json")
          end

          def version_cache_path(version)
            memo(__method__, version.to_s) do
              cache_path.join("version").join(version.to_s)
            end
          end

          def version_uri_cache_path(version_uri)
            memo(__method__, version_uri.to_s) do
              cache_path.join("version-uri").join(hexdigest(version_uri))
            end
          end

          def version_metadata_cache_path(version)
            version_uri = to_version_uri(version)
            version_uri_metadata_cache_path(version_uri)
          end

          def version_uri_metadata_cache_path(version_uri)
            memo(__method__, version_uri.to_s) do
              version_uri_cache_path(version_uri).join("metadata.json")
            end
          end

          def version_package_cache_path(version)
            version_uri = to_version_uri(version)
            version_uri_package_cache_path(version_uri)
          end

          def version_uri_package_cache_path(version_uri)
            memo(__method__, version_uri.to_s) do
              version_uri_cache_path(version_uri).join("package.tar.gz")
            end
          end

          def version_unpacked_cache_path(version)
            version_uri = to_version_uri(version)
            version_uri_unpacked_cache_path(version_uri)
          end

          def version_uri_unpacked_cache_path(version_uri)
            memo(__method__, version_uri.to_s) do
              version_uri_cache_path(version_uri).join("package")
            end
          end

          def cache_metadata!
            metadata_cached? and return or metadata_cached!
            cache_remote_json! metadata_cache_path, uri
          end

          def cache_version_uri_metadata!(version_uri)
            path = version_uri_metadata_cache_path(version_uri)
            path.file? and return

            cache_remote_json! path, version_uri
          end

          def cache_version!(version)
            path = version_cache_path(version)
            path.file? and return

            version_uris.each do |version_uri|
              m = version_uri_metadata(version_uri)
              v = m["version"]
              if version.to_s == v
                write! path, version_uri.to_s
                break
              end
            end
          end

          def cache_version_package!(version)
            version_uri = to_version_uri(version)
            cache_version_uri_package! version_uri
          end

          def cache_version_uri_package!(version_uri)
            path = version_uri_package_cache_path(version_uri)
            path.file? and return

            file_uri = version_uri_metadata(version_uri)["file"]
            cache_remote_object! path, file_uri
          end

          def cache_version_unpacked!(version)
            version_uri = to_version_uri(version)
            cache_version_uri_unpacked! version_uri
          end

          def cache_version_uri_unpacked!(version_uri)
            cache_version_uri_package!(version_uri)

            path = version_uri_unpacked_cache_path(version_uri)
            path.directory? and return

            package_path = version_uri_package_cache_path(version_uri)
            unpacked_path = version_uri_unpacked_cache_path(version_uri)

            unpack_package! unpacked_path, package_path
          end

          def cache_remote_json!(path, uri)
            cache_remote_object!(path, uri, :type => :json)
          end

          def cache_remote_object!(path, uri, options = { })
            path = Pathname(path)
            uri = to_uri(uri)
            type = options[:type]

            debug { "Caching #{uri} to #{path}" }

            response = http_get(uri)

            object = response.body
            case type
            when :json
              JSON.parse(object) # verify that it's really JSON.
            end
            write! path, object
          end

          def write!(path, bytes)
            path.dirname.mkpath
            path.open("wb"){|f| f.write(bytes)}
          end

          def path_detect_gzip?(path)
            Zlib::GzipReader.open(path) { true }
          rescue Zlib::GzipFile::Error
            false
          end

          def path_detect_tar?(path)
            path_read_bytes_at(path, 257, 8) == "ustar\x0000"
          end

          def path_read_bytes_at(path, pos, len)
            path = Pathname(path)
            path.stat.size >= pos + len or return
            path.open "rb" do |f|
              f.seek pos ; f.pos == pos or return
              f.read(len)
            end
          end

          def extract_archive!(source, destination)
            source = Pathname(source)
            destination = Pathname(destination)

            return extract_archive_targz! source, destination if path_detect_gzip?(source)
            return extract_archive_tar! source, destination if path_detect_tar?(source)
            raise "Unrecognized archive format!"
          end

          def extract_archive_targz!(source, destination)
            Zlib::GzipReader.open(source) do |input|
              Archive::Tar::Minitar.unpack(input, destination.to_s)
            end
          end

          def extract_archive_tar!(source, destination)
            source.open "rb" do |input|
              Archive::Tar::Minitar.unpack(input, destination.to_s)
            end
          end

          def unpack_package!(path, source)
            path = Pathname(path)
            source = Pathname(source)

            temp = environment.scratch_path.join(SecureRandom.hex(16))
            temp.mkpath

            debug { "Unpacking #{relative_path_to(source)} to #{relative_path_to(temp)}" }
            extract_archive! source, temp

            # Cookbook files, as pulled from Opscode Community Site API, are
            # embedded in a subdirectory of the tarball. If created by git archive they
            # can include the subfolder `pax_global_header`, which is ignored.
            subtemps = temp.children
            subtemps.empty? and raise "The package archive was empty!"
            subtemps.delete_if{|pth| pth.to_s[/pax_global_header/]}
            subtemps.size > 1 and raise "The package archive has too many children!"
            subtemp = subtemps.first
            debug { "Moving #{relative_path_to(subtemp)} to #{relative_path_to(path)}" }
            FileUtils.cp_r(subtemp, path)
            FileUtils.rm_rf(subtemp)
          ensure
            temp.rmtree if temp && temp.exist?
          end

          def parse_local_json(path)
            JSON.parse(path.read)
          end

          def hexdigest(bytes)
            Digest::MD5.hexdigest(bytes)[0..15]
          end

          def to_uri(uri)
            uri = URI(uri) unless URI === uri
            uri
          end

          def debug(*args, &block)
            environment.logger.debug(*args, &block)
          end

          def relative_path_to(path)
            environment.logger.relative_path_to(path)
          end

          def http(uri)
            net_http = environment.net_http_class(uri.host).new(uri.host, uri.port)
            net_http.use_ssl = true if uri.scheme == 'https'
            net_http
          end

          def http_get(uri)
            max_redirects = 10
            redirects = []

            loop do
              debug { "Performing http-get for #{uri}" }
              http = http(uri)
              http.use_ssl = uri.scheme == 'https'
              request = Net::HTTP::Get.new(uri.path)
              response = http.start{|http| http.request(request)}

              case response
              when Net::HTTPSuccess
                debug { "Responded with success" }
                return response
              when Net::HTTPRedirection
                location = response["Location"]
                debug { "Responded with redirect to #{uri}" }
                redirects.size > max_redirects and raise Error,
                  "Could not get #{uri} because too many redirects!"
                redirects.include?(location) and raise Error,
                  "Could not get #{uri} because redirect cycle!"
                redirects << location
                uri = URI.parse(location)
                # continue the loop
              else
                raise Error, "Could not get #{uri} because #{response.code} #{response.message}!"
              end
            end
          end

          def memo(method, *path)
            ivar = "@#{method}".to_sym
            unless memo = instance_variable_get(ivar)
              memo = instance_variable_set(ivar, { })
            end

            memo.key?(path) or memo[path] = yield
            memo[path]
          end

        end

        include Librarian::Source::BasicApi

        lock_name 'SITE'
        spec_options []

        attr_accessor :environment, :uri
        private :environment=, :uri=

        def initialize(environment, uri, options = {})
          self.environment = environment
          self.uri = uri
        end

        def to_s
          uri
        end

        def ==(other)
          other &&
          self.class  == other.class &&
          self.uri    == other.uri
        end

        def to_spec_args
          [uri, {}]
        end

        def to_lock_options
          {:remote => uri}
        end

        def pinned?
          false
        end

        def unpin!
        end

        def install!(manifest)
          manifest.source == self or raise ArgumentError

          name = manifest.name
          version = manifest.version
          install_path = install_path(name)
          line = line(name)

          info { "Installing #{manifest.name} (#{manifest.version})" }

          debug { "Installing #{manifest}" }

          line.install_version! version, install_path
        end

        # NOTE:
        #   Assumes the Opscode Site API responds with versions in reverse sorted order
        def manifests(name)
          line(name).manifests
        end

        def cache_path
          @cache_path ||= begin
            dir = Digest::MD5.hexdigest(uri)[0..15]
            environment.cache_path.join("source/chef/site/#{dir}")
          end
        end

        def install_path(name)
          environment.install_path.join(name)
        end

        def fetch_version(name, version_uri)
          line(name).to_version(version_uri)
        end

        def fetch_dependencies(name, version, version_uri)
          line(name).version_dependencies(version).map{|k, v| Dependency.new(k, v, nil)}
        end

      private

        def line(name)
          @line ||= { }
          @line[name] ||= Line.new(self, name)
        end

        def info(*args, &block)
          environment.logger.info(*args, &block)
        end

        def debug(*args, &block)
          environment.logger.debug(*args, &block)
        end

      end
    end
  end
end


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler;

import java.util.List;
import java.util.Set;

import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NMToken;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;

public class Allocation {

  final List<Container> containers;
  final Set<ContainerId> strictContainers;
  final Set<ContainerId> fungibleContainers;
  final List<ResourceRequest> fungibleResources;
  final List<NMToken> nmTokens;
  final List<Container> increasedContainers;
  final List<Container> decreasedContainers;
  final List<Container> promotedContainers;
  final List<Container> demotedContainers;
  private final List<Container> previousAttemptContainers;
  private Resource resourceLimit;

  public Allocation(List<Container> containers, Resource resourceLimit,
      Set<ContainerId> strictContainers, Set<ContainerId> fungibleContainers,
      List<ResourceRequest> fungibleResources) {
    this(containers,  resourceLimit,strictContainers,  fungibleContainers,
      fungibleResources, null);
  }

  public Allocation(List<Container> containers, Resource resourceLimit,
      Set<ContainerId> strictContainers, Set<ContainerId> fungibleContainers,
      List<ResourceRequest> fungibleResources, List<NMToken> nmTokens) {
    this(containers,  resourceLimit,strictContainers,  fungibleContainers,
      fungibleResources, nmTokens, null, null, null, null, null);
  }

  public Allocation(List<Container> containers, Resource resourceLimit,
      Set<ContainerId> strictContainers, Set<ContainerId> fungibleContainers,
      List<ResourceRequest> fungibleResources, List<NMToken> nmTokens,
      List<Container> increasedContainers, List<Container> decreasedContainer) {
    this(containers,  resourceLimit,strictContainers,  fungibleContainers,
        fungibleResources, nmTokens, increasedContainers, decreasedContainer,
        null, null, null);
  }

  public Allocation(List<Container> containers, Resource resourceLimit,
      Set<ContainerId> strictContainers, Set<ContainerId> fungibleContainers,
      List<ResourceRequest> fungibleResources, List<NMToken> nmTokens,
      List<Container> increasedContainers, List<Container> decreasedContainer,
      List<Container> promotedContainers, List<Container> demotedContainer,
      List<Container> previousAttemptContainers) {
    this.containers = containers;
    this.resourceLimit = resourceLimit;
    this.strictContainers = strictContainers;
    this.fungibleContainers = fungibleContainers;
    this.fungibleResources = fungibleResources;
    this.nmTokens = nmTokens;
    this.increasedContainers = increasedContainers;
    this.decreasedContainers = decreasedContainer;
    this.promotedContainers = promotedContainers;
    this.demotedContainers = demotedContainer;
    this.previousAttemptContainers = previousAttemptContainers;
  }

  public List<Container> getContainers() {
    return containers;
  }

  public Resource getResourceLimit() {
    return resourceLimit;
  }

  public Set<ContainerId> getStrictContainerPreemptions() {
    return strictContainers;
  }

  public Set<ContainerId> getContainerPreemptions() {
    return fungibleContainers;
  }

  public List<ResourceRequest> getResourcePreemptions() {
    return fungibleResources;
  }

  public List<NMToken> getNMTokens() {
    return nmTokens;
  }

  public List<Container> getIncreasedContainers() {
    return increasedContainers;
  }

  public List<Container> getDecreasedContainers() {
    return decreasedContainers;
  }

  public List<Container> getPromotedContainers() {
    return promotedContainers;
  }

  public List<Container> getDemotedContainers() {
    return demotedContainers;
  }

  public List<Container> getPreviousAttemptContainers() {
    return previousAttemptContainers;
  }

  @VisibleForTesting
  public void setResourceLimit(Resource resource) {
    this.resourceLimit = resource;
  }

  @Override
  public String toString() {
    return "Allocation{" + "containers=" + containers + ", strictContainers="
        + strictContainers + ", fungibleContainers=" + fungibleContainers
        + ", fungibleResources=" + fungibleResources + ", nmTokens=" + nmTokens
        + ", increasedContainers=" + increasedContainers
        + ", decreasedContainers=" + decreasedContainers
        + ", promotedContainers=" + promotedContainers + ", demotedContainers="
        + demotedContainers + ", previousAttemptContainers="
        + previousAttemptContainers + ", resourceLimit=" + resourceLimit + '}';
  }
}


text:
package com.elastisys.scale.cloudpool.aws.commons.functions;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

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

import com.amazonaws.services.ec2.model.HypervisorType;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceState;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.Monitoring;
import com.amazonaws.services.ec2.model.MonitoringState;
import com.amazonaws.services.ec2.model.Placement;
import com.amazonaws.services.ec2.model.Tag;
import com.elastisys.scale.cloudpool.api.types.CloudProviders;
import com.elastisys.scale.cloudpool.api.types.Machine;
import com.elastisys.scale.cloudpool.api.types.MachineState;
import com.elastisys.scale.cloudpool.api.types.MembershipStatus;
import com.elastisys.scale.cloudpool.api.types.ServiceState;
import com.elastisys.scale.cloudpool.aws.commons.ScalingTags;
import com.elastisys.scale.commons.json.JsonUtils;
import com.elastisys.scale.commons.util.time.FrozenTime;
import com.elastisys.scale.commons.util.time.UtcTime;

/**
 * Exercises the {@link InstanceToMachine} class.
 */
public class TestInstanceToMachine {

    @Before
    public void onSetup() {
        FrozenTime.setFixed(UtcTime.parse("2014-04-01T12:00:00Z"));
    }

    @Test
    public void convertCompleteInstance() {
        DateTime launchTime = UtcTime.now();
        Instance instance = new Instance().withInstanceId("i-1")
                .withState(new InstanceState().withName(InstanceStateName.Running)).withPublicIpAddress("1.2.3.4")
                .withPrivateIpAddress("1.2.3.5").withInstanceType(InstanceType.M1Small)
                .withLaunchTime(launchTime.toDate())
                .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen)
                .withPlacement(new Placement("us-east-1c"));

        Machine machine = convert(instance);
        assertThat(machine.getId(), is(instance.getInstanceId()));
        assertThat(machine.getLaunchTime(), is(launchTime));
        assertThat(machine.getMachineState(), is(MachineState.RUNNING));
        assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2));
        assertThat(machine.getRegion(), is("us-east-1"));
        assertThat(machine.getMachineSize(), is("m1.small"));
        assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus()));
        assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN));
        assertThat(machine.getPublicIps().size(), is(1));
        assertThat(machine.getPublicIps().get(0), is(instance.getPublicIpAddress()));
        assertThat(machine.getPrivateIps().size(), is(1));
        assertThat(machine.getPrivateIps().get(0), is(instance.getPrivateIpAddress()));
        assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance)));
    }

    @Test
    public void convertInstanceMissingPublicIp() {
        DateTime launchTime = UtcTime.now();

        Instance instance = new Instance().withInstanceId("i-1")
                .withState(new InstanceState().withName(InstanceStateName.Running)).withPrivateIpAddress("1.2.3.5")
                .withInstanceType(InstanceType.M1Small).withLaunchTime(launchTime.toDate())
                .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen)
                .withPlacement(new Placement("us-east-1a"));

        Machine machine = convert(instance);
        assertThat(machine.getId(), is(instance.getInstanceId()));
        assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2));
        assertThat(machine.getRegion(), is("us-east-1"));
        assertThat(machine.getMachineSize(), is("m1.small"));
        assertThat(machine.getLaunchTime(), is(launchTime));
        assertThat(machine.getMachineState(), is(MachineState.RUNNING));
        assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus()));
        assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN));
        assertThat(machine.getPublicIps().size(), is(0));
        assertThat(machine.getPrivateIps().size(), is(1));
        assertThat(machine.getPrivateIps().get(0), is(instance.getPrivateIpAddress()));
        assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance)));
    }

    @Test
    public void convertInstanceMissingPrivateIp() {
        DateTime launchTime = UtcTime.now();
        Instance instance = new Instance().withInstanceId("i-1")
                .withState(new InstanceState().withName(InstanceStateName.Running)).withPublicIpAddress("1.2.3.4")
                .withInstanceType(InstanceType.M1Medium).withLaunchTime(launchTime.toDate())
                .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen)
                .withPlacement(new Placement("us-east-1b"));

        Machine machine = convert(instance);
        assertThat(machine.getId(), is(instance.getInstanceId()));
        assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2));
        assertThat(machine.getRegion(), is("us-east-1"));
        assertThat(machine.getMachineSize(), is("m1.medium"));
        assertThat(machine.getLaunchTime(), is(launchTime));
        assertThat(machine.getMachineState(), is(MachineState.RUNNING));
        assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus()));
        assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN));
        assertThat(machine.getPublicIps().size(), is(1));
        assertThat(machine.getPublicIps().get(0), is(instance.getPublicIpAddress()));
        assertThat(machine.getPrivateIps().size(), is(0));
        assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance)));
    }

    @Test
    public void convertWithServiceStateTag() {
        Tag serviceStateTag = new Tag().withKey(ScalingTags.SERVICE_STATE_TAG)
                .withValue(ServiceState.OUT_OF_SERVICE.name());
        Instance instance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium)
                .withState(new InstanceState().withName(InstanceStateName.Running))
                .withPlacement(new Placement("us-east-1b")).withTags(serviceStateTag);

        Machine machine = convert(instance);
        assertThat(machine.getServiceState(), is(ServiceState.OUT_OF_SERVICE));
    }

    @Test
    public void convertWithMembershipStatusTag() {
        MembershipStatus status = MembershipStatus.awaitingService();
        String statusJsonString = JsonUtils.toString(JsonUtils.toJson(status));
        Tag membershipStatusTag = new Tag().withKey(ScalingTags.MEMBERSHIP_STATUS_TAG).withValue(statusJsonString);
        Instance instance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium)
                .withState(new InstanceState().withName(InstanceStateName.Running))
                .withPlacement(new Placement("us-east-1b")).withTags(membershipStatusTag);

        Machine machine = convert(instance);
        assertThat(machine.getMembershipStatus(), is(status));
    }

    /**
     * A converted spot instance {@link Machine} should have a cloud provider
     * value of {@link CloudProviders#AWS_SPOT} to distinguish it from a regular
     * EC2 on-demand instance.
     */
    @Test
    public void convertSpotInstance() {
        // convert on-demand instance: cloud provider should be AWS_EC2
        Instance onDemandInstance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium)
                .withState(new InstanceState().withName(InstanceStateName.Running))
                .withPlacement(new Placement("us-east-1b"));
        Machine onDemandMachine = convert(onDemandInstance);
        assertThat(onDemandMachine.getCloudProvider(), is(CloudProviders.AWS_EC2));

        // convert spot instance: cloud provider should be AWS_EC2
        Instance spotInstance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium)
                .withState(new InstanceState().withName(InstanceStateName.Running)).withSpotInstanceRequestId("sir-123")
                .withPlacement(new Placement("us-east-1b"));
        Machine spotMachine = convert(spotInstance);
        assertThat(spotMachine.getCloudProvider(), is(CloudProviders.AWS_SPOT));
    }

    public Machine convert(Instance instance) {
        return InstanceToMachine.convert(instance);
    }
}


text:
"""
Test to ensure we display a meaningful message when user gives bad input
for creating a bundle on the command line.
"""

import bundle_test_helper

#pragma out Expected Arguments: {source_filename} bundle_filename
bundle_test_helper.run_program("bundler.py", ["create"])


text:
package com.worescloud.workdesk.common.exception;

import com.worescloud.workdesk.common.exception.code.ExceptionCategory;
import com.worescloud.workdesk.common.exception.code.ExceptionCode;

import static com.worescloud.workdesk.common.exception.code.ExceptionCategory.ILLEGAL;
import static com.worescloud.workdesk.common.exception.code.ExceptionCategory.INNER;
import static com.worescloud.workdesk.common.exception.code.ExceptionModule.COMMON;

public class CommonException extends AbstractException {

	private static final long serialVersionUID = -3595143143148007167L;

    public enum Error {
        UNKNOWN(INNER, 0, "unknown error"),
        NOT_ANNOTATED_WITH_EXPECTED_ANNOTATION(ILLEGAL, 0, "class not annotated with expected annotation"),
        PROPERTY_METHOD_MISSING_PARAMETER(ILLEGAL, 1, "property set method missing parameters");

        private final ExceptionCode code;

        Error(ExceptionCategory category, int code, String description) {
            this.code = COMMON.createCode(category, code, description);
        }
    }

    public CommonException(Error error, Object... parameters) {
        super(error.code, parameters);
    }

    public CommonException(Throwable throwable) {
        super(throwable);
    }

    @Override
    protected ExceptionCode defaultCode() {
        return Error.UNKNOWN.code;
    }
}


text:
sm.Main.controller('MainController', [
  '$scope',
  '$log',
  'NAV_CONST',
  '$rootScope',
  '$timeout',
  function($scope, $log, NAV_CONST, $rootScope, $timeout){
    $log.debug('Main Controller');
    //$scope.mainNavCtx = {
    //  activeView: NAV_CONST.MARKET_VIEW
    //};
    $scope.mainNavCtx = {
      activeView: NAV_CONST.WELCOME_VIEW
    };
    $rootScope.$on('$stateChangeStart',
      function(event, toState, toParams, fromState, fromParams, options){
        //$log.debug('|');
        //$log.debug('|');
        //$log.debug('|   CHANGE STATE ', toState.name);
        $scope.mainNavCtx.isHome = false;
        $scope.mainNavCtx.isProfileView = false;

        if (toState.name === 'home') {
          $timeout(function() {
            $scope.mainNavCtx.isHome = true;
          }, 25);
        }
        else if (toState.name === 'userprofile_detail' || toState.name === 'org_profile') {

          $timeout(function() {
            $scope.mainNavCtx.isProfileView = true;
          }, 25);
        }
        else {
          $scope.mainNavCtx.isHome = false;
        }
        $log.debug('|');
        $log.debug('|');
      }
    );
    $scope.mainNavCtx.isHome = false;
    $log.debug('Main Controller after  SET CLASS ON BODY');

  }]);


text:
import { Injectable }             from '@angular/core';
import { Router, Resolve,
         ActivatedRouteSnapshot } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';

import { AdmnistrableItem } from '../../shared/administrable-item';
import { DatabaseService } from '../../shared/database.service';
import { AdminItemConfig, AIType, AdminItemConfigService } from '../shared/admin-item-config.module';

@Injectable()
export class ItemEditResolve implements Resolve<AdmnistrableItem> {

  constructor(private db: DatabaseService,
              private router: Router,
              private itemConfService : AdminItemConfigService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<any>|Promise<AdmnistrableItem>|boolean
  {
    console.log("editItem resolve begin");
    let itemConfig = this.itemConfService.getConfFromRoute(route.params['itemType']);
    if (itemConfig == null) this.router.navigate(['admin']);
    else
    {
      this.db.setItemConfig(itemConfig);
    }

    if (!route.params['slug'])
    {
     console.log("Resolve guard pas de slug on envoie un item vide");
     return Promise.resolve(new AdmnistrableItem());
    }

    return this.db.getItemBySlug(route.params['slug']).map(item =>
    {
      console.log("Resolve guard fetching item", item);
      if (item.slug) return item;
      else
      {
        console.log("Resolve guard fetching item is null redirect vers new");
        this.router.navigate(['../new']);
        return false;
      }
    }).first();/*.subscribe(item =>
    {

    }) as Observable<AdmnistrableItem>;*/

  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/task
  http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<context:annotation-config  />
<context:component-scan base-package="org/olat/test/scheduler"></context:component-scan>

<!-- id name will be used for thread names beginning -->
<task:scheduler id="schedulerTest" pool-size="1"/>

<task:annotation-driven scheduler="schedulerTest"/>

<!--  same as scheduler but with more options
<task:executor id="executorWithPoolSizeRange"
	               pool-size="5-25"
	               queue-capacity="100"/>
-->

</beans>


text:
package concurrency

type Request struct {
	Num  int
	Resp chan Response
}

type Response struct {
	Num      int
	WorkerID int
}

func PlusOneService(reqs <-chan Request, workerID int) {
	for req := range reqs {
		go func(req Request) {
			defer close(req.Resp)
			req.Resp <- Response{req.Num + 1, workerID}
		}(req)
	}
}


text:
package edu.northwestern.bioinformatics.studycalendar.restlets;

import org.restlet.data.Parameter;
import org.restlet.util.Series;

import java.util.Set;

/**
 * @author Jalpa Patel
 */
public class ResponseHeaderRestletFilterTest extends RestletTestCase {
    private ResponseHeaderRestletFilter filter;
    private MockRestlet next;
    private Series<Parameter> requestHeaders;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        useHttpRequest();

        next = new MockRestlet();

        filter = new ResponseHeaderRestletFilter();
        filter.setNext(next);
        requestHeaders = request.getHttpCall().getRequestHeaders();
    }

    public void testResponseHeaderForIE() throws Exception {
        requestHeaders.add("User-Agent","Mozilla/4.0(PC) (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)");
        replayMocks();
        filter.afterHandle(request, response);
        verifyMocks();
        Set<String> headerNames = response.getHttpCall().getResponseHeaders().getNames();
        assertNotContains("Response should not contain cache header", headerNames, "Cache-Control");
        assertNotContains("Response should not contain Pragma", headerNames, "Pragma");
    }

    public void testResponseHeaderForFireFox() throws Exception {
        requestHeaders.add("User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");
        replayMocks();
        filter.afterHandle(request, response);
        verifyMocks();
        Set<String> headerNames = response.getHttpCall().getResponseHeaders().getNames();
        assertContains("Response should contain cache header", headerNames, "Cache-Control");
        assertContains("Response should contain Pragma", headerNames, "Pragma");
    }
}