text:
date: 2018-12-19 00:50:00 GMT-2
image: '/files/2018/12/ssh-token.png'
layout: post
published: true
nickname: 'ssh-token'
title: 'SSH com autenticação em dois fatores usando certificado digital'
excerpt: 'Se você possui um certificado digital armazenado em uma mídia criptográfica, como um cartão inteligente ou um token, pode adicionar uma camada de segurança às conexões SSH com seu servidor configurando autenticação baseada em dois fatores (two-factor authentication ou 2FA). Com isso, para se conectar ao servidor, é necessário possuir a mídia criptográfica e conhecer sua senha PIN. Neste post, você verá como configurar autenticação com token no acesso remoto via SSH.'
---

{% include image.html src="/files/2018/12/ssh-token.png" %}

Se você possui um [certificado digital][how-to-token] armazenado em uma mídia criptográfica, como um [cartão inteligente][smart-card] ou um [*token*][token], pode adicionar uma camada de segurança às conexões [SSH] com seu servidor configurando [autenticação baseada em dois fatores][2fa] (*two-factor authentication* ou 2FA). Com isso, para se conectar ao servidor, é necessário possuir a mídia criptográfica e conhecer sua senha PIN.

Neste *post*, você verá como configurar autenticação com *token* no acesso remoto via SSH.

## Pré-requisitos

Aqui, parto do princípio que:

- o servidor está com o acesso remoto via SSH habilitado e funcionando,
- o computador cliente consegue acessar remotamente o servidor via SSH, e
- o computador cliente como consegue utilizar o *token*.

Recomendo a leitura de alguns *posts* anteriores:

- [Levante um servidor com o Linux openSUSE Leap - parte 1][how-to-server] (instalação),
- [Levante um servidor com o Linux openSUSE Leap - parte 2][how-to-server-config] (configuração), e
- [Configurando certificado digital no Linux openSUSE][how-to-token].

## Obtendo a chave pública do *token* e copiando para o servidor

O *token* armazena seu certificado [X.509][x509]. Sua chave pública deve ser conhecida pelo servidor para que ele aceite a conexão SSH encriptada com ela.

Para extrair a chave pública do *token* no formato [RSA], utilizado por padrão no SSH, use o comando [**ssh-keygen**][ssh-keygen] com o argumento `-D` e o caminho para a biblioteca do *token* (no meu caso, `/usr/lib64/libeToken.so`). Salve a saída em um arquivo (por exemplo, `chaves_token`):

```
$ ssh-keygen -D /usr/lib64/libeToken.so > chaves_token
```

Copie sua chave pública para o servidor usando o protocolo e comando [SCP] (semelhante ao SSH, mas usado para copiar arquivos):

```
$ scp chaves_token kamarada@meuservidor:/home/kamarada/
```

São informados, na sequência: o caminho no computador local do arquivo a ser copiado, o nome do usuário do servidor, o nome de rede (ou endereço IP) do servidor e o destino do arquivo no servidor.

## Configurando a autenticação no servidor

Acesse remotamente o servidor usando SSH:

```
$ ssh kamarada@meuservidor
```

No servidor, crie a pasta de configuração do SSH:

```
$ mkdir -p .ssh
```

Copie a chave pública RSA para o arquivo `.ssh/authorized_keys`:

```
$ cat chaves_token >> .ssh/authorized_keys
```

`authorized_keys` é um arquivo de configuração do SSH que especifica quais chaves podem ser aceitas no acesso remoto com a conta do usuário.

Você pode excluir o arquivo `chaves_token` e encerrar o acesso remoto:

```
$ rm chaves_token
$ exit
```

## Acesso remoto usando o token

Acesse remotamente o servidor via SSH, dessa vez adicionando o argumento `-I` e o caminho para a biblioteca do *token*:

```
$ ssh -I /usr/lib64/libeToken.so kamarada@meuservidor
```

Forneça a senha PIN do *token*:

```
Enter PIN for 'ANTONIO VINICIUS MENEZES MEDEIR':
```

E pronto: você está na linha de comando do servidor!

Encerre o acesso remoto, por enquanto:

```
$ exit
```

## Autenticando com o token por padrão

No momento, é possível acessar remotamente o servidor de duas formas:

- informando a senha do usuário do servidor, como de costume, com:

```
$ ssh kamarada@meuservidor
```

- ou usando o *token* e informando sua senha PIN com:

```
$ ssh -I /usr/lib64/libeToken.so kamarada@meuservidor
```

Para usar o *token* por padrão, edite o arquivo `~/.ssh/config`:

```
$ nano ~/.ssh/config
```

E adicione a linha:

```
PKCS11Provider /usr/lib64/libeToken.so
```

(lembre de mudar o caminho para a biblioteca do *token* conforme sua necessidade)

Feito isso, não é mais necessário adicionar o argumento `-I` para usar o *token*:

```
$ ssh kamarada@meuservidor
Enter PIN for 'ANTONIO VINICIUS MENEZES MEDEIR':
Last login: Mon Dec 17 00:47:15 2018 from 172.17.0.10
Have a lot of fun...
kamarada@meuservidor:~>
```

Se o *token* estiver plugado no computador cliente, será solicitada sua senha PIN. Senão, será solicitada a senha do usuário do servidor.

## Referências

Quero agradecer ao sabe-tudo [Leandro Peracchi][leandro] por ter compartilhado essa dica comigo.

Para escrever a explicação, consultei algumas páginas:

- [Linux smart card authentication - OpenSSH - Firas Kraïem][fkraiem]
- [OpenSSH and smart cards PKCS#11 - OpenSC/OpenSC Wiki - GitHub][github]
- [About SSH and Smart Card support (RHEL 7)][redhat]
- [Authorized_keys file in SSH - SSH.COM][ssh.com]

[how-to-token]:         {%post_url pt/2018-04-16-configurando-certificado-digital-no-linux-opensuse %}
[smart-card]:           https://pt.wikipedia.org/wiki/Cart%C3%A3o_inteligente
[token]:                https://pt.wikipedia.org/wiki/Token_(chave_eletr%C3%B4nica)
[ssh]:                  https://pt.wikipedia.org/wiki/Secure_Shell
[2fa]:                  https://en.wikipedia.org/wiki/Multi-factor_authentication
[how-to-server]:        {%post_url pt/2017-01-15-levante-um-servidor-com-o-linux-opensuse-leap %}
[how-to-server-config]: {%post_url pt/2017-02-18-levante-um-servidor-com-o-linux-opensuse-leap-parte-2 %}
[x509]:                 https://pt.wikipedia.org/wiki/X.509
[rsa]:                  https://pt.wikipedia.org/wiki/RSA_(sistema_criptogr%C3%A1fico)
[ssh-keygen]:           https://linux.die.net/man/1/ssh-keygen
[scp]:                  https://pt.wikipedia.org/wiki/Secure_copy
[opensuse-leap]:        {% post_url pt/2018-05-25-baseado-no-codigo-do-enterprise-testado-milhoes-de-vezes-opensuse-leap-15-lancado %}
[leandro]:              https://br.linkedin.com/in/leandro-peracchi-425463159
[fkraiem]:              http://blog.fkraiem.org/2013/03/13/linux-smart-card-authentication-openssh/
[github]:               https://github.com/OpenSC/OpenSC/wiki/OpenSSH-and-smart-cards-PKCS%2311
[redhat]:               https://access.redhat.com/articles/1523343
[ssh.com]:              https://www.ssh.com/ssh/authorized_keys/


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fungi Exsiccati Suecici 37-38: 25 (1950)

#### Original name
Corticium punctulatum Cooke, 1878

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Footer Template
 *
 * Contains footer content and widgets of menu_subnavigation, #includes
 * #main and #page div elements.
 *
 * @package WordPress
 * @subpackage sagarra
 */
?>

            <?php
            wp_nav_menu (array ( 'container_class' => 'menu-inicio',
                'theme_location'  => 'inicio' ));
            ?>

            <?php wp_nav_menu (array ( 'theme_location' => 'externo' )); ?>
            <?php if ( function_exists ('qts_language_menu') ) qts_language_menu ('text'); ?>
            <?php wp_nav_menu (array ( 'theme_location' => 'pie-pagina' )); ?>

<?php wp_footer (); ?>


text:
<?php

/**
 * Render a breadcrumb trail for the user based on the page they are on.
 *
 * @param array $Params
 * @param object $Smarty
 * @return string
 */
function smarty_function_breadcrumbs($Params, &$Smarty) {
    $Breadcrumbs = $Smarty->Controller->data('Breadcrumbs');
    if (!is_array($Breadcrumbs)) {
        $Breadcrumbs = array();
    }

    $Options = arrayTranslate($Params, array('homeurl' => 'HomeUrl', 'hidelast' => 'HideLast'));

    return Gdn_Theme::breadcrumbs($Breadcrumbs, val('homelink', $Params, true), $Options);
}


text:
/**
 * Indicates that the result of a {@link Pipe} transformation has changed even though the
 * reference has not changed.
 *
 * Wrapped values are unwrapped automatically during the change detection, and the unwrapped value
 * is stored.
 *
 * Example:
 *
 * ```
 * if (this._latestValue === this._latestReturnedValue) {
 *    return this._latestReturnedValue;
 *  } else {
 *    this._latestReturnedValue = this._latestValue;
 *    return WrappedValue.wrap(this._latestValue); // this will force update
 *  }
 * ```
 *
 * @publicApi
 */
export class WrappedValue {
  /** @deprecated from 5.3, use `unwrap()` instead - will switch to protected */
  wrapped: any;

  constructor(value: any) {
    this.wrapped = value;
  }

  /** Creates a wrapped value. */
  static wrap(value: any): WrappedValue {
    return new WrappedValue(value);
  }

  /**
   * Returns the underlying value of a wrapped value.
   * Returns the given `value` when it is not wrapped.
   **/
  static unwrap(value: any): any {
    return WrappedValue.isWrapped(value) ? value.wrapped : value;
  }

  /** Returns true if `value` is a wrapped value. */
  static isWrapped(value: any): value is WrappedValue {
    return value instanceof WrappedValue;
  }
}


text:
module adat {
	export class Transaction extends illa.EventHandler {

		static EVENT_ABORT = 'adat_Transaction_EVENT_ABORT';
		static EVENT_ERROR = 'adat_Transaction_EVENT_ERROR';
		static EVENT_COMPLETE = 'adat_Transaction_EVENT_COMPLETE';

		private transaction: IDBTransaction;
		private name = '';

		constructor(private database: Database, private requests: Request<any, any>[], private mode?: TransactionMode) {
			super();
		}

		process(): Transaction {
			if (this.database.getIsOpen()) {
				this.processInternal();
			} else {
				this.database.open();
				this.database.addEventCallback(Database.EVENT_OPEN_SUCCESS, this.processInternal, this);
			}
			return this;
		}

		processInternal(): void {
			if (!this.transaction) {
				this.transaction = this.database.getIDBDatabase().transaction(this.getObjectStoreNames(), Transaction.getModeValue(this.getMode()));
				this.transaction.onabort = illa.bind(this.onAbort, this);
				this.transaction.onerror = illa.bind(this.onError, this);
				this.transaction.oncomplete = illa.bind(this.onComplete, this);
			}

			for (var i = 0, n = this.requests.length; i < n; i++) {
				var request = this.requests[i];
				var objectStoreName = illa.ObjectUtil.getKeyOfValue(
					this.database.getCurrentVersionDescriptor().getObjectStoreDescriptors(),
					request.getObjectStoreDescriptor());
				request.process(this.transaction.objectStore(objectStoreName));
			}
		}

		getObjectStoreNames(): string[] {
			var result: string[] = [];
			var osds: ObjectStoreDescriptor<any, any>[] = [];

			for (var i = 0, n = this.requests.length; i < n; i++) {
				var osd = this.requests[i].getObjectStoreDescriptor();
				if (illa.ArrayUtil.indexOf(osds, osd) == -1) {
					osds.push(osd);
					result.push(illa.ObjectUtil.getKeyOfValue(this.database.getCurrentVersionDescriptor().getObjectStoreDescriptors(), osd));
				}
			}

			return result;
		}

		getMode(): TransactionMode {
			if (illa.isUndefinedOrNull(this.mode)) {
				return this.getModeFromRequests();
			} else {
				return this.mode;
			}
		}

		getModeFromRequests(): TransactionMode {
			var result = TransactionMode.READONLY;
			for (var i = 0, n = this.requests.length; i < n; i++) {
				var mode = this.requests[i].getMode();
				if (mode > result) {
					result = mode;
					break; // There is but one level above READONLY
				}
			}
			return result;
		}

		static getModeValue(mode: TransactionMode): string {
			switch (mode) {
				case TransactionMode.READONLY:
					return 'readonly';
				case TransactionMode.READWRITE:
					return 'readwrite';
			}
			return '';
		}

		onAbort(e) {
			illa.Log.warn('Aborted transaction.');

			new illa.Event(Transaction.EVENT_ABORT, this).dispatch();
		}

		onError(e: ErrorEvent) {
			illa.Log.error('Transaction error:', e.message);

			new illa.Event(Transaction.EVENT_ERROR, this).dispatch();
		}

		onComplete(e: Event) {
			illa.Log.infoIf(this.name, 'Transaction complete.');

			new illa.Event(Transaction.EVENT_COMPLETE, this).dispatch();
		}

		getDatabase() { return this.database }
		getRequests() { return this.requests }
		setRequests(value: Request<any, any>[]): Transaction { this.requests = value; return this }
		getIDBTransaction() { return this.transaction }
		setName(value: string): Transaction { this.name = value; return this }
		getName() { return this.name }
	}
}


text:
Vertex::Vertex(const IdType& id)
    : Vertex(id, id, 0, 1, false)
{}

Vertex::Vertex(const IdType& id, unsigned upper_quota)
    : Vertex(id, id, 0, upper_quota, false)
{}

Vertex::Vertex(const IdType& id, unsigned lower_quota, unsigned upper_quota)
    : Vertex(id, id, lower_quota, upper_quota, false)
{}

Vertex::Vertex(const IdType& id, unsigned lower_quota, unsigned upper_quota, bool dummy)
    : Vertex(id, id, lower_quota, upper_quota, dummy)
{}

Vertex::Vertex(const IdType& id, const IdType& cloned_for_id,
               unsigned lower_quota, unsigned upper_quota, bool dummy)
    : id_(id), cloned_for_id_(cloned_for_id),
      lower_quota_(lower_quota), upper_quota_(upper_quota),
      dummy_(dummy)
{}

IdType const& Vertex::get_id() const {
    return id_;
}

IdType const& Vertex::get_cloned_for_id() const {
    return cloned_for_id_;
}

unsigned Vertex::get_lower_quota() const {
    return lower_quota_;
}

unsigned Vertex::get_upper_quota() const {
    return upper_quota_;
}

bool Vertex::is_dummy() const {
    return dummy_;
}

PreferenceList& Vertex::get_preference_list() {
    return pref_list_;
}

PreferenceList const& Vertex::get_preference_list() const {
    return pref_list_;
}

/// print this vertex in the format v: p1, ..., pk
std::ostream& operator<<(std::ostream& out, VertexPtr v) {
    std::stringstream stmp;
    stmp << v->get_id() << ": "; // print vertex id
    stmp << v->get_preference_list() << '\n';
    return out << stmp.str();
}


text:
require 'net/https'
require 'yaml'

if ARGV.size < 2 || ARGV.size % 2 != 0
  fail "Usage: #$0 <param> <query> [param query...]"
end

# Param
query = ARGV.each_slice(2).inject({}) do |h, (k,v)|
  h.update(k => Regexp.compile(v))
end

# Client
http = Net::HTTP.new('localhost', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

# Request
resp = http.get('/nodes', 'Accept' => 'yaml')
nodes = YAML.load(resp.body)

# Find
result = nodes.find do |node|
  query.all? {|k,v| node['parameters'][k] =~ v}
end

# Print result
if result
  puts result['name']
  exit 0
else
  exit 1
end


text:
using namespace PaintsNow;
using namespace PaintsNow::NsMythForest;

ModelComponentModule::ModelComponentModule(Engine& engine) : ModuleImpl<ModelComponent>(engine) {}


text:
import random

import sqlalchemy as sa
from sqlalchemy import Column
from sqlalchemy import func
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import null
from sqlalchemy import select
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import true
from sqlalchemy import update
from sqlalchemy.orm import aliased
from sqlalchemy.orm import Bundle
from sqlalchemy.orm import defaultload
from sqlalchemy.orm import defer
from sqlalchemy.orm import join as orm_join
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import lazyload
from sqlalchemy.orm import Load
from sqlalchemy.orm import load_only
from sqlalchemy.orm import Query
from sqlalchemy.orm import relationship
from sqlalchemy.orm import selectinload
from sqlalchemy.orm import Session
from sqlalchemy.orm import subqueryload
from sqlalchemy.orm import synonym
from sqlalchemy.orm import with_expression
from sqlalchemy.orm import with_loader_criteria
from sqlalchemy.orm import with_polymorphic
from sqlalchemy.sql.base import CacheableOptions
from sqlalchemy.sql.expression import case
from sqlalchemy.sql.visitors import InternalTraversal
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import ne_
from sqlalchemy.testing.fixtures import fixture_session
from test.orm import _fixtures
from .inheritance import _poly_fixtures
from .test_query import QueryTest
from ..sql.test_compare import CacheKeyFixture

def stmt_20(*elements):
    return tuple(
        elem._statement_20() if isinstance(elem, Query) else elem
        for elem in elements
    )

class CacheKeyTest(CacheKeyFixture, _fixtures.FixtureTest):
    run_setup_mappers = "once"
    run_inserts = None
    run_deletes = None

    @classmethod
    def setup_mappers(cls):
        cls._setup_stock_mapping()

    def test_mapper_and_aliased(self):
        User, Address, Keyword = self.classes("User", "Address", "Keyword")

        self._run_cache_key_fixture(
            lambda: (inspect(User), inspect(Address), inspect(aliased(User))),
            compare_values=True,
        )

    def test_attributes(self):
        User, Address, Keyword = self.classes("User", "Address", "Keyword")

        self._run_cache_key_fixture(
            lambda: (
                User.id,
                Address.id,
                aliased(User).id,
                aliased(User, name="foo").id,
                aliased(User, name="bar").id,
                User.name,
                User.addresses,
                Address.email_address,
                aliased(User).addresses,
            ),
            compare_values=True,
        )

    def test_bundles_in_annotations(self):
        User = self.classes.User

        self._run_cache_key_fixture(
            lambda: (
                Bundle("mybundle", User.id).__clause_element__(),
                Bundle("myotherbundle", User.id).__clause_element__(),
                Bundle("mybundle", User.name).__clause_element__(),
                Bundle("mybundle", User.id, User.name).__clause_element__(),
            ),
            compare_values=True,
        )

    def test_bundles_directly(self):
        User = self.classes.User

        self._run_cache_key_fixture(
            lambda: (
                Bundle("mybundle", User.id),
                Bundle("mybundle", User.id).__clause_element__(),
                Bundle("myotherbundle", User.id),
                Bundle("mybundle", User.name),
                Bundle("mybundle", User.id, User.name),
            ),
            compare_values=True,
        )

    def test_query_expr(self):
        (User,) = self.classes("User")

        self._run_cache_key_fixture(
            lambda: (
                with_expression(User.name, true()),
                with_expression(User.name, null()),
                with_expression(User.name, func.foobar()),
                with_expression(User.name, User.name == "test"),
                Load(User).with_expression(User.name, true()),
                Load(User).with_expression(User.name, null()),
                Load(User).with_expression(User.name, func.foobar()),
                Load(User).with_expression(User.name, User.name == "test"),
            ),
            compare_values=True,
        )

    def test_loader_criteria(self):
        User, Address = self.classes("User", "Address")

        from sqlalchemy import Column, Integer, String

        class Foo(object):
            id = Column(Integer)
            name = Column(String)

        self._run_cache_key_fixture(
            lambda: (
                with_loader_criteria(User, User.name != "somename"),
                with_loader_criteria(User, User.id != 5),
                with_loader_criteria(User, lambda cls: cls.id == 10),
                with_loader_criteria(Address, Address.id != 5),
                with_loader_criteria(Foo, lambda cls: cls.id == 10),
            ),
            compare_values=True,
        )

    def test_loader_criteria_bound_param_thing(self):
        from sqlalchemy import Column, Integer

        class Foo(object):
            id = Column(Integer)

        def go(param):
            return with_loader_criteria(Foo, lambda cls: cls.id == param)

        g1 = go(10)
        g2 = go(20)

        ck1 = g1._generate_cache_key()
        ck2 = g2._generate_cache_key()

        eq_(ck1.key, ck2.key)
        eq_(ck1.bindparams[0].key, ck2.bindparams[0].key)
        eq_(ck1.bindparams[0].value, 10)
        eq_(ck2.bindparams[0].value, 20)

    def test_instrumented_attributes(self):
        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        self._run_cache_key_fixture(
            lambda: (
                User.addresses,
                User.addresses.of_type(aliased(Address)),
                User.orders,
                User.orders.and_(Order.id != 5),
                User.orders.and_(Order.description != "somename"),
            ),
            compare_values=True,
        )

    def test_unbound_options(self):
        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        self._run_cache_key_fixture(
            lambda: (
                joinedload(User.addresses),
                joinedload(User.addresses.of_type(aliased(Address))),
                joinedload("addresses"),
                joinedload(User.orders),
                joinedload(User.orders.and_(Order.id != 5)),
                joinedload(User.orders.and_(Order.id == 5)),
                joinedload(User.orders.and_(Order.description != "somename")),
                joinedload(User.orders).selectinload("items"),
                joinedload(User.orders).selectinload(Order.items),
                defer(User.id),
                defer("id"),
                defer("*"),
                defer(Address.id),
                subqueryload(User.orders),
                selectinload(User.orders),
                joinedload(User.addresses).defer(Address.id),
                joinedload(aliased(User).addresses).defer(Address.id),
                joinedload(User.addresses).defer("id"),
                joinedload(User.orders).joinedload(Order.items),
                joinedload(User.orders).subqueryload(Order.items),
                subqueryload(User.orders).subqueryload(Order.items),
                subqueryload(User.orders)
                .subqueryload(Order.items)
                .defer(Item.description),
                defaultload(User.orders).defaultload(Order.items),
                defaultload(User.orders),
            ),
            compare_values=True,
        )

    def test_unbound_sub_options(self):
        """test #6869"""

        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        self._run_cache_key_fixture(
            lambda: (
                joinedload(User.addresses).options(
                    joinedload(Address.dingaling)
                ),
                joinedload(User.addresses).options(
                    joinedload(Address.dingaling).options(load_only("name"))
                ),
                joinedload(User.orders).options(
                    joinedload(Order.items).options(joinedload(Item.keywords))
                ),
            ),
            compare_values=True,
        )

    def test_bound_options(self):
        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        a1 = aliased(Address)

        self._run_cache_key_fixture(
            lambda: (
                Load(User).joinedload(User.addresses),
                Load(User).joinedload(
                    User.addresses.of_type(aliased(Address))
                ),
                Load(User).joinedload(User.orders),
                Load(User).joinedload(User.orders.and_(Order.id != 5)),
                Load(User).joinedload(
                    User.orders.and_(Order.description != "somename")
                ),
                Load(User).defer(User.id),
                Load(User).subqueryload(User.addresses),
                Load(Address).defer(Address.id),
                Load(Address).defer("*"),
                Load(a1).defer(a1.id),
                Load(User).joinedload(User.addresses).defer(Address.id),
                Load(User).joinedload(User.orders).joinedload(Order.items),
                Load(User).joinedload(User.orders).subqueryload(Order.items),
                Load(User).subqueryload(User.orders).subqueryload(Order.items),
                Load(User)
                .subqueryload(User.orders)
                .subqueryload(Order.items)
                .defer(Item.description),
                Load(User).defaultload(User.orders).defaultload(Order.items),
                Load(User).defaultload(User.orders),
                Load(Address).raiseload("*"),
                Load(Address).raiseload(Address.user),
            ),
            compare_values=True,
        )

    def test_selects_w_orm_joins(self):

        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        a1 = aliased(Address)

        self._run_cache_key_fixture(
            lambda: (
                select(User).join(User.addresses),
                select(User).join(User.orders),
                select(User).join(User.addresses).join(User.orders),
                select(User).join(Address, User.addresses),
                select(User).join(a1, User.addresses),
                select(User).join(User.addresses.of_type(a1)),
                select(User).join(
                    User.addresses.and_(Address.email_address == "foo")
                ),
                select(User)
                .join(Address, User.addresses)
                .join_from(User, Order),
                select(User)
                .join(Address, User.addresses)
                .join_from(User, User.orders),
                select(User.id, Order.id).select_from(
                    orm_join(User, Order, User.orders)
                ),
            ),
            compare_values=True,
        )

    def test_orm_query_w_orm_joins(self):

        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        a1 = aliased(Address)

        self._run_cache_key_fixture(
            lambda: stmt_20(
                fixture_session().query(User).join(User.addresses),
                fixture_session().query(User).join(User.orders),
                fixture_session()
                .query(User)
                .join(User.addresses)
                .join(User.orders),
                fixture_session()
                .query(User)
                .join(User.addresses)
                .join(Address.dingaling),
                fixture_session().query(User).join(Address, User.addresses),
                fixture_session().query(User).join(a1, User.addresses),
                fixture_session().query(User).join(User.addresses.of_type(a1)),
            ),
            compare_values=True,
        )

    def test_orm_query_using_with_entities(self):
        """test issue #6503"""
        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        self._run_cache_key_fixture(
            lambda: stmt_20(
                fixture_session()
                .query(User)
                .join(User.addresses)
                .with_entities(Address.id),
                #
                fixture_session().query(Address.id).join(User.addresses),
                #
                fixture_session()
                .query(User)
                .options(selectinload(User.addresses))
                .with_entities(User.id),
                #
                fixture_session()
                .query(User)
                .options(selectinload(User.addresses)),
                #
                fixture_session().query(User).with_entities(User.id),
                #
                # here, propagate_attr->orm is Address, entity is Address.id,
                # but the join() + with_entities() will log a
                # _MemoizedSelectEntities to differentiate
                fixture_session()
                .query(Address, Order)
                .join(Address.dingaling)
                .with_entities(Address.id),
                #
                # same, propagate_attr->orm is Address, entity is Address.id,
                # but the join() + with_entities() will log a
                # _MemoizedSelectEntities to differentiate
                fixture_session()
                .query(Address, User)
                .join(Address.dingaling)
                .with_entities(Address.id),
            ),
            compare_values=True,
        )

    def test_synonyms(self, registry):
        """test for issue discovered in #7394"""

        @registry.mapped
        class User2(object):
            __table__ = self.tables.users

            name_syn = synonym("name")

        @registry.mapped
        class Address2(object):
            __table__ = self.tables.addresses

            name_syn = synonym("email_address")

        self._run_cache_key_fixture(
            lambda: (
                User2.id,
                User2.name,
                User2.name_syn,
                Address2.name_syn,
                Address2.email_address,
                aliased(User2).name_syn,
                aliased(User2, name="foo").name_syn,
                aliased(User2, name="bar").name_syn,
            ),
            compare_values=True,
        )

    def test_more_with_entities_sanity_checks(self):
        """test issue #6503"""
        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        sess = fixture_session()

        q1 = (
            sess.query(Address, Order)
            .with_entities(Address.id)
            ._statement_20()
        )
        q2 = (
            sess.query(Address, User).with_entities(Address.id)._statement_20()
        )

        assert not q1._memoized_select_entities
        assert not q2._memoized_select_entities

        # no joins or options, so q1 and q2 have the same cache key as Order/
        # User are discarded.  Note Address is first so propagate_attrs->orm is
        # Address.
        eq_(q1._generate_cache_key(), q2._generate_cache_key())

        q3 = sess.query(Order).with_entities(Address.id)._statement_20()
        q4 = sess.query(User).with_entities(Address.id)._statement_20()

        # with Order/User as lead entity, this affects propagate_attrs->orm
        # so keys are different
        ne_(q3._generate_cache_key(), q4._generate_cache_key())

        # confirm by deleting propagate attrs and memoized key and
        # running again
        q3._propagate_attrs = None
        q4._propagate_attrs = None
        del q3.__dict__["_generate_cache_key"]
        del q4.__dict__["_generate_cache_key"]
        eq_(q3._generate_cache_key(), q4._generate_cache_key())

        # once there's a join() or options() prior to with_entities, now they
        # are not discarded from the key; Order and User are in the
        # _MemoizedSelectEntities
        q5 = (
            sess.query(Address, Order)
            .join(Address.dingaling)
            .with_entities(Address.id)
            ._statement_20()
        )
        q6 = (
            sess.query(Address, User)
            .join(Address.dingaling)
            .with_entities(Address.id)
            ._statement_20()
        )

        assert q5._memoized_select_entities
        assert q6._memoized_select_entities
        ne_(q5._generate_cache_key(), q6._generate_cache_key())

    def test_orm_query_from_statement(self):
        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        self._run_cache_key_fixture(
            lambda: stmt_20(
                fixture_session()
                .query(User)
                .from_statement(text("select * from user")),
                select(User).from_statement(text("select * from user")),
                fixture_session()
                .query(User)
                .options(selectinload(User.addresses))
                .from_statement(text("select * from user")),
                fixture_session()
                .query(User)
                .options(subqueryload(User.addresses))
                .from_statement(text("select * from user")),
                fixture_session()
                .query(User)
                .from_statement(text("select * from user order by id")),
                fixture_session()
                .query(User.id)
                .from_statement(text("select * from user")),
            ),
            compare_values=True,
        )

    def test_orm_query_basic(self):

        User, Address, Keyword, Order, Item = self.classes(
            "User", "Address", "Keyword", "Order", "Item"
        )

        a1 = aliased(Address)

        self._run_cache_key_fixture(
            lambda: stmt_20(
                fixture_session().query(User),
                fixture_session().query(User).prefix_with("foo"),
                fixture_session().query(User).filter_by(name="ed"),
                fixture_session()
                .query(User)
                .filter_by(name="ed")
                .order_by(User.id),
                fixture_session()
                .query(User)
                .filter_by(name="ed")
                .order_by(User.name),
                fixture_session()
                .query(User)
                .filter_by(name="ed")
                .group_by(User.id),
                fixture_session()
                .query(User)
                .join(User.addresses)
                .filter(User.name == "ed"),
                fixture_session().query(User).join(User.orders),
                fixture_session()
                .query(User)
                .join(User.orders)
                .filter(Order.description == "adsf"),
                fixture_session()
                .query(User)
                .join(User.addresses)
                .join(User.orders),
                fixture_session().query(User).join(Address, User.addresses),
                fixture_session().query(User).join(a1, User.addresses),
                fixture_session().query(User).join(User.addresses.of_type(a1)),
                fixture_session().query(Address).join(Address.user),
                fixture_session().query(User, Address).filter_by(name="ed"),
                fixture_session().query(User, a1).filter_by(name="ed"),
            ),
            compare_values=True,
        )

    def test_options(self):
        class MyOpt(CacheableOptions):
            _cache_key_traversal = [
                ("x", InternalTraversal.dp_plain_obj),
                ("y", InternalTraversal.dp_plain_obj),
            ]
            x = 5
            y = ()

        self._run_cache_key_fixture(
            lambda: (
                MyOpt,
                MyOpt + {"x": 10},
                MyOpt + {"x": 15, "y": ("foo",)},
                MyOpt + {"x": 15, "y": ("foo",)} + {"y": ("foo", "bar")},
            ),
            compare_values=True,
        )

class PolyCacheKeyTest(CacheKeyFixture, _poly_fixtures._Polymorphic):
    run_setup_mappers = "once"
    run_inserts = None
    run_deletes = None

    def test_wp_objects(self):
        Person, Manager, Engineer, Boss = self.classes(
            "Person", "Manager", "Engineer", "Boss"
        )

        self._run_cache_key_fixture(
            lambda: (
                inspect(with_polymorphic(Person, [Manager, Engineer])),
                inspect(with_polymorphic(Person, [Manager])),
                inspect(with_polymorphic(Person, [Manager, Engineer, Boss])),
                inspect(
                    with_polymorphic(Person, [Manager, Engineer], flat=True)
                ),
                inspect(
                    with_polymorphic(
                        Person,
                        [Manager, Engineer],
                        select(Person)
                        .outerjoin(Manager)
                        .outerjoin(Engineer)
                        .subquery(),
                    )
                ),
            ),
            compare_values=True,
        )

    def test_wp_queries(self):
        Person, Manager, Engineer, Boss = self.classes(
            "Person", "Manager", "Engineer", "Boss"
        )

        def two():
            wp = with_polymorphic(Person, [Manager, Engineer])

            return fixture_session().query(wp)

        def three():
            wp = with_polymorphic(Person, [Manager, Engineer])

            return fixture_session().query(wp).filter(wp.name == "asdfo")

        def three_a():
            wp = with_polymorphic(Person, [Manager, Engineer], flat=True)

            return fixture_session().query(wp).filter(wp.name == "asdfo")

        def five():
            subq = (
                select(Person)
                .outerjoin(Manager)
                .outerjoin(Engineer)
                .subquery()
            )
            wp = with_polymorphic(Person, [Manager, Engineer], subq)

            return fixture_session().query(wp).filter(wp.name == "asdfo")

        self._run_cache_key_fixture(
            lambda: stmt_20(two(), three(), three_a(), five()),
            compare_values=True,
        )

    def test_wp_joins(self):
        Company, Person, Manager, Engineer, Boss = self.classes(
            "Company", "Person", "Manager", "Engineer", "Boss"
        )

        def one():
            return (
                fixture_session()
                .query(Company)
                .join(Company.employees)
                .filter(Person.name == "asdf")
            )

        def two():
            wp = with_polymorphic(Person, [Manager, Engineer])
            return (
                fixture_session()
                .query(Company)
                .join(Company.employees.of_type(wp))
                .filter(wp.name == "asdf")
            )

        def three():
            wp = with_polymorphic(Person, [Manager, Engineer])
            return (
                fixture_session()
                .query(Company)
                .join(Company.employees.of_type(wp))
                .filter(wp.Engineer.name == "asdf")
            )

        self._run_cache_key_fixture(
            lambda: stmt_20(one(), two(), three()),
            compare_values=True,
        )

class RoundTripTest(QueryTest, AssertsCompiledSQL):
    __dialect__ = "default"

    run_setup_mappers = None

    @testing.fixture
    def plain_fixture(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User,
        )

        self.mapper_registry.map_imperatively(
            User,
            users,
            properties={
                "addresses": relationship(
                    Address, back_populates="user", order_by=addresses.c.id
                )
            },
        )

        self.mapper_registry.map_imperatively(
            Address,
            addresses,
            properties={
                "user": relationship(User, back_populates="addresses")
            },
        )

        return User, Address

    def test_subqueryload(self, plain_fixture):

        # subqueryload works pretty poorly w/ caching because it has
        # to create a new query.  previously, baked query went through a
        # bunch of hoops to improve upon this and they were found to be
        # broken anyway.   so subqueryload currently pulls out the original
        # query as well as the requested query and works with them at row
        # processing time to create its own query.   all of which is fairly
        # non-performant compared to the selectinloader that has a fixed
        # query.
        User, Address = plain_fixture

        s = Session(testing.db, future=True)

        def query(names):
            stmt = (
                select(User)
                .where(User.name.in_(names))
                .options(subqueryload(User.addresses))
                .order_by(User.id)
            )
            return s.execute(stmt)

        def go1():
            r1 = query(["ed"])
            eq_(
                r1.scalars().all(),
                [User(name="ed", addresses=[Address(), Address(), Address()])],
            )

        def go2():
            r1 = query(["ed", "fred"])
            eq_(
                r1.scalars().all(),
                [
                    User(
                        name="ed", addresses=[Address(), Address(), Address()]
                    ),
                    User(name="fred", addresses=[Address()]),
                ],
            )

        for i in range(5):
            fn = random.choice([go1, go2])
            self.assert_sql_count(testing.db, fn, 2)

    @testing.combinations((True,), (False,), argnames="use_core")
    @testing.combinations((True,), (False,), argnames="arbitrary_element")
    @testing.combinations((True,), (False,), argnames="exercise_caching")
    def test_column_targeting_core_execute(
        self,
        plain_fixture,
        connection,
        use_core,
        arbitrary_element,
        exercise_caching,
    ):
        """test that CursorResultSet will do a column rewrite for any core
        execute even if the ORM compiled the statement.

        This translates the current stmt.selected_columns to the cached
        ResultSetMetaData._keymap.      The ORM skips this because loading.py
        has also cached the selected_columns that are used.   But for
        an outside-facing Core execute, this has to remain turned on.

        Additionally, we want targeting of SQL expressions to work with both
        Core and ORM statement executions. So the ORM still has to do some
        translation here for these elements to be supported.

        """
        User, Address = plain_fixture
        user_table = inspect(User).persist_selectable

        def go():

            my_thing = case((User.id > 9, 1), else_=2)

            # include entities in the statement so that we test that
            # the column indexing from
            # ORM select()._raw_columns -> Core select()._raw_columns is
            # translated appropriately
            stmt = (
                select(User, Address.email_address, my_thing, User.name)
                .join(Address)
                .where(User.name == "ed")
            )

            if arbitrary_element:
                target, exp = (my_thing, 2)
            elif use_core:
                target, exp = (user_table.c.name, "ed")
            else:
                target, exp = (User.name, "ed")

            if use_core:
                row = connection.execute(stmt).first()

            else:
                row = Session(connection).execute(stmt).first()

            eq_(row._mapping[target], exp)

        if exercise_caching:
            for i in range(3):
                go()
        else:
            go()

    @testing.combinations(
        (lazyload, 2),
        (joinedload, 1),
        (selectinload, 2),
        (subqueryload, 2),
        argnames="strat,expected_stmt_cache",
    )
    def test_cache_key_loader_strategies(
        self,
        plain_fixture,
        strat,
        expected_stmt_cache,
        connection,
    ):
        User, Address = plain_fixture

        cache = {}

        connection = connection.execution_options(compiled_cache=cache)
        sess = Session(connection)

        def go():
            stmt = (
                select(User).where(User.id == 7).options(strat(User.addresses))
            )

            u1 = sess.execute(stmt).scalars().first()
            eq_(u1.addresses, [Address(id=1)])

        go()

        lc = len(cache)

        stmt_entries = [k for k in cache]

        eq_(len(stmt_entries), expected_stmt_cache)

        for i in range(3):
            go()

        eq_(len(cache), lc)

class CompositeTest(fixtures.MappedTest):
    __dialect__ = "default"

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "edges",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("x1", Integer),
            Column("y1", Integer),
            Column("x2", Integer),
            Column("y2", Integer),
        )

    @classmethod
    def setup_mappers(cls):
        edges = cls.tables.edges

        class Point(cls.Comparable):
            def __init__(self, x, y):
                self.x = x
                self.y = y

            def __composite_values__(self):
                return [self.x, self.y]

            __hash__ = None

            def __eq__(self, other):
                return (
                    isinstance(other, Point)
                    and other.x == self.x
                    and other.y == self.y
                )

            def __ne__(self, other):
                return not isinstance(other, Point) or not self.__eq__(other)

        class Edge(cls.Comparable):
            def __init__(self, *args):
                if args:
                    self.start, self.end = args

        cls.mapper_registry.map_imperatively(
            Edge,
            edges,
            properties={
                "start": sa.orm.composite(Point, edges.c.x1, edges.c.y1),
                "end": sa.orm.composite(Point, edges.c.x2, edges.c.y2),
            },
        )

    def test_bulk_update_cache_key(self):
        """test secondary issue located as part of #7209"""
        Edge, Point = (self.classes.Edge, self.classes.Point)

        stmt = (
            update(Edge)
            .filter(Edge.start == Point(14, 5))
            .values({Edge.end: Point(16, 10)})
        )
        stmt2 = (
            update(Edge)
            .filter(Edge.start == Point(14, 5))
            .values({Edge.end: Point(17, 8)})
        )

        eq_(stmt._generate_cache_key(), stmt2._generate_cache_key())


text:
package com.dong.blog.facade.impl.assembler;

import java.util.HashSet;
import java.util.Set;

import com.dong.blog.core.domain.BlogType;
import com.dong.blog.core.domain.Category;
import com.dong.blog.facade.dto.BlogTypeDTO;
import com.dong.blog.facade.dto.CategoryDTO;
import com.dong.blog.util.BeanCopierUtil;

public class CategoryAssembler extends AbstractAssembler<Category, CategoryDTO> {

	public CategoryDTO toDto(Category source) {
		CategoryDTO dto = new CategoryDTO();
		try {
			BeanCopierUtil.copyProperties(source, dto);
			Set<BlogType> sets = source.getBlogTypes();
			for (BlogType blogType : sets) {
				BlogTypeDTO blogTypeDTO = new BlogTypeDTO();
				BeanCopierUtil.copyProperties(blogType, blogTypeDTO);
				dto.getList().add(blogTypeDTO);
			}
		} catch (Exception e) {

		}
		return dto;
	}

	public Category toEntity(CategoryDTO source) {
		Category category = new Category();
		BeanCopierUtil.copyProperties(source, category);
		Set<BlogType> set = new HashSet<BlogType>();
		for (BlogTypeDTO dto : source.getList()) {
			set.add(BlogType.get(BlogType.class, dto.getId()));
		}
		category.setBlogTypes(set);
		return category;
	}

	public Category transformEntityData(Category target, CategoryDTO source) {
		target.setCategoryName(source.getCategoryName());
		target.setSort(source.getSort());
		Set<BlogType> set = new HashSet<BlogType>();
		for (BlogTypeDTO dto : source.getList()) {
			set.add(BlogType.get(BlogType.class, dto.getId()));
		}
		target.setBlogTypes(set);
		return target;
	}

}


text:
import time

import pytest

from parsl.app.app import python_app
from parsl.tests.configs.local_threads import config

local_config = config

@python_app
def wait_sleep_double(x, fu_1, fu_2):
    import time
    time.sleep(2)   # Sleep for 2 seconds
    return x * 2

@pytest.mark.skip('fails with pytest+xdist')
def test_parallel(N=2):
    """Parallel workflow example from docs on composing a workflow
    """

    # Launch two apps, which will execute in parallel, since they don't have to
    # wait on any futures
    start = time.time()
    doubled_x = wait_sleep_double(N, None, None)
    doubled_y = wait_sleep_double(N, None, None)

    # The third depends on the first two :
    #    doubled_x   doubled_y     (2 s)
    #           \     /
    #           doublex_z          (2 s)
    doubled_z = wait_sleep_double(N, doubled_x, doubled_y)

    # doubled_z will be done in ~4s
    print(doubled_z.result())
    time.time()
    delta = time.time() - start

    assert doubled_z.result() == N * \
        2, "Expected doubled_z = N*2 = {0}".format(N * 2)
    assert delta > 4 and delta < 5, "Time delta exceeded expected 4 < duration < 5"

if __name__ == "__main__":

    test_parallel()


text:
export interface IBounds {
    bottom: number;
    left: number;
    right: number;
    top: number;
}


text:
<!doctype html>

	<meta charset="utf-8">
	<title>Carte de France</title>
	<link rel="stylesheet" href="js/jquery-jvectormap-1.2.2.css" type="text/css" media="screen"/>

    <link rel="stylesheet" type="text/css" href="js/fullPage.js-master/jquery.fullPage.css" />

	<link rel="stylesheet" type="text/css" href="style.css" />

L'ÉVOLUTION DE LA FISCALITÉ LOCALE DES ENTREPRISES

33 VILLES PASSÉES AU CRIBLE

				Où la pression fiscale sur les entreprises est-elle la plus forte en France ? La
				couleur politique des équipes en place a-t-elle une influence sur le niveau des
				taux que l'on trouve sur le territoire ?

C'est à ces deux questions que le Journal des entreprises s'emploie à répondre
				via ce classement interactif et évolutif (Lire notre méthodologie) qui compare
				les taux de 33 villes en France.

Les deux principales taxes locales payées par les entreprises ont été analysées :
				La Contribution foncière des entreprises (CFE) et la Taxe foncière sur les propriétés bâties.
                Pour avoir une meilleure vue de la politique fiscale d'une ville
				dans la durée, nous avons ajouté les taux de l'ancienne taxe professionnelle,
				remplacée en 2010, par la CFE et la CVAE (Contribution sur la valeur
				ajoutée des entreprises).

Ecoutez notre émission spéciale

 ÉVOLUTION DE

LA COTISATION FONCIÈRE
DES ENTREPRISES (CFE)
 ENTRE 2011 ET 2012

 ÉVOLUTION DE

LA TAXE PROFESSIONNELLE
ENTRE 2002 ET 2010

 ÉVOLUTION DE

LA TAXE FONCIÈRE SUR LES
PROPRIÉTÉS BÂTIES
 ENTRE 2002 ET 2012

Comment les agglomérations taxent les entreprises

C'est la première taxe locale payée par les entreprises. Et l'une des principales ressources financières des collectivités. Réformer la Contribution Foncière des entreprises (CFE) est donc un exercice de haute voltige. Surtout en ces temps de restriction budgétaire des collectivités et de diminution des marges des entreprises.

De nombreuses inégalités fiscales

En 2016, une réforme interviendra avec l'actualisation des valeurs locatives cadastrales, la base permettant de calculer l'impôt. Car la CFE comme la taxe foncière sur les propriétés bâties sont assises sur des valeurs locatives datant de 1970... Et les élus s'accordent à dire que la situation génère de nombreuses inégalités fiscales.

D'une ville à l'autre, d'une rue à l'autre, d'un immeuble à l'autre, le traitement fiscal diffère. Et la structure du tissu économique a un impact sur le montant global perçu par la collectivité. Par exemple, la présence, dans une ville, de nombreux entrepôts industriels a une influence directe sur la recette finale.

Un indicateur de la fiscalité locale des entreprises

Face à des situations locales aussi disparates que mouvantes, nous avons donc choisi de mesurer la pression fiscale des agglomérations et donc d'établir un palmarès des taux votés par les intercommunalités. Un indicateur qui complète notre précédent classement élaboré à partir du montant moyen de CFE payé par habitant et par ville (lejournaldesentreprises.com).

Avec l'évolution du taux de l'ancienne taxe professionnelle entre 2002 et 2008 et celui de la taxe sur le foncier bâti, il permet de se faire une meilleure idée de la politique fiscale d'une collectivité à l'adresse des entreprises. En cette période d'élections municipales, espérons que ce classement nourrira le débat entre élus et dirigeants d'entreprises.

EN SAVOIR +

Retrouvez plus d'informations, des articles et des interviews sur le site du
		Journal des Entreprises, et des podcasts sur La Radio des Entreprises.

Crédits

Réalisation (Polytech Nantes) : Kévin BENARD, Tanguy VOURCH

Design (AGR L'école de l'image) : Marion LE COQ, Pierrick DUPAQUIER

Editorial (SciencesCom) : Sophie CHATEL, Camille GOUY, Rym DJABALI

Avec la participation et l'aide d'Armelle GEGADEN (Le Journal des entreprises)

Sources : Direction générale des Finances Publiques

                                    Un projet issu des ateliers du


text:
<?php echo link_tag('plugins/datepicker/datepicker3.css'); ?>

			เอกสาร

				จัดการเอกสารต่างๆให้ตรงตามหมวดหมู่ เพื่อความง่ายต่อการเข้าถึงของผู้ใช้งาน

				<a href="<?php echo base_url(); ?>">

					หน้าแรก

				<a href="<?php echo base_url('document'); ?>">
					หมวดหมู่เอกสาร

				เพิ่มข้อมูลใหม่

					เพิ่มข้อมูล

			<form role="form" action="<?php echo base_url('document/postdata'); ?>" method="post" enctype="multipart/form-data">
			<input type="hidden" value="<?php echo $doc->id; ?>" name="id">
			<input type="hidden" value="<?php echo $doc->filename; ?>" name="datafile">

							หมวดหมู่เอกสาร
						 <?php echo $this->session->flashdata('err_categorie_id'); ?>
						<select class="form-control" name="categorie_id">
							<option value="">
								เลือกข้อมูล
							</option>
							<?php
							foreach($results as $result){
								?>
								<option value="<?php echo $result->id; ?>" <?php if($result->id==$doc->categorie_id){echo "selected"; } ?>>
									<?php echo $result->name; ?>
								</option>
								<?php
							} ?>
						</select>

							รหัสเอกสาร
						 <?php echo $this->session->flashdata('err_document_code'); ?>
						<input type="text" id="document_code" class="form-control" name="document_code" value="<?php echo $doc->document_code; ?>">

							ชื่อเอกสาร
						 <?php echo $this->session->flashdata('err_topic'); ?>
						<input type="text" id="topic" class="form-control" name="topic" value="<?php echo $doc->topic; ?>">

							วันที่ลงทะเบียนเอกสาร
						 <?php echo $this->session->flashdata('err_register_date'); ?>

							<input type="text" class="form-control pull-right" id="register_date" name="register_date" readonly="" data-date-format="yyyy-mm-dd" value="<?php echo date('Y-m-d',strtotime($doc->register_date)); ?>">

							อ้างอิงเอกสาร

						<input type="text" id="reference" class="form-control" name="reference" value="<?php echo $doc->reference; ?>">

							สถานที่จัดเก็บเอกสาร

						<input type="text" id="store" class="form-control" name="store" value="<?php echo $doc->store; ?>">

							อัพโหลดไฟล์เอกสารใหม่
							<a href="<?php echo base_url('uploads/' . $doc->filename); ?>" target="_blank">(ไฟล์เดิมคลิก)
						 <?php echo $this->session->flashdata('err_filename'); ?>
						<input type="file" name="userfile" id="userfile" >

							รายละเอียด

						<textarea rows="3" class="form-control" id="description" name="description"><?php echo $doc->description; ?></textarea>

					<button class="btn btn-primary" type="submit">

						บันทึกข้อมูล
					</button>
					<a class="btn btn-danger" href="<?php echo base_url('document'); ?>" role="button">

						ยกเลิก

			</form>


text:
===============
Using .xib files to create custom cells

Source: [iOS 8 Swift Programming Cookbook - Chapter 6.6](http://goo.gl/pvRtI8)


text:
using System;
using System.Text;
using Famoser.FrameworkEssentials.Logging;

namespace Famoser.Bookmarked.Business.Helper
{
    public class StringDecoder
    {
        private readonly string _payload;
        private byte[] _result;
        private int _faillureCode = 0;
        public StringDecoder(string payload)
        {
            _payload = payload;
        }

        public bool Encode()
        {
            try
            {
                if (_payload == null)
                {
                    _result = new byte[] { 0 };
                    return true;
                }

                return EncodeYEnc();
            }
            catch (Exception e)
            {
                _faillureCode = 99;
                LogHelper.Instance.LogException(e);
            }
            return false;
        }

        private bool EncodeYEnc()
        {
            var content = Encoding.GetEncoding("ASCII").GetBytes(_payload);
            _result = new byte[_payload.Length * 2];
            var byteIndex = 0;

            for (int i = 0; i < content.Length; i++)
            {
                int current = content[i];
                //check for escapes
                if (true)//current == 0 || current == 10 || current == )
                {
                    //escape caracter, so we need next
                    if (++i == _payload.Length)
                    {
                        //stream finished with escape caracter, fail!
                        _faillureCode = 101;
                        return false;
                    }
                    //inverse + 64 mod 256
                    current = _payload[i] - 64;
                    if (current < 0)
                        current += 256;
                }
                //inverse + 42 mod 256
                current -= 42;
                if (current < 0)
                    current += 256;
                _result[byteIndex++] = (byte)current;
            }

            return true;
        }

        public string GetFaillure()
        {
            switch (_faillureCode)
            {
                case 0:
                    return "no faillure";
                case 1:
                    return "payload null";
                case 2:
                    return "payload too short";
                case 3:
                    return "no encoding found";
                case 4:
                    return "no faillure";
                case 99:
                    return "exception occurred";
                case 101:
                    return "YEnc: Escape caracter at the end";
                default:
                    return "unknown faillure";
            }
        }

        public byte[] GetResult()
        {
            return _result;
        }
    }
}


text:
#include "config.h"

#include "wtf/RefCounted.h"
#include "wtf/Functional.h"
#include <gtest/gtest.h>

namespace {

static int returnFortyTwo()
{
    return 42;
}

TEST(FunctionalTest, Basic)
{
    Function<int()> emptyFunction;
    EXPECT_TRUE(emptyFunction.isNull());

    Function<int()> returnFortyTwoFunction = bind(returnFortyTwo);
    EXPECT_FALSE(returnFortyTwoFunction.isNull());
    EXPECT_EQ(42, returnFortyTwoFunction());
}

static int multiplyByTwo(int n)
{
    return n * 2;
}

static double multiplyByOneAndAHalf(double d)
{
    return d * 1.5;
}

TEST(FunctionalTest, UnaryBind)
{
    Function<int()> multiplyFourByTwoFunction = bind(multiplyByTwo, 4);
    EXPECT_EQ(8, multiplyFourByTwoFunction());

    Function<double()> multiplyByOneAndAHalfFunction = bind(multiplyByOneAndAHalf, 3);
    EXPECT_EQ(4.5, multiplyByOneAndAHalfFunction());
}

TEST(FunctionalTest, UnaryPartBind)
{
    Function<int(int)> multiplyByTwoFunction = bind<int>(multiplyByTwo);
    EXPECT_EQ(8, multiplyByTwoFunction(4));

    Function<double(double)> multiplyByOneAndAHalfFunction = bind<double>(multiplyByOneAndAHalf);
    EXPECT_EQ(4.5, multiplyByOneAndAHalfFunction(3));
}

static int multiply(int x, int y)
{
    return x * y;
}

static int subtract(int x, int y)
{
    return x - y;
}

TEST(FunctionalTest, BinaryBind)
{
    Function<int()> multiplyFourByTwoFunction = bind(multiply, 4, 2);
    EXPECT_EQ(8, multiplyFourByTwoFunction());

    Function<int()> subtractTwoFromFourFunction = bind(subtract, 4, 2);
    EXPECT_EQ(2, subtractTwoFromFourFunction());
}

TEST(FunctionalTest, BinaryPartBind)
{
    Function<int(int)> multiplyFourFunction = bind<int>(multiply, 4);
    EXPECT_EQ(8, multiplyFourFunction(2));
    Function<int(int, int)> multiplyFunction = bind<int, int>(multiply);
    EXPECT_EQ(8, multiplyFunction(4, 2));

    Function<int(int)> subtractFromFourFunction = bind<int>(subtract, 4);
    EXPECT_EQ(2, subtractFromFourFunction(2));
    Function<int(int, int)> subtractFunction = bind<int, int>(subtract);
    EXPECT_EQ(2, subtractFunction(4, 2));
}

static void sixArgFunc(int a, double b, char c, int* d, double* e, char* f)
{
    *d = a;
    *e = b;
    *f = c;
}

static void assertArgs(int actualInt, double actualDouble, char actualChar, int expectedInt, double expectedDouble, char expectedChar)
{
    EXPECT_EQ(expectedInt, actualInt);
    EXPECT_EQ(expectedDouble, actualDouble);
    EXPECT_EQ(expectedChar, actualChar);
}

TEST(FunctionalTest, MultiPartBind)
{
    int a = 0;
    double b = 0.5;
    char c = 'a';

    Function<void(int, double, char, int*, double*, char*)> unbound =
        bind<int, double, char, int*, double*, char*>(sixArgFunc);
    unbound(1, 1.5, 'b', &a, &b, &c);
    assertArgs(a, b, c, 1, 1.5, 'b');

    Function<void(double, char, int*, double*, char*)> oneBound =
        bind<double, char, int*, double*, char*>(sixArgFunc, 2);
    oneBound(2.5, 'c', &a, &b, &c);
    assertArgs(a, b, c, 2, 2.5, 'c');

    Function<void(char, int*, double*, char*)> twoBound =
        bind<char, int*, double*, char*>(sixArgFunc, 3, 3.5);
    twoBound('d', &a, &b, &c);
    assertArgs(a, b, c, 3, 3.5, 'd');

    Function<void(int*, double*, char*)> threeBound =
        bind<int*, double*, char*>(sixArgFunc, 4, 4.5, 'e');
    threeBound(&a, &b, &c);
    assertArgs(a, b, c, 4, 4.5, 'e');

    Function<void(double*, char*)> fourBound =
        bind<double*, char*>(sixArgFunc, 5, 5.5, 'f', &a);
    fourBound(&b, &c);
    assertArgs(a, b, c, 5, 5.5, 'f');

    Function<void(char*)> fiveBound =
        bind<char*>(sixArgFunc, 6, 6.5, 'g', &a, &b);
    fiveBound(&c);
    assertArgs(a, b, c, 6, 6.5, 'g');

    Function<void()> sixBound =
        bind(sixArgFunc, 7, 7.5, 'h', &a, &b, &c);
    sixBound();
    assertArgs(a, b, c, 7, 7.5, 'h');
}

class A {
public:
    explicit A(int i)
        : m_i(i)
    {
    }

    int f() { return m_i; }
    int addF(int j) { return m_i + j; }

private:
    int m_i;
};

TEST(FunctionalTest, MemberFunctionBind)
{
    A a(10);
    Function<int()> function1 = bind(&A::f, &a);
    EXPECT_EQ(10, function1());

    Function<int()> function2 = bind(&A::addF, &a, 15);
    EXPECT_EQ(25, function2());
}

TEST(FunctionalTest, MemberFunctionPartBind)
{
    A a(10);
    Function<int(class A*)> function1 = bind<class A*>(&A::f);
    EXPECT_EQ(10, function1(&a));

    Function<int(class A*, int)> unboundFunction2 =
        bind<class A*, int>(&A::addF);
    EXPECT_EQ(25, unboundFunction2(&a, 15));
    Function<int(int)> objectBoundFunction2 =
        bind<int>(&A::addF, &a);
    EXPECT_EQ(25, objectBoundFunction2(15));
}

class Number : public RefCounted<Number> {
public:
    static PassRefPtr<Number> create(int value)
    {
        return adoptRef(new Number(value));
    }

    ~Number()
    {
        m_value = 0;
    }

    int value() const { return m_value; }

private:
    explicit Number(int value)
        : m_value(value)
    {
    }

    int m_value;
};

static int multiplyNumberByTwo(Number* number)
{
    return number->value() * 2;
}

TEST(FunctionalTest, RefCountedStorage)
{
    RefPtr<Number> five = Number::create(5);
    Function<int()> multiplyFiveByTwoFunction = bind(multiplyNumberByTwo, five);
    EXPECT_EQ(10, multiplyFiveByTwoFunction());

    Function<int()> multiplyFourByTwoFunction = bind(multiplyNumberByTwo, Number::create(4));
    EXPECT_EQ(8, multiplyFourByTwoFunction());

    RefPtr<Number> six = Number::create(6);
    Function<int()> multiplySixByTwoFunction = bind(multiplyNumberByTwo, six.release());
    EXPECT_FALSE(six);
    EXPECT_EQ(12, multiplySixByTwoFunction());
}

} // namespace


text:
#ifndef gstdtlssrtpdemux_h
#define gstdtlssrtpdemux_h

#include <gst/gst.h>

G_BEGIN_DECLS

#define GST_TYPE_DTLS_SRTP_DEMUX \
    (gst_dtls_srtp_demux_get_type())
#define GST_DTLS_SRTP_DEMUX(obj) \
    (G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_DTLS_SRTP_DEMUX, GstDtlsSrtpDemux))
#define GST_DTLS_SRTP_DEMUX_CLASS(klass) \
    (G_TYPE_CHECK_CLASS_CAST((klass), GST_TYPE_DTLS_SRTP_DEMUX, GstDtlsSrtpDemuxClass))
#define GST_IS_DTLS_SRTP_DEMUX(obj) \
    (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_DTLS_SRTP_DEMUX))
#define GST_IS_DTLS_SRTP_DEMUX_CLASS(klass) \
    (G_TYPE_CHECK_CLASS_TYPE((klass), GST_TYPE_DTLS_SRTP_DEMUX))

typedef struct _GstDtlsSrtpDemux GstDtlsSrtpDemux;
typedef struct _GstDtlsSrtpDemuxClass GstDtlsSrtpDemuxClass;

struct _GstDtlsSrtpDemux {
    GstElement element;

    GstPad *rtp_src;
    GstPad *dtls_src;
};

struct _GstDtlsSrtpDemuxClass {
    GstElementClass parent_class;
};

GType gst_dtls_srtp_demux_get_type(void);

gboolean gst_dtls_srtp_demux_plugin_init(GstPlugin *);

G_END_DECLS

#endif /* gstdtlssrtpdemux_h */


text:
/* ecAttributeCode.c was originally generated by the autoSql program, which also
 * generated ecAttributeCode.h and ecAttributeCode.sql.  This module links the database and
 * the RAM representation of objects. */

/* Copyright (C) 2014 The Regents of the University of California
 * See README in this or parent directory for licensing information. */

#include "common.h"
#include "linefile.h"
#include "dystring.h"
#include "jksql.h"
#include "ecAttributeCode.h"

void ecAttributeCodeStaticLoad(char **row, struct ecAttributeCode *ret)
/* Load a row from ecAttributeCode table into ret.  The contents of ret will
 * be replaced at the next call to this function. */
{

strcpy(ret->type, row[0]);
ret->description = row[1];
}

struct ecAttributeCode *ecAttributeCodeLoad(char **row)
/* Load a ecAttributeCode from row fetched with select * from ecAttributeCode
 * from database.  Dispose of this with ecAttributeCodeFree(). */
{
struct ecAttributeCode *ret;

AllocVar(ret);
strcpy(ret->type, row[0]);
ret->description = cloneString(row[1]);
return ret;
}

struct ecAttributeCode *ecAttributeCodeLoadAll(char *fileName)
/* Load all ecAttributeCode from a whitespace-separated file.
 * Dispose of this with ecAttributeCodeFreeList(). */
{
struct ecAttributeCode *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[2];

while (lineFileRow(lf, row))
    {
    el = ecAttributeCodeLoad(row);
    slAddHead(&list, el);
    }
lineFileClose(&lf);
slReverse(&list);
return list;
}

struct ecAttributeCode *ecAttributeCodeLoadAllByChar(char *fileName, char chopper)
/* Load all ecAttributeCode from a chopper separated file.
 * Dispose of this with ecAttributeCodeFreeList(). */
{
struct ecAttributeCode *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[2];

while (lineFileNextCharRow(lf, chopper, row, ArraySize(row)))
    {
    el = ecAttributeCodeLoad(row);
    slAddHead(&list, el);
    }
lineFileClose(&lf);
slReverse(&list);
return list;
}

struct ecAttributeCode *ecAttributeCodeCommaIn(char **pS, struct ecAttributeCode *ret)
/* Create a ecAttributeCode out of a comma separated string.
 * This will fill in ret if non-null, otherwise will
 * return a new ecAttributeCode */
{
char *s = *pS;

if (ret == NULL)
    AllocVar(ret);
sqlFixedStringComma(&s, ret->type, sizeof(ret->type));
ret->description = sqlStringComma(&s);
*pS = s;
return ret;
}

void ecAttributeCodeFree(struct ecAttributeCode **pEl)
/* Free a single dynamically allocated ecAttributeCode such as created
 * with ecAttributeCodeLoad(). */
{
struct ecAttributeCode *el;

if ((el = *pEl) == NULL) return;
freeMem(el->description);
freez(pEl);
}

void ecAttributeCodeFreeList(struct ecAttributeCode **pList)
/* Free a list of dynamically allocated ecAttributeCode's */
{
struct ecAttributeCode *el, *next;

for (el = *pList; el != NULL; el = next)
    {
    next = el->next;
    ecAttributeCodeFree(&el);
    }
*pList = NULL;
}

void ecAttributeCodeOutput(struct ecAttributeCode *el, FILE *f, char sep, char lastSep)
/* Print out ecAttributeCode.  Separate fields with sep. Follow last field with lastSep. */
{
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->type);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->description);
if (sep == ',') fputc('"',f);
fputc(lastSep,f);
}

/* -------------------------------- End autoSql Generated Code -------------------------------- */


text:
<?php

namespace FlickrService\Model;

class PublicEditability {

    use DataMapper;

    static protected $dataMap = array(
        ['canComment','cancomment'],// => int 1
        ['canAddMeta','canaddmeta'],// => int 0
    );

    public $canComment;
    public $canAddMeta;

}


text:
package com.jxtech.jbo.util;

/**
 * 定义常量
 *
 * @author wmzsoft@gmail.com
 * @date 2013.08
 */
public class JxConstant {
    // 设定值时,不做任何校验
    public final static int SET_VALUE_NONE = 1;
    // 设定值时,检查字段是否存在
    public final static int SET_VALUE_EXIST = 2;

    // 直接读取Cache中的值
    public final static long READ_CACHE = 1;
    // 重新取值
    public final static long READ_RELOAD = 2;
    // 缓存中的数据和数据库中的数据全部加载进来
    public final static long READ_ALL = 4;

    public final static long READ_PERSISTENCE = 3;

    // 工作流-发送-同意
    public final static int WORKFLOW_ROUTE_AGREE = 1;
    // 工作流-发送-不同意退回申请人
    public final static int WORKFLOW_ROUTE_BACK_APP = 2;
    // 工作流-发送-不同意退回上一节点
    public final static int WORKFLOW_ROUTE_BACK_LAST = 4;
    // 工作流-发送-终止流程
    public final static int WORKFLOW_ROUTE_ABORT = 8;
    // 工作流-发送-不同意退回指定节点
    public final static int WORKFLOW_ROUTE_BACK_ACT = 16;
    // 工作流-发送-同意到指定节点
    public final static int WORKFLOW_ROUTE_TO_ACT = 32;
    // 工作流-发送-不检查当前发送人是否在当前节点---可以与其它值组合使用
    public final static int WORKFLOW_ROUTE_NOCHK_CURACT = 64;
    // 工作流-发送-不检查是否结束,可以发送到指定节点
    public final static int WORKFLOW_ROUTE_NOCHK_COLSE = 128;

    // 工作流-最后一个节点ACTNAME
    public final static String FINISH_ACTNAME = "结束节点";

    public final static String MPP_FILE = "MppFile";

    public final static String SHEET_PAGE = "SHEET_PAGE";

    // Oracle bpm action操作
    public final static String NO_ACTION = "NOACTION"; // 没有操作
    public final static String SUBMIT = "SUBMIT"; // 提交
    public final static String APPROVE = "APPROVE";// 同意
    public final static String REJECT = "REJECT";// 拒绝

    public final static int SLIBING_PREVIOUS = -1;
    public final static int SLIBING_NEXT = 1;

    public final static String ORG = "ORG";
    public final static String ORG_ZH = "组织";

    public final static String SITE = "SITE";
    public final static String SITE_ZH = "地点";

}


text:
from __future__ import unicode_literals

from decimal import Decimal
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.fields

class Migration(migrations.Migration):

    dependencies = [
        ('myshop', '0003_add_polymorphic'),
    ]

    operations = [
        migrations.CreateModel(
            name='Delivery',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('shipping_id', models.CharField(blank=True, help_text="The transaction processor's reference", max_length=255, null=True, verbose_name='Shipping ID')),
                ('fulfilled_at', models.DateTimeField(blank=True, null=True, verbose_name='Fulfilled at')),
                ('shipped_at', models.DateTimeField(blank=True, null=True, verbose_name='Shipped at')),
                ('shipping_method', models.CharField(help_text='The shipping backend used to deliver the items for this order', max_length=50, verbose_name='Shipping method')),
                ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myshop.Order')),
            ],
        ),
        migrations.CreateModel(
            name='DeliveryItem',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('quantity', models.IntegerField(default=0, verbose_name='Delivered quantity')),
                ('delivery', models.ForeignKey(help_text='Refer to the shipping provider used to ship this item', on_delete=django.db.models.deletion.CASCADE, to='myshop.Delivery', verbose_name='Delivery')),
            ],
        ),
        migrations.AddField(
            model_name='orderitem',
            name='canceled',
            field=models.BooleanField(default=False, verbose_name='Item canceled '),
        ),
        migrations.AlterField(
            model_name='commodity',
            name='unit_price',
            field=django.db.models.fields.DecimalField(decimal_places=3, default=Decimal('0'), help_text='Net price for this product', max_digits=30),
        ),
        migrations.AlterField(
            model_name='orderpayment',
            name='amount',
            field=django.db.models.fields.DecimalField(decimal_places=2, default=Decimal('0'), help_text='How much was paid with this particular transfer.', max_digits=30),
        ),
        migrations.AlterField(
            model_name='smartcard',
            name='unit_price',
            field=django.db.models.fields.DecimalField(decimal_places=3, default=Decimal('0'), help_text='Net price for this product', max_digits=30),
        ),
        migrations.AlterField(
            model_name='smartphone',
            name='unit_price',
            field=django.db.models.fields.DecimalField(decimal_places=3, default=Decimal('0'), help_text='Net price for this product', max_digits=30),
        ),
        migrations.AddField(
            model_name='deliveryitem',
            name='item',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myshop.OrderItem', verbose_name='Ordered item'),
        ),
    ]


text:
function [day] = yr2day(yr)
% Convert time from Julian years (365.25 days) to days.
% Chad Greene 2012
day = yr*365.25 ;


text:
anthropocene
============

Some stuff for anthropocene paper


text:
"""This module is deprecated. Please use `airflow.gcp.hooks.base`."""
import warnings

from airflow.gcp.hooks.base import CloudBaseHook

warnings.warn(
    "This module is deprecated. Please use `airflow.gcp.hooks.base`.",
    DeprecationWarning, stacklevel=2
)

class GoogleCloudBaseHook(CloudBaseHook):
    """
    This class is deprecated. Please use `airflow.gcp.hooks.base.CloudBaseHook`.
    """
    def __init__(self, *args, **kwargs):
        warnings.warn(
            "This class is deprecated. Please use `airflow.gcp.hooks.base.CloudBaseHook`.",
            DeprecationWarning, stacklevel=2
        )
        super().__init__(*args, **kwargs)


text:
package org.monte.media.pbm;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import org.monte.media.ilbm.*;
import org.monte.media.io.ImageInputStreamAdapter;

public class PBMImageReader extends ImageReader {

    private ArrayList<ColorCyclingMemoryImageSource> images = null;

    public PBMImageReader(PBMImageReaderSpi originatingProvider) {
        super(originatingProvider);
    }

    @Override
    public int getNumImages(boolean allowSearch) throws IOException {
        if (allowSearch && images == null) {
            readImages();
        }
        return images.size();
    }

    @Override
    public int getWidth(int imageIndex) throws IOException {
        readImages();
        return images.get(imageIndex).getWidth();
    }

    @Override
    public int getHeight(int imageIndex) throws IOException {
        readImages();
        return images.get(imageIndex).getHeight();
    }

    @Override
    public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IOException {
        readImages();
        ColorCyclingMemoryImageSource iip = images.get(imageIndex);

        LinkedList<ImageTypeSpecifier> l = new LinkedList<ImageTypeSpecifier>();
        l.add(new ImageTypeSpecifier(iip.getColorModel(),
                iip.getColorModel().createCompatibleSampleModel(iip.getWidth(), iip.getHeight())));
        return l.iterator();
    }

    @Override
    public float getAspectRatio(int imageIndex) throws IOException {
        readImages();
        ColorCyclingMemoryImageSource mis=images.get(imageIndex);
        float ratio = (float) getWidth(imageIndex) / getHeight(imageIndex);
        if (mis.getProperties().containsKey("aspect")) {
            ratio*=(Double)mis.getProperties().get("aspect");
        }
        return ratio;
    }

    @Override
    public IIOMetadata getStreamMetadata() throws IOException {
        return null;
    }

    @Override
    public IIOMetadata getImageMetadata(int imageIndex) throws IOException {
        return null;
    }

    @Override
    public BufferedImage read(int imageIndex, ImageReadParam param)
            throws IOException {
        readImages();

        return images.get(imageIndex).toBufferedImage();
    }

    private void readImages() throws IOException {
        ImageInputStream in = (ImageInputStream) getInput();
        if (images == null) {
            in.seek(0);
            PBMDecoder d = new PBMDecoder(new ImageInputStreamAdapter(in));
            images = d.produce();
        }
    }
}


text:
package net.imagej.ops.geom.geom2d;

import java.util.List;

import net.imagej.ops.Ops;
import net.imagej.ops.special.function.AbstractUnaryFunctionOp;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imglib2.RealLocalizable;
import net.imglib2.roi.geometric.Polygon;
import net.imglib2.util.Pair;
import net.imglib2.util.ValuePair;

import org.scijava.plugin.Plugin;

/**
 * Maximum Feret of a polygon.
 *
 * @author Tim-Oliver Buchholz, University of Konstanz
 */
@Plugin(type = Ops.Geometric.MaximumFeret.class)
public class DefaultMaximumFeret extends AbstractUnaryFunctionOp<Polygon, Pair<RealLocalizable, RealLocalizable>>
		implements Ops.Geometric.MaximumFeret {

	private UnaryFunctionOp<Polygon, Polygon> function;

	@Override
	public void initialize() {
		function = Functions.unary(ops(), Ops.Geometric.ConvexHull.class, Polygon.class, in());
	}

	@Override
	public Pair<RealLocalizable, RealLocalizable> calculate(Polygon input) {
		final List<? extends RealLocalizable> points = function.calculate(input).getVertices();

		double distance = Double.NEGATIVE_INFINITY;
		RealLocalizable p0 = points.get(0);
		RealLocalizable p1 = points.get(0);
		for (int i = 0; i < points.size(); i++) {
			for (int j = i + 2; j < points.size(); j++) {
				final RealLocalizable tmpP0 = points.get(i);
				final RealLocalizable tmpP1 = points.get(j);

				final double tmp = Math.sqrt(Math.pow(tmpP0.getDoublePosition(0) - tmpP1.getDoublePosition(0), 2)
						+ Math.pow(tmpP0.getDoublePosition(1) - tmpP1.getDoublePosition(1), 2));

				if (tmp > distance) {
					distance = tmp;
					p0 = tmpP0;
					p1 = tmpP1;
				}
			}
		}

		return new ValuePair<>(p0, p1);
	}

}


text:
package org.spoutcraft.client.game;

import gnu.trove.map.hash.TIntObjectHashMap;

/**
 * An enum of the game modes.
 */
public enum GameMode {
    ADVENTURE(2),
    CREATIVE(1),
    HARDCORE(3),
    SURVIVAL(0);
    private final int value;
    private static final TIntObjectHashMap<GameMode> map = new TIntObjectHashMap<>();

    static {
        for (GameMode mode : GameMode.values()) {
            map.put(mode.value(), mode);
        }
    }

    private GameMode(int value) {
        this.value = value;
    }

    /**
     * Returns the numerical value associated to the game mode.
     *
     * @return The numerical value
     */
    public int value() {
        return value;
    }

    /**
     * Returns the game mode associated to the numerical value (ID).
     *
     * @param id The ID to lookup
     * @return The associated game mode
     */
    public static GameMode get(int id) {
        return map.get(id);
    }

    /**
     * Returns the game mode of the given name.
     *
     * @param name The name to lookup
     * @return The associated game mode
     */
    public static GameMode get(String name) {
        return valueOf(name.toUpperCase());
    }
}


text:
#include "BaseLibInternals.h"

extern
UINT64
_break (
  CHAR8 BreakCode
  );

/**
  Generates a breakpoint on the CPU.

  Generates a breakpoint on the CPU. The breakpoint must be implemented such
  that code can resume normal execution after the breakpoint.

**/
VOID
EFIAPI
CpuBreakpoint (
  VOID
  )
{
  _break (3);
}

/**
  Used to serialize load and store operations.

  All loads and stores that proceed calls to this function are guaranteed to be
  globally visible when this function returns.

**/
VOID
EFIAPI
MemoryFence (
  VOID
  )
{
}

/**
  Disables CPU interrupts.

**/
VOID
EFIAPI
DisableInterrupts (
  VOID
  )
{
  ASSERT (FALSE);
}

/**
  Enables CPU interrupts.

**/
VOID
EFIAPI
EnableInterrupts (
  VOID
  )
{
  ASSERT (FALSE);
}

/**
  Retrieves the current CPU interrupt state.

  Returns TRUE means interrupts are currently enabled. Otherwise,
  returns FALSE.

  @retval TRUE  CPU interrupts are enabled.
  @retval FALSE CPU interrupts are disabled.

**/
BOOLEAN
EFIAPI
GetInterruptState (
  VOID
  )
{
  ASSERT (FALSE);
  return FALSE;
}

/**
  Enables CPU interrupts for the smallest window required to capture any
  pending interrupts.

**/
VOID
EFIAPI
EnableDisableInterrupts (
  VOID
  )
{
  EnableInterrupts ();
  DisableInterrupts ();
}

/**
  Requests CPU to pause for a short period of time.

  Requests CPU to pause for a short period of time. Typically used in MP
  systems to prevent memory starvation while waiting for a spin lock.

**/
VOID
EFIAPI
CpuPause (
  VOID
  )
{
}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;

namespace Grpc.Core.Tests
{
    public class ContextPropagationTest
    {
        MockServiceHelper helper;
        Server server;
        Channel channel;

        [SetUp]
        public void Init()
        {
            helper = new MockServiceHelper();

            server = helper.GetServer();
            server.Start();
            channel = helper.GetChannel();
        }

        [TearDown]
        public void Cleanup()
        {
            channel.Dispose();
            server.ShutdownAsync().Wait();
        }

        [TestFixtureTearDown]
        public void CleanupClass()
        {
            GrpcEnvironment.Shutdown();
        }

        [Test]
        public async Task PropagateCancellation()
        {
            helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
            {
                // check that we didn't obtain the default cancellation token.
                Assert.IsTrue(context.CancellationToken.CanBeCanceled);
                return "PASS";
            });

            helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
            {
                var propagationToken = context.CreatePropagationToken();
                Assert.IsNotNull(propagationToken.ParentCall);

                var callOptions = new CallOptions(propagationToken: propagationToken);
                return await Calls.AsyncUnaryCall(helper.CreateUnaryCall(callOptions), "xyz");
            });

            var cts = new CancellationTokenSource();
            var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token)));
            await call.RequestStream.CompleteAsync();
            Assert.AreEqual("PASS", await call);
        }

        [Test]
        public async Task PropagateDeadline()
        {
            var deadline = DateTime.UtcNow.AddDays(7);
            helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
            {
                Assert.IsTrue(context.Deadline < deadline.AddMinutes(1));
                Assert.IsTrue(context.Deadline > deadline.AddMinutes(-1));
                return "PASS";
            });

            helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
            {
                Assert.Throws(typeof(ArgumentException), () =>
                {
                    // Trying to override deadline while propagating deadline from parent call will throw.
                    Calls.BlockingUnaryCall(helper.CreateUnaryCall(
                        new CallOptions(deadline: DateTime.UtcNow.AddDays(8),
                                        propagationToken: context.CreatePropagationToken())), "");
                });

                var callOptions = new CallOptions(propagationToken: context.CreatePropagationToken());
                return await Calls.AsyncUnaryCall(helper.CreateUnaryCall(callOptions), "xyz");
            });

            var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(deadline: deadline)));
            await call.RequestStream.CompleteAsync();
            Assert.AreEqual("PASS", await call);
        }

        [Test]
        public async Task SuppressDeadlinePropagation()
        {
            helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
            {
                Assert.AreEqual(DateTime.MaxValue, context.Deadline);
                return "PASS";
            });

            helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
            {
                Assert.IsTrue(context.CancellationToken.CanBeCanceled);

                var callOptions = new CallOptions(propagationToken: context.CreatePropagationToken(new ContextPropagationOptions(propagateDeadline: false)));
                return await Calls.AsyncUnaryCall(helper.CreateUnaryCall(callOptions), "xyz");
            });

            var cts = new CancellationTokenSource();
            var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(deadline: DateTime.UtcNow.AddDays(7))));
            await call.RequestStream.CompleteAsync();
            Assert.AreEqual("PASS", await call);
        }
    }
}


text:
#ifndef GrTextureStripAtlas_DEFINED
#define GrTextureStripAtlas_DEFINED

#include "SkBitmap.h"
#include "GrTHashCache.h"
#include "SkGr.h"
#include "SkTDArray.h"
#include "GrBinHashKey.h"

/**
 * Maintains a single large texture whose rows store many textures of a small fixed height,
 * stored in rows across the x-axis such that we can safely wrap/repeat them horizontally.
 */
class GrTextureStripAtlas {
public:
    /**
     * Descriptor struct which we'll use as a hash table key
     **/
    struct Desc {
        Desc() { memset(this, 0, sizeof(*this)); }
        uint16_t fWidth, fHeight, fRowHeight;
        GrPixelConfig fConfig;
        GrContext* fContext;
        const uint32_t* asKey() const { return reinterpret_cast<const uint32_t*>(this); }
    };

    /**
     * Try to find an atlas with the required parameters, creates a new one if necessary
     */
    static GrTextureStripAtlas* GetAtlas(const Desc& desc);

    ~GrTextureStripAtlas();

    /**
     * Add a texture to the atlas
     *  @param data Bitmap data to copy into the row
     *  @return The row index we inserted into, or -1 if we failed to find an open row. The caller
     *      is responsible for calling unlockRow() with this row index when it's done with it.
     */
    int lockRow(const SkBitmap& data);
    void unlockRow(int row);

    /**
     * These functions help turn an integer row index in [0, 1, 2, ... numRows] into a scalar y
     * texture coordinate in [0, 1] that we can use in a shader.
     *
     * If a regular texture access without using the atlas looks like:
     *
     *      texture2D(sampler, vec2(x, y))
     *
     * Then when using the atlas we'd replace it with:
     *
     *       texture2D(sampler, vec2(x, yOffset + y * scaleFactor))
     *
     * Where yOffset, returned by getYOffset(), is the offset to the start of the row within the
     * atlas and scaleFactor, returned by getVerticalScaleFactor(), is the y-scale of the row,
     * relative to the height of the overall atlas texture.
     */
    SkScalar getYOffset(int row) const { return SkIntToScalar(row) / fNumRows; }
    SkScalar getVerticalScaleFactor() const { return SkIntToScalar(fDesc.fRowHeight) / fDesc.fHeight; }

    GrContext* getContext() const { return fDesc.fContext; }
    GrTexture* getTexture() const { return fTexture; }

private:

    // Key to indicate an atlas row without any meaningful data stored in it
    const static uint32_t kEmptyAtlasRowKey = 0xffffffff;

    /**
     * The state of a single row in our cache, next/prev pointers allow these to be chained
     * together to represent LRU status
     */
    struct AtlasRow : public GrNoncopyable {
        AtlasRow() : fKey(kEmptyAtlasRowKey), fLocks(0), fNext(NULL), fPrev(NULL) { }
        // GenerationID of the bitmap that is represented by this row, 0xffffffff means "empty"
        uint32_t fKey;
        // How many times this has been locked (0 == unlocked)
        int32_t fLocks;
        // We maintain an LRU linked list between unlocked nodes with these pointers
        AtlasRow* fNext;
        AtlasRow* fPrev;
    };

    /**
     * We'll only allow construction via the static GrTextureStripAtlas::GetAtlas
     */
    GrTextureStripAtlas(Desc desc);

    void lockTexture();
    void unlockTexture();

    /**
     * Initialize our LRU list (if one already exists, clear it and start anew)
     */
    void initLRU();

    /**
     * Grabs the least recently used free row out of the LRU list, returns NULL if no rows are free.
     */
    AtlasRow* getLRU();

    void appendLRU(AtlasRow* row);
    void removeFromLRU(AtlasRow* row);

    /**
     * Searches the key table for a key and returns the index if found; if not found, it returns
     * the bitwise not of the index at which we could insert the key to maintain a sorted list.
     **/
    int searchByKey(uint32_t key);

    /**
     * Compare two atlas rows by key, so we can sort/search by key
     */
    static int compareKeys(const AtlasRow* lhs, const AtlasRow* rhs) {
        return lhs->fKey - rhs->fKey;
    }

#ifdef SK_DEBUG
    void validate();
#endif

    /**
     * Clean up callback registered with GrContext. Allows this class to
     * free up any allocated AtlasEntry and GrTextureStripAtlas objects
     */
    static void CleanUp(const GrContext* context, void* info);

    // Hash table entry for atlases
    class AtlasEntry;
    typedef GrTBinHashKey<AtlasEntry, sizeof(GrTextureStripAtlas::Desc)> AtlasHashKey;
    class AtlasEntry : public ::GrNoncopyable {
    public:
        AtlasEntry() : fAtlas(NULL) {}
        ~AtlasEntry() { SkDELETE(fAtlas); }
        int compare(const AtlasHashKey& key) const { return fKey.compare(key); }
        AtlasHashKey fKey;
        GrTextureStripAtlas* fAtlas;
    };

    static GrTHashTable<AtlasEntry, AtlasHashKey, 8>* gAtlasCache;

    static GrTHashTable<AtlasEntry, AtlasHashKey, 8>* GetCache();

    // We increment gCacheCount for each atlas
    static int32_t gCacheCount;

    // A unique ID for this texture (formed with: gCacheCount++), so we can be sure that if we
    // get a texture back from the texture cache, that it's the same one we last used.
    const int32_t fCacheKey;

    // Total locks on all rows (when this reaches zero, we can unlock our texture)
    int32_t fLockedRows;

    const Desc fDesc;
    const uint16_t fNumRows;
    GrTexture* fTexture;

    // Array of AtlasRows which store the state of all our rows. Stored in a contiguous array, in
    // order that they appear in our texture, this means we can subtract this pointer from a row
    // pointer to get its index in the texture, and can save storing a row number in AtlasRow.
    AtlasRow* fRows;

    // Head and tail for linked list of least-recently-used rows (front = least recently used).
    // Note that when a texture is locked, it gets removed from this list until it is unlocked.
    AtlasRow* fLRUFront;
    AtlasRow* fLRUBack;

    // A list of pointers to AtlasRows that currently contain cached images, sorted by key
    SkTDArray<AtlasRow*> fKeyTable;
};

#endif


text:
require 'spec_helper'

RSpec.describe ApplicationCable::Connection, :clean_gitlab_redis_shared_state do
  let(:session_id) { Rack::Session::SessionId.new('6919a6f1bb119dd7396fadc38fd18d0d') }

  before do
    Gitlab::Redis::SharedState.with do |redis|
      redis.set("session:gitlab:#{session_id.private_id}", Marshal.dump(session_hash))
    end

    cookies[Gitlab::Application.config.session_options[:key]] = session_id.public_id
  end

  context 'when user is logged in' do
    let(:user) { create(:user) }
    let(:session_hash) { { 'warden.user.user.key' => [[user.id], user.encrypted_password[0, 29]] } }

    it 'sets current_user' do
      connect

      expect(connection.current_user).to eq(user)
    end

    context 'with a stale password' do
      let(:partial_password_hash) { build(:user, password: 'some_old_password').encrypted_password[0, 29] }
      let(:session_hash) { { 'warden.user.user.key' => [[user.id], partial_password_hash] } }

      it 'sets current_user to nil' do
        connect

        expect(connection.current_user).to be_nil
      end
    end
  end

  context 'when user is not logged in' do
    let(:session_hash) { {} }

    it 'sets current_user to nil' do
      connect

      expect(connection.current_user).to be_nil
    end
  end
end


text:
using System;
using System.IO;
using Windows.ApplicationModel;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
using Windows.System.Profile;
using Newtonsoft.Json;

namespace FHSDK.Services.Device
{
    /// <summary>
    ///     Device info service for windows phone
    /// </summary>
    internal class DeviceService : DeviceServiceBase
    {
        public override string GetDeviceId()
        {
            var token = HardwareIdentification.GetPackageSpecificToken(null);
            var hardwareId = token.Id;

            var hasher = HashAlgorithmProvider.OpenAlgorithm("MD5");
            var hashed = hasher.HashData(hardwareId);

            var hashedString = CryptographicBuffer.EncodeToHexString(hashed);
            return hashedString;
        }

        public override AppProps ReadAppProps()
        {
            AppProps appProps;
            var isLocalDev = false;
            var file = GetFile(Constants.LocalConfigFileName);
            if (null != file)
            {
                isLocalDev = true;
            }
            else
            {
                file = GetFile(Constants.ConfigFileName);
            }
            if (null != file)
            {
                var json = FileIO.ReadTextAsync(file).AsTask().Result;
                appProps = JsonConvert.DeserializeObject<AppProps>(json);
                appProps.IsLocalDevelopment = isLocalDev;
            }
            else
            {
                throw new IOException("Can not find resource " + Constants.ConfigFileName);
            }
            return appProps;
        }

        public override string GetDeviceDestination()
        {
            return "windows";
        }

        public override string GetPackageDir()
        {
            return Package.Current.InstalledLocation.Path;
        }

        private static StorageFile GetFile(string fileName)
        {
            StorageFile file = null;
            try
            {
                var folder = Package.Current.InstalledLocation;
                file = folder.GetFileAsync(fileName).AsTask().Result;
            }
            catch (AggregateException)
            {
            }
            return file;
        }
    }
}


text:
layout: default
title: Blog
---

  This is a blog documenting my progress on the 20 percent time project. 20 percent time is a Google inspired idea where the students get a portion of their school day to work on a personal project to help better their own skills.

Posts

      {% for post in paginator.posts %}

            <time>{{ post.date | date: '%B %d, %Y' }}</time>  -

              {{ post.title }}

{{ post.content | strip_html | truncatewords: 40 }}

           Read More

      {% endfor %}

{% include pagination.html %}