text:
//书籍渲染库

var _ = require('underscore');
var shell = require('./shell');
var fse = require('co-fs-extra');
var fs = require('co-fs');
var marked = require('marked');
var Gitbook = require('gitbook').Book;
var moment = require('moment');
//生成封面
var cover = require('./cover/index');

//默认配置
var defaultConfig = {
  src: 'book-md/',
  dest: 'book-html/',
  themes: {
    apebook: './theme/apebook',
    blog: './theme/blog'
  },
  //默认启用的插件
  "plugins": []
};

var Book = module.exports = function(config) {
  var self = this;
  config = _.extend(defaultConfig, config);
  if (config) {
    _.each(config, function(value, key) {
      self[key] = value;
    });
  }
};

Book.prototype = {
  //渲染md成html
  render: function *(config) {
    var self = this;
    var ctx = self.ctx;
    var user = this.user;
    var book = this.book;
    var src = self.bookPath();
    var hasSrc = yield fs.exists(src);
    if (!hasSrc) {
      return {'success': false, 'msg': '不存在 ' + book + ' 目录'};
    }
    //确定绑定的仓库是否符合gitbook规范
    var isBook = yield this.isBook();
    if (!isBook) {
      return {'success': false, 'msg': '仓库缺少 SUMMARY.md 或者 README.md'};
    }
    yield fse.ensureDir(self.dest + user);
    var path = self.dest + user + '/' + book;
    yield fse.ensureDir(path);
    //图书配置
    var bookJson = {};
    bookJson.theme = config && config.theme || self.themes['apebook'];
    bookJson.output = path;
    var data = this.data;
    bookJson.githubUser = data.githubUser;
    bookJson.githubRepo = data.githubRepo;
    bookJson.bookId = data.id;
    bookJson.bookName = book;
    bookJson.apebookHost = this.apebookHost;
    bookJson.assetHost = this.assetHost;
    bookJson.desc = data.desc;

    //github star 列表地址
    var githubUrl = 'https://github.com/'+data.githubUser+'/'+data.githubRepo;
    if (data.githubUrl) {
      githubUrl = data.githubUrl.split('.git')[0];
      var nameRepo = githubUrl.split('github.com/')[1];
      bookJson.githubUser = nameRepo.split('/')[0];
      bookJson.githubRepo = nameRepo.split('/')[1];
    }
    bookJson.starList = githubUrl + '/stargazers';

    //本地调试环境
    if (process.env.NODE_ENV !== 'local') {
      bookJson.localAssetHost = bookJson.assetHost;
    }

    bookJson.plugins = this.plugins;
    yield fse.writeFile(src + '/book.json', JSON.stringify(bookJson));
    ctx.log(bookJson);
    ctx.log('src ' + src);
    ctx.log('dest ' + path);
    var gitbook = new Gitbook(src, {
      'config': {
        'output': path
      }
    });
    var output = yield this.generate(gitbook);
    ctx.log(output);
    yield shell.exec('cd ' + src + ' && ' + 'git reset --hard');
    //删除生成的无用的gitbook目录
    yield shell.exec('cd ' + path + ' && ' + 'rm -rf -r gitbook');
    if (output === true) {
      ctx.log('build ok!');
      return {'success': true};
    } else {
      ctx.error(output);
      return {'success': false, 'error': output};
    }
  },
  generate: function(gitbook) {
    return new Promise(function(resolve) {
      gitbook.parse().then(function() {
        return gitbook.generate('website');
      }).then(function() {
        resolve(true);
      }).catch(function(err) {
        resolve(err);
      });
    });
  },
  //将文件push到oss存储
  pushOss: function*() {
    var user = this.user;
    var book = this.book;
    var oss = this.oss;
    var bucket = this.bucket;
    var path = this.dest + user + '/' + book;
    return yield oss.dir(path, './' + user + '/' + book, bucket);
  },
  //拉取代码
  pull: function *() {
    var self = this;
    var user = this.user;
    var output;
    //不存在目录用户,先予以创建
    yield fse.ensureDir(this.src + user);
    //不存在仓库目录,先予以创建,并clone 代码
    var src = self.bookPath();
    var isExist = yield fse.exists(src);
    yield fse.ensureDir(src);
    if (!isExist) {
      //克隆仓库
      output = yield this.clone(this.githubUrl, src);
    } else {
      output = yield shell.exec('cd ' + src + ' && git pull origin master');
    }

    //已经是最新
    if (/Already up-to-date/.test(output)) {
      return {'success': true, 'change': false, 'msg': '不存在变更的内容', output: output};
    } else {
      return {'success': true, 'change': true, output: output};
    }
  },
  //克隆仓库
  clone: function *(githubUrl, src) {
    var result = yield shell.exec('cd ' + src + ' && git init && git remote add origin ' + githubUrl);
    console.log(result);
    var output = yield shell.exec('cd ' + src + ' && git pull origin master');
    console.log(output);
    return output;
  },
  //github仓库是否符合book规范
  isBook: function *() {
    var self = this;
    var src = self.bookPath();
    var hasReadme = yield fs.exists(src + '/README.md');
    var hasSummary = yield fs.exists(src + '/SUMMARY.md');
    return hasReadme && hasSummary;
  },
  bookPath: function() {
    var user = this.user;
    var book = this.book;
    var path = user + '/' + book;
    return this.src + path;
  },
  //书籍介绍
  readMe: function*() {
    var src = this.bookPath();
    var url = src + '/' + 'README.md';
    return yield this.renderMd(url);
  },
  //书籍章节
  summary: function*(format) {
    var src = this.bookPath();
    var url = src + '/' + 'SUMMARY.md';
    if (format && format === 'json') {
      return yield Summary.json(url);
    } else {
      return yield this.renderMd(url);
    }
  },
  /**
   * 图书更新的章节内容
   * @param updateLog
   * @param oldSummary
   */
  updateChapters: function*(updateLog, oldSummary) {
    //var newSummary = yield this.summary('json');
    //yield Summary.updateData(updateLog,newSummary,oldSummary);
  },
  //章节数
  chapterCount: function*() {
    var src = this.bookPath();
    var url = src + '/' + 'SUMMARY.md';
    var exist = yield fs.exists(url);
    if (!exist) return 0;
    var content = yield fs.readFile(url);
    content = content.toString();
    return content.split('*').length - 1;
  },
  //渲染md文件成html
  renderMd: function*(url) {
    if (!url) return '';
    var exist = yield fs.exists(url);
    if (!exist) return '';
    var data = yield fs.readFile(url);
    data = data.toString();
    var tokens = marked.lexer(data);
    return marked.parser(tokens);
  },
  /**
   * 封面
   *
   */
  cover: function*(coverinfo, bookData, userData) {
    var data = bookData;
    var user = data.userName;
    var book = data.uri;
    var output = this.dest + user + '/' + book + '/cover.jpg';
    var author = bookData.author;
    if (!author) {
      author = userData.nick || userData.name;
    }
    var config = {
      title: data.name,
      author: author,
      bg: {},
      "size": {
        "w": 400,
        "h": 540
      }
    };

    //更新时间
    //不存在,使用创建时间
    if (data.updateTime) {
      config.update = moment(Number(data.updateTime)).format('YYYY-MM-DD') + ' update';
    } else {
      config.update = moment(Number(data.create)).format('YYYY-MM-DD') + ' create';
    }

    if (coverinfo) {
      //背景颜色
      if (coverinfo.color) {
        config.bg.color = coverinfo.color;
      }

    } else {

      var bgColors = ['#7c8577', '#999d9c', '#9d9087', '#74787c', '#4f5555',
        '#6c4c49', '#563624', '#3e4145', '#3c3645', '#281f1d', '#2f271d',
        '#1b315e', '#596032', '#ad8b3d'];

      var colorIndex = (parseInt(Math.random() * (14 - 1) + 1)) - 1;
      config.bg.color = bgColors[colorIndex];
    }

    //是否存在封面背景图片
    var coverBg = this.src + user + '/' + book + '/' + 'cover-bg.jpg';
    var existCoverBg = yield fse.exists(coverBg);
    if (existCoverBg) {
      config.bg.image = coverBg;
    }
    try {
      yield cover.render(output, config);
    } catch (e) {
      console.log(e);
      return false;
    }

    var path = user + '/' + book + '/cover.jpg';

    //返回封面数据
    return {
      ossPath: path,
      color: config.bg.color
    };
  }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<migration name="Add fiscal positions">
  <nomenclature-creation nomenclature="fiscal_positions"/>
  <property-creation property="fiscal_positions.country" type="item" choices="countries"/>
  <property-creation property="fiscal_positions.code" type="string"/>
  <item-creation item="fiscal_positions#fr_ba_ir" country="fr" code="BA-IR"/>
  <item-creation item="fiscal_positions#fr_ba_is" country="fr" code="BA-IS"/>
  <item-creation item="fiscal_positions#fr_bic_ir" country="fr" code="BIC-IR"/>
  <item-creation item="fiscal_positions#fr_bic_is" country="fr" code="BIC-IS"/>
  <item-creation item="fiscal_positions#fr_bnc_ir" country="fr" code="BNC-IR"/>
  <item-creation item="fiscal_positions#fr_bnc_is" country="fr" code="BNC-IS"/>
</migration>

redpajama_set_name: RedPajamaGithub


text:
@class NSColor;

@interface DVTVerticalMarkerGraphLayer : DVTAbstractGraphLayer
{
    BOOL _shouldDraw;
    double _xPosition;
    NSColor *_markerColor;
}

- (void).cxx_destruct;
@property BOOL shouldDraw; // @synthesize shouldDraw=_shouldDraw;
@property(retain) NSColor *markerColor; // @synthesize markerColor=_markerColor;
@property double xPosition; // @synthesize xPosition=_xPosition;
- (struct CGRect)_markerRectForVisibleGraphBounds:(struct _DVTGraphBounds)arg1;
- (void)drawLayerWithVisibleBounds:(struct _DVTGraphBounds)arg1;
- (id)initWithGraph:(id)arg1;

@end


text:
import copier
from copy_state_db import CopyStateDB
import multiprocessing
import oplog_applier
import os
import os.path
from pymongo.read_preferences import ReadPreference
import string
import sys
import utils

log = utils.get_logger(__name__)

PARENT_PROCESS_NAME = 'parent process'

#
# child processes
#

def die(msg):
    log.error(msg)
    sys.exit(1)

def ensure_empty_dest(dest):
    client = utils.mongo_connect(dest['host'], dest['port'],
                                 ensure_direct=True,
                                 max_pool_size=1,
                                 read_preference=ReadPreference.PRIMARY)
    collection = client[dest['db']][dest['collection']]
    if collection.count() > 0:
        die("destination must be empty!")

def copy_collection_parent(sources, dest, state_db, args):
    """
    drive the collection copying process by delegating work to a pool of worker processes
    """

    # ensure state db has rows for each source/dest pair
    for source in sources:
        state_db.add_source_and_dest(source, dest)

    # space-pad all process names so that tabular output formats line up
    process_names = {repr(source): "%s:%d" % (source['host'], source['port'])
                     for source in sources}
    process_names['parent'] = PARENT_PROCESS_NAME
    max_process_name_len = max(len(name) for name in process_names.itervalues())
    for key in process_names:
        process_names[key] = string.ljust(process_names[key], max_process_name_len)

    multiprocessing.current_process().name = process_names['parent']

    # -----------------------------------------------------------------------
    # perform initial copy, if it hasn't been done yet
    # -----------------------------------------------------------------------
    in_initial_copy = len(state_db.select_by_state(CopyStateDB.STATE_INITIAL_COPY))
    if in_initial_copy and in_initial_copy < len(sources):
        die("prior attempt at initial copy failed; rerun with --restart")
    if in_initial_copy > 0:
        ensure_empty_dest(dest)

        # each worker process copies one shard
        processes = []
        for source in sources:
            name = process_names[repr(source)]
            process = multiprocessing.Process(target=copier.copy_collection,
                                              name=name,
                                              kwargs=dict(source=source,
                                                          dest=dest,
                                                          state_path=state_db._path,
                                                          percent=args.percent))
            process.start()
            processes.append(process)

        # wait for all workers to finish
        utils.wait_for_processes(processes)

    # -----------------------------------------------------------------------
    # build indices on main process, since that only needs to be done once
    # -----------------------------------------------------------------------
    waiting_for_indices = len(state_db.select_by_state(CopyStateDB.STATE_WAITING_FOR_INDICES))
    if waiting_for_indices and waiting_for_indices < len(sources):
        die("not all initial copies have been completed; rerun with --restart")
    if waiting_for_indices > 0:
        log.info("building indices")
        copier.copy_indexes(sources[0], dest)
        for source in sources:
            state_db.update_state(source, dest, CopyStateDB.STATE_APPLYING_OPLOG)

    # -----------------------------------------------------------------------
    # apply oplogs
    # -----------------------------------------------------------------------
    applying_oplog = state_db.select_by_state(CopyStateDB.STATE_APPLYING_OPLOG)
    if len(applying_oplog) < len(sources):
        die("this shouldn't happen!")

    log.info("starting oplog apply")

    # create worker thread that prints headers for oplog stats on a regular basis;
    # we do this to prevent the visual clutter caused by multiple processes doing this
    #
    # we avoid using gevent in the parent process to avoid weirdness I've seen with fork()ed
    # gevent loops
    header_delay = max(float(20) / len(sources),10)
    stats_name = string.ljust("stats", max_process_name_len)
    stats_proc = multiprocessing.Process(target=oplog_applier.print_header_worker,
                                         args=(header_delay,),
                                         name=stats_name)
    stats_proc.start()

    # need to isolate calls to gevent here, to avoid forking with monkey-patched modules
    # (which seems to create funkiness)
    processes = []
    for source in sources:
        name = process_names[repr(source)]
        process = multiprocessing.Process(target=oplog_applier.apply_oplog,
                                          name=name,
                                          kwargs=dict(source=source,
                                                      dest=dest,
                                                      percent=args.percent,
                                                      state_path=state_db._path))
        process.start()
        processes.append(process)

    # this should *never* finish
    processes.append(stats_proc)
    utils.wait_for_processes(processes)

if __name__ == '__main__':
    # NOTE: we are not gevent monkey-patched here; only child processes are monkey-patched,
    #       so all ops below are synchronous

    # parse command-line options
    import argparse
    parser = argparse.ArgumentParser(description='Copies a collection from one mongod to another.')
    parser.add_argument(
        '--source', type=str, required=True, metavar='URL',
        help='source to read from; can be a file containing sources or a url like: host[:port]/db/collection; '
             'e.g. localhost:27017/prod_maestro.emails')
    parser.add_argument(
        '--dest', type=str, required=True, metavar='URL',
        help='source to read from; see --source for format')
    parser.add_argument(
        '--percent', type=int, metavar='PCT', default=None,
        help='copy only PCT%% of data')
    parser.add_argument(
        '--restart', action='store_true',
        help='restart from the beginning, ignoring any prior progress')
    parser.add_argument(
        '--state-db', type=str, metavar='PATH', default=None,
        help='path to state file (defaults to ./<source_database>.<source_collection>.db)')
    args = parser.parse_args()

    # parse source and destination
    dest = utils.parse_mongo_url(args.dest)
    if os.path.exists(args.source):
        sources = utils.parse_source_file(args.source)
    else:
        sources = [utils.parse_mongo_url(args.source)]

    # initialize sqlite database that holds our state (this may seem like overkill,
    # but it's actually needed to ensure proper synchronization of subprocesses)
    if not args.state_db:
        args.state_db = '%s.%s.db' % (sources[0]['db'], sources[0]['collection'])

    if args.state_db.startswith('/'):
        state_db_path = args.state_db
    else:
        state_db_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                                     args.state_db)

    log.info('using state db %s' % state_db_path)
    state_db_exists = os.path.exists(state_db_path)
    state_db = CopyStateDB(state_db_path)
    if not state_db_exists:
        state_db.drop_and_create()

    if args.restart:
        state_db.drop_and_create()

    # do the real work
    copy_collection_parent(sources, dest, state_db, args)

    log.error("shouldn't reach this point")
    sys.exit(1)


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.execution.resourceGroups;

import com.facebook.presto.execution.MockQueryExecution;
import com.facebook.presto.execution.resourceGroups.InternalResourceGroup.RootInternalResourceGroup;
import com.facebook.presto.spi.resourceGroups.ResourceGroupInfo;
import com.google.common.collect.ImmutableSet;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import org.apache.commons.math3.distribution.BinomialDistribution;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.facebook.presto.execution.QueryState.FAILED;
import static com.facebook.presto.execution.QueryState.QUEUED;
import static com.facebook.presto.execution.QueryState.RUNNING;
import static com.facebook.presto.spi.resourceGroups.SchedulingPolicy.QUERY_PRIORITY;
import static com.facebook.presto.spi.resourceGroups.SchedulingPolicy.WEIGHTED;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static io.airlift.testing.Assertions.assertGreaterThan;
import static io.airlift.testing.Assertions.assertLessThan;
import static io.airlift.units.DataSize.Unit.BYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.util.Collections.reverse;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.Assert.assertEquals;

public class TestResourceGroups
{
    @Test(timeOut = 10_000)
    public void testQueueFull()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        root.setMaxQueuedQueries(1);
        root.setMaxRunningQueries(1);
        MockQueryExecution query1 = new MockQueryExecution(0);
        root.run(query1);
        assertEquals(query1.getState(), RUNNING);
        MockQueryExecution query2 = new MockQueryExecution(0);
        root.run(query2);
        assertEquals(query2.getState(), QUEUED);
        MockQueryExecution query3 = new MockQueryExecution(0);
        root.run(query3);
        assertEquals(query3.getState(), FAILED);
        assertEquals(query3.getFailureCause().getMessage(), "Too many queued queries for \"root\"");
    }

    @Test(timeOut = 10_000)
    public void testFairEligibility()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        root.setMaxQueuedQueries(4);
        root.setMaxRunningQueries(1);
        InternalResourceGroup group1 = root.getOrCreateSubGroup("1");
        group1.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group1.setMaxQueuedQueries(4);
        group1.setMaxRunningQueries(1);
        InternalResourceGroup group2 = root.getOrCreateSubGroup("2");
        group2.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group2.setMaxQueuedQueries(4);
        group2.setMaxRunningQueries(1);
        InternalResourceGroup group3 = root.getOrCreateSubGroup("3");
        group3.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group3.setMaxQueuedQueries(4);
        group3.setMaxRunningQueries(1);
        MockQueryExecution query1a = new MockQueryExecution(0);
        group1.run(query1a);
        assertEquals(query1a.getState(), RUNNING);
        MockQueryExecution query1b = new MockQueryExecution(0);
        group1.run(query1b);
        assertEquals(query1b.getState(), QUEUED);
        MockQueryExecution query2a = new MockQueryExecution(0);
        group2.run(query2a);
        assertEquals(query2a.getState(), QUEUED);
        MockQueryExecution query2b = new MockQueryExecution(0);
        group2.run(query2b);
        assertEquals(query2b.getState(), QUEUED);
        MockQueryExecution query3a = new MockQueryExecution(0);
        group3.run(query3a);
        assertEquals(query3a.getState(), QUEUED);

        query1a.complete();
        root.processQueuedQueries();
        // 2a and not 1b should have started, as group1 was not eligible to start a second query
        assertEquals(query1b.getState(), QUEUED);
        assertEquals(query2a.getState(), RUNNING);
        assertEquals(query2b.getState(), QUEUED);
        assertEquals(query3a.getState(), QUEUED);

        query2a.complete();
        root.processQueuedQueries();
        assertEquals(query3a.getState(), RUNNING);
        assertEquals(query2b.getState(), QUEUED);
        assertEquals(query1b.getState(), QUEUED);

        query3a.complete();
        root.processQueuedQueries();
        assertEquals(query1b.getState(), RUNNING);
        assertEquals(query2b.getState(), QUEUED);
    }

    @Test(timeOut = 10_000)
    public void testFairQueuing()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        root.setMaxQueuedQueries(4);
        root.setMaxRunningQueries(1);
        InternalResourceGroup group1 = root.getOrCreateSubGroup("1");
        group1.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group1.setMaxQueuedQueries(4);
        group1.setMaxRunningQueries(2);
        InternalResourceGroup group2 = root.getOrCreateSubGroup("2");
        group2.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group2.setMaxQueuedQueries(4);
        group2.setMaxRunningQueries(2);
        MockQueryExecution query1a = new MockQueryExecution(0);
        group1.run(query1a);
        assertEquals(query1a.getState(), RUNNING);
        MockQueryExecution query1b = new MockQueryExecution(0);
        group1.run(query1b);
        assertEquals(query1b.getState(), QUEUED);
        MockQueryExecution query1c = new MockQueryExecution(0);
        group1.run(query1c);
        assertEquals(query1c.getState(), QUEUED);
        MockQueryExecution query2a = new MockQueryExecution(0);
        group2.run(query2a);
        assertEquals(query2a.getState(), QUEUED);

        query1a.complete();
        root.processQueuedQueries();
        // 1b and not 2a should have started, as it became queued first and group1 was eligible to run more
        assertEquals(query1b.getState(), RUNNING);
        assertEquals(query1c.getState(), QUEUED);
        assertEquals(query2a.getState(), QUEUED);

        // 2a and not 1c should have started, as all eligible sub groups get fair sharing
        query1b.complete();
        root.processQueuedQueries();
        assertEquals(query2a.getState(), RUNNING);
        assertEquals(query1c.getState(), QUEUED);
    }

    @Test(timeOut = 10_000)
    public void testMemoryLimit()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, BYTE));
        root.setMaxQueuedQueries(4);
        root.setMaxRunningQueries(3);
        MockQueryExecution query1 = new MockQueryExecution(1);
        root.run(query1);
        // Process the group to refresh stats
        root.processQueuedQueries();
        assertEquals(query1.getState(), RUNNING);
        MockQueryExecution query2 = new MockQueryExecution(0);
        root.run(query2);
        assertEquals(query2.getState(), QUEUED);
        MockQueryExecution query3 = new MockQueryExecution(0);
        root.run(query3);
        assertEquals(query3.getState(), QUEUED);

        query1.complete();
        root.processQueuedQueries();
        assertEquals(query2.getState(), RUNNING);
        assertEquals(query3.getState(), RUNNING);
    }

    @Test
    public void testSubgroupMemoryLimit()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(10, BYTE));
        root.setMaxQueuedQueries(4);
        root.setMaxRunningQueries(3);
        InternalResourceGroup subgroup = root.getOrCreateSubGroup("subgroup");
        subgroup.setSoftMemoryLimit(new DataSize(1, BYTE));
        subgroup.setMaxQueuedQueries(4);
        subgroup.setMaxRunningQueries(3);

        MockQueryExecution query1 = new MockQueryExecution(1);
        subgroup.run(query1);
        // Process the group to refresh stats
        root.processQueuedQueries();
        assertEquals(query1.getState(), RUNNING);
        MockQueryExecution query2 = new MockQueryExecution(0);
        subgroup.run(query2);
        assertEquals(query2.getState(), QUEUED);
        MockQueryExecution query3 = new MockQueryExecution(0);
        subgroup.run(query3);
        assertEquals(query3.getState(), QUEUED);

        query1.complete();
        root.processQueuedQueries();
        assertEquals(query2.getState(), RUNNING);
        assertEquals(query3.getState(), RUNNING);
    }

    @Test(timeOut = 10_000)
    public void testSoftCpuLimit()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, BYTE));
        root.setSoftCpuLimit(new Duration(1, SECONDS));
        root.setHardCpuLimit(new Duration(2, SECONDS));
        root.setCpuQuotaGenerationMillisPerSecond(2000);
        root.setMaxQueuedQueries(1);
        root.setMaxRunningQueries(2);

        MockQueryExecution query1 = new MockQueryExecution(1, "query_id", 1, new Duration(1, SECONDS));
        root.run(query1);
        assertEquals(query1.getState(), RUNNING);

        MockQueryExecution query2 = new MockQueryExecution(0);
        root.run(query2);
        assertEquals(query2.getState(), RUNNING);

        MockQueryExecution query3 = new MockQueryExecution(0);
        root.run(query3);
        assertEquals(query3.getState(), QUEUED);

        query1.complete();
        root.processQueuedQueries();
        assertEquals(query2.getState(), RUNNING);
        assertEquals(query3.getState(), QUEUED);

        root.generateCpuQuota(2);
        root.processQueuedQueries();
        assertEquals(query2.getState(), RUNNING);
        assertEquals(query3.getState(), RUNNING);
    }

    @Test(timeOut = 10_000)
    public void testHardCpuLimit()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, BYTE));
        root.setHardCpuLimit(new Duration(1, SECONDS));
        root.setCpuQuotaGenerationMillisPerSecond(2000);
        root.setMaxQueuedQueries(1);
        root.setMaxRunningQueries(1);
        MockQueryExecution query1 = new MockQueryExecution(1, "query_id", 1, new Duration(2, SECONDS));
        root.run(query1);
        assertEquals(query1.getState(), RUNNING);
        MockQueryExecution query2 = new MockQueryExecution(0);
        root.run(query2);
        assertEquals(query2.getState(), QUEUED);

        query1.complete();
        root.processQueuedQueries();
        assertEquals(query2.getState(), QUEUED);

        root.generateCpuQuota(2);
        root.processQueuedQueries();
        assertEquals(query2.getState(), RUNNING);
    }

    @Test(timeOut = 10_000)
    public void testPriorityScheduling()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        root.setMaxQueuedQueries(100);
        // Start with zero capacity, so that nothing starts running until we've added all the queries
        root.setMaxRunningQueries(0);
        root.setSchedulingPolicy(QUERY_PRIORITY);
        InternalResourceGroup group1 = root.getOrCreateSubGroup("1");
        group1.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group1.setMaxQueuedQueries(100);
        group1.setMaxRunningQueries(1);
        InternalResourceGroup group2 = root.getOrCreateSubGroup("2");
        group2.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group2.setMaxQueuedQueries(100);
        group2.setMaxRunningQueries(1);

        SortedMap<Integer, MockQueryExecution> queries = new TreeMap<>();

        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            int priority;
            do {
                priority = random.nextInt(1_000_000) + 1;
            } while (queries.containsKey(priority));

            MockQueryExecution query = new MockQueryExecution(0, "query_id", priority);
            if (random.nextBoolean()) {
                group1.run(query);
            }
            else {
                group2.run(query);
            }
            queries.put(priority, query);
        }

        root.setMaxRunningQueries(1);

        List<MockQueryExecution> orderedQueries = new ArrayList<>(queries.values());
        reverse(orderedQueries);

        for (MockQueryExecution query : orderedQueries) {
            root.processQueuedQueries();
            assertEquals(query.getState(), RUNNING);
            query.complete();
        }
    }

    @Test(timeOut = 10_000)
    public void testWeightedScheduling()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        root.setMaxQueuedQueries(4);
        // Start with zero capacity, so that nothing starts running until we've added all the queries
        root.setMaxRunningQueries(0);
        root.setSchedulingPolicy(WEIGHTED);
        InternalResourceGroup group1 = root.getOrCreateSubGroup("1");
        group1.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group1.setMaxQueuedQueries(2);
        group1.setMaxRunningQueries(2);
        InternalResourceGroup group2 = root.getOrCreateSubGroup("2");
        group2.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        group2.setMaxQueuedQueries(2);
        group2.setMaxRunningQueries(2);
        group2.setSchedulingWeight(2);

        Set<MockQueryExecution> group1Queries = fillGroupTo(group1, ImmutableSet.of(), 2);
        Set<MockQueryExecution> group2Queries = fillGroupTo(group2, ImmutableSet.of(), 2);
        root.setMaxRunningQueries(1);

        int group2Ran = 0;
        for (int i = 0; i < 1000; i++) {
            for (Iterator<MockQueryExecution> iterator = group1Queries.iterator(); iterator.hasNext(); ) {
                MockQueryExecution query = iterator.next();
                if (query.getState() == RUNNING) {
                    query.complete();
                    iterator.remove();
                }
            }
            for (Iterator<MockQueryExecution> iterator = group2Queries.iterator(); iterator.hasNext(); ) {
                MockQueryExecution query = iterator.next();
                if (query.getState() == RUNNING) {
                    query.complete();
                    iterator.remove();
                    group2Ran++;
                }
            }
            root.processQueuedQueries();
            group1Queries = fillGroupTo(group1, group1Queries, 2);
            group2Queries = fillGroupTo(group2, group2Queries, 2);
        }

        // group1 has a weight of 1 and group2 has a weight of 2, so group2 should account for (2 / (1 + 2)) of the queries.
        // since this is stochastic, we check that the result of 1000 trials are 2/3 with 99.9999% confidence
        BinomialDistribution binomial = new BinomialDistribution(1000, 2.0 / 3.0);
        int lowerBound = binomial.inverseCumulativeProbability(0.000001);
        int upperBound = binomial.inverseCumulativeProbability(0.999999);
        assertLessThan(group2Ran, upperBound);
        assertGreaterThan(group2Ran, lowerBound);
    }

    @Test
    public void testGetInfo()
    {
        RootInternalResourceGroup root = new RootInternalResourceGroup("root", (group, export) -> { }, directExecutor());
        root.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        root.setMaxQueuedQueries(40);
        // Start with zero capacity, so that nothing starts running until we've added all the queries
        root.setMaxRunningQueries(0);
        root.setSchedulingPolicy(WEIGHTED);

        InternalResourceGroup rootA = root.getOrCreateSubGroup("a");
        rootA.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        rootA.setMaxQueuedQueries(20);
        rootA.setMaxRunningQueries(2);

        InternalResourceGroup rootB = root.getOrCreateSubGroup("b");
        rootB.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        rootB.setMaxQueuedQueries(20);
        rootB.setMaxRunningQueries(2);
        rootB.setSchedulingWeight(2);
        rootB.setSchedulingPolicy(QUERY_PRIORITY);

        InternalResourceGroup rootAX = rootA.getOrCreateSubGroup("x");
        rootAX.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        rootAX.setMaxQueuedQueries(10);
        rootAX.setMaxRunningQueries(10);

        InternalResourceGroup rootAY = rootA.getOrCreateSubGroup("y");
        rootAY.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        rootAY.setMaxQueuedQueries(10);
        rootAY.setMaxRunningQueries(10);

        InternalResourceGroup rootBX = rootB.getOrCreateSubGroup("x");
        rootBX.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        rootBX.setMaxQueuedQueries(10);
        rootBX.setMaxRunningQueries(10);

        InternalResourceGroup rootBY = rootB.getOrCreateSubGroup("y");
        rootBY.setSoftMemoryLimit(new DataSize(1, MEGABYTE));
        rootBY.setMaxQueuedQueries(10);
        rootBY.setMaxRunningQueries(10);

        // Queue 40 queries (= maxQueuedQueries (40) + maxRunningQueries (0))
        Set<MockQueryExecution> queries = fillGroupTo(rootAX, ImmutableSet.of(), 10, false);
        queries.addAll(fillGroupTo(rootAY, ImmutableSet.of(), 10, false));
        queries.addAll(fillGroupTo(rootBX, ImmutableSet.of(), 10, true));
        queries.addAll(fillGroupTo(rootBY, ImmutableSet.of(), 10, true));

        ResourceGroupInfo info = root.getInfo();
        assertEquals(info.getNumAggregatedRunningQueries(), 0);
        assertEquals(info.getNumAggregatedQueuedQueries(), 40);

        // root.maxRunningQueries = 4, root.a.maxRunningQueries = 2, root.b.maxRunningQueries = 2. Will have 4 queries running and 36 left queued.
        root.setMaxRunningQueries(4);
        root.processQueuedQueries();
        info = root.getInfo();
        assertEquals(info.getNumAggregatedRunningQueries(), 4);
        assertEquals(info.getNumAggregatedQueuedQueries(), 36);

        // Complete running queries
        Iterator<MockQueryExecution> iterator = queries.iterator();
        while (iterator.hasNext()) {
            MockQueryExecution query = iterator.next();
            if (query.getState() == RUNNING) {
                query.complete();
                iterator.remove();
            }
        }

        // 4 more queries start running, 32 left queued.
        root.processQueuedQueries();
        info = root.getInfo();
        assertEquals(info.getNumAggregatedRunningQueries(), 4);
        assertEquals(info.getNumAggregatedQueuedQueries(), 32);

        // root.maxRunningQueries = 10, root.a.maxRunningQueries = 2, root.b.maxRunningQueries = 2. Still only have 4 running queries and 32 left queued.
        root.setMaxRunningQueries(10);
        root.processQueuedQueries();
        info = root.getInfo();
        assertEquals(info.getNumAggregatedRunningQueries(), 4);
        assertEquals(info.getNumAggregatedQueuedQueries(), 32);

        // root.maxRunningQueries = 10, root.a.maxRunningQueries = 2, root.b.maxRunningQueries = 10. Will have 10 running queries and 26 left queued.
        rootB.setMaxRunningQueries(10);
        root.processQueuedQueries();
        info = root.getInfo();
        assertEquals(info.getNumAggregatedRunningQueries(), 10);
        assertEquals(info.getNumAggregatedQueuedQueries(), 26);
    }

    private static Set<MockQueryExecution> fillGroupTo(InternalResourceGroup group, Set<MockQueryExecution> existingQueries, int count)
    {
        return fillGroupTo(group, existingQueries, count, false);
    }

    private static Set<MockQueryExecution> fillGroupTo(InternalResourceGroup group, Set<MockQueryExecution> existingQueries, int count, boolean queryPriority)
    {
        int existingCount = existingQueries.size();
        Set<MockQueryExecution> queries = new HashSet<>(existingQueries);
        for (int i = 0; i < count - existingCount; i++) {
            MockQueryExecution query = new MockQueryExecution(0, group.getId().toString().replace(".", "") + Integer.toString(i), queryPriority ? i + 1 : 1);
            queries.add(query);
            group.run(query);
        }
        return queries;
    }
}


text:
#region Apache Notice

#endregion

#region Using

using System;
using System.Xml.Serialization;
using IBatisNet.Common.Utilities;

#endregion

namespace IBatisNet.DataMapper.Configuration.Alias
{
	/// <summary>
	/// TypeAlias.
	/// </summary>
	[Serializable]
	[XmlRoot("typeAlias", Namespace="http://ibatis.apache.org/dataMapper")]
	public class TypeAlias
	{

		#region Fields
		[NonSerialized]
		private string _name = string.Empty;
		[NonSerialized]
		private string _className = string.Empty;
		[NonSerialized]
		private Type _class = null;
		#endregion

		#region Properties
		/// <summary>
		/// Name used to identify the typeAlias amongst the others.
		/// </summary>
		/// <example> Account</example>
		[XmlAttribute("alias")]
		public string Name
		{
			get { return _name; }
			set
			{
				if ((value == null) || (value.Length < 1))
				{
					throw new ArgumentNullException("The name attribute is mandatory in the typeAlias ");
				}
				_name = value;
			}
		}

		/// <summary>
		/// The type class for the typeAlias
		/// </summary>
		[XmlIgnore]
		public Type Class
		{
			get { return _class; }
		}

		/// <summary>
		/// The class name to identify the typeAlias.
		/// </summary>
		/// <example>Com.Site.Domain.Product</example>
		[XmlAttribute("type")]
		public string ClassName
		{
			get { return _className; }
			set
			{
				if ((value == null) || (value.Length < 1))
				{
					throw new ArgumentNullException("The class attribute is mandatory in the typeAlias " + _name);
				}
				_className = value;
			}
		}
		#endregion

		#region Constructor (s) / Destructor
		/// <summary>
		/// Do not use direclty, only for serialization.
		/// </summary>
		public TypeAlias()
		{}

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="type">a type.</param>
		public TypeAlias(Type type)
		{
			_class = type;
		}
		#endregion

		#region Methods
		/// <summary>
		/// Initialize the object,
		/// try to idenfify the .Net type class from the corresponding name.
		/// </summary>
		public void Initialize()
		{
            _class = TypeUtils.ResolveType(_className);
		}
		#endregion

	}
}


text:
package stroom.importexport.client.event;

import stroom.explorer.shared.ExplorerNode;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;

import java.util.List;

public class ExportConfigEvent extends GwtEvent<ExportConfigEvent.Handler> {

    private static Type<Handler> TYPE;

    private final List<ExplorerNode> selection;

    private ExportConfigEvent(final List<ExplorerNode> selection) {
        this.selection = selection;
    }

    public static void fire(final HasHandlers source, final List<ExplorerNode> selection) {
        source.fireEvent(new ExportConfigEvent(selection));
    }

    public static Type<Handler> getType() {
        if (TYPE == null) {
            TYPE = new Type<>();
        }
        return TYPE;
    }

    @Override
    public Type<Handler> getAssociatedType() {
        return getType();
    }

    @Override
    protected void dispatch(final Handler handler) {
        handler.onExport(this);
    }

    public List<ExplorerNode> getSelection() {
        return selection;
    }

    public interface Handler extends EventHandler {

        void onExport(ExportConfigEvent event);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
    Copyright 2017 Yan Zhenjie

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yanzhenjie.nohttp.sample">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:name=".Application"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.Main">
        <activity
            android:name=".activity.Main2Activity"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<!--
        <activity
            android:name=".activity.splash.SplashActivity"
            android:theme="@style/AppTheme.Splash">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
-->
        <activity
            android:name=".activity.splash.WelActivity"
            android:theme="@style/AppTheme.Splash" />
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:theme="@style/AppTheme.Main.Launcher"
            android:windowSoftInputMode="stateAlwaysHidden|stateHidden" />
        <activity
            android:name=".activity.OriginalActivity"
            android:label="@string/title_original_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.MethodActivity"
            android:label="@string/title_method_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.ImageActivity"
            android:label="@string/title_image_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.json.JsonActivity"
            android:label="@string/title_json_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.PostBodyActivity"
            android:label="@string/title_post_body_activity"
            android:theme="@style/AppTheme.Main"
            android:windowSoftInputMode="adjustPan|stateAlwaysHidden" />
        <activity
            android:name=".activity.define.DefineRequestActivity"
            android:label="@string/title_define_request_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cache.CacheActivity"
            android:label="@string/title_cache_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cache.CacheHttpActivity"
            android:label="@string/title_cache_http_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cache.CacheRequestFailedReadCacheActivity"
            android:label="@string/title_cache_request_failed_read_cache_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cache.CacheNoneCacheRequestNetWorkActivity"
            android:label="@string/title_cache_none_request_network_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cache.CacheOnlyReadCacheActivity"
            android:label="@string/title_cache_only_read_cache"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cache.CacheOnlyRequestNetworkActivity"
            android:label="@string/title_cache_only_request_network"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.RedirectActivity"
            android:label="@string/title_redirect_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.upload.UploadFileActivity"
            android:label="@string/title_upload_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.upload.UploadSingleFileActivity"
            android:label="@string/title_upload_single_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.upload.UploadMultiFileActivity"
            android:label="@string/title_upload_multi_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.upload.UploadFileListActivity"
            android:label="@string/title_upload_file_list_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.upload.UploadAlbumActivity"
            android:label="@string/title_upload_album"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.download.DownloadActivity"
            android:label="@string/title_download_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.download.DownloadSingleFileActivity"
            android:label="@string/title_download_single_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.download.DownloadFileListActivity"
            android:label="@string/title_download_list_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cancel.CancelActivity"
            android:label="@string/title_cancel_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cancel.CancelLinkageActivity"
            android:label="@string/title_cancel_linkage_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cancel.CancelSignActivity"
            android:label="@string/title_cancel_sign_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.cancel.CancelAllActivity"
            android:label="@string/title_cancel_all_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.SyncActivity"
            android:label="@string/title_sync_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.ProXYActivity"
            android:label="@string/title_proxy_activity"
            android:theme="@style/AppTheme.Main" />
        <activity
            android:name=".activity.HttpsActivity"
            android:label="@string/title_https_activity"
            android:theme="@style/AppTheme.Main" />
    </application>

</manifest>


text:
using System.ComponentModel;
using System.Collections.Generic;

namespace Ink.Runtime
{
    // Order is significant for type coersion.
    // If types aren't directly compatible for an operation,
    // they're coerced to the same type, downward.
    // Higher value types "infect" an operation.
    // (This may not be the most sensible thing to do, but it's worked so far!)
    internal enum ValueType
    {
        // Used in coersion
        Int,
        Float,
        List,
        String,

        // Not used for coersion described above
        DivertTarget,
        VariablePointer
    }

    internal abstract class Value : Runtime.Object
    {
        public abstract ValueType valueType { get; }
        public abstract bool isTruthy { get; }

        public abstract Value Cast(ValueType newType);

        public abstract object valueObject { get; }

        public static Value Create(object val)
        {
            // Implicitly lose precision from any doubles we get passed in
            if (val is double) {
                double doub = (double)val;
                val = (float)doub;
            }

            // Implicitly convert bools into ints
            if (val is bool) {
                bool b = (bool)val;
                val = (int)(b ? 1 : 0);
            }

            if (val is int) {
                return new IntValue ((int)val);
            } else if (val is long) {
                return new IntValue ((int)(long)val);
            } else if (val is float) {
                return new FloatValue ((float)val);
            } else if (val is double) {
                return new FloatValue ((float)(double)val);
            } else if (val is string) {
                return new StringValue ((string)val);
            } else if (val is Path) {
                return new DivertTargetValue ((Path)val);
            } else if (val is RawList) {
                return new ListValue ((RawList)val);
            }

            return null;
        }

        internal override Object Copy()
        {
            return Create (valueObject);
        }
    }

    internal abstract class Value<T> : Value
    {
        public T value { get; set; }

        public override object valueObject {
            get {
                return (object)value;
            }
        }

        public Value (T val)
        {
            value = val;
        }

        public override string ToString ()
        {
            return value.ToString();
        }
    }

    internal class IntValue : Value<int>
    {
        public override ValueType valueType { get { return ValueType.Int; } }
        public override bool isTruthy { get { return value != 0; } }

        public IntValue(int intVal) : base(intVal)
        {
        }

        public IntValue() : this(0) {}

        public override Value Cast(ValueType newType)
        {
            if (newType == valueType) {
                return this;
            }

            if (newType == ValueType.Float) {
                return new FloatValue ((float)this.value);
            }

            if (newType == ValueType.String) {
                return new StringValue("" + this.value);
            }

            throw new System.Exception ("Unexpected type cast of Value to new ValueType");
        }
    }

    internal class FloatValue : Value<float>
    {
        public override ValueType valueType { get { return ValueType.Float; } }
        public override bool isTruthy { get { return value != 0.0f; } }

        public FloatValue(float val) : base(val)
        {
        }

        public FloatValue() : this(0.0f) {}

        public override Value Cast(ValueType newType)
        {
            if (newType == valueType) {
                return this;
            }

            if (newType == ValueType.Int) {
                return new IntValue ((int)this.value);
            }

            if (newType == ValueType.String) {
                return new StringValue("" + this.value.ToString(System.Globalization.CultureInfo.InvariantCulture));
            }

            throw new System.Exception ("Unexpected type cast of Value to new ValueType");
        }
    }

    internal class StringValue : Value<string>
    {
        public override ValueType valueType { get { return ValueType.String; } }
        public override bool isTruthy { get { return value.Length > 0; } }

        public bool isNewline { get; private set; }
        public bool isInlineWhitespace { get; private set; }
        public bool isNonWhitespace {
            get {
                return !isNewline && !isInlineWhitespace;
            }
        }

        public StringValue(string str) : base(str)
        {
            // Classify whitespace status
            isNewline = value == "\n";
            isInlineWhitespace = true;
            foreach (var c in value) {
                if (c != ' ' && c != '\t') {
                    isInlineWhitespace = false;
                    break;
                }
            }
        }

        public StringValue() : this("") {}

        public override Value Cast(ValueType newType)
        {
            if (newType == valueType) {
                return this;
            }

            if (newType == ValueType.Int) {

                int parsedInt;
                if (int.TryParse (value, out parsedInt)) {
                    return new IntValue (parsedInt);
                } else {
                    return null;
                }
            }

            if (newType == ValueType.Float) {
                float parsedFloat;
                if (float.TryParse (value, System.Globalization.NumberStyles.Float ,System.Globalization.CultureInfo.InvariantCulture, out parsedFloat)) {
                    return new FloatValue (parsedFloat);
                } else {
                    return null;
                }
            }

            throw new System.Exception ("Unexpected type cast of Value to new ValueType");
        }
    }

    internal class DivertTargetValue : Value<Path>
    {
        public Path targetPath { get { return this.value; } set { this.value = value; } }
        public override ValueType valueType { get { return ValueType.DivertTarget; } }
        public override bool isTruthy { get { throw new System.Exception("Shouldn't be checking the truthiness of a divert target"); } }

        public DivertTargetValue(Path targetPath) : base(targetPath)
        {
        }

        public DivertTargetValue() : base(null)
        {}

        public override Value Cast(ValueType newType)
        {
            if (newType == valueType)
                return this;

            throw new System.Exception ("Unexpected type cast of Value to new ValueType");
        }

        public override string ToString ()
        {
            return "DivertTargetValue(" + targetPath + ")";
        }
    }

    // TODO: Think: Erm, I get that this contains a string, but should
    // we really derive from Value<string>? That seems a bit misleading to me.
    internal class VariablePointerValue : Value<string>
    {
        public string variableName { get { return this.value; } set { this.value = value; } }
        public override ValueType valueType { get { return ValueType.VariablePointer; } }
        public override bool isTruthy { get { throw new System.Exception("Shouldn't be checking the truthiness of a variable pointer"); } }

        // Where the variable is located
        // -1 = default, unknown, yet to be determined
        // 0  = in global scope
        // 1+ = callstack element index + 1 (so that the first doesn't conflict with special global scope)
        public int contextIndex { get; set; }

        public VariablePointerValue(string variableName, int contextIndex = -1) : base(variableName)
        {
            this.contextIndex = contextIndex;
        }

        public VariablePointerValue() : this(null)
        {
        }

        public override Value Cast(ValueType newType)
        {
            if (newType == valueType)
                return this;

            throw new System.Exception ("Unexpected type cast of Value to new ValueType");
        }

        public override string ToString ()
        {
            return "VariablePointerValue(" + variableName + ")";
        }

        internal override Object Copy()
        {
            return new VariablePointerValue (variableName, contextIndex);
        }
    }

    internal class ListValue : Value<RawList>
    {
        public override ValueType valueType {
            get {
                return ValueType.List;
            }
        }

        // Truthy if it contains any non-zero items
        public override bool isTruthy {
            get {
                foreach (var kv in value) {
                    int listItemIntValue = kv.Value;
                    if (listItemIntValue != 0)
                        return true;
                }
                return false;
            }
        }

        public override Value Cast (ValueType newType)
        {
            if (newType == ValueType.Int) {
                var max = value.maxItem;
                if( max.Key.isNull )
                    return new IntValue (0);
                else
                    return new IntValue (max.Value);
            }

            else if (newType == ValueType.Float) {
                var max = value.maxItem;
                if (max.Key.isNull)
                    return new FloatValue (0.0f);
                else
                    return new FloatValue ((float)max.Value);
            }

            else if (newType == ValueType.String) {
                var max = value.maxItem;
                if (max.Key.isNull)
                    return new StringValue ("");
                else {
                    return new StringValue (max.Key.ToString());
                }
            }

            if (newType == valueType)
                return this;

            throw new System.Exception ("Unexpected type cast of Value to new ValueType");
        }

        public ListValue () : base(null) {
            value = new RawList ();
        }

        public ListValue (RawList list) : base (null)
        {
            value = new RawList (list);
        }

        public ListValue (RawListItem singleItem, int singleValue) : base (null)
        {
            value = new RawList {
                {singleItem, singleValue}
            };
        }

        public static void RetainListOriginsForAssignment (Runtime.Object oldValue, Runtime.Object newValue)
        {
            var oldList = oldValue as ListValue;
            var newList = newValue as ListValue;

            // When assigning the emtpy list, try to retain any initial origin names
            if (oldList && newList && newList.value.Count == 0)
                newList.value.SetInitialOriginNames (oldList.value.originNames);
        }
    }

}


text:
layout: post
title:  "A reStructuredText plugin for Jekyll (by ReST)"
categories: markup
---

Overview
========

This plugin adds `ReStructuredText`_ support to `Jekyll`_ and `Octopress`_.
It renders ReST in posts and pages, and provides a custom directive to
support Octopress-compatible syntax highlighting.

Requirements
============

* Jekyll *or* Octopress >= 2.0
* Docutils
* Pygments
* `RbST`_

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

1. Install Docutils and Pygments.

   The most convenient way is to use virtualenv_burrito:

   ::

      $ curl -s https://raw.github.com/brainsik/virtualenv-burrito/master/virtualenv-burrito.sh | bash
      $ source /Users/xdissent/.venvburrito/startup.sh
      $ mkvirtualenv jekyll-rst
      $ pip install docutils pygments

2. Install RbST.

   If you use `bundler`_ with Octopress, add ``gem 'RbST'`` to
   your ``Gemfile`` in the ``development`` group, then run
   ``bundle install``. Otherwise, ``gem install RbST``.

3. Install the plugin.

   For Jekyll:

   ::

      $ cd <jekyll-project-path>
      $ git submodule add https://github.com/xdissent/jekyll-rst.git _plugins/jekyll-rst

   For Octopress:

   ::

      $ cd <octopress-project-path>
      $ git submodule add https://github.com/xdissent/jekyll-rst.git plugins/jekyll-rst

4. Start blogging in ReStructuredText. Any file with the ``.rst`` extension
   will be parsed as ReST and rendered into HTML.

   .. note:: Be sure to activate the ``jekyll-rst`` virtualenv before generating
      the site by issuing a ``workon jekyll-rst``. I suggest you follow `Harry
      Marr's advice`_ and create a ``.venv`` file that will  automatically
      activate the ``jekyll-rst`` virtualenv when you ``cd`` into your project.

Source Code Highlighting
========================

A ``code-block`` ReST directive is registered and aliased as ``sourcecode``.
It adds syntax highlighting to code blocks in your documents::

   .. code-block:: ruby

      # Output "I love ReST"
      say = "I love ReST"
      puts say

Optional arguments exist to supply a caption, link, and link title::

   .. code-block:: console
      :caption: Read Hacker News on a budget
      :url: http://news.ycombinator.com
      :title: Hacker News

      $ curl http://news.ycombinator.com | less

Octopress already includes style sheets for syntax highlighting, but you'll
need to generate one yourself if using Jekyll::

   $ pygmentize -S default -f html > css/pygments.css

Octopress Tips
==============

* Use ``.. more`` in your ReST documents to indicate where Octopress's
  ``excerpt`` tag should split your content for summary views.

.. _ReStructuredText: http://docutils.sourceforge.net/rst.html
.. _Jekyll: http://jekyllrb.com/
.. _Octopress: http://octopress.com/
.. _RbST: http://rubygems.org/gems/RbST
.. _bundler: http://gembundler.com/
.. _Harry Marr's advice: http://hmarr.com/2010/jan/19/making-virtualenv-play-nice-with-git/


text:
// ***********************************************************************
// Assembly         : PodioPCL
// Author           : OnsharpRyan
// Created          : 12-13-2014
//
// Last Modified By : OnsharpRyan
// Last Modified On : 12-13-2014
// ***********************************************************************
// <copyright file="NumericItemField.cs" company="Onsharp">
//     Copyright (c) Onsharp. All rights reserved.
// </copyright>
//
// ***********************************************************************
using System.Linq;

namespace PodioPCL.Models.ItemFields
{
	///
	/// A field that can hold a single number with decimals.
	///

	/// Application API Documentation
	///
    public class NumericItemField : ItemField
    {
		///
		/// Gets or sets the value.
		///
		/// <value>The value.</value>
        public double? Value
        {
            get
            {
                if (this.HasValue("value"))
                {
                    return (double)this.Values.First()["value"];
                }
                else
                {
                    return null;
                }
            }

            set
            {
                ensureValuesInitialized(true);
                this.Values.First()["value"] = value;
            }
        }
    }
}


text:
"""
The Cheqlist app.

:Copyright: © 2015-2021, Chris Warrick.
:License: BSD (see /LICENSE).
"""

import os
import sys
import io
import time
import cheqlist
from cheqlist import utils, undocommands
from cheqlist.undowidget import UndoWidget
from cheqlist.pastewindow import PasteWindow
try:
    from PySide2 import QtCore, QtGui, QtWidgets
    import PySide2
    CHEQLIST_BACKEND = "PySide2"
    BACKEND_VERSION = PySide2.__version__
    QT_VERSION = QtCore.__version__
except ImportError:
    from PyQt5 import QtCore, QtGui, QtWidgets
    import PyQt5.Qt
    CHEQLIST_BACKEND = "PyQt5"
    BACKEND_VERSION = PyQt5.Qt.PYQT_VERSION_STR
    QT_VERSION = PyQT5.Qt.QT_VERSION_STR

CHEQLIST_BACKEND_STR = '{0} v{1}, Qt v{2}'.format(
        CHEQLIST_BACKEND, BACKEND_VERSION, QT_VERSION)

__all__ = ('Main',)

PBAR_FORMAT_QT = "%v/%m (%p%)"
PBAR_FORMAT_PY = "%d/%d (%d%%)"

class Main(QtWidgets.QMainWindow):
    """The main window of the app."""

    def __init__(self, app):
        """Create the GUI."""
        super(Main, self).__init__()
        cheqlist.log.info("Backend: " + CHEQLIST_BACKEND_STR)
        self.app = app
        self.filename = None
        self.filebasename = None
        self.lastText = {}
        self.lastState = {}
        self.ignoreStruckOut = cheqlist.config.getboolean(
            'settings', 'ignore_struck_out')
        self.undoStack = QtWidgets.QUndoStack(self)

        self.centralwidget = QtWidgets.QWidget(self)
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.tasklist = QtWidgets.QListWidget(self.centralwidget)
        self.tasklist.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
        self.tasklist.setDefaultDropAction(QtCore.Qt.MoveAction)

        self.verticalLayout.addWidget(self.tasklist)
        self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressBar.setTextVisible(True)
        self.progressBar.setFormat(PBAR_FORMAT_QT)
        self.updateProgressBar()
        self.verticalLayout.addWidget(self.progressBar)
        self.setCentralWidget(self.centralwidget)
        self.toolBar = QtWidgets.QToolBar("Main", self)
        self.toolBar.setIconSize(QtCore.QSize(16, 16))
        self.toolBar.setFloatable(False)
        self.toolBar.setAllowedAreas(QtCore.Qt.TopToolBarArea)
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.editToolBar = QtWidgets.QToolBar("Edit", self)
        self.editToolBar.setIconSize(QtCore.QSize(16, 16))
        self.editToolBar.setFloatable(False)
        self.editToolBar.setAllowedAreas(QtCore.Qt.TopToolBarArea)
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.editToolBar)
        self.insertToolBarBreak(self.editToolBar)
        menu = self.menuBar()
        self.fileMenu = menu.addMenu("&File")
        self.editMenu = menu.addMenu("&Edit")
        self.helpMenu = menu.addMenu("&Help")

        self.actionAdd = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("list-add"), "&Add", self, shortcut='Ctrl+T',
            toolTip="Add", triggered=self.addItemHandler)

        self.actionEdit = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("edit-rename"), "&Edit", self,
            shortcut='Ctrl+E', toolTip="Edit", triggered=self.editItemHandler)

        self.actionDelete = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("list-remove"), "&Delete", self,
            shortcut='Delete', toolTip="Delete", triggered=self.delItemHandler)

        self.actionBold = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("format-text-bold"), "&Bold", self,
            shortcut='Ctrl+B', toolTip="Bold", checkable=True,
            triggered=self.boldItemHandler)

        self.actionItalic = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("format-text-italic"), "&Italic", self,
            shortcut='Ctrl+I', toolTip="Italic", checkable=True,
            triggered=self.italicItemHandler)

        self.actionUnderline = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("format-text-underline"), "&Underline", self,
            shortcut='Ctrl+U', toolTip="Underline", checkable=True,
            triggered=self.underlineItemHandler)

        self.actionStrikeOut = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("format-text-strikethrough"), "&Strike Out",
            self, shortcut='Ctrl+Alt+S', toolTip="Strike Out", checkable=True,
            triggered=self.strikeOutItemHandler)

        self.actionOpen = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("document-open"), "&Open…", self,
            shortcut='Ctrl+O', toolTip="Open", triggered=self.openHandler)

        self.actionSave = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("document-save"), "&Save…", self,
            shortcut='Ctrl+S', toolTip="Save", triggered=self.saveHandler)

        self.actionSaveAs = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("document-save-as"), "S&ave as…", self,
            shortcut='Ctrl+Shift+S', toolTip="Save as",
            triggered=self.saveAsHandler)

        self.actionClear = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("edit-clear-list"), "Clea&r", self,
            shortcut='Ctrl+R', toolTip="Clear", triggered=self.clear)

        self.actionMoveUp = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("go-up"), "&Move up", self,
            shortcut='Ctrl+Up', toolTip="Move up", triggered=self.moveUp)
        self.actionMoveDown = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("go-down"), "Move dow&n", self,
            shortcut='Ctrl+Down', toolTip="Move down", triggered=self.moveDown)

        self.actionPasteItems = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("edit-paste"), "&Paste items…", self,
            shortcut='Ctrl+V', toolTip="Paste items from clipboard",
            triggered=self.pasteItems)

        self.actionQuit = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("application-exit"), "&Quit", self,
            shortcut='Ctrl+Q', toolTip="Quit", triggered=self.quit)

        self.actionCheckAll = QtWidgets.QAction(
            "Check &All", self, toolTip="Check all items in the list.",
            triggered=self.checkAll)

        self.actionCheckNone = QtWidgets.QAction(
            "&Uncheck All", self, toolTip="Uncheck all items in the list.",
            triggered=self.checkNone)

        self.actionCheckInvert = QtWidgets.QAction(
            "In&vert Selection", self, toolTip="Check all unchecked items "
            "and uncheck all checked items.", triggered=self.checkInvert)

        self.actionIgnoreStruckOut = QtWidgets.QAction(
            "I&gnore struck out tasks", self, toolTip="Ignore tasks that are "
            "struck out from counts", triggered=self.ignoreStruckOutHandler,
            checkable=True)

        self.actionUsersGuide = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("help-contents"), "User's &Guide…", self,
            toolTip="Open the Cheqlist User's Guide", triggered=self.usersGuide)

        self.actionAbout = QtWidgets.QAction(
            QtGui.QIcon.fromTheme("help-about"), "&About Cheqlist…", self,
            toolTip="Open the Cheqlist About window", triggered=self.aboutWindow)

        self.actionUndo = self.undoStack.createUndoAction(self)
        self.actionUndo.setIcon(QtGui.QIcon.fromTheme("edit-undo"))
        self.actionUndo.setShortcut("Ctrl+Z")
        self.actionRedo = self.undoStack.createRedoAction(self)
        self.actionRedo.setIcon(QtGui.QIcon.fromTheme("edit-redo"))
        self.actionRedo.setShortcut("Ctrl+Y")

        self.actionShowUndoWindow = QtWidgets.QAction(
            "Show undo &window", self, toolTip="Show undo window with all "
            "operations performed", triggered=self.showUndoWindowHandler,
            checkable=True)

        self.toolBar.addAction(self.actionAdd)
        self.toolBar.addAction(self.actionDelete)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionOpen)
        self.toolBar.addAction(self.actionSave)
        self.toolBar.addAction(self.actionSaveAs)
        self.toolBar.addAction(self.actionClear)
        self.toolBar.addAction(self.actionQuit)

        self.editToolBar.addAction(self.actionBold)
        self.editToolBar.addAction(self.actionItalic)
        self.editToolBar.addAction(self.actionUnderline)
        self.editToolBar.addAction(self.actionStrikeOut)
        self.editToolBar.addSeparator()

        self.editToolBar.addAction(self.actionRedo)

        self.fileMenu.addAction(self.actionOpen)
        self.fileMenu.addAction(self.actionSave)
        self.fileMenu.addAction(self.actionSaveAs)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.actionQuit)

        self.editMenu.addAction(self.actionAdd)
        self.editMenu.addAction(self.actionEdit)
        self.editMenu.addAction(self.actionDelete)
        self.editMenu.addAction(self.actionClear)
        self.editMenu.addAction(self.actionPasteItems)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.actionBold)
        self.editMenu.addAction(self.actionItalic)
        self.editMenu.addAction(self.actionUnderline)
        self.editMenu.addAction(self.actionStrikeOut)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.actionMoveUp)
        self.editMenu.addAction(self.actionMoveDown)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.actionUndo)
        self.editMenu.addAction(self.actionRedo)
        self.editMenu.addAction(self.actionShowUndoWindow)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.actionCheckAll)
        self.editMenu.addAction(self.actionCheckNone)
        self.editMenu.addAction(self.actionCheckInvert)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.actionIgnoreStruckOut)

        self.helpMenu.addAction(self.actionUsersGuide)
        self.helpMenu.addAction(self.actionAbout)

        self.tasklist.itemChanged.connect(self.itemChangedHandler)
        self.tasklist.itemSelectionChanged.connect(self.selectionHandler)
        self.actionIgnoreStruckOut.setChecked(self.ignoreStruckOut)
        self.tasklist.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.tasklist.customContextMenuRequested.connect(
            self.tasklistMenuHandler)

        self.undoWidget = UndoWidget(self.undoStack)
        self.undoWidget.setWindowTitle("Operations — Cheqlist")
        self.undoWidget._mw = self

        self.setWindowIcon(QtGui.QIcon.fromTheme("checkbox"))
        self.setUnifiedTitleAndToolBarOnMac(True)
        self.updateWindowTitle()
        self.resize(250, 1000)
        self.updateUI()

        for a in sys.argv[1:]:
            self.readFile(a, clear=False)

        QtCore.QMetaObject.connectSlotsByName(self)
        self.show()

        cheqlist.log.info("Startup finished in {0:0.2f} s".format(
                          time.time() - cheqlist._starttime))

    # Item handling
    def items(self):
        """Yield items in the task list."""
        for n in range(0, self.tasklist.count()):
            yield self.tasklist.item(n)

    def clear(self, event=None, undoable=True):
        """Clear the task list."""
        if undoable:
            self.undoStack.push(undocommands.CommandClear(self))
        else:
            self.tasklist.clear()
            self.undoStack.clear()
            self.lastText = {}
            self.lastState = {}
        cheqlist.log.info("List cleared")
        self.updateUI()

    def addItem(self, text="New item", edit=False, checked=False, bold=False,
                italic=False, underline=False, strikeOut=False, undoable=True):
        """Add an item to the task list."""
        item = QtWidgets.QListWidgetItem(text, self.tasklist)
        if not edit:
            self.lastText[id(item)] = text
        item.setFlags(QtCore.Qt.ItemIsSelectable |
                      QtCore.Qt.ItemIsEditable |
                      QtCore.Qt.ItemIsDragEnabled |
                      QtCore.Qt.ItemIsDropEnabled |
                      QtCore.Qt.ItemIsUserCheckable |
                      QtCore.Qt.ItemIsEnabled)
        if checked:
            item.setCheckState(QtCore.Qt.Checked)
        else:
            item.setCheckState(QtCore.Qt.Unchecked)
        self.lastState[id(item)] = item.checkState()
        f = item.font()
        if bold:
            f.setBold(True)
        if italic:
            f.setItalic(True)
        if underline:
            f.setUnderline(True)
        if strikeOut:
            f.setStrikeOut(True)
        item.setFont(f)
        if edit:
            self.tasklist.addItem(item)
            item.setSelected(True)
            self.tasklist.editItem(item)
        elif undoable:
            self.undoStack.push(undocommands.CommandAdd(item, self))
        else:
            self.tasklist.addItem(item)
        self.updateUI()
        return self.tasklist.row(item)

    # File handling
    def loadFromText(self, items, undoable=False):
        """Load items from a text file."""
        self.updateUI_disable()
        for (item, checked, bold, italic, underline,
             strikeOut) in utils.parse_lines(items):
            self.addItem(item, False, checked, bold, italic, underline,
                         strikeOut, undoable)

        self.updateUI_enable()
        cheqlist.log.info("{0} tasks loaded".format(len(items)))

    # Action handling
    def addItemHandler(self, event=None):
        """Add an empty item."""
        self.addItem('', True)

    def editItemHandler(self, event=None):
        """Edit the currently selected item."""
        for i in self.tasklist.selectedItems():
            self.tasklist.editItem(i)

    def delItemHandler(self, event=None):
        """Delete the currently selected item."""
        for i in self.tasklist.selectedItems():
            self.undoStack.push(undocommands.CommandDelete(i, self))
        self.updateUI()

    def updateProgressBar(self):
        """Update progress bar."""
        done = 0
        count = self.tasklist.count()
        if self.ignoreStruckOut:
            for i in self.items():
                if i.font().strikeOut():
                    count -= 1
                elif i.checkState():
                    done += 1
        else:
            for i in self.items():
                if i.checkState():
                    done += 1
        self.progressBar.setMaximum(count)
        self.progressBar.setValue(done)
        try:
            percent = done/count * 100
        except ZeroDivisionError:
            percent = 0
        self.progressBar.setToolTip(PBAR_FORMAT_PY % (done, count, percent))

    def _formatItemHandler(self, attrName, commandName):
        for i in self.tasklist.selectedItems():
            if getattr(i.font(), attrName)():
                className = 'CommandUn' + commandName
            else:
                className = 'Command' + commandName
            self.undoStack.push(getattr(undocommands, className)(i, self))

    def boldItemHandler(self, event=None):
        """Toggle bold on an item."""
        self._formatItemHandler('bold', 'Bold')

    def italicItemHandler(self, event=None):
        """Toggle italic on an item."""
        self._formatItemHandler('italic', 'Italic')

    def underlineItemHandler(self, event=None):
        """Toggle underline on an item."""
        self._formatItemHandler('underline', 'Underline')

    def strikeOutItemHandler(self, event=None):
        """Toggle strike out on an item."""
        self._formatItemHandler('strikeOut', 'StrikeOut')

    def openHandler(self, event=None):
        """Open a file."""
        # Ask for unsaved changes first
        if not self.unsavedChanges():
            return

        openmode = cheqlist.config.get('directories', 'open_from')
        lastdir = cheqlist.config.get('directories', 'lastdir')
        path = os.path.expanduser(cheqlist.config.get('directories', openmode))
        fname, _ = QtWidgets.QFileDialog.getOpenFileName(
            self, "Open", path,
            "Markdown checklist files (*.cheqlist *.checklist *.md "
            "*.mdown *.markdown)")

        if not fname:
            return

        newpath = os.path.dirname(fname)
        if newpath != lastdir:
            cheqlist.config.set('directories', 'lastdir', newpath)
            cheqlist.config_write()

        self.readFile(fname)

    def readFile(self, fname, clear=True):
        """Read a file and load it."""
        cheqlist.log.info("Opening file " + fname)
        if clear:
            self.clear(undoable=False)
        with io.open(fname, 'r', encoding='utf-8') as fh:
            self.loadFromText(fh.readlines())
        self.filename = fname
        self.filebasename = os.path.basename(self.filename)
        self.updateWindowTitle()

    def saveHandler(self, event=None):
        """Save a file."""
        if self.filename:
            self.writeFile(self.filename)
        else:
            self.saveAsHandler(event)

    def saveAsHandler(self, event=None):
        """Save as a new file."""
        openmode = cheqlist.config.get('directories', 'open_from')
        lastdir = cheqlist.config.get('directories', 'lastdir')
        path = os.path.expanduser(cheqlist.config.get('directories', openmode))
        fname, _ = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save", path,
            "Markdown checklist files (*.cheqlist *.checklist *.md "
            "*.mdown *.markdown)")

        if not fname:
            return

        newpath = os.path.dirname(fname)
        if newpath != lastdir:
            cheqlist.config.set('directories', 'lastdir', newpath)
            cheqlist.config_write()

        self.writeFile(fname)

    def writeFile(self, fname):
        """Serialize and write into a file."""
        cheqlist.log.info("Saving to file " + fname)
        with io.open(fname, 'w', encoding='utf-8') as fh:
            fh.writelines(utils.serialize_qt(self.items()))
        self.filename = fname
        self.filebasename = os.path.basename(fname)
        self.undoStack.clear()
        self.updateUI()

    def showUndoWindowHandler(self, event=None):
        """Show/hide the Undo window."""
        self.undoWidget.setVisible(not self.undoWidget.isVisible())

    def quit(self, event=None):
        """Display a message on quit via Ctrl+Q."""
        if self.unsavedChanges():
            cheqlist.log.info("*** Goodbye!")
            QtWidgets.qApp.quit()
        else:
            cheqlist.log.info("Aborted quit")

    def closeEvent(self, event=None):
        """Display a message on quit via the X button."""
        if self.unsavedChanges():
            cheqlist.log.info("*** Goodbye!")
            # super(Main, self).closeEvent(event)
            self.undoWidget.hide()
            event.accept()
            QtWidgets.qApp.quit()
        else:
            cheqlist.log.info("Aborted quit")
            event.ignore()

    def unsavedChanges(self):
        """If there are unsaved changes, ask the user if they want to save."""
        if not self.undoStack.isClean():
            if self.filename:
                msg = "List \"{0}\" has been modified.".format(
                    self.filebasename)
            else:
                msg = "The list has been modified."
            msgBox = QtWidgets.QMessageBox(self)
            msgBox.setWindowTitle("Cheqlist")
            msgBox.setText(msg)
            msgBox.setInformativeText("Do you want to save your changes?")
            msgBox.setIcon(QtWidgets.QMessageBox.Question)
            msgBox.setStandardButtons(QtWidgets.QMessageBox.Save |
                                      QtWidgets.QMessageBox.Discard |
                                      QtWidgets.QMessageBox.Cancel)
            msgBox.setDefaultButton(QtWidgets.QMessageBox.Save)
            ret = msgBox.exec()
            if ret == QtWidgets.QMessageBox.Save:
                self.saveHandler(None)
                return True
            elif ret == QtWidgets.QMessageBox.Discard:
                return True
            elif ret == QtWidgets.QMessageBox.Cancel:
                return False
        else:
            return True

    def checkAll(self, event=None):
        """Check all items (complete the list)."""
        self.undoStack.push(undocommands.CommandCheckAll(self))

    def checkNone(self, event=None):
        """Uncheck all items (reset the list)."""
        self.undoStack.push(undocommands.CommandCheckNone(self))

    def checkInvert(self, event=None):
        """Check all unchecked items, uncheck all checked items."""
        self.undoStack.push(undocommands.CommandCheckInvert(self))

    def ignoreStruckOutHandler(self, event=None):
        """Toggle the setting that ignores struck out events."""
        self.ignoreStruckOut = self.actionIgnoreStruckOut.isChecked()
        cheqlist.config.set("settings", "ignore_struck_out",
                            utils.config_bool(self.ignoreStruckOut))
        cheqlist.config_write()
        self.updateProgressBar()

    def pasteItems(self, event=None):
        """Open the paste items dialog box."""
        pw = PasteWindow(self)
        if pw.exec():
            self.loadFromText(pw.textBox.toPlainText().splitlines())

    def usersGuide(self, event=None):
        """Open the User's Guide."""
        QtGui.QDesktopServices.openUrl(QtCore.QUrl(
            "https://cheqlist.readthedocs.io/en/latest/users-guide.html"))

    def aboutWindow(self, event=None):
        """Display the About window."""
        QtWidgets.QMessageBox.about(
            self, "Cheqlist v{0}".format(cheqlist.__version__),
            "Cheqlist v{0}\nA simple Qt checklist.\n"
            "Copyright © 2015-2021, Chris Warrick. All rights reserved.\n"
            "Licensed under the 3-clause BSD license.\nUsing {1}".format(
                cheqlist.__version__, CHEQLIST_BACKEND_STR))

    def moveUp(self, event=None):
        """Move the selected item up one row."""
        self.moveHandler(-1, 0)

    def moveDown(self, event=None):
        """Move the selected item down one row."""
        self.moveHandler(1, self.tasklist.count() - 1)

    # UI functions and helpers
    def tasklistMenuHandler(self, point):
        """Show the right-click menu of a task list."""
        pos = self.tasklist.mapToGlobal(point)
        m = QtWidgets.QMenu()
        m.addAction(self.actionAdd)
        if self.tasklist.count():
            m.addAction(self.actionEdit)
            m.addAction(self.actionDelete)
            m.addAction(self.actionBold)
            m.addAction(self.actionItalic)
            m.addAction(self.actionUnderline)
            m.addAction(self.actionStrikeOut)
        m.exec(pos)

    def cleanChanged(self, clean):
        """Update the window title to reflect that the window is dirty."""
        self.updateWindowTitle()

    def updateWindowTitle(self):
        """Set the appropriate window title (file name, dirty status)."""
        if self.filename and self.undoStack.isClean():
            self.setWindowTitle("{0} — Cheqlist".format(self.filebasename))
        elif self.filename:
            self.setWindowTitle("{0} * — Cheqlist".format(self.filebasename))
        else:
            self.setWindowTitle("Cheqlist")

    def itemChangedHandler(self, item):
        """Handle item changes."""
        try:
            lt = self.lastText[id(item)]
            it = item.text()
            if lt is None and it:
                # Text added
                self.undoStack.push(undocommands.CommandAdd(item, self))
            elif lt is not None and it != lt:
                # Item text changed, let's make this an edit action
                self.undoStack.push(undocommands.CommandEdit(
                    item, self, lt, it))
        except KeyError:
            self.lastText[id(item)] = None

        cs = item.checkState()
        try:
            ls = self.lastState[id(item)]
            if ls != cs and cs == QtCore.Qt.Checked:
                self.undoStack.push(undocommands.CommandCheck(item, self))
            elif ls != cs and cs == QtCore.Qt.Unchecked:
                self.undoStack.push(undocommands.CommandUnCheck(item, self))
        except KeyError:
            # lastState is set only after checkState is set
            pass
        self.updateUI()

    def updateBoldAction(self):
        """Set the bold action check status."""
        s = False
        for i in self.tasklist.selectedItems():
            s = i.font().bold()

        self.actionBold.setChecked(s)

    def updateItalicAction(self):
        """Set the italic action check status."""
        s = False
        for i in self.tasklist.selectedItems():
            s = i.font().italic()

        self.actionItalic.setChecked(s)

    def updateUnderlineAction(self):
        """Set the underline action check status."""
        s = False
        for i in self.tasklist.selectedItems():
            s = i.font().underline()

        self.actionUnderline.setChecked(s)

    def updateStrikeOutAction(self):
        """Set the strike out action check status."""
        s = False
        for i in self.tasklist.selectedItems():
            s = i.font().strikeOut()

        self.actionStrikeOut.setChecked(s)

    def updateDisabledButtons(self):
        """Disable buttons if the list is empty."""
        if self.tasklist.count() == 0:
            self.actionDelete.setEnabled(False)
            self.actionBold.setEnabled(False)
            self.actionBold.setChecked(False)
            self.actionItalic.setEnabled(False)
            self.actionItalic.setChecked(False)
            self.actionUnderline.setEnabled(False)
            self.actionUnderline.setChecked(False)
            self.actionStrikeOut.setEnabled(False)
            self.actionStrikeOut.setChecked(False)
            self.progressBar.setEnabled(False)
        else:
            self.actionDelete.setEnabled(True)
            self.actionBold.setEnabled(True)
            self.actionItalic.setEnabled(True)
            self.actionUnderline.setEnabled(True)
            self.actionStrikeOut.setEnabled(True)
            self.progressBar.setEnabled(True)

    def updateUI(self):
        """Update all UI."""
        self.updateProgressBar()
        self.selectionHandler()
        self.updateDisabledButtons()
        self.updateWindowTitle()

    def _updateUI_disabled(self):
        """Do nothing."""
        pass

    _updateUI_enabled = updateUI

    def updateUI_disable(self):
        """Disable the updateUI function for long running operations."""
        self.progressBar.setMaximum(0)
        self.progressBar.setValue(0)
        self.updateUI = self._updateUI_disabled

    def updateUI_enable(self):
        """Enable the updateUI function after long running operations."""
        self.updateUI = self._updateUI_enabled
        self.updateUI()

    def selectionHandler(self):
        """Update actions when the selection changes."""
        self.updateBoldAction()
        self.updateItalicAction()
        self.updateUnderlineAction()
        self.updateStrikeOutAction()

    def moveHandler(self, difference, finalPosition):
        """Handle a move operation."""
        row = self.tasklist.currentRow()
        if row == finalPosition:
            return

        item = self.tasklist.takeItem(row)
        self.tasklist.insertItem(row + difference, item)
        self.tasklist.setCurrentItem(item)


text:
<?php

namespace Pixers\SalesManagoAPI\Exception;

/**
 * @author Sylwester Łuczak <sylwester.luczak@pixers.pl>
 */
class SalesManagoAPIException extends \Exception
{
}