text:
/*global module,require*/
module.exports = function(grunt) {
	'use strict';

	/**
	 * Copy bower files from src to dist/web/whatever
	 */
	grunt.registerMultiTask('bowerCopy', 'Processes HTML', function() {
		var fs = require('fs')
			,oData = this.data
			,oBower = JSON.parse(fs.readFileSync(oData.json).toString())
			,oBowrc = JSON.parse(fs.readFileSync(oData.bowerrc).toString())
			,oOverrides = oBowrc.overrides||{}
			,sBaseUri = oBowrc.directory
		;
		for (var dep in oBower.dependencies) {
			var oDepBower = JSON.parse(fs.readFileSync(sBaseUri+'/'+dep+'/.bower.json').toString())
				,oMain = oOverrides.hasOwnProperty(dep)&&oOverrides[dep].hasOwnProperty('main')?oOverrides[dep].main:oDepBower.main
				,aMain = isString(oMain)?[oMain]:oMain
				,sSrcBase = sBaseUri.replace(/^src\//,'')+'/'+dep+'/'
			;
			if (!oMain) {
				console.log(dep+' could not be added, add manually!'); // log
			} else {

				aMain.forEach(function(src){
					var isCDN = !!src.match(/^(http)?s?:?\/\//)
						,sSrc = './'+sBaseUri+'/'+dep+'/'+(src[0]==='.'?src.substr(1):src)
						,sTarget = './'+oData.dest+'/'+sSrcBase+(src[0]==='.'?src.substr(1):src)
					;
					if (!isCDN) {
						copyFile(sSrc,sTarget);
					}
				});
			}
		}

		function isString(s){
			return typeof s==='string';
		}

		function copyFile(src,target) {
			var sSrc = fs.readFileSync(src)
				,sSlash = '/'
				,sTargetPath = (function(a){
					a.pop();return a.join(sSlash);
				})(target.split(sSlash))
				,aTargetPath = sTargetPath.split(sSlash)
			;
			for (var i=0,l=aTargetPath.length;i<l;i++) {
				var sSubPath = aTargetPath.slice(0,i+1).join(sSlash);
				if (!fs.existsSync(sSubPath)) fs.mkdirSync(sSubPath);
			}
			fs.writeFileSync(target,sSrc);
		}
	});

};

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * slim-routing (https://github.com/juliangut/slim-routing).
 * Slim framework routing.
 *
 * @license BSD-3-Clause
 * @link https://github.com/juliangut/slim-routing
 * @author Julián Gutiérrez <juliangut@gmail.com>
 */

declare(strict_types=1);

namespace Jgut\Slim\Routing\Response\Handler;

use Jgut\Slim\Routing\Response\ResponseType;
use Jgut\Slim\Routing\Response\ViewResponse;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Slim\Views\Twig;

/**
 * Twig view renderer response handler.
 */
class TwigViewResponseHandler extends AbstractResponseHandler
{
    /**
     * Twig renderer.
     *
     * @var Twig
     */
    protected $viewRenderer;

    /**
     * TwigViewResponseHandler constructor.
     *
     * @param ResponseFactoryInterface $responseFactory
     * @param Twig                     $viewRenderer
     */
    public function __construct(ResponseFactoryInterface $responseFactory, Twig $viewRenderer)
    {
        parent::__construct($responseFactory);

        $this->viewRenderer = $viewRenderer;
    }

    /**
     * {@inheritdoc}
     *
     * @throws \InvalidArgumentException
     */
    public function handle(ResponseType $responseType): ResponseInterface
    {
        if (!$responseType instanceof ViewResponse) {
            throw new \InvalidArgumentException(
                \sprintf('Response type should be an instance of %s', ViewResponse::class)
            );
        }

        $responseContent = $this->viewRenderer->fetch($responseType->getTemplate(), $responseType->getParameters());

        $response = $this->getResponse($responseType);
        $response->getBody()->write($responseContent);

        return $response->withHeader('Content-Type', 'text/html; charset=utf-8');
    }
}


text:
RCS_ID("$Id$")

@implementation OARegExFindPattern

- initWithString:(NSString *)aString selectedSubexpression:(int)subexpression backwards:(BOOL)backwards;
{
    [super init];
    regularExpression = [[OFRegularExpression alloc] initWithString:aString];
    selectedSubexpression = subexpression;
    isBackwards = backwards;
    return self;
}

- (void)setReplacementString:(NSString *)aString;
{
    if (aString != replacementString) {
        [replacementString release];
        replacementString = [aString retain];
    }
}

- (void)dealloc;
{
    [regularExpression release];
    [lastMatch release];
    [replacementString release];
    [super dealloc];
}

//
// OAFindPattern protocol
//

- (BOOL)findInString:(NSString *)aString foundRange:(NSRangePointer)rangePtr;
{
    OFRegularExpressionMatch *match;

    [lastMatch release];
    lastMatch = nil;

    if (aString == nil)
        return NO;

    if (!(match = [regularExpression matchInString:aString]))
        return NO;

    if (isBackwards) {
        OFRegularExpressionMatch *next;

        while ((next = [match nextMatch]))
            match = next;
    }

    if (rangePtr != NULL) {
        if (selectedSubexpression == SELECT_FULL_EXPRESSION)
            *rangePtr = [match matchRange];
        else
            *rangePtr = [match rangeOfSubexpressionAtIndex:selectedSubexpression];
    }

    lastMatch = [match retain];
    return YES;
}

- (BOOL)findInRange:(NSRange)range ofString:(NSString *)aString foundRange:(NSRangePointer)rangePtr;
{
    BOOL result;

    if (aString == nil)
        return NO;

    result = [self findInString:[aString substringWithRange:range] foundRange:rangePtr];
    if (rangePtr != NULL)
        rangePtr->location += range.location;
    return result;
}

- (NSString *)replacementStringForLastFind;
{
    OFStringScanner *scanner;
    NSMutableString *interpolatedString = [NSMutableString string];

    scanner = [[OFStringScanner alloc] initWithString:replacementString];
    while (scannerHasData(scanner)) {
        unsigned int subexpressionIndex = 0;
        BOOL readNumber = NO;
        unichar c;

        [interpolatedString appendString:[scanner readFullTokenWithDelimiterCharacter:'\\']];
        if (scannerReadCharacter(scanner) != '\\')
            break;

        c = scannerPeekCharacter(scanner);
        if ((c >= '0') && (c <= '9')) {
            scannerSkipPeekedCharacter(scanner);
            subexpressionIndex = (c - '0');
            readNumber = YES;
        } else if (c == '{') {
            scannerSkipPeekedCharacter(scanner);
            while ((c = scannerPeekCharacter(scanner)) && (c >= '0') && (c <= '9')) {
                scannerSkipPeekedCharacter(scanner);
                subexpressionIndex *= 10;
                subexpressionIndex += (c - '0');
                readNumber = YES;
            }
            if (c == '}')
                scannerSkipPeekedCharacter(scanner);
        } else if (c == 't') {
            scannerSkipPeekedCharacter(scanner);
            [interpolatedString appendString:@"\t"];
        } else if (c == 'n') {
            scannerSkipPeekedCharacter(scanner);
            [interpolatedString appendString:@"\n"];
        } else if (c == 'r') {
            scannerSkipPeekedCharacter(scanner);
            [interpolatedString appendString:@"\r"];
        } else if (c == '\\') {
            scannerSkipPeekedCharacter(scanner);
            [interpolatedString appendString:@"\\"];
        }

        if (readNumber && subexpressionIndex <= [regularExpression subexpressionCount]) {
            NSString *subString;

            if (subexpressionIndex)
                subString = [lastMatch subexpressionAtIndex:(subexpressionIndex - 1)];
            else
                subString = [lastMatch matchString];
            [interpolatedString appendString:subString];
        }
    }
    [scanner release];
    return interpolatedString;
}

// Allow the caller to inspect the contents of the find pattern (very helpful when they cannot efficiently reduce their target content to a string)

- (NSString *)findPattern;
{
    return [regularExpression patternString];
}

- (BOOL)isCaseSensitive;
{
    return NO;
}

- (BOOL)isBackwards;
{
    return isBackwards;
}

- (BOOL)isRegularExpression;
{
    return YES;
}

@end


text:
@interface VUMeter : CCNode
{
	CCSprite* needle;
	double db;
	double smoothing;
	double multiplier;
	double runningAverage;
}
@property(nonatomic,readwrite,assign) double db;
@property(nonatomic,readwrite,assign) double smoothing;
@property(nonatomic,readwrite,assign) double multiplier;

@property(nonatomic,readonly,assign) double runningAverage;

+ (VUMeter*) meter;

@end


text:
Ported from https://github.com/olikraus/u8glib

Here is black magic with ImageMagic package  for image conversion:

```bash
#!/bin/bash

mkdir out

for icon in *png; do
    convert $icon -depth 1 ./out/$(basename $icon .png)_1bpp.png
    if [[ "$icon" == *"black"* ]]; then
        convert ./out/$(basename $icon .png)_1bpp.png -background white -alpha Background ./out/$(basename $icon .png)_1bpp.xbm
    else
        convert ./out/$(basename $icon .png)_1bpp.png -background black -alpha Background ./out/$(basename $icon .png)_1bpp.xbm
    fi
    cat ./out/$(basename $icon .png)_1bpp.xbm | tr '\n' ' '  | tr -d " " |sed  -e s'#^.*{##g'  | sed s'#,}##' |sed s'/;//' | xxd -r -p > ./out/$(basename $icon .png).xbm.mono
done

rm out/*png out/*xbm
```
Convert all the png in the current folder and put resulting .mono to ./out

The convert binary  is a part of ImageMagic package. You need to install it.

```
sudo apt-get install imagemagick
```
for Debian/Ubuntu.


text:
product-cdm
===========
WSO2 CONNECTED DEVICE MANAGER

WSO2 Connected Device Manager (WSO2 CDM) is a comprehensive platform that helps solve mobile computing challenges enterprises face today when dealing with both corporate owned, personally enabled (COPE) devices and employee owned devices as part of a bring your own device (BYOD) program.

Whether it is device provisioning, device configuration management, policy enforcement, mobile application management, device data security, or compliance monitoring, WSO2 CDM offers a single enterprise-grade platform to develop extensions for IOT related device types.


text:
package jdk.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {

	private static final int ECHO_SERVER_PORT = 6789;

	public static void main(String[] args) {

		try(ServerSocket server = new ServerSocket(ECHO_SERVER_PORT)) {
			System.out.println("服务器已经启动...");
			while(true) {
				Socket client = server.accept();
				new Thread(new ClientHandler(client)).start();
			}
		}catch(IOException e) {
			e.printStackTrace();
		}
	}

	private static class ClientHandler implements Runnable {
		private Socket client;

		public ClientHandler(Socket client) {
			super();
			this.client = client;
		}

		@Override
		public void run() {
			try(BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
					PrintWriter pw = new PrintWriter(client.getOutputStream())) {
				String msg = br.readLine();
				System.out.println("收到"+client.getInetAddress()+"发送的:"+msg);
				pw.println(msg);
				pw.flush();
			}catch(Exception ex) {
				ex.printStackTrace();
			} finally {
				try{
					client.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: sjoder
 * Date: 03.04.2017
 * Time: 13:48
 */

namespace PM\Bundle\ToolBundle\Entity;

use DateTime;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class Image
 *
 * @package PM\Bundle\ToolBundle\Entity
 *
 * @ORM\MappedSuperclass()
 * @ORM\HasLifecycleCallbacks()
 */
abstract class Config
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="k_y", type="string", length=255, unique=true)
     */
    private $key;

    /**
     * @var mixed
     *
     * @ORM\Column(name="val_e", type="string", length=255)
     */
    private $value;

    /**
     * @var DateTime
     *
     * @ORM\Column(name="changed", type="datetime")
     */
    private $changed;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param mixed $value
     *
     * @return Config
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @return DateTime
     */
    public function getChanged()
    {
        return $this->changed;
    }

    /**
     * @param DateTime $changed
     *
     * @return Config
     */
    public function setChanged($changed)
    {
        $this->changed = $changed;

        return $this;
    }

    /**
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * @param string $key
     *
     * @return Config
     */
    public function setKey($key)
    {
        $this->key = $key;

        return $this;
    }

    /**
     * @ORM\PreFlush
     */
    public function update()
    {
        $this->setChanged(new DateTime());
    }

    /**
     * Get Keys Available
     *
     * @return array
     */
    public static function getKeysAvailable()
    {
        $reflection = new \ReflectionClass(get_called_class());

        return $reflection->getConstants();
    }
}


text:
<?php

class Google_Service_Books_VolumeSaleInfo extends Google_Collection
{
  protected $collection_key = 'offers';
  public $buyLink;
  public $country;
  public $isEbook;
  protected $listPriceType = 'Google_Service_Books_VolumeSaleInfoListPrice';
  protected $listPriceDataType = '';
  protected $offersType = 'Google_Service_Books_VolumeSaleInfoOffers';
  protected $offersDataType = 'array';
  public $onSaleDate;
  protected $retailPriceType = 'Google_Service_Books_VolumeSaleInfoRetailPrice';
  protected $retailPriceDataType = '';
  public $saleability;

  public function setBuyLink($buyLink)
  {
    $this->buyLink = $buyLink;
  }
  public function getBuyLink()
  {
    return $this->buyLink;
  }
  public function setCountry($country)
  {
    $this->country = $country;
  }
  public function getCountry()
  {
    return $this->country;
  }
  public function setIsEbook($isEbook)
  {
    $this->isEbook = $isEbook;
  }
  public function getIsEbook()
  {
    return $this->isEbook;
  }
  public function setListPrice(Google_Service_Books_VolumeSaleInfoListPrice $listPrice)
  {
    $this->listPrice = $listPrice;
  }
  public function getListPrice()
  {
    return $this->listPrice;
  }
  public function setOffers($offers)
  {
    $this->offers = $offers;
  }
  public function getOffers()
  {
    return $this->offers;
  }
  public function setOnSaleDate($onSaleDate)
  {
    $this->onSaleDate = $onSaleDate;
  }
  public function getOnSaleDate()
  {
    return $this->onSaleDate;
  }
  public function setRetailPrice(Google_Service_Books_VolumeSaleInfoRetailPrice $retailPrice)
  {
    $this->retailPrice = $retailPrice;
  }
  public function getRetailPrice()
  {
    return $this->retailPrice;
  }
  public function setSaleability($saleability)
  {
    $this->saleability = $saleability;
  }
  public function getSaleability()
  {
    return $this->saleability;
  }
}


text:
<!DOCTYPE HTML>

		<link rel="shortcut icon" type="image/png" href="images/logo.png">
		<title>LightVet</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />

		<link rel="stylesheet" href="assets/css/main.css" />

					Dr. Dany Freudenthal

Menu

Menu

Owners

Managment

Contact Us

Add Pet

					<form method="post" action="#" id="add_pet_form">

							<input type="text" name="name" id="name" placeholder="Pet's Name" />

							<input type="text" name="breed" id="breed" placeholder="Pet's Breed" />

							<input type="text" name="color" id="color" placeholder="Pet's Color" />

							<input type="text" name="pet-age" id="pet-age" placeholder="Pet's Age In Years.Months (4.11)" />

							<select name="pet-gender" id="pet-gender">
								<option value="" selected="selected">Pet's Gender</option>
								<option value="0">Male</option>
								<option value="1">Female</option>
							</select>

							<select name="pet-type" id="pet-type">
								<option value="" selected="selected">Pet's Type</option>
								<option value="1">Dog</option>
								<option value="2">Cat</option>
								<option value="3">Other</option>
							</select>

							<input type="text" name="chipNum" id="chipNum" placeholder="Chip Number" />

							<input type="checkbox" id="chipNumGenerator" name="chipNumGenerator">
							Check if there is no chip

<input type="submit" value="Add Pet" class="special"/>

					</form>

© Freudenthal. All rights reserved


text:
using GTA.Native;

namespace GrandTheftAuto
{
    class Mission
    {
        private class MissionData
        {
            public int numMissionsCompleted;
            public int sp0MissionsFailed, sp1MissionsFailed, sp2MissionsFailed;
            public int timesMissionSkipped;

            //num_missions_completed
            //sp0_missions_failed, sp1_missions_failed, sp2_missions_failed
            //times_mission_skipped
            public MissionData()
            {
                OutputArgument outArg = new OutputArgument();

                if (Function.Call<bool>(Hash.STAT_GET_INT, "num_missions_completed", outArg, -1))
                {
                    numMissionsCompleted = outArg.GetResult<int>();
                }
                else numMissionsCompleted = 0;

                if (Function.Call<bool>(Hash.STAT_GET_INT, "sp0_missions_failed", outArg, -1))
                {
                    sp0MissionsFailed = outArg.GetResult<int>();
                }
                else sp0MissionsFailed = 0;

                if (Function.Call<bool>(Hash.STAT_GET_INT, "sp1_missions_failed", outArg, -1))
                {
                    sp1MissionsFailed = outArg.GetResult<int>();
                }
                else sp1MissionsFailed = 0;

                if (Function.Call<bool>(Hash.STAT_GET_INT, "sp2_missions_failed", outArg, -1))
                {
                    sp2MissionsFailed = outArg.GetResult<int>();
                }
                else sp2MissionsFailed = 0;

                if (Function.Call<bool>(Hash.STAT_GET_INT, "times_mission_skipped", outArg, -1))
                {
                    timesMissionSkipped = outArg.GetResult<int>();
                }
                else timesMissionSkipped = 0;
            }

            public override bool Equals(object obj)
            {
                if (obj == null) return false;

                var data = obj as MissionData;

                return (numMissionsCompleted == data.numMissionsCompleted) &&
                    (sp0MissionsFailed == data.sp0MissionsFailed) && (sp1MissionsFailed == data.sp1MissionsFailed) &&
                    (sp2MissionsFailed == data.sp2MissionsFailed) && (timesMissionSkipped == data.timesMissionSkipped);
            }

            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
        }

        private static MissionData lastMissionData;

        public static bool DidMissionEnd
        {
            get
            {
                var newMissionData = new MissionData();

                bool equal = lastMissionData.Equals(newMissionData);

                lastMissionData = newMissionData;

                return equal;
            }
        }

        public static void Initialize()
        {
            lastMissionData = new MissionData();
        }
    }
}


text:
+--------+-------------------+
| npr1   | R Documentation   |
+--------+-------------------+

US Naval Petroleum Reserve No. 1 data
-------------------------------------

Description
~~~~~~~~~~~

Data on the locations, porosity and permeability (a measure of oil flow)
on 104 oil wells in the US Naval Petroleum Reserve No. 1 in California.

Usage
~~~~~

::

    npr1

Format
~~~~~~

This data frame contains the following columns:

``x``
    x coordinates, in miles (origin unspecified)..

``y``
    y coordinates, in miles.

``perm``
    permeability in milli-Darcies.

``por``
    porosity (%).

Source
~~~~~~

Maher, J.C., Carter, R.D. and Lantz, R.J. (1975) Petroleum geology of
Naval Petroleum Reserve No. 1, Elk Hills, Kern County, California. *USGS
Professional Paper* **912**.

References
~~~~~~~~~~

Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with
S.* Fourth edition. Springer.


text:
#ifndef HASHLIB_H
#define HASHLIB_H

/* Library's headers */
#include "HashContext.h"

/*  ====================================================================
Makes sure all the functions provided by the library are working as expected
*	MD5 : Based on RFC 1321 ; No NIST based test vector available
*	SHA1, SHA2 : Based on FIPS 180-4 NIST test vectors (byte-oriented) : http://csrc.nist.gov/groups/STM/cavp/secure-hashing.html
*/
 int HashLib_Init();

#endif // !HASHLIB_H


text:
package org.apache.jmeter;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.Authenticator;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import javax.swing.JTree;
import javax.swing.tree.TreePath;

import org.apache.commons.cli.avalon.CLArgsParser;
import org.apache.commons.cli.avalon.CLOption;
import org.apache.commons.cli.avalon.CLOptionDescriptor;
import org.apache.commons.cli.avalon.CLUtil;
import org.apache.jmeter.control.ReplaceableController;
import org.apache.jmeter.engine.ClientJMeterEngine;
import org.apache.jmeter.engine.JMeterEngine;
import org.apache.jmeter.engine.RemoteJMeterEngineImpl;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.exceptions.IllegalUserActionException;
import org.apache.jmeter.gui.GuiPackage;
import org.apache.jmeter.gui.MainFrame;
import org.apache.jmeter.gui.action.ActionNames;
import org.apache.jmeter.gui.action.ActionRouter;
import org.apache.jmeter.gui.action.Load;
import org.apache.jmeter.gui.action.LoadRecentProject;
import org.apache.jmeter.gui.tree.JMeterTreeListener;
import org.apache.jmeter.gui.tree.JMeterTreeModel;
import org.apache.jmeter.gui.tree.JMeterTreeNode;
import org.apache.jmeter.gui.util.FocusRequester;
import org.apache.jmeter.plugin.JMeterPlugin;
import org.apache.jmeter.plugin.PluginManager;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.samplers.Remoteable;
import org.apache.jmeter.samplers.SampleEvent;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestStateListener;
import org.apache.jmeter.threads.RemoteThreadsListenerTestElement;
import org.apache.jmeter.util.BeanShellInterpreter;
import org.apache.jmeter.util.BeanShellServer;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.SearchByClass;
import org.apache.jorphan.gui.ComponentUtil;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.reflect.ClassTools;
import org.apache.jorphan.util.HeapDumper;
import org.apache.jorphan.util.JMeterException;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;

import com.thoughtworks.xstream.converters.ConversionException;

/**
 * Main JMeter class; processes options and starts the GUI, non-GUI or server as appropriate.
 */
public class JMeter implements JMeterPlugin {

    private static final Logger log = LoggingManager.getLoggerForClass();

    public static final int UDP_PORT_DEFAULT = 4445; // needed for ShutdownClient

    public static final String HTTP_PROXY_PASS = "http.proxyPass"; // $NON-NLS-1$

    public static final String HTTP_PROXY_USER = "http.proxyUser"; // $NON-NLS-1$

    public static final String JMETER_NON_GUI = "JMeter.NonGui"; // $NON-NLS-1$

    // If the -t flag is to "LAST", then the last loaded file (if any) is used
    private static final String USE_LAST_JMX = "LAST";
    // If the -j  or -l flag is set to LAST or LAST.log|LAST.jtl, then the last loaded file name is used to
    // generate the log file name by removing .JMX and replacing it with .log|.jtl

    private static final int PROXY_PASSWORD     = 'a';// $NON-NLS-1$
    private static final int JMETER_HOME_OPT    = 'd';// $NON-NLS-1$
    private static final int HELP_OPT           = 'h';// $NON-NLS-1$
    // jmeter.log
    private static final int JMLOGFILE_OPT      = 'j';// $NON-NLS-1$
    // sample result log file
    private static final int LOGFILE_OPT        = 'l';// $NON-NLS-1$
    private static final int NONGUI_OPT         = 'n';// $NON-NLS-1$
    private static final int PROPFILE_OPT       = 'p';// $NON-NLS-1$
    private static final int PROPFILE2_OPT      = 'q';// $NON-NLS-1$
    private static final int REMOTE_OPT         = 'r';// $NON-NLS-1$
    private static final int SERVER_OPT         = 's';// $NON-NLS-1$
    private static final int TESTFILE_OPT       = 't';// $NON-NLS-1$
    private static final int PROXY_USERNAME     = 'u';// $NON-NLS-1$
    private static final int VERSION_OPT        = 'v';// $NON-NLS-1$

    private static final int SYSTEM_PROPERTY    = 'D';// $NON-NLS-1$
    private static final int JMETER_GLOBAL_PROP = 'G';// $NON-NLS-1$
    private static final int PROXY_HOST         = 'H';// $NON-NLS-1$
    private static final int JMETER_PROPERTY    = 'J';// $NON-NLS-1$
    private static final int LOGLEVEL           = 'L';// $NON-NLS-1$
    private static final int NONPROXY_HOSTS     = 'N';// $NON-NLS-1$
    private static final int PROXY_PORT         = 'P';// $NON-NLS-1$
    private static final int REMOTE_OPT_PARAM   = 'R';// $NON-NLS-1$
    private static final int SYSTEM_PROPFILE    = 'S';// $NON-NLS-1$
    private static final int REMOTE_STOP        = 'X';// $NON-NLS-1$

    /**
     * Define the understood options. Each CLOptionDescriptor contains:
     *

     *
The "long" version of the option. Eg, "help" means that "--help"
     * will be recognised.

     *
The option flags, governing the option's argument(s).

     *
The "short" version of the option. Eg, 'h' means that "-h" will be
     * recognised.

     *
A description of the option.

     *

     */
    private static final CLOptionDescriptor[] options = new CLOptionDescriptor[] {
            new CLOptionDescriptor("help", CLOptionDescriptor.ARGUMENT_DISALLOWED, HELP_OPT,
                    "print usage information and exit"),
            new CLOptionDescriptor("version", CLOptionDescriptor.ARGUMENT_DISALLOWED, VERSION_OPT,
                    "print the version information and exit"),
            new CLOptionDescriptor("propfile", CLOptionDescriptor.ARGUMENT_REQUIRED, PROPFILE_OPT,
                    "the jmeter property file to use"),
            new CLOptionDescriptor("addprop", CLOptionDescriptor.ARGUMENT_REQUIRED
                    | CLOptionDescriptor.DUPLICATES_ALLOWED, PROPFILE2_OPT,
                    "additional JMeter property file(s)"),
            new CLOptionDescriptor("testfile", CLOptionDescriptor.ARGUMENT_REQUIRED, TESTFILE_OPT,
                    "the jmeter test(.jmx) file to run"),
            new CLOptionDescriptor("logfile", CLOptionDescriptor.ARGUMENT_REQUIRED, LOGFILE_OPT,
                    "the file to log samples to"),
            new CLOptionDescriptor("jmeterlogfile", CLOptionDescriptor.ARGUMENT_REQUIRED, JMLOGFILE_OPT,
                    "jmeter run log file (jmeter.log)"),
            new CLOptionDescriptor("nongui", CLOptionDescriptor.ARGUMENT_DISALLOWED, NONGUI_OPT,
                    "run JMeter in nongui mode"),
            new CLOptionDescriptor("server", CLOptionDescriptor.ARGUMENT_DISALLOWED, SERVER_OPT,
                    "run the JMeter server"),
            new CLOptionDescriptor("proxyHost", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_HOST,
                    "Set a proxy server for JMeter to use"),
            new CLOptionDescriptor("proxyPort", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_PORT,
                    "Set proxy server port for JMeter to use"),
            new CLOptionDescriptor("nonProxyHosts", CLOptionDescriptor.ARGUMENT_REQUIRED, NONPROXY_HOSTS,
                    "Set nonproxy host list (e.g. *.apache.org|localhost)"),
            new CLOptionDescriptor("username", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_USERNAME,
                    "Set username for proxy server that JMeter is to use"),
            new CLOptionDescriptor("password", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_PASSWORD,
                    "Set password for proxy server that JMeter is to use"),
            new CLOptionDescriptor("jmeterproperty", CLOptionDescriptor.DUPLICATES_ALLOWED
                    | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, JMETER_PROPERTY,
                    "Define additional JMeter properties"),
            new CLOptionDescriptor("globalproperty", CLOptionDescriptor.DUPLICATES_ALLOWED
                    | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, JMETER_GLOBAL_PROP,
                    "Define Global properties (sent to servers)\n\t\te.g. -Gport=123 or -Gglobal.properties"),
            new CLOptionDescriptor("systemproperty", CLOptionDescriptor.DUPLICATES_ALLOWED
                    | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, SYSTEM_PROPERTY,
                    "Define additional system properties"),
            new CLOptionDescriptor("systemPropertyFile", CLOptionDescriptor.DUPLICATES_ALLOWED
                    | CLOptionDescriptor.ARGUMENT_REQUIRED, SYSTEM_PROPFILE,
                    "additional system property file(s)"),
            new CLOptionDescriptor("loglevel", CLOptionDescriptor.DUPLICATES_ALLOWED
                    | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, LOGLEVEL,
                    "[category=]level e.g. jorphan=INFO or jmeter.util=DEBUG"),
            new CLOptionDescriptor("runremote", CLOptionDescriptor.ARGUMENT_DISALLOWED, REMOTE_OPT,
                    "Start remote servers (as defined in remote_hosts)"),
            new CLOptionDescriptor("remotestart", CLOptionDescriptor.ARGUMENT_REQUIRED, REMOTE_OPT_PARAM,
                    "Start these remote servers (overrides remote_hosts)"),
            new CLOptionDescriptor("homedir", CLOptionDescriptor.ARGUMENT_REQUIRED, JMETER_HOME_OPT,
                    "the jmeter home directory to use"),
            new CLOptionDescriptor("remoteexit", CLOptionDescriptor.ARGUMENT_DISALLOWED, REMOTE_STOP,
            "Exit the remote servers at end of test (non-GUI)"),
                    };

    public JMeter() {
    }

    // Hack to allow automated tests to find when test has ended
    //transient boolean testEnded = false;

    private JMeter parent;

    private Properties remoteProps; // Properties to be sent to remote servers

    private boolean remoteStop; // should remote engines be stopped at end of non-GUI test?

    /**
     * Starts up JMeter in GUI mode
     */
    private void startGui(String testFile) {

        PluginManager.install(this, true);
        JMeterTreeModel treeModel = new JMeterTreeModel();
        JMeterTreeListener treeLis = new JMeterTreeListener(treeModel);
        treeLis.setActionHandler(ActionRouter.getInstance());
        // NOTUSED: GuiPackage guiPack =
        GuiPackage.getInstance(treeLis, treeModel);
        MainFrame main = new MainFrame(treeModel, treeLis);
        ComponentUtil.centerComponentInWindow(main, 80);
        main.setVisible(true);
        ActionRouter.getInstance().actionPerformed(new ActionEvent(main, 1, ActionNames.ADD_ALL));
        if (testFile != null) {
            FileInputStream reader = null;
            try {
                File f = new File(testFile);
                log.info("Loading file: " + f);
                FileServer.getFileServer().setBaseForScript(f);

                reader = new FileInputStream(f);
                HashTree tree = SaveService.loadTree(reader);

                GuiPackage.getInstance().setTestPlanFile(f.getAbsolutePath());

                Load.insertLoadedTree(1, tree);
            } catch (ConversionException e) {
                log.error("Failure loading test file", e);
                JMeterUtils.reportErrorToUser(SaveService.CEtoString(e));
            } catch (Exception e) {
                log.error("Failure loading test file", e);
                JMeterUtils.reportErrorToUser(e.toString());
            } finally {
                JOrphanUtils.closeQuietly(reader);
            }
        } else {
            JTree jTree = GuiPackage.getInstance().getMainFrame().getTree();
            TreePath path = jTree.getPathForRow(0);
            jTree.setSelectionPath(path);
            FocusRequester.requestFocus(jTree);
        }
    }

    /**
     * Takes the command line arguments and uses them to determine how to
     * startup JMeter.
     *
     * Called reflectively by {@link NewDriver#main(String[])}
     */
    public void start(String[] args) {

        CLArgsParser parser = new CLArgsParser(args, options);
        String error = parser.getErrorString();
        if (error == null){// Check option combinations
            boolean gui = parser.getArgumentById(NONGUI_OPT)==null;
            boolean nonGuiOnly = parser.getArgumentById(REMOTE_OPT)!=null
                               || parser.getArgumentById(REMOTE_OPT_PARAM)!=null
                               || parser.getArgumentById(REMOTE_STOP)!=null;
            if (gui && nonGuiOnly) {
                error = "-r and -R and -X are only valid in non-GUI mode";
            }
        }
        if (null != error) {
            System.err.println("Error: " + error);
            System.out.println("Usage");
            System.out.println(CLUtil.describeOptions(options).toString());
            return;
        }
        try {
            initializeProperties(parser); // Also initialises JMeter logging

            /*
             * The following is needed for HTTPClient.
             * (originally tried doing this in HTTPSampler2,
             * but it appears that it was done too late when running in GUI mode)
             * Set the commons logging default to Avalon Logkit, if not already defined
             */
            if (System.getProperty("org.apache.commons.logging.Log") == null) { // $NON-NLS-1$
                System.setProperty("org.apache.commons.logging.Log" // $NON-NLS-1$
                        , "org.apache.commons.logging.impl.LogKitLogger"); // $NON-NLS-1$
            }

            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    if (!(e instanceof ThreadDeath)) {
                        log.error("Uncaught exception: ", e);
                        System.err.println("Uncaught Exception " + e + ". See log file for details.");
                    }
                }
            });

            log.info(JMeterUtils.getJMeterCopyright());
            log.info("Version " + JMeterUtils.getJMeterVersion());
            logProperty("java.version"); //$NON-NLS-1$
            logProperty("java.vm.name"); //$NON-NLS-1$
            logProperty("os.name"); //$NON-NLS-1$
            logProperty("os.arch"); //$NON-NLS-1$
            logProperty("os.version"); //$NON-NLS-1$
            logProperty("file.encoding"); // $NON-NLS-1$
            log.info("Default Locale=" + Locale.getDefault().getDisplayName());
            log.info("JMeter  Locale=" + JMeterUtils.getLocale().getDisplayName());
            log.info("JMeterHome="     + JMeterUtils.getJMeterHome());
            logProperty("user.dir","  ="); //$NON-NLS-1$
            log.info("PWD       ="+new File(".").getCanonicalPath());//$NON-NLS-1$
            log.info("IP: "+JMeterUtils.getLocalHostIP()
                    +" Name: "+JMeterUtils.getLocalHostName()
                    +" FullName: "+JMeterUtils.getLocalHostFullName());
            setProxy(parser);

            updateClassLoader();
            if (log.isDebugEnabled())
            {
                String jcp=System.getProperty("java.class.path");// $NON-NLS-1$
                String bits[] =jcp.split(File.pathSeparator);
                log.debug("ClassPath");
                for(String bit : bits){
                    log.debug(bit);
                }
                log.debug(jcp);
            }

            // Set some (hopefully!) useful properties
            long now=System.currentTimeMillis();
            JMeterUtils.setProperty("START.MS",Long.toString(now));// $NON-NLS-1$
            Date today=new Date(now); // so it agrees with above
            // TODO perhaps should share code with __time() function for this...
            JMeterUtils.setProperty("START.YMD",new SimpleDateFormat("yyyyMMdd").format(today));// $NON-NLS-1$ $NON-NLS-2$
            JMeterUtils.setProperty("START.HMS",new SimpleDateFormat("HHmmss").format(today));// $NON-NLS-1$ $NON-NLS-2$

            if (parser.getArgumentById(VERSION_OPT) != null) {
                System.out.println(JMeterUtils.getJMeterCopyright());
                System.out.println("Version " + JMeterUtils.getJMeterVersion());
            } else if (parser.getArgumentById(HELP_OPT) != null) {
                System.out.println(JMeterUtils.getResourceFileAsText("org/apache/jmeter/help.txt"));// $NON-NLS-1$
            } else if (parser.getArgumentById(SERVER_OPT) != null) {
                // Start the server
                try {
                    RemoteJMeterEngineImpl.startServer(JMeterUtils.getPropDefault("server_port", 0)); // $NON-NLS-1$
                } catch (Exception ex) {
                    System.err.println("Server failed to start: "+ex);
                    log.error("Giving up, as server failed with:", ex);
                    throw ex;
                }
                startOptionalServers();
            } else {
                String testFile=null;
                CLOption testFileOpt = parser.getArgumentById(TESTFILE_OPT);
                if (testFileOpt != null){
                    testFile = testFileOpt.getArgument();
                    if (USE_LAST_JMX.equals(testFile)) {
                        testFile = LoadRecentProject.getRecentFile(0);// most recent
                    }
                }
                if (parser.getArgumentById(NONGUI_OPT) == null) {
                    startGui(testFile);
                    startOptionalServers();
                } else {
                    CLOption rem=parser.getArgumentById(REMOTE_OPT_PARAM);
                    if (rem==null) { rem=parser.getArgumentById(REMOTE_OPT); }
                    CLOption jtl = parser.getArgumentById(LOGFILE_OPT);
                    String jtlFile = null;
                    if (jtl != null){
                        jtlFile=processLAST(jtl.getArgument(), ".jtl"); // $NON-NLS-1$
                    }
                    startNonGui(testFile, jtlFile, rem);
                    startOptionalServers();
                }
            }
        } catch (IllegalUserActionException e) {
            System.out.println(e.getMessage());
            System.out.println("Incorrect Usage");
            System.out.println(CLUtil.describeOptions(options).toString());
        } catch (Throwable e) {
            log.fatalError("An error occurred: ",e);
            System.out.println("An error occurred: " + e.getMessage());
            System.exit(1); // TODO - could this be return?
        }
    }

    // Update classloader if necessary
    private void updateClassLoader() {
            updatePath("search_paths",";", true); //$NON-NLS-1$//$NON-NLS-2$
            updatePath("user.classpath",File.pathSeparator, true);//$NON-NLS-1$
            updatePath("plugin_dependency_paths",";", false);//$NON-NLS-1$
    }

    private void updatePath(String property, String sep, boolean cp) {
        String userpath= JMeterUtils.getPropDefault(property,"");// $NON-NLS-1$
        if (userpath.length() <= 0) { return; }
        log.info(property+"="+userpath); //$NON-NLS-1$
        StringTokenizer tok = new StringTokenizer(userpath, sep);
        while(tok.hasMoreTokens()) {
            String path=tok.nextToken();
            File f=new File(path);
            if (!f.canRead() && !f.isDirectory()) {
                log.warn("Can't read "+path);
            } else {
                if (cp) {
                    log.info("Adding to classpath and loader: "+path);
                    try {
                        NewDriver.addPath(path);
                    } catch (MalformedURLException e) {
                        log.warn("Error adding: "+path+" "+e.getLocalizedMessage());
                    }
                } else {
                    log.info("Adding to loader: "+path);
                    NewDriver.addURL(path);
                }
            }
        }
    }

    /**
     *
     */
    private void startOptionalServers() {
        int bshport = JMeterUtils.getPropDefault("beanshell.server.port", 0);// $NON-NLS-1$
        String bshfile = JMeterUtils.getPropDefault("beanshell.server.file", "");// $NON-NLS-1$ $NON-NLS-2$
        if (bshport > 0) {
            log.info("Starting Beanshell server (" + bshport + "," + bshfile + ")");
            Runnable t = new BeanShellServer(bshport, bshfile);
            t.run();
        }

        // Should we run a beanshell script on startup?
        String bshinit = JMeterUtils.getProperty("beanshell.init.file");// $NON-NLS-1$
        if (bshinit != null){
            log.info("Run Beanshell on file: "+bshinit);
            try {
                BeanShellInterpreter bsi = new BeanShellInterpreter();//bshinit,log);
                bsi.source(bshinit);
            } catch (ClassNotFoundException e) {
                log.warn("Could not start Beanshell: "+e.getLocalizedMessage());
            } catch (JMeterException e) {
                log.warn("Could not process Beanshell file: "+e.getLocalizedMessage());
            }
        }

        int mirrorPort=JMeterUtils.getPropDefault("mirror.server.port", 0);// $NON-NLS-1$
        if (mirrorPort > 0){
            log.info("Starting Mirror server (" + mirrorPort + ")");
            try {
                Object instance = ClassTools.construct(
                        "org.apache.jmeter.protocol.http.control.HttpMirrorControl",// $NON-NLS-1$
                        mirrorPort);
                ClassTools.invoke(instance,"startHttpMirror");
            } catch (JMeterException e) {
                log.warn("Could not start Mirror server",e);
            }
        }
    }

    /**
     * Sets a proxy server for the JVM if the command line arguments are
     * specified.
     */
    private void setProxy(CLArgsParser parser) throws IllegalUserActionException {
        if (parser.getArgumentById(PROXY_USERNAME) != null) {
            Properties jmeterProps = JMeterUtils.getJMeterProperties();
            if (parser.getArgumentById(PROXY_PASSWORD) != null) {
                String u, p;
                Authenticator.setDefault(new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME)
                        .getArgument(), p = parser.getArgumentById(PROXY_PASSWORD).getArgument()));
                log.info("Set Proxy login: " + u + "/" + p);
                jmeterProps.setProperty(HTTP_PROXY_USER, u);//for Httpclient
                jmeterProps.setProperty(HTTP_PROXY_PASS, p);//for Httpclient
            } else {
                String u;
                Authenticator.setDefault(new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME)
                        .getArgument(), ""));
                log.info("Set Proxy login: " + u);
                jmeterProps.setProperty(HTTP_PROXY_USER, u);
            }
        }
        if (parser.getArgumentById(PROXY_HOST) != null && parser.getArgumentById(PROXY_PORT) != null) {
            String h = parser.getArgumentById(PROXY_HOST).getArgument();
            String p = parser.getArgumentById(PROXY_PORT).getArgument();
            System.setProperty("http.proxyHost",  h );// $NON-NLS-1$
            System.setProperty("https.proxyHost", h);// $NON-NLS-1$
            System.setProperty("http.proxyPort",  p);// $NON-NLS-1$
            System.setProperty("https.proxyPort", p);// $NON-NLS-1$
            log.info("Set http[s].proxyHost: " + h + " Port: " + p);
        } else if (parser.getArgumentById(PROXY_HOST) != null || parser.getArgumentById(PROXY_PORT) != null) {
            throw new IllegalUserActionException(JMeterUtils.getResString("proxy_cl_error"));// $NON-NLS-1$
        }

        if (parser.getArgumentById(NONPROXY_HOSTS) != null) {
            String n = parser.getArgumentById(NONPROXY_HOSTS).getArgument();
            System.setProperty("http.nonProxyHosts",  n );// $NON-NLS-1$
            System.setProperty("https.nonProxyHosts", n );// $NON-NLS-1$
            log.info("Set http[s].nonProxyHosts: "+n);
        }
    }

    private void initializeProperties(CLArgsParser parser) {
        if (parser.getArgumentById(PROPFILE_OPT) != null) {
            JMeterUtils.loadJMeterProperties(parser.getArgumentById(PROPFILE_OPT).getArgument());
        } else {
            JMeterUtils.loadJMeterProperties(NewDriver.getJMeterDir() + File.separator
                    + "bin" + File.separator // $NON-NLS-1$
                    + "jmeter.properties");// $NON-NLS-1$
        }

        if (parser.getArgumentById(JMLOGFILE_OPT) != null){
            String jmlogfile=parser.getArgumentById(JMLOGFILE_OPT).getArgument();
            jmlogfile = processLAST(jmlogfile, ".log");// $NON-NLS-1$
            JMeterUtils.setProperty(LoggingManager.LOG_FILE,jmlogfile);
        }

        JMeterUtils.initLogging();
        JMeterUtils.initLocale();
        // Bug 33845 - allow direct override of Home dir
        if (parser.getArgumentById(JMETER_HOME_OPT) == null) {
            JMeterUtils.setJMeterHome(NewDriver.getJMeterDir());
        } else {
            JMeterUtils.setJMeterHome(parser.getArgumentById(JMETER_HOME_OPT).getArgument());
        }

        Properties jmeterProps = JMeterUtils.getJMeterProperties();
        remoteProps = new Properties();

        // Add local JMeter properties, if the file is found
        String userProp = JMeterUtils.getPropDefault("user.properties",""); //$NON-NLS-1$
        if (userProp.length() > 0){ //$NON-NLS-1$
            FileInputStream fis=null;
            try {
                File file = JMeterUtils.findFile(userProp);
                if (file.canRead()){
                    log.info("Loading user properties from: "+file.getCanonicalPath());
                    fis = new FileInputStream(file);
                    Properties tmp = new Properties();
                    tmp.load(fis);
                    jmeterProps.putAll(tmp);
                    LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier
                }
            } catch (IOException e) {
                log.warn("Error loading user property file: " + userProp, e);
            } finally {
                JOrphanUtils.closeQuietly(fis);
            }
        }

        // Add local system properties, if the file is found
        String sysProp = JMeterUtils.getPropDefault("system.properties",""); //$NON-NLS-1$
        if (sysProp.length() > 0){
            FileInputStream fis=null;
            try {
                File file = JMeterUtils.findFile(sysProp);
                if (file.canRead()){
                    log.info("Loading system properties from: "+file.getCanonicalPath());
                    fis = new FileInputStream(file);
                    System.getProperties().load(fis);
                }
            } catch (IOException e) {
                log.warn("Error loading system property file: " + sysProp, e);
            } finally {
                JOrphanUtils.closeQuietly(fis);
            }
        }

        // Process command line property definitions
        // These can potentially occur multiple times

        List<CLOption> clOptions = parser.getArguments();
        int size = clOptions.size();

        for (int i = 0; i < size; i++) {
            CLOption option = clOptions.get(i);
            String name = option.getArgument(0);
            String value = option.getArgument(1);
            FileInputStream fis = null;

            switch (option.getDescriptor().getId()) {

            // Should not have any text arguments
            case CLOption.TEXT_ARGUMENT:
                throw new IllegalArgumentException("Unknown arg: "+option.getArgument());

            case PROPFILE2_OPT: // Bug 33920 - allow multiple props
                try {
                    fis = new FileInputStream(new File(name));
                    Properties tmp = new Properties();
                    tmp.load(fis);
                    jmeterProps.putAll(tmp);
                    LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier
                } catch (FileNotFoundException e) {
                    log.warn("Can't find additional property file: " + name, e);
                } catch (IOException e) {
                    log.warn("Error loading additional property file: " + name, e);
                } finally {
                    JOrphanUtils.closeQuietly(fis);
                }
                break;
            case SYSTEM_PROPFILE:
                log.info("Setting System properties from file: " + name);
                try {
                    fis = new FileInputStream(new File(name));
                    System.getProperties().load(fis);
                } catch (IOException e) {
                    log.warn("Cannot find system property file "+e.getLocalizedMessage());
                } finally {
                    JOrphanUtils.closeQuietly(fis);
                }
                break;
            case SYSTEM_PROPERTY:
                if (value.length() > 0) { // Set it
                    log.info("Setting System property: " + name + "=" + value);
                    System.getProperties().setProperty(name, value);
                } else { // Reset it
                    log.warn("Removing System property: " + name);
                    System.getProperties().remove(name);
                }
                break;
            case JMETER_PROPERTY:
                if (value.length() > 0) { // Set it
                    log.info("Setting JMeter property: " + name + "=" + value);
                    jmeterProps.setProperty(name, value);
                } else { // Reset it
                    log.warn("Removing JMeter property: " + name);
                    jmeterProps.remove(name);
                }
                break;
            case JMETER_GLOBAL_PROP:
                if (value.length() > 0) { // Set it
                    log.info("Setting Global property: " + name + "=" + value);
                    remoteProps.setProperty(name, value);
                } else {
                    File propFile = new File(name);
                    if (propFile.canRead()) {
                        log.info("Setting Global properties from the file "+name);
                        try {
                            fis = new FileInputStream(propFile);
                            remoteProps.load(fis);
                        } catch (FileNotFoundException e) {
                            log.warn("Could not find properties file: "+e.getLocalizedMessage());
                        } catch (IOException e) {
                            log.warn("Could not load properties file: "+e.getLocalizedMessage());
                        } finally {
                            JOrphanUtils.closeQuietly(fis);
                        }
                    }
                }
                break;
            case LOGLEVEL:
                if (value.length() > 0) { // Set category
                    log.info("LogLevel: " + name + "=" + value);
                    LoggingManager.setPriority(value, name);
                } else { // Set root level
                    log.warn("LogLevel: " + name);
                    LoggingManager.setPriority(name);
                }
                break;
            case REMOTE_STOP:
                remoteStop = true;
                break;
            default:
                // ignored
                break;
            }
        }

        String sample_variables = (String) jmeterProps.get(SampleEvent.SAMPLE_VARIABLES);
        if (sample_variables != null){
            remoteProps.put(SampleEvent.SAMPLE_VARIABLES, sample_variables);
        }
        jmeterProps.put("jmeter.version", JMeterUtils.getJMeterVersion());
    }

    /*
     * Checks for LAST or LASTsuffix.
     * Returns the LAST name with .JMX replaced by suffix.
     */
    private String processLAST(String jmlogfile, String suffix) {
        if (USE_LAST_JMX.equals(jmlogfile) || USE_LAST_JMX.concat(suffix).equals(jmlogfile)){
            String last = LoadRecentProject.getRecentFile(0);// most recent
            final String JMX_SUFFIX = ".JMX"; // $NON-NLS-1$
            if (last.toUpperCase(Locale.ENGLISH).endsWith(JMX_SUFFIX)){
                jmlogfile=last.substring(0, last.length() - JMX_SUFFIX.length()).concat(suffix);
            }
        }
        return jmlogfile;
    }

    private void startNonGui(String testFile, String logFile, CLOption remoteStart)
            throws IllegalUserActionException {
        // add a system property so samplers can check to see if JMeter
        // is running in NonGui mode
        System.setProperty(JMETER_NON_GUI, "true");// $NON-NLS-1$
        JMeter driver = new JMeter();// TODO - why does it create a new instance?
        driver.remoteProps = this.remoteProps;
        driver.remoteStop = this.remoteStop;
        driver.parent = this;
        PluginManager.install(this, false);

        String remote_hosts_string = null;
        if (remoteStart != null) {
            remote_hosts_string = remoteStart.getArgument();
            if (remote_hosts_string == null) {
                remote_hosts_string = JMeterUtils.getPropDefault(
                        "remote_hosts", //$NON-NLS-1$
                        "127.0.0.1");//$NON-NLS-1$
            }
        }
        if (testFile == null) {
            throw new IllegalUserActionException("Non-GUI runs require a test plan");
        }
        driver.runNonGui(testFile, logFile, remoteStart != null, remote_hosts_string);
    }

    // run test in batch mode
    private void runNonGui(String testFile, String logFile, boolean remoteStart, String remote_hosts_string) {
        FileInputStream reader = null;
        try {
            File f = new File(testFile);
            if (!f.exists() || !f.isFile()) {
                println("Could not open " + testFile);
                return;
            }
            FileServer.getFileServer().setBaseForScript(f);

            reader = new FileInputStream(f);
            log.info("Loading file: " + f);

            HashTree tree = SaveService.loadTree(reader);

            @SuppressWarnings("deprecation") // Deliberate use of deprecated ctor
            JMeterTreeModel treeModel = new JMeterTreeModel(new Object());// Create non-GUI version to avoid headless problems
            JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
            treeModel.addSubTree(tree, root);

            // Hack to resolve ModuleControllers in non GUI mode
            SearchByClass<ReplaceableController> replaceableControllers = new SearchByClass<ReplaceableController>(ReplaceableController.class);
            tree.traverse(replaceableControllers);
            Collection<ReplaceableController> replaceableControllersRes = replaceableControllers.getSearchResults();
            for (Iterator<ReplaceableController> iter = replaceableControllersRes.iterator(); iter.hasNext();) {
                ReplaceableController replaceableController = iter.next();
                replaceableController.resolveReplacementSubTree(root);
            }

            // Remove the disabled items
            // For GUI runs this is done in Start.java
            convertSubTree(tree);

            Summariser summer = null;
            String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");//$NON-NLS-1$
            if (summariserName.length() > 0) {
                log.info("Creating summariser <" + summariserName + ">");
                println("Creating summariser <" + summariserName + ">");
                summer = new Summariser(summariserName);
            }

            if (logFile != null) {
                ResultCollector logger = new ResultCollector(summer);
                logger.setFilename(logFile);
                tree.add(tree.getArray()[0], logger);
            }
            else {
                // only add Summariser if it can not be shared with the ResultCollector
                if (summer != null) {
                    tree.add(tree.getArray()[0], summer);
                }
            }
            // Used for remote notification of threads start/stop,see BUG 54152
            // Summariser uses this feature to compute correctly number of threads
            // when NON GUI mode is used
            tree.add(tree.getArray()[0], new RemoteThreadsListenerTestElement());

            List<JMeterEngine> engines = new LinkedList<JMeterEngine>();
            tree.add(tree.getArray()[0], new ListenToTest(parent, (remoteStart && remoteStop) ? engines : null));
            println("Created the tree successfully using "+testFile);
            if (!remoteStart) {
                JMeterEngine engine = new StandardJMeterEngine();
                engine.configure(tree);
                long now=System.currentTimeMillis();
                println("Starting the test @ "+new Date(now)+" ("+now+")");
                engine.runTest();
                engines.add(engine);
            } else {
                java.util.StringTokenizer st = new java.util.StringTokenizer(remote_hosts_string, ",");//$NON-NLS-1$
                List<String> failingEngines = new ArrayList<String>(st.countTokens());
                while (st.hasMoreElements()) {
                    String el = (String) st.nextElement();
                    println("Configuring remote engine for " + el);
                    log.info("Configuring remote engine for " + el);
                    JMeterEngine eng = doRemoteInit(el.trim(), tree);
                    if (null != eng) {
                        engines.add(eng);
                    } else {
                        failingEngines.add(el);
                        println("Failed to configure "+el);
                    }
                }
                if (engines.isEmpty()) {
                    println("No remote engines were started.");
                    return;
                }
                if(failingEngines.size()>0) {
                    throw new IllegalArgumentException("The following remote engines could not be configured:"+failingEngines);
                }
                println("Starting remote engines");
                log.info("Starting remote engines");
                long now=System.currentTimeMillis();
                println("Starting the test @ "+new Date(now)+" ("+now+")");
                for (JMeterEngine engine : engines) {
                    engine.runTest();
                }
                println("Remote engines have been started");
                log.info("Remote engines have been started");
            }
            startUdpDdaemon(engines);
        } catch (Exception e) {
            System.out.println("Error in NonGUIDriver " + e.toString());
            log.error("Error in NonGUIDriver", e);
        } finally {
            JOrphanUtils.closeQuietly(reader);
        }
    }

    /**
     * Refactored from AbstractAction.java
     *
     * @param tree
     */
    public static void convertSubTree(HashTree tree) {
        LinkedList<Object> copyList = new LinkedList<Object>(tree.list());
        for (Object o  : copyList) {
            if (o instanceof TestElement) {
                TestElement item = (TestElement) o;
                if (item.isEnabled()) {
                    if (item instanceof ReplaceableController) {
                        ReplaceableController rc = ensureReplaceableControllerIsLoaded(item);

                        HashTree subTree = tree.getTree(item);
                        if (subTree != null) {
                            HashTree replacementTree = rc.getReplacementSubTree();
                            if (replacementTree != null) {
                                convertSubTree(replacementTree);
                                tree.replace(item, rc);
                                tree.set(rc, replacementTree);
                            }
                        }
                    } else { // not Replaceable Controller
                        convertSubTree(tree.getTree(item));
                    }
                } else { // Not enabled
                    tree.remove(item);
                }
            } else { // Not a TestElement
                JMeterTreeNode item = (JMeterTreeNode) o;
                if (item.isEnabled()) {
                    // Replacement only needs to occur when starting the engine
                    // @see StandardJMeterEngine.run()
                    if (item.getUserObject() instanceof ReplaceableController) {
                        TestElement controllerAsItem = item.getTestElement();
                        ReplaceableController rc = ensureReplaceableControllerIsLoaded(controllerAsItem);

                        HashTree subTree = tree.getTree(item);

                        if (subTree != null) {
                            HashTree replacementTree = rc.getReplacementSubTree();
                            if (replacementTree != null) {
                                convertSubTree(replacementTree);
                                tree.replace(item, rc);
                                tree.set(rc, replacementTree);
                            }
                        }
                    } else { // Not a ReplaceableController
                        convertSubTree(tree.getTree(item));
                        TestElement testElement = item.getTestElement();
                        tree.replace(item, testElement);
                    }
                 } else { // Not enabled
                    tree.remove(item);
                }
            }
        }
    }

    /**
     * Ensures the {@link ReplaceableController} is loaded
     * @param item {@link TestElement}
     * @return {@link ReplaceableController} loaded
     */
    private static ReplaceableController ensureReplaceableControllerIsLoaded(
            TestElement item) {
        ReplaceableController rc;
        // TODO this bit of code needs to be tidied up
        // Unfortunately ModuleController is in components, not core
        if (item.getClass().getName().equals("org.apache.jmeter.control.ModuleController")){ // Bug 47165
            rc = (ReplaceableController) item;
        } else {
            // HACK: force the controller to load its tree
            rc = (ReplaceableController) item.clone();
        }
        return rc;
    }

    private JMeterEngine doRemoteInit(String hostName, HashTree testTree) {
        JMeterEngine engine = null;
        try {
            engine = new ClientJMeterEngine(hostName);
        } catch (Exception e) {
            log.fatalError("Failure connecting to remote host: "+hostName, e);
            System.err.println("Failure connecting to remote host: "+hostName+" "+e);
            return null;
        }
        engine.configure(testTree);
        if (!remoteProps.isEmpty()) {
            engine.setProperties(remoteProps);
        }
        return engine;
    }

    /*
     * Listen to test and handle tidyup after non-GUI test completes.
     * If running a remote test, then after waiting a few seconds for listeners to finish files,
     * it calls ClientJMeterEngine.tidyRMI() to deal with the Naming Timer Thread.
     */
    private static class ListenToTest implements TestStateListener, Runnable, Remoteable {
        private final AtomicInteger started = new AtomicInteger(0); // keep track of remote tests

        //NOT YET USED private JMeter _parent;

        private final List<JMeterEngine> engines;

        /**
         * @param unused JMeter unused for now
         * @param engines List<JMeterEngine>
         */
        public ListenToTest(JMeter unused, List<JMeterEngine> engines) {
            //_parent = unused;
            this.engines=engines;
        }

        @Override
        public void testEnded(String host) {
            long now=System.currentTimeMillis();
            log.info("Finished remote host: " + host + " ("+now+")");
            if (started.decrementAndGet() <= 0) {
                Thread stopSoon = new Thread(this);
                stopSoon.start();
            }
        }

        @Override
        public void testEnded() {
            long now = System.currentTimeMillis();
            println("Tidying up ...    @ "+new Date(now)+" ("+now+")");
            println("... end of run");
            checkForRemainingThreads();
        }

        @Override
        public void testStarted(String host) {
            started.incrementAndGet();
            long now=System.currentTimeMillis();
            log.info("Started remote host:  " + host + " ("+now+")");
        }

        @Override
        public void testStarted() {
            long now=System.currentTimeMillis();
            log.info(JMeterUtils.getResString("running_test")+" ("+now+")");//$NON-NLS-1$
        }

        /**
         * This is a hack to allow listeners a chance to close their files. Must
         * implement a queue for sample responses tied to the engine, and the
         * engine won't deliver testEnded signal till all sample responses have
         * been delivered. Should also improve performance of remote JMeter
         * testing.
         */
        @Override
        public void run() {
            long now = System.currentTimeMillis();
            println("Tidying up remote @ "+new Date(now)+" ("+now+")");
            if (engines!=null){ // it will be null unless remoteStop = true
                println("Exitting remote servers");
                for (JMeterEngine e : engines){
                    e.exit();
                }
            }
            try {
                TimeUnit.SECONDS.sleep(5); // Allow listeners to close files
            } catch (InterruptedException ignored) {
            }
            ClientJMeterEngine.tidyRMI(log);
            println("... end of run");
            checkForRemainingThreads();
        }

        /**
         * Runs daemon thread which waits a short while;
         * if JVM does not exit, lists remaining non-daemon threads on stdout.
         */
        private void checkForRemainingThreads() {
            // This cannot be a JMeter class variable, because properties
            // are not initialised until later.
            final int REMAIN_THREAD_PAUSE =
                    JMeterUtils.getPropDefault("jmeter.exit.check.pause", 2000); // $NON-NLS-1$

            if (REMAIN_THREAD_PAUSE > 0) {
                Thread daemon = new Thread(){
                    @Override
                    public void run(){
                        try {
                            TimeUnit.MILLISECONDS.sleep(REMAIN_THREAD_PAUSE); // Allow enough time for JVM to exit
                        } catch (InterruptedException ignored) {
                        }
                        // This is a daemon thread, which should only reach here if there are other
                        // non-daemon threads still active
                        System.out.println("The JVM should have exitted but did not.");
                        System.out.println("The following non-daemon threads are still running (DestroyJavaVM is OK):");
                        JOrphanUtils.displayThreads(false);
                    }

                };
                daemon.setDaemon(true);
                daemon.start();
            }
        }

    }

    private static void println(String str) {
        System.out.println(str);
    }

    private static final String[][] DEFAULT_ICONS = {
        { "org.apache.jmeter.control.gui.TestPlanGui",               "org/apache/jmeter/images/beaker.gif" },     //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.timers.gui.AbstractTimerGui",           "org/apache/jmeter/images/timer.gif" },      //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.threads.gui.ThreadGroupGui",            "org/apache/jmeter/images/thread.gif" },     //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.visualizers.gui.AbstractListenerGui",   "org/apache/jmeter/images/meter.png" },      //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.config.gui.AbstractConfigGui",          "org/apache/jmeter/images/testtubes.png" },  //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.processor.gui.AbstractPreProcessorGui", "org/apache/jmeter/images/leafnode.gif"},    //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.processor.gui.AbstractPostProcessorGui","org/apache/jmeter/images/leafnodeflip.gif"},//$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.control.gui.AbstractControllerGui",     "org/apache/jmeter/images/knob.gif" },       //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.control.gui.WorkBenchGui",              "org/apache/jmeter/images/clipboard.gif" },  //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.samplers.gui.AbstractSamplerGui",       "org/apache/jmeter/images/pipet.png" },      //$NON-NLS-1$ $NON-NLS-2$
        { "org.apache.jmeter.assertions.gui.AbstractAssertionGui",   "org/apache/jmeter/images/question.gif"}     //$NON-NLS-1$ $NON-NLS-2$
    };

    @Override
    public String[][] getIconMappings() {
        final String defaultIconProp = "org/apache/jmeter/images/icon.properties"; //$NON-NLS-1$
        String iconProp = JMeterUtils.getPropDefault("jmeter.icons", defaultIconProp);//$NON-NLS-1$
        Properties p = JMeterUtils.loadProperties(iconProp);
        if (p == null && !iconProp.equals(defaultIconProp)) {
            log.info(iconProp + " not found - using " + defaultIconProp);
            iconProp = defaultIconProp;
            p = JMeterUtils.loadProperties(iconProp);
        }
        if (p == null) {
            log.info(iconProp + " not found - using inbuilt icon set");
            return DEFAULT_ICONS;
        }
        log.info("Loaded icon properties from " + iconProp);
        String[][] iconlist = new String[p.size()][3];
        Enumeration<?> pe = p.keys();
        int i = 0;
        while (pe.hasMoreElements()) {
            String key = (String) pe.nextElement();
            String icons[] = JOrphanUtils.split(p.getProperty(key), " ");//$NON-NLS-1$
            iconlist[i][0] = key;
            iconlist[i][1] = icons[0];
            if (icons.length > 1) {
                iconlist[i][2] = icons[1];
            }
            i++;
        }
        return iconlist;
    }

    @Override
    public String[][] getResourceBundles() {
        return new String[0][];
    }

    /**
     * Check if JMeter is running in non-GUI mode.
     *
     * @return true if JMeter is running in non-GUI mode.
     */
    public static boolean isNonGUI(){
        return "true".equals(System.getProperty(JMeter.JMETER_NON_GUI)); //$NON-NLS-1$
    }

    private void logProperty(String prop){
        log.info(prop+"="+System.getProperty(prop));//$NON-NLS-1$
    }
    private void logProperty(String prop,String separator){
        log.info(prop+separator+System.getProperty(prop));//$NON-NLS-1$
    }

    private static void startUdpDdaemon(final List<JMeterEngine> engines) {
        int port = JMeterUtils.getPropDefault("jmeterengine.nongui.port", UDP_PORT_DEFAULT); // $NON-NLS-1$
        int maxPort = JMeterUtils.getPropDefault("jmeterengine.nongui.maxport", 4455); // $NON-NLS-1$
        if (port > 1000){
            final DatagramSocket socket = getSocket(port, maxPort);
            if (socket != null) {
                Thread waiter = new Thread("UDP Listener"){
                    @Override
                    public void run() {
                        waitForSignals(engines, socket);
                    }
                };
                waiter.setDaemon(true);
                waiter.start();
            } else {
                System.out.println("Failed to create UDP port");
            }
        }
    }

    private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) {
        byte[] buf = new byte[80];
        System.out.println("Waiting for possible shutdown message on port "+socket.getLocalPort());
        DatagramPacket request = new DatagramPacket(buf, buf.length);
        try {
            while(true) {
                socket.receive(request);
                InetAddress address = request.getAddress();
                // Only accept commands from the local host
                if (address.isLoopbackAddress()){
                    String command = new String(request.getData(), request.getOffset(), request.getLength(),"ASCII");
                    System.out.println("Command: "+command+" received from "+address);
                    log.info("Command: "+command+" received from "+address);
                    if (command.equals("StopTestNow")){
                        for(JMeterEngine engine : engines) {
                            engine.stopTest(true);
                        }
                    } else if (command.equals("Shutdown")) {
                        for(JMeterEngine engine : engines) {
                            engine.stopTest(false);
                        }
                    } else if (command.equals("HeapDump")) {
                        HeapDumper.dumpHeap();
                    } else {
                        System.out.println("Command: "+command+" not recognised ");
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            socket.close();
        }
    }

    private static DatagramSocket getSocket(int udpPort, int udpPortMax) {
        DatagramSocket socket = null;
        int i = udpPort;
        while (i<= udpPortMax) {
            try {
                socket = new DatagramSocket(i);
                break;
            } catch (SocketException e) {
                i++;
            }
        }

        return socket;
    }
}


text:
layout: page
title: Michael Whitney's 37th Birthday
date: 2016-05-24
author: Stephanie Snyder
tags: weekly links, java
status: published
summary: Aenean cursus purus nisi, sit amet venenatis augue luctus.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/10/2018
  endDate: 04/14/2018
  ctyhocn: TUSSSHX
  groupCode: MW3B
published: true
---
Nulla facilisi. Sed mollis ipsum at metus dignissim varius. Quisque ac ex non leo vehicula mollis. Quisque luctus ultrices ante, at rutrum lacus congue sit amet. Phasellus imperdiet eget urna sit amet consequat. Nullam rhoncus ex vitae tortor mollis, vitae pellentesque elit pharetra. Pellentesque eu mattis enim, et hendrerit quam. Etiam vel justo nunc. Morbi et mi velit. Donec nunc nibh, finibus a luctus et, maximus quis nisi. Donec maximus consectetur ligula a imperdiet. Donec ac convallis justo. Etiam posuere a mi et facilisis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in congue sem. Cras scelerisque, ligula eget consectetur consequat, ex justo commodo diam, sit amet gravida neque tellus nec dolor.
Nulla non consequat dolor, ut faucibus augue. Nam luctus lectus id justo interdum, ac eleifend mauris tincidunt. Suspendisse non elementum felis. Suspendisse faucibus laoreet neque a molestie. Maecenas eleifend felis ac dolor tincidunt, nec sagittis augue bibendum. Quisque laoreet iaculis hendrerit. Ut justo orci, faucibus rhoncus vulputate in, accumsan eu nibh. Praesent vitae fermentum nisi. Nullam ac nibh malesuada, commodo lectus et, ornare nisi.

1 Sed sodales ipsum at tortor pretium fermentum
1 Nulla pretium sem nec erat vulputate, eu egestas velit ornare
1 Duis elementum eros et mauris pretium dignissim
1 Donec scelerisque nibh sit amet sem sagittis ultrices
1 Cras vestibulum nibh vel mattis auctor
1 In vitae turpis a augue fermentum convallis.

Integer lacinia porttitor quam ac aliquam. Nullam justo enim, aliquet vitae nunc et, imperdiet sollicitudin erat. Aliquam eget scelerisque orci. Integer pellentesque a erat pretium feugiat. Nulla auctor sagittis lacinia. Vivamus a leo sollicitudin, aliquet est quis, mollis lorem. Donec sagittis nisl eu gravida vestibulum. Phasellus sed finibus nibh, in ullamcorper nisl. Vivamus sed ipsum sit amet enim luctus posuere. Sed tellus turpis, tincidunt non ex sit amet, lobortis blandit est. Nunc consectetur dui eros, ac iaculis nisi euismod eu. Curabitur luctus tincidunt lacinia. Morbi malesuada lorem ac gravida ornare. Fusce tincidunt quam et neque dignissim, nec eleifend libero consectetur. Integer suscipit elit quis dapibus viverra.


text:
require 'spree_core'
require 'spree_product_facts/engine'


text:
import unittest
from ovs import bridge, docker
from ovs.utils import execute

class DockerTest(unittest.TestCase):

    def setUp(self):
        self.d = docker.Docker()
        self.b = bridge.Bridge()

    def test_docker_network(self):
        container_name = 'c1'
        br_name, br_ip = 'test-br', '192.168.150.1/24'
        c_ip, c_mask = '192.168.150.3', '24'

        c_pid, error = execute.exec_cmd('docker inspect --format={{.State.Pid}} ' + container_name)
        if c_pid.strip() and not error:
            self.__delete_container(container_name)

        execute.exec_cmd('docker run -d --name {0} --net=none interhui/alpine-ssh /usr/sbin/sshd -D'.format(container_name))

        self.d.add_network(br_name, br_ip)

        self.d.connect(container_name, br_name, '{0}/{1}'.format(c_ip, c_mask))
        result, _ = execute.exec_cmd('ping {0} -c 1 -q | grep packets'.format(c_ip))
        self.assertTrue('0% packet loss' in result.strip())

        self.d.disconnect(container_name, br_name)
        self.d.del_network(br_name)

        self.__delete_container(container_name)

    def __delete_container(self, container_name):
        execute.exec_cmd('docker stop ' + container_name)
        execute.exec_cmd('docker rm ' + container_name)

if __name__ =='__main__':
    unittest.main()


text:
<?php
/**
 * @file
 * Contains \Drupal\toornament\Plugin\Field\FieldWidget\ToornamentDefaultWidget.
 */

namespace Drupal\toornament\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'toornament_default' widget.
 *
 * @FieldWidget(
 *   id = "toornament_default",
 *   label = "Toornament widget",
 *   field_types = {
 *     "toornament"
 *   }
 * )
 */
class ToornamentDefaultWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + array(
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
      '#size' => $this->getSetting('size'),
      '#maxlength' => 24,
      '#attributes' => array('class' => array('text-full')),
    );

    return $element;
  }
}


text:
import __future__
import sys
import json

def banner():
    ban = '====' * 30
    print("{}\nSAMPLE INP:\n{}\n{}".format(ban,ban,open(ip, 'r').read()))
    print("{}\nSAMPLE OUT:\n{}\n{}".format(ban,ban,open(op, 'r').read()))
    print("{}\nSTART:\n{}".format(ban,ban))
    sys.stdin = open(ip, 'r')

cnt = -1
def comp(inp,ln):
    outl = output_arr[ln]
    if str(inp) != outl:
        raise Exception("Error input output: line {}, file: {}\ngot: {} expected: {}".format(ln,op,inp,outl))

ip = "./challenge_sample_input"
op = "./challenge_sample_output"

ip = "./input01.txt"
op = "./output01.txt"
output_arr = map(str,open(op,'r').read().split('\n'))
banner()
# https://www.hackerrank.com/challenges/defaultdict-tutorial/problem

import sys
from collections import defaultdict
n,m = map(int,raw_input().split(' '))
A = [raw_input() for _ in range(n)]
B = [raw_input() for _ in range(m)]

track = defaultdict(list)
for idx,v in enumerate(A):
    track[v].append(idx + 1)
for i in B:
    if i not in A:
        print(-1)
    else:
        print(" ".join(map(str,track[i])))


text:
cask 'cookie' do
  version '6.0.16'
  sha256 '3b34f6839297ab50f3e3f13a94da71f2eb0a8ad3f4c76d4768e17a576dfea91e'

  url 'https://sweetpproductions.com/products/cookieapp/Cookie.dmg'
  appcast 'https://sweetpproductions.com/products/cookieapp/appcast.xml'
  name 'Cookie'
  homepage 'https://sweetpproductions.com/'

  depends_on macos: '>= :mojave'

  app 'Cookie.app'

  zap trash: [
               '~/Library/Application Scripts/com.sweetpproductions.Cookie5',
               '~/Library/Containers/com.sweetpproductions.Cookie5',
               '~/Library/Preferences/com.sweetpproductions.Cookie5.plist',
               '~/Library/Application Scripts/com.sweetpproductions.CookieApp',
               '~/Library/Containers/com.sweetpproductions.CookieApp',
               '~/Library/Preferences/com.sweetpproductions.CookieApp.plist',
             ]
end


text:
<jboss-deployment-structure>
    <deployment>
        <dependencies>
            <module name="org.jboss.resteasy.resteasy-jackson-provider" services="import"/>
            <module name="org.codehaus.jackson.jackson-core-asl"/>
            <module name="org.codehaus.jackson.jackson-mapper-asl"/>
            <module name="org.infinispan"/>
        </dependencies>
        <exclusions>
            <module name="org.jboss.resteasy.resteasy-jackson2-provider"/>

            <!-- Exclude keycloak modules -->
            <module name="org.keycloak.keycloak-core" />
            <module name="org.keycloak.keycloak-adapter-core" />
            <module name="org.keycloak.keycloak-undertow-adapter" />
        </exclusions>
        <exclude-subsystems>
            <subsystem name="webservices"/>
        </exclude-subsystems>

    </deployment>
</jboss-deployment-structure>


text:
package cn.org.bachelor.architecture.ms.console.service;

import com.jcraft.jsch.Session;
import org.apache.commons.lang3.StringUtils;
import cn.org.bachelor.architecture.ms.console.utils.GitUtil;
import cn.org.bachelor.architecture.ms.console.vo.CommitLogVO;
import cn.org.bachelor.architecture.ms.console.vo.ConfigFileVO;
import cn.org.bachelor.core.exception.SystemException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @Author Alexhendar
 * @Modified By:
 */
@Service
@Configuration
public class ConfigRepositoryService {
  private static final Logger logger = LoggerFactory.getLogger(GitUtil.class);

 /* private String lineSeparator = "\n";

  private String webPageNewLine = "
";*/

  @Value("${config.git.filePath}")
  private String filePath;
  @Value("${config.git.repository}")
  private String repository;

  public static void main(String[] args) {
    ConfigRepositoryService configService = new ConfigRepositoryService();

    configService.listCurrentRepository();
  }

  public List<ConfigFileVO> listCurrentRepository(){
    File configRepository = new File(filePath);

    try(Git git = Git.open(configRepository)){
      GitUtil.pull(git);
    }catch(IOException ioe){
      logger.warn("git.pull.error",ioe);
    }

    if (!configRepository.exists()){
      // 配置文件目录不存在,返回异常
      throw new SystemException("config.repository.notexists");
    }

    File[] files = listFiles(configRepository);
    List<ConfigFileVO> configFileList = new ArrayList<>();
    for(File file:files){
      ConfigFileVO vo = new ConfigFileVO();
      vo.setFileName(file.getName());
      vo.setPhase(getPhase(file.getName()));
      configFileList.add(vo);
    }
    return configFileList;
  }

  public String getPhase(String fileName){
    if(fileName.contains("-")){
      return fileName.substring(fileName.lastIndexOf("-")+1,fileName.lastIndexOf("."));
    }
    return fileName.substring(0,fileName.lastIndexOf("."));
  }

  public List<ConfigFileVO> searchByNameAndPhase(String fileName,String phase){
    List<File> fileList = Arrays.asList(searchByNameAndPhase(new File(filePath),fileName,phase));
    return fileList.stream().map(file -> {
      ConfigFileVO vo = new ConfigFileVO();
      vo.setFileName(file.getName());
      vo.setPhase(getPhase(file.getName()));
      return vo;
    }).collect(Collectors.toList());
  }

  public List<CommitLogVO> logByFileName(String fileName){
    List<CommitLogVO> commitLogVOList = new ArrayList<>();
    try(Git git = Git.open(new File(filePath))){
      Iterable<RevCommit> commits = GitUtil.log(git,fileName);
      for(RevCommit commit:commits){
        CommitLogVO commitLog = new CommitLogVO();
        commitLog.setCommitId(commit.getId().getName());
        commitLog.setAuthor(commit.getAuthorIdent().getName());
        commitLog.setCommitTime(commit.getCommitterIdent().getWhen());
        commitLog.setMessage(commit.getFullMessage());

        commitLogVOList.add(commitLog);
      }
      return  commitLogVOList;
    }catch (IOException |GitAPIException gae){
      logger.error("浏览文件提交历史异常!");
    }
    throw new SystemException("git.file.not.load");
  }

  /**
   *
 diffWithCurrent : 比较当前内容与指定提交的文件内容

   * @Auther: Alexhendar
   * @param
   * @return
   */
  public List<String> diffWithCurrent(String commitId,String fileName){
    List<String> contentList = new ArrayList<>();
    try(Git git = Git.open(new File(filePath))){
      ObjectId lastCommitId = git.getRepository().resolve(Constants.HEAD);

      String currentContent = GitUtil.fileContentByCommit(git,lastCommitId,fileName);
//      contentList.add(currentContent.replaceAll(lineSeparator,webPageNewLine));
      contentList.add(currentContent);

      String originalContent = GitUtil.fileContentByCommit(git,ObjectId.fromString(commitId),fileName);
      contentList.add(originalContent);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return contentList;
  }

  /**
   *
contentInCommit : 查看指定提交中文件内容

   * @Auther: Alexhendar
   * @param
   * @return
   */
  public String contentInCommit(String commitId,String fileName){
    try(Git git = Git.open(new File(filePath))){
      ObjectId lastCommitId = git.getRepository().resolve(Constants.HEAD);

      String currentContent = GitUtil.fileContentByCommit(git,lastCommitId,fileName);
      return currentContent;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return StringUtils.EMPTY;
  }

  /**
   *
 pushCurrentRepository: 推送当前配置到仓库

   * @Auther: Alexhendar
   * @param
   * @return
   */
  public void pushCurrentRepository(){
    try(Git git = Git.open(new File(filePath))){
//      git.commit().call();
      // 这里直接推送,commit操作由内容修改操作执行
      GitUtil.push(git);
    } catch (GitAPIException | IOException e) {
      e.printStackTrace();
      throw new SystemException("config.git.push.error",e);
    }
  }

  public File[] listFiles(File dir){
    return dir.listFiles(accessFile->!accessFile.isHidden()&&accessFile.isFile());
  }

  private File[] searchByNameAndPhase(File dir, String fileName, String phase){
    return dir.listFiles(accessFile->!accessFile.isHidden()&&accessFile.isFile()
            &&(accessFile.getName().contains(fileName)&&accessFile.getName().contains(phase)));
  }

  @PostConstruct
  public void initClone(){
    File localRepository = new File(filePath);
    if(!localRepository.exists()){
      // 目录不存在则创建
      logger.info("repository not exists,create it!,{}",filePath);
      localRepository.mkdirs();
    }

    try{
      Git.open(localRepository);
    } catch (IOException e) {
      // 首次启动,本地不存在仓库,执行clone操作
      logger.info("clone repository from : {} to {}",repository,filePath);
      SshSessionFactory.setInstance(new JschConfigSessionFactory() {
        public void configure(OpenSshConfig.Host hc, Session session) {
          session.setConfig("StrictHostKeyChecking", "no");
        }
      });

      GitUtil.cloneRepository(repository,filePath);
    }
  }
}


text:
package pkg1;

public @interface Marker {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>Coventry, Coventry, West Midlands, UK</formatted_address>
  <address_component>
   <long_name>Coventry</long_name>
   <short_name>Coventry</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Coventry</long_name>
   <short_name>Coventry</short_name>
   <type>postal_town</type>
  </address_component>
  <address_component>
   <long_name>Coventry</long_name>
   <short_name>Coventry</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>West Midlands</long_name>
   <short_name>West Midlands</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>England</long_name>
   <short_name>England</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>United Kingdom</long_name>
   <short_name>GB</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>52.4068220</lat>
    <lng>-1.5196930</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>52.3639107</lat>
     <lng>-1.6058852</lng>
    </southwest>
    <northeast>
     <lat>52.4634723</lat>
     <lng>-1.4239508</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>52.3639107</lat>
     <lng>-1.6058852</lng>
    </southwest>
    <northeast>
     <lat>52.4634723</lat>
     <lng>-1.4239508</lng>
    </northeast>
   </bounds>
  </geometry>
  <partial_match>true</partial_match>
  <place_id>ChIJtyJuZVGxcEgRiQZPVvVg9gQ</place_id>
 </result>
</GeocodeResponse>


text:
Bridge.merge(new System.Globalization.CultureInfo("sn-Latn", true), {
    englishName: "Shona (Latin)",
    nativeName: "chiShona (Latin)",

    numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), {
        nanSymbol: "NaN",
        negativeSign: "-",
        positiveSign: "+",
        negativeInfinitySymbol: "-∞",
        positiveInfinitySymbol: "∞",
        percentSymbol: "%",
        percentGroupSizes: [3],
        percentDecimalDigits: 2,
        percentDecimalSeparator: ".",
        percentGroupSeparator: ",",
        percentPositivePattern: 1,
        percentNegativePattern: 1,
        currencySymbol: "$",
        currencyGroupSizes: [3],
        currencyDecimalDigits: 2,
        currencyDecimalSeparator: ".",
        currencyGroupSeparator: ",",
        currencyNegativePattern: 1,
        currencyPositivePattern: 0,
        numberGroupSizes: [3],
        numberDecimalDigits: 2,
        numberDecimalSeparator: ".",
        numberGroupSeparator: ",",
        numberNegativePattern: 1
    }),

    dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), {
        abbreviatedDayNames: ["Svo","Muv","Chp","Cht","Chn","Chs","Mug"],
        abbreviatedMonthGenitiveNames: ["Ndi","Kuk","Kur","Kub","Chv","Chk","Chg","Nya","Gun","Gum","Mbu","Zvi",""],
        abbreviatedMonthNames: ["Ndi","Kuk","Kur","Kub","Chv","Chk","Chg","Nya","Gun","Gum","Mbu","Zvi",""],
        amDesignator: "AM",
        dateSeparator: "-",
        dayNames: ["Svondo","Muvhuro","Chipiri","Chitatu","China","Chishanu","Mugovera"],
        firstDayOfWeek: 0,
        fullDateTimePattern: "yyyy MMMM d, dddd HH:mm:ss",
        longDatePattern: "yyyy MMMM d, dddd",
        longTimePattern: "HH:mm:ss",
        monthDayPattern: "MMMM d",
        monthGenitiveNames: ["Ndira","Kukadzi","Kurume","Kubvumbi","Chivabvu","Chikumi","Chikunguru","Nyamavhuvhu","Gunyana","Gumiguru","Mbudzi","Zvita",""],
        monthNames: ["Ndira","Kukadzi","Kurume","Kubvumbi","Chivabvu","Chikumi","Chikunguru","Nyamavhuvhu","Gunyana","Gumiguru","Mbudzi","Zvita",""],
        pmDesignator: "PM",
        rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
        shortDatePattern: "yyyy-MM-dd",
        shortestDayNames: ["Sv","Mu","Cp","Ct","Cn","Cs","Mg"],
        shortTimePattern: "HH:mm",
        sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
        sortableDateTimePattern1: "yyyy'-'MM'-'dd",
        timeSeparator: ":",
        universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
        yearMonthPattern: "yyyy MMMM",
        roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz"
    }),

    TextInfo: Bridge.merge(new System.Globalization.TextInfo(), {
        ANSICodePage: 0,
        CultureName: "sn-Latn-ZW",
        EBCDICCodePage: 500,
        IsRightToLeft: false,
        LCID: 4096,
        listSeparator: ";",
        MacCodePage: 2,
        OEMCodePage: 1,
        IsReadOnly: true
    })
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
	Copyright 2005-2009 The Kuali Foundation

	Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php

	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.
-->
<batch xmlns="http://www.kuali.org/kfs/gl/collector"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.kuali.org/kfs/gl/collector @externalizable.static.content.url@/xsd/gl/collector.xsd" >
	<header>
		<chartOfAccountsCode>IN</chartOfAccountsCode>
		<organizationCode>MDEP</organizationCode>
		<transmissionDate>2005-10-06</transmissionDate>
		<batchSequenceNumber>0</batchSequenceNumber>
		<personUserId>kul</personUserId>
		<emailAddress>knoreceipt-l@indiana.edu</emailAddress>
		<campusCode>BL</campusCode>
		<phoneNumber>123-456-7890</phoneNumber>
		<mailingAddress>1500 Berkeley</mailingAddress>
		<departmentName>Kuali Developers</departmentName>
	</header>
	<glEntry>
		<universityFiscalYear>2006</universityFiscalYear>
		<chartOfAccountsCode>bl</chartOfAccountsCode>
		<accountNumber>1031400</accountNumber>
		<subAccountNumber>adv</subAccountNumber>
		<objectCode>3000</objectCode>
		<subObjectCode>wac</subObjectCode>
		<balanceTypeCode>ac</balanceTypeCode>
		<objectTypeCode>ex</objectTypeCode>
		<universityFiscalAccountingPeriod>04</universityFiscalAccountingPeriod>
		<documentTypeCode>ex02</documentTypeCode>
		<originationCode>01</originationCode>
		<documentNumber>1000000</documentNumber>
		<transactionEntrySequenceId>1</transactionEntrySequenceId>
		<transactionLedgerEntryDescription>Description</transactionLedgerEntryDescription>
		<transactionLedgerEntryAmount>300.00</transactionLedgerEntryAmount>
		<debitOrCreditCode>C</debitOrCreditCode>
		<transactionDate>2005-10-05</transactionDate>
		<organizationDocumentNumber>ODN</organizationDocumentNumber>
		<projectCode>bat</projectCode>
		<organizationReferenceId>ORI</organizationReferenceId>
		<referenceDocumentTypeCode>ex02</referenceDocumentTypeCode>
		<referenceOriginationCode>01</referenceOriginationCode>
		<referenceDocumentNumber>1234</referenceDocumentNumber>
		<documentReversalDate>2005-10-31</documentReversalDate>
		<encumbranceUpdateCode>D</encumbranceUpdateCode>
	</glEntry>
	<detail>
		<universityFiscalAccountingPeriod>06</universityFiscalAccountingPeriod>
		<universityFiscalYear>2006</universityFiscalYear>
		<chartOfAccountsCode>BL</chartOfAccountsCode>
		<accountNumber>1031400</accountNumber>
		<subAccountNumber>adv</subAccountNumber>
		<objectCode>3000</objectCode>
		<subObjectCode>WAC</subObjectCode>
		<collectorDetailSequenceNumber>47</collectorDetailSequenceNumber>
		<originationCode>01</originationCode>
		<documentTypeCode>ex02</documentTypeCode>
		<documentNumber>1000000</documentNumber>
		<amount>1000000</amount>
		<detailText>Line 1b</detailText>
		<createDate>2007-08-01</createDate>
		<balanceTypeCode>AC</balanceTypeCode>
	</detail>
	<trailer>
		<totalRecords>2</totalRecords>
		<totalAmount>300.00</totalAmount>
	</trailer>
</batch>