text:
package ir

import (
	"fmt"
)

type (
	// Policy represents a planned policy query.
	Policy struct {
		Static *Static
		Plan   *Plan
		Funcs  *Funcs
	}

	// Static represents a static data segment that is indexed into by the policy.
	Static struct {
		Strings      []*StringConst
		BuiltinFuncs []*BuiltinFunc
	}

	// BuiltinFunc represents a built-in function that may be required by the
	// policy.
	BuiltinFunc struct {
		Name string
	}

	// Funcs represents a collection of planned functions to include in the
	// policy.
	Funcs struct {
		Funcs []*Func
	}

	// Func represents a named plan (function) that can be invoked. Functions
	// accept one or more parameters and return a value. By convention, the
	// input document and data documents are always passed as the first and
	// second arguments (respectively).
	Func struct {
		Name   string
		Params []Local
		Return Local
		Blocks []*Block // TODO(tsandall): should this be a plan?
	}

	// Plan represents an ordered series of blocks to execute. Plan execution
	// stops when a return statement is reached. Blocks are executed in-order.
	Plan struct {
		Blocks []*Block
	}

	// Block represents an ordered sequence of statements to execute. Blocks are
	// executed until a return statement is encountered, a statement is undefined,
	// or there are no more statements. If all statements are defined but no return
	// statement is encountered, the block is undefined.
	Block struct {
		Stmts []Stmt
	}

	// Stmt represents an operation (e.g., comparison, loop, dot, etc.) to execute.
	Stmt interface {
	}

	// Local represents a plan-scoped variable.
	//
	// TODO(tsandall): should this be int32 for safety?
	Local int

	// Const represents a constant value from the policy.
	Const interface {
		typeMarker()
	}

	// NullConst represents a null value.
	NullConst struct{}

	// BooleanConst represents a boolean value.
	BooleanConst struct {
		Value bool
	}

	// StringConst represents a string value.
	StringConst struct {
		Value string
	}

	// IntConst represents an integer constant.
	IntConst struct {
		Value int64
	}

	// FloatConst represents a floating-point constant.
	FloatConst struct {
		Value float64
	}
)

const (
	// Input is the local variable that refers to the global input document.
	Input Local = iota

	// Data is the local variable that refers to the global data document.
	Data

	// Unused is the free local variable that can be allocated in a plan.
	Unused
)

func (a *Policy) String() string {
	return "Policy"
}

func (a *Static) String() string {
	return fmt.Sprintf("Static (%d strings)", len(a.Strings))
}

func (a *Funcs) String() string {
	return fmt.Sprintf("Funcs (%d funcs)", len(a.Funcs))
}

func (a *Func) String() string {
	return fmt.Sprintf("%v (%d params: %v, %d blocks)", a.Name, len(a.Params), a.Params, len(a.Blocks))
}

func (a *Plan) String() string {
	return fmt.Sprintf("Plan (%d blocks)", len(a.Blocks))
}

func (a *Block) String() string {
	return fmt.Sprintf("Block (%d statements)", len(a.Stmts))
}

func (a *BooleanConst) typeMarker() {}
func (a *NullConst) typeMarker()    {}
func (a *IntConst) typeMarker()     {}
func (a *FloatConst) typeMarker()   {}
func (a *StringConst) typeMarker()  {}

// ReturnLocalStmt represents a return statement that yields a local value.
type ReturnLocalStmt struct {
	Source Local
}

// CallStmt represents a named function call. The result should be stored in the
// result local.
type CallStmt struct {
	Func   string
	Args   []Local
	Result Local
}

// BlockStmt represents a nested block. Nested blocks and break statements can
// be used to short-circuit execution.
type BlockStmt struct {
	Blocks []*Block
}

func (a *BlockStmt) String() string {
	return fmt.Sprintf("BlockStmt (%d blocks)", len(a.Blocks))
}

// BreakStmt represents a jump out of the current block. The index specifies how
// many blocks to jump starting from zero (the current block). Execution will
// continue from the end of the block that is jumped to.
type BreakStmt struct {
	Index uint32
}

// DotStmt represents a lookup operation on a value (e.g., array, object, etc.)
// The source of a DotStmt may be a scalar value in which case the statement
// will be undefined.
type DotStmt struct {
	Source Local
	Key    Local
	Target Local
}

// LenStmt represents a length() operation on a local variable. The
// result is stored in the target local variable.
type LenStmt struct {
	Source Local
	Target Local
}

// ScanStmt represents a linear scan over a composite value. The
// source may be a scalar in which case the block will never execute.
type ScanStmt struct {
	Source Local
	Key    Local
	Value  Local
	Block  *Block
}

// NotStmt represents a negated statement.
type NotStmt struct {
	Block *Block
}

// AssignBooleanStmt represents an assignment of a boolean value to a local variable.
type AssignBooleanStmt struct {
	Value  bool
	Target Local
}

// AssignIntStmt represents an assignment of an integer value to a
// local variable.
type AssignIntStmt struct {
	Value  int64
	Target Local
}

// AssignVarStmt represents an assignment of one local variable to another.
type AssignVarStmt struct {
	Source Local
	Target Local
}

// AssignVarOnceStmt represents an assignment of one local variable to another.
// If the target is defined, execution aborts with a conflict error.
//
// TODO(tsandall): is there a better name for this?
type AssignVarOnceStmt struct {
	Target Local
	Source Local
}

// MakeStringStmt constructs a local variable that refers to a string constant.
type MakeStringStmt struct {
	Index  int
	Target Local
}

// MakeNullStmt constructs a local variable that refers to a null value.
type MakeNullStmt struct {
	Target Local
}

// MakeBooleanStmt constructs a local variable that refers to a boolean value.
type MakeBooleanStmt struct {
	Value  bool
	Target Local
}

// MakeNumberFloatStmt constructs a local variable that refers to a
// floating-point number value.
type MakeNumberFloatStmt struct {
	Value  float64
	Target Local
}

// MakeNumberIntStmt constructs a local variable that refers to an integer value.
type MakeNumberIntStmt struct {
	Value  int64
	Target Local
}

// MakeNumberRefStmt constructs a local variable that refers to a number stored as a string.
type MakeNumberRefStmt struct {
	Index  int
	Target Local
}

// MakeArrayStmt constructs a local variable that refers to an array value.
type MakeArrayStmt struct {
	Capacity int32
	Target   Local
}

// MakeObjectStmt constructs a local variable that refers to an object value.
type MakeObjectStmt struct {
	Target Local
}

// MakeSetStmt constructs a local variable that refers to a set value.
type MakeSetStmt struct {
	Target Local
}

// EqualStmt represents an value-equality check of two local variables.
type EqualStmt struct {
	A Local
	B Local
}

// LessThanStmt represents a < check of two local variables.
type LessThanStmt struct {
	A Local
	B Local
}

// LessThanEqualStmt represents a <= check of two local variables.
type LessThanEqualStmt struct {
	A Local
	B Local
}

// GreaterThanStmt represents a > check of two local variables.
type GreaterThanStmt struct {
	A Local
	B Local
}

// GreaterThanEqualStmt represents a >= check of two local variables.
type GreaterThanEqualStmt struct {
	A Local
	B Local
}

// NotEqualStmt represents a != check of two local variables.
type NotEqualStmt struct {
	A Local
	B Local
}

// IsArrayStmt represents a dynamic type check on a local variable.
type IsArrayStmt struct {
	Source Local
}

// IsObjectStmt represents a dynamic type check on a local variable.
type IsObjectStmt struct {
	Source Local
}

// IsDefinedStmt represents a check of whether a local variable is defined.
type IsDefinedStmt struct {
	Source Local
}

// IsUndefinedStmt represents a check of whether local variable is undefined.
type IsUndefinedStmt struct {
	Source Local
}

// ArrayAppendStmt represents a dynamic append operation of a value
// onto an array.
type ArrayAppendStmt struct {
	Value Local
	Array Local
}

// ObjectInsertStmt represents a dynamic insert operation of a
// key/value pair into an object.
type ObjectInsertStmt struct {
	Key    Local
	Value  Local
	Object Local
}

// ObjectInsertOnceStmt represents a dynamic insert operation of a key/value
// pair into an object. If the key already exists and the value differs,
// execution aborts with a conflict error.
type ObjectInsertOnceStmt struct {
	Key    Local
	Value  Local
	Object Local
}

// ObjectMergeStmt performs a recursive merge of two object values. If either of
// the locals refer to non-object values this operation will abort with a
// conflict error. Overlapping object keys are merged recursively.
type ObjectMergeStmt struct {
	A      Local
	B      Local
	Target Local
}

// SetAddStmt represents a dynamic add operation of an element into a set.
type SetAddStmt struct {
	Value Local
	Set   Local
}

// WithStmt replaces the Local or a portion of the document referred to by the
// Local with the Value and executes the contained block. If the Path is
// non-empty, the Value is upserted into the Local. If the intermediate nodes in
// the Local referred to by the Path do not exist, they will be created. When
// the WithStmt finishes the Local is reset to it's original value.
type WithStmt struct {
	Local Local
	Path  []int
	Value Local
	Block *Block
}

// ResultSetAdd adds a value into the result set returned by the query plan.
type ResultSetAdd struct {
	Value Local
}


text:
layout: relation
title: 'nsubj:cleft'
shortdef: 'nominal residual subject of a cleft sentence'
udver: '2'
---

Cleft sentences arise when a phrase in a matrix clause is extracted for emphasis and put into a prominent position with respect to the other elements of the clause (cf. [`csubj:cleft`](la-dep/csubj-cleft)).

When the relative clause acting as the subject of a cleft sentence does have an antecedent, we have a nominal type of subject; if not, the subject will be treated as [clausal](la-dep/csubj-cleft). This construction can appear with any extracted argument, and is obligatory if the extracted element is a modifier of another element in the original matrix clause, in which case the antecedent will (usually) correspond to the originally modified element.

As with clausal subjects, some minor readjustments in the components of the cleft sentence may be needed to make the whole sentence grammatical.

In the following example, *\|* points to the splitting point in the cleft sentence.

~~~ sdparse
ROOT Fuit ergo hebraicum ydioma | illud quod primi loquentis labia fabricarunt . \n ROOT Was so Hebrew language that which first of-the-speaking lips they-made .
root(ROOT-1,ydioma)
amod(ydioma,hebraicum)
nsubj:cleft(ydioma,illud)
cop(ydioma,Fuit)
acl:relcl(illud,fabricarunt)
obj(fabricarunt,quod)
root(ROOT-15,language)
amod(language,Hebrew)
nsubj:cleft(language,that)
cop(language,Was)
acl:relcl(that,they-made)
obj(they-made,which)
~~~

'So the Hebrew language was that which the lips of the first speaker moulded.' (*De Vulgari Eloquentia*, UDante)

* Matrix clause:
    * *Primi loquentis labia **hebraicum ydioma** fabricarunt.* (object argument)

~~~ sdparse
ROOT Ego sum | ille qui longas terras et ignotas regiones peragravi , ego | ille qui tam longe abieram ut in patriam redire non possem . \n ROOT I am that who long lands and unknown regions I-have-traversed , I that who so long I-had-went-away so-that in fatherland to-go-back not may .
root(ROOT-1,Ego)
nsubj:cleft(Ego,ille-5)
cop(Ego,sum)
acl:relcl(ille-5,peragravi)
nsubj(peragravi,qui-6)
conj(Ego,ego)
nsubj:cleft(ego,ille-16)
acl:relcl(ille-16,abieram)
nsubj(abieram,qui-17)
root(ROOT-29,I-30)
nsubj:cleft(I-30,that-32)
cop(I-30,am)
acl:relcl(that-32,I-have-traversed)
nsubj(I-have-traversed,who-33)
conj(I-30,I-41)
nsubj:cleft(I-41,that-42)
acl:relcl(that-42,I-had-went-away)
nsubj(I-had-went-away,who-43)
~~~

'I am the one who went through faraway and unknown lands, me who got so far that I could not even return home.' (*Declamationes*, Quintilian)

* Matrix clauses:
    * *(**Ego**) longas terras et ignotas regiones peragravi.* (subject argument)
    * *(**Ego**) tam longe abieram ut in patriam redire non possem.* (subject argument)
* Note that the second conjunct shows ellipsis of the copula.
* The subject does not need to be made explicit in Latin, but can be extracted nonetheless.

###References

* Goria, E. (2013). *Towards a taxonomy of Latin cleft sentences*, Journal of Latin Linguistics, 12(2): 147 – 172
<!-- Interlanguage links updated Po lis 14 15:35:34 CET 2022 -->

redpajama_set_name: RedPajamaGithub


text:
[![Latest Version](https://img.shields.io/github/release/php-http/mock-client.svg?style=flat-square)](https://github.com/php-http/mock-client/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)
[![Build Status](https://img.shields.io/travis/php-http/mock-client.svg?style=flat-square)](https://travis-ci.org/php-http/mock-client)
[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/php-http/mock-client.svg?style=flat-square)](https://scrutinizer-ci.com/g/php-http/mock-client)
[![Quality Score](https://img.shields.io/scrutinizer/g/php-http/mock-client.svg?style=flat-square)](https://scrutinizer-ci.com/g/php-http/mock-client)
[![Total Downloads](https://img.shields.io/packagist/dt/php-http/mock-client.svg?style=flat-square)](https://packagist.org/packages/php-http/mock-client)

**Mock HTTP client**

## Install

Via Composer

```bash
composer require --dev php-http/mock-client
```

## Usage

This client does not actually send requests to any server.

Instead it stores the request and returns a pre-set response or throws an exception. This client is useful for unit
testing code that depends on a HTTPlug client to send requests and receive responses.

## Documentation

Please see the [mock client](http://docs.php-http.org/en/latest/clients/mock-client.html) section in the [official documentation](http://docs.php-http.org).

## Testing

```bash
composer test
```

## Contributing

Please see our [contributing guide](http://docs.php-http.org/en/latest/development/contributing.html).

## Security

If you discover any security related issues, please contact us at [security@php-http.org](mailto:security@php-http.org).

## Credits

Thanks to [David de Boer](https://github.com/ddeboer) for implementing the mock client.

## License

The MIT License (MIT). Please see [License File](LICENSE) for more information.


text:
#pragma once

#include <list>

class Player;

class ScoreTable {

		struct Entry {
				const Player *m_player;
				const unsigned m_time;

				Entry(const Player *p_player, unsigned p_time) :
					m_player(p_player),
					m_time(p_time)
					{}
		};

	public:

		ScoreTable();

		virtual ~ScoreTable();

		void add(const Player *p_player, unsigned p_time);

		void clear();

		int getEntriesCount() const;

		const Player* getEntryPlayer(size_t index) const;

		unsigned getEntryTime(size_t index) const;

	private:

		std::list<Entry> m_entries;

		const Entry &getEntry(size_t index) const;

};


text:
<?php

Yii::setAlias('tests', realpath(__DIR__ . '/../../tests'));


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

namespace Cosmos.Assembler
{
    public class LiteralAssemblerCode: Instruction
    {
        public LiteralAssemblerCode(string code)
        {
            Code = code;
        }

        public string Code
        {
            get;
            set;
        }

        public override void WriteText(Assembler aAssembler, System.IO.TextWriter aOutput)
        {
            aOutput.Write(Code);
        }
    }
}


text:
package org.apache.sling.engine.impl.parameters;

import org.apache.sling.api.request.RequestParameter;

abstract class AbstractRequestParameter implements RequestParameter {

    private String name;

    private String encoding;

    protected AbstractRequestParameter(String name, String encoding) {
        this.name = name;
        this.encoding = encoding;
    }

    void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public String getEncoding() {
        return this.encoding;
    }

}


text:
from oslo_log import log as logging

from cinder import exception
from cinder.i18n import _
from cinder import interface
from cinder import utils
from cinder.volume import driver
from cinder.volume.drivers.yadro.tatlin_common import TatlinCommonVolumeDriver
from cinder.volume.drivers.yadro.tatlin_exception import TatlinAPIException
from cinder.volume import volume_utils

LOG = logging.getLogger(__name__)

@interface.volumedriver
class TatlinISCSIVolumeDriver(TatlinCommonVolumeDriver, driver.ISCSIDriver):
    """ACCESS Tatlin ISCSI Driver.

    Executes commands relating to ISCSI.
    Supports creation of volumes.

    .. code-block:: none

     API version history:

        1.0 - Initial version.
    """

    VERSION = "1.0"

    SUPPORTS_ACTIVE_ACTIVE = True

    # ThirdPartySystems wiki
    CI_WIKI_NAME = "Yadro_Tatlin_Unified_CI"

    def __init__(self, vg_obj=None, *args, **kwargs):
        # Parent sets db, host, _execute and base config
        super(TatlinISCSIVolumeDriver, self).__init__(*args, **kwargs)
        if self.configuration:
            self.backend_name = (self.configuration.safe_get(
                'volume_backend_name') or 'TatlinISCSI')
        self.DRIVER_VOLUME_TYPE = 'iSCSI'

    @volume_utils.trace
    def initialize_connection(self, volume, connector):
        @utils.synchronized("tatlin-volume-connections-%s" % volume.name_id)
        def _initialize_connection():
            LOG.debug('Init %s with connector %s', volume.name_id, connector)
            eth_ports = self._get_ports_portals()
            current_host = self.find_current_host(connector['initiator'])
            self.add_volume_to_host(volume, current_host)
            mapped_lun = self._find_mapped_lun(
                volume.name_id, connector['initiator'])
            port_result = self.tatlin_api.get_volume_ports(volume.name_id)

            result = {
                'driver_volume_type': 'iscsi',
                'data': self._create_volume_data(port_result, eth_ports,
                                                 mapped_lun)
            }

            if self._is_cinder_host_connection(connector):
                self._connections.increment(volume.name_id)

            LOG.debug('Current connection info %s', result)
            return result

        return _initialize_connection()

    def _get_ports_portals(self):
        try:
            result = self.tatlin_api.get_port_portal("ip")
        except TatlinAPIException as exp:
            message = (_('Failed to get ports info due to %s') % exp.message)
            LOG.error(message)
            raise exception.VolumeBackendAPIException(message=message)

        ports = {}
        for p in result:
            ipaddr = p['params']['ipaddress']
            if not ipaddr:
                continue
            iface = p['params']['ifname']
            if iface.startswith('p'):
                if self._export_ports and iface not in self._export_ports:
                    continue
                if iface not in ports:
                    ports[iface] = []
                ports[iface].append(ipaddr + ':3260')

        return ports

    def _create_volume_data(self, port_inf, eth_ports, lun_id):
        res = {'target_discovered': True, 'target_lun': lun_id}

        tatlin_version = self.tatlin_api.get_tatlin_version()

        if tatlin_version > (2, 3):
            if self._auth_method == 'CHAP':
                res['auth_method'] = 'CHAP'
                res['auth_username'] = self._chap_username
                res['auth_password'] = self._chap_password
        else:
            cred = self.tatlin_api.get_iscsi_cred()
            res['auth_method'] = 'CHAP'
            res['auth_username'] = cred['userid']
            res['auth_password'] = cred['password']

        target_luns = []
        target_iqns = []
        target_portals = []
        LOG.debug('Port data: %s', port_inf)
        for port in port_inf:
            if port['port'] not in eth_ports.keys():
                continue

            ips = eth_ports[port['port']]
            target_portals += ips

            luns = [lun_id for _ in ips]
            target_luns += luns

            if 'running' in port:
                target_iqns += port['wwn'] * len(port['running'])
            else:
                target_iqns += port['wwn']

        if not target_portals or not target_iqns or not target_luns:
            message = (_('Not enough connection data, '
                         'luns: %s, portals: %s, iqns: %s') %
                       target_luns, target_portals, target_iqns)
            LOG.error(message)
            raise exception.VolumeBackendAPIException(message=message)

        res['target_lun'] = target_luns[0]
        res['target_luns'] = target_luns
        res['target_iqn'] = target_iqns[0]
        res['target_iqns'] = target_iqns
        res['target_portal'] = target_portals[0]
        res['target_portals'] = target_portals

        LOG.debug("Volume data = %s", res)
        return res

    def find_current_host(self, wwn):
        LOG.debug('Try to find host id for %s', wwn)

        gr_id = self.tatlin_api.get_host_group_id(self._host_group)

        group_info = self.tatlin_api.get_host_group_info(gr_id)
        LOG.debug('Group info for %s is %s', self._host_group, group_info)
        for host_id in group_info['host_ids']:
            if wwn in self.tatlin_api.get_host_info(host_id)['initiators']:
                LOG.debug('Found host %s for initiator %s', host_id, wwn)
                return host_id

        mess = _('Unable to find host for initiator %s' % wwn)
        LOG.error(mess)
        raise exception.VolumeBackendAPIException(message=mess)


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports["default"] = void 0;

var _isPristine = _interopRequireDefault(require("../selectors/isPristine"));

var _immutable = _interopRequireDefault(require("../structure/immutable"));

var _default = (0, _isPristine["default"])(_immutable["default"]);

exports["default"] = _default;


text:
<?php

namespace Ekyna\Bundle\CmsBundle\Entity;

use Ekyna\Component\Resource\Model as RM;

/**
 * Class SlideTranslation
 * @package Ekyna\Bundle\CmsBundle\Entity
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class SlideTranslation extends RM\AbstractTranslation
{
    /**
     * @var array
     */
    private $data = [];

    /**
     * Returns the data.
     *
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Sets the data.
     *
     * @param array $data
     *
     * @return SlideTranslation
     */
    public function setData(array $data)
    {
        $this->data = $data;

        return $this;
    }
}


text:
package discordbot.command.fun;

import discordbot.command.CooldownScope;
import discordbot.command.ICommandCooldown;
import discordbot.core.AbstractCommand;
import discordbot.db.controllers.CBanks;
import discordbot.db.model.OBank;
import discordbot.games.SlotMachine;
import discordbot.games.slotmachine.Slot;
import discordbot.handler.Template;
import discordbot.main.Config;
import discordbot.main.DiscordBot;
import discordbot.util.Misc;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;

import java.util.concurrent.Future;

/**
 * Created on 23-8-2016
 */
public class SlotMachineCommand extends AbstractCommand implements ICommandCooldown {

    private final long SPIN_INTERVAL = 2000L;
    private final int MAX_BET = 1000;

    public SlotMachineCommand() {
        super();
    }

    @Override
    public long getCooldownDuration() {
//		return 30L;
        return 1L;
    }

    @Override
    public CooldownScope getScope() {
        return CooldownScope.USER;
    }

    @Override
    public String getDescription() {
        return "Feeling lucky? try the slotmachine! You might just win a hand full of air!";
    }

    @Override
    public String getCommand() {
        return "slot";
    }

    @Override
    public String[] getUsage() {
        return new String[]{
                "slot              //spin the slotmachine",
                "slot [cookies]    //play for real cookies where [cookies] is the amount of cookies you bet",
                "slot info         //info about payout"
        };
    }

    @Override
    public String[] getAliases() {
        return new String[]{};
    }

    @Override
    public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author) {
        if (args.length == 0 || args.length >= 1 && !args[0].equals("info")) {
            final int betAmount;
            if (args.length > 0 && args[0].matches("\\d+")) {
                betAmount = Math.min(Misc.parseInt(args[0], 0), MAX_BET);
            } else {
                betAmount = 0;
            }
            if (betAmount > 0) {
                OBank bank = CBanks.findBy(author.getId());
                if (bank.currentBalance < betAmount) {
                    return Template.get("gamble_insufficient_funds", betAmount, Config.ECONOMY_CURRENCY_ICON);
                }
                bank.transferTo(CBanks.getBotAccount(), betAmount, "slot machine");
            }
            final SlotMachine slotMachine = new SlotMachine();
            bot.out.sendAsyncMessage(channel, slotMachine.toString(), message -> {
                final Future<?>[] f = {null};
                f[0] = bot.scheduleRepeat(() -> {
                    try {
                        if (slotMachine.gameInProgress()) {
                            slotMachine.spin();
                        }
                        String gameResult;
                        if (!slotMachine.gameInProgress()) {
                            int winMulti = slotMachine.getWinMultiplier();
                            if (winMulti > 0) {
                                if (betAmount > 0) {
                                    gameResult = Template.get("gamble_slot_win", slotMachine.getWinSlotTimes(), slotMachine.getWinSlot().getEmote(), betAmount * winMulti, Config.ECONOMY_CURRENCY_ICON);
                                    CBanks.getBotAccount().transferTo(CBanks.findBy(author.getId()), betAmount * winMulti, "slot winnings!");
                                } else {
                                    gameResult = "You rolled " + slotMachine.getWinSlotTimes() + " **" + slotMachine.getWinSlot().getEmote() + "** and won **nothing**";
                                }
                            } else {
                                gameResult = Template.get("gamble_ai_lose");
                            }
                            message.editMessage(slotMachine.toString() + Config.EOL + gameResult).queue();
                            f[0].cancel(false);
                        } else {
                            message.editMessage(slotMachine.toString()).queue();
                        }
                    } catch (Exception e) {
                        bot.getContainer().reportError(e, "slotmachine", author.getId(), "channel", ((TextChannel) channel).getAsMention(), bot);
                        f[0].cancel(false);
                    }
                }, 1000L, SPIN_INTERVAL);
            });
        } else {
            String ret = "The slotmachine!" + Config.EOL;
            ret += "payout is as follows: " + Config.EOL;
            for (Slot s : Slot.values()) {
                ret += String.format("%1$s %1$s %1$s = %2$s" + Config.EOL, s.getEmote(), s.getTriplePayout());
            }
            ret += "type **slot play** to give it a shot!";
            return ret;
        }
        return "";
    }
}


text:
package me.leckie.demo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import me.leckie.demo.R;
import me.leckie.demo.bean.NewsBean;
import me.leckie.demo.util.ImageLoader;

/**
 * @author leckie
 * @date 6/23/15
 */
public class NewsAdapter extends BaseAdapter implements AbsListView.OnScrollListener {

    private ListView mListView;

    private ImageLoader mImageLoader;

    private List<NewsBean> mList;

    private LayoutInflater mInflater;

    private int mStart;

    private int mEnd;

    public static String[] URLS;

    private boolean mFirst = true;

    public NewsAdapter(Context context, List<NewsBean> data, ListView listView) {
        mListView = listView;
        mList = data;
        mInflater = LayoutInflater.from(context);
        mImageLoader = new ImageLoader(listView);
        URLS = new String[data.size()];
        for (int i = 0; i < data.size(); i++) {
            URLS[i] = data.get(i).getNewsIconUrl();
        }

        mFirst = true;
        listView.setOnScrollListener(this);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_simple_async, null);
            viewHolder.mIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
            viewHolder.mTitle = (TextView) convertView.findViewById(R.id.tv_title);
            viewHolder.mContent = (TextView) convertView.findViewById(R.id.tv_content);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.mIcon.setImageResource(R.mipmap.ic_launcher);
        String url = mList.get(position).getNewsIconUrl();
        viewHolder.mIcon.setTag(url);
        // async load image
        //mImageLoader.showImageByThread(viewHolder.mIcon, url);
        //mImageLoader.showImageByAsyncTask(viewHolder.mIcon, url);
        viewHolder.mTitle.setText(mList.get(position).getNewsTitle());
        viewHolder.mContent.setText(mList.get(position).getNewsContent());
        return convertView;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_IDLE) {
            // 加载可见项
            mImageLoader.loadImages(mStart, mEnd);

        } else {
            // 停止任务
            mImageLoader.cancelAllTasks();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        mStart = firstVisibleItem;
        mEnd = firstVisibleItem + visibleItemCount;
        // 首次加载
        if (mFirst && visibleItemCount > 0) {
            mImageLoader.loadImages(mStart, mEnd);
            mFirst = false;
        }
    }

    class ViewHolder {
        public TextView mTitle;
        public TextView mContent;
        public ImageView mIcon;
    }
}


text:
/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the "License").  You may not use this file except
 * in compliance with the License.
 *
 * You can obtain a copy of the license at
 * http://www.opensource.org/licenses/cddl1.php
 * See the License for the specific language governing
 * permissions and limitations under the License.
 */

/*
 * GET.java
 *
 * Created on October 24, 2007, 5:12 PM
 *
 */

package javax.ws.rs;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Indicates that the annotated method responds to HTTP GET requests
 * @see HttpMethod
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod(HttpMethod.GET)
public @interface GET {
}


text:
namespace hsql {

  enum ShowType {
    kShowColumns,
    kShowTables
  };

  // Represents SQL SHOW statements.
  // Example "SHOW TABLES;"
  struct ShowStatement : SQLStatement {

    ShowStatement(ShowType type);
    virtual ~ShowStatement();

    ShowType type;
    char* name;
  };

} // namespace hsql
#endif


text:
package de.hatoka.common.capi.exceptions;

public class EntityNotFoundException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    public EntityNotFoundException(String message)
    {
        super(message);
    }
}


text:
var smash = require("smash"),
    d3 = require("d3"),
    jsdom = require("jsdom");

module.exports = function() {
  var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }),
      expression = "mpld3",
      sandbox = {console: console, d3: d3};

  files.unshift("src/start");
  files.push("src/version");
  files.push("src/end");

  function topic() {
    var callback = this.callback;
    smash.load(files, expression, sandbox, function(error, result) {
      if (error) console.trace(error.stack);
      callback(error, result);
    });
  }

  topic.expression = function(_) {
    expression = _;
    return topic;
  };

  topic.sandbox = function(_) {
    sandbox = _;
    return topic;
  };

  topic.document = function(_) {
    var document = jsdom.jsdom("");

    sandbox = {
      d3 : d3,
      console: console,
      document: document,
      window: document.createWindow()
    };

    return topic;
  };

  return topic;
};

process.on("uncaughtException", function(e) {
  console.trace(e.stack);
});


text:
package org.apache.camel.component.hl7;

import java.io.InputStream;
import java.io.OutputStream;

import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.util.Terser;
import org.apache.camel.Exchange;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.IOHelper;

/**
 * HL7 DataFormat (supports v2.x of the HL7 protocol).
 *

 * This data format supports two operations:
 *

 *
marshal = from Message to String (can be used when returning as response using the HL7 MLLP codec)

 *
unmarshal = from String to Message (can be used when receiving streamed data from the HL7 MLLP codec).
 *   This operation will also enrich the message by adding the MSH fields (MSH-3 to MSH-12) as headers on the message.

 *

 *

 * Uses the HAPI (HL7 API) for HL7 parsing.
 *

 * Uses the default PipeParser from the HAPI API. This DataFormat only supports the EDI based HL7
 * messages and not the XML based (their are not commonly used).
 *

 * The <tt>unmarshal</tt> operation adds these MSH fields as headers on the Camel message (key, MSH-field):
 *

 *
hl7.msh.sendingApplication = MSH-3

 *
hl7.msh.sendingFacility = MSH-4

 *
hl7.msh.receivingApplication = MSH-5

 *
hl7.msh.receivingFacility = MSH-6

 *
hl7.msh.timestamp = MSH-7

 *
hl7.msh.security = MSH-8

 *
hl7.msh.messageType = MSH-9-1

 *
hl7.msh.triggerEvent = MSH-9-2

 *
hl7.msh.messageControl = MSH-10

 *
hl7.msh.processingId = MSH-11

 *
hl7.msh.versionId = MSH-12

 *

 * All headers are String types.
 *

 * The HL7 spec can be downloaded as a pdf at
 *
 * @see org.apache.camel.component.hl7.HL7MLLPCodec
 */
public class HL7DataFormat implements DataFormat {

    private boolean validate = true;

    public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
        Message message = ExchangeHelper.convertToMandatoryType(exchange, Message.class, body);
        String encoded = HL7Converter.encode(message, validate);
        String charsetName = IOHelper.getCharsetName(exchange);
        outputStream.write(encoded.getBytes(charsetName));
    }

    public Object unmarshal(Exchange exchange, InputStream inputStream) throws Exception {
        String body = ExchangeHelper.convertToMandatoryType(exchange, String.class, inputStream);
        Message message = HL7Converter.parse(body, validate);

        // add MSH fields as message out headers
        Terser terser = new Terser(message);
        exchange.getOut().setHeader(HL7Constants.HL7_SENDING_APPLICATION, terser.get("MSH-3"));
        exchange.getOut().setHeader(HL7Constants.HL7_SENDING_FACILITY, terser.get("MSH-4"));
        exchange.getOut().setHeader(HL7Constants.HL7_RECEIVING_APPLICATION, terser.get("MSH-5"));
        exchange.getOut().setHeader(HL7Constants.HL7_RECEIVING_FACILITY, terser.get("MSH-6"));
        exchange.getOut().setHeader(HL7Constants.HL7_TIMESTAMP, terser.get("MSH-7"));
        exchange.getOut().setHeader(HL7Constants.HL7_SECURITY, terser.get("MSH-8"));
        exchange.getOut().setHeader(HL7Constants.HL7_MESSAGE_TYPE, terser.get("MSH-9-1"));
        exchange.getOut().setHeader(HL7Constants.HL7_TRIGGER_EVENT, terser.get("MSH-9-2"));
        exchange.getOut().setHeader(HL7Constants.HL7_MESSAGE_CONTROL, terser.get("MSH-10"));
        exchange.getOut().setHeader(HL7Constants.HL7_PROCESSING_ID, terser.get("MSH-11"));
        exchange.getOut().setHeader(HL7Constants.HL7_VERSION_ID, terser.get("MSH-12"));
        return message;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }
}


text:
package org.apache.flink.api.scala.typeutils

import org.apache.flink.annotation.Internal
import org.apache.flink.api.common.typeutils._
import org.apache.flink.api.java.typeutils.runtime.EitherSerializerConfigSnapshot
import org.apache.flink.core.memory.{DataInputView, DataOutputView}

/**
 * Serializer for [[Either]].
 */
@Internal
@SerialVersionUID(9219995873023657525L)
class EitherSerializer[A, B](
    val leftSerializer: TypeSerializer[A],
    val rightSerializer: TypeSerializer[B])
  extends TypeSerializer[Either[A, B]] {

  override def duplicate: EitherSerializer[A,B] = {
    val leftDup = leftSerializer.duplicate()
    val rightDup = rightSerializer.duplicate()

    if (leftDup.eq(leftSerializer) && rightDup.eq(rightSerializer)) {
      this
    } else {
      new EitherSerializer[A, B](leftDup, rightDup)
    }
  }

  override def createInstance: Either[A, B] = {
    Left(null).asInstanceOf[Left[A, B]]
  }

  override def isImmutableType: Boolean = {
    (leftSerializer == null || leftSerializer.isImmutableType) &&
      (rightSerializer == null || rightSerializer.isImmutableType)
  }

  override def getLength: Int = -1

  override def copy(from: Either[A, B]): Either[A, B] = from match {
    case Left(a) => Left(leftSerializer.copy(a))
    case Right(b) => Right(rightSerializer.copy(b))
  }

  override def copy(from: Either[A, B], reuse: Either[A, B]): Either[A, B] = copy(from)

  override def copy(source: DataInputView, target: DataOutputView): Unit = {
    val isLeft = source.readBoolean()
    target.writeBoolean(isLeft)
    if (isLeft) {
      leftSerializer.copy(source, target)
    } else {
      rightSerializer.copy(source, target)
    }
  }

  override def serialize(either: Either[A, B], target: DataOutputView): Unit = either match {
    case Left(a) =>
      target.writeBoolean(true)
      leftSerializer.serialize(a, target)
    case Right(b) =>
      target.writeBoolean(false)
      rightSerializer.serialize(b, target)
  }

  override def deserialize(source: DataInputView): Either[A, B] = {
    val isLeft = source.readBoolean()
    if (isLeft) {
      Left(leftSerializer.deserialize(source))
    } else {
      Right(rightSerializer.deserialize(source))
    }
  }

  override def deserialize(reuse: Either[A, B], source: DataInputView): Either[A, B] = {
    val isLeft = source.readBoolean()
    if (isLeft) {
      Left(leftSerializer.deserialize(source))
    } else {
      Right(rightSerializer.deserialize(source))
    }
  }

  override def equals(obj: Any): Boolean = {
    obj match {
      case eitherSerializer: EitherSerializer[_, _] =>
        eitherSerializer.canEqual(this) &&
        leftSerializer.equals(eitherSerializer.leftSerializer) &&
        rightSerializer.equals(eitherSerializer.rightSerializer)
      case _ => false
    }
  }

  override def canEqual(obj: Any): Boolean = {
    obj.isInstanceOf[EitherSerializer[_, _]]
  }

  override def hashCode(): Int = {
    31 * leftSerializer.hashCode() + rightSerializer.hashCode()
  }

  def getLeftSerializer: TypeSerializer[A] = leftSerializer

  def getRightSerializer: TypeSerializer[B] = rightSerializer

  // --------------------------------------------------------------------------------------------
  // Serializer configuration snapshotting & compatibility
  // --------------------------------------------------------------------------------------------

  override def snapshotConfiguration(): ScalaEitherSerializerSnapshot[A, B] = {
    new ScalaEitherSerializerSnapshot[A, B](leftSerializer, rightSerializer)
  }

  override def ensureCompatibility(
      configSnapshot: TypeSerializerConfigSnapshot[_]): CompatibilityResult[Either[A, B]] = {

    configSnapshot match {
      // backwards compatibility path;
      // Flink versions older or equal to 1.5.x uses a
      // EitherSerializerConfigSnapshot as the snapshot
      case legacyConfig: EitherSerializerConfigSnapshot[A, B] =>
        checkCompatibility(legacyConfig)

      case _ => CompatibilityResult.requiresMigration()
    }
  }

  private def checkCompatibility(
      configSnapshot: CompositeTypeSerializerConfigSnapshot[_]
    ): CompatibilityResult[Either[A, B]] = {

    val previousLeftRightSerWithConfigs =
      configSnapshot.getNestedSerializersAndConfigs

    val leftCompatResult = CompatibilityUtil.resolveCompatibilityResult(
      previousLeftRightSerWithConfigs.get(0).f0,
      classOf[UnloadableDummyTypeSerializer[_]],
      previousLeftRightSerWithConfigs.get(0).f1,
      leftSerializer)

    val rightCompatResult = CompatibilityUtil.resolveCompatibilityResult(
      previousLeftRightSerWithConfigs.get(1).f0,
      classOf[UnloadableDummyTypeSerializer[_]],
      previousLeftRightSerWithConfigs.get(1).f1,
      rightSerializer)

    if (leftCompatResult.isRequiresMigration
      || rightCompatResult.isRequiresMigration) {
      CompatibilityResult.requiresMigration()
    } else {
      CompatibilityResult.compatible()
    }
  }
}


text:
"""Sensor for Xbox Live account status."""
import logging

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_API_KEY, STATE_UNKNOWN
from homeassistant.helpers.entity import Entity

_LOGGER = logging.getLogger(__name__)

CONF_XUID = "xuid"

ICON = "mdi:xbox"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_API_KEY): cv.string,
        vol.Required(CONF_XUID): vol.All(cv.ensure_list, [cv.string]),
    }
)

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Xbox platform."""
    from xboxapi import xbox_api

    api = xbox_api.XboxApi(config.get(CONF_API_KEY))
    devices = []

    # request personal profile to check api connection
    profile = api.get_profile()
    if profile.get("error_code") is not None:
        _LOGGER.error(
            "Can't setup XboxAPI connection. Check your account or "
            " api key on xboxapi.com. Code: %s Description: %s ",
            profile.get("error_code", STATE_UNKNOWN),
            profile.get("error_message", STATE_UNKNOWN),
        )
        return

    for xuid in config.get(CONF_XUID):
        new_device = XboxSensor(hass, api, xuid)
        if new_device.success_init:
            devices.append(new_device)

    if devices:
        add_entities(devices, True)

class XboxSensor(Entity):
    """A class for the Xbox account."""

    def __init__(self, hass, api, xuid):
        """Initialize the sensor."""
        self._hass = hass
        self._state = None
        self._presence = {}
        self._xuid = xuid
        self._api = api

        # get profile info
        profile = self._api.get_user_gamercard(self._xuid)

        if profile.get("success", True) and profile.get("code") is None:
            self.success_init = True
            self._gamertag = profile.get("gamertag")
            self._gamerscore = profile.get("gamerscore")
            self._picture = profile.get("gamerpicSmallSslImagePath")
            self._tier = profile.get("tier")
        else:
            _LOGGER.error(
                "Can't get user profile %s. " "Error Code: %s Description: %s",
                self._xuid,
                profile.get("code", STATE_UNKNOWN),
                profile.get("description", STATE_UNKNOWN),
            )
            self.success_init = False

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._gamertag

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        attributes = {}
        attributes["gamerscore"] = self._gamerscore
        attributes["tier"] = self._tier

        for device in self._presence:
            for title in device.get("titles"):
                attributes[
                    "{} {}".format(device.get("type"), title.get("placement"))
                ] = title.get("name")

        return attributes

    @property
    def entity_picture(self):
        """Avatar of the account."""
        return self._picture

    @property
    def icon(self):
        """Return the icon to use in the frontend."""
        return ICON

    def update(self):
        """Update state data from Xbox API."""
        presence = self._api.get_user_presence(self._xuid)
        self._state = presence.get("state")
        self._presence = presence.get("devices", {})


text:
[Mao](http://en.wikipedia.org/wiki/Mao_%28card_game%29) is a card game, usually played amongst teenagers, where the rules are dynamic. Usually only one player (known as the Grand Chairman) knows the rules and is entrusted to enforce them fairly and consistently. Because this is a demanding job, especially when they also act as a player in the game, in this adaption of the game the computer handles the rules. This way, all the players can participate as clueless players.

# For educational purposes only
I wrote this originally in high school, as a learning excercise to learn Python/OO. Today, I use it as a means to try out new languages. Implementing a basic, networked card game is enough to test the strengths and weaknesess of a language.

The test is contrived, but due to its size it's better than most conventional tests (which are usually < 1000 lines of code). This was implemented originally with roughly 1300 lines of Python (including the GUI!), so it's usually possible to get around that with other languages, ± a few hundred lines of code.

There is one big benifit to this particular project in testing languages: you can work from either side (client or server) and test it out against this reference implementation because it all talks through a Unix socket.

The only way the original implementation differs from the current is that it used Python as the scripting language for rules, not Lua. Lua is much easier to embed, so that is what I will use going forward.

## Rules
Unlike most adaptations of the card game, which hard-code the most widely known rules and call it a day, rules are constructed from functions in Python modules. Each function requires at least one parameter, `server`, which represents the entire Server object. Though passing the entire Server gives rules a lot of power, this is balanced by both the availability of the source code and the fact that these functions should be written by the Server owner only. If a player is to make a rule, it would have to be made safe so that he does not do anything malicious. This last part has not been implemented yet, as I have yet to find a safe way to do this.

For each rule that is activated, the code runs in a separate thread, so rules can wait on different events or even go in infinite loops (though you should really put in pauses or the server could become overloaded)

The `trigger` that activate the rule (which can be a phrase or a card) is determined when the rule is imported into the server. It is not part of the rule's code at all. If a trigger is not specified, the rule's code is executed each time the current player ends his turn, but before the next player's turn starts.

Here is an example:

```python
def no_special_order(server):
    server.player_handler.order = 1
```
If this rule has no trigger, then the order will always be one (So the only way for other rules to edit the order is to manually call `next_player`).

If the `trigger` is a card, then the rule activate when the card is **successfully** placed down by the current player. I.e: it is that player's turn and that card is now the top card on the pile. Because of this, when the rule's code activate, <u>it is no longer that player's turn</u>. It is now the next player's turn.

Here is an example:

```python
def reverse_order(server):
    server.player_handler.order = -server.player_handler.order
    server.player_handler.next_player()
    server.player_handler.next_player()
```
This rule flips the order around. This rule works differently, depending on whether the trigger is a card or a phrase. If it is a phrase, it reverses the order and then immediately skips the next player (according to the new order). If it is a card, then the order is reversed **after** it is the next player's turn, so the next two `next_player` calls make it appear that the order change happened before the player who played the trigger card's turn ended.

A rule's code can also have parameters other than `server`, but they *should* be optional (`*args, **kargs`). If they are not optional

## Server Setup and Configuration
To start a server, just run and interactive session on Server.py (`python -i Server.py`). One word of warning: make sure you call `shutdown()` **before** you exit the prompt, or you'll have to kill the process manually.

The 'options.cfg' file contains options to control server options, such as the default amount of cards that a player receives when they are punished.

The server actually reads this information at runtime, so it can be edited while the server is running, without having to restart it each time.


text:
package org.apache.olingo.commons.core.edm.primitivetype;

import java.math.BigInteger;

import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;

/**
 * Implementation of the EDM primitive type Int16.
 */
public final class EdmInt16 extends SingletonPrimitiveType {

  private static final EdmInt16 INSTANCE = new EdmInt16();

  public static EdmInt16 getInstance() {
    return INSTANCE;
  }

  @Override
  public boolean isCompatible(final EdmPrimitiveType primitiveType) {
    return primitiveType instanceof EdmByte
        || primitiveType instanceof EdmSByte
        || primitiveType instanceof EdmInt16;
  }

  @Override
  public Class<?> getDefaultType() {
    return Short.class;
  }

  @Override
  protected <T> T internalValueOfString(final String value,
      final Boolean isNullable, final Integer maxLength, final Integer precision,
      final Integer scale, final Boolean isUnicode, final Class<T> returnType) throws EdmPrimitiveTypeException {
    Short valueShort;
    try {
      valueShort = Short.parseShort(value);
    } catch (final NumberFormatException e) {
      throw new EdmPrimitiveTypeException("The literal '" + value + "' has illegal content.", e);
    }

    try {
      return EdmInt64.convertNumber(valueShort, returnType);
    } catch (final IllegalArgumentException e) {
      throw new EdmPrimitiveTypeException("The literal '" + value
          + "' cannot be converted to value type " + returnType + ".", e);
    } catch (final ClassCastException e) {
      throw new EdmPrimitiveTypeException("The value type " + returnType + " is not supported.", e);
    }
  }

  @Override
  protected <T> String internalValueToString(final T value,
      final Boolean isNullable, final Integer maxLength, final Integer precision,
      final Integer scale, final Boolean isUnicode) throws EdmPrimitiveTypeException {
    if (value instanceof Byte || value instanceof Short) {
      return value.toString();
    } else if (value instanceof Integer || value instanceof Long) {
      if (((Number) value).longValue() >= Short.MIN_VALUE
          && ((Number) value).longValue() <= Short.MAX_VALUE) {
        return value.toString();
      } else {
        throw new EdmPrimitiveTypeException("The value '" + value + "' is not valid.");
      }
    } else if (value instanceof BigInteger) {
      if (((BigInteger) value).bitLength() < Short.SIZE) {
        return value.toString();
      } else {
        throw new EdmPrimitiveTypeException("The value '" + value + "' is not valid.");
      }
    } else {
      throw new EdmPrimitiveTypeException("The value type " + value.getClass() + " is not supported.");
    }
  }
}


text:
package gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import gov.nih.nci.ncicb.cadsr.common.dto.DesignationTransferObject;
import gov.nih.nci.ncicb.cadsr.common.dto.ReferenceDocumentTransferObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})
public class JDBCAdminComponentDAOV2Test {

	@Autowired
	JDBCFormDAOV2 adminComponentV2Dao;

	@Test
	public void testGetAllReferenceDocumentsIntFloat() {
		List<ReferenceDocumentTransferObject> refdocs =
				adminComponentV2Dao.getAllReferenceDocumentsForDE(64788, (float)2.31);

		assertNotNull(refdocs);
		assertTrue(refdocs.size() == 2);
		assertTrue(refdocs.get(0).getDocName().equalsIgnoreCase("CRF Text"));
		assertTrue(refdocs.get(0).getDocType().equalsIgnoreCase("Alternate Question Text")
				|| refdocs.get(0).getDocType().equalsIgnoreCase("Preferred Question Text"));

	}

	@Test
	public void testGetAllReferenceDocumentsByPublicIds() {
		List<String> publicIds = new ArrayList<String>();

		publicIds.add("2002460");
		publicIds.add("782"); //ver: 4.1
		publicIds.add("2001039");
		publicIds.add("2002713");
		publicIds.add("470"); //fake

		HashMap<String, List<ReferenceDocumentTransferObject>> des =
				adminComponentV2Dao.getReferenceDocumentsByCdePublicIds(publicIds);

		assertNotNull(des);
		assertTrue(des.size() >= 4);
		assertTrue(des.get("782-4.1") != null);

	}

	@Test
	public void testGetAllContextSeqIds() {

		HashMap<String, String> map = adminComponentV2Dao.getAllContextSeqIds();
		assertNotNull(map);

		Iterator<String> ite = map.keySet().iterator();
		while (ite.hasNext()) {
			String key = (String)ite.next();
			System.out.println("Context name: " + key + " seqid: " + map.get(key));
		}
	}

	@Test
	public void testGetDesignationsForForm() {
		//select * from sbr.designations_view
		//where detl_name='C3D Name' and lae_name='ENGLISH' and ac_idseq='C8B96C2F-397E-607A-E034-0003BA12F5E7'
		//		and name='VITALS_POSITION'

		List<DesignationTransferObject> desigs = adminComponentV2Dao.getDesignationsForForm(
				"C8B96C2F-397E-607A-E034-0003BA12F5E7",  //this is cde ac_seqid not form's
				"VITALS_POSITION", "C3D Name", "ENGLISH");

		assertNotNull(desigs);
		assertTrue(desigs.size() > 0);
	}

	@Test
	public void testGetAllDesignationTypes() {
		List<String> alltypes = adminComponentV2Dao.getAllDesignationTypes();
		assertTrue(alltypes.size() > 10 && alltypes.size() < 200);

	}

	@Test
	public void testGetAllRefdocTypes() {
		List<String> alltypes = adminComponentV2Dao.getAllRefdocTypes();
		assertTrue(alltypes.size() > 10 && alltypes.size() < 100);

	}

	@Test
	public void testGetAllDefinitionTypes() {
		List<String> alltypes = adminComponentV2Dao.getAllDefinitionTypes();
		assertTrue(alltypes.size() > 10 && alltypes.size() < 100);

	}

	@Test
	public void testGetAllWorkflowStatusName() {
		List<String> alltypes = adminComponentV2Dao.getAllWorkflowNames();
		assertTrue(alltypes.size() > 10 && alltypes.size() < 100);

	}

	@Test
	public void testUpdateWorkflowStatus() {
		String formseqid = "E9FA3574-4D30-3253-E040-BB8921B6498C";
		String wfName = "RETIRED DELETED";

		int res = adminComponentV2Dao.updateWorkflowStatus(formseqid, wfName, "FORMLOADER", "Unit testing update workflow");

		//Due to db refresh, the particular form record no longer exists in db.
		assertTrue(res == 0);
	}
}


text:
package seev

import (
	"encoding/xml"

	"github.com/fgrid/iso20022"
)

type Document03600101 struct {
	XMLName xml.Name                                `xml:"urn:iso:std:iso:20022:tech:xsd:seev.036.001.01 Document"`
	Message *CorporateActionMovementConfirmationV01 `xml:"CorpActnMvmntConf"`
}

func (d *Document03600101) AddMessage() *CorporateActionMovementConfirmationV01 {
	d.Message = new(CorporateActionMovementConfirmationV01)
	return d.Message
}

// Scope
// An account servicer sends the CorporateActionMovementConfirmation message to an account owner or its designated agent to confirm posting of securities or cash as a result of a corporate action event.
// Usage
// The message may also be used to:
// - re-send a message previously sent (the sub-function of the message is Duplicate),
// - provide a third party with a copy of a message for information (the sub-function of the message is Copy),
// - re-send to a third party a copy of a message for information (the sub-function of the message is Copy Duplicate).
// ISO 15022 - 20022 COEXISTENCE
// This ISO 20022 message is reversed engineered from ISO 15022. Both standards will coexist for a certain number of years. Until this coexistence period ends, the usage of certain data types is restricted to ensure interoperability between ISO 15022 and 20022 users. Compliance to these rules is mandatory in a coexistence environment.  The coexistence restrictions are described in a Textual Rule linked to the Message Items they concern. These coexistence textual rules are clearly identified as follows:  "CoexistenceXxxxRule".
type CorporateActionMovementConfirmationV01 struct {

	// Information that unambiguously identifies a CorporateActionMovementConfirmation message as know by the account servicer.
	Identification *iso20022.DocumentIdentification11 `xml:"Id"`

	// Identification of a previously sent notification document.
	NotificationIdentification *iso20022.DocumentIdentification15 `xml:"NtfctnId,omitempty"`

	// Identification of a previously sent movement preliminary advice document.
	MovementPreliminaryAdviceIdentification *iso20022.DocumentIdentification15 `xml:"MvmntPrlimryAdvcId,omitempty"`

	// Identification of a related instruction document.
	InstructionIdentification *iso20022.DocumentIdentification9 `xml:"InstrId,omitempty"`

	// Identification of other documents as well as the document number.
	OtherDocumentIdentification []*iso20022.DocumentIdentification13 `xml:"OthrDocId,omitempty"`

	// Identification of an other corporate action event that needs to be closely  linked to the processing of the event notified in this document.
	EventsLinkage []*iso20022.CorporateActionEventReference1 `xml:"EvtsLkg,omitempty"`

	// General information about the corporate action event.
	CorporateActionGeneralInformation *iso20022.CorporateActionGeneralInformation4 `xml:"CorpActnGnlInf"`

	// General information about the safekeeping account, owner and account balance.
	AccountDetails *iso20022.AccountAndBalance3 `xml:"AcctDtls"`

	// Information about the corporate action option.
	CorporateActionConfirmationDetails *iso20022.CorporateActionOption4 `xml:"CorpActnConfDtls"`

	// Provides additional information.
	AdditionalInformation *iso20022.CorporateActionNarrative4 `xml:"AddtlInf,omitempty"`

	// Party that originated the message, if other than the sender.
	MessageOriginator *iso20022.PartyIdentification10Choice `xml:"MsgOrgtr,omitempty"`

	// Party that is the final destination of the message, if other than the receiver.
	MessageRecipient *iso20022.PartyIdentification10Choice `xml:"MsgRcpt,omitempty"`

	// Party appointed to administer the event on behalf of the issuer company/offeror. The party may be contacted for more information about the event.
	IssuerAgent []*iso20022.PartyIdentification10Choice `xml:"IssrAgt,omitempty"`

	// Agent (principal or fiscal paying agent) appointed to execute the payment for the corporate action event on behalf of the issuer company/offeror.
	PayingAgent []*iso20022.PartyIdentification10Choice `xml:"PngAgt,omitempty"`

	// Sub-agent appointed to execute the payment for the corporate action event on behalf of the issuer company/offeror.
	SubPayingAgent []*iso20022.PartyIdentification10Choice `xml:"SubPngAgt,omitempty"`

	// Additional information that can not be captured in the structured fields and/or any other specific block.
	Extension []*iso20022.Extension2 `xml:"Xtnsn,omitempty"`
}

func (c *CorporateActionMovementConfirmationV01) AddIdentification() *iso20022.DocumentIdentification11 {
	c.Identification = new(iso20022.DocumentIdentification11)
	return c.Identification
}

func (c *CorporateActionMovementConfirmationV01) AddNotificationIdentification() *iso20022.DocumentIdentification15 {
	c.NotificationIdentification = new(iso20022.DocumentIdentification15)
	return c.NotificationIdentification
}

func (c *CorporateActionMovementConfirmationV01) AddMovementPreliminaryAdviceIdentification() *iso20022.DocumentIdentification15 {
	c.MovementPreliminaryAdviceIdentification = new(iso20022.DocumentIdentification15)
	return c.MovementPreliminaryAdviceIdentification
}

func (c *CorporateActionMovementConfirmationV01) AddInstructionIdentification() *iso20022.DocumentIdentification9 {
	c.InstructionIdentification = new(iso20022.DocumentIdentification9)
	return c.InstructionIdentification
}

func (c *CorporateActionMovementConfirmationV01) AddOtherDocumentIdentification() *iso20022.DocumentIdentification13 {
	newValue := new(iso20022.DocumentIdentification13)
	c.OtherDocumentIdentification = append(c.OtherDocumentIdentification, newValue)
	return newValue
}

func (c *CorporateActionMovementConfirmationV01) AddEventsLinkage() *iso20022.CorporateActionEventReference1 {
	newValue := new(iso20022.CorporateActionEventReference1)
	c.EventsLinkage = append(c.EventsLinkage, newValue)
	return newValue
}

func (c *CorporateActionMovementConfirmationV01) AddCorporateActionGeneralInformation() *iso20022.CorporateActionGeneralInformation4 {
	c.CorporateActionGeneralInformation = new(iso20022.CorporateActionGeneralInformation4)
	return c.CorporateActionGeneralInformation
}

func (c *CorporateActionMovementConfirmationV01) AddAccountDetails() *iso20022.AccountAndBalance3 {
	c.AccountDetails = new(iso20022.AccountAndBalance3)
	return c.AccountDetails
}

func (c *CorporateActionMovementConfirmationV01) AddCorporateActionConfirmationDetails() *iso20022.CorporateActionOption4 {
	c.CorporateActionConfirmationDetails = new(iso20022.CorporateActionOption4)
	return c.CorporateActionConfirmationDetails
}

func (c *CorporateActionMovementConfirmationV01) AddAdditionalInformation() *iso20022.CorporateActionNarrative4 {
	c.AdditionalInformation = new(iso20022.CorporateActionNarrative4)
	return c.AdditionalInformation
}

func (c *CorporateActionMovementConfirmationV01) AddMessageOriginator() *iso20022.PartyIdentification10Choice {
	c.MessageOriginator = new(iso20022.PartyIdentification10Choice)
	return c.MessageOriginator
}

func (c *CorporateActionMovementConfirmationV01) AddMessageRecipient() *iso20022.PartyIdentification10Choice {
	c.MessageRecipient = new(iso20022.PartyIdentification10Choice)
	return c.MessageRecipient
}

func (c *CorporateActionMovementConfirmationV01) AddIssuerAgent() *iso20022.PartyIdentification10Choice {
	newValue := new(iso20022.PartyIdentification10Choice)
	c.IssuerAgent = append(c.IssuerAgent, newValue)
	return newValue
}

func (c *CorporateActionMovementConfirmationV01) AddPayingAgent() *iso20022.PartyIdentification10Choice {
	newValue := new(iso20022.PartyIdentification10Choice)
	c.PayingAgent = append(c.PayingAgent, newValue)
	return newValue
}

func (c *CorporateActionMovementConfirmationV01) AddSubPayingAgent() *iso20022.PartyIdentification10Choice {
	newValue := new(iso20022.PartyIdentification10Choice)
	c.SubPayingAgent = append(c.SubPayingAgent, newValue)
	return newValue
}

func (c *CorporateActionMovementConfirmationV01) AddExtension() *iso20022.Extension2 {
	newValue := new(iso20022.Extension2)
	c.Extension = append(c.Extension, newValue)
	return newValue
}


text:
"""Arguments for UISRNN."""

import argparse

_DEFAULT_OBSERVATION_DIM = 256

def str2bool(value):
  """A function to convert string to bool value."""
  if value.lower() in {'yes', 'true', 't', 'y', '1'}:
    return True
  if value.lower() in {'no', 'false', 'f', 'n', '0'}:
    return False
  raise argparse.ArgumentTypeError('Boolean value expected.')

def parse_arguments():
  """Parse arguments.

  Returns:
    A tuple of:

      - `model_args`: model arguments
      - `training_args`: training arguments
      - `inference_args`: inference arguments
  """
  # model configurations
  model_parser = argparse.ArgumentParser(
      description='Model configurations.', add_help=False)

  model_parser.add_argument(
      '--observation_dim',
      default=_DEFAULT_OBSERVATION_DIM,
      type=int,
      help='The dimension of the embeddings (e.g. d-vectors).')

  model_parser.add_argument(
      '--rnn_hidden_size',
      default=512,
      type=int,
      help='The number of nodes for each RNN layer.')
  model_parser.add_argument(
      '--rnn_depth',
      default=1,
      type=int,
      help='The number of RNN layers.')
  model_parser.add_argument(
      '--rnn_dropout',
      default=0.2,
      type=float,
      help='The dropout rate for all RNN layers.')
  model_parser.add_argument(
      '--transition_bias',
      default=None,
      type=float,
      help='The value of p0, corresponding to Eq. (6) in the '
           'paper. If the value is given, we will fix to this value. If the '
           'value is None, we will estimate it from training data '
           'using Eq. (13) in the paper.')
  model_parser.add_argument(
      '--crp_alpha',
      default=1.0,
      type=float,
      help='The value of alpha for the Chinese restaurant process (CRP), '
           'corresponding to Eq. (7) in the paper. In this open source '
           'implementation, currently we only support using a given value '
           'of crp_alpha.')
  model_parser.add_argument(
      '--sigma2',
      default=None,
      type=float,
      help='The value of sigma squared, corresponding to Eq. (11) in the '
           'paper. If the value is given, we will fix to this value. If the '
           'value is None, we will estimate it from training data.')
  model_parser.add_argument(
      '--verbosity',
      default=2,
      type=int,
      help='How verbose will the logging information be. Higher value '
      'represents more verbose information. A general guideline: '
      '0 for errors; 1 for finishing important steps; '
      '2 for finishing less important steps; 3 or above for debugging '
      'information.')
  model_parser.add_argument(
      '--enable_cuda',
      default=True,
      type=str2bool,
      help='Whether we should use CUDA if it is avaiable. If False, we will '
      'always use CPU.')

  # training configurations
  training_parser = argparse.ArgumentParser(
      description='Training configurations.', add_help=False)

  training_parser.add_argument(
      '--optimizer',
      '-o',
      default='adam',
      choices=['adam'],
      help='The optimizer for training.')
  training_parser.add_argument(
      '--learning_rate',
      '-l',
      default=1e-3,
      type=float,
      help='The leaning rate for training.')
  training_parser.add_argument(
      '--train_iteration',
      '-t',
      default=20000,
      type=int,
      help='The total number of training iterations.')
  training_parser.add_argument(
      '--batch_size',
      '-b',
      default=10,
      type=int,
      help='The batch size for training.')
  training_parser.add_argument(
      '--num_permutations',
      default=10,
      type=int,
      help='The number of permutations per utterance sampled in the training '
           'data.')
  training_parser.add_argument(
      '--sigma_alpha',
      default=1.0,
      type=float,
      help='The inverse gamma shape for estimating sigma2. This value is only '
           'meaningful when sigma2 is not given, and estimated from data.')
  training_parser.add_argument(
      '--sigma_beta',
      default=1.0,
      type=float,
      help='The inverse gamma scale for estimating sigma2. This value is only '
           'meaningful when sigma2 is not given, and estimated from data.')
  training_parser.add_argument(
      '--regularization_weight',
      '-r',
      default=1e-5,
      type=float,
      help='The network regularization multiplicative.')
  training_parser.add_argument(
      '--grad_max_norm',
      default=5.0,
      type=float,
      help='Max norm of the gradient.')
  training_parser.add_argument(
      '--enforce_cluster_id_uniqueness',
      default=True,
      type=str2bool,
      help='Whether to enforce cluster ID uniqueness across different '
           'training sequences. Only effective when the first input to fit() '
           'is a list of sequences. In general, assume the cluster IDs for two '
           'sequences are [a, b] and [a, c]. If the `a` from the two sequences '
           'are not the same label, then this arg should be True.')

  # inference configurations
  inference_parser = argparse.ArgumentParser(
      description='Inference configurations.', add_help=False)

  inference_parser.add_argument(
      '--beam_size',
      '-s',
      default=10,
      type=int,
      help='The beam search size for inference.')
  inference_parser.add_argument(
      '--look_ahead',
      default=1,
      type=int,
      help='The number of look ahead steps during inference.')
  inference_parser.add_argument(
      '--test_iteration',
      default=2,
      type=int,
      help='During inference, we concatenate M duplicates of the test '
           'sequence, and run inference on this concatenated sequence. '
           'Then we return the inference results on the last duplicate as the '
           'final prediction for the test sequence.')

  # a super parser for sanity checks
  super_parser = argparse.ArgumentParser(
      parents=[model_parser, training_parser, inference_parser])

  # get arguments
  super_parser.parse_args()
  model_args, _ = model_parser.parse_known_args()
  training_args, _ = training_parser.parse_known_args()
  inference_args, _ = inference_parser.parse_known_args()

  return (model_args, training_args, inference_args)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/User_Register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/login_margin_e"
        android:background="@null"
        android:drawableLeft="@drawable/login_icon"
        android:drawablePadding="@dimen/login_drawablePadding_e"
        android:gravity="center_vertical"
        android:hint="@string/user_hint"
        android:maxLength="20"
        android:singleLine="true"
        android:textColorHint="#ccc" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginLeft="@dimen/login_marginLeft_v"
        android:layout_marginRight="@dimen/login_marginRight_v"
        android:background="#e1e1e1" />

    <EditText
        android:id="@+id/Password_Register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/login_margin_e"
        android:background="@null"
        android:drawableLeft="@drawable/login_pass"
        android:drawablePadding="@dimen/login_drawablePadding_e"
        android:gravity="center_vertical"
        android:hint="@string/password"
        android:inputType="textPassword"
        android:maxLength="20"
        android:singleLine="true"
        android:textColorHint="#ccc" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginLeft="@dimen/login_marginLeft_v"
        android:layout_marginRight="@dimen/login_marginRight_v"
        android:background="#e1e1e1" />

    <EditText
        android:id="@+id/Password_Repet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/login_margin_e"
        android:background="@null"
        android:drawableLeft="@drawable/login_pass"
        android:drawablePadding="@dimen/login_drawablePadding_e"
        android:gravity="center_vertical"
        android:hint="@string/password_repet"
        android:inputType="textPassword"
        android:maxLength="20"
        android:singleLine="true"
        android:textColorHint="#ccc" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginLeft="@dimen/login_marginLeft_v"
        android:layout_marginRight="@dimen/login_marginRight_v"
        android:background="#e1e1e1" />

     <Button
        android:id="@+id/Register_Me"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/login_margin_e"
        android:background="@drawable/login_btn_bg"
        android:gravity="center"
        android:enabled="false"
        android:padding="@dimen/login_Padding_b"
        android:text="@string/register"
        android:textColor="#ccc" />

</LinearLayout>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
CombinedIterable (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.xdgf.usermodel.section

Class CombinedIterable<T>

java.lang.Object
  org.apache.poi.xdgf.usermodel.section.CombinedIterable<T>

Type Parameters:
T -

All Implemented Interfaces:
java.lang.Iterable<T>

public class CombinedIterable<T>
extends java.lang.Object
implements java.lang.Iterable<T>

An iterator used to iterate over the base and master items

Constructor Summary

CombinedIterable(java.util.SortedMap<java.lang.Long,T> baseItems,
                 java.util.SortedMap<java.lang.Long,T> masterItems)

Method Summary

 java.util.Iterator<T>
iterator()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CombinedIterable

public CombinedIterable(java.util.SortedMap<java.lang.Long,T> baseItems,
                        java.util.SortedMap<java.lang.Long,T> masterItems)

Method Detail

iterator

public java.util.Iterator<T> iterator()

Specified by:
iterator in interface java.lang.Iterable<T>

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
#set($dollar = '$')
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>${groupId}</groupId>
	<artifactId>${artifactId}</artifactId>
	<packaging>war</packaging>
	<version>${version}</version>
	<!-- TODO project name  -->
	<name>${artifactId}</name>
	<description></description>
	<!--
		<organization>
			<name>company name</name>
			<url>company url</url>
		</organization>
	-->
	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>
	<properties>
		<orienteer.version>${orienteerVersion}</orienteer.version>
		<wicket.orientdb.version>${wicketOrientDBVersion}</wicket.orientdb.version>
		<jetty.version>7.6.13.v20130916</jetty.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- allowed values: R7, 1.0, 1.5, 2.0 or none -->
		<wtp.version>none</wtp.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.orienteer</groupId>
			<artifactId>orienteer-core</artifactId>
			<version>${dollar}{orienteer.version}</version>
		</dependency>
		<!-- ORIENTEER TESTS for TESTING -->
		<dependency>
			<groupId>org.orienteer</groupId>
			<artifactId>orienteer-core</artifactId>
			<version>${dollar}{orienteer.version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>ru.ydn.wicket.wicket-orientdb</groupId>
			<artifactId>wicket-orientdb</artifactId>
			<version>${dollar}{wicket.orientdb.version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<!--  JUNIT DEPENDENCY FOR TESTING -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

		<!--  JETTY DEPENDENCIES FOR TESTING  -->
		<dependency>
			<groupId>org.eclipse.jetty.aggregate</groupId>
			<artifactId>jetty-all-server</artifactId>
			<version>${jetty.version}</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<resources>
			<resource>
				<filtering>false</filtering>
				<directory>src/main/resources</directory>
			</resource>
			<resource>
				<filtering>false</filtering>
				<directory>src/main/java</directory>
				<includes>
					<include>**</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<filtering>false</filtering>
				<directory>src/test/resources</directory>
			</testResource>
			<testResource>
				<filtering>false</filtering>
				<directory>src/test/java</directory>
				<includes>
					<include>**</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</testResource>
		</testResources>
		<plugins>
			<plugin>
			      <groupId>org.apache.felix</groupId>
			      <artifactId>maven-bundle-plugin</artifactId>
			      <version>2.3.6</version>
			      <extensions>true</extensions>
			</plugin>
			<plugin>
			    <groupId>org.apache.maven.plugins</groupId>
			    <artifactId>maven-war-plugin</artifactId>
			    <version>2.4</version>
			</plugin>
			<plugin>
				<inherited>true</inherited>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>UTF-8</encoding>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>${dollar}{jetty.version}</version>
				<configuration>
					<connectors>
						<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
							<port>8080</port>
							<maxIdleTime>3600000</maxIdleTime>
						</connector>
						<connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
							<port>8443</port>
							<maxIdleTime>3600000</maxIdleTime>
							<keystore>${dollar}{project.build.directory}/test-classes/keystore</keystore>
							<password>wicket</password>
							<keyPassword>wicket</keyPassword>
						</connector>
					</connectors>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<wtpversion>${dollar}{wtp.version}</wtpversion>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>Apache Nexus</id>
			<url>https://repository.apache.org/content/repositories/snapshots/</url>
			<releases>
				<enabled>false</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
	</repositories>
	</project>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>I-log by donateoa</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">

I-log

share logger between nodejs modules

      View on GitHub
      Download .zip
      Download .tar.gz

i-log

Share logger between nodejs modules.
Use a dedicate key for each module and filter the module you want is writing.

Install

$ npm install --save i-log

Configuration

setting DEBUG variable when run your modules

# print all keys
DEBUG=i_log:* npm start

# print info keys
DEBUG=i_log:info npm start

Usage

var i_log = require('i_log')("your_module")
i_log.info("test info")
i_log.debug("test debug")
i_log.error("test error")

Output

your_module:info Wed Oct 19 2016 16:53:03 GMT+0200 (CEST) test info +0ms
your_module:debug Wed Oct 19 2016 16:53:03 GMT+0200 (CEST) test debug +117ms
your_module:error Wed Oct 19 2016 16:53:03 GMT+0200 (CEST) test error +117ms

        I-log is maintained by donateoa.

        This page was generated by GitHub Pages using the Cayman theme by Jason Long.


text:
#ifndef CTRL_CHESS_TXT_H
#define CTRL_CHESS_TXT_H
#include <vector>
#include "wx/wx.h"
#include "wx/richtext/richtextctrl.h"
#include "GameDocument.h"
#include "GameView.h"
#include "NavigationKey.h"

class GameLogic;
class CtrlChessTxt : public wxRichTextCtrl
{
public:
    GameLogic *gl;
    CtrlChessTxt( wxWindow* parent,
                  wxWindowID id = wxID_ANY,
                  const wxPoint& point = wxDefaultPosition,
                  const wxSize& size = wxDefaultSize );
    ~CtrlChessTxt() { if( context_menu ) {delete context_menu; context_menu=0; } }

public:
    void SetGameDocument( GameDocument *gd );
    void Goto( unsigned long pos, bool from_mouse_move=false );
    void NavigationKey( NAVIGATION_KEY nk );
    void Copy();
    void Paste();
    void Cut();
    void Delete();
    void SetFontSize();

private:
    void OnProcessCustom(wxCommandEvent& event);
    void OnMouseMove( wxMouseEvent& event );
    void OnMouseLeftUp( wxMouseEvent &event );
    void OnMouseLeftDown( wxMouseEvent &event );
    void OnContext( wxContextMenuEvent &event );
    void OnEraseBackground(wxEraseEvent& WXUNUSED(evt));
    void OnSize(wxSizeEvent& WXUNUSED(evt));
    void OnUndo(wxCommandEvent& WXUNUSED(event));
    void OnUpdateUndo( wxUpdateUIEvent &event );
    void OnRedo(wxCommandEvent& WXUNUSED(event));
    void OnUpdateRedo( wxUpdateUIEvent &event );

    // 13 event handlers
    void OnKeyDown(wxKeyEvent& event);
    void OnKeyUp(wxKeyEvent& event);
    void OnChar(wxKeyEvent& event);
    void OnText(wxCommandEvent& event);
    void OnTextEnter(wxCommandEvent& event);
    void OnTextURL(wxTextUrlEvent& event);
    void OnTextMaxLen(wxCommandEvent& event);
    void OnTextCut(wxClipboardTextEvent & event);
    void OnTextCopy(wxClipboardTextEvent & event);
    void OnTextPaste(wxClipboardTextEvent & event);
    void OnMouseEvent(wxMouseEvent& event);
    void OnMouseWheel(wxMouseEvent& event);
    void OnSetFocus(wxFocusEvent& event);
    void OnKillFocus(wxFocusEvent& event);

    void OnAnnotNag1( int nag1 );
    void OnAnnotNag2( int nag2 );
    void OnAnnot1(wxCommandEvent& event);
    void OnAnnot2(wxCommandEvent& event);
    void OnAnnot3(wxCommandEvent& event);
    void OnAnnot4(wxCommandEvent& event);
    void OnAnnot5(wxCommandEvent& event);
    void OnAnnot6(wxCommandEvent& event);
    void OnAnnot7(wxCommandEvent& event);
    void OnAnnot10(wxCommandEvent& event);
    void OnAnnot14(wxCommandEvent& event);
    void OnAnnot15(wxCommandEvent& event);
    void OnAnnot16(wxCommandEvent& event);
    void OnAnnot17(wxCommandEvent& event);
    void OnAnnot18(wxCommandEvent& event);
    void OnAnnot19(wxCommandEvent& event);
    void OnAnnot20(wxCommandEvent& event);

    int max_w, max_h, height;
private:
    wxFont font;
    wxMenu *context_menu;
    MoveTree *popup_mt;
    GameDocument *gd;
    GameView *gv;
    DECLARE_EVENT_TABLE()
};

#endif // CTRL_CHESS_TXT_H


text:
_.mixin(_.str.exports());
angular.module('fooApp', ['ui.bootstrap'])
  .controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {

    $scope.count = 0;
    $scope.cssBig = '';
    $scope.size = 0;
    $scope.targetIn = '';
    $scope.targetOut = '';
    $scope.inputSize = 0;
    $scope.outSize = 0;

    var socket = new WebSocket('ws://ws.blockchain.info/inv');
    socket.onopen = function() {
      console.log('Connected!');
      // Unconfirmed transactions
      socket.send('{"op":"unconfirmed_sub"}');
    };
    socket.onmessage = function(event) {
      data = JSON.parse(event.data);
      // console.log(data);
      //$scope.size = data.x.size;
      //console.log($scope.size);
      $scope.$apply(function() {
        var sum_input = _.reduce(data.x.inputs, function(memo, v) {
          return memo + v.prev_out.value;
        }, 0);
        var sum_out = _.reduce(data.x.out, function(memo, v) {
          return memo + v.value;
        }, 0);
        $scope.size = data.x.size;
        $scope.inputSize = data.x.inputs.length;
        $scope.outSize = data.x.out.length;
        var vIn = sum_input/100000000;
        var vOut = sum_out/100000000;
        $scope.targetIn = _.sprintf("%.8f",vIn);
        $scope.targetOut = _.sprintf("%.8f",vOut);
        if(vIn>=1){
            $scope.cssBig = 'bounce';
            $scope.count++;
            $timeout(function(){
                $scope.cssBig = '';
            },1500);
        }
      });
    };
    socket.onclose = function() {
      console.log('Lost connection!');
    };

  }]);


text:
package auth

import (
	"errors"
	"net/http"
	"strings"
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apiserver/pkg/authentication/authenticator"
	"k8s.io/apiserver/pkg/authentication/user"
	"k8s.io/apiserver/pkg/authorization/authorizer"
	restclient "k8s.io/client-go/rest"
	"k8s.io/kubernetes/pkg/api"
	authorizationapi "k8s.io/kubernetes/pkg/apis/authorization"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/plugin/pkg/admission/admit"
	"k8s.io/kubernetes/test/integration/framework"
)

// Inject into master an authorizer that uses user info.
// TODO(etune): remove this test once a more comprehensive built-in authorizer is implemented.
type sarAuthorizer struct{}

func (sarAuthorizer) Authorize(a authorizer.Attributes) (bool, string, error) {
	if a.GetUser().GetName() == "dave" {
		return false, "no", errors.New("I'm sorry, Dave")
	}

	return true, "you're not dave", nil
}

func alwaysAlice(req *http.Request) (user.Info, bool, error) {
	return &user.DefaultInfo{
		Name: "alice",
	}, true, nil
}

func TestSubjectAccessReview(t *testing.T) {
	masterConfig := framework.NewIntegrationTestMasterConfig()
	masterConfig.GenericConfig.Authenticator = authenticator.RequestFunc(alwaysAlice)
	masterConfig.GenericConfig.Authorizer = sarAuthorizer{}
	masterConfig.GenericConfig.AdmissionControl = admit.NewAlwaysAdmit()
	_, s, closeFn := framework.RunAMaster(masterConfig)
	defer closeFn()

	clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &api.Registry.GroupOrDie(api.GroupName).GroupVersion}})

	tests := []struct {
		name           string
		sar            *authorizationapi.SubjectAccessReview
		expectedError  string
		expectedStatus authorizationapi.SubjectAccessReviewStatus
	}{
		{
			name: "simple allow",
			sar: &authorizationapi.SubjectAccessReview{
				Spec: authorizationapi.SubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:     "list",
						Group:    api.GroupName,
						Version:  "v1",
						Resource: "pods",
					},
					User: "alice",
				},
			},
			expectedStatus: authorizationapi.SubjectAccessReviewStatus{
				Allowed: true,
				Reason:  "you're not dave",
			},
		},
		{
			name: "simple deny",
			sar: &authorizationapi.SubjectAccessReview{
				Spec: authorizationapi.SubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:     "list",
						Group:    api.GroupName,
						Version:  "v1",
						Resource: "pods",
					},
					User: "dave",
				},
			},
			expectedStatus: authorizationapi.SubjectAccessReviewStatus{
				Allowed:         false,
				Reason:          "no",
				EvaluationError: "I'm sorry, Dave",
			},
		},
		{
			name: "simple error",
			sar: &authorizationapi.SubjectAccessReview{
				Spec: authorizationapi.SubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:     "list",
						Group:    api.GroupName,
						Version:  "v1",
						Resource: "pods",
					},
				},
			},
			expectedError: "at least one of user or group must be specified",
		},
	}

	for _, test := range tests {
		response, err := clientset.Authorization().SubjectAccessReviews().Create(test.sar)
		switch {
		case err == nil && len(test.expectedError) == 0:

		case err != nil && strings.Contains(err.Error(), test.expectedError):
			continue

		case err != nil && len(test.expectedError) != 0:
			t.Errorf("%s: unexpected error: %v", test.name, err)
			continue
		default:
			t.Errorf("%s: expected %v, got %v", test.name, test.expectedError, err)
			continue
		}
		if response.Status != test.expectedStatus {
			t.Errorf("%s: expected %v, got %v", test.name, test.expectedStatus, response.Status)
			continue
		}
	}
}

func TestSelfSubjectAccessReview(t *testing.T) {
	username := "alice"
	masterConfig := framework.NewIntegrationTestMasterConfig()
	masterConfig.GenericConfig.Authenticator = authenticator.RequestFunc(func(req *http.Request) (user.Info, bool, error) {
		return &user.DefaultInfo{Name: username}, true, nil
	})
	masterConfig.GenericConfig.Authorizer = sarAuthorizer{}
	masterConfig.GenericConfig.AdmissionControl = admit.NewAlwaysAdmit()
	_, s, closeFn := framework.RunAMaster(masterConfig)
	defer closeFn()

	clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &api.Registry.GroupOrDie(api.GroupName).GroupVersion}})

	tests := []struct {
		name           string
		username       string
		sar            *authorizationapi.SelfSubjectAccessReview
		expectedError  string
		expectedStatus authorizationapi.SubjectAccessReviewStatus
	}{
		{
			name:     "simple allow",
			username: "alice",
			sar: &authorizationapi.SelfSubjectAccessReview{
				Spec: authorizationapi.SelfSubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:     "list",
						Group:    api.GroupName,
						Version:  "v1",
						Resource: "pods",
					},
				},
			},
			expectedStatus: authorizationapi.SubjectAccessReviewStatus{
				Allowed: true,
				Reason:  "you're not dave",
			},
		},
		{
			name:     "simple deny",
			username: "dave",
			sar: &authorizationapi.SelfSubjectAccessReview{
				Spec: authorizationapi.SelfSubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:     "list",
						Group:    api.GroupName,
						Version:  "v1",
						Resource: "pods",
					},
				},
			},
			expectedStatus: authorizationapi.SubjectAccessReviewStatus{
				Allowed:         false,
				Reason:          "no",
				EvaluationError: "I'm sorry, Dave",
			},
		},
	}

	for _, test := range tests {
		username = test.username

		response, err := clientset.Authorization().SelfSubjectAccessReviews().Create(test.sar)
		switch {
		case err == nil && len(test.expectedError) == 0:

		case err != nil && strings.Contains(err.Error(), test.expectedError):
			continue

		case err != nil && len(test.expectedError) != 0:
			t.Errorf("%s: unexpected error: %v", test.name, err)
			continue
		default:
			t.Errorf("%s: expected %v, got %v", test.name, test.expectedError, err)
			continue
		}
		if response.Status != test.expectedStatus {
			t.Errorf("%s: expected %v, got %v", test.name, test.expectedStatus, response.Status)
			continue
		}
	}
}

func TestLocalSubjectAccessReview(t *testing.T) {
	masterConfig := framework.NewIntegrationTestMasterConfig()
	masterConfig.GenericConfig.Authenticator = authenticator.RequestFunc(alwaysAlice)
	masterConfig.GenericConfig.Authorizer = sarAuthorizer{}
	masterConfig.GenericConfig.AdmissionControl = admit.NewAlwaysAdmit()
	_, s, closeFn := framework.RunAMaster(masterConfig)
	defer closeFn()

	clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &api.Registry.GroupOrDie(api.GroupName).GroupVersion}})

	tests := []struct {
		name           string
		namespace      string
		sar            *authorizationapi.LocalSubjectAccessReview
		expectedError  string
		expectedStatus authorizationapi.SubjectAccessReviewStatus
	}{
		{
			name:      "simple allow",
			namespace: "foo",
			sar: &authorizationapi.LocalSubjectAccessReview{
				ObjectMeta: metav1.ObjectMeta{Namespace: "foo"},
				Spec: authorizationapi.SubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:      "list",
						Group:     api.GroupName,
						Version:   "v1",
						Resource:  "pods",
						Namespace: "foo",
					},
					User: "alice",
				},
			},
			expectedStatus: authorizationapi.SubjectAccessReviewStatus{
				Allowed: true,
				Reason:  "you're not dave",
			},
		},
		{
			name:      "simple deny",
			namespace: "foo",
			sar: &authorizationapi.LocalSubjectAccessReview{
				ObjectMeta: metav1.ObjectMeta{Namespace: "foo"},
				Spec: authorizationapi.SubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:      "list",
						Group:     api.GroupName,
						Version:   "v1",
						Resource:  "pods",
						Namespace: "foo",
					},
					User: "dave",
				},
			},
			expectedStatus: authorizationapi.SubjectAccessReviewStatus{
				Allowed:         false,
				Reason:          "no",
				EvaluationError: "I'm sorry, Dave",
			},
		},
		{
			name:      "conflicting namespace",
			namespace: "foo",
			sar: &authorizationapi.LocalSubjectAccessReview{
				ObjectMeta: metav1.ObjectMeta{Namespace: "foo"},
				Spec: authorizationapi.SubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:      "list",
						Group:     api.GroupName,
						Version:   "v1",
						Resource:  "pods",
						Namespace: "bar",
					},
					User: "dave",
				},
			},
			expectedError: "must match metadata.namespace",
		},
		{
			name:      "missing namespace",
			namespace: "foo",
			sar: &authorizationapi.LocalSubjectAccessReview{
				ObjectMeta: metav1.ObjectMeta{Namespace: "foo"},
				Spec: authorizationapi.SubjectAccessReviewSpec{
					ResourceAttributes: &authorizationapi.ResourceAttributes{
						Verb:     "list",
						Group:    api.GroupName,
						Version:  "v1",
						Resource: "pods",
					},
					User: "dave",
				},
			},
			expectedError: "must match metadata.namespace",
		},
	}

	for _, test := range tests {
		response, err := clientset.Authorization().LocalSubjectAccessReviews(test.namespace).Create(test.sar)
		switch {
		case err == nil && len(test.expectedError) == 0:

		case err != nil && strings.Contains(err.Error(), test.expectedError):
			continue

		case err != nil && len(test.expectedError) != 0:
			t.Errorf("%s: unexpected error: %v", test.name, err)
			continue
		default:
			t.Errorf("%s: expected %v, got %v", test.name, test.expectedError, err)
			continue
		}
		if response.Status != test.expectedStatus {
			t.Errorf("%s: expected %#v, got %#v", test.name, test.expectedStatus, response.Status)
			continue
		}
	}
}