text:
module.exports = function (sender, context, data) {

    var authMngr = sender.server.require('./cms/authMngr.js')(sender.server);

    if (!context.internal) {
        if (!context.req.session.user) {
            return context.error(401, 'Access denied');
        }

        else if (context.req.session.user.id !== data.id) {
            if (!context.internal && !authMngr.isAuthorized(context.req.session.user, 'users', 'R'))
                return context.error(401, 'Access denied');
        }
    }

    context.done();

};


text:
// -------------------------------------------------------------------
//
// eleveldb: Erlang Wrapper for LevelDB (http://code.google.com/p/leveldb/)
//
// Copyright (c) 2011-2015 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.  You may obtain
// a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------

#include <syslog.h>

#ifndef INCL_WORKITEMS_H
    #include "workitems.h"
#endif

#include "leveldb/atomics.h"
#include "leveldb/cache.h"
#include "leveldb/filter_policy.h"
#include "leveldb/perf_count.h"

// error_tuple duplicated in workitems.cc and eleveldb.cc ... how to fix?
static ERL_NIF_TERM error_tuple(ErlNifEnv* env, ERL_NIF_TERM error, leveldb::Status& status)
{
    ERL_NIF_TERM reason = enif_make_string(env, status.ToString().c_str(),
                                           ERL_NIF_LATIN1);
    return enif_make_tuple2(env, eleveldb::ATOM_ERROR,
                            enif_make_tuple2(env, error, reason));
}

static ERL_NIF_TERM slice_to_binary(ErlNifEnv* env, leveldb::Slice s)
{
    ERL_NIF_TERM result;
    unsigned char* value = enif_make_new_binary(env, s.size(), &result);
    memcpy(value, s.data(), s.size());
    return result;
}

namespace eleveldb {

/**
 * WorkTask functions
 */

WorkTask::WorkTask(ErlNifEnv *caller_env, ERL_NIF_TERM& caller_ref)
    : terms_set(false)
{
    if (NULL!=caller_env)
    {
        local_env_ = enif_alloc_env();
        caller_ref_term = enif_make_copy(local_env_, caller_ref);
        caller_pid_term = enif_make_pid(local_env_, enif_self(caller_env, &local_pid));
        terms_set=true;
    }   // if
    else
    {
        local_env_=NULL;
        terms_set=false;
    }   // else

    return;

}   // WorkTask::WorkTask

WorkTask::WorkTask(ErlNifEnv *caller_env, ERL_NIF_TERM& caller_ref, DbObject * DbPtr)
    : m_DbPtr(DbPtr), terms_set(false)
{
    if (NULL!=caller_env)
    {
        local_env_ = enif_alloc_env();
        caller_ref_term = enif_make_copy(local_env_, caller_ref);
        caller_pid_term = enif_make_pid(local_env_, enif_self(caller_env, &local_pid));
        terms_set=true;
    }   // if
    else
    {
        local_env_=NULL;
        terms_set=false;
    }   // else

    return;

}   // WorkTask::WorkTask

WorkTask::~WorkTask()
{
    ErlNifEnv * env_ptr;

    // this is likely overkill in the present code, but seemed
    //  important at one time and leaving for safety
    env_ptr=local_env_;
    if (leveldb::compare_and_swap(&local_env_, env_ptr, (ErlNifEnv *)NULL)
        && NULL!=env_ptr)
    {
        enif_free_env(env_ptr);
    }   // if

    return;

}   // WorkTask::~WorkTask

void
WorkTask::operator()()
{
    // call the DoWork() method defined by the subclass
    basho::async_nif::work_result result = DoWork();
    if (result.is_set())
    {
        ErlNifPid pid;
        if(0 != enif_get_local_pid(this->local_env(), this->pid(), &pid))
        {
            /* Assemble a notification of the following form:
               { PID CallerHandle, ERL_NIF_TERM result } */
            ERL_NIF_TERM result_tuple = enif_make_tuple2(this->local_env(),
                                                         this->caller_ref(),
                                                         result.result());

            enif_send(0, &pid, this->local_env(), result_tuple);
        }
    }
}

/**
 * OpenTask functions
 */

OpenTask::OpenTask(
    ErlNifEnv* caller_env,
    ERL_NIF_TERM& _caller_ref,
    const std::string& db_name_,
    leveldb::Options *open_options_)
    : WorkTask(caller_env, _caller_ref),
    db_name(db_name_), open_options(open_options_)
{
}   // OpenTask::OpenTask

work_result
OpenTask::DoWork()
{
    void * db_ptr_ptr;
    leveldb::DB *db(0);

    leveldb::Status status = leveldb::DB::Open(*open_options, db_name, &db);

    if(!status.ok())
        return error_tuple(local_env(), ATOM_ERROR_DB_OPEN, status);

    db_ptr_ptr=DbObject::CreateDbObject(db, open_options);

    // create a resource reference to send erlang
    ERL_NIF_TERM result = enif_make_resource(local_env(), db_ptr_ptr);

    // clear the automatic reference from enif_alloc_resource in CreateDbObject
    enif_release_resource(db_ptr_ptr);

    return work_result(local_env(), ATOM_OK, result);

}   // OpenTask::DoWork()

/**
 * MoveTask functions
 */

work_result
MoveTask::DoWork()
{
    leveldb::Iterator* itr;

    itr=m_ItrWrap->get();

//
// race condition of prefetch clearing db iterator while
//  async_iterator_move looking at it.
//

    // iterator_refresh operation
    if (m_ItrWrap->m_Options.iterator_refresh && m_ItrWrap->m_StillUse)
    {
        struct timeval tv;

        gettimeofday(&tv, NULL);

        if (m_ItrWrap->m_IteratorStale < tv.tv_sec || NULL==itr)
        {
            m_ItrWrap->RebuildIterator();
            itr=m_ItrWrap->get();

            // recover position
            if (NULL!=itr && 0!=m_ItrWrap->m_RecentKey.size())
            {
                leveldb::Slice key_slice(m_ItrWrap->m_RecentKey);

                itr->Seek(key_slice);
                m_ItrWrap->m_StillUse=itr->Valid();
                if (!m_ItrWrap->m_StillUse)
                {
                    itr=NULL;
                    m_ItrWrap->PurgeIterator();
                }   // if
            }   // if
        }   // if
    }   // if

    // back to normal operation
    if(NULL == itr)
        return work_result(local_env(), ATOM_ERROR, ATOM_ITERATOR_CLOSED);

    switch(action)
    {
        case FIRST: itr->SeekToFirst(); break;

        case LAST:  itr->SeekToLast();  break;

        case PREFETCH:
        case PREFETCH_STOP:
        case NEXT:  if(itr->Valid()) itr->Next(); break;

        case PREV:  if(itr->Valid()) itr->Prev(); break;

        case SEEK:
        {
            leveldb::Slice key_slice(seek_target);

            itr->Seek(key_slice);
            break;
        }   // case

        default:
            // JFW: note: *not* { ERROR, badarg() } here-- we want the exception:
            // JDB: note: We can't send an exception as a message. It crashes Erlang.
            //            Changing to be {error, badarg}.
            return work_result(local_env(), ATOM_ERROR, ATOM_BADARG);
            break;

    }   // switch

    // Post processing before telling the world the results
    //  (while only one thread might be looking at objects)
    if (m_ItrWrap->m_Options.iterator_refresh)
    {
        if (itr->Valid())
        {
            m_ItrWrap->m_RecentKey.assign(itr->key().data(), itr->key().size());
        }   // if
        else if (PREFETCH_STOP!=action)
        {
            // release iterator now, not later
            m_ItrWrap->m_StillUse=false;
            m_ItrWrap->PurgeIterator();
            itr=NULL;
        }   // else
    }   // if

    // debug syslog(LOG_ERR, "                     MoveItem::DoWork() %d, %d, %d",
    //              action, m_ItrWrap->m_StillUse, m_ItrWrap->m_HandoffAtomic);

    // who got back first, us or the erlang loop
    if (leveldb::compare_and_swap(&m_ItrWrap->m_HandoffAtomic, 0, 1))
    {
        // this is prefetch of next iteration.  It returned faster than actual
        //  request to retrieve it.  Stop and wait for erlang to catch up.
        //  (even if this result is an Invalid() )
    }   // if
    else
    {
        // setup next race for the response
        m_ItrWrap->m_HandoffAtomic=0;

        if(NULL!=itr && itr->Valid())
        {
            if (PREFETCH==action && m_ItrWrap->m_PrefetchStarted)
                m_ResubmitWork=true;

            // erlang is waiting, send message
            if(m_ItrWrap->m_KeysOnly)
                return work_result(local_env(), ATOM_OK, slice_to_binary(local_env(), itr->key()));

            return work_result(local_env(), ATOM_OK,
                               slice_to_binary(local_env(), itr->key()),
                               slice_to_binary(local_env(), itr->value()));
        }   // if
        else
        {
            m_ItrWrap->m_PrefetchStarted=false;
            return work_result(local_env(), ATOM_ERROR, ATOM_INVALID_ITERATOR);
        }   // else

    }   // else

    return(work_result());
}

ErlNifEnv *
MoveTask::local_env()
{
    if (NULL==local_env_)
        local_env_ = enif_alloc_env();

    if (!terms_set)
    {
        caller_ref_term = enif_make_copy(local_env_, m_ItrWrap->itr_ref);
        caller_pid_term = enif_make_pid(local_env_, &local_pid);
        terms_set=true;
    }   // if

    return(local_env_);

}   // MoveTask::local_env

void
MoveTask::recycle()
{
    // test for race condition of simultaneous delete & recycle
    if (1<RefInc())
    {
        if (NULL!=local_env_)
            enif_clear_env(local_env_);

        terms_set=false;
        m_ResubmitWork=false;

        // only do this in non-race condition
        RefDec();
    }   // if
    else
    {
        // touch NOTHING
    }   // else

}   // MoveTask::recycle

/**
 * DestroyTask functions
 */

DestroyTask::DestroyTask(
    ErlNifEnv* caller_env,
    ERL_NIF_TERM& _caller_ref,
    const std::string& db_name_,
    leveldb::Options *open_options_)
    : WorkTask(caller_env, _caller_ref),
    db_name(db_name_), open_options(open_options_)
{
}   // DestroyTask::DestroyTask

work_result
DestroyTask::DoWork()
{
    leveldb::Status status = leveldb::DestroyDB(db_name, *open_options);

    if(!status.ok())
        return error_tuple(local_env(), ATOM_ERROR_DB_DESTROY, status);

    return work_result(ATOM_OK);

}   // DestroyTask::DoWork()

} // namespace eleveldb

redpajama_set_name: RedPajamaGithub


text:
var express = require('express');
var router = express.Router();
var store = require('../service/noteStore');
var noteController = require('../controllers/noteController');

// list all notes
router.post('/', function(req, res) {
    noteController.setSessionParameters(req.session, req.body);
    noteController.all(req, res);
});

router.get('/', function(req, res) {
    console.log("GET /notes");
    noteController.setSessionParameters(req.session, req.body);
    noteController.all(req, res);
});

// new note
router.get('/add', function(req, res) {
    console.log("GET /notes/new");
    res.format({
        'text/html': function(){
            var date = JSON.stringify(new Date());
            res.render("add" ,{style:req.session.style, actualDate:date.substring(1, 11)});
        },
        'application/json': function(){
            res.send({});
        }
    });
});

// create note
router.post('/add', function(req, res) {
    console.log("POST /notes create");
    var tempNote = {title: req.body.title, desc: req.body.description, dueDate: req.body.dueDate, importance: req.body.importance};
    var errors = noteController.validate(req);
    if (errors) {
        var date = JSON.stringify(new Date());
        res.render("add", {style:req.session.style, note: tempNote, errors:errors,actualDate:date.substring(1, 11)});
    }
    else {
        store.add(req.body.title, req.body.description, req.body.importance,req.body.dueDate,req.body.finished, "unkown", function(err, note) {
            res.redirect("/");
        });
    }
});

// edit note
router.get('/:id', function(req, res) {
    console.log("GET /notes/:id");
    store.get(req.params.id, function(err, note) {
        res.format({
            'text/html': function(){
                res.render("edit", {note:note, style:req.session.style});
            },
            'application/json': function(){
                res.json(note);
            }
        });
    });
});

// write edited note
router.post('/:id', function(req, res) {
    console.log("PUT /notes/:id");
    if(req.body.finished != undefined)
        req.body.state = 'FINISHED';
    var tempNote = {title: req.body.title, desc: req.body.description, dueDate: req.body.dueDate, importance: req.body.importance};

    var errors = noteController.validate(req);
    if (errors) {
        var date = JSON.stringify(new Date());
        res.render("edit", {style:req.session.style, note: tempNote, errors:errors,actualDate:date.substring(1, 11)});
    }
    else {
        store.modify(req.params.id, req.body.title, req.body.description, req.body.importance,req.body.state,req.body.dueDate, function(err, note) {
            res.redirect("/");
        });
    }

});

router.get('/delete/:id', function(req, res) {
    console.log("DELETE /notes/delete/:id");
    store.get(req.params.id, function(err, note) {
        res.format({
            'text/html': function(){
                res.render("delete", {note:note, blocking:'true', style:req.session.style});
            },
            'application/json': function(){
                res.json(note);
            }
        });
    });
});

router.post('/delete/:id', function(req, res) {
    console.log("POST /notes/delete/:id");
    store.delete(req.params.id, function(err,note){
        res.redirect("/");
    });
});

module.exports = router;


text:
========
Aerodata
========

This project aims to provide a collection of utilities for parsing various
aeronautical data formats, starting with METAR data (both NOAA/FAA and WMO).

------
To dos
------
- More complete test suite
- Add parsing of METAR remarks section
- Add more data formats


text:
/**
 * @module ol/interaction/KeyboardZoom
 */
import EventType from '../events/EventType.js';
import Interaction, {zoomByDelta} from './Interaction.js';
import {targetNotEditable} from '../events/condition.js';

/**
 * @typedef {Object} Options
 * @property {number} [duration=100] Animation duration in milliseconds.
 * @property {import("../events/condition.js").Condition} [condition] A function that
 * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
 * boolean to indicate whether that event should be handled. Default is
 * {@link module:ol/events/condition.targetNotEditable}.
 * @property {number} [delta=1] The zoom level delta on each key press.
 */

/**
 * @classdesc
 * Allows the user to zoom the map using keyboard + and -.
 * Note that, although this interaction is by default included in maps,
 * the keys can only be used when browser focus is on the element to which
 * the keyboard events are attached. By default, this is the map div,
 * though you can change this with the `keyboardEventTarget` in
 * {@link module:ol/Map~Map}. `document` never loses focus but, for any other
 * element, focus will have to be on, and returned to, this element if the keys
 * are to function.
 * See also {@link module:ol/interaction/KeyboardPan~KeyboardPan}.
 * @api
 */
class KeyboardZoom extends Interaction {
  /**
   * @param {Options} [opt_options] Options.
   */
  constructor(opt_options) {
    super();

    const options = opt_options ? opt_options : {};

    /**
     * @private
     * @type {import("../events/condition.js").Condition}
     */
    this.condition_ = options.condition ? options.condition : targetNotEditable;

    /**
     * @private
     * @type {number}
     */
    this.delta_ = options.delta ? options.delta : 1;

    /**
     * @private
     * @type {number}
     */
    this.duration_ = options.duration !== undefined ? options.duration : 100;
  }

  /**
   * Handles the {@link module:ol/MapBrowserEvent map browser event} if it was a
   * `KeyEvent`, and decides whether to zoom in or out (depending on whether the
   * key pressed was '+' or '-').
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} `false` to stop event propagation.
   * @this {KeyboardZoom}
   */
  handleEvent(mapBrowserEvent) {
    let stopEvent = false;
    if (
      mapBrowserEvent.type == EventType.KEYDOWN ||
      mapBrowserEvent.type == EventType.KEYPRESS
    ) {
      const keyEvent = /** @type {KeyboardEvent} */ (mapBrowserEvent.originalEvent);
      const charCode = keyEvent.charCode;
      if (
        this.condition_(mapBrowserEvent) &&
        (charCode == '+'.charCodeAt(0) || charCode == '-'.charCodeAt(0))
      ) {
        const map = mapBrowserEvent.map;
        const delta =
          charCode == '+'.charCodeAt(0) ? this.delta_ : -this.delta_;
        const view = map.getView();
        zoomByDelta(view, delta, undefined, this.duration_);
        keyEvent.preventDefault();
        stopEvent = true;
      }
    }
    return !stopEvent;
  }
}

export default KeyboardZoom;


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Set of functions used to build OpenDocument Text dumps of tables
 *
 * @package PhpMyAdmin-Export
 * @subpackage ODT
 */
if (! defined('PHPMYADMIN')) {
    exit;
}

/**
 *
 */
if (isset($plugin_list)) {
    $hide_structure = false;
    if ($plugin_param['export_type'] == 'table' && !$plugin_param['single_table']) {
        $hide_structure = true;
    }
    $plugin_list['odt'] = array(
        'text' => __('Open Document Text'),
        'extension' => 'odt',
        'mime_type' => 'application/vnd.oasis.opendocument.text',
        'force_file' => true,
        'options' => array(), /* Filled later */
        'options_text' => __('Options'),
        );

    /* what to dump (structure/data/both) */
    $plugin_list['odt']['options'][]
        = array('type' => 'begin_group', 'text' => __('Dump table') , 'name' => 'general_opts');
    $plugin_list['odt']['options'][]
        = array('type' => 'radio', 'name' => 'structure_or_data', 'values' => array('structure' => __('structure'), 'data' => __('data'), 'structure_and_data' => __('structure and data')));
    $plugin_list['odt']['options'][] = array('type' => 'end_group');

    /* Structure options */
    if (!$hide_structure) {
        $plugin_list['odt']['options'][]
            = array('type' => 'begin_group', 'name' => 'structure', 'text' => __('Object creation options'), 'force' => 'data');
        if (!empty($GLOBALS['cfgRelation']['relation'])) {
            $plugin_list['odt']['options'][]
                = array('type' => 'bool', 'name' => 'relation', 'text' => __('Display foreign key relationships'));
        }
        $plugin_list['odt']['options'][]
            = array('type' => 'bool', 'name' => 'comments', 'text' => __('Display comments'));
        if (!empty($GLOBALS['cfgRelation']['mimework'])) {
            $plugin_list['odt']['options'][]
                = array('type' => 'bool', 'name' => 'mime', 'text' => __('Display MIME types'));
        }
        $plugin_list['odt']['options'][]
            = array('type' => 'end_group');
    }
    /* Data */
    $plugin_list['odt']['options'][]
        = array('type' => 'begin_group', 'name' => 'data', 'text' => __('Data dump options'), 'force' => 'structure');
    $plugin_list['odt']['options'][]
        = array('type' => 'bool', 'name' => 'columns', 'text' => __('Put columns names in the first row'));
    $plugin_list['odt']['options'][]
        = array('type' => 'text', 'name' => 'null', 'text' => __('Replace NULL with:'));
    $plugin_list['odt']['options'][]
        = array('type' => 'end_group');
} else {

    $GLOBALS['odt_buffer'] = '';
    include_once './libraries/opendocument.lib.php';

    /**
     * Outputs export footer
     *
     * @return bool Whether it succeeded
     *
     * @access public
     */
    function PMA_exportFooter()
    {
        $GLOBALS['odt_buffer'] .= '</office:text>'
            . '</office:body>'
            . '</office:document-content>';
        if (! PMA_exportOutputHandler(PMA_createOpenDocument('application/vnd.oasis.opendocument.text', $GLOBALS['odt_buffer']))) {
            return false;
        }
        return true;
    }

    /**
     * Outputs export header
     *
     * @return bool Whether it succeeded
     *
     * @access public
     */
    function PMA_exportHeader()
    {
        $GLOBALS['odt_buffer'] .= '<?xml version="1.0" encoding="utf-8"?' . '>'
            . '<office:document-content '. $GLOBALS['OpenDocumentNS'] . 'office:version="1.0">'
            . '<office:body>'
            . '<office:text>';
        return true;
    }

    /**
     * Outputs database header
     *
     * @param string $db Database name
     *
     * @return bool Whether it succeeded
     *
     * @access public
     */
    function PMA_exportDBHeader($db)
    {
        $GLOBALS['odt_buffer'] .= '<text:h text:outline-level="1" text:style-name="Heading_1" text:is-list-header="true">'
            . __('Database') . ' ' . htmlspecialchars($db) . '</text:h>';
        return true;
    }

    /**
     * Outputs database footer
     *
     * @param string $db Database name
     *
     * @return bool Whether it succeeded
     *
     * @access public
     */
    function PMA_exportDBFooter($db)
    {
        return true;
    }

    /**
     * Outputs CREATE DATABASE statement
     *
     * @param string $db Database name
     *
     * @return bool Whether it succeeded
     *
     * @access public
     */
    function PMA_exportDBCreate($db)
    {
        return true;
    }

    /**
     * Outputs the content of a table in ODT format
     *
     * @param string $db        database name
     * @param string $table     table name
     * @param string $crlf      the end of line sequence
     * @param string $error_url the url to go back in case of error
     * @param string $sql_query SQL query for obtaining data
     *
     * @return bool Whether it succeeded
     *
     * @access public
     */
    function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
    {
        global $what;

        // Gets the data from the database
        $result      = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
        $fields_cnt  = PMA_DBI_num_fields($result);
        $fields_meta = PMA_DBI_get_fields_meta($result);
        $field_flags = array();
        for ($j = 0; $j < $fields_cnt; $j++) {
            $field_flags[$j] = PMA_DBI_field_flags($result, $j);
        }

        $GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2" text:is-list-header="true">'
            . __('Dumping data for table') . ' ' . htmlspecialchars($table) . '</text:h>';
        $GLOBALS['odt_buffer'] .= '<table:table table:name="' . htmlspecialchars($table) . '_structure">';
        $GLOBALS['odt_buffer'] .= '<table:table-column table:number-columns-repeated="' . $fields_cnt . '"/>';

        // If required, get fields name at the first line
        if (isset($GLOBALS[$what . '_columns'])) {
            $GLOBALS['odt_buffer'] .= '<table:table-row>';
            for ($i = 0; $i < $fields_cnt; $i++) {
                $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                    . '<text:p>' . htmlspecialchars(stripslashes(PMA_DBI_field_name($result, $i))) . '</text:p>'
                    . '</table:table-cell>';
            } // end for
            $GLOBALS['odt_buffer'] .= '</table:table-row>';
        } // end if

        // Format the data
        while ($row = PMA_DBI_fetch_row($result)) {
            $GLOBALS['odt_buffer'] .= '<table:table-row>';
            for ($j = 0; $j < $fields_cnt; $j++) {
                if (!isset($row[$j]) || is_null($row[$j])) {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p>' . htmlspecialchars($GLOBALS[$what . '_null']) . '</text:p>'
                        . '</table:table-cell>';
                // ignore BLOB
                } elseif (stristr($field_flags[$j], 'BINARY')
                        && $fields_meta[$j]->blob) {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p></text:p>'
                        . '</table:table-cell>';
                } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && ! $fields_meta[$j]->blob) {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="float" office:value="' . $row[$j] . '" >'
                        . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>'
                        . '</table:table-cell>';
                } else {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>'
                        . '</table:table-cell>';
                }
            } // end for
            $GLOBALS['odt_buffer'] .= '</table:table-row>';
        } // end while
        PMA_DBI_free_result($result);

        $GLOBALS['odt_buffer'] .= '</table:table>';

        return true;
    }

    /**
     * Outputs table's structure
     *
     * @param string $db          database name
     * @param string $table       table name
     * @param string $crlf        the end of line sequence
     * @param string $error_url   the url to go back in case of error
     * @param bool   $do_relation whether to include relation comments
     * @param bool   $do_comments whether to include the pmadb-style column comments
     *                            as comments in the structure; this is deprecated
     *                            but the parameter is left here because export.php
     *                            calls PMA_exportStructure() also for other export
     *                            types which use this parameter
     * @param bool   $do_mime     whether to include mime comments
     * @param bool   $dates       whether to include creation/update/check dates
     * @param string $export_mode 'create_table', 'triggers', 'create_view', 'stand_in'
     * @param string $export_type 'server', 'database', 'table'
     *
     * @return bool Whether it succeeded
     *
     * @access public
     */
    function PMA_exportStructure($db, $table, $crlf, $error_url, $do_relation = false, $do_comments = false, $do_mime = false, $dates = false, $export_mode, $export_type)
    {
        global $cfgRelation;

        /* Heading */
        $GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2" text:is-list-header="true">'
            . __('Table structure for table') . ' ' . htmlspecialchars($table) . '</text:h>';

        /**
         * Get the unique keys in the table
         */
        $unique_keys = array();
        $keys        = PMA_DBI_get_table_indexes($db, $table);
        foreach ($keys as $key) {
            if ($key['Non_unique'] == 0) {
                $unique_keys[] = $key['Column_name'];
            }
        }

        /**
         * Gets fields properties
         */
        PMA_DBI_select_db($db);

        // Check if we can use Relations
        if ($do_relation && !empty($cfgRelation['relation'])) {
            // Find which tables are related with the current one and write it in
            // an array
            $res_rel = PMA_getForeigners($db, $table);

            if ($res_rel && count($res_rel) > 0) {
                $have_rel = true;
            } else {
                $have_rel = false;
            }
        } else {
               $have_rel = false;
        } // end if

        /**
         * Displays the table structure
         */
        $GLOBALS['odt_buffer'] .= '<table:table table:name="' . htmlspecialchars($table) . '_data">';
        $columns_cnt = 4;
        if ($do_relation && $have_rel) {
            $columns_cnt++;
        }
        if ($do_comments) {
            $columns_cnt++;
        }
        if ($do_mime && $cfgRelation['mimework']) {
            $columns_cnt++;
        }
        $GLOBALS['odt_buffer'] .= '<table:table-column table:number-columns-repeated="' . $columns_cnt . '"/>';
        /* Header */
        $GLOBALS['odt_buffer'] .= '<table:table-row>';
        $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
            . '<text:p>' . __('Column') . '</text:p>'
            . '</table:table-cell>';
        $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
            . '<text:p>' . __('Type') . '</text:p>'
            . '</table:table-cell>';
        $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
            . '<text:p>' . __('Null') . '</text:p>'
            . '</table:table-cell>';
        $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
            . '<text:p>' . __('Default') . '</text:p>'
            . '</table:table-cell>';
        if ($do_relation && $have_rel) {
            $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                . '<text:p>' . __('Links to') . '</text:p>'
                . '</table:table-cell>';
        }
        if ($do_comments) {
            $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                . '<text:p>' . __('Comments') . '</text:p>'
                . '</table:table-cell>';
            $comments = PMA_getComments($db, $table);
        }
        if ($do_mime && $cfgRelation['mimework']) {
            $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                . '<text:p>' . __('MIME type') . '</text:p>'
                . '</table:table-cell>';
            $mime_map = PMA_getMIME($db, $table, true);
        }
        $GLOBALS['odt_buffer'] .= '</table:table-row>';

        $columns = PMA_DBI_get_columns($db, $table);
        foreach ($columns as $column) {
            $field_name = $column['Field'];
            $GLOBALS['odt_buffer'] .= '<table:table-row>';
            $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                . '<text:p>' . htmlspecialchars($field_name) . '</text:p>'
                . '</table:table-cell>';

            $extracted_fieldspec = PMA_extractFieldSpec($column['Type']);
            $type = htmlspecialchars($extracted_fieldspec['print_type']);
            if (empty($type)) {
                $type     = ' ';
            }

            $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                . '<text:p>' . htmlspecialchars($type) . '</text:p>'
                . '</table:table-cell>';
            if (!isset($column['Default'])) {
                if ($column['Null'] != 'NO') {
                    $column['Default'] = 'NULL';
                } else {
                    $column['Default'] = '';
                }
            } else {
                $column['Default'] = $column['Default'];
            }
            $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                . '<text:p>' . (($column['Null'] == '' || $column['Null'] == 'NO') ? __('No') : __('Yes')) . '</text:p>'
                . '</table:table-cell>';
            $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                . '<text:p>' . htmlspecialchars($column['Default']) . '</text:p>'
                . '</table:table-cell>';

            if ($do_relation && $have_rel) {
                if (isset($res_rel[$field_name])) {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p>' . htmlspecialchars($res_rel[$field_name]['foreign_table'] . ' (' . $res_rel[$field_name]['foreign_field'] . ')') . '</text:p>'
                        . '</table:table-cell>';
                }
            }
            if ($do_comments) {
                if (isset($comments[$field_name])) {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p>' . htmlspecialchars($comments[$field_name]) . '</text:p>'
                        . '</table:table-cell>';
                } else {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p></text:p>'
                        . '</table:table-cell>';
                }
            }
            if ($do_mime && $cfgRelation['mimework']) {
                if (isset($mime_map[$field_name])) {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p>' . htmlspecialchars(str_replace('_', '/', $mime_map[$field_name]['mimetype'])) . '</text:p>'
                        . '</table:table-cell>';
                } else {
                    $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">'
                        . '<text:p></text:p>'
                        . '</table:table-cell>';
                }
            }
            $GLOBALS['odt_buffer'] .= '</table:table-row>';
        } // end while

        $GLOBALS['odt_buffer'] .= '</table:table>';
        return true;
    } // end of the 'PMA_exportStructure' function

} // end else
?>


text:
// ---------------------------------------------------------------------------------------
// <copyright file="Static.cs" company="Corale">
//     Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
//     Permission is hereby granted, free of charge, to any person obtaining a copy of
//     this software and associated documentation files (the "Software"), to deal in
//     the Software without restriction, including without limitation the rights to
//     use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//     of the Software, and to permit persons to whom the Software is furnished to do
//     so, subject to the following conditions:
//
//     The above copyright notice and this permission notice shall be included in all
//     copies or substantial portions of the Software.
//
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//     WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//     CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//     Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
//     of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
//     do not take responsibility for any harm caused, direct or indirect, to any
//     Razer peripherals via the use of Colore.
//
//     "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------

namespace Corale.Colore.Razer.Keypad.Effects
{
    using System.Runtime.InteropServices;

    using Corale.Colore.Core;

    /// <summary>
    /// Static color effect.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct Static
    {
        /// <summary>
        /// Color to use.
        /// </summary>
        public Color Color;

        /// <summary>
        /// Initializes a new instance of the <see cref="Static" /> struct.
        /// </summary>
        /// <param name="color">Color to set.</param>
        public Static(Color color)
        {
            Color = color;
        }
    }
}


text:
package org.jboss.hal.client.patching.wizard;

import javax.inject.Provider;

import org.jboss.hal.ballroom.wizard.Wizard;
import org.jboss.hal.config.Environment;
import org.jboss.hal.core.runtime.server.Server;
import org.jboss.hal.core.runtime.server.ServerActions;
import org.jboss.hal.dmr.Operation;
import org.jboss.hal.dmr.Property;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.dmr.dispatch.Dispatcher;
import org.jboss.hal.flow.FlowContext;
import org.jboss.hal.flow.Progress;
import org.jboss.hal.flow.Task;
import org.jboss.hal.meta.Metadata;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.resources.Messages;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.spi.Callback;

import elemental2.promise.Promise;

import static java.util.Collections.singletonList;
import static org.jboss.hal.client.patching.PatchesColumn.PATCHING_TEMPLATE;
import static org.jboss.hal.client.patching.wizard.PatchState.CHECK_SERVERS;
import static org.jboss.hal.client.patching.wizard.PatchState.ROLLBACK;
import static org.jboss.hal.dmr.ModelDescriptionConstants.OVERRIDE;
import static org.jboss.hal.dmr.ModelDescriptionConstants.OVERRIDE_ALL;
import static org.jboss.hal.dmr.ModelDescriptionConstants.OVERRIDE_MODULE;
import static org.jboss.hal.dmr.ModelDescriptionConstants.PATCH_ID;
import static org.jboss.hal.dmr.ModelDescriptionConstants.PRESERVE;
import static org.jboss.hal.dmr.ModelDescriptionConstants.RESET_CONFIGURATION;
import static org.jboss.hal.dmr.ModelDescriptionConstants.ROLLBACK_OPERATION;
import static org.jboss.hal.dmr.ModelDescriptionConstants.ROLLBACK_TO;
import static org.jboss.hal.flow.Flow.sequential;

public class RollbackWizard extends PatchWizard {

    private final String patchId;

    public RollbackWizard(String patchId, Resources resources, Environment environment, Metadata metadata,
            StatementContext statementContext, Dispatcher dispatcher,
            Provider<Progress> progress, ServerActions serverActions, Callback callback) {
        super(resources, environment, metadata, statementContext, dispatcher, progress, serverActions, callback);
        this.patchId = patchId;
    }

    public void show() {
        Messages messages = resources.messages();
        Wizard.Builder<PatchContext, PatchState> wb = new Wizard.Builder<>(resources.constants().rollback(),
                new PatchContext());

        checkServersState(servers -> {
            if (servers != null) {
                wb.addStep(CHECK_SERVERS, new CheckRunningServersStep(resources, servers,
                        statementContext.selectedHost()));
            }
            wb.addStep(ROLLBACK, new org.jboss.hal.client.patching.wizard.RollbackStep(metadata, resources,
                    statementContext.selectedHost(), patchId))

                    .onBack((context, currentState) -> {
                        PatchState previous = null;
                        switch (currentState) {
                            case CHECK_SERVERS:
                                break;
                            case ROLLBACK:
                                previous = CHECK_SERVERS;
                                break;
                            default:
                                break;
                        }
                        return previous;
                    })
                    .onNext((context, currentState) -> {
                        PatchState next = null;
                        switch (currentState) {
                            case CHECK_SERVERS:
                                next = ROLLBACK;
                                break;
                            case ROLLBACK:
                                break;
                            default:
                                break;
                        }
                        return next;
                    })

                    .stayOpenAfterFinish()
                    .onFinish((wzd, context) -> {
                        String name = context.patchId;
                        wzd.showProgress(resources.constants().rollbackInProgress(), messages.rollbackInProgress(name));

                        sequential(new FlowContext(progress.get()),
                                singletonList(new RollbackTask(statementContext, dispatcher, serverActions, context)))
                                .then(__ -> {
                                    callback.execute();
                                    wzd.showSuccess(
                                            resources.constants().rollbackSuccessful(),
                                            messages.rollbackSucessful(name));
                                    return null;
                                })
                                .catch_(error -> {
                                    String message = String.valueOf(error);
                                    wzd.showError(resources.constants().rollbackError(),
                                            messages.rollbackError(message),
                                            message);
                                    return null;
                                });
                    });
            Wizard<PatchContext, PatchState> wizard = wb.build();
            wizard.show();
        });
    }

    static final class RollbackTask implements Task<FlowContext> {

        private final Dispatcher dispatcher;
        private final StatementContext statementContext;
        private final ServerActions serverActions;
        private final PatchContext patchContext;

        RollbackTask(StatementContext statementContext, Dispatcher dispatcher,
                ServerActions serverActions, PatchContext patchContext) {

            this.statementContext = statementContext;
            this.dispatcher = dispatcher;
            this.serverActions = serverActions;
            this.patchContext = patchContext;
        }

        @Override
        public Promise<FlowContext> apply(final FlowContext context) {
            if (patchContext.restartServers) {
                for (Property serverProp : patchContext.servers) {
                    Server server = new Server(statementContext.selectedHost(), serverProp);
                    serverActions.stopNow(server);
                }
            }

            ResourceAddress address = PATCHING_TEMPLATE.resolve(statementContext);
            Operation.Builder opBuilder = new Operation.Builder(address, ROLLBACK_OPERATION)
                    .param(PATCH_ID, patchContext.patchId)
                    .param(ROLLBACK_TO, patchContext.rollbackTo)
                    .param(RESET_CONFIGURATION, patchContext.resetConfiguration)
                    .param(OVERRIDE_ALL, patchContext.overrideAll)
                    .param(OVERRIDE_MODULE, patchContext.overrideModules);

            if (patchContext.override != null) {
                opBuilder.param(OVERRIDE, patchContext.override.toArray(new String[0]));
            }
            if (patchContext.preserve != null) {
                opBuilder.param(PRESERVE, patchContext.preserve.toArray(new String[0]));
            }
            Operation operation = opBuilder.build();

            return dispatcher.execute(operation).then(__ -> Promise.resolve(context));
        }
    }
}


text:
import { connect } from 'react-redux'

import {
  clearOAuthServer,
  fetchOAuthServer,
  fetchOAuthServerSchema,
  confirmAction
} from '../../../store/actions'

import OAuthServerItem from './OAuthServerItem'

const mapStateToProps = state => ({
  oAuthServer: state.oAuthServerReducer.oAuthServer,
  schema: state.oAuthServerReducer.oAuthServerSchema
})

export default connect(
  mapStateToProps,
  {
    clearOAuthServer,
    fetchOAuthServer,
    fetchOAuthServerSchema,
    confirmAction
  }
)(OAuthServerItem)


text:
package pvtdata

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"path/filepath"
	"time"

	"github.com/hyperledger/fabric/integration/chaincode/kvexecutor"
	"github.com/hyperledger/fabric/integration/nwo"
	"github.com/hyperledger/fabric/integration/nwo/commands"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"

	"github.com/tedsuo/ifrit"
)

var _ bool = Describe("Pvtdata dissemination for implicit collection", func() {
	var (
		network       *nwo.Network
		process       ifrit.Process
		orderer       *nwo.Orderer
		testChaincode chaincode
	)

	BeforeEach(func() {
		By("setting up the network")
		network = initThreeOrgsSetup(false)

		By("disabling pvtdata pull/dissemination/reconciliation on all peers except for enabling dissemination on org1 peers")
		for _, p := range network.Peers {
			core := network.ReadPeerConfig(p)
			core.Peer.Gossip.PvtData.PullRetryThreshold = 0
			core.Peer.Gossip.PvtData.ReconciliationEnabled = false
			// set timeout and reconnect interval to prevent test flake
			core.Peer.Gossip.DialTimeout = 5 * time.Second
			core.Peer.Gossip.ConnTimeout = 5 * time.Second
			core.Peer.Gossip.ReconnectInterval = 7 * time.Second
			if p.Organization == "Org1" {
				// enable dissemination on org1 peers
				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.RequiredPeerCount = 1
				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.MaxPeerCount = 3
				core.Peer.Gossip.PvtData.PushAckTimeout = 10 * time.Second
			} else {
				// disable dissemination on non-org1 peers
				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.RequiredPeerCount = 0
				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.MaxPeerCount = 0
			}
			network.WritePeerConfig(p, core)
		}

		By("starting the network")
		process, orderer = startNetwork(network)

		By("deploying new lifecycle chaincode")
		testChaincode = chaincode{
			Chaincode: nwo.Chaincode{
				Name:        "kvexecutor",
				Version:     "1.0",
				Path:        components.Build("github.com/hyperledger/fabric/integration/chaincode/kvexecutor/cmd"),
				Lang:        "binary",
				PackageFile: filepath.Join(network.RootDir, "kvexecutor.tar.gz"),
				Label:       "kvexecutor",
				Sequence:    "1",
			},
			isLegacy: false,
		}
		nwo.EnableCapabilities(network, channelID, "Application", "V2_0", orderer, network.Peers...)

		By("verifying org1.peer0 discovers all peers to ensure that gossip has been initialized")
		discoverAllPeers(network, network.Peer("Org1", "peer0"), channelID, 3, 5*time.Second)

		By("verifying org1.peer1 discovers all peers to ensure that gossip has been initialized")
		discoverAllPeers(network, network.Peer("Org1", "peer1"), channelID, 3, 5*time.Second)

		By("deploying chaincode to all peers")
		deployChaincode(network, orderer, testChaincode)
	})

	AfterEach(func() {
		testCleanup(network, process)
	})

	It("disseminates pvtdata of implicit collection for the peer's own org but not implicit collection for another org", func() {
		org1peer0 := network.Peer("Org1", "peer0")
		org1peer1 := network.Peer("Org1", "peer1")
		org2peer0 := network.Peer("Org2", "peer0")
		org2peer1 := network.Peer("Org2", "peer1")

		By("writing private data to org1's and org2's implicit collections")
		writeInput := []kvexecutor.KVData{
			{Collection: "_implicit_org_Org1MSP", Key: "org1_key1", Value: "org1_value1"},
			{Collection: "_implicit_org_Org2MSP", Key: "org2_key1", Value: "org2_value1"},
		}
		writeImplicitCollection(network, orderer, testChaincode.Name, writeInput, org1peer0, org2peer0)

		By("querying org1.peer0 for _implicit_org_Org1MSP collection data, expecting pvtdata")
		readInput1 := []kvexecutor.KVData{{Collection: "_implicit_org_Org1MSP", Key: "org1_key1"}}
		expectedMsg1, err := json.Marshal(writeInput[:1])
		Expect(err).NotTo(HaveOccurred())
		readImplicitCollection(network, org1peer0, testChaincode.Name, readInput1, string(expectedMsg1), true)

		// org1.peer1 should have _implicit_org_Org1MSP pvtdata because dissemination is enabled on org1 peers
		By("querying org1.peer1 for _implicit_org_Org1MSP collection data, expecting pvtdata")
		readImplicitCollection(network, org1peer1, testChaincode.Name, readInput1, string(expectedMsg1), true)

		By("querying org2.peer0 for _implicit_org_Org1MSP collection data, expecting error")
		readImplicitCollection(network, org2peer0, testChaincode.Name, readInput1,
			"private data matching public hash version is not available", false)

		By("querying org2.peer1 for _implicit_org_Org1MSP collection data, expecting error")
		readImplicitCollection(network, org2peer1, testChaincode.Name, readInput1,
			"private data matching public hash version is not available", false)

		By("querying org2.peer0 for _implicit_org_Org2MSP collection data, expecting pvtdata")
		readInput2 := []kvexecutor.KVData{{Collection: "_implicit_org_Org2MSP", Key: "org2_key1"}}
		expectedMsg2, err := json.Marshal(writeInput[1:])
		Expect(err).NotTo(HaveOccurred())
		readImplicitCollection(network, org2peer0, testChaincode.Name, readInput2, string(expectedMsg2), true)

		// org2.peer1 should have no _implicit_org_Org2MSP pvtdata because pull/dissemination/reconciliation are disabled on org2 peers
		By("querying org2.peer1 for _implicit_org_Org2MSP collection data, expecting error")
		readImplicitCollection(network, org2peer1, testChaincode.Name, readInput2,
			"private data matching public hash version is not available", false)

		By("querying org1.peer0 for _implicit_org_Org2MSP collection data, expecting error")
		readImplicitCollection(network, org1peer0, testChaincode.Name, readInput2,
			"private data matching public hash version is not available", false)

		By("querying org1.peer1 for _implicit_org_Org2MSP collection data, expecting error")
		readImplicitCollection(network, org1peer1, testChaincode.Name, readInput2,
			"private data matching public hash version is not available", false)
	})
})

func writeImplicitCollection(n *nwo.Network, orderer *nwo.Orderer, chaincodeName string, writeInput []kvexecutor.KVData, peers ...*nwo.Peer) {
	writeInputBytes, err := json.Marshal(writeInput)
	Expect(err).NotTo(HaveOccurred())
	writeInputBase64 := base64.StdEncoding.EncodeToString(writeInputBytes)

	peerAddresses := make([]string, 0)
	for _, peer := range peers {
		peerAddresses = append(peerAddresses, n.PeerAddress(peer, nwo.ListenPort))
	}
	command := commands.ChaincodeInvoke{
		ChannelID:     channelID,
		Orderer:       n.OrdererAddress(orderer, nwo.ListenPort),
		Name:          chaincodeName,
		Ctor:          fmt.Sprintf(`{"Args":["readWriteKVs","%s","%s"]}`, "", writeInputBase64),
		PeerAddresses: peerAddresses,
		WaitForEvent:  true,
	}
	invokeChaincode(n, peers[0], command)
	nwo.WaitUntilEqualLedgerHeight(n, channelID, nwo.GetLedgerHeight(n, peers[0], channelID), n.Peers...)
}

func readImplicitCollection(n *nwo.Network, peer *nwo.Peer, chaincodeName string, readInput []kvexecutor.KVData, expectedMsg string, expectSuccess bool) {
	readInputBytes, err := json.Marshal(readInput)
	Expect(err).NotTo(HaveOccurred())
	readInputBase64 := base64.StdEncoding.EncodeToString(readInputBytes)

	command := commands.ChaincodeQuery{
		ChannelID: channelID,
		Name:      chaincodeName,
		Ctor:      fmt.Sprintf(`{"Args":["readWriteKVs","%s","%s"]}`, readInputBase64, ""),
	}
	queryChaincode(n, peer, command, expectedMsg, expectSuccess)
}

func invokeChaincode(n *nwo.Network, peer *nwo.Peer, command commands.ChaincodeInvoke) {
	sess, err := n.PeerUserSession(peer, "User1", command)
	Expect(err).NotTo(HaveOccurred())
	Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit(0))
	Expect(sess.Err).To(gbytes.Say("Chaincode invoke successful."))
}

func queryChaincode(n *nwo.Network, peer *nwo.Peer, command commands.ChaincodeQuery, expectedMessage string, expectSuccess bool) {
	sess, err := n.PeerUserSession(peer, "User1", command)
	Expect(err).NotTo(HaveOccurred())
	if expectSuccess {
		Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit(0))
		Expect(sess).To(gbytes.Say(expectedMessage))
	} else {
		Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit())
		Expect(sess.Err).To(gbytes.Say(expectedMessage))
	}
}

func discoverAllPeers(n *nwo.Network, peer *nwo.Peer, channelID string, retries int, retryInterval time.Duration) {
	var discoveredPeers []nwo.DiscoveredPeer
	numPeers := len(n.Peers)
	for i := 0; i < retries; i++ {
		discoveredPeers = nwo.DiscoverPeers(n, peer, "User1", channelID)()
		if len(discoveredPeers) == numPeers || i == retries-1 {
			break
		}
		time.Sleep(retryInterval)
	}
	Expect(discoveredPeers).To(HaveLen(numPeers))
}


text:
// Generated by delombok at Sun Nov 06 21:21:45 CET 2022

class BuilderWithToBuilderOnMethod<T, K> {
	private String one;
	private String two;
	private T foo;
	private K bar;
	private int some;

	public static <Z> BuilderWithToBuilderOnMethod<Z, String> test(String one, Z bar) {
		return new BuilderWithToBuilderOnMethod<Z, String>();
	}

	@java.lang.SuppressWarnings("all")
	public static class BuilderWithToBuilderOnMethodBuilder<Z> {
		@java.lang.SuppressWarnings("all")
		private String one;
		@java.lang.SuppressWarnings("all")
		private Z bar;

		@java.lang.SuppressWarnings("all")
		BuilderWithToBuilderOnMethodBuilder() {
		}

		/**
		 * @return {@code this}.
		 */
		@java.lang.SuppressWarnings("all")
		public BuilderWithToBuilderOnMethod.BuilderWithToBuilderOnMethodBuilder<Z> one(final String one) {
			this.one = one;
			return this;
		}

		/**
		 * @return {@code this}.
		 */
		@java.lang.SuppressWarnings("all")
		public BuilderWithToBuilderOnMethod.BuilderWithToBuilderOnMethodBuilder<Z> bar(final Z bar) {
			this.bar = bar;
			return this;
		}

		@java.lang.SuppressWarnings("all")
		public BuilderWithToBuilderOnMethod<Z, String> build() {
			return BuilderWithToBuilderOnMethod.<Z>test(this.one, this.bar);
		}

		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		public java.lang.String toString() {
			return "BuilderWithToBuilderOnMethod.BuilderWithToBuilderOnMethodBuilder(one=" + this.one + ", bar=" + this.bar + ")";
		}
	}

	@java.lang.SuppressWarnings("all")
	public static <Z> BuilderWithToBuilderOnMethod.BuilderWithToBuilderOnMethodBuilder<Z> builder() {
		return new BuilderWithToBuilderOnMethod.BuilderWithToBuilderOnMethodBuilder<Z>();
	}

	@java.lang.SuppressWarnings("all")
	public BuilderWithToBuilderOnMethod.BuilderWithToBuilderOnMethodBuilder<T> toBuilder() {
		return new BuilderWithToBuilderOnMethod.BuilderWithToBuilderOnMethodBuilder<T>().one(this.one).bar(this.foo);
	}
}


text:
.. _stginga-install:

Installation
============

``stginga`` requires:

* Astropy 1.0 or later, available from
  `Astropy's GitHub page <https://github.com/astropy/astropy>`_.
* The latest version of Ginga, available from
  `Ginga's GitHub page <https://github.com/ejeschke/ginga/>`_.
* The latest version of ``stginga`` available from
  `stginga's GitHub page <https://github.com/spacetelescope/stginga>`_.

We suggest using  `Anaconda <https://www.continuum.io/downloads>`_ as a
python distribution that is known to work with ``stginga``.

To install ``stginga`` from source::

    python setup.py install [--prefix=/my/install/path]


text:
package it.unimi.di.law.warc.filters;

import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;

import java.net.URI;
import java.util.Set;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;

// RELEASE-STATUS: DIST

/** A filter accepting only URIs whose path ends (case-insensitively) with one of a given set of suffixes. */
public class PathEndsWithOneOf extends AbstractFilter<URI> {

	/** The splitter used to parse a set of comma separated extensions in an arraylist */
	private static final Splitter SPLITTER = Splitter.on( ',' ).trimResults().omitEmptyStrings();

	/** The accepted suffixes, downcased. */
	private final String[] suffixes;

	/** Creates a filter that only accepts URLs whose path ends with one of a given set of suffixes.
	 *
	 * @param suffixes the accepted suffixes.
	 */
	public PathEndsWithOneOf( final String[] suffixes ) {
		this.suffixes = new String[ suffixes.length ];
		for ( int i = 0; i < suffixes.length; i++ ) this.suffixes[ i ] = suffixes[ i ].toLowerCase();
	}

	/**
	 * Apply the filter to a given URI
	 *
	 * @param uri the URI to be filtered
	 * @return true if uri ends with one of the accepted suffixes
	 */
	@Override
	public boolean apply( final URI uri ) {
		String file = uri.getRawPath().toLowerCase();
		for ( String suffix: suffixes ) if ( file.endsWith( suffix ) ) return true;
		return false;
	}

	/**
	 * Get a new PathEndsWithOneOf that will accept only URIs whose suffix is one of the allowed suffixes
	 *
	 * @param spec a string containing the allowed suffixes (separated by ',')
	 * @return a new PathEndsWithOneOf that will accept only URIs whose path suffix is one of the strings specified by spec
	 */
	public static PathEndsWithOneOf valueOf( String spec ) {
		return new PathEndsWithOneOf( Iterables.toArray( SPLITTER.split( spec ), String.class ) );
	}

	/**
	 * A string representation of the state of this object, that is just the suffixes allowed.
	 *
	 * @return the strings used by this object to compare suffixes
	 */
	public String toString() {
		return toString( (Object[])suffixes );
	}

	/**
	 * Compare this with a given generic object
	 *
	 * @return true if x is an instance of HostEndsWithOneOf and the suffixes allowed by x are allowed by this and vice versa
	 */
	public boolean equals( Object x ) {
		if ( x instanceof PathEndsWithOneOf ) {
			Set<String> suffixSet = new ObjectOpenHashSet<String>( suffixes );
			Set<String> xSuffixSet = new ObjectOpenHashSet<String>( ((PathEndsWithOneOf)x).suffixes );
			return suffixSet.equals( xSuffixSet );
		}
		else return false;
	}

	@Override
	public Filter<URI> copy() {
		return this;
	}
}


text:
from django.db import models
from django import forms
from users.models import User

from datetime import datetime
from django.utils.timezone import localtime

MAX_MESSAGE_LENGTH = 2000

class Message(models.Model):
	sender = models.ForeignKey(User, related_name='sender')				# User ID of user sent message
	recipient = models.ForeignKey(User, related_name='recipient')		# User ID of user that message was sent to
	body = models.CharField(max_length=MAX_MESSAGE_LENGTH)
	timestamp = models.DateTimeField(auto_now_add=True)
	read = models.BooleanField(default=False)
	encrypted = models.BooleanField(default=False)
	key = models.BinaryField(default=None, null=True)

	@property
	def sent_today(self):
		return datetime.today().date() == localtime(self.timestamp).date()


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Caloplaca magnussoni Herre

### Remarks
null


text:
package com.jetbrains.python.packaging;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;

import java.awt.*;

/**
 * @author yole
 */
public abstract class PyPackageManager {
  public static PyPackageManager getInstance(Sdk sdk) {
    return PyPackageManagers.getInstance().forSdk(sdk);
  }

  /**
   * Returns true if pip is installed for the specific interpreter; returns false if pip is not
   * installed or if it is not currently known whether it's installed (e.g. for a remote interpreter).
   *
   * @return true if pip is known to be installed, false otherwise.
   */
  public abstract boolean hasPip();
  public abstract void install(String requirementString) throws PyExternalProcessException;
  public abstract void showInstallationError(Project project, String title, String description);
  public abstract void showInstallationError(Component owner, String title, String description);
  public abstract void refresh();
}


text:
<?php
namespace Mockery\Adapter\Phpunit;

/**
 * Integrates Mockery into PHPUnit. Ensures Mockery expectations are verified
 * for each test and are included by the assertion counter.
 */
trait MockeryPHPUnitIntegration
{
    /**
     * Performs assertions shared by all tests of a test case. This method is
     * called before execution of a test ends and before the tearDown method.
     */
    protected function assertPostConditions()
    {
        parent::assertPostConditions();

        // Add Mockery expectations to assertion count.
        if (($container = \Mockery::getContainer()) !== null) {
            $this->addToAssertionCount($container->mockery_getExpectationCount());
        }

        // Verify Mockery expectations.
        \Mockery::close();
    }
}


text:
/// <reference path="../../_all.ts" />

'use strict';
module app {

    angular
        .module('blocks.interceptor')
        .factory('interceptor', interceptor);

    interceptor.$inject = ['$q', '$injector', '$location'];
    function interceptor($q, $injector, $location) {

        var _request = function (config) {

            config.headers = config.headers || {};
            //use this?: self.notifyingCache.get(app.CONST.sessionStorageKey);
            var authData = sessionStorage.getItem('authorizationData');
            if (authData && config.url != 'token') {  //do not use when loging in
                config.headers.Authorization = 'Bearer ' + JSON.parse(authData).access_token;
            }

            return config;
        }

        //var _responseError = function (rejection) {
        //    if (rejection.status === 401) {
        //        var accountService = $injector.get('accountService');
        //        var authData = sessionStorage.getItem('authorizationData');

        //        if (authData) {
        //            var parsedAuthData = JSON.parse(authData);
        //            if (parsedAuthData.useRefreshTokens) {
        //                /* remember the url that caused 401 and retry only once more */
        //                var authorizationRefreshTorUrl = sessionStorage.getItem('authorizationRefreshTorUrl');
        //                if (authorizationRefreshTorUrl !== rejection.url) {
        //                    /* refresh access_token using refresh token */
        //                    var model = new app.useraccount.models.Refresh();
        //                    model.username = parsedAuthData.userName;
        //                    model.refresh_token = parsedAuthData.refresh_token;
        //                    accountService.$refresh(model).then(function (data) {
        //                        $location.path(rejection.config.url);
        //                        sessionStorage.removeItem('authorizationRefreshTorUrl');
        //                    }, function (err) {
        //                        sessionStorage.setItem('authorizationRefreshTorUrl', rejection.url);
        //                    });

        //                    return $q.reject(rejection);
        //                }

        //                $location.path('/401');
        //            }
        //        }
        //        //authService.logOut();
        //        $location.path('/login');
        //    }
        //    return $q.reject(rejection);
        //}

        var authInterceptorServiceFactory = {
            request: _request
            //,
            //responseError: _responseError
        };

        return authInterceptorServiceFactory ;

    }

}


text:
import { Component }                                         from '@angular/core';
import { NavController, ToastController, LoadingController } from 'ionic-angular';
import { BankPage }                                          from '../bank/bank';
import { LoginService }                                      from '../services/login.service';

@Component({
    selector: 'page-login',
    templateUrl: 'login.html'
})
export class LoginPage {
    email: string;
    password: string;

    constructor(
        public navCtrl: NavController,
        private _loginService: LoginService,
        public toastCtrl: ToastController,
        public loadingCtrl: LoadingController
    ) { }

    ngOnInit(): void {
        if(localStorage.getItem('token') != null){
            this.loadPage();
        }
    }

    login(): void {
        const loading = this.loadingCtrl.create({
            content: 'Please wait...'
        });

        loading.present();

        this._loginService.login(this.email, this.password).subscribe(response => {
            if(response){
                this.loadPage();
            }
            if(!response){
                this.presentToast();
            }
            loading.dismiss();
        });
    }

    loadPage(): void {
        this.navCtrl.setRoot(BankPage);
    }

    presentToast() {
        const toast = this.toastCtrl.create({
            message: 'Login Error: Email or Password is incorrect',
            duration: 1700,
            position: 'middle'
        });
        toast.present();
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | A sqlite backend for persistent.
module Database.Persist.Sqlite
    ( withSqlitePool
    , withSqliteConn
    , createSqlitePool
    , module Database.Persist.Sql
    , SqliteConf (..)
    , runSqlite
    , wrapConnection
    ) where

import Database.Persist.Sql

import qualified Database.Sqlite as Sqlite

import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Logger (NoLoggingT, runNoLoggingT, MonadLogger)
import Data.IORef
import qualified Data.Map as Map
import Control.Monad.Trans.Control (control)
import Data.Acquire (Acquire, mkAcquire, with)
import qualified Control.Exception as E
import Data.Text (Text)
import Data.Aeson
import qualified Data.Text as T
import Data.Conduit
import qualified Data.Conduit.List as CL
import Control.Applicative
import Data.Int (Int64)
import Data.Monoid ((<>))
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Resource (ResourceT, runResourceT)

createSqlitePool :: (MonadIO m, MonadLogger m, MonadBaseControl IO m) => Text -> Int -> m ConnectionPool
createSqlitePool s = createSqlPool $ open' s

withSqlitePool :: (MonadBaseControl IO m, MonadIO m, MonadLogger m)
               => Text
               -> Int -- ^ number of connections to open
               -> (ConnectionPool -> m a) -> m a
withSqlitePool s = withSqlPool $ open' s

withSqliteConn :: (MonadBaseControl IO m, MonadIO m, MonadLogger m)
               => Text -> (SqlBackend -> m a) -> m a
withSqliteConn = withSqlConn . open'

open' :: Text -> LogFunc -> IO SqlBackend
open' connStr logFunc = Sqlite.open connStr >>= flip wrapConnection logFunc

-- | Wrap up a raw 'Sqlite.Connection' as a Persistent SQL 'Connection'.
--
-- Since 1.1.5
wrapConnection :: Sqlite.Connection -> LogFunc -> IO SqlBackend
wrapConnection conn logFunc = do
    smap <- newIORef $ Map.empty
    return SqlBackend
        { connPrepare = prepare' conn
        , connStmtMap = smap
        , connInsertSql = insertSql'
        , connClose = Sqlite.close conn
        , connMigrateSql = migrate'
        , connBegin = helper "BEGIN"
        , connCommit = helper "COMMIT"
        , connRollback = ignoreExceptions . helper "ROLLBACK"
        , connEscapeName = escape
        , connNoLimit = "LIMIT -1"
        , connRDBMS = "sqlite"
        , connLimitOffset = decorateSQLWithLimitOffset "LIMIT -1"
        , connLogFunc = logFunc
        }
  where
    helper t getter = do
        stmt <- getter t
        _ <- stmtExecute stmt []
        stmtReset stmt
    ignoreExceptions = E.handle (\(_ :: E.SomeException) -> return ())

-- | A convenience helper which creates a new database connection and runs the
-- given block, handling @MonadResource@ and @MonadLogger@ requirements. Note
-- that all log messages are discarded.
--
-- Since 1.1.4
runSqlite :: (MonadBaseControl IO m, MonadIO m)
          => Text -- ^ connection string
          -> SqlPersistT (NoLoggingT (ResourceT m)) a -- ^ database action
          -> m a
runSqlite connstr = runResourceT
                  . runNoLoggingT
                  . withSqliteConn connstr
                  . runSqlConn

prepare' :: Sqlite.Connection -> Text -> IO Statement
prepare' conn sql = do
    stmt <- Sqlite.prepare conn sql
    return Statement
        { stmtFinalize = Sqlite.finalize stmt
        , stmtReset = Sqlite.reset conn stmt
        , stmtExecute = execute' conn stmt
        , stmtQuery = withStmt' conn stmt
        }

insertSql' :: EntityDef -> [PersistValue] -> InsertSqlResult
insertSql' ent vals =
  case entityPrimary ent of
    Just _ ->
      ISRManyKeys sql vals
        where sql = T.concat
                [ "INSERT INTO "
                , escape $ entityDB ent
                , "("
                , T.intercalate "," $ map (escape . fieldDB) $ entityFields ent
                , ") VALUES("
                , T.intercalate "," (map (const "?") $ entityFields ent)
                , ")"
                ]
    Nothing ->
      ISRInsertGet ins sel
        where
          sel = T.concat
              [ "SELECT "
              , escape $ fieldDB (entityId ent)
              , " FROM "
              , escape $ entityDB ent
              , " WHERE _ROWID_=last_insert_rowid()"
              ]
          ins = T.concat
              [ "INSERT INTO "
              , escape $ entityDB ent
              , if null (entityFields ent)
                    then " VALUES(null)"
                    else T.concat
                      [ "("
                      , T.intercalate "," $ map (escape . fieldDB) $ entityFields ent
                      , ") VALUES("
                      , T.intercalate "," (map (const "?") $ entityFields ent)
                      , ")"
                      ]
              ]

execute' :: Sqlite.Connection -> Sqlite.Statement -> [PersistValue] -> IO Int64
execute' conn stmt vals = flip finally (liftIO $ Sqlite.reset conn stmt) $ do
    Sqlite.bind stmt vals
    _ <- Sqlite.step stmt
    Sqlite.changes conn

withStmt'
          :: MonadIO m
          => Sqlite.Connection
          -> Sqlite.Statement
          -> [PersistValue]
          -> Acquire (Source m [PersistValue])
withStmt' conn stmt vals = do
    _ <- mkAcquire
        (Sqlite.bind stmt vals >> return stmt)
        (Sqlite.reset conn)
    return pull
  where
    pull = do
        x <- liftIO $ Sqlite.step stmt
        case x of
            Sqlite.Done -> return ()
            Sqlite.Row -> do
                cols <- liftIO $ Sqlite.columns stmt
                yield cols
                pull

showSqlType :: SqlType -> Text
showSqlType SqlString = "VARCHAR"
showSqlType SqlInt32 = "INTEGER"
showSqlType SqlInt64 = "INTEGER"
showSqlType SqlReal = "REAL"
showSqlType (SqlNumeric precision scale) = T.concat [ "NUMERIC(", T.pack (show precision), ",", T.pack (show scale), ")" ]
showSqlType SqlDay = "DATE"
showSqlType SqlTime = "TIME"
showSqlType SqlDayTime = "TIMESTAMP"
showSqlType SqlBlob = "BLOB"
showSqlType SqlBool = "BOOLEAN"
showSqlType (SqlOther t) = t

migrate' :: [EntityDef]
         -> (Text -> IO Statement)
         -> EntityDef
         -> IO (Either [Text] [(Bool, Text)])
migrate' allDefs getter val = do
    let (cols, uniqs, _) = mkColumns allDefs val
    let newSql = mkCreateTable False def (filter (not . safeToRemove val . cName) cols, uniqs)
    stmt <- getter "SELECT sql FROM sqlite_master WHERE type='table' AND name=?"
    oldSql' <- with (stmtQuery stmt [PersistText $ unDBName table]) ($$ go)
    case oldSql' of
        Nothing -> return $ Right [(False, newSql)]
        Just oldSql -> do
            if oldSql == newSql
                then return $ Right []
                else do
                    sql <- getCopyTable allDefs getter val
                    return $ Right sql
  where
    def = val
    table = entityDB def
    go = do
        x <- CL.head
        case x of
            Nothing -> return Nothing
            Just [PersistText y] -> return $ Just y
            Just y -> error $ "Unexpected result from sqlite_master: " ++ show y

-- | Check if a column name is listed as the "safe to remove" in the entity
-- list.
safeToRemove :: EntityDef -> DBName -> Bool
safeToRemove def (DBName colName)
    = any (elem "SafeToRemove" . fieldAttrs)
    $ filter ((== DBName colName) . fieldDB)
    $ entityFields def

getCopyTable :: [EntityDef]
             -> (Text -> IO Statement)
             -> EntityDef
             -> IO [(Bool, Text)]
getCopyTable allDefs getter def = do
    stmt <- getter $ T.concat [ "PRAGMA table_info(", escape table, ")" ]
    oldCols' <- with (stmtQuery stmt []) ($$ getCols)
    let oldCols = map DBName $ filter (/= "id") oldCols' -- need to update for table id attribute ?
    let newCols = filter (not . safeToRemove def) $ map cName cols
    let common = filter (`elem` oldCols) newCols
    let id_ = fieldDB (entityId def)
    return [ (False, tmpSql)
           , (False, copyToTemp $ id_ : common)
           , (common /= filter (not . safeToRemove def) oldCols, dropOld)
           , (False, newSql)
           , (False, copyToFinal $ id_ : newCols)
           , (False, dropTmp)
           ]
  where
    getCols = do
        x <- CL.head
        case x of
            Nothing -> return []
            Just (_:PersistText name:_) -> do
                names <- getCols
                return $ name : names
            Just y -> error $ "Invalid result from PRAGMA table_info: " ++ show y
    table = entityDB def
    tableTmp = DBName $ unDBName table <> "_backup"
    (cols, uniqs, _) = mkColumns allDefs def
    cols' = filter (not . safeToRemove def . cName) cols
    newSql = mkCreateTable False def (cols', uniqs)
    tmpSql = mkCreateTable True def { entityDB = tableTmp } (cols', uniqs)
    dropTmp = "DROP TABLE " <> escape tableTmp
    dropOld = "DROP TABLE " <> escape table
    copyToTemp common = T.concat
        [ "INSERT INTO "
        , escape tableTmp
        , "("
        , T.intercalate "," $ map escape common
        , ") SELECT "
        , T.intercalate "," $ map escape common
        , " FROM "
        , escape table
        ]
    copyToFinal newCols = T.concat
        [ "INSERT INTO "
        , escape table
        , " SELECT "
        , T.intercalate "," $ map escape newCols
        , " FROM "
        , escape tableTmp
        ]

mkCreateTable :: Bool -> EntityDef -> ([Column], [UniqueDef]) -> Text
mkCreateTable isTemp entity (cols, uniqs) =
  case entityPrimary entity of
    Just pdef ->
       T.concat
        [ "CREATE"
        , if isTemp then " TEMP" else ""
        , " TABLE "
        , escape $ entityDB entity
        , "("
        , T.drop 1 $ T.concat $ map sqlColumn cols
        , ", PRIMARY KEY "
        , "("
        , T.intercalate "," $ map (escape . fieldDB) $ compositeFields pdef
        , ")"
        , ")"
        ]
    Nothing -> T.concat
        [ "CREATE"
        , if isTemp then " TEMP" else ""
        , " TABLE "
        , escape $ entityDB entity
        , "("
        , escape $ fieldDB (entityId entity)
        , " "
        , showSqlType $ fieldSqlType $ entityId entity
        ," PRIMARY KEY"
        , mayDefault $ defaultAttribute $ fieldAttrs $ entityId entity
        , T.concat $ map sqlColumn cols
        , T.concat $ map sqlUnique uniqs
        , ")"
        ]

mayDefault :: Maybe Text -> Text
mayDefault def = case def of
    Nothing -> ""
    Just d -> " DEFAULT " <> d

sqlColumn :: Column -> Text
sqlColumn (Column name isNull typ def _cn _maxLen ref) = T.concat
    [ ","
    , escape name
    , " "
    , showSqlType typ
    , if isNull then " NULL" else " NOT NULL"
    , mayDefault def
    , case ref of
        Nothing -> ""
        Just (table, _) -> " REFERENCES " <> escape table
    ]

sqlUnique :: UniqueDef -> Text
sqlUnique (UniqueDef _ cname cols _) = T.concat
    [ ",CONSTRAINT "
    , escape cname
    , " UNIQUE ("
    , T.intercalate "," $ map (escape . snd) cols
    , ")"
    ]

escape :: DBName -> Text
escape (DBName s) =
    T.concat [q, T.concatMap go s, q]
  where
    q = T.singleton '"'
    go '"' = "\"\""
    go c = T.singleton c

-- | Information required to connect to a sqlite database
data SqliteConf = SqliteConf
    { sqlDatabase :: Text
    , sqlPoolSize :: Int
    }

instance FromJSON SqliteConf where
    parseJSON = withObject "SqliteConf" $ \o -> SqliteConf
        <$> o .: "database"
        <*> o .: "poolsize"
instance PersistConfig SqliteConf where
    type PersistConfigBackend SqliteConf = SqlPersistT
    type PersistConfigPool SqliteConf = ConnectionPool
    createPoolConfig (SqliteConf cs size) = runNoLoggingT $ createSqlitePool cs size -- FIXME
    runPool _ = runSqlPool
    loadConfig = parseJSON

finally :: MonadBaseControl IO m
        => m a -- ^ computation to run first
        -> m b -- ^ computation to run afterward (even if an exception was raised)
        -> m a
finally a sequel = control $ \runInIO ->
                     E.finally (runInIO a)
                               (runInIO sequel)
{-# INLINABLE finally #-}


text:
NS_ASSUME_NONNULL_BEGIN
typedef void(^SJAnimationCompletionHandler)(void);
typedef void(^SJPresentedAnimationHandler)(__kindof UIViewController *vc, SJAnimationCompletionHandler completion);
typedef void(^SJDismissedAnimationHandler)(__kindof UIViewController *vc, SJAnimationCompletionHandler completion);

@interface UIViewController (SJBaseVideoPlayerExtended)

- (void)setTransitionDuration:(NSTimeInterval)dutaion presentedAnimation:(SJPresentedAnimationHandler)presentedAnimation dismissedAnimation:(SJDismissedAnimationHandler)dismissedAnimation;

@end
NS_ASSUME_NONNULL_END


text:
FROM nginx:1.11.4
MAINTAINER Raphael Jansen <raphael.jansen@gmail.com>


text:
<%componentName% controller="%componentNamespace%.%componentName%">
  <style>
    %componentName% {
      display: block;
    }
  </style>

</%componentName%>


text:
package com.impetus.kundera.client.cassandra.crud;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import junit.framework.Assert;

import org.apache.cassandra.thrift.Compression;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.impetus.client.cassandra.common.CassandraConstants;
import com.impetus.kundera.PersistenceProperties;
import com.impetus.kundera.client.Client;
import com.impetus.kundera.client.cassandra.dsdriver.DSClient;
import com.impetus.kundera.client.cassandra.persistence.CassandraCli;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl;

/**
 * <Prove description of functionality provided by this Type>
 *
 * @author vivek.mishra
 */
public class NativeQueryCQLV3Test
{

    private final String schema = "KunderaExamples";

    private EntityManagerFactoryImpl emf;

    private static final String _PU = "ds_pu";

    /**
     * Sets the up.
     *
     * @throws Exception
     *             the exception
     */
    @Before
    public void setUp() throws Exception
    {
        CassandraCli.cassandraSetUp();
        CassandraCli.dropKeySpace(schema);
        String nativeSql = "CREATE KEYSPACE \"" + schema
                + "\" with replication = {'class':'SimpleStrategy', 'replication_factor':1}";
        CassandraCli.getClient().execute_cql3_query(ByteBuffer.wrap(nativeSql.getBytes("UTF-8")), Compression.NONE,
                ConsistencyLevel.ONE);
        emf = getEntityManagerFactory();
    }

    /**
     * Test create insert column family query.
     */
    @Test
    public void testCreateInsertColumnFamilyQueryVersion3()
    {

        String useNativeSql = "USE \"" + schema + "\"";
        EntityManager em = emf.createEntityManager();

        Map<String, Client> clientMap = (Map<String, Client>) em.getDelegate();
        DSClient pc = (DSClient) clientMap.get(_PU);
        pc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);

        Query q = em.createNativeQuery(useNativeSql);
        q.executeUpdate();
        // create column family
        String colFamilySql = "CREATE COLUMNFAMILY users (key varchar PRIMARY KEY,full_name varchar, birth_date int,state varchar)";
        q = em.createNativeQuery(colFamilySql);
        q.executeUpdate();
        Assert.assertTrue(CassandraCli.columnFamilyExist("users", schema));

        // Add indexes
        String idxSql = "CREATE INDEX ON users (birth_date)";
        q = em.createNativeQuery(idxSql);
        q.executeUpdate();
        idxSql = "CREATE INDEX ON users (state)";
        q = em.createNativeQuery(idxSql);
        q.executeUpdate();
        // insert users.
        String insertSql = "INSERT INTO users (key, full_name, birth_date, state) VALUES ('bsanderson', 'Brandon Sanderson', 1975, 'UT')";
        q = em.createNativeQuery(insertSql);
        q.executeUpdate();
        // select key and state
        String selectSql = "SELECT key, state FROM users";

        q = em.createNativeQuery(selectSql, CassandraEntity.class);
        List<CassandraEntity> results = q.getResultList();
        Assert.assertNotNull(results);
        Assert.assertEquals(1, results.size());
        Assert.assertEquals("bsanderson", results.get(0).getKey());
        Assert.assertEquals("UT", results.get(0).getState());
        Assert.assertNull(results.get(0).getFull_name());

        // insert users.
        insertSql = "INSERT INTO users (key, full_name, birth_date, state) VALUES ('prothfuss', 'Patrick Rothfuss', 1973, 'WI')";
        q = em.createNativeQuery(insertSql);
        q.getResultList();

        insertSql = "INSERT INTO users (key, full_name, birth_date, state) VALUES ('htayler', 'Howard Tayler', 1968, 'UT')";
        q = em.createNativeQuery(insertSql);
        q.getResultList();

        // select all
        String selectAll = "SELECT * FROM users WHERE state='UT' AND birth_date > 1970 Allow Filtering";
        q = em.createNativeQuery(selectAll, CassandraEntity.class);
        results = q.getResultList();
        Assert.assertNotNull(results);
        Assert.assertEquals(1, results.size());
        Assert.assertEquals("bsanderson", results.get(0).getKey());
        Assert.assertEquals("UT", results.get(0).getState());
        Assert.assertEquals("Brandon Sanderson", results.get(0).getFull_name());
        Assert.assertEquals(new Integer(1975), results.get(0).getBirth_date());
        emf.close();
    }

    /**
     * Gets the entity manager factory.
     *
     * @return the entity manager factory
     */
    private EntityManagerFactoryImpl getEntityManagerFactory()
    {
        Map propertyMap = null;
        if (propertyMap  == null)
        {
            propertyMap = new HashMap();
            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, "");
        }

        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_PU,propertyMap);
    }

    @Test
    public void testCQLBatch()
    {
        String useNativeSql = "USE \"" + schema + "\"";
        String createColumnFamily = "CREATE TABLE CassandraBatchEntity ( user_name varchar PRIMARY KEY, password varchar, name varchar)";
        String batchOps = "BEGIN BATCH INSERT INTO CassandraBatchEntity (user_name, password, name) VALUES ('user2', 'ch@ngem3b', 'second user') UPDATE CassandraBatchEntity SET password = 'ps22dhds' WHERE user_name = 'user2' INSERT INTO CassandraBatchEntity (user_name, password) VALUES ('user3', 'ch@ngem3c') DELETE name FROM CassandraBatchEntity WHERE user_name = 'user2' INSERT INTO CassandraBatchEntity (user_name, password, name) VALUES ('user4', 'ch@ngem3c', 'Andrew') APPLY BATCH";

        EntityManager em = emf.createEntityManager();

        Map<String, Client> clientMap = (Map<String, Client>) em.getDelegate();
        DSClient pc = (DSClient) clientMap.get(_PU);
        pc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);

        Query q = em.createNativeQuery(useNativeSql);
        // q.getResultList();
        q.executeUpdate();

        pc.setConsistencyLevel(ConsistencyLevel.QUORUM);
        q = em.createNativeQuery(createColumnFamily);
        // q.getResultList();
        q.executeUpdate();

        pc.setConsistencyLevel(ConsistencyLevel.QUORUM);
        q = em.createNativeQuery(batchOps);
        // q.getResultList();
        q.executeUpdate();

        q = em.createNativeQuery("select * from CassandraBatchEntity", CassandraBatchEntity.class);
        List<CassandraBatchEntity> results = q.getResultList();
        Assert.assertNotNull(results);
        Assert.assertEquals(3, results.size());

        // Multiple table batch processing.

        createColumnFamily = "create table test1 (id timeuuid primary key, url text, userid uuid, datetime timestamp, linkcounts int)";
        em.createNativeQuery(createColumnFamily).executeUpdate();
        createColumnFamily = "create table test2 (key text primary key, count int)";
        em.createNativeQuery(createColumnFamily).executeUpdate();
        batchOps = "BEGIN BATCH INSERT INTO test1(id, url) VALUES (64907b40-29a1-11e2-93fa-90b11c71b811,'w') INSERT INTO test2(key, count) VALUES ('key1',12) APPLY BATCH";
        em.createNativeQuery(batchOps).executeUpdate();
        emf.close();
    }

    /**
     * Tear down.
     *
     * @throws Exception
     *             the exception
     */
    @After
    public void tearDown() throws Exception
    {
        CassandraCli.dropKeySpace(schema);
    }

}


text:
package com.jwtexample.service.jsonmappers.weather;

import java.util.List;

public class WeatherJson {

	private WeatherCoord coord;
	private List<Weather> weather;

	public WeatherCoord getCoord() {
		return coord;
	}
	public void setCoord(WeatherCoord coord) {
		this.coord = coord;
	}
	public List<Weather> getWeather() {
		return weather;
	}
	public void setWeather(List<Weather> weather) {
		this.weather = weather;
	}

}


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

<title>Candidate (MaltParser 1.8.1)</title>
<meta name="date" content="2014-11-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

MaltParser 1.8.1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.maltparser.parser.history.kbest

Class Candidate

java.lang.Object

org.maltparser.parser.history.kbest.Candidate

Direct Known Subclasses:

ScoredCandidate

public class Candidate
extends java.lang.Object

A candidate in the k-best list.

Author:

Johan Hall

Field Summary

Fields

Modifier and Type
Field and Description

protected int
actionCode

The integer representation of the predicted action

Constructor Summary

Constructors

Constructor and Description

Candidate()

Constructs a candidate object

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

int
getActionCode()

Returns an integer representation of the predicted action

int
hashCode()

void
reset()

Resets the candidate object

void
setActionCode(int actionCode)

Sets the integer representation of the predicted action

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

actionCode

protected int actionCode

The integer representation of the predicted action

Constructor Detail

Candidate

public Candidate()

Constructs a candidate object

Method Detail

getActionCode

public int getActionCode()

Returns an integer representation of the predicted action

Returns:

an integer representation of the predicted action

setActionCode

public void setActionCode(int actionCode)

Sets the integer representation of the predicted action

Parameters:

actionCode - an integer representation of the predicted action

reset

public void reset()

Resets the candidate object

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

equals

public boolean equals(java.lang.Object obj)

Overrides:

equals in class java.lang.Object

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

MaltParser 1.8.1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright 2007-2014 Johan Hall, Jens Nilsson and Joakim Nivre.


text:
import tvm
from tvm import te
import re
import os
import ctypes

def test_popcount():
    target = "llvm -mtriple=armv7l-none-linux-gnueabihf -mcpu=cortex-a53 -mattr=+neon"

    def check_correct_assembly(type, elements, counts):
        n = tvm.runtime.convert(elements)
        A = te.placeholder(n, dtype=type, name="A")
        B = te.compute(A.shape, lambda i: tvm.tir.popcount(A[i]), name="B")
        s = te.create_schedule(B.op)
        s[B].vectorize(s[B].op.axis[0])
        f = tvm.build(s, [A, B], target)

        # Verify we see the correct number of vpaddl and vcnt instructions in the assembly
        assembly = f.get_source("asm")
        matches = re.findall("vpaddl", assembly)
        assert len(matches) == counts
        matches = re.findall("vcnt", assembly)
        assert len(matches) == 1

    check_correct_assembly("uint16", 8, 1)
    check_correct_assembly("uint16", 4, 1)
    check_correct_assembly("uint32", 4, 2)
    check_correct_assembly("uint32", 2, 2)
    check_correct_assembly("uint64", 2, 3)

def test_vmlal_s16():
    target = "llvm -mtriple=armv7l-none-linux-gnueabihf -mcpu=cortex-a53 -mattr=+neon"

    def check_correct_assembly(N):
        K = te.size_var("K")
        A = te.placeholder((K, N), dtype="int8", name="A")
        B = te.placeholder((K, N), dtype="int8", name="B")
        k = te.reduce_axis((0, K))
        C = te.compute(
            (N,),
            lambda n: te.sum(A[k, n].astype("int32") * B[k, n].astype("int32"), axis=[k]),
            name="C",
        )
        s = te.create_schedule(C.op)
        s[C].vectorize(s[C].op.axis[0])
        f = tvm.build(s, [A, B, C], target)

        # Verify we see the correct number of vmlal.s16 instructions
        assembly = f.get_source("asm")
        matches = re.findall("vmlal.s16", assembly)
        assert len(matches) == N // 4

    check_correct_assembly(8)
    check_correct_assembly(16)
    check_correct_assembly(32)
    check_correct_assembly(64)

    def check_broadcast_correct_assembly(N):
        K = te.size_var("K")
        A = te.placeholder((K, N), dtype="int8", name="A")
        B = te.placeholder((K,), dtype="int8", name="B")
        k = te.reduce_axis((0, K))
        C = te.compute(
            (N,),
            lambda n: te.sum(A[k, n].astype("int32") * B[k].astype("int32"), axis=[k]),
            name="C",
        )
        s = te.create_schedule(C.op)
        s[C].vectorize(s[C].op.axis[0])
        f = tvm.build(s, [A, B, C], target)

        # Verify we see the correct number of vmlal.s16 instructions
        assembly = f.get_source("asm")
        matches = re.findall("vmlal.s16", assembly)
        assert len(matches) == N // 4

    check_broadcast_correct_assembly(8)
    check_broadcast_correct_assembly(16)
    check_broadcast_correct_assembly(32)
    check_broadcast_correct_assembly(64)

if __name__ == "__main__":
    test_popcount()
    test_vmlal_s16()


text:
<meta charset="UTF-8">

<canvas width="600" height="400"></canvas>

<script>
    function desenhaQuadrado(x, y, tamanho, cor) {

        pincel.fillStyle = cor;
        pincel.fillRect(x, y, tamanho, tamanho)
        pincel.fill();
    }

    function desenhaCirculo(x, y, raio, cor) {

        pincel.fillStyle = cor;
        pincel.beginPath();
        pincel.arc(x, y, raio, 0, 2 * 3.14);
        pincel.fill();

    }

    function desenhaPaletaDeCores() {

        desenhaQuadrado(xVermelho, yQuadrados, tamanhoQuadrados, 'red');
        desenhaQuadrado(xVerde, yQuadrados, tamanhoQuadrados, 'green');
        desenhaQuadrado(xAzul, yQuadrados, tamanhoQuadrados, 'blue');

    }

    function lidaComMovimentoDoMouse(evento) {
        var x = evento.pageX - tela.offsetLeft;
        var y = evento.pageY - tela.offsetTop;

        if (desenha && podeDesenharNaArea(x, y)) {

            desenhaCirculo(x, y, 5, corAtual);
        }
    }

    function habilitaDesenhar() {

        desenha = true;
    }

    function desabilitaDesenhar() {

        desenha = false;
    }

    function podeDesenharNaArea(x, y) {
        if (x >= 0 && x < 600 && y >= 0 && y < 60) {
            return false;
        } else {
            return true;
        }
    }

    function selectColor() {

        var x = evento.pageX - tela.offsetLeft;
        var x = eventi.pageY - tela.offsetTop;

        if (x > xVermelho && x < xVermelho + tamanhoQuadrados &&
            y > yQuadrados && y < tamanhoQuadrados) {
            corAtual = 'red';
        } else if (x > xVerde && x < xVerde + tamanhoQuadrados &&
            y > yQuadrados && y < tamanhoQuadrados) {
            corAtual = 'green';
        } else if (x > xAzul && x < xAzul + tamanhoQuadrados &&
            y > xAzul && y < tamanhoQuadrados) {
            corAtual = 'blue';
        }

    }

    var tela = document.querySelector('canvas');
    var pincel = tela.getContext('2d');
    pincel.fillStyle = 'lightgray';
    pincel.fillRect(0, 0, 600, 400);

    var desenha = false;
    var corAtual = 'blue';
    var xVermelho = 0;
    var xVerde = 50;
    var xAzul = 100;
    var yQuadrados = 0;
    var tamanhoQuadrados = 50;

    desenhaPaletaDeCores(); // mostra os quadrados de seleção de cores

    tela.onmousemove = lidaComMovimentoDoMouse;

    tela.onmousedown = habilitaDesenhar;

    tela.onmouseup = desabilitaDesenhar;

    tela.onclick = selectColor;
</script>


text:
#ifndef BONES_LUA_CONTEXT_H_
#define BONES_LUA_CONTEXT_H_

#include "bones.h"
#include "lua.hpp"

namespace bones
{
class LuaContext
{
public:
    static bool StartUp();

    static void ShutDown();

    static void Reset();

    static lua_State * State();

    static void GetGlobalTable(lua_State * l);

    static void GetCO2LOTable(lua_State * l);

    static void ClearLOFromCO(lua_State * l, void * co);

    static void * GetEventCache(lua_State * l, int count);

    static int SafeLOPCall(lua_State * l, int nargs, int nresults);

    static void GetLOFromCO(lua_State * l, void * co);

    static void SetGetCObject(lua_State * l, void * co);

    static void * CallGetCObject(lua_State *l);

    static void PushScriptArg(lua_State * l, BonesObject::ScriptArg arg);

    static BonesObject::ScriptArg GetScriptArg(lua_State * l, int idx);
};

}

#endif


text:
namespace Google.Cloud.DataQnA.V1Alpha.Snippets
{
    // [START dataqna_v1alpha_generated_QuestionService_CreateQuestion_async]
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.DataQnA.V1Alpha;
    using System.Threading.Tasks;

    public sealed partial class GeneratedQuestionServiceClientSnippets
    {
        /// <summary>Snippet for CreateQuestionAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateQuestionRequestObjectAsync()
        {
            // Create client
            QuestionServiceClient questionServiceClient = await QuestionServiceClient.CreateAsync();
            // Initialize request argument(s)
            CreateQuestionRequest request = new CreateQuestionRequest
            {
                ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
                Question = new Question(),
            };
            // Make the request
            Question response = await questionServiceClient.CreateQuestionAsync(request);
        }
    }
    // [END dataqna_v1alpha_generated_QuestionService_CreateQuestion_async]
}


text:
module FFI32
  class Struct
    def self.method_missing(method, *args, &block)
      YAML.load(FFI32::Library.server.call("ffi32.struct_method_missing", name, method, YAML.dump(args)))
    end
  end
end


text:
import {Injectable}     from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import {User} from "../../models/user.model";

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch'

@Injectable()
export class UserService {

  constructor(private http: Http) {}

  private baseUrl = 'http://localhost:8080/webresources/user';  // URL to web api

  getUsers() {
    return this.http.get(this.baseUrl)
      .map(res => <User[]> res.json())
      .catch(this.handleError);
  }

  getUser(id: number): Observable<User> {
    let options = new RequestOptions(
      { headers: new Headers(
        {'Content-Type': 'application/json'})
      });

    return this.http.get(this.baseUrl + "/" + id, options)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  addUser(body: Object): Observable<User> {
    let bodyString = JSON.stringify(body); // Stringify payload
    let headers = new Headers({'Content-Type': 'application/json'}); // ... Set content type to JSON
    let options = new RequestOptions({headers: headers}); // Create a request option

    return this.http.post(this.baseUrl + "/create", body, options) // ...using post request
      .map((res: Response) => res.json()) // ...and calling .json() on the response to return data
      .catch((error: any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
  }

  deleteUser(body: Object): Observable<string> {
    let options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

    return this.http.post(this.baseUrl + "/delete", body, options)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  updateUser(body: Object): Observable<string> {
    let options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

    return this.http.post(this.baseUrl + "/update", body, options)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  signIn(body: Object): Observable<Object> {
    let options = new RequestOptions(
      { headers: new Headers(
        {'Content-Type': 'application/json'})
      });

    return this.http.post(this.baseUrl + "/signin", body, options)
      .map((res: Response) => res.json()) //
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  private handleError(error: Response) {
    console.log(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}


text:
title: Alison Lumb
submitted: 2015-12-21
gender: female
course:
  - History
graduated: 1979

---

I was a member of NTG 1978-79, going with them to the Edinburgh Fringe for two seasons, summer 78 and 79.
I was an assistant stage manager initially, then pianist in the band for various shows in Edinburgh and around campus.

Thanks to that  life-changing experience, I avoided a career as an archivist in the basement of the arts library, and after a few years of dogsbody jobs, worked at  the BBC/ITV etc as an assistant floor manager, script editor, producer and executive producer, from 1981 until around 2009.