text:
namespace ARKBreedingStats.ocr
{
    /// <summary>
    /// Lookup table to count set bits of a number.
    /// </summary>
    public static class HammingWeight
    {
        // Hamming-weight lookup-table, https://en.wikipedia.org/wiki/Hamming_weight

        private static byte[] _bitCounts = new byte[byte.MaxValue + 1];

        private static bool _hammingIsInitialized;

        /// <summary>
        /// Returns the number of 1-bits in an uint. E.g. 3 == 0b11 => 2, 4 == 0b100 => 1, 7 == 0b111 => 3.
        /// </summary>
        private static byte BitsSetCountWegner(uint input)
        {
            byte count;
            for (count = 0; input != 0; count++)
            {
                input &= input - 1; // turn off the rightmost 1-bit
            }
            return count;
        }

        /// <summary>
        /// Initialized bit counts if not yet done.
        /// </summary>
        public static void InitializeBitCounts()
        {
            if (_hammingIsInitialized) return;

            //// for ushort
            //_bitCounts = new byte[ushort.MaxValue + 1];
            //_bitCounts[ushort.MaxValue] = 16;

            // for byte
            _bitCounts = new byte[byte.MaxValue + 1];
            _bitCounts[byte.MaxValue] = 8;

            //for (uint i = 0; i < ushort.MaxValue; i++)
            for (uint i = 0; i < byte.MaxValue; i++)
                _bitCounts[i] = BitsSetCountWegner(i);

            _hammingIsInitialized = true;
        }

        /// <summary>
        /// Returns the number of set bits in the passed value.
        /// To compare two integers pass with xor ^
        /// </summary>
        public static int SetBitCount(byte i) => _bitCounts[i];
        //public static int SetBitCount(uint i) => _bitCounts[i & 0xFFFF] + _bitCounts[(i >> 16) & 0xFFFF];
    }
}


text:
/**
* Handles connecting and communicating with our API's,
* this module wraps our Socket so we can replace it if
* needs be.
**/

/**
* Get our modules
**/
const pkg           = require('../package.json');
const Log           = require('./utils/log');
const S             = require('string');
const args          = require('./utils/args');
const Payload       = require('./payload');
const async         = require('async');
const _             = require('lodash');
const fs            = require('fs');
const url           = require('url');
const dns           = require('dns');
const request       = require('request');
const Config        = require('./config');
const stdin         = require('./utils/stdin');
const api           = require('./api');

/**
*
**/
Client = {};

/**
* Load in the commands
**/
Client.commands = {

  version:      require('./commands/version'),
  subscribe:    require('./commands/subscribe'),
  submit:       require('./commands/submit'),
  get:          require('./commands/get'),
  whoami:       require('./commands/token.get'),
  tokenSet:     require('./commands/token.set'),
  balance:      require('./commands/balance'),
  connect:      require('./commands/connect'),
  disconnect:   require('./commands/disconnect'),
  websites:     require('./commands/websites'),
  website:      require('./commands/website')

};

/**
* Creates the current payload for us to use till the end
**/
Client.payload = Payload;

/**
* Returns the current payload
**/
Client.getPayload = function() { return Client.payload; };

/**
* Handles the formatted output
**/
Client.handleOutput = function(err) {

  // clear the timeout checker
  if(Client.commandTimer) clearInterval(Client.commandTimer);

  // get the event ended
  var ended = new Date();

  /**
  * did we get a error ? If so exist with =1,
  * we rely on the commands to output errors
  * as they see we fit in this case.
  **/
  if(err) {

    // run the track
    return api.track({

      key:      'exception',
      message:  (err.message || '').toString() + ': ' + (err.stack || '').toString(),
      type:     'error'

    }, function(){

      // exit badly
      process.exit(1);

    });

  }

  // get the our payload we used
  var payload = Client.getPayload();
  var output  = '';

  // check the format given
  if(args.format == 'json') {

    // output the JSON
    output = payload.getJSON();

  } else {

    // output the text version
    output = payload.getText();

  }

  // should we write out ?
  if( S(args.o).isEmpty() === false ) {

    // yeap write it out to file
    fs.writeFile(args.o, output, function(err) {

      // check the error
      if(err) {

        // output our error
        Log.error('Could not write to the specified output file', err);

      }

      // wait till next callback event
      setTimeout(function(){

        // do the actual exit
        process.exit(payload.getExecCode());

      }, 0);

    });

  } else if(output !== null &&
              output !== undefined) {

    // output the text version
    process.stdout.write(output + '\n', function() {

      // wait till next callback event
      setTimeout(function(){

        // do the actual exit
        process.exit(payload.getExecCode());

      }, 0);

    });

  } else {

    // wait till next callback event
    setTimeout(function(){

      // do the actual exit
      process.exit(payload.getExecCode());

    }, 0);

  }

};

/**
* Executes the given command
**/
Client.executeCommand = function(path) {

  // make sure to trim the path
  cleanedPath = S(path).trim().s.toLowerCase();

  // get the payload to use
  var payload = Client.getPayload();
  var body    = payload.getBody();

  // set a timeout for STDIN
  Client.commandTimer = setInterval(function() {

    // get the last activte time
    if(new Date().getTime() - payload.getLastActive() > 1000 * 60) {

      // output to log
      Log.error('\nCommand timed out after 60 seconds of complete inactivity');

      // exit with a 1
      return process.exit(1);

    }

  }, 1000 * 10);

  // according to the path, route our command
  if(cleanedPath == 'version') {

    // route to version
    Client.commands.version(payload, Client.handleOutput);

  } else if(cleanedPath == 'websites') {

    // route to websites
    Client.commands.websites(payload, Client.handleOutput);

  } else if(cleanedPath.indexOf('websites') == 0 && path.split(' ').length == 2) {

    // route to token
    Client.commands.website(payload, Client.handleOutput);

  } else if(cleanedPath.indexOf('get') == 0) {

    // route to token
    Client.commands.get(payload, Client.handleOutput);

  } else if(cleanedPath.indexOf('connect') == 0 && path.split(' ').length == 2) {

    // route to token
    Client.commands.tokenSet(payload, Client.handleOutput);

  } else if(cleanedPath == 'whoami') {

    // route to token
    Client.commands.whoami(payload, Client.handleOutput);

  } else if(cleanedPath == 'user') {

    // route to token
    Client.commands.whoami(payload, Client.handleOutput);

  } else if(cleanedPath.indexOf('invite') === 0) {

    // route to token
    Client.commands.subscribe(payload, Client.handleOutput);

  } else if(cleanedPath == 'connect') {

    // route to version
    Client.commands.connect(payload, Client.handleOutput);

  } else if(cleanedPath == 'disconnect') {

    // route to version
    Client.commands.disconnect(payload, Client.handleOutput);

  } else if(cleanedPath == 'balance') {

    // route to token
    Client.commands.balance(payload, Client.handleOutput);

  } else {

    // find all the urls to run/crawl
    var urls = body.split(args.delimiter || Client.guessDelimiter(body));

    // urls that failed and cleaned
    var cleanedUrls        = [];
    var failedUrls         = [];

    // loop and validate the requested urls
    async.each(urls, function(givenUrl, cb) {

      // skip if empty
      if(S(givenUrl).isEmpty() == true) return cb(null);

      // validate it
      Client.validateURL(givenUrl, function(err, result, parsedUrl) {

        // return the return
        if(result === true) {

          // add as cleaned
          cleanedUrls.push(url.format(parsedUrl));

          // return as good
          return cb(null);

        }

        // ok so this was not a valid givenUrl
        failedUrls.push(givenUrl);

        // log
        Log.error(givenUrl + ' did not validate as a URL', err);

        // done with no problems, move on
        cb(err);

      });

    }, function(err) {

      // handle a error
      if(err) {

        // exit the process
        return process.exit(1);

      }

      // handle a error
      if(failedUrls.length > 0) {

        // exit the process
        return process.exit(1);

      }

      // check if we actually got any to run
      if(cleanedUrls.length == 0) {

        // show the error
        Log.error('No urls supplied, usage - passmarked example.com');

        // done
        process.exit(1);

      }

      // set our payload
      payload.setTargets(cleanedUrls);

      // try to run it
      Client.commands.submit(payload, Client.handleOutput);

    });

  }

};

/**
* Tries to figure out what the delimiter is
**/
Client.guessDelimiter = function(body) {

  // the max we found on one of the options
  var max           = 0;

  // the final delimiter we want got from the guess
  var delimiter     = null;

  // list of delimiters we have seen
  var delimiters    = [ '\n', ',', '|', '\t', '\r\n' ];

  // loop each and find check if bigger than max
  for(var i = 0; i < delimiters.length; i++) {

    // get the count of a split
    var count = body.split(delimiters[i]).length;

    // split the string
    if(count > max) {

      // set the new max
      max       = count;
      delimiter = delimiters[i];

    }

  }

  // default to newline
  return delimiter || '\n';

};

/**
* Prefixes http:// if not present
**/
Client.prefixMissingProtocol = function(givenUrl) {

  // if already specified just return
  if( S( givenUrl.toLowerCase() ).startsWith('http://') ||
        S( givenUrl.toLowerCase() ).startsWith('https://') )
    return givenUrl;

  // else return it now
  return 'http://' + givenUrl;

};

/**
* Validates the body before starting a report
**/
Client.validateURL = function(givenUrl, fn) {

  // clean the url
  var cleanedURL  = S(givenUrl).trim().s;

  // add missing protocol if not present
  cleanedURL      = Client.prefixMissingProtocol(givenUrl);

  // url we are going to be using after parse
  var uri         = null;

  try {

    // parse the url
    uri = url.parse(cleanedURL);

  } catch(err) { /** Override with our error **/ }

  // did we get a uri component ?
  if(!uri) return fn(null, false);

  // ok so parse out the hostname
  var hostname    = uri.hostname;
  var ip          = null;

  // must be either a ip or a
  if(
    hostname.match(/[\d]+\.[\d]+\.[\d]+\.[\d]+/gi) !== null ||
    hostname.match(/(([a-zA-Z0-9]{1,4}|):){1,7}([a-zA-Z0-9]{1,4}|:)/gi) !== null) {

    // it's a ip already
    ip = hostname;

    // awesome move on
    fn(null, true, uri);

  } else {

    // start tracking duration
    var resolveStarted = new Date();

    // try to resolve the domain
    dns.lookup(hostname, {}, function(err, address, family) {

      // start tracking duration
      var resolveEnded = new Date();

      // get the duration
      var duration = resolveEnded.getTime() - resolveStarted.getTime();

      // did we get a error ?
      if(err) {

        return api.resolve({

          records:  null,
          family:   null,
          domain:   hostname,
          duration: duration,
          servers:  dns.getServers().join(',')

        }, function() {

          // what type of error ?
          fn(err, false);

        });

      }

      // record to save
      if(!address) {

        return api.resolve({

          records:  null,
          family:   null,
          domain:   hostname,
          duration: duration,
          servers:  dns.getServers().join(',')

        }, function() {

          // what type of error ?
          fn(err, false);

        });

      }

      // add anounymous resolution to shield database
      api.resolve({

        records:  address,
        family:   'IPV' + family,
        domain:   hostname,
        duration: duration,
        servers:  dns.getServers().join(',')

      }, function() {

        // sanity check that we got a address ?
        if(!address) return fn(null, false);

        // got the the ip
        ip = address;

        // awesome move on
        fn(null, true, uri);

      });

    });

  }

};

/**
* Starts the actual CLI client
**/
Client.boot = function() {

  // set the timestamp
  Client.started = new Date();

  // create our config file
  Config.build(function(){

    // set our payload command
    Client.getPayload().setCommand(args._.join(' '));

    /**
    * Checks if any actual path arguments
    * were given
    **/
    if(args.in) {

      /**
      * Read the file in
      **/
      fs.readFile(args.in, function(err, data) {

        // handle a error if any
        if(err) {

          // output to log
          Log.error('Something went wrong while reading in the input file', err);

          // exit with a 1
          return process.exit(1);

        }

        // set the content that we read in
        Client.getPayload().setBody( data.toString() );

        // Find the command
        Client.executeCommand( Client.getPayload().getCommand() );

      });

    } else if(!args._[0]) {

      // set a timeout for STDIN
      var stdinTimer = setTimeout(function() {

        // kill it then

        // output to log
        Log.error('Nothing for 5 seconds, killing instance');

        // exit with a 1
        return process.exit(1);

      }, 1000 * 5);

      /**
      * Start reading in the STDIN
      **/
      stdin.read(function(err, content){

        // stop timer
        clearTimeout(stdinTimer);

        // handle a error if any
        if(err) {

          // output to log
          Log.error('Something went wrong while reading STDIN', err);

          // exit with a 1
          return process.exit(1);

        }

        // set the content that we read in
        Client.getPayload().setBody(content);

        // Find the command
        Client.executeCommand( Client.getPayload().getCommand() );

      });

    } else {

      // set the body as the params passed
      Client.getPayload().setBody( Client.getPayload().getCommand() );

      // execute the actual command
      Client.executeCommand(Client.getPayload().getCommand());

    }

  });

};

/**
* Expose the Client
**/
module.exports = exports = Client;

redpajama_set_name: RedPajamaGithub


text:
/**
 @param {object} element
 @param {string} type
 @param {string} crossType
 @param {Function} listener
 @param {boolean} [useCapture]
 */
var addListener = function(element, type, crossType, listener, useCapture) {
	if (window.addEventListener)
		element.addEventListener(type, listener, !!useCapture);
	else element.attachEvent(crossType ? crossType : type, listener);
};

var isOnArray = function(arr, value) {

	for (var i = arr.length; i--; )
		if (arr[i] == value)
			return true;

	return false;

};

/* Scroll To */

var getScrollTop = function() {
	var doc = document.documentElement;
	return (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
};

// easing functions http://goo.gl/5HLl8
Math.easeInOutQuad = function (t, b, c, d) {
	t /= d/2;
	if (t < 1) {
		return c/2*t*t + b
	}
	t--;
	return -c/2 * (t*(t-2) - 1) + b;
};

Math.easeInCubic = function(t, b, c, d) {
	var tc = (t/=d)*t*t;
	return b+c*(tc);
};

Math.inOutQuintic = function(t, b, c, d) {
	var ts = (t/=d)*t,
		tc = ts*t;
	return b+c*(6*tc*ts + -15*ts*ts + 10*tc);
};

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = (function(){
	return  window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };
})();

function scrollTo(to, callback, duration) {
	// because it's so fucking difficult to detect the scrolling element, just move them all
	function move(amount) {
		document.documentElement.scrollTop = amount;
		document.body.parentNode.scrollTop = amount;
		document.body.scrollTop = amount;
	}
	function position() {
		return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop;
	}
	var start = position(),
		change = to - start,
		currentTime = 0,
		increment = 20;
	duration = (typeof(duration) === 'undefined') ? 500 : duration;
	var animateScroll = function() {
		// increment the time
		currentTime += increment;
		// find the value with the quadratic in-out easing function
		var val = Math.easeInOutQuad(currentTime, start, change, duration);
		// move the document.body
		move(val);
		// do the animation unless its over
		if (currentTime < duration) {
			requestAnimFrame(animateScroll);
		} else {
			if (callback && typeof(callback) === 'function') {
				// the animation is done so lets callback
				callback();
			}
		}
	};
	animateScroll();
}


text:
@class NSString;

@interface DBMessageBizExt : NSObject <WCDBCoding>
{
    unsigned int msgLocalId;
    unsigned int msgType;
    unsigned int msgInnerType;
    unsigned int msgExtColInt1;
    unsigned int msgExtColInt2;
    NSString *chatUsername;
    NSString *bizId;
    NSString *msgExtColString1;
    NSString *msgExtColString2;
    long long m___rowID;
}

+ (const basic_string_a490aa4c *)getWCDBPrimaryColumnName;
+ (const struct WCDBIndexHelper *)getWCDBIndexArray;
+ (unsigned long long)getWCDBIndexArrayCount;
+ (const map_0e718273 *)getFileValueTagIndexMap;
+ (id)getFileValueTypeTable;
+ (const map_0e718273 *)getPackedValueTagIndexMap;
+ (id)getPackedValueTypeTable;
+ (const map_7a576766 *)getValueNameIndexMap;
+ (id)getValueTable;
+ (id)dummyObject;
@property(nonatomic) long long __rowID; // @synthesize __rowID=m___rowID;
@property(retain, nonatomic) NSString *msgExtColString2; // @synthesize msgExtColString2;
@property(retain, nonatomic) NSString *msgExtColString1; // @synthesize msgExtColString1;
@property(nonatomic) unsigned int msgExtColInt2; // @synthesize msgExtColInt2;
@property(nonatomic) unsigned int msgExtColInt1; // @synthesize msgExtColInt1;
@property(retain, nonatomic) NSString *bizId; // @synthesize bizId;
@property(nonatomic) unsigned int msgInnerType; // @synthesize msgInnerType;
@property(nonatomic) unsigned int msgType; // @synthesize msgType;
@property(nonatomic) unsigned int msgLocalId; // @synthesize msgLocalId;
@property(retain, nonatomic) NSString *chatUsername; // @synthesize chatUsername;
- (void).cxx_destruct;
- (const map_0e718273 *)getValueTagIndexMap;
- (id)getValueTypeTable;
- (const WCDBCondition_22fabacd *)db_msgExtColString2;
- (const WCDBCondition_22fabacd *)db_msgExtColString1;
- (const WCDBCondition_c6db074e *)db_msgExtColInt2;
- (const WCDBCondition_c6db074e *)db_msgExtColInt1;
- (const WCDBCondition_22fabacd *)db_bizId;
- (const WCDBCondition_c6db074e *)db_msgInnerType;
- (const WCDBCondition_c6db074e *)db_msgType;
- (const WCDBCondition_c6db074e *)db_msgLocalId;
- (const WCDBCondition_22fabacd *)db_chatUsername;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
/*
 * (c)2016-2017, Cris Luengo.
 * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
 *
 * 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.
 */

namespace dip {
namespace Feature {

class FeatureMajorAxes : public Composite {
   public:
      FeatureMajorAxes() : Composite( { "MajorAxes", "Principal axes of the binary object", false } ) {};

      virtual ValueInformationArray Initialize( Image const& label, Image const&, dip::uint /*nObjects*/ ) override {
         nD_ = label.Dimensionality();
         ValueInformationArray out = MuEigenVectorInformation( nD_, label.PixelSize() );
         hasIndex_ = false;
         return out;
      }

      virtual StringArray Dependencies() override {
         StringArray out( 1 );
         out[ 0 ] = "Mu";
         return out;
      }

      virtual void Compose( Measurement::IteratorObject& dependencies, Measurement::ValueIterator output ) override {
         auto it = dependencies.FirstFeature();
         if( !hasIndex_ ) {
            muIndex_ = dependencies.ValueIndex( "Mu" );
            hasIndex_ = true;
         }
         dfloat const* data = &it[ muIndex_ ];
         FloatArray tmp( nD_ );
         SymmetricEigenDecompositionPacked( nD_, data, tmp.data(), output );
      }

   private:
      dip::uint muIndex_;
      bool hasIndex_;
      dip::uint nD_;
};

} // namespace feature
} // namespace dip


text:
require('./fake-uri-parser-factory');

angular
.module('fake')
.factory('FakePath', [
  '$httpBackend',
  'FakeUriParser',
  ($httpBackend, FakeUriParser) => {

    return class FakePath {

      constructor(path) {
        this.$$parser = new FakeUriParser(path);
      }

      $$makeRequest(method, url, data, headers) {
        return {
          method: method,
          url: url,
          data: data,
          headers: headers,
          params: this.$$parser.parse(url)
        };
      }

      $$makeResponse() {
        return {
          send: (status = 200, ...data) => [status, ...data]
        };
      }

      $$makeResponder(config) {
        return (method, url, data, headers) => {
          let response = [0];

          if(angular.isArray(config) && angular.isNumber(config[0])) {
            response = config;
          } else if(angular.isNumber(config)) {
            response = [config];
          } else if(angular.isFunction(config)) {
            let requestObject = this.$$makeRequest(method, url, data, headers),
                responseObject = this.$$makeResponse();

            response = config(requestObject, responseObject) || [0];
          }

          return response;
        };
      }

      $$setupHttpBackend(method, config) {
        return $httpBackend
          .when(method.toUpperCase(), this.$$parser.pattern)
          .respond(this.$$makeResponder(config));
      };

      when(configs) {
        Object.keys(configs).forEach((method) => {
          this.$$setupHttpBackend(method, configs[method]);
        });
      };
    };
  }
]);


text:
package org.vafer.drift.generator;

import java.io.IOException;

public interface CodeWriter {

	void write( final String sourceName, final String sourceContent ) throws IOException;
}


text:
package com.vittaw.mvplibrary.utils;

import android.content.Context;
import android.view.Window;
import android.view.WindowManager;

/**
 * Created by Administrator on 2017/3/27 0027.
 */

public class ScreenUtil {

    private static int widthPixels;
    private static int heightPixels;

    public static int getScreenWidth(Context context){
        if (widthPixels == 0){
            widthPixels = context.getResources().getDisplayMetrics().widthPixels;
        }
        return widthPixels;
    }

    public static int getScreenHeight(Context context){
        if (heightPixels == 0){
            heightPixels = context.getResources().getDisplayMetrics().heightPixels;
        }
        return heightPixels;
    }

}


text:
#pragma once
#include <aws/chime/Chime_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Chime
{
namespace Model
{
  class AWS_CHIME_API LogoutUserResult
  {
  public:
    LogoutUserResult();
    LogoutUserResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    LogoutUserResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace Chime
} // namespace Aws


text:
{% extends "base.html" %}

{% block title %}{{ profile_user.username }} | user page{% endblock %}

{% block content %}

{{ profile_user.username }}

Joined: {{ profile_user.date_joined|date:"d F Y" }}

{% endblock %}


text:
package dpnm.tool;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintStream;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import dpnm.mobiledevice.policy.ruleobjects.Rule;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Timer;

import dpnm.Conf;
import dpnm.mobiledevice.MobileApplication;
import dpnm.mobiledevice.event.*;
import dpnm.mobilenode.MobileNodeFactory;
import dpnm.network.NetworkFactory;
import dpnm.network.device.NetworkDevice;
import dpnm.server.ContextServer;
import dpnm.server.Server;
import dpnm.tool.comp.*;
import dpnm.tool.data.*;
import dpnm.util.*;

/**
 * This class is for simulating networks
 *
 * @author eliot
 *
 */
public class HMNNetworkSimulator extends JFrame
	implements ActionListener, MouseMotionListener, UpdateListener, MouseWheelListener,
		MobileNodeComponentManager, NetworkHandoverListener, ChangeListener, MouseListener {
	/**
	 *
	 */
	private static final long serialVersionUID = -4321782005899245361L;

	/*
	 * Owner of This GUI
	 */
	private HMNEmulator owner = null;
	private NetworkMapInfo mapInfo = null;
	private long interval = 0;

	private NetworkPlayer player = null;

	private JTextField fileFld = null;

	private JTextField background = null;
	private JTextField randomFile = null;

	private boolean isIconMode = false;

	private long duration = 0;
	private long end = 0;

    /* toolbar button */
	private static final String toolbarBtnStr[][][] = {
			{
    			{"Open", Resources.OPEN_ICON, "Open", "Open"},
			},
			{
				{"Run", Resources.RUN_ICON, "RunNetwork", "Run Network Emulator"},
				{"Stop", Resources.STOP_ICON, "StopNetwork", "Stop Network Emulator"},
			},
			{
				{"MonitorView", Resources.MONITOR_ICON, "LaunchMonitorView", "Launch Monitor View"}
			},
			{
				{"Export MAP PNG", Resources.EXPORT_ICON, "Export", "Export PNG image..."},
				{"Export Graph PNG", Resources.EXPORT_ICON, "ExportGraph", "Export Graph PNG image..."}
			},
			{
				{"Random Simulation", Resources.SIMULATOR_ICON, "RandomSimulation", "Generate Network Map Randomly"}
			}
	};

	//	speed rate
	private JSlider speedRateBar = null;
	private double speedRate = 1.0;

	private Vector<NetworkComponent> networks;
	private Vector<MobileNodeSimComponent> mnodes;
	private Vector<ServerComponent> snodes;
	private ContextServer currentContextServer = null;

	/*	UI */
	static ResourceFinder rf = new ResourceFinder();

	Image deviceImg[] = new Image[Resources.DEVICE_IMG_STR.length];
	Image mobileNodeImg[] = new Image[Resources.MOBILENODE_IMG_STR.length];
	Image serverImg[] = new Image[Resources.SERVER_IMG_STR.length];

	private DesComponent desComp = new DesComponent();

	/*	View */
	private NetworkMapView view = null;
	private JTabbedPane tp = null;
	private JTabbedPane ntp = null;
	private JTabbedPane mtp = null;
	private JList networkList = null;
	private JList mnodeList = null;
	private JTextArea numberNetwork = null;
	private JTextArea numberMobileNode = null;
	private DefaultListModel networkListModel = null;
	private DefaultListModel mnodeListModel = null;

	private StatusBar statusBar = new StatusBar();

	private JTextArea mNodeArea = null;
	private JTextArea networkArea = null;
	private JTextArea handoverInfoArea = null;

	/*	Monitor View */
	private MonitorView monitorView = null;

	/*	Simulation Result View */
	private SimulationResultView resultView = null;

	/*	Timer */
	private Timer timer = null;
	private TimerTask task = null;

	/*	Select network and mobile node */
	private JCheckBox networkCheckBox[] = null;
	private JCheckBox mobileNodeCheckBox[] = null;
	private JToggleButton networkBtn = null;
	private JToggleButton mNodeBtn = null;

	public HMNNetworkSimulator(HMNEmulator owner, String title) {
		super(title);
		this.owner = owner;

		setIconImage(getToolkit().getImage(rf.getURL(
				Resources.ICON_DIR+File.separator+Resources.SIMULATOR_ICON)));

		player = new NetworkPlayer();

		networks = new Vector<NetworkComponent>();
		mnodes = new Vector<MobileNodeSimComponent>();
		snodes = new Vector<ServerComponent>();

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setSize(Env.SIMULATOR_WIDTH, Env.SIMULATOR_HEIGHT);
		setBounds((screenSize.width/2) - (Env.SIMULATOR_WIDTH/2),
				(screenSize.height/2) - (Env.SIMULATOR_HEIGHT/2),
				Env.SIMULATOR_WIDTH, Env.SIMULATOR_HEIGHT);

		loadImages();

		createUI();
		createView();

		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				exit();
			}
    		}
    	);
		setZoom(1.0);
		setSimState("STOPPED");
		setTime(duration);

		timer = dpnm.util.UpdateTimer.getInstance().getTimer();
	}

	boolean isIconMode() {
		return isIconMode;
	}

	void setIconMode(boolean isIconMode) {
		this.isIconMode = isIconMode;
	}

	private void loadImages() {
		//	load images
		for (int i = 0; i < Resources.DEVICE_IMG_STR.length; i++) {
			deviceImg[i] = rf.getImage(Resources.DEVICE_DIR +
					Resources.DEVICE_IMG_STR[i]);
		}
		for (int i = 0; i < Resources.SERVER_IMG_STR.length; i++) {
			serverImg[i] = rf.getImage(Resources.SERVER_DIR +
					Resources.SERVER_IMG_STR[i]);
		}
	}

	private void createUI() {
		JPanel contentPane = new JPanel();
		contentPane.setLayout(new BorderLayout());
		contentPane.add(createToolBar(), BorderLayout.NORTH);
		contentPane.add(createComponentToolBar(), BorderLayout.WEST);
		contentPane.add(statusBar, BorderLayout.SOUTH);
		setContentPane(contentPane);
	}

    private JToolBar createToolBar()
    {
        JToolBar toolBar = new JToolBar() ;
        for (int i = 0; i < toolbarBtnStr.length; i++) {
            for (int j = 0; j < toolbarBtnStr[i].length; j++) {
                JButton button = new HoverButton(toolbarBtnStr[i][j][0],
                rf.getIcon(Resources.ICON_DIR+toolbarBtnStr[i][j][1]));
                button.setActionCommand(toolbarBtnStr[i][j][2]);
                button.setToolTipText(toolbarBtnStr[i][j][3]);
                button.addActionListener(this);
                toolBar.add(button);
            }
            toolBar.addSeparator();
        }

        speedRateBar = new JSlider(JSlider.HORIZONTAL, 1, 40, 10);
        speedRateBar.addChangeListener(this);
        speedRateBar.setMajorTickSpacing(1);
        speedRateBar.setPaintTicks(true);
        //Create the label table
        Hashtable labelTable = new Hashtable();
        labelTable.put( new Integer( 1 ), new JLabel("0.1") );
        labelTable.put( new Integer( 10 ), new JLabel("1.0") );
        labelTable.put( new Integer( 20), new JLabel("2.0") );
        labelTable.put( new Integer( 30), new JLabel("3.0") );
        labelTable.put( new Integer( 40), new JLabel("4.0") );
        speedRateBar.setLabelTable( labelTable );
        speedRateBar.setPaintLabels(true);
        toolBar.add(speedRateBar);
//        toolBar.add(new Label("                    "));
        toolBar.addSeparator(new Dimension(50, 20));

        return toolBar ;
    }

    private JToolBar createComponentToolBar() {
    	JToolBar toolBar = new JToolBar(JToolBar.VERTICAL);

    	String networkNames[] = NetworkFactory.getInstance().getNetworkNames();

    	JLabel label = new JLabel("Networks");
    	toolBar.add(label);
//        JButton button = new HoverButton("Select All");
        networkBtn = new JToggleButton("Select All");
        networkBtn.setToolTipText("Select All Networks");
        networkBtn.setSelected(true);
        networkBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                	for (int i = 0; i < networkCheckBox.length; i++) {
                		networkCheckBox[i].setSelected(networkBtn.isSelected());
                	}
            		for (int j = 0; j < networks.size(); j++) {
        				networks.elementAt(j).setVisible(networkBtn.isSelected());
            		}
                }
            });
        toolBar.add(networkBtn);
        networkCheckBox = new JCheckBox[networkNames.length];
    	for (int i = 0; i < networkNames.length; i++) {
            networkCheckBox[i] = new JCheckBox(networkNames[i], true);
            networkCheckBox[i].setToolTipText("Show/Hide " + networkNames[i] + " Network");
            networkCheckBox[i].addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                	//	toggle visible flag;
                	if (e.getSource() instanceof JCheckBox) {
                		boolean isVisible = ((JCheckBox)e.getSource()).isSelected();
                		String name = ((JCheckBox)e.getSource()).getText();
                		for (int j = 0; j < networks.size(); j++) {
                			if (networks.elementAt(j).getDeviceInfo().getDevice().getNetworkStr().intern() ==
                				name.intern()) {
                				networks.elementAt(j).setVisible(isVisible);
                			}
                		}
                		view.repaint();
                	}
                }
            });
            toolBar.add(networkCheckBox[i]);
    	}

    	toolBar.addSeparator();

    	String mNodeNames[] = MobileNodeFactory.getInstance().getMobileNodeNames();

    	label = new JLabel("Mobile Nodes");
    	toolBar.add(label);
        mNodeBtn = new JToggleButton("Select All");
        mNodeBtn.setToolTipText("Select All Mobile Nodes");
        mNodeBtn.setSelected(true);
        mNodeBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                	for (int i = 0; i < mobileNodeCheckBox.length; i++) {
                		mobileNodeCheckBox[i].setSelected(mNodeBtn.isSelected());
                	}
            		for (int j = 0; j < mnodes.size(); j++) {
        				mnodes.elementAt(j).setVisible(mNodeBtn.isSelected());
            		}

                }
            });
        toolBar.add(mNodeBtn);

        mobileNodeCheckBox = new JCheckBox[mNodeNames.length];
    	for (int i = 0; i < mNodeNames.length; i++) {
            mobileNodeCheckBox[i] = new JCheckBox(mNodeNames[i],
        					HMNEmulatorGUI.getResizedImage(
        					Resources.MOBILENODE_DIR+File.separator+
        							MobileNodeFactory.getInstance().getMobileNodeAt(i).getIconStr(), 16, 16),
        					true);
            mobileNodeCheckBox[i].setSelectedIcon(HMNEmulatorGUI.getCheckedResizedImage(
        					Resources.MOBILENODE_DIR+File.separator+
        							MobileNodeFactory.getInstance().getMobileNodeAt(i).getIconStr(), 16, 16));
            mobileNodeCheckBox[i].setToolTipText("Show/Hide " + mNodeNames[i] + " Mobile Node");
            mobileNodeCheckBox[i].setSelected(true);
            mobileNodeCheckBox[i].addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                	//	toggle visible flag;
                	if (e.getSource() instanceof JCheckBox) {
                		boolean isVisible = ((JCheckBox)e.getSource()).isSelected();
                		String name = ((JCheckBox)e.getSource()).getText();
                		for (int j = 0; j < mnodes.size(); j++) {
                			if (mnodes.elementAt(j).getDeviceInfo().getMobileNode().getName().intern() ==
                				name.intern()) {
                				mnodes.elementAt(j).setVisible(isVisible);
                			}
                		}
                		view.repaint();
                	}
                }
            });
            toolBar.add(mobileNodeCheckBox[i]);
    	}

    	return toolBar;

    }

	private void createView() {
    	view = new NetworkMapView();
		view.setBackground(Color.white);
		view.setLayout(null);

        view.setPreferredSize(new Dimension(Env.VIEW_WIDTH, Env.VIEW_HEIGHT));
        JScrollPane js = new JScrollPane(view, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        tp = new JTabbedPane();
        tp.addTab(Env.TAB_TITLE+" []", js);

        networkArea = new JTextArea();
        JScrollPane js2 = new JScrollPane(networkArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        tp.addTab("Network Status", js2);

        mNodeArea = new JTextArea();
        JScrollPane js3 = new JScrollPane(mNodeArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        tp.addTab("Mobile Node Status", js3);

        handoverInfoArea = new JTextArea();
        JScrollPane js4 = new JScrollPane(handoverInfoArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        tp.addTab("Handover Status", js4);

        resultView = new SimulationResultView();
        tp.addTab("Simulation Performance", new JScrollPane(resultView));

		//	add listeners
        view.addMouseMotionListener(this);
        view.addMouseWheelListener(this);
        view.addMouseListener(this);

        ntp = new JTabbedPane();
        networkListModel = new DefaultListModel();
        networkList = new JList(networkListModel);
        ntp.addTab("Networks", new JScrollPane(networkList));

        numberNetwork = new JTextArea();
        numberNetwork.setEditable(false);
        ntp.addTab("# of Network", new JScrollPane(numberNetwork));
        ntp.setToolTipTextAt(1, "Number of each network");

        mtp = new JTabbedPane();
        mnodeListModel = new DefaultListModel();
        mnodeList = new JList(mnodeListModel);
        mtp.addTab("Mobile Nodes", new JScrollPane(mnodeList));

        numberMobileNode = new JTextArea();
        numberMobileNode.setEditable(false);
        mtp.addTab("# of Mobile Node", new JScrollPane(numberMobileNode));
        mtp.setToolTipTextAt(1, "Number of each mobile node");

        JPanel leftPane = new JPanel();
        leftPane.setLayout(new GridLayout(2,1));
        leftPane.add(ntp);
        leftPane.add(mtp);
		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
		                           tp, leftPane);
		splitPane.setOneTouchExpandable(true);
		splitPane.setDividerLocation(Env.VIEW_WIDTH-100);

		//Provide minimum sizes for the two components in the split pane
		Dimension minimumSize = new Dimension(100, 50);
		tp.setMinimumSize(minimumSize);
		leftPane.setMinimumSize(minimumSize);

        getContentPane().add(splitPane, BorderLayout.CENTER);
	}

	void setViewTitle(String mapName) {
        tp.setTitleAt(0, Env.TAB_TITLE+" [" +
    		(mapName != null ? mapName : "")+" - ("+interval+" ms)");
	}

	void setNetworkTitle(int count) {
		ntp.setTitleAt(0, "Networks ("+count+")");
	}

	void setMnodeTitle(int count) {
		mtp.setTitleAt(0, "Mobile Nodes ("+count+")");
	}

	void loadNetworkMapInfo(NetworkMapInfo mapInfo) {
		if (mapInfo == null) {
			return;
		}
		this.mapInfo = mapInfo;
        view.setPreferredSize(new Dimension(mapInfo.getWidth(), mapInfo.getHeight()));

    	if (mapInfo !=null && mapInfo.getBackground() != null &&
         		!mapInfo.getBackground().equalsIgnoreCase("")) {
            JLabel label = new JLabel();
            label.setLocation(0,0);
            label.setIcon(getBackgroundImage(
						Resources.MAP_DIR+mapInfo.getBackground(),
						mapInfo.getWidth(), mapInfo.getHeight()));
            label.setSize(new Dimension(mapInfo.getWidth(), mapInfo.getHeight()));
            view.add(label,0);
    	}
    	NetworkDeviceInfo[] info = mapInfo.getDevices();
    	if (info != null) {
        	for (int i = 0; i < info.length; i++) {
        		NetworkComponent comp = new NetworkComponent(this);
        		comp.setDeviceInfo(info[i]);
                comp.setIcon(deviceImg[info[i].getIcon()], info[i].getIcon());
                comp.setSim(true);
        		view.add(comp,0);
                networks.add(comp);
                networkListModel.addElement(info[i]);
        	}
    	}
    	setNetworkTitle(networkListModel.getSize());
    	// # of each network
    	int count[] = owner.getEachNetworkCount(info);
    	for (int i = 0; count != null && i < count.length; i++) {
    		numberNetwork.append(NetworkFactory.getInstance().getNetworkNameAt(i) + ": " + count[i]+"\n");
    	}

    	NetworkMobileNodeInfo[] nodeInfo = mapInfo.getMnodes();
    	if (nodeInfo != null) {
        	for (int i = 0; i < nodeInfo.length; i++) {
        		MobileNodeSimComponent comp = new MobileNodeSimComponent(isIconMode);
        		comp.setNetworkMobileNodeInfo(nodeInfo[i]);
                comp.setIcon(nodeInfo[i].getMobileNode().getIcon());
        		view.add(comp,0);
                mnodes.add(comp);
                mnodeListModel.addElement(nodeInfo[i]);

                nodeInfo[i].initializeMove();
                nodeInfo[i].getDevice().getNetworkInterfaceManager().addNetworkHandoverListener(this);
        	}
    	}
    	setMnodeTitle(mnodeListModel.getSize());

    	// # of each mobile node
    	count = owner.getEachMobileNodeCount(nodeInfo);
    	for (int i = 0; count != null && i < count.length; i++) {
    		numberMobileNode.append(MobileNodeFactory.getInstance().getMobileNodeNameAt(i) + ": " + count[i]+"\n");
    	}
    	player.loadNetworkMapInfo(mapInfo);

    	//	simulation result graph
    	resultView.setMobileNodeInfo(nodeInfo);

    	setMnodeTitle(mnodeListModel.getSize());
    	ServerInfo[] serverInfo = mapInfo.getServers();
    	if (nodeInfo != null) {
        	for (int i = 0; i < serverInfo.length; i++) {
        		ServerComponent comp = new ServerComponent();
        		comp.setServerInfo(serverInfo[i]);
    			comp.setIcon(serverImg[serverInfo[i].getType()]);
        		view.add(comp,0);
                snodes.add(comp);

                if (serverInfo[i].getServer().getType() == Server.CONTEXT) {
                	currentContextServer = (ContextServer)serverInfo[i].getServer();
                }
                //	add network server listener
//                nodeInfo[i].getDevice().getNetworkInterfaceManager().addNetworkHandoverListener(this);
        	}
    	}

		addDesComponent();

		updateInfo();

        repaint();
	}

	void reset() {
		mapInfo = null;
		if (networks != null)
			networks.removeAllElements();
		if (mnodes != null) {
			for (int i = 0; i < mnodes.size(); i++) {
				mnodes.elementAt(i).getDeviceInfo().getDevice().getNetworkInterfaceManager().removeNetworkHandoverListener(this);
			}
			mnodes.removeAllElements();
		}
		if (view != null)
			view.removeAll();
		if (!networkListModel.isEmpty())
			networkListModel.removeAllElements();
		if (!mnodeListModel.isEmpty())
			mnodeListModel.removeAllElements();
		numberNetwork.setText("");
		numberMobileNode.setText("");
		duration = 0;
		if (resultView != null) {
			resultView.reset();
		}
		setTime(duration);
		setZoom(1.0);
	}

	private void addDesComponent() {
		if (desComp != null) {
			view.remove(desComp);
			desComp = null;
		}
		desComp = new DesComponent();
		desComp.setLocation(200, 100);
		desComp.setVisible(false);
		view.add(desComp, 0);
	}

    ImageIcon getBackgroundImage(String background, int width, int height) {
    	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    	try {
    		BufferedImage bi =  rf.getBufferedImage(background);
    		BufferedImage bi2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    		Graphics2D g = bi2.createGraphics();
    		g.drawImage(bi, 0, 0, width, height, null);
    		ImageIO.write(bi2, "png", outputStream);
    	} catch (Exception ex) {
    		ex.printStackTrace();
    	}
    	return new ImageIcon(outputStream.toByteArray());
    }

	private void setDesComp(int x, int y, String text, Color background, boolean isVisible) {
        desComp.setLocation(x,y);
        desComp.setText(text);
        desComp.setBackground(background);
        desComp.setVisible(isVisible);
    }

	public void mouseDragged(MouseEvent e) {
	}

	public void mouseMoved(MouseEvent e) {
		int x = (int)(e.getX()/view.getZoom());
		int y = (int)(e.getY()/view.getZoom());
		statusBar.setPosition(x, y);
        for (int i = 0; i < networks.size(); i++) {
            NetworkComponent comp = (NetworkComponent)networks.elementAt(i);
            if (comp.isIn(x, y)) {
    			setDesComp(x, y, comp.getDeviceInfo().getComment(), Resources.DES_COLOR_NETWORK, true);
                view.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                view.repaint();
                return;
            }
        }
        for (int i = 0; i < mnodes.size(); i++) {
            MobileNodeSimComponent comp = (MobileNodeSimComponent)mnodes.elementAt(i);
            if (comp.isIn(x, y)) {
    			setDesComp(x, y, comp.getDeviceInfo().getComment(), Resources.DES_COLOR_MOBILENODE, true);
                view.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                view.repaint();
                return;
            }
        }
        for (int i = 0; i < snodes.size(); i++) {
            ServerComponent comp = (ServerComponent)snodes.elementAt(i);
            if (comp.isIn(x, y)) {
    			setDesComp(x, y, comp.getServerInfo().getComment(), Resources.DES_COLOR_SERVER, true);
                view.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                view.repaint();
                return;
            }
        }

        view.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        desComp.setVisible(false);
	}

	public void openMonitorView(NetworkMapInfo mapInfo) {
		if (mapInfo == null) {
			JOptionPane.showMessageDialog(this, "Map Info is Null", "Warning", JOptionPane.WARNING_MESSAGE);
			return;
		}
		monitorView = new MonitorView(mapInfo.getName());
    	monitorView.setMapInfo(mapInfo);
    	monitorView.repaint();
		monitorView.setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		String menuItemString = e.getActionCommand();

		if (menuItemString.intern() == "Open") {
			openNetworkMap();
		} else if (menuItemString.intern() == "Save") {
		} else if (menuItemString.intern() == "LaunchMonitorView") {
			openMonitorView(mapInfo);
		} else if (menuItemString.intern() == "RunNetwork") {
			startSimulation();
			setSimState("RUNNING");
		} else if (menuItemString.intern() == "StopNetwork") {
			stopSimulation();
			setSimState("STOPPED");
		} else if (menuItemString.intern() == "Export") {
			exportPNGImage();
		} else if (menuItemString.intern() == "ExportGraph") {
			exportGraphPNGImage();
    	} else if (menuItemString.intern() == "RandomSimulation") {
    		randomSimulation();
    	}
	}

	public void startSimulation() {
		//	determine applications for mobile nodes
 	    Object[] message = new Object[2];
	    JPanel p = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
	    p.setLayout(gridbag);

		JLabel label = new JLabel("Time interval (ms)");
		c.gridwidth = GridBagConstraints.RELATIVE;
		gridbag.setConstraints(label,c);
		p.add(label);

		JTextField time = new JTextField(6);
		time.setText("1000");
		time.setForeground(Color.blue);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(time,c);
		p.add(time);

		label = new JLabel("End time (ms)");
		c.gridwidth = GridBagConstraints.RELATIVE;
		gridbag.setConstraints(label,c);
		p.add(label);

		JTextField endtime = new JTextField(8);
		endtime.setText("600000");
		endtime.setForeground(Color.blue);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(endtime,c);
		p.add(endtime);

    	NetworkMobileNodeInfo nodeInfo[] = mapInfo.getMnodes();
    	JComboBox appCombo[] = new JComboBox[nodeInfo.length];
    	JComboBox policyCombo[] = new JComboBox[nodeInfo.length];
    	for (int i = 0; i < nodeInfo.length; i++) {
	        label = new JLabel(nodeInfo[i].getDevice().getId());
	        c.gridwidth = GridBagConstraints.RELATIVE;
	        gridbag.setConstraints(label,c);
	        p.add(label);

	        JPanel pane = new JPanel();
	        appCombo[i] = new JComboBox(nodeInfo[i].getDevice().getApplications());
	        pane.add(appCombo[i]);

	        policyCombo[i] = new JComboBox(nodeInfo[i].getDevice().getPolicies());
	        pane.add(policyCombo[i]);

	        c.gridwidth = GridBagConstraints.REMAINDER;
	        gridbag.setConstraints(pane,c);
	        p.add(pane);
    	}

		message[0] = "Start Network Simulator";
	    message[1] = p;

	    int result;

		result = JOptionPane.showOptionDialog(null, message, "Start Network Simulator",
				JOptionPane.OK_CANCEL_OPTION,
				JOptionPane.INFORMATION_MESSAGE, null, null, null);

		if ( result == JOptionPane.OK_OPTION ) {
            if (time.getText() == null || time.getText().intern() == "".intern()) {
                JOptionPane.showMessageDialog(this, "Please, insert time interval",
                        "Error", JOptionPane.ERROR_MESSAGE);
            	return;
            }

            interval = Long.parseLong(time.getText());
            end = Long.parseLong(endtime.getText());

            String appNames[] = new String[nodeInfo.length];
	    	for (int i = 0; nodeInfo != null && i < nodeInfo.length; i++) {
        		nodeInfo[i].getDevice().getPolicyManager().setCurrentPolicy((Rule)policyCombo[i].getSelectedItem());
        		appNames[i] = ((MobileApplication)appCombo[i].getSelectedItem()).getName();
	    	}
			//	initialize log

			owner.initLogging(mapInfo, appNames[0]);

			task = new SimulationTask();
			player.start();

			try {
				timer.schedule(task, 0, interval);
			} catch (Exception ex) {
				ex.printStackTrace();
			}

	    	UpdateTimer.getInstance().addUpdateListener(this);
	    	updateInfo();

	    	for (int i = 0; nodeInfo != null && i < nodeInfo.length; i++) {
        		nodeInfo[i].getDevice().getApplicationManager().startApplication(((MobileApplication)appCombo[i].getSelectedItem()).getName());
        		nodeInfo[i].getDevice().updateApplication();
	    	}
		}
	}

	public void stopSimulation() {
	   	//	stop any application
		if (mapInfo != null) {
        	NetworkMobileNodeInfo nodeInfo[] = mapInfo.getMnodes();
        	for (int i = 0; nodeInfo != null && i < nodeInfo.length; i++) {
    			nodeInfo[i].getDevice().getApplicationManager().stop();
    		}
		}
		if (timer == null || task == null) {
			return;
		}
		try {
			task.cancel();
			task = null;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		player.stop();
		UpdateTimer.getInstance().removeUpdateListener(this);

	}

	void setSimState(String state) {
		statusBar.setState(state);
	}

	void setTime(long time) {
		if (mapInfo != null) {
			NetworkDeviceInfo deviceInfo[] = mapInfo.getDevices();
			for (int i = 0; i < deviceInfo.length; i++) {
				deviceInfo[i].getData().setCurrentTime(time);
			}
		}
		int ms = (int)(time % 1000);
		int s = (int)((time/1000)%60);
		int m = (int)((time/1000/60)%60);
		int h = (int)(time/1000/60/60);

		statusBar.setTime(String.format("%04dh %02dm %02ds %03d", h, m, s, ms));
	}

    private void exit() {
    	stopSimulation();
    	owner.exitSimulator();
    }

 	private synchronized void openNetworkMap() {
        Object[] message = new Object[2];
        JPanel p = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        p.setLayout(gridbag);

        JLabel label = new JLabel("Map File");
        c.gridwidth = GridBagConstraints.RELATIVE;
        gridbag.setConstraints(label,c);
        p.add(label);

        JPanel bPane = new JPanel();
        fileFld = new JTextField(30);
        fileFld.setForeground(Color.blue);
        bPane.add(fileFld);
        c.gridwidth = GridBagConstraints.REMAINDER;

        JButton btn = new JButton("...");
        btn.setToolTipText("Browsing...");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
    			JFileChooser jf = new JFileChooser(new File(Resources.DATA_DIR));
    			jf.setDialogTitle("Choose a map file");
    			jf.setDialogType(JFileChooser.OPEN_DIALOG);
    			jf.setFileSelectionMode(JFileChooser.FILES_ONLY);

    			ZFileFilter filter = new ZFileFilter();
    			filter.addExtension("xml");
    			filter.setDescription("Map File");
    			jf.setFileFilter(filter);

    			if (jf.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    				File file = jf.getSelectedFile();
					if (!file.getName().endsWith(".xml")) {
        				file = new File(file.getPath()+".xml");
        			}
    				fileFld.setText(file.getAbsolutePath());
    			}
            }
        });
        bPane.add(btn);

        gridbag.setConstraints(bPane,c);
        p.add(bPane);

		label = new JLabel("Time Interval (ms)");
		c.gridwidth = GridBagConstraints.RELATIVE;
		gridbag.setConstraints(label,c);
		p.add(label);

		JTextField interval = new JTextField(8);
		interval.setText("100");
		interval.setForeground(Color.blue);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(interval,c);
		p.add(interval);

        message[0] = "Open Network Map";
        message[1] = p;

        int result;

        result = JOptionPane.showOptionDialog(null, message, "Open Network Map",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.INFORMATION_MESSAGE, null, null, null);

        if ( result == JOptionPane.OK_OPTION ) {
            if (fileFld.getText() == null || fileFld.getText().intern() == "".intern()) {
                JOptionPane.showMessageDialog(this, "Please, insert map name",
                        "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            owner.openSimulator(Long.parseLong(interval.getText()), fileFld.getText());

            //TODO: open network map and load policy for each mobile node
        }
    }

    public void setTimeInterval(long timeinterval) {
    	interval = timeinterval;
    }

	public class SimulationTask extends TimerTask {
    	public void run() {
			setTime(duration);

    		//	fire event
			for (int i = 0; i < mapInfo.getMnodes().length; i++) {
				mapInfo.getMnodes()[i].move(interval, speedRate);
//				mnodes.elementAt(i).move();
				view.repaint();
			}
			if (Conf.LOG){
				owner.logging(mapInfo, duration);
			}
			//	update duration timer
			duration+=interval;
			if (duration > end) {
				if (Conf.LOG){
					owner.loggingTable(mapInfo);
					owner.loggingGraph(mapInfo);
				}
				stopSimulation();
			}
    	}
	}

	public void updateInfo() {
		if (mapInfo != null) {
			networkArea.setText(mapInfo.getNetworkStatus());
			mNodeArea.setText(mapInfo.getMobleNodeStatus());
		}
		if (resultView != null) {
			resultView.updateMobileNode(duration);
		}
//		view.repaint();
	}

    private void exportPNGImage() {
    	File f = new File("png");
    	if (!f.exists()) {
    		f.mkdir();
    	}
        JFileChooser fc = new JFileChooser(f);
        fc.setDialogTitle("Save to PNG file");
        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File pngFile = fc.getSelectedFile();
            if (!pngFile.getPath().endsWith(".png")) {
            	pngFile = new File(pngFile.getPath()+".png");
            }
            exportPNGImage(pngFile);
        }
    }

    private void exportGraphPNGImage() {
    	File f = new File("png");
    	if (!f.exists()) {
    		f.mkdir();
    	}
        JFileChooser fc = new JFileChooser(f);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setDialogTitle("Save Graph to PNG file(s)");
        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        	if (resultView != null) {
        		resultView.exportAllGraph(fc.getSelectedFile());
        	}
        }
    }

    void exportPNGImage(File pngFile) {
        BufferedImage bi = new BufferedImage(view.getWidth(), view.getHeight()+25,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        g.setColor(Color.white);
//        g.fillRect(0,0, getWidth(), getHeight()+25);
        g.fillRect(0,0, view.getWidth(), view.getHeight()+25);
        g.translate(0, 25);
        view.paint(g);
        g.setFont(Resources.DIALOG_12B);
        g.setColor(Color.black);
        g.translate(0, -25);
        g.drawString("MAP TITLE : " + mapInfo.getName() + " ( " + mapInfo.getDescr()+ " ) - " +
                mapInfo.getWidth() + " x " + mapInfo.getHeight(), 5, 16);

        try {
            ImageIO.write(bi, "png", pngFile);
        } catch ( Exception ex) {

        }
    }

    private void randomSimulation() {
	    Object[] message = new Object[2];
	    JPanel p = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
	    p.setLayout(gridbag);

		String nameStr[] = {"Name", "Width", "Height", "# of Networks", "# of Mobile Nodes",
				"Max Path", "Max Stay time"};
		String valueStr[] = {"", "1024", "768", "40", "100", String.valueOf(Env.RANDOM_MAX_PATH),
				String.valueOf(Env.RANDOM_MAX_STAY)};

		JTextField valueFld[] = new JTextField[nameStr.length];

		for (int i = 0; i < nameStr.length; i++) {
			JLabel label = new JLabel(nameStr[i]);
			c.gridwidth = GridBagConstraints.RELATIVE;
			gridbag.setConstraints(label,c);
			p.add(label);

			valueFld[i] = new JTextField(30);
			valueFld[i].setText(valueStr[i]);
			valueFld[i].setForeground(Color.blue);
			c.gridwidth = GridBagConstraints.REMAINDER;
			gridbag.setConstraints(valueFld[i],c);
			p.add(valueFld[i]);
		}

        JLabel label = new JLabel("Background");
        c.gridwidth = GridBagConstraints.RELATIVE;
        gridbag.setConstraints(label,c);
        p.add(label);

        JPanel bPane = new JPanel();
        background = new JTextField(20);
        background.setText("");
        background.setForeground(Color.blue);
        bPane.add(background);
        c.gridwidth = GridBagConstraints.REMAINDER;

        JButton btn = new JButton("...");
        btn.setToolTipText("Browsing...");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
    			JFileChooser jf = new JFileChooser(new File(Resources.HOME+File.separator+Resources.MAP_DIR));
    			jf.setDialogTitle("Choose a background file");
    			jf.setDialogType(JFileChooser.OPEN_DIALOG);
    			jf.setFileSelectionMode(JFileChooser.FILES_ONLY);

    			ZFileFilter filter = new ZFileFilter();
    			filter.addExtension("png");
    			filter.addExtension("jpg");
    			filter.addExtension("gif");
    			filter.setDescription("Image Files");
    			jf.setFileFilter(filter);

    			if (jf.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    				File file = jf.getSelectedFile();
    				background.setText(file.getName());
    			}
            }
        });
        bPane.add(btn);
        gridbag.setConstraints(bPane,c);
        p.add(bPane);

        label = new JLabel("File");
        c.gridwidth = GridBagConstraints.RELATIVE;
        gridbag.setConstraints(label,c);
        p.add(label);

        bPane = new JPanel();
        randomFile = new JTextField(20);
        randomFile.setText("");
        randomFile.setForeground(Color.blue);
        bPane.add(randomFile);
        c.gridwidth = GridBagConstraints.REMAINDER;

        btn = new JButton("...");
        btn.setToolTipText("Browsing...");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
    			JFileChooser jf = new JFileChooser(new File(Resources.DATA_DIR));
    			jf.setDialogTitle("Choose a map file");
    			jf.setDialogType(JFileChooser.SAVE_DIALOG);
    			jf.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    			ZFileFilter filter = new ZFileFilter();
    			filter.addExtension("xml");
    			filter.setDescription("Map File");
    			jf.setFileFilter(filter);

    			if (jf.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    				File file = jf.getSelectedFile();
					if (!file.getName().endsWith(".xml")) {
        				file = new File(file.getPath()+".xml");
        			}
    				randomFile.setText(file.getAbsolutePath());
    			}
            }
        });
        bPane.add(btn);

        gridbag.setConstraints(bPane,c);
        p.add(bPane);

	    message[0] = "Random Simulation";
	    message[1] = p;

	    int result;

		result = JOptionPane.showOptionDialog(null, message, "Create a new map randomly",
				JOptionPane.OK_CANCEL_OPTION,
				JOptionPane.INFORMATION_MESSAGE, null, null, null);

		if ( result == JOptionPane.OK_OPTION ) {
            if (valueFld[0].getText() == null || valueFld[0].getText().intern() == "".intern()) {
                JOptionPane.showMessageDialog(this, "Please, insert map name",
                        "Error", JOptionPane.ERROR_MESSAGE);
            	return;
            }
            owner.simulate(randomFile.getText(), valueFld[0].getText(), Integer.parseInt(valueFld[1].getText()),
            		Integer.parseInt(valueFld[2].getText()), background.getText(),
            		Integer.parseInt(valueFld[3].getText()),
            		Integer.parseInt(valueFld[4].getText()),
            		Integer.parseInt(valueFld[5].getText()),
            		Integer.parseInt(valueFld[6].getText()));
		}
    }

    private void changeZoom(double unit) {
    	double currentZoom = view.getZoom();
    	currentZoom += unit;
    	currentZoom = currentZoom < 0.1 ? 0.1 : currentZoom;
    	currentZoom = currentZoom > 3.0 ? 3.0 : currentZoom;
    	setZoom(currentZoom);
    }

    private void setZoom(double zoom) {
    	statusBar.setZoom(zoom);
    	if (mapInfo != null) {
    		view.setZoom(zoom);
        	int w = mapInfo.getWidth();
        	int h = mapInfo.getHeight();

        	Dimension dim = new Dimension((int)(w * zoom), (int)(h*zoom));
        	view.setPreferredSize(dim);
        	view.repaint();

        	/*
        	int w1 = view.getWidth();
        	int h1 = view.getHeight();
        	System.out.println(String.format("w: %d, w1: %d, h: %d, h1: %d", w, w1, h, h1));
        	System.out.println(dim);
        	*/
    	}
    }

	public void mouseWheelMoved(MouseWheelEvent e) {
		if (e.getWheelRotation() > 0) {
			//	zoom in
			changeZoom(-0.1);
		} else {
			//	zoom out
			changeZoom(0.1);
		}
	}
	public MobileNodeComponent getMobileNodeComponent(String name) {
		if (mnodes != null) {
			for (int i = 0; i < mnodes.size(); i++) {
				if (mnodes.elementAt(i).getDeviceInfo().getDevice().getId().intern() == name.intern()) {
					return mnodes.elementAt(i);
				}
			}
		}
		return null;
	}

	public void handover(NetworkHandoverEvent evt) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd HHmmss.SSS");
		handoverInfoArea.append(sdf.format(new Date(System.currentTimeMillis())));
		StringBuffer sb = new StringBuffer();
		if (evt.getType() == NetworkHandoverEvent.HORIZONTAL_HANDOVER) {
    		sb.append(" [H] ");
		} else {
    		sb.append(" [V] ");
		}
		sb.append(" {" + evt.getHost().getId()+"} ");
		NetworkDevice prev = (NetworkDevice)evt.getPrevNetwork();
		NetworkDevice next = (NetworkDevice)evt.getNextNetwork();
		sb.append(prev.getName() +"("+prev.getNetworkStr()+") -> ");
		sb.append(next.getName() +"("+next.getNetworkStr()+")\n");
		handoverInfoArea.append(sb.toString());

		/*
		if (Conf.DEBUG) {
			Logger.getInstance().logEmulator("Simulator", sb.toString());
		}
		*/
		handoverInfoArea.getCaret().setDot(handoverInfoArea.getText().length());
	}

	public void stateChanged(ChangeEvent e) {
	    JSlider source = (JSlider)e.getSource();
	    if (!source.getValueIsAdjusting()) {
	        speedRate = (double)source.getValue()/10;
	    }
	}

	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		int x = (int)(e.getX()/view.getZoom());
		int y = (int)(e.getY()/view.getZoom());
		if (e.getModifiers() == MouseEvent.BUTTON1_MASK) {
			if (e.getClickCount() == 2) {
				MobileNodeComponent comp = findMobileNodeComponent(x,y);
				if (comp != null) {
	            	comp.getDeviceInfo().getDevice().showGUI();
				}
			}
		}
	}

	private MobileNodeComponent findMobileNodeComponent(int x, int y) {
       for (int i = 0; i < mnodes.size(); i++) {
            MobileNodeComponent comp = mnodes.elementAt(i);
            if (comp.isIn(x, y) && comp.isVisible()) {
                return comp;
            }
        }
		return null;
	}

	public void setEndTime(long end) {
		this.end = end;
	}

	public long getEndTime() {
		return end;
	}
}


text:
package org.cloudfoundry.client.v2.applications;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;

/**
 * The response payload for the v2 Create Application request.
 */
@JsonDeserialize
@Value.Immutable
abstract class _CreateApplicationResponse extends AbstractApplicationResource {

}


text:
<?php

namespace Finite\Test\Bundle\FiniteBundle\DependencyInjection\Compiler;

use Finite\Bundle\FiniteBundle\DependencyInjection\Compiler\ContainerCallbackPass;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Test of ContainerCallbackPass
 *
 * @author Alexandre Bacco <alexandre.bacco@gmail.com>
 */
class ContainerCallbackPassTest extends TestCase
{
    /**
     * @var ContainerBuilder
     */
    protected $container;

    protected function setUp(): void
    {
        $this->container = new ContainerBuilder;

        $this->load($this->container);
    }

    public function testPass()
    {
        $config = $this->container->getDefinition('loader')->getArgument(0);
        $this->assertEquals('@my_service', $config['callbacks']['before'][0]['do'][0]);

        $compilerPass = new ContainerCallbackPass();
        $compilerPass->process($this->container);

        $newConfig = $this->container->getDefinition('loader')->getArgument(0);
        $callback = $newConfig['callbacks']['before'][0]['do'][0];
        $this->assertTrue($callback instanceof Reference);
        $this->assertEquals('my_service', (string) $callback);
        $this->assertEquals('not_a_service', $newConfig['callbacks']['before'][1]['do'][0]);
        $this->assertTrue($newConfig['callbacks']['after'][0]['do'] instanceof \Closure);
    }

    private function load(ContainerBuilder $container)
    {
        $loader = new Definition();
        $loader->addTag('finite.loader');
        $loader->addArgument(array(
            'callbacks' => array(
                'before' => array(
                    array(
                        'do' => array('@my_service', 'myMethod')
                    ),
                    array(
                        'do' => array('not_a_service', 'myMethod')
                    )
                ),
                'after' => array(
                    array(
                        'do' => function() {
                                // Not a service
                            }
                    )
                )
            )
        ));
        $container->setDefinition('loader', $loader);

        $service = new Definition('\Finite\Bundle\DependencyInjection\Compiler\ContainerCallbackPass');
        $container->setDefinition('my_service', $service);
    }
}


text:
This is a simple LoopBack client written in Swift using an in-development version of LoopBack iOS SDK.

This basically is a Swift version of the iOS client found in this tutorial: ["How-to Build CRUD Enabled iOS Apps with the LoopBack API Server"](https://strongloop.com/strongblog/how-to-crud-ios-nodejs-loopback-api-server-part-1/) with the following differences:

 * Written in Swift, rather than Objective-C.
 * The LoopBack API server used in this demo is created by following [Getting started with LoopBack/Create a simple API](https://docs.strongloop.com/display/public/LB/Create+a+simple+API) instead of [the one](https://docs.strongloop.com/display/DOC/Creating+a+LoopBack+application) referenced in Step 2 of [the original tutorial](https://strongloop.com/strongblog/how-to-crud-ios-nodejs-loopback-api-server-part-1/), since it doesn't seem to exist anymore.  Because of this change, the app deals with `CoffeeShops` instead of `Books`.
 * The client workspace already includes a module-enabled version of the LoopBack iOS SDK framework.  **The bundled `LoopBack.framework` is an in-development version of [strongloop/loopback-sdk-ios](https://github.com/strongloop/loopback-sdk-ios) at revhash of `897293f` (12/25/2015)**.
 * Swipe-to-delete feature of the table view is added to demonstrate deletion of a model.

### How to Try Out

 1. Clone the repo: e.g. `git clone https://github.com/hideya/loopback-swift-simple-example`
 *  `cd test-server`
 *  `npm install` to install the node modules required by the server.
 *  `node .` to run the server.
 *  Open the client Xcode project from `swift-client/CoffeeShops/CoffeeShops.xcodeproj`
 *  Build and run the client by typing command⌘-R.

### Key Code Fragments

The following code fragments show key parts of LoopBack iOS SDK usage with Swift.

Model definition:

```
import LoopBack

class CoffeeShop: LBPersistedModel {
    var name: String!
    var city: String!
}

class CoffeeShopRepository: LBPersistedModelRepository {
    override init() {
        super.init(className: "CoffeeShops")
    }

    class func repository() -> CoffeeShopRepository {
        return CoffeeShopRepository()
    }
}
```

Instantiation of the adapter and the repository:

```
    static let adapter = LBRESTAdapter(url: URL(string: "http://localhost:3000/api"))
    static let coffeeShopRepo = adapter?.repository(with: CoffeeShopRepository.self) as! CoffeeShopRepository
```

Find all the models:

```
    coffeeShopRepo.all(
            success: { (models) -> Void in
            // success block
            let tableData = models as! [CoffeeShop]
            ...
        },
        failure: { (error: Error?) -> Void in
            // failure block
            ...
        })
```

Create a new model:

```
    let newCoffeeShop = coffeeShopRepo.modelWithDictionary(nil) as! CoffeeShop
    newCoffeeShop.name = nameField.text!
    newCoffeeShop.city = cityField.text!

    newCoffeeShop.save(
            success: { () -> Void in
            // success block
            ...
        },
        failure: { (error: Error?) -> Void in
            // failure block
            ...
        })
```

Delete an existing model:

```
        coffeeShop.destroy(
                success: { () -> Void in

            // success block
            ...
        },
        failure: { (error: Error?) -> Void in
            // failure block
            ...
        })
```


text:
// @flow
import forgot_password from './authFns/forgot_password';
import login from './authFns/login';
import logout from './authFns/logout';
import register from './authFns/register';
import restoreAuth from './authFns/restoreAuth';
import { checkEmailUniqueness, checkUsernameUniqueness } from './authFns/uniqueFns';

/**
 * @name- auth.js
 *
 * @chill- Do not seek to follow in the footsteps of the wise one: seek what they sought. - Matsuo Basho
 *
 *
 * @description- Middleware to handle user auth related actions.
 *
 * @author- heartit pirates were here
 */

("use strict");

export default store => next => action => {
  switch (action.type) {
    case "RESTORE_AUTH":
      return restoreAuth(store, next, action);
      break;
    case "LOGIN":
      return login(store, next, action);
      break;
    case "REGISTER":
      return register(store, next, action);
      break;
    case "CHECK_EMAIL_UNIQUENESS":
      return checkEmailUniqueness(store, next, action);
      break;
    case "CHECK_USERNAME_UNIQUENESS":
      return checkUsernameUniqueness(store, next, action);
      break;
    case "LOGOUT":
      return logout(store, next, action);
      break;
    case "FORGOT_PASSWORD":
      return forgot_password(store, next, action);
      break;
    default:
      return next(action);
  }
};


text:
require 'spec_helper'

describe "Admin Runners" do
  before do
    login_as :admin
  end

  describe "Runners page" do
    before do
      runner = FactoryGirl.create(:ci_runner)
      pipeline = FactoryGirl.create(:ci_pipeline)
      FactoryGirl.create(:ci_build, pipeline: pipeline, runner_id: runner.id)
      visit admin_runners_path
    end

    it { page.has_text? "Manage Runners" }
    it { page.has_text? "To register a new runner" }
    it { page.has_text? "Runners with last contact less than a minute ago: 1" }

    describe 'search' do
      before do
        FactoryGirl.create :ci_runner, description: 'runner-foo'
        FactoryGirl.create :ci_runner, description: 'runner-bar'

        search_form = find('#runners-search')
        search_form.fill_in 'search', with: 'runner-foo'
        search_form.click_button 'Search'
      end

      it { expect(page).to have_content("runner-foo") }
      it { expect(page).not_to have_content("runner-bar") }
    end
  end

  describe "Runner show page" do
    let(:runner) { FactoryGirl.create :ci_runner }

    before do
      @project1 = FactoryGirl.create(:empty_project)
      @project2 = FactoryGirl.create(:empty_project)
      visit admin_runner_path(runner)
    end

    describe 'runner info' do
      it { expect(find_field('runner_token').value).to eq runner.token }
    end

    describe 'projects' do
      it { expect(page).to have_content(@project1.name_with_namespace) }
      it { expect(page).to have_content(@project2.name_with_namespace) }
    end

    describe 'search' do
      before do
        search_form = find('#runner-projects-search')
        search_form.fill_in 'search', with: @project1.name
        search_form.click_button 'Search'
      end

      it { expect(page).to have_content(@project1.name_with_namespace) }
      it { expect(page).not_to have_content(@project2.name_with_namespace) }
    end

    describe 'enable/create' do
      before do
        @project1.runners << runner
        visit admin_runner_path(runner)
      end

      it 'enables specific runner for project' do
        within '.unassigned-projects' do
          click_on 'Enable'
        end

        assigned_project = page.find('.assigned-projects')

        expect(assigned_project).to have_content(@project2.path)
      end
    end

    describe 'disable/destroy' do
      before do
        @project1.runners << runner
        visit admin_runner_path(runner)
      end

      it 'enables specific runner for project' do
        within '.assigned-projects' do
          click_on 'Disable'
        end

        new_runner_project = page.find('.unassigned-projects')

        expect(new_runner_project).to have_content(@project1.path)
      end
    end
  end

  describe 'runners registration token' do
    let!(:token) { current_application_settings.runners_registration_token }
    before { visit admin_runners_path }

    it 'has a registration token' do
      expect(page).to have_content("Registration token is #{token}")
      expect(page).to have_selector('#runners-token', text: token)
    end

    describe 'reload registration token' do
      let(:page_token) { find('#runners-token').text }

      before do
        click_button 'Reset runners registration token'
      end

      it 'changes registration token' do
        expect(page_token).not_to eq token
      end
    end
  end
end


text:
using System.ComponentModel.DataAnnotations.Schema;

namespace zvs.DataModel
{
    [Table("DeviceSettingOptions", Schema = "ZVS")]
    public class DeviceSettingOption : BaseOption, IIdentity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public int? DeviceSettingId { get; set; }
        public virtual DeviceSetting DeviceSetting { get; set; }
    }
}


text:
module SpringBoot {

    export var metricsMBean = 'org.springframework.boot:type=Endpoint,name=metricsEndpoint';

    export var metricsMBeanOperation = 'getData()';

    export function callIfSpringBootAppAvailable(jolokia, callbackFunc) {
        jolokia.execute(metricsMBean, metricsMBeanOperation, onSuccess(function (data) {
            callbackFunc()
        }));
    }

    // Printing user friendly metrics

    var metricsFriendlyNames = {
        'counter.status.200.favicon.ico': 'Successful Favicon requests',
        'counter.status.200.jolokia': 'Successful Jolokia requests',
        'counter.status.200.jolokia.exec.org.springframework.boot:type=Endpoint,name=metricsEndpoint.getData()': 'Successful metrics Jolokia requests',
        'counter.status.200.jolokia.read.java.lang:type=Runtime.Name': 'Successful Jolokia Runtime.Name reads',
        'counter.status.200.jolokia.root': 'Successful Jolokia root requests',
        'counter.status.200.jolokia.search.*:type=Connector,*': 'Successful Jolokia connectors search queries',
        'counter.status.200.metrics': 'Successful metrics REST requests',
        'counter.status.405.auth.login.root': 'Method Not Allowed (405) login responses',
        'gauge.response.auth.login.root': 'Authentication time (ms)',
        'gauge.response.jolokia': 'Jolokia response time (ms)',
        'gauge.response.jolokia.exec.org.springframework.boot:type=Endpoint,name=metricsEndpoint.getData()': 'Metrics Jolokia response time (ms)',
        'gauge.response.jolokia.root': 'Jolokia root response time (ms)',
        'gauge.response.metrics': 'Metrics response time (ms)',
        'gc.ps_marksweep.count': 'Parallel scavenge mark-sweep collector count',
        'gc.ps_marksweep.time':	'Parallel scavenge mark-sweep collector time (ms)',
        'gc.ps_scavenge.count':	'Parallel scavenge collector count',
        'gc.ps_scavenge.time': 'Parallel scavenge collector time (ms)',
        'mem': 'Memory used (bytes)',
        'mem.free': 'Memory available (bytes)',
        'processors': 'Processors number',
        'uptime': 'Node uptime (ms)',
        'instance.uptime': 'Service uptime (ms)',
        'heap.committed': 'Heap committed (bytes)',
        'heap.init': 'Initial heap (bytes)',
        'heap.used': 'Heap used (bytes)',
        'heap': 'Total Heap (bytes)',
        'classes': 'Classes',
        'classes.loaded': 'Classes loaded',
        'classes.unloaded': 'Classes unloaded',
        'threads' : 'Threads count',
        'threads.daemon': 'Daemon threads',
        'threads.peak' : 'Threads peak count'
    };

    export function convertRawMetricsToUserFriendlyFormat(scope, data) {
        var userFriendlyData = [];
        var metricIndex;
        for (metricIndex in Object.keys(data)) {
            var metric = Object.keys(data)[metricIndex];
            var friendlyName = metricsFriendlyNames[metric];
            if (!friendlyName) {
                userFriendlyData[metricIndex] = {code: metric, name: metric, value: data[metric]}
            } else {
                userFriendlyData[metricIndex] = {code: metric, name: friendlyName, value: data[metric]}
            }
        }
        scope.metrics = userFriendlyData;
        scope.$apply();
    }

}


text:
package com.google.api.gax.rpc;

import com.google.api.gax.retrying.RetryingExecutorWithContext;
import com.google.api.gax.retrying.RetryingFuture;
import com.google.common.base.Preconditions;

/**
 * A UnaryCallable that will keep issuing calls to an inner callable until it succeeds or times out.
 *
 * <p>Package-private for internal use.
 */
class RetryingCallable<RequestT, ResponseT> extends UnaryCallable<RequestT, ResponseT> {
  private final ApiCallContext callContextPrototype;
  private final UnaryCallable<RequestT, ResponseT> callable;
  private final RetryingExecutorWithContext<ResponseT> executor;

  RetryingCallable(
      ApiCallContext callContextPrototype,
      UnaryCallable<RequestT, ResponseT> callable,
      RetryingExecutorWithContext<ResponseT> executor) {
    this.callContextPrototype = Preconditions.checkNotNull(callContextPrototype);
    this.callable = Preconditions.checkNotNull(callable);
    this.executor = Preconditions.checkNotNull(executor);
  }

  @Override
  public RetryingFuture<ResponseT> futureCall(RequestT request, ApiCallContext inputContext) {
    ApiCallContext context = callContextPrototype.nullToSelf(inputContext);
    AttemptCallable<RequestT, ResponseT> retryCallable =
        new AttemptCallable<>(callable, request, context);

    RetryingFuture<ResponseT> retryingFuture = executor.createFuture(retryCallable, inputContext);
    retryCallable.setExternalFuture(retryingFuture);
    retryCallable.call();

    return retryingFuture;
  }

  @Override
  public String toString() {
    return String.format("retrying(%s)", callable);
  }
}


text:
package Toolkit;
use strict;
use warnings;
use FileHandle;
use Getopt::Long;

my $usage = '
usage: -out <output file name> [-help] [-first <first time stamp>]
       <input file name>
';

my ($help, $outFileName, $first);

GetOptions("out=s"=>\$outFileName, "first=i"=>\$first, "help|?!" => \$help);

$first = -1 unless defined $first; # no adjustment by default

if (not $help and (not $outFileName or not @ARGV)) {
  print "Missing required parameter(s)\n";
  print $usage;
  exit();
}

if ($help) {
  print 'Dieselnet trace converter.';
  print "\n$usage";
   print '
options:
out   Name of the output file

first Time stamp for the first connection event. Adjusts all timestamps so
      that the first event happens at this time (by N seconds from the start
      of the simulation). By default, the times are not adjusted at all.
';
  exit();
}

# Input example:
# PVTA_3201 PVTA_3117 0:16:14 235560.0 584.0 42.38768 -72.52352

# Output example:
# 974 CONN 12 7 up
# 1558 CONN 12 7 down

my $inputFile = shift @ARGV;
my $inFh = new FileHandle;
my $outFh = new FileHandle;
$inFh->open("<$inputFile") or die "Can't open input file $inputFile";
$outFh->open(">$outFileName") or die "Can't create outputfile $outFileName";

print $outFh "# Connection trace file for the ONE. Converted from $inputFile \n";

my @lines = <$inFh>; # read whole file to array
my @output;
my $nextNodeId = 0;
my ($nodeId1, $nodeId2, %nodeIds);

foreach (@lines) {
  if (m/^\s$/) {
    next; # skip empty lines
  }

  my ($node1, $node2, $h, $m, $s, $duration) =
    m/(\w+) (\w+) (\d+):(\d+):(\d+) [\d\.E]+ (\d+\.\d+)/;
  die "Invalid input line: $_" unless ($node1 and $node2);
  my $time = $h * 3600 + $m * 60 + $s;

  # map node IDs consistently to network addresses
  if (exists $nodeIds{$node1}) {
    $nodeId1 = $nodeIds{$node1};
  }
  else {
    $nodeId1 = $nextNodeId;
    $nodeIds{$node1} = $nextNodeId;
    $nextNodeId++;
  }
  if (exists $nodeIds{$node2}) {
    $nodeId2 = $nodeIds{$node2};
  }
  else {
    $nodeId2 = $nextNodeId;
    $nodeIds{$node2} = $nextNodeId;
    $nextNodeId++;
  }

  my $conEndTime = $time + $duration;
  push(@output, "$time CONN $nodeId1 $nodeId2 up");
  push(@output, "$conEndTime CONN $nodeId1 $nodeId2 down");
}

# sort result by time stamp
@output = sort
{
  my ($t1) = $a =~ m/^(\d+)/;
  my ($t2) = $b =~ m/^(\d+)/;
  $t1 <=> $t2;
} @output;

# adjust time stamps (if requested with cmd line option)
if ($first != -1) {
  my ($firstTime) = $output[0] =~ m/^(\d+)/;
  my $diff = $firstTime - $first;
  print "Adjusting timestamps by $diff seconds\n";
  foreach (@output) {
    my ($ts) = m/^(\d+)/;
    my $newTime = $ts - $diff;
    s/$ts/$newTime/;
  }
}

# print all the result lines to output file
print $outFh join("\n", @output);

print "Node name to network ID mapping:\n";
while (my ($k,$v) = each %nodeIds ) {
    print "$k => $v\n";
}

$outFh->close();
$inFh->close();


text:
package main

import (
	"fmt"
	"sync"
	"time"
	"context"
)

func main() {
	var wg sync.WaitGroup
	ctx, cancel := context.WithCancel(context.Background())

	// Spawn a handfull of goroutines
	for i := 1; i <= 5; i++ {
		// Add the goroutine to the WaitGroup before starting
		wg.Add(1)
		go func(wid int) {
			// When the goroutine is finished remove it from the WaitGroup
			defer func() {
				wg.Done()
				fmt.Printf("worker %d done\n", wid)
			}()

			// Infinite loop with context Done channel
			for {
				select {
				case <-ctx.Done():
					// Somebody canceled us
					return
				default:
					// Dummy work which takes one second
					fmt.Printf("worker %d\n", wid)
					time.Sleep(time.Second)
				}
			}
		}(i)
	}

	// Reap all the running goroutines after 3 seconds with the cancel() method
	wg.Add(1)
	go func() {
		time.Sleep(time.Second * 3)
		cancel()
		wg.Done()
	}()

	// Wait until all goroutines are finished including the reaper
	wg.Wait()
}


text:
var startTest = function() {
  document.querySelector('#webview-tag-container').innerHTML =
      '<webview style="width: 10px; height: 10px; margin: 0; padding: 0;"' +
      '></webview>';

  var webview = document.querySelector('webview');
  var onLoadStop = function(e) {
    chrome.test.sendMessage('WebViewTest.LAUNCHED');
  };

  webview.addEventListener('loadstop', onLoadStop);
  webview.src = 'data:text/html,<body>Guest</body>';
};

window.onload = startTest;


text:
(function () {
    var app = angular.module('mainApp', ['ui.bootstrap', 'ngMessages']);

    var ForgotPasswordController = function ($scope, $http) {
        var model = this;

        model.user = {
            email: ""
        };

        $scope.alerts = [];

        $scope.closeAlert = function (index) {
            $scope.alerts.splice(index, 1);
        };

        model.submit = function (isValid) {
            if (isValid) {
                $http.post('http://localhost:5000/api/v1/auth/local/forgot', model.user)
                    .success(function (data) {
                        var response = JSON.stringify(data);
                        if (response === '{"message":"user does not exist"}') {
                            if ($scope.alerts.length > 0)
                                $scope.alerts = [];

                            $scope.alerts.push({
                                type: 'danger',
                                msg: 'Sorry, this email address has not been registered with us.'
                            });
                        }
                        else {
                            if ($scope.alerts.length > 0)
                                $scope.alerts = [];

                            $scope.alerts.push({
                                type: 'success',
                                msg: 'Please check your email for instructions on how to proceed further.'
                            });
                        }

                    })
                    .error(function (data) {
                        // need to do some logging with data.
                        if ($scope.alerts.length > 0)
                            $scope.alerts = [];
                        $scope.alerts.push({
                            type: 'danger',
                            msg: 'Our sincere apologies but we could not email you at the moment. Please try again later.'
                        });
                    });
            }
            else {
                if ($scope.alerts.length > 0)
                    $scope.alerts = [];
                $scope.alerts.push({type: 'warning', msg: 'There are still some invalid fields below.'});
            }

        };

    };
    app.controller("ForgotPasswordController", ForgotPasswordController);

}());


text:
Welcome to the TacticalGaming 2nd Battalion SUT section. This section includes files from the 2nd Battalion's game servers for all operations. Please ask for permission before use of our file. Thank you.
If you have any questions you can visit us at http://www.tacticalgaming.net/hq for more info.

## To-do
    - Restructure ACE Medical system for Advanced Operations (On Hold)
    - Make Experimental Loadouts ready for release


text:
!DOCTYPE html>

    <title class="app_name"></title>
    <link rel="stylesheet" href="static/css/jquery.mobile-1.3.2.css" />
    <link rel="stylesheet" href="static/css/mainstyle.css" />

Express, anonymously.

Home

Lets make sure you're human. Please enter the value of the image below.

Incorrect catcha image value

        	<input type="text" id="catcha_value" />
           Enter

       2013 - Khulekani Ngongoma

Express, anonymously.

Home

Drop a customization photo here.

 lets you pour your heart and speak your mind about situations or stuff that is happening in your live, using a username of "Anonymous". You will get to vote for the best post of the week, and dislike posts which you feel are not desirable. When a post gets five dislike it gets removed from the app.

About

 Name :

                    Version : 1.0

                    Developer : Khulekani Ngongoma

Home

Articles

Random

Chat

Express, anonymously.

Articles

Send Article

                        Select Category
                        <select id="article_category">
                            <option>Select Category</option>
                        </select>
                        Head:
                        <input type="text" id="article_post_heading" placeholder="Heading" />
                        Message:
                        <textarea id="article_post" placeholder="Message" rows="5"></textarea>
                        Send
                        Clear

Suggested Article Category

Home

Articles

Random

Chat

Express, anonymously.

Random

Send Message

                        Head:
                        <input type="text" id="random_post_heading" placeholder="Heading" />
                        Message:
                        <textarea id="random_post" placeholder="Message"></textarea>
                        Send
                        Clear

Home

Articles

Random

Chat

Express, anonymously.

Chat

       <textarea id="message"></textarea>
       Send
       Clear

Home

Articles

Random

Chat

Express, anonymously.

SocialHub

Register once, and use your login details on all our games.

        					Username:
        					<input type="text" id="username" placeholder="Enter username" data-inset="true" />
        					Password:
        					<input type="password" id="password" placeholder="Enter password" data-inset="true" />
        					Re-type Password (Registration):
        					<input type="password" id="password_2" placeholder="Re-type password" data-inset="true" />
        					Login
        					Register

Home

Articles

Random

Chat


text:
Before running, be sure to modify input.csv with the list of SKUs, currently they are expected to be in the 2nd column.

Run SKU hunter with the commands below. Any successful hits will be downloaded into the tmp directory.

```
chmod +x sku-hunter.rb # only used the first time you run SKU hunter
./sku-hunter.rb
```


text:
package org.inbloom.portal;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes = {Application.class})
public class AppIntegrationTests {
    private MockMvc mockMvc;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    protected WebApplicationContext wac;

    @Before
    public void setup() {
        this.mockMvc = webAppContextSetup(this.wac).build();
    }

    @Test
    public void simple() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("hello"));
    }

}


text:
{% extends "base.html" %}
{% load i18n %}
{% load markdown_deux_tags %}
{% load static %}

{% block title %}
{% trans 'Ticket Checkout' %}
{% endblock title %}

{% block content %}

{% trans "Ticket Checkout" %}

                        {% trans "LAN" %}
                        {{ lan }} ({% trans "view LAN" %})

                        {% trans "Ticket type" %}
                        {{ ticket_type }} ({% trans "view all tickets" %})

                        {% trans "Description" %}
                        {{ ticket_type.get_translation.description }}

                        {% trans "Price" %}
                        {{ ticket_type.verbose_price }}

{% trans "Your Information" %}

                {% url 'update_profile' as update_profile_url %}
                {% blocktrans trimmed %}
                By purchasing a ticket, you are confirming that all of the information about you is correct.
                If not, update it now in your profile settings.
                {% endblocktrans %}

                        {% trans "First name" %}
                        {{ user.first_name }}

                        {% trans "Last name" %}
                        {{ user.last_name }}

                        {% trans "Email" %}
                        {{ user.email }}

                        {% trans "Date of birth" %}
                        {{ user.profile.date_of_birth }}

                        {% trans "Street address" %}
                        {{ user.profile.address }}

                        {% trans "Postal code" %}
                        {{ user.profile.zip_code }}

                        {% trans "Phone" %}
                        {{ user.profile.phone }}

{% trans "Payment" %}

            <form id="card-form">

{% trans "Card holder name" %}

                    <input class="form-control" id="cardholder-name" name="cardholder-name" placeholder="{% trans "Card holder name" %}" type="text" required/>

{% trans "Card info" %}

                    <input id="accept-rules" name="accept-rules" type="checkbox" required/>
                    {% trans "I accept the rules for the LAN, as described on the LAN page. (Required)" %}

                    <input id="correct-information" name="correct-information" type="checkbox" required/>
                    {% trans "My information above is correct. (Required)" %}

                    <button class="btn btn-success" id="card-button">{% trans "Submit payment" %}</button>

                <input type="submit" id="test-submit" style="display: none" />
            </form>

            {% trans "About our payment security" %}

{% endblock content %}

{% block script %}

{% endblock script %}


text:
@import UIKit;
#import "BSAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([BSAppDelegate class]));
    }
}


text:
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

namespace Swashbuckle.Dummy.Controllers
{
    [RoutePrefix("FileDownload")]
    public class FileDownloadController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage GetFile()
        {
            var response = new HttpResponseMessage();
            var stream = new FileStream(@"c:\test.txt", FileMode.Open);
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            return response;
        }

        [HttpGet]
        [Route("filename")]
        public HttpResponseMessage GetFileWithFilename()
        {
            var response = new HttpResponseMessage();
            var stream = new FileStream(@"c:\test.txt", FileMode.Open);
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "test.txt"
            };
            return response;
        }
    }
}


text:
import React from 'react';
import { addons, types } from '@storybook/addons';
import { ToolbarManager } from './components/ToolbarManager';
import { ADDON_ID } from './constants';

addons.register(ADDON_ID, () =>
  addons.add(ADDON_ID, {
    title: ADDON_ID,
    type: types.TOOL,
    match: () => true,
    render: () => <ToolbarManager />,
  })
);


text:
import {validateData, writeScript} from '../3p/3p';

/**
 * @param {!Window} global
 * @param {!Object} data
 */
export function adition(global, data) {
  validateData(data, ['version']);
  global.data = data;
  writeScript(global, 'https://imagesrv.adition.com/js/amp/v'
      + encodeURIComponent(data['version']) + '.js');
}