text:
[![NPM version][npm-image]][npm-url]

## About
DB is javascript library / wrapper used to communicate with IndexedDB efficiently. DB have set of predefined function which helps developers ease in writing object oriented code for storing, manipulating and retrieving data in indexedDB.

## Versions
**Changes in 1.0.2:**
- Updated code to remove unwanted methods and variables.

## Install
### In Browser
```html
<script src="DB.js"></script>
```
### npm
```
npm i --save DB;
```
### In Node
```javascript
// ES2015
import {DB} from '@dharmesh-hemaram/DB';

//require JS
let DB =  require('@dharmesh-hemaram/DB').DB;

//AMD
define(['@dharmesh-hemaram/DB'], function (package) {
  let DB = package.DB;
});

```
## Getting started
### Configuration
create database configuration file db_confog.json
```JSON
{
  "databaseName":"testDB",
  "version":1,
  "tables":[
    {
      "name":"customers",
      "keyPath":"customerId",
      "autoIncrement":false,
      "columns":[
        {
          "name":"customerName",
          "nullable":false,
          "type":"string"
        },{}
      ]
    },{}
  ]
}
```
### Setup
```javascript
import {DB} from '@dharmesh-hemaram/DB';

DB.setup(databaseJSON).then(dbInst => console.log(dbInst));
```
### Serve
```javascript
  DB.getInst().databaseName.tableName.get().then(result).catch(error);
```

### [Query](https://github.com/dharmesh-hemaram/DB/wiki/Query)

### Usefull Stuff:

 * [E-Mail](dharmesh.hemaram@gmail.com)
 * [Wiki](https://github.com/dharmesh-hemaram/DB/wiki/)
 * [Test](https://dharmesh-hemaram.github.io/DB/test.html)

 If this project help you reduce time to develop, you can give me a cup of coffee :)
 [![PayPal](https://www.paypalobjects.com/webstatic/paypalme/images/pp_logo_small.png)](https://paypal.me/DharmeshH/25?_ga=1.267642062.1305492970.1507529951)

## Licensing

[The code in this project is licensed under Apache 2.0 license.](LICENSE)

redpajama_set_name: RedPajamaGithub


text:
package org.daisy.pipeline.css.calabash.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;

import static com.google.common.collect.Iterators.forArray;

import com.xmlcalabash.core.XProcException;
import com.xmlcalabash.core.XProcRuntime;
import com.xmlcalabash.io.ReadablePipe;
import com.xmlcalabash.io.WritablePipe;
import com.xmlcalabash.library.DefaultStep;
import com.xmlcalabash.model.RuntimeValue;
import com.xmlcalabash.runtime.XAtomicStep;

import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;

import org.daisy.common.saxon.SaxonHelper;
import org.daisy.common.xproc.calabash.XMLCalabashInputValue;
import org.daisy.common.xproc.calabash.XMLCalabashOutputValue;
import org.daisy.common.xproc.calabash.XProcStep;
import org.daisy.common.xproc.calabash.XProcStepProvider;
import org.daisy.pipeline.css.CssCascader;
import org.daisy.pipeline.css.Medium;
import org.daisy.pipeline.css.SassCompiler;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CssCascadeStep extends DefaultStep implements XProcStep {

	private ReadablePipe sourcePipe = null;
	private ReadablePipe contextPipe = null;
	private WritablePipe resultPipe = null;
	private Map<String,String> sassVariables = new HashMap<String,String>();
	private final InMemoryURIResolver inMemoryResolver;
	private final URIResolver cssURIResolver;
	private final SassCompiler sassCompiler;
	private final Iterable<CssCascader> inliners;

	private static final QName _default_stylesheet = new QName("default-stylesheet");
	private static final QName _type = new QName("type");
	private static final QName _media = new QName("media");
	private static final QName _attribute_name = new QName("attribute-name");

	private static final String DEFAULT_MEDIUM = "embossed";
	private static final String DEFAULT_TYPES = "text/css text/x-scss";
	private static final QName DEFAULT_ATTRIBUTE_NAME = new QName("style");

	private CssCascadeStep(XProcRuntime runtime, XAtomicStep step, Iterable<CssCascader> inliners, final URIResolver resolver) {
		super(runtime, step);
		this.inliners = inliners;
		// URI resolver that can resolve in-memory documents
		inMemoryResolver = new InMemoryURIResolver();
		// URI resolver for CSS files
		// first check memory and fall back to the resolver from module-registry
		cssURIResolver = fallback(inMemoryResolver, resolver);
		sassCompiler = new SassCompiler(cssURIResolver, Collections.unmodifiableMap(sassVariables));
	}

	@Override
	public void setInput(String port, ReadablePipe pipe) {
		if ("source".equals(port))
			sourcePipe = pipe;
		else
			contextPipe = pipe;
	}

	@Override
	public void setOutput(String port, WritablePipe pipe) {
		resultPipe = pipe;
	}

	@Override
	public void setParameter(String port, QName name, RuntimeValue value) {
		if ("sass-variables".equals(port))
			if ("".equals(name.getNamespaceURI())) {
				sassVariables.put(name.getLocalName(), value.getString());
				return; }
		super.setParameter(port, name, value);
	}

	@Override
	public void setParameter(QName name, RuntimeValue value) {
		// Calabash calls this function and never setParameter(String port,
		// ...) so I just have to assume that port is "sass-variables"
		setParameter("sass-variables", name, value);
	}

	@Override
	public void reset() {
		sourcePipe.resetReader();
		resultPipe.resetWriter();
	}

	@Override
	public void run() throws SaxonApiException {
		super.run();
		try {
			Medium medium = Medium.parse(getOption(_media, DEFAULT_MEDIUM));
			List<String> types = Arrays.asList(getOption(_type, DEFAULT_TYPES).trim().split("\\s+"));
			if (!types.contains("text/css"))
				throw new IllegalArgumentException("'type' option must contain 'text/css'");
			boolean enableSass = types.contains("text/x-scss");
			for (CssCascader inliner : inliners)
				if (inliner.supportsMedium(medium)) {
					QName attributeName = getOption(_attribute_name, DEFAULT_ATTRIBUTE_NAME);
					inMemoryResolver.setContext(contextPipe);
					inliner.newInstance(
						medium,
						getOption(_default_stylesheet, ""),
						cssURIResolver,
						enableSass ? sassCompiler : null,
						SaxonHelper.jaxpQName(attributeName)
					).transform(
						new XMLCalabashInputValue(sourcePipe, runtime),
						new XMLCalabashOutputValue(resultPipe, runtime)
					).run();
					return; }
			throw new RuntimeException("No CSS inliner implementation found for medium " + medium); }
		catch (Exception e) {
			logger.error("px:css-cascade failed", e);
			throw new XProcException(step.getNode(), e); }
	}

	private static URIResolver fallback(final URIResolver... resolvers) {
		return new URIResolver() {
			public Source resolve(String href, String base) throws javax.xml.transform.TransformerException {
				Iterator<URIResolver> iterator = forArray(resolvers);
				while (iterator.hasNext()) {
					Source source = iterator.next().resolve(href, base);
					if (source != null)
						return source; }
				return null;
			}
		};
	}

	@Component(
		name = "pxi:css-cascade",
		service = { XProcStepProvider.class },
		property = { "type:String={http://www.daisy.org/ns/pipeline/xproc/internal}css-cascade" }
	)
	public static class Provider implements XProcStepProvider {

		private URIResolver resolver;
		private final List<CssCascader> inliners = new ArrayList<>();

		@Override
		public XProcStep newStep(XProcRuntime runtime, XAtomicStep step) {
			return new CssCascadeStep(runtime, step, inliners, resolver);
		}

		@Reference(
			name = "URIResolver",
			unbind = "-",
			service = URIResolver.class,
			cardinality = ReferenceCardinality.MANDATORY,
			policy = ReferencePolicy.STATIC
		)
		public void setUriResolver(URIResolver resolver) {
			this.resolver = resolver;
		}

		@Reference(
			name = "CssCascader",
			unbind = "unbindCssCascader",
			service = CssCascader.class,
			cardinality = ReferenceCardinality.MULTIPLE,
			policy = ReferencePolicy.DYNAMIC
		)
		public void bindCssCascader(CssCascader inliner) {
			this.inliners.add(inliner);
		}

		public void unbindCssCascader(CssCascader inliner) {
			this.inliners.remove(inliner);
		}
	}

	private static final Logger logger = LoggerFactory.getLogger(CssCascadeStep.class);

}


text:
"""
Print detailed information about a process.
Author: Giampaolo Rodola' <g.rodola@gmail.com>

$ python3 scripts/procinfo.py
pid           4600
name          chrome
parent        4554 (bash)
exe           /opt/google/chrome/chrome
cwd           /home/giampaolo
cmdline       /opt/google/chrome/chrome
started       2016-09-19 11:12
cpu-tspent    27:27.68
cpu-times     user=8914.32, system=3530.59,
              children_user=1.46, children_system=1.31
cpu-affinity  [0, 1, 2, 3, 4, 5, 6, 7]
memory        rss=520.5M, vms=1.9G, shared=132.6M, text=95.0M, lib=0B,
              data=816.5M, dirty=0B
memory %      3.26
user          giampaolo
uids          real=1000, effective=1000, saved=1000
uids          real=1000, effective=1000, saved=1000
terminal      /dev/pts/2
status        sleeping
nice          0
ionice        class=IOPriority.IOPRIO_CLASS_NONE, value=0
num-threads   47
num-fds       379
I/O           read_count=96.6M, write_count=80.7M,
              read_bytes=293.2M, write_bytes=24.5G
ctx-switches  voluntary=30426463, involuntary=460108
children      PID    NAME
              4605   cat
              4606   cat
              4609   chrome
              4669   chrome
open-files    PATH
              /opt/google/chrome/icudtl.dat
              /opt/google/chrome/snapshot_blob.bin
              /opt/google/chrome/natives_blob.bin
              /opt/google/chrome/chrome_100_percent.pak
              [...]
connections   PROTO LOCAL ADDR            REMOTE ADDR               STATUS
              UDP   10.0.0.3:3693         *:*                       NONE
              TCP   10.0.0.3:55102        172.217.22.14:443         ESTABLISHED
              UDP   10.0.0.3:35172        *:*                       NONE
              TCP   10.0.0.3:32922        172.217.16.163:443        ESTABLISHED
              UDP   :::5353               *:*                       NONE
              UDP   10.0.0.3:59925        *:*                       NONE
threads       TID              USER          SYSTEM
              11795             0.7            1.35
              11796            0.68            1.37
              15887            0.74            0.03
              19055            0.77            0.01
              [...]
              total=47
res-limits    RLIMIT                     SOFT       HARD
              virtualmem             infinity   infinity
              coredumpsize                  0   infinity
              cputime                infinity   infinity
              datasize               infinity   infinity
              filesize               infinity   infinity
              locks                  infinity   infinity
              memlock                   65536      65536
              msgqueue                 819200     819200
              nice                          0          0
              openfiles                  8192      65536
              maxprocesses              63304      63304
              rss                    infinity   infinity
              realtimeprio                  0          0
              rtimesched             infinity   infinity
              sigspending               63304      63304
              stack                   8388608   infinity
mem-maps      RSS      PATH
              381.4M   [anon]
              62.8M    /opt/google/chrome/chrome
              15.8M    /home/giampaolo/.config/google-chrome/Default/History
              6.6M     /home/giampaolo/.config/google-chrome/Default/Favicons
              [...]
"""

import argparse
import datetime
import socket
import sys

import psutil
from psutil._common import bytes2human

ACCESS_DENIED = ''
NON_VERBOSE_ITERATIONS = 4
RLIMITS_MAP = {
    "RLIMIT_AS": "virtualmem",
    "RLIMIT_CORE": "coredumpsize",
    "RLIMIT_CPU": "cputime",
    "RLIMIT_DATA": "datasize",
    "RLIMIT_FSIZE": "filesize",
    "RLIMIT_MEMLOCK": "memlock",
    "RLIMIT_MSGQUEUE": "msgqueue",
    "RLIMIT_NICE": "nice",
    "RLIMIT_NOFILE": "openfiles",
    "RLIMIT_NPROC": "maxprocesses",
    "RLIMIT_NPTS": "pseudoterms",
    "RLIMIT_RSS": "rss",
    "RLIMIT_RTPRIO": "realtimeprio",
    "RLIMIT_RTTIME": "rtimesched",
    "RLIMIT_SBSIZE": "sockbufsize",
    "RLIMIT_SIGPENDING": "sigspending",
    "RLIMIT_STACK": "stack",
    "RLIMIT_SWAP": "swapuse",
}

def print_(a, b):
    if sys.stdout.isatty() and psutil.POSIX:
        fmt = '\x1b[1;32m%-13s\x1b[0m %s' % (a, b)
    else:
        fmt = '%-11s %s' % (a, b)
    print(fmt)

def str_ntuple(nt, convert_bytes=False):
    if nt == ACCESS_DENIED:
        return ""
    if not convert_bytes:
        return ", ".join(["%s=%s" % (x, getattr(nt, x)) for x in nt._fields])
    else:
        return ", ".join(["%s=%s" % (x, bytes2human(getattr(nt, x)))
                          for x in nt._fields])

def run(pid, verbose=False):
    try:
        proc = psutil.Process(pid)
        pinfo = proc.as_dict(ad_value=ACCESS_DENIED)
    except psutil.NoSuchProcess as err:
        sys.exit(str(err))

    # collect other proc info
    with proc.oneshot():
        try:
            parent = proc.parent()
            if parent:
                parent = '(%s)' % parent.name()
            else:
                parent = ''
        except psutil.Error:
            parent = ''
        try:
            pinfo['children'] = proc.children()
        except psutil.Error:
            pinfo['children'] = []
        if pinfo['create_time']:
            started = datetime.datetime.fromtimestamp(
                pinfo['create_time']).strftime('%Y-%m-%d %H:%M')
        else:
            started = ACCESS_DENIED

    # here we go
    print_('pid', pinfo['pid'])
    print_('name', pinfo['name'])
    print_('parent', '%s %s' % (pinfo['ppid'], parent))
    print_('exe', pinfo['exe'])
    print_('cwd', pinfo['cwd'])
    print_('cmdline', ' '.join(pinfo['cmdline']))
    print_('started', started)

    cpu_tot_time = datetime.timedelta(seconds=sum(pinfo['cpu_times']))
    cpu_tot_time = "%s:%s.%s" % (
        cpu_tot_time.seconds // 60 % 60,
        str((cpu_tot_time.seconds % 60)).zfill(2),
        str(cpu_tot_time.microseconds)[:2])
    print_('cpu-tspent', cpu_tot_time)
    print_('cpu-times', str_ntuple(pinfo['cpu_times']))
    if hasattr(proc, "cpu_affinity"):
        print_("cpu-affinity", pinfo["cpu_affinity"])
    if hasattr(proc, "cpu_num"):
        print_("cpu-num", pinfo["cpu_num"])

    print_('memory', str_ntuple(pinfo['memory_info'], convert_bytes=True))
    print_('memory %', round(pinfo['memory_percent'], 2))
    print_('user', pinfo['username'])
    if psutil.POSIX:
        print_('uids', str_ntuple(pinfo['uids']))
    if psutil.POSIX:
        print_('uids', str_ntuple(pinfo['uids']))
    if psutil.POSIX:
        print_('terminal', pinfo['terminal'] or '')

    print_('status', pinfo['status'])
    print_('nice', pinfo['nice'])
    if hasattr(proc, "ionice"):
        try:
            ionice = proc.ionice()
        except psutil.Error:
            pass
        else:
            if psutil.WINDOWS:
                print_("ionice", ionice)
            else:
                print_("ionice", "class=%s, value=%s" % (
                    str(ionice.ioclass), ionice.value))

    print_('num-threads', pinfo['num_threads'])
    if psutil.POSIX:
        print_('num-fds', pinfo['num_fds'])
    if psutil.WINDOWS:
        print_('num-handles', pinfo['num_handles'])

    if 'io_counters' in pinfo:
        print_('I/O', str_ntuple(pinfo['io_counters'], convert_bytes=True))
    if 'num_ctx_switches' in pinfo:
        print_("ctx-switches", str_ntuple(pinfo['num_ctx_switches']))
    if pinfo['children']:
        template = "%-6s %s"
        print_("children", template % ("PID", "NAME"))
        for child in pinfo['children']:
            try:
                print_('', template % (child.pid, child.name()))
            except psutil.AccessDenied:
                print_('', template % (child.pid, ""))
            except psutil.NoSuchProcess:
                pass

    if pinfo['open_files']:
        print_('open-files', 'PATH')
        for i, file in enumerate(pinfo['open_files']):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_('', file.path)
    else:
        print_('open-files', '')

    if pinfo['connections']:
        template = '%-5s %-25s %-25s %s'
        print_('connections',
               template % ('PROTO', 'LOCAL ADDR', 'REMOTE ADDR', 'STATUS'))
        for conn in pinfo['connections']:
            if conn.type == socket.SOCK_STREAM:
                type = 'TCP'
            elif conn.type == socket.SOCK_DGRAM:
                type = 'UDP'
            else:
                type = 'UNIX'
            lip, lport = conn.laddr
            if not conn.raddr:
                rip, rport = '*', '*'
            else:
                rip, rport = conn.raddr
            print_('', template % (
                type,
                "%s:%s" % (lip, lport),
                "%s:%s" % (rip, rport),
                conn.status))
    else:
        print_('connections', '')

    if pinfo['threads'] and len(pinfo['threads']) > 1:
        template = "%-5s %12s %12s"
        print_('threads', template % ("TID", "USER", "SYSTEM"))
        for i, thread in enumerate(pinfo['threads']):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_('', template % thread)
        print_('', "total=%s" % len(pinfo['threads']))
    else:
        print_('threads', '')

    if hasattr(proc, "rlimit"):
        res_names = [x for x in dir(psutil) if x.startswith("RLIMIT")]
        resources = []
        for res_name in res_names:
            try:
                soft, hard = proc.rlimit(getattr(psutil, res_name))
            except psutil.AccessDenied:
                pass
            else:
                resources.append((res_name, soft, hard))
        if resources:
            template = "%-12s %15s %15s"
            print_("res-limits", template % ("RLIMIT", "SOFT", "HARD"))
            for res_name, soft, hard in resources:
                if soft == psutil.RLIM_INFINITY:
                    soft = "infinity"
                if hard == psutil.RLIM_INFINITY:
                    hard = "infinity"
                print_('', template % (
                    RLIMITS_MAP.get(res_name, res_name), soft, hard))

    if hasattr(proc, "environ") and pinfo['environ']:
        template = "%-25s %s"
        print_("environ", template % ("NAME", "VALUE"))
        for i, k in enumerate(sorted(pinfo['environ'])):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_("", template % (k, pinfo['environ'][k]))

    if pinfo.get('memory_maps', None):
        template = "%-8s %s"
        print_("mem-maps", template % ("RSS", "PATH"))
        maps = sorted(pinfo['memory_maps'], key=lambda x: x.rss, reverse=True)
        for i, region in enumerate(maps):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_("", template % (bytes2human(region.rss), region.path))

def main(argv=None):
    parser = argparse.ArgumentParser(
        description="print information about a process")
    parser.add_argument("pid", type=int, help="process pid", nargs='?')
    parser.add_argument('--verbose', '-v', action='store_true',
                        help="print more info")
    args = parser.parse_args()
    run(args.pid, args.verbose)

if __name__ == '__main__':
    sys.exit(main())


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>app.forms.EditUserForm — Eventum 0.1 documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="Eventum 0.1 documentation" href="../../../index.html"/>
        <link rel="up" title="app" href="../../app.html"/>

           Eventum

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Quickstart

Stack

Setup

Developing

Documentation

Testing

Organization / Structure

The Eventum App

Forms

Library Functions

Models

Routes

Module contents

Forms

Form Fields

app.forms.AddToWhitelistForm

app.forms.CreateBlogPostForm

app.forms.CreateEventForm

app.forms.CreateProfileForm

app.forms.DeleteEventForm

app.forms.EditEventForm

app.forms.EditUserForm

app.forms.UploadImageForm

app.forms.validators

Library Functions

app.lib.decorators

app.lib.error

app.lib.events

app.lib.google_calendar

app.lib.google_calendar_resource_builder

app.lib.networking

app.lib.text

Models

Model Fields

app.models.BlogPost

app.models.Event

app.models.EventSeries

app.models.Image

app.models.Post

app.models.User

app.models.Whitelist

Routes

Admin Routes

Submodules

app.routes.base

app.routes.blog

app.routes.client

        Eventum

Docs »

Module code »

app »

app.forms.EditUserForm

Source code for app.forms.EditUserForm

"""
.. module:: EditUserForm
    :synopsis: A form for editing a :class:`~app.models.User`.

.. moduleauthor:: Dan Schlosser <dan@danrs.ch>
"""

from flask.ext.wtf import Form
from wtforms import StringField, RadioField
from wtforms.validators import Required, Email

EMAIL_ERROR = 'Please provide a valid email address.'

[docs]class EditUserForm(Form):
    """A form for editing a :class:`~app.models.User`.

    :ivar name: :class:`wtforms.fields.StringField` - The user's name
    :ivar email: :class:`wtforms.fields.StringField` - The user's email address
    :ivar image_url: :class:`wtforms.fields.StringField` - A URL to a profile
        picture
    :ivar user_type: :class:`wtforms.fields.RadioField` - The permission level
        for the user.
    """
    name = StringField('Full Name', [Required("Please type a name")])
    email = StringField('Email Address',
                      [Email(message=EMAIL_ERROR),
                       Required(message=EMAIL_ERROR)])
    image_url = StringField('Image URL')
    user_type = RadioField('User Type',
                           [Required(message="Please select a user type.")],
                           choices=[('editor', "Editor"),
                                    ('publisher', "Publisher"),
                                    ('admin', "Admin"),
                                    ("fake_user", "Fake User")])

        © Copyright 2014, Dan Schlosser.

  Built with Sphinx using a theme provided by Read the Docs.


text:
package org.keycloak.subsystem.adapter.extension;

import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.logging.Logger;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.LoginConfigMetaData;
import org.keycloak.subsystem.adapter.logging.KeycloakLogger;

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

/**
 * Pass authentication data (keycloak.json) as a servlet context param so it can be read by the KeycloakServletExtension.
 *
 * @author Stan Silvert ssilvert@redhat.com (C) 2014 Red Hat Inc.
 */
public class KeycloakAdapterConfigDeploymentProcessor implements DeploymentUnitProcessor {
    protected Logger log = Logger.getLogger(KeycloakAdapterConfigDeploymentProcessor.class);

    // This param name is defined again in Keycloak Undertow Integration class
    // org.keycloak.adapters.undertow.KeycloakServletExtension.  We have this value in
    // two places to avoid dependency between Keycloak Subsystem and Keyclaok Undertow Integration.
    public static final String AUTH_DATA_PARAM_NAME = "org.keycloak.json.adapterConfig";

    // not sure if we need this yet, keeping here just in case
    protected void addSecurityDomain(DeploymentUnit deploymentUnit, KeycloakAdapterConfigService service) {
        if (!service.isSecureDeployment(deploymentUnit)) {
            return;
        }
        WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
        if (warMetaData == null) return;
        JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
        if (webMetaData == null) return;

        LoginConfigMetaData loginConfig = webMetaData.getLoginConfig();
        if (loginConfig == null || !loginConfig.getAuthMethod().equalsIgnoreCase("KEYCLOAK")) {
            return;
        }

        webMetaData.setSecurityDomain("keycloak");
    }

    @Override
    public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

        KeycloakAdapterConfigService service = KeycloakAdapterConfigService.getInstance();
        if (service.isSecureDeployment(deploymentUnit) && service.isDeploymentConfigured(deploymentUnit)) {
            addKeycloakAuthData(phaseContext, service);
        }

        // FYI, Undertow Extension will find deployments that have auth-method set to KEYCLOAK

        // todo notsure if we need this
        // addSecurityDomain(deploymentUnit, service);
    }

    private void addKeycloakAuthData(DeploymentPhaseContext phaseContext, KeycloakAdapterConfigService service) throws DeploymentUnitProcessingException {
        DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
        if (warMetaData == null) {
            throw new DeploymentUnitProcessingException("WarMetaData not found for " + deploymentUnit.getName() + ".  Make sure you have specified a WAR as your secure-deployment in the Keycloak subsystem.");
        }

        addJSONData(service.getJSON(deploymentUnit), warMetaData);
        JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
        if (webMetaData == null) {
            webMetaData = new JBossWebMetaData();
            warMetaData.setMergedJBossWebMetaData(webMetaData);
        }

        LoginConfigMetaData loginConfig = webMetaData.getLoginConfig();
        if (loginConfig == null) {
            loginConfig = new LoginConfigMetaData();
            webMetaData.setLoginConfig(loginConfig);
        }
        loginConfig.setAuthMethod("KEYCLOAK");
        loginConfig.setRealmName(service.getRealmName(deploymentUnit));
        KeycloakLogger.ROOT_LOGGER.deploymentSecured(deploymentUnit.getName());
    }

    private void addJSONData(String json, WarMetaData warMetaData) {
        JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
        if (webMetaData == null) {
            webMetaData = new JBossWebMetaData();
            warMetaData.setMergedJBossWebMetaData(webMetaData);
        }

        List<ParamValueMetaData> contextParams = webMetaData.getContextParams();
        if (contextParams == null) {
            contextParams = new ArrayList<ParamValueMetaData>();
        }

        ParamValueMetaData param = new ParamValueMetaData();
        param.setParamName(AUTH_DATA_PARAM_NAME);
        param.setParamValue(json);
        contextParams.add(param);

        webMetaData.setContextParams(contextParams);
    }

    @Override
    public void undeploy(DeploymentUnit du) {

    }

}


text:
.example1 {
    -webkit-appearance: none;
    -moz-appearance: none;
}

.example2 {
    appearance: none; /* unprefixed */
}


text: The docs are now hosted on [goa.design](https://goa.design).


text:
while getopts d: option
  do case "${option}" in
  d) DEST=${OPTARG}/;;
  esac
done

: ${DEST:=./};

if [ ! -d "$DEST" ]; then
  echo "Directory $DEST does not exist";
  exit -1;
fi

DBNAME=`cat localSettings.php | grep MYSQL_DB_NAME | cut -d \' -f 4`;
DBUSER=`cat localSettings.php | grep MYSQL_USER | cut -d \' -f 4`;
DBPASS=`cat localSettings.php | grep MYSQL_PASSWORD | cut -d \' -f 4`;

APPNAME=`cat settings.php | grep APPLICATION_NAME | cut -d \' -f 4`;

DIRNAME=$APPNAME-$(date +%Y-%m-%d-%H-%M-%S);
FULLPATHDIRNAME=$DEST$DIRNAME;

mkdir $FULLPATHDIRNAME;

echo `git rev-parse --abbrev-ref HEAD` > $FULLPATHDIRNAME/branch.txt;
echo `git rev-parse HEAD` > $FULLPATHDIRNAME/rev.txt;
mysqldump -u $DBUSER -p$DBPASS $DBNAME > $FULLPATHDIRNAME/database.sql;

tar -C $DEST -cvf ${FULLPATHDIRNAME}.tar $DIRNAME;

rm -rf $FULLPATHDIRNAME;


text:
<?php

namespace kalat\site\entry;

use kalat\entity\KalatEntry;
use kalat\SiteConfig;

class EntryHelper{

	/**
	 * @return KalatEntry
	 * @param KalatEntry $entry
	 */
	public static function findPreviousEntry(KalatEntry $entry, $options = array()){

		list($query,$binds) = self::buildQuery($entry,$options,"desc");

		try{
			$res = KalatEntry::DAO()->executeQuery($query, $binds);
		}catch(\Exception $e){

		}

		if(count($res) < 1)return null;

		$obj = KalatEntry::DAO()->getObject($res[0]);
		return $obj;
	}

	/**
	 * @return KalatEntry
	 * @param KalatEntry $entry
	 */
	public static function findNextEntry(KalatEntry $entry, $options = array()){

		list($query,$binds) = self::buildQuery($entry, $options);

		try{
			$res = KalatEntry::DAO()->executeQuery($query, $binds);
		}catch(\Exception $e){

		}

		if(count($res) < 1)return null;

		$obj = KalatEntry::DAO()->getObject($res[0]);
		return $obj;

	}

	private static function buildQuery(KalatEntry $entry, $options = array(), $order = "asc"){

		$order_type = ($order == "asc");
		$order_query_sort = ($order_type) ? "asc" : "desc";
		$compare_type = ($order_type) ? ">" : "<";
		$compare_type_eq = $compare_type . "=";
		$mode_collection = (isset($options["category"]) && $options["category"] == true) ? true : false;

		$binds = array();

		//
		$where_query = array();
		if($mode_collection){
			$where_query[] = "directory = :directory";
			$binds[":directory"] = $entry->getDirectory();
		}else{
			$where_query[] = "collection = :collection";
			$binds[":collection"] = $entry->getCollection();
		}

		//現在のコレクションの設定を取得する
		$collectionName = $entry->getCollection();
		$orderby = SiteConfig::get("collections." . $collectionName . ".orderby","create");

		//並び順
		$order_query = array();
		if($orderby == "create"){

			$order_query[] = "create_date " . $order_query_sort;
			$order_query[] = "id " . $order_query_sort;
			$where_query[] = "create_date " . $compare_type_eq .":create_date";
			$where_query[] = "id <> :id";
			$binds[":create_date"] = $entry->getCreateDate();
			$binds[":id"] = $entry->getId();

		}else if($orderby == "slug"){

			$where_query[] = "id ".$compare_type." :id";
			$order_query[] = "id " . $order_query_sort;
			$order_query[] = "create_date " . $order_query_sort;
			$binds[":id"] = $entry->getId();

		}else{

			$order_query[] = "id " . $order_query_sort;
			$where_query[] = "id <> :id";
			$binds[":id"] = $entry->getId();
		}

		//SQLを構築
		$where_query = implode(" AND ", $where_query);
		$order_query = implode(",", $order_query);

		$query = "select id,title,url from " . KalatEntry::TABLE() . " where ";
		$query .= $where_query;
		$query .= " order by " . $order_query;
		$query .= " limit 1";

		return array($query, $binds);
	}

}


text:
Common build tools for C/C++ projects. Supports PC and 3DS targets.

Requires some form of the zip/unzip commands. When embedding binary files, xxd is required as well.


text:
<?php
/**
 * User: stephen.parker
 * Date: 13/03/2016
 * Time: 13:57
 */

namespace Api\Controller\Factory;

use Api\Controller\IndexController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class IndexControllerFactory implements FactoryInterface
{

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     *
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $logger = $serviceLocator->getServiceLocator()->get('EnliteMonologService');
        $weatherProviderInterface = $serviceLocator->getServiceLocator()->get('Weather/Service/OpenWeatherMapProvider');
        $forecastProviderInterface = $serviceLocator->getServiceLocator()->get('Weather/Service/OpenWeatherMapProvider');

        $service = new IndexController($logger, $weatherProviderInterface, $forecastProviderInterface);

        return $service;
    }
}


text:
<!DOCTYPE html SYSTEM "about:legacy-compat">

	  <meta charset="UTF-8">

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

	  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <title>Webd2 | Casteels Meiyin | Styleguide</title>

    <meta name="description" content="Lees hier alles over nieuwe media, html5 en andere ontwikkelingen in webdevelopment en mobile development. De docenten NMD willen graag hun kennis delen met jou!">
    <meta name="keywords" content="HTML5, JavaScript, jQuery, CSS3">
    <meta name="author" content="Arteveldehogeschool - Bachelor in de grafische en digitale media | MMP">
    <meta name="copyright" content="Copyright 2010-17 Arteveldehogeschool. All Rights Reserved.">

    <meta property="og:type" content="website">
    <meta property="og:title" content=">HTML5 | Webdesign II | GDM">
    <meta property="og:description" content="Lees hier alles over nieuwe media, html5 en andere ontwikkelingen in webdevelopment en mobile development. De docenten NMD willen graag hun kennis delen met jou!">
    <meta property="og:url" content="http://www.gdm.gent/">
    <meta property="og:site_name" content="GDM.GENT">
    <meta property="og:image" content="assets/images/ahs.png">
    <meta property="og:image:width" content="129">
    <meta property="og:image:height" content="129">

    <link rel="author" type="text/plain" href="/humans.txt">

    <link rel="dns-prefetch" href="//cdnjs.cloudflare.com">
    <link rel="dns-prefetch" href="//code.jquery.com">
    <link rel="dns-prefetch" href="//maxcdn.bootstrapcdn.com">

    <link rel="apple-touch-icon" sizes="180x180" href="assets/icons/apple-touch-icon.png">
    <link rel="icon" type="image/png" href="assets/icons/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="assets/icons/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="assets/icons/manifest.json">
    <link rel="mask-icon" href="assets/icons/safari-pinned-tab.svg" color="#ee9900">
    <link rel="shortcut icon" href="assets/icons/favicon.ico">
    <meta name="apple-mobile-web-app-title" content="GDM">
    <meta name="application-name" content="GDM">
    <meta name="msapplication-config" content="assets/icons/browserconfig.xml">
    <meta name="theme-color" content="#ffffff">

    <link rel="stylesheet" media="all" href="vendor/normalize/normalize.css">
    <link rel="stylesheet" href="css/grid.css">

    <link rel="stylesheet" media="all" href="css/fonts.css">
    <link rel="stylesheet" media="all" href="css/typography.css">
    <link rel="stylesheet" media="all" href="css/main.css">
    <link rel="stylesheet" media="all" href="css/styleguide.css">

                    home

                    about us

                    contact

Interactive Style Guide

                Logo

                  Colors

#540C11

#A0222E

#C2C6D9

#2E2E2E

#1D1D1B

                Typography

Title

Content

Accent

                Link

Open Sans Regular | 32pt

Roboto Regular | 12pt

Roboto Bold | 12pt

                Roboto Regular | 12pt

                Icons

                Actions

          <form action="/action_page.php">

            First Name

            <input type="text" id="fname" name="firstname">

            Last Name

            <input type="text" id="lname" name="lastname">

            Subject

            <textarea id="subject" name="subject" style="height:200px"></textarea>

            send

          </form>

Sitemap

                  Home

                  About Us

                  Contact


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

from dropbot import __version__ as pkg_version

readme = open('README.md').read()

requirements = [
    'sleekxmpp==1.3.1',
    'eveapi==1.2.6',
    'redis==2.10.2',
    'requests==2.3.0',
    'humanize==0.5',
    'dnspython==1.11.1',
    'networkx==1.9',
]

test_requirements = [
    'mock==1.0.1',
]

setup(
    name='dropbot',
    version=pkg_version,
    description='A XMPP bot to provide simple services to NOG8S and Predditors in general',
    long_description=readme,
    author='Andrew Williams',
    author_email='andy@tensixtyone.com',
    url='https://github.com/nikdoof/dropbot/',
    packages=[
        'dropbot',
    ],
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements,
    entry_points = {
        'console_scripts': ['dropbot=dropbot.cli:main'],
    }
)


text:
//
// kerneldiskrep - the kernel's own disk representation.
//
// This is a very special case.
// It's here primarily so we don't have to add special cases for the kernel
// all over the higher layers.
//
#ifndef _H_KERNELDISKREP
#define _H_KERNELDISKREP

#include "diskrep.h"

namespace Security {
namespace CodeSigning {

//
// A KernelDiskRep represents a (the) kernel on disk.
// It has no write support, so we can't sign the kernel,
// which is fine since we unconditionally trust it anyway.
//
class KernelDiskRep : public DiskRep {
public:
	KernelDiskRep();

	CFDataRef component(CodeDirectory::SpecialSlot slot);
	CFDataRef identification();
	std::string mainExecutablePath();
	CFURLRef copyCanonicalPath();
	size_t signingLimit();
	std::string format();
	UnixPlusPlus::FileDesc &fd();

	std::string recommendedIdentifier(const SigningContext &ctx);
};

} // end namespace CodeSigning
} // end namespace Security

#endif // !_H_KERNELDISKREP


text:
const char* utils::end_symbol          = "**END**";
const char* utils::unknown_word_symbol = "███████";

namespace utils {
	typename Vocab::ind_t Vocab::operator[](const std::string& word) const {
        auto found = word2index.find(word);
        if (found != word2index.end()) {
            return found->second;
        }
        return unknown_word;
    }

    void Vocab::construct_word2index() {
        uint i = 0;
        for (auto& s : index2word)
            word2index[s] = i++;
    }
    void Vocab::add_unknown_word() {
        if (word2index.find(unknown_word_symbol) == word2index.end()) {
            index2word.emplace_back(unknown_word_symbol);
            word2index[unknown_word_symbol] = index2word.size() - 1;
            unknown_word = index2word.size() - 1;
        } else {
            unknown_word = word2index.at(unknown_word_symbol);
        }
    }

    size_t Vocab::size() const {
        return index2word.size();
    }

    std::vector<typename Vocab::ind_t> Vocab::encode(const std::vector<std::string>& words, bool with_end_symbol) const {
        std::vector<ind_t> result;
        result.reserve(words.size() + (with_end_symbol ? 1 : 0));
        std::transform(words.begin(), words.end(),
                       std::back_inserter(result), [this](const std::string& word) {
            if (word2index.find(word) == word2index.end()) {
                return unknown_word;
            } else {
                return word2index.at(word);
            }
        });
        if (with_end_symbol) {
            result.emplace_back(word2index.at(utils::end_symbol));
        }
        return result;
    }

    void Vocab::add(const std::vector<std::string>& words) {
        for (auto& word : words) {
            add(word);
        }
    }

    void Vocab::add(const std::string& word) {
        auto found = word2index.find(word) != word2index.end();
        if (!found) {
            uint next_index = word2index.size();
            word2index[word] = next_index;
            index2word.emplace_back(word);
        }
    }

    std::vector<std::string> Vocab::decode(const std::vector<int>& indices, bool remove_end_symbol) const {
        std::vector<std::string> result;
        result.reserve(indices.size());
        bool has_end_symbol = false;
        if (indices.size() > 0) {
            // either the decoding must remove the end symbol
            // if there is one, or we assume there is none to remove.
            has_end_symbol = remove_end_symbol ?
                (int)indices[indices.size() - 1] == word2index.at(utils::end_symbol) :
                false;
        }
        int length = indices.size();
        if (has_end_symbol) --length;
        for (int i = 0; i < length; i++) {
            int idx = indices[i];
            if (idx >= 0 && idx < index2word.size()) {
                result.emplace_back(index2word[idx]);
            } else {
                result.emplace_back(index2word[unknown_word]);
            }
        }
        return result;
    }

    Vocab::Vocab() : unknown_word(-1) {add_unknown_word();};

    Vocab::Vocab(std::vector<std::string>& _index2word) : index2word(_index2word), unknown_word(-1) {
        construct_word2index();
        add_unknown_word();
    }
    Vocab::Vocab(std::vector<std::string>& _index2word, bool _unknown_word) : index2word(_index2word), unknown_word(-1) {
        construct_word2index();
        if (_unknown_word) add_unknown_word();
    }

    Vocab::Vocab(std::vector<std::string>&& _index2word) : Vocab(_index2word) {
    }
    Vocab::Vocab(std::vector<std::string>&& _index2word, bool _unknown_word) : Vocab(_index2word, _unknown_word) {
    }

    CharacterVocab::CharacterVocab(int min_char, int max_char)
        : min_char(min_char), max_char(max_char) {
        ASSERT2(max_char > min_char, utils::make_message(
                "Maximum character (", max_char, ") must be larger than minimum character (",
                min_char, ")."));
        ASSERT2(max_char >= 0 && min_char >= 0, "Cannot have negative characters in mapping");
    }

    size_t CharacterVocab::size() const {
        return (size_t) ((max_char - min_char) + 1);
    }

    std::vector<typename Vocab::ind_t> CharacterVocab::encode(const std::vector<std::string>& words) const {
        std::vector<ind_t> result;
        int char_size = 0;
        // add all characters:
        for (auto& w : words) char_size += w.size();
        // for spaces:
        if (words.size() > 0) char_size += words.size() - 1;

        result.reserve(char_size);
        int unknown_char = max_char - min_char;
        int space_char = ' ' - min_char;

        if (space_char < 0) space_char = unknown_char;

        int word_idx = 0;
        for (auto& w : words) {
            for (auto& c : w) {
                if ((int)c >= min_char && (int)c < max_char) {
                    result.emplace_back(c - min_char);
                } else {
                    // all unknown get replaced by max_char
                    result.emplace_back(unknown_char);
                }
            }
            word_idx++;
            if (word_idx < words.size()) result.emplace_back(space_char);
        }
        return result;
    }

    std::vector<std::string> CharacterVocab::decode(const std::vector<int>& indices) const {
        std::vector<std::string> result;
        result.reserve(indices.size());

        std::stringstream stream;
        for (size_t i = 0; i < indices.size(); i++) {
            if (indices[i] == max_char) {
                stream << "█";
            } else {
                stream << ((char) (indices[i] + min_char));
            }
        }
        return tokenize(stream.str());
    }

    std::vector<std::string> CharacterVocab::decode_characters(const std::vector<int>& indices) const {
        std::vector<std::string> result(indices.size());
        int char_idx = 0;
        for (size_t i = 0; i < indices.size(); i++) {
            if (indices[i] == max_char) {
                result[char_idx++] = "█";
            } else {
                result[char_idx++] = (char) (indices[i] + min_char);
            }
        }
        return result;
    }
}


text:
namespace FluentValidation {
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Linq.Expressions;
	using System.Threading.Tasks;
	using Internal;
	using Resources;
	using Validators;

	/// <summary>
	/// Default options that can be used to configure a validator.
	/// </summary>
	public static class DefaultValidatorOptions {

		/// <summary>
		/// Specifies the cascade mode for failures.
		/// If set to 'Stop' then execution of the rule will stop once the first validator in the chain fails.
		/// If set to 'Continue' then all validators in the chain will execute regardless of failures.
		/// </summary>
		public static IRuleBuilderInitial<T, TProperty> Cascade<T, TProperty>(this IRuleBuilderInitial<T, TProperty> ruleBuilder, CascadeMode cascadeMode) {
			return ruleBuilder.Configure(cfg => {
				cfg.CascadeMode = cascadeMode;
			});
		}

		/// <summary>
		/// Specifies a custom action to be invoked when the validator fails.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="TProperty"></typeparam>
		/// <param name="rule"></param>
		/// <param name="onFailure"></param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> OnAnyFailure<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<T> onFailure) {
			return rule.Configure(config => {
				config.OnFailure = onFailure.CoerceToNonGeneric();
			});
		}

		/// <summary>
		/// Specifies a custom error message to use if validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="errorMessage">The error message to use</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage) {
			return rule.WithMessage(errorMessage, null as object[]);
		}

		/// <summary>
		/// Specifies a custom error message to use if validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="errorMessage">The error message to use</param>
		/// <param name="formatArgs">Additional arguments to be specified when formatting the custom error message.</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params object[] formatArgs) {
			var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs);
			return rule.WithMessage(errorMessage, funcs);
		}

		/// <summary>
		/// Specifies a custom error message to use if validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="errorMessage">The error message to use</param>
		/// <param name="funcs">Additional property values to be included when formatting the custom error message.</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params Func<T, object>[] funcs) {
			errorMessage.Guard("A message must be specified when calling WithMessage.");

			return rule.Configure(config => {
				config.CurrentValidator.ErrorMessageSource = new StaticStringSource(errorMessage);

				funcs.Select(func => new Func<object, object, object>((instance, value) => func((T) instance)))
					.ForEach(config.CurrentValidator.CustomMessageFormatArguments.Add);
			});
		}

	/// <summary>
		/// Specifies a custom error message to use if validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="errorMessage">The error message to use</param>
		/// <param name="funcs">Additional property values to use when formatting the custom error message.</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params Func<T, TProperty, object>[] funcs) {
			errorMessage.Guard("A message must be specified when calling WithMessage.");

			return rule.Configure(config => {
				config.CurrentValidator.ErrorMessageSource = new StaticStringSource(errorMessage);

				funcs
					.Select(func => new Func<object, object, object>((instance, value) => func((T)instance, (TProperty)value)))
					.ForEach(config.CurrentValidator.CustomMessageFormatArguments.Add);
			});
		}

		/// <summary>
		/// Specifies a custom error message to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="messageProvider">Delegate that will be invoked to retrieve the localized message. </param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, string> messageProvider) {
			messageProvider.Guard("A messageProvider must be provided.");
			Func<object, string> newFunc = x => messageProvider((T)x);
			return rule.Configure(config => {
				config.CurrentValidator.ErrorMessageSource = new LazyStringSource(newFunc);
			});
		}

		/// <summary>
		/// Specifies a custom error code to use if validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="errorCode">The error code to use</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithErrorCode<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorCode) {
			errorCode.Guard("A error code must be specified when calling WithErrorCode.");

			return rule.Configure(config => {
				config.CurrentValidator.ErrorCodeSource = new StaticStringSource(errorCode);
			});
		}

		/// <summary>
		/// Specifies a custom error message resource to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
		/// <returns></returns>
		[Obsolete("Use WithLocalizedMessage(Type resourceType, string resourceName) instead.")]
		public static IRuleBuilderOptions<T,TProperty> WithLocalizedMessage<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector) {
			// We use the StaticResourceAccessorBuilder here because we don't want calls to WithLocalizedMessage to be overriden by the ResourceProviderType.
			return rule.WithLocalizedMessage(resourceSelector, new StaticResourceAccessorBuilder());
		}

		/// <summary>
		/// Specifies a custom error message resource to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
		/// <param name="formatArgs">Custom message format args</param>
		/// <returns></returns>
		[Obsolete("Use WithLocalizedMessage(Type resourceType, string resourceName, params object[] formatArgs) instead.")]
		public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Expression<Func<string>> resourceSelector, params object[] formatArgs) {
			var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs);
			return rule.WithLocalizedMessage(resourceSelector, funcs);
		}

		/// <summary>
		/// Specifies a custom error message resource to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
		/// <param name="formatArgs">Custom message format args</param>
		/// <returns></returns>
		[Obsolete("Use WithLocalizedMessage(Type resourceType, string resourceName, params Func<T, object>[] formatArgs) instead.")]
		public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Expression<Func<string>> resourceSelector, params Func<T, object>[] formatArgs) {
			// We use the StaticResourceAccessorBuilder here because we don't want calls to WithLocalizedMessage to be overriden by the ResourceProviderType.
			return rule.WithLocalizedMessage(resourceSelector, new StaticResourceAccessorBuilder())
				.Configure(cfg => {
					formatArgs
						.Select(func => new Func<object, object, object>((instance, value) => func((T)instance)))
						.ForEach(cfg.CurrentValidator.CustomMessageFormatArguments.Add);
				});

		}

		/// <summary>
		/// Specifies a custom error message resource to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
		/// <param name="resourceAccessorBuilder">The resource accessor builder to use. </param>
		/// <returns></returns>
		[Obsolete("Use WithLocalizedMessage(Type resourceType, string resourceName, IResourceAccessorBuilder instead) instead.")]
		public static IRuleBuilderOptions<T,TProperty> WithLocalizedMessage<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector, IResourceAccessorBuilder resourceAccessorBuilder) {
			resourceSelector.Guard("An expression must be specified when calling WithLocalizedMessage, eg .WithLocalizedMessage(() => Messages.MyResource)");

			return rule.Configure(config => {
				config.CurrentValidator.ErrorMessageSource = LocalizedStringSource.CreateFromExpression(resourceSelector, resourceAccessorBuilder);
			});
		}

		/// <summary>
		/// Specifies a custom error message resource to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
		/// <param name="resourceName">Name of resource</param>
		/// <param name="formatArgs">Custom message format args</param>
		/// <param name="resourceType">Type of resource representing a resx file</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Type resourceType, string resourceName, params object[] formatArgs)
		{
			var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs);
			return rule.WithLocalizedMessage(resourceType, resourceName, funcs);
		}

		/// <summary>
		/// Specifies a custom error message resource to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceName">Resource name</param>
		/// <param name="formatArgs">Custom message format args</param>
		/// <param name="resourceType">Resource type representing a resx file</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Type resourceType, string resourceName, params Func<T, object>[] formatArgs)
		{
			// We use the StaticResourceAccessorBuilder here because we don't want calls to WithLocalizedMessage to be overriden by the ResourceProviderType.
			return rule.WithLocalizedMessage(resourceType, resourceName)
				.Configure(cfg => {
					formatArgs
						.Select(func => new Func<object, object, object>((instance, value) => func((T)instance)))
						.ForEach(cfg.CurrentValidator.CustomMessageFormatArguments.Add);
				});
		}

		/// <summary>
		/// Specifies a custom error message resource to use when validation fails.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceType">Resource type representing a resx file</param>
		/// <param name="resourceName">Name of resource</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Type resourceType, string resourceName) {
			resourceType.Guard("A resource type must be provided.");
			resourceName.Guard("A resource name must be provided.");

			return rule.Configure(config => {
				config.CurrentValidator.ErrorMessageSource = new LocalizedStringSource(resourceType, resourceName, new StaticResourceAccessorBuilder());
			});
		}

		/// <summary>
		/// Specifies a condition limiting when the validator should run.
		/// The validator will only be executed if the result of the lambda returns true.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="predicate">A lambda expression that specifies a condition for when the validator should run</param>
		/// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> When<T,TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
			predicate.Guard("A predicate must be specified when calling When.");
			// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
			return rule.Configure(config => {
				config.ApplyCondition(predicate.CoerceToNonGeneric(), applyConditionTo);
			});
		}

		/// <summary>
		/// Specifies a condition limiting when the validator should not run.
		/// The validator will only be executed if the result of the lambda returns false.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="predicate">A lambda expression that specifies a condition for when the validator should not run</param>
		/// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> Unless<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
			predicate.Guard("A predicate must be specified when calling Unless");
			return rule.When(x => !predicate(x), applyConditionTo);
		}

		/// <summary>
		/// Specifies an asynchronous condition limiting when the validator should run.
		/// The validator will only be executed if the result of the lambda returns true.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="predicate">A lambda expression that specifies a condition for when the validator should run</param>
		/// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WhenAsync<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators)
		{
			predicate.Guard("A predicate must be specified when calling WhenAsync.");
			// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
			return rule.Configure(config => {
				config.ApplyAsyncCondition(predicate.CoerceToNonGeneric(), applyConditionTo);
			});
		}

		/// <summary>
		/// Specifies an asynchronous condition limiting when the validator should not run.
		/// The validator will only be executed if the result of the lambda returns false.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="predicate">A lambda expression that specifies a condition for when the validator should not run</param>
		/// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> UnlessAsync<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators)
		{
			predicate.Guard("A predicate must be specified when calling UnlessAsync");
			return rule.WhenAsync(x => predicate(x).Then(y => !y), applyConditionTo);
		}

		/// <summary>
		/// Triggers an action when the rule passes. Typically used to configure dependent rules. This applies to all preceding rules in the chain.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="action">An action to be invoked if the rule is valid</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> DependentRules<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<DependentRules<T>>  action) {
			var dependencyContainer = new DependentRules<T>();
			action(dependencyContainer);

			rule.Configure(cfg => {

				if (!string.IsNullOrEmpty(cfg.RuleSet)) {
					foreach (var dependentRule in dependencyContainer) {
						var propRule = dependentRule as PropertyRule;
						if (propRule != null && string.IsNullOrEmpty(propRule.RuleSet)) {
							propRule.RuleSet = cfg.RuleSet;
						}
					}
				}

				cfg.DependentRules.AddRange(dependencyContainer);
			});
			return rule;
		}

		/// <summary>
		/// Specifies a custom property name to use within the error message.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="overridePropertyName">The property name to use</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string overridePropertyName) {
			overridePropertyName.Guard("A property name must be specified when calling WithName.");
			return rule.Configure(config => {
				config.DisplayName = new StaticStringSource(overridePropertyName);
			});
		}

		/// <summary>
		/// Specifies a localized name for the error message.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
		/// <param name="resourceAccessorBuilder">Resource accessor builder to use</param>
		public static IRuleBuilderOptions<T, TProperty> WithLocalizedName<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector, IResourceAccessorBuilder resourceAccessorBuilder = null) {
			resourceSelector.Guard("A resource selector must be specified.");
			// default to the static resource accessor builder - explicit resources configured with WithLocalizedName should take precedence over ResourceProviderType.
			resourceAccessorBuilder = resourceAccessorBuilder ?? new StaticResourceAccessorBuilder();

			return rule.Configure(config => {
				config.DisplayName = LocalizedStringSource.CreateFromExpression(resourceSelector, resourceAccessorBuilder);
			});
		}

		/// <summary>
		/// Overrides the name of the property associated with this rule.
		/// NOTE: This is a considered to be an advanced feature. 99% of the time that you use this, you actually meant to use WithName.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="propertyName">The property name to use</param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> OverridePropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string propertyName) {
			propertyName.Guard("A property name must be specified when calling WithNamePropertyName.");
			return rule.Configure(config => config.PropertyName = propertyName);
		}

		/// <summary>
		/// Overrides the name of the property associated with this rule.
		/// NOTE: This is a considered to be an advanced feature. 99% of the time that you use this, you actually meant to use WithName.
		/// </summary>
		/// <param name="rule">The current rule</param>
		/// <param name="propertyName">The property name to use</param>
		/// <returns></returns>
		[Obsolete("WithPropertyName has been deprecated. If you wish to set the name of the property within the error message, use 'WithName'. If you actually intended to change which property this rule was declared against, use 'OverridePropertyName' instead.")]
		public static IRuleBuilderOptions<T, TProperty> WithPropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string propertyName) {
			return rule.OverridePropertyName(propertyName);
		}

		/// <summary>
		/// Specifies custom state that should be stored alongside the validation message when validation fails for this rule.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="TProperty"></typeparam>
		/// <param name="rule"></param>
		/// <param name="stateProvider"></param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithState<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, object> stateProvider) {
			stateProvider.Guard("A lambda expression must be passed to WithState");
			return rule.Configure(config => config.CurrentValidator.CustomStateProvider = stateProvider.CoerceToNonGeneric());
		}

		///<summary>
		/// Specifies custom severity that should be stored alongside the validation message when validation fails for this rule.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="TProperty"></typeparam>
		/// <param name="rule"></param>
		/// <param name="severity"></param>
		/// <returns></returns>
		public static IRuleBuilderOptions<T, TProperty> WithSeverity<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Severity severity) {
			return rule.Configure(config => config.CurrentValidator.Severity = severity);
		}

		static Func<T, object>[] ConvertArrayOfObjectsToArrayOfDelegates<T>(object[] objects) {
			if(objects == null || objects.Length == 0) {
				return new Func<T, object>[0];
			}
			return objects.Select(obj => new Func<T, object>(x => obj)).ToArray();
		}
	}
}


text:
import sys
import re
from solvertools.normalize import normalize_wp_link
assert sys.getdefaultencoding() == 'utf-8'

LINE_RE = re.compile("^ *([0-9]+) (.*)$")

def transform():
    for line in sys.stdin:
        line = line.rstrip()
        match = LINE_RE.match(line)
        if match:
            freq = int(match.group(1))
            if freq == 1:
                break
            name = normalize_wp_link(match.group(2)).strip()

            if name and '###' not in name:
                print('%s,%d' % (name, freq))

transform()


text:
using System;

namespace DotArguments.Attributes
{
    /// <summary>
    /// Basic attribute for positional arguments.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public abstract class PositionalArgumentAttribute : ArgumentAttribute
    {
        private readonly int index;
        private readonly string name;

        /// <summary>
        /// Initializes a new instance of the <see cref="PositionalArgumentAttribute"/> class.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="name">The name.</param>
        internal PositionalArgumentAttribute(int index, string name)
            : base()
        {
            this.index = index;
            this.name = name;
        }

        /// <summary>
        /// Gets the index.
        /// </summary>
        /// <value>The index.</value>
        public int Index
        {
            get { return this.index; }
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name
        {
            get { return this.name; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is optional.
        /// </summary>
        /// <value><c>true</c> if this instance is optional; otherwise, <c>false</c>.</value>
        public bool IsOptional { get; set; }
    }
}


text:
'use strict';

define(['app'], function(app) {
    console.log('Kernel Auth service loaded ...');

    angular.module('app')
        .service('authService', ['$modal',
            function($modal) {
                return {
                    authenticateWithModal: function() {
                        var modalAuthInstance = $modal.open({
                            templateUrl: '/app/Aisel/User/views/modal/login.html',
                            controller: 'ModalAuthCtrl'
                        });
                    }
                }
            }
        ]);

    angular.module('app')
        .controller('ModalAuthCtrl', ['$scope', '$rootScope', '$state', 'userService', 'notify', 'Environment',
            function($scope, $rootScope, $state, userService, notify, Environment) {
                var locale = Environment.currentLocale();

                $scope.passwordForgot = function() {
                    $scope.$dismiss('close');
                    $state.transitionTo('userPasswordForgot', {
                        locale: locale
                    });
                }

                $scope.register = function() {
                    $scope.$dismiss('close');
                    $state.transitionTo('userRegister', {
                        locale: locale
                    });
                }

                $scope.login = function(username, password) {
                    userService.login(username, password).success(
                        function(data, status) {
                            notify(data.message);

                            if (data.status) {
                                if (data.user.username) {
                                    $rootScope.user = data.user;
                                    $scope.$dismiss('close');
                                }
                            }
                        }
                    );
                };
            }
        ]);
});


text:
/*
	JS-Core Notify Plugin, version 1.1
	Todo: Поправить ошибку при отрисовке более одного notify-окна.
*/
core.notify = {
	show: function(t,bgcolor,timeout) {
		var jscnt = window.setTimeout(function() {$("js-core-notify").remove();if(jscni)clearInterval(jscni);}, timeout);
		var jscnti = timeout/1000;
		var jscni = setInterval(function(){$('js-core-notify-other').text('Это сообщение самоликвидируется через ' + (jscnti - 1) + " секунд(ы)!");jscnti-=1; } , 1000);
		$(document.body).prepend('div').css("background",bgcolor).id('js-core-notify')
		$('js-core-notify').append('div').id('js-notify-close').append('a').attr({href:"#"}).html('⊗').click(
			function(e){
				clearInterval(jscni);
				clearTimeout(jscnt);
				$('js-core-notify').remove();
				$.stop(e);
			}
		);
		$('js-notify-close').css("visibility","hidden");
		$('js-core-notify').append('div').id('js-core-notify-text').html(t);
		$('js-core-notify').append('div').id('js-core-notify-other').text('Это сообщение самоликвидируется через ' + timeout / 1000 + " секунд(ы)!");
		$('js-core-notify').bind('mouseover',
			function(e) {
				$('js-notify-close').css("visibility","visible");
				$('js-core-notify').addClass('js-core-notify-unopacity');
				$.stop(e);
			}
		);
		$('js-core-notify').bind('mouseout',
			function(e) {
				$('js-notify-close').css("visibility","hidden");
				$('js-core-notify').removeClass('js-core-notify-unopacity');
				$('js-core-notify').addClass('js-core-notify-opacity');
				$.stop(e);
			}
		);
	}
}


text:
import React from 'react'
import {search, getPreviewSnapshot} from './client-adapters/reference'
import ReferenceInput from '../../inputs/ReferenceInput'

export default class LyraReference extends React.Component {
  setInput = input => {
    this._input = input
  }
  focus() {
    this._input.focus()
  }
  render() {
    return (
      <ReferenceInput
        {...this.props}
        onSearch={search}
        getPreviewSnapshot={getPreviewSnapshot}
        ref={this.setInput}
      />
    )
  }
}


text:
package de.lessvoid.nifty.elements.events;

import de.lessvoid.nifty.NiftyEvent;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.input.NiftyMouseInputEvent;

import javax.annotation.Nonnull;

public class NiftyMouseWheelEvent implements NiftyEvent {
  private final Element element;
  private final int mouseWheel;

  public NiftyMouseWheelEvent(final Element element, @Nonnull final NiftyMouseInputEvent source) {
    this.element = element;
    this.mouseWheel = source.getMouseWheel();
  }

  public Element getElement() {
    return element;
  }

  public int getMouseWheel() {
    return mouseWheel;
  }
}


text:
var App = require('app');

/**
 * initialize common cache container for mappers
 * App.cache contains shared data, used for syncronizing incoming server data among mappers
 */
App.cache = {
  'previousHostStatuses': {},
  'previousComponentStatuses': {},
  'previousComponentPassiveStates': {},
  'staleConfigsComponentHosts': {},
  'services': [],
  'currentConfigVersions': {}
};

App.cache.clear = function () {
  var clear = App.cache.clear;
  App.cache = {
    'previousHostStatuses': {},
    'previousComponentStatuses': {},
    'previousComponentPassiveStates': {},
    'services': [],
    'currentConfigVersions': {}
  };
  App.cache.clear = clear;
};

App.store.reopen({
  safeLoadMany: function(model, records) {
    try {
      this.loadMany(model, records);
    } catch (e) {
      console.debug('Resolve uncommitted records before load');
      this.fastCommit();
      this.loadMany(model, records);
    }
  },

  safeLoad: function(model, record) {
    try {
      this.load(model, record);
    } catch (e) {
      console.debug('Resolve uncommitted record before load');
      this.fastCommit();
      this.load(model, record);
    }
  },

  /**
   * App.store.commit() - creates new transaction,
   * and them move all records from old to new transactions which is expensive
   *
   * We should use only defaultTransaction,
   * and then we can stub removeCleanRecords method,
   * because it would remove from and add records to the same (default) transaction
   */
  fastCommit: function() {
    console.time('store commit');
    App.store.defaultTransaction.commit();
    console.timeEnd('store commit');
  }
});

App.ServerDataMapper = Em.Object.extend({
  jsonKey: false,
  map: function (json) {
    if (json) {
      var model = this.get('model');
      var jsonKey = this.get('jsonKey');

      if (jsonKey && json[jsonKey]) { // if data come as { hdfs: {...} }
        json = json[jsonKey];
      }

      $.each(json, function (field, value) {
        model.set(field, value);
      })
    }
  }
});

App.QuickDataMapper = App.ServerDataMapper.extend({
  config: {},
  model: null,
  map: function (json) {
    if (!this.get('model')) {
      return;
    }

    if (json.items) {
      var result = [];

      json.items.forEach(function (item) {
        result.push(this.parseIt(item, this.config));
      }, this);

      App.store.safeLoadMany(this.get('model'), result);
    }
  },

  parseIt: function (data, config) {
    var result = {};
    for ( var i in config) {
      if (i.substr(0, 1) === '$') {
        i = i.substr(1, i.length);
        result[i] = config['$' + i];
      } else {
        var isSpecial = false;
        if (i.substr(-5) == '_type') {
          var prefix = i.substr(0, i.length - 5);
          isSpecial = config[prefix + '_key'] != null;
        } else if (i.substr(-4) == '_key') {
          var prefix = i.substr(0, i.length - 4);
          isSpecial = config[prefix + '_type'] != null;
        }
        if (!isSpecial && typeof config[i] == 'string') {
          result[i] = this.getJsonProperty(data, config[i]);
        } else if (typeof config[i] == 'object') {
          result[i] = [];
          var _data = this.getJsonProperty(data, config[i + '_key']);
          var _type = config[i + '_type'];
          var l = _data.length;
          for ( var index = 0; index < l; index++) {
            if (_type == 'array') {
              result[i].push(this.getJsonProperty(_data[index], config[i].item));
            } else {
              result[i].push(this.parseIt(_data[index], config[i]));
            }
          }
          // As for 'widgets', just show the original order
          if(_type == 'array' && i != 'widgets'){
            result[i] = result[i].sort();
          }
        }
      }
    }
    return result;
  },

  getJsonProperty: function (json, path) {
    var pathArr = path.split('.');
    var current = json;
    while (pathArr.length && current) {
      if (pathArr[0].substr(-1) == ']') {
        var index = parseInt(pathArr[0].substr(-2, 1));
        var attr = pathArr[0].substr(0, pathArr[0].length - 3);
        if (attr in current) {
          current = current[attr][index];
        }
      } else {
        current = current[pathArr[0]];
      }
      pathArr.splice(0, 1);
    }
    return current;
  },

  /**
   * properly delete record from model
   * @param item
   */
  deleteRecord: function (item) {
    if (item.get('isLoaded')) {
      item.deleteRecord();
      App.store.fastCommit();
      item.get('stateManager').transitionTo('loading');
    }
  },
  /**
   * check mutable fields whether they have been changed and if positive
   * return host object only with properties, that contains new value
   * @param current
   * @param previous
   * @param fields
   * @return {*}
   */
  getDiscrepancies: function (current, previous, fields) {
    var result = {};
    if (previous) {
      fields.forEach(function (field) {
        if (Array.isArray(current[field])) {
          if (JSON.stringify(current[field]) !== JSON.stringify(previous[field])) {
            result[field] = current[field];
            result.isLoadNeeded = true;
          }
        } else {
          if (current[field] != previous[field]) result[field] = current[field];
        }
      });
      return result;
    }
    return current;
  },

  /**
   * Binary search searchElement in the array (should be sorted!)
   * @param {number[]|string[]} array
   * @param {number|string} searchElement
   * @returns {number} position of the needed element or negative value, if value wasn't found
   * @method binaryIndexOf
   */
  binaryIndexOf: function (array, searchElement) {
    var minIndex = 0;
    var maxIndex = array.length - 1;
    var currentIndex;
    var currentElement;
    var resultIndex;

    if (array[0] > searchElement || array[array.length - 1] < searchElement) {
      return -1;
    }
    while (minIndex <= maxIndex) {
      resultIndex = currentIndex = (minIndex + maxIndex) / 2 | 0;
      currentElement = array[currentIndex];

      if (currentElement < searchElement) {
        minIndex = currentIndex + 1;
      }
      else
      if (currentElement > searchElement) {
        maxIndex = currentIndex - 1;
      }
      else {
        return currentIndex;
      }
    }

    return ~maxIndex;
  },

  /**
   * @param {Em.Object} record
   * @param {object} event
   * @param {object} config
   */
  updatePropertiesByConfig: function(record, event, config) {
    if (record.get('isLoaded')) {
      for (var internalProp in config) {
        let externalProp = config[internalProp];
        if (!Em.isNone(event[externalProp])) {
          record.set(internalProp, event[externalProp]);
        }
      }
    }
  }

});


text:
'use strict';

var ReactDOMComponentTree = require('ReactDOMComponentTree');

var focusNode = require('fbjs/lib/focusNode');

var AutoFocusUtils = {
  focusDOMComponent: function() {
    focusNode(ReactDOMComponentTree.getNodeFromInstance(this));
  },
};

module.exports = AutoFocusUtils;


text:
package com.soebes.subversion.sapm;

import java.util.ArrayList;

/**
 * Convenience class for the grammar to handle a list of {@link Group}s.
 * @author Karl Heinz Marbaise
 *
 */
public class Groups {
    private ArrayList<Group> groupsList;

    public Groups() {
        setGroupsList(new ArrayList<Group>());
    }

    public void setGroupsList(ArrayList<Group> groupsList) {
        this.groupsList = groupsList;
    }

    /**
     * Get the list of all groups
     * @return The list of Groups.
     */
    public ArrayList<Group> getGroupsList() {
        return groupsList;
    }

    /**
     * Add a single {@link Group group} to the list of groups.
     * @param group The {@link Group group} which will added to the list.
     */
    public void add(Group group) {
        getGroupsList().add(group);
    }

    /**
     * Check if a group with the given groupName exists in the
     * list or not.
     * The check will be done case-sensitive.
     * @param groupName The name we are searching for.
     * @return true if the group has been found false otherwise.
     */
    public boolean hasGroup(String groupName) {
        boolean result = false;
        for (Group item : getGroupsList()) {
            if (item.getName().equals(groupName)) {
                result = true;
            }
        }
        return result;
    }

    public Group getGroup(Group group) {
        return getGroup(group.getName());
    }

    /**
     * Get the Group instance from the list by
     * name.
     * @param groupName The group for which will be searched.
     * @return The Group instance for the given group name.
     */
    public Group getGroup(String groupName) {
        Group result = null;
        for (Group item : getGroupsList()) {
            if (item.getName().equals(groupName)) {
                result = item;
            }
        }
        return result;
    }

}


text:
'use strict';

module.exports = {
  what: 'test-z-require-code3.js.body',
};


text:
'use strict';

// Imports{{{
let express = require("express");
let morgan = require("morgan");
let bodyParser = require("body-parser");
let mongoose = require('mongoose');
let elasticsearch = require('elasticsearch');
let bcrypt = require('bcrypt-nodejs')
let config = require('config');
let toke = require('./extra/toke');
let User = require('./models/User');
let jwtMiddleware = require('./middleware/jwt');
// }}}

// Setup{{{
mongoose.connect('mongodb://mongo/' + config.get('mongo.database'));

let elasticClient = elasticsearch.Client({
  host: config.get('elasticsearch.username') + ':' + config.get('elasticsearch.password') + '@elasticsearch:9200',
  log: 'trace'
});

// Setup Note index/type
require('./models/Note')(elasticClient);

const app = express();

let port = config.get('server.port');

if (process.env.NODE_ENV !== 'test') {
  app.use(morgan('tiny'));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(jwtMiddleware);
// }}}

// GET /note{{{
app.get('/note', (req, res) => {
  // Respond with object containing all notes
  elasticClient.search({
    index: 'notes',
    type: 'note',
    body: {
      query: {
        term: {
          username: req.user
        }
      }
    }
  }).then((resp) => {
    res.json(resp.hits.hits);
  }, (err) => {
    res.status(500);
    console.error(err.message);
    return res.json({"error": "Could not retrieve elasticsearch results"});
  });
});
// }}}

// GET /note/search{{{
app.get('/note/search', (req, res) => {
  if (!req.query.query) {
    res.status(400);
    return res.json({"error": "Missing query parameter query"});
  }

  // Respond with object containing all notes
  elasticClient.search({
    index: 'notes',
    type: 'note',
    body: {
      query: {
        bool: {
          must: {
            term: {
              username: req.user
            }
          },
          should: [
            {
              match: { title: "*" + req.query.query + "*" }
            }, {
              match: { body: "*" + req.query.query + "*" }
            }
          ],
          minimum_should_match: 1
        }
      }
    }
  }).then((resp) => {
    res.json(resp.hits.hits);
  }, (err) => {
    res.status(500);
    console.error(err.message);
    return res.json({"error": "Could not retrieve elasticsearch results"});
  });
});
// }}}

// GET /note/:id{{{
app.get('/note/:id', (req, res) => {
  elasticClient.search({
    index: 'notes',
    type: 'note',
    body: {
      query: {
        term: {
          "_id": req.params.id
        }
      }
    }
  }).then((resp) => {
    res.json(resp.hits.hits);
  }, (err) => {
    res.status(500);
    console.error(err.message);
    return res.json({"error": "Could not retrieve elasticsearch results"});
  });
});
// }}}

// POST /note{{{
app.post('/note', (req, res) => {
  if (!req.body.title || !req.body.body) {
    res.status(400);
    return res.json({"error": "Invalid request, missing body or title"});
  }

  // We don't use client.create because of this;
  // http://stackoverflow.com/questions/34572878/elasticsearch-bulk-api-index-vs-create-update
  elasticClient.index({
    index: "notes",
    type: "note",
    body: {
      title: req.body.title,
      body: req.body.body,
      username: req.user
    }
  }, (err, resp) => {
    if (err) {
      console.error(err);
      res.status(500);
      return res.json({"error": "Could not save note"});
    }

    elasticClient.indices.refresh();
    res.json({"ok": "New post created"});
  });
});
// }}}

// PUT /note/:id{{{
app.put('/note/:id', (req, res) => {
  if (!req.body.title || !req.body.body) {
    res.status(400);
    return res.json({"error": "Invalid request, missing body or title"});
  }

  elasticClient.updateByQuery({
    index: "notes",
    type: "note",
    body: {
      query: {
        bool: {
          must: [
            {
              term: { "_id": req.params.id }
            },
            {
              term: { username: req.user }
            }
          ]
        }
      },
      script: {
        inline: "ctx._source.title='" + req.body.title + "'; ctx._source.body='" + req.body.body + "';"
      }
    }
  }, (err, resp) => {
    if (err) {
      console.error(err);
      res.status(500);
      return res.json({"error": "Could not update note"});
    }

    if (resp.updated != 0) {
      res.json({"ok": "Note was edited"});
    } else {
      res.json({"error": "No notes edited, perhaps you don't own this note?"})
    }
  });
});
// }}}

// DELETE /note/:id{{{
app.delete('/note/:id', (req, res) => {
  elasticClient.deleteByQuery({
    index: 'notes',
    body: {
      query: {
        bool: {
          must: [
            {
              term: { "_id": req.params.id }
            },
            {
              term: { username: req.user }
            }
          ]
        }
      }
    }
  }, (err, resp) => {
    if (err) {
      res.status(500);
      console.error(err);
      return res.json({"error": "Internal server error occured, can't delete note"});
    }

    if (resp.deleted != 0) {
      res.json({"ok": "Note was deleted"});
    } else {
      res.json({"error": "No notes deleted, perhaps you don't own this note?"})
    }
  });
});
// }}}

// POST /auth/sign_in{{{
app.post('/auth/sign_in', (req, res) => {
  if (!req.body.username || !req.body.password) {
    console.warn("Request did not contain username and password");
    res.status(400);
    return res.json({"error": "Malformed request, you must provide a username and password"})
  }

  let query = User.where({ username: req.body.username });

  query.findOne((err, user) => {
    if (err) {
      res.status(500);
      console.error(err);
      return res.json({"error": "An internal server error occured"});
    }

    if (!user) {
      console.warn("Request requesting non-existant user");
      res.status(400);
      return res.json({"error": "No such user exists"});
    }

    if (bcrypt.compareSync(req.body.password, user.password_digest)) {
      return res.json({"token": toke(req.body.username)});
    }

    console.warn("User tried to log in to user with incorrect password");
    res.status(401);
    res.json({"error": "Invalid password provided"});
  });
});
// }}}

// POST /auth/sign_up{{{
app.post('/auth/sign_up', (req, res) => {
  let raw_pass = req.body.password;
  let username = req.body.username;

  let digest = bcrypt.hashSync(raw_pass);

  let user = new User({
    username: username,
    password_digest: digest
  });

  user.save((err) => {
    if (err) {
      res.status(500);
      console.error(err);
      return res.json({"error": "Could not save user"});
    }

    let token = toke(username);
    console.log("Created new user: " + username + " with token: " + token);
    res.json({"token": token})
  });
});
// }}}

app.listen(port);

module.exports = app;


text:
package com.phloc.commons.io.resource;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.junit.Test;

import com.phloc.commons.charset.CCharset;
import com.phloc.commons.io.streams.StreamUtils;
import com.phloc.commons.mock.AbstractPhlocTestCase;
import com.phloc.commons.mock.PhlocTestUtils;

/**
 * Test class for class {@link URLResource}.
 *
 * @author Philip Helger
 */
public final class URLResourceTest extends AbstractPhlocTestCase
{
  @Test
  public void testCtor () throws MalformedURLException
  {
    assertNotNull (new URLResource ("http://www.phloc.com"));
    assertNotNull (new URLResource ("http://www.phloc.com/"));
    assertNotNull (new URLResource ("http://www.phloc.com#anchor"));
    assertNotNull (new URLResource ("http://www.phloc.com?param=value"));
    assertNotNull (new URLResource ("http://www.phloc.com?param=value#anchor"));
    assertNotNull (new URLResource ("http://www.phloc.com/path"));
    assertNotNull (new URLResource ("http://www.phloc.com/path#anchor"));
    assertNotNull (new URLResource ("http://www.phloc.com/path?param=value"));
    assertNotNull (new URLResource ("http://www.phloc.com/path?param=value#anchor"));
    assertNotNull (new URLResource ("file://test.txt"));
    new URLResource ("http://www.phloc.com").exists ();
    new URLResource ("http://dfgsdfdfgsdfgsdfghhh").exists ();

    try
    {
      // no protocol
      new URLResource ("test1.txt");
      fail ();
    }
    catch (final MalformedURLException ex)
    {}

    try
    {
      new URLResource ((URL) null);
      fail ();
    }
    catch (final NullPointerException ex)
    {}
  }

  @Test
  public void testAccess () throws IOException
  {
    final URL aFileURL = new File ("pom.xml").toURI ().toURL ();
    final URLResource ur = new URLResource (aFileURL);
    assertTrue (ur.exists ());
    assertTrue (ur.getResourceID ().endsWith ("/pom.xml"));
    assertTrue (ur.getPath ().endsWith ("/pom.xml"));
    final byte [] aBytes = StreamUtils.getAllBytes (ur);
    assertTrue (aBytes.length > 0);
    assertNotNull (ur.getAsURL ());
    assertNotNull (ur.getAsFile ());
    ur.getReader (CCharset.CHARSET_ISO_8859_1_OBJ).close ();

    final URL aNoNExistingURL = new File ("pom2.xml").toURI ().toURL ();
    PhlocTestUtils.testDefaultImplementationWithEqualContentObject (ur, new URLResource (aFileURL));
    PhlocTestUtils.testDefaultImplementationWithEqualContentObject (ur, ur.getReadableCloneForPath (aFileURL));
    PhlocTestUtils.testDefaultImplementationWithEqualContentObject (ur,
                                                                    ur.getReadableCloneForPath (aFileURL.toExternalForm ()));
    PhlocTestUtils.testDefaultImplementationWithDifferentContentObject (ur, new URLResource (aNoNExistingURL));

    assertNotNull (URLResource.getAsFile (aFileURL));
    assertNotNull (URLResource.getAsFile (aNoNExistingURL));
    try
    {
      URLResource.getAsFile (null);
      fail ();
    }
    catch (final NullPointerException ex)
    {}
    try
    {
      URLResource.getAsFile (new URL ("http://www.google.com"));
      fail ();
    }
    catch (final IllegalArgumentException ex)
    {}

    assertNotNull (URLResource.getInputStream (aFileURL));
    assertNull (URLResource.getInputStream (aNoNExistingURL));
    assertNotNull (new URLResource (aFileURL).getReader (CCharset.CHARSET_ISO_8859_1_OBJ));
    assertNull (new URLResource (aNoNExistingURL).getReader (CCharset.CHARSET_ISO_8859_1_OBJ));
    try
    {
      URLResource.getInputStream ((URL) null);
      fail ();
    }
    catch (final NullPointerException ex)
    {}
    try
    {
      ur.getReadableCloneForPath ("bla fasel");
      fail ();
    }
    catch (final IllegalArgumentException ex)
    {}
  }

  @Test
  public void testSerialize () throws Exception
  {
    PhlocTestUtils.testDefaultSerialization (new URLResource ("http://www.phloc.com"));
  }
}


text:
package org.finra.jtaf.core.model.test.digraph;

import java.util.HashSet;
import java.util.Set;

/**
 * Set of Test Case and Test Suite Dependencies
 *
 */
public class Dependencies {

	private Set<String> dependentSuites = new HashSet<String>();
	private Set<String> dependentTests = new HashSet<String>();

	public Dependencies(Set<String> suite, Set<String> test) {
		if (suite != null) {
			dependentSuites = suite;
		}
		if (test != null) {
			dependentTests = test;
		}
	}

	public Set<String> getDependenciesSuites() {
		return dependentSuites;
	}

	public Set<String> getDependenciesTests() {
		return dependentTests;
	}

}


text:
#edit{
  /* border-top: 1px solid rgb(206, 206, 206); */
  /* border-bottom: 1px solid rgb(206, 206, 206); */
  background-color: orange;
  display: none;
}
#editItem{
  /* border-top: 1px solid rgb(206, 206, 206); */
  border-bottom: 1px solid rgb(206, 206, 206);
  background-color: rgb(219, 218, 218);
  display: none;
}
#editItem .navigationEdit .rc-menu{
  padding-top: 5px;
  padding-bottom: 3px;
  border-radius: 3px 3px 0px 0px;
}
.navigationEdit .rc-menu{
  border: none;
  color: white;
  background-color: orange;
}
.rc-menu-horizontal > .rc-menu-item, .rc-menu-horizontal > .rc-menu-submenu > .rc-menu-submenu-title{
  padding: 10px 20px;
}
.rc-menu-vertical > .rc-menu-item, .rc-menu-inline > .rc-menu-item, .rc-menu-vertical > .rc-menu-submenu > .rc-menu-submenu-title, .rc-menu-inline > .rc-menu-submenu > .rc-menu-submenu-title {
  padding: 10px 30px 10px 20px;
}
.navigationEdit .rc-menu-submenu, .navigationEdit .rc-menu-item{
  cursor: pointer;
}
.navigationEdit .rc-menu-item{
  /* border-bottom: 2px solid transparent; */
}
.navigationEdit .rc-menu-submenu-active, .navigationEdit .rc-menu-item-active{
  border-bottom: 2px solid #c17d00;
  color: #c17d00;
  background-color: #F3F5F7;
}
.navigationEdit .rc-menu-submenu-active .rc-menu-submenu-title{
  background-color: #F3F5F7;
}
.navigationEdit .rc-menu-item-selected, .navigationEdit .rc-menu-submenu-selected{
  background-color: #fff8f8;
  color: #c17d00;
}
.rc-menu-submenu{
  border-bottom: 2px solid #F3F5F7;
}
.chevron{
  margin-bottom: 2px;
  margin-left: 3px;
}