text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/disk_cache/simple/simple_index_file.h"

#include <vector>

#include "base/file_util.h"
#include "base/files/memory_mapped_file.h"
#include "base/hash.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/pickle.h"
#include "base/single_thread_task_runner.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_restrictions.h"
#include "net/disk_cache/simple/simple_entry_format.h"
#include "net/disk_cache/simple/simple_index.h"
#include "net/disk_cache/simple/simple_synchronous_entry.h"
#include "net/disk_cache/simple/simple_util.h"
#include "third_party/zlib/zlib.h"

namespace disk_cache {
namespace {

const int kEntryFilesHashLength = 16;
const int kEntryFilesSuffixLength = 2;

const uint64 kMaxEntiresInIndex = 100000000;

const char kIndexFileName[] = "the-real-index";
const char kTempIndexFileName[] = "temp-index";

uint32 CalculatePickleCRC(const Pickle& pickle) {
  return crc32(crc32(0, Z_NULL, 0),
               reinterpret_cast<const Bytef*>(pickle.payload()),
               pickle.payload_size());
}

void DoomEntrySetReply(const net::CompletionCallback& reply_callback,
                       int result) {
  reply_callback.Run(result);
}

void WriteToDiskInternal(const base::FilePath& index_filename,
                         const base::FilePath& temp_index_filename,
                         scoped_ptr<Pickle> pickle,
                         const base::TimeTicks& start_time,
                         bool app_on_background) {
  int bytes_written = file_util::WriteFile(
      temp_index_filename,
      reinterpret_cast<const char*>(pickle->data()),
      pickle->size());
  DCHECK_EQ(bytes_written, implicit_cast<int>(pickle->size()));
  if (bytes_written != static_cast<int>(pickle->size())) {
    // TODO(felipeg): Add better error handling.
    LOG(ERROR) << "Could not write Simple Cache index to temporary file: "
               << temp_index_filename.value();
    base::DeleteFile(temp_index_filename, /* recursive = */ false);
  } else {
    // Swap temp and index_file.
    bool result = base::ReplaceFile(temp_index_filename, index_filename, NULL);
    DCHECK(result);
  }
  if (app_on_background) {
    UMA_HISTOGRAM_TIMES("SimpleCache.IndexWriteToDiskTime.Background",
                        (base::TimeTicks::Now() - start_time));
  } else {
    UMA_HISTOGRAM_TIMES("SimpleCache.IndexWriteToDiskTime.Foreground",
                        (base::TimeTicks::Now() - start_time));
  }
}

// Called for each cache directory traversal iteration.
void ProcessEntryFile(SimpleIndex::EntrySet* entries,
                      const base::FilePath& file_path) {
  static const size_t kEntryFilesLength =
      kEntryFilesHashLength + kEntryFilesSuffixLength;
  // Converting to std::string is OK since we never use UTF8 wide chars in our
  // file names.
  const base::FilePath::StringType base_name = file_path.BaseName().value();
  const std::string file_name(base_name.begin(), base_name.end());
  if (file_name.size() != kEntryFilesLength)
    return;
  const base::StringPiece hash_string(
      file_name.begin(), file_name.begin() + kEntryFilesHashLength);
  uint64 hash_key = 0;
  if (!simple_util::GetEntryHashKeyFromHexString(hash_string, &hash_key)) {
    LOG(WARNING) << "Invalid entry hash key filename while restoring index from"
                 << " disk: " << file_name;
    return;
  }

  base::PlatformFileInfo file_info;
  if (!file_util::GetFileInfo(file_path, &file_info)) {
    LOG(ERROR) << "Could not get file info for " << file_path.value();
    return;
  }
  base::Time last_used_time;
#if defined(OS_POSIX)
  // For POSIX systems, a last access time is available. However, it's not
  // guaranteed to be more accurate than mtime. It is no worse though.
  last_used_time = file_info.last_accessed;
#endif
  if (last_used_time.is_null())
    last_used_time = file_info.last_modified;

  int64 file_size = file_info.size;
  SimpleIndex::EntrySet::iterator it = entries->find(hash_key);
  if (it == entries->end()) {
    SimpleIndex::InsertInEntrySet(
        hash_key,
        EntryMetadata(last_used_time, file_size),
        entries);
  } else {
    // Summing up the total size of the entry through all the *_[0-2] files
    it->second.SetEntrySize(it->second.GetEntrySize() + file_size);
  }
}

}  // namespace

SimpleIndexLoadResult::SimpleIndexLoadResult() : did_load(false),
                                                 flush_required(false) {
}

SimpleIndexLoadResult::~SimpleIndexLoadResult() {
}

void SimpleIndexLoadResult::Reset() {
  did_load = false;
  flush_required = false;
  entries.clear();
}

SimpleIndexFile::IndexMetadata::IndexMetadata() :
    magic_number_(kSimpleIndexMagicNumber),
    version_(kSimpleVersion),
    number_of_entries_(0),
    cache_size_(0) {}

SimpleIndexFile::IndexMetadata::IndexMetadata(
    uint64 number_of_entries, uint64 cache_size) :
    magic_number_(kSimpleIndexMagicNumber),
    version_(kSimpleVersion),
    number_of_entries_(number_of_entries),
    cache_size_(cache_size) {}

void SimpleIndexFile::IndexMetadata::Serialize(Pickle* pickle) const {
  DCHECK(pickle);
  pickle->WriteUInt64(magic_number_);
  pickle->WriteUInt32(version_);
  pickle->WriteUInt64(number_of_entries_);
  pickle->WriteUInt64(cache_size_);
}

bool SimpleIndexFile::IndexMetadata::Deserialize(PickleIterator* it) {
  DCHECK(it);
  return it->ReadUInt64(&magic_number_) &&
      it->ReadUInt32(&version_) &&
      it->ReadUInt64(&number_of_entries_)&&
      it->ReadUInt64(&cache_size_);
}

bool SimpleIndexFile::IndexMetadata::CheckIndexMetadata() {
  return number_of_entries_ <= kMaxEntiresInIndex &&
      magic_number_ == disk_cache::kSimpleIndexMagicNumber &&
      version_ == disk_cache::kSimpleVersion;
}

SimpleIndexFile::SimpleIndexFile(
    base::SingleThreadTaskRunner* cache_thread,
    base::TaskRunner* worker_pool,
    const base::FilePath& cache_directory)
    : cache_thread_(cache_thread),
      worker_pool_(worker_pool),
      cache_directory_(cache_directory),
      index_file_(cache_directory_.AppendASCII(kIndexFileName)),
      temp_index_file_(cache_directory_.AppendASCII(kTempIndexFileName)) {
}

SimpleIndexFile::~SimpleIndexFile() {}

void SimpleIndexFile::LoadIndexEntries(base::Time cache_last_modified,
                                       const base::Closure& callback,
                                       SimpleIndexLoadResult* out_result) {
  base::Closure task = base::Bind(&SimpleIndexFile::SyncLoadIndexEntries,
                                  cache_last_modified, cache_directory_,
                                  index_file_, out_result);
  worker_pool_->PostTaskAndReply(FROM_HERE, task, callback);
}

void SimpleIndexFile::WriteToDisk(const SimpleIndex::EntrySet& entry_set,
                                  uint64 cache_size,
                                  const base::TimeTicks& start,
                                  bool app_on_background) {
  IndexMetadata index_metadata(entry_set.size(), cache_size);
  scoped_ptr<Pickle> pickle = Serialize(index_metadata, entry_set);
  cache_thread_->PostTask(FROM_HERE, base::Bind(
      &WriteToDiskInternal,
      index_file_,
      temp_index_file_,
      base::Passed(&pickle),
      base::TimeTicks::Now(),
      app_on_background));
}

void SimpleIndexFile::DoomEntrySet(
    scoped_ptr<std::vector<uint64> > entry_hashes,
    const net::CompletionCallback& reply_callback) {
  PostTaskAndReplyWithResult(
      worker_pool_,
      FROM_HERE,
      base::Bind(&SimpleSynchronousEntry::DoomEntrySet,
                 base::Passed(entry_hashes.Pass()), cache_directory_),
      base::Bind(&DoomEntrySetReply, reply_callback));
}

// static
void SimpleIndexFile::SyncLoadIndexEntries(
    base::Time cache_last_modified,
    const base::FilePath& cache_directory,
    const base::FilePath& index_file_path,
    SimpleIndexLoadResult* out_result) {
  // TODO(felipeg): probably could load a stale index and use it for something.
  const SimpleIndex::EntrySet& entries = out_result->entries;

  const bool index_file_exists = base::PathExists(index_file_path);

  // Used in histograms. Please only add new values at the end.
  enum {
    INDEX_STATE_CORRUPT = 0,
    INDEX_STATE_STALE = 1,
    INDEX_STATE_FRESH = 2,
    INDEX_STATE_FRESH_CONCURRENT_UPDATES = 3,
    INDEX_STATE_MAX = 4,
  } index_file_state;

  // Only load if the index is not stale.
  if (IsIndexFileStale(cache_last_modified, index_file_path)) {
    index_file_state = INDEX_STATE_STALE;
  } else {
    index_file_state = INDEX_STATE_FRESH;
    base::Time latest_dir_mtime;
    if (simple_util::GetMTime(cache_directory, &latest_dir_mtime) &&
        IsIndexFileStale(latest_dir_mtime, index_file_path)) {
      // A file operation has updated the directory since we last looked at it
      // during backend initialization.
      index_file_state = INDEX_STATE_FRESH_CONCURRENT_UPDATES;
    }

    const base::TimeTicks start = base::TimeTicks::Now();
    SyncLoadFromDisk(index_file_path, out_result);
    UMA_HISTOGRAM_TIMES("SimpleCache.IndexLoadTime",
                        base::TimeTicks::Now() - start);
    UMA_HISTOGRAM_COUNTS("SimpleCache.IndexEntriesLoaded",
                         out_result->did_load ? entries.size() : 0);
    if (!out_result->did_load)
      index_file_state = INDEX_STATE_CORRUPT;
  }
  UMA_HISTOGRAM_ENUMERATION("SimpleCache.IndexFileStateOnLoad",
                            index_file_state,
                            INDEX_STATE_MAX);

  if (!out_result->did_load) {
    const base::TimeTicks start = base::TimeTicks::Now();
    SyncRestoreFromDisk(cache_directory, index_file_path, out_result);
    UMA_HISTOGRAM_MEDIUM_TIMES("SimpleCache.IndexRestoreTime",
                        base::TimeTicks::Now() - start);
    UMA_HISTOGRAM_COUNTS("SimpleCache.IndexEntriesRestored",
                         entries.size());
  }

  // Used in histograms. Please only add new values at the end.
  enum {
    INITIALIZE_METHOD_RECOVERED = 0,
    INITIALIZE_METHOD_LOADED = 1,
    INITIALIZE_METHOD_NEWCACHE = 2,
    INITIALIZE_METHOD_MAX = 3,
  };
  int initialize_method;
  if (index_file_exists) {
    if (out_result->flush_required)
      initialize_method = INITIALIZE_METHOD_RECOVERED;
    else
      initialize_method = INITIALIZE_METHOD_LOADED;
  } else {
    UMA_HISTOGRAM_COUNTS("SimpleCache.IndexCreatedEntryCount",
                         entries.size());
    initialize_method = INITIALIZE_METHOD_NEWCACHE;
  }

  UMA_HISTOGRAM_ENUMERATION("SimpleCache.IndexInitializeMethod",
                            initialize_method, INITIALIZE_METHOD_MAX);
}

// static
void SimpleIndexFile::SyncLoadFromDisk(const base::FilePath& index_filename,
                                       SimpleIndexLoadResult* out_result) {
  out_result->Reset();

  base::MemoryMappedFile index_file_map;
  if (!index_file_map.Initialize(index_filename)) {
    LOG(WARNING) << "Could not map Simple Index file.";
    base::DeleteFile(index_filename, false);
    return;
  }

  SimpleIndexFile::Deserialize(
      reinterpret_cast<const char*>(index_file_map.data()),
      index_file_map.length(), out_result);

  if (!out_result->did_load)
    base::DeleteFile(index_filename, false);
}

// static
scoped_ptr<Pickle> SimpleIndexFile::Serialize(
    const SimpleIndexFile::IndexMetadata& index_metadata,
    const SimpleIndex::EntrySet& entries) {
  scoped_ptr<Pickle> pickle(new Pickle(sizeof(SimpleIndexFile::PickleHeader)));

  index_metadata.Serialize(pickle.get());
  for (SimpleIndex::EntrySet::const_iterator it = entries.begin();
       it != entries.end(); ++it) {
    pickle->WriteUInt64(it->first);
    it->second.Serialize(pickle.get());
  }
  SimpleIndexFile::PickleHeader* header_p =
      pickle->headerT<SimpleIndexFile::PickleHeader>();
  header_p->crc = CalculatePickleCRC(*pickle);
  return pickle.Pass();
}

// static
void SimpleIndexFile::Deserialize(const char* data, int data_len,
                                  SimpleIndexLoadResult* out_result) {
  DCHECK(data);

  out_result->Reset();
  SimpleIndex::EntrySet* entries = &out_result->entries;

  Pickle pickle(data, data_len);
  if (!pickle.data()) {
    LOG(WARNING) << "Corrupt Simple Index File.";
    return;
  }

  PickleIterator pickle_it(pickle);

  SimpleIndexFile::PickleHeader* header_p =
      pickle.headerT<SimpleIndexFile::PickleHeader>();
  const uint32 crc_read = header_p->crc;
  const uint32 crc_calculated = CalculatePickleCRC(pickle);

  if (crc_read != crc_calculated) {
    LOG(WARNING) << "Invalid CRC in Simple Index file.";
    return;
  }

  SimpleIndexFile::IndexMetadata index_metadata;
  if (!index_metadata.Deserialize(&pickle_it)) {
    LOG(ERROR) << "Invalid index_metadata on Simple Cache Index.";
    return;
  }

  if (!index_metadata.CheckIndexMetadata()) {
    LOG(ERROR) << "Invalid index_metadata on Simple Cache Index.";
    return;
  }

#if !defined(OS_WIN)
  // TODO(gavinp): Consider using std::unordered_map.
  entries->resize(index_metadata.GetNumberOfEntries() + kExtraSizeForMerge);
#endif
  while (entries->size() < index_metadata.GetNumberOfEntries()) {
    uint64 hash_key;
    EntryMetadata entry_metadata;
    if (!pickle_it.ReadUInt64(&hash_key) ||
        !entry_metadata.Deserialize(&pickle_it)) {
      LOG(WARNING) << "Invalid EntryMetadata in Simple Index file.";
      entries->clear();
      return;
    }
    SimpleIndex::InsertInEntrySet(hash_key, entry_metadata, entries);
  }

  out_result->did_load = true;
}

// static
void SimpleIndexFile::SyncRestoreFromDisk(
    const base::FilePath& cache_directory,
    const base::FilePath& index_file_path,
    SimpleIndexLoadResult* out_result) {
  LOG(INFO) << "Simple Cache Index is being restored from disk.";
  base::DeleteFile(index_file_path, /* recursive = */ false);
  out_result->Reset();
  SimpleIndex::EntrySet* entries = &out_result->entries;

  // TODO(felipeg,gavinp): Fix this once we have a one-file per entry format.
  COMPILE_ASSERT(kSimpleEntryFileCount == 3,
                 file_pattern_must_match_file_count);

  const bool did_succeed = TraverseCacheDirectory(
      cache_directory, base::Bind(&ProcessEntryFile, entries));
  if (!did_succeed) {
    LOG(ERROR) << "Could not reconstruct index from disk";
    return;
  }
  out_result->did_load = true;
  // When we restore from disk we write the merged index file to disk right
  // away, this might save us from having to restore again next time.
  out_result->flush_required = true;
}

// static
bool SimpleIndexFile::IsIndexFileStale(base::Time cache_last_modified,
                                       const base::FilePath& index_file_path) {
  base::Time index_mtime;
  if (!simple_util::GetMTime(index_file_path, &index_mtime))
    return true;
  return index_mtime < cache_last_modified;
}

}  // namespace disk_cache


text:
package services.reporting

import org.specs2.mutable.Specification
import org.specs2.execute.Result
import java.io.FileOutputStream

class ReportRunnerSpec extends Specification with ReportFormats {

  val runner = new ReportRunner with JRXmlReportCompiler with ClasspathResourceReportLoader

  "simple report" in {
    runReport("/order2.jrxml", EmptyExpression, XmlParameterExpression("conf/order2.xml", "/order/items/product"))

  }

  def runReport(source: String, parametersExpression: Expression, dataSourceExpression: DataSourceExpression): Result = {

    runner.runReportT(source)(PdfDS, parametersExpression, dataSourceExpression).run.toEither match {
      case Left(e) => failure(e.getMessage)
      case Right(pdf) =>
        val fos = new FileOutputStream("target/order2.pdf")
        fos.write(pdf)
        fos.close()
        success
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import { createEpicMiddleware } from 'redux-observable';

import reducers from '../src/reducers';
import rootEpic from '../src/epics';

import delay from '../src/lib/delay';

const VAULT_HOST = 'http://127.0.0.1:8200';
global.nock = require('nock');
global.vaultObservable = require('../src/vault-observable');
global.chai = require('chai');
global.expect = chai.expect;
global.assert = chai.assert;

global.vaultConfig = {
  uri: VAULT_HOST,
  auth: {
    token: 'token'
  }
};
global.nocker = nock(VAULT_HOST);

global.storeFactory = () =>
  createStore(
    combineReducers({
      ...reducers,
      form: formReducer
    }),
    compose(applyMiddleware(createEpicMiddleware(rootEpic)))
  );

global.delay = delay;
global.rootEpic = rootEpic;

global.vaultConfig = {
  url: null,
  auth: {
    token: null
  },
  secret: {
    generic: {
      mount: '/secret'
    }
  }
};

global.initVault = function() {
  vaultConfig.auth.token = process.env.VAULT_TOKEN;
  if (!vaultConfig.auth.token)
    throw Error('VAULT_TOKEN env variable is not set');
  vaultConfig.url = process.env.VAULT_ADDR;
  if (!vaultConfig.url) throw Error('VAULT_ADDR env variable is not set');
  vaultConfig.secret.generic.mount =
    process.env.VAULT_SECRET_GENERIC_MOUNT || vaultConfig.secret.generic.mount;
};


text:
// source:

package nl.uva.vlet.util.bdii;

import java.net.URISyntaxException;
import java.util.ArrayList;

import javax.naming.NamingException;

import nl.uva.vlet.Global;
import nl.uva.vlet.exception.VlException;
import nl.uva.vlet.exception.VlServerException;
import nl.uva.vlet.util.bdii.BDIIQuery;
import nl.uva.vlet.util.bdii.BdiiException;
import nl.uva.vlet.util.bdii.BdiiService;
import nl.uva.vlet.util.bdii.StorageArea;
import nl.uva.vlet.util.bdii.ServiceInfo;
import nl.uva.vlet.util.bdii.info.glue.GlueObject;

public class TestGetLFCs
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        Global.setDebug(true);

        getSEs();
    }

    public static void getSEs()
    {

        try
        {
            BdiiService bdii=new BdiiService("bdii.grid.sara.nl",2170);
            ArrayList<ServiceInfo> sas = bdii.getLFCsforVO("pvier");
            sas.get(0).getHost();
         //   System.err.println("LFC VO path ="+bdii.getLFCVoPathFor("lfc.grid.sara.nl","pvier"));
        }

        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}


text:
<?php

namespace Mtt\UserBundle\DependencyInjection\Security\Factory;

use Mtt\UserBundle\Security\Authentication\Provider\WsseAuthenticationProvider;
use Mtt\UserBundle\Security\Http\Firewall\WsseAuthenticationListener;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class WsseFactory implements SecurityFactoryInterface
{
    /**
     * @param ContainerBuilder $container
     * @param $id
     * @param $config
     * @param $userProvider
     * @param $defaultEntryPoint
     *
     * @return array
     */
    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {
        $providerId = 'security.authentication.provider.wsse.' . $id;
        $container
            ->setDefinition($providerId, new ChildDefinition(WsseAuthenticationProvider::class))
            ->setArgument(0, new Reference($userProvider))
        ;

        $listenerId = 'security.authentication.listener.wsse.' . $id;
        $container->setDefinition($listenerId, new ChildDefinition(WsseAuthenticationListener::class));

        return [$providerId, $listenerId, $defaultEntryPoint];
    }

    /**
     * @return string
     */
    public function getPosition()
    {
        return 'pre_auth';
    }

    /**
     * @return string
     */
    public function getKey()
    {
        return 'wsse';
    }

    /**
     * @param NodeDefinition $builder
     */
    public function addConfiguration(NodeDefinition $builder)
    {
        $builder
            ->children()
                ->scalarNode('lifetime')->defaultValue(300)->end()
            ->end();
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Foundation 5</title>

<link rel="stylesheet"
	href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.3/css/normalize.min.css">
<link rel="stylesheet"
	href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.3/css/foundation.min.css">
<link
	href='http://cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/foundation-icons.css'
	rel='stylesheet' type='text/css'>

Link 1

Link 2

Link 3

Link 4

This is a content section.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation
				eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore
				aliqua non est magna in labore pig pork biltong. Eiusmod swine spare
				ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned
				beef.

This is a content section.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation
				eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore
				aliqua non est magna in labore pig pork biltong. Eiusmod swine spare
				ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned
				beef.

This is a content section.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation
				eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore
				aliqua non est magna in labore pig pork biltong. Eiusmod swine spare
				ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned
				beef.

Get in touch!

We'd love to hear from you, you attractive person you.

						Contact Us

© Copyright no one at all. Go to town.

Link 1

Link 2

Link 3

Link 4


text:
AutobahnPython API Reference
============================

The AutobahnPython API reference is available [online](http://autobahn.ws/python/reference).

The documentation is generated automatically from the Python source file via [Sphinx](http://sphinx.pocoo.org/).

To generate the documentation yourself, you will need to install Sphinx:

	easy_install sphinx
   easy_install repoze.sphinx.autointerface

and then

	cd doc
	make html

This will create the documentation under

	_build/html

To adjust the AutobahnPython version printed in the documentation, edit

	conf.py

for

	version = '0.5'
	release = '0.5.2'


text:
package pe.fu.rbac.user.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import pe.fu.module.db.mybatis.BaseMapper;
import pe.fu.rbac.user.bean.RbacAssoUserRole;

@Repository
public interface RbacAssoUserRoleMapper extends BaseMapper<RbacAssoUserRole>{

	/**
	 * 删除用户拥有的角色
	 *
	 * @param userId
	 */
	int deleteByUserId(@Param(value = "userId") Long userId);

	/**
	 * 批量插入
	 *
	 * @param assoUserRoles
	 */
	void insertByBatch(List<RbacAssoUserRole> assoUserRoles);
	/**
	 * 通过用户ID查询角色
	 * @param userId
	 * @return
	 */
	List<RbacAssoUserRole> selectByUserId(@Param(value = "userId") Long userId);
	/**
	 * 通过角色ID查询用户
	 * @param roleId
	 * @return
	 */
	List<RbacAssoUserRole> selectByRoleId(@Param(value = "roleId") Long roleId);
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Classes (state-machine O.2 API)</title>
<meta name="date" content="2017-02-12">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

BehaviorCollectionFactory

ObservableStateMachine

OnEntryAndExitStateMachine

OnEntryStateMachine

OnExitStateMachine

PerStateReactingStateMachine

StateMachine


text:
import sys

from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy import exc
from sqlalchemy import func
from sqlalchemy import INT
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import VARCHAR
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import ne_
from sqlalchemy.testing.engines import testing_engine
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table

users, metadata = None, None

class TransactionTest(fixtures.TestBase):
    __backend__ = True

    @classmethod
    def setup_class(cls):
        global users, metadata
        metadata = MetaData()
        users = Table(
            "query_users",
            metadata,
            Column("user_id", INT, primary_key=True),
            Column("user_name", VARCHAR(20)),
            test_needs_acid=True,
        )
        users.create(testing.db)

    def teardown(self):
        testing.db.execute(users.delete()).close()

    @classmethod
    def teardown_class(cls):
        users.drop(testing.db)

    def test_commits(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction.commit()

        transaction = connection.begin()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.commit()

        transaction = connection.begin()
        result = connection.exec_driver_sql("select * from query_users")
        assert len(result.fetchall()) == 3
        transaction.commit()
        connection.close()

    def test_rollback(self):
        """test a basic rollback"""

        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.rollback()
        result = connection.exec_driver_sql("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    def test_raise(self):
        connection = testing.db.connect()

        transaction = connection.begin()
        try:
            connection.execute(users.insert(), user_id=1, user_name="user1")
            connection.execute(users.insert(), user_id=2, user_name="user2")
            connection.execute(users.insert(), user_id=1, user_name="user3")
            transaction.commit()
            assert False
        except Exception as e:
            print("Exception: ", e)
            transaction.rollback()

        result = connection.exec_driver_sql("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    def test_nested_rollback(self):
        connection = testing.db.connect()
        try:
            transaction = connection.begin()
            try:
                connection.execute(
                    users.insert(), user_id=1, user_name="user1"
                )
                connection.execute(
                    users.insert(), user_id=2, user_name="user2"
                )
                connection.execute(
                    users.insert(), user_id=3, user_name="user3"
                )
                trans2 = connection.begin()
                try:
                    connection.execute(
                        users.insert(), user_id=4, user_name="user4"
                    )
                    connection.execute(
                        users.insert(), user_id=5, user_name="user5"
                    )
                    raise Exception("uh oh")
                    trans2.commit()
                except Exception:
                    trans2.rollback()
                    raise
                transaction.rollback()
            except Exception:
                transaction.rollback()
                raise
        except Exception as e:
            try:
                # and not "This transaction is inactive"
                # comment moved here to fix pep8
                assert str(e) == "uh oh"
            finally:
                connection.close()

    def test_branch_nested_rollback(self):
        connection = testing.db.connect()
        try:
            connection.begin()
            branched = connection.connect()
            assert branched.in_transaction()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            assert not connection.in_transaction()

            assert_raises_message(
                exc.InvalidRequestError,
                "This connection is on an inactive transaction.  Please",
                connection.exec_driver_sql,
                "select 1",
            )

        finally:
            connection.close()

    def test_inactive_due_to_subtransaction_no_commit(self):
        connection = testing.db.connect()
        trans = connection.begin()
        trans2 = connection.begin()
        trans2.rollback()
        assert_raises_message(
            exc.InvalidRequestError,
            "This transaction is inactive",
            trans.commit,
        )

    def test_branch_autorollback(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            try:
                branched.execute(users.insert(), user_id=1, user_name="user1")
            except exc.DBAPIError:
                pass
        finally:
            connection.close()

    def test_branch_orig_rollback(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin()
            assert branched.in_transaction()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            eq_(
                connection.exec_driver_sql(
                    "select count(*) from query_users"
                ).scalar(),
                1,
            )

        finally:
            connection.close()

    def test_branch_autocommit(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            branched.execute(users.insert(), user_id=1, user_name="user1")
        finally:
            connection.close()
        eq_(
            testing.db.execute(
                text("select count(*) from query_users")
            ).scalar(),
            1,
        )

    @testing.requires.savepoints
    def test_branch_savepoint_rollback(self):
        connection = testing.db.connect()
        try:
            trans = connection.begin()
            branched = connection.connect()
            assert branched.in_transaction()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin_nested()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            assert connection.in_transaction()
            trans.commit()
            eq_(
                connection.exec_driver_sql(
                    "select count(*) from query_users"
                ).scalar(),
                1,
            )

        finally:
            connection.close()

    @testing.requires.two_phase_transactions
    def test_branch_twophase_rollback(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            assert not branched.in_transaction()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin_twophase()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            assert not connection.in_transaction()
            eq_(
                connection.exec_driver_sql(
                    "select count(*) from query_users"
                ).scalar(),
                1,
            )

        finally:
            connection.close()

    @testing.requires.python2
    @testing.requires.savepoints_w_release
    def test_savepoint_release_fails_warning(self):
        with testing.db.connect() as connection:
            connection.begin()

            with expect_warnings(
                "An exception has occurred during handling of a previous "
                "exception.  The previous exception "
                r"is:.*..SQL\:.*RELEASE SAVEPOINT"
            ):

                def go():
                    with connection.begin_nested() as savepoint:
                        connection.dialect.do_release_savepoint(
                            connection, savepoint._savepoint
                        )

                assert_raises_message(
                    exc.DBAPIError, r".*SQL\:.*ROLLBACK TO SAVEPOINT", go
                )

    def test_retains_through_options(self):
        connection = testing.db.connect()
        try:
            transaction = connection.begin()
            connection.execute(users.insert(), user_id=1, user_name="user1")
            conn2 = connection.execution_options(dummy=True)
            conn2.execute(users.insert(), user_id=2, user_name="user2")
            transaction.rollback()
            eq_(
                connection.exec_driver_sql(
                    "select count(*) from query_users"
                ).scalar(),
                0,
            )
        finally:
            connection.close()

    def test_nesting(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans2 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        connection.execute(users.insert(), user_id=5, user_name="user5")
        trans2.commit()
        transaction.rollback()
        self.assert_(
            connection.exec_driver_sql(
                "select count(*) from " "query_users"
            ).scalar()
            == 0
        )
        result = connection.exec_driver_sql("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    def test_with_interface(self):
        connection = testing.db.connect()
        trans = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        try:
            connection.execute(users.insert(), user_id=2, user_name="user2.5")
        except Exception:
            trans.__exit__(*sys.exc_info())

        assert not trans.is_active
        self.assert_(
            connection.exec_driver_sql(
                "select count(*) from " "query_users"
            ).scalar()
            == 0
        )

        trans = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans.__exit__(None, None, None)
        assert not trans.is_active
        self.assert_(
            connection.exec_driver_sql(
                "select count(*) from " "query_users"
            ).scalar()
            == 1
        )
        connection.close()

    def test_close(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans2 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        connection.execute(users.insert(), user_id=5, user_name="user5")
        assert connection.in_transaction()
        trans2.close()
        assert connection.in_transaction()
        transaction.commit()
        assert not connection.in_transaction()
        self.assert_(
            connection.exec_driver_sql(
                "select count(*) from " "query_users"
            ).scalar()
            == 5
        )
        result = connection.exec_driver_sql("select * from query_users")
        assert len(result.fetchall()) == 5
        connection.close()

    def test_close2(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans2 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        connection.execute(users.insert(), user_id=5, user_name="user5")
        assert connection.in_transaction()
        trans2.close()
        assert connection.in_transaction()
        transaction.close()
        assert not connection.in_transaction()
        self.assert_(
            connection.exec_driver_sql(
                "select count(*) from " "query_users"
            ).scalar()
            == 0
        )
        result = connection.exec_driver_sql("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    @testing.requires.savepoints
    def test_nested_subtransaction_rollback(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans2 = connection.begin_nested()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        trans2.rollback()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (3,)],
        )
        connection.close()

    @testing.requires.savepoints
    def test_nested_subtransaction_commit(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans2 = connection.begin_nested()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        trans2.commit()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (2,), (3,)],
        )
        connection.close()

    @testing.requires.savepoints
    def test_rollback_to_subtransaction(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans2 = connection.begin_nested()
        connection.execute(users.insert(), user_id=2, user_name="user2")

        trans3 = connection.begin()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans3.rollback()

        assert_raises_message(
            exc.InvalidRequestError,
            "This connection is on an inactive savepoint transaction.",
            connection.exec_driver_sql,
            "select 1",
        )
        trans2.rollback()

        connection.execute(users.insert(), user_id=4, user_name="user4")
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (4,)],
        )
        connection.close()

    @testing.requires.two_phase_transactions
    def test_two_phase_transaction(self):
        connection = testing.db.connect()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction.prepare()
        transaction.commit()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        transaction.commit()
        transaction.close()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.rollback()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        transaction.prepare()
        transaction.rollback()
        transaction.close()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (2,)],
        )
        connection.close()

    # PG emergency shutdown:
    # select * from pg_prepared_xacts
    # ROLLBACK PREPARED '<xid>'
    # MySQL emergency shutdown:
    # for arg in `mysql -u root -e "xa recover" | cut -c 8-100 |
    #     grep sa`; do mysql -u root -e "xa rollback '$arg'"; done
    @testing.crashes("mysql", "Crashing on 5.5, not worth it")
    @testing.requires.skip_mysql_on_windows
    @testing.requires.two_phase_transactions
    @testing.requires.savepoints
    def test_mixed_two_phase_transaction(self):
        connection = testing.db.connect()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction2 = connection.begin()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        transaction3 = connection.begin_nested()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction4 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        transaction4.commit()
        transaction3.rollback()
        connection.execute(users.insert(), user_id=5, user_name="user5")
        transaction2.commit()
        transaction.prepare()
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (2,), (5,)],
        )
        connection.close()

    @testing.requires.two_phase_transactions
    @testing.requires.two_phase_recovery
    def test_two_phase_recover(self):

        # MySQL recovery doesn't currently seem to work correctly
        # Prepared transactions disappear when connections are closed
        # and even when they aren't it doesn't seem possible to use the
        # recovery id.

        connection = testing.db.connect()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction.prepare()
        connection.invalidate()

        connection2 = testing.db.connect()
        eq_(
            connection2.execution_options(autocommit=True)
            .execute(select([users.c.user_id]).order_by(users.c.user_id))
            .fetchall(),
            [],
        )
        recoverables = connection2.recover_twophase()
        assert transaction.xid in recoverables
        connection2.commit_prepared(transaction.xid, recover=True)
        eq_(
            connection2.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,)],
        )
        connection2.close()

    @testing.requires.two_phase_transactions
    def test_multiple_two_phase(self):
        conn = testing.db.connect()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=1, user_name="user1")
        xa.prepare()
        xa.commit()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=2, user_name="user2")
        xa.prepare()
        xa.rollback()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=3, user_name="user3")
        xa.rollback()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=4, user_name="user4")
        xa.prepare()
        xa.commit()
        result = conn.execute(
            select([users.c.user_name]).order_by(users.c.user_id)
        )
        eq_(result.fetchall(), [("user1",), ("user4",)])
        conn.close()

    @testing.requires.two_phase_transactions
    def test_reset_rollback_two_phase_no_rollback(self):
        # test [ticket:2907], essentially that the
        # TwoPhaseTransaction is given the job of "reset on return"
        # so that picky backends like MySQL correctly clear out
        # their state when a connection is closed without handling
        # the transaction explicitly.

        eng = testing_engine()

        # MySQL raises if you call straight rollback() on
        # a connection with an XID present
        @event.listens_for(eng, "invalidate")
        def conn_invalidated(dbapi_con, con_record, exception):
            dbapi_con.close()
            raise exception

        with eng.connect() as conn:
            rec = conn.connection._connection_record
            raw_dbapi_con = rec.connection
            conn.begin_twophase()
            conn.execute(users.insert(), user_id=1, user_name="user1")

        assert rec.connection is raw_dbapi_con

        with eng.connect() as conn:
            result = conn.execute(
                select([users.c.user_name]).order_by(users.c.user_id)
            )
            eq_(result.fetchall(), [])

class ResetAgentTest(fixtures.TestBase):
    __backend__ = True

    def test_begin_close(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            assert connection.connection._reset_agent is trans
        assert not trans.is_active

    def test_begin_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            assert connection.connection._reset_agent is trans
            trans.rollback()
            assert connection.connection._reset_agent is None

    def test_begin_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.savepoints
    def test_begin_nested_close(self):
        with testing.db.connect() as connection:
            trans = connection.begin_nested()
            assert connection.connection._reset_agent is trans
        assert not trans.is_active

    @testing.requires.savepoints
    def test_begin_begin_nested_close(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin_nested()
            assert connection.connection._reset_agent is trans
        assert trans2.is_active  # was never closed
        assert not trans.is_active

    @testing.requires.savepoints
    def test_begin_begin_nested_rollback_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin_nested()
            assert connection.connection._reset_agent is trans
            trans2.rollback()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.savepoints
    def test_begin_begin_nested_rollback_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin_nested()
            assert connection.connection._reset_agent is trans
            trans2.rollback()
            assert connection.connection._reset_agent is trans
            trans.rollback()
            assert connection.connection._reset_agent is None

    def test_begin_begin_rollback_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin()
            assert connection.connection._reset_agent is trans
            trans2.rollback()
            assert connection.connection._reset_agent is None
            trans.rollback()
            assert connection.connection._reset_agent is None

    def test_begin_begin_commit_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin()
            assert connection.connection._reset_agent is trans
            trans2.commit()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.two_phase_transactions
    def test_reset_via_agent_begin_twophase(self):
        with testing.db.connect() as connection:
            trans = connection.begin_twophase()
            assert connection.connection._reset_agent is trans

    @testing.requires.two_phase_transactions
    def test_reset_via_agent_begin_twophase_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin_twophase()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.two_phase_transactions
    def test_reset_via_agent_begin_twophase_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin_twophase()
            assert connection.connection._reset_agent is trans
            trans.rollback()
            assert connection.connection._reset_agent is None

class AutoRollbackTest(fixtures.TestBase):
    __backend__ = True

    @classmethod
    def setup_class(cls):
        global metadata
        metadata = MetaData()

    @classmethod
    def teardown_class(cls):
        metadata.drop_all(testing.db)

    def test_rollback_deadlock(self):
        """test that returning connections to the pool clears any object
        locks."""

        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        users = Table(
            "deadlock_users",
            metadata,
            Column("user_id", INT, primary_key=True),
            Column("user_name", VARCHAR(20)),
            test_needs_acid=True,
        )
        users.create(conn1)
        conn1.exec_driver_sql("select * from deadlock_users")
        conn1.close()

        # without auto-rollback in the connection pool's return() logic,
        # this deadlocks in PostgreSQL, because conn1 is returned to the
        # pool but still has a lock on "deadlock_users". comment out the
        # rollback in pool/ConnectionFairy._close() to see !

        users.drop(conn2)
        conn2.close()

class ExplicitAutoCommitTest(fixtures.TestBase):

    """test the 'autocommit' flag on select() and text() objects.

    Requires PostgreSQL so that we may define a custom function which
    modifies the database. """

    __only_on__ = "postgresql"

    @classmethod
    def setup_class(cls):
        global metadata, foo
        metadata = MetaData(testing.db)
        foo = Table(
            "foo",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("data", String(100)),
        )
        with testing.db.connect() as conn:
            metadata.create_all(conn)
            conn.exec_driver_sql(
                "create function insert_foo(varchar) "
                "returns integer as 'insert into foo(data) "
                "values ($1);select 1;' language sql"
            )

    def teardown(self):
        with testing.db.connect() as conn:
            conn.execute(foo.delete())

    @classmethod
    def teardown_class(cls):
        with testing.db.connect() as conn:
            conn.exec_driver_sql("drop function insert_foo(varchar)")
            metadata.drop_all(conn)

    def test_control(self):

        # test that not using autocommit does not commit

        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(select([func.insert_foo("data1")]))
        assert conn2.execute(select([foo.c.data])).fetchall() == []
        conn1.execute(text("select insert_foo('moredata')"))
        assert conn2.execute(select([foo.c.data])).fetchall() == []
        trans = conn1.begin()
        trans.commit()
        assert conn2.execute(select([foo.c.data])).fetchall() == [
            ("data1",),
            ("moredata",),
        ]
        conn1.close()
        conn2.close()

    def test_explicit_compiled(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(
            select([func.insert_foo("data1")]).execution_options(
                autocommit=True
            )
        )
        assert conn2.execute(select([foo.c.data])).fetchall() == [("data1",)]
        conn1.close()
        conn2.close()

    def test_explicit_connection(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execution_options(autocommit=True).execute(
            select([func.insert_foo("data1")])
        )
        eq_(conn2.execute(select([foo.c.data])).fetchall(), [("data1",)])

        # connection supersedes statement

        conn1.execution_options(autocommit=False).execute(
            select([func.insert_foo("data2")]).execution_options(
                autocommit=True
            )
        )
        eq_(conn2.execute(select([foo.c.data])).fetchall(), [("data1",)])

        # ditto

        conn1.execution_options(autocommit=True).execute(
            select([func.insert_foo("data3")]).execution_options(
                autocommit=False
            )
        )
        eq_(
            conn2.execute(select([foo.c.data])).fetchall(),
            [("data1",), ("data2",), ("data3",)],
        )
        conn1.close()
        conn2.close()

    def test_explicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(
            text("select insert_foo('moredata')").execution_options(
                autocommit=True
            )
        )
        assert conn2.execute(select([foo.c.data])).fetchall() == [
            ("moredata",)
        ]
        conn1.close()
        conn2.close()

    def test_implicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(text("insert into foo (data) values ('implicitdata')"))
        assert conn2.execute(select([foo.c.data])).fetchall() == [
            ("implicitdata",)
        ]
        conn1.close()
        conn2.close()

class IsolationLevelTest(fixtures.TestBase):
    __requires__ = ("isolation_level", "ad_hoc_engines")
    __backend__ = True

    def _default_isolation_level(self):
        return testing.requires.get_isolation_levels(testing.config)["default"]

    def _non_default_isolation_level(self):
        levels = testing.requires.get_isolation_levels(testing.config)

        default = levels["default"]
        supported = levels["supported"]

        s = set(supported).difference(["AUTOCOMMIT", default])
        if s:
            return s.pop()
        else:
            assert False, "no non-default isolation level available"

    def test_engine_param_stays(self):

        eng = testing_engine()
        isolation_level = eng.dialect.get_isolation_level(
            eng.connect().connection
        )
        level = self._non_default_isolation_level()

        ne_(isolation_level, level)

        eng = testing_engine(options=dict(isolation_level=level))
        eq_(eng.dialect.get_isolation_level(eng.connect().connection), level)

        # check that it stays
        conn = eng.connect()
        eq_(eng.dialect.get_isolation_level(conn.connection), level)
        conn.close()

        conn = eng.connect()
        eq_(eng.dialect.get_isolation_level(conn.connection), level)
        conn.close()

    def test_default_level(self):
        eng = testing_engine(options=dict())
        isolation_level = eng.dialect.get_isolation_level(
            eng.connect().connection
        )
        eq_(isolation_level, self._default_isolation_level())

    def test_reset_level(self):
        eng = testing_engine(options=dict())
        conn = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._default_isolation_level(),
        )

        eng.dialect.set_isolation_level(
            conn.connection, self._non_default_isolation_level()
        )
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )

        eng.dialect.reset_isolation_level(conn.connection)
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._default_isolation_level(),
        )

        conn.close()

    def test_reset_level_with_setting(self):
        eng = testing_engine(
            options=dict(isolation_level=self._non_default_isolation_level())
        )
        conn = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )
        eng.dialect.set_isolation_level(
            conn.connection, self._default_isolation_level()
        )
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._default_isolation_level(),
        )
        eng.dialect.reset_isolation_level(conn.connection)
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )
        conn.close()

    def test_invalid_level(self):
        eng = testing_engine(options=dict(isolation_level="FOO"))
        assert_raises_message(
            exc.ArgumentError,
            "Invalid value '%s' for isolation_level. "
            "Valid isolation levels for %s are %s"
            % (
                "FOO",
                eng.dialect.name,
                ", ".join(eng.dialect._isolation_lookup),
            ),
            eng.connect,
        )

    def test_connection_invalidated(self):
        eng = testing_engine()
        conn = eng.connect()
        c2 = conn.execution_options(
            isolation_level=self._non_default_isolation_level()
        )
        c2.invalidate()
        c2.connection

        # TODO: do we want to rebuild the previous isolation?
        # for now, this is current behavior so we will leave it.
        eq_(c2.get_isolation_level(), self._default_isolation_level())

    def test_per_connection(self):
        from sqlalchemy.pool import QueuePool

        eng = testing_engine(
            options=dict(poolclass=QueuePool, pool_size=2, max_overflow=0)
        )

        c1 = eng.connect()
        c1 = c1.execution_options(
            isolation_level=self._non_default_isolation_level()
        )
        c2 = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(c1.connection),
            self._non_default_isolation_level(),
        )
        eq_(
            eng.dialect.get_isolation_level(c2.connection),
            self._default_isolation_level(),
        )
        c1.close()
        c2.close()
        c3 = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(c3.connection),
            self._default_isolation_level(),
        )
        c4 = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(c4.connection),
            self._default_isolation_level(),
        )

        c3.close()
        c4.close()

    def test_warning_in_transaction(self):
        eng = testing_engine()
        c1 = eng.connect()
        with expect_warnings(
            "Connection is already established with a Transaction; "
            "setting isolation_level may implicitly rollback or commit "
            "the existing transaction, or have no effect until next "
            "transaction"
        ):
            with c1.begin():
                c1 = c1.execution_options(
                    isolation_level=self._non_default_isolation_level()
                )

                eq_(
                    eng.dialect.get_isolation_level(c1.connection),
                    self._non_default_isolation_level(),
                )
        # stays outside of transaction
        eq_(
            eng.dialect.get_isolation_level(c1.connection),
            self._non_default_isolation_level(),
        )

    def test_per_statement_bzzt(self):
        assert_raises_message(
            exc.ArgumentError,
            r"'isolation_level' execution option may only be specified "
            r"on Connection.execution_options\(\), or "
            r"per-engine using the isolation_level "
            r"argument to create_engine\(\).",
            select([1]).execution_options,
            isolation_level=self._non_default_isolation_level(),
        )

    def test_per_engine(self):
        # new in 0.9
        eng = create_engine(
            testing.db.url,
            execution_options={
                "isolation_level": self._non_default_isolation_level()
            },
        )
        conn = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )

    def test_isolation_level_accessors_connection_default(self):
        eng = create_engine(testing.db.url)
        with eng.connect() as conn:
            eq_(conn.default_isolation_level, self._default_isolation_level())
        with eng.connect() as conn:
            eq_(conn.get_isolation_level(), self._default_isolation_level())

    def test_isolation_level_accessors_connection_option_modified(self):
        eng = create_engine(testing.db.url)
        with eng.connect() as conn:
            c2 = conn.execution_options(
                isolation_level=self._non_default_isolation_level()
            )
            eq_(conn.default_isolation_level, self._default_isolation_level())
            eq_(
                conn.get_isolation_level(), self._non_default_isolation_level()
            )
            eq_(c2.get_isolation_level(), self._non_default_isolation_level())


text:
.. Atmosphere-cli documentation master file, created by
   sphinx-quickstart on Mon May 15 12:25:45 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to the Atmosphere-CLI documentation!
==========================================

.. toctree::
   :maxdepth: 2
   :caption: Introduction

   index

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
require 'bundler/setup'
Bundler.setup

require 'pry'

require 'togglr'

RSpec.configure do |config|
  # some (optional) config here
end


text:
import * as assert from "assert";
import { testContext, disposeTestDocumentStore } from "../Utils/TestUtil";

import {
    IDocumentStore,
} from "../../src";
import { TypeUtil } from "../../src/Utility/TypeUtil";

describe("TypeUtil", function () {

    let store: IDocumentStore;

    beforeEach(async function () {
        store = await testContext.getDocumentStore();
    });

    afterEach(async () =>
        await disposeTestDocumentStore(store));

    it("isClass()", async () => {
        assert.ok(TypeUtil.isClass(class Test {}));

        // eslint-disable-next-line @typescript-eslint/no-empty-function
        assert.ok(!TypeUtil.isClass(function () {}));

        // eslint-disable-next-line @typescript-eslint/no-empty-function
        assert.ok(!TypeUtil.isClass(() => {}));
        assert.ok(!TypeUtil.isClass(1));
        assert.ok(!TypeUtil.isClass("test"));

        assert.ok(!TypeUtil.isClass(Symbol("test")));
    });
});


text:
'use strict'
var SpriteGrid = function (container) {
    const self = this;
    const SIZE = 16;
    const CONTAINER = container;

    var Direction = {
        UP: "up",
        DOWN: "down",
        LEFT: "left",
        RIGHT: "right",
        NONE: "none"
    }

    var Pixel = function (x, y, classList, direction) {
        var _this = this;
        x = x || 0;
        y = y || 0;
        classList = classList || [];
        direction = direction || Direction.NONE;

        this.element = document.createElement("div");
        classList.forEach(function (c) {
            _this.element.classList.add(c);
        });
        this.element.classList.add("sprite");

        this.setx(x);
        this.sety(y);
        this.setDirection(direction);

        this.element.addEventListener("animationiteration", function (e) {
            var direction = Direction.NONE;
            if (e.animationName === "moveRight") {
                direction = Direction.RIGHT;
                _this.setx(_this.getx() + 1);
            } else if (e.animationName === "moveLeft") {
                direction = Direction.LEFT;
                _this.setx(_this.getx() - 1);
            } else if (e.animationName === "moveUp") {
                direction = Direction.UP;
                _this.sety(_this.gety() - 1);
            } else if (e.animationName === "moveDown") {
                direction = Direction.DOWN;
                _this.sety(_this.gety() + 1);
            }
            _this.tick({
                direction: direction,
                pixel: _this,
                x: _this.getx(),
                y: _this.gety()
            });
        }, false);
        CONTAINER.appendChild(this.element);
        return this;
    };
    Pixel.prototype.getx = function() {
        return parseInt(this.element.getAttribute("data-position-x"));
    }
    Pixel.prototype.setx = function(x) {
        this.element.setAttribute("data-position-x", x);
    }
    Pixel.prototype.gety = function() {
        return parseInt(this.element.getAttribute("data-position-y"));
    }
    Pixel.prototype.sety = function(y) {
        this.element.setAttribute("data-position-y", y);
    }
    Pixel.prototype.collidesWith = function (other) {
        return this.getx() === other.getx() && this.gety() === other.gety();
    }
    Pixel.prototype.tick = function (event) {
    }
    Pixel.prototype.setDirection = function (d) {
        this.element.setAttribute("data-direction", d);
    }
    Pixel.prototype.getDirection = function (d) {
        return this.element.getAttribute("data-direction");
    }
    this.Pixel = Pixel;
    this.Direction = Direction;
    this.Size = function () { return SIZE };
};


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

namespace StackVM
{
	class Program
	{
		static void Main(string[] args)
		{
			TestFramework.Run();
			Console.WriteLine("ALL TESTS FINISHED");
			Console.ReadLine();
		}
	}
}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/libcore/luni/src/main/java/org/apache/harmony/security/asn1/BerInputStream.java
//

#ifndef _OrgApacheHarmonySecurityAsn1BerInputStream_H_
#define _OrgApacheHarmonySecurityAsn1BerInputStream_H_

#include "J2ObjC_header.h"

@class IOSByteArray;
@class IOSIntArray;
@class JavaIoInputStream;
@class OrgApacheHarmonySecurityAsn1ASN1Sequence;
@class OrgApacheHarmonySecurityAsn1ASN1SequenceOf;
@class OrgApacheHarmonySecurityAsn1ASN1Set;
@class OrgApacheHarmonySecurityAsn1ASN1SetOf;
@class OrgApacheHarmonySecurityAsn1ASN1StringType;

/*!
 @author Vladimir N. Molotkov, Stepan M. Mishura
 @version $Revision$
 */

#define OrgApacheHarmonySecurityAsn1BerInputStream_INDEFINIT_LENGTH -1

/*!
 @brief Decodes ASN.1 types encoded with BER (X.690)
 */
@interface OrgApacheHarmonySecurityAsn1BerInputStream : NSObject {
 @public
  IOSByteArray *buffer_;
  /*!
   @brief The position in the buffer.
   Next read must place data into the buffer from this offset
   */
  jint offset_;
  /*!
   @brief Current decoded tag
   */
  jint tag_;
  /*!
   @brief Current decoded length
   */
  jint length_;
  /*!
   @brief Current decoded content
   */
  id content_;
  /*!
   @brief Current decoded tag offset
   */
  jint tagOffset_;
  /*!
   @brief Current decoded content offset
   */
  jint contentOffset_;
  /*!
   @brief The last choice index
   */
  jint choiceIndex_;
  /*!
   @brief Keeps last decoded: year, month, day, hour, minute, second, millisecond
   */
  IOSIntArray *times_;
  jint oidElement_;
  /*!
   @brief Indicates verify or store mode.
   In store mode a decoded content is stored in a newly allocated
 appropriate object. The content variable holds
 a reference to the last created object.
 In verify mode a decoded content is not stored.
   */
  jboolean isVerify_;
  /*!
   @brief Indicates defined or indefined reading mode for associated InputStream.
   This mode is defined by reading a length
 for a first ASN.1 type from InputStream.
   */
  jboolean isIndefinedLength_;
}

#pragma mark Public

/*!
 @brief Creates stream for decoding.
 */
- (instancetype)initWithByteArray:(IOSByteArray *)encoded;

/*!
 @brief Creates stream for decoding.
 @param encoded bytes array to be decoded
 @param offset the encoding offset
 @param expectedLength expected length of full encoding, this includes
 identifier, length an content octets
 */
- (instancetype)initWithByteArray:(IOSByteArray *)encoded
                          withInt:(jint)offset
                          withInt:(jint)expectedLength;

/*!
 @brief Creates stream for decoding.
 Allocates initial buffer of default size
 */
- (instancetype)initWithJavaIoInputStream:(JavaIoInputStream *)inArg;

/*!
 @brief Creates stream for decoding.
 @param initialSize the internal buffer initial size
 */
- (instancetype)initWithJavaIoInputStream:(JavaIoInputStream *)inArg
                                  withInt:(jint)initialSize;

/*!
 @brief Reallocates the buffer in order to make it
 exactly the size of data it contains
 */
- (void)compactBuffer;

- (id)getWithId:(id)key;

/*!
 @brief Returns internal buffer used for decoding
 */
- (IOSByteArray *)getBuffer;

/*!
 @brief Returns encoded array.
 MUST be invoked after decoding corresponding ASN.1 notation
 */
- (IOSByteArray *)getEncoded;

/*!
 @brief Returns end offset for the current encoded type
 */
- (jint)getEndOffset;

/*!
 @brief Returns length of the current content for decoding
 */
- (jint)getLength;

/*!
 @brief Returns the length of the encoding
 */
+ (jint)getLengthWithByteArray:(IOSByteArray *)encoding;

/*!
 @brief Returns the current offset
 */
- (jint)getOffset;

/*!
 @brief Returns start offset for the current encoded type
 */
- (jint)getTagOffset;

/*!
 @brief Decodes next encoded type.
 Initializes tag, length, tagOffset and contentOffset variables
 @return next decoded tag
 @throws IOException if error occured
 */
- (jint)next;

- (void)putWithId:(id)key
           withId:(id)entry_;

/*!
 @brief Decodes ASN.1 bitstring type
 */
- (void)readBitString;

/*!
 @brief Decodes ASN.1 boolean type
 */
- (void)readBoolean;

/*!
 @brief Reads the next encoded content from the encoded input stream.
 The method MUST be used for reading a primitive encoded content.
 */
- (void)readContent;

/*!
 @brief Decodes ASN.1 Enumerated type
 */
- (void)readEnumerated;

/*!
 @brief Decodes ASN.1 GeneralizedTime type
 @throws IOException if error occured
 */
- (void)readGeneralizedTime;

/*!
 @brief Decodes ASN.1 Integer type
 */
- (void)readInteger;

/*!
 @brief Decodes ASN.1 Octetstring type
 */
- (void)readOctetString;

/*!
 @brief Decodes ASN.1 ObjectIdentifier type
 */
- (void)readOID;

/*!
 @brief Decodes ASN.1 Sequence type
 */
- (void)readSequenceWithOrgApacheHarmonySecurityAsn1ASN1Sequence:(OrgApacheHarmonySecurityAsn1ASN1Sequence *)sequence;

/*!
 @brief Decodes ASN.1 SequenceOf type
 */
- (void)readSequenceOfWithOrgApacheHarmonySecurityAsn1ASN1SequenceOf:(OrgApacheHarmonySecurityAsn1ASN1SequenceOf *)sequenceOf;

/*!
 @brief Decodes ASN.1 Set type
 */
- (void)readSetWithOrgApacheHarmonySecurityAsn1ASN1Set:(OrgApacheHarmonySecurityAsn1ASN1Set *)set;

/*!
 @brief Decodes ASN.1 SetOf type
 */
- (void)readSetOfWithOrgApacheHarmonySecurityAsn1ASN1SetOf:(OrgApacheHarmonySecurityAsn1ASN1SetOf *)setOf;

/*!
 @brief Decodes ASN.1 String type
 @throws IOException if an I/O error occurs or the end of the stream is reached
 */
- (void)readStringWithOrgApacheHarmonySecurityAsn1ASN1StringType:(OrgApacheHarmonySecurityAsn1ASN1StringType *)type;

/*!
 @brief Decodes ASN.1 UTCTime type
 @throws IOException if an I/O error occurs or the end of the stream is reached
 */
- (void)readUTCTime;

/*!
 @brief Resets this stream to initial state.
 @param encoded a new bytes array to be decoded
 @throws IOException if an error occurs
 */
- (void)resetWithByteArray:(IOSByteArray *)encoded;

/*!
 @brief Sets verify mode.
 */
- (void)setVerify;

#pragma mark Protected

/*!
 @brief Reads the next encoded byte from the encoded input stream.
 */
- (jint)read;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheHarmonySecurityAsn1BerInputStream)

J2OBJC_FIELD_SETTER(OrgApacheHarmonySecurityAsn1BerInputStream, buffer_, IOSByteArray *)
J2OBJC_FIELD_SETTER(OrgApacheHarmonySecurityAsn1BerInputStream, content_, id)
J2OBJC_FIELD_SETTER(OrgApacheHarmonySecurityAsn1BerInputStream, times_, IOSIntArray *)

J2OBJC_STATIC_FIELD_GETTER(OrgApacheHarmonySecurityAsn1BerInputStream, INDEFINIT_LENGTH, jint)

FOUNDATION_EXPORT void OrgApacheHarmonySecurityAsn1BerInputStream_initWithByteArray_(OrgApacheHarmonySecurityAsn1BerInputStream *self, IOSByteArray *encoded);

FOUNDATION_EXPORT OrgApacheHarmonySecurityAsn1BerInputStream *new_OrgApacheHarmonySecurityAsn1BerInputStream_initWithByteArray_(IOSByteArray *encoded) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void OrgApacheHarmonySecurityAsn1BerInputStream_initWithByteArray_withInt_withInt_(OrgApacheHarmonySecurityAsn1BerInputStream *self, IOSByteArray *encoded, jint offset, jint expectedLength);

FOUNDATION_EXPORT OrgApacheHarmonySecurityAsn1BerInputStream *new_OrgApacheHarmonySecurityAsn1BerInputStream_initWithByteArray_withInt_withInt_(IOSByteArray *encoded, jint offset, jint expectedLength) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void OrgApacheHarmonySecurityAsn1BerInputStream_initWithJavaIoInputStream_(OrgApacheHarmonySecurityAsn1BerInputStream *self, JavaIoInputStream *inArg);

FOUNDATION_EXPORT OrgApacheHarmonySecurityAsn1BerInputStream *new_OrgApacheHarmonySecurityAsn1BerInputStream_initWithJavaIoInputStream_(JavaIoInputStream *inArg) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void OrgApacheHarmonySecurityAsn1BerInputStream_initWithJavaIoInputStream_withInt_(OrgApacheHarmonySecurityAsn1BerInputStream *self, JavaIoInputStream *inArg, jint initialSize);

FOUNDATION_EXPORT OrgApacheHarmonySecurityAsn1BerInputStream *new_OrgApacheHarmonySecurityAsn1BerInputStream_initWithJavaIoInputStream_withInt_(JavaIoInputStream *inArg, jint initialSize) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT jint OrgApacheHarmonySecurityAsn1BerInputStream_getLengthWithByteArray_(IOSByteArray *encoding);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheHarmonySecurityAsn1BerInputStream)

#endif // _OrgApacheHarmonySecurityAsn1BerInputStream_H_