text:
"""
The owsproxy is a service which acts as a proxy for registered OWS services.

The implementation of owsproxy is based on `papyrus_ogcproxy <https://github.com/elemoine/papyrus_ogcproxy>`_

See also: https://github.com/nive/outpost/blob/master/outpost/proxy.py
"""
import requests

from pyramid.response import Response
from pyramid.settings import asbool
from typing import TYPE_CHECKING

from twitcher.owsexceptions import OWSAccessForbidden, OWSAccessFailed
from twitcher.utils import (
    replace_caps_url,
    get_settings,
    get_twitcher_url,
    is_valid_url)

import logging
LOGGER = logging.getLogger('TWITCHER')

if TYPE_CHECKING:
    from twitcher.typedefs import AnySettingsContainer  # noqa: F401
    from pyramid.config import Configurator             # noqa: F401
    from typing import AnyStr                           # noqa: F401

allowed_content_types = (
    "application/xml",                       # XML
    "text/xml",
    "text/xml;charset=ISO-8859-1"
    "application/vnd.ogc.se_xml",            # OGC Service Exception
    "application/vnd.ogc.se+xml",            # OGC Service Exception
    # "application/vnd.ogc.success+xml",      # OGC Success (SLD Put)
    "application/vnd.ogc.wms_xml",           # WMS Capabilities
    # "application/vnd.ogc.gml",              # GML
    # "application/vnd.ogc.sld+xml",          # SLD
    "application/vnd.google-earth.kml+xml",  # KML
    "application/vnd.google-earth.kmz",
    "image/png",                             # PNG
    "image/png;mode=32bit",
    "image/gif",                             # GIF
    "image/jpeg",                            # JPEG
    "application/json",                      # JSON
    "application/json;charset=ISO-8859-1",
)

# TODO: configure allowed hosts
allowed_hosts = (
    # list allowed hosts here (no port limiting)
    # "localhost",
)

# requests.models.Response defaults its chunk size to 128 bytes, which is very slow
class BufferedResponse(object):
    def __init__(self, resp):
        self.resp = resp

    def __iter__(self):
        return self.resp.iter_content(64 * 1024)

def _send_request(request, service, extra_path=None, request_params=None):

    # TODO: fix way to build url
    url = service['url']
    if extra_path:
        url += '/' + extra_path
    if request_params:
        url += '?' + request_params
    LOGGER.debug('url = {}'.format(url))

    # forward request to target (without Host Header)
    h = dict(request.headers)
    h.pop("Host", h)
    h['Accept-Encoding'] = None
    #
    service_type = service.get('type', 'wps')
    service_verify = service.get('verify', True)
    if service_type and (service_type.lower() != 'wps'):
        try:
            resp_iter = requests.request(method=request.method.upper(), url=url, data=request.body, headers=h,
                                         stream=True, verify=service_verify)
        except Exception as e:
            return OWSAccessFailed("Request failed: {}".format(e))

        # Headers meaningful only for a single transport-level connection
        hop_by_hop = ['connection', 'keep-alive', 'public', 'proxy-authenticate', 'transfer-encoding', 'upgrade']
        return Response(app_iter=BufferedResponse(resp_iter),
                        headers={k: v for k, v in list(resp_iter.headers.items()) if k.lower() not in hop_by_hop},
                        status_code=resp_iter.status_code)
    else:
        try:
            resp = requests.request(method=request.method.upper(), url=url, data=request.body, headers=h,
                                    verify=service_verify)
        except Exception as e:
            return OWSAccessFailed("Request failed: {}".format(e))

        if resp.ok is False:
            if 'ExceptionReport' in resp.text:
                pass
            else:
                return OWSAccessFailed("Response is not ok: {}".format(resp.reason))

        # check for allowed content types
        ct = None
        # LOGGER.debug("headers=", resp.headers)
        if "Content-Type" in resp.headers:
            ct = resp.headers["Content-Type"]
            if not ct.split(";")[0] in allowed_content_types:
                msg = "Content type is not allowed: {}.".format(ct)
                LOGGER.error(msg)
                return OWSAccessForbidden(msg)
        else:
            # return OWSAccessFailed("Could not get content type from response.")
            LOGGER.warn("Could not get content type from response")

        try:
            if ct in ['text/xml', 'application/xml', 'text/xml;charset=ISO-8859-1']:
                # replace urls in xml content
                # ... if public URL is not configured use proxy url.
                if is_valid_url(service.get('purl')):
                    public_url = service['purl']
                else:
                    public_url = request.route_url('owsproxy', service_name=service['name'])
                # TODO: where do i need to replace urls?
                content = replace_caps_url(resp.content, public_url, service['url'])
            else:
                # raw content
                content = resp.content
        except Exception:
            return OWSAccessFailed("Could not decode content.")

        headers = {}
        if ct:
            headers["Content-Type"] = ct
        return Response(content, status=resp.status_code, headers=headers)

def owsproxy_base_path(container):
    # type: (AnySettingsContainer) -> AnyStr
    settings = get_settings(container)
    return settings.get('twitcher.ows_proxy_protected_path', '/ows').rstrip('/').strip()

def owsproxy_base_url(container):
    # type: (AnySettingsContainer) -> AnyStr
    twitcher_url = get_twitcher_url(container)
    owsproxy_path = owsproxy_base_path(container)
    return twitcher_url + owsproxy_path

def owsproxy_view(request):
    try:
        service_name = request.matchdict.get('service_name')
        extra_path = request.matchdict.get('extra_path')
        service = request.owsregistry.get_service_by_name(service_name)
    except Exception:
        return OWSAccessFailed("Could not find service")
    if request.is_verified is False:
        raise OWSAccessForbidden("Access to service is forbidden.")
    return _send_request(request, service, extra_path, request_params=request.query_string)

def owsproxy_defaultconfig(config):
    # type: (Configurator) -> None
    settings = get_settings(config)
    if asbool(settings.get('twitcher.ows_proxy', True)):
        protected_path = owsproxy_base_path(settings)

        config.include('twitcher.oauth2')
        config.include('twitcher.owsregistry')
        config.include('twitcher.owssecurity')
        config.add_route('owsproxy', protected_path + '/proxy/{service_name}')
        config.add_route('owsproxy_extra', protected_path + '/proxy/{service_name}/{extra_path:.*}')
        config.add_view(owsproxy_view, route_name='owsproxy')
        config.add_view(owsproxy_view, route_name='owsproxy_extra')

def includeme(config):
    from twitcher.adapter import get_adapter_factory
    get_adapter_factory(config).owsproxy_config(config)


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Dialog Example</title>

	<link rel="stylesheet" href="docs.css">
	<link rel="stylesheet" href="src/dialog.css">

Filament Group

<p class="docs">
  <a href="#mydialog" id="mydialog-btn">Open Dialog</a>
</p>

<div class="dialog" id="mydialog">
  <p>This is a dialog</p>
  <a href="#mydialog-btn" class="dialog-close">Close</a>
</div>

			Open Dialog

This is a dialog

			Close

<p class="docs">
  <a href="#mytransparentdialog" id="mytransparentdialog-btn">Open Dialog with Transparent Background</a>
</p>

<div class="dialog" id="mytransparentdialog" data-transbg>
  <p>This is a dialog with a transparent background</p>
  <a href="#mytransparentdialog-btn" class="dialog-close">Close</a>
</div>

			Open Dialog with Transparent Background

This is a dialog with a transparent background

			Close

<p class="docs">
  <a href="example-external.html" data-dialog-link>Open Ajax Dialog</a>
</p>

			Open Ajax Dialog

redpajama_set_name: RedPajamaGithub


text:
package org.mifos.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ResourceUtils;

/**
 * Load resources from the classpath.
 */
public final class MifosResourceUtil {
    private MifosResourceUtil() {
    }

    private static final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    public static File getFile(String fileNameWithLocation) {
        File file;
        try {
            file = ResourceUtils.getFile(fileNameWithLocation);
        } catch (FileNotFoundException e) {
            throw new MifosRuntimeException("file not found :" + fileNameWithLocation, e);
        }
        return file;
    }

    private static File getFile(String location, String fileName) {
        return getFile(location + fileName);
    }

    public static Reader getSQLFileAsReader(String fileName) throws FileNotFoundException {
        return new FileReader(getFile("/sql/", fileName));
    }

    public static InputStream getSQLFileAsStream(String fileName) throws FileNotFoundException {
        return new FileInputStream(getFile("/sql/" + fileName));
    }

    /**
     * Should be avoided, because an InputStream needs to be closed by somebody, more clear if caller creates the IS from a Resource.
     * Use {@link #getClassPathResourceAsResource(String)} instead.
     */
    public static InputStream getClassPathResourceAsStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    }

    public static Resource getClassPathResourceAsResource(String fileName) throws IOException {
        return new ClassPathResource(fileName);
    }

    /**
     * Find a Resource on the Classpath and return it's URI (as a String).
     *
     * Intended for calling code which accepts URI, such as the javax.xml APIs. Better than File-based API, which should
     * never be used. Better than InputStream, because an InputStream needs to be closed by somebody - and that's
     * usually forgotten.
     *
     * If calling code can deal directly with a org.springframework.core.io.Resource, that's always preferable over a
     * raw URI; simply use new ClassPathResource(path) in that case.
     *
     * @param path Path on the classpath, e.g. "org/mifos/something.xml"
     * @return a Stringified Classpath URI
     */
    public static String getClassPathResourceAsURIString(String path) throws IOException {
        return new ClassPathResource(path).getURI().toString();
    }

    /**
     * Returns all classpath resources matching a certain pattern.
     *
     * @param pattern an Ant-style "/"-based (not "."-based) resource path pattern, WITHOUT any prefix
     * (like "classpath:" or "classpath*:"); so e.g. "org/mifos/package/**/*.xml".
     * @return an array of {@link Resource}. These may not actually be ClassPathResource instance, but any Resource (e.g. FileSystemResource)
     * @throws IOException in case of I/O errors
     */
    public static Resource[] getClassPathResourcesAsResources(String pattern) throws IOException {
        return resourcePatternResolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/" + pattern);
    }
}


text:
require 'thor'
require 'gitx'
require 'gitx/cli/base_command'

module Gitx
  module Cli
    class CleanupCommand < BaseCommand
      desc 'cleanup', 'Cleanup branches that have been merged into main from the repo'
      def cleanup
        update_base_branch
        say 'Deleting local and remote branches that have been merged into '
        say config.base_branch, :green
        filtered_merged_branches(:remote).each do |branch|
          run_git_cmd 'push', 'origin', '--delete', branch
        end
        filtered_merged_branches(:local).each do |branch|
          run_git_cmd 'branch', '--delete', branch
        end
      end

      private

      def update_base_branch
        checkout_branch config.base_branch
        run_git_cmd 'pull'
        run_git_cmd 'remote', 'prune', 'origin'
      end

      # @return list of branches that have been merged
      # filter out reserved and aggregate branches
      def filtered_merged_branches(source)
        merged_branches(source).select do |branch|
          deletable_branch?(branch)
        end
      end

      def deletable_branch?(branch)
        return false if config.reserved_branches.include?(branch)
        return false if config.aggregate_branch?(branch)
        return false if config.base_branch == branch

        true
      end

      # @return list of branches that have been merged
      # see http://stackoverflow.com/questions/26804024/git-branch-merged-sha-via-rugged-libgit2-bindings
      def merged_branches(source)
        merged_branches = repo.branches.each(source).select do |branch|
          target = branch.resolve.target
          repo.merge_base(base_branch_merge_target, target) == target.oid
        end
        merged_branches.map do |branch|
          branch.name.gsub('origin/', '')
        end
      end

      def base_branch_merge_target
        repo.head.target
      end
    end
  end
end


text:
<<<<<<< HEAD
##What is it?
This is a smart package built for use with Meteor and the Twitter Bootstrap library, using the [example defined here](http://datatables.net/blog/Twitter_Bootstrap_2) as a basis.

##How to install
1. `npm install -g meteorite` (if not already installed)
2. `mrt add datatables`

##HTML & Javascript quick start

              Rendering engine
              Browser
              Platform(s)
              Engine version
              CSS grade

              Trident
              Internet
                 Explorer 4.0
              Win 95+
               4
              X

##

    $('#example').dataTable({
        "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>"
        , "sPaginationType": "bootstrap"
        , "oLanguage": {
            "sLengthMenu": "_MENU_ records per page"
        }
    });

You can learn more about the [DataTables API here](http://datatables.net/index).
=======
data-bootstrap-3
================

Datatables packages for meteor and with bootstrap 3 syntax but without the css
>>>>>>> 293a3f5b5d165df4e2eb3a07a6a2799f4bbf5091


text:
class AddIdentifierToQbrickPages < ActiveRecord::Migration
  def change
    add_column :qbrick_pages, :identifier, :string
    add_index :qbrick_pages, :identifier, unique: true
  end
end


text:
#ifndef TB_REGEX_PREFIX_H
#define TB_REGEX_PREFIX_H

/* //////////////////////////////////////////////////////////////////////////////////////
 * includes
 */
#include "../prefix.h"
#include "../libc/libc.h"
#include "../container/container.h"

#endif


text:
"""
Universe Notebook Widget
#########################
To visualize a universe containing atoms, molecules, orbitals, etc., do
the following in a Jupyter notebook environment.

.. code-block:: Python

    exatomic.UniverseWidget(u)    # type(u) is exatomic.core.universe.Universe

"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
#from traitlets import Unicode, link
from traitlets import Unicode
from ipywidgets import (Button, Dropdown, jslink, register, VBox, HBox,
                        IntSlider, IntRangeSlider, FloatSlider, Play,
                        FloatText, Layout, Text, Label)
from .widget_base import (ExatomicScene, UniverseScene,
                          TensorScene, ExatomicBox)
from .widget_utils import _wlo, _ListDict, Folder
from .traits import uni_traits
from exatomic.core.tensor import Tensor

class DemoContainer(ExatomicBox):
    """A proof-of-concept mixing GUI controls with a three.js scene."""
    def _field_folder(self, **kwargs):
        """Folder that houses field GUI controls."""
        folder = super(DemoContainer, self)._field_folder(**kwargs)
        fopts = Dropdown(options=['null', 'Sphere', 'Torus', 'Ellipsoid'])
        fopts.active = True
        fopts.disabled = False
        def _field(c):
            for scn in self.active():
                scn.field = c.new
        fopts.observe(_field, names='value')
        folder.insert(1, 'options', fopts)
        return folder

    def _init_gui(self, **kwargs):
        """Initialize generic GUI controls and observe callbacks."""
        mainopts = super(DemoContainer, self)._init_gui()
        geom = Button(icon='gear', description=' Mesh', layout=_wlo)
        def _geom(b):
            for scn in self.active():
                scn.geom = not scn.geom
        geom.on_click(_geom)
        mainopts.update([('geom', geom),
                         ('field', self._field_folder(**kwargs))])
        return mainopts

    def __init__(self, *scenes, **kwargs):
        super(DemoContainer, self).__init__(*scenes,
                                            uni=False,
                                            test=True,
                                            typ=ExatomicScene,
                                            **kwargs)

@register
class TensorContainer(ExatomicBox):
    """
    A simple container to implement cartesian tensor visualization.

    Args:
        file_path (string): Takes a file path name to pass through the Tensor.from_file function. Default to None.
    """
    _model_name = Unicode('TensorContainerModel').tag(sync=True)
    _view_name = Unicode('TensorContainerView').tag(sync=True)

    def _update_active(self, b):
        """
        Control which scenes are controlled by the GUI.

        Additionally align traits with active scenes so that
        the GUI reflects that correct values of active scenes.
        """
        super(TensorContainer, self)._update_active(b)
        scns = self.active()
        if not scns or len(scns) == 1: return
        carts = ['x', 'y', 'z']
        cache = {}
        for i in carts:
            for j in carts:
                tij = 't' + i + j
                cache[tij] = getattr(scns[0], tij)
        for tij, val in cache.items():
            for scn in scns[1:]:
                setattr(scn, tij, val)

    def _init_gui(self, **kwargs):
        """Initialize generic GUI controls and observe callbacks."""
        mainopts = super(TensorContainer, self)._init_gui(**kwargs)
        scn = self.scenes[0]
        alo = Layout(width='74px')
        rlo = Layout(width='235px')
        if self._df is not None:
            scn.txx = self._df.loc[0,'xx']
            scn.txy = self._df.loc[0,'xy']
            scn.txz = self._df.loc[0,'xz']
            scn.tyx = self._df.loc[0,'yx']
            scn.tyy = self._df.loc[0,'yy']
            scn.tyz = self._df.loc[0,'yz']
            scn.tzx = self._df.loc[0,'zx']
            scn.tzy = self._df.loc[0,'zy']
            scn.tzz = self._df.loc[0,'zz']
        xs = [FloatText(value=scn.txx , layout=alo),
              FloatText(value=scn.txy , layout=alo),
              FloatText(value=scn.txz , layout=alo)]
        ys = [FloatText(value=scn.tyx , layout=alo),
              FloatText(value=scn.tyy , layout=alo),
              FloatText(value=scn.tyz , layout=alo)]
        zs = [FloatText(value=scn.tzx , layout=alo),
              FloatText(value=scn.tzy , layout=alo),
              FloatText(value=scn.tzz , layout=alo)]
        #scale =  FloatSlider(max=10.0, step=0.01, readout=True, value=1.0)
        opt = [0] if self._df is None else [int(x) for x in self._df.index.values]
        tensorIndex = Dropdown(options=opt, value=opt[0], layout=rlo)
        tdxlabel = Label(value='Select the tensor index:')
        def _x0(c):
            for scn in self.active(): scn.txx = c.new
        def _x1(c):
            for scn in self.active(): scn.txy = c.new
        def _x2(c):
            for scn in self.active(): scn.txz = c.new
        def _y0(c):
            for scn in self.active(): scn.tyx = c.new
        def _y1(c):
            for scn in self.active(): scn.tyy = c.new
        def _y2(c):
            for scn in self.active(): scn.tyz = c.new
        def _z0(c):
            for scn in self.active(): scn.tzx = c.new
        def _z1(c):
            for scn in self.active(): scn.tzy = c.new
        def _z2(c):
            for scn in self.active(): scn.tzz = c.new
        xs[0].observe(_x0, names='value')
        xs[1].observe(_x1, names='value')
        xs[2].observe(_x2, names='value')
        ys[0].observe(_y0, names='value')
        ys[1].observe(_y1, names='value')
        ys[2].observe(_y2, names='value')
        zs[0].observe(_z0, names='value')
        zs[1].observe(_z1, names='value')
        zs[2].observe(_z2, names='value')
        rlo = Layout(width='234px')
        xbox = HBox(xs, layout=rlo)
        ybox = HBox(ys, layout=rlo)
        zbox = HBox(zs, layout=rlo)
        geom = Button(icon='cubes', description=' Geometry', layout=_wlo)

        def _change_tensor(tdx=0):
            carts = ['x','y','z']
            for i, bra in enumerate(carts):
                for j, ket in enumerate(carts):
                    if i == 0:
                        xs[j].value = self._df.loc[tdx,bra+ket]
                    elif i == 1:
                        ys[j].value = self._df.loc[tdx,bra+ket]
                    elif i == 2:
                        zs[j].value = self._df.loc[tdx,bra+ket]

        def _geom(b):
            for scn in self.active(): scn.geom = not scn.geom

        def _tdx(c):
            for scn in self.active(): scn.tdx = c.new
            _change_tensor(c.new)

        geom.on_click(_geom)
        tensorIndex.observe(_tdx, names="value")
        mainopts.update([('geom', geom),
                         ('tlbl', tdxlabel),
                         ('tidx', tensorIndex),
                         ('xbox', xbox),
                         ('ybox', ybox),
                         ('zbox', zbox)])
        return mainopts

    def __init__(self, *args, **kwargs):
        file_path = kwargs.pop("file_path", None)
        if file_path is not None:
            self._df = Tensor.from_file(file_path)
        else:
            self._df = None
        super(TensorContainer, self).__init__(*args,
                                              uni=False,
                                              test=False,
                                              typ=TensorScene,
                                              **kwargs)

class DemoUniverse(ExatomicBox):
    """A showcase of functional forms used in quantum chemistry."""
    def _update_active(self, b):
        """
        Control which scenes are controlled by the GUI.

        Additionally align traits with active scenes so that
        the GUI reflects that correct values of active scenes.
        """
        super(DemoUniverse, self)._update_active(b)
        scns = self.active()
        if not scns: return
        flds = [scn.field for scn in scns]
        fks = [scn.field_kind for scn in scns]
        fmls = [scn.field_ml for scn in scns]
        folder = self._controls['field']
        fopts = folder['fopts'].options
        fld = flds[0]
        fk = fks[0]
        fml = fmls[0]
        if not len(set(flds)) == 1:
            for scn in scns: scn.field = fld
        if not len(set(fks)) == 1:
            for scn in scns: scn.field_kind = fk
        if not len(set(fmls)) == 1:
            for scn in scns: scn.field_ml = fml
        folder[fld].value = fk
        folder.activate(fld, enable=True)
        folder.deactivate(*[f for f in fopts if f != fld])
        if fld == 'SolidHarmonic':
            ofks = [str(i) for i in range(8) if str(i) != fk]
            folder.activate(fk, enable=True)
            folder.deactivate(*ofks)
        folder._set_gui()

    def _field_folder(self, **kwargs):
        """Folder that houses field GUI controls."""
        folder = super(DemoUniverse, self)._field_folder(**kwargs)
        uni_field_lists = _ListDict([
            ('Hydrogenic', ['1s',   '2s',   '2px', '2py', '2pz',
                            '3s',   '3px',  '3py', '3pz',
                            '3d-2', '3d-1', '3d0', '3d+1', '3d+2']),
            ('Gaussian', ['s', 'px', 'py', 'pz', 'd200', 'd110',
                          'd101', 'd020', 'd011', 'd002', 'f300',
                          'f210', 'f201', 'f120', 'f111', 'f102',
                          'f030', 'f021', 'f012', 'f003']),
            ('SolidHarmonic', [str(i) for i in range(8)])])
        kind_widgets = _ListDict([
            (key, Dropdown(options=vals))
            for key, vals in uni_field_lists.items()])
        ml_widgets = _ListDict([
            (str(l), Dropdown(options=[str(i) for i in range(-l, l+1)]))
            for l in range(8)])
        fopts = list(uni_field_lists.keys())
        folder.update(kind_widgets, relayout=True)
        folder.update(ml_widgets, relayout=True)

        def _field(c):
            fk = uni_field_lists[c.new][0]
            for scn in self.active():
                scn.field = c.new
                scn.field_kind = fk
            folder.deactivate(c.old)
            folder[c.new].value = fk
            folder.activate(c.new, enable=True)
            if c.new == 'SolidHarmonic':
                folder.activate(fk, enable=True)
            else:
                aml = [key for key in folder._get(keys=True)
                       if key.isnumeric()]
                if aml:
                    folder.deactivate(*aml)
            folder._set_gui()

        def _field_kind(c):
            for scn in self.active():
                scn.field_kind = c.new
                if scn.field == 'SolidHarmonic':
                    scn.field_ml = folder[c.new].options[0]
                    folder.activate(c.new, enable=True)
                    folder.deactivate(c.old)
                    if scn.field_ml != '0':
                        folder.deactivate('0')
                else:
                    aml = [i for i in folder._get(keys=True)
                           if i.isnumeric()]
                    if aml:
                        folder.deactivate(*aml)
            folder._set_gui()

        def _field_ml(c):
            for scn in self.active(): scn.field_ml = c.new

        for key, obj in kind_widgets.items():
            folder.deactivate(key)
            obj.observe(_field_kind, names='value')
        for key, obj in ml_widgets.items():
            folder.deactivate(key)
            obj.observe(_field_ml, names='value')
        fopts = Dropdown(options=fopts)
        fopts.observe(_field, names='value')
        folder.insert(1, 'fopts', fopts)
        folder.activate('Hydrogenic', enable=True, update=True)
        folder.move_to_end('alpha', 'iso', 'nx', 'ny', 'nz')
        return folder

    def _init_gui(self, **kwargs):
        """Initialize generic GUI controls and observe callbacks."""
        for scn in self.scenes:
            for attr in ['field_ox', 'field_oy', 'field_oz']:
                setattr(scn, attr, -30.0)
            for attr in ['field_fx', 'field_fy', 'field_fz']:
                setattr(scn, attr, 30.0)
            scn.field = 'Hydrogenic'
            scn.field_iso = 0.0005
            scn.field_kind = '1s'
        mainopts = super(DemoUniverse, self)._init_gui()
        mainopts.update([('field', self._field_folder(**kwargs))])
        return mainopts

    def __init__(self, *scenes, **kwargs):
        super(DemoUniverse, self).__init__(*scenes, uni=True, test=True,
                                           typ=ExatomicScene, **kwargs)

@register
class UniverseWidget(ExatomicBox):
    """
    Visualize a :class:`~exatomic.core.universe.Universe`.

    .. code-block:: python

        u = exatomic.Universe.load(exatomic.base.resource("adf-lu-valid.hdf5"))
        scenekwargs = dict(atomcolors=dict(Lu="black"))
        exatomic.UniverseWidget(u, scenekwargs=scenekwargs)    # In Jupyter notebook

        scenekwargs = dict(atomcolors=dict(Lu="#f442f1"), atomradii=dict(Lu=1.0))
        exatomic.UniverseWidget(u, scenekwargs=scenekwargs)    # In Jupyter notebook

    Args:
        uni: The Universe object
        scenekwargs (dict): Keyword args to be passed to :class:`~exatomic.widgets.widget_base.ExatomicScene`
    """
    def _frame_folder(self, nframes):
        playable = bool(nframes <= 1)
        flims = dict(min=0, max=nframes-1, step=1, value=0)
        control = Button(description=' Animate', icon='play')
        content = _ListDict([
            ('playing', Play(disabled=playable, **flims)),
            ('scn_frame', IntSlider(description='Frame', **flims))])

        def _scn_frame(c):
            for scn in self.active(): scn.frame_idx = c.new

        content['scn_frame'].observe(_scn_frame, names='value')
        content['playing'].active = False
        jslink((content['playing'], 'value'),
               (content['scn_frame'], 'value'))
        folder = Folder(control, content)
        return folder

    def _field_folder(self, fields, **kwargs):
        folder = super(UniverseWidget, self)._field_folder(**kwargs)
        folder.deactivate('nx', 'ny', 'nz')
        fopts = Dropdown(options=fields)
        def _fopts(c):
            for scn in self.active(): scn.field_idx = c.new
        fopts.observe(_fopts, names='value')
        folder['fopts'] = fopts
        return folder

    def _iso_folder(self, folder):
        isos = Button(description=' Isosurfaces', icon='cube')
        def _fshow(b):
            for scn in self.active(): scn.field_show = not scn.field_show
        isos.on_click(_fshow)
        isofolder = Folder(isos, _ListDict([
            ('fopts', folder['fopts']),
            ('alpha', folder.pop('alpha')),
            ('iso', folder.pop('iso'))]))
        isofolder.move_to_end('alpha', 'iso')
        folder.insert(1, 'iso', isofolder, active=True)

    def _contour_folder(self, folder):
        control = Button(description=' Contours', icon='dot-circle-o')
        def _cshow(b):
            for scn in self.active(): scn.cont_show = not scn.cont_show
        control.on_click(_cshow)
        content = _ListDict([
            ('fopts', folder['fopts']),
            ('axis', Dropdown(options=['x', 'y', 'z'], value='z')),
            ('num', IntSlider(description='N', min=5, max=20,
                              value=10, step=1)),
            ('lim', IntRangeSlider(description='10**Limits', min=-8,
                                   max=0, step=1, value=[-7, -1])),
            ('val', FloatSlider(description='Value',
                                min=-5, max=5, value=0))])
        def _cont_axis(c):
            for scn in self.active(): scn.cont_axis = c.new
        def _cont_num(c):
            for scn in self.active(): scn.cont_num = c.new
        def _cont_lim(c):
            for scn in self.active(): scn.cont_lim = c.new
        def _cont_val(c):
            for scn in self.active(): scn.cont_val = c.new
        content['axis'].observe(_cont_axis, names='value')
        content['num'].observe(_cont_num, names='value')
        content['lim'].observe(_cont_lim, names='value')
        content['val'].observe(_cont_val, names='value')
        contour = Folder(control, content)
        folder.insert(2, 'contour', contour, active=True, update=True)

#    def _filter_labels(self,scn=0):
#        labels = []
#        filtered = self.active()[scn].atom_l.strip('[[')
#        filtered = filtered.strip(']]')
#        lbls = filtered.split(',')
#        for i in range(len(lbls)):
#            if lbls[i] != "":
#                labels.append(lbls[i].strip('"'))
#        return labels

    def _filter_coords(self,scn=0):
        coords = []
        filtered = [self.active()[scn].atom_x.strip('[['),
                    self.active()[scn].atom_y.strip('[['),
                    self.active()[scn].atom_z.strip('[[')]
        filtered = [filtered[0].strip(']]'),
                    filtered[1].strip(']]'),
                    filtered[2].strip(']]')]
        lbls = [filtered[0].split(','),
                filtered[1].split(','),
                filtered[2].split(',')]
        for rows in lbls:
            coords.append([])
            for cols in rows:
                if cols != "":
                    coords[-1].append(float(cols))
        return coords

    def _tensor_folder(self):
        alo = Layout(width='70px')
        rlo = Layout(width='220px')
        scale =  FloatSlider(max=10.0, step=0.001, readout=True, value=1.0)
        xs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        ys = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        zs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        cs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        cidx = HBox([Text(disabled=True,description='Atom Index',layout=rlo)])
        xbox = HBox(xs, layout=rlo)
        ybox = HBox(ys, layout=rlo)
        zbox = HBox(zs, layout=rlo)
        cbox = HBox(cs, layout=rlo)
        tens = Button(description=' Tensor', icon='bank')
        tensor_cont = VBox([xbox,ybox,zbox])
        tensorIndex = Dropdown(options=[0],value=0,description='Tensor')
#        sceneIndex = Dropdown(options=[0],value=0,description='Scene')
        ten_label = Label(value="Change selected tensor:")
        sel_label = Label(value="Selected tensor in gray frame")
        cod_label = Label(value="Center of selected tensor: (x,y,z)")
        tensor = []
        self.coords = []

        def _changeTensor(tensor, tdx):
            carts = ['x','y','z']
            for i,bra in enumerate(carts):
                for j,ket in enumerate(carts):
                    tensor_cont.children[i].children[j].disabled=False
                    tensor_cont.children[i].children[j].value = \
                                            str(tensor[0][tdx][bra+ket])
                    tensor_cont.children[i].children[j].disabled=True
            adx = tensor[0][tdx]['atom']
            cidx.children[0].value = str(adx)
            cbox.children[0].value = str(self.coords[0][int(adx)])
            cbox.children[1].value = str(self.coords[1][int(adx)])
            cbox.children[2].value = str(self.coords[2][int(adx)])
#            scale.value = tensor[0][tdx]['scale']

        def _tens(c):
            for scn in self.active(): scn.tens = not scn.tens
            self.coords = self._filter_coords()
#            sceneIndex.options = [x for x in range(len(self.active()))]
#            sceneIndex.value = sceneIndex.options[0]
            tensor = self.active()[0].tensor_d
            tensorIndex.options = [x for x in range(len(tensor[0]))]
            tensorIndex.value = tensorIndex.options[0]
            tdx = tensorIndex.value
            _changeTensor(tensor, tdx)

        def _scale(c):
            for scn in self.active(): scn.scale = c.new
#            tdx = tensorIndex.value
#            tensor = self.active()[0].tensor_d
#            tensor[0][tdx]['scale'] = c.new

        def _idx(c):
            for scn in self.active(): scn.tidx = c.new
            tensor = self.active()[0].tensor_d
            tdx = c.new
            _changeTensor(tensor, tdx)

#        def _sdx(c):
#            tensor = self.active()[sceneIndex.value].tensor_d
#            tensorIndex.options = [x for x in range(len(tensor[0]))]
#            tensorIndex.value = tensorIndex.options[0]
#            tdx = tensorIndex.value
#            _changeTensor(tensor, tdx)

        tens.on_click(_tens)
        scale.observe(_scale, names='value')
        tensorIndex.observe(_idx, names='value')
#        sceneIndex.observe(_sdx, names='value')
        content = _ListDict([
                ('scale', scale),
                ('ten', ten_label),
#               ('sdx', sceneIndex),
                ('tdx', tensorIndex),
                ('tensor', tensor_cont),
                ('sel', sel_label),
                ('cidx', cidx),
                ('center', cod_label),
                ('coord', cbox)])
        return Folder(tens, content)

    def _init_gui(self, **kwargs):
        nframes = kwargs.pop("nframes", 1)
        fields = kwargs.pop("fields", None)
        tensors = kwargs.pop("tensors", None)
        mainopts = super(UniverseWidget, self)._init_gui(**kwargs)
        atoms = Button(description=' Fill', icon='adjust', layout=_wlo)
        axis = Button(description=' Axis', icon='arrows-alt', layout=_wlo)

        def _atom_3d(b):
            for scn in self.active(): scn.atom_3d = not scn.atom_3d

        def _axis(b):
            for scn in self.active(): scn.axis = not scn.axis

        atoms.on_click(_atom_3d)
        axis.on_click(_axis)
        atoms.active = True
        atoms.disabled = False
        axis.active = True
        atoms.disabled = False
        mainopts.update([('atom_3d', atoms), ('axis', axis),
                         ('frame', self._frame_folder(nframes))])
        if fields is not None:
            folder = self._field_folder(fields, **kwargs)
            self._iso_folder(folder)
            self._contour_folder(folder)
            folder.pop('fopts')
            mainopts.update([('field', folder)])

        if tensors is not None:
            mainopts.update([('tensor', self._tensor_folder())])

        return mainopts

    def __init__(self, *unis, **kwargs):
        scenekwargs = kwargs.pop('scenekwargs', {})
        scenekwargs.update({'uni': True, 'test': False})
        atomcolors = scenekwargs.get('atomcolors', None)
        atomradii = scenekwargs.get('atomradii', None)
        atomlabels = scenekwargs.get('atomlabels', None)
        fields, masterkwargs = [], []
        tensors = []
        for uni in unis:
            unargs, flds, tens = uni_traits(uni,
                                            atomcolors=atomcolors,
                                            atomradii=atomradii,
                                            atomlabels=atomlabels)
            tensors = tens
            fields = flds if len(flds) > len(fields) else fields
            unargs.update(scenekwargs)
            masterkwargs.append(unargs)
        nframes = max((uni.atom.nframes
                      for uni in unis)) if len(unis) else 1
        super(UniverseWidget, self).__init__(*masterkwargs,
                                             uni=True,
                                             test=False,
                                             nframes=nframes,
                                             fields=fields,
                                             typ=UniverseScene,
                                             tensors=tensors,
                                             **kwargs)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 12: 341 (1967)

#### Original name
Lecania hookeri C.W. Dodge

### Remarks
null


text:
TopContainerView::TopContainerView(BrowserView* browser_view)
    : browser_view_(browser_view) {
}

TopContainerView::~TopContainerView() {
}

const char* TopContainerView::GetClassName() const {
  return "TopContainerView";
}

void TopContainerView::PaintChildren(const ui::PaintContext& context) {
  if (browser_view_->immersive_mode_controller()->IsRevealed()) {
    // Top-views depend on parts of the frame (themes, window title,
    // window controls) being painted underneath them. Clip rect has already
    // been set to the bounds of this view, so just paint the frame.
    views::View* frame = browser_view_->frame()->GetFrameView();
    // Use a clone without invalidation info, as we're painting something
    // outside of the normal parent-child relationship, so invalidations are
    // no longer in the correct space to compare.
    frame->Paint(context.CloneWithoutInvalidation());
  }
  View::PaintChildren(context);
}


text:
export function selectBook(book) {
  // selectBook is an ActionCreator, it needs to return an action,
  // an object with a type property.
  return {
    'type': 'BOOK_SELECTED',
    'payload': book
  }
}


text:
<?php

namespace hustshenl\metronic\widgets;

use hustshenl\metronic\Metronic;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use Yii;
use yii\helpers\Url;
use yii\widgets\ActiveForm as CoreActiveForm;

/**
 * Metronic menu displays a multi-level menu using nested HTML lists.
 *
 * The main property of Menu is [[items]], which specifies the possible items in the menu.
 * A menu item can contain sub-items which specify the sub-menu under that menu item.
 *
 * Menu checks the current route and request parameters to toggle certain menu items
 * with active state.
 *
 * Note that Menu only renders the HTML tags about the menu. It does do any styling.
 * You are responsible to provide CSS styles to make it look like a real menu.
 *
 * The following example shows how to use Menu:
 *
 * ```php
 * echo Menu::widget([
 *     'items' => [
 *         // Important: you need to specify url as 'controller/action',
 *         // not just as 'controller' even if default action is used.
 *         [
 *           'icon' => '',
 *           'label' => 'Home',
 *           'url' => ['site/index']
 *         ],
 *         // 'Products' menu item will be selected as long as the route is 'product/index'
 *         ['label' => 'Products', 'url' => ['product/index'], 'items' => [
 *             ['label' => 'New Arrivals', 'url' => ['product/index', 'tag' => 'new']],
 *             ['label' => 'Most Popular', 'url' => ['product/index', 'tag' => 'popular']],
 *         ]],
 *         ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
 *     ],
 *     'search' => [
 *         // required, whether search box is visible. Defaults to 'true'.
 *         'visible' => true,
 *         // optional, the configuration array for [[ActiveForm]].
 *         'form' => [],
 *         // optional, input options with default values
 *         'input' => [
 *             'name' => 'search',
 *             'value' => '',
 *             'options' => [
 *             'placeholder' => 'Search...',
 *         ]
 *     ],
 * ]
 * ]);
 * ```
 *
 */
class Menu extends \yii\widgets\Menu {

    /**
     * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
     * The activated parent menu items will also have its CSS classes appended with [[activeCssClass]].
     */
    public $activateParents = true;

    /**
     * @var string the CSS class that will be assigned to the first item in the main menu or each submenu.
     */
    public $firstItemCssClass = 'start';

    /**
     * @var string the CSS class that will be assigned to the last item in the main menu or each submenu.
     */
    public $lastItemCssClass = 'last';

    /**
     * @var string the template used to render a list of sub-menus.
     * In this template, the token `{items}` will be replaced with the renderer sub-menu items.
     */
    public $submenuTemplate = "\n
\n{items}\n
\n";

    /**
     * @var string the template used to render the body of a menu which is a link.
     * In this template, the token `{url}` will be replaced with the corresponding link URL;
     * while `{label}` will be replaced with the link text.
     * The token `{icon}` will be replaced with the corresponding link icon.
     * The token `{arrow}` will be replaced with the corresponding link arrow.
     * This property will be overridden by the `template` option set in individual menu items via [[items]].
     */
    public $linkTemplate = '{icon}{label}{badge}{arrow}';

    /**
     * @var bool Indicates whether menu is visible.
     */
    public $visible = true;

    /**
     * Initializes the widget.
     */
    public function init()
    {
        Metronic::registerThemeAsset($this->getView());

        $this->_initOptions();
    }

    /**
     * Renders the widget.
     */
    public function run()
    {
        echo Html::beginTag('div', ['class' => 'page-sidebar-wrapper']);
        echo Html::beginTag('div', ['class' => 'page-sidebar navbar-collapse collapse']);

        parent::run();

        echo Html::endTag('div');
        echo Html::endTag('div');
    }

    /**
     * Recursively renders the menu items (without the container tag).
     * @param array $items the menu items to be rendered recursively
     * @param integer $level the item level, starting with 1
     * @return string the rendering result
     */
    protected function renderItems($items, $level = 1)
    {
        $n = count($items);
        $lines = [];
        foreach ($items as $i => $item)
        {
            $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
            $tag = ArrayHelper::remove($options, 'tag', 'li');
            $class = [];
            if ($item['active'])
            {
                $class[] = $this->activeCssClass;
            }
            if ($i === 0 && $this->firstItemCssClass !== null)
            {
                $class[] = $this->firstItemCssClass;
            }
            if ($i === $n - 1 && $this->lastItemCssClass !== null)
            {
                $class[] = $this->lastItemCssClass;
            }
            if (!empty($class))
            {
                if (empty($options['class']))
                {
                    $options['class'] = implode(' ', $class);
                }
                else
                {
                    $options['class'] .= ' ' . implode(' ', $class);
                }
            }

            // set parent flag
            $item['level'] = $level;
            $menu = $this->renderItem($item);
            if (!empty($item['items']))
            {
                $menu .= strtr($this->submenuTemplate, [
                    '{items}' => $this->renderItems($item['items'], $level + 1),
                ]);
            }
            $lines[] = Html::tag($tag, $menu, $options);
        }
        return implode("\n", $lines);
    }

    /**
     * Renders the content of a menu item.
     * Note that the container and the sub-menus are not rendered here.
     * @param array $item the menu item to be rendered. Please refer to [[items]] to see what data might be in the item.
     * @return string the rendering result
     */
    protected function renderItem($item)
    {
        return strtr(ArrayHelper::getValue($item, 'template', $this->linkTemplate), [
            '{url}' => $this->_pullItemUrl($item),
            '{label}' => $this->_pullItemLabel($item),
            '{icon}' => $this->_pullItemIcon($item),
            '{arrow}' => $this->_pullItemArrow($item),
            '{badge}' => $this->_pullItemBadge($item),
        ]);
    }

    /**
     * Pulls out item url
     * @param array $item given item
     * @return string item url
     */
    private function _pullItemUrl($item)
    {
        $url = ArrayHelper::getValue($item, 'url', '#');

        if ('#' === $url)
        {
            return 'javascript:;';
        }

        return Url::toRoute($item['url']);
    }

    /**
     * Pulls out item label
     * @param array $item given item
     * @return string item label
     */
    private function _pullItemLabel($item)
    {
        $label = ArrayHelper::getValue($item, 'label', '');

        $level = ArrayHelper::getValue($item, 'level', 1);

        if (1 == $level)
        {
            return Html::tag('span', $label, ['class' => 'title']);
        }

        return sprintf(' %s', $label);
    }

    /**
     * Pulls out item icon
     * @param array $item given item
     * @return string item icon
     */
    private function _pullItemIcon($item)
    {
        $icon = ArrayHelper::getValue($item, 'icon', null);

        if ($icon)
        {
            return Html::tag('i', '', ['class' => $icon]);
        }

        return '';
    }

    /**
     * Pulls out item arrow
     * @param array $item given item
     * @return string item arrow
     */
    private function _pullItemArrow($item)
    {
        $active = ArrayHelper::getValue($item, 'active', false);

        $level = ArrayHelper::getValue($item, 'level', 1);

        $items = ArrayHelper::getValue($item, 'items', []);

        if (!empty($items))
        {
            return Html::tag('span', '', ['class' => 'arrow' . ($active ? ' open' : '')]);
        }

        return '';
    }

    /**
     * Pulls out item badge
     * @param array $item given item
     * @return string item badge
     */
    private function _pullItemBadge($item)
    {
        return ArrayHelper::getValue($item, 'badge', '');
    }

    /**
     * Inits options
     */
    private function _initOptions()
    {
        Html::addCssClass($this->options, 'page-sidebar-menu');

        if (Metronic::SIDEBAR_MENU_HOVER === Metronic::getComponent()->sidebarMenu)
        {
            Html::addCssClass($this->options, 'page-sidebar-menu-hover-submenu');
        }

        $this->options['data-slide-speed'] = 200;
        $this->options['data-auto-scroll'] = 'true';
        $this->options['data-keep-expanded'] = 'false';
        $this->options['data-height'] = 261;
    }

}


text:
package AsposeWordsCloud::Object::FieldNamesResponse;

require 5.6.0;
use strict;
use warnings;
use utf8;
use JSON qw(decode_json);
use Data::Dumper;
use Module::Runtime qw(use_module);
use Log::Any qw($log);
use Date::Parse;
use DateTime;

use base "AsposeWordsCloud::Object::BaseObject";

#
#
#
#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
#

my $swagger_types = {
    'FieldNames' => 'FieldNames',
    'Code' => 'string',
    'Status' => 'string'
};

my $attribute_map = {
    'FieldNames' => 'FieldNames',
    'Code' => 'Code',
    'Status' => 'Status'
};

# new object
sub new {
    my ($class, %args) = @_;
    my $self = {
        #
        'FieldNames' => $args{'FieldNames'},
        #
        'Code' => $args{'Code'},
        #
        'Status' => $args{'Status'}
    };

    return bless $self, $class;
}

# get swagger type of the attribute
sub get_swagger_types {
    return $swagger_types;
}

# get attribute mappping
sub get_attribute_map {
    return $attribute_map;
}

1;


text:
package com.sissi.pipeline.in.iq.disco;

import com.sissi.context.JIDContext;
import com.sissi.pipeline.Input;
import com.sissi.protocol.Protocol;
import com.sissi.protocol.ProtocolType;
import com.sissi.protocol.iq.disco.Disco;
import com.sissi.protocol.iq.disco.DiscoFeature;

/**
 * @author kim 2014年2月13日
 */
public class DiscoInfoProcessor implements Input {

	private final DiscoFeature[] features;

	public DiscoInfoProcessor(DiscoFeature[] features) {
		this.features = features;
	}

	@Override
	public boolean input(JIDContext context, Protocol protocol) {
		context.write(protocol.cast(Disco.class).add(this.features).parent().reply().setType(ProtocolType.RESULT));
		return true;
	}
}


text:
Initial Setup of Nablarch batch Project for Container
----------------------------------------------------------

The following is procedures of initial setup of the Nablarch batch project for container:

* Generating Nablarch batch project for container
* Confirm communications of Nablarch batch project
* Create a container image
* Run Container Image

Overview of the generated project
----------------------------------------------------------

The overview of the project generated by this procedure is as follows.

.. list-table::
  :header-rows: 1
  :class: white-space-normal
  :widths: 8,20

  * - Item
    - Description
  * - Project type
    - Maven project
  * - Project composition
    - Single project composition
  * - DB used
    - H2 Database Engine (embedded in the application)
  * - What is included in the generated project?
    - The following is included in the generated project:

      * Basic configuration for the Nablarch batch application
      * On-demand batch application for communication confirmation
      * Messaging using tables as queues for communication confirmation
      * Email send batch configuration \ [#mailSendBatch]_\
      * Initial configuration of the tool that operates in conjunction with Maven (is imported by referring to :ref:`about_maven_parent_module`).

.. [#mailSendBatch]
   Email send batch functions as a :ref:`resident batch<nablarch_batch-resident_batch>` and sends mail to the SMTP server.
   Sample component configuration file is present in ``src/main/resources/mail-sender-boot.xml``.
   Email send batch is not necessary when building the initial environment, but when it becomes necessary, use after reading the description of :ref:`send email<mail>`.

For relationship with other projects and directories, see :doc:`../MavenModuleStructures/index`.

.. _firstStepGenerateContainerBatchBlankProject:

Create blank project
----------------------------------------------------------

Generate a blank project using the archetypes provided by Nablarch.

Execute the mvn command
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use `Maven Archetype Plugin(external site) <https://maven.apache.org/archetype/maven-archetype-plugin/usage.html>`_ to generate a blank project.

Change the current directory to the directory where the blank project (can be any directory) is to be created, and place the following file.

:download:`Batch file <bat/generateContainerNablarchBatchProject.bat>`

After placing the file, specify the necessary parameters in the arguments and execute the bat file.

generateContainerNablarchBatchProject.bat |nablarch_version| <<groupId>> <<artifactId>> <<version>> <<package(optional)>>

The parameters configured in the above command are as follows.
If you want to change the version of Nablarch, change |nablarch_version|.
Change the current directory to the directory where the blank project (can be any directory) is to be created.

=========== ================================================= =======================
Input item  Description                                       Configuration example
=========== ================================================= =======================
groupId      Group ID (normally, enter the package name)      ``com.example``
artifactId   Artifact ID                                      ``myapp-container-batch``
version      Version number                                   ``0.1.0``
package      Package (normally the same as group ID)          ``com.example``
=========== ================================================= =======================

.. important::
   Item groupId and package are mapped to the Java package name.
   Use lowercase letters, numbers, and dots for these input values, and do not use hyphens.

If the command ends normally, a blank project is created under the current directory.

.. _firstStepContainerBatchStartupTest:

Communication confirmation
-------------------------------------------

The communication confirmation mechanism and procedures are the same as for a normal Nablarch batch project. Thus, see :ref:`Initial Setup of the Nablarch Batch Project <firstStepBatchStartupTest>`.

.. note::

  The artifact ID should be replaced with ``myapp-container-batch`` to specify the directory and command.

.. _firstStepBuildContainerBatchDockerImage:

Create a container image
----------------------------------

The blank project has a plugin named `Jib <https://github.com/GoogleContainerTools/jib/tree/master/jib-maven-plugin>`_ (External sites) built in to create an image of a Docker container.

The ``jib: dockerBuild`` goal of this plugin can be executed to create a container image.

.. code-block:: text

  cd myapp-container-batch
  mvn compile jib:dockerBuild

If the execution is successful, the log given below will be output to the console.

.. code-block:: text

  (omission)
  [INFO] Built image to Docker daemon as myapp-container-batch, myapp-container-batch, myapp-container-batch:0.1.0
  [INFO] Executing tasks:
  [INFO] [==============================] 100.0% complete
  [INFO]
  [INFO] ------------------------------------------------------------------------
  [INFO] BUILD SUCCESS
  [INFO] ------------------------------------------------------------------------
  (Omitted)

Built Docker images are stored in a local repository.
Can see the images stored in the local repository with the following command.

.. code-block:: text

  docker image ls
  REPOSITORY              TAG         IMAGE ID       CREATED        SIZE
  myapp-container-batch   0.1.0       1cafd4108237   51 years ago   253MB
  myapp-container-batch   latest      1cafd4108237   51 years ago   253MB

Can see that there are 2 images registered: ``myapp-container-batch:0.1.0`` and ``myapp-container-batch:latest`` .

As you can see, the blank project is configured to create the following two images by executing ``jib:dockerBuild``.

* ``${project.artifactId}:latest``
* ``${project.artifactId}:${project.version}``

`OpenJDK image <https://hub.docker.com/_/adoptopenjdk>`_ (External sites) is used as base image by default.

The base image can be changed with the ``jib.from.image`` property.
For example, if you want to use ``adoptopenjdk:11.0.11_9-jre-hotspot`` for your base image, you would write it in ``pom.xml`` .

.. code-block:: xml

  <project>
    <! -- Omitted ...-->
    <properties>
      <! -- Omitted ...-->
      <jib.from.image>adoptopenjdk:11.0.11_9-jre-hotspot</jib.from.image>
    </properties>
    <! -- Omitted ...-->
  </project>

.. tip::

  In the blank project, the base image is specified with a Docker image tag. In this case, the latest version of the specified image will be selected.
  If a different version is selected than at the time of verification, it may affect the operation of the application.
  Therefore, it is recommended to specify the base image as a digest in order to specify exactly which version, after the test is completed.

  An example of setting by digest is shown below.

  .. code-block:: xml

    <jib.from.image>adoptopenjdk@sha256:df316691a2c655de2f835a626f8611c74af67dad2cf92711f6608b54e5aa6c61</jib.from.image>

.. _firstStepRunContainerBatchDockerImage:

Run a container image
----------------------------------

Once you have created a container image, you can run it with the following command.

.. _firstStepContainerBatchStartupInnerBatchOndemand:

On-demand batch
~~~~~~~~~~~~~~~~~
.. code-block:: text

  cd myapp-container-batch
  docker run  --rm -v %CD%\\h2:/h2 -v %CD%\\src\\main\\format:/var/nablarch/format -v %CD%\\work\\output:/var/nablarch/output  --name myapp-container-batch myapp-container-batch:latest -diConfig classpath:batch-boot.xml -requestPath SampleBatch -userId batch_user

It works the same as for :ref:`Communication confirmation (on-demand batch))<firstStepBatchStartupTest>`.
If the startup is successful, a log similar to :ref:`Launching the on-demand batch application <firstStepBatchExecOnDemandBatch>` will be output to the console.

.. _firstStepContainerBatchStartupInnerBatchDbMessaging:

Messaging Using Tables as Queues
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: text

  cd myapp-container-batch
  docker run -it  --rm -v %CD%\\h2:/h2 --name myapp-container-batch --rm myapp-container-batch:latest -diConfig classpath:resident-batch-boot.xml -requestPath SampleResiBatch -userId batch_user

It works the same as for :ref:`Communication confirmation (messaging using tables as queues)<firstStepBatchStartupTestDbMessagingBatch>` .
If the startup is successful, a log similar to :ref:`Launching the application <firstStepBatchExecDbMessagingBatch>` will be output to the console.
It will go into standby mode, so force quit it with ctrl+c after confirming.

Supplementary notes
--------------------

 About the commands to run the container image.
  * When the above command is executed, the container will be started, batch processing will be executed, and then the container will be terminated automatically.
    Also, -rm option is specified in order to make automatically container deleted when the container is ended.

  * The above command is an example of the case where SAMPLE.h2.db, which is included in the blank project beforehand, is used as the database.
    If you do not use SAMPLE.h2.db, you do not need to specify a volume (``-v``) for ``%CD%\\h2:/h2``.

  * In addition to the above, in :ref:`On-demand batch<firstStepContainerBatchStartupInnerBatchOndemand>` The blank project ``./work/format`` and ``./work/output`` are mounted in a container.

  * Even for :ref:`Messaging Using Tables as Queues<firstStepContainerBatchStartupInnerBatchDbMessaging>`, the ``-it option`` of the docker command can be omitted, but the batch cannot be killed by ctrl+c from the docker host.
    In that case, exit the container with the following command.

     .. code-block:: text

      docker stop myapp-container-batch

 About Docker
  Running Docker assumes that you are using Docker Desktop (see :ref:`Prerequisite <firstStepPreamble>`).
  If you are using the Docker Toolbox, the volume specification in the above example will fail.

  If you are using the Docker Toolbox, Docker is running in a VM on VirtualBox.
  Therefore, the path that can be specified on the host side of the volume is the path on the VM.

  On Windows, by default ``C:\Users`` is mounted in ``/c/users`` on the VM.
  Thus, if you are using the Docker Toolbox, you must specify the volume as ``-v/c/users/path/to/project/h2:/usr/local/tomcat/h2`` .

 About H2 and tools
  For information on the method of confirming the data of H2 and tools included in the blank project, see :doc:`../firstStep_appendix/firststep_complement`.


text:
using System;
using System.Threading;
using NUnit.Framework;
using Selenium;

namespace ThoughtWorks.Selenium.IntegrationTests
{
	[TestFixture]
    [Ignore("Integration tests require set up of a Selenium server.")]
	public class SeleniumIntegrationTest
	{
		private ISelenium selenium;

		[SetUp]
		public void SetupTest()
		{
			selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.irian.at");
			selenium.Start();
		}

		[TearDown]
		public void TeardownTest()
		{
			try
			{
				selenium.Stop();
			}
			catch (Exception)
			{
				// Ignore errors if unable to close the browser
			}
		}

		[Test]
        [Ignore("The server this depends on appears to be down")]
		public void IISIntegrationTest()
		{
			String inputId = "ac4";
			String updateId = "ac4update";

			selenium.Open("http://www.irian.at/selenium-server/tests/html/ajax/ajax_autocompleter2_test.html");
			selenium.KeyPress(inputId, "\\74");
			Thread.Sleep(500);
			selenium.KeyPress(inputId, "\\97");
			selenium.KeyPress(inputId, "\\110");
			Thread.Sleep(500);
			Assert.AreEqual("Jane Agnews", selenium.GetText(updateId));
			selenium.KeyPress(inputId, "\\9");
			Thread.Sleep(500);
			Assert.AreEqual("Jane Agnews", selenium.GetValue(inputId));
		}
	}
}


text:
using NiL.JS.Core;

namespace NiL.JS.Expressions
{
    public sealed class SuspendableExpression : Expression
    {
        private Expression _prototype;
        private CodeNode[] _parts;

        internal SuspendableExpression(Expression prototype, CodeNode[] parts)
        {
            _prototype = prototype;
            _parts = parts;
        }

        public override JSValue Evaluate(Context context)
        {
            var i = 0;

            if (context._executionMode >= ExecutionMode.Resume)
            {
                i = (int)context.SuspendData[this];
            }

            for (; i < _parts.Length; i++)
            {
                _parts[i].Evaluate(context);
                if (context._executionMode == ExecutionMode.Suspend)
                {
                    context.SuspendData[this] = i;
                    return null;
                }
            }

            var result = _prototype.Evaluate(context);
            if (context._executionMode == ExecutionMode.Suspend)
            {
                context.SuspendData[this] = i;
                return null;
            }

            return result;
        }

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


text:
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Web.Context;
using wojilu.Web.Mvc;

namespace wojilu.Web.Controller.Forum.Utils {

    public class LinkUtil {

        public static String appendListPage( String url, MvcContext ctx ) {
            //if (ctx.route.page > 1) url = url + "?lp=" + ctx.route.page;
            return url;
        }

        public static String appendListPageToTopic( String url, MvcContext ctx ) {
            //if (ctx.GetInt( "lp" ) > 0) return url = url + "?lp=" + ctx.GetInt( "lp" );
            return url;
        }

        public static String appendListPageToBoard( String url, MvcContext ctx ) {
            //if ( ctx.GetInt( "lp" ) > 0) url = appendPage( url, ctx.GetInt( "lp" ) );
            return url;
        }

        //private static string appendPage( string url, int page ) {
        //    String urlNoExt = strUtil.TrimEnd( url, MvcConfig.Instance.UrlExt );
        //    return strUtil.Join( urlNoExt, "p" + page ) + MvcConfig.Instance.UrlExt;
        //}

    }

}


text:
from typing import Optional

from .. import config
from ..io import io_consts

class IntegerCopyNumberSegment:
    """Represents a constant copy-number genomic interval ("segment") and stores various quality metrics.

    Note:
        Quality metric attributes are considered optional.

    Attributes:
        contig: contig name
        start: segment start genomic position
        end: segment end genomic position
        num_points: number of points (e.g. bins or intervals) contained in the segment
        call_copy_number: segment most-likely copy-number call
        baseline_copy_number: baseline copy-number for the contig
        quality_some_called: complementary phred-scaled probably that one or more of the points in the segment
            agree with the segment copy-number call (normalized by `num_points`)
        quality_all_called: complementary phred-scaled probability that all of points in the segment
            agree with the segment copy-number call
        quality_start: complementary phred-scaled probability that the leftmost point of the segment
            is a change-point to the segment copy-number call
        quality_end: complementary phred-scaled probability that the rightmost point of the segment
            is a change-point to the segment copy-number call
    """
    def __init__(self, contig: str, start: int, end: int,
                 num_points: int,
                 call_copy_number: int,
                 baseline_copy_number: int):
        self.contig: str = contig
        self.start: int = start
        self.end: int = end
        self.num_points: int = num_points
        self.call_copy_number: int = call_copy_number
        self.baseline_copy_number = baseline_copy_number
        self.quality_some_called: Optional[float] = None
        self.quality_all_called: Optional[float] = None
        self.quality_start: Optional[float] = None
        self.quality_end: Optional[float] = None

    @staticmethod
    def get_header_column_string():
        return '\t'.join([io_consts.contig_column_name,
                          io_consts.start_column_name,
                          io_consts.end_column_name,
                          io_consts.num_points_column_name,
                          io_consts.call_copy_number_column_name,
                          io_consts.baseline_copy_number_column_name,
                          io_consts.quality_some_called_column_name,
                          io_consts.quality_all_called_column_name,
                          io_consts.quality_start_column_name,
                          io_consts.quality_end_column_name])

    @staticmethod
    def _repr_quality(quality):
        return '{0:.{1}f}'.format(quality, config.phred_decimals) if quality is not None else '.'

    def __repr__(self):
        return '\t'.join([self.contig,
                          repr(self.start),
                          repr(self.end),
                          repr(self.num_points),
                          repr(self.call_copy_number),
                          repr(self.baseline_copy_number),
                          self._repr_quality(self.quality_some_called),
                          self._repr_quality(self.quality_all_called),
                          self._repr_quality(self.quality_start),
                          self._repr_quality(self.quality_end)])


text:
<?php

namespace Sekai\Models;

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Validator\Email as EmailValidator;
use Phalcon\Mvc\Model\Validator\Uniqueness as UniquenessValidator;
use Phalcon\Db\RawValue;

use Sekai\i18n;

class User extends ModelBase {
    public $uid;
    public $username;
    public $groupid;

    public function initialize() {
    }

    public function beforeValidationOnCreate() {
        $this->groupid = 2;
    }

    public static function findUserByName($username) {
        $user = User::findFirst(array(
            "(username = :username:)",
            'bind' => array('username' => $username)
        ));
        return $user;
    }

    public static function findUserByID($uid) {
        $user = User::findFirst(array(
            "uid = :uid:", 'bind' => array('uid' => $uid)));
        return $user;
    }
}


text:
export class StringUtil {
  /**
   * Camelcases a string
   *
   * @param string input
   * @param string splitchar
   * @return string
   */
  static camelCase (input, splitChar) {
    splitChar = typeof splitChar !== 'undefined' ? splitChar : '_'
    const regex = new RegExp(splitChar + '(.)', 'g')
    return input.toLowerCase().replace(regex, function (match, group1) {
      return group1.toUpperCase()
    })
  }

  /**
   * underscore a string
   *
   * @param string input
   * @param string splitchar
   * @return string
   */
  static underscore (input, splitChar) {
    return input.split(/(?=[A-Z])/).join(splitChar || '_').toLowerCase()
  }

  /**
   * Fix a HTML5-chunk, so IE can render it
   *
   * @return string
   * @param string html
   */
  static html5 (html) {
    const html5 = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' ')
    let i = 0
    let div = false

    // create div if needed
    if (div === false) {
      div = document.createElement('div')

      div.innerHTML = ''

      if (div.childNodes.length !== 1) {
        const fragment = document.createDocumentFragment()
        i = html5.length
        while (i--) fragment.createElement(html5[i])

        fragment.appendChild(div)
      }
    }

    html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
      .replace(/


text:
package org.attoparser.simple;

import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;
import org.attoparser.ParseException;
import org.attoparser.config.ParseConfiguration;

/*
 *
 * @author Daniel Fernandez
 * @since 2.0.0
 */
public class SimpleOutputMarkupHandlerTest extends TestCase {

    public void test() throws Exception {

        final ParseConfiguration xmlConfig = ParseConfiguration.xmlConfiguration();
        final ParseConfiguration xmlAutoCloseConfig = ParseConfiguration.xmlConfiguration();
        xmlAutoCloseConfig.setElementBalancing(ParseConfiguration.ElementBalancing.AUTO_CLOSE);
        final ParseConfiguration htmlConfig = ParseConfiguration.htmlConfiguration();

        check(xmlConfig, "
hello
", "
hello
");
        check(xmlConfig, "
\n
hello
\n
", "
\n
hello
\n
");

        check(htmlConfig, "
hello
", "
hello
");
        check(htmlConfig, "
\n
hello
\n
", "
\n
hello
\n
");
        check(htmlConfig, "

\n
hello
\n
", "

\n
hello
\n
");
        check(htmlConfig, "
\n
hello
\n

", "
\n
hello
\n

");

        check(htmlConfig, "

hello
goodbye
", "

hello
goodbye
");
        check(htmlConfig, "

hello
goodbye", "

hello
goodbye");
        check(xmlAutoCloseConfig, "

hello
goodbye
", "

hello
goodbye
");
        check(xmlAutoCloseConfig, "

hello
goodbye", "

hello
goodbye");

        check(xmlConfig, "<!DOCTYPE html PUBLIC \"hello\" \"goodbye\">\n\nhello", "<!DOCTYPE html PUBLIC \"hello\" \"goodbye\">\n\nhello");
        check(htmlConfig, "<!DOCTYPE html PUBLIC \"hello\" \"goodbye\">\n\nhello", "<!DOCTYPE html PUBLIC \"hello\" \"goodbye\">\n\nhello");
        check(htmlConfig, "<!doctype html PUBLIC \"hello\" \"goodbye\">\n\nhello", "<!doctype html PUBLIC \"hello\" \"goodbye\">\n\nhello");

        check(xmlConfig, "onetwo", "onetwo");
        check(htmlConfig, "onetwo", "onetwo");

    }

    private static void check(final ParseConfiguration configuration, final String input, final String expectedOutput) throws Exception {

        final ISimpleMarkupParser parser = new SimpleMarkupParser(configuration);
        final ISimpleMarkupHandler handler = new TestSimpleMarkupHandler();

        try {
            parser.parse(input, handler);
            assertTrue(true);
        } catch (ParseException e) {
            assertTrue(false);
        }

    }

    private static class TestSimpleMarkupHandler extends AbstractSimpleMarkupHandler {

        private final Map<String,String> names = new HashMap<String, String>();

        @Override
        public void handleStandaloneElement(final String elementName, final Map<String, String> attributes, final boolean minimized, final int line, final int col) throws ParseException {

            if (!this.names.containsKey(elementName)) {
                this.names.put(elementName, elementName);
            } else {
                final String mapElementName = this.names.get(elementName);
                if (mapElementName != elementName) {
                    throw new ParseException("Not same string: " + mapElementName);
                }
            }

            if (attributes != null) {
                for (final Map.Entry<String,String> entry : attributes.entrySet()) {
                    final String attributeName = entry.getKey();
                    if (!this.names.containsKey(attributeName)) {
                        this.names.put(attributeName, attributeName);
                    } else {
                        final String mapAttributeName = this.names.get(attributeName);
                        if (mapAttributeName != attributeName) {
                            throw new ParseException("Not same string: " + mapAttributeName);
                        }
                    }
                }
            }

        }

        @Override
        public void handleOpenElement(final String elementName, final Map<String, String> attributes, final int line, final int col) throws ParseException {

            if (!this.names.containsKey(elementName)) {
                this.names.put(elementName, elementName);
            } else {
                final String mapElementName = this.names.get(elementName);
                if (mapElementName != elementName) {
                    throw new ParseException("Not same string: " + mapElementName);
                }
            }

            if (attributes != null) {
                for (final Map.Entry<String,String> entry : attributes.entrySet()) {
                    final String attributeName = entry.getKey();
                    if (!this.names.containsKey(attributeName)) {
                        this.names.put(attributeName, attributeName);
                    } else {
                        final String mapAttributeName = this.names.get(attributeName);
                        if (mapAttributeName != attributeName) {
                            throw new ParseException("Not same string: " + mapAttributeName);
                        }
                    }
                }
            }

        }

        @Override
        public void handleCloseElement(final String elementName, final int line, final int col) throws ParseException {

            if (!this.names.containsKey(elementName)) {
                this.names.put(elementName, elementName);
            } else {
                final String mapElementName = this.names.get(elementName);
                if (mapElementName != elementName) {
                    throw new ParseException("Not same string: " + mapElementName);
                }
            }

        }

        @Override
        public void handleAutoCloseElement(final String elementName, final int line, final int col) throws ParseException {

            if (!this.names.containsKey(elementName)) {
                this.names.put(elementName, elementName);
            } else {
                final String mapElementName = this.names.get(elementName);
                if (mapElementName != elementName) {
                    throw new ParseException("Not same string: " + mapElementName);
                }
            }

        }

        @Override
        public void handleUnmatchedCloseElement(final String elementName, final int line, final int col) throws ParseException {
            super.handleUnmatchedCloseElement(elementName, line, col);
        }
    }

}


text:
package org.xmeta.cache;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.xmeta.Thing;

/**
 *
弱引用事物实体列表。

 *
 *
被引用的事物是链表中的最后一个事物,当前面的事物发生了改变时后面的事物引用就无效,此时
 * 引用返回null。

 *
 * 此类一般用于事物的动作缓存等,当事物发生变更时,通常动作等需要重新组织。
 *
 * @author zyx
 *
 */
public class LinkedThingEntry {
	protected List<ThingEntry> thingEntrys = new ArrayList<ThingEntry>();

	public void addThing(Thing thing){
		thingEntrys.add(new ThingEntry(thing));
	}

	public void removeLast(){
		if(thingEntrys.size() > 0){
			thingEntrys.remove(thingEntrys.size() - 1);
		}
	}

	public Thing getThing(){
		for(Iterator<ThingEntry> iter = thingEntrys.iterator(); iter.hasNext();){
			ThingEntry thingEntry = iter.next();

			if(iter.hasNext() && thingEntry.isChanged()){
				return null;
			}

			if(!iter.hasNext()){
				return thingEntry.getThing();
			}
		}

		return null;
	}
}


text:
var spinner = $("#spinner-form");

if (spinner.is(":checked")) {
  spinner.prop("checked", false);
}

// Toggle mennu
$("#menu-toggle").click(function(e) {
  $("#wrapper").toggleClass("toggled");
});

// enable the bio tooltips on page ready
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})