text:
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/elf.h>
#include <linux/reboot.h>
#include <linux/interrupt.h>
#include <linux/pagemap.h>

#include <asm/asm-offsets.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/setup.h>
#include <asm/pgtable.h>
#include <asm/tlb.h>
#include <asm/gdb-stub.h>
#include <asm/mb-regs.h>

#include "local.h"

asmlinkage void ret_from_fork(void);

#include <asm/pgalloc.h>

void (*pm_power_off)(void);
EXPORT_SYMBOL(pm_power_off);

struct task_struct *alloc_task_struct_node(int node)
{
	struct task_struct *p = kmalloc_node(THREAD_SIZE, GFP_KERNEL, node);

	if (p)
		atomic_set((atomic_t *)(p+1), 1);
	return p;
}

void free_task_struct(struct task_struct *p)
{
	if (atomic_dec_and_test((atomic_t *)(p+1)))
		kfree(p);
}

static void core_sleep_idle(void)
{
#ifdef LED_DEBUG_SLEEP
	/* Show that we're sleeping... */
	__set_LEDS(0x55aa);
#endif
	frv_cpu_core_sleep();
#ifdef LED_DEBUG_SLEEP
	/* ... and that we woke up */
	__set_LEDS(0);
#endif
	mb();
}

void (*idle)(void) = core_sleep_idle;

/*
 * The idle thread. There's no useful work to be
 * done, so just try to conserve power and have a
 * low exit latency (ie sit in a loop waiting for
 * somebody to say that they'd like to reschedule)
 */
void cpu_idle(void)
{
	/* endless idle loop with no priority at all */
	while (1) {
		while (!need_resched()) {
			check_pgt_cache();

			if (!frv_dma_inprogress && idle)
				idle();
		}

		preempt_enable_no_resched();
		schedule();
		preempt_disable();
	}
}

void machine_restart(char * __unused)
{
	unsigned long reset_addr;
#ifdef CONFIG_GDBSTUB
	gdbstub_exit(0);
#endif

	if (PSR_IMPLE(__get_PSR()) == PSR_IMPLE_FR551)
		reset_addr = 0xfefff500;
	else
		reset_addr = 0xfeff0500;

	/* Software reset. */
	asm volatile("      dcef @(gr0,gr0),1 ! membar !"
		     "      sti     %1,@(%0,0) !"
		     "      nop ! nop ! nop ! nop ! nop ! "
		     "      nop ! nop ! nop ! nop ! nop ! "
		     "      nop ! nop ! nop ! nop ! nop ! "
		     "      nop ! nop ! nop ! nop ! nop ! "
		     : : "r" (reset_addr), "r" (1) );

	for (;;)
		;
}

void machine_halt(void)
{
#ifdef CONFIG_GDBSTUB
	gdbstub_exit(0);
#endif

	for (;;);
}

void machine_power_off(void)
{
#ifdef CONFIG_GDBSTUB
	gdbstub_exit(0);
#endif

	for (;;);
}

void flush_thread(void)
{
	/* nothing */
}

inline unsigned long user_stack(const struct pt_regs *regs)
{
	while (regs->next_frame)
		regs = regs->next_frame;
	return user_mode(regs) ? regs->sp : 0;
}

asmlinkage int sys_fork(void)
{
#ifndef CONFIG_MMU
	/* fork almost works, enough to trick you into looking elsewhere:-( */
	return -EINVAL;
#else
	return do_fork(SIGCHLD, user_stack(__frame), __frame, 0, NULL, NULL);
#endif
}

asmlinkage int sys_vfork(void)
{
	return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, user_stack(__frame), __frame, 0,
		       NULL, NULL);
}

/*****************************************************************************/
/*
 * clone a process
 * - tlsptr is retrieved by copy_thread()
 */
asmlinkage int sys_clone(unsigned long clone_flags, unsigned long newsp,
			 int __user *parent_tidptr, int __user *child_tidptr,
			 int __user *tlsptr)
{
	if (!newsp)
		newsp = user_stack(__frame);
	return do_fork(clone_flags, newsp, __frame, 0, parent_tidptr, child_tidptr);
} /* end sys_clone() */

/*****************************************************************************/
/*
 * This gets called before we allocate a new thread and copy
 * the current task into it.
 */
void prepare_to_copy(struct task_struct *tsk)
{
	//unlazy_fpu(tsk);
} /* end prepare_to_copy() */

/*****************************************************************************/
/*
 * set up the kernel stack and exception frames for a new process
 */
int copy_thread(unsigned long clone_flags,
		unsigned long usp, unsigned long topstk,
		struct task_struct *p, struct pt_regs *regs)
{
	struct pt_regs *childregs0, *childregs, *regs0;

	regs0 = __kernel_frame0_ptr;
	childregs0 = (struct pt_regs *)
		(task_stack_page(p) + THREAD_SIZE - FRV_FRAME0_SIZE);
	childregs = childregs0;

	/* set up the userspace frame (the only place that the USP is stored) */
	*childregs0 = *regs0;

	childregs0->gr8		= 0;
	childregs0->sp		= usp;
	childregs0->next_frame	= NULL;

	/* set up the return kernel frame if called from kernel_thread() */
	if (regs != regs0) {
		childregs--;
		*childregs = *regs;
		childregs->sp = (unsigned long) childregs0;
		childregs->next_frame = childregs0;
		childregs->gr15 = (unsigned long) task_thread_info(p);
		childregs->gr29 = (unsigned long) p;
	}

	p->set_child_tid = p->clear_child_tid = NULL;

	p->thread.frame	 = childregs;
	p->thread.curr	 = p;
	p->thread.sp	 = (unsigned long) childregs;
	p->thread.fp	 = 0;
	p->thread.lr	 = 0;
	p->thread.pc	 = (unsigned long) ret_from_fork;
	p->thread.frame0 = childregs0;

	/* the new TLS pointer is passed in as arg #5 to sys_clone() */
	if (clone_flags & CLONE_SETTLS)
		childregs->gr29 = childregs->gr12;

	save_user_regs(p->thread.user);

	return 0;
} /* end copy_thread() */

/*
 * sys_execve() executes a new program.
 */
asmlinkage int sys_execve(const char __user *name,
			  const char __user *const __user *argv,
			  const char __user *const __user *envp)
{
	int error;
	char * filename;

	filename = getname(name);
	error = PTR_ERR(filename);
	if (IS_ERR(filename))
		return error;
	error = do_execve(filename, argv, envp, __frame);
	putname(filename);
	return error;
}

unsigned long get_wchan(struct task_struct *p)
{
	struct pt_regs *regs0;
	unsigned long fp, pc;
	unsigned long stack_limit;
	int count = 0;
	if (!p || p == current || p->state == TASK_RUNNING)
		return 0;

	stack_limit = (unsigned long) (p + 1);
	fp = p->thread.fp;
	regs0 = p->thread.frame0;

	do {
		if (fp < stack_limit || fp >= (unsigned long) regs0 || fp & 3)
			return 0;

		pc = ((unsigned long *) fp)[2];

		/* FIXME: This depends on the order of these functions. */
		if (!in_sched_functions(pc))
			return pc;

		fp = *(unsigned long *) fp;
	} while (count++ < 16);

	return 0;
}

unsigned long thread_saved_pc(struct task_struct *tsk)
{
	/* Check whether the thread is blocked in resume() */
	if (in_sched_functions(tsk->thread.pc))
		return ((unsigned long *)tsk->thread.fp)[2];
	else
		return tsk->thread.pc;
}

int elf_check_arch(const struct elf32_hdr *hdr)
{
	unsigned long hsr0 = __get_HSR(0);
	unsigned long psr = __get_PSR();

	if (hdr->e_machine != EM_FRV)
		return 0;

	switch (hdr->e_flags & EF_FRV_GPR_MASK) {
	case EF_FRV_GPR64:
		if ((hsr0 & HSR0_GRN) == HSR0_GRN_32)
			return 0;
	case EF_FRV_GPR32:
	case 0:
		break;
	default:
		return 0;
	}

	switch (hdr->e_flags & EF_FRV_FPR_MASK) {
	case EF_FRV_FPR64:
		if ((hsr0 & HSR0_FRN) == HSR0_FRN_32)
			return 0;
	case EF_FRV_FPR32:
	case EF_FRV_FPR_NONE:
	case 0:
		break;
	default:
		return 0;
	}

	if ((hdr->e_flags & EF_FRV_MULADD) == EF_FRV_MULADD)
		if (PSR_IMPLE(psr) != PSR_IMPLE_FR405 &&
		    PSR_IMPLE(psr) != PSR_IMPLE_FR451)
			return 0;

	switch (hdr->e_flags & EF_FRV_CPU_MASK) {
	case EF_FRV_CPU_GENERIC:
		break;
	case EF_FRV_CPU_FR300:
	case EF_FRV_CPU_SIMPLE:
	case EF_FRV_CPU_TOMCAT:
	default:
		return 0;
	case EF_FRV_CPU_FR400:
		if (PSR_IMPLE(psr) != PSR_IMPLE_FR401 &&
		    PSR_IMPLE(psr) != PSR_IMPLE_FR405 &&
		    PSR_IMPLE(psr) != PSR_IMPLE_FR451 &&
		    PSR_IMPLE(psr) != PSR_IMPLE_FR551)
			return 0;
		break;
	case EF_FRV_CPU_FR450:
		if (PSR_IMPLE(psr) != PSR_IMPLE_FR451)
			return 0;
		break;
	case EF_FRV_CPU_FR500:
		if (PSR_IMPLE(psr) != PSR_IMPLE_FR501)
			return 0;
		break;
	case EF_FRV_CPU_FR550:
		if (PSR_IMPLE(psr) != PSR_IMPLE_FR551)
			return 0;
		break;
	}

	return 1;
}

int dump_fpu(struct pt_regs *regs, elf_fpregset_t *fpregs)
{
	memcpy(fpregs,
	       &current->thread.user->f,
	       sizeof(current->thread.user->f));
	return 1;
}


text:
<?php

use modules\themes\admin\widgets\Box;
use yii\helpers\Html;
use yii\grid\ActionColumn;
use modules\themes\admin\widgets\GridView;
use yii\grid\CheckboxColumn;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use modules\lang\models\Lang;

$this->title = 'Технологии';
$this->params['subtitle'] = 'Список';
$this->params['breadcrumbs'] = [
    $this->title
];

$gridId = 'technology-grid';
$gridConfig = [
    'id' => $gridId,
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'class' => CheckboxColumn::classname()
        ],
        'title',
        'text',
        'directionName',
        [
            'attribute' => 'originalLanguageName',
            'format' => 'raw',
            'filter' => Html::activeDropDownList($searchModel, 'originalLanguageName',
                ArrayHelper::map(Lang::find()->all(), 'id', 'name'),
                ['class'=>'form-control','prompt' => 'Все языки']
            ),
        ],
    ]
];

$boxButtons = $actions = [];

$boxButtons[] = '{create}';
$boxButtons[] = '{batch-delete}';

$actions[] = '{update}';
$actions[] = '{delete}';

$showActions = true;

$gridButtons = [];

if ($showActions === true) {
    $gridConfig['columns'][] = [
        'class' => ActionColumn::className(),
        'template' => implode(' ', $actions),
        'buttons'=>$gridButtons,
    ];
}

$boxButtons = !empty($boxButtons) ? implode(' ', $boxButtons) : null; ?>

        <?php Box::begin(
            [
                'title' => $this->params['subtitle'],
                'bodyOptions' => [
                    'class' => 'table-responsive'
                ],
                'buttonsTemplate' => $boxButtons,
                'grid' => $gridId,
            ]
        ); ?>
        <?=  GridView::widget($gridConfig);?>
        <?php Box::end(); ?>

redpajama_set_name: RedPajamaGithub


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var egret;
(function (egret) {
    (function (gui) {
        /**
        * @class egret.gui.ListBase
        * @classdesc
        * 支持选择内容的所有组件的基类。
        * @extends egret.gui.SkinnableDataContainer
        */
        var ListBase = (function (_super) {
            __extends(ListBase, _super);
            /**
            * @method egret.gui.ListBase#constructor
            */
            function ListBase() {
                _super.call(this);
                /**
                * 正在进行所有数据源的刷新操作
                * @member egret.gui.ListBase#_doingWholesaleChanges
                */
                this._doingWholesaleChanges = false;
                this._labelField = "label";
                this._requireSelection = false;
                this.requireSelectionChanged = false;
                /**
                * 在属性提交前缓存真实的选中项的值
                */
                this._proposedSelectedIndex = ListBase.NO_PROPOSED_SELECTION;
                this._selectedIndex = ListBase.NO_SELECTION;
                /**
                * 是否允许自定义的选中项
                * @member egret.gui.ListBase#_allowCustomSelectedItem
                */
                this._allowCustomSelectedItem = false;
                /**
                * 索引改变后是否需要抛出事件
                * @member egret.gui.ListBase#_dispatchChangeAfterSelection
                */
                this._dispatchChangeAfterSelection = false;
                this._useVirtualLayout = false;
                this.selectedIndexAdjusted = false;
            }
            ListBase.prototype._setDataProvider = function (value) {
                if (this.dataProvider)
                    this.dataProvider.removeEventListener(gui.CollectionEvent.COLLECTION_CHANGE, this.dataProvider_collectionChangeHandler, this);

                this.dataProviderChanged = true;
                this._doingWholesaleChanges = true;

                if (value)
                    value.addEventListener(gui.CollectionEvent.COLLECTION_CHANGE, this.dataProvider_collectionChangeHandler, this);

                _super.prototype._setDataProvider.call(this, value);
                this.invalidateProperties();
            };

            Object.defineProperty(ListBase.prototype, "layout", {
                /**
                * 布局对象
                * @member egret.gui.ListBase#layout
                */
                get: function () {
                    return (this.dataGroup) ? this.dataGroup.layout : this._dataGroupProperties.layout;
                },
                /**
                * @inheritDoc
                */
                set: function (value) {
                    if (value && this.useVirtualLayout)
                        value.useVirtualLayout = true;

                    this._setLayout(value);
                },
                enumerable: true,
                configurable: true
            });

            Object.defineProperty(ListBase.prototype, "labelField", {
                /**
                * 数据项如果是一个对象,此属性为数据项中用来显示标签文字的字段名称。
                * 若设置了labelFunction,则设置此属性无效。
                * @member egret.gui.ListBase#labelField
                */
                get: function () {
                    return this._labelField;
                },
                set: function (value) {
                    this._setLabelField(value);
                },
                enumerable: true,
                configurable: true
            });

            ListBase.prototype._setLabelField = function (value) {
                if (value == this._labelField)
                    return;
                this._labelField = value;
                this.labelFieldOrFunctionChanged = true;
                this.invalidateProperties();
            };

            Object.defineProperty(ListBase.prototype, "labelFunction", {
                /**
                * 用户提供的函数,在每个项目上运行以确定其标签。
                * 示例:function labelFunc(item:Object):String 。
                * @member egret.gui.ListBase#labelFunction
                */
                get: function () {
                    return this._labelFunction;
                },
                set: function (value) {
                    this._setLabelFunction(value);
                },
                enumerable: true,
                configurable: true
            });

            ListBase.prototype._setLabelFunction = function (value) {
                if (value == this._labelFunction)
                    return;

                this._labelFunction = value;
                this.labelFieldOrFunctionChanged = true;
                this.invalidateProperties();
            };

            Object.defineProperty(ListBase.prototype, "requireSelection", {
                /**
                * 如果为 true,则必须始终在控件中选中数据项目。

                * 如果该值为 true,则始终将 selectedIndex 属性设置为 0 和 (dataProvider.length - 1) 之间的一个值。
                * @member egret.gui.ListBase#requireSelection
                */
                get: function () {
                    return this._requireSelection;
                },
                set: function (value) {
                    this._setRequireSelection(value);
                },
                enumerable: true,
                configurable: true
            });

            ListBase.prototype._setRequireSelection = function (value) {
                if (value == this._requireSelection)
                    return;

                this._requireSelection = value;

                if (value) {
                    this.requireSelectionChanged = true;
                    this.invalidateProperties();
                }
            };

            Object.defineProperty(ListBase.prototype, "selectedIndex", {
                /**
                * 选中项目的基于 0 的索引。

                * 或者如果未选中项目,则为-1。设置 selectedIndex 属性会取消选择当前选定的项目并选择指定索引位置的数据项目。

                * 当用户通过与控件交互来更改 selectedIndex 属性时,此控件将分派 change 和 changing 事件。

                * 当以编程方式更改 selectedIndex 属性的值时,此控件不分派 change 和 changing 事件。
                * @member egret.gui.ListBase#selectedIndex
                */
                get: function () {
                    return this._getSelectedIndex();
                },
                set: function (value) {
                    this._setSelectedIndex(value, false);
                },
                enumerable: true,
                configurable: true
            });

            ListBase.prototype._getSelectedIndex = function () {
                if (this._proposedSelectedIndex != ListBase.NO_PROPOSED_SELECTION)
                    return this._proposedSelectedIndex;

                return this._selectedIndex;
            };

            /**
            * 设置选中项
            */
            ListBase.prototype._setSelectedIndex = function (value, dispatchChangeEvent) {
                if (typeof dispatchChangeEvent === "undefined") { dispatchChangeEvent = false; }
                if (value == this.selectedIndex) {
                    return;
                }

                if (dispatchChangeEvent)
                    this._dispatchChangeAfterSelection = (this._dispatchChangeAfterSelection || dispatchChangeEvent);
                this._proposedSelectedIndex = value;
                this.invalidateProperties();
            };

            Object.defineProperty(ListBase.prototype, "selectedItem", {
                /**
                * 当前已选中的项目。设置此属性会取消选中当前选定的项目并选择新指定的项目。

                * 当用户通过与控件交互来更改 selectedItem 属性时,此控件将分派 change 和 changing 事件。

                * 当以编程方式更改 selectedItem 属性的值时,此控件不分派 change 和 changing 事件。
                * @member egret.gui.ListBase#selectedItem
                */
                get: function () {
                    if (this._pendingSelectedItem !== undefined)
                        return this._pendingSelectedItem;

                    if (this._allowCustomSelectedItem && this.selectedIndex == ListBase.CUSTOM_SELECTED_ITEM)
                        return this._selectedItem;

                    if (this.selectedIndex == ListBase.NO_SELECTION || this.dataProvider == null)
                        return undefined;

                    return this.dataProvider.length > this.selectedIndex ? this.dataProvider.getItemAt(this.selectedIndex) : undefined;
                },
                set: function (value) {
                    this._setSelectedItem(value, false);
                },
                enumerable: true,
                configurable: true
            });

            /**
            * 设置选中项数据源
            * @method egret.gui.ListBase#_setSelectedItem
            * @param value {any}
            * @param dispatchChangeEvent {boolean}
            */
            ListBase.prototype._setSelectedItem = function (value, dispatchChangeEvent) {
                if (typeof dispatchChangeEvent === "undefined") { dispatchChangeEvent = false; }
                if (this.selectedItem === value)
                    return;

                if (dispatchChangeEvent)
                    this._dispatchChangeAfterSelection = (this._dispatchChangeAfterSelection || dispatchChangeEvent);

                this._pendingSelectedItem = value;
                this.invalidateProperties();
            };

            Object.defineProperty(ListBase.prototype, "useVirtualLayout", {
                /**
                * 是否使用虚拟布局,默认flase
                * @member egret.gui.ListBase#useVirtualLayout
                */
                get: function () {
                    return this._getUseVirtualLayout();
                },
                set: function (value) {
                    this._setUseVirtualLayout(value);
                },
                enumerable: true,
                configurable: true
            });

            ListBase.prototype._getUseVirtualLayout = function () {
                return (this.layout) ? this.layout.useVirtualLayout : this._useVirtualLayout;
            };

            ListBase.prototype._setUseVirtualLayout = function (value) {
                if (value == this.useVirtualLayout)
                    return;

                this._useVirtualLayout = value;
                if (this.layout)
                    this.layout.useVirtualLayout = value;
            };

            /**
            * @method egret.gui.ListBase#commitProperties
            */
            ListBase.prototype.commitProperties = function () {
                _super.prototype.commitProperties.call(this);

                if (this.dataProviderChanged) {
                    this.dataProviderChanged = false;
                    this._doingWholesaleChanges = false;

                    if (this.selectedIndex >= 0 && this.dataProvider && this.selectedIndex < this.dataProvider.length)
                        this.itemSelected(this.selectedIndex, true);
                    else if (this.requireSelection)
                        this._proposedSelectedIndex = 0;
                    else
                        this._setSelectedIndex(-1, false);
                }

                if (this.requireSelectionChanged) {
                    this.requireSelectionChanged = false;

                    if (this.requireSelection && this.selectedIndex == ListBase.NO_SELECTION && this.dataProvider && this.dataProvider.length > 0) {
                        this._proposedSelectedIndex = 0;
                    }
                }

                if (this._pendingSelectedItem !== undefined) {
                    if (this.dataProvider)
                        this._proposedSelectedIndex = this.dataProvider.getItemIndex(this._pendingSelectedItem);
                    else
                        this._proposedSelectedIndex = ListBase.NO_SELECTION;

                    if (this._allowCustomSelectedItem && this._proposedSelectedIndex == -1) {
                        this._proposedSelectedIndex = ListBase.CUSTOM_SELECTED_ITEM;
                        this._selectedItem = this._pendingSelectedItem;
                    }

                    this._pendingSelectedItem = undefined;
                }

                var changedSelection = false;
                if (this._proposedSelectedIndex != ListBase.NO_PROPOSED_SELECTION)
                    changedSelection = this.commitSelection();

                if (this.selectedIndexAdjusted) {
                    this.selectedIndexAdjusted = false;
                    if (!changedSelection) {
                        gui.UIEvent.dispatchUIEvent(this, gui.UIEvent.VALUE_COMMIT);
                    }
                }

                if (this.labelFieldOrFunctionChanged) {
                    if (this.dataGroup != null) {
                        var itemIndex;

                        if (this.layout && this.layout.useVirtualLayout) {
                            var list = this.dataGroup.getElementIndicesInView();
                            var length = list.length;
                            for (var i = 0; i < length; i++) {
                                var itemIndex = list[i];
                                this.updateRendererLabelProperty(itemIndex);
                            }
                        } else {
                            var n = this.dataGroup.numElements;
                            for (itemIndex = 0; itemIndex < n; itemIndex++) {
                                this.updateRendererLabelProperty(itemIndex);
                            }
                        }
                    }

                    this.labelFieldOrFunctionChanged = false;
                }
            };

            /**
            *  更新项呈示器文字标签
            */
            ListBase.prototype.updateRendererLabelProperty = function (itemIndex) {
                var renderer = (this.dataGroup.getElementAt(itemIndex));
                if (renderer)
                    renderer.label = this.itemToLabel(renderer.data);
            };

            /**
            * @method egret.gui.ListBase#partAdded
            * @param partName {string}
            * @param instance {any}
            */
            ListBase.prototype.partAdded = function (partName, instance) {
                _super.prototype.partAdded.call(this, partName, instance);

                if (instance == this.dataGroup) {
                    if (this._useVirtualLayout && this.dataGroup.layout)
                        this.dataGroup.layout.useVirtualLayout = true;

                    this.dataGroup.addEventListener(gui.RendererExistenceEvent.RENDERER_ADD, this.dataGroup_rendererAddHandler, this);
                    this.dataGroup.addEventListener(gui.RendererExistenceEvent.RENDERER_REMOVE, this.dataGroup_rendererRemoveHandler, this);
                }
            };

            /**
            * @method egret.gui.ListBase#partRemoved
            * @param partName {string}
            * @param instance {any}
            */
            ListBase.prototype.partRemoved = function (partName, instance) {
                _super.prototype.partRemoved.call(this, partName, instance);

                if (instance == this.dataGroup) {
                    this.dataGroup.removeEventListener(gui.RendererExistenceEvent.RENDERER_ADD, this.dataGroup_rendererAddHandler, this);
                    this.dataGroup.removeEventListener(gui.RendererExistenceEvent.RENDERER_REMOVE, this.dataGroup_rendererRemoveHandler, this);
                }
            };

            /**
            * @method egret.gui.ListBase#updateRenderer
            * @param renderer {IItemRenderer}
            * @param itemIndex {number}
            * @param data {any}
            * @returns {IItemRenderer}
            */
            ListBase.prototype.updateRenderer = function (renderer, itemIndex, data) {
                this.itemSelected(itemIndex, this._isItemIndexSelected(itemIndex));
                return _super.prototype.updateRenderer.call(this, renderer, itemIndex, data);
            };

            /**
            * @method egret.gui.ListBase#itemToLabel
            * @param item {any}
            * @returns {string}
            */
            ListBase.prototype.itemToLabel = function (item) {
                if (this._labelFunction != null)
                    return this._labelFunction(item);

                if (typeof (item) == "string")
                    return item;

                if (item instanceof egret.XML) {
                    try  {
                        if (item[this.labelField].length() != 0)
                            item = item[this.labelField];
                    } catch (e) {
                    }
                } else if (item instanceof Object) {
                    try  {
                        if (item[this.labelField] != null)
                            item = item[this.labelField];
                    } catch (e) {
                    }
                }

                if (typeof (item) == "string")
                    return item;

                try  {
                    if (item !== null)
                        return item.toString();
                } catch (e) {
                }

                return " ";
            };

            /**
            * 选中或取消选中项目时调用。子类必须覆盖此方法才可设置选中项。
            * @method egret.gui.ListBase#itemSelected
            * @param index {number} 已选中的项目索引。
            * @param selected {boolean} true为选中,false取消选中
            */
            ListBase.prototype.itemSelected = function (index, selected) {
                if (!this.dataGroup)
                    return;
                var renderer = (this.dataGroup.getElementAt(index));
                if (renderer == null)
                    return;
                renderer.selected = selected;
            };

            /**
            * 返回指定索引是否等于当前选中索引
            */
            ListBase.prototype._isItemIndexSelected = function (index) {
                return index == this.selectedIndex;
            };

            /**
            * 提交选中项属性,返回是否成功提交,false表示被取消
            * @method egret.gui.ListBase#commitSelection
            * @param dispatchChangedEvents {boolean}
            * @returns {boolean}
            */
            ListBase.prototype.commitSelection = function (dispatchChangedEvents) {
                if (typeof dispatchChangedEvents === "undefined") { dispatchChangedEvents = true; }
                var maxIndex = this.dataProvider ? this.dataProvider.length - 1 : -1;
                var oldSelectedIndex = this._selectedIndex;
                var e;

                if (!this._allowCustomSelectedItem || this._proposedSelectedIndex != ListBase.CUSTOM_SELECTED_ITEM) {
                    if (this._proposedSelectedIndex < ListBase.NO_SELECTION)
                        this._proposedSelectedIndex = ListBase.NO_SELECTION;
                    if (this._proposedSelectedIndex > maxIndex)
                        this._proposedSelectedIndex = maxIndex;
                    if (this.requireSelection && this._proposedSelectedIndex == ListBase.NO_SELECTION && this.dataProvider && this.dataProvider.length > 0) {
                        this._proposedSelectedIndex = ListBase.NO_PROPOSED_SELECTION;
                        this._dispatchChangeAfterSelection = false;
                        return false;
                    }
                }

                var tmpProposedIndex = this._proposedSelectedIndex;

                if (this._dispatchChangeAfterSelection) {
                    var result = gui.IndexChangeEvent.dispatchIndexChangeEvent(this, gui.IndexChangeEvent.CHANGING, this._selectedIndex, this._proposedSelectedIndex, true);
                    if (!result) {
                        this.itemSelected(this._proposedSelectedIndex, false);
                        this._proposedSelectedIndex = ListBase.NO_PROPOSED_SELECTION;
                        this._dispatchChangeAfterSelection = false;
                        return false;
                    }
                }

                this._selectedIndex = tmpProposedIndex;
                this._proposedSelectedIndex = ListBase.NO_PROPOSED_SELECTION;

                if (oldSelectedIndex != ListBase.NO_SELECTION)
                    this.itemSelected(oldSelectedIndex, false);
                if (this._selectedIndex != ListBase.NO_SELECTION)
                    this.itemSelected(this._selectedIndex, true);

                //子类若需要自身抛出Change事件,而不是在此处抛出,可以设置dispatchChangedEvents为false
                if (dispatchChangedEvents) {
                    if (this._dispatchChangeAfterSelection) {
                        gui.IndexChangeEvent.dispatchIndexChangeEvent(this, gui.IndexChangeEvent.CHANGE, oldSelectedIndex, this._selectedIndex);
                        this._dispatchChangeAfterSelection = false;
                    }
                    gui.UIEvent.dispatchUIEvent(this, gui.UIEvent.VALUE_COMMIT);
                    ;
                }

                return true;
            };

            /**
            * 仅调整选中索引值而不更新选中项,即在提交属性阶段itemSelected方法不会被调用,也不会触发changing和change事件。
            * @method egret.gui.ListBase#adjustSelection
            * @param newIndex {number} 新索引。
            * @param add {boolean} 如果已将项目添加到组件,则为 true;如果已删除项目,则为 false。
            */
            ListBase.prototype.adjustSelection = function (newIndex, add) {
                if (typeof add === "undefined") { add = false; }
                if (this._proposedSelectedIndex != ListBase.NO_PROPOSED_SELECTION)
                    this._proposedSelectedIndex = newIndex;
                else
                    this._selectedIndex = newIndex;
                this.selectedIndexAdjusted = true;
                this.invalidateProperties();
            };

            /**
            * 数据项添加
            * @method egret.gui.ListBase#itemAdded
            * @param index {number}
            */
            ListBase.prototype.itemAdded = function (index) {
                if (this._doingWholesaleChanges)
                    return;

                if (this.selectedIndex == ListBase.NO_SELECTION) {
                    if (this.requireSelection)
                        this.adjustSelection(index, true);
                } else if (index <= this.selectedIndex) {
                    this.adjustSelection(this.selectedIndex + 1, true);
                }
            };

            /**
            * 数据项移除
            * @method egret.gui.ListBase#itemRemoved
            * @param index {number}
            */
            ListBase.prototype.itemRemoved = function (index) {
                if (this.selectedIndex == ListBase.NO_SELECTION || this._doingWholesaleChanges)
                    return;

                if (index == this.selectedIndex) {
                    if (this.requireSelection && this.dataProvider && this.dataProvider.length > 0) {
                        if (index == 0) {
                            this._proposedSelectedIndex = 0;
                            this.invalidateProperties();
                        } else
                            this._setSelectedIndex(0, false);
                    } else
                        this.adjustSelection(-1, false);
                } else if (index < this.selectedIndex) {
                    this.adjustSelection(this.selectedIndex - 1, false);
                }
            };

            /**
            * 项呈示器被添加
            * @method egret.gui.ListBase#dataGroup_rendererAddHandler
            * @param event {RendererExistenceEvent}
            */
            ListBase.prototype.dataGroup_rendererAddHandler = function (event) {
                var renderer = (event.renderer);

                if (renderer == null)
                    return;

                renderer.addEventListener(egret.TouchEvent.TOUCH_ROLL_OVER, this.item_mouseEventHandler, this);
                renderer.addEventListener(egret.TouchEvent.TOUCH_ROLL_OUT, this.item_mouseEventHandler, this);
            };

            /**
            * 项呈示器被移除
            * @method egret.gui.ListBase#dataGroup_rendererRemoveHandler
            * @param event {RendererExistenceEvent}
            */
            ListBase.prototype.dataGroup_rendererRemoveHandler = function (event) {
                var renderer = (event.renderer);

                if (renderer == null)
                    return;

                renderer.removeEventListener(egret.TouchEvent.TOUCH_ROLL_OVER, this.item_mouseEventHandler, this);
                renderer.removeEventListener(egret.TouchEvent.TOUCH_ROLL_OUT, this.item_mouseEventHandler, this);
            };

            /**
            * 项呈示器鼠标事件
            */
            ListBase.prototype.item_mouseEventHandler = function (event) {
                var type = event.type;
                type = ListBase.TYPE_MAP[type];
                if (this.hasEventListener(type)) {
                    var itemRenderer = (event.currentTarget);
                    this._dispatchListEvent(event, type, itemRenderer);
                }
            };

            /**
            * 抛出列表事件
            * @method egret.gui.ListBase#_dispatchListEvent
            * @param touchEvent {TouchEvent} 相关联的鼠标事件
            * @param type {string} 事件名称
            * @param itemRenderer {IItemRenderer} 关联的条目渲染器实例
            */
            ListBase.prototype._dispatchListEvent = function (touchEvent, type, itemRenderer) {
                var itemIndex = -1;
                if (itemRenderer)
                    itemIndex = itemRenderer.itemIndex;
                else
                    itemIndex = this.dataGroup.getElementIndex((touchEvent.currentTarget));

                var item = this.dataProvider.getItemAt(itemIndex);
                gui.ListEvent.dispatchListEvent(this, type, touchEvent, itemIndex, item, itemRenderer);
            };

            /**
            * 数据源发生改变
            * @method egret.gui.ListBase#dataProvider_collectionChangeHandler
            * @param event {CollectionEvent}
            */
            ListBase.prototype.dataProvider_collectionChangeHandler = function (event) {
                var items = event.items;
                if (event.kind == gui.CollectionEventKind.ADD) {
                    var length = items.length;
                    for (var i = 0; i < length; i++) {
                        this.itemAdded(event.location + i);
                    }
                } else if (event.kind == gui.CollectionEventKind.REMOVE) {
                    length = items.length;
                    for (i = length - 1; i >= 0; i--) {
                        this.itemRemoved(event.location + i);
                    }
                } else if (event.kind == gui.CollectionEventKind.MOVE) {
                    this.itemRemoved(event.oldLocation);
                    this.itemAdded(event.location);
                } else if (event.kind == gui.CollectionEventKind.RESET) {
                    if (this.dataProvider.length == 0) {
                        this._setSelectedIndex(ListBase.NO_SELECTION, false);
                    } else {
                        this.dataProviderChanged = true;
                        this.invalidateProperties();
                    }
                } else if (event.kind == gui.CollectionEventKind.REFRESH) {
                    this._setSelectedIndex(ListBase.NO_SELECTION, false);
                }
            };
            ListBase.NO_SELECTION = -1;

            ListBase.NO_PROPOSED_SELECTION = -2;

            ListBase.CUSTOM_SELECTED_ITEM = -3;

            ListBase.TYPE_MAP = {
                rollOver: "itemRollOver",
                rollOut: "itemRollOut" };
            return ListBase;
        })(gui.SkinnableDataContainer);
        gui.ListBase = ListBase;
        ListBase.prototype.__class__ = "egret.gui.ListBase";
    })(egret.gui || (egret.gui = {}));
    var gui = egret.gui;
})(egret || (egret = {}));


text:
package qlog

import (
	"time"
)

//这里定义和数据库表结构相对应的结构体

//日志记录
type QLogRecord struct {
	Id         string
	Bucket     string
	Date       string
	ReqIp      string
	ReqTime    time.Time
	ReqMethod  string
	ReqPath    string
	ReqProto   string
	StatusCode int
	TotalBytes int
	Referer    string
	UserAgent  string
	Host       string
	Version    string
}

//日志分析状态
type QLogSyncStatus struct {
	Id     string
	Bucket string
	Date   string
	Done   bool
}

//日志同步的配置
type QLogSyncSettings struct {
	Bucket              string
	SaveBucket          string
	SaveBucketDomain    string
	IsSaveBucketPrivate bool
}


text:
title: Video podcast de ViveCodigo 00×10 – Coding Dojo
author: neodevelop
layout: post
date: 2011-12-26
url: /2011/12/26/video-podcast-de-vivecodigo-00x10-coding-dojo/
enclosure:
  - |
    |
        http://s3.amazonaws.com/media.vivecodigo.org/podcast/temporada0/ViveCodigo00x10.mp3
        26528623
        audio/mpeg

categories:
  - Podcast
tags:
  - 'Coding Dojo'
  - 'Vive Codigo'
---
Se ha publicado un nuevo episodio de ViveCodigo, en donde se llevó a cabo un Coding Dojo.

> __Una de las actividades que practican los artesanos de software.__

Si sólo deseas escucharlo entonces:

<audio width="300" height="32" controls="controls"><source src="http://s3.amazonaws.com/media.vivecodigo.org/podcast/temporada0/ViveCodigo00x10.mp3" type="audio/mpeg" /></audio>

El video del podcast:

<iframe src="https://player.vimeo.com/video/34008369" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

[La liga del artículo con los vínculos y demás información][1]

Que lo disfruten!!

[1]: http://vivecodigo.org/2011/12/21/podcast-10-de-la-temporada-0/


text:
layout: page
title: Brown Vision Motors Conference
date: 2016-05-24
author: Frank Frank
tags: weekly links, java
status: published
summary: Mauris ac risus enim. In enim diam, ullamcorper.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 09/27/2016
  endDate: 09/29/2016
  ctyhocn: MVNHHHX
  groupCode: BVMC
published: true
---
Phasellus eu convallis justo, quis feugiat erat. Duis sed diam molestie dolor aliquam placerat eget at mauris. Sed faucibus rutrum libero, quis commodo orci facilisis porttitor. Ut ex odio, rutrum at magna ut, pulvinar rutrum sem. In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus viverra massa sit amet enim ornare egestas.
Maecenas luctus dignissim eros vitae ullamcorper. Nullam bibendum tortor eget semper efficitur. Donec in purus et purus mattis efficitur ullamcorper eget tellus. Sed luctus dolor sit amet suscipit egestas. Ut libero ipsum, mattis quis volutpat a, eleifend accumsan leo. Praesent ut urna lacinia, pellentesque neque et, pharetra lacus. Praesent quis enim nec quam feugiat pellentesque ut in tellus. Quisque fermentum dolor ac risus laoreet, vitae hendrerit justo ullamcorper. Sed congue tellus a turpis porttitor, non tempus purus porttitor. Nulla eget eros eu magna iaculis dictum nec at enim. Mauris rutrum, diam quis dignissim cursus, nunc sapien porttitor tortor, vitae dignissim sem orci quis risus. Pellentesque condimentum mollis ultricies. In hac habitasse platea dictumst.

* Etiam ac diam faucibus, semper lectus non, efficitur elit
* Fusce a nulla nec diam aliquam suscipit
* Aenean suscipit ex nec velit tristique consectetur
* Sed consequat nisi efficitur condimentum accumsan
* Etiam ut ante tincidunt, pellentesque diam non, condimentum nisi
* Ut quis erat et lacus molestie commodo.

Vestibulum dapibus maximus facilisis. Vivamus eu hendrerit lectus. In eleifend eget nibh a cursus. Suspendisse ullamcorper hendrerit augue eu sagittis. Quisque at magna eget erat elementum vulputate. Vivamus aliquet tellus sit amet leo tristique, eu viverra ipsum commodo. Ut ac metus vitae lacus varius luctus ut et lectus. Cras at maximus eros. Pellentesque laoreet ligula id porta consectetur. Curabitur sed dictum ligula.


text:
console.log('iguana connector loading...')

/// ////////////////////////////////////////
// REQUIRES
// Request (for HTTP calls) and xml2js for
// converting xml response to JSON
/// ////////////////////////////////////////
var xml2js = require('xml2js')
var request = require('request')
var common = require('../connectors/common')

/// ////////////////////////////////////////
// VARIABLES
/// ////////////////////////////////////////
var itemSearch = 'Application=Bib&BestMatch=99&FacetedSearch=Yes&Associations=Also&Database=[DB]&ExportByTemplate=Brief&fu=BibSearch&Index=Isbn&Language=eng&NumberToRetrieve=10&RequestType=ResultSet_DisplayList&SearchTechnique=Find&WithoutRestrictions=Yes&TemplateId=[TID]&Profile=Iguana&Request=[ISBN]'
var facetSearch = 'FacetedSearch=[RESULTID]&FacetsFound=&fu=BibSearch'
var reqHeader = { 'Content-Type': 'application/x-www-form-urlencoded' }
var home = 'www.main.cls'

/// ////////////////////////////////////////
// Function: getService
/// ////////////////////////////////////////
exports.getService = function (svc) {
  var service = common.getService(svc)
  service.CatalogueUrl = svc.Url + home
  return service;
}

/// ////////////////////////////////////////
// Function: getLibraries
// Iguana doesn't seem to offer filter by
// library on their advanced search.
// Hmmmmm, do a very general search and get the facets.
/// ////////////////////////////////////////
exports.getLibraries = function (service, callback) {
  var responseLibraries = { service: service.Name, code: service.Code, libraries: [], start: new Date() }

  var getFacets = function (resultId) {
    // Request 2:
    request.post({ url: service.Url + 'Proxy.SearchRequest.cls', jar: true, body: facetSearch.replace('[RESULTID]', resultId), headers: reqHeader, timeout: 30000 }, function (error, msg, response) {
      if (common.handleErrors(callback, responseLibraries, error, msg)) return
      xml2js.parseString(response, function (err, res) {
        if (common.handleErrors(callback, responseLibraries, err)) return
        var facets = res.VubisFacetedSearchResponse.Facets[0].Facet
        if (facets) {
          facets.forEach(function (facet) {
            if (facet.FacetWording[0] == service.LibraryFacet) {
              facet.FacetEntry.forEach(function (location) {
                responseLibraries.libraries.push(location.Display[0])
              })
            }
          })
        }
        common.completeCallback(callback, responseLibraries)
      })
    })
  }

  // Request 1:
  request.post({ url: service.Url + 'Proxy.SearchRequest.cls', jar: true, body: itemSearch.replace('[ISBN]', 'a').replace('Index=Isbn', 'Index=Keywords').replace('[DB]', service.Database).replace('[TID]', 'Iguana_Brief'), headers: reqHeader, timeout: 30000 }, function (error, msg, response) {
    if (common.handleErrors(callback, responseLibraries, error, msg)) return
    xml2js.parseString(response, function (err, res) {
      if (common.handleErrors(callback, responseLibraries, err, msg)) return
      // Some installations support faceted searching and filtering
      if (service.Faceted) {
        var resultId = res['zs:searchRetrieveResponse']['zs:resultSetId'][0]
        getFacets(resultId)
      } else {
        if (res && res['zs:searchRetrieveResponse'] && res['zs:searchRetrieveResponse']['zs:records']) {
          // Loop through the search results and try to get unique entries from holdings data.
          res['zs:searchRetrieveResponse']['zs:records'][0]['zs:record'].forEach(function (record) {
            // Loop through all the holdings records.
            var recData = record['zs:recordData']
            if (recData && recData[0] && recData[0].BibDocument && recData[0].BibDocument[0] && recData[0].BibDocument[0].HoldingsSummary && recData[0].BibDocument[0].HoldingsSummary[0]) {
              recData[0].BibDocument[0].HoldingsSummary[0].ShelfmarkData.forEach(function (item) {
                var lib = item.Shelfmark[0].split(' : ')[0]
                if (responseLibraries.libraries.indexOf(lib) == -1) responseLibraries.libraries.push(lib)
              })
            }
          })
        }
        common.completeCallback(callback, responseLibraries)
      }
    })
  })
}

/// ////////////////////////////////////////
// Function: searchByISBN
/// ////////////////////////////////////////
exports.searchByISBN = function (isbn, lib, callback) {
  var responseHoldings = { service: lib.Name, code: lib.Code, availability: [], start: new Date() }

  // Request 1: Post to the search web service
  request.post({ url: lib.Url + 'Proxy.SearchRequest.cls', body: itemSearch.replace('[ISBN]', isbn).replace('[DB]', lib.Database).replace('[TID]', 'Iguana_Brief'), headers: reqHeader, timeout: 60000 }, function (error, msg, response) {
    if (common.handleErrors(callback, responseHoldings, error, msg)) return
    xml2js.parseString(response, function (err, res) {
      if (common.handleErrors(callback, responseHoldings, error)) return
      if (res && res['zs:searchRetrieveResponse']) var record = res['zs:searchRetrieveResponse']['zs:records'][0]['zs:record']
      if (record) var recordData = record[0]['zs:recordData']
      // Loop through all the holdings records.
      if (recordData && recordData[0] && recordData[0].BibDocument && recordData[0].BibDocument[0] && recordData[0].BibDocument[0].HoldingsSummary && recordData[0].BibDocument[0].HoldingsSummary[0]) {
        recordData[0].BibDocument[0].HoldingsSummary[0].ShelfmarkData.forEach(function (item) {
          var lib = item.Shelfmark[0].split(' : ')[0]
          responseHoldings.availability.push({ library: lib, available: item.Available ? item.Available[0] : 0, unavailable: item.Available == '0' ? 1 : 0 })
        })
      }
      common.completeCallback(callback, responseHoldings)
    })
  })
}


text:
package org.nd4j.linalg.api.ops.impl.transforms.strict;

import lombok.NoArgsConstructor;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.imports.NoOpNameFoundException;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseTransformStrictOp;

import java.util.Collections;
import java.util.List;

@NoArgsConstructor
public class Erf extends BaseTransformStrictOp {

    public Erf(SameDiff sameDiff, SDVariable i_v) {
        this(sameDiff, i_v, false);
    }

    public Erf(SameDiff sameDiff, SDVariable i_v, boolean inPlace) {
        super(sameDiff, i_v, inPlace);
    }

    public Erf(INDArray x, INDArray z) {
        super(x, z);
    }

    public Erf(INDArray x) {
        super(x);
    }

    @Override
    public int opNum() {
        return 45;
    }

    @Override
    public String opName() {
        return "erf";
    }

    @Override
    public String onnxName() {
        throw new NoOpNameFoundException("No onnx op opName found for " + opName());
    }

    @Override
    public String tensorflowName() {
        return "Erf";
    }

    @Override
    public List<SDVariable> doDiff(List<SDVariable> i_v) {
        // Derivative of erf(z) is 2 / sqrt(pi) * e^(-z^2)
        SDVariable gradient = i_v.get(0);
        SDVariable z = arg();
        SDVariable constant = sameDiff.onesLike(gradient).mul(2.0 / Math.sqrt(Math.PI));
        SDVariable ret = constant.mul(sameDiff.math().exp(z.mul(z).mul(-1))).mul(gradient);
        return Collections.singletonList(ret);
    }

}


text:
package com.crunchbang.takshak;

import android.os.Bundle;

import com.actionbarsherlock.app.SherlockActivity;

public class SocialQuizActivity extends SherlockActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String type = getIntent().getExtras().getString(HomeActivity.KEY);

		if (type.equalsIgnoreCase("social")) {
			setContentView(R.layout.social_layout);
		} else if (type.equalsIgnoreCase("nozione")) {
			setContentView(R.layout.nozione_layout);
		}

	}
}


text:
using UnityEngine;
using UnityEngine.UI;

public class TankShooting : MonoBehaviour
{
    public Rigidbody m_Shell;                   // Prefab of the shell.
    public Transform m_FireTransform;           // A child of the tank where the shells are spawned.
    public Slider m_AimSlider;                  // A child of the tank that displays the current launch force.
    public AudioSource m_ShootingAudio;         // Reference to the audio source used to play the shooting audio. NB: different to the movement audio source.
    public AudioClip m_ChargingClip;            // Audio that plays when each shot is charging up.
    public AudioClip m_FireClip;                // Audio that plays when each shot is fired.
    public float m_MinLaunchForce = 15f;        // The force given to the shell if the fire button is not held.
    public float m_MaxLaunchForce = 30f;        // The force given to the shell if the fire button is held for the max charge time.
    public float m_MaxChargeTime = 0.75f;       // How long the shell can charge for before it is fired at max force.

    private float m_CurrentLaunchForce;         // The force that will be given to the shell when the fire button is released.
    private float m_ChargeSpeed;                // How fast the launch force increases, based on the max charge time.
    private bool m_Charging;

	public bool IsCharging
	{
		get { return m_Charging; }
	}

    private void OnEnable()
    {
        // When the tank is turned on, reset the launch force and the UI
        m_CurrentLaunchForce = m_MinLaunchForce;
        m_AimSlider.value = m_MinLaunchForce;
    }

    private void Start ()
    {
        // The rate that the launch force charges up is the range of possible forces by the max charge time.
        m_ChargeSpeed = (m_MaxLaunchForce - m_MinLaunchForce) / m_MaxChargeTime;
    }

	public void BeginChargingShot()
	{
		if (m_Charging) return;

		m_CurrentLaunchForce = m_MinLaunchForce;

		// Change the clip to the charging clip and start it playing.
		m_ShootingAudio.clip = m_ChargingClip;
		m_ShootingAudio.Play();

		m_Charging = true;
	}

	public void FireChargedShot()
	{
		if (!m_Charging) return;

		Fire();
		m_Charging = false;
	}

	private void Update()
	{
		if (m_Charging)
		{
			m_CurrentLaunchForce = Mathf.Min(m_MaxLaunchForce, m_CurrentLaunchForce + m_ChargeSpeed*Time.deltaTime);
			m_AimSlider.value = m_CurrentLaunchForce;
		}
		else
		{
			m_AimSlider.value = m_MinLaunchForce;
		}
	}

    private void Fire ()
    {
        // Create an instance of the shell and store a reference to it's rigidbody.
        Rigidbody shellInstance =
            Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) as Rigidbody;

        // Set the shell's velocity to the launch force in the fire position's forward direction.
        shellInstance.velocity = m_CurrentLaunchForce * m_FireTransform.forward;

        // Change the clip to the firing clip and play it.
        m_ShootingAudio.clip = m_FireClip;
        m_ShootingAudio.Play ();

        // Reset the launch force.  This is a precaution in case of missing button events.
        m_CurrentLaunchForce = m_MinLaunchForce;
    }
}


text:
package org.springframework.autobuilds.ejbtest.simple.ejb;

import junit.framework.Test;
import junit.framework.TestCase;

import org.apache.cactus.ServletTestSuite;
import org.springframework.autobuilds.ejbtest.Constants;
import org.springframework.autobuilds.ejbtest.simple.SimpleService;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;

/**
 * Test calling into a CMT EJB which then calls into a POJO which is NOT wrapped
 * with Spring transactions, including one test in which that POJO calls into another
 * another POJO which does persistence via Hibernate.
 *
 * @author colin sampaleanu
 */
public class CmtWrappedEjbDelegatingToSpringTxWrappedPojoTests extends TestCase {

	// --- statics
	public static final String SERVICE_ID_LOCAL_PROXY = "simpleWithCmtAndSpringTx";

	// --- attributes

	BeanFactoryReference bfr;

	// --- methods

	public static Test suite() {
		ServletTestSuite suite = new ServletTestSuite();
		suite.addTestSuite(CmtWrappedEjbDelegatingToSpringTxWrappedPojoTests.class);
		return suite;
	}

	protected void setUp() throws Exception {
		bfr = ContextSingletonBeanFactoryLocator.getInstance().useBeanFactory(
				Constants.SERVICE_LAYER_CONTEXT_ID);
	}

	protected void tearDown() throws Exception {
		bfr.release();
	}

	public void testCmtDelegatingToOneLayerOfSpringTx() {
		SimpleService ejb = (SimpleService) bfr.getFactory().getBean(SERVICE_ID_LOCAL_PROXY);
		ejb.echo("hello");
		ejb.echo("hello2");
		ejb.echo2("whatever");
		ejb.echo2("whatever2");
	}

	public void xxxtestCmtDelegatingToTwoLayersOfSpringTxIncludingHibernatePersistence() {
		SimpleService ejb = (SimpleService) bfr.getFactory().getBean(SERVICE_ID_LOCAL_PROXY);
		ejb.echo("hello");
		ejb.echo("hello2");
		ejb.echo2("whatever");
		ejb.echo2("whatever2");
		ejb.echo3("goodbye");
		ejb.echo3("goodbye2");
	}

	public void xxxtestSingleMultiLayerTxCallStack() {
		SimpleService ejb = (SimpleService) bfr.getFactory().getBean(SERVICE_ID_LOCAL_PROXY);
		ejb.echo3("goodbye");
	}

}


text:
from django.core import urlresolvers
from django.contrib import admin
from django.template import defaultfilters
from .. import models

# Helpers ##########

class ModelAdmin(admin.ModelAdmin):
    """ deletion of top level objects is evil """
    def has_delete_permission(self, request, obj=None):
        return False

    # we probably don't want to add anything through the interface
    def has_add_permission(self, request):
        return False

class ReadOnlyTabularInline(admin.TabularInline):
    def has_add_permission(self, request):
        return False
    can_delete = False

class IdentifierInline(admin.TabularInline):
    fields = readonly_fields = ('identifier', 'scheme')
    extra = 0
    can_delete = False
    verbose_name = "ID from another system"
    verbose_name_plural = "IDs from other systems"

class LinkInline(admin.TabularInline):
    fields = ('url', 'note')
    extra = 0

class ContactDetailInline(admin.TabularInline):
    fields = ('type', 'value', 'note', 'label')
    extra = 0
    verbose_name = "Piece of contact information"
    verbose_name_plural = "Contact information"

class OtherNameInline(admin.TabularInline):
    fields = ('name', 'note', 'start_date', 'end_date')
    extra = 0
    verbose_name = "Alternate name"
    verbose_name_plural = "Alternate names"

# class MimetypeLinkInline(admin.TabularInline):
#    fields = ('media_type', 'url')
# class RelatedEntityInline(admin.TabularInline):
#    fields = ('name', 'entity_type', 'organization', 'person')

# Divisions & Jurisdictions ##########

@admin.register(models.Division)
class DivisionAdmin(ModelAdmin):
    list_display = ('name', 'id')
    search_fields = list_display
    fields = readonly_fields = ('id', 'name', 'redirect', 'country')
    ordering = ('id',)

class LegislativeSessionInline(ReadOnlyTabularInline):
    model = models.LegislativeSession
    readonly_fields = ('identifier', 'name')
    ordering = ('-identifier',)

@admin.register(models.Jurisdiction)
class JurisdictionAdmin(ModelAdmin):
    list_display = ('name', 'id')
    readonly_fields = fields = ('id', 'name', 'division', 'classification',
                                'feature_flags', 'extras')
    fields = readonly_fields + ('url', )
    ordering = ('id',)
    inlines = [LegislativeSessionInline]

# Organizations and Posts #############

class OrganizationIdentifierInline(IdentifierInline):
    model = models.OrganizationIdentifier

class OrganizationNameInline(OtherNameInline):
    model = models.OrganizationName

class OrganizationContactDetailInline(ContactDetailInline):
    model = models.OrganizationContactDetail

class OrganizationLinkInline(LinkInline):
    model = models.OrganizationLink

class OrganizationSourceInline(LinkInline):
    model = models.OrganizationSource

class PostInline(admin.TabularInline):
    """ a read-only inline for posts here, with links to the real thing """
    model = models.Post
    extra = 0
    fields = readonly_fields = ('label', 'role')
    ordering = ('label',)
    can_delete = False
    show_change_link = True

class OrgMembershipInline(ReadOnlyTabularInline):
    model = models.Membership
    fk_name = "organization"
    readonly_fields = ('person', 'post')
    fields = ('person', 'post', 'label', 'role', 'start_date', 'end_date', 'id')
    extra = 0
    can_delete = True

@admin.register(models.Organization)
class OrganizationAdmin(ModelAdmin):
    readonly_fields = ('id', 'classification', 'parent', 'jurisdiction', 'extras')
    fields = (
        'name', 'jurisdiction', 'id', 'classification',
        'parent', ('founding_date', 'dissolution_date'),
        'image', 'extras')
    search_fields = ('name',)

    inlines = [
        OrganizationIdentifierInline,
        OrganizationNameInline,
        OrganizationContactDetailInline,
        OrganizationLinkInline,
        OrganizationSourceInline,
        PostInline,
        OrgMembershipInline,
    ]

    def get_org_name(self, obj):
        parent = obj.parent
        if parent:
            return "{org} ({parent})".format(org=obj.name, parent=parent.name)
        return obj.name
    get_org_name.short_description = "Name"
    get_org_name.allow_tags = True
    get_org_name.admin_order_field = "name"

    def get_jurisdiction(self, obj):
        jurisdiction = obj.jurisdiction
        if jurisdiction:
            admin_url = urlresolvers.reverse('admin:opencivicdata_jurisdiction_change',
                                             args=(jurisdiction.pk,))
            tmpl = '%s'
            return tmpl % (admin_url, jurisdiction.name)

        return "(none)"

    get_jurisdiction.short_description = 'Jurisdiction'
    get_jurisdiction.allow_tags = True
    get_jurisdiction.admin_order_field = 'jurisdiction__name'

    list_select_related = ('jurisdiction',)
    list_display = ('get_org_name', 'get_jurisdiction', 'classification')
    ordering = ('name',)

class PostContactDetailInline(ContactDetailInline):
    model = models.PostContactDetail

class PostLinkInline(LinkInline):
    model = models.PostLink

@admin.register(models.Post)
class PostAdmin(ModelAdmin):
    readonly_fields = ('id', 'label', 'organization', 'division', 'extras', 'role')
    fields = readonly_fields + (('start_date', 'end_date'), )
    list_display = ('label', 'organization', 'division')
    ordering = ('organization__name',)
    inlines = [
        PostContactDetailInline,
        PostLinkInline,
    ]
    search_fields = ('organization__name', 'label')

# People & Memberships #######

class PersonIdentifierInline(IdentifierInline):
    model = models.PersonIdentifier

class PersonNameInline(OtherNameInline):
    model = models.PersonName

class PersonContactDetailInline(ContactDetailInline):
    model = models.PersonContactDetail

class PersonLinkInline(LinkInline):
    verbose_name = "Related link"
    verbose_name_plural = "Related links"
    model = models.PersonLink

class PersonSourceInline(LinkInline):
    verbose_name = "Source link"
    verbose_name_plural = "Source links"
    model = models.PersonSource

class MembershipInline(ReadOnlyTabularInline):
    model = models.Membership
    readonly_fields = ('organization', 'post')
    fields = ('organization', 'post', 'label', 'role', 'start_date', 'end_date', 'id')
    extra = 0
    can_delete = True

# TODO field locking
@admin.register(models.Person)
class PersonAdmin(ModelAdmin):
    search_fields = ['name']
    readonly_fields = ('id', 'name', 'extras')
    fields = (
        'name', 'id', 'image',
        ('birth_date', 'death_date'),
        ('gender', 'national_identity', 'sort_name', 'summary'),
        'biography', 'extras',
    )
    ordering = ('name',)

    inlines = [
        PersonIdentifierInline,
        PersonNameInline,
        PersonContactDetailInline,
        PersonLinkInline,
        PersonSourceInline,
        MembershipInline
    ]

    def get_memberships(self, obj):
        memberships = obj.memberships.select_related('organization__jurisdiction')
        html = []
        SHOW_N = 5
        for memb in memberships[:SHOW_N]:
            org = memb.organization
            admin_url = urlresolvers.reverse('admin:opencivicdata_organization_change',
                                             args=(org.pk,))
            tmpl = '%s%s\n'
            html.append(tmpl % (
                admin_url,
                (memb.organization.jurisdiction.name +
                 ": " if memb.organization.jurisdiction else ''),
                memb.organization.name))
        more = len(memberships) - SHOW_N
        if 0 < more:
            html.append('And %d more' % more)
        return '
'.join(html)

    get_memberships.short_description = 'Memberships'
    get_memberships.allow_tags = True

    list_select_related = ('memberships',)
    list_display = ('name', 'id', 'get_memberships')

# Bills ################

class BillAbstractInline(ReadOnlyTabularInline):
    model = models.BillAbstract
    readonly_fields = ('abstract', 'note')
    can_delete = False

class BillTitleInline(ReadOnlyTabularInline):
    model = models.BillTitle
    readonly_fields = ('title', 'note')
    can_delete = False

class BillIdentifierInline(IdentifierInline):
    model = models.BillIdentifier

class BillActionInline(ReadOnlyTabularInline):
    model = models.BillAction

    def get_related_entities(self, obj):
        ents = obj.related_entities.all()
        # this seems to be a uuid problem, get
        # rid of the below return stmt when uuids are fixed
        return None
        ent_list = [e.name for e in ents]
        return ', '.join(ent_list)

    get_related_entities.short_description = 'Related Entities'
    get_related_entities.allow_tags = True

    list_select_related = ('BillActionRelatedEntity',)
    readonly_fields = ('date', 'organization', 'description', 'get_related_entities')

class RelatedBillInline(ReadOnlyTabularInline):
    model = models.RelatedBill
    fk_name = 'bill'
    readonly_fields = fields = ('identifier', 'legislative_session', 'relation_type')
    extra = 0

class BillSponsorshipInline(ReadOnlyTabularInline):
    model = models.BillSponsorship
    readonly_fields = fields = ('name', 'primary', 'classification')
    extra = 0

class BillDocumentInline(ReadOnlyTabularInline):
    model = models.BillDocument

    def get_link(self, obj):
        return None  # TODO: get rid of this line when uuid issue fixed
        link = obj.links.first()
        return link.url

    get_link.short_description = 'Link'
    get_link.allow_tags = True

    list_select_related = ('BillDocumentLink',)
    readonly_fields = ('note', 'date', 'get_link')

class BillVersionInline(ReadOnlyTabularInline):
    model = models.BillVersion

    def get_link(self, obj):
        return None   # TODO: get rid of this line when uuid issue fixed
        link = obj.links.first()
        return link.url

    get_link.short_description = 'Link'
    get_link.allow_tags = True

    list_select_related = ('BillVersionLink',)
    readonly_fields = ('note', 'date', 'get_link')

class BillSourceInline(ReadOnlyTabularInline):
    fields = ('url', 'note')
    model = models.BillSource

@admin.register(models.Bill)
class BillAdmin(ModelAdmin):
    readonly_fields = fields = (
        'identifier', 'legislative_session', 'bill_classifications',
        'from_organization', 'title', 'id', 'extras')
    search_fields = ['identifier', 'title']
    list_select_related = (
        'sources',
        'legislative_session',
        'legislative_session__jurisdiction',
    )
    inlines = [
        BillAbstractInline,
        BillTitleInline,
        BillIdentifierInline,
        BillActionInline,
        BillSponsorshipInline,
        BillSourceInline,
        RelatedBillInline,
        BillVersionInline,
        BillDocumentInline,
    ]

    def bill_classifications(self, obj):
        return ", ".join(obj.classification)

    def get_jurisdiction_name(self, obj):
        return obj.legislative_session.jurisdiction.name
    get_jurisdiction_name.short_description = 'Jurisdiction'

    def get_session_name(self, obj):
        return obj.legislative_session.name
    get_session_name.short_description = 'Session'
    get_session_name.admin_order_field = 'legislative_session__name'

    def source_link(self, obj):
        source = obj.sources.filter(url__icontains="legislationdetail").get()
        tmpl = u'View source'
        return tmpl.format(source.url)
    source_link.short_description = 'View source'
    source_link.allow_tags = True

    def get_truncated_sponsors(self, obj):
        spons = ', '.join(s.name for s in obj.sponsorships.all()[:5])
        return defaultfilters.truncatewords(spons, 10)
    get_truncated_sponsors.short_description = 'Sponsors'

    def get_truncated_title(self, obj):
        return defaultfilters.truncatewords(obj.title, 25)
    get_truncated_title.short_description = 'Title'

    list_display = (
        'identifier', 'get_jurisdiction_name',
        'get_session_name', 'get_truncated_sponsors',
        'get_truncated_title', 'source_link')

    list_filter = ('legislative_session__jurisdiction__name',)


text:
module ActionController
  class Base
    def rescue_with_handler_with_decorator_view_context(exception)
      ActiveDecorator::ViewContext.push(view_context)
      rescue_with_handler_without_decorator_view_context(exception)
    ensure
      ActiveDecorator::ViewContext.pop
    end
    alias_method_chain :rescue_with_handler, :decorator_view_context
  end
end


text:
Each exercise has its own directory preloaded with shaders for you to edit.
Generally, there will be
a link like this one that *will
open that directory for you*. If the link does not work for you, you can find
the files for each exercise in the `answers/` directory.

In this exercise's directory you'll find a file called `hello.glsl` that
exports a function called `brightness`. Currently it returns `-1.0` – simply
change it to `1.0` to pass the exercise.

***

## How Shader School Works

For each lesson there is an **expected** and an **actual** shader. The former is
provided by us, and your goal is to simply modify the **actual** shader so that
it matches the expected one.

### The Diff Tool

You'll notice some buttons and a slider below: these are for modifying how the
two are displayed so that you can easily track down any differences between
them.

By default, "slide" mode will be enabled, which will display your
shader's output on the left and our shader's on the right. "Onion" mode will
allow you to overlay the two – in both cases, you can use the slider to adjust
how much is displayed of either the actual or expected output. There's also
"diff" mode, which will display pixels of different values brighter than the
others. If they're exactly the same, they'll be black. Here,
you can use the slider to adjust the sensitivity of the the comparison.

### Verifying the Lesson

Once you're confident that the two shaders are equivalent, you can click the
green icon above to verify (and hopefully, pass!) the lesson.


text:
This is Python Bytes, Python headlines and news deliver directly to your earbuds: episode 7, recorded on Wednesday, January 4th.

In this episode we discuss Python 3.6 being release, a blazing Python web framework called Sanic, how we are failing our open source infrastructure, and more. [more]

This episode was brought to you by [Rollbar: they help you take the pain out of errors](http://rollbar.com/pythonbytes).

**#1 (Brian)**:  **Python 3.6 is officially released**

- Dec 23 Announcement on blog.python.org: [http://blog.python.org/2016/12/python-360-is-now-available.html](http://blog.python.org/2016/12/python-360-is-now-available.html)
- What's new article on docs.python.org: [https://docs.python.org/3.6/whatsnew/3.6.html](https://docs.python.org/3.6/whatsnew/3.6.html)

Here's a few more articles:

- Python 3.6 is packed with goodness - Serdar Yegulalp -  InfoWorld
  - [http://www.infoworld.com/article/3149782/application-development/python-36-is-packed-with-goodness.html](http://www.infoworld.com/article/3149782/application-development/python-36-is-packed-with-goodness.html)
  - A list of cool things in Python 3.6
    - async/await in more places
    - Improved memory usage and speed
    - frame evaluation API to provide better support for JITs, tracers, debuggers
    - secrets module for common security-related functions such as generating tokens
- One thing that could stop a team from switching to Python 3 would be that they looked into it once, and a package they needed was not ported yet. That's different now, most are ported, or have been replaced with some other way.
- Adopt Python 3 - Dibya Chakravorty - on Medium
  - [https://medium.com/broken-window/python-3-support-for-third-party-libraries-dcd7a156e5bd](https://medium.com/broken-window/python-3-support-for-third-party-libraries-dcd7a156e5bd)
  - A discussion of packages that support Python 2 and 3, those that are 2 only, those that are 3 only.
  - Two lists of most downloaded packages and their py3 readiness:
    - Wall of superpowers: [http://python3wos.appspot.com/](http://python3wos.appspot.com/), 187/200 = 93.5%
    - Python 3 readiness: [http://py3readiness.org/](http://py3readiness.org/), 341/360 = 94.7%
  - Go further:
    - all pypi packages that are stable and active (at least one release in 2016), about 6000 packages
    - total python 3 coverage is 72%
    - 14% are Python 3 only
    - 28% are Python 2 only
    - of the 28%, author estimates only 25% of the remaining packages would be difficult to port, based on their size, and included that list.
    - Also entire code for this article is in an iPython notebook:[https://github.com/gutfeeling/pypi_explorer/blob/master/pypi_database/analysis.ipynb](https://github.com/gutfeeling/pypi_explorer/blob/master/pypi_database/analysis.ipynb)

**#2 (Michael)**
**Roads and Bridges: The Unseen Labor Behind Our Digital Infrastructure by Nadia Eghbal**
[http://www.fordfoundation.org/library/reports-and-studies/roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure](http://www.fordfoundation.org/library/reports-and-studies/roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure)

- From The Ford Foundation, 14 JULY 2016
- Features Eric Holscher from Read the Docs & Donald Stufft from PyPI
- Discussed on Talk Python episode [#84: Are we failing to fund Python's core infrastructure?](https://talkpython.fm/episodes/show/84/are-we-failing-to-fund-python-s-core-infrastructure)
- Some highlights from the 149 page report:
  - Our modern society—everything  from hospitals to stock markets to  newspapers to social media—runs on  software. But take a closer look, and  you'll find that the tools we use to build  software are buckling under demand. (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.4)
  - No individual company or organization is incentivized to address the  problem alone, because open source code is a public good. (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.9)
  - By 2014, two-thirds of all Web servers were using OpenSSL, enabling  websites to securely pass credit card and other sensitive information  over the Internet. (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.11)
  - Institutional efforts to support digital  infrastructure: There are some institutional efforts to collectively organize and help  support open source projects. Some are independent software  foundations; other sources of support come from software companies themselves. Administrative support and fiscal sponsorship Several foundations provide organizational support, such as fiscal  sponsorship, to open source projects: in other words, taking care of  the non-coding tasks that many developers would prefer not to do (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.109)
  - Of Heartbleed, Marquess wrote, "The mystery is not that a few over-worked volunteers missed this bug; the mystery is why it hasn't  happened more often." (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.13)
  - Heartbleed, had been included in a 2011  update. It had gone unnoticed for years. Heartbleed could allow any  sophisticated hacker to capture secure information being passed to  vulnerable web servers, including passwords, credit card information,  and other sensitive data (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.13)
  - People expressed their support by sending donations to the foundation. Although Marquess was grateful for their enthusiasm, the first  round of donations came out to roughly $9,000: not nearly enough  to sustain a team. (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.13)
  - After Heartbleed, OpenSSL finally got more of the funding it  needed—at least for now. They currently have enough money to pay  four full-time employees for three years. But a year and a half into  that funding, Marquess isn't sure what will come next. (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.14)
  - Free software makes it exponentially cheaper  and easier to build software (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.23)
  - Free software is directly responsible for  today's current startup renaissance (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.24)
  - Software not getting the necessary  maintenance it needs Building digital infrastructure in a haphazard fashion means that all  software gets built more slowly and inefficiently. One example of  this can be found in the history of Python infrastructure. An important infrastructure project for Python developers is called setuptools. (roads-and-bridges-the-unseen-labor-behind-our-digital-infrastructure, p.80)

**#3 (Brian)**: **Matplotlib 2.0.0 rc2 was released by Thomas Caswell**
- install instructions: [http://matplotlib.org/style_changes.html](http://matplotlib.org/style_changes.html)
- List of top level changes in release history on github
-[https://github.com/matplotlib/matplotlib/releases](https://github.com/matplotlib/matplotlib/releases)
- Changes to the default style - matplotlib.org
- [http://matplotlib.org/2.0.0rc2/users/dflt_style_changes.html](http://matplotlib.org/2.0.0rc2/users/dflt_style_changes.html)
- Post visually shows all of the new changes.
- What's new in matplotlib 2.0 - also on [http://matplotlib.org](matplotlib.org)
- [http://matplotlib.org/2.0.0rc2/users/whats_new.html](http://matplotlib.org/2.0.0rc2/users/whats_new.html)

**#4 (Michael)**
**Introduction to MongoDB and Python**
[https://realpython.com/blog/python/introduction-to-mongodb-and-python/](https://realpython.com/blog/python/introduction-to-mongodb-and-python/)

- SQL vs NoSQL
- PyMongo
  - Inserting and querying data
- MongoEngine
  - Classes
  - Constraints
  - OOP
- Michael's 1.5 hour presentation at Software Architect conference in London: [Applied NoSQL with MongoDB and Python](https://www.youtube.com/watch?v=_r7ozqiTN2k)

**#5: (Brian)**: **Introducing Maya: Datetimes for Humans**
[https://www.kennethreitz.org/essays/introducing-maya-datetimes-for-humans](https://www.kennethreitz.org/essays/introducing-maya-datetimes-for-humans)
- Working with dates is harder than it should be. Kenneth has proven that he understands how to make reasonable interfaces to hide complicated things.

From "why is this useful?" section

- All timezone algebra will behave identically on all machines, *regardless of system locale*.
- Complete symmetric import and export of both **ISO 8601** and **RFC 2822** datetime stamps.
- Fantastic parsing of both dates written for/by humans and machines (**maya.when()** *vs.* **maya.parse()**).
- Support for human slang, both import and export (e.g. 'an hour ago').
- Datetimes can very easily be generated, with our without timezone information attached (naive).
- This library is based around epoch time, but dates before Jan 1 1970 are indeed supported, via negative integers.

**#6 (Michael)**: **Sanic: Python 3.5+ web server that's written to go fast**
[https://github.com/channelcat/sanic](https://github.com/channelcat/sanic)

- Sanic is a Flask-like Python 3.5+ web server that's written to go fast. It's based on the work done by the amazing folks at magicstack, and was inspired by this article: [https://magic.io/blog/uvloop-blazing-fast-python-networking/](https://magic.io/blog/uvloop-blazing-fast-python-networking/).
- On top of being Flask-like, Sanic supports async request handlers. This means you can use the new shiny async/await syntax from Python 3.5, making your code non-blocking and speedy.

A basic action method

    @app.route("/")
    async def test(request):  # async def !!!
        return json({ "hello": "world" })

- Performance numbers:
    - | Server  | Implementation      | Requests/sec | Avg Latency |
    - | Sanic   | Python 3.5 + uvloop |       33,342 |      2.96ms |
    - | Bottle  | gunicorn + meinheld |       13,596 |      7.36ms |
    - | Flask   | gunicorn + meinheld |        4,988 |     20.08ms |
    - | Aiohttp | Python 3.5 + uvloop |        2,979 |     33.42ms |
    - | Tornado | Python 3.5          |        2,138 |     46.66ms |


text:
{% load xextends %}

{% xextends "admin/members/base.html" with tertiary_nav="tags" %}
{% load datetime %}

{% block admin_members_content %}

        {% if tags.count > 0 %}

                        Tag
                        Number of uses

                    {% for tag in tags %}

                                {{tag.tag}}

                            {{tag.users.count}}

                                {% if tag.users.count == 0 %}

                                {% endif %}

                    {% endfor %}

        {% else %}

No tags have been created yet. Why not create one?

        {% endif %}

{% endblock %}

{% block secondary_content %}

Tags

Tags allow you to mark members so that they can be tracked and filtered. This can be used with tracking links, emails, and other places where you want to target specific users.

 New Tag

{% endblock %}


text:
<measure>
  <schema_version>3.0</schema_version>
  <name>enable_dcv_and_replace_fan_with_vfd</name>
  <uid>c40878ac-f0f3-4600-98d6-d43af9a8ac1c</uid>
  <version_id>cb8fc838-7cb3-4ab6-a4d5-72e9c28ea0f6</version_id>
  <version_modified>20160301T075223</version_modified>
  <xml_checksum>266557E5</xml_checksum>
  <class_name>EnableDCVAndReplaceFanWithVFD</class_name>
  <display_name>Add DCV to each airloop and a VFD fan</display_name>
  <description>Does what it says</description>
  <modeler_description>does stuff like measure ruby</modeler_description>
  <arguments>
    <argument>
      <name>loop</name>
      <display_name>Select the Air Loop to affect, leave blank to affect all</display_name>
      <description>Select '------ All airLoopHVACs -------' to affect all loops'</description>
      <type>Choice</type>
      <required>true</required>
      <model_dependent>false</model_dependent>
      <default_value>{00000000-0000-0000-0000-000000000000}</default_value>
      <choices>
        <choice>
          <value>{00000000-0000-0000-0000-000000000000}</value>
          <display_name>------ All airLoopHVACs -------</display_name>
        </choice>
      </choices>
    </argument>
    <argument>
      <name>has_DCV</name>
      <display_name>Demand Controlled Ventilation?</display_name>
      <type>Boolean</type>
      <required>false</required>
      <model_dependent>false</model_dependent>
      <default_value>false</default_value>
      <choices>
        <choice>
          <value>true</value>
          <display_name>true</display_name>
        </choice>
        <choice>
          <value>false</value>
          <display_name>false</display_name>
        </choice>
      </choices>
    </argument>
    <argument>
      <name>has_VFD</name>
      <display_name>Include a Variable Volume Fan?</display_name>
      <type>Boolean</type>
      <required>false</required>
      <model_dependent>false</model_dependent>
      <default_value>false</default_value>
      <choices>
        <choice>
          <value>true</value>
          <display_name>true</display_name>
        </choice>
        <choice>
          <value>false</value>
          <display_name>false</display_name>
        </choice>
      </choices>
    </argument>
  </arguments>
  <provenances/>
  <tags>
    <tag>HVAC.Ventilation</tag>
  </tags>
  <attributes>
    <attribute>
      <name>Measure Type</name>
      <value>ModelMeasure</value>
      <datatype>string</datatype>
    </attribute>
    <attribute>
      <name>Intended Software Tool</name>
      <value>Apply Measure Now</value>
      <datatype>string</datatype>
    </attribute>
    <attribute>
      <name>Intended Software Tool</name>
      <value>OpenStudio Application</value>
      <datatype>string</datatype>
    </attribute>
    <attribute>
      <name>Intended Software Tool</name>
      <value>Parametric Analysis Tool</value>
      <datatype>string</datatype>
    </attribute>
  </attributes>
  <files>
    <file>
      <filename>example_model.osm</filename>
      <filetype>osm</filetype>
      <usage_type>test</usage_type>
      <checksum>C4F35230</checksum>
    </file>
    <file>
      <filename>enable_dcv_and_vfd_fan_test.rb</filename>
      <filetype>rb</filetype>
      <usage_type>test</usage_type>
      <checksum>2C361643</checksum>
    </file>
    <file>
      <version>
        <software_program>OpenStudio</software_program>
        <identifier>1.7.0</identifier>
        <min_compatible>1.7.0</min_compatible>
      </version>
      <filename>measure.rb</filename>
      <filetype>rb</filetype>
      <usage_type>script</usage_type>
      <checksum>F8EC7B73</checksum>
    </file>
  </files>
</measure>


text:
using System;

namespace Platinum.Validation
{
    /// <summary />
    [AttributeUsage( AttributeTargets.Property, AllowMultiple = false )]
    public class TotalDigitsAttribute : Attribute, IValidationRule
    {
        /// <summary />
        public TotalDigitsAttribute( int maxTotalDigits )
        {
            this.MaxTotalDigits = maxTotalDigits;
        }

        /// <summary>
        /// Gets the maximum number of decimal digits.
        /// </summary>
        public int MaxTotalDigits
        {
            get;
            private set;
        }

        /// <summary />
        public void Validate( ValidationContext context, ValidationResult result, object value )
        {
            #region Validations

            if ( context == null )
                throw new ArgumentNullException( nameof( context ) );

            if ( result == null )
                throw new ArgumentNullException( nameof( result ) );

            #endregion

            if ( value == null )
                return;

            // TODO: What for float/double?
            decimal v = (decimal) value;
            int dd = Math.TotalDigits( v );

            if ( dd > this.MaxTotalDigits )
            {
                ValidationException vex = new ValidationException( ER.TotalDigits_Max, context.Path, context.Property, this.MaxTotalDigits );
                result.AddError( vex );
            }
        }
    }
}


text:
import Ember from 'ember';
import { module, test, skip } from 'qunit';
import { withChai } from 'ember-cli-chai/qunit';
import moment from 'moment';

import {
  make, makeList, build,
  mockFindAll, mockFindRecord,
  mockSetup, mockTeardown
} from 'ember-data-factory-guy';

import moduleForAcceptance from 'aeonvera/tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | At The Door | Events | POS | Navigation', {
  beforeEach() { mockSetup({ logLevel: 1, mockjaxLogLevel: 4 }); },
  afterEach() { mockTeardown(); }
});

async function setup(event) {
  authenticateSession();
  await visit(`/dashboard/event-at-the-door/${event.id}`)
}

async function toPOS(event) {
  await visit(`/dashboard/event-at-the-door/${event.id}/a-la-carte`);
}

function makeEvent() {
  const competitions = makeList('competition', 3);
  const packages = makeList('package', 4)
  const event = make('event', { competitions, packages });
  mockFindRecord('event').returns({ model: event });
  return event;
}

test('navigate to the at the door home', withChai(async expect => {
  const event = makeEvent();
  await setup(event);

  expect(currentRouteName()).to.eq('event-at-the-door.index');
}));

test('navigate to the pos', withChai(async expect => {
  const event = makeEvent();
  await setup(event);
  await toPOS(event);

  expect(currentRouteName()).to.eq('event-at-the-door.a-la-carte.index');
}));

test('navigate to tab on the pos', withChai(async expect => {
  const event = makeEvent();
  await setup(event);
  await visit(`dashboard/event-at-the-door/${event.id}/a-la-carte/competitions`);

  expect(currentRouteName()).to.eq('event-at-the-door.a-la-carte.competitions');
}));

const competitionsSelector = '[data-test-puchasable-items="competitions"]';
const ticketsSelector = '[data-test-puchasable-items="packages"]';
const purchasableItemSelector = '[data-test-puchasable-item]';

test('competitions show up in the competition tab', withChai(async expect => {
  const event = makeEvent();
  await setup(event);
  await visit(`dashboard/event-at-the-door/${event.id}/a-la-carte/competitions`);

  const items = find(`${purchasableItemSelector}`);

  expect(items.length).to.eq(3);
}));

test('packages do not show in the competitions tab', withChai(async expect => {
  const event = makeEvent();
  await setup(event);
  await visit(`dashboard/event-at-the-door/${event.id}/a-la-carte/competitions`);

  const items = find(`${ticketsSelector}`);

  expect(items.length).to.eq(0);
}));


text:
package com.shipdream.lib.android.mvc.view.nav;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.shipdream.lib.android.mvc.MvcFragment;
import com.shipdream.lib.android.mvc.Reason;
import com.shipdream.lib.android.mvc.view.test.R;

import javax.inject.Inject;

public class NavFragmentG extends MvcFragment {
    @Inject
    private ControllerG presenterG;

    private TextView textView;

    @Override
    protected Class getControllerClass() {
        return null;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_mvc_test_nav_e;
    }

    @Override
    public void onViewReady(View view, Bundle savedInstanceState, Reason reason) {
        super.onViewReady(view, savedInstanceState, reason);
        textView = (TextView) view.findViewById(R.id.nav_frag_e_text);

        textView.setText(presenterG.getValue());
    }

    @Override
    public void update() {

    }
}


text:
.class public interface abstract Lcom/android/server/accessibility/AccessibilityInputFilter$Explorer;
.super Ljava/lang/Object;
.source "AccessibilityInputFilter.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/accessibility/AccessibilityInputFilter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "Explorer"
.end annotation

# virtual methods
.method public abstract clear()V
.end method

.method public abstract clear(Landroid/view/MotionEvent;I)V
.end method

.method public abstract onMotionEvent(Landroid/view/MotionEvent;I)V
.end method


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Internal.Runtime.Augments
{
    /// <summary>For internal use only.  Exposes runtime functionality to the Environments implementation in corefx.</summary>
    public static partial class EnvironmentAugments
    {
        private static string GetEnvironmentVariableCore(string variable)
        {
            Debug.Assert(variable != null);
            return Marshal.PtrToStringAnsi(Interop.Sys.GetEnv(variable));
        }

        private static void SetEnvironmentVariableCore(string variable, string value)
        {
            Debug.Assert(variable != null);
            throw new NotImplementedException();
        }

        public static IEnumerable<KeyValuePair<string,string>> EnumerateEnvironmentVariables()
        {
            if ("".Length != 0)
                throw new NotImplementedException(); // Need to return something better than an empty environment block.

            return Array.Empty<KeyValuePair<string,string>>();
        }

        private static void ExitRaw()
        {
            Interop.Sys.Exit(s_latchedExitCode);
        }
    }
}


text:
AffixerDialog::AffixerDialog(QWidget *parent) : QDialog(parent)
{
    m_toplayout = new QGridLayout;
    m_bottomlayout = new QHBoxLayout;
    m_layout = new QVBoxLayout;
    this->setLayout(m_layout);

    m_prefixeslabel = new QLabel("Prefixes:");
    m_toplayout->addWidget(m_prefixeslabel, 0, 0);

    m_rootslabel = new QLabel("Roots:");
    m_toplayout->addWidget(m_rootslabel, 0, 1);

    m_infixeslabel = new QLabel("Infixes:");
    m_toplayout->addWidget(m_infixeslabel, 0, 2);

    m_suffixeslabel = new QLabel("Suffixes:");
    m_toplayout->addWidget(m_suffixeslabel, 0, 3);

    m_previewlabel = new QLabel("Preview:");
    m_toplayout->addWidget(m_previewlabel, 0, 4);

    m_prefixes = new QPlainTextEdit;
    m_prefixes->setPlainText("*");
    m_toplayout->addWidget(m_prefixes, 1, 0);

    m_roots = new QPlainTextEdit;
    m_toplayout->addWidget(m_roots, 1, 1);

    m_infixes = new QPlainTextEdit;
    m_infixes->setPlainText("1");
    m_toplayout->addWidget(m_infixes, 1, 2);

    m_suffixes = new QPlainTextEdit;
    m_suffixes->setPlainText("*");
    m_toplayout->addWidget(m_suffixes, 1, 3);

    m_preview = new QPlainTextEdit;
    m_preview->setReadOnly(true);
    m_toplayout->addWidget(m_preview, 1, 4);

    m_addToStart = new QPushButton("Add to start");
    m_bottomlayout->addWidget(m_addToStart);

    m_addToEnd = new QPushButton("Add to end");
    m_bottomlayout->addWidget(m_addToEnd);

    m_addAtCursor = new QPushButton("Add at cursor position");
    m_bottomlayout->addWidget(m_addAtCursor);

    m_overwritetext = new QPushButton("Replace text");
    m_bottomlayout->addWidget(m_overwritetext);

    m_layout->addLayout(m_toplayout);
    m_layout->addLayout(m_bottomlayout);

    connect(m_prefixes, &QPlainTextEdit::textChanged, this, &AffixerDialog::textEntered);
    connect(m_roots, &QPlainTextEdit::textChanged, this, &AffixerDialog::textEntered);
    connect(m_infixes, &QPlainTextEdit::textChanged, this, &AffixerDialog::textEntered);
    connect(m_suffixes, &QPlainTextEdit::textChanged, this, &AffixerDialog::textEntered);
    connect(m_addToEnd, &QPushButton::clicked, this, &AffixerDialog::emitAddTextToEnd);
    connect(m_addToStart, &QPushButton::clicked, this, &AffixerDialog::emitAddTextToStart);
    connect(m_addAtCursor, &QPushButton::clicked, this, &AffixerDialog::emitAddTextAtCursor);
    connect(m_overwritetext, &QPushButton::clicked, this, &AffixerDialog::emitOverwriteText);
}

void AffixerDialog::textEntered()
{
    m_preview->setPlainText(this->GetWords().join('\n'));
}

void AffixerDialog::emitAddTextToEnd()
{
    emit addText(this->GetWords(), PlaceToAdd::AddToEnd);
}

void AffixerDialog::emitAddTextToStart()
{
    emit addText(this->GetWords(), PlaceToAdd::AddToStart);
}

void AffixerDialog::emitAddTextAtCursor()
{
    emit addText(this->GetWords(), PlaceToAdd::AddAtCursor);
}

void AffixerDialog::emitOverwriteText()
{
    emit addText(this->GetWords(), PlaceToAdd::Overwrite);
}

QStringList AffixerDialog::GetWords()
{
    QStringList words;
    QStringList roots = m_roots->toPlainText().split('\n', QString::SkipEmptyParts);

    QList<QStringList> prefixSlots = GetSlotAffixes(m_prefixes->toPlainText().split('\n', QString::SkipEmptyParts));
    QList<QStringList> infixSlots  = GetSlotAffixes(m_infixes ->toPlainText().split('\n', QString::SkipEmptyParts));
    QList<QStringList> suffixSlots = GetSlotAffixes(m_suffixes->toPlainText().split('\n', QString::SkipEmptyParts));

    QList<QStringList> prefixcombs = CartesianProduct(prefixSlots);
    QList<QStringList> infixcombs  = CartesianProduct(infixSlots);
    QList<QStringList> suffixcombs = CartesianProduct(suffixSlots);

    QList<int> infixnums;
    for (QStringList infixSlot : infixSlots)
    {
        for (QString infix : infixSlot)
        {
            QRegularExpressionMatch match = QRegularExpression(R"re(^(\d+)(.*)$)re").match(infix);
            int num = match.captured(1).toInt();
            if (!infixnums.contains(num)) infixnums.append(num);
        }
    }
    for (QString root : roots)
    {
        for (QStringList prefixcomb : prefixcombs)
        {
            for (QStringList infixcomb : infixcombs)
            {
                QList<std::pair<int, QString>> infixes;
                for (QString infix : infixcomb)
                {
                    QRegularExpressionMatch match = QRegularExpression(R"re(^(\d+)(.*)$)re").match(infix);
                    if (match.hasMatch())
                    {
                        int num = match.captured(1).toInt();
                        infixes.append(std::make_pair(num, match.captured(2)));
                    }
                }

                for (QStringList suffixcomb : suffixcombs)
                {
                    QString word(root);
                    for (std::pair<int, QString> infix : infixes)
                    {
                        word = word.replace(QString::number(infix.first), infix.second);
                    }

                    for (int infixnum : infixnums)
                    {
                        word = word.replace(QString::number(infixnum), "");
                    }

                    word = prefixcomb.join("").append(word);
                    word = word.append(suffixcomb.join(""));
                    words.append(word);
                }
            }
        }
    }

    return words;
}

QList<QStringList> AffixerDialog::GetSlotAffixes(QStringList affixGroups)
{
    QList<QStringList> result;
    for (QString slot : affixGroups)
    {
        QStringList affixes;
        QStringList splitSlots = slot.split(' ', QString::SkipEmptyParts);
        for (QString affix : splitSlots)
        {
            affixes.append((affix == "*") ? "" : affix);
        }
        result.append(affixes);
    }
    return result;
}

QList<QStringList> AffixerDialog::CartesianProduct(QList<QStringList> sequences)
{
    if (sequences.count() == 0) return QList<QStringList>();

    QList<QStringList> result;
    for (QString s : sequences.at(0))
    {
        result.append({ QStringList(s) });
    }

    for (int i = 1; i < sequences.count(); i++)
    {
        QList<QStringList> temp;
        for (QStringList sl : result)
        {
            for (QString s : sequences.at(i))
            {
                QStringList tempStrList = QStringList(sl);
                tempStrList.append(s);
                temp.append(tempStrList);
            }
        }
        result = QList<QStringList>(temp);
    }

    return result;
}