text:
/*
 Combined processedModules by KISSY Module Compiler:

 xtemplate/runtime/commands
 xtemplate/runtime
*/

/**
 * native commands for xtemplate.
 * @author yiminghe@gmail.com
 * @ignore
 */
KISSY.add("xtemplate/runtime/commands", function (S) {
    var commands;

    return commands = {
        'each': function (scopes, config) {
            var params = config.params;
            var param0 = params[0];
            var buffer = '';
            var xcount;
            // if undefined, will emit warning by compiler
            if (param0) {
                // skip array check for performance
                var opScopes = [0, 0].concat(scopes);
                if (S.isArray(param0)) {
                    xcount = param0.length;
                    for (var xindex = 0; xindex < xcount; xindex++) {
                        // two more variable scope for array looping
                        opScopes[0] = param0[xindex];
                        opScopes[1] = {
                            xcount: xcount,
                            xindex: xindex
                        };
                        buffer += config.fn(opScopes);
                    }
                } else {
                    for (var name in param0) {
                        opScopes[0] = param0[name];
                        opScopes[1] = {
                            xindex: name
                        };
                        buffer += config.fn(opScopes);
                    }
                }

            } else if (config.inverse) {
                buffer = config.inverse(scopes);
            }
            return buffer;
        },

        'with': function (scopes, config) {
            var params = config.params;
            var param0 = params[0];
            var opScopes = [0].concat(scopes);
            var buffer = '';
            if (param0) {
                // skip object check for performance
                opScopes[0] = param0;
                buffer = config.fn(opScopes);
            } else if (config.inverse) {
                buffer = config.inverse(scopes);
            }
            return buffer;
        },

        'if': function (scopes, config) {
            var params = config.params;
            var param0 = params[0];
            var buffer = '';
            if (param0) {
                if (config.fn) {
                    buffer = config.fn(scopes);
                }
            } else if (config.inverse) {
                buffer = config.inverse(scopes);
            }
            return buffer;
        },

        'set': function (scopes, config) {
            // in case scopes[0] is not object ,{{#each}}{{set }}{{/each}}
            for (var i = scopes.length - 1; i >= 0; i--) {
                if (typeof scopes[i] == 'object') {
                    S.mix(scopes[i], config.hash);
                    break;
                }
            }
            return '';
        },

        include: function (scopes, config) {
            var params = config.params;
            // allow hash to shadow parent scopes
            var extra = config.hash ? [config.hash] : [];
            scopes = extra.concat(scopes);

            if (!params || params.length != 1) {
                S.error('include must has one param');
                return '';
            }

            var myName = this.config.name;
            var subTplName = params[0];

            if (subTplName.charAt(0) == '.') {
                if (myName == 'unspecified') {
                    S.error('parent template does not have name' + ' for relative sub tpl name: ' + subTplName);
                    return '';
                }
                subTplName = S.Path.resolve(myName, '../', subTplName);
            }

            var tpl = this.config.loader.call(this, subTplName);

            config = S.merge(this.config);
            // template file name
            config.name = subTplName;
            // pass commands to sub template
            config.commands = this.config.commands;
            // share macros with parent template and sub template
            config.macros = this.config.macros;
            return this.invokeEngine(tpl, scopes, config)
        },

        'macro': function (scopes, config) {
            var params = config.params;
            var macroName = params[0];
            var params1 = params.slice(1);
            var macros = this.config.macros;
            // definition
            if (config.fn) {
                // parent template override child template
                if (!macros[macroName]) {
                    macros[macroName] = {
                        paramNames: params1,
                        fn: config.fn
                    };
                }
            } else {
                var paramValues = {};
                var macro = macros[macroName];
                if (!macro) {
                    macro = S.require(macroName);
                    if (!macro) {
                        S.error("can not find macro module:" + name);
                    }
                }
                S.each(macro.paramNames, function (p, i) {
                    paramValues[p] = params1[i];
                });
                var newScopes = scopes.concat();
                newScopes.unshift(paramValues);
                return macro.fn.call(this, newScopes);
            }
            return '';
        },

        parse: function (scopes, config) {
            // abandon parent scopes
            return commands.include.call(this, [], config);
        }
    };
});
/**
 * xtemplate runtime
 * @author yiminghe@gmail.com
 * @ignore
 */
KISSY.add('xtemplate/runtime', function (S, commands, undefined) {
    var escapeHtml = S.escapeHtml;
    var logger = S.getLogger('s/xtemplate');

    function info(s) {
        logger.info(s);
    }

    function findCommand(commands, name) {
        var parts = name.split('.');
        var cmd = commands;
        var len = parts.length;
        for (var i = 0; i < len; i++) {
            cmd = cmd[parts[i]];
            if (!cmd) {
                break;
            }
        }
        return cmd;
    }

    function getProperty(parts, scopes, depth) {
        // this refer to current scope object
        if (parts === '.') {
            parts = 'this';
        }
        parts = parts.split('.');
        var len = parts.length,
            i,
            j = depth || 0,
            v,
            p,
            valid,
            sl = scopes.length;
        // root keyword for root scope
        if (parts[0] == 'root') {
            j = sl - 1;
            parts.shift();
            len--;
        }
        for (; j < sl; j++) {
            v = scopes[j];
            valid = 1;
            for (i = 0; i < len; i++) {
                p = parts[i];
                if (p === 'this') {
                    continue;
                }
                // may not be object at all
                else if (typeof v != 'object' || !(p in v)) {
                    valid = 0;
                    break;
                }
                v = v[p];
            }
            if (valid) {
                // support property function return value as property value
                if (typeof v == 'function') {
                    v = v.call(scopes[0]);
                }
                return [v];
            }
        }
        return false;
    }

    var utils = {
            'runBlockCommand': function (engine, scopes, options, name, line) {
                var config = engine.config;
                var logFn = config.silent ? info : S.error;
                var commands = config.commands;
                var command = findCommand(commands, name);
                if (!command) {
                    if (!options.params && !options.hash) {
                        var property = getProperty(name, scopes);
                        if (property === false) {
                            logFn("can not find property: '" + name + "' at line " + line);
                            property = '';
                        } else {
                            property = property[0];
                        }
                        command = commands['if'];
                        if (S.isArray(property)) {
                            command = commands.each;
                        }
                        else if (typeof property == 'object') {
                            command = commands['with'];
                        }
                        options.params = [property];
                    } else {
                        S.error("can not find command module: " + name + "' at line " + line);
                        return '';
                    }
                }
                var ret = '';
                try {
                    ret = command.call(engine, scopes, options);
                } catch (e) {
                    S.error(e.message + ": '" + name + "' at line " + line);
                }
                if (ret === undefined) {
                    ret = '';
                }
                return ret;
            },

            'getExpression': function (exp, escaped) {
                if (exp === undefined) {
                    exp = '';
                }
                return escaped && exp ? escapeHtml(exp) : exp;
            },

            'getPropertyOrRunCommand': function (engine, scopes, options, name, depth, line, escape, preserveUndefined) {
                var id0;
                var config = engine.config;
                var commands = config.commands;
                var command1 = findCommand(commands, name);
                var logFn = config.silent ? info : S.error;
                if (command1) {
                    try {
                        id0 = command1.call(engine, scopes, options);
                    } catch (e) {
                        S.error(e.message + ": '" + name + "' at line " + line);
                        return '';
                    }
                }
                else {
                    var tmp2 = getProperty(name, scopes, depth);
                    if (tmp2 === false) {
                        logFn("can not find property: '" +
                            name + "' at line " + line, "warn");
                        // undefined for expression
                        // {{n+2}}
                        return preserveUndefined ? undefined : '';
                    } else {
                        id0 = tmp2[0];
                    }
                }
                if (!preserveUndefined && id0 === undefined) {
                    id0 = '';
                }
                return escape && id0 ? escapeHtml(id0) : id0;
            }
        },

        defaultConfig = {

            /**
             * whether throw exception when template variable is not found in data
             *
             * or
             *
             * command is not found
             *
             *
             *      '{{title}}'.render({t2:0})
             *
             *
             * @cfg {Boolean} silent
             * @member KISSY.XTemplate.Runtime
             */
            silent: true,

            /**
             * template file name for chrome debug
             *
             * @cfg {Boolean} name
             * @member KISSY.XTemplate.Runtime
             */
            name: 'unspecified',

            /**
             * tpl loader to load sub tpl by name
             * @cfg {Function} loader
             * @member KISSY.XTemplate.Runtime
             */
            loader: function (subTplName) {
                var tpl = S.require(subTplName);
                if (!tpl) {
                    S.error('template "' + subTplName + '" does not exist, ' + 'need to be required or used first!');
                }
                return tpl;
            }

        };

    /**
     * XTemplate runtime. only accept tpl as function.
     *
     *
     *      @example
     *      KISSY.use('xtemplate/runtime',function(S, XTemplateRunTime){
     *          document.writeln(
     *              new XTemplateRunTime(function(scopes){ return scopes[0].title;}).render({title:2})
     *          );
     *      });
     *
     * @class KISSY.XTemplate.Runtime
     */
    function XTemplateRuntime(tpl, config) {
        var self = this;
        self.tpl = tpl;
        config = S.merge(defaultConfig, config);
        config.commands = S.merge(config.commands, commands);
        config.utils = utils;
        config.macros = config.macros || {};
        this.config = config;
    }

    S.mix(XTemplateRuntime, {
        commands: commands,

        utils: utils,

        /**
         * add command to all template
         * @method
         * @static
         * @param {String} commandName
         * @param {Function} fn
         * @member KISSY.XTemplate.Runtime
         */
        addCommand: function (commandName, fn) {
            commands[commandName] = fn;
        },

        /**
         * remove command from all template by name
         * @method
         * @static
         * @param {String} commandName
         * @member KISSY.XTemplate.Runtime
         */
        removeCommand: function (commandName) {
            delete commands[commandName];
        }
    });

    XTemplateRuntime.prototype = {
        constructor: XTemplateRuntime,

        // allow str sub template
        invokeEngine: function (tpl, scopes, config) {
            return new this.constructor(tpl, config).render(scopes, true);
        },

        /**
         * remove command by name
         * @param commandName
         */
        'removeCommand': function (commandName) {
            delete this.config.commands[commandName];
        },

        /**
         * add command definition to current template
         * @param commandName
         * @param {Function} fn command definition
         */
        addCommand: function (commandName, fn) {
            this.config.commands[commandName] = fn;
        },

        /**
         * get result by merge data with template
         * @param data
         * @return {String}
         * @param {Boolean} [keepDataFormat] for internal use
         */
        render: function (data, keepDataFormat) {
            if (!keepDataFormat) {
                data = [data];
            }
            return this.tpl(data, S);
        }
    };

    return XTemplateRuntime;
}, {
    requires: [ './runtime/commands']
});

/**
 * @ignore
 *
 * 2012-09-12 yiminghe@gmail.com
 *  - 参考 velocity, 扩充 ast
 *          - Expression/ConditionalOrExpression
 *          - EqualityExpression/RelationalExpression...
 *
 * 2012-09-11 yiminghe@gmail.com
 *  - 初步完成,添加 tc
 *
 * 对比 template
 *
 *  优势
 *      - 不会莫名其妙报错(with)
 *      - 更多出错信息,直接给出行号
 *      - 更容易扩展 command,sub-tpl
 *      - 支持子模板
 *      - 支持作用域链: ..\x ..\..\y
 *      - 内置 escapeHtml 支持
 *      - 支持预编译
 *      - 支持简单表达式 +-/%* ()
 *      - 支持简单比较 === !===
 *   劣势
 *      - 不支持表达式
 *      - 不支持复杂比较操作
 *      - 不支持 js 语法
 *
 */


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <extension
         point="org.eclipse.search.searchPages">
      <page
            canSearchEnclosingProjects="true"
            class="org.xtuml.bp.ui.search.pages.ModelSearchPage"
            enabled="true"
            icon="icons/bp_search.gif"
            id="org.xtuml.bp.ui.search.xtumlSearchPage"
            label="xtuml Search"
            showScopeSection="true"
            tabPosition="0">
      </page>
   </extension>
   <extension
         point="org.eclipse.search.searchResultViewPages">
      <viewPage
            class="org.xtuml.bp.ui.search.pages.ModelSearchResultPage"
            icon="icons/bp_search.gif"
            id="org.xtuml.bp.ui.search.modelSearchResultPage"
            label="Model Search"
            searchResultClass="org.xtuml.bp.search.results.ModelSearchResult">
      </viewPage>
   </extension>

</plugin>

redpajama_set_name: RedPajamaGithub


text:
.class final Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;
.super Ljava/util/AbstractSet;
.source "CustomConcurrentHashMap.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/common/collect/CustomConcurrentHashMap;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x10
    name = "KeySet"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/util/AbstractSet",
        "<TK;>;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

# direct methods
.method constructor <init>(Lcom/google/common/collect/CustomConcurrentHashMap;)V
    .locals 0

    .prologue
    .line 3598
    .local p0, "this":Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;, "Lcom/google/common/collect/CustomConcurrentHashMap<TK;TV;>.KeySet;"
    iput-object p1, p0, Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;->this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

    invoke-direct {p0}, Ljava/util/AbstractSet;-><init>()V

    return-void
.end method

# virtual methods
.method public clear()V
    .locals 1

    .prologue
    .line 3621
    .local p0, "this":Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;, "Lcom/google/common/collect/CustomConcurrentHashMap<TK;TV;>.KeySet;"
    iget-object v0, p0, Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;->this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

    invoke-virtual {v0}, Lcom/google/common/collect/CustomConcurrentHashMap;->clear()V

    .line 3622
    return-void
.end method

.method public contains(Ljava/lang/Object;)Z
    .locals 1
    .param p1, "o"    # Ljava/lang/Object;

    .prologue
    .line 3613
    .local p0, "this":Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;, "Lcom/google/common/collect/CustomConcurrentHashMap<TK;TV;>.KeySet;"
    iget-object v0, p0, Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;->this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

    invoke-virtual {v0, p1}, Lcom/google/common/collect/CustomConcurrentHashMap;->containsKey(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public isEmpty()Z
    .locals 1

    .prologue
    .line 3609
    .local p0, "this":Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;, "Lcom/google/common/collect/CustomConcurrentHashMap<TK;TV;>.KeySet;"
    iget-object v0, p0, Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;->this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

    invoke-virtual {v0}, Lcom/google/common/collect/CustomConcurrentHashMap;->isEmpty()Z

    move-result v0

    return v0
.end method

.method public iterator()Ljava/util/Iterator;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/Iterator",
            "<TK;>;"
        }
    .end annotation

    .prologue
    .line 3601
    .local p0, "this":Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;, "Lcom/google/common/collect/CustomConcurrentHashMap<TK;TV;>.KeySet;"
    new-instance v0, Lcom/google/common/collect/CustomConcurrentHashMap$KeyIterator;

    iget-object v1, p0, Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;->this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

    invoke-direct {v0, v1}, Lcom/google/common/collect/CustomConcurrentHashMap$KeyIterator;-><init>(Lcom/google/common/collect/CustomConcurrentHashMap;)V

    return-object v0
.end method

.method public remove(Ljava/lang/Object;)Z
    .locals 1
    .param p1, "o"    # Ljava/lang/Object;

    .prologue
    .line 3617
    .local p0, "this":Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;, "Lcom/google/common/collect/CustomConcurrentHashMap<TK;TV;>.KeySet;"
    iget-object v0, p0, Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;->this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

    invoke-virtual {v0, p1}, Lcom/google/common/collect/CustomConcurrentHashMap;->remove(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public size()I
    .locals 1

    .prologue
    .line 3605
    .local p0, "this":Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;, "Lcom/google/common/collect/CustomConcurrentHashMap<TK;TV;>.KeySet;"
    iget-object v0, p0, Lcom/google/common/collect/CustomConcurrentHashMap$KeySet;->this$0:Lcom/google/common/collect/CustomConcurrentHashMap;

    invoke-virtual {v0}, Lcom/google/common/collect/CustomConcurrentHashMap;->size()I

    move-result v0

    return v0
.end method


text:
using Scada.Web.Plugins.WebPage;
using System.Collections.Generic;
using System.IO;

namespace Scada.Web.Plugins
{
    /// <summary>
    /// Web page plugin specification.
    /// <para>Спецификация плагина веб-страниц.</para>
    /// </summary>
    public class PlgWebPageSpec : PluginSpec
    {
        /// <summary>
        /// The plugin version.
        /// </summary>
        internal const string PlgVersion = "5.0.1.0";

        private DictUpdater dictUpdater; // updates the plugin dictionary

        /// <summary>
        /// Gets the plugin name.
        /// </summary>
        public override string Name
        {
            get
            {
                return Localization.UseRussian ?
                    "Веб-страницы" :
                    "Web pages";
            }
        }

        /// <summary>
        /// Gets the plugin description.
        /// </summary>
        public override string Descr
        {
            get
            {
                return Localization.UseRussian ?
                    "Плагин обеспечивает отображение произвольных веб-страниц." :
                    "The plugin provides displaying arbitrary web pages.";
            }
        }

        /// <summary>
        /// Gets the plugin version.
        /// </summary>
        public override string Version
        {
            get
            {
                return PlgVersion;
            }
        }

        /// <summary>
        /// Get the view specifications that the plugin implements.
        /// </summary>
        public override List<ViewSpec> ViewSpecs
        {
            get
            {
                return new List<ViewSpec>() { new WebPageViewSpec() };
            }
        }

        /// <summary>
        /// Initializes the plugin.
        /// </summary>
        public override void Init()
        {
            dictUpdater = new DictUpdater(
                string.Format("{0}WebPage{1}lang{1}", AppDirs.PluginsDir, Path.DirectorySeparatorChar),
                "PlgWebPage", null, Log);
        }

        /// <summary>
        /// Perform actions after a successful user login.
        /// </summary>
        public override void OnUserLogin(UserData userData)
        {
            dictUpdater.Update();
        }
    }
}


text:
<!DOCTYPE html>
<html xmlns:wx>
<head>
	<link rel="stylesheet" href="../../../codebase/webix.css" type="text/css" media="screen" charset="utf-8" />
	<script src="../../../codebase/webix.js" type="text/javascript" charset="utf-8"></script>
	<title>XML init : custom namespace</title>
</head>
<body>

<div style='width:600px; height:250px;'>
<wx:ui>
	<wx:form id="log_form" width="300">
		<wx:text label="Email"></wx:text>
		<wx:text label="Password"></wx:text>
		<wx:cols margin="5">
			<wx:button value="Login" type="form"></wx:button>
			<wx:button value="Cancel"></wx:button>
		</wx:cols>
	</wx:form>
</wx:ui>
</div>

<script type="text/javascript">
	webix.markup.namespace = "wx";
	webix.markup.init();
</script>
</body>
</html>


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{\label{sec:vmuniverse}Virtual Machine Applications}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\index{virtual machine universe|(}
\index{universe!vm}
\index{vm universe}

The \SubmitCmd{vm} universe facilitates an HTCondor job
that matches and then lands a disk image on an execute machine
within an HTCondor pool.
This disk image is intended to be a virtual machine.
In this manner, the virtual machine is the job to be executed.

This section describes this type of HTCondor job.
See section~\ref{sec:Config-VMs}
for details of configuration variables.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{\label{sec:vm-submitfile}The Submit Description File}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Different than all other universe jobs,
the \SubmitCmd{vm} universe job specifies a disk image,
not an executable.
Therefore, the submit commands \SubmitCmd{input}, \SubmitCmd{output},
and \SubmitCmd{error} do not apply.
If specified, \Condor{submit} rejects the job with an error.
The \SubmitCmd{executable} command changes definition within a
\SubmitCmd{vm} universe job.
It no longer specifies an executable file, but instead
provides a string that identifies the job for tools such
as \Condor{q}.
Other commands specific to the type of virtual machine software
identify the disk image.

VMware, Xen, and KVM virtual machine software are supported.
As these differ from each other, the submit description file
specifies one of
\begin{verbatim}
  vm_type = vmware
\end{verbatim}
or
\begin{verbatim}
  vm_type = xen
\end{verbatim}
or
\begin{verbatim}
  vm_type = kvm
\end{verbatim}

The job is required to specify its memory needs
for the disk image with \SubmitCmd{vm\_memory},
which is given in Mbytes.
HTCondor uses this number to assure a match with a machine
that can provide the needed memory space.

Virtual machine networking is enabled with the command
\begin{verbatim}
  vm_networking = true
\end{verbatim}
And, when networking is enabled, a definition of
\SubmitCmd{vm\_networking\_type} as \SubmitCmd{bridge}
matches the job only with a machine that is configured to use
bridge networking.
A definition of
\SubmitCmd{vm\_networking\_type} as \SubmitCmd{nat}
matches the job only with a machine that is configured to use
NAT networking.
When no definition of
\SubmitCmd{vm\_networking\_type} is given,
HTCondor may
match the job with a machine that enables networking,
and further, the choice of bridge or NAT networking
is determined by the machine's configuration.

Modified disk images are transferred back to the machine from which
the job was submitted as the \SubmitCmd{vm} universe job completes.
Job completion for a \SubmitCmd{vm} universe job occurs when
the virtual machine is shut down, and HTCondor notices
(as the result of a periodic check on the state of the virtual machine).
Should the job not want any files transferred back (modified or not),
for example because the job explicitly transferred its own files,
the submit command to prevent the transfer is
\begin{verbatim}
  vm_no_output_vm = true
\end{verbatim}

The required disk image must be identified for a virtual machine.
This \SubmitCmd{vm\_disk} command specifies a list of comma-separated files.
Each disk file is specified by colon-separated fields.
The first field is the path and file name of the disk file.
The second field specifies the device.
The third field specifies permissions, and the optional
fourth specifies the format.
Here is an example that identifies a single file:
\footnotesize
\begin{verbatim}
  vm_disk = /var/lib/libvirt/images/swap.img:sda2:w:raw
\end{verbatim}
\normalsize

Setting values in the submit description file for some commands
have consequences for the virtual machine description file.
These commands are
\begin{itemize}
  \item \SubmitCmd{vm\_memory}
  \item \SubmitCmd{vm\_macaddr}
  \item \SubmitCmd{vm\_networking}
  \item \SubmitCmd{vm\_networking\_type}
  \item \SubmitCmd{vm\_disk}
\end{itemize}
For VMware virtual machines,
setting values for these commands causes HTCondor to modify the
\File{.vmx} file, overwriting existing values.
For KVM and Xen virtual machines,
HTCondor uses these values when it produces the description file.

For Xen and KVM jobs, if any files need to be transferred from the submit machine
to the machine where the \SubmitCmd{vm} universe job will execute,
HTCondor must be explicitly told to do so with the
standard file transfer attributes:
\footnotesize
\begin{verbatim}
  should_transfer_files = YES
  when_to_transfer_output = ON_EXIT
  transfer_input_files = /myxen/diskfile.img,/myxen/swap.img
\end{verbatim}
\normalsize
Any and all needed files on a system without a shared file
system (between the submit machine and the machine where the
job will execute) must be listed.

Further commands specify information that is specific to the
virtual machine type targeted.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{\label{sec:vm-VMwaresubmitfile}VMware-Specific Submit Commands}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\index{vm universe!submit commands specific to VMware}

Specific to VMware, the submit description file command
\SubmitCmd{vmware\_dir} gives the path and directory
(on the machine from which the job is submitted)
to where VMware-specific files and applications reside.
One example of a VMware-specific application is the VMDK files,
which form a virtual hard drive (disk image) for the virtual machine.
VMX files containing the primary configuration for the virtual
machine would also be in this directory.

HTCondor must be told whether or not the contents of the \SubmitCmd{vmware\_dir}
directory must be transferred to the machine where the job is
to be executed.
This required information is given with the submit command
\SubmitCmd{vmware\_should\_transfer\_files}.
With a value of \Expr{True},
HTCondor does transfer the contents of the directory.
With a value of \Expr{False},
HTCondor does not transfer the contents of the directory,
and instead presumes that access to this directory is
available through a shared file system.

By default, HTCondor uses a snapshot disk for new and modified files.
They may also be utilized for checkpoints.
The snapshot disk is initially quite small,
growing only as new files are created or files are modified.
When \SubmitCmd{vmware\_should\_transfer\_files} is \Expr{True},
a job may specify that a snapshot disk is \emph{not} to be
used with the command
\begin{verbatim}
  vmware_snapshot_disk = False
\end{verbatim}
In this case, HTCondor will utilize original disk files in producing
checkpoints.
Note that \Condor{submit} issues an error message and does not
submit the job if both \SubmitCmd{vmware\_should\_transfer\_files}
and \SubmitCmd{vmware\_snapshot\_disk} are \Expr{False}.

Note that if snapshot disks are requested and file transfer is not
being used, the \SubmitCmd{vmware\_dir} setting given in
the submit description file
should not contain any symbolic link path components.
This is to work around the issue discussed
in the FAQ entry in section~\ref{sec:vmware-symlink-bug}.

Here is a sample submit description file for a VMware virtual machine:
\begin{verbatim}
universe                     = vm
executable                   = vmware_sample_job
log                          = simple.vm.log.txt
vm_type                      = vmware
vm_memory                    = 64
vmware_dir                   = C:\condor-test
vmware_should_transfer_files = True
queue
\end{verbatim}
This sample uses the \SubmitCmd{vmware\_dir} command to identify
the location of the disk image to be executed as an HTCondor job.
The contents of this directory are transferred to the machine assigned
to execute the HTCondor job.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{\label{sec:vm-Xensubmitfile}Xen-Specific Submit Commands}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\index{vm universe!submit commands specific to Xen}

% xen_kernel description
A Xen \SubmitCmd{vm} universe job requires specification of the
guest kernel.
The \SubmitCmd{xen\_kernel} command accomplishes this,
utilizing one of the following definitions.
\begin{enumerate}
\item \SubmitCmd{xen\_kernel = included} implies that the kernel
  is to be found in disk image given by the definition of the single file
  specified in \SubmitCmd{vm\_disk}.

\item \SubmitCmd{xen\_kernel = path-to-kernel} gives a full path and
  file name of the required kernel.  If this kernel must be transferred
  to machine on which the \SubmitCmd{vm} universe job will execute,
  it must also be included in the \SubmitCmd{xen\_transfer\_files} command.

  This form of the \SubmitCmd{xen\_kernel} command also requires further
  definition of the \SubmitCmd{xen\_root} command.
  \SubmitCmd{xen\_root} defines the device containing files needed by
  \Login{root}.

\end{enumerate}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{\label{sec:vm-checkpoints}Checkpoints}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\index{vm universe!checkpoints}

Creating a checkpoint is straightforward for a virtual machine,
as a checkpoint is a set of files that represent
a snapshot of both disk image and memory.
The checkpoint is created and all files are transferred back
to the \MacroUNI{SPOOL} directory on the machine from which
the job was submitted.
The submit command to create checkpoints is
\begin{verbatim}
  vm_checkpoint = true
\end{verbatim}
Without this command, no checkpoints are created (by default).
With the command, a checkpoint is created any time the \SubmitCmd{vm}
universe jobs is evicted from the machine upon which it is executing.
This occurs as a result of the machine configuration indicating
that it will no longer execute this job.

\SubmitCmd{vm} universe jobs can \emph{not} use a checkpoint server.

Periodic creation of checkpoints is not supported at this time.

Enabling both networking and checkpointing for a \SubmitCmd{vm}
universe job can cause networking problems when the job restarts,
particularly if the job migrates to a different machine.
\Condor{submit} will normally reject such jobs.
To enable both, then add the command
\begin{verbatim}
  when_to_transfer_output = ON_EXIT_OR_EVICT
\end{verbatim}

Take care with respect to the use of network connections within
the virtual machine and their interaction with checkpoints.
Open network connections at the time of the checkpoint will likely
be lost when the checkpoint is subsequently used to resume execution
of the virtual machine.
This occurs whether or not the execution resumes
on the same machine or a different one within the HTCondor pool.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{\label{sec:vm-disk-image-details}Disk Images}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{\label{sec:vm-disk-image-details-vmware}
VMware on Windows and Linux}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Following the platform-specific
guest OS installation instructions found at
\URL{http://partnerweb.vmware.com/GOSIG/home.html},
creates a VMware disk image.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{\label{sec:vm-disk-image-details-xen}Xen and KVM}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
While the following web page contains instructions specific to
Fedora on how to create a virtual guest image,
it should provide a good starting point for
other platforms as well.

\URL{http://fedoraproject.org/wiki/Virtualization\_Quick\_Start}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{\label{sec:vm-job-completion-details}Job Completion in the vm Universe}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Job completion for a \SubmitCmd{vm} universe job occurs when
the virtual machine is shut down, and HTCondor notices
(as the result of a periodic check on the state of the virtual machine).
This is different from jobs executed under the environment of other
universes.

Shut down of a virtual machine occurs from within the virtual
machine environment.
A script, executed with the proper authorization level,
is the likely source of the shut down commands.

Under a Windows 2000, Windows XP, or Vista virtual machine,
an administrator issues the command
\begin{verbatim}
  shutdown -s -t 01
\end{verbatim}

Under a Linux virtual machine,
the \Login{root} user executes
\begin{verbatim}
  /sbin/poweroff
\end{verbatim}
The command \verb@/sbin/halt@ will not completely
shut down some Linux distributions, and instead
causes the job to hang.

Since the successful completion of the \SubmitCmd{vm} universe job
requires the successful shut down of the virtual machine,
it is good advice to try the shut down procedure outside of
HTCondor, before a \SubmitCmd{vm} universe job is submitted.

\index{virtual machine universe|)}


text:
"""Logger module: contains the logger class which creates and writes
   data to log files on disk"""

import sys
import time
import math

class Logger:
    def __init__(self, fileName="log"):
        """
        Logger constructor
        """
        self.__timeStamp = 1
        self.__startTime = 0.0
        self.__logFile = None
        self.__logFileName = fileName

    def setTimeStamp(self, bool):
        """
        Toggle time stamp printing with log entries on and off
        """
        self.__timeStamp = bool

    def getTimeStamp(self):
        """
        Return whether or not we are printing time stamps with log entries
        """
        return(self.__timeStamp)

    # logging control

    def resetStartTime(self):
        """
        Reset the start time of the log file for time stamps
        """
        self.__startTime = time.time()

    def log(self, entryString):
        """log(self, string)
        Print the given string to the log file"""
        if (self.__logFile == None):
            self.__openLogFile()
        if (self.__timeStamp):
            self.__logFile.write(self.__getTimeStamp())
        self.__logFile.write(entryString + '\n')

    # logging functions

    def __openLogFile(self):
        """
        Open a file for logging error/warning messages
        """
        self.resetStartTime()
        t = time.localtime(self.__startTime)
        st = time.strftime("%m-%d-%Y-%H-%M-%S", t)
        logFileName = self.__logFileName + "." + st
        self.__logFile = open(logFileName, "w")

    def __closeLogFile(self):
        """
        Close the error/warning output file
        """
        if (self.__logFile != None):
            self.__logFile.close()

    def __getTimeStamp(self):
        """
        Return the offset between current time and log file startTime
        """
        t = time.time()
        dt = t - self.__startTime
        if (dt >= 86400):
            days = int(math.floor(dt/86400))
            dt = dt%86400
        else:
            days = 0
        if (dt >= 3600):
            hours = int(math.floor(dt/3600))
            dt = dt%3600
        else:
            hours = 0
        if (dt >= 60):
            minutes = int(math.floor(dt/60))
            dt = dt%60
        else:
            minutes = 0
        seconds = int(math.ceil(dt))
        return("%02d:%02d:%02d:%02d: " % (days, hours, minutes, seconds))


text:
<?
spl_autoload_register(function($classname) {
    include_once(CORE_PATH . "/libs/$classname.php");
});
?>


text:
Gcloud stuff
==================

Configuring gsutil
------------------

Download google cloud tools from https://cloud.google.com/storage/docs/gsutil_install

Unzip and run ``./install.sh``. Then start a new shell and type ``gsutil config -a`` (or ``gcloud init``). Enter Gcloud ID and secret key. Those can be copied from another machine you have configured (they should be in a file called ``application_default_credentials.json`` under ``~/.config/gcloud/``,
namely ``client_id`` and ``client_secret``.

Then run::

    gcloud auth login --no-launch-browser

And point your browser at the URL, followed by copying the access code. Then::

    gcloud config set project <PROJECT_NAME>

To allow applications such as Pandas read/write access, follow up with::

    gcloud auth application-default login --no-launch-browser


text:
var Checker = require('../../../lib/checker');
var expect = require('chai').expect;

describe('rules/require-camelcase-or-uppercase-identifiers', function() {
    var checker;

    beforeEach(function() {
        checker = new Checker();
        checker.registerDefaultRules();
    });

    describe('option value `true`', function() {
        beforeEach(function() {
            checker.configure({ requireCamelCaseOrUpperCaseIdentifiers: true });
        });

        it('should report inner all-lowercase underscores', function() {
            expect(checker.checkString('var x_y = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report inner some-lowercase underscores', function() {
            expect(checker.checkString('var X_y = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should not report inner all-uppercase underscores', function() {
            expect(checker.checkString('var X_Y = "x";')).to.have.no.errors();
        });

        it('should not report no underscores', function() {
            expect(checker.checkString('var xy = "x";')).to.have.no.errors();
        });

        it('should not report leading underscores', function() {
            expect(checker.checkString('var _x = "x", __y = "y";')).to.have.no.errors();
        });

        it('should report trailing underscores', function() {
            expect(checker.checkString('var x_ = "x", y__ = "y";')).to.have.no.errors();
        });

        it('should not report underscore.js', function() {
            expect(checker.checkString('var extend = _.extend;')).to.have.no.errors();
        });

        it('should not report node globals', function() {
            expect(checker.checkString('var a = __dirname + __filename;')).to.have.no.errors();
        });

        it('should report object keys', function() {
            expect(checker.checkString('var extend = { snake_case: a };'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report object properties', function() {
            expect(checker.checkString('var extend = a.snake_case;'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that are the last token', function() {
            expect(checker.checkString('var a = snake_case'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that are the first token', function() {
            expect(checker.checkString('snake_case = a;'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report object destructring', function() {
            expect(checker.checkString(
                '({camelCase: snake_case, camelCase2: {camelCase3: snake_case2}}) => camelCase.length;'))
              .to.have.validation.errors.from('requireCamelCaseOrUpperCaseIdentifiers');
        });
    });

    describe('option value `"ignoreProperties"`', function() {
        beforeEach(function() {
            checker.configure({ requireCamelCaseOrUpperCaseIdentifiers: 'ignoreProperties' });
        });

        it('should not report object keys', function() {
            expect(checker.checkString('var extend = { snake_case: a };')).to.have.no.errors();
        });

        it('should not report object properties', function() {
            expect(checker.checkString('var extend = a.snake_case;')).to.have.no.errors();
        });

        it('should report identifiers that are the last token', function() {
            expect(checker.checkString('var a = snake_case'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that are the first token', function() {
            expect(checker.checkString('snake_case = a;'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should not report es5 getters', function() {
            expect(checker.checkString('var extend = { get a_b() { } };')).to.have.no.errors();
        });

        it('should not report es5 setters', function() {
            expect(checker.checkString('var extend = { set c_d(v) { } };')).to.have.no.errors();
        });

        it('should not report object destructring', function() {
            expect(checker.checkString(
                '({camelCase: snake_case, camelCase2: {camelCase3: snake_case2}}) => camelCase.length;'))
              .to.have.no.errors();
        });
    });

    describe('option object value `"ignoreProperties"`', function() {
        beforeEach(function() {
            checker.configure({ requireCamelCaseOrUpperCaseIdentifiers: {ignoreProperties: true} });
        });

        it('should not report object keys', function() {
            expect(checker.checkString('var extend = { snake_case: a };')).to.have.no.errors();
        });

        it('should not report object properties', function() {
            expect(checker.checkString('var extend = a.snake_case;')).to.have.no.errors();
        });

        it('should report identifiers that are the last token', function() {
            expect(checker.checkString('var a = snake_case'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that are the first token', function() {
            expect(checker.checkString('snake_case = a;'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should not report es5 getters', function() {
            expect(checker.checkString('var extend = { get a_b() { } };')).to.have.no.errors();
        });

        it('should not report es5 setters', function() {
            expect(checker.checkString('var extend = { set c_d(v) { } };')).to.have.no.errors();
        });

        it('should not report object destructring', function() {
            expect(checker.checkString(
                '({camelCase: snake_case, camelCase2: {camelCase3: snake_case2}}) => camelCase.length;'))
              .to.have.no.errors();
        });
    });

    describe('option object value `"strict"`', function() {
        beforeEach(function() {
            checker.configure({ requireCamelCaseOrUpperCaseIdentifiers: {strict: true} });
        });

        it('should report capital', function() {
            expect(checker.checkString('var X = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report capital word', function() {
            expect(checker.checkString('var Xoe = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report capital used even with second one lower cased', function() {
            expect(checker.checkString('var Xy = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should not report no capital used', function() {
            expect(checker.checkString('var xy = "x";')).to.have.no.errors();
        });

        it('should not report leading underscores', function() {
            expect(checker.checkString('var _x = "x", __y = "y";')).to.have.no.errors();
        });

        it('should report trailing underscores', function() {
            expect(checker.checkString('var x_ = "x", y__ = "y";')).to.have.no.errors();
        });

        it('should not report underscore.js', function() {
            expect(checker.checkString('var extend = _.extend;')).to.have.no.errors();
        });

        it('should not report node globals', function() {
            expect(checker.checkString('var a = __dirname + __filename;')).to.have.no.errors();
        });

        it('should report object keys', function() {
            expect(checker.checkString('var extend = { snake_case: a };'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report object properties', function() {
            expect(checker.checkString('var extend = a.snake_case;'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should not report object properties without capital', function() {
            expect(checker.checkString('var extend = a.snakeCase;')).to.have.no.errors();
        });

        it('should report object properties with capital', function() {
            expect(checker.checkString('var extend = a.SnakeCase;'))
            .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that are the last token', function() {
            expect(checker.checkString('var a = snake_case'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that are the first token', function() {
            expect(checker.checkString('snake_case = a;'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that start with a capital', function() {
            expect(checker.checkString('E'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });
    });

    describe('option object value `"strict"` and `"ignoreProperties"`', function() {
        beforeEach(function() {
            checker.configure({ requireCamelCaseOrUpperCaseIdentifiers: {strict: true, ignoreProperties: true} });
        });

        it('should report capital', function() {
            expect(checker.checkString('var X = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report capital word', function() {
            expect(checker.checkString('var Xoe = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report capital used even with second one lower cased', function() {
            expect(checker.checkString('var Xy = "x";'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should not report no capital used', function() {
            expect(checker.checkString('var xy = "x";')).to.have.no.errors();
        });

        it('should not report leading underscores', function() {
            expect(checker.checkString('var _x = "x", __y = "y";')).to.have.no.errors();
        });

        it('should report trailing underscores', function() {
            expect(checker.checkString('var x_ = "x", y__ = "y";')).to.have.no.errors();
        });

        it('should not report underscore.js', function() {
            expect(checker.checkString('var extend = _.extend;')).to.have.no.errors();
        });

        it('should not report node globals', function() {
            expect(checker.checkString('var a = __dirname + __filename;')).to.have.no.errors();
        });

        it('should not report object keys', function() {
            expect(checker.checkString('var extend = { snake_case: a };')).to.have.no.errors();
        });

        it('should not report object properties', function() {
            expect(checker.checkString('var extend = a.snake_case;')).to.have.no.errors();
        });

        it('should not report object properties without capital', function() {
            expect(checker.checkString('var extend = a.snakeCase;')).to.have.no.errors();
        });

        it('should report object properties with capital', function() {
            expect(checker.checkString('var extend = a.SnakeCase;')).to.have.no.errors();
        });

        it('should report identifiers that are the last token', function() {
            expect(checker.checkString('var a = snake_case'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that are the first token', function() {
            expect(checker.checkString('snake_case = a;'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should report identifiers that start with a capital', function() {
            expect(checker.checkString('E'))
              .to.have.one.validation.error.from('requireCamelCaseOrUpperCaseIdentifiers');
        });

        it('should not report object destructring', function() {
            expect(checker.checkString(
                '({camelCase: snake_case, camelCase2: {camelCase3: snake_case2}}) => camelCase.length;'))
              .to.have.no.errors();
        });
    });
});


text:
' Reports model class
'
' Part of ASP.NET osa framework  www.osalabs.com/osafw/asp.net
' (c) 2009-2018 Oleg Savchuk www.osalabs.com

Imports Microsoft.VisualBasic

Public Class Reports
    Inherits FwModel

    Public Sub New()
        MyBase.New()
        'table_name = "demo_dicts"
    End Sub

    Function cleanupRepcode(repcode As String) As String
        Return LCase(Regex.Replace(repcode, "[^\w-]", ""))
    End Function
    ''' <summary>
    ''' Convert report code into class name
    ''' </summary>
    ''' <param name="repcode">pax-something-summary</param>
    ''' <returns>ReportPaxSomethingSummary</returns>
    ''' <remarks></remarks>
    Function repcodeToClass(repcode As String) As String
        Dim result As String = ""
        Dim pieces As String() = Split(repcode, "-")
        For Each piece As String In pieces
            result &= Utils.capitalize(piece)
        Next
        Return "Report" & result
    End Function

    ''' <summary>
    ''' Create instance of report class by repcode
    ''' </summary>
    ''' <param name="repcode">cleaned report code</param>
    ''' <param name="f">filters passed from request</param>
    ''' <returns></returns>
    Function createInstance(repcode As String, f As Hashtable) As ReportBase
        Dim report_class_name As String = repcodeToClass(repcode)
        If Not report_class_name > "" Then Throw New ApplicationException("Wrong Report Code")

        Dim report As ReportBase = Activator.CreateInstance(Type.GetType(report_class_name, True))
        report.init(fw, repcode, f)
        Return report
    End Function

End Class


text:
import { Component, ViewChild } from '@angular/core';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { NavController, ViewController } from 'ionic-angular';

import { Camera } from '@ionic-native/camera';

/*
  Generated class for the ItemCreate page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-item-create',
  templateUrl: 'item-create.html'
})
export class ItemCreatePage {
  @ViewChild('fileInput') fileInput;

  isReadyToSave: boolean;

  item: any;

  form: FormGroup;

  constructor(public navCtrl: NavController, public viewCtrl: ViewController, formBuilder: FormBuilder, private camera: Camera) {
    this.form = formBuilder.group({
      profilePic: [''],
      name: ['', Validators.required],
      about: ['']
    });

    // Watch the form for changes, and
    this.form.valueChanges.subscribe((v) => {
      this.isReadyToSave = this.form.valid;
    });
  }

  ionViewDidLoad() {

  }

  getPicture() {
    if (this.camera['installed']()) {
      this.camera.getPicture({
        targetWidth: 96,
        targetHeight: 96
      }).then((data) => {
        this.form.patchValue({ 'profilePic': 'data:image/jpg;base64,' +  data });
      }, (err) => {
        alert('Unable to take photo');
      })
    } else {
      this.fileInput.nativeElement.click();
    }
  }

  processWebImage(event) {
    let input = this.fileInput.nativeElement;

    var reader = new FileReader();
    reader.onload = (readerEvent) => {
      input.parentNode.removeChild(input);

      var imageData = (readerEvent.target as any).result;
      this.form.patchValue({ 'profilePic': imageData });
    };

    reader.readAsDataURL(event.target.files[0]);
  }

  getProfileImageStyle() {
    return 'url(' + this.form.controls['profilePic'].value + ')'
  }

  /**
   * The user cancelled, so we dismiss without sending data back.
   */
  cancel() {
    this.viewCtrl.dismiss();
  }

  /**
   * The user is done and wants to create the item, so return it
   * back to the presenter.
   */
  done() {
    if(!this.form.valid) { return; }
    this.viewCtrl.dismiss(this.form.value);
  }
}


text:
//
//  UITableViewCell+MAC.m
//  WeiSchoolTeacher
//
//  Created by MacKun on 15/12/18.
//  Copyright © 2015年 MacKun. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "UITableViewCell+MAC.h"

@implementation UITableViewCell(MAC)

/**
 *  @brief  加载同类名的nib
 *
 *  @return cell
 */
+(id)nibCell{
//    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];
//
//    return  [nib objectAtIndex:0];

    return  [[[UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil]instantiateWithOwner:nil options:nil] objectAtIndex:0];
}
+ (NSString*)cellIdentifier {

    return NSStringFromClass(self);
}

+ (id)loadFromCellStyle:(UITableViewCellStyle)cellStyle {

    return [[self alloc] initWithStyle:cellStyle reuseIdentifier:NSStringFromClass(self)];
}

@end


text:
'use strict';

var React = require('react');

var component = {

	foo: function() {

	},

	render: function() {
		return (
			React.DOM.div({})
		);
	}
};

module.exports = React.createClass(component);


text:
layout: post
title: "Nothing Else Matters"
permalink: nothing-else-matters
date: 2021-11-17 08:05:59
comments: true
description: "Nothing Else Matters"
keywords: ""
categories: ["poetry"]

tags: ["poetry"]

---

So close, no matter how far
Couldn't be much more from the PM fit
Forever building who we are
And nothing else matters

Never worked myself this way
Life is ours, we live it our way
All these words, I don't just say
And nothing else matters

Revenue I seek and I find in you
Every day we ship something new
Open figma for a different view
And nothing else matters

Never cared for what they do
Never cared for what they know
But I know
So close, no matter how far
It couldn't be much more from the heart
Forever trusting who we are
And nothing else matters
Never cared for what they do
Never cared for what they know
But I know
I never opened myself this way
Life is ours, we live it our way
All these words, I don't just say
And nothing else matters
Trust I seek and I find in you
Every day for us something new
Open mind for a different view
And nothing else matters
Never cared for what they say
Never cared for games they play
Never cared for what they do
Never cared for what they know
And I know, yeah, yeah
So close, no matter how far
Couldn't be much more from the heart
Forever trusting who we are
No, nothing else matters


text:
<?php
/*
 * Created on Sept. 11, 2007
 */

namespace crazedsanity\xml;

use crazedsanity\core\ToolBox;
use \cs_arrayToPath;
use \cs_phpxmlCreator;

abstract class xmlAbstract {

	public $isTest = FALSE;
	protected $a2p;
	protected $rootElement;
	protected $preserveCase=false;
	const dataIndex = '__data__';
	const attributeIndex = '__attribs__';

	//=========================================================================
	public function __construct(array $data=null) {
//		$this->set_version_file_location(dirname(__FILE__) . '/VERSION');
		if(!is_array($data)) {
			$data = array();
		}
		$this->a2p = new \cs_arrayToPath($data);
	}//end __construct()
	//=========================================================================

	//=========================================================================
	/**
	 * Returns a list delimited by the given delimiter.  Does the work of
	 * checking if the given variable has data in it already, that needs to be
	 * added to, vs. setting the variable with the new content.
	 */
	final public function create_list($string = NULL, $addThis = NULL, $delimiter = ", ") {
		if($string) {
			$retVal = $string . $delimiter . $addThis;
		}
		else {
			$retVal = $addThis;
		}

		return ($retVal);
	} //end create_list()
	//=========================================================================

	//=================================================================================
	/**
	 * Takes an array created by explode_path() and reconstitutes it into a proper path.
	 */
	protected function reconstruct_path(array $pathArr) {
		//setup the path variable.
		$path = "";
		foreach($pathArr as $index=>$tagName) {
			//add this tag to the current path.
			$path = $this->create_list($path, $tagName, '/');
		}

		//add the leading '/'.
		$path = '/'. $path;

		//give 'em what they want.
		return($path);
	}//end reconstruct_path()
	//=================================================================================

	//=================================================================================
	protected function explode_path($path) {
		//make sure it has a leading slash.
		$path = preg_replace('/^\//', '', $path);
		$path = '/'. $path;

		//explode the path on slashes (/)
		$pathArr = explode('/', $path);

		//now, remove the first element, 'cuz it's blank.
		array_shift($pathArr);

		return($pathArr);
	}//end explode_path()
	//=================================================================================

	//=================================================================================
	/**
	 * Calls $this->a2p->get_data($path).  Just a wrapper for private data.
	 */
	public function get_data($path=NULL) {
		if(!is_null($path) && $path != '/') {
			$path = $this->fix_path($path);
		}

		$retval = $this->a2p->get_data($path);
		return($retval);
	}//end get_data()
	//=================================================================================

	//=================================================================================
	public function get_tag_value($path) {
		$usePath = $this->fix_path($path);
		$data = $this->a2p->get_data($usePath);
		if(isset($data[\cs_phpxmlCreator::dataIndex])) {
			$retval = $data[\cs_phpxmlCreator::dataIndex];
		}
		else {
			throw new exception(__METHOD__ .": invalid path (". $path .") or no value present");
		}
		return($retval);
	}//end get_tag_value()
	//=================================================================================

	//=================================================================================
	public function get_attribute($path, $attributeName=NULL) {
		$retval = NULL;
		if(!is_null($path)) {
			$path = preg_replace('/\/$/', '', $path);
			if(!$this->preserveCase) {
				$path = strtoupper($path);
				$attributeName = strtoupper($attributeName);
			}
			$data = $this->get_path($path);
			if(is_array($data[\cs_phpxmlCreator::attributeIndex])) {
				$data = $data[\cs_phpxmlCreator::attributeIndex];
				$retval = $data;
				if(!is_null($attributeName)) {
					if(isset($data[$attributeName])) {
						$retval = $data[$attributeName];
					}
					else {
						throw new exception(__METHOD__ .": no such attribute (". $attributeName .") on path=(". $path .")");
					}
				}
			}
			else {
				throw new exception(__METHOD__ .": no attributes found on path=(". $path .")");
			}
		}

		return($retval);

	}//end get_attribute()
	//=================================================================================

	//=================================================================================
	/**
	 * Break the path into bits, explicitely removing the rootElement from the
	 * given path: once numeric indexes have been added, the rootElement will
	 * then be prepended.
	 *
	 * NOTE: this must NOT be used when altering attributes of the root path or
	 * in the instance that the root element contains data.
	 */
	protected function fix_path($path) {
		if(!strlen($this->rootElement)) {
			throw new exception(__METHOD__ .": invalid root element");
		}
		if($path === '/') {
			$path = "";
		}
		else {
			$path = preg_replace('/\/$/', '', $path);
			if(!$this->preserveCase) {
				$path = strtoupper($path);
			}
			$path = preg_replace('/\/+/', '/', $path);

			$bits = $this->explode_path($path);

			//don't append '/0' if they're looking for an attribute or data value.
			$appendThis = null;
			{
				if($bits[(count($bits)-1)] == \cs_phpxmlCreator::dataIndex) {
					$appendThis = array_pop($bits);
				}
				if($bits[(count($bits)-1)] == \cs_phpxmlCreator::attributeIndex) {
					$appendThis = array_pop($bits);
				}
			}

			if(preg_match('/^\//', $path)) {
				/*  absolute path: first item MUST be root element, followed by 0 -- a higher number
				 *	would indicate multiple root elements.
				 */
				if(preg_match('/^\/'. $this->rootElement .'\/{0,1}/i', $path) || $path == '/') {
					array_shift($bits);
					if(preg_match('/^\/'. $this->rootElement .'\/0\/{0,1}/i', $path)) {
						array_shift($bits);
					}
				}
				else {
					throw new exception(__METHOD__ .": absolute paths must start with rootElement (". $this->rootElement ."), " .
							"and any numeric indexed directly following it MUST be zero (path: ". $path . ")");
				}
			}
			elseif(preg_match('/^'. $this->rootElement .'/i', $path)) {
				array_shift($bits);
				if(preg_match('/^'. $this->rootElement .'\/0/i', $path)) {
					array_shift($bits);
				}
			}

			/* the key::: each tag should have a number in the path beyond it.  So "/path/to/something" becomes
			 *	"/path/0/to/0/something/0", but "/path/to/1/something" must become "/path/0/to/1/something/0"
			 *	(instead of "/path/0/to/0/1/0/something/0" by automatically adding a 0 to each bit)
			 *
			 * The index handled should ALWAYS be a tag: should the next index be numeric, it will be skipped.
			 */

			if(count($bits) == 1 && (is_null($bits[0]) || strlen($bits[0]) == 0)) {
				$bits = array();
			}
			//this array will be transformed into a path again later.
			$useRoot = $this->rootElement;
			if(!$this->preserveCase) {
				$useRoot = strtoupper($this->rootElement);
			}
			$newBits = array(
				0	=> $useRoot,
				1	=> "0"
			);
			$highestBit = (count($bits) -1);
			for($i=0;$i<count($bits);$i++) {
				$currentBit = $bits[$i];
				if(is_numeric($currentBit)) {
					/*
					 * This happens when:
					 * 	-- there are two numerics in a row ("/path/0/0")
					 */
					throw new exception(__METHOD__ .": found numeric (". $currentBit .") where tag should have been");
				}
				else {
					//add this tag ($n) to the array
					$newBits[] = $currentBit;

					//make sure we don't go past the end of the array.
					if($i < $highestBit) {
						if(is_numeric($bits[($i+1)])) {
							//next item is numeric: put it into the path & skip it.
							$newBits[] = $bits[($i+1)];
							$i++;
						}
						else {
							$newBits[] = "0";
						}
					}
					else {
						//the next bit would have been beyond the end of the array, so the index would be 0.
						$newBits[] = "0";
						break;
					}
				}
			}

			if(!is_null($appendThis)) {
				$newBits[] = $appendThis;
			}
			$path = $this->reconstruct_path($newBits);
		}
		if(preg_match('/\/\//', $path)) {
			throw new exception(__METHOD__ .": path has too many slashes (". $path .")");
		}

		return($path);
	}//end fix_path()
	//=================================================================================

	//=================================================================================
	public function get_path($path=null) {
		$path = $this->fix_path($path);
		return($this->a2p->get_data($path));
	}//end get_path()
	//=================================================================================
}
?>


text:
{{field.value}}

{{field.value}}

{{field.value}}

***

{{field.value}}

{{field.value}}

    {{item.name}}

    {{item}}

        {{item.name}}: {{item.value}}

{{field.value | date:'mediumDate'}}

{{field.value | date:'mediumDate'}} {{field.value | date:'smallTime'}}

    Yes
    No

{{field.value}}


text:
namespace Scrumfish.WebApi.v2.ApiSite.Areas.HelpPage.ModelDescriptions
{
    public class DictionaryModelDescription : KeyValuePairModelDescription
    {
    }
}


text:
module RequestLogAnalyzer::RSpec::Macros
  def test_databases
    require 'yaml'
    hash = YAML.load(File.read("#{File.dirname(__FILE__)}/../database.yml"))
    hash.reduce({}) { |res, (name, h)| res[name] = h.map { |(k, v)| "#{k}=#{v}" }.join(';'); res  }
  end

  # Create or return a new TestingFormat
  def testing_format
    @testing_format ||= TestingFormat.create
  end

  def default_orm_class_names
    %w(Warning Request Source)
  end
end


text:
require 'spec_helper'
require Rails.root.join('db', 'post_migrate', '20180913142237_schedule_digest_personal_access_tokens.rb')

describe ScheduleDigestPersonalAccessTokens, :migration, :sidekiq do
  let(:personal_access_tokens) { table(:personal_access_tokens) }
  let(:users) { table(:users) }

  before do
    stub_const("#{described_class.name}::BATCH_SIZE", 4)

    users.create(id: 1, email: 'user@example.com', projects_limit: 10)

    personal_access_tokens.create!(id: 1, user_id: 1, name: 'pat-01', token: 'token-01')
    personal_access_tokens.create!(id: 2, user_id: 1, name: 'pat-02', token: 'token-02')
    personal_access_tokens.create!(id: 3, user_id: 1, name: 'pat-03', token_digest: 'token_digest')
    personal_access_tokens.create!(id: 4, user_id: 1, name: 'pat-04', token: 'token-04')
    personal_access_tokens.create!(id: 5, user_id: 1, name: 'pat-05', token: 'token-05')
    personal_access_tokens.create!(id: 6, user_id: 1, name: 'pat-06', token: 'token-06')
  end

  it 'correctly schedules background migrations' do
    Sidekiq::Testing.fake! do
      migrate!

      expect(described_class::MIGRATION).to(
        be_scheduled_delayed_migration(
          5.minutes, 'PersonalAccessToken', 'token', 'token_digest', 1, 5))
      expect(described_class::MIGRATION).to(
        be_scheduled_delayed_migration(
          10.minutes, 'PersonalAccessToken', 'token', 'token_digest', 6, 6))
      expect(BackgroundMigrationWorker.jobs.size).to eq 2
    end
  end

  it 'schedules background migrations' do
    perform_enqueued_jobs do
      plain_text_token = 'token IS NOT NULL'

      expect(personal_access_tokens.where(plain_text_token).count).to eq 5

      migrate!

      expect(personal_access_tokens.where(plain_text_token).count).to eq 0
    end
  end
end


text:
<!DOCTYPE html>

		<meta charset="utf-8">

		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

		<title>Nested 3 Cols</title>
		<meta name="description" content="">
		<meta name="author" content="mkerry">

		<meta name="viewport" content="width=device-width; initial-scale=1.0">

		<link rel="shortcut icon" href="/favicon.ico">
		<link rel="apple-touch-icon" href="/apple-touch-icon.png">

Nested 3 Cols

These 3 blocks should form 3 even columns at maximum screen width, then should change to 2 even columns for tablet, with blocks 2 and 3 stacked vertically on the right, and 1 for phone

 block 1

						Integer vitae dictum sem. Ut commodo dui a urna ullamcorper, sed consectetur magna tincidunt. Suspendisse sed nisi mauris. Donec volutpat ultricies magna volutpat porta. Duis et ipsum sagittis, consectetur nibh id, mollis ante. Proin ullamcorper ac lorem sed laoreet. Mauris molestie nulla eget augue tincidunt vulputate. Vestibulum id dui at sem semper rutrum. Duis eget interdum urna. Sed a massa in orci pulvinar elementum. Quisque lacinia eros purus, id dignissim erat imperdiet nec. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

 block 2

							Integer vitae dictum sem. Ut commodo dui a urna ullamcorper, sed consectetur magna tincidunt. Suspendisse sed nisi mauris. Donec volutpat ultricies magna volutpat porta. Duis et ipsum sagittis, consectetur nibh id, mollis ante. Proin ullamcorper ac lorem sed laoreet. Mauris molestie nulla eget augue tincidunt vulputate. Vestibulum id dui at sem semper rutrum. Duis eget interdum urna. Sed a massa in orci pulvinar elementum. Quisque lacinia eros purus, id dignissim erat imperdiet nec. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

 block 3

							Integer vitae dictum sem. Ut commodo dui a urna ullamcorper, sed consectetur magna tincidunt. Suspendisse sed nisi mauris. Donec volutpat ultricies magna volutpat porta. Duis et ipsum sagittis, consectetur nibh id, mollis ante. Proin ullamcorper ac lorem sed laoreet. Mauris molestie nulla eget augue tincidunt vulputate. Vestibulum id dui at sem semper rutrum. Duis eget interdum urna. Sed a massa in orci pulvinar elementum. Quisque lacinia eros purus, id dignissim erat imperdiet nec. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.


text:
cask 'sabaki' do
  version '0.35.1'
  sha256 'c70229f75ced3b45d5b1b79224fdda3eceadcda352f50c2c4815c7043b192951'

  # github.com/SabakiHQ/Sabaki was verified as official when first introduced to the cask
  url "https://github.com/SabakiHQ/Sabaki/releases/download/v#{version}/sabaki-v#{version}-mac-x64.7z"
  appcast 'https://github.com/SabakiHQ/Sabaki/releases.atom'
  name 'Sabaki'
  homepage 'https://sabaki.yichuanshen.de/'

  app 'Sabaki.app'
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:layout_marginTop="5dp"
    android:clipChildren="false"
    >

    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:cardCornerRadius="@dimen/menu_btn_radius"
        app:cardElevation="@dimen/menu_btn_elevation"
        app:cardBackgroundColor="@color/white"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:clipToPadding="false"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:orientation="vertical"
                android:layout_toLeftOf="@+id/li_btn"
                android:padding="10dp"
                >

                <TextView
                    android:id="@+id/tv_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Title"
                    android:textColor="@color/dark_gray"
                    android:textSize="25sp"
                    android:gravity="center"
                    />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/li_btn"
                android:layout_width="100dp"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_alignParentRight="true"
                >

                <Button
                    android:id="@+id/btn_select"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:background="@drawable/two_btn_active_right_radius"
                    android:text="@string/select_srt"
                    android:textColor="@color/white"
                    android:textSize="@dimen/default_font_size"
                    />

            </LinearLayout>

        </RelativeLayout>

    </android.support.v7.widget.CardView>
</LinearLayout>


text:
package com.intellij.lang.folding;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Allows a custom language plugin to define rules for folding code in the language handled
 * by the plugin.
 *
 * @author max
 * @see com.intellij.lang.folding.LanguageFolding#forLanguage(com.intellij.lang.Language)
 */

public abstract class FoldingBuilderEx implements FoldingBuilder {
  /**
   * Builds the folding regions for the specified node in the AST tree and its children.
   *
   * @param root     the element for which folding is requested.
   * @param document the document for which folding is built. Can be used to retrieve line
   *                 numbers for folding regions.
   * @param quick    whether the result should be provided as soon as possible. Is true, when
   *                 an editor is opened and we need to auto-fold something immediately, like Java imports.
   *                 If true, one should perform no reference resolving and avoid complex checks if possible.
   * @return the array of folding descriptors.
   */
  @NotNull
  public abstract FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick);

  @Override
  @NotNull
  public FoldingDescriptor[] buildFoldRegions(@NotNull ASTNode node, @NotNull Document document) {
    return buildFoldRegions(node.getPsi(), document, false);
  }

  /**
   * Returns the text which is displayed in the editor for the folding region related to the
   * specified node when the folding region is collapsed.
   *
   *
   * @param node the node for which the placeholder text is requested.
   * @param range text range within whole file to fold
   * @return the placeholder text.
   */
  @Nullable
  public String getPlaceholderText(@NotNull ASTNode node, @NotNull TextRange range){
    return getPlaceholderText(node);
  }

  /**
   * Returns the default collapsed state for the folding region related to the specified node.
   *
   * @param node the node for which the collapsed state is requested.
   * @return true if the region is collapsed by default, false otherwise.
   */
  @Override
  public abstract boolean isCollapsedByDefault(@NotNull ASTNode node);
}


text:
This is a java project to build a stand-alone server which implements the Swagger spec.  You can find out
more about both the spec and the framework at http://swagger.io.

### To run (with Maven)
To run the server, run this task:
```
mvn jetty:run-war
```

This will start Jetty embedded on port 8002.

### Testing the server
Once started, you can navigate to http://localhost:8002/api/swagger.json to view the Swagger Resource Listing.
This tells you that the server is up and ready to demonstrate Swagger.

### Using the UI
There is an HTML5-based API tool bundled in this sample--you can view it it at [http://localhost:8002](http://localhost:8002). This lets you inspect the API using an interactive UI.  You can access the source of this code from [here](https://github.com/swagger-api/swagger-ui)

You can then open the dist/index.html file in any HTML5-enabled browser.  Upen opening, enter the
URL of your server in the top-centered input box (default is http://localhost:8002/api/swagger.json).  Click the "Explore"
button and you should see the resources available on the server.

### Applying an API key
The sample app has an implementation of the Swagger ApiAuthorizationFilter.  This restricts access to resources
based on api-key.  There are two keys defined in the sample app:

- default-key

- special-key

When no key is applied, the "default-key" is applied to all operations.  If the "special-key" is entered, a
number of other resources are shown in the UI, including sample CRUD operations.


text:
package com.squareup.okhttp.contrib.oauth.signing;

import com.squareup.okhttp.contrib.oauth.OAuth;

public class RsaSha1SignatureMethod implements SignatureMethod {

    @Override
    public SignatureMethod withKey(String consumerSecret, String tokenSecret) throws SigningException {
        throw new SigningException("Not yet implemented", null);
    }

    @Override
    public String signatureOf(String baseString) throws SigningException {
        throw new SigningException("Not yet implemented", null);
    }

    @Override
    public String methodName() {
        return OAuth.SIGNATURE_METHOD_VALUE_RSA_SHA1;
    }
}


text:
package org.apache.camel.component.jms;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.ConnectionFactory;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.util.concurrent.ThreadHelper;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

/**
 *
 */
public class JmsDefaultTaskExecutorTypeTest extends CamelTestSupport {

    private static final Logger LOG = LoggerFactory.getLogger(JmsDefaultTaskExecutorTypeTest.class);
    @Rule public TestName name = new TestName();

    @Test
    public void testThreadPoolTaskExecutor() throws Exception {
        context.getRouteController().startRoute("threadPool");
        Long beforeThreadCount = currentThreadCount();
        getMockEndpoint("mock:result.threadPool").expectedMessageCount(1000);
        doSendMessages("foo.threadPool", 500, 5, DefaultTaskExecutorType.ThreadPool);
        Thread.sleep(100);
        doSendMessages("foo.threadPool", 500, 5, DefaultTaskExecutorType.ThreadPool);
        assertMockEndpointsSatisfied();
        Long numberThreadsCreated = currentThreadCount() - beforeThreadCount;
        LOG.info("Number of threads created, testThreadPoolTaskExecutor: " + numberThreadsCreated);
        assertTrue("Number of threads created should be equal or lower than "
                + "100 with ThreadPoolTaskExecutor", numberThreadsCreated <= 100);
    }

    @Test
    public void testSimpleAsyncTaskExecutor() throws Exception {
        context.getRouteController().startRoute("simpleAsync");
        Long beforeThreadCount = currentThreadCount();
        getMockEndpoint("mock:result.simpleAsync").expectedMessageCount(1000);
        doSendMessages("foo.simpleAsync", 500, 5, DefaultTaskExecutorType.SimpleAsync);
        Thread.sleep(100);
        doSendMessages("foo.simpleAsync", 500, 5, DefaultTaskExecutorType.SimpleAsync);
        assertMockEndpointsSatisfied();
        Long numberThreadsCreated = currentThreadCount() - beforeThreadCount;
        LOG.info("Number of threads created, testSimpleAsyncTaskExecutor: " + numberThreadsCreated);
        assertTrue("Number of threads created should be equal or higher than "
                + "800 with SimpleAsyncTaskExecutor", numberThreadsCreated >= 800);
    }

    @Test
    public void testDefaultTaskExecutor() throws Exception {
        context.getRouteController().startRoute("default");
        Long beforeThreadCount = currentThreadCount();
        getMockEndpoint("mock:result.default").expectedMessageCount(1000);
        doSendMessages("foo.default", 500, 5, null);
        Thread.sleep(100);
        doSendMessages("foo.default", 500, 5, null);
        assertMockEndpointsSatisfied();
        Long numberThreadsCreated = currentThreadCount() - beforeThreadCount;
        LOG.info("Number of threads created, testDefaultTaskExecutor: " + numberThreadsCreated);
        assertTrue("Number of threads created should be equal or higher than "
                + "800 with default behaviour", numberThreadsCreated >= 800);
    }

    @Test
    public void testDefaultTaskExecutorThreadPoolAtComponentConfig() throws Exception {
        // the default behaviour changes in this test, see createCamelContext method below
        // the behaviour is the same as with testThreadPoolTaskExecutor test method above
        context.getRouteController().startRoute("default");
        Long beforeThreadCount = currentThreadCount();
        getMockEndpoint("mock:result.default").expectedMessageCount(1000);
        doSendMessages("foo.default", 500, 5, DefaultTaskExecutorType.ThreadPool);
        Thread.sleep(100);
        doSendMessages("foo.default", 500, 5, DefaultTaskExecutorType.ThreadPool);
        assertMockEndpointsSatisfied();
        Long numberThreadsCreated = currentThreadCount() - beforeThreadCount;
        LOG.info("Number of threads created, testDefaultTaskExecutorThreadPoolAtComponentConfig: " + numberThreadsCreated);
        assertTrue("Number of threads created should be equal or lower than "
                + "100 with ThreadPoolTaskExecutor as a component default", numberThreadsCreated <= 100);
    }

    private Long currentThreadCount() throws NoSuchMethodException,
            IllegalAccessException, InvocationTargetException {
        Method m = ThreadHelper.class.getDeclaredMethod("nextThreadCounter", (Class<?>[]) null);
        m.setAccessible(true);
        Long nextThreadCount = (Long) m.invoke(null);
        return nextThreadCount;
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();
        ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
        JmsComponent jmsComponent = jmsComponentAutoAcknowledge(connectionFactory);
        jmsComponent.getConfiguration().setMaxMessagesPerTask(1);
        jmsComponent.getConfiguration().setIdleTaskExecutionLimit(1);
        jmsComponent.getConfiguration().setConcurrentConsumers(3);
        jmsComponent.getConfiguration().setMaxConcurrentConsumers(10);
        jmsComponent.getConfiguration().setReceiveTimeout(50);
        if ("testDefaultTaskExecutorThreadPoolAtComponentConfig".equals(getTestMethodName())) {
            jmsComponent.getConfiguration().setDefaultTaskExecutorType(DefaultTaskExecutorType.ThreadPool);
        }
        camelContext.addComponent("activemq", jmsComponent);
        return camelContext;
    }

    private void doSendMessages(final String queueName, int messages, int poolSize,
            final DefaultTaskExecutorType defaultTaskExecutorType) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(poolSize);
        final CountDownLatch latch = new CountDownLatch(messages);
        for (int i = 0; i < messages; i++) {
            final int index = i;
            executor.submit(() -> {
                String options = defaultTaskExecutorType == null ? "" : "?defaultTaskExecutorType="
                        + defaultTaskExecutorType.toString();
                template.requestBody("activemq:queue:" + queueName + options, "Message " + index);
                latch.countDown();
                return null;
            });
        }
        latch.await();
        executor.shutdown();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("activemq:queue:foo.simpleAsync?defaultTaskExecutorType=SimpleAsync").routeId("simpleAsync").noAutoStartup()
                    .to("mock:result.simpleAsync")
                    .setBody(constant("Reply"));

                from("activemq:queue:foo.threadPool?defaultTaskExecutorType=ThreadPool").routeId("threadPool").noAutoStartup()
                    .to("mock:result.threadPool")
                    .setBody(constant("Reply"));

                from("activemq:queue:foo.default").routeId("default").noAutoStartup()
                    .to("mock:result.default")
                    .setBody(constant("Reply"));
            }
        };
    }
}


text:
FROM ubuntu:16.04
MAINTAINER Christian Heitman

RUN apt-get -y update && \
    apt-get install -y graphviz z3 python-pip git

RUN useradd -m barf
USER barf
WORKDIR /home/barf
ENV HOME /home/barf

RUN git clone https://github.com/programa-stic/barf-project.git && \
    cd barf-project && \
    pip install .

CMD ["/bin/bash"]