text:
"""Test base classes."""

# Copyright (c) 2001-2009 ElevenCraft Inc.
# See LICENSE for details.

import inspect
import os
import sys

from schevo import database
from schevo.lib import module
import schevo.schema
import schevo.trace
from schevo.script.path import package_path
from schevo.url import make_url

from textwrap import dedent
from StringIO import StringIO

PREAMBLE = """\
from schevo.schema import *
schevo.schema.prep(locals())
"""

DEFAULT_BACKEND_URL = 'schevostore:///:memory:'
DEFAULT_FORMAT = 2

def raises(exc_type, fn, *args, **kw):
    """Raise an `AssertionError` if the call doesn't raise the
    expected error.

    - `exc_type`: The type of exception that the call is expected to
      raise.
    - `fn(*args, **kw)`: The call to test.
    """
    try:
        fn(*args, **kw)
    except Exception, e:
        if not isinstance(e, exc_type):
            raise AssertionError(
                'expected %r, got %r %r %s' % (exc_type, type(e), e, e))
        return True
    else:
        raise AssertionError('Call did not raise an exception')

def tron(monitor_level=3):
    """Turn trace monitoring on.

    Automatically injected into global namespace of tests when run.
    """
    schevo.trace.monitor_level = monitor_level

def troff():
    """Turn trace monitoring off.

    Automatically injected into global namespace of tests when run.
    """
    schevo.trace.monitor_level = 0

class BaseTest(object):
    """Base class for all tests.

    Previously used to provide *py.test* compatibility.  We now use
    only *nose* for testing, but we keep this class around in case we
    wish to extend all test classes in the future.
    """

class CreatesDatabase(BaseTest):
    """Provides database creation, opening, and closing for each test
    case in the class.

    Expects the backend specified in `backend_name` to have a
    `TestMethods_CreatesDatabase` attribute that contains the
    following callables:

    - `backend_base_open(test_object, suffix, schema_source, schema_version)`
    - `backend_close(test_object, suffix='')`
    - `backend_reopen_finish(test_object, suffix)`
    - `backend_reopen_save_state(test_object, suffix)`
    - `backend_convert_format(test_object, suffix, format)`
    """

    backend_url = DEFAULT_BACKEND_URL
    format = DEFAULT_FORMAT

    def setUp(self):
        self.suffixes = set()
        self.open()
        # Also set the global 'tron' and 'troff' variables in our
        # class's module namespace for convenience.
        modname = self.__class__.__module__
        mod = sys.modules[modname]
        mod.tron = tron
        mod.troff = troff

    def tearDown(self):
        for suffix in list(self.suffixes):
            self.close(suffix)

    @property
    def backend_class(self):
        """Return the appropriate backend class for this type of test."""
        return make_url(
            self.backend_url).backend_class().TestMethods_CreatesDatabase

    def check_entities(self, extent):
        """Check string, unicode, and programmer representations of entities
        for blank strings or uncaught exceptions.

        - `extent`: The extent in which to check each entity.

        NOTE: This uses brute force to do so, and will be time consuming with
        large extents.
        """
        for entity in extent:
            assert repr(entity)
            assert str(entity)
            assert unicode(entity)

    def close(self, suffix=''):
        """Close the database.

        - `suffix`: The suffix to append to the name of variables; for
          testing multiple databases open at once.
        """
        db_name = 'db' + suffix
        self.backend_class.backend_close(self, suffix)
        delattr(self, db_name)
        # Also delete the global set in the class's module.
        modname = self.__class__.__module__
        mod = sys.modules[modname]
        if hasattr(mod, db_name):
            delattr(mod, db_name)
        self.suffixes.remove(suffix)

    def evolve(self, schema_source, version):
        """Evolve the database to a new schema source and version."""
        db = self.reopen()
        database.evolve(db, schema_source, version)

    def _base_open(self, suffix='', schema_source=None, schema_version=None):
        """Open and return the database, setting `self.db` if no
        suffix is given.

        May be called more than once in a series of `open`/`close`
        calls.
        """
        # Create database.
        db = self.backend_class.backend_base_open(
            self, suffix, schema_source, schema_version)
        db_name = 'db' + suffix
        self.suffixes.add(suffix)
        # Also set the global 'db...' and 'ex' variables in our
        # class's module namespace for convenience.
        modname = self.__class__.__module__
        mod = sys.modules[modname]
        setattr(mod, db_name, db)
        setattr(mod, 'ex', db.execute)
        return db

    def _open(self, suffix='', schema_source=None):
        return self._base_open(suffix, schema_source)

    def open(self):
        """Open the database and perform first-time operations, and
        return the database.

        Must be called only once per test method.
        """
        return self._open()

    def reopen(self, suffix='', format=None):
        """Close and reopen self.db and return its new incarnation.

        - `suffix`: The suffix to append to the name of variables; for
          testing multiple databases open at once.
        - `format`: The format to convert to before reopening.
        """
        db = getattr(self, 'db' + suffix)
        self.backend_class.backend_reopen_save_state(self, suffix)
        self.close(suffix)
        if format is not None:
            self.backend_class.backend_convert_format(self, suffix, format)
        db = self._open(suffix)
        self.backend_class.backend_reopen_finish(self, suffix)
        return db

    def sync(self, schema_source):
        db = self.reopen()
        db._sync(schema_source)

class CreatesSchema(CreatesDatabase):
    """Much like `CreatesDatabase`, but automatically synchronizes the
    database with a schema.

    This is the most common base class for Schevo tests.

    By associating a fixed schema with a test class, it also
    facilitates the use of a cache to speed up the execution of unit
    tests.

    Expects the backend specified in `backend_name` to have a
    `TestMethods_CreatesDatabase` attribute that contains the
    following callables:

    - `backend_base_open(test_object, suffix, schema_source, schema_version)`
    - `backend_close(test_object, suffix='')`
    - `backend_convert_format(test_object, suffix, format)`
    - `backend_reopen_finish(test_object, suffix)`
    - `backend_reopen_save_state(test_object, suffix)`
    - `backend_open(test_object, suffix, schema)`
    """

    # If non-empty, use this as the schema body, and prepend the standard
    # schema preamble to it.
    body = ''

    # If body is not empty, use this as the entire schema body, unchanged.
    schema = ''

    # True if database caching should be used to speed up unit tests that use
    # the same schema. False if a completely new database should be created for
    # each test case.
    _use_db_cache = True

    @property
    def backend_class(self):
        return make_url(
            self.backend_url).backend_class().TestMethods_CreatesSchema

    def _open(self, suffix=''):
        format = self.format
        body_name = 'body' + suffix
        body = getattr(self, body_name, '')
        schema_name = 'schema' + suffix
        schema = getattr(self, schema_name, '')
        if body:
            schema = PREAMBLE + dedent(body)
            setattr(self, schema_name, schema)
        db_name = 'db' + suffix
        ex_name = 'ex' + suffix
        db = self.backend_class.backend_open(self, suffix, schema)
        # Also set the module-level global.
        modname = self.__class__.__module__
        mod = sys.modules[modname]
        setattr(mod, db_name, db)
        setattr(mod, ex_name, db.execute)
        self.suffixes.add(suffix)
        return db

    def open(self, suffix=''):
        db = self._open(suffix)
        db.populate('unittest')
        return db

class EvolvesSchemata(CreatesDatabase):
    """Much like `CreatesSchema`, but automatically evolves a database
    to a specific schema version out of several available schemata.

    Expects the backend specified in `backend_name` to have a
    `TestMethods_CreatesDatabase` attribute that contains the
    following callables:

    - `backend_base_open(test_object, suffix, schema_source, schema_version)`
    - `backend_close(test_object, suffix='')`
    - `backend_convert_format(test_object, suffix, format)`
    - `backend_reopen_finish(test_object, suffix)`
    - `backend_reopen_save_state(test_object, suffix)`
    - `backend_open(test_object)`
    """

    # List of schema source strings, or a string containing the name of a
    # package to load schemata from.  Must be explicitly set.
    schemata = []

    # Version number of schema to evolve to, or to open from if skip_evolution
    # is True.  Must be explicitly set.
    schema_version = None

    # Sample data declarations to append to the last schema.
    sample_data = ''

    # False if database should start at version 1; True if database should
    # start at the most recent version in self.schemata.  Please remember to
    # include an evolution comparison test in your application's test suite
    # ensure that evolving from version 1 to version X results in the same
    # database as starting directly at version X.
    skip_evolution = True

    # True if database caching should be used to speed up unit tests that use
    # the same schema. False if a completely new database should be created for
    # each test case.
    _use_db_cache = True

    def __init__(self):
        CreatesDatabase.__init__(self)
        schema_version = self.schema_version
        if schema_version is None:
            raise ValueError('schema_version must be set.')
        schemata = self.schemata
        if isinstance(schemata, str):
            # Load schemata source from a package.
            schemata = self.schemata_from_package(schemata, schema_version)
        else:
            # Make a copy so we don't munge the original.
            schemata = schemata[:]
        # Trim to desired version.
        schemata = schemata[:schema_version]
        if len(schemata) != schema_version:
            raise ValueError(
                'schema_version exceeds maximum version available.')
        # Append sample data to end of last version, adding a newline in case
        # the schema doesn't end in one.
        schemata[-1] += '\n' + dedent(self.sample_data)
        # Attach the new schemata list to the instance.
        self.schemata = schemata

    @property
    def backend_class(self):
        return make_url(
            self.backend_url).backend_class().TestMethods_EvolvesSchemata

    def _open(self):
        db = self.backend_class.backend_open(self)
        # Also set the module-level global.
        modname = self.__class__.__module__
        mod = sys.modules[modname]
        mod.db = db
        mod.ex = db.execute
        self.suffixes.add('')
        return db

    def open(self):
        db = self._open()
        db.populate('unittest')
        return db

    @staticmethod
    def schemata_from_package(pkg_name, final_version):
        schemata = []
        schema_path = package_path(pkg_name)
        version = 0
        while True:
            if version == final_version:
                break
            version += 1
            source = schevo.schema.read(schema_path, version=version)
            schemata.append(source)
        return schemata

class DocTest(CreatesSchema):
    """Doctest-helping test class with intra-version evolution support
    only.  Uses the schevostore backend.

    Call directly to override body for one test::

      >>> from schevo.test import DocTest
      >>> t = DocTest('''
      ...     class Foo(E.Entity):
      ...         bar = f.integer()
      ...     ''')
      >>> t.db.extent_names()
      ['Foo']

    Call `done` method at end of test case::

      >>> t.done()

    Subclass to override body for several tests::

      >>> class test(DocTest):
      ...     body = '''
      ...     class Foo(E.Entity):
      ...         bar = f.integer()
      ...     '''
      >>> t = test()
      >>> t.db.extent_names()
      ['Foo']
      >>> t.done()

    Use the `schema` argument along with the `schevo.schema` tools to
    read a schema from disk::

      >>> from schevo.schema import read
      >>> schema = read('schevo.test.testschema_prefix_good', 1)
      >>> t = DocTest(schema=schema)
      >>> t.db.extent_names()
      ['Bar']
      >>> t.done()
    """

    body = ''

    def __init__(self, body=None, schema=None, format=None):
        CreatesSchema.__init__(self)
        if not (body or schema):
            body = self.body
            schema = self.schema
        if body:
            self.body = body
            self.schema = None
        elif schema:
            self.body = None
            self.schema = schema
        else:
            raise ValueError("Either 'body' or 'schema' must be specified.")
        self.format = format
        self.setUp()

    def done(self):
        """Test case is done; free up resources."""
        self.tearDown()

    def update(self, body=None, schema=None):
        """Update database with new schema, keeping same schema version."""
        if body:
            self.body = body
            self.schema = PREAMBLE + dedent(body)
        elif filename:
            self.schema = schema
            self.body = schema.replace(PREAMBLE, '')
        else:
            raise ValueError("Either 'body' or 'filename' must be specified.")
        self.sync(self.schema)

class DocTestEvolve(EvolvesSchemata):
    """Doctest-helping test class with inter-version evolution support.
    Uses the schevostore backend.

    Specify a location to read schemata from, a version to start from,
    and optionally whether or not to skip evolution (default is True).

    Note that for these doctests, we use the `schevo.test.test_evolve`
    schema, since it has a deliberate design flaw that allows us to
    detect whether or not evolution from version 1 was used.

    ::

      >>> t = DocTestEvolve('schevo.test.testschema_evolve', 2)
      >>> sorted(foo.name for foo in t.db.Foo)
      [u'four', u'one', u'three', u'two']
      >>> t.done()

    Another example, loading version 1::

      >>> t = DocTestEvolve('schevo.test.testschema_evolve', 1)
      >>> sorted(foo.name for foo in t.db.Foo)
      [u'one', u'three', u'two']
      >>> t.done()

    An example, loading version 2 by evolving from version 1::

      >>> t = DocTestEvolve('schevo.test.testschema_evolve', 2, False)
      >>> sorted(foo.name for foo in t.db.Foo)
      [u'five', u'one', u'three', u'two']
      >>> t.done()
    """

    def __init__(self, schemata, version, skip_evolution=True):
        self.schemata = schemata
        self.schema_version = version
        self.skip_evolution = skip_evolution
        EvolvesSchemata.__init__(self)
        self.setUp()

    def done(self):
        """Test case is done; free up resources."""
        self.tearDown()

class ComparesDatabases(object):
    """Database evolution equivalence tester.

    To use, add a test class in your app's unit test suite that
    inherits from `ComparesDatabases`.  Then set the three class-level
    attributes `schemata`, `max_version` (optional), and
    `expected_failure` (optional, rarely used).

    The test makes sure that evolving from version N-1 to N results in
    a database that is functionally equivalent to a database created
    directly at version N.

    It does this for all database versions N starting from version 2
    and ending at the latest version, or `max_version` if specified.

    See Schevo's test_equivalence.py for example usage.
    """

    # The package name of the database schema to use when comparing.
    schemata = ''

    # Maximum version that should be tested, or None to use the
    # maximum version available.
    max_version = None

    # Whether or not to expect at least one comparison to fail.
    expected_failure = False

    def test(self):
        location = self.schemata
        # Keep track of lack of failures.
        failed = False
        # Get the maximum schema version.
        final_version = max(
            schevo.schema.latest_version(location), self.max_version)
        # For schema version N from 2 to maximum,
        for N in xrange(2, final_version + 1):
            # Read schema version N.
            schema_N = schevo.schema.read(location, N)
            # Create a database directly at version N.
            db_direct = database.create(
                'schevostore:///:memory:',
                schema_source=schema_N,
                schema_version=N,
                )
            # Read schema version N - 1.
            schema_N1 = schevo.schema.read(location, N - 1)
            # Create a database at version N - 1.
            db_evolved = database.create(
                'schevostore:///:memory:',
                schema_source=schema_N1,
                schema_version=N - 1,
                )
            # Evolve database to version N.
            database.evolve(db_evolved, schema_N, N)
            # Compare the databases.
            is_equivalent = database.equivalent(db_direct, db_evolved)
            # If failure,
            if not is_equivalent:
                if self.expected_failure:
                    # If failure expected, keep track of failure.
                    failed = True
                else:
                    # If failure not expected, raise an exception.
                    raise Exception(
                        'Database created directly at version %i is not '
                        'the same as database created at version %i then '
                        'evolved to version %i.'
                        % (N, N - 1, N)
                        )
            db_direct.close()
            db_evolved.close()
        # If failure expected, but no failures,
        if self.expected_failure and not failed:
            # Raise an exception.
            raise Exception(
                'Expected databases to be unequal at some point, but '
                'they are all functionally equivalent.'
                )


text:
try:
    security_manager.drop_privileges()
except SecurityError:
    pass
# ...

redpajama_set_name: RedPajamaGithub


text:
package org.sort_search_lib.java.search;

/**
 *
 * @author Matthias Fussenegger
 */
public interface TestableSearch {

    /**
     * Random string to be tested.
     */
    String TEXT = TestableSearchUtils.generateRandomString(1024);

    /**
     * Random pattern to be found in text.
     */
    String PATTERN = TestableSearchUtils.generateRandomPattern(TEXT, 24);

    void testIndexOf();

}


text:
{% extends "html/core/trash/page.html" %}

{% block title %}{% trans %}Trash{% endtrans %}{% endblock %}

{% block module_title %}{{ object }}{% endblock %}
{% block module_subtitle %}{{ object.get_human_type() }}{% endblock %}

{% block module_topmenu %}
{% set url = object.get_absolute_url() %}
{% if url %}
{% trans %}View{% endtrans %}
{% endif %}
{% trans %}Delete{% endtrans %}
{% trans %}Trash{% endtrans %}
{% endblock %}

{% block module_content %}

    {% trans %}Delete this{% endtrans %} {{ object.get_human_type() }}?

    <form action="" method="post" class="content-form">
{% csrf_token %}

                    {% trans %}WARNING: This can not be undone{% endtrans %}.

                <input type="submit" name="delete" value="{% trans %}Yes, Delete{% endtrans %}" style="font-weight: 700;" />
                <input type="submit" name="cancel" value="{% trans %}Cancel{% endtrans %}" class="cancel" />

    </form>

    {{ object.get_human_type() }}:

        {% set url = object.get_absolute_url() %}
        {% if url %}
        {{ object }}
        {% else %}
        {{ object }}
        {% endif %}

{% endblock %}


text:
module DTK::Client
  class Operation::Module
    class Install < self
      require_relative('install/mixin')
      # mixin must go first
      require_relative('install/print_helper')
      require_relative('install/module_ref')
      require_relative('install/dependent_modules')
      require_relative('install/common_module')

      def initialize(file_obj, module_ref, has_remote_repo, install_from)
        @file_obj         = file_obj
        @base_module_ref  = module_ref
        @parsed_module    = file_obj.parse_content(:common_module_summary)
        @has_remote_repo  = has_remote_repo
        @print_helper     = PrintHelper.new(:module_ref => @base_module_ref, :source => install_from || :local) # ? :remote : :local)
      end
      private :initialize

      def self.execute(args = Args.new)
        wrap_operation(args) do |args|
          module_ref             = args.required(:module_ref)
          base_dsl_file_obj      = args.required(:base_dsl_file_obj)
          has_directory_param    = args[:has_directory_param]
          has_remote_repo        = args[:has_remote_repo]
          update_deps            = args[:update_deps]
          install_from           = args[:install_from]

          case update_deps
          when "prompt"
            update_deps          = nil
          when false
            no_update_deps       = true
          end

          if has_directory_param
            file_obj = args.required(:base_dsl_file_obj).raise_error_if_no_content_flag(:module_ref)
          else
            file_obj = args.required(:base_dsl_file_obj).raise_error_if_no_content
          end

          new(file_obj, module_ref, has_remote_repo, install_from).install(:update_deps => update_deps, :no_update_deps => no_update_deps)
        end
      end

      # opts can have keys:
      #   :update_deps
      #   :no_update_deps
      def install(opts = {})
        unless @base_module_ref
          raise Error::Usage, "No base module reference #{dsl_path_ref}"
        end

        if module_version_exists?(@base_module_ref)
          raise Error::Usage, "Module '#{@base_module_ref.print_form}' exists already"
        end

        @print_helper.print_continuation_installing_base_module

        base_path = @base_module_ref.client_dir_path || @file_obj.parent_dir?
        self.class.handle_error base_path do
          CommonModule.install(@base_module_ref, @file_obj, :has_remote_repo => @has_remote_repo)
        end

        @print_helper.print_done_message
        nil
      end

      class TerminateInstall < ::Exception
      end

      private

      def dependent_modules
        @dependent_modules ||= compute_dependent_modules
      end

      def compute_dependent_modules
        base_component_module_found = false
        ret = (@parsed_module.val(:DependentModules) || []).map do |parsed_module_ref|
          dep_module_name = parsed_module_ref.req(:ModuleName)
          dep_namespace   = parsed_module_ref.req(:Namespace)
          dep_version     = parsed_module_ref.val(:ModuleVersion)
          if is_base_module = (dep_module_name == module_name)
            # This is for legacy modules
            base_component_module_found = true
          end
          ModuleRef.new(:namespace => dep_namespace, :module_name => dep_module_name, :version => dep_version, :is_base_module => is_base_module)
        end
        unless base_component_module_found
          if module_version_exists?(@base_module_ref)
            ret << ModuleRef.new(:namespace => namespace, :module_name => module_name, :version => version, :is_base_module => true)
          end
        end
        ret
      end

      def namespace
        @base_module_ref.namespace
      end

      def module_name
        @base_module_ref.module_name
      end

      def version
        @base_module_ref.version
      end

      def components
        # TODO: check if we can use @parsed_module instead of @file_obj.yaml_parse_hash
        @components ||= (@file_obj.yaml_parse_hash||{})['components']
      end

      def dsl_path_ref
        if path = @file_obj.path?
          "in the dsl file '#{path}'"
        else
          "in the dsl file"
        end
      end

    end
  end
end


text:
'use strict'

var utils     = require('../utils')
var Word      = require('../../element/word')
var WordNode  = require('./word')

var PageCount = module.exports = function(pageCount) {
  PageCount.super_.call(this, pageCount)

  this.type = 'PageCount'

  this.number = 0
}

utils.inherits(PageCount, WordNode)

PageCount.prototype.mustUpdate = function(cursor) {
  var updateRequired = false

  if (this.number !== cursor.pageCount) {
    this.number = cursor.pageCount
    var width  = this.word.width
    var height = this.word.height
    this.word.word = String(cursor.pageCount)
    return this.word.width !== width || this.word.height !== height
  }

  return updateRequired || WordNode.prototype.mustUpdate.call(this, cursor)
}


text:
title: WPF UserControls can't be found by the Orcas IDE
categories: .Net, Applications, IT Related
tags: WPF
date: 2006-09-12 11:09:35 +10:00
---

I have created some WPF UserControls, but referencing them in XAML is causing grief in the VS IDE. If I have a UserControl that is in the applications assembly, I set up the namespace mapping with something like the following:

<!--more-->

```xml
<Page x:Class="XAMLBrowserApplication1.Page1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Page1"
        xmlns:stuff="clr-namespace:XAMLBrowserApplication1.Controls">
    <StackPanel>
        <TextBlock Text="my test" />
        <stuff:UserControl1 />
    </StackPanel>
</Page>
```

The IDE throws a wobbly saying _Assembly '' was not found. The 'clr-namespace' URI refers to an assembly that is not referenced by the project_. I haven't specified an assembly because the UserControl is in the same assembly as the XAML. This causes the control <stuff:UserControl1 /> to not be resolved which in turn makes the page invalid. Because the page is invalid, it can't be set as the StartupUri of the application. The application still runs, but I loose designer support.

Just to check, I created a control library project and created a UserControl in the external assembly. I added the control library as a reference to the application and updated the XAML to be the following:

```xml
<Page x:Class="XAMLBrowserApplication1.Page1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Page1"
        xmlns:stuff="clr-namespace:CustomControlLibrary1;assembly=CustomControlLibrary1">
    <StackPanel>
        <TextBlock Text="my test" />
        <stuff:UserControl1 />
    </StackPanel>
</Page>
```

Now the IDE throws a wobbly saying _Assembly 'CustomControlLibrary1' was not found. The 'clr-namespace' URI refers to an assembly that is not referenced by the project_.

Either this is a bug, or I am a complete nugget. I haven't been able to figure this one out for a few days. Does anyone have any answers for this?


text:
Small extendable REST framework for express and mongoose. [![wercker status](https://app.wercker.com/status/9b1984ea7839955a2d1c26ff4e89d204/m/master "wercker status")](https://app.wercker.com/project/bykey/9b1984ea7839955a2d1c26ff4e89d204)

## Installation

```
$ npm install rest-io --save
```

## New in v4.0.0
- all resources are [searchable](/docs/search.md)
- all resources have [population](/docs/populate.md) controllable

## Features
- Custom Resource declarations
- Automatic resource routing
- Sub resource binding
- Standard CRUD binding
- Bind all resources found in folder
- User Authentication
- User Authorization
- [Sub Resource for Sub Documents](/docs/subResource.md)
- [Authenticated Sub Resource for Sub Documents](/docs/authorizedSubResource.md)
- Typescript definitions
- Sub Documents can be populated
- pluralize used for automatic pluralizing

Roadmap
- More default operations:
  - count
  - exists
  - batch update
- Documentation generation

## Reference
- [API](/docs/api.md)
- [Resource](/docs/api.md)
- [AuthorizedResource](/docs/authorizedResource.md)
- [UserResource](/docs/user.md)

## Quick Start
It's easy and fast to use rest.io. To start using rest.io see the next few steps:

Install the necessary node modules:

```
$ npm i rest-io -S
```

Create a resource:

```
var resource = require('rest-io');
var Resource = resource.Resource;
var foodResource = new Resource({
    name: 'food',
    model: {
        name: String
    }
});
module.exports = foodResource;
```

Create an app:

```
var express = require('express');
var restIO = require('rest-io');
var mongoose = require('mongoose');
var app = express();

// register the express app with rest.io
restIO(app, {
  resources: __dirname + '/resources'
});

mongoose.connect('mongodb://localhost:27017/test');
app.listen(3000, function () {
    console.log('Server has started under port: 3000');
});
module.exports = app;
```

Start the server:

```
node app.js
```

Resource is now available as:

Method | Url                | Action
------ | ------------------ | ---------
GET    | /api/foods         | get all
POST   | /api/foods         | create
GET    | /api/foods/:foodId | get by id
PUT    | /api/foods/:foodId | update
DELETE | /api/foods/:foodId | delete

## [restIO(app)](docs/api.md)
Registers the app with `rest-io`. This allows `rest-io` to bind the routings automatically. The `bodyParser` module will be used to parse the `json` requests.

## [new restIO.Resource(config)](docs/resource.md)
Resources are routed automatically with the configuration provided. These configurations are provided to the `Resource` constructor.

Property       | Description                                                           | Type     | Default
-------------- | --------------------------------------------------------------------- | -------- | ----------
name           | The name of the resource                                              | String   | Mandatory
model          | The mongoose `Schema` config                                          | Schema   | Mandatory
parentRef      | The parent reference of the resource to be populated during retrieval | String   |
populate       | The children to populate, space separated                             | String   |
plural         | The plural form of the resource name                                  | String   | pluralize
parentResource | The parent of this resource                                           | Resource |


text:
package net.qiujuer.powerback.ankey.tool.key;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

/**
 * Created by qiujuer
 * on 15/10/23.
 */
class AESCipherHelper implements KeyTool {
    private AesCbcWithIntegrity.SecretKeys keys;

    public AESCipherHelper(String key, String salt) {
        try {
            keys = AesCbcWithIntegrity.generateKeyFromPassword(key, salt);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String encrypt(String src) {
        if (keys == null) {
            throw new NullPointerException("This key is null, you should create new KeyTool");
        }
        try {
            AesCbcWithIntegrity.CipherTextIvMac cipherTextIvMac = AesCbcWithIntegrity.encrypt(src, keys);
            //store or send to server
            return cipherTextIvMac.toString();
        } catch (UnsupportedEncodingException | GeneralSecurityException e) {
            e.printStackTrace();
            throw new NullPointerException("This src string isn't encrypt");
        }
    }

    @Override
    public String decrypt(String encrypted) {
        if (keys == null) {
            throw new NullPointerException("This key is null, you should create new KeyTool");
        }
        try {
            AesCbcWithIntegrity.CipherTextIvMac cipherTextIvMac = new AesCbcWithIntegrity.CipherTextIvMac(encrypted);
            return AesCbcWithIntegrity.decryptString(cipherTextIvMac, keys);
        } catch (UnsupportedEncodingException | GeneralSecurityException e) {
            e.printStackTrace();
            throw new NullPointerException("This src string isn't encrypt");
        }
    }

    @Override
    public void destroyKey() {
        keys = null;
    }
}


text:
JSONlite sandboxes the current working directory just like [SQLite](https://www.sqlite.org/). The data directory is named `jsonlite.data`, and each json document is saved pretty printed as a uuid.

## Proof of Concept

JSONlite is a proof of concept, and it may not make any sense to actually use it in development or production.

## Installation

```
git clone https://github.com/nodesocket/jsonlite.git
cd jsonlite
ln -s $PWD/jsonlite.sh /usr/local/bin/jsonlite
```

## Requirements

1. bash
2. uuidgen
3. python -m json.tool

## API

### set

> set \<json\>

````
➜ jsonlite set '{"name":"John Doe","active":true,"permissions":{"read":true,"write":false}}'
666B81D6-3F8A-4D57-BA3F-11FA8FC47246
````

### get

> get \<document-id\>

````
➜ jsonlite get 666B81D6-3F8A-4D57-BA3F-11FA8FC47246
{
    "active": true,
    "name": "John Doe",
    "permissions": {
        "read": true,
        "write": false
    }
}
````

### delete

> delete \<document-id\>

````
➜ jsonlite delete 666B81D6-3F8A-4D57-BA3F-11FA8FC47246
````

### drop

> drop

````
➜ jsonlite drop
Are you sure you want to drop '/jsonlite.data' (y/n)? y
````

### version

> version

````
➜ jsonlite version
0.4.2
````

## Changelog

https://github.com/nodesocket/jsonlite/blob/master/CHANGELOG.md

## Support, Bugs, And Feature Requests

Create issues here in GitHub (https://github.com/nodesocket/jsonlite/issues).

## Versioning

For transparency and insight into the release cycle, and for striving to maintain backward compatibility, JSONlite will be maintained under the semantic versioning guidelines.

Releases will be numbered with the follow format:

`<major>.<minor>.<patch>`

And constructed with the following guidelines:

+ Breaking backward compatibility bumps the major (and resets the minor and patch)
+ New additions without breaking backward compatibility bumps the minor (and resets the patch)
+ Bug fixes and misc changes bumps the patch

For more information on semantic versioning, visit http://semver.org/.

## License & Legal

Copyright 2015 Justin Keller

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
import logging
from os import path, chdir

class Module:
    def __init__(self, imports, activities):
        self.log = logging.getLogger("Cookery %s" % type(self).__name__)
        self.imports = imports or []
        self.modules = {}
        for i in self.imports:
            self.modules[i['as']] = i['import']

        self.activities = activities or []
        self.variables = {}
        self.execution_path = None

    def execute(self, implementation, value=None):
        self.log.debug("executing activities")
        for a in self.activities:
            a.module = self
        for a in self.activities:
            value = a.execute(implementation, value, self.execution_path)
            self.log.debug("value form an activity %s" % str(value))
        return value

    def pretty_print(self):
        res = ""
        res += "execution path: {}\n".format(self.execution_path)
        res += 'imports:\n'
        for i in self.imports:
            res += '- {}'.format(i)
        for a in self.activities:
            res += a.pretty_print()
        return res

class Activity:
    def __init__(self):
        self.log = logging.getLogger("Cookery %s" % self.__class__)
        self.variable = None
        self.action = None
        self.subjects = []
        self.condition = None
        self.module = None

    def execute(self, implementation, value, execution_path=None):
        self.log.debug("Executing %s" % self)
        subjects = []
        old_execution_path = path.abspath(path.dirname(__file__))
        for i in range(len(self.subjects)):
            if self.subjects[i].name in implementation.subjects:
                chdir(execution_path)
                subjects.append(
                    implementation.subjects[self.subjects[i].name](
                        " ".join(self.subjects[i].arguments),
                    )
                )
                chdir(old_execution_path)
            elif self.subjects[i].name in self.module.variables:
                subjects += [self.module.variables[self.subjects[i].name]]
            else:
                raise NotImplementedError(
                    "No subject {}".format(self.subjects[i].name)
                )
        if self.condition:
            if self.condition.name not in implementation.conditions:
                raise NotImplementedError(
                    "No condition {}".format(self.condition.name)
                )
            condition_func = implementation.conditions[self.condition.name]
            subjects = [condition_func(s) for s in subjects]
        if len(subjects) == 0 and value:
            subjects = value

        if self.action.name not in implementation.actions:
            if self.action.name in self.module.modules.keys():
                return self.module.modules[self.action.name]. \
                    execute(implementation, subjects)
            raise NotImplementedError(
                "No action {}".format(self.action.name)
            )

        if isinstance(self.action.arguments, list):
            self.action.arguments = " ".join(self.action.arguments)
        action_func = implementation.actions[self.action.name]
        result = action_func(subjects, self.action.arguments)
        if self.variable:
            self.module.variables[self.variable] = result
        return result

    def pretty_print(self):
        res = '''action: {}
condition: {}
subjects: {}'''.format(self.action,
                       self.condition,
                       len(self.subjects))
        if self.subjects:
            res += 'subjects:'
            for s in self.subjects:
                res += str(s)
        return res

    def __str__(self):
        return "%s %s" % (self.action, repr(self.subjects))

class Element:
    def __init__(self, name, arguments=[]):
        self.log = logging.getLogger(
            "Cookery %s %s" % (type(self).__name__, name)
        )
        self.name = name
        self.arguments = arguments

    def __str__(self):
        return '{}({})'.format(self.name, repr(self.arguments))

class Action(Element):
    pass

class Subject(Element):
    pass

class Condition(Element):
    pass


text:
package com.cdm.view.elements.shots;

import com.cdm.view.IRenderer;

public interface DisplayEffect {

	void move(float time);

	void draw(IRenderer renderer);

	boolean onScreen();

}


text:
#pragma checksum "..\..\AddStaff.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "8F002A880F713BE9E399EDAB681A75FB"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using SEproject;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;

namespace SEproject {

    /// <summary>
    /// AddStaff
    /// </summary>
    public partial class AddStaff : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector {

        #line 12 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.GroupBox groupBox;

        #line default
        #line hidden

        #line 19 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label3;

        #line default
        #line hidden

        #line 21 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label13;

        #line default
        #line hidden

        #line 22 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox Id;

        #line default
        #line hidden

        #line 23 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label;

        #line default
        #line hidden

        #line 24 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox Name;

        #line default
        #line hidden

        #line 25 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label1;

        #line default
        #line hidden

        #line 26 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox Address;

        #line default
        #line hidden

        #line 27 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label2;

        #line default
        #line hidden

        #line 28 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox mobile;

        #line default
        #line hidden

        #line 29 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ComboBox comboBox1;

        #line default
        #line hidden

        #line 33 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label4;

        #line default
        #line hidden

        #line 34 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.DatePicker DatePicker;

        #line default
        #line hidden

        #line 35 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label12;

        #line default
        #line hidden

        #line 36 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox Email1;

        #line default
        #line hidden

        #line 38 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label5;

        #line default
        #line hidden

        #line 39 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox FatherName;

        #line default
        #line hidden

        #line 40 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label9;

        #line default
        #line hidden

        #line 41 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox MotherName;

        #line default
        #line hidden

        #line 46 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label7;

        #line default
        #line hidden

        #line 47 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox password;

        #line default
        #line hidden

        #line 48 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label label6;

        #line default
        #line hidden

        #line 49 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ComboBox comboBox;

        #line default
        #line hidden

        #line 55 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Image image1;

        #line default
        #line hidden

        #line 56 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Button button1;

        #line default
        #line hidden

        #line 57 "..\..\AddStaff.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Button button;

        #line default
        #line hidden

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/SEproject;component/addstaff.xaml", System.UriKind.Relative);

            #line 1 "..\..\AddStaff.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
            switch (connectionId)
            {
            case 1:
            this.groupBox = ((System.Windows.Controls.GroupBox)(target));
            return;
            case 2:
            this.label3 = ((System.Windows.Controls.Label)(target));
            return;
            case 3:
            this.label13 = ((System.Windows.Controls.Label)(target));
            return;
            case 4:
            this.Id = ((System.Windows.Controls.TextBox)(target));
            return;
            case 5:
            this.label = ((System.Windows.Controls.Label)(target));
            return;
            case 6:
            this.Name = ((System.Windows.Controls.TextBox)(target));
            return;
            case 7:
            this.label1 = ((System.Windows.Controls.Label)(target));
            return;
            case 8:
            this.Address = ((System.Windows.Controls.TextBox)(target));
            return;
            case 9:
            this.label2 = ((System.Windows.Controls.Label)(target));
            return;
            case 10:
            this.mobile = ((System.Windows.Controls.TextBox)(target));
            return;
            case 11:
            this.comboBox1 = ((System.Windows.Controls.ComboBox)(target));

            #line 29 "..\..\AddStaff.xaml"
            this.comboBox1.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.comboBox1_SelectionChanged);

            #line default
            #line hidden
            return;
            case 12:
            this.label4 = ((System.Windows.Controls.Label)(target));
            return;
            case 13:
            this.DatePicker = ((System.Windows.Controls.DatePicker)(target));
            return;
            case 14:
            this.label12 = ((System.Windows.Controls.Label)(target));
            return;
            case 15:
            this.Email1 = ((System.Windows.Controls.TextBox)(target));
            return;
            case 16:
            this.label5 = ((System.Windows.Controls.Label)(target));
            return;
            case 17:
            this.FatherName = ((System.Windows.Controls.TextBox)(target));
            return;
            case 18:
            this.label9 = ((System.Windows.Controls.Label)(target));
            return;
            case 19:
            this.MotherName = ((System.Windows.Controls.TextBox)(target));
            return;
            case 20:
            this.label7 = ((System.Windows.Controls.Label)(target));
            return;
            case 21:
            this.password = ((System.Windows.Controls.TextBox)(target));
            return;
            case 22:
            this.label6 = ((System.Windows.Controls.Label)(target));
            return;
            case 23:
            this.comboBox = ((System.Windows.Controls.ComboBox)(target));

            #line 49 "..\..\AddStaff.xaml"
            this.comboBox.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.comboBox_SelectionChanged_1);

            #line default
            #line hidden
            return;
            case 24:
            this.image1 = ((System.Windows.Controls.Image)(target));
            return;
            case 25:
            this.button1 = ((System.Windows.Controls.Button)(target));
            return;
            case 26:
            this.button = ((System.Windows.Controls.Button)(target));

            #line 57 "..\..\AddStaff.xaml"
            this.button.Click += new System.Windows.RoutedEventHandler(this.button_Click);

            #line default
            #line hidden
            return;
            }
            this._contentLoaded = true;
        }
    }
}


text:
(function ($) {
    "use strict";

    var isEmpty = function (value, trim) {
            return value === null || value === undefined || value === [] || value === '' || trim && $.trim(value) === '';
        },
        popupDialog = function (url, name, w, h) {
            var left = (screen.width / 2) - (w / 2), top = 60,
                existWin = window.open('', name, '', true);
            existWin.close();
            return window.open(url, name,
                'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
        },
        popupTemplate = '' +
            '<title>Export Data - © Krajee</title>' +
            '' +
            '{msg}' +
            '' +
            '';

    var ExportData = function (element, options) {
        var self = this;
        self.$element = $(element);
        $.each(options, function (key, val) {
            self[key] = val;
        });
        var settings = options.settings;
        self.$form = $("#" + settings.formId);
        self.messages = settings.messages;
        self.popup = '';
        self.listen();
    };

    ExportData.prototype = {
        constructor: ExportData,
        setPopupAlert: function (msg) {
            var self = this;
            if (!self.popup.document) {
                return;
            }
            if (arguments.length && arguments[1]) {
                var el = self.popup.document.getElementsByTagName('body');
                setTimeout(function () {
                    el[0].innerHTML = msg;
                }, 4000);
            } else {
                var newmsg = popupTemplate.replace('{msg}', msg);
                self.popup.document.write(newmsg);
            }
        },
        listen: function () {
            var self = this;
            self.$form.attr('action', window.location.href).appendTo('body');
            self.listenClick();
            if (self.target === '_popup') {
                self.$form.off('submit.exportmenu').on('submit.exportmenu', function () {
                    setTimeout(function () {
                        self.setPopupAlert(self.messages.downloadComplete, true);
                    }, 1000);
                });
            }
        },
        processExport: function (fmt) {
            var self = this, $selected, cols = [];
            self.$form.find('[name="export_type"]').val(fmt);
            if (self.target === '_popup') {
                self.popup = popupDialog('', 'kvExportFullDialog', 350, 120);
                self.popup.focus();
                self.setPopupAlert(self.messages.downloadProgress);
            }
            if (!isEmpty(self.columnSelectorId)) {
                $selected = $('#' + self.columnSelectorId).parent().find('input[name="export_columns_selector[]"]');
                $selected.each(function () {
                    var $el = $(this);
                    if ($el.is(':checked')) {
                        cols.push($el.attr('data-key'));
                    }
                });
                self.$form.find('input[name="export_columns"]').val(JSON.stringify(cols));
            }
            self.$form.trigger('submit');
        },
        listenClick: function () {
            var self = this;
            self.$element.off('click.exportmenu').on('click.exportmenu', function (e) {
                var fmt, msgs, msg = '', msg1, msg2, msg3, lib = window[self.dialogLib];
                fmt = $(this).data('format');
                e.preventDefault();
                e.stopPropagation();
                if (!self.showConfirmAlert) {
                    self.processExport(fmt);
                    return;
                }
                msgs = self.messages;
                msg1 = isEmpty(self.alertMsg) ? '' : self.alertMsg;
                msg2 = isEmpty(msgs.allowPopups) ? '' : msgs.allowPopups;
                msg3 = isEmpty(msgs.confirmDownload) ? '' : msgs.confirmDownload;
                if (msg1.length && msg2.length) {
                    msg = msg1 + '\n\n' + msg2;
                } else {
                    if (!msg1.length && msg2.length) {
                        msg = msg2;
                    } else {
                        msg = (msg1.length && !msg2.length) ? msg1 : '';
                    }
                }
                if (msg3.length) {
                    msg = msg + '\n\n' + msg3;
                }
                if (isEmpty(msg)) {
                    self.processExport(fmt);
                    return;
                }
                lib.confirm(msg, function (result) {
                    if (result) {
                        self.processExport(fmt);
                    }
                });
            });
        }
    };

    //ExportData plugin definition
    $.fn.exportdata = function (option) {
        var args = Array.apply(null, arguments);
        args.shift();
        return this.each(function () {
            var $this = $(this),
                data = $this.data('exportdata'),
                options = typeof option === 'object' && option;

            if (!data) {
                $this.data('exportdata',
                    (data = new ExportData(this, $.extend({}, $.fn.exportdata.defaults, options, $(this).data()))));
            }

            if (typeof option === 'string') {
                data[option].apply(data, args);
            }
        });
    };

    $.fn.exportdata.defaults = {
        filename: 'export',
        target: '_popup',
        showConfirmAlert: true,
        columnSelectorId: null,
        alertMsg: '',
        dialogLib: 'krajeeDialog',
        settings: {
            formId: '',
            messages: {
                allowPopups: '',
                confirmDownload: '',
                downloadProgress: '',
                downloadComplete: ''
            }
        }
    };
})(window.jQuery);


text:
namespace SoundFingerprinting.Hashing.NeuralHashing.MMI
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;

    using SoundFingerprinting.Hashing.Utils;

    [Serializable]
    public class MinimalMutualInfoPattern
    {
        [NonSerialized] private readonly List<int> indexList = new List<int>();
        private readonly MinimalMutualInfoGroup[] minimalMutualInfoGroups;
        [NonSerialized] private readonly List<MinimalMutualInfoPair> mmiPairs = new List<MinimalMutualInfoPair>();

        /// <summary>
        /// Initializes a new instance of the <see cref="MinimalMutualInfoPattern"/> class.
        /// </summary>
        /// <param name="numberOfGroups">
        /// Number of groups to create [18]
        /// </param>
        /// <param name="sizeOfGroup">
        /// Size of group [22]
        /// </param>
        public MinimalMutualInfoPattern(int numberOfGroups, int sizeOfGroup)
        {
            NumberOfGroups = numberOfGroups;
            minimalMutualInfoGroups = new MinimalMutualInfoGroup[this.NumberOfGroups];
            for (int i = 0; i < this.NumberOfGroups; i++)
            {
                minimalMutualInfoGroups[i] = new MinimalMutualInfoGroup(sizeOfGroup);
            }
        }

        /// <summary>
        ///   Gets the number of groups that the pattern contains
        /// </summary>
        public int NumberOfGroups { get; private set; }

        /// <summary>
        ///   Gets the output dimensionality of the network ensemble
        /// </summary>
        public int NeuralNetworkEnsembleDimensionality { get; private set; }

        /// <summary>
        ///   The group of the pattern on the specified index
        /// </summary>
        /// <param name = "index">Index of the group</param>
        /// <returns>The group on index</returns>
        public MinimalMutualInfoGroup this[int index]
        {
            get { return minimalMutualInfoGroups[index]; }
        }

        /// <summary>
        ///   Creates the hash pattern according to the number of groups specified and their size
        /// </summary>
        /// <param name = "outputs">The data on which mutual information is computed</param>
        public void CreatePattern(double[][] outputs)
        {
            if (outputs.Length * outputs[0].Length < NumberOfGroups * minimalMutualInfoGroups[0].Count)
            {
                throw new ArgumentException("Not enough outputs in order to create a pattern");
            }

            NeuralNetworkEnsembleDimensionality = outputs[0].Length; /*400*/

            // Create a list of indixes
            for (int i = 0; i < outputs[0].Length /*400*/; i++)
            {
                indexList.Add(i);
            }

            ComputePairs(outputs); /*Compute MI between all pairs*/
            InitializeGroups();
            FillGroupsConservative();
        }

        /// <summary>
        ///   Initializes the mmi groups with starting elements that have the highest unconditional entropy
        /// </summary>
        protected void InitializeGroups()
        {
            // Clear all groups
            for (int i = 0; i < minimalMutualInfoGroups.Length; i++)
            {
                minimalMutualInfoGroups[i].Clear();
            }

            // Compute unconditional entropy
            KeyValuePair<int, double>[] uncodEntropy = new KeyValuePair<int, double>[NeuralNetworkEnsembleDimensionality];
            for (int i = 0; i < NeuralNetworkEnsembleDimensionality; i++)
            {
                double uncodEntrpy = 0.0;
                List<MinimalMutualInfoPair> list = mmiPairs.FindAll(pair => pair.IndexFirst == i || pair.IndexSecond == i);
                foreach (MinimalMutualInfoPair pair in list)
                {
                    uncodEntrpy += pair.MutualInformation;
                }

                uncodEntropy[i] = new KeyValuePair<int, double>(i, uncodEntrpy);
            }

            List<KeyValuePair<int, double>> query = new List<KeyValuePair<int, double>>(uncodEntropy.OrderBy(kv => kv.Value));

            // Assign elements that have highest unconditional entropy
            for (int i = 0; i < minimalMutualInfoGroups.Length; i++)
            {
                minimalMutualInfoGroups[i].AddToGroup(query[i].Key);
                indexList.Remove(query[i].Key);
            }
        }

        /// <summary>
        ///  The most agressive of the methods min ( min (MI(s,t)))
        ///  where s is a permutation and t is a member of the group
        /// </summary>
        protected void FillGroupsAgressive()
        {
            for (int i = 0; i < minimalMutualInfoGroups.Length; i++)
            {
                if (minimalMutualInfoGroups[i].Count != 1)
                {
                    throw new ConstraintException("The groups shouldn't be full or uninitialized");
                }
            }

            while (true)
            {
                MinimalMutualInfoPair minMi = new MinimalMutualInfoPair(-1, -1, double.MaxValue);
                int groupIndexToAdd = -1;
                int uniqueIndex = -1;
                for (int i = 0; i < indexList.Count; i++)
                {
                    for (int j = 0; j < minimalMutualInfoGroups.Length; j++)
                    {
                        if (minimalMutualInfoGroups[j].Count == minimalMutualInfoGroups[j].GroupSize)
                        {
                            continue;
                        }

                        for (int k = 0; k < minimalMutualInfoGroups[j].Count; k++)
                        {
                            // Find mi between selected index and current member of the group
                            MinimalMutualInfoPair mi = mmiPairs.Find(
                                pair => (pair.IndexFirst == indexList[i] && pair.IndexSecond == minimalMutualInfoGroups[j][k]) ||
                                        (pair.IndexFirst == minimalMutualInfoGroups[j][k] && pair.IndexSecond == indexList[i]));
                            if (minMi.MutualInformation > mi.MutualInformation)
                            {
                                minMi = mi;
                                groupIndexToAdd = j;
                                uniqueIndex = minimalMutualInfoGroups[j].Contains(minMi.IndexFirst) ? minMi.IndexSecond : minMi.IndexFirst;
                            }
                        }
                    }
                }

                if (minMi.IndexFirst == -1)
                {
                    break;
                }

                indexList.Remove(uniqueIndex);
                minimalMutualInfoGroups[groupIndexToAdd].AddToGroup(uniqueIndex);
            }
        }

        /// <summary>
        ///   The most conservative method due to the fact that it minimizes the worst of correlations
        ///   min ( max (MI(s,t)))
        ///   where s is a permutation and t is a member of the group
        ///   Assign  MI to a group to be the maximum of the MIs between s and any member of
        ///   this group. Select the minimum of these across groups and unselected indeces
        /// </summary>
        protected void FillGroupsConservative()
        {
            for (int i = 0; i < minimalMutualInfoGroups.Length; i++)
            {
                if (minimalMutualInfoGroups[i].Count != 1)
                {
                    throw new ConstraintException("The groups shouldn't be full or uninitialized");
                }
            }

            while (true)
            {
                double minMi = double.MaxValue;
                int groupIndexToAdd = -1;
                int uniqueIndex = -1;
                bool finished = true;
                for (int i = 0; i < indexList.Count; i++)
                {
                    for (int j = 0; j < minimalMutualInfoGroups.Length; j++)
                    {
                        double groupMax = 0.0;
                        if (minimalMutualInfoGroups[j].Count == minimalMutualInfoGroups[j].GroupSize)
                        {
                            continue;
                        }

                        finished = false;
                        for (int k = 0; k < minimalMutualInfoGroups[j].Count; k++)
                        {
                            // Find mi between selected index and current member of the group
                            MinimalMutualInfoPair mi = mmiPairs.Find(
                                pair => (pair.IndexFirst == indexList[i] && pair.IndexSecond == minimalMutualInfoGroups[j][k]) ||
                                        (pair.IndexFirst == minimalMutualInfoGroups[j][k] && pair.IndexSecond == indexList[i]));
                            if (mi.MutualInformation > groupMax)
                            {
                                groupMax = mi.MutualInformation;
                            }
                        }

                        if (minMi > groupMax)
                        {
                            minMi = groupMax;
                            groupIndexToAdd = j;
                            uniqueIndex = indexList[i];
                        }
                    }
                }

                if (finished)
                {
                    break;
                }

                indexList.Remove(uniqueIndex);
                minimalMutualInfoGroups[groupIndexToAdd].AddToGroup(uniqueIndex);
            }
        }

        /// <summary>
        ///   Computes mutual information between all pairs
        /// </summary>
        /// <param name = "outputs">Actual data on which MI is computed</param>
        private void ComputePairs(double[][] outputs)
        {
            int netOutputsCount = outputs[0].Length;

            double[] samples1 = new double[outputs.Length];
            double[] samples2 = new double[outputs.Length];

            for (int i = 0; i < netOutputsCount - 1 /*400*/; i++)
            {
                for (int j = i + 1; j < netOutputsCount; j++)
                {
                    // Copy to arrays the contents of particular i and j
                    for (int k = 0, n = outputs.Length; k < n; k++)
                    {
                        samples1[k] = outputs[k][i];
                        samples2[k] = outputs[k][j];
                    }

                    double mutualInf = SignalUtils.MutualInformation(samples1, samples2);
                    mmiPairs.Add(new MinimalMutualInfoPair(i, j, mutualInf));
                }
            }
        }
    }
}


text:
layout: page
title: Velasquez Family Reunion
date: 2016-05-24
author: Melissa Wong
tags: weekly links, java
status: published
summary: Etiam tincidunt quam nec tellus ultricies.
banner: images/banner/office-01.jpg
booking:
  startDate: 05/19/2016
  endDate: 05/24/2016
  ctyhocn: GOJNNHX
  groupCode: VFR
published: true
---
Donec magna mi, interdum quis ligula eleifend, placerat dapibus lectus. Etiam rhoncus, ipsum sed porta ultrices, velit elit suscipit ipsum, ac rhoncus augue diam nec ipsum. Nam semper nulla eu justo vestibulum vulputate. Vestibulum semper et diam gravida congue. Praesent vehicula turpis metus, sed pellentesque tellus mollis vel. Fusce hendrerit molestie magna, malesuada sodales tellus scelerisque eget. Nam pharetra finibus sem sed sodales.

* Vestibulum vestibulum turpis non velit lobortis, sit amet varius nibh luctus
* Proin fringilla magna in arcu suscipit, a malesuada diam lacinia
* Nulla volutpat enim consectetur leo imperdiet, eu ultrices ipsum ornare
* Nullam vestibulum lacus ac felis feugiat ultrices
* Vestibulum at odio vitae libero mattis porta.

Etiam sit amet sapien ut eros aliquam eleifend. Morbi et risus ante. Donec pulvinar nunc sit amet sagittis egestas. Proin sodales fermentum faucibus. Nunc porttitor consectetur ex sit amet commodo. Maecenas ut ante ac turpis porttitor posuere. Proin auctor, odio vitae sodales volutpat, diam ante consequat diam, nec auctor elit justo nec enim. Proin nec viverra leo. Nulla euismod maximus mi at luctus. Pellentesque euismod egestas mauris sit amet placerat. Integer nunc leo, blandit vel lectus sed, posuere sagittis arcu. Proin consequat congue turpis ut euismod. Cras eu mi dolor. Mauris scelerisque pretium euismod. Fusce a pulvinar lectus. Aliquam erat volutpat.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla auctor ornare felis sit amet laoreet. Cras convallis odio sed erat viverra mollis. Pellentesque at sem semper, fringilla arcu non, rhoncus velit. Morbi in lobortis orci. Ut egestas est eu leo suscipit, ut tincidunt eros pretium. Cras ut eros et ex varius aliquam.


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/feed/core/v2/public/ntp_feed_content_fetcher.h"

#include <memory>
#include "components/feed/core/proto/v2/wire/client_info.pb.h"
#include "components/feed/core/proto/v2/wire/stream_structure.pb.h"
#include "components/feed/core/v2/feed_network_impl.h"
#include "components/feed/core/v2/proto_util.h"
#include "components/feed/feed_feature_list.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"

namespace feed {
namespace {

constexpr int kTargetArticleCount = 3;

void HandleWebFeedListContentsResponse(
    base::OnceCallback<void(std::vector<NtpFeedContentFetcher::Article>)>
        callback,
    FeedNetwork::ApiResult<feedwire::Response> response) {
  std::vector<NtpFeedContentFetcher::Article> result;
  if (!response.response_body) {
    DLOG(ERROR) << "Failed to fetch content for feed NTP module. Status: "
                << response.response_info.status_code;
    return std::move(callback).Run(std::move(result));
  }

  // Get the first several articles from the response. No attempt is made
  // to show a variety of publishers.
  for (const feedwire::DataOperation& data_operation :
       response.response_body->feed_response().data_operation()) {
    if (data_operation.operation() !=
            feedwire::DataOperation::UPDATE_OR_APPEND ||
        !data_operation.has_feature() ||
        !data_operation.feature().has_content()) {
      continue;
    }

    for (const feedwire::PrefetchMetadata& prefetch_metadata :
         data_operation.feature().content().prefetch_metadata()) {
      auto& article = result.emplace_back();
      article.title = prefetch_metadata.title();
      article.publisher = prefetch_metadata.publisher();
      article.url = GURL(prefetch_metadata.uri());
      article.thumbnail_url = GURL(prefetch_metadata.image_url());
      article.favicon_url = GURL(prefetch_metadata.favicon_url());
      if (result.size() >= kTargetArticleCount)
        return std::move(callback).Run(std::move(result));
    }
  }
  DLOG_IF(ERROR, result.size() < kTargetArticleCount)
      << "Request for content for the feed NTP module succeeded but the "
         "response contained fewer than "
      << kTargetArticleCount << " articles.";
  std::move(callback).Run(std::move(result));
}

}  // namespace

NtpFeedContentFetcher::NtpFeedContentFetcher(
    signin::IdentityManager* identity_manager,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    const std::string& api_key,
    PrefService* pref_service)
    : feed_network_delegate_(identity_manager) {
  feed_network_ = std::make_unique<FeedNetworkImpl>(
      &feed_network_delegate_, identity_manager, api_key, url_loader_factory,
      pref_service);
}

NtpFeedContentFetcher::~NtpFeedContentFetcher() = default;

NtpFeedContentFetcher::Article::Article() = default;
NtpFeedContentFetcher::Article::Article(const Article&) = default;
NtpFeedContentFetcher::Article::~Article() = default;

void NtpFeedContentFetcher::FetchFollowingFeedArticles(
    base::OnceCallback<void(std::vector<NtpFeedContentFetcher::Article>)>
        callback) {
  feedwire::Request request = CreateFeedQueryRefreshRequest(
      StreamType(StreamKind::kFollowing),
      feedwire::FeedQuery::INTERACTIVE_WEB_FEED, RequestMetadata(),
      /*consistency_token=*/std::string());

  feedwire::ClientInfo* client_info =
      request.mutable_feed_request()->mutable_client_info();
  // TODO(https://crbug.com/1328951): For the desktop feed prototype we call the
  // Android endpoint and need to pretend we are an Android client. This won't
  // be the case for the launch.
  client_info->set_platform_type(feedwire::ClientInfo::ANDROID_ID);
  client_info->set_app_type(feedwire::ClientInfo::CHROME_ANDROID);

  // For the prototype, it's okay if the request fails or the user is signed
  // out; the module will be empty.
  feed_network_->SendApiRequest<WebFeedListContentsDiscoverApi>(
      request, feed_network_delegate_.GetAccountInfo(), RequestMetadata(),
      base::BindOnce(&HandleWebFeedListContentsResponse, std::move(callback)));
}

void NtpFeedContentFetcher::SetFeedNetworkForTesting(
    std::unique_ptr<FeedNetwork> feed_network) {
  feed_network_ = std::move(feed_network);
}

NtpFeedContentFetcher::NetworkDelegate::NetworkDelegate(
    signin::IdentityManager* identity_manager)
    : identity_manager_(identity_manager) {}

std::string NtpFeedContentFetcher::NetworkDelegate::GetLanguageTag() {
  // TODO(https://crbug.com/1328951): Change this for the final implementation.
  return std::string();
}

AccountInfo NtpFeedContentFetcher::NetworkDelegate::GetAccountInfo() {
  return AccountInfo(identity_manager_->GetPrimaryAccountInfo(
      GetConsentLevelNeededForPersonalizedFeed()));
}

bool NtpFeedContentFetcher::NetworkDelegate::IsOffline() {
  // TODO(https://crbug.com/1328951): Change this for the final implementation.
  return false;
}

}  // namespace feed


text:
@class BookmarkTextFieldItem;

// Delegates the cell's text field's events.
@protocol BookmarkTextFieldItemDelegate<UITextFieldDelegate>

// Called when the `text` of the item was changed via the textfield. The item's
// `text` is up-to-date when this is called.
- (void)textDidChangeForItem:(BookmarkTextFieldItem*)item;

@end

@interface BookmarkTextFieldItem : TableViewItem

// The text field content.
@property(nonatomic, copy) NSString* text;

// The text field placeholder.
@property(nonatomic, copy) NSString* placeholder;

// Receives the text field events.
@property(nonatomic, weak) id<BookmarkTextFieldItemDelegate> delegate;

@end

@interface BookmarkTextFieldCell : TableViewCell

// Label to display the type of content `self.textField` is displaying.
@property(nonatomic, strong) UILabel* titleLabel;

// Text field to display the title or the URL of the bookmark node.
@property(nonatomic, strong) UITextField* textField;

// Returns the appropriate text color to use for the given `editing` state.
+ (UIColor*)textColorForEditing:(BOOL)editing;

@end

#endif  // IOS_CHROME_BROWSER_UI_BOOKMARKS_CELLS_BOOKMARK_TEXT_FIELD_ITEM_H_


text:
package org.camunda.bpm.spring.boot.starter;

import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.spring.boot.starter.test.TestApplication;
import org.camunda.bpm.spring.boot.starter.test.jpa.domain.TestEntity;
import org.camunda.bpm.spring.boot.starter.test.jpa.repository.TestEntityRepository;
import org.camunda.bpm.spring.boot.starter.test.service.TransactionalTestService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.transaction.Transactional;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestApplication.class})
@Transactional
public class CamundaJpaAutoConfigurationIT extends AbstractCamundaAutoConfigurationIT {

  @Autowired
  private TestEntityRepository testEntityRepository;

  @Autowired
  private TransactionalTestService transactionalTestService;

  @Test
  public void jpaTest() {
    ProcessInstance processInstance = transactionalTestService.doOk();
    TestEntity testEntity = (TestEntity) runtimeService.getVariable(
      processInstance.getId(), "test");
    assertNotNull(testEntity);
    assertEquals("text", testEntity.getText());
    assertEquals(processInstance.getId(), runtimeService.createProcessInstanceQuery()
      .variableValueEquals("test", testEntity).singleResult().getId());
    testEntity.setText("text2");
    testEntityRepository.save(testEntity);
    testEntity = (TestEntity) runtimeService.getVariable(processInstance.getId(),
      "test");
    assertEquals("text2", testEntity.getText());
  }

  @Test
  public void transactionTest() {
    assertEquals(0, testEntityRepository.count());
    try {
      transactionalTestService.doThrowing();
      fail();
    } catch (IllegalStateException e) {
      assertEquals(0, testEntityRepository.count());
      assertEquals(0, runtimeService.createProcessInstanceQuery()
        .processDefinitionKey("TestProcess").count());
    }
  }
}


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
    {
        "file": "plugins/com.ionic.keyboard/www/keyboard.js",
        "id": "com.ionic.keyboard.keyboard",
        "clobbers": [
            "cordova.plugins.Keyboard"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.device/www/device.js",
        "id": "org.apache.cordova.device.device",
        "clobbers": [
            "device"
        ]
    }
];
module.exports.metadata =
// TOP OF METADATA
{
    "com.ionic.keyboard": "1.0.2",
    "org.apache.cordova.device": "0.2.10"
}
// BOTTOM OF METADATA
});


text:
/**
 * @api {get} /user/:id Request User information
 * @apiName GetUser
 * @apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "firstname": "John",
 *       "lastname": "Doe"
 *     }
 *
 * @apiError UserNotFound The id of the User was not found.
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *       "error": "UserNotFound"
 *     }

 /**
 * @api {post} /user/:id Create User account
 * @apiName CreateUser
 * @apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "firstname": "John",
 *       "lastname": "Doe"
 *     }
 *
 * @apiError UserNotFound The id of the User was not found.
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *       "error": "UserNotFound"
 *     }
 */


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class ScheduledTaskEvent extends Event
{
  public ScheduledTaskEventArgument scheduledTask;
  public ManagedEntityEventArgument entity;

  public ScheduledTaskEventArgument getScheduledTask()
  {
    return this.scheduledTask;
  }

  public ManagedEntityEventArgument getEntity()
  {
    return this.entity;
  }

  public void setScheduledTask(ScheduledTaskEventArgument scheduledTask)
  {
    this.scheduledTask=scheduledTask;
  }

  public void setEntity(ManagedEntityEventArgument entity)
  {
    this.entity=entity;
  }
}


text:
(function () {
    'use strict';

    window.RATCHET.Class.SegmentedControl = window.RATCHET.Class.Component.extend({
        init: function (componentToggle, component) {
            var self = this;

            self.componentToggle = componentToggle;
            self.component = component;

            // Find all control items.
            self.controlItems = self.component.querySelectorAll('.control-item');

            self.initEvents();
        },

        initEvents: function(){
            var self = this;

            self.componentToggleTouchEnd = function (event) {
                self.onComponentToggleTouchEnd(event);
            };

            var controlItemLength = self.controlItems.length;

            for (var i = 0; i < controlItemLength; i++) {
                var ci = self.controlItems[i];

                ci.addEventListener('touchend', self.componentToggleTouchEnd);
            }
        },

        onComponentToggleTouchEnd: function (event) {
            var self = this;
            self._super(event);

            var targetTab = event.target;

            if (targetTab && targetTab.classList.contains('control-item')) {
                var activeTab;
                var activeBodies;
                var targetBody;
                var className = 'active';
                var classSelector = '.control-content.' + className;
                var tabClassSelector = '.control-item.' + className;

                activeTab = targetTab.parentNode.querySelector(tabClassSelector);

                if (activeTab) {
                    activeTab.classList.remove(className);
                }

                targetTab.classList.add(className);

                if (!targetTab.hash) {
                    return;
                }

                targetBody = document.querySelector(targetTab.hash);

                if (!targetBody) {
                    return;
                }

                activeBodies = targetBody.parentNode.querySelectorAll(classSelector);

                for (var i = 0; i < activeBodies.length; i++) {
                    activeBodies[i].classList.remove(className);
                }

                targetBody.classList.add(className);

                // prevents rewriting url.
                event.preventDefault();
                event.stopPropagation();
            }
        }
    });
})();


text:
[![Build Status](https://travis-ci.org/dls-controls/dls_ade.svg)](https://travis-ci.org/dls-controls/dls_ade)
[![Coverage Status](https://coveralls.io/repos/github/dls-controls/dls_ade/badge.svg?branch=master)](https://coveralls.io/github/dls-controls/dls_ade?branch=master)
[![Code Health](https://landscape.io/github/dls-controls/dls_ade/master/landscape.svg?style=flat)](https://landscape.io/github/dls-controls/dls_ade/master)

# DLS Application Development Environment (ADE)

A collection of scripts used in the DLS Controls Group Application Development Environment.

## Development Environment

Setup a virtualenv in the root of the project and install the dependencies:

```
  virtualenv -p /path/to/your/python2.7 venv
  source venv/bin/activate
  pip install -r requirements.txt

  # Setup the module in development mode
  python setup.py develop

  # Optional: Build an egg for distribution
  python setup.py bdist_egg

  # Optional: Build the docs with sphinx
  python setup.py build_sphinx

  # Optional: Run the unittests with nose
  python setup.py nosetests
```

## dls-release.py offline testing

To inspect changes to the build server release scripts,
generated by dls-release.py, one can override the location
of the production build server queue by setting environment
variables DLSBUILD_ROOT_DIR and/or DLSBUILD_WIN_ROOT_DIR

```
  # Assuming the above example virtualenv has been configured first

  mkdir -p $HOME/test/work/etc/build/queue
  export DLSBUILD_ROOT_DIR=$HOME/test
  export DLSBUILD_WIN_ROOT_DIR=$HOME/test
  dls-release.py somemodule 1-1dls44

  # Now see and/or run build script in
  # $HOME/test/work/etc/build/queue
```

## Logging

The dls_ade scripts produce log messages as they progress. Messages for the regular
user is printed to stdout and further debug and info messages are logged to the DLS
graylog system.
A local debug log is also written to the users home dir: `$HOME/.dls_ade_debug.log`

To review logs produced by the scripts for a given user, visit
https://graylog2.diamond.ac.uk
and search `package:dls_ade AND username:fedid` (replacing `fedid` for the users FedID)

For releases on the build server, it is possible to view both logs from the client side
script (i.e. dls-release.py) as well as the build server process. See all logs for a
given module that you have released with the search:
`username:FEDID module:MODULE` replacing FEDID and MODULE.

The environment variables ADE_GELFLOG_SERVER and ADE_GELFLOG_SERVER_PORT can be used to
override the log destination of the ADE scripts for testing/development purposes.

The environment variables ADE_SYSLOG_SERVER and ADE_SYSLOG_SERVER_PORT can be used to
override the log destination of the Controls Build Server scripts for testing/development purposes.


text:
<?php

namespace PServerCore\Service;

use Doctrine\ORM\EntityManager;
use PServerCore\Entity\UserInterface;
use PServerCore\Options\EntityOptions;
use Zend\Form\FormInterface;
use Zend\Mvc\Controller\PluginManager;

class UserRole
{
    const ERROR_NAME_SPACE = 'p-server-admin-user-panel';

    /** @var  EntityManager */
    protected $entityManager;

    /** @var  FormInterface */
    protected $adminUserRoleForm;

    /** @var  EntityOptions */
    protected $entityOptions;

    /** @var  PluginManager */
    protected $controllerPluginManager;

    /**
     * UserRole constructor.
     * @param EntityManager $entityManager
     * @param FormInterface $adminUserRoleForm
     * @param EntityOptions $entityOptions
     * @param PluginManager $controllerPluginManager
     */
    public function __construct(
        EntityManager $entityManager,
        FormInterface $adminUserRoleForm,
        EntityOptions $entityOptions,
        PluginManager $controllerPluginManager
    ) {
        $this->entityManager = $entityManager;
        $this->adminUserRoleForm = $adminUserRoleForm;
        $this->entityOptions = $entityOptions;
        $this->controllerPluginManager = $controllerPluginManager;
    }

    /**
     * @param $data
     * @param $userId
     * @return \PServerCore\Entity\UserInterface|bool
     */
    public function addRoleForm($data, $userId)
    {
        /** @var FormInterface $form */
        $form = $this->adminUserRoleForm;
        $form->setData($data);

        if (!$form->isValid()) {
            $this->addFormMessagesInFlashMessenger($form, $this::ERROR_NAME_SPACE);

            return false;
        }

        $data = $form->getData();
        $roleId = $data['roleId'];

        $user = $this->getUser4Id($userId);

        if ($user) {
            $this->addRole4User($user, $roleId);
        }

        return $user;
    }

    /**
     * @param $userId
     * @param $roleId
     */
    public function removeRole($userId, $roleId)
    {
        $user = $this->getUser4Id($userId);
        $this->removeRole4User($user, $roleId);
    }

    /**
     * @return FormInterface
     */
    public function getAdminUserRoleForm()
    {
        return $this->adminUserRoleForm;
    }

    /**
     * @param UserInterface $user
     * @param               $roleId
     * @return bool
     */
    protected function removeRole4User(UserInterface $user, $roleId)
    {
        $role = $this->getRoleEntity4Id($roleId);
        if (!$role) {
            return false;
        }

        $user->removeUserRole($role);
        $role->removeUser($user);
        $this->entityManager->persist($role);
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        return true;
    }

    /**
     * @param UserInterface $user
     * @param               $roleId
     * @return bool
     */
    protected function addRole4User(UserInterface $user, $roleId)
    {
        $result = false;

        if (!$this->isRoleAlreadyAdded($user, $roleId)) {
            $role = $this->getRoleEntity4Id($roleId);
            $role->addUser($user);
            $user->addUserRole($role);
            $this->entityManager->persist($role);
            $this->entityManager->persist($user);
            $this->entityManager->flush();
            $result = true;
        }

        return $result;
    }

    /**
     * @param $roleId
     * @return null|\PServerCore\Entity\UserRole
     */
    protected function getRoleEntity4Id($roleId)
    {
        /** @var \PServerCore\Entity\Repository\UserRole $repository */
        $repository = $this->entityManager->getRepository($this->entityOptions->getUserRole());
        return $repository->getRole4Id($roleId);
    }

    /**
     * @param UserInterface $user
     * @param               $roleId
     * @return bool
     */
    protected function isRoleAlreadyAdded(UserInterface $user, $roleId)
    {
        $result = false;
        foreach ($user->getRoles() as $role) {
            if ($role->getId() == $roleId) {
                $result = true;
                break;
            }
        }

        return $result;
    }

    /**
     * @return \Zend\Mvc\Plugin\FlashMessenger\FlashMessenger
     */
    protected function getFlashMessenger()
    {
        return $this->controllerPluginManager->get('flashMessenger');
    }

    /**
     * @param FormInterface $form
     * @param $namespace
     */
    protected function addFormMessagesInFlashMessenger(FormInterface $form, $namespace)
    {
        $messages = $form->getMessages();
        foreach ($messages as $elementMessages) {
            foreach ($elementMessages as $message) {
                $this->getFlashMessenger()->setNamespace($namespace)->addMessage($message);
            }
        }
    }

    /**
     * @param $userId
     *
     * @return null|\PServerCore\Entity\UserInterface
     */
    protected function getUser4Id($userId)
    {
        /** @var \PServerCore\Entity\Repository\User $userRepository */
        $userRepository = $this->entityManager->getRepository($this->entityOptions->getUser());

        return $userRepository->getUser4Id($userId);
    }
}