text:
<?php

namespace ImageOptim;

use ImageOptim\Result\FileResult;
use ImageOptim\Result\OptimizationResult;
use ImageOptim\Exception;
use ImageOptim\Exception\ExceptionExec;
use ImageOptim\Exception\ExceptionInvalidCommand;

class Optimizer {

    const ARGUMENT_PREV = "PREV";
    const ARGUMENT_POST = "POST";

    const VAR_TARGET_PATH = "{TARGET_PATH}";    // Argument variable: full target path (/tmp/logo.jpg)
    const VAR_TARGET_FILE = "{TARGET_FILE}";    // Argument variable: filename (logo.jpg)
    const VAR_TARGET_NAME = "{TARGET_NAME}";    // Argument variable: name (logo)
    const VAR_TARGET_DIR = "{TARGET_DIR}";      // Argument variable: target dir (/tmp/)

    /**
     * Exif image types supported, check IMAGETYPE_XXXXX constants
     * @var array
     */
    protected $exifImageTypes = array();

    /**
     * @var
     */
    protected $command;

    /**
     * Prev arguments
     * @var array
     */
    protected $prev_arguments = array();

    /**
     * Post arguments
     * @var array
     */
    protected $post_arguments = array();

    /**
     * @param string $command
     * @param array $exifImageTypes
     * @param bool|true $autoAddTargetPathAsArgument automatically add target filename as first of the post arguments
     * @throws ExceptionInvalidCommand
     */
    public function __construct($command, array $exifImageTypes, $autoAddTargetPathAsArgument = true) {
        if (strlen($command)<2) {
            throw new ExceptionInvalidCommand("Invalid optimization command: ".$command);
        }
        $this->command = $command;
        $this->exifImageTypes = $exifImageTypes;
        if ($autoAddTargetPathAsArgument) {
            $this->addPostArgument(self::VAR_TARGET_PATH);
        }
    }

    /**
     * Optimizes the image
     * @param FileResult $result
     * @return OptimizationResult|null
     */
    public function optimize(FileResult $result)  {
        if (!in_array($result->exifImageType, $this->exifImageTypes)) {
            return null; /* Ignore optimizer for this file */
        }
        $optimResult = new OptimizationResult($this);
        $optimResult->originalSize = $result->fileInfo->getSize();
        try {
            $arguments = implode(" ",$this->prev_arguments) . " ".implode(" ",$this->post_arguments);
            $arguments = str_replace(array(
                self::VAR_TARGET_PATH,
                self::VAR_TARGET_FILE,
                self::VAR_TARGET_NAME,
                self::VAR_TARGET_DIR
            ),array(
                $result->filePath,
                $result->fileInfo->getFilename(),
                $result->fileInfo->getBasename($result->fileInfo->getExtension()),
                dirname($result->filePath)
            ),$arguments);
            $optimResult->optimizerCommand = $this->command . " " . $arguments . " 2>&1";
            $optimResult->optimizerOutput = shell_exec($optimResult->optimizerCommand);
            if ($optimResult->optimizerOutput===null) {
                throw new ExceptionExec("Optimization command returned null: ".$optimResult->optimizerCommand);
            }
        } catch(\Exception $e) {
            $optimResult->exception = new ExceptionExec("Error executing optimization command: ".$e->getMessage(), 0, $e);
        }
        clearstatcache(true, $result->filePath); // Refresh cache for the file to get the new file size
        $optimResult->optimizedSize = $result->fileInfo->getSize();
        $optimResult->bytesOptimized = $optimResult->originalSize - $optimResult->optimizedSize;
        if ($optimResult->originalSize > 0) {
            $optimResult->percentOptimized = round(($optimResult->bytesOptimized / $optimResult->originalSize) * 100, 2);
        }
        if (!$optimResult->exception) {
            $optimResult->success = true;
        }
        // Append optimization operation automatically
        $result->optimizations[] = $optimResult;
        if ($optimResult->exception) {
            $result->exception = $optimResult->exception;
        }
        return $optimResult;
    }

    /**
     * Adds the argument as prev argument (before post arguments)
     * @param string $argument argument to add (variables available at self::VAR_XXXXXXX)
     */
    public function addPrevArgument($argument) {
        $this->addArgument(self::ARGUMENT_PREV, $argument);
    }

    /**
     * Adds the argument as post argument (after prev arguments)
     * @param string $argument argument to add (variables available at self::VAR_XXXXXXX)
     */
    public function addPostArgument($argument) {
        $this->addArgument(self::ARGUMENT_POST, $argument);
    }

    /**
     * Adds an argument
     * @param string $position
     * @param string $argument
     * @throws Exception
     * @throws InvalidArgumentException
     */
    protected function addArgument($position, $argument) {
        if (empty($argument) || !is_string($argument)) {
            throw new InvalidArgumentException('$argument must be a string');
        }
        switch($position) {
            case self::ARGUMENT_POST:
                $this->post_arguments[] = $argument;
                break;
            case self::ARGUMENT_PREV:
                $this->prev_arguments[] = $argument;
                break;
            default:
                throw new Exception('Unsupported argument position: '.$position);
                break;
        }
    }

}


text:
package io.crnk.core.engine.http;

public class HttpHeaders {

	private HttpHeaders() {
	}

	public static final String X_FORWARDED_PROTO_HEADER = "X-Forwarded-Proto";

	public static final String HTTP_HEADER_ACCEPT = "Accept";

	public static final String HTTP_HEADER_CRNK_COMPACT = "Crnk-Compact";

	public static final String HTTP_CONTENT_TYPE = "Content-Type";

	public static final String JSONAPI_CONTENT_TYPE = "application/vnd.api+json";

	public static final String JSON_CONTENT_TYPE = "application/json";

	public static final String DEFAULT_CHARSET = "utf-8";

	public static final String JSONAPI_CONTENT_TYPE_AND_CHARSET = JSONAPI_CONTENT_TYPE + "; charset=" +
			DEFAULT_CHARSET;

	public static final String VERSION_ACCEPT_PARAMETER = "version";

}

redpajama_set_name: RedPajamaGithub


text:
""" colr_run.py
    Run a subprocess, but don't let it output to stdout. Instead, capture it
    and show an animation. Stdout output from the process goes straight to
    /dev/null. Stderr too, if the -e option is given on the command line.
    -Christopher Welborn 07-08-2019
"""

import os
import subprocess
import sys

from .base import __version__ as colr_version
from .colr import (
    Colr as C,
    auto_disable as colr_auto_disable,
)
from .progress import AnimatedProgress
from .progress_frames import (
    _build_rainbow_variants,
    Frames,
)

try:
    from .colr_docopt import docopt
except ImportError as ex:
    if 'docopt' in ex.name.lower():
        print(
            'Import error while import colr_docopt: {}'.format(ex),
            file=sys.stderr,
        )
        print(
            '\nYou must have Docopt installed to use this tool.',
            file=sys.stderr,
        )
        print('Install it with: `pip install docopt`', file=sys.stderr)
    else:
        print('Cannot import docopt!: {}'.format(ex), file=sys.stderr)
    sys.exit(1)

_build_rainbow_variants(Frames)
colr_auto_disable()

NAME = 'Colr Run'
VERSION = '0.0.1'
VERSIONSTR = '{} v. {}'.format(NAME, VERSION)
SCRIPT = os.path.split(os.path.abspath(sys.argv[0]))[1]
SCRIPTDIR = os.path.abspath(sys.path[0])

# Default delay, in seconds, between animation frames.
DEFAULT_DELAY = 0.3

USAGESTR = """{versionstr} (Colr v. {colr_version})
    Runs a program, captures/silences stdout, and prints an animation instead.

    Usage:
        {script} -h | -v
        {script} -l
        {script} [-a] [-e] [-d secs] [-f name] [-m msg] -- ARGS...

    Options:
        ARGS                   : Command and arguments to run.
        -a,--append            : Append command to message.
        -d secs,--delay secs   : Delay, in seconds, between animation frames.
                                 Default: {delay}s
        -e,--stderr            : Capture stderr also.
        -f name,--frames name  : Name of a frame set to use.
                                 Use -l to list known names.
        -h,--help              : Show this help message.
        -l,--listframes        : List available animated frames names.
        -m msg,--msg msg       : Message to display.
        -v,--version           : Show version.

    Basic Example:
        To run a program with the default settings, -- is still required:
            {script} -- bash -c 'x=0; while ((x<1000000)); do let x+=1; done'

        Any output from the program will ruin the animation. You can silence
        stderr output with -e if you don't need it:
            {script} -e -- some-long-running-command

    Exit Status:
        The exit status of {script} is the exit status of the command being
        executed. For {script} errors, the exit status is 1 for basic errors,
        and 2 for cancelled commands.

""".format(
    script=SCRIPT,
    versionstr=VERSIONSTR,
    colr_version=colr_version,
    delay=DEFAULT_DELAY,
)

def main(argd):
    """ Main entry point, expects docopt arg dict as argd. """
    if argd['--listframes']:
        return list_frames()

    try:
        frameset = Frames.get_by_name(argd['--frames'] or 'dots_rainbow')
    except ValueError:
        raise InvalidArg('not a known frame set: {}'.format(argd['--frames']))
    return run_cmd(
        argd['ARGS'],
        delay=parse_float(argd['--delay'], default=DEFAULT_DELAY, minimum=0.1),
        msg=argd['--msg'],
        frameset=frameset,
        append=argd['--append'],
        stderr=argd['--stderr'],
    )

def list_frames():
    """ List all available frames names. """
    # Filter colored frames.
    names = Frames.names()
    basicnames = [
        s for s in names
        if not getattr(Frames, s).has_codes()
    ]
    print('\nAvailable Frames ({}):\n    '.format(len(basicnames)), end='')
    print('\n    '.join(basicnames))

    colored = sorted(set(
        name.rpartition('_')[-1]
        for name in names
        if (name not in basicnames) and (not name.endswith('_rgb'))
    ))
    print(
        '\nColor variants available ({}):\n    '.format(len(colored)),
        end='',
    )
    print('\n    '.join(
        '<name>_{}'.format(s)
        for s in colored
    ))
    return 0

def parse_float(s, default=None, minimum=None):
    """ Parse a string as a float. If the argument is "falsey", `default` is
        returned. On error, an InvalidArg is raised.

        Arguments:
            s        : String to parse.
            default  : Default value, when a "falsey" argument is given.
            minimum  : Minimum accepted value. InvalidArg is raised if this is
                       set and the value is less than `minimum`.
    """
    if not s:
        return default
    try:
        f = float(s)
    except ValueError:
        raise InvalidArg('not a float/number: {}'.format(s))
    if (minimum is not None) and (f < minimum):
        raise InvalidArg(
            'below minimum value, {:.2f}: {:.2f}'.format(minimum, f)
        )
    return f

def print_err(*args, **kwargs):
    """ A wrapper for print() that uses stderr by default.
        Colorizes messages, unless a Colr itself is passed in.
    """
    if kwargs.get('file', None) is None:
        kwargs['file'] = sys.stderr

    # Use color if the file is a tty.
    if kwargs['file'].isatty():
        # Keep any Colr args passed, convert strs into Colrs.
        msg = kwargs.get('sep', ' ').join(
            str(a) if isinstance(a, C) else str(C(a, 'red'))
            for a in args
        )
    else:
        # The file is not a tty anyway, no escape codes.
        msg = kwargs.get('sep', ' ').join(
            str(a.stripped() if isinstance(a, C) else a)
            for a in args
        )

    print(msg, **kwargs)

def run_cmd(
        args, msg=None, delay=None,
        frameset=None, append=False, stderr=False):
    """ Run a command, but capture it's stdout. Show an animation instead.
    """
    cmdstr = ' '.join(args)
    if msg:
        if append:
            msg = f'{msg}: {cmdstr}'
    else:
        msg = cmdstr
    p = AnimatedProgress(
        msg,
        delay=DEFAULT_DELAY if delay is None else delay,
        frames=(frameset or Frames.dots_rainbow).prepend(' '),
        show_time=True,
        auto_disable=True,
    )
    p.start()
    try:
        ret = subprocess.check_call(
            args,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL if stderr else None,
        )
    except subprocess.CalledProcessError:
        ret = 1
    p.stop()
    return ret

class InvalidArg(ValueError):
    """ Raised when the user has used an invalid argument. """
    def __init__(self, msg=None):
        self.msg = msg or ''

    def __str__(self):
        if self.msg:
            return f'Invalid argument, {self.msg}'
        return 'Invalid argument!'

def entry_point():
    """ Wrapper for if __name__ == '__main__', for setuptools console scripts.
    """
    try:
        mainret = main(docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT))
    except InvalidArg as ex:
        print_err(ex)
        mainret = 1
    except (EOFError, KeyboardInterrupt):
        print_err('\nUser cancelled.\n')
        mainret = 2
    except BrokenPipeError:
        print_err('\nBroken pipe, input/output was interrupted.\n')
        mainret = 3
    sys.exit(mainret)

if __name__ == '__main__':
    entry_point()


text:
from __future__ import absolute_import
# Copyright (c) 2010-2019 openpyxl

from .cell import Cell, WriteOnlyCell, MergedCell
from .read_only import ReadOnlyCell


text:
(function () {
	function BlocChatCookies($cookies, $uibModal) {
		var currentUser = $cookies.get('blocChatCurrentUser'); // retrieve cookie
		if (!currentUser || currentUser === '') {
			$uibModal.open({
				templateUrl: '/templates/usernamemodal.html',
				controller: 'UserModalInstanceCtrl',
				controllerAs: 'usermodal',
				size: 'sm',
				backdrop: 'static',
				keyboard: false
			})

			this.toggleAnimation = function () {
				this.animationsEnabled = !this.animationsEnabled;
			};
		}
		//return currentUser;
	}

	angular
		.module('blocChat')
		.run(['$cookies', '$uibModal', BlocChatCookies]);
})();


text:
package org.oskari.print.request;

import java.util.Optional;

import fi.nls.oskari.domain.map.wfs.WFSLayerOptions;
import org.json.JSONObject;
import org.oskari.service.user.UserLayerService;
import org.oskari.print.util.StyleUtil;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.domain.map.OskariLayer;

public class PrintLayer {
    private static final String KEY_FEATURE_STYLE = "featureStyle";

    private final int zIndex;
    private String layerId;
    private OskariLayer oskariLayer;
    private String style;
    private int opacity;
    private Optional<UserLayerService> processor;
    private PrintTile[] tiles;
    private JSONObject customStyle;

    public PrintLayer(int zIndex) {
        this.zIndex = zIndex;
    }

    public int getZIndex() {
        return zIndex;
    }

    public String getLayerId() {
        return layerId;
    }

    public void setLayerId(String layerId) {
        this.layerId = layerId;
    }

    public OskariLayer getOskariLayer() {
        return oskariLayer;
    }

    public void setOskariLayer(OskariLayer oskariLayer) {
        this.oskariLayer = oskariLayer;
    }

    public int getId() {
        return oskariLayer.getId();
    }

    public String getType() {
        return oskariLayer.getType();
    }

    public String getName() {
        return oskariLayer.getName();
    }

    public String getUrl() {
        return oskariLayer.getUrl();
    }

    public String getStyle() {
        return style != null ? style : oskariLayer.getStyle();
    }

    public void setStyle(String style) {
        this.style = style;
    }

    public String getVersion() {
        return oskariLayer.getVersion();
    }

    public int getOpacity() {
        return opacity;
    }

    public void setOpacity(int opacity) {
        this.opacity = opacity;
    }

    public String getUsername() {
        return oskariLayer.getUsername();
    }

    public String getPassword() {
        return oskariLayer.getPassword();
    }

    public PrintTile[] getTiles() {
        return tiles;
    }

    public void setTiles(PrintTile[] tiles) {
        this.tiles = tiles;
    }

    public Optional<UserLayerService> getProcessor() {
        return processor == null ? Optional.empty() : processor;
    }

    public void setProcessor(Optional<UserLayerService> processor) {
        this.processor = processor;
    }

    public void setCustomStyle (JSONObject customStyle) { this.customStyle = customStyle; }

    public JSONObject getCustomStyle () { return customStyle; }

    public JSONObject getOskariStyle () {
        if (customStyle != null) {
            return customStyle;
        }
        // TODO: print should support optionalStyles and whole style should be returned
        // return featureStyle for now
        if (getProcessor().isPresent()) {
            return getProcessor().get().getWFSLayerOptions(layerId).getDefaultFeatureStyle();
        }
        JSONObject styleJson = new WFSLayerOptions(oskariLayer.getOptions()).getNamedStyle(style);
        if (styleJson.has(KEY_FEATURE_STYLE)) {
            return JSONHelper.getJSONObject(styleJson, KEY_FEATURE_STYLE);
        }
        return WFSLayerOptions.getDefaultOskariStyle();
    }

}


text:
package com.googlecode.qlink.core.pruning;

import java.util.List;

import com.googlecode.qlink.api.tuple.Pair;

public interface IPruningAction<TChainType, TBlock>
{

	/**
	 * @param stackTop - NOTE: the topmost element will come first !!!
	 * @return
	 */
	List<Pair<TChainType, TBlock>> applyOnStack(List<Pair<TChainType, TBlock>> stackTop);

}


text:
package org.apache.catalina.tribes.test.channel;

import org.junit.Assert;
import org.junit.Test;

import org.apache.catalina.ha.session.BackupManager;
import org.apache.catalina.ha.tcp.SimpleTcpCluster;
import org.apache.catalina.tribes.Channel;

public class TestChannelConfig {

    @Test
    public void testIntInput() {

        SimpleTcpCluster cluster = new SimpleTcpCluster();
        cluster.setChannelSendOptions(Channel.SEND_OPTIONS_ASYNCHRONOUS | Channel.SEND_OPTIONS_MULTICAST);
        Assert.assertEquals(Channel.SEND_OPTIONS_ASYNCHRONOUS | Channel.SEND_OPTIONS_MULTICAST, cluster.getChannelSendOptions());
    }

    @Test
    public void testStringInputSimple() {

        SimpleTcpCluster cluster = new SimpleTcpCluster();
        cluster.setChannelSendOptions("multicast");
        Assert.assertEquals(Channel.SEND_OPTIONS_MULTICAST, cluster.getChannelSendOptions());
    }

    @Test
    public void testStringInputCompound() {

        SimpleTcpCluster cluster = new SimpleTcpCluster();
        cluster.setChannelSendOptions("async, multicast");
        Assert.assertEquals(Channel.SEND_OPTIONS_ASYNCHRONOUS | Channel.SEND_OPTIONS_MULTICAST, cluster.getChannelSendOptions());
    }

    @Test
    public void testStringRepresentationOfIntValue() {

        String options = "multicast, async";
        SimpleTcpCluster cluster = new SimpleTcpCluster();
        cluster.setChannelSendOptions(options);
        Assert.assertEquals(options, cluster.getChannelSendOptionsName());
    }

    @Test
    public void testStringInputForMapSendOptions() {

        BackupManager manager = new BackupManager();
        manager.setMapSendOptions("async, multicast");
        Assert.assertEquals(Channel.SEND_OPTIONS_ASYNCHRONOUS | Channel.SEND_OPTIONS_MULTICAST, manager.getMapSendOptions());
    }

}


text:
from UrlProvider import UrlProvider

import lxml.html
import logging

class SingleDemot(UrlProvider):
    def __init__(self, imageUrl):
        UrlProvider.__init__(self)
        self.image = imageUrl

    def provideUrl(self):
        if (self.image is None):
            return ""
        url = self.image
        self.image = None
        return url

    def isEmpty(self):
        return (self.image is not None)

class DemotGalleryBrowser(UrlProvider):
    def __init__(self, galleryUrl):
        UrlProvider.__init__(self)
        self.article = galleryUrl
        self.images = None
        ## print "Starting article:", self.article

    def provideUrl(self):
        if (self.images is None):
            body = self.getPageBody( self.article )
            self.images = self.parseArticle(body)

        if (len(self.images) < 1):
            ## end of images
            logging.warning("No more images in gallery")
            return ""

        url = self.images.pop(0)
        return url

    def isEmpty(self):
        if self.images is None:
            return False
        return (len(self.images) < 1)

    def parseArticle(self, body):
        inlineBody = body.replace("\r\n", " ")
        inlineBody = inlineBody.replace('\r', " ")
        inlineBody = inlineBody.replace('\n', " ")
        ## print "Body:\n", inlineBody

        lxmlSite = lxml.html.fromstring(inlineBody)
        players = lxmlSite.xpath("//article/div[contains(@class, 'demotivator')]/div[contains(@class, 'gallery')]")
        if (len(players) < 1):
            return ""

        ## print "Players:", players

        play = players[0]
        imgTags = play.xpath("//div[@class='rsSlideContent']//img[contains(@class, 'rsImg')]")
        ## print "Images:", imgTags

        retList = []
        for img in imgTags:
            url = img.get("src")
            if len(url) < 1:
                continue
            if url[0] == '/':
                retList.append( "http://demotywatory.pl/" + url )
            else:
                retList.append( url )

        return retList

class Demotywatory(UrlProvider):
    def __init__(self, random = False):
        UrlProvider.__init__(self)
        self.baseUrl = "http://www.demotywatory.pl"
        self.randomMode = random
        ##self.galleryProvider = DemotGalleryBrowser('http://demotywatory.pl/4750418/26-internautow-opowiada-o-najbardziej-zenujacych-wpadkach-i')
        self.providers = []

    def provideUrl(self):
        ##url = self.galleryProvider.provideUrl()
        ##return url

        if (self.randomMode):
            return self.randomUrl()

        ## main page images
        if len(self.providers) < 1:
            self.extractUrls()

        while len(self.providers) > 0:
            provider = self.providers[0]
            if provider.isEmpty():
                self.providers.pop(0)
            return provider.provideUrl()
        logging.warning("Empty providers list")
        return ""

    def randomUrl(self):
        body = self.getPageBody( 'http://demotywatory.pl/losuj' )
        urlList = self.parseRandomPage(body)
        if (len(urlList) < 1):
            logging.warning("No url found")
            return ""
        return urlList[0]

    def extractUrls(self):
        body = self.getPageBody( self.baseUrl )
        self.providers = self.parseMainPage(body)

    def parseMainPage(self, body):
        inlineBody = body.replace("\r\n", " ")
        inlineBody = inlineBody.replace('\r', " ")
        inlineBody = inlineBody.replace('\n', " ")

        lxmlSite = lxml.html.fromstring(inlineBody)
        demotTags = lxmlSite.xpath("//article/div[contains(@class, 'demotivator')]/div[contains(@class, 'demot_pic')]")

        ##print "Found:", demotTags
        ##lxml.etree.tostring( imgTags[0] )

        retList = []
        for elem in demotTags:
            classes = elem.get("class")
            ## print "Classes:", classes
            if "gallery" in classes:
                ## gallery case
                aTags = elem.xpath("./a[contains(@class, 'picwrapper')]")
                if len(aTags)<1:
                    logging.error("Invalid 'a' tag")
                    continue
                aElem = aTags[0]
                url = aElem.get("href")
                if len(url) < 1:
                    continue
                galleryUrl = self.checkUrl(url)
                ## print "Found gallery:", galleryUrl
                retList.append( DemotGalleryBrowser(galleryUrl) )
                continue
            ## else standard picture

            imgTags = elem.xpath(".//img")
            if len(imgTags)<1:
                logging.error("Invalid 'img' tag")
                continue
            img = imgTags[0]
            url = img.get("src")
            if len(url) < 1:
                continue
            imgUrl = self.checkUrl(url)
            ## print "Found image:", imgUrl
            retList.append( SingleDemot(imgUrl) )

        return retList

    def checkUrl(self, anUrl):
        if anUrl[0] == '/':
            return self.baseUrl + anUrl
        return anUrl

    def parseRandomPage(self, body):
        inlineBody = body.replace("\r\n", " ")
        inlineBody = inlineBody.replace('\r', " ")
        inlineBody = inlineBody.replace('\n', " ")

        lxmlSite = lxml.html.fromstring(inlineBody)
        imgTags = lxmlSite.xpath("//article/div[contains(@class, 'demotivator')]/div[contains(@class, 'demot_pic')]//img")

        ##print "Found:", imgTags
        ##lxml.etree.tostring( imgTags[0] )

        retList = []
        for img in imgTags:
            url = img.get("src")
            if len(url) < 1:
                continue
            if url[0] == '/':
                retList.append( self.baseUrl + url )
            else:
                retList.append( url )

        return retList


text:
package org.uva.sea.ql.interpreter.widget;

import java.util.EventListener;

import javax.swing.JComponent;
import javax.swing.JLabel;

import org.uva.sea.ql.ast.stmt.Question;
import org.uva.sea.ql.interpreter.value.Str;
import org.uva.sea.ql.interpreter.value.Value;

public class Label extends Widget {

	protected JLabel widget = new JLabel();

	public Label(Question question, Value<?> value){
		widget.setName(question.getIdent().getName());
		setValue(value);
	}

	@Override
	public JComponent getWidget() {
		return widget;
	}

	@Override
	public void setWidget(JComponent widget) {
		this.widget = (JLabel) widget;
	}

	@Override
	public void setValue(Value<?> value) {
		widget.setText(value.getValue().toString());
	}

	public Value<?> getValue() {
		return new Str(widget.getText());
	}

	@Override
	public void setActionListener(EventListener listener) {
	}

}


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

namespace DataConnect.Domain.ActivityModule.Aggregates
{
    public struct Speed
    {
        public  SpeedUnit Unit { get; set; }
        public decimal Value { get; set; }
    }
}


text:
Elixir treats documentation as a first-class citizen. This means documentation should be easy to write and easy to read. In this document you will learn how to write documentation in Elixir, covering constructs like module attributes, style practices and doctests.

## Markdown

Elixir documentation is written using Markdown. There are plenty of guides on Markdown online, we recommend the ones available at GitHub as a getting started point:

  * [Basic writing and formatting syntax](https://help.github.com/articles/basic-writing-and-formatting-syntax/)
  * [Mastering Markdown](https://guides.github.com/features/mastering-markdown/)

## Module Attributes

Documentation in Elixir is usually attached to module attributes. Let's see an example:

    defmodule MyApp.Hello do
      @moduledoc """
      This is the Hello module.
      """

      @doc """
      Says hello to the given `name`.

      Returns `:ok`.

      ## Examples

          iex> MyApp.Hello.world(:john)
          :ok

      """
      def world(name) do
        IO.puts "hello #{name}"
      end
    end

The `@moduledoc` attribute is used to add documentation to the module. `@doc` is used before a function to provide documentation for it. Besides the attributes above, `@typedoc` can also be used to attach documentation to types defined as part of typespecs.

## Function Arguments

When documenting a function, argument names are inferred by the compiler. For example:

    def size(%{size: size}) do
      size
    end

The compiler will infer this argument as `map`. Sometimes the inference will be suboptimal, especially if the function contains multiple clauses with the argument matching on different values each time. You can specify the proper names for documentation by declaring only the function head at any moment before the implementation:

    def size(map)
    def size(%{size: size}) do
      size
    end

## Recommendations

When writing documentation:

  * Keep the first paragraph of the documentation concise and simple, typically one-line. Tools like [ExDoc](https://github.com/elixir-lang/ex_doc/) use the first line to generate a summary.

  * Reference modules by their full name.

  Markdown uses backticks (`` ` ``) to quote code. Elixir builds on top of that to automatically generate links when module or function names are referenced. For this reason, always use full module names. If you have a module called `MyApp.Hello`, always reference it as `` `MyApp.Hello` `` and never as `` `Hello` ``.

  * Reference functions by name and arity if they are local, as in `` `world/1` ``, or by module, name and arity if pointing to an external module: `` `MyApp.Hello.world/1` ``.

  * Reference a `@callback` by prepending `c:`, as in `` `c:world/1` ``.

  * Reference a `@type` by prepending `t:`, as in `` `t:values/0` ``.

  * Start new sections with second level Markdown headers `##`. First level headers are reserved for module and function names.

  * Place documentation before the first clause of multi-clause functions. Documentation is always per function and arity and not per clause.

## Doctests

We recommend that developers include examples in their documentation, often under their own `## Examples` heading. To ensure examples do not get out of date, Elixir's test framework (ExUnit) provides a feature called doctests that allows developers to test the examples in their documentation. Doctests work by parsing out code samples starting with `iex>` from the documentation. You can read more about it at `ExUnit.DocTest`.

Notice doctests have limitations. When you cannot doctest a function, because it relies on state or side-effects, we recommend developers include examples directly without the `iex>` prompt.

## Documentation != Comments

Elixir treats documentation and code comments as different concepts. Documentation is for users of your Application Programming Interface (API), be it your co-worker or your future self. Modules and functions must always be documented if they are part of your API.

Code comments are for developers reading the code. They are useful to mark improvements, leave notes for developers reading the code (for example, you decided not to call a function due to a bug in a library) and so forth.

In other words: documentation is required, code comments are optional.

## Hiding Internal Modules and Functions

Besides the modules and functions libraries provide as part of their public interface, libraries may also implement important functionality that is not part of their API. While these modules and functions can be accessed, they are meant to be internal to the library and thus should not have documentation for end users.

Luckily, Elixir allows developers to hide modules and functions from the documentation. For example, one common practice for documenting internal behaviour is to set the `@moduledoc` attribute to `false` while documenting each function:

    defmodule MyApp.Hidden do
      @moduledoc false

      @doc """
      This function won't be listed in docs.
      """
      def function_that_wont_be_listed_in_docs do
        # ...
      end
    end

Similarly, developers can add `@doc false` to functions they do not want to be publicly exposed:

    defmodule MyApp.Sample do
      @doc false
      def add(a, b), do: a + b
    end

However, keep in mind that adding `@doc false` does not make the function private. The function above can still be invoked as `MyApp.Sample.add(1, 2)`. Not only that, if `MyApp.Sample` is imported, the `add/2` function will also be imported into the caller. For those reasons, be cautious when adding `@doc false` to functions, instead use one of these two options:

  * Move the undocumented function to a module with `@moduledoc false`, like `MyApp.Hidden`, ensuring the function won't be accidentally exposed or imported. Remember you can use `@moduledoc false` to hide a whole module and still document each function with `@doc`. Tools will still ignore the module.

  * Start the function name with one or two underscores, for example, `__add__/2`, and add `@doc false`. The compiler does not import functions with leading underscores and they hint to anyone reading the code of their intended private usage.

## Documenting Private Functions

Elixir warns if a private function has a `@doc` attribute and discards its content, because `@doc` is intended to be used only for your public interface.

Private functions may still need internal documentation for maintainers, though. That can be accomplished with code comments.

## Code.get_docs/2

Elixir stores documentation inside pre-defined chunks in the bytecode. It can be accessed from Elixir by using the `Code.get_docs/2` function. This also means documentation is only accessed when required and not when modules are loaded by the Virtual Machine. The only downside is that modules defined in-memory, like the ones defined in IEx, cannot have their documentation accessed as they do not have their bytecode written to disk.


text:
using System;

namespace RemoteExecution.Dispatchers.Messages
{
	[Serializable]
	internal class ExceptionResponseMessage : IResponseMessage
	{
		public string ExceptionType { get; set; }
		public string Message { get; set; }

		public ExceptionResponseMessage()
		{
		}

		public ExceptionResponseMessage(string id, Type exceptionType, string message)
		{
			ExceptionType = exceptionType.AssemblyQualifiedName;
			Message = message;
			CorrelationId = id;
		}

		#region IResponseMessage Members

		public object Value
		{
			get { throw (Exception)Activator.CreateInstance(Type.GetType(ExceptionType, true), Message); }
		}

		public string CorrelationId { get; set; }
		public string MessageType { get { return CorrelationId; } }

		#endregion
	}
}


text:
require 'rails/generators/base'
require 'rails/generators/active_record'

module OmniauthBoilerplate
  # ```sh
  # $ rails generate omniauth_boilerplate:install
  # ```
  #
  # The omniauth-boilerplate install generator:
  #
  # * Inserts `OmniauthBoilerplate::User` into your `User` model
  # * Inserts `OmniauthBoilerplate::Controller` into your `ApplicationController`
  # * Mounts the engine at `/auth`
  # * Creates an initializer file to allow further configuration.
  # * Creates a migration file that creates an authentications table
  class InstallGenerator < Rails::Generators::Base
    include Rails::Generators::Migration
    desc 'Install boilerplate code for omniauth'
    source_root File.expand_path('../templates', __FILE__)

    def create_omniauth_initializer
      copy_file 'omniauth.rb', 'config/initializers/omniauth.rb'
    end

    def inject_omniauth_boilerplate_into_application_controller
      inject_into_class(
        'app/controllers/application_controller.rb',
        ApplicationController,
        "  include OmniauthBoilerplate::Controller\n"
      )
    end

    def mount_omniauth_boilerplate_engine_at_auth
      route "mount OmniauthBoilerplate::Engine => '/auth'"
    end

    def create_or_inject_omniauth_boilerplate_into_user_model
      if File.exist? 'app/models/user.rb'
        inject_into_class(
          'app/models/user.rb',
          User,
          "  include OmniauthBoilerplate::User\n\n",
        )
      else
        @inherit_from = models_inherit_from
        template('user.rb.erb', 'app/models/user.rb')
      end
    end

    def create_omniauth_boilerplate_migration
      create_migration_if_required_for(:users)
      create_migration_if_required_for(:omniauth_boilerplate_authentications)

    end

    def display_readme_in_terminal
      readme 'README'
    end

    # for generating a timestamp when using `create_migration`
    def self.next_migration_number(dir)
      ActiveRecord::Generators::Base.next_migration_number(dir)
    end

    private

    def create_migration_if_required_for(table_name)
      return if table_exists? table_name
      copy_migration "create_#{table_name}.rb"
    end

    def copy_migration(migration_name, config = {})
      unless migration_exists?(migration_name)
        migration_template(
          "db/migrate/#{migration_name}.erb",
          "db/migrate/#{migration_name}",
          config.merge(migration_version: migration_version)
        )
      end
    end

    def migration_exists?(name)
      existing_migrations.include?(name)
    end

    def existing_migrations
      @existing_migrations ||= Dir.glob('db/migrate/*.rb').map do |file|
        migration_name_without_timestamp(file)
      end
    end

    def migration_name_without_timestamp(file)
      file.sub(%r{^.*(db/migrate/)(?:\d+_)?}, '')
    end

    def table_exists?(table_name)
      if ActiveRecord::Base.connection.respond_to?(:data_source_exists?)
        ActiveRecord::Base.connection.data_source_exists?(table_name)
      else
        ActiveRecord::Base.connection.table_exists?(table_name)
      end
    end

    def migration_version
      return unless Rails.version >= '5.0.0'
      "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]"
    end

    def models_inherit_from
      if Rails.version >= '5.0.0'
        'ApplicationRecord'
      else
        'ActiveRecord::Base'
      end
    end
  end
end


text:
package main

import (
	"fmt"
	"time"
)

func worker(done chan bool) {
	fmt.Println("working...")
	time.Sleep(time.Second)
	fmt.Println("done")

	done <- true
}

func main() {
	done := make(chan bool,1)
	go worker(done)
	<-done
}


text:
package de.adito.propertly.serialization;

import de.adito.propertly.core.api.Hierarchy;
import de.adito.propertly.core.common.PropertlyDebug;
import de.adito.propertly.core.spi.*;
import de.adito.propertly.serialization.converter.ConverterRegistry;
import de.adito.propertly.serialization.converter.impl.*;
import de.adito.propertly.serialization.xml.XMLSerializationProvider;
import de.adito.propertly.test.core.impl.*;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.awt.*;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * @author j.boesl, 27.02.15
 */
public class SerializationTest
{

  @Test
  public void simple() throws ParserConfigurationException, TransformerException
  {
    IHierarchy<TProperty> hierarchy = new VerifyingHierarchy<>(new Hierarchy<>("root", new TProperty()));
    TProperty tProperty = hierarchy.getValue();

    PropertyTestChildren children = tProperty.setCHILD(new PropertyTestChildren());

    tProperty.setX(123);
    tProperty.setFF(new Dimension(123, 456));

    children.addProperty(Color.class, "color1").setValue(Color.BLACK);
    children.addProperty(Color.class, "color2").setValue(Color.RED);
    children.addProperty(TProperty.class, "pppChild");

    Serializer<Map<String, Object>> mapSerializer = Serializer.create(new MapSerializationProvider());

    Map<String, Object> serialize = mapSerializer.serialize(hierarchy);
    IPropertyPitProvider deserialize = mapSerializer.deserialize(serialize);

    assertEquals(PropertlyDebug.toTreeString(tProperty),
                        PropertlyDebug.toTreeString(deserialize));

    Serializer<Document> xmlSerializer = Serializer.create(new XMLSerializationProvider(_getConverterRegistry()));
    Document document = xmlSerializer.serialize(hierarchy);
    deserialize = xmlSerializer.deserialize(document);

    assertEquals(PropertlyDebug.toTreeString(tProperty),
                        PropertlyDebug.toTreeString(deserialize));
  }

  private static ConverterRegistry _getConverterRegistry()
  {
    ConverterRegistry converterRegistry = new ConverterRegistry();

    TypePPPStringConverter typePPPStringConverter = new TypePPPStringConverter();
    typePPPStringConverter.register(TProperty.class, null);
    converterRegistry.register(typePPPStringConverter);

    EnumStringConverter enumStringConverter = new EnumStringConverter();
    converterRegistry.register(enumStringConverter);

    return converterRegistry;
  }

}


text:
namespace flutter {
namespace testing {

class EmbedderTestCompositorVulkan : public EmbedderTestCompositor {
 public:
  EmbedderTestCompositorVulkan(SkISize surface_size,
                               sk_sp<GrDirectContext> context);

  ~EmbedderTestCompositorVulkan() override;

 private:
  bool UpdateOffscrenComposition(const FlutterLayer** layers,
                                 size_t layers_count) override;

  FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorVulkan);
};

}  // namespace testing
}  // namespace flutter

#endif  // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_VULKAN_H_


text:
import Ember from 'ember';

export default Ember.Route.extend({
	model: function() {
		return this.store.find('timeslot');
	},

	setupController: function(controller, model) {
		controller.set('timeslots', model); // transform the model into something semantically richer...
		controller.set('model', model);
	}
});


text:
/* eslint quotes: ["error", "double"] */
/* nls files need to use double quotes */
define({
  "viewer": {
    "common": {
      "save": "Spremi",
      "close": "Zatvori"
    },
    "errors": {
      "noConfigName": "Konfiguracija nije navedena u index.html > configOptions.story",
      "configFormatError": "Navedena konfiguracije nije se mogla učitati zbog pogreške u JSON sintaksi.",
      "configNotFound": "Navedena konfiguracije nije pronađena ili se nije mogla učitati zbog pogreške u JSON sintaksi.",
      "boxTitle": "Došlo je do pogreške",
      "servedFromFile": "Aplikaciji treba pristupiti putem web-poslužitelja. Pojedinosti potražite u ${USER_GUIDE}.",
      "userGuide": "korisnički vodič",
      "invalidConfig": "Nevaljana konfiguracija",
      "invalidConfigNoApp": "Identifikator aplikacije za web-kartiranje nije određen u index.html.",
      "invalidConfigNoAppDev": "Identifikator aplikacije za web-kartiranje nije određen u parametrima URL-a (?appid=). U načinu rada razvoja ignorira se konfiguracija za appid u index.html.",
      "unspecifiedConfigOwner": "Preuzmite kratku poveznicu",
      "invalidConfigOwner": "Ovo nije dostupno u načinu automatske reprodukcije",
      "invalidConfignoOAuth": "Ova priča zahtijeva provjeru autentičnosti, konfigurirajte ArcGIS OAuth ID in index.html ili učinite priču javnom.",
      "invalidApp": "Ova se priča ne može učitati.",
      "appLoadingFail": "Nešto nije u redu, predložak {TPL_NAME} nije se točno učitao.",
      "notConfiguredDesktop": "Priča još nije konfigurirana.",
      "notConfiguredMobile": "Sastavljač predloška {TPL_NAME} nije podržan u ovoj veličini prikaza. Ako je moguće, promijenite veličinu preglednika da biste pristupili sastavljaču ili izradite priču na uređaju s većim zaslonom.",
      "notConfiguredMobile2": "Zakrenite uređaj u vodoravno usmjerenje kako biste upotrijebili sastavljač {TPL_NAME}.",
      "notAuthorized": "Niste ovlašteni za pristup ovoj priči",
      "notAuthorizedBuilder": "Niste ovlašteni za upotrebu sastavljača {TPL_NAME}.",
      "noViewerIE": "Priča nije podržana u ranijim verzijama preglednika Internet Explorer prije verzije ${VERSION}. ${UPGRADE}.",
      "noViewerIE2": "Pokušavate prikazati ovu priču preko starijeg, nepodržanog preglednika. Možda neki geoobjekti ne rade ili je došlo do drugih neočekivanih problema. Predlažemo nadogradnju u Internet Explorer 11 ili korištenje drugog preglednika, primjerice Chromea.",
      "noViewerIE3": "Krajem 2017. ova se priča više neće moći učitati u ovom pregledniku. Tada ćete morati koristiti podržani preglednik za prikaz ove priče.",
      "upgradeBrowser": "Ažurirajte svoj preglednik",
      "mapLoadingFail": "Nešto nije u redu, karta se nije točno učitala.",
      "signOut": "Odjava",
      "builderSupport1": "Sastavljač Story Map Cascade podržan je samo u ${CHROME} i ${SAFARI}. Međutim, Cascade priče koje izradite sa sastavljačem mogu se prikazati u tim preglednicima, Internet Exploreru 11+ i Firefoxu.",
      "builderSupport2": "Sastavljač Story Map Cascade nije podržan za iPad. Cascade priče koje izradite i podijelite radit će na iPadu.",
      "builderSupport3": "Cascade priče mogu se prikazati u preglednicima Chrome, Safari, Firefox i Internet Explorer 11+, ali sastavljač Story Map Cascade podržan je samo u ${CHROME} i ${SAFARI}.",
      "builderSupport4": "Cascade priče mogu se prikazati u preglednicima Chrome, Safari, Firefox i Internet Explorer 11+, ali sastavljač Story Map Cascade podržan je samo u ${CHROME} i ${SAFARI}.

Ako trebate sastavljač Cascade za podržavanje drugog preglednika, obratite se ${ESRI-SUPPORT} ili kliknite za glasanje: ${FIREFOX-BUILDER} | ${IE-BUILDER}.",
      "sorry": "Pozor:"
    },
    "mobileWarning": {
      "message1": "Pročitali ste mobilnu verziju ove priče. Za cijelu verziju s bogatijim elementima medija isprobajte je na stolnom računalu.",
      "email": "Pošaljite poveznicu na ovu priču e-poštom"
    },
    "media": {
      "captionPlaceholder": "Vaš natpis ovdje...",
      "loadingError": "Žao nam je, ovaj sadržaj nije dostupan",
      "explore": "Istraži",
      "exploreMap": "Istražite kartu",
      "exploreStop": "Zaustavi istraživanje",
      "sceneNotSupported": "Žao nam je, ova 3D karta nije podržana na vašem uređaju.",
      "loading1": "Učitavanje...",
      "loading2": "Učitavanje karte...",
      "videoPlayPause": "reproduciraj/pauziraj",
      "videoMuteUnmute": "isključi/uključi zvuk"
    },
    "headerFromCommon": {
      "defaultTagline": "${STORY_MAP}",
      "share": "Podijeli",
      "tooltipAutoplayDisabled": "Ovo nije dostupno u načinu automatske reprodukcije"
    },
    "shareFromCommon": {
      "copy": "Kopiraj",
      "copied": "Kopirano",
      "open": "Otvori",
      "embed": "Ugradi u web-stranicu",
      "embedExplain": "Upotrijebite sljedeći HTML kod da biste ugradili priču u web-stranicu.",
      "size": "Veličina (širina/visina):",
      "autoplayLabel": "Način automatske reprodukcije",
      "autoplayExplain1": "Način automatske reprodukcije napredovat će kroz vašu priču u redovitim intervalima. To je idealno za kiosk ili javno prikazani zaslon, no budite svjesni da će se u drugim situacijama priča možda teže čitati. Ova značajka nije podržana na malim zaslonima.",
      "autoplayExplain2": "Uredite trenutačni obuhvat",
      "linksupdated": "Poveznice ažurirane!"
    }
  }
});


text:
package com.example.expressiontree;

/**
 * @class PrintCommand
 *
 * @brief Prints the expression tree in the desired format, e.g.,
 *        "in-order," "pre-order," "post-order", or "level-order".
 *        This plays the role of the "ConcreteCommand" in the Command
 *        pattern.
 */
public class PrintCommand extends UserCommand {
    /** Format to print out the tree.*/
    private String format;

    /**
     * Constructor that provides the appropriate @a
     * TreeOps and the requested format.
     */
    PrintCommand(TreeOps context,
                 String printFormat) {
        super.treeOps = context;
        format = printFormat;
    }

    /** Print the expression tree. */
    public void execute() throws Exception {
        treeOps.print(format);
    }

    /** Print the valid commands available to users. */
    public void printValidCommands(boolean verboseField) {
        Platform platform = Platform.instance();
    	platform.disableAll(verboseField);
        platform.outputMenu("",
                            "",
                            "");
        platform.outputMenu("1a.",
                            "eval",
                            "[post-order]");
        platform.outputMenu("1b.",
                            "print",
                            "[in-order | pre-order | post-order| level-order]");
        platform.outputMenu("0a.",
                            "format",
                            "[in-order]");
        platform.outputMenu("0b.",
                            "set",
                            "[variable = value]");
        platform.outputMenu("0c.",
                            "quit",
                            "");
        platform.outputMenu("",
                            "",
                            "");
    }
}


text:
package me.minidigger.voxelgameslib.api.world;

import java.util.Optional;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;

import me.minidigger.voxelgameslib.api.command.CommandArguments;
import me.minidigger.voxelgameslib.api.command.CommandExecutor;
import me.minidigger.voxelgameslib.api.command.CommandInfo;
import me.minidigger.voxelgameslib.api.lang.Lang;
import me.minidigger.voxelgameslib.api.lang.LangKey;
import me.minidigger.voxelgameslib.api.map.Map;
import me.minidigger.voxelgameslib.api.role.Role;
import me.minidigger.voxelgameslib.libs.net.md_5.bungee.api.chat.TextComponent;

/**
 * Commands related to worlds
 */
@Singleton
@CommandExecutor
@SuppressWarnings("JavaDoc") // commands don't need javadoc, go read the command's descriptions
public class WorldCommands {

    //TODO world command completer

    @Inject
    private WorldHandler handler;

    @CommandInfo(name = "world", perm = "command.world", role = Role.ADMIN)
    public void world(@Nonnull CommandArguments args) {
//TODO remove me once GH-17 is implemented
        args.getSender().sendMessage(new TextComponent("It works! You are on " + args.getSender().getWorld()));
    }

    @CommandInfo(name = "world.load", perm = "command.world.load", role = Role.ADMIN, description = "Loads a world", min = 1)
    public void load(@Nonnull CommandArguments args) {
        Optional<Map> o = handler.getMap(args.getArg(0));
        Map map = o.orElseGet(() -> handler.loadMap(args.getArg(0)));

        handler.loadWorld(map);
    }

    @CommandInfo(name = "world.loadlocal", perm = "command.world.loadlocal", role = Role.ADMIN, description = "Loads a local world", min = 1)
    public void loadLocal(@Nonnull CommandArguments args) {
        handler.loadLocalWorld(args.getArg(0));
    }

    @CommandInfo(name = "world.unloadlocal", perm = "command.world.unloadlocal", role = Role.ADMIN, description = "Unloads a local world", min = 1)
    public void unloadLocal(@Nonnull CommandArguments args) {
        handler.unloadLocalWorld(args.getArg(0));
    }

    @CommandInfo(name = "world.unload", perm = "command.world.unload", role = Role.ADMIN, description = "Unloads a world", min = 1)
    public void unload(@Nonnull CommandArguments args) {
        Optional<Map> o = handler.getMap(args.getArg(0));
        if (o.isPresent()) {
            handler.unloadWorld(o.get());
        } else {
            Lang.msg(args.getSender(), LangKey.WORLD_UNKNOWN_MAP, args.getArg(0));
        }
    }

    @CommandInfo(name = "world.tp", perm = "command.world.tp", role = Role.MODERATOR, description = "TPs to a world", min = 1)
    public void tp(@Nonnull CommandArguments args) {
        Optional<Map> o = handler.getMap(args.getArg(0));
        if (o.isPresent()) {
            Map map = o.get();
            args.getSender().teleport(map.getWorldName(), map.getCenter());
        } else {
            args.getSender().teleport(args.getArg(0));
            Lang.msg(args.getSender(), LangKey.WORLD_UNKNOWN_MAP, args.getArg(0));
        }
    }
}


text:
package org.knowm.xchange.itbit.v1.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;

public class ItBitPlaceOrderRequest {

  @JsonProperty("type")
  protected String type;

  @JsonProperty("currency")
  protected String baseCurrency;

  @JsonProperty("side")
  private String side;

  @JsonProperty("amount")
  private String amount;

  @JsonProperty("price")
  private String price;

  @JsonProperty("instrument")
  private String instrument;

  public ItBitPlaceOrderRequest(
      String side,
      String type,
      String baseCurrency,
      String amount,
      String price,
      String instrument) {

    super();
    this.side = side;
    this.type = type;
    this.baseCurrency = baseCurrency;
    this.amount = amount;
    this.price = price;
    this.instrument = instrument;
  }

  public String getSide() {

    return side;
  }

  public String getType() {

    return type;
  }

  public String getBaseCurrency() {

    return baseCurrency;
  }

  public String getAmount() {

    return amount;
  }

  public String getPrice() {

    return price;
  }

  public String getInstrument() {

    return instrument;
  }
}


text:
You remove the marshmallow and then you feel some guilt.

It's Mothers Day. Did you call your mother?

[Call Mother](../mom/eatwithmom.md)


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;

namespace nialscorva.FCEEasyMods
{
    using StateCoroutine = IEnumerator<ModMachineEntity.StateReturn>;
    using Coroutine = IEnumerator<int>;

    class CoroutineEntry
    {
        protected long nextRun = 0;
        private Coroutine coroutine;
        public bool IsRunning { get; private set; } = true;

        public CoroutineEntry(Coroutine coroutine)
        {
            this.coroutine = coroutine;
        }
        public CoroutineEntry(IEnumerable<int> coroutine)
        {
            this.coroutine = coroutine.GetEnumerator();
        }
        public void Step(long now)
        {
            if (IsRunning && nextRun <= now)
            {
                IsRunning = coroutine.MoveNext();
                nextRun = now + coroutine.Current;
            }
        }
    }
    public class ModMachineEntity : MachineEntity
    {
        //=======================================================
        // Logging helpers
        //=======================================================
        protected string LOGGER_PREFIX;
        protected void log(String msg, params object[] args)
        {
            UnityEngine.Debug.Log(LOGGER_PREFIX + ": " + String.Format(msg, args));
        }

        //=======================================================
        // Static fields for timing
        //=======================================================
        protected static Stopwatch stopwatch = new Stopwatch();
        static ModMachineEntity()
        {
            stopwatch.Start();
        }
        public static long Now { get { return stopwatch.ElapsedMilliseconds; }}

        //=======================================================
        // Game Object members
        //=======================================================
        protected GameObject primaryGO = null;

        //=======================================================
        // Orientation
        //=======================================================
        public Vector3 Forward  { get; protected set; }
        public Vector3 Back     { get { return -Forward; } }
        public Vector3 Left     { get; protected set; }
        public Vector3 Right    { get { return -Left; } }
        public Vector3 Up       { get; protected set; }
        public Vector3 Down     { get { return -Up; } }

        //=======================================================
        // State Management
        //=======================================================
        public class StateReturn
        {
            public long NextRun = 0;
            public StateCoroutine NextState = null;
            public StateReturn(int n) { this.NextRun = n; }
            public StateReturn(StateCoroutine i) { NextState = i; }
            public static implicit operator StateReturn(int n) { return new StateReturn(n); }
        }

        public class State
        {
            protected long nextRun = 0;
            private StateCoroutine coroutine;
            public bool IsRunning { get; private set; } = true;

            public State(StateCoroutine coroutine) { this.coroutine = coroutine; }
            public void Step(long now)
            {
                if (IsRunning && nextRun <= now)
                {
                    IsRunning = coroutine.MoveNext();
                    StateReturn sr = coroutine.Current;
                    nextRun = now + (sr?.NextRun ?? 0);
                    if (sr?.NextState != null)
                    {
                        coroutine = sr.NextState;
                        IsRunning = true;
                    }
                }
            }
        }

        private State CurrentState;
        private State CurrentAnimationState;

        protected static StateReturn NextState(StateCoroutine next) { return new StateReturn(next); }

        //=======================================================
        // Coroutines for the timers
        //=======================================================
        List<CoroutineEntry> lowFreqCoroutines = new List<CoroutineEntry>();
        List<CoroutineEntry> animationCoroutines = new List<CoroutineEntry>();

        //=======================================================
        // Rotation Actions
        //=======================================================
        public delegate void RotationEventHandler(ModMachineEntity sender, Quaternion rotation);
        public event RotationEventHandler RotationEvent;

        public delegate void HoverEventHandler(ModMachineEntity sender);
        public event HoverEventHandler HoverEvent;

        //=======================================================
        // Constructors
        //=======================================================
        protected ModMachineEntity(ModCreateSegmentEntityParameters parameters) : base(parameters) {
            mbNeedsLowFrequencyUpdate = true;
            mbNeedsUnityUpdate = true;

            LOGGER_PREFIX = "[" + this.GetType().FullName + this.ToNormalizedCoordinates() + "]";

            StartLowFrequencyCoroutine(UpdateRotationOnce());
        }

        //=======================================================
        // Low Frequency Thread Handlers
        //=======================================================
        protected void StartLowFrequencyCoroutine(Coroutine coroutine)
        {
            lowFreqCoroutines.Add(new CoroutineEntry(coroutine));
        }
        protected void SetState(StateCoroutine s)
        {
            CurrentState = new State(s);
        }

        public override void LowFrequencyUpdate()
        {
            base.LowFrequencyUpdate();
            long now = stopwatch.ElapsedMilliseconds;

            CurrentState?.Step(now);

            foreach (CoroutineEntry i in lowFreqCoroutines)
            {
                i.Step(now);
            }
            // clean up the coroutines that have ended
            lowFreqCoroutines.RemoveAll(e => !e.IsRunning);

            // clean up the animation routines here, just to save time in the animation loop
            animationCoroutines.RemoveAll(e => !e.IsRunning);

        }

        //=======================================================
        // Render Thread Handlers
        //=======================================================
        protected virtual void InitializeGameObjects() { }

        protected void StartAnimationCoroutine(Coroutine coroutine)
        {
            animationCoroutines.Add(new CoroutineEntry(coroutine));
        }
        protected void SetAnimationState(StateCoroutine s)
        {
            CurrentAnimationState = new State(s);
        }
        public override void UnityUpdate()
        {
            base.UnityUpdate();
            if (this?.mWrapper?.mbHasGameObject != true)
            {
                return;
            }
            long now = stopwatch.ElapsedMilliseconds;
            if (primaryGO == null)
            {
                primaryGO = this.mWrapper?.mGameObjectList?[0];
                if (primaryGO != null)
                {
                    InitializeGameObjects();
                }
            }
            else
            {
                CurrentAnimationState?.Step(now);

                foreach (CoroutineEntry i in animationCoroutines)
                {
                    i.Step(now);
                }
            }
        }
        //=======================================================
        // Rotation Handlers
        //=======================================================
        public override void OnUpdateRotation(byte newFlags)
        {
            base.OnUpdateRotation(newFlags);
            Quaternion rotation = SegmentCustomRenderer.GetRotationQuaternion(newFlags);

            Forward = rotation * Vector3.forward;
            Left = rotation * Vector3.left;
            Up = rotation * Vector3.up;

            RotationEvent?.Invoke(this, rotation);
        }

        private Coroutine UpdateRotationOnce()
        {
            OnUpdateRotation(this.mFlags);
            yield break;
        }

        //=======================================================
        // Spatial Queries
        //=======================================================

        public T GetEntityAt<T>(CubeCoord relativeLoc) where T : class { return GetEntityAt<T>((long)relativeLoc.x, (long)relativeLoc.y, (long)relativeLoc.z); }
        public T GetEntityAt<T>(Vector3 relativeLoc) where T : class  {return GetEntityAt<T>((long)relativeLoc.x, (long)relativeLoc.y, (long)relativeLoc.z); }
        public T GetEntityAt<T>(long x, long y, long z) where T : class
        {
            x += this.mnX;
            y += this.mnY;
            z += this.mnZ;

            object se = base.AttemptGetSegment(x, y, z)?.SearchEntity(x, y, z);
            if (se is T)
            {
                return (T)se;
            }
            return null;

        }

        protected void StartNeighborSearchCoroutine<T>(IEnumerable<CubeCoord> coords,Func<T,Coroutine> whenFound) where T: class
        {
            StartLowFrequencyCoroutine(SearchForNeighbor<T>(coords,whenFound));
        }
        protected Coroutine SearchForNeighbor<T>(IEnumerable<CubeCoord> coords, Func<T, Coroutine> whenFound) where T : class
        {
            T neighbor=null;
            while (true)
            {
                foreach (CubeCoord c in coords)
                {
                    neighbor = GetEntityAt<T>(c);
                    if (neighbor != null)
                    {
                        break;
                    }
                    yield return 0;
                }
                // if we fell through because we found a neighbor, then delegate to the whenFound state.
                // Otherwise, loop back through and scan some more
                if (neighbor != null) {
                    Coroutine it = whenFound(neighbor);

                    while ((neighbor as SegmentEntity)?.mbDelete != true && it.MoveNext())
                    {
                        yield return it.Current;
                    }

                    // resume scanning
                    neighbor = null;
                }

            }
        }

        private string DebugText ="";
        protected virtual string PopupText {  get
            {
                if (DebugText.Equals(""))
                {
                    DebugText = DebugComponentsText();
                }
                return DebugText;
            }
        }

        public override string GetPopupText()
        {
            HoverEvent(this);
            return PopupText;
        }

        //=======================================================
        // Debugging Helpers
        //=======================================================

        /*
         * Gets a list of mesh renderers, animations, and scrollers.  Useful for putting in GetPopupText() when seeing what you can manipulate for a given GameObject
         */
        public string DebugComponentsText()
        {
            string msg = "";
            if (primaryGO == null)
            {
                return "";
            }
            foreach (GameObject go in mWrapper.mGameObjectList)
            {
                msg += go.name + ": \n  Mesh: ";
                msg += String.Join(", ",
                    (go.GetComponentsInChildren<MeshRenderer>())
                        .Select(m => m.name)
                        .ToArray()
                ) + "\n";
                foreach (Animation a in go.GetComponentsInChildren<Animation>())
                {
                    msg += "  Anim: " + a.name + "[";
                    foreach (AnimationState state in a)
                    {
                        msg += state.name + ",";
                    }
                    msg += "]\n";
                }
                var scrollers = go.GetComponentsInChildren<UVScroller_PG>();
                if (scrollers.Length > 0)
                {
                    msg += "  UVScroll_PG: " + String.Join(", ", scrollers.Select(m => m.name).ToArray());
                }
            }
            return msg;
        }
        protected void RotateMesh(Mesh m, Quaternion rot)
        {
            Vector3[] newVertices = new Vector3[m.vertices.Length];

            for (int i = 0; i < m.vertices.Length; ++i)
            {
                newVertices[i] = rot * m.vertices[i];
            }
            m.vertices = newVertices;
        }
    }
}


text:
"use strict";
var core_1 = require('@angular/core');
var googleMaps_loader_1 = require('./googleMaps.loader');
var GoogleMaps = (function () {
    function GoogleMaps(_elementRef) {
        this._elementRef = _elementRef;
    }
    GoogleMaps.prototype.ngAfterViewInit = function () {
        var el = this._elementRef.nativeElement.querySelector('.google-maps');
        // TODO: do not load this each time as we already have the library after first attempt
        googleMaps_loader_1.GoogleMapsLoader.load(function (google) {
            new google.maps.Map(el, {
                center: new google.maps.LatLng(44.5403, -78.5463),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
        });
    };
    GoogleMaps = __decorate([
        core_1.Component({
            selector: 'google-maps',
            styles: [require('./googleMaps.scss')],
            template: require('./googleMaps.html'),
        }),
        __metadata('design:paramtypes', [core_1.ElementRef])
    ], GoogleMaps);
    return GoogleMaps;
}());
exports.GoogleMaps = GoogleMaps;
//# sourceMappingURL=googleMaps.component.js.map


text:
@interface InputListModel : NSObject

@property (nonatomic, strong) NSArray * inputModel;

-(instancetype)initWithDictionary:(NSDictionary *)dictionary;

-(NSDictionary *)toDictionary;

@end


text:
require 'spec_helper'

describe Scripterator::Runner do
  let(:runner)      { Scripterator::Runner.new(description, &awesome_script) }
  let(:description) { 'Convert widgets to eggplant parmigiana' }
  let(:options)     { {start_id: start_id, output_stream: StringIO.new} }
  let(:start_id)    { 1 }

  let(:awesome_script) do
    Proc.new do
      before          { Widget.before_stuff }
      for_each_widget { |widget| Widget.transform_a_widget(widget) }
      after_batch     { |batch| Widget.after_batch_stuff(batch) }
    end
  end

  subject { runner.run(options) }

  shared_examples_for 'raises an error' do
    specify do
      expect { subject }.to raise_error(StandardError)
    end
  end

  it 'infers the model from the for_each block' do
    expect(runner.send(:model_finder)).to eq Widget
  end

  context 'when a model block is defined' do
    let(:awesome_script) do
      Proc.new do
        model           { Widget.where(name: 'bla') }
        before          { Widget.before_stuff }
        for_each_widget { |widget| Widget.transform_a_widget(widget) }
        after_batch     { |batch| Widget.after_batch_stuff(batch) }
      end
    end
    let!(:widget1) { Widget.create(name: 'foo') }
    let!(:widget2) { Widget.create(name: 'bla') }

    it 'uses the given model finder code' do
      expect(Widget).to receive(:transform_a_widget).once.with(widget2)
      expect(Widget).not_to receive(:transform_a_widget).with(widget1)
      subject
    end
  end

  context 'when no start or end ID is passed' do
    let(:options) { {} }

    it_behaves_like 'raises an error'
  end

  context 'when an id list is passed' do
    before { num_widgets.times { Widget.create! } }

    let(:num_widgets) { 3 }
    let(:options) { { id_list: Widget.all.map(&:id) } }

    it 'transforms each widget in the list' do
      options[:id_list].each do |id|
        expect(runner).to receive(:transform_one_record) do |arg1|
          expect(arg1.id).to eq id
        end
      end
      subject
    end
  end

  context 'when no per-record block is defined' do
    let(:awesome_script) do
      Proc.new do
        model  { Widget }
        before { Widget.before_stuff }
      end
    end

    it_behaves_like 'raises an error'

    it 'does not run any other given blocks' do
      expect(Widget).to_not receive(:before_stuff)
      subject rescue nil
    end
  end

  context 'when there are no records for the specified model' do
    it 'does not run the per-record block' do
      expect(Widget).to_not receive(:transform_a_widget)
      subject
    end
  end

  context 'when there are records for the specified model' do
    let(:num_widgets) { 3 }

    before { num_widgets.times { Widget.create! } }

    it 'runs the given script blocks' do
      expect(Widget).to receive(:before_stuff)
      expect(Widget).to receive(:transform_a_widget).exactly(num_widgets).times
      expect(Widget).to receive(:after_batch_stuff)
      subject
    end

    context 'when not all records are checked' do
      let(:start_id) { Widget.last.id }

      it 'marks only the checked IDs as checked' do
        subject
        expect(Scripterator.already_run_for?(description, Widget.first.id)).to be_falsey
        expect(Scripterator.checked_ids(description)).to_not include Widget.first.id
        expect(Scripterator.already_run_for?(description, Widget.last.id)).to be_truthy
        expect(Scripterator.checked_ids(description)).to include Widget.last.id
      end
    end

    context 'when some records have already been checked' do
      let(:checked_ids) { [Widget.first.id] }

      before do
        allow(Scripterator).to receive(:checked_ids).and_return(checked_ids)
        allow_any_instance_of(Scripterator::ScriptRedis).to receive(:already_run_for?).and_return(false)
        allow_any_instance_of(Scripterator::ScriptRedis).to receive(:already_run_for?).with(Widget.first.id).and_return(true)
      end

      it 'only runs the per-record code for unchecked records' do
        expect(Widget).to receive(:transform_a_widget).exactly(num_widgets - 1).times
        subject
      end
    end

    context 'when the code for some records fails' do
      before do
        allow(Widget).to receive(:transform_a_widget) do |widget|
          raise 'Last widget expl0de' if widget.id == Widget.last.id
          true
        end
      end

      it 'marks only the failed IDs as failed' do
        subject
        expect(Scripterator.failed_ids(description)).to_not include Widget.first.id
        expect(Scripterator.failed_ids(description)).to include Widget.last.id
      end
    end

    context 'when Redis client is set to nil' do
      before { Scripterator.configure { |config| config.redis = nil } }
      after  { Scripterator.instance_variable_set(:@config, nil) }

      it 'runs without Redis' do
        expect { subject }.not_to raise_error
        expect(Scripterator.checked_ids(description)).to be_empty
      end
    end
  end
end


text:
import time

from RULEngine.Debug.debug_interface import DebugInterface
from RULEngine.Game.Referee import RefereeCommand
from ai.Algorithm.auto_play import SimpleAutoPlay
from ai.executors.executor import Executor
from ai.states.world_state import WorldState
from config.config_service import ConfigService

class PlayExecutor(Executor):

    def __init__(self, p_world_state: WorldState):
        """
        initialise le PlayExecutor

        :param p_world_state: (WorldState) instance du worldstate
        """
        super().__init__(p_world_state)
        cfg = ConfigService()
        self.auto_play = SimpleAutoPlay(self.ws)
        self.ws.play_state.autonomous_flag = cfg.config_dict["GAME"]["autonomous_play"] == "true"
        self.last_time = 0

    def exec(self) -> None:
        """
        Execute la stratégie courante et envoie le status des robots et les livres de tactiques et stratégies

        :return: None
        """

        if self.ws.play_state.autonomous_flag:
            self.auto_play.update()

        self._execute_strategy()

        if time.time() - self.last_time > 0.25:
            # TODO use handshake with the UI-DEBUG to stop sending it every frame! MGL 2017/03/16
            self._send_books()
            self.ws.debug_interface.send_team_color()

            self._send_robots_status()
            self._send_auto_state()
            self.last_time = time.time()

    def _execute_strategy(self) -> None:
        """
        Éxecute la stratégie courante.

        :return: None
        """
        # Applique un stratégie par défault s'il n'en a pas (lors du démarage par exemple)
        # TODO change this so we don't send humancontrol when nothing is set/ Donothing would be better
        if self.ws.play_state.current_strategy is None:
            self.ws.play_state.set_strategy(self.ws.play_state.get_new_strategy("HumanControl")(self.ws.game_state))
        # L'éxécution en tant que telle
        self.ws.play_state.current_strategy.exec()
        # self.ws.play_state.current_ai_commands = self.ws.play_state.current_strategy.exec()

    def _send_robots_status(self) -> None:
        """
        Envoie le status des robots (id, nom tactic + flag de status,
         nom action (phase tactic), target) par le debug interface.

        :return: None
        """
        states = self.ws.play_state.get_current_tactical_state()
        for state in states:
            player_id = state[0]
            tactic_name = state[1]
            action_name = state[2]
            target = (int(state[3].position.x), int(state[3].position.y))
            self.ws.debug_interface.send_robot_strategic_state(player_id,
                                                               tactic_name,
                                                               action_name,
                                                               target)

    def _send_auto_state(self) -> None:
        self.ws.debug_interface.send_play_info(self.ws.game_state.game.referee.info,
                                                self.ws.game_state.game.referee.team_info,
                                                self.auto_play.info,
                                                self.ws.play_state.autonomous_flag)

    def _send_books(self) -> None:
        """
        Envoie les livres de stratégies et de tactiques

        :return: None
        """
        cmd_tactics = {'strategy': self.ws.play_state.
                       strategy_book.get_strategies_name_list(),
                       'tactic': self.ws.play_state.tactic_book.
                       get_tactics_name_list(),
                       'action': ['None']}
        self.ws.debug_interface.send_books(cmd_tactics)


text:
<?php

namespace Nakupujem\ShopBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Mapping as ORM;

/**
 * Photos
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Photo
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="path", type="text")
     */
    private $path;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToOne(targetEntity="Nakupujem\ShopBundle\Entity\Product")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     *  }
     * )
     */
    private $product;

    private $uploadDir;

    /**
     * @Assert\File(maxSize="6000000")
     */
    private $file;

    public function __constructor()
    {
        $this->product = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set path
     *
     * @param string $path
     * @return Photos
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Set product
     *
     * @param \Nakupujem\ShopBundle\Entity\Product $product
     * @return Photo
     */
    public function setProduct(\Nakupujem\ShopBundle\Entity\Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \Nakupujem\ShopBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }

    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    public function getAbsolutePath()
    {
        return null === $this->path
            ? null
            : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path
            ? null
            : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return $this->uploadDir;
    }

    public function setUploadDir($hash)
    {
        $this->uploadDir = "uploads/photos/" . $hash . "/";
    }

    public function upload($hash)
    {
    // the file property can be empty if the field is not required
    if (null === $this->getFile()) {
        return;
    }

    // use the original file name here but you should
    // sanitize it at least to avoid any security issues

    // move takes the target directory and then the
    // target filename to move to
    $this->getFile()->move(
        $this->getUploadRootDir(),
        $this->getFile()->getClientOriginalName()
    );

    // set the path property to the filename where you've saved the file
    $this->path = $hash . "/" . $this->getFile()->getClientOriginalName();

    // clean up the file property as you won't need it anymore
    $this->file = null;

}
}


text:
package com.google.appengine.datanucleus.jdo;

import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.datanucleus.Utils;
import com.google.appengine.datanucleus.test.jdo.BidirectionalChildListJDO;
import com.google.appengine.datanucleus.test.jdo.Flight;
import com.google.appengine.datanucleus.test.jdo.HasKeyAncestorKeyPkJDO;
import com.google.appengine.datanucleus.test.jdo.HasOneToManyListJDO;
import com.google.appengine.datanucleus.test.jdo.HasOneToOneJDO;

import java.lang.reflect.Method;

import javax.jdo.JDOUserException;

/**
 * @author Max Ross <maxr@google.com>
 */
public class JDOBatchDeleteTest extends JDOBatchTestCase {

  private static Entity newFlightEntity() {
    return Flight.newFlightEntity("Harold", "BOS", "MIA", 4, 2);
  }

  private static Entity newFlightEntity(Key parent, int childIndex) {
    Entity e = Flight.newFlightEntity(parent, null, "Harold", "BOS", "MIA", 4, 2, 23);
    e.setProperty("flights_INTEGER_IDX", childIndex);
    return e;
  }

  private static Entity newBidirChildEntity(Key parent, int childIndex) {
    Entity e = new Entity(BidirectionalChildListJDO.class.getSimpleName(), parent);
    e.setProperty("bidirChildren_INTEGER_IDX", childIndex);
    return e;
  }

  BatchRecorder newBatchRecorder() {
    DatastoreServiceConfig config = getStoreManager().getDefaultDatastoreServiceConfigForReads();
    return new BatchRecorder(config) {
      boolean isBatchMethod(Method method) {
        return method.getName().equals("delete") &&
          (method.getParameterTypes().length == 1 && Iterable.class.isAssignableFrom(method.getParameterTypes()[0])) ||
          (method.getParameterTypes().length == 2 && Iterable.class.isAssignableFrom(method.getParameterTypes()[1]));
      }
    };
  }

  public void testDeletePersistentAll_NoTxn() {
    switchDatasource(PersistenceManagerFactoryName.nontransactional);
    Key k1 = ds.put(newFlightEntity());
    Key k2 = ds.put(newFlightEntity());
    Flight f1 = pm.getObjectById(Flight.class, k1);
    Flight f2 = pm.getObjectById(Flight.class, k2);
    pm.deletePersistentAll(f1, f2);
    assertEquals(0, countForClass(Flight.class));
    assertEquals(1, batchRecorder.batchOps);

    Key k3 = ds.put(newFlightEntity());
    Key k4 = ds.put(newFlightEntity());
    Flight f3 = pm.getObjectById(Flight.class, k3);
    Flight f4 = pm.getObjectById(Flight.class, k4);
    pm.deletePersistentAll(Utils.newArrayList(f3, f4));
    assertEquals(0, countForClass(Flight.class));
    assertEquals(2, batchRecorder.batchOps);
  }

  public void testDeletePersistentAll_OneEntity_NoTxn() {
    switchDatasource(PersistenceManagerFactoryName.nontransactional);
    Key k1 = ds.put(newFlightEntity());
    Flight f1 = pm.getObjectById(Flight.class, k1);
    pm.deletePersistentAll(f1);
    assertEquals(0, countForClass(Flight.class));
    assertEquals(0, batchRecorder.batchOps);

    Key k2 = ds.put(newFlightEntity());
    Flight f2 = pm.getObjectById(Flight.class, k2);
    pm.deletePersistentAll(Utils.newArrayList(f2));
    assertEquals(0, countForClass(Flight.class));
    assertEquals(0, batchRecorder.batchOps);
  }

  public void testDeletePersistentAll_Txn_MultipleEntityGroups() {
    switchDatasource(PersistenceManagerFactoryName.transactional);
    Key k1 = ds.put(newFlightEntity());
    Key k2 = ds.put(newFlightEntity());
    beginTxn();
    Flight f1 = pm.getObjectById(Flight.class, k1);
    commitTxn();
    beginTxn();
    Flight f2 = pm.getObjectById(Flight.class, k2);
    commitTxn();
    beginTxn();
    try {
      pm.deletePersistentAll(f1, f2);
      fail("expected exception");
    } catch (JDOUserException e) {
      // good
    }
    rollbackTxn();
    assertEquals(2, countForClass(Flight.class));
    // We don't get to the batch delete because we blow up
    // before we get there.
    assertEquals(0, batchRecorder.batchOps);

    Key k3 = ds.put(newFlightEntity());
    Key k4 = ds.put(newFlightEntity());
    beginTxn();
    Flight f3 = pm.getObjectById(Flight.class, k3);
    commitTxn();
    beginTxn();
    Flight f4 = pm.getObjectById(Flight.class, k4);
    commitTxn();
    beginTxn();
    try {
      pm.deletePersistentAll(Utils.newArrayList(f3, f4));
      fail("expected exception");
    } catch (JDOUserException e) {
      // good
    }
    rollbackTxn();
    assertEquals(4, countForClass(Flight.class));
    assertEquals(0, batchRecorder.batchOps);
    // cleanup outside tx
    pm.deletePersistentAll(Utils.newArrayList(f1, f2, f3, f4));
  }

  public void testDeletePersistentAll_Txn_OneEntityGroup() {
    switchDatasource(PersistenceManagerFactoryName.transactional);
    Key parentKey = KeyFactory.createKey("yar", 24);
    Key k1 = ds.put(new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey));
    Key k2 = ds.put(new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey));
    beginTxn();
    HasKeyAncestorKeyPkJDO child1 = pm.getObjectById(HasKeyAncestorKeyPkJDO.class, k1);
    HasKeyAncestorKeyPkJDO child2 = pm.getObjectById(HasKeyAncestorKeyPkJDO.class, k2);
    pm.deletePersistentAll(child1, child2);
    commitTxn();
    assertEquals(0, countForClass(HasKeyAncestorKeyPkJDO.class));
    assertEquals(1, batchRecorder.batchOps);
  }

  public void testDeletePersistentAll_OneEntity_Txn() {
    switchDatasource(PersistenceManagerFactoryName.transactional);
    Key k1 = ds.put(newFlightEntity());
    beginTxn();
    Flight f1 = pm.getObjectById(Flight.class, k1);
    pm.deletePersistentAll(f1);
    commitTxn();
    assertEquals(0, countForClass(Flight.class));
    assertEquals(0, batchRecorder.batchOps);

    Key k2 = ds.put(newFlightEntity());
    beginTxn();
    Flight f2 = pm.getObjectById(Flight.class, k2);
    pm.deletePersistentAll(Utils.newArrayList(f2));
    commitTxn();
    assertEquals(0, countForClass(Flight.class));
    assertEquals(0, batchRecorder.batchOps);
  }

  public void testDeletePersistentAll_CascadeDelete_OneToOne_NoTxn() {
    switchDatasource(PersistenceManagerFactoryName.nontransactional);
    Key k1 = ds.put(new Entity(HasOneToOneJDO.class.getSimpleName()));
    Key k2 = ds.put(new Entity(HasOneToOneJDO.class.getSimpleName()));
    ds.put(newFlightEntity(k1, 1));
    ds.put(newFlightEntity(k2, 1));
    HasOneToOneJDO parent1 = pm.getObjectById(HasOneToOneJDO.class, k1);
    HasOneToOneJDO parent2 = pm.getObjectById(HasOneToOneJDO.class, k2);
    pm.deletePersistentAll(parent1, parent2);
    assertEquals(0, countForClass(HasOneToOneJDO.class));
    assertEquals(0, countForClass(Flight.class));
    assertEquals(1, batchRecorder.batchOps);
  }

  public void testDeletePersistentAll_CascadeDelete_OneToOne_MultipleEntityGroups_Txn() {
    switchDatasource(PersistenceManagerFactoryName.transactional);
    Key k1 = ds.put(new Entity(HasOneToOneJDO.class.getSimpleName()));
    Key k2 = ds.put(new Entity(HasOneToOneJDO.class.getSimpleName()));
    ds.put(newFlightEntity(k1, 1));
    ds.put(newFlightEntity(k2, 1));
    beginTxn();
    HasOneToOneJDO parent1 = pm.getObjectById(HasOneToOneJDO.class, k1);
    commitTxn();
    beginTxn();
    HasOneToOneJDO parent2 = pm.getObjectById(HasOneToOneJDO.class, k2);
    commitTxn();
    beginTxn();
    try {
      pm.deletePersistentAll(parent1, parent2);
      fail("expected exception");
    } catch (JDOUserException e) {
      // good
    }
    rollbackTxn();
    assertEquals(2, countForClass(HasOneToOneJDO.class));
    assertEquals(2, countForClass(Flight.class));
    assertEquals(1, batchRecorder.batchOps);
    // cleanup outside tx
    pm.deletePersistentAll(parent1, parent2);
  }

  public void testDeletePersistentAll_CascadeDelete_OneToOne_OneEntityGroup_Txn() {
    switchDatasource(PersistenceManagerFactoryName.transactional);

    Key k1 = ds.put(new Entity(HasOneToOneJDO.class.getSimpleName(), KeyFactory.createKey("Yar", 43)));
    Key k2 = ds.put(new Entity(HasOneToOneJDO.class.getSimpleName(), KeyFactory.createKey("Yar", 43)));
    ds.put(newFlightEntity(k1, 1));
    ds.put(newFlightEntity(k2, 1));
    beginTxn();
    HasOneToOneJDO parent1 = pm.getObjectById(HasOneToOneJDO.class, k1);
    HasOneToOneJDO parent2 = pm.getObjectById(HasOneToOneJDO.class, k2);
    pm.deletePersistentAll(parent1, parent2);
    commitTxn();
    assertEquals(0, countForClass(HasOneToOneJDO.class));
    assertEquals(0, countForClass(Flight.class));
    assertEquals(1, batchRecorder.batchOps);
  }

  public void testDeletePersistentAll_CascadeDelete_OneToMany_NoTxn() {
    switchDatasource(PersistenceManagerFactoryName.nontransactional);

    Entity owner1Entity = new Entity(HasOneToManyListJDO.class.getSimpleName());
    Key k1 = ds.put(owner1Entity);
    Entity owner2Entity = new Entity(HasOneToManyListJDO.class.getSimpleName());
    Key k2 = ds.put(owner2Entity);

    Entity fl1 = newFlightEntity(k1, 1);
    Entity fl2 = newFlightEntity(k1, 2);
    Entity fl3 = newFlightEntity(k2, 1);
    Entity fl4 = newFlightEntity(k2, 2);
    ds.put(fl1);
    ds.put(fl2);
    ds.put(fl3);
    ds.put(fl4);

    Entity bi1 = newBidirChildEntity(k1, 1);
    Entity bi2 = newBidirChildEntity(k1, 2);
    Entity bi3 = newBidirChildEntity(k2, 1);
    Entity bi4 = newBidirChildEntity(k2, 2);
    ds.put(bi1);
    ds.put(bi2);
    ds.put(bi3);
    ds.put(bi4);

    owner1Entity.setProperty("flights", Utils.newArrayList(fl1.getKey(), fl2.getKey()));
    owner1Entity.setProperty("bidirChildren", Utils.newArrayList(bi1.getKey(), bi2.getKey()));
    ds.put(owner1Entity);

    owner2Entity.setProperty("flights", Utils.newArrayList(fl3.getKey(), fl4.getKey()));
    owner2Entity.setProperty("bidirChildren", Utils.newArrayList(bi3.getKey(), bi4.getKey()));
    ds.put(owner2Entity);

    HasOneToManyListJDO parent1 = pm.getObjectById(HasOneToManyListJDO.class, k1);
    assertEquals(2, parent1.getFlights().size());
    assertEquals(2, parent1.getBidirChildren().size());
    HasOneToManyListJDO parent2 = pm.getObjectById(HasOneToManyListJDO.class, k2);
    assertEquals(2, parent2.getFlights().size());
    assertEquals(2, parent2.getBidirChildren().size());
    pm.deletePersistentAll(parent1, parent2);
    assertEquals(0, countForClass(HasOneToManyListJDO.class));
    assertEquals(0, countForClass(Flight.class));
    assertEquals(0, countForClass(BidirectionalChildListJDO.class));
    assertEquals(1, batchRecorder.batchOps);
  }

  public void testDeletePersistentAll_CascadeDelete_OneToMany_MultipleEntityGroups_Txn() {
    switchDatasource(PersistenceManagerFactoryName.transactional);
    Entity owner1Entity = new Entity(HasOneToManyListJDO.class.getSimpleName());
    Key k1 = ds.put(owner1Entity);
    Entity owner2Entity = new Entity(HasOneToManyListJDO.class.getSimpleName());
    Key k2 = ds.put(owner2Entity);

    Entity fl1 = newFlightEntity(k1, 1);
    Entity fl2 = newFlightEntity(k1, 2);
    Entity fl3 = newFlightEntity(k2, 1);
    Entity fl4 = newFlightEntity(k2, 2);
    ds.put(fl1);
    ds.put(fl2);
    ds.put(fl3);
    ds.put(fl4);

    Entity bi1 = newBidirChildEntity(k1, 1);
    Entity bi2 = newBidirChildEntity(k1, 2);
    Entity bi3 = newBidirChildEntity(k2, 1);
    Entity bi4 = newBidirChildEntity(k2, 2);
    ds.put(bi1);
    ds.put(bi2);
    ds.put(bi3);
    ds.put(bi4);

    owner1Entity.setProperty("flights", Utils.newArrayList(fl1.getKey(), fl2.getKey()));
    owner1Entity.setProperty("bidirChildren", Utils.newArrayList(bi1.getKey(), bi2.getKey()));
    ds.put(owner1Entity);

    owner2Entity.setProperty("flights", Utils.newArrayList(fl3.getKey(), fl4.getKey()));
    owner2Entity.setProperty("bidirChildren", Utils.newArrayList(bi3.getKey(), bi4.getKey()));
    ds.put(owner2Entity);

    beginTxn();
    HasOneToManyListJDO parent1 = pm.getObjectById(HasOneToManyListJDO.class, k1);
    assertEquals(2, parent1.getFlights().size());
    assertEquals(2, parent1.getBidirChildren().size());
    commitTxn();
    beginTxn();
    HasOneToManyListJDO parent2 = pm.getObjectById(HasOneToManyListJDO.class, k2);
    assertEquals(2, parent2.getFlights().size());
    assertEquals(2, parent2.getBidirChildren().size());
    commitTxn();
    beginTxn();
    try {
      pm.deletePersistentAll(parent1, parent2);
      fail("expected exception");
    } catch (JDOUserException e) {
      // good
    }
    rollbackTxn();
    assertEquals(2, countForClass(HasOneToManyListJDO.class));
    assertEquals(4, countForClass(Flight.class));
    assertEquals(4, countForClass(BidirectionalChildListJDO.class));
    assertEquals(1, batchRecorder.batchOps);
    // cleanup outside tx
    pm.deletePersistentAll(parent1, parent2);
  }

  public void testDeletePersistentAll_CascadeDelete_OneToMany_OneEntityGroup_Txn() {
    switchDatasource(PersistenceManagerFactoryName.transactional);
    Entity owner1Entity = new Entity(HasOneToManyListJDO.class.getSimpleName(), KeyFactory.createKey("yar", 43));
    Entity owner2Entity = new Entity(HasOneToManyListJDO.class.getSimpleName(), KeyFactory.createKey("yar", 43));
    Key k1 = ds.put(owner1Entity);
    Key k2 = ds.put(owner2Entity);

    Entity fl1 = newFlightEntity(k1, 1);
    Entity fl2 = newFlightEntity(k1, 2);
    Entity fl3 = newFlightEntity(k2, 1);
    Entity fl4 = newFlightEntity(k2, 2);
    ds.put(fl1);
    ds.put(fl2);
    ds.put(fl3);
    ds.put(fl4);

    Entity bi1 = newBidirChildEntity(k1, 1);
    Entity bi2 = newBidirChildEntity(k1, 2);
    Entity bi3 = newBidirChildEntity(k2, 1);
    Entity bi4 = newBidirChildEntity(k2, 2);
    ds.put(bi1);
    ds.put(bi2);
    ds.put(bi3);
    ds.put(bi4);

    owner1Entity.setProperty("flights", Utils.newArrayList(fl1.getKey(), fl2.getKey()));
    owner1Entity.setProperty("bidirChildren", Utils.newArrayList(bi1.getKey(), bi2.getKey()));
    ds.put(owner1Entity);

    owner2Entity.setProperty("flights", Utils.newArrayList(fl3.getKey(), fl4.getKey()));
    owner2Entity.setProperty("bidirChildren", Utils.newArrayList(bi3.getKey(), bi4.getKey()));
    ds.put(owner2Entity);

    beginTxn();
    HasOneToManyListJDO parent1 = pm.getObjectById(HasOneToManyListJDO.class, k1);
    assertEquals(2, parent1.getFlights().size());
    assertEquals(2, parent1.getBidirChildren().size());
    HasOneToManyListJDO parent2 = pm.getObjectById(HasOneToManyListJDO.class, k2);
    assertEquals(2, parent2.getFlights().size());
    assertEquals(2, parent2.getBidirChildren().size());
    pm.deletePersistentAll(parent1, parent2);
    commitTxn();

    assertEquals(0, countForClass(HasOneToManyListJDO.class));
    assertEquals(0, countForClass(Flight.class));
    assertEquals(0, countForClass(BidirectionalChildListJDO.class));
    assertEquals(1, batchRecorder.batchOps);
  }
}


text:
module Types where

import Data.Word (Word8)
import Foreign.ForeignPtr (ForeignPtr)

data Options = Options {
    acceptInUnbound :: Bool
  , yieldAfterSend  :: Bool
  , useRawSend      :: Bool
  , useRawRecv      :: Bool
  , prepareRecvBuf  :: Bool
  , useMalloc       :: Bool
  , processes       :: Int
  }

defaultOptions :: Options
defaultOptions = Options {
    acceptInUnbound = False
  , yieldAfterSend  = False
  , useRawSend      = False
  , useRawRecv      = False
  , prepareRecvBuf  = False
  , useMalloc       = False
  , processes       = 1
  }

type Receiver = IO Int
type Sender = IO ()
type Closer = IO ()

type Buffer = ForeignPtr Word8

recvBufferSize :: Int
recvBufferSize = 4096

arenaSize :: Int
arenaSize = 1000


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Linn. Soc. London 160(2): 149 (1949)

#### Original name
Asterina champereiae Hansf.

### Remarks
null


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

namespace SampSharp.GameMode.Controllers
{
    /// <summary>
    ///     A controller processing all vehicle actions.
    /// </summary>
    [Controller]
    public class BaseVehicleController : Disposable, IEventListener, ITypeProvider, IGameServiceProvider
    {
        /// <summary>
        ///     Registers the events this VehicleController wants to listen to.
        /// </summary>
        /// <param name="gameMode">The running GameMode.</param>
        public virtual void RegisterEvents(BaseMode gameMode)
        {
            //Register all vehicle events
            gameMode.VehicleSpawned += (sender, args) => (sender as BaseVehicle)?.OnSpawn(args);
            gameMode.VehicleDied += (sender, args) => (sender as BaseVehicle)?.OnDeath(args);
            gameMode.PlayerEnterVehicle += (sender, args) => args.Vehicle?.OnPlayerEnter(args);
            gameMode.PlayerExitVehicle += (sender, args) => args.Vehicle?.OnPlayerExit(args);
            gameMode.VehicleMod += (sender, args) => (sender as BaseVehicle)?.OnMod(args);
            gameMode.VehiclePaintjobApplied += (sender, args) => (sender as BaseVehicle)?.OnPaintjobApplied(args);
            gameMode.VehicleResprayed += (sender, args) => (sender as BaseVehicle)?.OnResprayed(args);
            gameMode.VehicleDamageStatusUpdated +=
                (sender, args) => (sender as BaseVehicle)?.OnDamageStatusUpdated(args);
            gameMode.UnoccupiedVehicleUpdated += (sender, args) => (sender as BaseVehicle)?.OnUnoccupiedUpdate(args);
            gameMode.VehicleStreamIn += (sender, args) => (sender as BaseVehicle)?.OnStreamIn(args);
            gameMode.VehicleStreamOut += (sender, args) => (sender as BaseVehicle)?.OnStreamOut(args);
            gameMode.TrailerUpdate += (sender, args) => (sender as BaseVehicle)?.OnTrailerUpdate(args);
            gameMode.VehicleSirenStateChange += (sender, args) => (sender as BaseVehicle)?.OnSirenStateChanged(args);
        }

        /// <summary>
        ///     Registers the services this controller provides.
        /// </summary>
        /// <param name="gameMode">The game mode.</param>
        /// <param name="serviceContainer">The service container.</param>
        public virtual void RegisterServices(BaseMode gameMode, GameModeServiceContainer serviceContainer)
        {
            serviceContainer.AddService<IVehicleFactory>(new BaseVehicleFactory(gameMode));
        }

        /// <summary>
        ///     Registers types this VehicleController requires the system to use.
        /// </summary>
        public virtual void RegisterTypes()
        {
            BaseVehicle.Register<BaseVehicle>();
        }

        /// <summary>
        ///     Performs tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <param name="disposing">Whether managed resources should be disposed.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (var vehicle in BaseVehicle.All)
                {
                    vehicle.Dispose();
                }
            }
        }
    }
}


text:
package ml.polymetric.textgame03;

public class Launcher
{
    public static final boolean debugMode = true; // Whether to print debug messages/generate bug report code

	private static Game	game = new Game(); // Create new Game object

	public static void main(String[] args)
	{
		game.start();
	}

	public static Game getGame() {return game;}
}