text:
"""
    1Channel XBMC Addon
    Copyright (C) 2014 tknorris

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import os
import urllib
import time
import csv
import xbmc
import xbmcvfs
from addon.common.addon import Addon
import utils

def enum(**enums):
    return type('Enum', (), enums)

DB_TYPES= enum(MYSQL='mysql', SQLITE='sqlite')
CSV_MARKERS = enum(FAVORITES='***FAVORITES***', SUBSCRIPTIONS='***SUBSCRIPTIONS***', BOOKMARKS='***BOOKMARKS***', EXT_SUBS='***EXTERNAL SUBSCRIPTIONS***')

_1CH = Addon('plugin.video.1channel')

class DB_Connection():
    def __init__(self):
        global db_lib
        self.dbname = _1CH.get_setting('db_name')
        self.username = _1CH.get_setting('db_user')
        self.password = _1CH.get_setting('db_pass')
        self.address = _1CH.get_setting('db_address')
        self.db=None

        if _1CH.get_setting('use_remote_db') == 'true':
            if self.address is not None and self.username is not None \
            and self.password is not None and self.dbname is not None:
                import mysql.connector as db_lib
                utils.log('Loading MySQL as DB engine')
                self.db_type = DB_TYPES.MYSQL
            else:
                utils.log('MySQL is enabled but not setup correctly', xbmc.LOGERROR)
                raise ValueError('MySQL enabled but not setup correctly')
        else:
            try:
                from sqlite3 import dbapi2 as db_lib
                utils.log('Loading sqlite3 as DB engine')
            except:
                from pysqlite2 import dbapi2 as db_lib
                utils.log('pysqlite2 as DB engine')
            self.db_type = DB_TYPES.SQLITE
            db_dir = xbmc.translatePath("special://database")
            self.db_path = os.path.join(db_dir, 'onechannelcache.db')
        self.__connect_to_db()

    def flush_cache(self):
        sql = 'DELETE FROM url_cache'
        self.__execute(sql)

    # return the bookmark for the requested url or None if not found
    def get_bookmark(self,url):
        if not url: return None
        sql='SELECT resumepoint FROM new_bkmark where url=?'
        bookmark = self.__execute(sql, (url,))
        if bookmark:
            return bookmark[0][0]
        else:
            return None

    # get all bookmarks
    def get_bookmarks(self):
        sql='SELECT * FROM new_bkmark'
        bookmarks = self.__execute(sql)
        return bookmarks

    # return true if bookmark exists
    def bookmark_exists(self, url):
        return self.get_bookmark(url) != None

    def set_bookmark(self, url,offset):
        if not url: return
        sql = 'REPLACE INTO new_bkmark (url, resumepoint) VALUES(?,?)'
        self.__execute(sql, (url,offset))

    def clear_bookmark(self, url):
        if not url: return
        sql = 'DELETE FROM new_bkmark WHERE url=?'
        self.__execute(sql, (url,))

    def get_favorites(self, fav_type=None):
        sql = 'SELECT * FROM favorites'
        if fav_type:
            sql = sql + self.__format(' WHERE type = ? ORDER BY NAME')
            favs=self.__execute(sql, (fav_type,))
        else:
            favs=self.__execute(sql)
        return favs

    def get_favorites_count(self, fav_type=None):
        sql = 'SELECT count(*) FROM favorites'
        if fav_type:
            sql = sql + self.__format(' WHERE type = ?')
            rows=self.__execute(sql, (fav_type,))
        else:
            rows=self.__execute(sql)

        return rows[0][0]

    def save_favorite(self, fav_type, name, url, year):
        sql = 'INSERT INTO favorites (type, name, url, year) VALUES (?, ?, ?, ?)'
        try:
            title = urllib.unquote_plus(unicode(name, 'latin1'))
            self.__execute(sql, (fav_type, title, url, year))
        except db_lib.IntegrityError:
            raise

    # delete a list of favorites, urls must be a list
    def delete_favorites(self, urls):
        url_string=', '.join('?' for _ in urls)
        sql = self.__format('DELETE FROM favorites WHERE url in ('+url_string+')')
        self.__execute(sql, urls)

    def delete_favorite(self, url):
        self.delete_favorites([url])

    def get_subscriptions(self, day=None, order_matters=False):
        sql = 'SELECT * FROM subscriptions'
        if day is not None: sql += ' WHERE days like ?'

        # order subscription by their days values, forcing ALLs to the top, forcing disabled (i.e. nulls and blank) to the end, with the rest sorted lexicographically, then by alphabetically by title
        if order_matters: sql += ' ORDER BY CASE WHEN days="0123456" THEN 0 WHEN days IS NULL THEN 2 WHEN days="" THEN 2 ELSE 1 END, days,title'
        if day is None:
            rows=self.__execute(sql)
        else:
            rows=self.__execute(sql,('%{0}%'.format(day),))
        return rows

    def add_subscription(self, url, title, img, year, imdbnum, days):
        sql = 'REPLACE INTO subscriptions (url, title, img, year, imdbnum, days) VALUES (?, ?, ?, ?, ?, ?)'
        self.__execute(sql, (url, title, img, year, imdbnum, days))

    def delete_subscription(self, url):
        sql = 'DELETE FROM subscriptions WHERE url=?'
        self.__execute(sql, (url,))

    def edit_days(self, url, days):
        sql = "UPDATE subscriptions SET days=? WHERE url=?"
        self.__execute(sql, (days, url))

    def add_ext_sub(self, sub_type, url, imdbnum, days):
        sql = 'REPLACE INTO external_subs (type, url, imdbnum, days) VALUES (?, ?, ?, ?)'
        self.__execute(sql, (sub_type, url, imdbnum, days))

    def delete_ext_sub(self, sub_type, url):
        sql = 'DELETE FROM external_subs WHERE type=? and url=?'
        self.__execute(sql, (sub_type, url,))

    def edit_external_days(self, sub_type, url, days):
        sql = "UPDATE external_subs SET days=? WHERE type=? and url=?"
        self.__execute(sql, (days, sub_type, url))

    def get_external_subs(self, sub_type=None, day=None):
        sql = 'SELECT type, url, imdbnum, days FROM external_subs'
        if sub_type: sql +=' WHERE type=?'
        if day:
            if sub_type:
                sql += ' AND'
            else:
                sql += ' WHERE'
            sql += ' days LIKE ?'

        params=None
        if sub_type and day:
            params=(sub_type, day)
        elif sub_type:
            params = (sub_type,)
        elif day:
            params = (day,)

        if not params:
            rows=self.__execute(sql)
        else:
            rows=self.__execute(sql, params)

        return rows

    def cache_url(self,url,body):
        now = time.time()
        sql = 'REPLACE INTO url_cache (url,response,timestamp) VALUES(?, ?, ?)'
        self.__execute(sql, (url, body, now))

    def get_cached_url(self, url, cache_limit=8):
        html=''
        now = time.time()
        limit = 60 * 60 * cache_limit
        sql = 'SELECT * FROM url_cache WHERE url = ?'
        rows=self.__execute(sql, (url,))

        if rows:
            created = float(rows[0][2])
            age = now - created
            if age < limit:
                html=rows[0][1]

        return html

    def cache_season(self, season_num,season_html):
        sql = 'REPLACE INTO seasons(season,contents) VALUES(?, ?)'
        self.__execute(sql, (season_num, season_html))

    def get_cached_season(self, season_num):
        sql = 'SELECT contents FROM seasons WHERE season=?'
        season_html=self.__execute(sql, (season_num,))[0][0]
        return season_html

    def export_from_db(self, full_path):
        temp_path = os.path.join(xbmc.translatePath("special://profile"),'temp_export_%s.csv' % (int(time.time())))
        with open(temp_path, 'w') as f:
            writer=csv.writer(f)
            f.write('***VERSION: %s***\n' % self.__get_db_version())
            if self.__table_exists('favorites'):
                f.write(CSV_MARKERS.FAVORITES+'\n')
                for fav in self.get_favorites():
                    writer.writerow(fav)
            if self.__table_exists('subscriptions'):
                f.write(CSV_MARKERS.SUBSCRIPTIONS+'\n')
                for sub in self.get_subscriptions():
                    writer.writerow(sub)
            if self.__table_exists('new_bkmark'):
                f.write(CSV_MARKERS.BOOKMARKS+'\n')
                for bookmark in self.get_bookmarks():
                    writer.writerow(bookmark)
            if self.__table_exists('external_subs'):
                f.write(CSV_MARKERS.EXT_SUBS+'\n')
                for sub in self.get_external_subs():
                    writer.writerow(sub)

        utils.log('Copying export file from: |%s| to |%s|' %(temp_path, full_path), xbmc.LOGDEBUG)
        if not xbmcvfs.copy(temp_path, full_path):
            raise Exception('Export: Copy from |%s| to |%s| failed' % (temp_path, full_path))

        if not xbmcvfs.delete(temp_path):
            raise Exception('Export: Delete of %s failed.' % (temp_path))

    def import_into_db(self, full_path):
        temp_path = os.path.join(xbmc.translatePath("special://profile"), 'temp_import_%s.csv' % (int(time.time())))
        utils.log('Copying import file from: |%s| to |%s|' %(full_path, temp_path), xbmc.LOGDEBUG)
        if not xbmcvfs.copy(full_path, temp_path):
            raise Exception('Import: Copy from |%s| to |%s| failed' % (full_path, temp_path))

        try:
            with open(temp_path,'r') as f:
                    reader=csv.reader(f)
                    mode=''
                    _=f.readline() #read header
                    for line in reader:
                        if CSV_MARKERS.FAVORITES in line[0] or CSV_MARKERS.SUBSCRIPTIONS in line[0] or CSV_MARKERS.BOOKMARKS in line[0] or CSV_MARKERS.EXT_SUBS in line[0]:
                            mode=line[0]
                            continue
                        elif mode==CSV_MARKERS.FAVORITES:
                            try:
                                self.save_favorite(line[0], line[1], line[2], line[3])
                            except: pass # save_favorite throws exception on dupe
                        elif mode==CSV_MARKERS.SUBSCRIPTIONS:
                            # don't allow import of days with values other than 0-6
                            if line[5].translate(None,'0123456'): line[5] = '0123456'
                            self.add_subscription(line[0], line[1], line[2], line[3], line[4], line[5])
                        elif mode==CSV_MARKERS.BOOKMARKS:
                            self.set_bookmark(line[0], line[1])
                        elif mode==CSV_MARKERS.EXT_SUBS:
                            self.add_ext_sub(line[0], line[1], line[2], line[3])
                        else:
                            raise Exception('CSV line found while in no mode')
        finally:
            if not xbmcvfs.delete(temp_path):
                raise Exception('Import: Delete of %s failed.' % (temp_path))

    def execute_sql(self, sql):
        return self.__execute(sql)

    # intended to be a common method for creating a db from scratch
    def init_database(self):
        cur_version = _1CH.get_version()
        db_version = self.__get_db_version()
        if db_version is not None and cur_version !=  db_version:
            utils.log('DB Upgrade from %s to %s detected.' % (db_version,cur_version))
            self.__prep_for_reinit()

        utils.log('Building PrimeWire Database', xbmc.LOGDEBUG)
        if self.db_type == DB_TYPES.MYSQL:
            self.__execute('CREATE TABLE IF NOT EXISTS seasons (season INTEGER UNIQUE, contents MEDIUMBLOB)')
            self.__execute('CREATE TABLE IF NOT EXISTS favorites (type VARCHAR(10), name TEXT, url VARCHAR(255) UNIQUE, year VARCHAR(10))')
            self.__execute('CREATE TABLE IF NOT EXISTS subscriptions (url VARCHAR(255) UNIQUE, title TEXT, img TEXT, year TEXT, imdbnum TEXT, days VARCHAR(7))')
            self.__execute('CREATE TABLE IF NOT EXISTS url_cache (url VARCHAR(255) NOT NULL, response MEDIUMBLOB, timestamp TEXT, PRIMARY KEY(url))')
            self.__execute('CREATE TABLE IF NOT EXISTS db_info (setting TEXT, value TEXT)')
            self.__execute('CREATE TABLE IF NOT EXISTS new_bkmark (url VARCHAR(255) PRIMARY KEY NOT NULL, resumepoint DOUBLE NOT NULL)')
            self.__execute('CREATE TABLE IF NOT EXISTS external_subs (type INTEGER NOT NULL, url VARCHAR(255) NOT NULL, imdbnum TEXT, days VARCHAR(7), PRIMARY KEY (type, url))')
            try: self.__execute('DROP INDEX unique_db_info ON db_info')
            except: pass # ignore failures if the index doesn't exist
            self.__execute('CREATE UNIQUE INDEX unique_db_info ON db_info (setting (255))')
        else:
            self.__create_sqlite_db()
            self.__execute('CREATE TABLE IF NOT EXISTS seasons (season UNIQUE, contents)')
            self.__execute('CREATE TABLE IF NOT EXISTS favorites (type, name, url, year)')
            self.__execute('CREATE TABLE IF NOT EXISTS subscriptions (url, title, img, year, imdbnum, days VARCHAR(7))')
            self.__execute('CREATE TABLE IF NOT EXISTS url_cache (url UNIQUE, response, timestamp)')
            self.__execute('CREATE TABLE IF NOT EXISTS db_info (setting TEXT, value TEXT)')
            self.__execute('CREATE TABLE IF NOT EXISTS new_bkmark (url TEXT PRIMARY KEY NOT NULL, resumepoint DOUBLE NOT NULL)')
            self.__execute('CREATE TABLE IF NOT EXISTS external_subs (type INTEGER NOT NULL, url TEXT NOT NULL, imdbnum TEXT, days VARCHAR(7), PRIMARY KEY (type, url))')
            self.__execute('CREATE UNIQUE INDEX IF NOT EXISTS unique_fav ON favorites (url)')
            self.__execute('CREATE UNIQUE INDEX IF NOT EXISTS unique_sub ON subscriptions (url)')
            self.__execute('CREATE UNIQUE INDEX IF NOT EXISTS unique_url ON url_cache (url)')
            self.__execute('CREATE UNIQUE INDEX IF NOT EXISTS unique_db_info ON db_info (setting)')

        # reload the previously saved backup export
        if db_version is not None and cur_version !=  db_version:
            utils.log('Restoring DB from backup at %s' % (self.mig_path), xbmc.LOGDEBUG)
            self.import_into_db(self.mig_path)
            utils.log('DB restored from %s' % (self.mig_path))

        sql = 'REPLACE INTO db_info (setting, value) VALUES(?,?)'
        self.__execute(sql, ('version', _1CH.get_version()))

    def __table_exists(self, table):
        if self.db_type==DB_TYPES.MYSQL:
            sql='SHOW TABLES LIKE ?'
        else:
            sql='select name from sqlite_master where type="table" and name = ?'
        rows=self.__execute(sql, (table,))

        if not rows:
            return False
        else:
            return True

    def repair_meta_images(self):
        from metahandler import metahandlers
        from metahandler import metacontainers
        import xbmcgui
        __metaget__ = metahandlers.MetaData()

        cont = metacontainers.MetaContainer()
        if self.db_type == DB_TYPES.MYSQL:
            db = db_lib.connect(database=self.dbname, user=self.username, password=self.password, host=self.address, buffered=True)
        else:
            db = db_lib.connect(cont.videocache)
        dbcur = db.cursor()
        dlg = xbmcgui.DialogProgress()
        dlg.create('Repairing Images', '', '', '')
        for video_type in ('tvshow', 'movie'):
            total = 'SELECT count(*) from %s_meta WHERE ' % video_type
            total += 'imgs_prepacked = "true"'
            total = dbcur.execute(total).fetchone()[0]
            statement = 'SELECT title,cover_url,backdrop_url'
            if video_type == 'tvshow': statement += ',banner_url'
            statement += ' FROM %s_meta WHERE imgs_prepacked = "true"' % video_type
            complete = 1.0
            start_time = time.time()
            already_existing = 0

            for row in dbcur.execute(statement):
                title = row[0]
                cover = row[1]
                backdrop = row[2]
                if video_type == 'tvshow':
                    banner = row[3]
                else:
                    banner = False
                percent = int((complete * 100) / total)
                entries_per_sec = (complete - already_existing)
                entries_per_sec /= max(float((time.time() - start_time)), 1)
                total_est_time = total / max(entries_per_sec, 1)
                eta = total_est_time - (time.time() - start_time)

                eta = utils.format_eta(eta)
                dlg.update(percent, eta + title, '')
                if cover:
                    dlg.update(percent, eta + title, cover)
                    img_name = __metaget__._picname(cover)
                    img_path = os.path.join(__metaget__.mvcovers, img_name[0].lower())
                    file_path = os.path.join(img_path, img_name)
                    if not os.path.isfile(file_path):
                        retries = 4
                        while retries:
                            try:
                                __metaget__._downloadimages(cover, img_path, img_name)
                                break
                            except:
                                retries -= 1
                    else:
                        already_existing -= 1
                if backdrop:
                    dlg.update(percent, eta + title, backdrop)
                    img_name = __metaget__._picname(backdrop)
                    img_path = os.path.join(__metaget__.mvbackdrops, img_name[0].lower())
                    file_path = os.path.join(img_path, img_name)
                    if not os.path.isfile(file_path):
                        retries = 4
                        while retries:
                            try:
                                __metaget__._downloadimages(backdrop, img_path, img_name)
                                break
                            except:
                                retries -= 1
                    else:
                        already_existing -= 1
                if banner:
                    dlg.update(percent, eta + title, banner)
                    img_name = __metaget__._picname(banner)
                    img_path = os.path.join(__metaget__.tvbanners, img_name[0].lower())
                    file_path = os.path.join(img_path, img_name)
                    if not os.path.isfile(file_path):
                        retries = 4
                        while retries:
                            try:
                                __metaget__._downloadimages(banner, img_path, img_name)
                                break
                            except:
                                retries -= 1
                    else:
                        already_existing -= 1
                if dlg.iscanceled(): return False
                complete += 1

    def reset_db(self):
        if self.db_type==DB_TYPES.SQLITE:
            os.remove(self.db_path)
            self.db=None
            self.__connect_to_db()
            self.init_database()
            return True
        else:
            return False

    def __execute(self, sql, params=None):
        if params is None:
            params=[]

        rows=None
        sql=self.__format(sql)
        cur = self.db.cursor()
        utils.log('Running: %s with %s' % (sql, params), xbmc.LOGDEBUG)
        cur.execute(sql, params)
        if sql[:6].upper() == 'SELECT' or sql[:4].upper() == 'SHOW':
            rows=cur.fetchall()
        cur.close()
        self.db.commit()
        return rows

    def __get_db_version(self):
        version=None
        try:
            sql = 'SELECT value FROM db_info WHERE setting="version"'
            rows=self.__execute(sql)
        except:
            return None

        if rows:
            version=rows[0][0]

        return version

    # purpose is to save the current db with an export, drop the db, recreate it, then connect to it
    def __prep_for_reinit(self):
        self.mig_path = os.path.join(xbmc.translatePath("special://database"), 'mig_export_%s.csv' % (int(time.time())))
        utils.log('Backing up DB to %s' % (self.mig_path), xbmc.LOGDEBUG)
        self.export_from_db(self.mig_path)
        utils.log('Backup export of DB created at %s' % (self.mig_path))
        self.__drop_all()
        utils.log('DB Objects Dropped', xbmc.LOGDEBUG)

    def __create_sqlite_db(self):
        if not xbmcvfs.exists(os.path.dirname(self.db_path)):
            try: xbmcvfs.mkdirs(os.path.dirname(self.db_path))
            except: os.mkdir(os.path.dirname(self.db_path))

    def __drop_all(self):
        if self.db_type==DB_TYPES.MYSQL:
            sql = 'show tables'
        else:
            sql = 'select name from sqlite_master where type="table"'
        rows=self.__execute(sql)
        db_objects = [row[0] for row in rows]

        for db_object in db_objects:
            sql = 'DROP TABLE IF EXISTS %s' % (db_object)
            self.__execute(sql)

    def __connect_to_db(self):
        if not self.db:
            if self.db_type == DB_TYPES.MYSQL:
                self.db = db_lib.connect(database=self.dbname, user=self.username, password=self.password, host=self.address, buffered=True)
            else:
                self.db = db_lib.connect(self.db_path)
                self.db.text_factory = str

    # apply formatting changes to make sql work with a particular db driver
    def __format(self, sql):
        if self.db_type ==DB_TYPES.MYSQL:
            sql = sql.replace('?', '%s')

        if self.db_type == DB_TYPES.SQLITE:
            if sql[:7]=='REPLACE':
                sql = 'INSERT OR ' + sql

        return sql


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Olog - JIRA Report</title>

    <link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
    <meta name="Date-Revision-yyyymmdd" content="20140411" />
    <meta http-equiv="Content-Language" content="en" />

                OlogAPI

        Last Published: 2014-04-11
                   | Version: 2.2.7-SNAPSHOT

                    EPICS

OlogAPI

                          Overview

                          Download

Project Documentation

                          Project Information

                          Project Reports

            JIRA Report

                          JavaDocs

                          Source Xref

JIRA Report

An error occured that made it impossible to generate this report. Please check the console for information on what might be the cause of this.

              Copyright ©                    2010-2014
                      Michigan State University.
            All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
sudo apt-get install --only-upgrade pygments=1.5+dfsg-1+deb7u1 -y
sudo apt-get install --only-upgrade python-pygments=1.5+dfsg-1+deb7u1 -y
sudo apt-get install --only-upgrade python3-pygments=1.5+dfsg-1+deb7u1 -y


text:
@charset "utf-8";
*{padding:0px; margin:0px;}
body{background:#fff; color:#333; padding-bottom:50px; font-size:12px; font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;}
img{border:none; vertical-align:middle; border: none}
img.icon {width:16px;height:16px;padding-bottom:2px}
ul,dl{list-style:none;}
a{color:#004b8d; text-decoration:none}
a:hover{color:#4192d9; text-decoration:none}
hr.common{margin-top:10px;margin-bottom:10px;}
.fc_red{color:#f26101}
.fc_blue{color:#004b8d}
.fc_gray{color:#656565}
button, input, select{vertical-align:middle}
button{margin-right:5px;cursor:pointer;}
.btn1{height:22px;padding:0 6px;font-size:10pt;line-height:22px;color:#333;border:1px solid #d9e8f5;background:url(../img/button_bg1.gif) repeat-x; cursor:pointer;}
.highlight{background:#ffffe0}
.disn{display:none}

.mtitle{width:100%;margin:0px auto; height:29px; background:url(../img/mtitle_bg.gif) left top repeat-x; overflow:hidden; clear:both}
.mtitle h1{width:48%; height:29px; float:left; line-height:27px; font-size:12pt; font-weight:bold; text-indent:14px; letter-spacing:2px; color:#333;}
.mtitle span{float:right;}

.tform{width:100%; margin:0 auto; border-bottom:1px solid #d9e8f5; height:26px;line-height:26px;text-align:right;}

table .title{color:#333;font-weight:bold;background:#d9e8f5;}
table thead tr{height:24px;line-height:24px;}
table thead th{padding:3px;color:#333;}

.tlist{width:100%; margin:7px auto 0px; border-collapse:collapse}
.tlist tbody tr{height:20px;line-height:20px;background:#fff;font-weight:normal;color:#333;border-bottom:1px dotted #d9e8f5}
.tlist tr td{line-height:15px;padding:5px;color:#333;}
.tlist tbody td{border-bottom:1px dotted #d9e8f5}
.tlist tfoot tr{text-align:left;}
.tlist tfoot td{padding-left:0px;}

.titem {border-collapse:separate;}
.titem input {font-size:12px;}
.titem select {font-size:12px;}
.titem textarea {font-size:12px;}
.titem td.field {border:#d9e8f5 solid 1px;background:#d9e8f5;padding:3px;width:80px}
.titem td.value {border:#d9e8f5 solid 1px;padding:3px;}
.titem td.value input.common {width:300px}
.titem td.value textarea.common {width:300px}
.titem select.common {width:304px}
.titem select optgroup option {padding-left:23px}
.titem td.submit {padding-top:10px;}
.titem td.submit input {width:50px}

.pagelist{padding:0px;}
.pagelist b{overflow:hidden;display:inline; padding:4px;text-decoration:none; color:#333; border:1px solid #eeeeee;}
.pagelist a{overflow:hidden;display:inline; padding:4px;text-decoration:none; color:#333; border:1px solid #ebebeb;}
.pagelist a:hover,.pagelist strong{border:1px solid #ffd375;color:#f26101;padding:4px;}
.pagelist span{margin:0 5px;}

img.chart_common{width:800px;height:440px}
img.chart_line{width:1000px;height:500px}
img.chart_pie{width:500px;height:300px}

input.filter_input{width:50px}

div.errorbox{width:100%; border:#ff0000 solid 1px;margin-bottom:10px;}
div.errorbox span{padding:3px 5px 3px 5px;display:block}

div.main{height:100%;margin:0px;padding:10px;}
div.maintop{padding:5px 0px 10px 0px; border-bottom:#ccc dashed 1px}
div.mainbox{margin-top:10px;margin-bottom:20px}
div.tablebox{width:800px}


text:
<resources>
    <string name="app_name">易用天气</string>
</resources>


text:
void register_PointSet_class();

#endif//PointSet_hpp__pyplusplus_wrapper


text:
<?php

namespace AppBundle\Controller\Api;

use AppBundle\Entity\Account;
use AppBundle\Entity\Organization;
use AppBundle\Form\Account\AddAccountType;
use HttpException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

/**
 * @Route("/api/organizations")
 */
class ApiOrganizationAccountController extends Controller
{
    /**
     * @Route("/{id}/accounts/new", name="api_organization_accounts_add")
     * @Method({"POST"})
     */
    public function apiOrganizationNewAccountAction(Request $request, $id)
    {
//        $encoders = array(new JsonEncoder());
//        $normalizer = new ObjectNormalizer(null);
////        $normalizer->setIgnoredAttributes(array('email'));
//        $normalizer->setCircularReferenceHandler(function ($object) {
//            return $object->getId();
//        });
//        $normalizers = array($normalizer);
//        $serializer = new Serializer($normalizers, $encoders);

        $em = $this->getDoctrine()->getManager();

        $organization = $em->getRepository(Organization::class)->find($id);
        if (!$organization) {
            return $this->json('Organization not found', 404);
        }
        if ($organization->getCreator()->getId() != $this->getUser()->getId()) {
            return $this->json('Not creator', 403);
        }

//        $membersIds = array();
//        foreach ($organization->getMembers() as $member) {
//            array_push($membersIds, $member->getId());
//        }
//        if (!in_array($this->getUser()->getId(), $membersIds)) {
//            return $this->json('Not a member', 404);
//        }

        $data = json_decode($request->getContent(), true);

        $account = new Account();
        $form = $this->createForm(AddAccountType::class, $account);
        $form->submit($data['account']);

        if ($form->isSubmitted() && $form->isValid()) {
            $account->setOrganization($organization);
            $account->setBalance(0);
            $account->setCreatedAt(new \DateTime());
            $account->setUpdatedAt(new \DateTime());

            $em->persist($organization);
            $em->persist($account);
            $em->flush();

            $this->get('logger')->info("test");

//            return $this->json(['account' => $account], 200, [], [AbstractNormalizer::GROUPS => ['group2']]);
            return $this->json(['account' => $account], 200);
//            return new JsonResponse($account);

//            return new Response($serializer->serialize($account, 'json'));
        }

        return $this->json('Invalid data', 400);
    }

    /**
     * @Route("/{id}/accounts/all", name="api_organization_accounts_all")
     * @Method({"GET"})
     */
    public function apiOrganizationAllAccountsAction($id)
    {
        $accounts = $this
            ->getDoctrine()
            ->getRepository(Organization::class)
            ->find($id)
            ->getAccounts();
        return $this->json(['accounts' => $accounts], 200);
    }

    /**
     * @Route("/{id}/accounts/{accountId}/edit", name="api_organization_accounts_edit")
     * @Method({"PUT"})
     */
    public function apiOrganizationEditAccountAction(Request $request, $id, $accountId)
    {
        $em = $this->getDoctrine()->getManager();

        $organization = $em->getRepository(Organization::class)->find($id);
        if (!$organization) {
            return $this->json('Organization not found', 404);
        }
        if ($organization->getCreator()->getId() != $this->getUser()->getId()) {
            return $this->json('Not creator', 403);
        }

//        $membersIds = array();
//        foreach ($organization->getMembers() as $member) {
//            array_push($membersIds, $member->getId());
//        }
//        if (!in_array($this->getUser()->getId(), $membersIds)) {
//            return $this->json('Not a member', 404);
//        }

        $account = $em->getRepository(Account::class)->find($accountId);
        if (!$account) {
            return $this->json('Account not found', 404);
        }

        $data = json_decode($request->getContent(), true);

        $form = $this->createForm(AddAccountType::class, $account);
        $form->submit($data['account']);

        if ($account != null && $form->isSubmitted() && $form->isValid()) {
            $account->setUpdatedAt(new \DateTime());
            $em->flush();
            return $this->json(['account' => $account], 200);
        }

        return $this->json('Invalid data', 400);
    }

    /**
     * @Route("/{id}/accounts/{accountId}/delete", name="api_organization_accounts_delete")
     * @Method({"DELETE"})
     */
    public function apiOrganizationDeleteAccountAction(Request $request, $id, $accountId)
    {
        $em = $this->getDoctrine()->getManager();

        $organization = $em->getRepository(Organization::class)->find($id);
        if (!$organization) {
            return $this->json('Organization not found', 404);
        }
        if ($organization->getCreator()->getId() != $this->getUser()->getId()) {
            return $this->json('Not creator', 403);
        }

//        $membersIds = array();
//        foreach ($organization->getMembers() as $member) {
//            array_push($membersIds, $member->getId());
//        }
//        if (!in_array($this->getUser()->getId(), $membersIds)) {
//            return $this->json('Not a member', 404);
//        }

        $account = $em->getRepository(Account::class)->find($accountId);
        if (!$account) {
            return $this->json('Account not found', 404);
        }

        $em->remove($account);
        $em->flush();

        return $this->json(['msg' => 'Deleted'], 200);
    }

    /**
     * @Route("/{id}/accounts/{accountId}/details", name="api_organization_account_details")
     * @Method("GET")
     */
    public function apiOrganizationAccountAction($id, $accountId)
    {
        $em = $this->getDoctrine()->getManager();

        $organization = $em->getRepository(Organization::class)->find($id);
        if (!$organization) {
            return $this->json('Organization not found', 404);
        }

        $membersIds = array();
        foreach ($organization->getMembers() as $member) {
            array_push($membersIds, $member->getId());
        }
        if (!in_array($this->getUser()->getId(), $membersIds)) {
            return $this->json('Not a member', 404);
        }

        $account = $em->getRepository(Account::class)->find($accountId);
        if (!$account) {
            return $this->json('Account not found', 404);
        }

        return $this->json(['account' => $account], 200);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
Fail: (1301) Compartment units must not be set if spatialDimensions is
zero.
-->

<sbml xmlns="http://www.sbml.org/sbml/level2/version2" level="2" version="2">
  <model>
    <listOfCompartments>
      <compartment id="c" spatialDimensions="0" units="ml"/>
    </listOfCompartments>
  </model>
</sbml>


text:
#include "config.h"

#define DEBUG_FLAG DEBUG_PROXY
#include "debug.h"
#include "hashmap.h"
#define CRYPTOKI_EXPORTS
#include "pkcs11.h"
#include "p11-kit.h"
#include "private.h"
#include "util.h"

#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/* Start wrap slots slightly higher for testing */
#define MAPPING_OFFSET 0x10
#define FIRST_HANDLE   0x10

typedef struct _Mapping {
	CK_SLOT_ID wrap_slot;
	CK_SLOT_ID real_slot;
	CK_FUNCTION_LIST_PTR funcs;
} Mapping;

typedef struct _Session {
	CK_SESSION_HANDLE wrap_session;
	CK_SESSION_HANDLE real_session;
	CK_SLOT_ID wrap_slot;
} Session;

/* Forward declaration */
static CK_FUNCTION_LIST proxy_function_list;

/*
 * Shared data between threads, protected by the mutex, a structure so
 * we can audit thread safety easier.
 */
static struct _Shared {
	Mapping *mappings;
	unsigned int n_mappings;
	int mappings_refs;
	hashmap *sessions;
	CK_ULONG last_handle;
} gl = { NULL, 0, 0, NULL, FIRST_HANDLE };

#define MANUFACTURER_ID         "PKCS#11 Kit                     "
#define LIBRARY_DESCRIPTION     "PKCS#11 Kit Proxy Module        "
#define LIBRARY_VERSION_MAJOR   1
#define LIBRARY_VERSION_MINOR   1

/* -----------------------------------------------------------------------------
 * PKCS#11 PROXY MODULE
 */

static CK_RV
map_slot_unlocked (CK_SLOT_ID slot, Mapping *mapping)
{
	assert (mapping);

	if (slot < MAPPING_OFFSET)
		return CKR_SLOT_ID_INVALID;
	slot -= MAPPING_OFFSET;

	if (slot > gl.n_mappings) {
		return CKR_SLOT_ID_INVALID;
	} else {
		assert (gl.mappings);
		memcpy (mapping, &gl.mappings[slot], sizeof (Mapping));
		return CKR_OK;
	}
}

static CK_RV
map_slot_to_real (CK_SLOT_ID_PTR slot, Mapping *mapping)
{
	CK_RV rv;

	assert (mapping);

	_p11_lock ();

		if (!gl.mappings)
			rv = CKR_CRYPTOKI_NOT_INITIALIZED;
		else
			rv = map_slot_unlocked (*slot, mapping);
		if (rv == CKR_OK)
			*slot = mapping->real_slot;

	_p11_unlock ();

	return rv;
}

static CK_RV
map_session_to_real (CK_SESSION_HANDLE_PTR handle, Mapping *mapping, Session *session)
{
	CK_RV rv = CKR_OK;
	Session *sess;

	assert (handle);
	assert (mapping);

	_p11_lock ();

		if (!gl.sessions) {
			rv = CKR_CRYPTOKI_NOT_INITIALIZED;
		} else {
			assert (gl.sessions);
			sess = _p11_hash_get (gl.sessions, handle);
			if (sess != NULL) {
				*handle = sess->real_session;
				rv = map_slot_unlocked (sess->wrap_slot, mapping);
				if (session != NULL)
					memcpy (session, sess, sizeof (Session));
			} else {
				rv = CKR_SESSION_HANDLE_INVALID;
			}
		}

	_p11_unlock ();

	return rv;
}

static void
finalize_mappings_unlocked (void)
{
	assert (gl.mappings_refs);

	if (--gl.mappings_refs)
		return;

	/* No more mappings */
	free (gl.mappings);
	gl.mappings = NULL;
	gl.n_mappings = 0;

	/* no more sessions */
	_p11_hash_free (gl.sessions);
	gl.sessions = NULL;
}

void
_p11_kit_proxy_after_fork (void)
{
	/*
	 * After a fork the callers are supposed to call C_Initialize and all.
	 * In addition the underlying libraries may change their state so free
	 * up any mappings and all
	 */

	_p11_lock ();

		gl.mappings_refs = 1;
		finalize_mappings_unlocked ();
		assert (!gl.mappings);

	_p11_unlock ();
}

static CK_RV
proxy_C_Finalize (CK_VOID_PTR reserved)
{
	CK_RV rv;

	_p11_debug ("in");

	/* WARNING: This function must be reentrant */

	if (reserved) {
		rv = CKR_ARGUMENTS_BAD;

	} else {
		_p11_lock ();

			/* WARNING: Reentrancy can occur here */
			rv = _p11_kit_finalize_registered_unlocked_reentrant ();

			/*
			 * If modules are all gone, then this was the last
			 * finalize, so cleanup our mappings
			 */
			if (gl.mappings_refs)
				finalize_mappings_unlocked ();

		_p11_unlock ();
	}

	_p11_debug ("out: %lu", rv);
	return rv;
}

static CK_RV
initialize_mappings_unlocked_reentrant (void)
{
	CK_FUNCTION_LIST_PTR *funcss, *f;
	CK_FUNCTION_LIST_PTR funcs;
	Mapping *mappings = NULL;
	int n_mappings = 0;
	CK_SLOT_ID_PTR slots;
	CK_ULONG i, count;
	CK_RV rv = CKR_OK;

	assert (!gl.mappings);

	funcss = _p11_kit_registered_modules_unlocked ();
	for (f = funcss; *f; ++f) {
		funcs = *f;

		assert (funcs);
		slots = NULL;

		_p11_unlock ();

			/* Ask module for its slots */
			rv = (funcs->C_GetSlotList) (FALSE, NULL, &count);
			if (rv == CKR_OK && count) {
				slots = calloc (sizeof (CK_SLOT_ID), count);
				if (!slots)
					rv = CKR_HOST_MEMORY;
				else
					rv = (funcs->C_GetSlotList) (FALSE, slots, &count);
			}

		_p11_lock ();

		if (rv != CKR_OK) {
			free (slots);
			break;
		}

		mappings = _p11_realloc (mappings, sizeof (Mapping) * (n_mappings + count));
		if (!mappings) {
			free (slots);
			rv = CKR_HOST_MEMORY;
			break;
		}

		/* And now add a mapping for each of those slots */
		for (i = 0; i < count; ++i) {
			mappings[n_mappings].funcs = funcs;
			mappings[n_mappings].wrap_slot = n_mappings + MAPPING_OFFSET;
			mappings[n_mappings].real_slot = slots[i];
			++n_mappings;
		}

		free (slots);
	}

	/* Another thread raced us here due to above reentrancy */
	if (gl.mappings) {
		free (mappings);
		return CKR_OK;
	}

	assert (!gl.sessions);
	gl.mappings = mappings;
	gl.n_mappings = n_mappings;
	gl.sessions = _p11_hash_create (_p11_hash_ulongptr_hash, _p11_hash_ulongptr_equal, NULL, free);
	++gl.mappings_refs;

	/* Any cleanup necessary for failure will happen at caller */
	return rv;
}

static CK_RV
proxy_C_Initialize (CK_VOID_PTR init_args)
{
	CK_RV rv;

	_p11_library_init_once ();

	/* WARNING: This function must be reentrant */

	_p11_debug ("in");

	_p11_lock ();

		/* WARNING: Reentrancy can occur here */
		rv = _p11_kit_initialize_registered_unlocked_reentrant ();

		/* WARNING: Reentrancy can occur here */
		if (rv == CKR_OK && gl.mappings_refs == 0)
			rv = initialize_mappings_unlocked_reentrant ();

	_p11_unlock ();

	_p11_debug ("here");

	if (rv != CKR_OK)
		proxy_C_Finalize (NULL);

	_p11_debug ("out: %lu", rv);
	return rv;
}

static CK_RV
proxy_C_GetInfo (CK_INFO_PTR info)
{
	CK_RV rv = CKR_OK;

	_p11_library_init_once ();

	if (info == NULL)
		return CKR_ARGUMENTS_BAD;

	_p11_lock ();

		if (!gl.mappings)
			rv = CKR_CRYPTOKI_NOT_INITIALIZED;

	_p11_unlock ();

	if (rv != CKR_OK)
		return rv;

	info->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR;
	info->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR;
	info->libraryVersion.major = LIBRARY_VERSION_MAJOR;
	info->libraryVersion.minor = LIBRARY_VERSION_MINOR;
	info->flags = 0;
	strncpy ((char*)info->manufacturerID, MANUFACTURER_ID, 32);
	strncpy ((char*)info->libraryDescription, LIBRARY_DESCRIPTION, 32);
	return CKR_OK;
}

static CK_RV
proxy_C_GetFunctionList (CK_FUNCTION_LIST_PTR_PTR list)
{
	/* Can be called before C_Initialize */

	if (!list)
		return CKR_ARGUMENTS_BAD;
	*list = &proxy_function_list;
	return CKR_OK;
}

static CK_RV
proxy_C_GetSlotList (CK_BBOOL token_present, CK_SLOT_ID_PTR slot_list,
                       CK_ULONG_PTR count)
{
	CK_SLOT_INFO info;
	Mapping *mapping;
	CK_ULONG index;
	CK_RV rv = CKR_OK;
	int i;

	if (!count)
		return CKR_ARGUMENTS_BAD;

	_p11_lock ();

		if (!gl.mappings) {
			rv = CKR_CRYPTOKI_NOT_INITIALIZED;
		} else {
			index = 0;

			/* Go through and build up a map */
			for (i = 0; i < gl.n_mappings; ++i) {
				mapping = &gl.mappings[i];

				/* Skip ones without a token if requested */
				if (token_present) {
					rv = (mapping->funcs->C_GetSlotInfo) (mapping->real_slot, &info);
					if (rv != CKR_OK)
						break;
					if (!(info.flags & CKF_TOKEN_PRESENT))
						continue;
				}

				/* Fill in the slot if we can */
				if (slot_list && *count > index)
					slot_list[index] = mapping->wrap_slot;

				++index;
			}

			if (slot_list && *count < index)
				rv = CKR_BUFFER_TOO_SMALL;

			*count = index;
		}

	_p11_unlock ();

	return rv;
}

static CK_RV
proxy_C_GetSlotInfo (CK_SLOT_ID id, CK_SLOT_INFO_PTR info)
{
	Mapping map;
	CK_RV rv;

	rv = map_slot_to_real (&id, &map);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetSlotInfo) (id, info);
}

static CK_RV
proxy_C_GetTokenInfo (CK_SLOT_ID id, CK_TOKEN_INFO_PTR info)
{
	Mapping map;
	CK_RV rv;

	rv = map_slot_to_real (&id, &map);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetTokenInfo) (id, info);
}

static CK_RV
proxy_C_GetMechanismList (CK_SLOT_ID id, CK_MECHANISM_TYPE_PTR mechanism_list,
                          CK_ULONG_PTR count)
{
	Mapping map;
	CK_RV rv;

	rv = map_slot_to_real (&id, &map);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetMechanismList) (id, mechanism_list, count);
}

static CK_RV
proxy_C_GetMechanismInfo (CK_SLOT_ID id, CK_MECHANISM_TYPE type,
                          CK_MECHANISM_INFO_PTR info)
{
	Mapping map;
	CK_RV rv;

	rv = map_slot_to_real (&id, &map);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetMechanismInfo) (id, type, info);
}

static CK_RV
proxy_C_InitToken (CK_SLOT_ID id, CK_UTF8CHAR_PTR pin, CK_ULONG pin_len, CK_UTF8CHAR_PTR label)
{
	Mapping map;
	CK_RV rv;

	rv = map_slot_to_real (&id, &map);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_InitToken) (id, pin, pin_len, label);
}

static CK_RV
proxy_C_WaitForSlotEvent (CK_FLAGS flags, CK_SLOT_ID_PTR slot, CK_VOID_PTR reserved)
{
	return CKR_FUNCTION_NOT_SUPPORTED;
}

static CK_RV
proxy_C_OpenSession (CK_SLOT_ID id, CK_FLAGS flags, CK_VOID_PTR user_data,
                     CK_NOTIFY callback, CK_SESSION_HANDLE_PTR handle)
{
	Session *sess;
	Mapping map;
	CK_RV rv;

	if (handle == NULL)
		return CKR_ARGUMENTS_BAD;

	rv = map_slot_to_real (&id, &map);
	if (rv != CKR_OK)
		return rv;

	rv = (map.funcs->C_OpenSession) (id, flags, user_data, callback, handle);

	if (rv == CKR_OK) {
		_p11_lock ();

			if (!gl.sessions) {
				/*
				 * The underlying module should have returned an error, so this
				 * code should never be reached with properly behaving modules.
				 * That's why we don't cleanup and close the newly opened session here
				 * or anything like that.
				 */
				rv = CKR_CRYPTOKI_NOT_INITIALIZED;

			} else {
				sess = calloc (1, sizeof (Session));
				sess->wrap_slot = map.wrap_slot;
				sess->real_session = *handle;
				sess->wrap_session = ++gl.last_handle; /* TODO: Handle wrapping, and then collisions */
				_p11_hash_set (gl.sessions, &sess->wrap_session, sess);
				*handle = sess->wrap_session;
			}

		_p11_unlock ();
	}

	return rv;
}

static CK_RV
proxy_C_CloseSession (CK_SESSION_HANDLE handle)
{
	CK_SESSION_HANDLE key;
	Mapping map;
	CK_RV rv;

	key = handle;
	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	rv = (map.funcs->C_CloseSession) (handle);

	if (rv == CKR_OK) {
		_p11_lock ();

			if (gl.sessions)
				_p11_hash_remove (gl.sessions, &key);

		_p11_unlock ();
	}

	return rv;
}

static CK_RV
proxy_C_CloseAllSessions (CK_SLOT_ID id)
{
	CK_SESSION_HANDLE_PTR to_close;
	CK_RV rv = CKR_OK;
	Session *sess;
	CK_ULONG i, count = 0;
	hashiter iter;

	_p11_lock ();

		if (!gl.sessions) {
			rv = CKR_CRYPTOKI_NOT_INITIALIZED;
		} else {
			to_close = calloc (sizeof (CK_SESSION_HANDLE), _p11_hash_size (gl.sessions));
			if (!to_close) {
				rv = CKR_HOST_MEMORY;
			} else {
				_p11_hash_iterate (gl.sessions, &iter);
				count = 0;
				while (_p11_hash_next (&iter, NULL, (void**)&sess)) {
					if (sess->wrap_slot == id && to_close)
						to_close[count++] = sess->wrap_session;
				}
			}
		}

	_p11_unlock ();

	if (rv != CKR_OK)
		return rv;

	for (i = 0; i < count; ++i)
		proxy_C_CloseSession (to_close[i]);

	free (to_close);
	return CKR_OK;
}

static CK_RV
proxy_C_GetFunctionStatus (CK_SESSION_HANDLE handle)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetFunctionStatus) (handle);
}

static CK_RV
proxy_C_CancelFunction (CK_SESSION_HANDLE handle)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_CancelFunction) (handle);
}

static CK_RV
proxy_C_GetSessionInfo (CK_SESSION_HANDLE handle, CK_SESSION_INFO_PTR info)
{
	Mapping map;
	CK_RV rv;

	if (info == NULL)
		return CKR_ARGUMENTS_BAD;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;

	rv = (map.funcs->C_GetSessionInfo) (handle, info);
	if (rv == CKR_OK)
		info->slotID = map.wrap_slot;

	return rv;
}

static CK_RV
proxy_C_InitPIN (CK_SESSION_HANDLE handle, CK_UTF8CHAR_PTR pin, CK_ULONG pin_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;

	return (map.funcs->C_InitPIN) (handle, pin, pin_len);
}

static CK_RV
proxy_C_SetPIN (CK_SESSION_HANDLE handle, CK_UTF8CHAR_PTR old_pin, CK_ULONG old_pin_len,
                CK_UTF8CHAR_PTR new_pin, CK_ULONG new_pin_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;

	return (map.funcs->C_SetPIN) (handle, old_pin, old_pin_len, new_pin, new_pin_len);
}

static CK_RV
proxy_C_GetOperationState (CK_SESSION_HANDLE handle, CK_BYTE_PTR operation_state, CK_ULONG_PTR operation_state_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetOperationState) (handle, operation_state, operation_state_len);
}

static CK_RV
proxy_C_SetOperationState (CK_SESSION_HANDLE handle, CK_BYTE_PTR operation_state,
                           CK_ULONG operation_state_len, CK_OBJECT_HANDLE encryption_key,
                           CK_OBJECT_HANDLE authentication_key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SetOperationState) (handle, operation_state, operation_state_len, encryption_key, authentication_key);
}

static CK_RV
proxy_C_Login (CK_SESSION_HANDLE handle, CK_USER_TYPE user_type,
               CK_UTF8CHAR_PTR pin, CK_ULONG pin_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;

	return (map.funcs->C_Login) (handle, user_type, pin, pin_len);
}

static CK_RV
proxy_C_Logout (CK_SESSION_HANDLE handle)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_Logout) (handle);
}

static CK_RV
proxy_C_CreateObject (CK_SESSION_HANDLE handle, CK_ATTRIBUTE_PTR template,
                      CK_ULONG count, CK_OBJECT_HANDLE_PTR new_object)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;

	return (map.funcs->C_CreateObject) (handle, template, count, new_object);
}

static CK_RV
proxy_C_CopyObject (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object,
                    CK_ATTRIBUTE_PTR template, CK_ULONG count,
                    CK_OBJECT_HANDLE_PTR new_object)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_CopyObject) (handle, object, template, count, new_object);
}

static CK_RV
proxy_C_DestroyObject (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DestroyObject) (handle, object);
}

static CK_RV
proxy_C_GetObjectSize (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object,
                       CK_ULONG_PTR size)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetObjectSize) (handle, object, size);
}

static CK_RV
proxy_C_GetAttributeValue (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object,
                           CK_ATTRIBUTE_PTR template, CK_ULONG count)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GetAttributeValue) (handle, object, template, count);
}

static CK_RV
proxy_C_SetAttributeValue (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE object,
                           CK_ATTRIBUTE_PTR template, CK_ULONG count)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SetAttributeValue) (handle, object, template, count);
}

static CK_RV
proxy_C_FindObjectsInit (CK_SESSION_HANDLE handle, CK_ATTRIBUTE_PTR template,
                         CK_ULONG count)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_FindObjectsInit) (handle, template, count);
}

static CK_RV
proxy_C_FindObjects (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE_PTR objects,
                     CK_ULONG max_count, CK_ULONG_PTR count)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_FindObjects) (handle, objects, max_count, count);
}

static CK_RV
proxy_C_FindObjectsFinal (CK_SESSION_HANDLE handle)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_FindObjectsFinal) (handle);
}

static CK_RV
proxy_C_EncryptInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                     CK_OBJECT_HANDLE key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_EncryptInit) (handle, mechanism, key);
}

static CK_RV
proxy_C_Encrypt (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len,
                 CK_BYTE_PTR encrypted_data, CK_ULONG_PTR encrypted_data_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_Encrypt) (handle, data, data_len, encrypted_data, encrypted_data_len);
}

static CK_RV
proxy_C_EncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part,
                       CK_ULONG part_len, CK_BYTE_PTR encrypted_part,
                       CK_ULONG_PTR encrypted_part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_EncryptUpdate) (handle, part, part_len, encrypted_part, encrypted_part_len);
}

static CK_RV
proxy_C_EncryptFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR last_part,
                      CK_ULONG_PTR last_part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_EncryptFinal) (handle, last_part, last_part_len);
}

static CK_RV
proxy_C_DecryptInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                     CK_OBJECT_HANDLE key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DecryptInit) (handle, mechanism, key);
}

static CK_RV
proxy_C_Decrypt (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_data,
                 CK_ULONG enc_data_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_Decrypt) (handle, enc_data, enc_data_len, data, data_len);
}

static CK_RV
proxy_C_DecryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part,
                       CK_ULONG enc_part_len, CK_BYTE_PTR part, CK_ULONG_PTR part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DecryptUpdate) (handle, enc_part, enc_part_len, part, part_len);
}

static CK_RV
proxy_C_DecryptFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR last_part,
                      CK_ULONG_PTR last_part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DecryptFinal) (handle, last_part, last_part_len);
}

static CK_RV
proxy_C_DigestInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DigestInit) (handle, mechanism);
}

static CK_RV
proxy_C_Digest (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len,
                CK_BYTE_PTR digest, CK_ULONG_PTR digest_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_Digest) (handle, data, data_len, digest, digest_len);
}

static CK_RV
proxy_C_DigestUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DigestUpdate) (handle, part, part_len);
}

static CK_RV
proxy_C_DigestKey (CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DigestKey) (handle, key);
}

static CK_RV
proxy_C_DigestFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR digest,
                     CK_ULONG_PTR digest_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DigestFinal) (handle, digest, digest_len);
}

static CK_RV
proxy_C_SignInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                  CK_OBJECT_HANDLE key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SignInit) (handle, mechanism, key);
}

static CK_RV
proxy_C_Sign (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len,
              CK_BYTE_PTR signature, CK_ULONG_PTR signature_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_Sign) (handle, data, data_len, signature, signature_len);
}

static CK_RV
proxy_C_SignUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SignUpdate) (handle, part, part_len);
}

static CK_RV
proxy_C_SignFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature,
                   CK_ULONG_PTR signature_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SignFinal) (handle, signature, signature_len);
}

static CK_RV
proxy_C_SignRecoverInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                         CK_OBJECT_HANDLE key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SignRecoverInit) (handle, mechanism, key);
}

static CK_RV
proxy_C_SignRecover (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len,
                     CK_BYTE_PTR signature, CK_ULONG_PTR signature_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SignRecover) (handle, data, data_len, signature, signature_len);
}

static CK_RV
proxy_C_VerifyInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                    CK_OBJECT_HANDLE key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_VerifyInit) (handle, mechanism, key);
}

static CK_RV
proxy_C_Verify (CK_SESSION_HANDLE handle, CK_BYTE_PTR data, CK_ULONG data_len,
                CK_BYTE_PTR signature, CK_ULONG signature_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_Verify) (handle, data, data_len, signature, signature_len);
}

static CK_RV
proxy_C_VerifyUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part, CK_ULONG part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_VerifyUpdate) (handle, part, part_len);
}

static CK_RV
proxy_C_VerifyFinal (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature,
                     CK_ULONG signature_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_VerifyFinal) (handle, signature, signature_len);
}

static CK_RV
proxy_C_VerifyRecoverInit (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                           CK_OBJECT_HANDLE key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_VerifyRecoverInit) (handle, mechanism, key);
}

static CK_RV
proxy_C_VerifyRecover (CK_SESSION_HANDLE handle, CK_BYTE_PTR signature,
                       CK_ULONG signature_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_VerifyRecover) (handle, signature, signature_len, data, data_len);
}

static CK_RV
proxy_C_DigestEncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part,
                             CK_ULONG part_len, CK_BYTE_PTR enc_part,
                             CK_ULONG_PTR enc_part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DigestEncryptUpdate) (handle, part, part_len, enc_part, enc_part_len);
}

static CK_RV
proxy_C_DecryptDigestUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part,
                             CK_ULONG enc_part_len, CK_BYTE_PTR part,
                             CK_ULONG_PTR part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DecryptDigestUpdate) (handle, enc_part, enc_part_len, part, part_len);
}

static CK_RV
proxy_C_SignEncryptUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR part,
                           CK_ULONG part_len, CK_BYTE_PTR enc_part,
                           CK_ULONG_PTR enc_part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SignEncryptUpdate) (handle, part, part_len, enc_part, enc_part_len);
}

static CK_RV
proxy_C_DecryptVerifyUpdate (CK_SESSION_HANDLE handle, CK_BYTE_PTR enc_part,
                             CK_ULONG enc_part_len, CK_BYTE_PTR part,
                             CK_ULONG_PTR part_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DecryptVerifyUpdate) (handle, enc_part, enc_part_len, part, part_len);
}

static CK_RV
proxy_C_GenerateKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                     CK_ATTRIBUTE_PTR template, CK_ULONG count,
                     CK_OBJECT_HANDLE_PTR key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GenerateKey) (handle, mechanism, template, count, key);
}

static CK_RV
proxy_C_GenerateKeyPair (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                         CK_ATTRIBUTE_PTR pub_template, CK_ULONG pub_count,
                         CK_ATTRIBUTE_PTR priv_template, CK_ULONG priv_count,
                         CK_OBJECT_HANDLE_PTR pub_key, CK_OBJECT_HANDLE_PTR priv_key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GenerateKeyPair) (handle, mechanism, pub_template, pub_count, priv_template, priv_count, pub_key, priv_key);
}

static CK_RV
proxy_C_WrapKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                 CK_OBJECT_HANDLE wrapping_key, CK_OBJECT_HANDLE key,
                 CK_BYTE_PTR wrapped_key, CK_ULONG_PTR wrapped_key_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_WrapKey) (handle, mechanism, wrapping_key, key, wrapped_key, wrapped_key_len);
}

static CK_RV
proxy_C_UnwrapKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                   CK_OBJECT_HANDLE unwrapping_key, CK_BYTE_PTR wrapped_key,
                   CK_ULONG wrapped_key_len, CK_ATTRIBUTE_PTR template,
                   CK_ULONG count, CK_OBJECT_HANDLE_PTR key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_UnwrapKey) (handle, mechanism, unwrapping_key, wrapped_key, wrapped_key_len, template, count, key);
}

static CK_RV
proxy_C_DeriveKey (CK_SESSION_HANDLE handle, CK_MECHANISM_PTR mechanism,
                   CK_OBJECT_HANDLE base_key, CK_ATTRIBUTE_PTR template,
                   CK_ULONG count, CK_OBJECT_HANDLE_PTR key)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_DeriveKey) (handle, mechanism, base_key, template, count, key);
}

static CK_RV
proxy_C_SeedRandom (CK_SESSION_HANDLE handle, CK_BYTE_PTR seed, CK_ULONG seed_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_SeedRandom) (handle, seed, seed_len);
}

static CK_RV
proxy_C_GenerateRandom (CK_SESSION_HANDLE handle, CK_BYTE_PTR random_data,
                          CK_ULONG random_len)
{
	Mapping map;
	CK_RV rv;

	rv = map_session_to_real (&handle, &map, NULL);
	if (rv != CKR_OK)
		return rv;
	return (map.funcs->C_GenerateRandom) (handle, random_data, random_len);
}

/* --------------------------------------------------------------------
 * MODULE ENTRY POINT
 */

static CK_FUNCTION_LIST proxy_function_list = {
	{ CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR },  /* version */
	proxy_C_Initialize,
	proxy_C_Finalize,
	proxy_C_GetInfo,
	proxy_C_GetFunctionList,
	proxy_C_GetSlotList,
	proxy_C_GetSlotInfo,
	proxy_C_GetTokenInfo,
	proxy_C_GetMechanismList,
	proxy_C_GetMechanismInfo,
	proxy_C_InitToken,
	proxy_C_InitPIN,
	proxy_C_SetPIN,
	proxy_C_OpenSession,
	proxy_C_CloseSession,
	proxy_C_CloseAllSessions,
	proxy_C_GetSessionInfo,
	proxy_C_GetOperationState,
	proxy_C_SetOperationState,
	proxy_C_Login,
	proxy_C_Logout,
	proxy_C_CreateObject,
	proxy_C_CopyObject,
	proxy_C_DestroyObject,
	proxy_C_GetObjectSize,
	proxy_C_GetAttributeValue,
	proxy_C_SetAttributeValue,
	proxy_C_FindObjectsInit,
	proxy_C_FindObjects,
	proxy_C_FindObjectsFinal,
	proxy_C_EncryptInit,
	proxy_C_Encrypt,
	proxy_C_EncryptUpdate,
	proxy_C_EncryptFinal,
	proxy_C_DecryptInit,
	proxy_C_Decrypt,
	proxy_C_DecryptUpdate,
	proxy_C_DecryptFinal,
	proxy_C_DigestInit,
	proxy_C_Digest,
	proxy_C_DigestUpdate,
	proxy_C_DigestKey,
	proxy_C_DigestFinal,
	proxy_C_SignInit,
	proxy_C_Sign,
	proxy_C_SignUpdate,
	proxy_C_SignFinal,
	proxy_C_SignRecoverInit,
	proxy_C_SignRecover,
	proxy_C_VerifyInit,
	proxy_C_Verify,
	proxy_C_VerifyUpdate,
	proxy_C_VerifyFinal,
	proxy_C_VerifyRecoverInit,
	proxy_C_VerifyRecover,
	proxy_C_DigestEncryptUpdate,
	proxy_C_DecryptDigestUpdate,
	proxy_C_SignEncryptUpdate,
	proxy_C_DecryptVerifyUpdate,
	proxy_C_GenerateKey,
	proxy_C_GenerateKeyPair,
	proxy_C_WrapKey,
	proxy_C_UnwrapKey,
	proxy_C_DeriveKey,
	proxy_C_SeedRandom,
	proxy_C_GenerateRandom,
	proxy_C_GetFunctionStatus,
	proxy_C_CancelFunction,
	proxy_C_WaitForSlotEvent
};

#ifdef OS_WIN32
__declspec(dllexport)
#endif

CK_RV
C_GetFunctionList (CK_FUNCTION_LIST_PTR_PTR list)
{
	_p11_library_init_once ();
	return proxy_C_GetFunctionList (list);
}


text:
int main(void)
{
    size_t failedTestCount = 0;
    RUN_TEST_SUITE(serializer_ut_without_init, failedTestCount);
    return failedTestCount;
}


text:
<?php

namespace ChadicusTest\Slim\OAuth2\Routes;

use Chadicus\Slim\OAuth2\Routes\Token;

/**
 * Unit tests for the \Chadicus\Slim\OAuth2\Routes\Token class.
 *
 * @coversDefaultClass \Chadicus\Slim\OAuth2\Routes\Token
 * @covers ::<private>
 * @covers ::__construct
 */
final class TokenTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Verify basic behavior of __invoke()
     *
     * @test
     * @covers ::__invoke
     *
     * @return void
     */
    public function invoke()
    {
        $storage = new \OAuth2\Storage\Memory(
            [
                'client_credentials' => [
                    'testClientId' => [
                        'client_id' => 'testClientId',
                        'client_secret' => 'testClientSecret',
                    ],
                ],
            ]
        );

        $server = new \OAuth2\Server(
            $storage,
            [
                'access_lifetime' => 3600,
            ],
            [
                new \OAuth2\GrantType\ClientCredentials($storage),
            ]
        );

        $json = json_encode(
            [
                'client_id' => 'testClientId',
                'client_secret' => 'testClientSecret',
                'grant_type' => 'client_credentials',
            ]
        );

        \Slim\Environment::mock(
            [
                'REQUEST_METHOD' => 'POST',
                'CONTENT_TYPE' => 'application/json',
                'PATH_INFO' => '/token',
                'CONTENT_LENGTH' => strlen($json),
                'slim.input' => $json,
            ]
        );

        $slim = new \Slim\Slim();
        $slim->post('/token', new Token($slim, $server));

        ob_start();

        $slim->run();

        ob_get_clean();

        $this->assertSame(200, $slim->response->status());

        $actual = json_decode($slim->response->getBody(), true);
        $this->assertSame(
            [
                'access_token' => $actual['access_token'],
                'expires_in' => 3600,
                'token_type' => 'Bearer',
                'scope' => null,
            ],
            $actual
        );
    }

    /**
     * Verify basic behavior of register
     *
     * @test
     * @covers ::register
     *
     * @return void
     */
    public function register()
    {
        $storage = new \OAuth2\Storage\Memory([]);
        $server = new \OAuth2\Server($storage, [], []);

        \Slim\Environment::mock();

        $slim = new \Slim\Slim();

        Token::register($slim, $server);

        $route = $slim->router()->getNamedRoute('token');

        $this->assertInstanceOf('\Slim\Route', $route);
        $this->assertInstanceOf('\Chadicus\Slim\OAuth2\Routes\Token', $route->getCallable());
        $this->assertSame([\Slim\Http\Request::METHOD_POST], $route->getHttpMethods());
    }
}


text:
package integration

import (
	"testing"

	"github.com/golang/glog"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/wait"
	utilwait "k8s.io/apimachinery/pkg/util/wait"
	kinformers "k8s.io/client-go/informers"
	restclient "k8s.io/client-go/rest"
	kctrlmgr "k8s.io/kubernetes/cmd/kube-controller-manager/app"
	cmapp "k8s.io/kubernetes/cmd/kube-controller-manager/app/options"
	kapi "k8s.io/kubernetes/pkg/api"
	kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/controller"

	buildtypedclient "github.com/openshift/origin/pkg/build/generated/internalclientset/typed/build/internalversion"
	"github.com/openshift/origin/pkg/cmd/server/bootstrappolicy"
	"github.com/openshift/origin/pkg/cmd/server/origin"
	origincontrollers "github.com/openshift/origin/pkg/cmd/server/origin/controller"
	"github.com/openshift/origin/pkg/cmd/server/start"
	imagetypedclient "github.com/openshift/origin/pkg/image/generated/internalclientset/typed/image/internalversion"
	"github.com/openshift/origin/test/common/build"
	testutil "github.com/openshift/origin/test/util"
	testserver "github.com/openshift/origin/test/util/server"
)

type controllerCount struct {
	BuildControllers,
	ImageChangeControllers,
	ConfigChangeControllers int
}

// TestConcurrentBuildControllers tests the transition of a build from new to pending. Ensures that only a single New -> Pending
// transition happens and that only a single pod is created during a set period of time.
func TestConcurrentBuildControllers(t *testing.T) {
	// Start a master with multiple BuildControllers
	buildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t)
	defer fn()
	build.RunBuildControllerTest(t, buildClient, kClient)
}

// TestConcurrentBuildControllersPodSync tests the lifecycle of a build pod when running multiple controllers.
func TestConcurrentBuildControllersPodSync(t *testing.T) {
	// Start a master with multiple BuildControllers
	buildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t)
	defer fn()
	build.RunBuildControllerPodSyncTest(t, buildClient, kClient)
}

func TestConcurrentBuildImageChangeTriggerControllers(t *testing.T) {
	// Start a master with multiple ImageChangeTrigger controllers
	buildClient, imageClient, _, fn := setupBuildControllerTest(controllerCount{ImageChangeControllers: 5}, t)
	defer fn()
	build.RunImageChangeTriggerTest(t, buildClient, imageClient)
}

func TestBuildDeleteController(t *testing.T) {
	buildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{}, t)
	defer fn()
	build.RunBuildDeleteTest(t, buildClient, kClient)
}

func TestBuildRunningPodDeleteController(t *testing.T) {
	buildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{}, t)
	defer fn()
	build.RunBuildRunningPodDeleteTest(t, buildClient, kClient)
}

func TestBuildCompletePodDeleteController(t *testing.T) {
	buildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{}, t)
	defer fn()
	build.RunBuildCompletePodDeleteTest(t, buildClient, kClient)
}

func TestConcurrentBuildConfigControllers(t *testing.T) {
	buildClient, _, _, fn := setupBuildControllerTest(controllerCount{ConfigChangeControllers: 5}, t)
	defer fn()
	build.RunBuildConfigChangeControllerTest(t, buildClient)
}

func setupBuildControllerTest(counts controllerCount, t *testing.T) (buildtypedclient.BuildInterface, imagetypedclient.ImageInterface, kclientset.Interface, func()) {
	master, clusterAdminKubeConfig, err := testserver.StartTestMaster()
	if err != nil {
		t.Fatal(err)
	}

	clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
	if err != nil {
		t.Fatal(err)
	}

	clusterAdminKubeClientset, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
	if err != nil {
		t.Fatal(err)
	}
	_, err = clusterAdminKubeClientset.Core().Namespaces().Create(&kapi.Namespace{
		ObjectMeta: metav1.ObjectMeta{Name: testutil.Namespace()},
	})
	if err != nil {
		t.Fatal(err)
	}

	if err := testserver.WaitForServiceAccounts(clusterAdminKubeClientset, testutil.Namespace(), []string{bootstrappolicy.BuilderServiceAccountName, bootstrappolicy.DefaultServiceAccountName}); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	informers, err := start.NewInformers(*master)
	if err != nil {
		t.Fatal(err)
	}

	openshiftConfig, err := origin.BuildMasterConfig(*master, informers)
	if err != nil {
		t.Fatal(err)
	}

	// this test wants to duplicate the controllers, so it needs to duplicate the wiring.
	// TODO have this simply start the particular controller it wants multiple times
	controllerManagerOptions := cmapp.NewCMServer()
	rootClientBuilder := controller.SimpleControllerClientBuilder{
		ClientConfig: &openshiftConfig.PrivilegedLoopbackClientConfig,
	}
	saClientBuilder := controller.SAControllerClientBuilder{
		ClientConfig:         restclient.AnonymousClientConfig(&openshiftConfig.PrivilegedLoopbackClientConfig),
		CoreClient:           openshiftConfig.PrivilegedLoopbackKubernetesClientsetExternal.Core(),
		AuthenticationClient: openshiftConfig.PrivilegedLoopbackKubernetesClientsetExternal.Authentication(),
		Namespace:            "kube-system",
	}
	availableResources, err := kctrlmgr.GetAvailableResources(rootClientBuilder)
	if err != nil {
		t.Fatal(err)
	}

	go func() {
		informers.GetBuildInformers().Start(utilwait.NeverStop)
		informers.GetImageInformers().Start(utilwait.NeverStop)
		informers.GetAppInformers().Start(utilwait.NeverStop)
		informers.GetSecurityInformers().Start(utilwait.NeverStop)
	}()

	controllerContext := kctrlmgr.ControllerContext{
		ClientBuilder: saClientBuilder,
		InformerFactory: genericInformers{
			SharedInformerFactory: informers.GetExternalKubeInformers(),
			generic: []GenericResourceInformer{
				genericInternalResourceInformerFunc(func(resource schema.GroupVersionResource) (kinformers.GenericInformer, error) {
					return informers.GetImageInformers().ForResource(resource)
				}),
				genericInternalResourceInformerFunc(func(resource schema.GroupVersionResource) (kinformers.GenericInformer, error) {
					return informers.GetBuildInformers().ForResource(resource)
				}),
				genericInternalResourceInformerFunc(func(resource schema.GroupVersionResource) (kinformers.GenericInformer, error) {
					return informers.GetAppInformers().ForResource(resource)
				}),
				informers.GetExternalKubeInformers(),
			},
		},
		Options:            *controllerManagerOptions,
		AvailableResources: availableResources,
		Stop:               wait.NeverStop,
	}
	openshiftControllerContext := origincontrollers.ControllerContext{
		ClientBuilder: origincontrollers.OpenshiftControllerClientBuilder{
			ControllerClientBuilder: controller.SAControllerClientBuilder{
				ClientConfig:         restclient.AnonymousClientConfig(&openshiftConfig.PrivilegedLoopbackClientConfig),
				CoreClient:           openshiftConfig.PrivilegedLoopbackKubernetesClientsetExternal.Core(),
				AuthenticationClient: openshiftConfig.PrivilegedLoopbackKubernetesClientsetExternal.Authentication(),
				Namespace:            bootstrappolicy.DefaultOpenShiftInfraNamespace,
			},
		},
		ExternalKubeInformers: informers.GetExternalKubeInformers(),
		InternalKubeInformers: informers.GetInternalKubeInformers(),
		AppInformers:          informers.GetAppInformers(),
		BuildInformers:        informers.GetBuildInformers(),
		ImageInformers:        informers.GetImageInformers(),
		SecurityInformers:     informers.GetSecurityInformers(),
		Stop:                  controllerContext.Stop,
	}

	openshiftControllerConfig, err := origincontrollers.BuildOpenshiftControllerConfig(*master)
	if err != nil {
		t.Fatal(err)
	}
	openshiftControllerInitializers, err := openshiftControllerConfig.GetControllerInitializers()
	if err != nil {
		t.Fatal(err)
	}

	for i := 0; i < counts.BuildControllers; i++ {
		_, err := openshiftControllerInitializers["openshift.io/build"](openshiftControllerContext)
		if err != nil {
			t.Fatal(err)
		}
	}
	for i := 0; i < counts.ImageChangeControllers; i++ {
		_, err := openshiftControllerInitializers["openshift.io/image-trigger"](openshiftControllerContext)
		if err != nil {
			t.Fatal(err)
		}
	}
	for i := 0; i < counts.ConfigChangeControllers; i++ {
		_, err := openshiftControllerInitializers["openshift.io/build-config-change"](openshiftControllerContext)
		if err != nil {
			t.Fatal(err)
		}
	}
	return buildtypedclient.NewForConfigOrDie(clusterAdminClientConfig),
		imagetypedclient.NewForConfigOrDie(clusterAdminClientConfig),
		clusterAdminKubeClientset,
		func() {
			testserver.CleanupMasterEtcd(t, master)
		}
}

type GenericResourceInformer interface {
	ForResource(resource schema.GroupVersionResource) (kinformers.GenericInformer, error)
}

// genericInternalResourceInformerFunc will return an internal informer for any resource matching
// its group resource, instead of the external version. Only valid for use where the type is accessed
// via generic interfaces, such as the garbage collector with ObjectMeta.
type genericInternalResourceInformerFunc func(resource schema.GroupVersionResource) (kinformers.GenericInformer, error)

func (fn genericInternalResourceInformerFunc) ForResource(resource schema.GroupVersionResource) (kinformers.GenericInformer, error) {
	resource.Version = runtime.APIVersionInternal
	return fn(resource)
}

type genericInformers struct {
	kinformers.SharedInformerFactory
	generic []GenericResourceInformer
}

func (i genericInformers) ForResource(resource schema.GroupVersionResource) (kinformers.GenericInformer, error) {
	informer, firstErr := i.SharedInformerFactory.ForResource(resource)
	if firstErr == nil {
		return informer, nil
	}
	for _, generic := range i.generic {
		if informer, err := generic.ForResource(resource); err == nil {
			return informer, nil
		}
	}
	glog.V(4).Infof("Couldn't find informer for %v", resource)
	return nil, firstErr
}


text:
class CodeBlock(object):
    def __init__(self):
        """If the element starts with <pre><code> then it is code block.
        Block is updated with language, callbacks, and indents.
        In the future I hope to split make cells with the correct indent pattern
        """
        if self.is_code:
            lines=self.code.split('\n')
            self.offset = [len(line) - len(line.lstrip()) for line in lines]
    @property
    def callback(self):
        """The callback for the language if it exists"""
        callbacks=self.env.globals['callback']
        if self.language in callbacks:
            return callbacks[self.language]
        return None
    @property
    def language(self):
        """Get language of the current code block"""
        lang = self.env.globals['default_lang']
        if self.query('code').attr('class'):
            lang = [c.lstrip(self.env.globals['lang_prefix']) for c in self.query('code').attr('class').split() if c.startswith(self.env.globals['lang_prefix'])][0]
        return lang

class Block(CodeBlock):
    """
    A stream of non-code elements or a code element.
    """
    def __init__(self, query,env):
        self.env,self.query=[env,query]
    @property
    def code(self):
        if self.is_code:
            return self.query('code').html()
        return self.query.outerHtml()

    @property
    def tag(self):
        return self.query[0].tag
    @property
    def is_code(self):
        return self.tag in ['pre']


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="Description" content="scikit-optimize: machine learning in Python">

  <title>Version 0.3 — scikit-optimize 0.9.0 documentation</title>

  <link rel="canonical" href="https://scikit-optimize.github.io/whats_new/v0.3.html" />

  <link rel="shortcut icon" href="../_static/favicon.ico"/>

  <link rel="stylesheet" href="../_static/css/vendor/bootstrap.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/sg_gallery.css" type="text/css" />
  <link rel="stylesheet" href="../_static/sg_gallery-binder.css" type="text/css" />
  <link rel="stylesheet" href="../_static/sg_gallery-dataframe.css" type="text/css" />
  <link rel="stylesheet" href="../_static/sg_gallery-rendered-html.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

    <button
      id="sk-navbar-toggler"
      class="navbar-toggler"
      type="button"
      data-toggle="collapse"
      data-target="#navbarSupportedContent"
      aria-controls="navbarSupportedContent"
      aria-expanded="false"
      aria-label="Toggle navigation"
    >

    </button>

          Install

          User Guide

          API

          Examples

          Getting Started

          Development

          GitHub

          Other Versions

          More

              Getting Started
              Development
              GitHub
              Other Versions

          <form class="search" action="../search.html" method="get">
            <input class="sk-search-text-input" type="text" name="q" aria-labelledby="searchlabel" />
            <input class="sk-search-text-btn" type="submit" value="Go" />
          </form>

    <input type="checkbox" name="sk-toggle-checkbox" id="sk-toggle-checkbox">
    Toggle Menu

            PrevUp
            Next

          scikit-optimize 0.9.0

            Other versions

Version 0.3

New features

Bug fixes

API Changes

Version 0.3¶

Third time's a charm.

New features¶

Accuracy improvements of the optimization of the acquisition function by pre-selecting good candidates as starting points when using acq_optimizer='lbfgs'.

Support a ask-and-tell interface. Check out the Optimizer class if you need fine grained control over the iterations.

Parallelize L-BFGS minimization runs over the acquisition function.

Implement weighted hamming distance kernel for problems with only categorical dimensions.

New acquisition function gp_hedge that probabilistically chooses one of EI, PI or LCB at every iteration depending upon the cumulative gain.

Bug fixes¶

Warnings are now raised if a point is chosen as the candidate optimum multiple times.

Infinite gradients that were raised in the kernel gradient computation are now fixed.

Integer dimensions are now normalized to [0, 1] internally in gp_minimize.

API Changes¶

The default acq_optimizer function has changed from "auto" to "lbfgs" in gp_minimize.

            © 2017 - 2020, scikit-optimize contributors (BSD License).
          Show this page source


text:
TEST(storage, negatiov_load){
    key_value_storage::storage storage;
    ASSERT_TRUE(storage.load(std::string("3edcc")));
}

TEST(storage, posetiv_load){
    key_value_storage::storage storage;
    ASSERT_FALSE(storage.load(std::string("data_set")));
}

TEST(storage, negatiov_get){
    key_value_storage::storage storage;
    storage.load(std::string("data_set"));
    ASSERT_EQ(storage.get("2wsx"),key_value_storage::service_line_error);
}

TEST(storage, posetiv_get){
    key_value_storage::storage storage;
    storage.load(std::string("data_set"));
    ASSERT_EQ(storage.get("key#6"), std::string("value#7"));
}

int main(int argc, char *argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
package main

import (
	"flag"
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/c4pt0r/cfg"
	"github.com/docopt/docopt-go"

	"github.com/CodisLabs/codis/pkg/utils/errors"
	"github.com/CodisLabs/codis/pkg/utils/log"
	"github.com/CodisLabs/codis/pkg/utils"
)

// global objects
var (
	globalEnv            Env
	livingNode           string
	createdDashboardNode bool
)

type Command struct {
	Run   func(cmd *Command, args []string)
	Usage string
	Short string
	Long  string
	Flag  flag.FlagSet
	Ctx   interface{}
}

var usage = `usage: codis-config  [-c <config_file>] [-L <log_file>] [--log-level=<loglevel>]
		<command> [<args>...]
options:
   -c	set config file
   -L	set output log file, default is stdout
   --log-level=<loglevel>	set log level: info, warn, error, debug [default: info]

commands:
	server
	slot
	dashboard
	action
	proxy
`

func init() {
	log.SetLevel(log.LEVEL_INFO)
}

func setLogLevel(level string) {
	var lv = log.LEVEL_INFO
	switch strings.ToLower(level) {
	case "error":
		lv = log.LEVEL_ERROR
	case "warn", "warning":
		lv = log.LEVEL_WARN
	case "debug":
		lv = log.LEVEL_DEBUG
	case "info":
		fallthrough
	default:
		lv = log.LEVEL_INFO
	}
	log.SetLevel(lv)
	log.Infof("set log level to %s", lv)
}

func runCommand(cmd string, args []string) (err error) {
	argv := make([]string, 1)
	argv[0] = cmd
	argv = append(argv, args...)
	switch cmd {
	case "action":
		return errors.Trace(cmdAction(argv))
	case "dashboard":
		return errors.Trace(cmdDashboard(argv))
	case "server":
		return errors.Trace(cmdServer(argv))
	case "proxy":
		return errors.Trace(cmdProxy(argv))
	case "slot":
		return errors.Trace(cmdSlot(argv))
	}
	return errors.Errorf("%s is not a valid command. See 'codis-config -h'", cmd)
}

func main() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	go func() {
		<-c
		if createdDashboardNode {
			releaseDashboardNode()
		}
		log.Panicf("ctrl-c or SIGTERM found, exit")
	}()

	args, err := docopt.Parse(usage, nil, true, utils.Version, true)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// set output log file
	if s, ok := args["-L"].(string); ok && s != "" {
		f, err := os.OpenFile(s, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
		if err != nil {
			log.PanicErrorf(err, "open log file failed: %s", s)
		} else {
			defer f.Close()
			log.StdLog = log.New(f, "")
		}
	}
	log.SetLevel(log.LEVEL_INFO)
	log.SetFlags(log.Flags() | log.Lshortfile)

	// set log level
	if s, ok := args["--log-level"].(string); ok && s != "" {
		setLogLevel(s)
	}

	// set config file
	var configFile string
	if args["-c"] != nil {
		configFile = args["-c"].(string)
	} else {
		configFile = "config.ini"
	}
	config := cfg.NewCfg(configFile)

	if err := config.Load(); err != nil {
		log.PanicErrorf(err, "load config file error")
	}

	// load global vars
	globalEnv = LoadCodisEnv(config)

	cmd := args["<command>"].(string)
	cmdArgs := args["<args>"].([]string)

	go http.ListenAndServe(":10086", nil)
	err = runCommand(cmd, cmdArgs)
	if err != nil {
		log.PanicErrorf(err, "run sub-command failed")
	}
}


text:
"use strict";

// share logic with maboss callproc


text:
<?php

namespace Games\UserBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/hello/Fabien');

        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
    }
}


text:
<?php

namespace D4D\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Oldusers
 */
class Oldusers
{
    /**
     * @var string
     */
    private $useremail;

    /**
     * Get useremail
     *
     * @return string
     */
    public function getUseremail()
    {
        return $this->useremail;
    }
}


text:
package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"regexp"
	"strconv"
)

const (
	GCRegexp   = `gc\d+\(\d+\): \d+\+\d+\+\d+\+\d+ us, \d+ -> (?P<Heap1>\d+) MB, \d+ \(\d+-\d+\) objects,( \d+ goroutines,)? \d+\/\d+\/\d+ sweeps, \d+\(\d+\) handoff, \d+\(\d+\) steal, \d+\/\d+\/\d+ yields`
	SCVGRegexp = `scvg\d+: inuse: (?P<inuse>\d+), idle: (?P<idle>\d+), sys: (?P<sys>\d+), released: (?P<released>\d+), consumed: (?P<consumed>\d+) \(MB\)`
)

var (
	gcre   = regexp.MustCompile(GCRegexp)
	scvgre = regexp.MustCompile(SCVGRegexp)
)

type Parser struct {
	reader   io.Reader
	gcChan   chan *gctrace
	scvgChan chan *scvgtrace
}

func (p *Parser) Run() {
	sc := bufio.NewScanner(p.reader)

	for sc.Scan() {
		line := sc.Text()

		if result := gcre.FindStringSubmatch(line); result != nil {
			p.gcChan <- parseGCTrace(result)
			continue
		}

		if result := scvgre.FindStringSubmatch(line); result != nil {
			p.scvgChan <- parseSCVGTrace(result)
			continue
		}

		fmt.Println(line)
	}

	if err := sc.Err(); err != nil {
		log.Fatal(err)
	}
}

func parseGCTrace(matches []string) *gctrace {
	matchMap := getMatchMap(gcre, matches)

	return &gctrace{
		Heap1: matchMap["Heap1"],
	}
}

func parseSCVGTrace(matches []string) *scvgtrace {
	matchMap := getMatchMap(scvgre, matches)

	return &scvgtrace{
		inuse:    matchMap["inuse"],
		idle:     matchMap["idle"],
		sys:      matchMap["sys"],
		released: matchMap["released"],
		consumed: matchMap["consumed"],
	}
}

// Transform our matches in a readable hash map.
//
// The resulting hash map will be something like { "Heap1": 123 }
func getMatchMap(re *regexp.Regexp, matches []string) map[string]int64 {
	matchingNames := re.SubexpNames()
	matchMap := map[string]int64{}
	for i, value := range matches {
		intVal, err := strconv.ParseInt(value, 10, 64)
		if err != nil {
			// Happens on first element of range and any matching parenthesis
			// that includes non-parseable string
			//
			// For example a matching array would contain:
			// [ "scvg1: inuse:3 ..." "3" ]
			continue
		}
		matchMap[matchingNames[i]] = intVal
	}
	return matchMap
}


text:
const { getFilter } = require('./util');
const getIntercept = require('./intercept');

module.exports = (options, filter, proxy) => {
  const intercept = getIntercept(options);
  filter = getFilter(options, filter);
  const middleware = async (ctx, next) => {
    let res = intercept(ctx.req, filter);
    if (res !== false) {
      res = await res;
    }
    if (res === false) {
      return await next();
    }
    ctx.status = res.statusCode;
    ctx.set(res.headers);
    if (res.pipe) {
      ctx.body = res;
    }
  };
  Object.assign(middleware, proxy);
  return middleware;
};


text:
#!/usr/bin/env node

// Require some node.js modules
var Path = require('path');
var async = require('async');
var Promise = require('bluebird');
var fsWriteFile = Promise.promisify(require('fs').writeFile);
var measureTime = require('measure-time');
var assert = require('./assert');
var config = require('./config');
var sectors = require('./sectors');
var serviceLocations = require('./service-locations');

var APIClient = require('./APIClient');

assert("Config must specify host property", config.host);

var queue = async.queue(function (language, done) {
    // Create a context for data that needs to be shared between transform
    // functions.
    var context = {};

    var langCode = language.toLowerCase();
    var apiClient = new APIClient(config.protocol, config.host, langCode, config.auth);

    log(langCode, 'starting');

    var timer = measureTime();

    Promise.resolve()
        // First fetch sectors, perform transformation and write to file.
        .then(function () {
            return apiClient.fetchJSON('service-sectors')
                .then(function (data) {
                    assert("Sectors JSON data has 'nodes' property", data.nodes);
                    return sectors.transformSectors(data.nodes);
                })
                .then(addToContext('sectors'))
                .then(prettyStringify)
                .then(writeFile('sectors_' + langCode.toUpperCase() + '.json'));
        })
        // First fetch regions, perform transformation and write to file.
        .then(function () {
            return apiClient.fetchAll('api/service_region')
                .then(function (data) {
                    return sectors.transformSectors(data);
                })
                .then(addToContext('regions'))
                .then(prettyStringify)
                .then(writeFile('regions_' + langCode.toUpperCase() + '.json'));
        })
        // Next fetch service partners, save to context.
        .then(function () {
            return apiClient.fetchAll('api/service_partner')
                .then(indexByProperty('id'))
                .then(addToContext('servicePartners'));
                // .then(prettyStringify)
                // .then(writeFile('partners-' + langCode + '.json'));
        })
        // Then fetch service locations, perform transformations (including
        // embedding service partners) and then save to file.
        .then(function () {
            return apiClient.fetchAll('api/service_location')
                .then(addToContext('serviceLocations'))
                .then(function (data) {
                    return serviceLocations.transform(data, context);
                })
                .then(prettyStringify)
                .then(writeFile('services_' + langCode.toUpperCase() + '.json'))
                .then(function () {
                    var elapsed = timer();
                    var numSeconds = (elapsed.millisecondsTotal / 1000);
                    log('\t', "Complete; '"+ langCode +"' services imported in " + numSeconds + " seconds");
                })
        })
        // Finally fetch loacale strings and save to file.
        .then(function () {
            return apiClient.fetchJSON('service-strings')
                .then(addToContext('locale'))
                .then(prettyStringify)
                .then(writeFile('locale-' + langCode.toUpperCase() + '.json'));
        })
        .then(function () {
            // Notify queue tasks complete for language.
            done();
        })
        .catch(function (error) {
            // Notify queue of any errors.
            done(error);
        });

    /**
     * Helper function for managing "global" context state.
     */
    function addToContext(name) {
        return function (data) {
            assert("Context '"+ name +"' cannot be defined", context[name] === undefined);
            context[name] = data;
            return data;
        };
    }
});

queue.error = function (error, langCode) {
    console.error("There was an error fetching Service Locations: '" + error + "' during language: " + langCode);
};

config.languages.forEach(function (language) {
    log(language, "Adding to Service Location fetch queue.");
    queue.push(language);
});

function log(ref, message) {
    console.log("[" + ref + "] " + message);
}

function prettyStringify(value) {
    return JSON.stringify(value, null, '  ');
}

function writeFile(filename) {
    return function (data) {
        var filepath = Path.resolve(__dirname, config.dest, filename);
        log('\t', "writing: " + filepath);
        return fsWriteFile(filepath, data);
    };
}

function indexByProperty(prop) {
    return function (items) {
        return items.reduce(
            function (index, item) {
                assert('Item must have ' + prop + ' property', item[prop]);
                var key = item[prop];
                index[key] = item;
                return index;
            },
            {}
        );
    };
}


text:
package org.kuali.rice.krad.datadictionary.impl;

import org.apache.commons.beanutils.BeanUtils;
import org.kuali.rice.krad.datadictionary.FieldOverride;

import java.lang.reflect.InvocationTargetException;

/**
 * A Field Override used to replace value elements from a Data Dictionary bean.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class FieldOverrideForValueReplaceImpl implements FieldOverride {

    private String propertyName;
    private Object value;

    public String getPropertyName() {
        return propertyName;
    }

    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public Object performFieldOverride(Object bean, Object property) {
        try {
            BeanUtils.setProperty(bean, this.getPropertyName(), this.getValue());
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return getValue();
    }
}


text:
create class test_class (bigint_col bigint);

insert into test_class(bigint_col) values (-9223372036854775808);
insert into test_class(bigint_col) values (9223372036854775807);
insert into test_class(bigint_col) values (100);
insert into test_class(bigint_col) values (-100);
insert into test_class(bigint_col) values (0);

create index idx_bigint_col on test_class(bigint_col);

select * from test_class order by 1 desc;

drop class test_class;


text:
package com.xinyuan.pub.model.security.po.query;

import com.xinyuan.pub.model.po.BasePaginationQuery;

/**
 * @Description: 查询角色信息 Query类
 * @author liangyongjian
 * @Version V1.0
 * @date 2017-09-24 下午09:03:20
 */
public class RolesQuery extends BasePaginationQuery {

	private Long id;// 用户ID
	private String roleName;// 角色名称

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

}


text:
<?php
namespace Seeker\Adapter;

use Seeker\Adapter\Query\DatabaseQuery;

/**
 * Interface for database adapters
 */
interface DatabaseAdapterInterface
{
    /**
     * Returns the database connection instance
     *
     * @param array $dbConfig
     * @return mixed
     */
    public static function getConnectionInstance($dbConfig);

    /**
     * Executes a database query and returns the result set
     *
     * @param DatabaseQuery $query
     * @return mixed
     */
    public function query(DatabaseQuery $query);
}


text:
package com.outerspacecat.memcache;

import com.outerspacecat.connection.DataSource;
import javax.annotation.concurrent.ThreadSafe;

/**
 * Provides lookup of Memcache nodes by key.
 *
 * @author Caleb Richardson
 */
@ThreadSafe
public interface Continuum
{
  /**
   * Returns the node for {@code key}.
   *
   * @param key the Memcache key. Must be non {@code null}.
   * @return the node for {@code key}. Never {@code null}.
   */
  DataSource<MemcacheConnection> getNode ( String key );
}