text:
local skynet = require "skynet"
local socket = require "socket"
local socketchannel = require "socketchannel"

local table = table
local string = string
local assert = assert

local ssdb = {}
local command = {}
local meta = {
	__index = command,
	-- DO NOT close channel in __gc
}

---------- ssdb response
local redcmd = {}

redcmd[36] = function(fd, data) -- '$'
	local bytes = tonumber(data)
	if bytes < 0 then
		return true,nil
	end
	local firstline = fd:read(bytes+2)
	return true,string.sub(firstline,1,-3)
end

redcmd[43] = function(fd, data) -- '+'
	return true,data
end

redcmd[45] = function(fd, data) -- '-'
	return false,data
end

redcmd[58] = function(fd, data) -- ':'
	-- todo: return string later
	return true, tonumber(data)
end

local function read_response(fd)
	local result = fd:readline "\r\n"
	local firstchar = string.byte(result)
	local data = string.sub(result,2)
	return redcmd[firstchar](fd,data)
end

redcmd[42] = function(fd, data)	-- '*'
	local n = tonumber(data)
	if n < 0 then
		return true, nil
	end
	local bulk = {}
	local noerr = true
	for i = 1,n do
		local ok, v = read_response(fd)
		if ok then
			bulk[i] = v
		else
			noerr = false
		end
	end
	return noerr, bulk
end

-------------------

local function ssdb_login(auth, db)
	if auth == nil and db == nil then
		return
	end
	return function(so)
		if auth then
			so:request("AUTH "..auth.."\r\n", read_response)
		end
		if db then
			so:request("SELECT "..db.."\r\n", read_response)
		end
	end
end

function ssdb.connect(db_conf)
	local channel = socketchannel.channel {
		host = db_conf.host,
		port = db_conf.port or 6379,
		auth = ssdb_login(db_conf.auth, db_conf.db),
		nodelay = true,
	}
	-- try connect first only once
	channel:connect(true)
	return setmetatable( { channel }, meta )
end

function command:disconnect()
	self[1]:close()
	setmetatable(self, nil)
end

-- msg could be any type of value

local function make_cache(f)
	return setmetatable({}, {
		__mode = "kv",
		__index = f,
	})
end

local header_cache = make_cache(function(t,k)
		local s = "\r\n$" .. k .. "\r\n"
		t[k] = s
		return s
	end)

local command_cache = make_cache(function(t,cmd)
		local s = "\r\n$"..#cmd.."\r\n"..cmd:upper()
		t[cmd] = s
		return s
	end)

local count_cache = make_cache(function(t,k)
		local s = "*" .. k
		t[k] = s
		return s
	end)

local function compose_message(cmd, msg)
	local t = type(msg)
	local lines = {}

	if t == "table" then
		lines[1] = count_cache[#msg+1]
		lines[2] = command_cache[cmd]
		local idx = 3
		for _,v in ipairs(msg) do
			v= tostring(v)
			lines[idx] = header_cache[#v]
			lines[idx+1] = v
			idx = idx + 2
		end
		lines[idx] = "\r\n"
	else
		msg = tostring(msg)
		lines[1] = "*2"
		lines[2] = command_cache[cmd]
		lines[3] = header_cache[#msg]
		lines[4] = msg
		lines[5] = "\r\n"
	end

	return lines
end

setmetatable(command, { __index = function(t,k)
	local cmd = string.upper(k)
	local f = function (self, v, ...)
		if type(v) == "table" then
			return self[1]:request(compose_message(cmd, v), read_response)
		else
			return self[1]:request(compose_message(cmd, {v, ...}), read_response)
		end
	end
	t[k] = f
	return f
end})

local function read_boolean(so)
	local ok, result = read_response(so)
	return ok, result ~= 0
end

function command:exists(key)
	local fd = self[1]
	return fd:request(compose_message ("EXISTS", key), read_boolean)
end

function command:sismember(key, value)
	local fd = self[1]
	return fd:request(compose_message ("SISMEMBER", {key, value}), read_boolean)
end

local function compose_table(lines, msg)
	local tinsert = table.insert
	tinsert(lines, count_cache[#msg])
	for _,v in ipairs(msg) do
		v = tostring(v)
		tinsert(lines,header_cache[#v])
		tinsert(lines,v)
	end
	tinsert(lines, "\r\n")
	return lines
end

function command:pipeline(ops,resp)
	assert(ops and #ops > 0, "pipeline is null")

	local fd = self[1]

	local cmds = {}
	for _, cmd in ipairs(ops) do
		compose_table(cmds, cmd)
	end

	if resp then
		return fd:request(cmds, function (fd)
			for i=1, #ops do
				local ok, out = read_response(fd)
				table.insert(resp, {ok = ok, out = out})
			end
			return true, resp
		end)
	else
		return fd:request(cmds, function (fd)
			local ok, out
			for i=1, #ops do
				ok, out = read_response(fd)
			end
			-- return last response
			return ok,out
		end)
	end
end

--- watch mode

local watch = {}

local watchmeta = {
	__index = watch,
	__gc = function(self)
		self.__sock:close()
	end,
}

local function watch_login(obj, auth)
	return function(so)
		if auth then
			so:request("AUTH "..auth.."\r\n", read_response)
		end
		for k in pairs(obj.__psubscribe) do
			so:request(compose_message ("PSUBSCRIBE", k))
		end
		for k in pairs(obj.__subscribe) do
			so:request(compose_message("SUBSCRIBE", k))
		end
	end
end

function ssdb.watch(db_conf)
	local obj = {
		__subscribe = {},
		__psubscribe = {},
	}
	local channel = socketchannel.channel {
		host = db_conf.host,
		port = db_conf.port or 6379,
		auth = watch_login(obj, db_conf.auth),
		nodelay = true,
	}
	obj.__sock = channel

	-- try connect first only once
	channel:connect(true)
	return setmetatable( obj, watchmeta )
end

function watch:disconnect()
	self.__sock:close()
	setmetatable(self, nil)
end

local function watch_func( name )
	local NAME = string.upper(name)
	watch[name] = function(self, ...)
		local so = self.__sock
		for i = 1, select("#", ...) do
			local v = select(i, ...)
			so:request(compose_message(NAME, v))
		end
	end
end

watch_func "subscribe"
watch_func "psubscribe"
watch_func "unsubscribe"
watch_func "punsubscribe"

function watch:message()
	local so = self.__sock
	while true do
		local ret = so:response(read_response)
		local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4]
		if type == "message" then
			return data, channel
		elseif type == "pmessage" then
			return data2, data, channel
		elseif type == "subscribe" then
			self.__subscribe[channel] = true
		elseif type == "psubscribe" then
			self.__psubscribe[channel] = true
		elseif type == "unsubscribe" then
			self.__subscribe[channel] = nil
		elseif type == "punsubscribe" then
			self.__psubscribe[channel] = nil
		end
	end
end

return ssdb


text:
package configtx

import (
	"bytes"

	cb "github.com/hyperledger/fabric/protos/common"
)

type comparable struct {
	*cb.ConfigGroup
	*cb.ConfigValue
	*cb.ConfigPolicy
	key  string
	path []string
}

func (cg comparable) equals(other comparable) bool {
	switch {
	case cg.ConfigGroup != nil:
		if other.ConfigGroup == nil {
			return false
		}
		return equalConfigGroup(cg.ConfigGroup, other.ConfigGroup)
	case cg.ConfigValue != nil:
		if other.ConfigValue == nil {
			return false
		}
		return equalConfigValues(cg.ConfigValue, other.ConfigValue)
	case cg.ConfigPolicy != nil:
		if other.ConfigPolicy == nil {
			return false
		}
		return equalConfigPolicies(cg.ConfigPolicy, other.ConfigPolicy)
	}

	// Unreachable
	return false
}

func (cg comparable) version() uint64 {
	switch {
	case cg.ConfigGroup != nil:
		return cg.ConfigGroup.Version
	case cg.ConfigValue != nil:
		return cg.ConfigValue.Version
	case cg.ConfigPolicy != nil:
		return cg.ConfigPolicy.Version
	}

	// Unreachable
	return 0
}

func (cg comparable) modPolicy() string {
	switch {
	case cg.ConfigGroup != nil:
		return cg.ConfigGroup.ModPolicy
	case cg.ConfigValue != nil:
		return cg.ConfigValue.ModPolicy
	case cg.ConfigPolicy != nil:
		return cg.ConfigPolicy.ModPolicy
	}

	// Unreachable
	return ""
}

func equalConfigValues(lhs, rhs *cb.ConfigValue) bool {
	return lhs.Version == rhs.Version &&
		lhs.ModPolicy == rhs.ModPolicy &&
		bytes.Equal(lhs.Value, rhs.Value)
}

func equalConfigPolicies(lhs, rhs *cb.ConfigPolicy) bool {
	if lhs.Version != rhs.Version ||
		lhs.ModPolicy != rhs.ModPolicy {
		return false
	}

	if lhs.Policy == nil || rhs.Policy == nil {
		return lhs.Policy == rhs.Policy
	}

	return lhs.Policy.Type == rhs.Policy.Type &&
		bytes.Equal(lhs.Policy.Value, rhs.Policy.Value)
}

// The subset functions check if inner is a subset of outer
// TODO, try to consolidate these three methods into one, as the code
// contents are the same, but the function signatures need to be different
func subsetOfGroups(inner, outer map[string]*cb.ConfigGroup) bool {
	// The empty set is a subset of all sets
	if len(inner) == 0 {
		return true
	}

	// If inner has more elements than outer, it cannot be a subset
	if len(inner) > len(outer) {
		return false
	}

	// If any element in inner is not in outer, it is not a subset
	for key := range inner {
		if _, ok := outer[key]; !ok {
			return false
		}
	}

	return true
}

func subsetOfPolicies(inner, outer map[string]*cb.ConfigPolicy) bool {
	// The empty set is a subset of all sets
	if len(inner) == 0 {
		return true
	}

	// If inner has more elements than outer, it cannot be a subset
	if len(inner) > len(outer) {
		return false
	}

	// If any element in inner is not in outer, it is not a subset
	for key := range inner {
		if _, ok := outer[key]; !ok {
			return false
		}
	}

	return true
}

func subsetOfValues(inner, outer map[string]*cb.ConfigValue) bool {
	// The empty set is a subset of all sets
	if len(inner) == 0 {
		return true
	}

	// If inner has more elements than outer, it cannot be a subset
	if len(inner) > len(outer) {
		return false
	}

	// If any element in inner is not in outer, it is not a subset
	for key := range inner {
		if _, ok := outer[key]; !ok {
			return false
		}
	}

	return true
}

func equalConfigGroup(lhs, rhs *cb.ConfigGroup) bool {
	if lhs.Version != rhs.Version ||
		lhs.ModPolicy != rhs.ModPolicy {
		return false
	}

	if !subsetOfGroups(lhs.Groups, rhs.Groups) ||
		!subsetOfGroups(rhs.Groups, lhs.Groups) ||
		!subsetOfPolicies(lhs.Policies, rhs.Policies) ||
		!subsetOfPolicies(rhs.Policies, lhs.Policies) ||
		!subsetOfValues(lhs.Values, rhs.Values) ||
		!subsetOfValues(rhs.Values, lhs.Values) {
		return false
	}

	return true
}

redpajama_set_name: RedPajamaGithub


text:
goog.setTestOnly();
goog.require('goog.Promise');
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.recordFunction');
goog.require('lf.Global');
goog.require('lf.Type');
goog.require('lf.backstore.WebSql');
goog.require('lf.cache.DefaultCache');
goog.require('lf.index.MemoryIndexStore');
goog.require('lf.schema');
goog.require('lf.schema.DataStoreType');
goog.require('lf.service');
goog.require('lf.service.ServiceId');
goog.require('lf.testing.Capability');

/** @type {!goog.testing.AsyncTestCase} */
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall('WebSqlRaw');

/** @type {!lf.testing.Capability} */
var capability;

/** @type {!goog.testing.PropertyReplacer} */
var stub;

/** @type {?Database} */
var upgradeDb;

/** @type {string} */
var upgradeDbName;

/** @type {!lf.Global} */
var upgradeGlobal;

function setUpPage() {
  capability = lf.testing.Capability.get();
  if (!capability.webSql) {
    return;
  }

  stub = new goog.testing.PropertyReplacer();
  upgradeDbName = 'upgrade' + goog.now();
  upgradeDb = window.openDatabase(
      upgradeDbName, '', 'upgrade', 2 * 1024 * 1024);
}

function setUp() {
  if (!capability.webSql) {
    return;
  }

  var global = lf.Global.get();
  global.registerService(lf.service.CACHE, new lf.cache.DefaultCache());
  global.registerService(
      lf.service.INDEX_STORE, new lf.index.MemoryIndexStore());
  upgradeGlobal = new lf.Global();
  global.registerService(
      new lf.service.ServiceId('ns_' + upgradeDbName), upgradeGlobal);
  upgradeGlobal.registerService(
      lf.service.INDEX_STORE, new lf.index.MemoryIndexStore());
}

function tearDown() {
  if (!capability.webSql) {
    return;
  }

  lf.Global.get().clear();
  stub.reset();
}

/**
 * @param {string=} opt_name
 * @return {!lf.schema.Database}
 */
function getOldSchema(opt_name) {
  var builder = lf.schema.create(opt_name || 'test' + goog.now(), 1);
  builder.createTable('A').
      addColumn('id', lf.Type.STRING).
      addColumn('name', lf.Type.STRING);
  return builder.getSchema();
}

// Tests that onUpgrade function is still called with version 0 for a new DB
// instance.
function testNewDBInstance() {
  if (!capability.webSql) {
    return;
  }

  asyncTestCase.waitForAsync('testNewDBInstance');

  var schema = getOldSchema();
  lf.Global.get().registerService(lf.service.SCHEMA, schema);

  /**
   * @param {!lf.raw.BackStore} rawDb
   * @return {!IThenable}
   */
  var onUpgrade = goog.testing.recordFunction(function(rawDb) {
    assertEquals(0, rawDb.getVersion());
    return goog.Promise.resolve();
  });

  var db = new lf.backstore.WebSql(lf.Global.get(), getOldSchema());
  db.init(onUpgrade).then(function() {
    onUpgrade.assertCallCount(1);
    asyncTestCase.continueTesting();
  });
}

/** @return {!IThenable} */
function populateOldData() {
  /** @const {!Object} */
  var CONTENTS = {'id': 'hello', 'name': 'world'};
  /** @const {!Object} */
  var CONTENTS2 = {'id': 'hello2', 'name': 'world2'};

  var builder = lf.schema.create(upgradeDbName, 1);
  builder.createTable('A').
      addColumn('id', lf.Type.STRING).
      addColumn('name', lf.Type.STRING);

  var db;
  var tableA;
  return builder.connect({
    storeType: lf.schema.DataStoreType.WEB_SQL
  }).then(function(dbRet) {
    db = dbRet;
    tableA = db.getSchema().tables()[0];
    var rows = [tableA.createRow(CONTENTS), tableA.createRow(CONTENTS2)];
    return db.insert().into(tableA).values(rows).exec();
  }).then(function() {
    return db.select().from(tableA).exec();
  }).then(function(results) {
    assertEquals(2, results.length);
    return goog.Promise.resolve();
  });
}

/**
 * @param {string} name
 * @param {string} version
 * @param {string} desc
 * @param {number} size
 * @param {!function(?Database)=} opt_callback
 * @return {?Database}
 */
function openDatabaseStub(name, version, desc, size, opt_callback) {
  if (goog.isDefAndNotNull(opt_callback)) {
    opt_callback(upgradeDb);
  }
  return upgradeDb;
}

/**
 * @param {!lf.schema.Builder} builder
 * @param {!function(!lf.raw.BackStore):!IThenable} onUpgrade
 * @param {!function(!Array<!Object>)} checker
 * @param {boolean=} opt_populateOldData
 * @return {!IThenable}
 */
function runTest(builder, onUpgrade, checker, opt_populateOldData) {
  stub.replace(window, 'openDatabase', openDatabaseStub);

  var promise = opt_populateOldData ?
      populateOldData() : goog.Promise.resolve();

  return promise.then(function() {
    // Re-register schema
    upgradeGlobal.registerService(lf.service.SCHEMA, builder.getSchema());
    return builder.connect({
      onUpgrade: onUpgrade,
      storeType: lf.schema.DataStoreType.WEB_SQL
    });
  }).then(function(db) {
    var tableA = db.getSchema().tables()[0];
    return db.select().from(tableA).exec();
  }).then(function(results) {
    checker(results);
    return goog.Promise.resolve();
  });
}

function test1AddTableColumn() {
  if (!capability.webSql) {
    return;
  }

  asyncTestCase.waitForAsync('test1AddTableColumn');
  var builder = lf.schema.create(upgradeDbName, 2);
  builder.createTable('A').
      addColumn('id', lf.Type.STRING).
      addColumn('name', lf.Type.STRING).
      addColumn('something', lf.Type.STRING);

  /**
   * @param {!lf.raw.BackStore} store
   * @return {!IThenable}
   */
  var onUpgrade = function(store) {
    return store.addTableColumn('A', 'something', 'nothing');
  };

  runTest(builder, onUpgrade, function(results) {
    assertEquals(2, results.length);
    assertEquals('nothing', results[0]['something']);
  }, true).then(asyncTestCase.continueTesting.bind(asyncTestCase), fail);
}

function test2DropTableColumn() {
  if (!capability.webSql) {
    return;
  }

  asyncTestCase.waitForAsync('test1AddTableColumn');
  var builder = lf.schema.create(upgradeDbName, 3);
  builder.createTable('A').
      addColumn('id', lf.Type.STRING).
      addColumn('name', lf.Type.STRING);

  /**
   * @param {!lf.raw.BackStore} store
   * @return {!IThenable}
   */
  var onUpgrade = function(store) {
    return store.dropTableColumn('A', 'something');
  };

  runTest(builder, onUpgrade, function(results) {
    assertEquals(2, results.length);
    var payload = results[0];
    assertTrue(payload.hasOwnProperty('id'));
    assertTrue(payload.hasOwnProperty('name'));
    assertFalse(payload.hasOwnProperty('something'));
  }).then(asyncTestCase.continueTesting.bind(asyncTestCase), fail);
}

function test3RenameTableColumn() {
  if (!capability.webSql) {
    return;
  }

  asyncTestCase.waitForAsync('test3RenameTableColumn');
  var builder = lf.schema.create(upgradeDbName, 4);
  builder.createTable('A').
      addColumn('id', lf.Type.STRING).
      addColumn('lastName', lf.Type.STRING);

  /**
   * @param {!lf.raw.BackStore} store
   * @return {!IThenable}
   */
  var onUpgrade = function(store) {
    return store.renameTableColumn('A', 'name', 'lastName');
  };

  runTest(builder, onUpgrade, function(results) {
    assertEquals(2, results.length);
    assertEquals('world', results[0]['lastName']);
  }).then(asyncTestCase.continueTesting.bind(asyncTestCase), fail);
}

function test4Dump() {
  if (!capability.webSql) {
    return;
  }

  asyncTestCase.waitForAsync('test4Dump');
  var builder = lf.schema.create(upgradeDbName, 5);
  builder.createTable('A').
      addColumn('id', lf.Type.STRING).
      addColumn('lastName', lf.Type.STRING);

  var dumpResult;

  /**
   * @param {!lf.raw.BackStore} store
   * @return {!IThenable}
   */
  var onUpgrade = function(store) {
    return store.dump().then(function(results) {
      dumpResult = results;
    });
  };

  runTest(builder, onUpgrade, function(results) {
    var rowsA = dumpResult['A'];
    assertEquals(2, rowsA.length);
    assertObjectEquals('world', rowsA[0]['value']['lastName']);
  }).then(asyncTestCase.continueTesting.bind(asyncTestCase), fail);
}

function test5DropTable() {
  if (!capability.webSql) {
    return;
  }

  asyncTestCase.waitForAsync('test5DropTable');
  var builder = lf.schema.create(upgradeDbName, 6);
  builder.createTable('B').
      addColumn('id', lf.Type.STRING).
      addColumn('lastName', lf.Type.STRING);

  /**
   * @param {!lf.raw.BackStore} store
   * @return {!IThenable}
   */
  var onUpgrade = function(store) {
    return store.dropTable('A');
  };

  runTest(builder, onUpgrade, function(results) {
    var resolver = goog.Promise.withResolver();
    upgradeDb.readTransaction(function(tx) {
      tx.executeSql(
          'SELECT tbl_name FROM sqlite_master WHERE type="table"',
          [],
          function(tx, rowsSet) {
            var results = [];
            for (var i = 0; i < rowsSet.rows.length; ++i) {
              results.push(rowsSet.rows.item(i)['tbl_name']);
            }
            assertTrue(results.indexOf('B') != -1);
            assertEquals(-1, results.indexOf('A'));
            resolver.resolve();
          },
          resolver.reject.bind(resolver));
    });
    return resolver.promise;
  }).then(asyncTestCase.continueTesting.bind(asyncTestCase), fail);
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28985_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Existing Wells Within Spacing Unit

    <p class="styleSans85.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Continental Resources, Inc. has identified the following wells which currently exist in the spacing unit consisting of:
Sec 4 & 9, T155N, R98W Williams County, ND
Horizontal

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">CRI has determined that the identified existing wells in the spacing unit specified above are not within 500' ofthe proposed Bismarck 7-9H wellbore and do not pose any collision threats during drilling or completion operations.


text:
<?php

class Swift_Mime_ContentEncoder_NativeQpContentEncoderAcceptanceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Swift_Mime_ContentEncoder_NativeQpContentEncoder
     */
    protected $_encoder;

    public function setUp()
    {
        $this->_samplesDir = realpath(__DIR__.'/../../../../_samples/charsets');
        $this->_encoder = new Swift_Mime_ContentEncoder_NativeQpContentEncoder();
    }

    public function testEncodingAndDecodingSamples()
    {
        $sampleFp = opendir($this->_samplesDir);
        while (false !== $encodingDir = readdir($sampleFp)) {
            if (substr($encodingDir, 0, 1) == '.') {
                continue;
            }

            $sampleDir = $this->_samplesDir.'/'.$encodingDir;

            if (is_dir($sampleDir)) {
                $fileFp = opendir($sampleDir);
                while (false !== $sampleFile = readdir($fileFp)) {
                    if (substr($sampleFile, 0, 1) == '.') {
                        continue;
                    }

                    $text = file_get_contents($sampleDir.'/'.$sampleFile);

                    $os = new Swift_ByteStream_ArrayByteStream();
                    $os->write($text);

                    $is = new Swift_ByteStream_ArrayByteStream();
                    $this->_encoder->encodeByteStream($os, $is);

                    $encoded = '';
                    while (false !== $bytes = $is->read(8192)) {
                        $encoded .= $bytes;
                    }

                    $this->assertEquals(
                        quoted_printable_decode($encoded),
                        // CR and LF are converted to CRLF
                        preg_replace('~\r(?!\n)|(?<!\r)\n~', "\r\n", $text),
                        '%s: Encoded string should decode back to original string for sample '.$sampleDir.'/'.$sampleFile
                    );
                }
                closedir($fileFp);
            }
        }
        closedir($sampleFp);
    }

    public function testEncodingAndDecodingSamplesFromDiConfiguredInstance()
    {
        $encoder = $this->_createEncoderFromContainer();
        $this->assertSame('=C3=A4=C3=B6=C3=BC=C3=9F', $encoder->encodeString('äöüß'));
    }

    /**
     * @expectedException RuntimeException
     */
    public function testCharsetChangeNotImplemented()
    {
        $this->_encoder->charsetChanged('utf-8');
        $this->_encoder->charsetChanged('charset');
        $this->_encoder->encodeString('foo');
    }

    public function testGetName()
    {
        $this->assertSame('quoted-printable', $this->_encoder->getName());
    }

    private function _createEncoderFromContainer()
    {
        return Swift_DependencyContainer::getInstance()
            ->lookup('mime.nativeqpcontentencoder')
            ;
    }
}


text:
SELECT 9 FROM (SELECT * FROM t1)
UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a)
ORDER BY 1
LIMIT ii;


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

namespace HTLib2.Bioinfo
{
    using Atom  = Pdb.Atom;
    using IAtom = Pdb.IAtom;
    public static partial class PdbStatic
    {
        public static IAtom ToIAtom<ATOM>(this ATOM atom)
            where ATOM:IAtom
        {
            return atom;
        }

        public static IAtom[] ToIAtoms<ATOM>(this ATOM[] atoms)
            where ATOM : IAtom
        {
            IAtom[] iatoms = new IAtom[atoms.Length];
            for(int i = 0; i < atoms.Length; i++)
                iatoms[i] = atoms[i];
            return iatoms;
        }

        public static List<IAtom> ToIAtoms<ATOM>(this List<ATOM> atoms)
            where ATOM : IAtom
        {
            List<IAtom> iatoms = new List<IAtom>(atoms.Count);
            for(int i = 0; i < atoms.Count; i++)
                iatoms.Add(atoms[i]);
            return iatoms;
        }

        public static IList<IAtom> ToIAtoms<ATOM>(this IList<ATOM> atoms)
            where ATOM : IAtom
        {
            IAtom[] iatoms = new IAtom[atoms.Count];
            for(int i = 0; i < atoms.Count; i++)
                iatoms[i] = atoms[i];
            return iatoms;
        }
    }
}


text:
package com.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.utility.DataStorage;
import com.utility.DroneData;

/*
 * codeforindia.herokuapp.com/data?droneId=1&isAlive=true&latitude=33&longtitude=33&objectId=2&objectIsAlive=true
 */
@SuppressWarnings("serial")
@WebServlet(
        name = "ReceiveCustomerData",
        urlPatterns = {"/custdata"}
    )
public class ReceiveCustomerData extends HttpServlet {
    private static final Object ONE = "1";
	private static final Object ZERO = "0";
	protected final Log logger = LogFactory.getLog(getClass());

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    	String droneId = request.getParameter("droneId");
    	if(droneId == null || droneId.isEmpty()) {
    		return;
    	}

    	String isAlive = request.getParameter("isAlive");
    	String latitude = request.getParameter("latitude");
    	String longtitude = request.getParameter("longtitude");
    	String objectId = request.getParameter("objectId");
    	String objectIsAlive = request.getParameter("objectIsAlive");

    	Map<String, DroneData> droneData = new HashMap<String, DroneData>();

    	DroneData drone = new DroneData();
    	drone.setAlive(getAliveData(isAlive));
    	drone.setLongitude(Float.parseFloat(longtitude));
    	drone.setLatitude(Float.parseFloat(latitude));

    	Map<String, Boolean> objects = new HashMap<String, Boolean>();
    	if(objectId != null && !objectId.isEmpty()) {
    	    objects.put(objectId, getAliveData(objectIsAlive));
    	}

    	drone.setObjects(objects);

    	DroneData droneHashMapData =  DataStorage.getDromeList(droneId);

    	if(droneHashMapData != null) {
    		droneHashMapData.setAlive(getAliveData(isAlive));
    		droneHashMapData.setLatitude(Float.parseFloat(latitude));
    		droneHashMapData.setLongitude(Float.parseFloat(longtitude));

    		if(getAliveData(isAlive)) {
    			// Update the objects hash map.
    			Map<String, Boolean> oldObjects = droneHashMapData.getObjects();
    			oldObjects.put(objectId, getAliveData(objectIsAlive));
    		}

    		droneData.put(droneId, droneHashMapData);
    		DataStorage.appendDroneList(droneData);
    	} else {
    		droneData.put(droneId, drone);
    		DataStorage.appendDroneList(droneData);
    	}

        Map<String, DroneData> droneList = DataStorage.getDroneList();
        Gson gson = new Gson();
        ServletOutputStream out = response.getOutputStream();
        out.write(gson.toJson(droneList).getBytes());
        out.flush();
    }

    private Boolean getAliveData(String objectIsAlive) {
		boolean isAlive = false;
		if(objectIsAlive != null && !objectIsAlive.equals(ZERO)) {
			isAlive = true;
		}
		return isAlive;
	}

	@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    	doGet(req, resp);
    }
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	doGet(request, response);
    	return null;
    }
}


text:
add_dependencies({
    people: 'js/people.js',
    pm_conversations: 'js/pm_conversations.js',
    util: 'js/util.js',
});

var noop = function () {};
var with_overrides = global.with_overrides;
var people = global.people;

set_global('$', global.make_zjquery());
set_global('document', 'document-stub');

set_global('alert_words', {
    process_message: noop,
});

set_global('topic_data' , {
    add_message: noop,
});

set_global('recent_senders', {
    process_message_for_senders: noop,
});

set_global('page_params', {
    realm_allow_message_editing: true,
    is_admin: true,
});

set_global('blueslip', {});

var me = {
    email: 'me@example.com',
    user_id: 101,
    full_name: 'Me Myself',
};

var alice = {
    email: 'alice@example.com',
    user_id: 102,
    full_name: 'Alice',
};

var bob = {
    email: 'bob@example.com',
    user_id: 103,
    full_name: 'Bob',
};

var cindy = {
    email: 'cindy@example.com',
    user_id: 104,
    full_name: 'Cindy',
};

people.add_in_realm(me);
people.add_in_realm(alice);
people.add_in_realm(bob);
people.add_in_realm(cindy);

global.people.initialize_current_user(me.user_id);

var message_store = require('js/message_store.js');

(function test_insert_recent_private_message() {
    message_store.insert_recent_private_message('1', 1001);
    message_store.insert_recent_private_message('2', 2001);
    message_store.insert_recent_private_message('1', 3001);

    // try to backdate user1's timestamp
    message_store.insert_recent_private_message('1', 555);

    assert.deepEqual(message_store.recent_private_messages, [
        {user_ids_string: '1', timestamp: 3001},
        {user_ids_string: '2', timestamp: 2001},
    ]);
}());

(function test_add_message_metadata() {
    var message = {
        sender_email: 'me@example.com',
        sender_id: me.user_id,
        type: 'private',
        display_recipient: [me, bob, cindy],
        flags: ['has_alert_word'],
        is_me_message: false,
        id: 2067,
    };
    message_store.add_message_metadata(message);

    assert.equal(message.is_private, true);
    assert.equal(message.reply_to, 'bob@example.com,cindy@example.com');
    assert.equal(message.to_user_ids, '103,104');
    assert.equal(message.display_reply_to, 'Bob, Cindy');
    assert.equal(message.alerted, true);
    assert.equal(message.is_me_message, false);

    var retrieved_message = message_store.get(2067);
    assert.equal(retrieved_message, message);

    // access cached previous message, and test match subject/content
    message = {
        id: 2067,
        match_subject: "subject foo",
        match_content: "bar content",
    };
    message = message_store.add_message_metadata(message);

    assert.equal(message.reply_to, 'bob@example.com,cindy@example.com');
    assert.equal(message.to_user_ids, '103,104');
    assert.equal(message.display_reply_to, 'Bob, Cindy');
    assert.equal(message.match_subject, 'subject foo');
    assert.equal(message.match_content, 'bar content');

    message = {
        sender_email: 'me@example.com',
        sender_id: me.user_id,
        type: 'stream',
        display_recipient: [me, cindy],
        stream: 'Zoolippy',
        topic: 'cool thing',
        subject: 'the_subject',
        id: 2068,
    };

    // test stream properties
    with_overrides(function (override) {
        override('compose.empty_topic_placeholder', function () {
            return 'the_subject';
        });
        global.with_stub(function (stub) {
            set_global('composebox_typeahead', {add_topic: stub.f});
            message_store.add_message_metadata(message);
            var typeahead_added = stub.get_args('stream', 'subject');
            assert.deepEqual(typeahead_added.stream, [me, cindy]);
            assert.equal(message.subject, typeahead_added.subject);
        });

        assert.deepEqual(message.stream, [me, cindy]);
        assert.equal(message.reply_to, 'me@example.com');
        assert.deepEqual(message.flags, []);
        assert.equal(message.alerted, false);
    });

}());

(function test_errors() {
    // Test a user that doesn't exist
    var message = {
        type: 'private',
        display_recipient: [{user_id: 92714}],
    };

    var blueslip_errors = 0;
    blueslip.error = function () {
        blueslip_errors += 1;
    };

    // Expect each to throw two blueslip errors
    // One from message_store.js, one from person.js
    var emails = message_store.get_pm_emails(message);
    assert.equal(emails, '?');
    assert.equal(blueslip_errors, 2);

    blueslip_errors = 0;
    var names = message_store.get_pm_full_names(message);
    assert.equal(names, '?');
    assert.equal(blueslip_errors, 2);

    message = {
        type: 'stream',
        display_recipient: [{}],
    };

    // This should early return and not run pm_conversation.set_partner
    var num_partner = 0;
    set_global('pm_conversation', {
        set_partner: function () {
            num_partner += 1;
        },
    });
    message_store.process_message_for_recent_private_messages(message);
    assert.equal(num_partner, 0);
}());

(function test_message_id_change() {
    var message = {
        sender_email: 'me@example.com',
        sender_id: me.user_id,
        type: 'private',
        display_recipient: [me, bob, cindy],
        flags: ['has_alert_word'],
        id: 401,
    };
    message_store.add_message_metadata(message);

    set_global('pointer', {
        furthest_read: 401,
    });

    set_global('message_list', {});
    set_global('home_msg_list', {});

    var opts = {
        old_id: 401,
        new_id: 402,
    };

    global.with_stub(function (stub) {
        home_msg_list.change_message_id = stub.f;
        message_store.reify_message_id(opts);
        var msg_id = stub.get_args('old', 'new');
        assert.equal(msg_id.old, 401);
        assert.equal(msg_id.new, 402);
    });

    home_msg_list.view = {};
    global.with_stub(function (stub) {
        home_msg_list.view.change_message_id = stub.f;
        message_store.reify_message_id(opts);
        var msg_id = stub.get_args('old', 'new');
        assert.equal(msg_id.old, 401);
        assert.equal(msg_id.new, 402);
    });

}());


text:
Niew in deze versie

Partituur editen: slepen en verwijderen (met backspace) van symbolen

Tijdens operaties met de partituur wordt nog steeds door het filmpje
genavigeert. Dat maakt het vervrissen van de partituur GUI soms fout gaan (er
blijven stukjes symbool achter). Ik werk aan een oplossing - betere
implementatie van het scrollen.

(Technische detail - het plaatsen van cursor is nu indirect - eerst wordt de
"playback hoofd" van de video speler verplaatst, dan stuurt video speler een
signal dat cursor verplaatst moet worden. De twee teken procedures - van
slepen en van feedback van het speler werken elkaar tegen. Dat hoeft echter
niet: als we aan het slepen zijn hoeven we helemaal niet reageren op de speler
zijn feedback, want we weten waar de cursor is. Het is alleen tijdens het
afspelen dat dat signal relevant is. De reden dat het op deze manier is
geimplementeerd is vertalen van Max - daar was het al zo geimplementeerd)


text:
package com.zhy.base.imageloader.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.zhy.base.imageloader.ImageLoader;
import com.zhy.base.imageloader.R;

/**
 * http://blog.csdn.net/lmj623565791/article/details/41874561
 *
 * @author zhy
 */
public class ListImgsFragment extends Fragment
{
    private GridView mGridView;
    private String[] mUrlStrs = Images.imageThumbUrls;
    private ImageLoader mImageLoader;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_list_imgs, container,
                false);
        mGridView = (GridView) view.findViewById(R.id.id_gridview);
        setUpAdapter();
        return view;
    }

    private void setUpAdapter()
    {
        if (getActivity() == null || mGridView == null)
            return;

        if (mUrlStrs != null)
        {
            mGridView.setAdapter(new ListImgItemAdaper(getActivity(), 0,
                    mUrlStrs));
        } else
        {
            mGridView.setAdapter(null);
        }

    }

    private class ListImgItemAdaper extends ArrayAdapter<String>
    {

        public ListImgItemAdaper(Context context, int resource, String[] datas)
        {
            super(getActivity(), 0, datas);
            Log.e("TAG", "ListImgItemAdaper");
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = getActivity().getLayoutInflater().inflate(
                        R.layout.item_fragment_list_imgs, parent, false);
            }
            ImageView imageview = (ImageView) convertView
                    .findViewById(R.id.id_img);
            imageview.setImageResource(R.drawable.pictures_no);

            ImageLoader.with(getContext()).load(getItem(position), imageview);
            return convertView;
        }

    }

}


text:
#ifndef RT_CONFIG_H__
#define RT_CONFIG_H__

/* Automatically generated file; DO NOT EDIT. */
/* RT-Thread Project Configuration */

/* RT-Thread Kernel */

#define RT_NAME_MAX 8
#define RT_ALIGN_SIZE 4
/* RT_THREAD_PRIORITY_8 is not set */
#define RT_THREAD_PRIORITY_32
/* RT_THREAD_PRIORITY_256 is not set */
#define RT_THREAD_PRIORITY_MAX 32
#define RT_TICK_PER_SECOND 100
#define RT_USING_OVERFLOW_CHECK
#define RT_USING_HOOK
#define RT_IDLE_HOOK_LIST_SIZE 4
#define IDLE_THREAD_STACK_SIZE 256
/* RT_USING_TIMER_SOFT is not set */
#define RT_DEBUG
#define RT_DEBUG_COLOR
/* RT_DEBUG_INIT_CONFIG is not set */
/* RT_DEBUG_THREAD_CONFIG is not set */
/* RT_DEBUG_SCHEDULER_CONFIG is not set */
/* RT_DEBUG_IPC_CONFIG is not set */
/* RT_DEBUG_TIMER_CONFIG is not set */
/* RT_DEBUG_IRQ_CONFIG is not set */
/* RT_DEBUG_MEM_CONFIG is not set */
/* RT_DEBUG_SLAB_CONFIG is not set */
/* RT_DEBUG_MEMHEAP_CONFIG is not set */
/* RT_DEBUG_MODULE_CONFIG is not set */

/* Inter-Thread communication */

#define RT_USING_SEMAPHORE
#define RT_USING_MUTEX
#define RT_USING_EVENT
#define RT_USING_MAILBOX
#define RT_USING_MESSAGEQUEUE
/* RT_USING_SIGNALS is not set */

/* Memory Management */

#define RT_USING_MEMPOOL
/* RT_USING_MEMHEAP is not set */
/* RT_USING_NOHEAP is not set */
#define RT_USING_SMALL_MEM
/* RT_USING_SLAB is not set */
/* RT_USING_MEMTRACE is not set */
#define RT_USING_HEAP

/* Kernel Device Object */

#define RT_USING_DEVICE
/* RT_USING_DEVICE_OPS is not set */
/* RT_USING_INTERRUPT_INFO is not set */
#define RT_USING_CONSOLE
#define RT_CONSOLEBUF_SIZE 128
#define RT_CONSOLE_DEVICE_NAME "uart1"
/* RT_USING_MODULE is not set */
#define ARCH_ARM
#define ARCH_ARM_CORTEX_A
#define ARCH_ARM_CORTEX_A7

/* RT-Thread Components */

#define RT_USING_COMPONENTS_INIT
#define RT_USING_USER_MAIN
#define RT_MAIN_THREAD_STACK_SIZE 2048
#define RT_MAIN_THREAD_PRIORITY 10

/* C++ features */

/* RT_USING_CPLUSPLUS is not set */

/* Command shell */

#define RT_USING_FINSH
#define FINSH_THREAD_NAME "tshell"
#define FINSH_USING_HISTORY
#define FINSH_HISTORY_LINES 5
#define FINSH_USING_SYMTAB
#define FINSH_USING_DESCRIPTION
/* FINSH_ECHO_DISABLE_DEFAULT is not set */
#define FINSH_THREAD_PRIORITY 20
#define FINSH_THREAD_STACK_SIZE 4096
#define FINSH_CMD_SIZE 80
/* FINSH_USING_AUTH is not set */
#define FINSH_USING_MSH
#define FINSH_USING_MSH_DEFAULT
#define FINSH_USING_MSH_ONLY
#define FINSH_ARG_MAX 10

/* Device virtual file system */

/* RT_USING_DFS is not set */

/* Device Drivers */

#define RT_USING_DEVICE_IPC
#define RT_PIPE_BUFSZ 512
#define RT_USING_SERIAL
#define RT_SERIAL_USING_DMA
/* RT_USING_CAN is not set */
/* RT_USING_HWTIMER is not set */
/* RT_USING_CPUTIME is not set */
/* RT_USING_I2C is not set */
/* RT_USING_PIN is not set */
/* RT_USING_PWM is not set */
/* RT_USING_MTD_NOR is not set */
/* RT_USING_MTD_NAND is not set */
/* RT_USING_RTC is not set */
/* RT_USING_SDIO is not set */
/* RT_USING_SPI is not set */
/* RT_USING_WDT is not set */
/* RT_USING_WIFI is not set */
/* RT_USING_AUDIO is not set */

/* Using USB */

/* RT_USING_USB_HOST is not set */
/* RT_USING_USB_DEVICE is not set */

/* POSIX layer and C standard library */

/* RT_USING_LIBC is not set */
/* RT_USING_PTHREADS is not set */

/* Network */

/* Socket abstraction layer */

/* RT_USING_SAL is not set */

/* light weight TCP/IP stack */

/* RT_USING_LWIP is not set */

/* Modbus master and slave stack */

/* RT_USING_MODBUS is not set */

/* AT commands */

/* RT_USING_AT is not set */

/* VBUS(Virtual Software BUS) */

/* RT_USING_VBUS is not set */

/* Utilities */

/* RT_USING_LOGTRACE is not set */
/* RT_USING_RYM is not set */

/* RT-Thread online packages */

/* IoT - internet of things */

/* PKG_USING_PAHOMQTT is not set */
/* PKG_USING_WEBCLIENT is not set */
/* PKG_USING_MONGOOSE is not set */
/* PKG_USING_WEBTERMINAL is not set */
/* PKG_USING_CJSON is not set */
/* PKG_USING_JSMN is not set */
/* PKG_USING_LJSON is not set */
/* PKG_USING_EZXML is not set */
/* PKG_USING_NANOPB is not set */

/* Wi-Fi */

/* Marvell WiFi */

/* PKG_USING_WLANMARVELL is not set */

/* Wiced WiFi */

/* PKG_USING_WLAN_WICED is not set */
/* PKG_USING_COAP is not set */
/* PKG_USING_NOPOLL is not set */
/* PKG_USING_NETUTILS is not set */
/* PKG_USING_AT_DEVICE is not set */

/* IoT Cloud */

/* PKG_USING_ONENET is not set */
/* PKG_USING_GAGENT_CLOUD is not set */
/* PKG_USING_ALI_IOTKIT is not set */
/* PKG_USING_AZURE is not set */

/* security packages */

/* PKG_USING_MBEDTLS is not set */
/* PKG_USING_libsodium is not set */
/* PKG_USING_TINYCRYPT is not set */

/* language packages */

/* PKG_USING_LUA is not set */
/* PKG_USING_JERRYSCRIPT is not set */
/* PKG_USING_MICROPYTHON is not set */

/* multimedia packages */

/* PKG_USING_OPENMV is not set */
/* PKG_USING_MUPDF is not set */

/* tools packages */

/* PKG_USING_CMBACKTRACE is not set */
/* PKG_USING_EASYFLASH is not set */
/* PKG_USING_EASYLOGGER is not set */
/* PKG_USING_SYSTEMVIEW is not set */

/* system packages */

/* PKG_USING_GUIENGINE is not set */
/* PKG_USING_PERSIMMON is not set */
/* PKG_USING_CAIRO is not set */
/* PKG_USING_PIXMAN is not set */
/* PKG_USING_LWEXT4 is not set */
/* PKG_USING_PARTITION is not set */
/* PKG_USING_FAL is not set */
/* PKG_USING_SQLITE is not set */
/* PKG_USING_RTI is not set */
/* PKG_USING_LITTLEVGL2RTT is not set */

/* peripheral libraries and drivers */

/* PKG_USING_STM32F4_HAL is not set */
/* PKG_USING_STM32F4_DRIVERS is not set */
/* PKG_USING_REALTEK_AMEBA is not set */
/* PKG_USING_SHT2X is not set */
/* PKG_USING_AHT10 is not set */

/* miscellaneous packages */

/* PKG_USING_LIBCSV is not set */
/* PKG_USING_OPTPARSE is not set */
/* PKG_USING_FASTLZ is not set */
/* PKG_USING_MINILZO is not set */
/* PKG_USING_QUICKLZ is not set */
/* PKG_USING_MULTIBUTTON is not set */
/* PKG_USING_CANFESTIVAL is not set */
/* PKG_USING_ZLIB is not set */
/* PKG_USING_DSTR is not set */

/* sample package */

/* PKG_USING_SAMPLES is not set */

/* example package: hello */

/* PKG_USING_HELLO is not set */
#define BCM2836_SOC
#define RT_USING_UART1

#endif


text:
package org.apache.gobblin.source.extractor.hadoop;

import java.io.IOException;
import java.util.Iterator;

import org.apache.avro.Schema;
import org.apache.avro.generic.GenericRecord;

import com.google.common.base.Throwables;

import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.source.extractor.filebased.FileBasedExtractor;
import org.apache.gobblin.source.extractor.filebased.FileBasedHelperException;

/**
 * A custom type of {@link FileBasedExtractor}s for extracting data from Avro files.
 */
public class AvroFileExtractor extends FileBasedExtractor<Schema, GenericRecord> {

  public AvroFileExtractor(WorkUnitState workUnitState) {
    super(workUnitState, new AvroFsHelper(workUnitState));
  }

  @Override
  public Iterator<GenericRecord> downloadFile(String file) throws IOException {
    try {
      return this.closer.register(((AvroFsHelper) this.fsHelper).getAvroFile(file));
    } catch (FileBasedHelperException e) {
      Throwables.propagate(e);
    }
    return null;
  }

  /**
   * Assumption is that all files in the input directory have the same schema
   */
  @Override
  public Schema getSchema() {
    if (this.workUnit.contains(ConfigurationKeys.SOURCE_SCHEMA)) {
      return new Schema.Parser().parse(this.workUnit.getProp(ConfigurationKeys.SOURCE_SCHEMA));
    }

    AvroFsHelper hfsHelper = (AvroFsHelper) this.fsHelper;
    if (this.filesToPull.isEmpty()) {
      return null;
    }
    try {
      return hfsHelper.getAvroSchema(this.filesToPull.get(0));
    } catch (FileBasedHelperException e) {
      Throwables.propagate(e);
      return null;
    }
  }
}


text:
import * as actionsConstants from '../actions/actions';

/* ================== SECTION: state = state.assignedTags ================== */
function deleteAssignedTag(state, actionTag) {
  const filteredState = state.filter(tag => (tag.id !== actionTag.tagCategory.id));
  const selectedItem = state.find(tag => (tag.id === actionTag.tagCategory.id));
  const filteredTagValues = selectedItem.values.filter(value => (value.id !== actionTag.tagValue.id));
  return [...filteredState,
    {
      description: actionTag.tagCategory.description,
      id: actionTag.tagCategory.id,
      values: [...filteredTagValues],
    },
  ].filter(tag => (tag.values.length !== 0));
}

/**
 * Replaces all assigned tags with the received ones.
 *
 * If single value tags are used it will receive array with length 1.
 * With multi select enabled it can receive arrays with variable sizes.
 * When receiving an empty array it removes also the category from the
 * assigned arrays.
 */
function changeAssignedTags(state, actionTag) {
  const filteredState = state.filter(tag => (tag.id !== actionTag.tagCategory.id));

  if (actionTag.tagValue && actionTag.tagValue.length > 0) {
    return [...filteredState,
      {
        description: actionTag.tagCategory.description,
        id: actionTag.tagCategory.id,
        values: actionTag.tagValue,
      }];
  }

  return [...filteredState];
}

export const modifyAssignedTags = (state = [], action) => {
  switch (action.type) {
    case actionsConstants.DELETE_ASSIGNED_TAG:
      return deleteAssignedTag(state, action.tag);
    case actionsConstants.DELETE_ALL_ASSIGNED_TAGS:
      return [];
    case actionsConstants.CHANGE_ASSIGNED_TAGS:
    case actionsConstants.ADD_ASSIGNED_TAG:
      return changeAssignedTags(state, action.tag);
    default:
      return state;
  }
};

/* ================ SECTION: state = state = state.selected ================ */
export const toggle = (state = { tagCategory: {}, tagValue: {} }, action) => {
  switch (action.type) {
    case actionsConstants.TOGGLE_TAG_CATEGORY_CHANGE:
      return { tagCategory: action.tagCategory, tagValue: {} };
    case actionsConstants.TOGGLE_TAG_VALUE_CHANGE:
      return { tagCategory: state.tagCategory, tagValue: action.tag.tagValue[action.tag.tagValue.length - 1] };
    default:
      return state;
  }
};

export const tags = (state = []) => state;
export const affectedItems = (state = []) => state;

export const initialize = (state = {}, action) => {
  switch (action.type) {
    case actionsConstants.LOAD_STATE:
      return {
        ...state,
        initialState: action.initialState,
        appState: {
          tags: action.initialState.tags,
          assignedTags: action.initialState.assignedTags,
          affectedItems: action.initialState.affectedItems,
        },
      };
    case actionsConstants.RESET_STATE:
      return { ...state, appState: { ...state.initialState } };
    default:
      return { ...state };
  }
};


text:
/* matmul1D.cpp - Data-movement operations on arrays of slots
 */
#include <algorithm>
#include <NTL/BasicThreadPool.h>
#include "EncryptedArray.h"
#include "matmul.h"
//#include "multiAutomorph.h"

#if 0

// Translate a value x in Zm* to the index e s.t. g_i^e=x (mod m)
// in a native dimension, returns e in 0..ord_i-1
// in a non-native dimension, returns e in -ord_i+1..ord_i-1
// returns -ord_i if it can't find such an e

// For now, this is just done by brute-force search, which is
// probably good enough.
static
long val2index(const PAlgebra& zMStar, long dim, long x)
{
  FHE_TIMER_START;

  long m = zMStar.getM();
  long g = zMStar.ZmStarGen(dim);
  long ord = zMStar.OrderOf(dim);

  long e = 0;
  long g2e = 1;

  mulmod_precon_t gminv = PrepMulModPrecon(g, m);

  while (e < ord && g2e != x) {
    e++;
    g2e = MulModPrecon(g2e, g, m, gminv);
  }

  if (e < ord) return e;

  if (zMStar.SameOrd(dim)) return -ord;

  x = MulMod(x, g2e, m);

  e = 0;
  g2e = 1;

  while (e < ord && g2e != x) {
    e++;
    g2e = MulModPrecon(g2e, g, m, gminv);
  }

  if (e < ord) return e-ord;

  return -ord;

}

// A class that implements the basic (sparse) 1D matrix-vector functions
template<class type> class matmul1D_impl {
  PA_INJECT(type)
  const MatrixCacheType buildCache;
  std::unique_ptr<CachedzzxMatrix> zCache;
  std::unique_ptr<CachedDCRTMatrix> dCache;

  MatMul<type>& mat;
  const EncryptedArrayDerived<type>& ea;

public:
  matmul1D_impl(MatMulBase& _mat, MatrixCacheType tag, long dim)
    : buildCache(tag), mat(dynamic_cast< MatMul<type>& >(_mat)),
      ea(_mat.getEA().getDerived(type()))
  {
    long D = ea.sizeOfDimension(dim);
    long sz = ea.nativeDimension(dim) ? D : (2*D-1);

    if (buildCache==cachezzX)
      zCache.reset(new CachedzzxMatrix(NTL::INIT_SIZE,sz));
    else if (buildCache==cacheDCRT)
      dCache.reset(new CachedDCRTMatrix(NTL::INIT_SIZE,sz));
  }

  // Get the i'th diagonal along dimension dim, encoded as a
  // single constant. All blocks use the same transofmration.
  // Returns true if this is a zero diagonal, false otherwise
  bool processDiagonal1(zzX& cPoly, long dim, long i, long D)
  {
    vector<RX> tmpDiag(D);
    bool zDiag = true; // is this a zero diagonal?
    long nzLast = -1;  // index of last non-zero entry
    RX entry;

    // Process the entries in this diagonal one at a time
    for (long j = 0; j < D; j++) { // process entry j
      bool zEntry = mat.get(entry, mcMod(j-i, D), j); // entry [j-i mod D, j]
      assert(zEntry || deg(entry) < ea.getDegree());
      // get(...) returns true if the entry is empty, false otherwise

      if (!zEntry && IsZero(entry)) zEntry = true;// zero is an empty entry too

      if (!zEntry) {   // not a zero entry
        zDiag = false; // mark diagonal as non-empty

        // clear entries between last nonzero entry and this one
        for (long jj = nzLast+1; jj < j; jj++) clear(tmpDiag[jj]);
        tmpDiag[j] = entry;
        nzLast = j;
      }
    }
    if (zDiag) return true; // zero diagonal, nothing to do

    // clear trailing zero entries
    for (long jj = nzLast+1; jj < D; jj++) clear(tmpDiag[jj]);

    vector<RX> diag(ea.size());
    if (D==1) diag.assign(ea.size(), tmpDiag[0]); // dimension of size one
    else for (long j = 0; j < ea.size(); j++)
           diag[j] = tmpDiag[ ea.coordinate(dim,j) ];
           // rearrange the indexes based on the current dimension

    ea.encode(cPoly, diag);
    return false; // a nonzero diagonal
  }

  // Get the i'th diagonal along dimension dim, encoded as a
  // single constant. Different blocks use different transofmrations.
  // Returns true if this is a zero diagonal, false otherwise
  bool processDiagonal2(zzX& poly, long dim, long idx, long D)
  {
    bool zDiag = true; // is this a zero diagonal?
    long nzLast = -1;  // index of last non-zero entry
    RX entry;

    // Process the entries in this diagonal one at a time
    long blockIdx, innerIdx;
    vector<RX> diag(ea.size());
    for (long j=0; j<ea.size(); j++) {
      if (D==1) {
	blockIdx=j; innerIdx = 0;
      } else {
	std::tie(blockIdx, innerIdx) // std::pair<long,long> idxes
	  = ea.getContext().zMStar.breakIndexByDim(j, dim);
	//	blockIdx = idxes.first;  // which transformation
	//	innerIdx = idxes.second; // index along diemnssion dim
      }
      // process entry j
      bool zEntry=mat.multiGet(entry,mcMod(innerIdx-idx,D),innerIdx,blockIdx);
      // entry [i,j-i mod D] in the block corresponding to blockIdx
      // multiGet(...) returns true if the entry is empty, false otherwise

      // If non-zero, make sure the degree is not too large
      assert(zEntry || deg(entry) < ea.getDegree());

      if (!zEntry && IsZero(entry)) zEntry = true; // zero is an empty entry too

      if (!zEntry) {   // not a zero entry
	zDiag = false; // mark diagonal as non-empty

	// clear entries between last nonzero entry and this one
	for (long jj = nzLast+1; jj < j; jj++) clear(diag[jj]);
	nzLast = j;
	diag[j] = entry;
      }
    }
    if (zDiag) return true; // zero diagonal, nothing to do

    // clear trailing zero entries
    for (long jj = nzLast+1; jj < ea.size(); jj++) clear(diag[jj]);
    ea.encode(poly, diag);
    return false; // a nonzero diagonal
  }

  void fixup(zzX& cpoly, const RX& c, long i, long signed_i, long dim)
  {
    const PAlgebraModDerived<type>& tab = ea.getTab();
    const vector< vector< RX > >& maskTable = tab.getMaskTable();
    const RXModulus& PhimXMod = tab.getPhimXMod();

    long D = ea.sizeOfDimension(dim);

    if (signed_i > 0) {
      RX mask = maskTable[dim][i];
      MulMod(mask, mask, c, PhimXMod);
      convert(cpoly, mask);
    }
    else {
      RX mask;
      NTL::negate(mask, maskTable[dim][i]);
      MulMod(mask, mask, c, PhimXMod);
      add(mask, mask, c);
      convert(cpoly, mask);
    }
  }

  void multiply(Ctxt* ctxt, long dim, bool oneTransform)
  {
    FHE_TIMER_START;

    assert(dim >= 0 && dim < ea.dimension());
    RBak bak; bak.save(); ea.getTab().restoreContext(); // backup NTL modulus

    std::unique_ptr<Ctxt> res, shCtxt;
    if (ctxt!=nullptr) { // we need to do an actual multiplication
      ctxt->cleanUp(); // not sure, but this may be a good idea
      res.reset(new Ctxt(ZeroCtxtLike, *ctxt));
      shCtxt.reset(new Ctxt(ZeroCtxtLike, *ctxt));
    }

    // Check if we have the relevant constant in cache
    CachedzzxMatrix* zcp;
    CachedDCRTMatrix* dcp;
    mat.getCache(&zcp, &dcp);

    // set up the AutoIterator, if we have a ctxt
    std::unique_ptr<AutoIterator> autoIterator;
    if (ctxt) {
      FHE_NTIMER_START(AutoIterator_build);
      autoIterator.reset(AutoIterator::build(*ctxt, ctxt->getPubKey().getTree4dim(dim)));
    }

    // Process the diagonals one at a time
    if (ea.nativeDimension(dim)) {
      zzX cpoly;
      long D = ea.sizeOfDimension(dim);

      for (long cnt = 0; cnt < D; cnt++) { // process one diagonal
	long i; //process diagonal i

	if (!ctxt) {
	  i = cnt;
	}
	else if (cnt == 0) {
	  i = 0;
	  *shCtxt = *ctxt;
	}
	else {
          FHE_NTIMER_START(AutoIterator_next);
	  long x = autoIterator->next(*shCtxt);
	  assert(x !=0);
	  i = val2index(ea.getContext().zMStar, dim, x);
	  assert(i >= 0);
	}

	zzX* zxPtr=nullptr;
	DoubleCRT* dxPtr=nullptr;

	if (dcp != nullptr)         // DoubleCRT cache exists
	  dxPtr = (*dcp)[i].get();
	else if (zcp != nullptr)    // zzx cache exists but no DoubleCRT
	  zxPtr = (*zcp)[i].get();
	else { // no cache, compute const
	  bool zero = oneTransform? processDiagonal1(cpoly, dim, i, D)
				  : processDiagonal2(cpoly, dim, i, D);
	  if (!zero) zxPtr = &cpoly; // if it is not a zero value, point to it
	}

	// if zero diagonal, nothing to do for this iteration
	if (zxPtr==nullptr && dxPtr==nullptr)
	  continue;

	// Non-zero diagonal, store it in cache and/or multiply/add it

	if (ctxt) {
	  if (dxPtr!=nullptr) shCtxt->multByConstant(*dxPtr);
	  else                shCtxt->multByConstant(*zxPtr);

	  *res += *shCtxt;

	}

	if (buildCache==cachezzX) {
	  (*zCache)[i].reset(new zzX(*zxPtr));
	}
	else if (buildCache==cacheDCRT) {
	  (*dCache)[i].reset(new DoubleCRT(*zxPtr, ea.getContext()));
	}
      } // end of loop over diagonals
    }
    else {

      zzX cpoly;
      long D = ea.sizeOfDimension(dim);

      std::vector< unique_ptr<RX> > local_cache;
      if (!dcp && !zcp) {
        local_cache.resize(D);
      }

      for (long cnt = 0; cnt < 2*D-1; cnt++) { // process one diagonal
	long i; //process diagonal i
        long signed_i;

	if (!ctxt) {
          if (cnt == 0) {
             i = 0;
             signed_i = 0;
          }
          else {
             i = (cnt+1)/2;
             signed_i = (cnt % 2) ? (i - D) : i;
          }
	}
	else if (cnt == 0) {
	  i = 0;
          signed_i = 0;
	  *shCtxt = *ctxt;
	}
	else {
	  long x = autoIterator->next(*shCtxt);
	  assert(x !=0);
	  signed_i = val2index(ea.getContext().zMStar, dim, x);
          i = signed_i;
          if (i < 0) i += D;
	}

        long i_off = signed_i + (D-1);

	zzX* zxPtr=nullptr;
	DoubleCRT* dxPtr=nullptr;

	if (dcp != nullptr)         // DoubleCRT cache exists
	  dxPtr = (*dcp)[i_off].get();
	else if (zcp != nullptr)    // zzx cache exists but no DoubleCRT
	  zxPtr = (*zcp)[i_off].get();
	else if (local_cache[i]) {
          if (*local_cache[i] != 0) {
             convert(cpoly, *local_cache[i]);
             zxPtr = &cpoly;
             if (i) fixup(cpoly, *local_cache[i], i, signed_i, dim);
          }
          local_cache[i].reset(); // we've used it, so we can kill it
        }
        else { // no cache, compute const
	  bool zero = oneTransform? processDiagonal1(cpoly, dim, i, D)
				  : processDiagonal2(cpoly, dim, i, D);
	  if (!zero) {
            zxPtr = &cpoly; // if it is not a zero value, point to it
            local_cache[i].reset(new RX());
            convert(*local_cache[i], cpoly);
            if (i) fixup(cpoly, *local_cache[i], i, signed_i, dim);
          }
          else {
            local_cache[i].reset(new RX());
          }
	}

	// if zero diagonal, nothing to do for this iteration
	if (zxPtr==nullptr && dxPtr==nullptr)
	  continue;

	// Non-zero diagonal, store it in cache and/or multiply/add it

	if (ctxt) {
	  if (dxPtr!=nullptr) shCtxt->multByConstant(*dxPtr);
	  else                shCtxt->multByConstant(*zxPtr);
	  *res += *shCtxt;
	}
	if (buildCache==cachezzX) {
	  (*zCache)[i_off].reset(new zzX(*zxPtr));
	}
	else if (buildCache==cacheDCRT) {
	  (*dCache)[i_off].reset(new DoubleCRT(*zxPtr, ea.getContext()));
	}
      } // end of loop over diagonals
    }

    if (ctxt) // copy result back to ctxt
      *ctxt = *res;

    // "install" the cache (if needed)
    if (buildCache == cachezzX)
      mat.installzzxcache(zCache);
    else if (buildCache == cacheDCRT)
      mat.installDCRTcache(dCache);
  } // end of multiply(...)
};

// Wrapper functions around the implemenmtation class
static void matmul1d(Ctxt* ctxt, MatMulBase& mat, long dim,
		     bool oneTransform, MatrixCacheType buildCache)
{
  MatMulLock locking(mat, buildCache);

  // If locking.getType()!=cacheEmpty then we really do need to
  // build the cache, and we also have the lock for it.

  if (locking.getType()==cacheEmpty && ctxt==nullptr) //  nothing to do
    return;

  switch (mat.getEA().getTag()) {
    case PA_GF2_tag: {
      matmul1D_impl<PA_GF2> M(mat, locking.getType(), dim);
      M.multiply(ctxt, dim, oneTransform);
      break;
    }
    case PA_zz_p_tag: {
      matmul1D_impl<PA_zz_p> M(mat, locking.getType(), dim);
      M.multiply(ctxt, dim, oneTransform);
      break;
    }
    default:
      throw std::logic_error("matmul1d: neither PA_GF2 nor PA_zz_p");
  }
}
void buildCache4MatMul1D(MatMulBase& mat, long dim, MatrixCacheType buildCache)
{ matmul1d(nullptr, mat, dim, true, buildCache); }

void matMul1D(Ctxt& ctxt, MatMulBase& mat,long dim, MatrixCacheType buildCache)
{ matmul1d(&ctxt, mat, dim, true, buildCache); }

void buildCache4MatMulti1D(MatMulBase& mat,long dim,MatrixCacheType buildCache)
{ matmul1d(nullptr, mat, dim, false, buildCache); }

void matMulti1D(Ctxt& ctxt,MatMulBase& mat,long dim,MatrixCacheType buildCache)
{ matmul1d(&ctxt, mat, dim, false, buildCache); }

/********************************************************************
 ********************************************************************/
// Applying matmul to plaintext, useful for debugging

template<class type>
class matmul1D_pa_impl {
public:
  PA_INJECT(type)

  static void multiply(NewPlaintextArray& pa, MatMul<type>& mat,
		       long dim, bool oneTrans)
  {
    const EncryptedArrayDerived<type>& ea = mat.getEA().getDerived(type());
    RBak bak; bak.save(); ea.getTab().restoreContext();

    long n = ea.size();
    long D = ea.sizeOfDimension(dim);

    vector< vector<RX> > data1(n/D);
    for (long k = 0; k < n/D; k++)
      data1[k].resize(D);

    // copy the data into a vector of 1D vectors
    vector<RX>& data = pa.getData<type>();
    for (long i = 0; i < n; i++) {
      long k,j;
      std::tie(k,j) = ea.getContext().zMStar.breakIndexByDim(i, dim);
      data1[k][j] = data[i];       // k= along dim, j = the rest of i
    }

    // multiply each one of the vectors by the same matrix
    for (long k = 0; k < n/D; k++) {
      for (long j = 0; j < D; j++) { // simple matrix-vector multiplication
	std::pair<long,long> p(k,j);
	long idx = ea.getContext().zMStar.assembleIndexByDim(p, dim);

	RX acc, val, tmp;
	acc = 0;
        for (long i = 0; i < D; i++) {
          bool zero = oneTrans? mat.get(val, i, j) : mat.multiGet(val,i,j,k);
          if (!zero) {
            NTL::mul(tmp, data1[k][i], val);
            NTL::add(acc, acc, tmp);
          }
        }
        rem(data[idx], acc, ea.getG()); // store the result in the data array
      }
    }
  }
};
// A wrapper around the implementation class
static void matmul1d(NewPlaintextArray& pa, MatMulBase& mat,
		     long dim, bool oneTrans)
{
  switch (mat.getEA().getTag()) {
    case PA_GF2_tag: {
      matmul1D_pa_impl<PA_GF2>::multiply(pa,
                      dynamic_cast< MatMul<PA_GF2>& >(mat), dim, oneTrans);
      return;
    }
    case PA_zz_p_tag: {
      matmul1D_pa_impl<PA_zz_p>::multiply(pa,
                      dynamic_cast<MatMul<PA_zz_p>&>(mat), dim, oneTrans);
      return;
    }
    default:
      throw std::logic_error("matMul1D: neither PA_GF2 nor PA_zz_p");
  }
}

void matMul1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)
{
  matmul1d(pa, mat, dim, true);
}
void matMulti1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)
{
  matmul1d(pa, mat, dim, false);
}

#else

// baby-step giant-step implementation

struct PtxtPtr {
  enum Type { ZERO=0, ZZX=1, DCRT=2 };
  zzX*       zp;
  DoubleCRT* dp;

  PtxtPtr(): zp(nullptr), dp(nullptr) {}
};

// A class that implements the basic (sparse) 1D matrix-vector functions
template<class type> class matmul1D_impl {
  PA_INJECT(type)
  const MatrixCacheType buildCache;
  std::unique_ptr<CachedzzxMatrix> zCache;
  std::unique_ptr<CachedDCRTMatrix> dCache;

  MatMul<type>& mat;
  const EncryptedArrayDerived<type>& ea;

public:
  matmul1D_impl(MatMulBase& _mat, long dim, MatrixCacheType tag)
    : buildCache(tag), mat(dynamic_cast< MatMul<type>& >(_mat)),
      ea(_mat.getEA().getDerived(type()))
  {
    if (buildCache==cachezzX) {
      zCache.reset(new CachedzzxMatrix(NTL::INIT_SIZE,ea.sizeOfDimension(dim)));
    } else if (buildCache==cacheDCRT) {
      dCache.reset(new CachedDCRTMatrix(NTL::INIT_SIZE,ea.sizeOfDimension(dim)));
    }
  }

  // Get the i'th diagonal along dimension dim, encoded as a
  // single constant. All blocks use the same transofmration.
  // Returns true if this is a zero diagonal, false otherwise
  bool processDiagonal1(zzX& cPoly, long dim, long i, long D, long rotAmt)
  {
    vector<RX> tmpDiag(D);
    bool zDiag = true; // is this a zero diagonal?
    long nzLast = -1;  // index of last non-zero entry
    RX entry;

    // Process the entries in this diagonal one at a time
    for (long j = 0; j < D; j++) { // process entry j
      long rotJ = (j+rotAmt) % D;  // need to rotate constant by rotAmt
      bool zEntry = mat.get(entry, mcMod(rotJ-i, D), rotJ); // entry [j-i mod D, j]
      assert(zEntry || deg(entry) < ea.getDegree());
      // get(...) returns true if the entry is empty, false otherwise

      if (!zEntry && IsZero(entry)) zEntry = true;// zero is an empty entry too

      if (!zEntry) {   // not a zero entry
        zDiag = false; // mark diagonal as non-empty

        // clear entries between last nonzero entry and this one
        for (long jj = nzLast+1; jj < j; jj++) clear(tmpDiag[jj]);
        tmpDiag[j] = entry;
        nzLast = j;
      }
    }
    if (zDiag) return true; // zero diagonal, nothing to do

    // clear trailing zero entries
    for (long jj = nzLast+1; jj < D; jj++) clear(tmpDiag[jj]);

    vector<RX> diag(ea.size());
    if (D==1) diag.assign(ea.size(), tmpDiag[0]); // dimension of size one
    else for (long j = 0; j < ea.size(); j++)
           diag[j] = tmpDiag[ ea.coordinate(dim,j) ];
           // rearrange the indexes based on the current dimension

    ea.encode(cPoly, diag);
    return false; // a nonzero diagonal
  }

  // Get the i'th diagonal along dimension dim, encoded as a
  // single constant. Different blocks use different transofmrations.
  // Returns true if this is a zero diagonal, false otherwise
  bool processDiagonal2(zzX& poly, long dim, long idx, long D, long rotAmt)
  {
    bool zDiag = true; // is this a zero diagonal?
    long nzLast = -1;  // index of last non-zero entry
    RX entry;

    // Process the entries in this diagonal one at a time
    long blockIdx, innerIdx;
    vector<RX> diag(ea.size());
    for (long j=0; j<ea.size(); j++) {
      if (D==1) {
	blockIdx=j; innerIdx = 0;
      } else {
	std::tie(blockIdx, innerIdx) // std::pair<long,long> idxes
	  = ea.getContext().zMStar.breakIndexByDim(j, dim);
	//	blockIdx = idxes.first;  // which transformation
	//	innerIdx = idxes.second; // index along diemnssion dim
        innerIdx = (innerIdx+rotAmt) % D;  // need to rotate constant by rotAmt
      }
      // process entry j
      bool zEntry=mat.multiGet(entry,mcMod(innerIdx-idx,D),innerIdx,blockIdx);
      // entry [i,j-i mod D] in the block corresponding to blockIdx
      // multiGet(...) returns true if the entry is empty, false otherwise

      // If non-zero, make sure the degree is not too large
      assert(zEntry || deg(entry) < ea.getDegree());

      if (!zEntry && IsZero(entry)) zEntry = true; // zero is an empty entry too

      if (!zEntry) {   // not a zero entry
	zDiag = false; // mark diagonal as non-empty

	// clear entries between last nonzero entry and this one
	for (long jj = nzLast+1; jj < j; jj++) clear(diag[jj]);
	nzLast = j;
	diag[j] = entry;
      }
    }
    if (zDiag) return true; // zero diagonal, nothing to do

    // clear trailing zero entries
    for (long jj = nzLast+1; jj < ea.size(); jj++) clear(diag[jj]);

    ea.encode(poly, diag);
    return false; // a nonzero diagonal
  }

  // Returns in vec all the constants needed for a single giant-step.
  // The return value is ZERO(=0) if all these constants are zero.
  // Otherwise it is ZZX(=1) if using zzX or DCRT(=2) if using DoubleCRT
  PtxtPtr::Type getConsts(std::vector<PtxtPtr>& vec, std::vector<zzX>& polys,
                          CachedzzxMatrix* zcp, CachedDCRTMatrix* dcp,
                          long dim, long jg, long D, bool oneTrans)
  {
    PtxtPtr::Type typ = PtxtPtr::ZERO;
    long g = polys.size(); // how many constants do we need
    vec.assign(g,PtxtPtr());

    if (dcp!=nullptr) {        // we have DCRT cache
      for (long i=0, idx=jg; i<g && idx<D; i++, idx++) {
        if ((vec[i].dp = (*dcp)[idx].get()) != nullptr)
          typ = PtxtPtr::DCRT;
      }
    } else if (zcp!=nullptr) { // we have ZZX cache
      for (long i=0, idx=jg; i<g && idx<D; i++, idx++) {
        if ((vec[i].zp = (*zcp)[idx].get()) != nullptr)
          typ = PtxtPtr::ZZX;
      }
    } else {                   // no cache, compute consts
      for (long i=0, idx=jg; i<g && idx<D; i++, idx++) {
        bool zero = oneTrans? processDiagonal1(polys[i], dim, idx, D, i)
                            : processDiagonal2(polys[i], dim, idx, D, i);
        if (!zero) {
          vec[i].zp = &(polys[i]); // if not a zero, point to it
          typ = PtxtPtr::ZZX;
        }
      }
    }
    return typ;
  }

  void multiply(Ctxt* ctxt, long dim, bool oneTransform)
  {
    assert(dim >= 0 && dim <= ea.dimension());
    RBak bak; bak.save(); ea.getTab().restoreContext(); // backup NTL modulus

    long D = (dim==ea.dimension())? 1 : ea.sizeOfDimension(dim);
    long g = mat.getGstep();
    if (g<1 || g>=D) g=1; // sanity check
    long dDivg = divc(D,g);

    // Process the diagonals in baby-step/giant-step ordering.
    //   sum_{i=0}^{d-1} const_i rot^i(X)
    //   = \sum_{i=0}^{g-1} \sum_{j=0}^{d/g -1} const_{i+g*j} rot^{i+g*j}(X)
    //   = \sum_{i=0}^{g-1} rot^i(sum_j rot^{-i}(const_{i+g*j}) rot^{g*j}(X))
    //
    // so for i=0..g-1 we let
    //    Y_i = sum_j rot^{-i}(const_{i+g*j}) rot^{g*j}(X)
    // then compute \sum_{i=0}^{g-1} rot^i(Y_i).
    //
    // Computing the Y_i's, we initialize an accumulator for each Y_i,
    // then compute the rotations X_j = rot^{g*j}(X), j=0,...,d/g-1.
    // Each X_j is multiplied by all the constants rot^{-i}(const_{i+g*j}),
    // i=0,...,g-1, and the i'th product is added to the accumulator for
    // the corresponding Y_i.

    long lastRotate = 0;
    std::vector<Ctxt> acc; // accumulators
    if (ctxt!=nullptr) {   // we need to do an actual multiplication
      ctxt->cleanUp();     // not sure, but this may be a good idea
      Ctxt tmp(ZeroCtxtLike, *ctxt);
      acc.resize(g, tmp);
    }

    // Check if we have the relevant constant in cache
    CachedzzxMatrix* zcp;
    CachedDCRTMatrix* dcp;
    mat.getCache(&zcp, &dcp);

    // Process the diagonals in giant-step/baby-step order
    std::vector<zzX> cpolys(g); // scratch space for encoding consts
    std::vector<PtxtPtr> ptrs;  // pointers to these constants
    for (long j = 0; j < dDivg; j++) { // giant steps
      long jg = j*g;            // beginning index of this giant step

      // get all the constants rot^{-i}(const_{i+g*j}) for this step
      PtxtPtr::Type ty = getConsts(ptrs, cpolys, zcp, dcp,
                                   dim, jg, D, oneTransform);

      if (ty==PtxtPtr::ZERO) continue; // all consts are zero

      // Store constants in cache and/or multiply/add them

      if (ctxt!=nullptr) {  // rotate by jg, multiply & add
        Ctxt shCtxt(*ctxt); // temporary to hold current rot^{g*j}(X)

        if (j>0) {
          shCtxt = *ctxt;
          ea.rotate1D(shCtxt, dim, jg); // rotate by i
	} // if j==0 we already have *shCtxt == *ctxt

        if (ty==PtxtPtr::DCRT) for (long i=0; i<min(g,D-jg); i++) {
            if (ptrs[i].dp!=nullptr) {
              Ctxt tmp(shCtxt);
              tmp.multByConstant(*(ptrs[i].dp));
              acc[i] += tmp;
            }
          }
        else /*ty==PtxtPtr::ZZX*/ for (long i=0; i<min(g,D-jg); i++) {
            if (ptrs[i].zp!=nullptr) {
              Ctxt tmp(shCtxt);
              tmp.multByConstant(*(ptrs[i].zp));
              acc[i] += tmp;
            }
          }
      }

      if (buildCache==cachezzX) for (long i=0; i<min(g,D-jg); i++) {
          if (ptrs[i].zp!=nullptr)
            (*zCache)[i+jg].reset(new zzX(*(ptrs[i].zp)));
        }
      else if (buildCache==cacheDCRT) for (long i=0; i<min(g,D-jg); i++) {
          if (ptrs[i].zp!=nullptr)
            (*dCache)[i+jg].reset(new DoubleCRT(*(ptrs[i].zp),ea.getContext()));
        }
      // end of giant-step loop
    }
    // Compute the result as \sum_{i=0}^{g-1} rho^i(Y_i)
    if (ctxt!=nullptr) {
      *ctxt = acc[0];
      for (long i = 1; i < g; i++) {
        ea.rotate1D(acc[i], dim, i);
        *ctxt += acc[i];
      }
    }
    // "install" the cache if needed
    if (buildCache == cachezzX)
      mat.installzzxcache(zCache);
    else if (buildCache == cacheDCRT)
      mat.installDCRTcache(dCache);
  } // end of multiply(...)
};

// Wrapper functions around the implemenmtation class
static void matmul1d(Ctxt* ctxt, MatMulBase& mat, long dim, bool oneTransform,
                     MatrixCacheType buildCache)
{
  MatMulLock locking(mat, buildCache);

  // If locking.getType()!=cacheEmpty then we really do need to
  // build the cache, and we also have the lock for it.

  if (locking.getType()==cacheEmpty && ctxt==nullptr) //  nothing to do
    return;

  switch (mat.getEA().getTag()) {
    case PA_GF2_tag: {
      matmul1D_impl<PA_GF2> M(mat, dim, locking.getType());
      M.multiply(ctxt, dim, oneTransform);
      break;
    }
    case PA_zz_p_tag: {
      matmul1D_impl<PA_zz_p> M(mat, dim, locking.getType());
      M.multiply(ctxt, dim, oneTransform);
      break;
    }
    default:
      throw std::logic_error("matmul1d: neither PA_GF2 nor PA_zz_p");
  }
}
void buildCache4MatMul1D(MatMulBase& mat, long dim,
                         MatrixCacheType buildCache)
{ matmul1d(nullptr, mat, dim, true, buildCache); }

void matMul1D(Ctxt& ctxt, MatMulBase& mat,long dim,
              MatrixCacheType buildCache)
{ matmul1d(&ctxt, mat, dim, true, buildCache); }

void buildCache4MatMulti1D(MatMulBase& mat,long dim,
                           MatrixCacheType buildCache)
{ matmul1d(nullptr, mat, dim, false, buildCache); }

void matMulti1D(Ctxt& ctxt,MatMulBase& mat,long dim,
                MatrixCacheType buildCache)
{ matmul1d(&ctxt, mat, dim, false, buildCache); }

/********************************************************************
 ********************************************************************/
// Applying matmul to plaintext, useful for debugging

template<class type>
class matmul1D_pa_impl {
public:
  PA_INJECT(type)

  static void multiply(NewPlaintextArray& pa, MatMul<type>& mat,
		       long dim, bool oneTrans)
  {
    const EncryptedArrayDerived<type>& ea = mat.getEA().getDerived(type());
    RBak bak; bak.save(); ea.getTab().restoreContext();

    long n = ea.size();
    long D = ea.sizeOfDimension(dim);

    vector< vector<RX> > data1(n/D);
    for (long k = 0; k < n/D; k++)
      data1[k].resize(D);

    // copy the data into a vector of 1D vectors
    vector<RX>& data = pa.getData<type>();
    for (long i = 0; i < n; i++) {
      long k,j;
      std::tie(k,j) = ea.getContext().zMStar.breakIndexByDim(i, dim);
      data1[k][j] = data[i];       // k= along dim, j = the rest of i
    }

    // multiply each one of the vectors by the same matrix
    for (long k = 0; k < n/D; k++) {
      for (long j = 0; j < D; j++) { // simple matrix-vector multiplication
	std::pair<long,long> p(k,j);
	long idx = ea.getContext().zMStar.assembleIndexByDim(p, dim);

	RX acc, val, tmp;
	acc = 0;
        for (long i = 0; i < D; i++) {
          bool zero = oneTrans? mat.get(val, i, j) : mat.multiGet(val,i,j,k);
          if (!zero) {
            NTL::mul(tmp, data1[k][i], val);
            NTL::add(acc, acc, tmp);
          }
        }
        rem(data[idx], acc, ea.getG()); // store the result in the data array
      }
    }
  }
};
// A wrapper around the implementation class
static void matmul1d(NewPlaintextArray& pa, MatMulBase& mat,
		     long dim, bool oneTrans)
{
  switch (mat.getEA().getTag()) {
    case PA_GF2_tag: {
      matmul1D_pa_impl<PA_GF2>::multiply(pa,
                      dynamic_cast< MatMul<PA_GF2>& >(mat), dim, oneTrans);
      return;
    }
    case PA_zz_p_tag: {
      matmul1D_pa_impl<PA_zz_p>::multiply(pa,
                      dynamic_cast<MatMul<PA_zz_p>&>(mat), dim, oneTrans);
      return;
    }
    default:
      throw std::logic_error("matMul1D: neither PA_GF2 nor PA_zz_p");
  }
}

void matMul1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)
{
  matmul1d(pa, mat, dim, true);
}
void matMulti1D(NewPlaintextArray& pa, MatMulBase& mat, long dim)
{
  matmul1d(pa, mat, dim, false);
}

#endif


text:
#pragma once

#include "GCIncomingRefCounted.h"
#include "Heap.h"

namespace JSC {

template<typename T>
bool GCIncomingRefCounted<T>::addIncomingReference(JSCell* cell)
{
    if (!hasAnyIncoming()) {
        m_encodedPointer = bitwise_cast<uintptr_t>(cell) | singletonFlag();
        this->setIsDeferred(true);
        ASSERT(hasSingleton());
        return true;
    }

    ASSERT(Heap::heap(incomingReferenceAt(0)) == Heap::heap(cell));

    if (hasSingleton()) {
        Vector<JSCell*>* vector = new Vector<JSCell*>();
        vector->append(singleton());
        vector->append(cell);
        m_encodedPointer = bitwise_cast<uintptr_t>(vector);
        ASSERT(hasVectorOfCells());
        return false;
    }

    vectorOfCells()->append(cell);
    return false;
}

template<typename T>
template<typename FilterFunctionType>
bool GCIncomingRefCounted<T>::filterIncomingReferences(FilterFunctionType& filterFunction)
{
    const bool verbose = false;

    if (verbose)
        dataLog("Filtering incoming references.\n");

    if (!hasAnyIncoming()) {
        ASSERT(!this->isDeferred());
        ASSERT(this->refCount());
        if (verbose)
            dataLog("    Has no incoming.\n");
        return false;
    }

    ASSERT(this->isDeferred());

    if (hasSingleton()) {
        if (filterFunction(singleton())) {
            if (verbose)
                dataLog("   Singleton passed.\n");
            return false;
        }

        if (verbose)
            dataLog("   Removing singleton.\n");
        m_encodedPointer = 0;
        ASSERT(!hasAnyIncoming());
        this->setIsDeferred(false);
        return true;
    }

    if (verbose)
        dataLog("   Has ", vectorOfCells()->size(), " entries.\n");
    for (size_t i = 0; i < vectorOfCells()->size(); ++i) {
        if (filterFunction(vectorOfCells()->at(i)))
            continue;
        vectorOfCells()->at(i--) = vectorOfCells()->last();
        vectorOfCells()->removeLast();
    }

    if (vectorOfCells()->size() >= 2) {
        if (verbose)
            dataLog("   Still has ", vectorOfCells()->size(), " entries.\n");
        return false;
    }

    if (vectorOfCells()->isEmpty()) {
        if (verbose)
            dataLog("   Removing.\n");
        delete vectorOfCells();
        m_encodedPointer = 0;
        ASSERT(!hasAnyIncoming());
        this->setIsDeferred(false);
        return true;
    }

    if (verbose)
        dataLog("   Shrinking to singleton.\n");
    JSCell* singleton = vectorOfCells()->at(0);
    delete vectorOfCells();
    m_encodedPointer = bitwise_cast<uintptr_t>(singleton) | singletonFlag();
    ASSERT(hasSingleton());
    return false;
}

} // namespace JSC


text:
package packp

import (
	"bytes"
	"fmt"
	"io"

	"gopkg.in/src-d/go-git.v4/plumbing"
	"gopkg.in/src-d/go-git.v4/plumbing/format/pktline"
)

const (
	shallowLineLen   = 48
	unshallowLineLen = 50
)

type ShallowUpdate struct {
	Shallows   []plumbing.Hash
	Unshallows []plumbing.Hash
}

func (r *ShallowUpdate) Decode(reader io.Reader) error {
	s := pktline.NewScanner(reader)

	for s.Scan() {
		line := s.Bytes()
		line = bytes.TrimSpace(line)

		var err error
		switch {
		case bytes.HasPrefix(line, shallow):
			err = r.decodeShallowLine(line)
		case bytes.HasPrefix(line, unshallow):
			err = r.decodeUnshallowLine(line)
		case bytes.Equal(line, pktline.Flush):
			return nil
		}

		if err != nil {
			return err
		}
	}

	return s.Err()
}

func (r *ShallowUpdate) decodeShallowLine(line []byte) error {
	hash, err := r.decodeLine(line, shallow, shallowLineLen)
	if err != nil {
		return err
	}

	r.Shallows = append(r.Shallows, hash)
	return nil
}

func (r *ShallowUpdate) decodeUnshallowLine(line []byte) error {
	hash, err := r.decodeLine(line, unshallow, unshallowLineLen)
	if err != nil {
		return err
	}

	r.Unshallows = append(r.Unshallows, hash)
	return nil
}

func (r *ShallowUpdate) decodeLine(line, prefix []byte, expLen int) (plumbing.Hash, error) {
	if len(line) != expLen {
		return plumbing.ZeroHash, fmt.Errorf("malformed %s%q", prefix, line)
	}

	raw := string(line[expLen-40 : expLen])
	return plumbing.NewHash(raw), nil
}

func (r *ShallowUpdate) Encode(w io.Writer) error {
	e := pktline.NewEncoder(w)

	for _, h := range r.Shallows {
		if err := e.Encodef("%s%s\n", shallow, h.String()); err != nil {
			return err
		}
	}

	for _, h := range r.Unshallows {
		if err := e.Encodef("%s%s\n", unshallow, h.String()); err != nil {
			return err
		}
	}

	return e.Flush()
}


text:
@interface NewRegulationViewController () <ERDataManagerDelegate, UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *regTitle;
@property (weak, nonatomic) IBOutlet UITextField *regFaculty;
@property (weak, nonatomic) IBOutlet UITextField *regDegree;
@property (weak, nonatomic) IBOutlet UITextField *regCP;
@property (weak, nonatomic) IBOutlet UIButton *regCreateButton;
@property (weak, nonatomic) IBOutlet UITextField *regDate;
- (IBAction)regCreate:(id)sender;

@end

@implementation NewRegulationViewController
@synthesize regTitle;
@synthesize regFaculty;
@synthesize regDegree;
@synthesize regCP;
@synthesize regCreateButton;
@synthesize regDate;

- (void)viewDidUnload {
    [self setRegTitle:nil];
    [self setRegFaculty:nil];
    [self setRegDegree:nil];
    [self setRegCP:nil];
    [self setRegDate:nil];
    [self setRegCreateButton:nil];
    [super viewDidUnload];
}

- (void) viewDidLoad
{
    [super viewDidLoad];
    self.dataManager = [[ERDataManager alloc] init];
    self.dataManager.delegate = self;
    [self.dataManager accessDatabase];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *backgroundImage = [userDefaults stringForKey:@"backgroundImage"];
    if (!backgroundImage)
    {
        backgroundImage = @"background_1.jpg";
        [userDefaults setObject:backgroundImage forKey:@"backgroundImage"];
        [userDefaults synchronize];
    }
    self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImage]];
}

- (IBAction)touchDownBackground:(id)sender {
    [self.regCP resignFirstResponder];
    [self.regFaculty resignFirstResponder];
    [self.regTitle resignFirstResponder];
    [self.regDate resignFirstResponder];
    [self.regDegree resignFirstResponder];
    NSLog(@"touched");
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)ERDocumentIsReady:(ERDataManager *)sender
{
    NSLog(@"Datamanager bereit, Knopf aktiviert");
    [self.regCreateButton setUserInteractionEnabled:YES];
}

- (void)ERSavingComplete:(ERDataManager *)sender
{
    self.dataManager = nil;
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (IBAction)cancel:(id)sender {
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (IBAction)regCreate:(id)sender {
    //check all textfields for information
    if (![self.regTitle.text isEqualToString:@""] && ![self.regFaculty.text isEqualToString:@""] && ![self.regDegree.text isEqualToString:@""] && ![self.regDate.text isEqualToString:@""] && ![self.regCP.text isEqualToString:@""]) {
        NSLog(@"Alle Felder ausgefuellt");
        [self.dataManager saveEmptyRegulation:self.regTitle.text date:self.regDate.text degree:self.regDegree.text cp:self.regCP.text faculty:self.regFaculty.text];
    }else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Achtung" message:@"Bitte füllen sie alle Felder aus!" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
        [alertView show];
        [self resignFirstResponder];
    }
}

@end


text:
typedef struct
{
   // Handle to a program object
   GLuint programObject;

   // Sampler location
   GLint samplerLoc;

   // Texture handle
   GLuint textureId;

} UserData;

///
// Create a simple 2x2 texture image with four different colors
//
GLuint CreateSimpleTexture2D( )
{
   // Texture object handle
   GLuint textureId;

   // 2x2 Image, 3 bytes per pixel (R, G, B)
   GLubyte pixels[4 * 3] =
   {
      255,   0,   0, // Red
        0, 255,   0, // Green
        0,   0, 255, // Blue
      255, 255,   0  // Yellow
   };

   // Use tightly packed data
   glPixelStorei ( GL_UNPACK_ALIGNMENT, 1 );

   // Generate a texture object
   glGenTextures ( 1, &textureId );

   // Bind the texture object
   glBindTexture ( GL_TEXTURE_2D, textureId );

   // Load the texture
   glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels );

   // Set the filtering mode
   glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
   glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

   return textureId;

}

///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
   UserData *userData = esContext->userData;
   char vShaderStr[] =
      "#version 300 es                            \n"
      "layout(location = 0) in vec4 a_position;   \n"
      "layout(location = 1) in vec2 a_texCoord;   \n"
      "out vec2 v_texCoord;                       \n"
      "void main()                                \n"
      "{                                          \n"
      "   gl_Position = a_position;               \n"
      "   v_texCoord = a_texCoord;                \n"
      "}                                          \n";

   char fShaderStr[] =
      "#version 300 es                                     \n"
      "precision mediump float;                            \n"
      "in vec2 v_texCoord;                                 \n"
      "layout(location = 0) out vec4 outColor;             \n"
      "uniform sampler2D s_texture;                        \n"
      "void main()                                         \n"
      "{                                                   \n"
      "  outColor = texture( s_texture, v_texCoord );      \n"
      "}                                                   \n";

   // Load the shaders and get a linked program object
   userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );

   // Get the sampler location
   userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );

   // Load the texture
   userData->textureId = CreateSimpleTexture2D ();

   glClearColor ( 1.0f, 1.0f, 1.0f, 0.0f );
   return TRUE;
}

///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
   UserData *userData = esContext->userData;
   GLfloat vVertices[] = { -0.5f,  0.5f, 0.0f,  // Position 0
                            0.0f,  0.0f,        // TexCoord 0
                           -0.5f, -0.5f, 0.0f,  // Position 1
                            0.0f,  1.0f,        // TexCoord 1
                            0.5f, -0.5f, 0.0f,  // Position 2
                            1.0f,  1.0f,        // TexCoord 2
                            0.5f,  0.5f, 0.0f,  // Position 3
                            1.0f,  0.0f         // TexCoord 3
                         };
   GLushort indices[] = { 0, 1, 2, 0, 2, 3 };

   // Set the viewport
   glViewport ( 0, 0, esContext->width, esContext->height );

   // Clear the color buffer
   glClear ( GL_COLOR_BUFFER_BIT );

   // Use the program object
   glUseProgram ( userData->programObject );

   // Load the vertex position
   glVertexAttribPointer ( 0, 3, GL_FLOAT,
                           GL_FALSE, 5 * sizeof ( GLfloat ), vVertices );
   // Load the texture coordinate
   glVertexAttribPointer ( 1, 2, GL_FLOAT,
                           GL_FALSE, 5 * sizeof ( GLfloat ), &vVertices[3] );

   glEnableVertexAttribArray ( 0 );
   glEnableVertexAttribArray ( 1 );

   // Bind the texture
   glActiveTexture ( GL_TEXTURE0 );
   glBindTexture ( GL_TEXTURE_2D, userData->textureId );

   // Set the sampler texture unit to 0
   glUniform1i ( userData->samplerLoc, 0 );

   glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
}

///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
   UserData *userData = esContext->userData;

   // Delete texture object
   glDeleteTextures ( 1, &userData->textureId );

   // Delete program object
   glDeleteProgram ( userData->programObject );
}

int esMain ( ESContext *esContext )
{
   esContext->userData = malloc ( sizeof ( UserData ) );

   esCreateWindow ( esContext, "Simple Texture 2D", 320, 240, ES_WINDOW_RGB );

   if ( !Init ( esContext ) )
   {
      return GL_FALSE;
   }

   esRegisterDrawFunc ( esContext, Draw );
   esRegisterShutdownFunc ( esContext, ShutDown );

   return GL_TRUE;
}


text:
package com.elastisys.scale.cloudpool.openstack.driver.lab;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.elastisys.scale.cloudpool.api.CloudPool;
import com.elastisys.scale.cloudpool.api.types.CloudProviders;
import com.elastisys.scale.cloudpool.commons.basepool.BaseCloudPool;
import com.elastisys.scale.cloudpool.commons.basepool.StateStorage;
import com.elastisys.scale.cloudpool.commons.basepool.driver.CloudPoolDriver;
import com.elastisys.scale.cloudpool.commons.util.cli.CloudPoolCommandLineDriver;
import com.elastisys.scale.cloudpool.openstack.driver.OpenStackPoolDriver;
import com.elastisys.scale.cloudpool.openstack.driver.client.StandardOpenstackClient;
import com.elastisys.scale.commons.json.JsonUtils;
import com.google.gson.JsonObject;

/**
 * Simple lab program that exercises the OpenStack {@link CloudPool} via
 * commands read from {@code stdin}.
 */
public class RunPool {
    static Logger LOG = LoggerFactory.getLogger(RunPool.class);

    private static final Path configFile = Paths.get(System.getenv("HOME"), ".elastisys", "openstack", "config.json");

    private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

    public static void main(String[] args) throws Exception {
        StateStorage stateStorage = StateStorage.builder(new File("target/state")).build();
        CloudPoolDriver openstackDriver = new OpenStackPoolDriver(new StandardOpenstackClient(),
                CloudProviders.OPENSTACK);
        CloudPool pool = new BaseCloudPool(stateStorage, openstackDriver, executor);

        JsonObject config = JsonUtils.parseJsonFile(configFile.toFile()).getAsJsonObject();
        pool.configure(config);

        new CloudPoolCommandLineDriver(pool).start();

        executor.shutdownNow();
    }
}


text:
Imports SistFoncreagro.BussinessEntities
Public Interface IAsistenteCotizacionRepository
    Sub SaveAsistenteCotizacion(ByVal asistenteCotizacion As AsistenteCotizacion)
    Sub DeleteAsistenteCotizacion(ByVal IdAsistenteCotizacion As Int32)
    Function GetAllFromAsistennteCotizacionByIdCotizacion(ByVal IdCotizacion As Int32) As List(Of AsistenteCotizacion)
End Interface


text:
Webpy Framework
===============

Webpy_ framework is easy to setup, once that python-social-auth_ is installed
or accessible in the ``PYTHONPATH``, just add the needed configurations to make
it run.

Dependencies
------------

The `Webpy app` depends on sqlalchemy_, there's no support for others
ORMs yet but pull-requests are welcome.

Installing
----------

From pypi_::

    $ pip install social-auth-app-webpy

Configuration
-------------

Add the needed settings into ``web.config`` store. Settings are prefixed with
``SOCIAL_AUTH_`` but there's a helper for it::

    from social_core.utils import setting_name

    web.config[setting_name('USER_MODEL')] = 'models.User'
    web.config[setting_name('LOGIN_REDIRECT_URL')] = '/done/'
    web.config[setting_name('AUTHENTICATION_BACKENDS')] = (
        'social_core.backends.google.GoogleOAuth2',
        ...
    )

Add all the settings needed for the app (check Configuration_ section for
details).

URLs
----

Add the social application into URLs::

    from social_webpy import app as social_app

    urls = (
        ...
        '', social_app.app_social
        ...
    )

Session
-------

python-social-auth_ depends on sessions storage to keep some essential values,
usually redirects and ``state`` parameters used to validate authentication
process on OAuth providers.

The `Webpy built-in app` expects the session reference to be available under
``web.web_session`` so ensure it's available there.

User model
----------

Like the other apps, the User model must be defined on settings since
a reference to it is kept on ``UserSocialAuth`` instance. Define like this::

    web.config[setting_name('USER_MODEL')] = 'models.User'

Where the value is the import path to the User model used on your project.

.. _python-social-auth: https://github.com/python-social-auth
.. _Webpy: http://webpy.org/
.. _Webpy built-in app: https://github.com/python-social-auth/social-app-webpy
.. _sqlalchemy: http://www.sqlalchemy.org/
.. _pypi: http://pypi.python.org/pypi/social-auth-app-webpy/


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'chrome://resources/cr_elements/cr_toggle/cr_toggle.js';
import 'chrome://resources/cr_elements/cr_radio_group/cr_radio_group.js';
import 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.js';

import {CrRadioButtonElement} from 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.js';
import {CrRadioGroupElement} from 'chrome://resources/cr_elements/cr_radio_group/cr_radio_group.js';
import {CrToggleElement} from 'chrome://resources/cr_elements/cr_toggle/cr_toggle.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {CustomizeChromePageHandlerInterface} from './customize_chrome.mojom-webui.js';
import {CustomizeChromeApiProxy} from './customize_chrome_api_proxy.js';
import {getTemplate} from './shortcuts.html.js';

export interface ShortcutsElement {
  $: {
    showToggle: CrToggleElement,
    shortcutsRadioSelection: CrRadioGroupElement,
    customLinksButton: CrRadioButtonElement,
    mostVisitedButton: CrRadioButtonElement,
  };
}

export interface ShortcutsElement {}

export class ShortcutsElement extends PolymerElement {
  static get is() {
    return 'customize-chrome-shortcuts';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      customLinksEnabled_: Boolean,
      show_: Boolean,
    };
  }

  private customLinksEnabled_: boolean;
  private show_: boolean;
  private pageHandler_: CustomizeChromePageHandlerInterface;

  constructor() {
    super();
    const {handler} = CustomizeChromeApiProxy.getInstance();
    this.pageHandler_ = handler;
    // TODO(crbug.com/1384278) Auto update most visited settings if they change
    // while the side panel is open.
    this.pageHandler_.getMostVisitedSettings().then(
        ({customLinksEnabled, shortcutsVisible}) => {
          this.customLinksEnabled_ = customLinksEnabled;
          this.show_ = shortcutsVisible;
        });
  }

  override connectedCallback() {
    super.connectedCallback();
  }

  private setMostVisitedSettings_() {
    this.pageHandler_.setMostVisitedSettings(
        this.customLinksEnabled_, /* shortcutsVisible= */ this.show_);
  }

  private onShortcutsRadioSelectionChanged_(e: CustomEvent<{value: string}>) {
    this.customLinksEnabled_ = e.detail.value === 'customLinksOption';
    this.setMostVisitedSettings_();
  }

  private shortcutsRadioSelection_(): string {
    return this.customLinksEnabled_ ? 'customLinksOption' : 'mostVisitedOption';
  }

  private onShowChange_(e: CustomEvent<boolean>) {
    this.show_ = e.detail;
    this.setMostVisitedSettings_();
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'customize-chrome-shortcuts': ShortcutsElement;
  }
}

customElements.define(ShortcutsElement.is, ShortcutsElement);