text:
/* global Ember */

(function() {

var VERSION = '0.2.1';

if (Ember.libraries) {
  Ember.libraries.register('Ember Validator', VERSION);
}

/**
 * @module Ember.Validator
 * @main Ember.Validator
 */

/**
 * @class Ember.Validator
 * @namespace Ember
 * @extends Ember.Object
 * @static
 */
Ember.Validator = Ember.Object.create({
  options: {
    /**
     * Option to trim whitespace from string values before validation.
     *
     * @property trim
     * @default true
     * @type {Boolean}
     */
    trim: true,

    /**
     * Option to set the trimmed value on the object. Trim must be true for
     * this to work.
     *
     * @property trimApply
     * @default true
     * @type {Boolean}
     */
    trimApply: true
  },

  /**
   * Looks for rules property in the errorKey set in validations
   *
   * @private
   * @method _getRulesForKey
   * @pram {object} validations
   * @param {string} key
   */
  _getRulesForKey: function(validations, key) {
    var property = validations[key];

    if (property && Ember.typeOf(property.rules) === 'array') {
      return property.rules;
    } else {
      Ember.Logger.warn('No valid defined rules found for property \''+
        key + '\'.' + ' Please check your validation definitions.');
      return [];
    }
  },

  /**
   * Creates the error message.
   *
   * @private
   * @method _createResultMessage
   * @param {String} errorKey
   * @param {Ember.Validator.Rule} rule
   */
  _createResultMessage: function(errorKey, rule) {
    var propertyFormat = rule.get('propertyFormat'),
        messageFormats = rule.get('messageFormats');

    propertyFormat = propertyFormat ? propertyFormat : errorKey;

    return this._formatMessage(rule, propertyFormat, messageFormats);
  },

  /**
   * Formats the message based on the errorKey and messageFormats.
   * The errorKey is always set as the first argument
   *
   * Related:
   * {{#crossLink "Validator.Rule/propertyFormat:property"}}{{/crossLink}},
   * {{#crossLink "Validator.Rule/messageFormats:property"}}{{/crossLink}}
   *
   * @private
   * @method _formatMessage
   * @param {Ember.Validator.Rule} rule
   * @param  {String} propertyFormat
   * @param  {Array} messageFormats
   * @return {String} The formatted string
   */
  _formatMessage: function(rule, propertyFormat, messageFormats) {
    var formats = [],
        message = rule.get('message');

    Ember.assert('You must specify an error message for rule name ' +
      '(%@)'.fmt(rule.get('name')), message);

    formats = formats.concat(messageFormats);
    formats.unshift(propertyFormat);

    return Ember.String.fmt(message, formats);
  },

  /**
   * Looks for a rule object defined as custom or defined in {@link Ember.Validator.Rules}.
   * Any custom rules with the same name in {@link Ember.Validator.Rules} are merged.
   *
   * @private
   * @method _getRuleObj
   * @param {String} context
   * @param {String} key
   * @param {String} ruleName
   * @return {Object} - The rule object
   */
  _getRuleObj: function(context, key, ruleName) {
    var validations = context.validations,
        Rules = Ember.Validator.Rules,
        customRule = validations[key][ruleName],
        builtInRuleCopy = Ember.copy(Rules[ruleName]);

    if (customRule) {
      var rule = builtInRuleCopy ? Ember.merge(builtInRuleCopy, customRule) : customRule,
          hasValidateMethod = typeof rule.validate === 'function';

      Ember.assert('Must have validate function defined in custom rule.',
        hasValidateMethod);

      return Ember.Validator.Rule.create(rule, { name: ruleName });
    }

    if (builtInRuleCopy) {
      return Ember.Validator.Rule.create(builtInRuleCopy);
    } else {
      Ember.assert('No valid rules were found.', false);
    }
  },

  /**
   * Responsible for running validation rules and adding the error to an
   * instance of Ember.Validator.Error.
   *
   * Result generation will stop at the first failed validation per key.
   *
   * @private
   * @method _generateResult
   * @param {Object} context - The object doing the validation
   * @param {Array} rules - rule names defined as strings
   * @param {String} key - the current property being validated
   */
  _generateResult: function(context, ruleNames, key, options) {
    var self = this,
        valueForKey = context.get(key),
        result = context.get('validatorResult');

    if (options.trim && Ember.typeOf(valueForKey) === 'string') {
      var trimmed = valueForKey.trim();

      if (options.trimApply) {
        context.set(key, trimmed);
      }

      valueForKey = trimmed;
    }

    ruleNames.find(function(ruleName) {
      var rule = self._getRuleObj(context, key, ruleName);

      // Should only run rules on required or values that are not undefined
      if (ruleName === 'required' || !Ember.isEmpty(valueForKey)) {
        // Add a context to rule instance for use in validate options
        rule.set('context', context);

        var didValidate = rule.validate(valueForKey, rule);

        if (!didValidate) {
          var message = options && options.squelch ?
                null : self._createResultMessage(key, rule),
              error = Ember.Validator.Error.create();

          error.setProperties({
            message: message,
            context: context,
            isValid: false,
            ruleName: ruleName,
            errorKey: key
          });

          result.set(key, error);

          return true;
        }
      }
    });
  }
});

/**
 * The base rule class which stores the validate method and message settings.
 *
 * @class Rule
 * @constructor
 * @namespace Validator
 * @extends Ember.Object
 */
Ember.Validator.Rule = Ember.Object.extend({
  /**
   * Property used to customize the message formatting
   *
   * @property messageFormats
   * @type array
   */
  messageFormats: [],

  /**
   * Set this property when you want to customize the message to show something
   * other than the default errorKey.
   *
   * See: {{#crossLink "Ember.Validator.Error/errorKey:property"}}errorKey{{/crossLink}}
   *
   * @property propertyFormat
   * @type string
   */
  propertyFormat: null,

  /**
   * The property used to display the error message. Can be set to a customized
   * message with formatting or without.
   *
   * message is formatted like so:
   *
   * @example
   *  ```
   *  // %@1: errorKey || propertyFormat
   *  // %@2+: messageFormats
   *
   *  '%@1 has invalid length, must be %@2 %@3 chars'.fmt(errorKey, messageFormats);
   *  ```
   * errorKey is defaulted to %@1 and messageFormats are designated for %@2+
   *
   * Related: {{#crossLink "Validator.Error/errorKey:property"}}{{/crossLink}}
   *
   * @property message
   * @uses messageFormats
   * @type string
   */
  message: null,

  /**
   * Define validations in this method and return the Boolean value.
   *
   * @method validate
   * @param {*} value - The property value to validate
   * @param {Object} options - The object validator with an object context included
   * @return {Boolean}
   */
  validate: function() {
    Ember.assert('You must define a validate function for this to be a valid rule', false);
  }
});

/**
 * A static class used to defined reusable rules. Each property defined on the
 * root of this class are wrapped in Ember.Validator.Rule.
 *
 * An example of adding more rules:
 *
 * ```javascript
 * Ember.Validator.Rules.reopen({
 *   minLength: {
 *     min: 6,
 *
 *     validate: function(value, options) {
 *       this.messageFormats = ['Minimum', options.min];
 *       return value.split('').length > options.min;
 *     },
 *
 *     message: '%@2 of %@3 characters required.'
 *   }
 * });
 * ```
 *
 * Related:
 * {{#crossLink "Validator.Rule"}}{{/crossLink}},
 * http://emberjs.com/api/classes/Ember.String.html#method_fmt
 *
 * @static
 * @class Rules
 * @namespace Validator
 */
Ember.Validator.Rules = Ember.Object.create({
  required: {
    validate: function(value) {
      return !Ember.isEmpty(value);
    },

    message: '%@1 is required'
  },

  number: {
    validate: function(value) {
      return !isNaN(parseInt(value, 10));
    },

    message: '%@1 is not a number'
  }
});

/**
 * Validation result object used to store the validation.
 *
 * @class Error
 * @constructor
 * @namespace Validator
 * @extends Ember.Object
 */
Ember.Validator.Error = Ember.Object.extend({
  /**
   * @property message
   * @type String
   */
  message: null,

  /**
   * The object that is running the validation.
   *
   * @property context
   * @type {Object || Ember.Object}
   */
  context: null,

  /**
   * @property errorKey
   * @type string
   */
  errorKey: null,

  /**
   * @property isValid
   * @type boolean
   */
  isValid: null,

  /**
   * @property ruleName
   * @type string
   */
  ruleName: null
});

/**
 * The array proxy which stores all the validation results
 *
 * @constructor
 * @class Result
 * @namespace Validator
 * @extends Ember.ObjectProxy
 */
Ember.Validator.Result = Ember.ObjectProxy.extend({
  /**
   * All errors are set in the content property.
   *
   * @property content
   * @type Object
   */
  content: null,

  /**
   * @property error
   * @type {Object}
   */
  error: Ember.computed.alias('content'),

  /**
   * An array of all errors that exist in the content property
   *
   * @property errors
   * @type {Array}
   */
  errors: function() {
    var content = this.get('content');

    return Ember.keys(content).reduce(function(errors, key) {
      errors.pushObject(content.get(key));
      return errors;
    }, []);
  }.property('content'),

  /**
   * An array of all the error messages generated
   *
   * @property messages
   * @type {Array}
   */
  messages: Ember.computed.mapBy('errors', 'message'),

  /**
   * Set to false if any errors were generated in the validation
   *
   * @property isValid
   * @type {Boolean}
   */
  isValid: function() {
    return Ember.isEmpty(this.get('errors'));
  }.property('errors.@each')
});

/**
 * Add this mixin to any object to add validation support. Exposes the validate()
 * method which looks for a validations object.
 *
 * @class Support
 * @static
 * @namespace Validator
 * @type {Ember.Mixin}
 */
Ember.Validator.Support = Ember.Mixin.create({
  init: function() {
    this._super();
    this.set('validatorResult', Ember.Validator.Result.create({ content: {} }));
  },

  /**
   * The property where validations are defined.
   *
   * @example
   * ```javascript
   * App.Person = Ember.Object.extend(Ember.Validator.Support, {
   *  name: null,
   *  phone: null,
   *
   *  validations: {
   *    name: {
   *      rules: ['required']
   *    },
   *    phone: {
   *       rules: ['required', 'phone']
   *       phone: function(value, options) {
   *         // run validations
   *       }
   *    }
   *  }
   * });
   * ```
   *
   * @property validations
   * @required
   * @type {Object}
   */
  validations: null,

  /**
   * Runs all validations defined in the validations object and stores results.
   * The method returns a results object.
   *
   * ### Getting validation
   * ```
   * var person = App.Person.create({ name: null, age: 29 });
   *
   * person.validate().get('isValid') // false;;
   * ```
   *
   * ### Getting error messages
   * ```
   * person.validate().get('error.name.message'); // 'name is required'
   * ```
   *
   * You can also choose which keys to run validations on by passing an array
   * to properties inside an options object.
   * ```javascript
   * person.validate({ properties: ['name', 'age'] });
   * ```
   *
   * ### Supressing (Squelch) Error Messages
   *
   * Running validations without generating messages is possible with squelch.
   * This is useful for when you want to validate an object but not generate
   * error messages when using messages in a view.
   *
   * ```javascript
   * person.validate({ squelch: true });
   * ```
   *
   * Related:
   * {{#crossLink "Validator.Results"}}{{/crossLink}},
   * {{#crossLink "Validator.Support/validations:property"}}{{/crossLink}}
   *
   * @method validate
   * @param {Object} options
   * @return {Ember.Validator.Result}
   */
  validate: function(options) {
    var self = this,
        validations = this.get('validations'),
        Validator = Ember.Validator,
        keys = Ember.keys(validations),
        defaultOptions = Em.copy(Ember.Validator.options);

    if (options) {
      options = Ember.merge(defaultOptions, options);
    } else {
      options = defaultOptions;
    }

    Ember.assert('You do not have a \'validations\' object defined', validations);

    // Check if keys are being sent as args in the method before checking
    // validations object.
    if (options.properties) {
      keys = options.properties;
    }

    // Prep and/or clear out old errors
    this.set('validatorResult.content', Ember.Validator.Error.create());

    keys.forEach(function(key) {
      var rules = Validator._getRulesForKey(validations, key);
      Validator._generateResult(self, rules, key, options);
    });

    return this.get('validatorResult');
  }
});

})();


text:
package org.apache.droids.exception;

/**
 *
 * @version 1.0
 *
 */
public class InvalidTaskException extends DroidsException
{
  private static final long serialVersionUID = -3786805476765424195L;

/**
   * @param msg
   *                error message
   */
  public InvalidTaskException( String msg ) {
    super( msg );
  }
}

redpajama_set_name: RedPajamaGithub


text:
#include <cstdlib>
#include <ios>
#include <iostream>
#include <iomanip>
#include <ostream>
#include <stdexcept>

#include "tma.h"
#include "load.h"

// TODO parse and pass cmd line args to timed library

enum
{
    USAGE_FAIL=1,
    DLL_LOAD_FAIL,
    ENTRY_ADDR_FAIL,
};

void usage_and_exit(int rc=0)
{
    using namespace std;

    cerr    << "usage: tma <TIMED_LIBRARY> [TIMED_OPTIONS]"
            << endl;

    exit(rc);
}

int main(int argc, char* argv[])
{
    using namespace std;

    if (argc < 2) usage_and_exit(USAGE_FAIL);

    HMODULE dll = load_dll(argv[1]);
    if (!dll)
    {
        cerr    << "[ERROR] unable to load '"
                << argv[1]
                << "' library"
                << endl;

        exit(DLL_LOAD_FAIL);
    }

    timed_fcn time_me = reinterpret_cast<timed_fcn>(symbol_from_dll(dll, "timed_main"));
    if (!time_me)
    {
        cerr    << "[ERROR] unable to retrieve the timed library entry function"
                << endl;

        close_dll(dll);
        exit(ENTRY_ADDR_FAIL);
    }

    time_me(0, NULL);
    close_dll(dll);

    return 0;

}


text:
namespace llvm {

class MCWasmStreamer;
class MCSymbolWasm;

/// WebAssembly-specific streamer interface, to implement support
/// WebAssembly-specific assembly directives.
class WebAssemblyTargetStreamer : public MCTargetStreamer {
public:
  explicit WebAssemblyTargetStreamer(MCStreamer &S);

  /// .param
  virtual void emitParam(MCSymbol *Symbol, ArrayRef<MVT> Types) = 0;
  /// .result
  virtual void emitResult(MCSymbol *Symbol, ArrayRef<MVT> Types) = 0;
  /// .local
  virtual void emitLocal(ArrayRef<MVT> Types) = 0;
  /// .endfunc
  virtual void emitEndFunc() = 0;
  /// .functype
  virtual void emitIndirectFunctionType(MCSymbol *Symbol,
                                        SmallVectorImpl<MVT> &Params,
                                        SmallVectorImpl<MVT> &Results) = 0;
  /// .indidx
  virtual void emitIndIdx(const MCExpr *Value) = 0;
  /// .import_global
  virtual void emitGlobalImport(StringRef name) = 0;
  /// .import_module
  virtual void emitImportModule(MCSymbolWasm *Sym, StringRef ModuleName) = 0;

protected:
  void emitValueType(wasm::ValType Type);
};

/// This part is for ascii assembly output
class WebAssemblyTargetAsmStreamer final : public WebAssemblyTargetStreamer {
  formatted_raw_ostream &OS;

public:
  WebAssemblyTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS);

  void emitParam(MCSymbol *Symbol, ArrayRef<MVT> Types) override;
  void emitResult(MCSymbol *Symbol, ArrayRef<MVT> Types) override;
  void emitLocal(ArrayRef<MVT> Types) override;
  void emitEndFunc() override;
  void emitIndirectFunctionType(MCSymbol *Symbol,
                                SmallVectorImpl<MVT> &Params,
                                SmallVectorImpl<MVT> &Results) override;
  void emitIndIdx(const MCExpr *Value) override;
  void emitGlobalImport(StringRef name) override;
  void emitImportModule(MCSymbolWasm *Sym, StringRef ModuleName) override;
};

/// This part is for Wasm object output
class WebAssemblyTargetWasmStreamer final : public WebAssemblyTargetStreamer {
public:
  explicit WebAssemblyTargetWasmStreamer(MCStreamer &S);

  void emitParam(MCSymbol *Symbol, ArrayRef<MVT> Types) override;
  void emitResult(MCSymbol *Symbol, ArrayRef<MVT> Types) override;
  void emitLocal(ArrayRef<MVT> Types) override;
  void emitEndFunc() override;
  void emitIndirectFunctionType(MCSymbol *Symbol,
                                SmallVectorImpl<MVT> &Params,
                                SmallVectorImpl<MVT> &Results) override;
  void emitIndIdx(const MCExpr *Value) override;
  void emitGlobalImport(StringRef name) override;
  void emitImportModule(MCSymbolWasm *Sym, StringRef ModuleName) override;
};

} // end namespace llvm

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<testadapter>
  <codec encode="json">
    <plugin id="com.testingtech.ttworkbench.json.rt">
      <parameter id="class" value="com.testingtech.ttworkbench.json.rt.JSONCodecPlugin"/>
    </plugin>
    <parameter id="taParams">
      <parameter id="pretty-print">
        <value>
          <Values:boolean xmlns:Values="Values.xsd" type="boolean">
            <Values:value>true</Values:value>
          </Values:boolean>
        </value>
      </parameter>
    </parameter>
    <parameter id="default" value="true"/>
  </codec>
  <extfunc>
    <plugin id="com.testingtech.playits.canfilter.control">
      <parameter id="class" value="com.testingtech.playits.canfilter.control.Car2XControlExternalFunctionProvider"/>
    </plugin>
  </extfunc>
  <port>
    <plugin id="com.testingtech.ttworkbench.tt3rt.tcp.port.TcpPortPlugin">
      <parameter id="class" value="com.testingtech.ttworkbench.tt3rt.tcp.port.TcpPortPluginProvider"/>
    </plugin>
    <parameter id="taParams">
      <parameter id="TCP_REMOTE_HOST" value="${Car2X_ModuleParameters.TCP_REMOTE_HOST}"/>
      <parameter id="TCP_REMOTE_PORT" value="${Car2X_ModuleParameters.TCP_REMOTE_PORT}"/>
      <parameter id="TCP_MODE">
        <value>
          <Values:charstring xmlns:Values="Values.xsd" type="charstring">
            <Values:value>mixed</Values:value>
          </Values:charstring>
        </value>
      </parameter>
      <parameter id="FILTER" value="${Car2X_ModuleParameters.FILTER}"/>
      <parameter id="TCP_SERVER_WAIT_TIME">
        <value>
          <Values:integer xmlns:Values="Values.xsd" type="integer">
            <Values:value>-1</Values:value>
          </Values:integer>
        </value>
      </parameter>
    </parameter>
    <parameter id="portType" value="Car2X_ConfigSystem.FilterPortType"/>
    <parameter id="default" value="true"/>
  </port>
</testadapter>


text:
package nl.esciencecenter.xenon.adaptors.ssh;

import nl.esciencecenter.xenon.XenonException;

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

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * @author Jason Maassen <J.Maassen@esciencecenter.nl>
 *
 */
class SshSession {

    private static final Logger LOGGER = LoggerFactory.getLogger(SshSession.class);

    private static final int MAX_OPEN_CHANNELS = 7;

    private final Session session;
    private final int tunnelPort;
    private final int sessionID;

    private ChannelSftp sftpChannelCache;
    private int openChannels = 0;

    SshSession(Session session, int tunnelPort, int sessionID) {
        this.session = session;
        this.tunnelPort = tunnelPort;
        this.sessionID = sessionID;
    }

    protected Session getSession() {
        return session;
    }

    protected int getTunnelPort() {
        return tunnelPort;
    }

    protected int getSessionID() {
        return sessionID;
    }

    protected boolean incOpenChannels(String info) {

        if (openChannels == MAX_OPEN_CHANNELS) {
            return false;
        }

        openChannels++;
        LOGGER.debug("SSHSESSION-{}: ++Open channels: {} {}", sessionID, openChannels, info);
        return true;
    }

    protected void decOpenChannels(String info) {
        openChannels--;
        LOGGER.debug("SSHSESSION-{}: --Open channels: {} {}", sessionID, openChannels, info);
    }

    protected ChannelSftp getSftpChannelFromCache() {
        ChannelSftp channel = sftpChannelCache;
        sftpChannelCache = null;
        return channel;
    }

    protected boolean putSftpChannelInCache(ChannelSftp channel) {

        if (sftpChannelCache != null) {

            if (sftpChannelCache == channel) {
                // If the given channel is the one that is currently cached, we should return true to
                // prevent the channel from being closed.
                return true;
            }

            return false;
        }

        sftpChannelCache = channel;
        return true;
    }

    protected void releaseExecChannel(ChannelExec channel) {
        LOGGER.debug("SSHSESSION-{}: Releasing EXEC channel", sessionID);
        channel.disconnect();
        decOpenChannels("EXEC");
    }

    protected void failedExecChannel(ChannelExec channel) {
        LOGGER.debug("SSHSESSION-{}: Releasing FAILED EXEC channel", sessionID);
        channel.disconnect();
        decOpenChannels("FAILED EXEC");
    }

    protected void releaseSftpChannel(ChannelSftp channel) {
        LOGGER.debug("SSHSESSION-{}: Releasing SFTP channel", sessionID);

        if (!putSftpChannelInCache(channel)) {
            channel.disconnect();
            decOpenChannels("SFTP");
        }
    }

    protected void failedSftpChannel(ChannelSftp channel) {
        LOGGER.debug("SSHSESSION-{}: Releasing FAILED SFTP channel", sessionID);
        channel.disconnect();
        decOpenChannels("FAILED SFTP");
    }

    protected void disconnect() {
        if (sftpChannelCache != null) {
            sftpChannelCache.disconnect();
        }

        session.disconnect();
    }

    protected ChannelExec getExecChannel() throws XenonException {

        if (openChannels == MAX_OPEN_CHANNELS) {
            return null;
        }

        ChannelExec channel = null;

        try {
            LOGGER.debug("SSHSESSION-{}: Creating EXEC channel {}", sessionID, openChannels);
            channel = (ChannelExec) session.openChannel("exec");
        } catch (JSchException e) {
            LOGGER.debug("SSHSESSION-{}: Failed to create EXEC channel {}", sessionID, openChannels, e);
            throw new XenonException(SshAdaptor.ADAPTOR_NAME, e.getMessage(), e);
        }

        incOpenChannels("EXEC");
        return channel;
    }

    protected ChannelSftp getSftpChannel() throws XenonException {

        ChannelSftp channel = getSftpChannelFromCache();

        if (channel != null) {
            LOGGER.debug("SSHSESSION-{}: Reusing SFTP channel {}", sessionID, openChannels);
            return channel;
        }

        if (openChannels == MAX_OPEN_CHANNELS) {
            return null;
        }

        try {
            LOGGER.debug("SSHSESSION-{}: Creating SFTP channel {}", sessionID, openChannels);
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
        } catch (JSchException e) {
            LOGGER.debug("SSHSESSION-{}: Failed to create SFTP channel {}", sessionID, openChannels, e);
            throw new XenonException(SshAdaptor.ADAPTOR_NAME, e.getMessage(), e);
        }

        incOpenChannels("SFTP");
        return channel;
    }

    protected int addTunnel(int localPort, String targetHost, int targetPort) throws XenonException {

        LOGGER.debug("SSHSESSION-{}: Creating tunnel from localhost:{} via {}:{} to {}:{}", sessionID, localPort,
                session.getHost(), session.getPort(), targetHost, targetPort);

        if (tunnelPort > 0) {
            LOGGER.debug("SSHSESSION-{}: Tunnel already in used for this session!", sessionID);
            throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Tunnel already in use!");
        }

        try {
            return session.setPortForwardingL(0, targetHost, targetPort);
        } catch (JSchException e) {
            LOGGER.debug("SSHSESSION-{}: Failed to create tunnel to {}:{}", sessionID, targetHost, targetPort, e);
            throw new XenonException(SshAdaptor.ADAPTOR_NAME, e.getMessage(), e);
        }
    }

    protected void removeTunnel(int localPort) throws XenonException {

        LOGGER.debug("SSHSESSION-{}: Removing tunnel at localhost:{}", sessionID, localPort);

        try {
            session.delPortForwardingL(localPort);
        } catch (JSchException e) {
            LOGGER.debug("SSHSESSION-{}: Failed to remove tunnel at localhost:{}", sessionID, localPort, e);
            throw new XenonException(SshAdaptor.ADAPTOR_NAME, e.getMessage(), e);
        }
    }
}


text:
package com.pugwoo.hessoa.utils;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

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

public class NetUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(NetUtils.class);

	public static class IPPort {
		public String ip;
		public int port;
		public IPPort(String ip, int port) {
			this.ip = ip;
			this.port = port;
		}
		@Override
		public boolean equals(Object obj) {
			if(obj == null || !(obj instanceof IPPort)) {
				return false;
			}
			IPPort object = (IPPort) obj;
			if(port != object.port) {
				return false;
			}
			if(ip == null) {
				return object.ip == null;
			}
			return ip.equals(object.ip);
		}
		@Override
		public int hashCode() {
			return this.port + (this.ip == null ? 0 : this.ip.hashCode());
		}
	}

	public static boolean isIpLAN(String ip) {
		for(int i = 0; i <= 3; i++) {
			if(isIpInRange(ip, i)) {
				return true;
			}
		}
		return false;
	}

	/**判断ipv4是否在某类局域网中,range=0本地,range=1为A类,range=2为B类, range=3为C类*/
	public static boolean isIpInRange(String ip, int range) {
		if(ip == null) {
			return false;
		}
		if(range == 0) {
			return ip.startsWith("127.");
		} else if(range == 1) {
			return ip.startsWith("10.");
		} else if(range == 2) {
			if(ip.startsWith("172.")) {
				String strs[] = ip.split("\\.");
				if(strs.length == 4) {
					int second = Integer.valueOf(strs[1]);
					if(second >= 16 && second <= 31) {
						return true;
					}
				}
			}
			return false;
		} else if (range == 3) {
			return ip.startsWith("192.168.");
		}

		return false;
	}

	public static IPPort parseIpPort(String url) {
		if(url == null) {
			return null;
		}

		int defaultPort = 80;
		if(url.startsWith("http://")) {
			url = url.substring("http://".length());
			defaultPort = 80;
		} else if (url.startsWith("https://")) {
			url = url.substring("https://".length());
			defaultPort = 443;
		}

		int index = url.indexOf("/");
		if(index >= 0) {
			url = url.substring(0, index);
		}

		index = url.indexOf(":");
		String ip = null;
		int port = 0;
		if(index > 0) {
			ip = url.substring(0, index);
			port = Integer.valueOf(url.substring(index + 1));
		} else {
			ip = url;
			port = defaultPort;
		}

		return new IPPort(ip, port);
	}

	/**
	 * 检查链接是否可以联通, url支持各种不规范的写法,
	 * 例如http://或https://开头等,例如192.168.1.22:8087。
	 * 超时配置取自Configs的超时配置
	 */
	public static boolean checkUrlAlive(IPPort ipPort) {
		if(ipPort == null || ipPort.ip == null) {
			return false;
		}

		Socket client = null;
		try {
			client = new Socket();
			client.connect(new InetSocketAddress(ipPort.ip, ipPort.port),
					Configs.getNetworkCheckTimeout());
			return true;
		} catch (Throwable e) {
			return false;
		} finally {
			if(client != null) {
				try {
					client.close();
				} catch (Throwable e) {
				}
			}
		}
	}

	/**
	 * 获得本机的ipv4的所有ip列表,返回的是网卡别称  到 ip 的map <br>
	 * 排除本机ip 127.开头的
	 * @return
	 */
	public static List<String> getIpv4IPs() {
		List<String> ips = new ArrayList<String>();
		String regex = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
		Pattern pattern = Pattern.compile(regex);
		try {
			for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
					ifaces.hasMoreElements();) {
				NetworkInterface iface = ifaces.nextElement();
				for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses.hasMoreElements();) {
					InetAddress address = addresses.nextElement();
					if(pattern.matcher(address.getHostAddress()).find() && !address.getHostAddress().startsWith("127.")) {
						ips.add(address.getHostAddress());
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("getIpv4IPs fail", e);
		}

		return ips;
	}

}


text:
package com.weisong.test.message.twoway;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import com.weisong.test.message.DeviceRequest;

@Getter @Setter @ToString(callSuper = true)
public class ChallengeCompleteRequest extends DeviceRequest {
    private Boolean successful;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".KotlinTestActivity">

    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Im kotlin activity."/>
</LinearLayout>


text:
package edu.neu.coe.info6205.equable;

import java.util.Collection;
import java.util.Iterator;

public class Equable {

    public Equable(Collection<?> elements) {
        this.elements = elements;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Equable equable = (Equable) o;
        Iterator<?> thisIterator = elements.iterator();
        Iterator<?> thatIterator = equable.elements.iterator();
        while (thisIterator.hasNext())
            if (thatIterator.hasNext()) {
                if (!thisIterator.next().equals(thatIterator.next())) return false;
            } else
                return false;
        return true;
    }

    @Override
    public int hashCode() {
        int result = 0;
        for (Object element : elements) result = 31 * result + element.hashCode();
        return result;
    }

    protected final Collection<?> elements;

}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package erp.lib.table;

import erp.lib.SLibConstants;

/**
 *
 * @author Sergio Flores
 */
public class STabFilterDateCutOff extends javax.swing.JPanel {

    private erp.client.SClientInterface miClient;
    private erp.lib.table.STableTabInterface miTableTab;

    private java.util.Date mtDate;
    private erp.lib.table.STableSetting moSetting;

    /** Creates new form DTabFilterDateCutOff */
    public STabFilterDateCutOff(erp.client.SClientInterface client, erp.lib.table.STableTabInterface tableTab) {
        this(client, tableTab, null);
    }

    /** Creates new form DTabFilterDateCutOff */
    public STabFilterDateCutOff(erp.client.SClientInterface client, erp.lib.table.STableTabInterface tableTab, java.util.Date dateCutOff) {
        miClient = client;
        miTableTab = tableTab;
        mtDate = dateCutOff;
        initComponents();
        initComponentsExtra();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jtfDate = new javax.swing.JTextField();
        jbDate = new javax.swing.JButton();
        jbSystemDate = new javax.swing.JButton();
        jbDateNull = new javax.swing.JButton();

        setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 3, 0));

        jtfDate.setEditable(false);
        jtfDate.setText("01/01/2000");
        jtfDate.setToolTipText("Fecha de corte");
        jtfDate.setFocusable(false);
        jtfDate.setPreferredSize(new java.awt.Dimension(65, 20));
        add(jtfDate);

        jbDate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_cal.gif"))); // NOI18N
        jbDate.setToolTipText("Seleccionar fecha de corte");
        jbDate.setPreferredSize(new java.awt.Dimension(23, 23));
        jbDate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbDateActionPerformed(evt);
            }
        });
        add(jbDate);

        jbSystemDate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_day.gif"))); // NOI18N
        jbSystemDate.setToolTipText("Hoy");
        jbSystemDate.setPreferredSize(new java.awt.Dimension(23, 23));
        jbSystemDate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSystemDateActionPerformed(evt);
            }
        });
        add(jbSystemDate);

        jbDateNull.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_null.gif"))); // NOI18N
        jbDateNull.setToolTipText("Quitar fecha de corte");
        jbDateNull.setPreferredSize(new java.awt.Dimension(23, 23));
        jbDateNull.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbDateNullActionPerformed(evt);
            }
        });
        add(jbDateNull);
    }// </editor-fold>//GEN-END:initComponents

    private void jbDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDateActionPerformed
        actionDate();
    }//GEN-LAST:event_jbDateActionPerformed

    private void jbSystemDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSystemDateActionPerformed
        mtDate = miClient.getSessionXXX().getWorkingDate();
        moSetting.setSetting(mtDate);
        miTableTab.updateSetting(moSetting);
        renderDate();
}//GEN-LAST:event_jbSystemDateActionPerformed

    private void jbDateNullActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDateNullActionPerformed
        mtDate = null;
        moSetting.setSetting(mtDate);
        miTableTab.updateSetting(moSetting);
        renderDate();
    }//GEN-LAST:event_jbDateNullActionPerformed

    private void initComponentsExtra() {
        moSetting = null;

        mtDate = null;  // The date is null because the user need to see all the documents at the beginning
        moSetting = new STableSetting(STableConstants.SETTING_FILTER_PERIOD, mtDate);
        miTableTab.addSetting(moSetting);
        renderDate();
    }

    private void renderDate() {
        if (mtDate == null) {
            jtfDate.setText("∞");
        }
        else {
            jtfDate.setText(miClient.getSessionXXX().getFormatters().getDateFormat().format(mtDate));
        }
    }

    private void actionDate() {
        if (mtDate == null) {
            mtDate = miClient.getSessionXXX().getWorkingDate();
        }

        miClient.getGuiDatePickerXXX().formReset();
        miClient.getGuiDatePickerXXX().setDate(mtDate);
        miClient.getGuiDatePickerXXX().setVisible(true);

        if (miClient.getGuiDatePickerXXX().getFormResult() == SLibConstants.FORM_RESULT_OK) {
            mtDate = miClient.getGuiDatePickerXXX().getGuiDate();
            moSetting.setSetting(mtDate);
            miTableTab.updateSetting(moSetting);
            renderDate();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbDate;
    private javax.swing.JButton jbDateNull;
    private javax.swing.JButton jbSystemDate;
    private javax.swing.JTextField jtfDate;
    // End of variables declaration//GEN-END:variables
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;

using Sce.Atf.Applications;

namespace MaterialTool
{
    [Export(typeof(ControlsLibraryExt.Material.ActiveMaterialContext))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class ActiveMaterialContext : ControlsLibraryExt.Material.ActiveMaterialContext
    {
        public override IEnumerable<string> AssignableTechniqueConfigs
        {
            get
            {
                foreach (var d in _documentRegistry.Documents)
                {
                    // if the document is a DiagramDocument with a TechniqueConfig
                    // enabled, we can consider it a candidate technique config
                    var doc = d as DiagramDocument;
                    if (doc == null) continue;

                    var gc = doc.UnderlyingDocument.GraphContext;
                    if (gc.HasTechniqueConfig)
                    {
                        var cwd = new Uri(System.IO.Directory.GetCurrentDirectory().TrimEnd('\\') + "\\");
                        var relTo = new Uri(cwd, "game/xleres/techniques/");
                        var t = relTo.MakeRelativeUri(doc.Uri).OriginalString;
                        var e = t.LastIndexOf('.'); // we must remove the extension... Using simple string parsing
                        if (e > 0) t = t.Substring(0, e);
                        yield return t;
                    }
                }
            }
        }

        [Import] IDocumentRegistry _documentRegistry;
    }
}


text:
package ma.glasnost.orika.test.converter;

import java.math.BigDecimal;

import org.junit.Assert;
import org.junit.Test;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.converter.CustomConverterBase;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.test.MappingUtil;

public class PrimitiveConversionTestCase {

	@Test
	public void testPrimitiveToWrapper() {
		MapperFactory factory = MappingUtil.getMapperFactory();
		factory.getConverterFactory().registerConverter(new CustomConverterBase<Double, BigDecimal>() {

			public BigDecimal convert(Double source,
			        Class<? extends BigDecimal> destinationType) {
				return BigDecimal.valueOf(source);
			}
		});

		factory.getConverterFactory().registerConverter(new CustomConverterBase<BigDecimal, Double>() {

			public Double convert(BigDecimal source,
					Class<? extends Double> destinationType) {
				return source.doubleValue();
			}
		});

		factory.registerClassMap(ClassMapBuilder.map(A.class, B.class).byDefault().toClassMap());

		A source = new A();
		source.setValue(BigDecimal.TEN);

		B target = factory.getMapperFacade().map(source, B.class);

		Assert.assertTrue(target.getValue() == 10.0);
	}

	public static class A {
		private BigDecimal value;

		public BigDecimal getValue() {
			return value;
		}

		public void setValue(BigDecimal value) {
			this.value = value;
		}

	}

	public static class B {
		private double value;

		public double getValue() {
			return value;
		}

		public void setValue(double value) {
			this.value = value;
		}

	}
}


text:
package com.firenio.codec.http2;

import com.firenio.component.Channel;

public class Http2Session {

    private Channel ch;

    private Http2Headers http2Headers = new Http2HeadersImpl();

    private boolean prefaceRead = true;

    private long[] settings = new long[]{0, 4096, 1, 128, 65535, 16384, 0};

    public Channel getChannel() {
        return ch;
    }

    public Http2Headers getHttp2Headers() {
        return http2Headers;
    }

    public long[] getSettings() {
        return settings;
    }

    public long getSettings(int i) {
        return settings[i];
    }

    public boolean isPrefaceRead() {
        return prefaceRead;
    }

    public void setChannel(Channel ch) {
        this.ch = ch;
    }

    public void setPrefaceRead(boolean prefaceRead) {
        this.prefaceRead = prefaceRead;
    }

    public void setSettings(int key, long value) {
        settings[key] = value;
    }

}


text:
struct Frame {
  double frameno;
  Bbox bounds;
  Frame(double frameno, const Bbox &bounds) : frameno(frameno), bounds(bounds) {}
  Frame() : frameno(-1) {}
};

#endif


text:
package v1alpha1

import (
	"context"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"knative.dev/eventing-rabbitmq/pkg/utils"
	"knative.dev/pkg/apis"
	"knative.dev/pkg/apis/duck"
	"knative.dev/pkg/kmp"
)

func (r *RabbitmqBrokerConfig) Validate(ctx context.Context) *apis.FieldError {
	if apis.IsInUpdate(ctx) {
		original := apis.GetBaseline(ctx).(*RabbitmqBrokerConfig)
		if original != nil {
			if diff, err := kmp.ShortDiff(original.Spec, r.Spec); err != nil {
				return &apis.FieldError{
					Message: "Failed to diff RabbitmqBrokerConfig",
					Paths:   []string{"spec"},
					Details: err.Error(),
				}
			} else if diff != "" {
				// spec is immutable
				return &apis.FieldError{
					Message: "Immutable fields changed",
					Paths:   []string{"spec"},
					Details: diff,
				}
			}
		}
	}

	if apiErr := utils.ValidateRabbitMQClusterReference(r.Spec.RabbitmqClusterReference); apiErr != nil {
		return apiErr
	}

	return nil
}

func ValidateRabbitmqBrokerConfig(ctx context.Context, unstructured *unstructured.Unstructured) error {
	if unstructured == nil {
		return nil
	}
	r := &RabbitmqBrokerConfig{}
	if err := duck.FromUnstructured(unstructured, r); err != nil {
		return err
	}
	return r.Validate(ctx)
}


text:
require_relative 'universe/world'

class Life

  # @param world [World]
  def initialize(world)
    @world = world
  end

  def evolve!
    go_alive_next_step = []
    go_dead_next_step = []

    @world.each do |cell|
      if cell.living_next_step?(@world)
        go_alive_next_step.push(cell)
      else
        go_dead_next_step.push(cell)
      end
    end

    go_alive_next_step.each do |cell|
      @world.cell_live!(cell)
    end

    go_dead_next_step.each do |cell|
      @world.cell_die!(cell)
    end
  end

  def each
    @world.each do |cell|
      yield cell
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
PathMatchingResourcePatternResolver (Spring Framework)
</TITLE>

<META NAME="keywords" CONTENT="org.springframework.core.io.support.PathMatchingResourcePatternResolver class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.springframework.core.io.support

Class PathMatchingResourcePatternResolver

java.lang.Object
  org.springframework.core.io.support.PathMatchingResourcePatternResolver

All Implemented Interfaces:
ResourcePatternResolver

public class PathMatchingResourcePatternResolver
extends java.lang.Object
implements ResourcePatternResolver

ResourcePatternResolver that applies Ant-style path matching, using Spring's
 PathMatcher class.

Locations can either be suitable for ResourceLoader.getResource
 (URLs like "file:C:/context.xml", pseudo-URLs like "classpath:/context.xml",
 relative file paths like "/WEB-INF/context.xml"), or Ant-style patterns
 like "/WEB-INF/*-context.xml".

In the pattern case, the locations have to be resolvable to java.io.File,
 to allow for searching though the specified directory tree. In particular,
 this will neither work with WAR files that are not expanded nor with class
 path resources in a JAR file.

There is special support for retrieving multiple class path resources with
 the same name, via the "classpath*" prefix. For example, "classpath*:/beans.xml"
 will find all beans.xml files in the class path, be it in "classes" directories
 or in JAR files. This is particularly useful for auto-detecting config files.

If neither given a PathMatcher pattern nor a "classpath*:" location, this
 resolver will return a single resource via the underlying ResourceLoader.

Since:

01.05.2004

Author:

Juergen Hoeller

See Also:
ResourcePatternResolver.CLASSPATH_URL_PREFIX,
PathMatcher,
ResourceLoader.getResource(java.lang.String)

Field Summary

protected  org.apache.commons.logging.Log
logger

Fields inherited from interface org.springframework.core.io.support.ResourcePatternResolver

CLASSPATH_URL_PREFIX

Constructor Summary

PathMatchingResourcePatternResolver()

          Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader.

PathMatchingResourcePatternResolver(java.lang.ClassLoader classLoader)

          Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader.

PathMatchingResourcePatternResolver(ResourceLoader resourceLoader)

          Create a new PathMatchingResourcePatternResolver.

PathMatchingResourcePatternResolver(ResourceLoader resourceLoader,
                                    java.lang.ClassLoader classLoader)

          Create a new PathMatchingResourcePatternResolver.

Method Summary

protected  java.lang.String
determineRootDir(java.lang.String location)

          Determine the root directory for the given location.

protected  void
doRetrieveMatchingFiles(java.lang.String fullPattern,
                        java.io.File dir,
                        java.util.List result)

          Recursively retrieve files that match the given pattern,
 adding them to the given result list.

protected  Resource[]
findAllClassPathResources(java.lang.String location)

          Find all class location resources with the given location via the ClassLoader.

protected  Resource[]
findPathMatchingFileResources(java.lang.String locationPattern)

          Find all file resources that match the given location pattern
 via the Ant-style PathMatcher utility.

 java.lang.ClassLoader
getClassLoader()

          Return the ClassLoader that this pattern resolver works with,
 or null if using the thread context class loader on actual access
 (applying to the thread that does the "getResources" call).

 ResourceLoader
getResourceLoader()

          Return the ResourceLoader that this pattern resolver works with.

 Resource[]
getResources(java.lang.String locationPattern)

          Resolve the given location pattern into Resource objects.

protected  java.util.List
retrieveMatchingFiles(java.io.File rootDir,
                      java.lang.String pattern)

          Retrieve files that match the given path pattern,
 checking the given directory and its subdirectories.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

logger

protected final org.apache.commons.logging.Log logger

Constructor Detail

PathMatchingResourcePatternResolver

public PathMatchingResourcePatternResolver()

Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader.

ClassLoader access will happen via the thread context class loader on actual
 access (applying to the thread that does the "getResources" call)

See Also:
DefaultResourceLoader

PathMatchingResourcePatternResolver

public PathMatchingResourcePatternResolver(java.lang.ClassLoader classLoader)

Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader.

Parameters:
classLoader - the ClassLoader to load classpath resources with,
 or null for using the thread context class loader on actual access
 (applying to the thread that does the "getResources" call)
See Also:
DefaultResourceLoader

PathMatchingResourcePatternResolver

public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader)

Create a new PathMatchingResourcePatternResolver.

ClassLoader access will happen via the thread context class loader on actual
 access (applying to the thread that does the "getResources" call)

Parameters:
resourceLoader - ResourceLoader to load root directories
 and actual resources with

PathMatchingResourcePatternResolver

public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader,
                                           java.lang.ClassLoader classLoader)

Create a new PathMatchingResourcePatternResolver.

Parameters:
resourceLoader - ResourceLoader to load root directories
 and actual resources with
classLoader - the ClassLoader to load classpath resources with,
 or null for using the thread context class loader on actual access
 (applying to the thread that does the "getResources" call)

Method Detail

getResourceLoader

public ResourceLoader getResourceLoader()

Return the ResourceLoader that this pattern resolver works with.

getClassLoader

public java.lang.ClassLoader getClassLoader()

Return the ClassLoader that this pattern resolver works with,
 or null if using the thread context class loader on actual access
 (applying to the thread that does the "getResources" call).

getResources

public Resource[] getResources(java.lang.String locationPattern)
                        throws java.io.IOException

Description copied from interface: ResourcePatternResolver

Resolve the given location pattern into Resource objects.

Specified by:
getResources in interface ResourcePatternResolver

Parameters:
locationPattern - the location pattern to resolve

Returns:
the corresponding Resource objects

Throws:

java.io.IOException - in case of I/O errors

findAllClassPathResources

protected Resource[] findAllClassPathResources(java.lang.String location)
                                        throws java.io.IOException

Find all class location resources with the given location via the ClassLoader.

Parameters:
location - the absolute path within the classpath

Returns:
the result as Resource array

Throws:

java.io.IOException - in case of I/O errors
See Also:
ClassLoader.getResources(java.lang.String)

findPathMatchingFileResources

protected Resource[] findPathMatchingFileResources(java.lang.String locationPattern)
                                            throws java.io.IOException

Find all file resources that match the given location pattern
 via the Ant-style PathMatcher utility.

Parameters:
locationPattern - the location pattern to match

Returns:
the result as Resource array

Throws:

java.io.IOException - in case of I/O errors
See Also:
PathMatcher

determineRootDir

protected java.lang.String determineRootDir(java.lang.String location)

Determine the root directory for the given location.

Used for determining the starting point for file matching,
 resolving the root directory location to a java.io.File and
 passing it into retrieveMatchingFiles, with the
 remainder of the location as pattern.

Will return "/WEB-INF" for the pattern "/WEB-INF/*.xml",
 for example.

Parameters:
location - the location to check

Returns:
the part of the location that denotes the root directory
See Also:
retrieveMatchingFiles(java.io.File, java.lang.String)

retrieveMatchingFiles

protected java.util.List retrieveMatchingFiles(java.io.File rootDir,
                                               java.lang.String pattern)
                                        throws java.io.IOException

Retrieve files that match the given path pattern,
 checking the given directory and its subdirectories.

Parameters:
rootDir - the directory to start from
pattern - the pattern to match against,
 relative to the root directory

Returns:
the List of matching File instances

Throws:

java.io.IOException - if directory contents could not be retrieved

doRetrieveMatchingFiles

protected void doRetrieveMatchingFiles(java.lang.String fullPattern,
                                       java.io.File dir,
                                       java.util.List result)
                                throws java.io.IOException

Recursively retrieve files that match the given pattern,
 adding them to the given result list.

Parameters:
fullPattern - the pattern to match against,
 with preprended root directory path
dir - the current directory
result - the list of matching files to add to

Throws:

java.io.IOException - if directory contents could not be retrieved

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (C) 2003-2004 The Spring Framework Project.


text:
// See http://www.graphics.rwth-aachen.de/redmine/projects/acgl/wiki/ACGL_compile_time_settings
// for a comment what unsupported means.
#ifdef deprecated

#include <ACGL/OpenGL/HiLevelObjects/RenderObject.hh>
#if (ACGL_OPENGL_VERSION >= 30)

#include <ACGL/OpenGL/Tools.hh>
#include <ACGL/Utils/StringHelpers.hh>
#include <ACGL/OpenGL/Data/LocationMappings.hh>

#include <iostream>
#include <fstream>

using namespace ACGL::Base;
using namespace ACGL::Utils;
using namespace ACGL::OpenGL;

void RenderObject::updateMappings()
{
    /*
    if (mpFrameBufferObject) {
        // set ShaderProgram out-mappings by the definition of the FBO
        mpShaderProgramObject->getShaderProgram()->setFragmentDataLocations( mpFrameBufferObject->getAttachmentLocations() );
    }

    mpVertexArrayObject->setAttributeLocations( mpShaderProgramObject->getShaderProgram()->getAttributeLocations() );
    */
}

void RenderObject::enableFrameBufferObject() const
{
    glGetIntegerv( GL_FRAMEBUFFER_BINDING, &mLastFBO );

    if(mpFrameBufferObject)
    {
        mpFrameBufferObject->bind();
    }
    else
    {
        glBindFramebuffer( GL_FRAMEBUFFER, 0 );
    }
}

void RenderObject::disableFrameBufferObject() const
{
    glBindFramebuffer( GL_FRAMEBUFFER, mLastFBO );
}

void RenderObject::enableShaderProgramObject() const
{
    glGetIntegerv( GL_CURRENT_PROGRAM, &mLastShaderProgram );
    mpShaderProgramObject->use();
}

void RenderObject::disableShaderProgramObject() const
{
    glUseProgram( mLastShaderProgram );
}

void RenderObject::enableVertexArrayObject() const
{
    // remember old VAO
    glGetIntegerv( GL_VERTEX_ARRAY_BINDING, &mLastVAO );

    mpVertexArrayObject->bind();
}

void RenderObject::disableVertexArrayObject() const
{
    glBindVertexArray( mLastVAO );
}

void RenderObject::enableViewport() const
{
    mLastViewport.setFromGLContext();

    if(mpViewport)
    {
        mpViewport->use();
    } else if (mpFrameBufferObject) {
        glm::uvec3 size = mpFrameBufferObject->getSize();
        glViewport( 0, 0, size.x, size.y );
    }
}

void RenderObject::disableViewport() const
{
    mLastViewport.use();
}

#endif

#endif


text:
module Capistrano
  module Tincan
    VERSION = '0.1.0'
  end
end


text:
// Copyright [2011] [PagSeguro Internet Ltda.]
//
//   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.

using System;
using System.Collections.Generic;
using Uol.PagSeguro.Util;

namespace Uol.PagSeguro.Domain
{
    /// <summary>
    /// Represents the party on the transaction that is sending the money
    /// </summary>
    public class Sender
    {

        private IList<SenderDocument> _documents;

        /// <summary>
        /// Sender name
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Sender email
        /// </summary>
        public string Email
        {
            get;
            set;
        }

        /// <summary>
        /// Sender phone number
        /// </summary>
        public Phone Phone
        {
            get;
            set;
        }

        /// <summary>
        /// Sender documents
        /// </summary>
        public IList<SenderDocument> Documents
        {
            get
            {
                if(this._documents == null)
                {
                    this._documents = new List<SenderDocument>();
                }
                return this._documents;
            }
            set { this._documents = value; }
        }

        internal Sender()
        {
        }

        /// <summary>
        /// Initializes a new instance of the Sender class
        /// </summary>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="areaCode"></param>
        /// <param name="number"></param>
        /// <param name="type"></param>
        /// <param name="value"></param>
        public Sender(string name, string email, string areaCode, string number, string type, string value)
        {
            this.Name = name;
            this.Email = email;
            this.Phone = new Phone(areaCode, number);
            this.Documents.Add(new SenderDocument(type,value));
        }

        /// <summary>
        /// Initializes a new instance of the Sender class
        /// </summary>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="phone"></param>
        public Sender(string name, string email, Phone phone)
        {
            this.Name = name;
            this.Email = email;
            this.Phone = phone;
        }

        /// <summary>
        /// Gets toString class
        /// </summary>
        /// <returns>string</returns>
        public override string  ToString()
        {
            return "Sender [name=" + Name + ", email=" + Email + ", phone=" + Phone
                    + ", documents=" + Documents + "]";
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="@string/edit" android:id="@+id/edit_list" android:titleCondensed="@string/edit"></item>
<item android:id="@+id/delete_list" android:title="@string/delete" android:titleCondensed="@string/delete"></item>

</menu>


text:
<?php
/**
 * Created by PhpStorm.
 * User: Fehiniaina
 * Date: 17/02/15
 * Time: 17:59
 */
namespace Server\OAuthBundle\Repository;

use Doctrine\ORM\EntityRepository;

class UsersRepository extends EntityRepository
{

    public function getUserByToken($token)
    {
        $sql = 'SELECT u.*
                FROM users u
                JOIN accesstoken ac ON u.id = ac.client_id
                WHERE ac.token="'.$token.'"';

        $query = $this->getEntityManager()
                      ->getConnection()
                      ->prepare($sql);

        $query->execute();
        $result = $query->fetchAll();

        return $result;

    }

}


text:
package com.lunatic.mlx.cuisines.mllib

import com.lunatic.mlx.cuisines.Configuration
import org.apache.spark.mllib.clustering.KMeans
import org.apache.spark.{SparkConf, SparkContext}

object KMeansTrainer {

  def main(args: Array[String]) = {

    val conf = new SparkConf(true).setAppName(this.getClass.getSimpleName).
      setMaster("local[*]")

    implicit val sc = new SparkContext(conf)
    implicit val configuration = Configuration(args)

    val flowData = FlowData.load(configuration.dataPath)

    val parsedData = flowData.data.map(lp => lp.features)

    // Cluster the data into two classes using KMeans
    val numClusters = 20
    val numIterations = 1000
    val runs = 5
    val clusters = KMeans.train(parsedData, numClusters, numIterations, runs)

    // Evaluate clustering by computing Within Set Sum of Squared Errors
    val WSSSE = clusters.computeCost(parsedData)
    println("Within Set Sum of Squared Errors = " + WSSSE)

    val predictionsClusters =  flowData.data.map(lp => (lp.label.toInt, clusters.predict(lp.features)))

    predictionsClusters.groupBy(_._1).collect.foreach{case (label, pred) =>

      val clustersWeights = pred.map(x => x._2)
        .groupBy(x => x).map(x => (x._1, x._2.size))
        .toSeq.sortBy(x => x._2).reverse.take(5)
        .map(x => f"${x._1}%2d : ${x._2}%4d")
        .mkString(" | ")

      println(f"| ${flowData.indexToLabel(label)}%-20s | ${label}%02d | ${clustersWeights} | ")
    }

  }
}


text:
package net.typedrest.vaadin.views;

import com.google.common.eventbus.EventBus;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Window;

/**
 * Base class for building view components that use an {@link EventBus} and can
 * be wrapped in {@link Window}s.
 */
public abstract class ViewComponent
        extends CustomComponent implements View {

    /**
     * Used to send event between components.
     */
    protected final EventBus eventBus;

    /**
     * Creates a new view component.
     *
     * @param eventBus Used to send event between components.
     */
    protected ViewComponent(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    private boolean eventBusRegistered;

    @Override
    public void attach() {
        super.attach();

        if (!eventBusRegistered) {
            eventBus.register(this);
            eventBusRegistered = true;
        }
    }

    @Override
    public void detach() {
        if (eventBusRegistered) {
            eventBus.unregister(this);
            eventBusRegistered = false;
        }

        super.detach();
    }

    /**
     * Opens a child component as a {@link Window}.
     *
     * @param component The child component to open.
     */
    protected void open(ViewComponent component) {
        getUI().addWindow(component.asWindow());
    }

    private Window containingWindow;

    /**
     * Wraps the control in a {@link Window}.
     *
     * @return The newly created window.
     */
    protected Window asWindow() {
        if (containingWindow == null) {
            containingWindow = new Window(getCaption(), this);
            containingWindow.setWidth(80, Unit.PERCENTAGE);
            containingWindow.setHeight(80, Unit.PERCENTAGE);
            containingWindow.center();
        }
        return containingWindow;
    }

    /**
     * Closes the containing {@link Window}.
     */
    protected void close() {
        if (containingWindow != null) {
            containingWindow.close();
        }
    }

    @Override
    public void setCaption(String caption) {
        super.setCaption(caption);
        if (containingWindow != null) {
            containingWindow.setCaption(caption);
        }
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
    }
}


text:
<?php

defined('_JEXEC') or die;

/**
 * Content categories view.
 *
 * @package     Joomla.Site
 * @subpackage  com_content
 * @since       1.5
 */
class ContentViewCategories extends JViewCategories
{
	/**
	 * Language key for default page heading
	 *
	 * @var    string
	 * @since  3.2
	 */
	protected $pageHeading = 'JGLOBAL_ARTICLES';

	/**
	 * @var    string  The name of the extension for the category
	 * @since  3.2
	 */
	protected $extension = 'com_content';
}


text:
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Eto.Addin.VisualStudio.Wizards
{
	public class RootWizard : IWizard
	{
		public static Dictionary<string, string> Globals = new Dictionary<string, string>();

		public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
		{
			foreach (var replacement in replacementsDictionary)
				Globals[replacement.Key] = replacement.Value;
		}

		public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
		{
		}

		public void ProjectFinishedGenerating(EnvDTE.Project project)
		{
		}

		public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
		{
		}

		public void RunFinished()
		{
		}

		public bool ShouldAddProjectItem(string filePath)
		{
			return true;
		}
	}
}


text:
package pl.stqa.pft.sandbox;

import org.testng.annotations.Test;
import org.testng.Assert;

public class PrimeTests {

  @Test
  public void testPrimes() {
    Assert.assertTrue(Primes.isPrime(Integer.MAX_VALUE));
  }

  @Test
  public void testNoPrime() {
    Assert.assertFalse(Primes.isPrime(Integer.MAX_VALUE - 2));
  }
}


text:
@class FLStringToObjectConversionManager;
@class FLParsedXmlElement;

@interface FLXmlObjectBuilder : NSObject {
@private
    FLStringToObjectConversionManager* _decoder;

    BOOL _strict;
}
@property (readwrite, assign, nonatomic) BOOL strict;
@property (readonly, strong,nonatomic) FLStringToObjectConversionManager* decoder;

- (id) initWithDataDecoder:(FLStringToObjectConversionManager*) decoder;
+ (id) xmlObjectBuilder:(FLStringToObjectConversionManager*) decoder;
+ (id) xmlObjectBuilder;

- (id) buildObjectOfClass:(Class) aClass withXML:(FLParsedXmlElement*) element;
- (id) buildObjectOfType:(NSString*) type withXML:(FLParsedXmlElement*) element;

@end

#define FLXmlObjectBuilderErrorDomain @"FLXmlObjectBuilderErrorDomain"

typedef NS_ENUM(NSInteger, FLXmlObjectBuilderError) {
    FLXmlObjectBuilderErrorUnknownProperty = 1,
    FLXmlObjectBuilderErrorObjectNotInflated

};


text:
class Rect {
    constructor(x, y, w, h, bouncy=false) {
	    this._x = x;
	    this._left = x;
	    this._y = y;
	    this._top = y;
	    this._w = w;
	    this._h = h;

	    this._vx = 0; //velocity X
	    this._vy = 0; //velocity Y

	    this._centerx = x + ( w / 2 );
	    this._centery = y + ( h / 2 );
	    this._center = [this._centerx, this._centery];

	    this._right = x + w;
	    this._bottom = y + h;

	    this.bouncy = bouncy;
	    this.direction = 0;
    }
    get x() { return this._x; }
    get y() { return this._y; }
    get w() { return this._w; }
    get h() { return this._h; }
    get left() { return this._x; }
    get top() { return this._y; }
    get right() { return this._right; }
    get bottom() { return this._bottom; }
    get centerx() { return this._centerx; }
    get centery() { return this._centery; }
    get center() { return this._center; }
    get vx() { return this._vx; }
    get vy() { return this._vy; }

    set x(value) {
    	this._x = value;
    	this._left = value;
    	this._right = this._w + value;
    	this.RecalcCenter();
    }
    set y(value) {
    	this._y = value;
    	this._top = value;
		this._bottom = this._h + value;
    	this.RecalcCenter();
    }
    set w(value) {
    	value = Math.abs(value);
    	this._w = value;
    	this._right = this._x + value;
    	this.RecalcCenter();
    }
    set h(value) {
    	value = Math.abs(value);
    	this._h = value;
    	this._bottom = this._y + value;
    	this.RecalcCenter();
    }
    set left(value) {
    	this._x = value;
    	this._left = value;
    	this._right = this._w + value;
    	this.RecalcCenter();
    }
    set top(value) {
    	this._y = value;
    	this._top = value;
		this._bottom = this._h + value;
    	this.RecalcCenter();
    }
    set right(value) {
    	this._right = value;
    	this._x = value - this._w;
    	this._left = this._x;
    	this.RecalcCenter();
    }
    set bottom(value) {
    	this._bottom = value;
    	this._y = value - this._h;
		this._top = this._y;
    	this.RecalcCenter();
    }
    set centerx(value){
    	this._centerx = value;
    	this._x = value - (this._w / 2);
    	this._left = this._x;
    	this._right = this._x + this._w;
    }
    set centery(value){
    	this._centery = value;
    	this._y = value - (this._h / 2);
    	this._top = this._y;
    	this._bottom = this._y + this._h;
    }
    set center(xytuple){
    	this._center = xytuple;
    	x = xytuple[0];
    	y = xytuple[1];

    	this._x = value - (this._w / 2);
    	this._left = this._x;
    	this._right = this._x + this._w;

    	this._y = value - (this._y / 2);
    	this._top = this._y;
    	this._bottom = this._y + this._h;
    }

    set vx(value){
    	this._vx = value;
    	if (!value && !this.vy) {return;}
    	this.direction = Math.atan2(this.vy, value);
    }

    set vy(value){
    	this._vy = value;
    	if (!value && !this.vx) {return;}
    	this.direction = Math.atan2(value, this.vx);
    }

    RecalcCenter(){
    	this._centerx = this._x + (this._w / 2);
    	this._centery = this._y + (this._h / 2);
    	this._center = (this._centerx, this._centery);
    }

    collidePoint(x, y){
    	//is the rect overlapping this point?
    	return (this._left <= x && x < this._right) && (this._top <= y && y < this._bottom);
    }
    collideRect(otherRect){
    	//are the rects colliding?
    	//there is probably a better way to do this ------ not anymore! (this used to be bad)
    	//x axis
    	let differencex = Math.abs(this.centerx - otherRect.centerx);
    	let x = differencex < (this.w + otherRect.w) / 2  - 0.0001;
    	//y axis
    	let differencey = Math.abs(this.centery - otherRect.centery);
    	let y = differencey < (this.h + otherRect.h) / 2 - 0.0001;
    	return x && y;
    }
    contains(otherRect){ //true if otherRect is completely inside this rect.
    	return (this.left <= otherRect.left && this.right >= otherRect.right) && (this.top <= otherRect.top && this.bottom >= otherRect.bottom);
    }
    clamp_ip(otherRect){ //move other rect fully inside this one. Will center the rect if the container is smaller.
    	//if (this.contains(otherRect)) {return;}
    	if (this.left > otherRect.left) {
    		otherRect.left = this.left;
    	}
    	else if (this.right < otherRect.right) {
    		otherRect.right = this.right;
    	}
    	if (this.top > otherRect.top) {
    		otherRect.top = this.top;
    	}
    	else if (this.bottom < otherRect.bottom) {
    		otherRect.bottom = this.bottom;
    	}
    }

    expell_ip(otherRect){ //fully exert otherRect so that it does not collide with this rect anymore
    	//NOTE:additionally returns axis adjusted in array
    	//Will pick the shortest path to move it out.
    	if (!this.collideRect(otherRect)) {return [false, false];} //assuming that there is a collision

    	//what is the shortest path to move this rect out?

    	let differencex = this.centerx - otherRect.centerx;
    	let differencey = this.centery - otherRect.centery;

    	if (Math.abs(differencex) >= Math.abs(differencey)) {
    		if (differencex < 0) {
	    		otherRect.x = this.right;
	    	}
	    	else{
	    		otherRect.right = this.left;
	    	}
	    	return [true, false];
    	}
    	else{
    		if (differencey < 0){
	    		otherRect.y = this.bottom;
	    	}
	    	else{
	    		otherRect.bottom = this.top;
	    	}
	    	return [false, true];
    	}
    }

    expell(otherRect){
    	let newRect = new Rect(0,0,0,0);
    	newRect.copyFromOther(otherRect);
    	this.expell_ip(newRect);
    	return newRect;
    }

    clamp(otherRect){ //not really very useful, but...
    	let newRect = new Rect(0,0,0,0);
    	newRect.copyFromOther(otherRect);
    	this.clamp_ip(newRect);
    	return newRect;
    }

    draw(canvas, color){
    	canvas.fillStyle = color;
    	canvas.fillRect(this._x, this._y, this._w, this._h);
    }
    drawImage(canvas, image){
    	canvas.drawImage(image, Math.round(this.x), Math.round(this.y), Math.round(this.w), Math.round(this.h));
    }
    drawText(canvas, text, font='sans-serif', color='white', stroke=true) //Draws text not exceeding the size of the rect.
    {
    	let size = this.h;
    	canvas.font = `${size}px ${font}`;
    	if (canvas.measureText(text).width > this.w) {
    		size = measureTextBinaryMethod(text, font, 0, Math.min(this.h, 600), this.w, canvas);
			canvas.font = `${size}px ${font}`;
    	}
    	canvas.fillStyle = color;
    	canvas.textAlign = 'center';
    	canvas.fillText(text, this.centerx, this.centery, this.w);
    	if (stroke) {
    		canvas.lineWidth = size / 30;
      		canvas.strokeStyle = `lightgray`;
    		canvas.strokeText(text, this.centerx, this.centery, this.w);
    	}
    }
    drawOutline(canvas, color){
    	canvas.strokeStyle = color;
    	canvas.lineWidth=1;
    	canvas.beginPath();
    	canvas.rect(this.x, this.y, this.w, this.h);
		canvas.stroke();
    }
    copyFromOther(otherRect){
    	this.x = otherRect.x;
    	this.y = otherRect.y;
    	this.h = otherRect.h;
    	this.w = otherRect.w;

    	this.vx = otherRect.vx;
    	this.vy = otherRect.vy;
    }
    centerIn(otherRect){
    	this.centerx = otherRect.centerx;
    	this.centery = otherRect.centery;
    }
}

class Player extends Rect{
	constructor(x, y, w, h, direction, speed) {
		super(x,y,w,h);
		this.direction = direction;
		this.speed = speed;
    }
}

class Bullet extends Rect{
	constructor(x, y, w, h, direction, speed, lifeSpan=5000) {
		super(x,y,w,h);
		this.direction = direction; //in radians
		this.born = Date.now();
		this.lifeSpan = lifeSpan; //in milliseconds
		this.death = this.born + this.lifeSpan;

		this.vx = Math.cos(direction);
		this.vy = Math.sin(direction);
    }
}

class Asteroid extends Rect{
	constructor(x, y, w, h, rotation=0, scale=1, lifeSpan=30000) {
		super(x,y,w,h, true);
		this.born = Date.now();
		this.lifeSpan = lifeSpan;
		this.death = this.born + this.lifeSpan;
		this.rotation = rotation;
		this.scale = scale;
    }

}