text:
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FreneticScript;
using FreneticScript.CommandSystem;
using Voxalia.ServerGame.TagSystem.TagObjects;
using Voxalia.Shared;

namespace Voxalia.ServerGame.PlayerCommandSystem.CommonCommands
{
    public class RemotePlayerCommand : AbstractPlayerCommand
    {
        public RemotePlayerCommand()
        {
            Name = "remote";
            Silent = false;
            // TODO: Required permission.
        }

        public override void Execute(PlayerCommandEntry entry)
        {
            if (entry.InputArguments.Count <= 0)
            {
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "/remote <commands>");
                return;
            }
            CommandQueue queue = CommandScript.SeparateCommands("command_line", entry.AllArguments(),
                entry.Player.TheServer.Commands.CommandSystem, false).ToQueue(entry.Player.TheServer.Commands.CommandSystem);
            queue.SetVariable("player", new PlayerTag(entry.Player));
            queue.Outputsystem = (message, messageType) =>
            {
                string bcolor = "^r^7";
                switch (messageType)
                {
                    case MessageType.INFO:
                    case MessageType.GOOD:
                        bcolor = "^r^2";
                        break;
                    case MessageType.BAD:
                        bcolor = "^r^3";
                        break;
                }
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, entry.Player.TheServer.Commands.CommandSystem.TagSystem.ParseTagsFromText(message, bcolor,
                    queue.CommandStack.Peek().Variables, DebugMode.FULL, (o) => { /* DO NOTHING */ }, true));
            };
            queue.Execute();
        }
    }
}


text:
/*jshint strict: false */
/*global arango, db, assertTrue, assertFalse, assertEqual */

// //////////////////////////////////////////////////////////////////////////////
// / @brief Helper for JavaScript Tests
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / 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.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Wilfried Goesgens
// / @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

const internal = require('internal'); // OK: processCsvFile
const {
  getServerById,
  getServersByType,
  getEndpointById,
  getEndpointsByType,
  Helper,
  deriveTestSuite,
  deriveTestSuiteWithnamespace,
  typeName,
  isEqual,
  compareStringIds,
} = require('@arangodb/test-helper-common');
const fs = require('fs');
const pu = require('@arangodb/testutils/process-utils');
const _ = require('lodash');

exports.getServerById = getServerById;
exports.getServersByType = getServersByType;
exports.getEndpointById = getEndpointById;
exports.getEndpointsByType = getEndpointsByType;
exports.Helper = Helper;
exports.deriveTestSuite = deriveTestSuite;
exports.deriveTestSuiteWithnamespace = deriveTestSuiteWithnamespace;
exports.typeName = typeName;
exports.isEqual = isEqual;
exports.compareStringIds = compareStringIds;

let reconnectRetry = exports.reconnectRetry = require('@arangodb/replication-common').reconnectRetry;

/// @brief set failure point
exports.debugCanUseFailAt = function (endpoint) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");

    let res = arango.GET_RAW('/_admin/debug/failat');
    return res.code === 200;
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
};

/// @brief set failure point
exports.debugSetFailAt = function (endpoint, failAt) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");
    let res = arango.PUT_RAW('/_admin/debug/failat/' + failAt, {});
    if (res.parsedBody !== true) {
      throw "Error setting failure point + " + res;
    }
    return true;
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
};

exports.debugResetRaceControl = function (endpoint) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");
    let res = arango.DELETE_RAW('/_admin/debug/raceControl');
    if (res.code !== 200) {
      throw "Error resetting race control.";
    }
    return false;
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
};

/// @brief remove failure point
exports.debugRemoveFailAt = function (endpoint, failAt) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");
    let res = arango.DELETE_RAW('/_admin/debug/failat/' + failAt);
    if (res.code !== 200) {
      throw "Error removing failure point";
    }
    return true;
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
};

exports.debugClearFailAt = function (endpoint) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");
    let res = arango.DELETE_RAW('/_admin/debug/failat');
    if (res.code !== 200) {
      throw "Error removing failure points";
    }
    return true;
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
};

exports.debugGetFailurePoints = function (endpoint) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");
    let haveFailAt = arango.GET("/_admin/debug/failat") === true;
    if (haveFailAt) {
      let res = arango.GET_RAW('/_admin/debug/failat/all');
      if (res.code !== 200) {
        throw "Error checking failure points = " + JSON.stringify(res);
      }
      return res.parsedBody;
    }
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
  return [];
};

exports.getChecksum = function (endpoint, name) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");
    let res = arango.GET_RAW( '/_api/collection/' + name + '/checksum');
    if (res.code !== 200) {
      throw "Error getting collection checksum";
    }
    return res.parsedBody.checksum;
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
};

exports.getMetric = function (endpoint, name) {
  const primaryEndpoint = arango.getEndpoint();
  try {
    reconnectRetry(endpoint, db._name(), "root", "");
    let res = arango.GET_RAW( '/_admin/metrics/v2');
    if (res.code !== 200) {
      throw "error fetching metric";
    }
    let re = new RegExp("^" + name);
    let matches = res.body.split('\n').filter((line) => !line.match(/^#/)).filter((line) => line.match(re));
    if (!matches.length) {
      throw "Metric " + name + " not found";
    }
    return Number(matches[0].replace(/^.* (\d+)$/, '$1'));
  } finally {
    reconnectRetry(primaryEndpoint, "_system", "root", "");
  }
};

const debug = function (text) {
  console.warn(text);
};

const runShell = function(args, prefix) {
  let options = internal.options();

  let endpoint = arango.getEndpoint().replace(/\+vpp/, '').replace(/^http:/, 'tcp:').replace(/^https:/, 'ssl:').replace(/^vst:/, 'tcp:').replace(/^h2:/, 'tcp:');
  let moreArgs = {
    'javascript.startup-directory': options['javascript.startup-directory'],
    'server.endpoint': endpoint,
    'server.database': arango.getDatabaseName(),
    'server.username': arango.connectedUser(),
    'server.password': '',
    'server.request-timeout': '10',
    'log.foreground-tty': 'false',
    'log.output': 'file://' + prefix + '.log'
  };
  _.assign(args, moreArgs);
  let argv = internal.toArgv(args);

  for (let o in options['javascript.module-directory']) {
    argv.push('--javascript.module-directory');
    argv.push(options['javascript.module-directory'][o]);
  }

  let result = internal.executeExternal(global.ARANGOSH_BIN, argv, false /*usePipes*/);
  assertTrue(result.hasOwnProperty('pid'));
  let status = internal.statusExternal(result.pid);
  assertEqual(status.status, "RUNNING");
  return result.pid;
};

const buildCode = function(key, command, cn) {
  let file = fs.getTempFile() + "-" + key;
  fs.write(file, `
(function() {
let tries = 0;
while (true) {
  if (++tries % 3 === 0) {
    if (db['${cn}'].exists('stop')) {
      break;
    }
  }
  ${command}
}
let saveTries = 0;
while (++saveTries < 100) {
  try {
    /* saving our status may actually fail because of failure points set */
    db['${cn}'].insert({ _key: "${key}", done: true, iterations: tries });
    break;
  } catch (err) {
    /* try again */
  }
}
})();
  `);

  let args = {'javascript.execute': file};
  let pid = runShell(args, file);
  debug("started client with key '" + key + "', pid " + pid + ", args: " + JSON.stringify(args));
  return { key, file, pid };
};
exports.runShell = runShell;

exports.runParallelArangoshTests = function (tests, duration, cn) {
  assertTrue(fs.isFile(global.ARANGOSH_BIN), "arangosh executable not found!");

  assertFalse(db[cn].exists("stop"));
  let clients = [];
  debug("starting " + tests.length + " test clients");
  try {
    tests.forEach(function (test) {
      let key = test[0];
      let code = test[1];
      let client = buildCode(key, code, cn);
      client.done = false;
      client.failed = true; // assume the worst
      clients.push(client);
    });

    debug("running test for " + duration + " s...");

    internal.sleep(duration);

    debug("stopping all test clients");

    // broad cast stop signal
    assertFalse(db[cn].exists("stop"));
    let saveTries = 0;
    while (++saveTries < 100) {
      try {
        // saving our stop signal may actually fail because of failure points set
        db[cn].insert({ _key: "stop" }, { overwriteMode: "ignore" });
        break;
      } catch (err) {
        // try again
      }
    }
    let tries = 0;
    const allClientsDone = () => clients.every(client => client.done);
    while (++tries < 120) {
      clients.forEach(function (client) {
        if (!client.done) {
          let status = internal.statusExternal(client.pid);
          if (status.status === 'NOT-FOUND' || status.status === 'TERMINATED') {
            client.done = true;
          }
          if (status.status === 'TERMINATED' && status.exit === 0) {
            client.failed = false;
          }
        }
      });

      if (allClientsDone()) {
        break;
      }

      internal.sleep(0.5);
    }

    if (!allClientsDone()) {
      console.warn("Not all shells could be joined!");
    }
  } finally {
    clients.forEach(function(client) {
      try {
        fs.remove(client.file);
      } catch (err) { }

      const logfile = client.file + '.log';
      if (client.failed) {
        if (fs.exists(logfile)) {
          debug("test client with pid " + client.pid + " has failed and wrote logfile: " + fs.readFileSync(logfile).toString());
        } else {
          debug("test client with pid " + client.pid + " has failed and did not write a logfile");
        }
      }
      try {
        fs.remove(logfile);
      } catch (err) { }

      if (!client.done) {
        // hard-kill all running instances
        try {
          let status = internal.statusExternal(client.pid).status;
          if (status === 'RUNNING') {
            debug("forcefully killing test client with pid " + client.pid);
            internal.killExternal(client.pid, 9 /*SIGKILL*/);
          }
        } catch (err) { }
      }
    });
  }
  return clients;
};

exports.waitForShardsInSync = function(cn, timeout) {
  if (!timeout) {
    timeout = 300;
  }
  let start = internal.time();
  while (true) {
    if (internal.time() - start > timeout) {
      assertTrue(false, "Shards were not getting in sync in time, giving up!");
      return;
    }
    let shardDistribution = arango.GET("/_admin/cluster/shardDistribution");
    assertFalse(shardDistribution.error);
    assertEqual(200, shardDistribution.code);
    let collInfo = shardDistribution.results[cn];
    let shards = Object.keys(collInfo.Plan);
    let insync = 0;
    for (let s of shards) {
      if (collInfo.Plan[s].followers.length === collInfo.Current[s].followers.length) {
        ++insync;
      }
    }
    if (insync === shards.length) {
      return;
    }
    console.warn("insync=", insync, ", collInfo=", collInfo, internal.time() - start);
    internal.wait(1);
  }
};

redpajama_set_name: RedPajamaGithub


text:
package com.bitdubai.fermat_p2p_plugin.layer.communication.cloud_client.developer.bitdubai;

import com.bitdubai.fermat_api.Plugin;
import com.bitdubai.fermat_api.PluginDeveloper;
import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency;
import com.bitdubai.fermat_api.layer.all_definition.enums.TimeFrequency;
import com.bitdubai.fermat_api.layer.all_definition.license.PluginLicensor;
import com.bitdubai.fermat_p2p_plugin.layer.communication.cloud_client.developer.bitdubai.version_1.CloudClientCommunicationChannelPluginRoot;

/**
 * Created by ciencias on 20.01.15.
 */
public class DeveloperBitDubai implements PluginDeveloper, PluginLicensor {

    Plugin plugin;

    @Override
    public Plugin getPlugin() {
        return plugin;
    }

    public DeveloperBitDubai () {

        /**
         * I will choose from the different versions of my implementations which one to start. Now there is only one, so
         * it is easy to choose.
         */

        plugin = new CloudClientCommunicationChannelPluginRoot();

    }

    @Override
    public int getAmountToPay() {
        return 100;
    }

    @Override
    public CryptoCurrency getCryptoCurrency() {
        return CryptoCurrency.BITCOIN;
    }

    @Override
    public String getAddress() {
        return "13gpMizSNvQCbJzAPyGCUnfUGqFD8ryzcv";
    }

    @Override
    public TimeFrequency getTimePeriod() {
        return TimeFrequency.MONTHLY;
    }
}


text:
This is only a collection of programming fonts,just share this with the programmers.

#### Copyright Declaration:

All the fonts are from the internet.If I have copyright infringement,please tell me to remove the fonts.

#### The following fonts are here:

1.Source Code Pro

| Information         | Description
| ------------------- | -----------
| Designer(s)         | [Paul D. Hunt](http://www.adobe.com/products/type/font-designers/paul-hunt.html)
| Foundry             | [Adobe Systems](http://www.adobe.com/)
| Date created        | 2012
| License             | [SIL Open Font License](https://en.wikipedia.org/wiki/SIL_Open_Font_License)

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Source-Code-Pro/font-source-code-pro-sample.png "Font Source Code Pro Sample")

Source Code Pro/Extra Light/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Source-Code-Pro/programming-font-source-code-pro-display-result.png "Programming Font Source Code Pro Display Result")

2.Courier New

| Information         | Description
| ------------------- | -----------
| Classification      | [Slab serif](https://en.wikipedia.org/wiki/Slab_serif)
| Designer(s)         | [Adrian Frutiger](https://en.wikipedia.org/wiki/Adrian_Frutiger)
| Foundry             | [IBM](http://www.ibm.com)
| Date created        | Unknown

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Courier-New/font-courier-new-sample.png "Font Courier New Sample")

Courier New/Regular/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Courier-New/programming-font-courier-new-display-result.png "Programming Font Courier New Display Result")

3.Andale Mono

| Information         | Description
| ------------------- | -----------
| Designer(s)         | [Steve Matteson](https://en.wikipedia.org/wiki/Steve_Matteson)
| Foundry             | [Monotype Imaging, Inc.](https://en.wikipedia.org/wiki/Monotype_Corporation)
| Date created        | Unknown

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Andale-Mono/font-andale-mono-sample.png "Font Andale Mono Sample")

Andale Mono/Regular/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Andale-Mono/programming-font-andale-mono-display-result.png "Programming Font Andale Mono Display Result")

4.Monaco

| Information         | Description
| ------------------- | -----------
| Designer(s)         | [Susan Kare](https://en.wikipedia.org/wiki/Susan_Kare) [Kris Holmes](https://en.wikipedia.org/wiki/Kris_Holmes)
| Foundry             | [Apple Inc.](http://www.apple.com/)
| Date created        | Unknown

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Monaco/font-monaco-sample.png "Font Monaco Sample")

Monaco/Regular/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Monaco/programming-font-monaco-display-result.png "Programming Font Monaco Display Result")

5.Monofur

| Information         | Description
| ------------------- | -----------
| Designer(s)         | Tobias Benjamin Köhler
| Date created        | Unknown

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Monofur/font-monofur-sample.png "Font Monofur Sample")

Monofur/Regular/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Monofur/programming-font-monofur-display-result.png "Programming Font Monofur Display Result")

6.Proggy

| Information         | Description
| ------------------- | -----------
| Designer(s)         | Tristan Grimmer
| Official Site       | [http://www.upperbounds.net/](http://www.upperbounds.net/)

ProggyCleanTT/Regular/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Proggy/programming-font-proggy-display-result.png "Programming Font Proggy Display Result")

7.Droid Sans Mono

| Information         | Description
| ------------------- | -----------
| Designer(s)         | [Steve Matteson](https://en.wikipedia.org/wiki/Steve_Matteson)
| Foundry             | [Ascender Corp.](https://en.wikipedia.org/wiki/Ascender_Corporation)
| Date created        | Unknown
| License             | [Apache License](https://en.wikipedia.org/wiki/Apache_License)

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Droid-Sans-Mono/font-droid-sans-mono-sample.png "Font Droid Sans Mono Sample")

Droid Sans Mono/Regular/14:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Droid-Sans-Mono/programming-font-droid-sans-mono-display-result.png "Programming Font Droid Sans Mono Display Result")

8.Deja Vu Sans Mono

| Information         | Description
| ------------------- | -----------
| Designer(s)         | Deja Vu
| Date created        | 2004
| License             | [Bitstream Vera Fonts Copyright](http://dejavu-fonts.org/wiki/License),[Arev Fonts Copyright](http://dejavu-fonts.org/wiki/License)
| Official Site       | [http://dejavu-fonts.org/wiki/Main_Page](http://dejavu-fonts.org/wiki/Main_Page)

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Deja-Vu-Sans-Mono/font-deja-vu-sans-mono-sample.png "Font Deja Vu Sans Mono Sample")

Deja Vu Sans Mono/Book/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Deja-Vu-Sans-Mono/programming-font-deja-vu-sans-mono-display-result.png "Programming Font Deja Vu Sans Mono Display Result")

9.Consolas

| Information         | Description
| ------------------- | -----------
| Designer(s)         | [Luc(as) de Groot](https://en.wikipedia.org/wiki/Luc(as)_de_Groot)
| Foundry             | [Microsoft](http://www.microsoft.com/)
| Date created        | Unknown

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Consolas/font-consolas-sample.png "Font Consolas Sample")

Consolas/Regular/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Consolas/programming-font-consolas-display-result.png "Programming Font Consolas Display Result")

10.Inconsolata

| Information         | Description
| ------------------- | -----------
| Designer(s)         | [Raph Levien](https://en.wikipedia.org/wiki/Raph_Levien)
| Date created        | 2001
| Design based on     | Consolas, Avenir, Letter Gothic
| License             | [SIL Open Font License](https://en.wikipedia.org/wiki/SIL_Open_Font_License)

Sample:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Inconsolata/font-inconsolata-sample.png "Font Inconsolata Sample")

Inconsolata/Medium/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Inconsolata/programming-font-inconsolata-display-result.png "Programming Font Inconsolata Display Result")

11.Fira Code

| Information         | Description
| ------------------- | -----------
| Designer(s)         | [Nikita Prokopov](https://github.com/tonsky)
| Date created        | 2014
| License             | [SIL Open Font License](https://en.wikipedia.org/wiki/SIL_Open_Font_License)

Fira Code/Regular/16:

![](https://raw.githubusercontent.com/ifeegoo/ifeegoo-programming-fonts-collections/master/Fira-Code/programming-font-fira-code-display-result.png "Programming Font Fira Code Display Result")

#### More Information:

[http://www.ifeegoo.com/recommended-programming-fonts.html](http://www.ifeegoo.com/recommended-programming-fonts.html)

#### Notice:

The fonts here maybe not the latest,and lack of some fonts,but I will update by continuous.

#### Share:

If you have more programming fonts to share with programmers,please tell me in the issues!


text:
[![Build Status](https://travis-ci.org/bloodyowl/class.svg)](https://travis-ci.org/bloodyowl/class)

[![browser support](https://ci.testling.com/bloodyowl/class.png)](https://ci.testling.com/bloodyowl/class)

### Install

```
$ npm install bloody-class
```

### Require

```javascript
var klass = require("bloody-class")
```

### Definition

Classes are objects that contain inherits for instances.
You can extend and create instances of an existing class.
Classes are based on prototypal inheritance, that way, you can easily update
all subclasses and instances from one of their parent class.

### Methods

#### `klass.extend([object])` -> `newClass`

Creates a new class that inherits from `klass`. Optionaly takes an `object`
arguments that extends the `newClass` as owned properties.

##### `object`

- `object.mixins` : array

list of classes the given class should compose with.

#### `klass.create([args …])` -> `newInstance`

Creates a new instance that inherits from `klass`. Its arguments are passed to
`klass.constructor` which is called if `klass` owns a `constructor` method.

#### `instance.destroy([args …])`

Removes all the internal references to `instance`, as in `parent.instances` for
instance. Its arguments are passed to `klass.destructor` which is called if
`klass` owns a `destructor` method.

#### `instance.accessor(name) > function`

Returns a function that calls `instance[name]` with `instance` as `thisValue`
and passes its arguments to the method.

### Example

```javascript
var klass = require("bloody-class")
var $ = require("jquery")

var view = klass.extend({
  constructor : function(){
    this.element = $(this.element || document.createElement("div"))
    if(typeof this.name != "string") {
      throw new TypeError("name must be a string")
    }
    if(typeof this.initialise == "function") {
      this.initialise.apply(this, arguments)
    }
    this.initEvent()
  },
  $ : function(selector){
    return this.element.find(selector)
  },
  destructor : function(){
    this.element.off("." + this.name)
    if(typeof this.release == "function") {
      this.release.apply(this, arguments)
    }
  },
  initEvent : function(){
    if(!this.events) return
    var index = -1
    var length = this.events.length
    var thisValue = this
    while(++index < length) {
      ;(function(object){
        this.element.on(
          object.type + ("." + this.name),
          object.selector,
          function() {
            return thisValue[object.listener]
              .apply(thisValue, arguments)
          }
        )
      }).call(this, this.events[index])
    }
  }
})

var myView = view.create({
  name : "elementView",
  element : "#element",
  mixins : [events],
  events : [
    {
      type : "click",
      selector : ".js-anchor"
      listener : "navigateTo"
    }
  ],
  navigateTo : function(eventObject){
    window.scrollTo(0, $(eventObject.currentTarget).offset().top)
  }
})
```


text:
package lithium.classloadertest.impl;

import lithium.classloadertest.common.TransformingURLClassLoader.ClassTransformer;

import net.sf.cglib.asm.AnnotationVisitor;
import net.sf.cglib.asm.Attribute;
import net.sf.cglib.asm.ClassReader;
import net.sf.cglib.asm.ClassVisitor;
import net.sf.cglib.asm.ClassWriter;
import net.sf.cglib.asm.FieldVisitor;
import net.sf.cglib.asm.Label;
import net.sf.cglib.asm.MethodVisitor;
import net.sf.cglib.asm.Opcodes;

/**
 * Transforms the bytes of a class to remove all final designation on Classes, Methods and Fields as
 * well as making private and protected members and the class itself public.  Useful when creating
 * a fresh classloader as it will make the specified classes more testable with mocking and proxying frameworks.
 *
 * @author jeff.collins
 */
public class UnfinalizingClassTransformer implements ClassTransformer {

	@Override
	public byte[] transformClass(byte[] inputClass) {
		ClassReader classReader = new ClassReader(inputClass);
		ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_MAXS);
		UnfinalizingClassVisitor ufcv = new UnfinalizingClassVisitor(classWriter);
		classReader.accept(ufcv, 0);
		return classWriter.toByteArray();
	}

	/**
	 *
	 * @author jeff.collins
	 *
	 */
	private class UnfinalizingClassVisitor implements ClassVisitor {
		private final ClassVisitor cv;
		private String className;

		public UnfinalizingClassVisitor(ClassVisitor cv) {
			this.cv = cv;
		}

		private int removeFinalAndMakePublic(int access) {
			// change modifier.
			if ((access & Opcodes.ACC_PRIVATE) == Opcodes.ACC_PRIVATE)
				access -= Opcodes.ACC_PRIVATE;
			if ((access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED)
				access -= Opcodes.ACC_PROTECTED;
			access |= Opcodes.ACC_PUBLIC;
			if ((access & Opcodes.ACC_FINAL) != 0) {
				access -= Opcodes.ACC_FINAL;
			}
			return access;
		}

		@Override
		public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
			className = name;
			cv.visit(version, removeFinalAndMakePublic(access), name, signature, superName, interfaces);
		}

		@Override
		public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
			return cv.visitAnnotation(desc, visible);
		}

		@Override
		public void	visitAttribute(Attribute attr) {
			cv.visitAttribute(attr);
		}

		@Override
		public void	visitEnd() {
			cv.visitEnd();
		}

		@Override
		public FieldVisitor	visitField(int access, String name, String desc, String signature, Object value) {
			return cv.visitField(removeFinalAndMakePublic(access), name, desc, signature, value);
		}

		@Override
		public void	visitInnerClass(String name, String outerName, String innerName, int access) {
			cv.visitInnerClass(name, outerName, innerName, removeFinalAndMakePublic(access));
		}

		@Override
		public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
			MethodVisitor mv = cv.visitMethod(removeFinalAndMakePublic(access), name, desc, signature, exceptions);
			return new UnprivatizingMethodVisitor(mv, className);
		}

		@Override
		public void	visitOuterClass(String owner, String name, String desc) {
			cv.visitOuterClass(owner, name, desc);
		}

		@Override
		public void visitSource(String source, String debug) {
			cv.visitSource(source, debug);
		}
	}

	/*
	 * Modifies calls to private methods to use InvokeVirtual instead of InvokeSpecial.  Without this,
	 * private helper methods in a test class will not by overridden by dynamically created proxies, and instead
	 * the private method will be called directly.
	 */
	class UnprivatizingMethodVisitor implements MethodVisitor {
		private final MethodVisitor mv;
		private final String className;

		public UnprivatizingMethodVisitor(MethodVisitor mv, String className) {
			this.mv = mv;
			this.className = className;
		}

		@Override
		public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
			return mv.visitAnnotation(desc, visible);
		}

		@Override
		public AnnotationVisitor visitAnnotationDefault() {
			return mv.visitAnnotationDefault();
		}

		@Override
		public void visitAttribute(Attribute attr) {
			mv.visitAttribute(attr);
		}

		@Override
		public void visitCode() {
			mv.visitCode();
		}

		@Override
		public void visitEnd() {
			mv.visitEnd();
		}

		@Override
		public void visitFieldInsn(int opcode, String owner, String name, String desc) {
			mv.visitFieldInsn(opcode, owner, name, desc);
		}

		@Override
		public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
			mv.visitFrame(type, nLocal, local, nStack, stack);
		}

		@Override
		public void visitIincInsn(int var, int increment) {
			mv.visitIincInsn(var, increment);
		}

		@Override
		public void visitInsn(int opcode) {
			mv.visitInsn(opcode);
		}

		@Override
		public void visitIntInsn(int opcode, int operand) {
			mv.visitIntInsn(opcode, operand);
		}

		@Override
		public void visitJumpInsn(int opcode, Label label) {
			mv.visitJumpInsn(opcode, label);
		}

		@Override
		public void visitLabel(Label label) {
			mv.visitLabel(label);
		}

		@Override
		public void visitLdcInsn(Object cst) {
			mv.visitLdcInsn(cst);
		}

		@Override
		public void visitLineNumber(int line, Label start) {
			mv.visitLineNumber(line, start);
		}

		@Override
		public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
			mv.visitLocalVariable(name, desc, signature, start, end, index);
		}

		@Override
		public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
			mv.visitLookupSwitchInsn(dflt, keys, labels);
		}

		@Override
		public void visitMaxs(int maxStack, int maxLocals) {
			mv.visitMaxs(maxStack, maxLocals);
		}

		@Override
		public void visitMethodInsn(int opcode, String owner, String name, String desc) {
			if (opcode == Opcodes.INVOKESPECIAL && !name.equals("<init>") && className.equals(owner)) {
				// if the method we're calling is private (because of the invokespecial designation, and
				// is not a constructor, and not from another class, change to calling with InvokeVirtual
				// which will allow use of the virtual tables, and thus overriding by a proxy subclass...
				opcode = Opcodes.INVOKEVIRTUAL;
			}
			mv.visitMethodInsn(opcode, owner, name, desc);
		}

		@Override
		public void visitMultiANewArrayInsn(String desc, int dims) {
			mv.visitMultiANewArrayInsn(desc, dims);
		}

		@Override
		public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) {
			return mv.visitParameterAnnotation(parameter, desc, visible);
		}

		@Override
		public void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels) {
			mv.visitTableSwitchInsn(min, max, dflt, labels);
		}

		@Override
		public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
			mv.visitTryCatchBlock(start, end, handler, type);
		}

		@Override
		public void visitTypeInsn(int opcode, String type) {
			mv.visitTypeInsn(opcode, type);
		}

		@Override
		public void visitVarInsn(int opcode, int var) {
			mv.visitVarInsn(opcode, var);
		}

	}

}


text:
package org.hippoecm.repository;

import java.security.AccessControlException;

import javax.jcr.Credentials;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.onehippo.repository.testutils.RepositoryTestCase;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class MissingReferenceAuthorizationTest extends RepositoryTestCase {

    private Node testDomain;

    @Before
    public void setUp() throws Exception {
        super.setUp();

        // create content
        final Node root = session.getRootNode();
        final Node test = root.addNode("test");
        final Node folder = test.addNode("folder", "hippostd:folder");
        folder.setProperty("hippostd:foldertype", new String[]{"foo", "bar"});
        final Node authDocument = folder.addNode("authDocument", "hippo:authtestdocument");
        authDocument.setProperty("authDocumentProp", "foo");
        final Node compound = authDocument.addNode("compound", "hippo:authtestdocument");
        compound.setProperty("compoundProp", "bar");
        final Node testDocument = folder.addNode("testDocument", "hippo:testdocument");
        testDocument.setProperty("testDocumentProp", "lux");

        // create test user
        final Node users = session.getNode("/hippo:configuration/hippo:users");
        final Node user = users.addNode("testUser", "hipposys:user");
        user.setProperty("hipposys:password", "password");

        // create test domain
        final Node domains = session.getNode("/hippo:configuration/hippo:domains");
        testDomain = domains.addNode("testDomain", "hipposys:domain");

        // test user is admin in test domain
        final Node authRole = testDomain.addNode("authRole", "hipposys:authrole");
        authRole.setProperty("hipposys:users", new String[]{ "testUser" });
        authRole.setProperty("hipposys:role", "admin");

        session.save();
    }

    @After
    @Override
    public void tearDown() throws Exception {
        removeNode("/hippo:configuration/hippo:users/testUser");
        removeNode("/hippo:configuration/hippo:domains/testDomain");
        super.tearDown();
    }

    @Test(expected = AccessControlException.class)
    public void one_true_missing_reference_in_facet_rule_domain_rule() throws Exception {

        // domain with single facet rule that has equals = true & non existing reference
        // should result in no read access below /test/folder

        final Node domainRule = testDomain.addNode("domainrule", "hipposys:domainrule");
        createFacetRule(domainRule, true, "jcr:path", "Reference", "/test/folder/non/existing");
        session.save();

        Session testSession = null;
        try {
            testSession = loginTestUser();
            assertTrue(testSession.nodeExists("/test"));
            assertFalse(testSession.nodeExists("/test/folder"));
            testSession.checkPermission("/test/folder", "jcr:read");
        } finally {
            if (testSession != null) {
                testSession.logout();
            }
        }
    }

    @Test(expected = AccessControlException.class)
    public void one_false_missing_reference_in_facet_rule_domain_rule() throws Exception {

        // domain with single facet rule that has equals = false & non existing reference
        // should result in no read access below /test/folder

        final Node domainRule = testDomain.addNode("domainRule", "hipposys:domainrule");
        createFacetRule(domainRule, false, "jcr:path", "Reference", "/test/folder/non/existing");
        session.save();

        Session testSession = null;
        try {
            testSession = loginTestUser();
            assertTrue(testSession.nodeExists("/test"));
            assertFalse(testSession.nodeExists("/test/folder"));
            testSession.checkPermission("/test/folder", "jcr:read");
        } finally {
            if (testSession != null) {
                testSession.logout();
            }
        }
    }

    @Test(expected = AccessControlException.class)
    public void combined_true_missing_reference_in_facet_rules_domain_rule() throws Exception {

        // domain with two AND-ed facet rules : both have equals = true and one contains
        // non existing reference. Result should be no read access below /test/folder

        final Node domainRule = testDomain.addNode("domainRule", "hipposys:domainrule");
        createFacetRule(domainRule, true, "jcr:path", "Reference", "/test/folder");
        createFacetRule(domainRule, true, "jcr:path", "Reference", "/test/folder/non/existing");
        session.save();

        Session testSession = null;
        try {
            testSession = loginTestUser();
            assertTrue(testSession.nodeExists("/test"));
            assertFalse(testSession.nodeExists("/test/folder"));
            testSession.checkPermission("/test/folder", "jcr:read");
        } finally {
            if (testSession != null) {
                testSession.logout();
            }
        }
    }

    @Test
    public void combined_false_missing_reference_in_facet_rules_domain_rule() throws Exception {

        // domain with two AND-ed facet rules : one rule matches everything below /test/folder
        // and other one has a non-existing reference but has equals = false. Result should be that everything below /test/folder
        // is readable

        final Node domainRule = testDomain.addNode("domainRule", "hipposys:domainrule");
        createFacetRule(domainRule, true, "jcr:path", "Reference", "/test/folder");
        createFacetRule(domainRule, false, "jcr:path", "Reference", "/test/folder/non/existing");
        session.save();

        Session testSession = null;
        try {
            testSession = loginTestUser();

            assertTrue(testSession.nodeExists("/test"));
            assertTrue(testSession.nodeExists("/test/folder"));
            assertTrue(testSession.nodeExists("/test/folder/authDocument"));
            assertTrue(testSession.nodeExists("/test/folder/authDocument/compound"));
            assertTrue(testSession.nodeExists("/test/folder/testDocument"));

            testSession.checkPermission("/test/folder", "jcr:read");
            testSession.checkPermission("/test/folder", "jcr:write");

            testSession.checkPermission("/test/folder/authDocument", "jcr:read");
            testSession.checkPermission("/test/folder/authDocument", "jcr:write");

            testSession.checkPermission("/test/folder/authDocument/compound", "jcr:read");
            testSession.checkPermission("/test/folder/authDocument/compound", "jcr:write");

            testSession.checkPermission("/test/folder/testDocument", "jcr:read");
            testSession.checkPermission("/test/folder/testDocument", "jcr:write");

        } finally {
            if (testSession != null) {
                testSession.logout();
            }
        }
    }

    @Test(expected = AccessControlException.class)
    public void only_true_missing_references_in_facet_rules_domain_rule() throws Exception {

        // domain with two AND-ed facet rules : both have equals = true and one contains
        // non existing reference. Result should be no read access below /test/folder

        final Node domainRule = testDomain.addNode("domainRule", "hipposys:domainrule");
        createFacetRule(domainRule, true, "jcr:path", "Reference", "/test/folder/non/existing/one");
        createFacetRule(domainRule, true, "jcr:path", "Reference", "/test/folder/non/existing/two");
        session.save();

        Session testSession = null;
        try {
            testSession = loginTestUser();
            assertTrue(testSession.nodeExists("/test"));
            assertFalse(testSession.nodeExists("/test/folder"));
            testSession.checkPermission("/test/folder", "jcr:read");
        } finally {
            if (testSession != null) {
                testSession.logout();
            }
        }
    }

    @Test(expected = AccessControlException.class)
    public void only_false_missing_references_in_facet_rules_domain_rule() throws Exception {

        // domain with two AND-ed facet rules : both have equals = true and one contains
        // non existing reference. Result should be no read access below /test/folder

        final Node domainRule = testDomain.addNode("domainRule", "hipposys:domainrule");
        createFacetRule(domainRule, false, "jcr:path", "Reference", "/test/folder/non/existing/one");
        createFacetRule(domainRule, false, "jcr:path", "Reference", "/test/folder/non/existing/two");
        session.save();

        Session testSession = null;
        try {
            testSession = loginTestUser();
            assertTrue(testSession.nodeExists("/test"));
            assertFalse(testSession.nodeExists("/test/folder"));
            testSession.checkPermission("/test/folder", "jcr:read");
        } finally {
            if (testSession != null) {
                testSession.logout();
            }
        }
    }

    @Test
    public void combined_false_missing_reference_UUID_in_facet_rules_domain_rule() throws Exception {

        // domain with two AND-ed facet rules : one rule matches everything below /test/folder
        // and other one has a non-existing reference but has equals = false and with jcr:uuid. Result should be that everything below /test/folder
        // is readable

        final Node domainRule = testDomain.addNode("domainRule", "hipposys:domainrule");
        createFacetRule(domainRule, true, "jcr:path", "Reference", "/test/folder");
        // INSTEAD OF jcr:path now jcr:uuid !!!!!!!!!!!!!!!!!!!!!!!!!!!!
        createFacetRule(domainRule, false, "jcr:uuid", "Reference", "/test/folder/non/existing");
        session.save();

        Session testSession = null;
        try {
            testSession = loginTestUser();

            assertTrue(testSession.nodeExists("/test"));
            assertTrue(testSession.nodeExists("/test/folder"));
            assertTrue(testSession.nodeExists("/test/folder/authDocument"));
            assertTrue(testSession.nodeExists("/test/folder/authDocument/compound"));
            assertTrue(testSession.nodeExists("/test/folder/testDocument"));

            testSession.checkPermission("/test/folder", "jcr:read");
            testSession.checkPermission("/test/folder", "jcr:write");

            testSession.checkPermission("/test/folder/authDocument", "jcr:read");
            testSession.checkPermission("/test/folder/authDocument", "jcr:write");

            testSession.checkPermission("/test/folder/authDocument/compound", "jcr:read");
            testSession.checkPermission("/test/folder/authDocument/compound", "jcr:write");

            testSession.checkPermission("/test/folder/testDocument", "jcr:read");
            testSession.checkPermission("/test/folder/testDocument", "jcr:write");

        } finally {
            if (testSession != null) {
                testSession.logout();
            }
        }
    }

    private Session loginTestUser() throws RepositoryException {
        return server.login(new SimpleCredentials("testUser", "password".toCharArray()));
    }

    private void createFacetRule(final Node domainRule, boolean equals, String facet, String type, String value) throws RepositoryException {
        final Node facetRule = domainRule.addNode("hippo:facetrule", "hipposys:facetrule");
        facetRule.setProperty("hipposys:equals", equals);
        facetRule.setProperty("hipposys:facet", facet);
        facetRule.setProperty("hipposys:type", type);
        facetRule.setProperty("hipposys:value", value);
    }

}


text:
package com.vaadin.v7.tests.components.textfield;

import com.vaadin.tests.components.TestBase;
import com.vaadin.tests.util.Log;
import com.vaadin.v7.data.Property.ValueChangeEvent;
import com.vaadin.v7.data.Property.ValueChangeListener;
import com.vaadin.v7.event.FieldEvents.TextChangeEvent;
import com.vaadin.v7.event.FieldEvents.TextChangeListener;
import com.vaadin.v7.ui.TextField;

public class TextChangeEventsWithNonImmediateValueChange extends TestBase {
    Log l = new Log(5);

    @Override
    protected void setup() {

        TextField tf = new TextField("Default");

        TextChangeListener inputEventListener = new TextChangeListener() {

            @Override
            public void textChange(TextChangeEvent event) {
                l.log("Text change event, text content currently:'"
                        + event.getText() + "' Cursor at index:"
                        + event.getCursorPosition());
            }
        };

        tf.addTextChangeListener(inputEventListener);

        // tf.setImmediate(true); // works when this is set

        tf.addListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                l.log("Value change: '" + event.getProperty().getValue() + "'");
            }
        });

        getLayout().addComponent(tf);

        getLayout().addComponent(l);
    }

    @Override
    protected String getDescription() {
        return "Type a, pause for a second, type ENTER,  type a. Text field should not forget the last textchange event right after valuechange (enter)."
                + "<br />Then press backspace. The text field should send a text change event even though the text in the field is the same as the field's value";
    }

    @Override
    protected Integer getTicketNumber() {
        return 6866;
    }

}


text:
package com.hymane.materialhome.ui.adapter;

import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hymane.materialhome.R;
import com.hymane.materialhome.bean.http.douban.BookReviewResponse;
import com.hymane.materialhome.bean.http.douban.BookReviewsListResponse;
import com.hymane.materialhome.utils.common.UIUtils;

import java.util.List;

/**
 * Author   :hymanme
 * Email    :hymanme@163.com
 * Create at 2016/1/9 0009
 */
public class BookReviewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_EMPTY = 0;
    private static final int TYPE_DEFAULT = 1;
    private static final int AVATAR_SIZE_DP = 24;
    private final BookReviewsListResponse reviewsListResponse;

    public BookReviewsAdapter(BookReviewsListResponse responses) {
        this.reviewsListResponse = responses;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        if (viewType == TYPE_DEFAULT) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book_comment, parent, false);
            return new BookCommentHolder(view);
        } else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_empty, parent, false);
            return new EmptyHolder(view);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (reviewsListResponse.getReviews() == null || reviewsListResponse.getReviews().isEmpty()) {
            return TYPE_EMPTY;
        } else {
            return TYPE_DEFAULT;
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof BookCommentHolder) {
            List<BookReviewResponse> reviews = reviewsListResponse.getReviews();
            Glide.with(UIUtils.getContext())
                    .load(reviews.get(position).getAuthor().getAvatar())
                    .asBitmap()
                    .centerCrop()
                    .into(new BitmapImageViewTarget(((BookCommentHolder) holder).iv_avatar) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            RoundedBitmapDrawable circularBitmapDrawable =
                                    RoundedBitmapDrawableFactory.create(UIUtils.getContext().getResources(), resource);
                            circularBitmapDrawable.setCircular(true);
                            ((BookCommentHolder) holder).iv_avatar.setImageDrawable(circularBitmapDrawable);
                        }
                    });
            ((BookCommentHolder) holder).tv_user_name.setText(reviews.get(position).getAuthor().getName());
            if (reviews.get(position).getRating() != null) {
                ((BookCommentHolder) holder).ratingBar_hots.setRating(Float.valueOf(reviews.get(position).getRating().getValue()));
            }
            ((BookCommentHolder) holder).tv_comment_content.setText(reviews.get(position).getSummary());
            ((BookCommentHolder) holder).tv_favorite_num.setText(reviews.get(position).getVotes() + "");
            ((BookCommentHolder) holder).tv_update_time.setText(reviews.get(position).getUpdated().split(" ")[0]);
        }
    }

    @Override
    public int getItemCount() {
        return reviewsListResponse.getReviews().size();
    }

    class BookCommentHolder extends RecyclerView.ViewHolder {
        //        private TextView tv_comment_title;
        private ImageView iv_avatar;
        private TextView tv_user_name;
        private AppCompatRatingBar ratingBar_hots;
        private TextView tv_comment_content;
        //        private ImageView iv_favorite;
        private TextView tv_favorite_num;
        private TextView tv_update_time;
//        private TextView tv_more_comment;

        public BookCommentHolder(View itemView) {
            super(itemView);
//            tv_comment_title = (TextView) itemView.findViewById(R.id.tv_comment_title);
            iv_avatar = (ImageView) itemView.findViewById(R.id.iv_avatar);
            tv_user_name = (TextView) itemView.findViewById(R.id.tv_user_name);
            ratingBar_hots = (AppCompatRatingBar) itemView.findViewById(R.id.ratingBar_hots);
            tv_comment_content = (TextView) itemView.findViewById(R.id.tv_comment_content);
//            iv_favorite = (ImageView) itemView.findViewById(R.id.iv_favorite);
            tv_favorite_num = (TextView) itemView.findViewById(R.id.tv_favorite_num);
            tv_update_time = (TextView) itemView.findViewById(R.id.tv_update_time);
//            tv_more_comment = (TextView) itemView.findViewById(R.id.tv_more_comment);
        }
    }

    class EmptyHolder extends RecyclerView.ViewHolder {

        public EmptyHolder(View itemView) {
            super(itemView);
        }
    }
}


text:
import logging
import numpy as np

from neon import NervanaObject

logging.basicConfig(level=20)
logger = logging.getLogger()

def test_dropout(backend_default):
    ng = NervanaObject.be
    ng.bsz = ng.batch_size = 15

    d_array2 = ng.array(np.random.randn(24).reshape((6, 4)), dtype=np.float32)
    d_error = ng.array(np.random.randn(24).reshape((6, 4)), dtype=np.float32)
    mask = ng.empty((6, 4))

    logger.info("FPROP")
    print d_array2.get()
    # d_array2[:] = ng.dropout(0.5) * d_array2
    ng.make_binary_mask(mask, keepthresh=0.5)
    d_array2[:] = mask * d_array2
    print d_array2.get()

    logger.info("BPROP")
    print d_error.get()
    d_error[:] = (d_array2 != 0) * d_error
    print d_error.get()


text:
#include <aws/application-insights/model/Tier.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace ApplicationInsights
  {
    namespace Model
    {
      namespace TierMapper
      {

        static const int CUSTOM_HASH = HashingUtils::HashString("CUSTOM");
        static const int DEFAULT_HASH = HashingUtils::HashString("DEFAULT");
        static const int DOT_NET_CORE_HASH = HashingUtils::HashString("DOT_NET_CORE");
        static const int DOT_NET_WORKER_HASH = HashingUtils::HashString("DOT_NET_WORKER");
        static const int DOT_NET_WEB_TIER_HASH = HashingUtils::HashString("DOT_NET_WEB_TIER");
        static const int DOT_NET_WEB_HASH = HashingUtils::HashString("DOT_NET_WEB");
        static const int SQL_SERVER_HASH = HashingUtils::HashString("SQL_SERVER");
        static const int SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP_HASH = HashingUtils::HashString("SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP");
        static const int MYSQL_HASH = HashingUtils::HashString("MYSQL");
        static const int POSTGRESQL_HASH = HashingUtils::HashString("POSTGRESQL");
        static const int JAVA_JMX_HASH = HashingUtils::HashString("JAVA_JMX");
        static const int ORACLE_HASH = HashingUtils::HashString("ORACLE");

        Tier GetTierForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == CUSTOM_HASH)
          {
            return Tier::CUSTOM;
          }
          else if (hashCode == DEFAULT_HASH)
          {
            return Tier::DEFAULT;
          }
          else if (hashCode == DOT_NET_CORE_HASH)
          {
            return Tier::DOT_NET_CORE;
          }
          else if (hashCode == DOT_NET_WORKER_HASH)
          {
            return Tier::DOT_NET_WORKER;
          }
          else if (hashCode == DOT_NET_WEB_TIER_HASH)
          {
            return Tier::DOT_NET_WEB_TIER;
          }
          else if (hashCode == DOT_NET_WEB_HASH)
          {
            return Tier::DOT_NET_WEB;
          }
          else if (hashCode == SQL_SERVER_HASH)
          {
            return Tier::SQL_SERVER;
          }
          else if (hashCode == SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP_HASH)
          {
            return Tier::SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP;
          }
          else if (hashCode == MYSQL_HASH)
          {
            return Tier::MYSQL;
          }
          else if (hashCode == POSTGRESQL_HASH)
          {
            return Tier::POSTGRESQL;
          }
          else if (hashCode == JAVA_JMX_HASH)
          {
            return Tier::JAVA_JMX;
          }
          else if (hashCode == ORACLE_HASH)
          {
            return Tier::ORACLE;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<Tier>(hashCode);
          }

          return Tier::NOT_SET;
        }

        Aws::String GetNameForTier(Tier enumValue)
        {
          switch(enumValue)
          {
          case Tier::CUSTOM:
            return "CUSTOM";
          case Tier::DEFAULT:
            return "DEFAULT";
          case Tier::DOT_NET_CORE:
            return "DOT_NET_CORE";
          case Tier::DOT_NET_WORKER:
            return "DOT_NET_WORKER";
          case Tier::DOT_NET_WEB_TIER:
            return "DOT_NET_WEB_TIER";
          case Tier::DOT_NET_WEB:
            return "DOT_NET_WEB";
          case Tier::SQL_SERVER:
            return "SQL_SERVER";
          case Tier::SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP:
            return "SQL_SERVER_ALWAYSON_AVAILABILITY_GROUP";
          case Tier::MYSQL:
            return "MYSQL";
          case Tier::POSTGRESQL:
            return "POSTGRESQL";
          case Tier::JAVA_JMX:
            return "JAVA_JMX";
          case Tier::ORACLE:
            return "ORACLE";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace TierMapper
    } // namespace Model
  } // namespace ApplicationInsights
} // namespace Aws


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2018 Regents of the University of Minnesota.
  ~
  ~ 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.
  -->

<analysisEngineDescription xmlns="http://uima.apache.org/resourceSpecifier">
  <frameworkImplementation>org.apache.uima.java</frameworkImplementation>
  <primitive>true</primitive>
  <annotatorImplementationName>edu.umn.biomedicus.uima.util.AnnotationVerifier
  </annotatorImplementationName>
  <analysisEngineMetaData>
    <name>Annotation Verifier</name>
    <description>Verifies annotations</description>
    <version>${project.version}</version>
    <vendor>${organization.name}</vendor>
    <operationalProperties>
      <modifiesCas>false</modifiesCas>
      <multipleDeploymentAllowed>true</multipleDeploymentAllowed>
      <outputsNewCASes>false</outputsNewCASes>
    </operationalProperties>
  </analysisEngineMetaData>
</analysisEngineDescription>


text:
class Gizmo {
  public void spin() {}
}

public class FinalArguments {
  void with(final Gizmo g) {
    //! g = new Gizmo(); // Illegal -- g is final
  }
  void without(Gizmo g) {
    g = new Gizmo(); // OK -- g not final
    g.spin();
  }
  // void f(final int i) { i++; } // Can't change
  // You can only read from a final primitive:
  int g(final int i) { return i + 1; }
  public static void main(String[] args) {
    FinalArguments bf = new FinalArguments();
    bf.without(null);
    bf.with(null);
  }
} ///:~


text:
package context

import (
	"path/filepath"
	"testing"
)

// Tests if initializing an OrbitContext throws an error
// with wrong parameters or no error if the parameters are OK.
func TestNewOrbitContext(t *testing.T) {
	// case 1: uses an empty template file path.
	if _, err := NewOrbitContext("", "", "", nil); err == nil {
		t.Error("OrbitContext should not have been instantiated!")
	}

	// case 2: uses a non existing template file path.
	if _, err := NewOrbitContext("non_existing_file", "", "", nil); err == nil {
		t.Error("OrbitContext should not have been instantiated!")
	}

	// case 3: uses an existing template file path.
	templateFilePath, _ := filepath.Abs("../../_tests/template.yml")
	if _, err := NewOrbitContext(templateFilePath, "", "", nil); err != nil {
		t.Error("OrbitContext should have been instantiated!")
	}

	// case 4: uses a broken payload string.
	if _, err := NewOrbitContext(templateFilePath, "key", "", nil); err == nil {
		t.Error("OrbitContext should not have been instantiated!")
	}

	// case 5: uses a correct payload string.
	if _, err := NewOrbitContext(templateFilePath, "key,value", "", nil); err != nil {
		t.Error("OrbitContext should have been instantiated!")
	}

	// case 6: uses a broken payload entry.
	brokenPayloadEntryFilePath, _ := filepath.Abs("../../_tests/broken-data-source.yml")
	if _, err := NewOrbitContext(templateFilePath, "key,"+brokenPayloadEntryFilePath, "", nil); err == nil {
		t.Error("OrbitContext should not have been instantiated!")
	}

	// case 7: uses a correct payload entry.
	payloadEntryFilePath, _ := filepath.Abs("../../_tests/data-source.yml")
	if _, err := NewOrbitContext(templateFilePath, "key,"+payloadEntryFilePath, "", nil); err != nil {
		t.Error("OrbitContext should have been instantiated!")
	}

	// case 8: uses a nil template delimiter set
	if _, err := NewOrbitContext(templateFilePath, "", "", nil); err != nil {
		t.Error("OrbitContext should have been instantiated!")
	}

	// case 9: uses a valid, two-element delimiter set
	templateDelimiters := []string{"a", "b"}
	if _, err := NewOrbitContext(templateFilePath, "", "", templateDelimiters); err != nil {
		t.Error("OrbitContext should have been instantiated!")
	}

	// case 10: uses an invalid, empty delimiter set
	templateDelimiters = []string{}
	if _, err := NewOrbitContext(templateFilePath, "", "", templateDelimiters); err == nil {
		t.Error("OrbitContext should not have been instantiated!")
	}

	// case 11: uses an invalid, one-element delimiter set
	templateDelimiters = []string{"a"}
	if _, err := NewOrbitContext(templateFilePath, "", "", templateDelimiters); err == nil {
		t.Error("OrbitContext should not have been instantiated!")
	}

	// case 12: uses an invalid, three-element delimiter set
	templateDelimiters = []string{"a", "b", "c"}
	if _, err := NewOrbitContext(templateFilePath, "", "", templateDelimiters); err == nil {
		t.Error("OrbitContext should not have been instantiated!")
	}
}


text:
<?php

namespace DalaiLomo\ACE\Process;

use DalaiLomo\ACE\Helper\CommandOutputHelper;
use React\ChildProcess\Process;
use React\EventLoop\LoopInterface;
use React\Stream\Stream;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ProcessGroup
{
    const PERIODIC_TIMER_INTERVAL = 0.5;

    /**
     * @var LoopInterface
     */
    private $loop;

    /**
     * @var InputInterface
     */
    private $input;

    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * @var array
     */
    private $commandsOutput = [];

    /**
     * @var ProcessMonitoring
     */
    private $processMonitoring;

    public function __construct(LoopInterface $loop, InputInterface $input, OutputInterface $output)
    {
        $this->loop = $loop;
        $this->input = $input;
        $this->output = $output;
    }

    public function add(Process $process)
    {
        $process->start($this->loop);

        /** @var Stream $stdout */
        $stdout = $process->stdout;

        /** @var Stream $stderr */
        $stderr = $process->stderr;

        $process->on('exit', function() use($process) {
            $this->onProcessExit($process);
        });

        $stdout->on('data', function($streamOutput) use($process) {
            $this->onProcessSTDOUT($process, $streamOutput);
        });

        $stderr->on('data', function($streamOutput) use($process) {
            $this->onProcessSTDERR($process, $streamOutput);
        });

        if ($this->processMonitoring) {
            $this->processMonitoring->add($process);
        }
    }

    public function addProcessMonitoring(ProcessMonitoring $processMonitoring)
    {
        $this->processMonitoring = $processMonitoring;
    }

    public function runLoop()
    {
        if ($this->processMonitoring) {
            $this->loop->addPeriodicTimer(self::PERIODIC_TIMER_INTERVAL, $this->processMonitoring->onPeriodicTimerTick());
        }

        $this->loop->run();
    }

    public function getCommandsOutput()
    {
        return $this->commandsOutput;
    }

    private function onProcessExit(Process $process)
    {
        $this->output->writeln(
            sprintf(
                "Finished <fg=magenta>%s</> : <info>%s</info> : Exit code (<fg=%s>%s</>)",
                $process->getPid(),
                $process->getCommand(),
                ($process->getExitCode() === 0) ? 'green' : 'red',
                $process->getExitCode()
            )
        );
    }

    private function onProcessSTDOUT(Process $process, $streamOutput)
    {
        $this->collectOutput('stdout', $process->getPid(), $streamOutput, $process->getCommand());
    }

    private function onProcessSTDERR(Process $process, $streamOutput)
    {
        $this->collectOutput('stderr', $process->getPid(), $streamOutput, $process->getCommand());

        if (false === $this->input->getOption('diagnosis')) {
            return;
        }

        $this->output->writeln(CommandOutputHelper::ninjaSeparator());
        $this->output->writeln(
            sprintf(
                "<fg=blue>Diagnosis output</> <fg=magenta>%s</> : <info>'%s</info>'",
                $process->getPid(),
                $process->getCommand()
            )
        );
        $this->output->writeln("$streamOutput");
    }

    private function collectOutput($stream, $pid, $outputChunk, $command)
    {
        isset($this->commandsOutput[$pid][$command][$stream])
            ? $this->commandsOutput[$pid][$command][$stream] .= $outputChunk
            : $this->commandsOutput[$pid][$command][$stream] = $outputChunk;
    }
}


text:
layout: default
title: "Better understanding floods"
author: Julie Vano
date: 2017-11-16 10:46:43
tags: [news]
categories:
- news
---

A new project, <i> Identifying Sources of Uncertainty in Flood Frequency Analyses</i>, is now underway.  Andrew Newman will lead an effort, working closely with the Bureau of Reclamation, to improve our understanding of uncertainities associated with large flood estimates.  The team will examine hydrologic model structure and parameterization for locations critical to Reclamation's operations.


text:
"""Tests for sudo handling of engage_utils.process and engage.drivers.action.
There are three modes that we can be running in:
 1. If running as root, sudo actions will be transparently run directly
 2. If running as normal user, but no password is needed for sudo access,
    process utilities will call sudo -n.
 3. If running as normal user, and a sudo password is neeed, process
    utilities will call sudo -p "" -S and provide the password via stdin.

If an sudo password is required, the tests cannon be run under Nose - they will
only be available as a command line script. For the other two cases, the tests
will be run.
"""

import sys
import os.path
import getpass
import logging
import time
import optparse
import tempfile

try:
    import engage
except:
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
    import engage

import engage_utils.process as process
import engage.drivers.action as action
from engage.drivers.action import _check_file_exists
import engage.tests.test_common as tc

logger = logging.getLogger()

class TestError(Exception):
    pass

def _assert(pred, msg):
    if not pred:
        raise TestError(msg)

server_log_dir = None

def tst_run_program(sudo_password):
    logger.debug("tst_run_program() Starting")
    process.run_sudo_program(["/bin/ls", "/"], sudo_password,
                             logger)
    process.run_sudo_program(["/bin/ls", "/"], sudo_password,
                             logger, user=getpass.getuser())
    logger.debug("tst_run_program() Successful")

def tst_cat_file(sudo_password):
    """This test relies on the fact that sudo_cat_file() doesn't actually
    check the file permissions, but just returns it"""
    logger.debug("tst_cat_file() Starting")
    data = process.sudo_cat_file(__file__, logger, sudo_password)
    _assert(len(data)>0,
            "Should have gotten length of this test file, instead got 0")
    logger.debug("tst_cat_file() Successful")

def tst_run_sudo_program_and_scan_results(sudo_password):
    logger.debug("tst_run_sudo_program_and_scan_results() Starting")
    cmd = ["/bin/ls", "/"]
    re_map={"bin_dir":"^bin$"}
    (rc, result_map) = process.run_sudo_program_and_scan_results(cmd, re_map,
                                                                 logger,
                                                                 sudo_password,
                                                                 log_output=True)
    _assert(rc==0, "Return code of /bin/ls was %d" % rc)
    _assert(result_map["bin_dir"]==True,
            "Expecting bin_dir regexp to be found, got %s" %
            result_map["bin_dir"])
    logger.debug("tst_run_sudo_program_and_scan_results() Successful")

def tst_sudo_run_server(sudo_password):
    """Tests of sudo_run_server(), sudo_check_server_status,
       and sudo_stop_server_process()
    """
    logger.debug("tst_sudo_run_server() Starting")
    if server_log_dir:
        td = server_log_dir
        if not os.path.exists(server_log_dir):
            os.makedirs(server_log_dir)
    else:
        td = tempfile.mkdtemp(prefix="test_sudo")
    try:
        pidfile = os.path.join(td, "server.pid")
        logger.debug("pidfile=%s" % pidfile)
        cwd = os.path.abspath(os.path.dirname(__file__))
        process.sudo_run_server([sys.executable,
                                 os.path.abspath(__file__), "--run-server",
                                 pidfile],
                                {}, os.path.join(td, "server.log"),
                                logger, sudo_password,
                                cwd=cwd)
        found = False
        for i in range(5):
            pid = process.sudo_check_server_status(pidfile, logger,
                                                   sudo_password)
            if pid!=None:
                logger.info("Verified that server started. Pid is %d" % pid)
                found = True
                break
            else:
                time.sleep(5)
        _assert(found, "Test server processs not found after 25 seconds")
        process.sudo_stop_server_process(pidfile, logger, "test",
                                         sudo_password)
        found = True
        for i in range(5):
            pid = process.sudo_check_server_status(pidfile, logger,
                                                   sudo_password)
            if pid==None:
                logger.info("Verified that server stopped")
                found = False
                break
            else:
                time.sleep(5)
        _assert(not found, "Test server processs not stopped after 25 seconds")

    finally:
        if not server_log_dir:
            process.sudo_rm(td, sudo_password, logger)
    logger.debug("tst_sudo_run_server() Successful")

class LsAction(action.SudoAction):
    """This is a test action that just runs /bin/ls under the regular user
    or super user.
    """
    NAME="LsAction"
    def __init__(self, ctx):
        super(LsAction, self).__init__(ctx)

    def run(self, path):
        rc = process.run_and_log_program(["/bin/ls", path],
                                         {}, self.ctx.logger)
        if rc!=0:
            raise Exception("Bad rc from /bin/ls: %d" % rc)

    def dry_run(self, path):
        pass

    def sudo_run(self, path):
        process.run_sudo_program(["/bin/ls", path],
                                  self.ctx._get_sudo_password(self),
                                  self.ctx.logger)

class CatValueAction(action.SudoValueAction):
    NAME = "CatValueAction"
    def __init__(self, ctx):
        super(CatValueAction, self).__init__(ctx)

    def run(self, path, mode="b"):
        _check_file_exists(path, self)
        with open(path, "r" + mode) as f:
            data = f.read()
        return data

    def sudo_run(self, path, mode="b"):
        return process.sudo_cat_file(path, self.ctx.logger,
                                     self.ctx._get_sudo_password(self))

    def dry_run(self, path, mode="b"):
        pass

def _make_context(testname, sudo_password):
    ctx = action.Context({"id": testname}, logger, __file__,
                         lambda : sudo_password,
                         dry_run=False)
    return ctx

def tst_r_su(sudo_password):
    """Test the r_su() method of the action module's Context object
    """
    ctx = _make_context("tst_r_su", sudo_password)
    ctx.r(LsAction, "/")
    ctx.r_su(LsAction, "/")

def tst_rv_su(sudo_password):
    ctx = _make_context("tst_rv_su", sudo_password)
    d1 = ctx.rv(CatValueAction, __file__)
    d2 = ctx.rv_su(CatValueAction, __file__)
    _assert(d1 == d2, "Data from su and regular file reading are different")

ALL_TESTS = [tst_run_program, tst_cat_file,
             tst_run_sudo_program_and_scan_results,
             tst_sudo_run_server, tst_r_su, tst_rv_su]

def test_sudo_generator():
    """Generate sudo tests for Nose. If a pasword is required (meaning we cannot
    run non-interactively), don't generate any tests.
    """
    if process.SUDO_PASSWORD_REQUIRED==True:
        tests = []
    else:
        tests = ALL_TESTS
    for test in tests:
        yield test, None

def run_server(pidfile):
    logger.info("Starting server")
    with open(pidfile, "w") as f:
        f.write("%d" % os.getpid())
    logger.debug("Wrote pidfile %s" % pidfile)
    while True:
        time.sleep(5)
        logger.debug("Server woke up")
    return 0

if __name__ == "__main__":
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    h = logging.StreamHandler(sys.stdout)
    h.setLevel(logging.DEBUG)
    root_logger.addHandler(h)

    usage = "%prog [options] test1 test2...\n  If not tests specified, all are run"
    parser = optparse.OptionParser(usage=usage)
    parser.add_option("--run-server", default=False, action="store_true",
                      help="If specified, start a test server instead of running the tests")
    parser.add_option("--server-log-dir", default=None,
                      help="If specified, use the directory for server logfiles rather than a temporary directory")
    (options, args) = parser.parse_args()
    if options.run_server and options.server_log_dir!=None:
        parser.error("Option --server-log-dir not valid with --run-server")
    if options.run_server:
        if len(args)!=1:
            parser.error("Need to specify pidfile")
        sys.exit(run_server(args[0]))

    if options.server_log_dir:
        server_log_dir = os.path.abspath(os.path.expanduser(options.server_log_dir))

    if len(args)==0:
        tests = ALL_TESTS
    else:
        test_names_to_functions = {}
        for tf in ALL_TESTS:
            test_names_to_functions[tf.__name__] = tf
        tests = []
        all_test_names = [t.__name__ for t in ALL_TESTS]
        for test in args:
            if not test_names_to_functions.has_key(test):
                parser.error("Unknown test %s. Valid tests are: %s" %
                             (test, ', '.join(all_test_names)))
            tests.append(test_names_to_functions[test])

    if process.SUDO_PASSWORD_REQUIRED==True:
        sudo_password = getpass.getpass("Sudo Password:")
    else:
        sudo_password = None

    logger.info("Starting sudo tests, SUDO_PASSWORD_REQUIRED=%s" %
                process.SUDO_PASSWORD_REQUIRED)
    for test in tests:
        test(sudo_password)
    logger.info("sudo tests successful")
    sys.exit(0)


text:
@interface SPLFXFormViewController ()

@end

@implementation SPLFXFormViewController

+ (instancetype)formViewControllerWithForm:(id<FXForm>)form {
    SPLFXFormViewController *vc = [self new];
    vc.formController.form = form;
    return vc;
}

- (void)bindToObject:(id)object {
    [self.formController enumerateFieldsWithBlock:^(FXFormField *field, NSIndexPath *indexPath) {
        if ([field.key length] == 0) {
            return;
        }

        DLog(@"Filling %@ => %@", field.key, field.value);

        [object setValue:field.value
                  forKey:field.key];
    }];
}

@end


text: from pyface.wizard.simple_wizard_controller import *


text:
import Buttons from './buttons';
import clearPage from './clear-page';

var buttons = new Buttons();

clearPage();


text: tomcat image from alpine


text:
/*
 * This code implements a `root nexus' for Intel Architecture
 * machines.  The function of the root nexus is to serve as an
 * attachment point for both processors and buses, and to manage
 * resources which are common to all of them.  In particular,
 * this code implements the core resource managers for interrupt
 * requests, DMA requests (which rightfully should be a part of the
 * ISA code but it's easier to do it here for now), I/O port addresses,
 * and I/O memory address space.
 */

#include "opt_isa.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bus.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <machine/bus.h>
#include <sys/rman.h>
#include <sys/interrupt.h>

#include <machine/vmparam.h>
#include <vm/vm.h>
#include <vm/pmap.h>
#include <machine/pmap.h>

#include <machine/resource.h>
#ifdef APIC_IO
#include <machine/smp.h>
#include <machine/mpapic.h>
#endif

#ifdef DEV_ISA
#include <isa/isavar.h>
#ifdef PC98
#include <pc98/pc98/pc98.h>
#else
#include <i386/isa/isa.h>
#endif
#endif
#include <i386/isa/icu.h>
#include <i386/isa/intr_machdep.h>
#include <sys/rtprio.h>

static MALLOC_DEFINE(M_NEXUSDEV, "nexusdev", "Nexus device");
struct nexus_device {
	struct resource_list	nx_resources;
};

#define DEVTONX(dev)	((struct nexus_device *)device_get_ivars(dev))

static struct rman irq_rman, drq_rman, port_rman, mem_rman;

static	int nexus_probe(device_t);
static	int nexus_attach(device_t);
static	int nexus_print_all_resources(device_t dev);
static	int nexus_print_child(device_t, device_t);
static device_t nexus_add_child(device_t bus, int order, const char *name,
				int unit);
static	struct resource *nexus_alloc_resource(device_t, device_t, int, int *,
					      u_long, u_long, u_long, u_int);
static	int nexus_activate_resource(device_t, device_t, int, int,
				    struct resource *);
static	int nexus_deactivate_resource(device_t, device_t, int, int,
				      struct resource *);
static	int nexus_release_resource(device_t, device_t, int, int,
				   struct resource *);
static	int nexus_setup_intr(device_t, device_t, struct resource *, int flags,
			     void (*)(void *), void *, void **);
static	int nexus_teardown_intr(device_t, device_t, struct resource *,
				void *);
static	int nexus_set_resource(device_t, device_t, int, int, u_long, u_long);
static	int nexus_get_resource(device_t, device_t, int, int, u_long *, u_long *);
static void nexus_delete_resource(device_t, device_t, int, int);

static device_method_t nexus_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		nexus_probe),
	DEVMETHOD(device_attach,	nexus_attach),
	DEVMETHOD(device_detach,	bus_generic_detach),
	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
	DEVMETHOD(device_suspend,	bus_generic_suspend),
	DEVMETHOD(device_resume,	bus_generic_resume),

	/* Bus interface */
	DEVMETHOD(bus_print_child,	nexus_print_child),
	DEVMETHOD(bus_add_child,	nexus_add_child),
	DEVMETHOD(bus_alloc_resource,	nexus_alloc_resource),
	DEVMETHOD(bus_release_resource,	nexus_release_resource),
	DEVMETHOD(bus_activate_resource, nexus_activate_resource),
	DEVMETHOD(bus_deactivate_resource, nexus_deactivate_resource),
	DEVMETHOD(bus_setup_intr,	nexus_setup_intr),
	DEVMETHOD(bus_teardown_intr,	nexus_teardown_intr),
	DEVMETHOD(bus_set_resource,	nexus_set_resource),
	DEVMETHOD(bus_get_resource,	nexus_get_resource),
	DEVMETHOD(bus_delete_resource,	nexus_delete_resource),

	{ 0, 0 }
};

static driver_t nexus_driver = {
	"nexus",
	nexus_methods,
	1,			/* no softc */
};
static devclass_t nexus_devclass;

DRIVER_MODULE(nexus, root, nexus_driver, nexus_devclass, 0, 0);

static int
nexus_probe(device_t dev)
{

	device_quiet(dev);	/* suppress attach message for neatness */

	/*
	 * XXX working notes:
	 *
	 * - IRQ resource creation should be moved to the PIC/APIC driver.
	 * - DRQ resource creation should be moved to the DMAC driver.
	 * - The above should be sorted to probe earlier than any child busses.
	 *
	 * - Leave I/O and memory creation here, as child probes may need them.
	 *   (especially eg. ACPI)
	 */

	/*
	 * IRQ's are on the mainboard on old systems, but on the ISA part
	 * of PCI->ISA bridges.  There would be multiple sets of IRQs on
	 * multi-ISA-bus systems.  PCI interrupts are routed to the ISA
	 * component, so in a way, PCI can be a partial child of an ISA bus(!).
	 * APIC interrupts are global though.
	 *
	 * XXX We depend on the AT PIC driver correctly claiming IRQ 2
	 *     to prevent its reuse elsewhere in the !APIC_IO case.
	 */
	irq_rman.rm_start = 0;
	irq_rman.rm_type = RMAN_ARRAY;
	irq_rman.rm_descr = "Interrupt request lines";
#ifdef APIC_IO
	irq_rman.rm_end = APIC_INTMAPSIZE - 1;
#else
	irq_rman.rm_end = 15;
#endif
	if (rman_init(&irq_rman)
	    || rman_manage_region(&irq_rman,
				  irq_rman.rm_start, irq_rman.rm_end))
		panic("nexus_probe irq_rman");

	/*
	 * ISA DMA on PCI systems is implemented in the ISA part of each
	 * PCI->ISA bridge and the channels can be duplicated if there are
	 * multiple bridges.  (eg: laptops with docking stations)
	 */
	drq_rman.rm_start = 0;
#ifdef PC98
	drq_rman.rm_end = 3;
#else
	drq_rman.rm_end = 7;
#endif
	drq_rman.rm_type = RMAN_ARRAY;
	drq_rman.rm_descr = "DMA request lines";
	/* XXX drq 0 not available on some machines */
	if (rman_init(&drq_rman)
	    || rman_manage_region(&drq_rman,
				  drq_rman.rm_start, drq_rman.rm_end))
		panic("nexus_probe drq_rman");

	/*
	 * However, IO ports and Memory truely are global at this level,
	 * as are APIC interrupts (however many IO APICS there turn out
	 * to be on large systems..)
	 */
	port_rman.rm_start = 0;
	port_rman.rm_end = 0xffff;
	port_rman.rm_type = RMAN_ARRAY;
	port_rman.rm_descr = "I/O ports";
	if (rman_init(&port_rman)
	    || rman_manage_region(&port_rman, 0, 0xffff))
		panic("nexus_probe port_rman");

	mem_rman.rm_start = 0;
	mem_rman.rm_end = ~0u;
	mem_rman.rm_type = RMAN_ARRAY;
	mem_rman.rm_descr = "I/O memory addresses";
	if (rman_init(&mem_rman)
	    || rman_manage_region(&mem_rman, 0, ~0))
		panic("nexus_probe mem_rman");

	return 0;
}

static int
nexus_attach(device_t dev)
{

	bus_generic_probe(dev);
	bus_generic_attach(dev);
	return 0;
}

static int
nexus_print_all_resources(device_t dev)
{
	struct	nexus_device *ndev = DEVTONX(dev);
	struct resource_list *rl = &ndev->nx_resources;
	int retval = 0;

	if (SLIST_FIRST(rl))
		retval += printf(" at");

	retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#lx");
	retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#lx");
	retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%ld");

	return retval;
}

static int
nexus_print_child(device_t bus, device_t child)
{
	int retval = 0;

	retval += bus_print_child_header(bus, child);
	retval += nexus_print_all_resources(child);
	retval += printf(" on motherboard\n");	/* XXX "motherboard", ick */

	return (retval);
}

static device_t
nexus_add_child(device_t bus, int order, const char *name, int unit)
{
	device_t		child;
	struct nexus_device	*ndev;

	ndev = malloc(sizeof(struct nexus_device), M_NEXUSDEV, M_NOWAIT|M_ZERO);
	if (!ndev)
		return(0);
	resource_list_init(&ndev->nx_resources);

	child = device_add_child_ordered(bus, order, name, unit);

	/* should we free this in nexus_child_detached? */
	device_set_ivars(child, ndev);

	return(child);
}

/*
 * Allocate a resource on behalf of child.  NB: child is usually going to be a
 * child of one of our descendants, not a direct child of nexus0.
 * (Exceptions include npx.)
 */
static struct resource *
nexus_alloc_resource(device_t bus, device_t child, int type, int *rid,
		     u_long start, u_long end, u_long count, u_int flags)
{
	struct nexus_device *ndev = DEVTONX(child);
	struct	resource *rv;
	struct resource_list_entry *rle;
	struct	rman *rm;
	int needactivate = flags & RF_ACTIVE;

	/*
	 * If this is an allocation of the "default" range for a given RID, and
	 * we know what the resources for this device are (ie. they aren't maintained
	 * by a child bus), then work out the start/end values.
	 */
	if ((start == 0UL) && (end == ~0UL) && (count == 1)) {
		if (ndev == NULL)
			return(NULL);
		rle = resource_list_find(&ndev->nx_resources, type, *rid);
		if (rle == NULL)
			return(NULL);
		start = rle->start;
		end = rle->end;
		count = rle->count;
	}

	flags &= ~RF_ACTIVE;

	switch (type) {
	case SYS_RES_IRQ:
		rm = &irq_rman;
		break;

	case SYS_RES_DRQ:
		rm = &drq_rman;
		break;

	case SYS_RES_IOPORT:
		rm = &port_rman;
		break;

	case SYS_RES_MEMORY:
		rm = &mem_rman;
		break;

	default:
		return 0;
	}

	rv = rman_reserve_resource(rm, start, end, count, flags, child);
	if (rv == 0)
		return 0;

	if (type == SYS_RES_MEMORY) {
		rman_set_bustag(rv, I386_BUS_SPACE_MEM);
	} else if (type == SYS_RES_IOPORT) {
		rman_set_bustag(rv, I386_BUS_SPACE_IO);
#ifndef PC98
		rman_set_bushandle(rv, rv->r_start);
#endif
	}

#ifdef PC98
	if ((type == SYS_RES_MEMORY || type == SYS_RES_IOPORT) &&
	    i386_bus_space_handle_alloc(rv->r_bustag, rv->r_start, count,
					&rv->r_bushandle) != 0) {
		rman_release_resource(rv);
		return 0;
	}
#endif

	if (needactivate) {
		if (bus_activate_resource(child, type, *rid, rv)) {
#ifdef PC98
			if (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT) {
				i386_bus_space_handle_free(rv->r_bustag,
				    rv->r_bushandle, rv->r_bushandle->bsh_sz);
			}
#endif
			rman_release_resource(rv);
			return 0;
		}
	}

	return rv;
}

static int
nexus_activate_resource(device_t bus, device_t child, int type, int rid,
			struct resource *r)
{
	/*
	 * If this is a memory resource, map it into the kernel.
	 */
	if (rman_get_bustag(r) == I386_BUS_SPACE_MEM) {
		caddr_t vaddr = 0;

		if (rman_get_end(r) < 1024 * 1024) {
			/*
			 * The first 1Mb is mapped at KERNBASE.
			 */
			vaddr = (caddr_t)(uintptr_t)(KERNBASE + rman_get_start(r));
		} else {
			u_int32_t paddr;
			u_int32_t psize;
			u_int32_t poffs;

			paddr = rman_get_start(r);
			psize = rman_get_size(r);

			poffs = paddr - trunc_page(paddr);
			vaddr = (caddr_t) pmap_mapdev(paddr-poffs, psize+poffs) + poffs;
		}
		rman_set_virtual(r, vaddr);
#ifdef PC98
		/* PC-98: the type of bus_space_handle_t is the structure. */
		r->r_bushandle->bsh_base = (bus_addr_t) vaddr;
#else
		/* IBM-PC: the type of bus_space_handle_t is u_int */
		rman_set_bushandle(r, (bus_space_handle_t) vaddr);
#endif
	}
	return (rman_activate_resource(r));
}

static int
nexus_deactivate_resource(device_t bus, device_t child, int type, int rid,
			  struct resource *r)
{
	/*
	 * If this is a memory resource, unmap it.
	 */
	if ((rman_get_bustag(r) == I386_BUS_SPACE_MEM) &&
	    (rman_get_end(r) >= 1024 * 1024)) {
		u_int32_t psize;

		psize = rman_get_size(r);
		pmap_unmapdev((vm_offset_t)rman_get_virtual(r), psize);
	}

	return (rman_deactivate_resource(r));
}

static int
nexus_release_resource(device_t bus, device_t child, int type, int rid,
		       struct resource *r)
{
	if (rman_get_flags(r) & RF_ACTIVE) {
		int error = bus_deactivate_resource(child, type, rid, r);
		if (error)
			return error;
	}
#ifdef PC98
	if (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT) {
		i386_bus_space_handle_free(r->r_bustag, r->r_bushandle,
					   r->r_bushandle->bsh_sz);
	}
#endif
	return (rman_release_resource(r));
}

/*
 * Currently this uses the really grody interface from kern/kern_intr.c
 * (which really doesn't belong in kern/anything.c).  Eventually, all of
 * the code in kern_intr.c and machdep_intr.c should get moved here, since
 * this is going to be the official interface.
 */
static int
nexus_setup_intr(device_t bus, device_t child, struct resource *irq,
		 int flags, void (*ihand)(void *), void *arg, void **cookiep)
{
	driver_t	*driver;
	int		error;

	/* somebody tried to setup an irq that failed to allocate! */
	if (irq == NULL)
		panic("nexus_setup_intr: NULL irq resource!");

	*cookiep = 0;
	if ((irq->r_flags & RF_SHAREABLE) == 0)
		flags |= INTR_EXCL;

	driver = device_get_driver(child);

	/*
	 * We depend here on rman_activate_resource() being idempotent.
	 */
	error = rman_activate_resource(irq);
	if (error)
		return (error);

	error = inthand_add(device_get_nameunit(child), irq->r_start,
	    ihand, arg, flags, cookiep);

	return (error);
}

static int
nexus_teardown_intr(device_t dev, device_t child, struct resource *r, void *ih)
{
	return (inthand_remove(ih));
}

static int
nexus_set_resource(device_t dev, device_t child, int type, int rid, u_long start, u_long count)
{
	struct nexus_device	*ndev = DEVTONX(child);
	struct resource_list	*rl = &ndev->nx_resources;

	/* XXX this should return a success/failure indicator */
	resource_list_add(rl, type, rid, start, start + count - 1, count);
	return(0);
}

static int
nexus_get_resource(device_t dev, device_t child, int type, int rid, u_long *startp, u_long *countp)
{
	struct nexus_device	*ndev = DEVTONX(child);
	struct resource_list	*rl = &ndev->nx_resources;
	struct resource_list_entry *rle;

	rle = resource_list_find(rl, type, rid);
	device_printf(child, "type %d  rid %d  startp %p  countp %p - got %p\n",
		      type, rid, startp, countp, rle);
	if (!rle)
		return(ENOENT);
	if (startp)
		*startp = rle->start;
	if (countp)
		*countp = rle->count;
	return(0);
}

static void
nexus_delete_resource(device_t dev, device_t child, int type, int rid)
{
	struct nexus_device	*ndev = DEVTONX(child);
	struct resource_list	*rl = &ndev->nx_resources;

	resource_list_delete(rl, type, rid);
}

#ifdef DEV_ISA
/*
 * Placeholder which claims PnP 'devices' which describe system
 * resources.
 */
static struct isa_pnp_id sysresource_ids[] = {
	{ 0x010cd041 /* PNP0c01 */, "System Memory" },
	{ 0x020cd041 /* PNP0c02 */, "System Resource" },
	{ 0 }
};

static int
sysresource_probe(device_t dev)
{
	int	result;

	if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, sysresource_ids)) <= 0) {
		device_quiet(dev);
	}
	return(result);
}

static int
sysresource_attach(device_t dev)
{
	return(0);
}

static device_method_t sysresource_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		sysresource_probe),
	DEVMETHOD(device_attach,	sysresource_attach),
	DEVMETHOD(device_detach,	bus_generic_detach),
	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
	DEVMETHOD(device_suspend,	bus_generic_suspend),
	DEVMETHOD(device_resume,	bus_generic_resume),
	{ 0, 0 }
};

static driver_t sysresource_driver = {
	"sysresource",
	sysresource_methods,
	1,		/* no softc */
};

static devclass_t sysresource_devclass;

DRIVER_MODULE(sysresource, isa, sysresource_driver, sysresource_devclass, 0, 0);
#endif /* DEV_ISA */


text:
package org.kuali.kra.budget.personnel;

public interface JobCodeService {

    /**
     *
     * This method provides the appropriate JobCode Title
     * for a particular jobCode string.
     *
     * @param JobCode
     * @return
     */
    public String findJobCodeTitle(String JobCode);

    /**
     *
     * This method provides the appropriate JobCode object
     * for a particular jobCode string.
     *
     * @param JobCode
     * @return
     */
    public JobCode findJobCodeRef(String jobCode);

}


text:
package com.niomongo.conversion.custom.validation;

import com.niomongo.conversion.custom.Email;

/**
 * Created by Yevgen Bushuyev on 20.01.15.
 */
public class EmailValidator implements Validator {

  private enum State {

    beforeFirstChar {
      public void onAt(EmailValidator validator) {
        validator.result = notValid;
      }

      @Override
      public void onDot(EmailValidator validator) {
        validator.result = notValid;
      }

      @Override
      public void onByte(EmailValidator validator) {
        validator.state = beforeAt;

      }
    },

    beforeAt {
      public void onAt(EmailValidator validator) {
        if (validator.lastDot == true) {
          validator.result = notValid;
        }
        validator.state = afterAt;
      }

      @Override
      public void onDot(EmailValidator validator) {
        validator.lastDot = true;
      }

      @Override
      public void onByte(EmailValidator validator) {
        validator.lastDot = false;
      }
    },

    afterAt {
      @Override
      public void onAt(EmailValidator validator) {
        validator.result = notValid; //TODO \@ cases
      }

      @Override
      public void onDot(EmailValidator validator) {
        if (validator.lastDot) {
          validator.result = notValid;
        }
        validator.hasDotsAfterAt = true;
        validator.lastDot = true;

      }

      @Override
      public void onByte(EmailValidator validator) {
        validator.lastDot = false;
        if (validator.hasDotsAfterAt) {
          validator.result = allOK;
        }
      }
    };

    public void onAt(EmailValidator validator) {
    }

    public void onByte(EmailValidator validator) {
    }

    public void onDot(EmailValidator validator) {
    }
  }

  public interface EmailValidationResponseBuilder<C> extends ValidationResponseBuilder {
    void onInvalidEmail(C context);
  }

  public final static ValidationResult notValid = new ValidationResult<EmailValidationResponseBuilder>() {
    @Override
    public void accept(EmailValidationResponseBuilder validationResponseBuilder, Object context) {
      validationResponseBuilder.onInvalidEmail(context);
    }
  };

  private State state = State.beforeFirstChar;
  private ValidationResult result = null;
  private boolean lastDot;
  private boolean hasDotsAfterAt;

  public EmailValidator() {
  }

  @Override
  public void validate(byte b) {
    if (result == notValid) {
      return;
    }

    if (b < 0x1F || b > 0x7e || b == 0x2C || b == 0x3C || b == 0x3e || b == 0x24 || b == 0x2f || b == 0x3a || b == 0x3b || b == 0x96) {//special chars
      result = notValid;
      return;
    }

    switch (b) {
      case 0x40:
        state.onAt(this);
        break;
      case 0x2E:
        state.onDot(this);
        break;
      default:
        state.onByte(this);
        break;
    }
  }

  @Override
  public ValidationResult getValidationResult() {
    return result != null ? result : notValid;
  }

  public static class Factory implements ValidatorFactory<Email> {

    private Email annotation;

    @Override
    public Validator newValidator() {
      return new EmailValidator();
    }

    @Override
    public void setAnnotation(Email annotation) {

      this.annotation = annotation;
    }
  }
}


text:
@interface TYHBaseViewController : UIViewController

@end


text:
<?php
namespace Posts\Form;
use Zend\Form\Element;
use Zend\InputFilter\Factory as InputFilterFactory;
class CategoryForm extends \MDS\Form\AbstractForm{

    public function init()
    {
        $inputFilterFactory = new InputFilterFactory();
        $inputFilter        = $inputFilterFactory->createInputFilter(
            array(
                'title'=>array(
                    'required' => true,
                    'validators' => array(
                        array('name' => 'not_empty'),
                    )
                ),
                'slug'=>array(
                    'required' => true,
                    'validators' => array(
                        array('name' => 'not_empty'),

                    )
                ),
                'active'=>array(
                		'required' => true,
                		'validators' => array(
                				array('name' => 'not_empty'),
                		)
                ),

                'metakey'=>array(
                		'required' => true,
                		'validators' => array(
                				array('name' => 'not_empty'),

                		)
                ),
                'metades'=>array(
                		'required' => true,
                		'validators' => array(
                				array('name' => 'not_empty'),
                		)
                ),

            )
        );

        $this->setInputFilter($inputFilter);
        $category = new Element('title');
        $category->setLabel('Title')->setLabelAttributes(array('class'=>'control-label'));
        $category->setAttribute('class','input-xlarge');
        $this->add($category);

        $category = new Element('slug');
        $category->setLabel("Slug")->setLabelAttributes(array('class'=>'control-label'));
        $category->setAttribute('class','input-xlarge');
        $this->add($category);

        $name = new Element('parent_id');
        $name->setLabel("Name Category");
        $this->add($name);

        $category = new Element\Checkbox('active');
        $category->setLabel("Active")->setLabelAttributes(array('class'=>'control-label'));
        $category->setAttribute('class','input-xlarge');
        $category->setOptions(
        	array(
        	 '0' =>'UnActive',
        	 '1' =>'Active'
            )
        );
        $category->setChecked(0);
        $this->add($category);

        $category = new Element('metakey');
        $category->setLabel("Metakey")->setLabelAttributes(array('class'=>'control-label'));
        $category->setAttribute('type', 'textarea');
        $category->setAttribute('class','input-block-level');
        $this->add($category);

        $category = new Element('metades');
        $category->setLabel("Metades")->setLabelAttributes(array('class'=>'control-label'));
        $category->setAttribute('type', 'textarea');
        $category->setAttribute('class','input-block-level');
        $this->add($category);

        $this->add(new Element('redirect'));
    }
}