text:
#ifndef EXTENSIONS_SMJS_SCRIPT_RUNTIME_CONVERTER_H__
#define EXTENSIONS_SMJS_SCRIPT_RUNTIME_CONVERTER_H__

#include <string>
#include <ggadget/common.h>
#include <ggadget/variant.h>
#include "libmozjs_glue.h"

namespace ggadget {
namespace smjs {

class NativeJSWrapper;

/**
 * Converts a @c jsval to a @c Variant of desired type.
 * @param cx JavaScript context.
 * @param owner the related JavaScript object wrapper in which the owner of
 *     the converted value is wrapped.
 * @param prototype providing the desired target type information.
 * @param js_val source @c jsval value.
 * @param[out] native_val result @c Variant value.
 * @return @c JS_TRUE if succeeds.
 */
JSBool ConvertJSToNative(JSContext *cx, NativeJSWrapper *owner,
                         const Variant &prototype,
                         jsval js_val, Variant *native_val);

/**
 * Converts a @c jsval to a @c Variant depending source @c jsval type.
 * @param cx JavaScript context.
 * @param js_val source @c jsval value.
 * @param[out] native_val result @c Variant value.
 * @return @c JS_TRUE if succeeds.
 */
JSBool ConvertJSToNativeVariant(JSContext *cx, jsval js_val,
                                Variant *native_val);

/**
 * Frees a native value that was created by @c ConvertJSToNative(),
 * if some failed conditions preventing this value from successfully
 * passing to the native code.
 */
void FreeNativeValue(const Variant &native_val);

/**
 * Converts a @c jsval to a @c std::string for printing.
 */
std::string PrintJSValue(JSContext *cx, jsval js_val);

/**
 * Converts JavaScript arguments to native for a native slot.
 */
JSBool ConvertJSArgsToNative(JSContext *cx, NativeJSWrapper *owner,
                             const char *name, Slot *slot,
                             uintN argc, jsval *argv,
                             Variant **params, uintN *expected_argc);

/**
 * Converts a @c Variant to a @c jsval.
 * @param cx JavaScript context.
 * @param native_val source @c Variant value.
 * @param[out] js_val result @c jsval value.
 * @return @c JS_TRUE if succeeds.
 */
JSBool ConvertNativeToJS(JSContext* cx,
                         const Variant &native_val,
                         jsval* js_val);

/**
 * Compiles function source into JSFunction *.
 */
JSFunction *CompileFunction(JSContext *cx, const char *script,
                            const char *filename, int lineno);

/**
 * Compile and evaluate a piece of script.
 */
JSBool EvaluateScript(JSContext *cx, JSObject *object, const char *script,
                      const char *filename, int lineno, jsval *rval);

/**
 * Checks if there is pending exception. If there is, convert it into jsval
 * and throws it into the script engine.
 */
JSBool CheckException(JSContext *cx, ScriptableInterface *scriptable);

/**
 * Report an exception into the script engine.
 */
JSBool RaiseException(JSContext *cx, const char *format, ...)
    PRINTF_ATTRIBUTE(2, 3);

} // namespace smjs
} // namespace ggadget

#endif  // EXTENSIONS_SMJS_SCRIPT_RUNTIME_CONVERTER_H__


text:
<!--
********************************************************************************
	Project owner:		GTWGames
	Project name:		GTW-RPG
	Developers:			GTWCode

	Source code:		https://github.com/404rq/GTW-RPG/
	Bugtracker:			http://forum.albonius.com/bug-reports/
	Suggestions:		http://forum.albonius.com/mta-servers-development/

	Version:			Open source
	License:			GPL v.3 or later
	Status:				Stable release
********************************************************************************
-->

<meta>
    <info type="script" name="GTWcoremap" author="GTWCode" version="108" description="Core map for Grand Theft Walrus"></info>
    <script src="core_map.lua" type="client"></script>
</meta>

redpajama_set_name: RedPajamaGithub


text:
<readable><title>391020801_aaaae1e42b</title><content>
A man gesticulates .
A man in a white shirt holding both hands out .
An elderly male wearing a white Wal Mart smock with his arms and hand extended in front of him .
A old man in a Wall Mart unifrom holds his arms out to the camera .
a walmart worker wearing a white coat .
</content></readable>


text:
package com.networknt.email;

import com.networknt.common.SecretConstants;
import com.networknt.config.Config;
import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Email sender that support both text and attachment.
 *
 * @author Steve Hu
 */
public class EmailSender {
    private static final Logger logger = LoggerFactory.getLogger(EmailSender.class);
    public static final String CONFIG_EMAIL = "email";
    public static final String CONFIG_SECRET = "secret";

    static final EmailConfig emailConfg = (EmailConfig)Config.getInstance().getJsonObjectConfig(CONFIG_EMAIL, EmailConfig.class);

    public EmailSender() {
    }

    /**
     * Send email with a string content.
     *
     * @param to destination email address
     * @param subject email subject
     * @param content email content
     * @throws MessagingException message exception
     */
    public void sendMail (String to, String subject, String content) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.user", emailConfg.getUser());
        props.put("mail.smtp.host", emailConfg.getHost());
        props.put("mail.smtp.port", emailConfg.getPort());
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.debug", emailConfg.getDebug());
        props.put("mail.smtp.auth", emailConfg.getAuth());
        props.put("mail.smtp.ssl.trust", emailConfg.host);

        String pass = emailConfg.getPass();
        if(pass == null) {
            Map<String, Object> secret = Config.getInstance().getJsonMapConfig(CONFIG_SECRET);
            pass = (String)secret.get(SecretConstants.EMAIL_PASSWORD);
        }

        SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), pass);
        Session session = Session.getInstance(props, auth);

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(emailConfg.getUser()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject(subject);

        message.setContent(content, "text/html");

        // Send message
        Transport.send(message);
        if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject);
    }

    /**
     * Send email with a string content and attachment
     *
     * @param to destination eamil address
     * @param subject email subject
     * @param content email content
     * @param filename attachment filename
     * @throws MessagingException messaging exception
     */
    public void sendMailWithAttachment (String to, String subject, String content, String filename) throws MessagingException{
        Properties props = new Properties();
        props.put("mail.smtp.user", emailConfg.getUser());
        props.put("mail.smtp.host", emailConfg.getHost());
        props.put("mail.smtp.port", emailConfg.getPort());
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.debug", emailConfg.getDebug());
        props.put("mail.smtp.auth", emailConfg.getAuth());
        props.put("mail.smtp.ssl.trust", emailConfg.host);

        String pass = emailConfg.getPass();
        if(pass == null) {
            Map<String, Object> secret = Config.getInstance().getJsonMapConfig(CONFIG_SECRET);
            pass = (String)secret.get(SecretConstants.EMAIL_PASSWORD);
        }

        SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), pass);
        Session session = Session.getInstance(props, auth);

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(emailConfg.getUser()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject);
    }

    private static class SMTPAuthenticator extends Authenticator {
        public  String user;
        public  String password;

        public SMTPAuthenticator(String user, String password) {
            this.user = user;
            this.password = password ;
        }

        @Override
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(this.user, this.password);
        }
    }

    /**
     * This is the template variable replacement utility to replace [name] with a key
     * name in the map with the value in the template to generate the final email body.
     *
     * @param text The template in html format
     * @param replacements A map that contains key/value pair for variables
     * @return String of processed template
     */
    public static String replaceTokens(String text,
                                       Map<String, String> replacements) {
        Pattern pattern = Pattern.compile("\\[(.+?)\\]");
        Matcher matcher = pattern.matcher(text);
        StringBuffer buffer = new StringBuffer();

        while (matcher.find()) {
            String replacement = replacements.get(matcher.group(1));
            if (replacement != null) {
                matcher.appendReplacement(buffer, "");
                buffer.append(replacement);
            }
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }
}


text:
<?php

namespace humhub\libs;

use Yii;
use yii\web\UploadedFile;
use yii\helpers\Url;
use humhub\modules\file\libs\ImageConverter;

/**
 * LogoImage
 */
class LogoImage
{

    /**
     * @var Integer height of the image
     */
    protected $height = 40;

    /**
     * @var String folder name inside the uploads directory
     */
    protected $folder_images = "logo_image";

    /**
     * Returns the URl of Logo Image
     *
     * @return String Url of the profile image
     */
    public function getUrl()
    {
        $cacheId = 0;
        $path = "";

        // Workaround for absolute urls in console applications (Cron)
        if (Yii::$app->request->isConsoleRequest) {
            $path = Url::base(true);
        } else {
            $path = Url::base();
        }

        if (file_exists($this->getPath())) {
            $path .= '/uploads/' . $this->folder_images . '/logo.png';
        }
        $path .= '?cacheId=' . $cacheId;
        return $path;
    }

    /**
     * Indicates there is a logo image
     *
     * @return Boolean is there a logo image
     */
    public function hasImage()
    {
        return file_exists($this->getPath());
    }

    /**
     * Returns the Path of the logo image
     *
     * @return String Path to the logo image
     */
    public function getPath()
    {
        $path = \Yii::getAlias("@webroot") . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $this->folder_images . DIRECTORY_SEPARATOR;

        if (!is_dir($path))
            mkdir($path);

        $path .= 'logo.png';

        return $path;
    }

    /**
     * Sets a new logo image by given temp file
     *
     * @param CUploadedFile $file
     */
    public function setNew(UploadedFile $file)
    {
        $this->delete();
        move_uploaded_file($file->tempName, $this->getPath());

        ImageConverter::Resize($this->getPath(), $this->getPath(), array('height' => $this->height, 'width' => 0, 'mode' => 'max', 'transparent' => ($file->getExtension() == 'png' && ImageConverter::checkTransparent($this->getPath()))));
    }

    /**
     * Deletes current logo
     */
    public function delete()
    {
        @unlink($this->getPath());
    }

}

?>


text:
var tape = require('tape');
var tests = require('./test');

for(var key in tests) {
    if(key !== 'complexity') tape(key, tests[key]);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <base href="/">
    <title><%= app_names.classed %></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

  <body ng-app="<%= app_names.slug %>">

    <ui-view></ui-view>


text:
package flatbuf

type TimeUnit = int16
const (
	TimeUnitSECOND TimeUnit = 0
	TimeUnitMILLISECOND TimeUnit = 1
	TimeUnitMICROSECOND TimeUnit = 2
	TimeUnitNANOSECOND TimeUnit = 3
)

var EnumNamesTimeUnit = map[TimeUnit]string{
	TimeUnitSECOND:"SECOND",
	TimeUnitMILLISECOND:"MILLISECOND",
	TimeUnitMICROSECOND:"MICROSECOND",
	TimeUnitNANOSECOND:"NANOSECOND",
}


text:
<?php

/**
 * Get database types.
 *
 * @param string $testConfigDir
 * @return array
 */
function getSqlDbTypes($testConfigDir)
{
    // setup testing for whichever db config testing files exist
    $d = dir($testConfigDir);
    $dbTypes = array();
    while (false !== ($entry = $d->read())) {
        if ($entry === 'mysql.ini') {
            $dbTypes[] = 'mysql';
        } elseif ($entry === 'pgsql.ini') {
            $dbTypes[] = 'pgsql';
        } elseif ($entry === 'sqlite.ini') {
            $dbTypes[] = 'sqlite';
        }
    }
    $d->close();

    return $dbTypes;
}

/**
 * Load database adapter.
 *
 * @param string $testConfigDir
 * @param string $dbType
 * @return Zend_Db_Adapter_Abstract
 * @throws Zend_Exception
 */
function loadDbAdapter($testConfigDir, $dbType)
{
    // create the lockfile for this dbType
    $dbConfigFile = $testConfigDir.'/'.$dbType.'.ini';
    $lockFile = $testConfigDir.'/lock.'.$dbType.'.ini';
    copy($dbConfigFile, $lockFile);

    // load the lockfile as the test dbConfig
    if (file_exists($lockFile)) {
        $configDatabase = new Zend_Config_Ini($lockFile, 'testing');
    } else {
        throw new Zend_Exception('Error, cannot load lockfile: '.$lockFile);
    }

    if (empty($configDatabase->database->params->driver_options)) {
        $driverOptions = array();
    } else {
        $driverOptions = $configDatabase->database->params->driver_options->toArray();
    }
    $params = array(
        'dbname' => $configDatabase->database->params->dbname,
        'driver_options' => $driverOptions,
    );
    if ($dbType != 'sqlite') {
        $params['username'] = $configDatabase->database->params->username;
        $params['password'] = $configDatabase->database->params->password;
        if (empty($configDatabase->database->params->unix_socket)) {
            $params['host'] = $configDatabase->database->params->host;
            $params['port'] = $configDatabase->database->params->port;
        } else {
            $params['unix_socket'] = $configDatabase->database->params->unix_socket;
        }
    }
    $db = Zend_Db::factory($configDatabase->database->adapter, $params);
    Zend_Db_Table::setDefaultAdapter($db);
    Zend_Registry::set('dbAdapter', $db);
    Zend_Registry::set('configDatabase', $configDatabase);

    return $db;
}

/**
 * Drop database tables.
 *
 * @param Zend_Db_Adapter_Abstract $db
 * @param string $dbType
 * @throws Zend_Exception
 */
function dropTables($db, $dbType)
{
    $db->beginTransaction();
    try {
        $tables = $db->listTables();
        foreach ($tables as $table) {
            if ($dbType === 'mysql') {
                $db->query('DROP TABLE IF EXISTS `'.$table.'` CASCADE;');
            } elseif ($dbType === 'pgsql') {
                $db->query('DROP TABLE IF EXISTS "'.$table.'" CASCADE;');
            } elseif ($dbType === 'sqlite' && $table != 'sqlite_sequence') {
                $db->query('DROP TABLE IF EXISTS "'.$table.'";');
            } else {
                continue;
            }
        }
        $db->commit();
    } catch (Zend_Exception $exception) {
        $db->rollBack();
        throw $exception;
    }
}

/**
 * Install and upgrade core.
 *
 * @param Zend_Db_Adapter_Abstract $db
 * @param string $dbType
 * @param UtilityComponent $utilityComponent
 * @throws Zend_Exception
 */
function installCore($db, $dbType, $utilityComponent)
{
    if ($dbType !== 'mysql' && $dbType !== 'pgsql' && $dbType !== 'sqlite') {
        throw new Zend_Exception('Unknown database type: '.$dbType);
    }

    require_once BASE_PATH.'/core/controllers/components/UpgradeComponent.php';
    $upgradeComponent = new UpgradeComponent();
    $upgradeComponent->dir = BASE_PATH.'/core/database/'.$dbType;
    $upgradeComponent->init = true;

    $newestVersion = $upgradeComponent->getNewestVersion(true);
    $sqlFile = BASE_PATH.'/core/database/'.$dbType.'/'.$newestVersion.'.sql';

    if (!file_exists($sqlFile)) {
        throw new Zend_Exception('Unable to find SQL file: '.$sqlFile);
    }

    $utilityComponent->run_sql_from_file($db, $sqlFile);

    Zend_Registry::set('models', array());

    $configCore = new Zend_Config_Ini(BASE_PATH.'/core/configs/core.ini', 'global');
    Zend_Registry::set('configCore', $configCore);

    /** @var ModuleModel $moduleModel */
    $moduleModel = MidasLoader::loadModel('Module');
    /** @var ModuleDao $moduleDao */
    $moduleDao = MidasLoader::newDao('ModuleDao');
    $moduleDao->setName('core');
    $moduleDao->setUuid(str_replace('-', '', $configCore->get('uuid')));
    $moduleDao->setCurrentVersion($newestVersion);
    $moduleDao->setEnabled(1);
    $moduleModel->save($moduleDao);

    $upgradeComponent->initUpgrade('core', $db, 'PDO_'.strtoupper($dbType));
    $upgradeComponent->upgrade($newestVersion, true /* true for testing */);
}

/** Create default asset store. */
function createDefaultAssetstore()
{
    Zend_Registry::set('models', array());

    /** @var AssetstoreModel $assetStoreModel */
    $assetStoreModel = MidasLoader::loadModel('Assetstore');

    // path munging
    require_once BASE_PATH.'/core/controllers/components/UtilityComponent.php';
    $testAssetstoreBase = UtilityComponent::getTempDirectory().'/test/';
    $testAssetstoreBase = str_replace('tests/../', '', $testAssetstoreBase);
    $testAssetstoreBase = str_replace('//', '/', $testAssetstoreBase);

    // create assetstore directory
    if (!is_dir($testAssetstoreBase)) {
        mkdir($testAssetstoreBase);
    }
    $testAssetstore = $testAssetstoreBase.'/assetstore';
    if (!is_dir($testAssetstore)) {
        mkdir($testAssetstore);
    }

    // create default assetstore in db
    require_once BASE_PATH.'/core/models/dao/AssetstoreDao.php';
    $assetstoreDao = new AssetstoreDao();
    $assetstoreDao->setName('Default');
    $assetstoreDao->setPath($testAssetstore);
    $assetstoreDao->setType(MIDAS_ASSETSTORE_LOCAL);
    $assetStoreModel->save($assetstoreDao);
}

/**
 * Install and upgrade modules.
 *
 * @param UtilityComponent $utilityComponent
 */
function installModules($utilityComponent)
{
    // What to do about module config files, these should be copied into
    // core/configs when a module is installed, but we can't do that
    // as there are already module files there, and we may not want
    // all the module files
    // we could copy the existing ones somewhere, then copy them back at the end
    // but I don't like that idea
    // for now do nothing
    $modules = $utilityComponent->getAllModules();
    foreach ($modules as $moduleName => $module) {
        $utilityComponent->installModule($moduleName);
    }
}

/**
 * Release lock file.
 *
 * @param string $dbType
 */
function releaseLock($dbType)
{
    if (file_exists(BASE_PATH.'/tests/configs/lock.'.$dbType.'.ini')) {
        rename(BASE_PATH.'/tests/configs/lock.'.$dbType.'.ini', BASE_PATH.'/tests/configs/'.$dbType.'.ini');
    }
}

// general setup
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

define('BASE_PATH', realpath(dirname(__FILE__).'/../'));
define('APPLICATION_ENV', 'testing');
define('APPLICATION_PATH', BASE_PATH.'/core');
define('LIBRARY_PATH', BASE_PATH.'/library');
define('TESTS_PATH', BASE_PATH.'/tests');

require_once BASE_PATH.'/vendor/autoload.php';
require_once BASE_PATH.'/core/include.php';

Zend_Session::$_unitTestEnabled = true;
Zend_Session::start();

$logger = Zend_Log::factory(
    array(
        array(
            'writerName' => 'Stream',
            'writerParams' => array('stream' => LOGS_PATH.'/testing.log'),
            'filterName' => 'Priority',
            'filterParams' => array('priority' => Zend_Log::DEBUG),
        ),
    )
);

Zend_Registry::set('logger', $logger);

// get the config properties
$configGlobal = new Zend_Config_Ini(APPLICATION_CONFIG, 'global', true);
$configGlobal->environment = 'testing';
Zend_Registry::set('configGlobal', $configGlobal);

$config = new Zend_Config_Ini(APPLICATION_CONFIG, 'testing');
Zend_Registry::set('config', $config);

// get database type
// for now only supporting MySQL, PostgreSQL, and SQLite
// get the database type from the existing config files
$testConfigDir = BASE_PATH.'/tests/configs/';
$dbTypes = getSqlDbTypes($testConfigDir);

foreach ($dbTypes as $dbType) {
    try {
        echo 'Dropping and installing tables for database type: '.$dbType.PHP_EOL;
        $dbAdapter = loadDbAdapter($testConfigDir, $dbType);
        dropTables($dbAdapter, $dbType);
        require_once BASE_PATH.'/core/controllers/components/UtilityComponent.php';
        $utilityComponent = new UtilityComponent();

        installCore($dbAdapter, $dbType, $utilityComponent);
        createDefaultAssetstore();
        installModules($utilityComponent);

        releaseLock($dbType);
    } catch (Zend_Exception $ze) {
        echo $ze->getMessage();
        exit(1);
    }
}

exit(0);


text:
using System;
using System.Collections.Generic;

namespace MsgPack.Serialization
{
	public sealed class MillisecondsDateTimeComparer : IEqualityComparer<DateTime>
	{
		public static readonly MillisecondsDateTimeComparer Instance = new MillisecondsDateTimeComparer();

		private MillisecondsDateTimeComparer() { }

		public bool Equals( DateTime x, DateTime y )
		{
			var xms = new DateTime( x.Year, x.Month, x.Day, x.Hour, x.Minute, x.Second, x.Millisecond, x.Kind );
			var yms = new DateTime( y.Year, y.Month, y.Day, y.Hour, y.Minute, y.Second, y.Millisecond, y.Kind );
			return xms.Equals( yms );
		}

		public int GetHashCode( DateTime obj )
		{
			return new DateTime( obj.Year, obj.Month, obj.Day, obj.Hour, obj.Minute, obj.Second, obj.Millisecond, obj.Kind ).GetHashCode();
		}
	}
}


text:
module Slack
  ( SlackMessage(..)
  , SlackAttachment(..)
  , SlackField(..)
  ) where

import Data.Aeson (toJSON)
import Data.Aeson.TH (deriveJSON)
import Data.Default (Default(..))
import Data.Text (Text)
import Network.Wreq.Types (Postable(..))

import Rules (slackOptions)

-- | A field in a message attachment.
data SlackField = SlackField
  { fieldTitle :: Text
  , fieldValue :: Text
  , fieldShort :: Bool
  } deriving (Show, Eq)

deriveJSON slackOptions ''SlackField

-- | A Slack message attachment.
data SlackAttachment = SlackAttachment
  { attachmentFallback :: Text
  , attachmentColor :: Maybe Text
  , attachmentPretext :: Maybe Text
  , attachmentAuthorName :: Maybe Text
  , attachmentAuthorLink :: Maybe Text
  , attachmentAuthorIcon :: Maybe Text
  , attachmentTitle :: Text
  , attachmentTitleLink :: Maybe Text
  , attachmentText :: Maybe Text
  , attachmentFields :: [SlackField]
  , attachmentMrkdwnIn :: [Text]
  } deriving (Show, Eq)

deriveJSON slackOptions ''SlackAttachment

instance Default SlackAttachment where
  def = SlackAttachment
        { attachmentFallback = ""
        , attachmentColor = Nothing
        , attachmentPretext = Nothing
        , attachmentAuthorName = Nothing
        , attachmentAuthorLink = Nothing
        , attachmentAuthorIcon = Nothing
        , attachmentTitle = ""
        , attachmentTitleLink = Nothing
        , attachmentText = Nothing
        , attachmentFields = []
        , attachmentMrkdwnIn = []
        }

-- | A Slack message.
data SlackMessage = SlackMessage
  { messageText :: Maybe Text
  , messageUsername :: Maybe Text
  , messageIconEmoji :: Maybe Text
  , messageChannel :: Maybe Text
  , messageAttachments :: [SlackAttachment]
  } deriving (Show, Eq)

deriveJSON slackOptions ''SlackMessage

instance Default SlackMessage where
  def = SlackMessage
        { messageText = Nothing
        , messageUsername = Nothing
        , messageIconEmoji = Nothing
        , messageChannel = Nothing
        , messageAttachments = []
        }

instance Postable SlackMessage where
  postPayload = postPayload . toJSON


text:
https://github.com/vigo/dotfiles-fever is the new rising ☆

---

OS X, Ubuntu and Gentoo Linux competible dot-files / shell environment
collection.

## Requirements
### OSX

You need [Homebrew][brew] and `git`. Install [Homebrew][brew] first and then
install `git` via `brew install git`.

### Ubuntu

`git` required. `sudo aptitude install git` can help you out...

### Gentoo

`git` required :) `emerge dev-vcs/git`

## Installation and Removal

You need to clone the repo:

    git clone https://github.com/vigo/dotfiles-universal.git $HOME/Dotfiles
    bash $HOME/Dotfiles/scripts/install.sh

`nanorc` is optional now. Please check `rc/nanorc.example` for more information.

Dotfiles is shiped with configurable `PS1` feature. PS1 elements are:

    ps1_Horizontal_Line
    ps1_Shell_Name
    ps1_Free_Memory
    ps1_Battery_Status
    ps1_IP_List
    ps1_Username_and_Hostname
    ps1_Database_Status
    ps1_Virtualenv_Status
    ps1_RBENV_Status
    ps1_PYENV_Status
    ps1_GIT_Status
    ps1_Mercurial_Status

There are two pre-defined configurations:

        ps1_PREFS_Full
        ps1_PREFS_Basic

Default value for `PS1` is `ps1_PREFS_Basic`:

```bash
# you'll see this:
export PS1=$ps1_PREFS_Basic
```

You can override this via putting your own config under `Private/` folder as `ps1`:

```bash
# example custom PS1
export PS1=$ps1_PREFS_Full

# or
export PS1="${ps1_Username_and_Hostname}\n$ "

# or
export PS1="$ps1_Username_and_Hostname
$ps1_RBENV_Status$ps1_GIT_Status
> "
```

If you like to uninstall;

    cd $HOME/Dotfiles
    bash scripts/uninstall.sh

### OSX Special

If you like to tweak Yosemite, try:

    bash $HOME/Dotfiles/scripts/tweaks_osx.sh

Need to restart shell / logout - login or `exec $SHELL`.

## Goodies

* Fancy `history`
* Color-full files :)
* `.inputrc` magic!
* OSX specific aliases: `desktop_hide`, `desktop_show`, `shadow_screenshot_disable`,
`shadow_screenshot_enable`, `ios_backup_disable`, `ios_backup_enable`,
`ds_store_clear`, `reload_textmate`
* try `alias` to see additions. `what_is_my_real_ip`, `what_is_my_public_ip`

Put all of your **private** stuff under `Private/` folder! Custom functions,
env, aliases etc...

## Functions and Aliases

### Functions

- `webserver` : SimpleHTTPServer.
- `webserver_rb` : Ruby version of simple http server uses `httpd` of ruby!
- `gz_analyse` : Shows not/gzipped size diffs
- `dataurl` : Creates base64 encoded image!
- `mkdir_cd`: Creates folder and cd'ies in to it!

### Aliases

- `ll`, `la`, `l` : Listing directory, you know the drill!
- `grep`, `fgrep` : Incase sensitive and color enabled.
- `less`, `more` : Enabled raw control characters.
- `rm` : By default : `rm -i`
- `what_is_my_public_ip`, `what_is_my_real_ip` : Use `what_is_my_public_ip` if `dig` installed.
- `restart_bash` : Reload bash environment

## Prompt Shell Features

**OSX**: Free Memory, Battery status, IP List, Database (MySQL + PostgresQL) Status

**BOTH**: Rbenv, Pyenv, Git / Mercurial prompt, Virtualenv

## Screenshots

![Terminal Screen](screenshot.png)

## Change Log

You can browse [change log here](CHANGELOG.md).

## Contributer(s)

* [Uğur "vigo" Özyılmazel][01] - Creator, maintainer

## License

This project is licensed under MIT.

[01]: https://github.com/vigo
[brew]: http://brew.sh


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Smobiler.Core;
using Smobiler.Core.Controls;

namespace SmoONE.UI.Layout
{
    partial class frmAttendanceStatSelfLayout : Smobiler.Core.Controls.MobileUserControl
    {
        /// <summary>
        /// Ìøתµ½Ç©µ½Ïêϸ½çÃæ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_Press(object sender, EventArgs e)
        {
            try
            {
                if ( Convert.ToInt32(lblNumber.BindDataValue) > 0)
                {
                    SmoONE.UI.Attendance.frmAttendanceStatSelfDetail newFrm = new SmoONE.UI.Attendance.frmAttendanceStatSelfDetail();
                    newFrm.Type = lblID.BindDisplayValue.ToString ();           //Ç©µ½ÀàÐÍ
                    newFrm.Daytime = ((SmoONE.UI.Attendance.frmAttendanceStatSelf)this.Form).Daytime;                   //ʱ¼ä
                    newFrm.UserID = ((SmoONE.UI.Attendance.frmAttendanceStatSelf)this.Form).UserID;                     //Óû§ID
                 //   newFrm.TitleText =((SmoONE.UI.Attendance.frmAttendanceStatSelf)this.Form). lblName.Text + lblID.BindDisplayValue.ToString () + "¼Ç¼";
                    this.Form.Show(newFrm);
                }
            }
            catch (Exception ex)
            {
               this.Form. Toast(ex.Message);
            }
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// Tests the delisting of the composite Symbol (ETF symbol) and the removal of
    /// the universe and the symbol from the algorithm.
    /// </summary>
    public class ETFConstituentUniverseCompositeDelistingRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
    {
        protected virtual bool AddETFSubscription { get; set; } = true;

        private Symbol _gdvd;
        private Symbol _aapl;
        private DateTime _delistingDate;
        private int _universeSymbolCount;
        private bool _universeAdded;
        private bool _universeRemoved;

        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2020, 12, 1);
            SetEndDate(2021, 1, 31);
            SetCash(100000);

            UniverseSettings.Resolution = Resolution.Hour;

            _delistingDate = new DateTime(2021, 1, 21);

            _aapl = AddEquity("AAPL", Resolution.Hour).Symbol;
            if (AddETFSubscription)
            {
                Log("Adding ETF constituent universe Symbol by using AddEquity(...)");
                _gdvd = AddEquity("GDVD", Resolution.Hour).Symbol;
            }
            else
            {
                Log("Adding ETF constituent universe Symbol by using Symbol.Create(...)");
                _gdvd = QuantConnect.Symbol.Create("GDVD", SecurityType.Equity, Market.USA);
            }

            AddUniverse(Universe.ETF(_gdvd, universeFilterFunc: FilterETFs));
        }

        private IEnumerable<Symbol> FilterETFs(IEnumerable<ETFConstituentData> constituents)
        {
            if (UtcTime.Date > _delistingDate)
            {
                throw new Exception($"Performing constituent universe selection on {UtcTime:yyyy-MM-dd HH:mm:ss.fff} after composite ETF has been delisted");
            }

            var constituentSymbols = constituents.Select(x => x.Symbol).ToList();
            _universeSymbolCount = constituentSymbols.Count;

            return constituentSymbols;
        }

        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (UtcTime.Date > _delistingDate && data.Keys.Any(x => x != _aapl))
            {
                throw new Exception($"Received unexpected slice in OnData(...) after universe was deselected");
            }

            if (!Portfolio.Invested)
            {
                SetHoldings(_aapl, 0.5m);
            }
        }

        public override void OnSecuritiesChanged(SecurityChanges changes)
        {
            if (changes.AddedSecurities.Count != 0 && UtcTime > _delistingDate)
            {
                throw new Exception("New securities added after ETF constituents were delisted");
            }

            _universeAdded |= changes.AddedSecurities.Count >= _universeSymbolCount;
            // Subtract 1 from universe Symbol count for AAPL, since it was manually added to the algorithm
            _universeRemoved |= changes.RemovedSecurities.Count == _universeSymbolCount - 1 && UtcTime.Date >= _delistingDate && UtcTime.Date < EndDate;
        }

        public override void OnEndOfAlgorithm()
        {
            if (!_universeAdded)
            {
                throw new Exception("ETF constituent universe was never added to the algorithm");
            }
            if (!_universeRemoved)
            {
                throw new Exception("ETF constituent universe was not removed from the algorithm after delisting");
            }
            if (ActiveSecurities.Count > 2)
            {
                throw new Exception($"Expected less than 2 securities after algorithm ended, found {Securities.Count}");
            }
        }

        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public Language[] Languages { get; } = { Language.CSharp, Language.Python };

        /// <summary>
        /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
        /// </summary>
        public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
        {
            {"Total Trades", "1"},
            {"Average Win", "0%"},
            {"Average Loss", "0%"},
            {"Compounding Annual Return", "26.315%"},
            {"Drawdown", "5.400%"},
            {"Expectancy", "0"},
            {"Net Profit", "3.893%"},
            {"Sharpe Ratio", "1.309"},
            {"Probabilistic Sharpe Ratio", "53.929%"},
            {"Loss Rate", "0%"},
            {"Win Rate", "0%"},
            {"Profit-Loss Ratio", "0"},
            {"Alpha", "0.131"},
            {"Beta", "0.697"},
            {"Annual Standard Deviation", "0.139"},
            {"Annual Variance", "0.019"},
            {"Information Ratio", "0.889"},
            {"Tracking Error", "0.122"},
            {"Treynor Ratio", "0.261"},
            {"Total Fees", "$2.04"},
            {"Estimated Strategy Capacity", "$260000000.00"},
            {"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
            {"Fitness Score", "0.011"},
            {"Kelly Criterion Estimate", "0"},
            {"Kelly Criterion Probability Value", "0"},
            {"Sortino Ratio", "5.155"},
            {"Return Over Maximum Drawdown", "9.927"},
            {"Portfolio Turnover", "0.012"},
            {"Total Insights Generated", "0"},
            {"Total Insights Closed", "0"},
            {"Total Insights Analysis Completed", "0"},
            {"Long Insight Count", "0"},
            {"Short Insight Count", "0"},
            {"Long/Short Ratio", "100%"},
            {"Estimated Monthly Alpha Value", "$0"},
            {"Total Accumulated Estimated Alpha Value", "$0"},
            {"Mean Population Estimated Insight Value", "$0"},
            {"Mean Population Direction", "0%"},
            {"Mean Population Magnitude", "0%"},
            {"Rolling Averaged Population Direction", "0%"},
            {"Rolling Averaged Population Magnitude", "0%"},
            {"OrderListHash", "49d511dbd5e31d6c25afda0f55aa28c2"}
        };
    }
}


text:
module Google
  module Cloud
    module Logging
      ##
      # # AsyncWriter
      #
      # An object that batches and transmits log entries asynchronously.
      #
      # Use this object to transmit log entries efficiently. It keeps a queue
      # of log entries, and runs a background thread that transmits them to
      # the logging service in batches. Generally, adding to the queue will
      # not block.
      #
      # This object is thread-safe; it may accept write requests from
      # multiple threads simultaneously, and will serialize them when
      # executing in the background thread.
      #
      # @example
      #   require "google/cloud/logging"
      #
      #   logging = Google::Cloud::Logging.new
      #
      #   async = logging.async_writer
      #
      #   entry1 = logging.entry payload: "Job started."
      #   entry2 = logging.entry payload: "Job completed."
      #
      #   labels = { job_size: "large", job_code: "red" }
      #   resource = logging.resource "gae_app",
      #                               "module_id" => "1",
      #                               "version_id" => "20150925t173233"
      #
      #   async.write_entries [entry1, entry2],
      #                       log_name: "my_app_log",
      #                       resource: resource,
      #                       labels: labels
      #
      class AsyncWriter
        DEFAULT_MAX_QUEUE_SIZE = 10000

        ##
        # @private Item in the log entries queue.
        QueueItem = Struct.new(:entries, :log_name, :resource, :labels) do
          def try_combine next_item
            if log_name == next_item.log_name &&
               resource == next_item.resource &&
               labels == next_item.labels
              entries.concat(next_item.entries)
              true
            else
              false
            end
          end
        end

        ##
        # @private The logging object.
        attr_accessor :logging

        ##
        # @private The maximum size of the entries queue, or nil if not set.
        attr_accessor :max_queue_size

        ##
        # The current state. Either :running, :suspended, :stopping, or :stopped
        attr_reader :state

        ##
        # The last exception thrown by the background thread, or nil if nothing
        # has been thrown.
        attr_reader :last_exception

        ##
        # @private Creates a new AsyncWriter instance.
        def initialize logging, max_queue_size = DEFAULT_MAX_QUEUE_SIZE
          @logging = logging
          @max_queue_size = max_queue_size
          @startup_lock = Mutex.new
          @thread = nil
          @state = :running
        end

        ##
        # Asynchronously write one or more log entries to the Stackdriver
        # Logging service.
        #
        # Unlike the main write_entries method, this method usually does not
        # block. The actual write RPCs will happen in the background, and may
        # be batched with related calls. However, if the queue is full, this
        # method will block until enough space has cleared out.
        #
        # @param [Google::Cloud::Logging::Entry,
        #   Array<Google::Cloud::Logging::Entry>] entries One or more entry
        #   objects to write. The log entries must have values for all required
        #   fields.
        # @param [String] log_name A default log ID for those log entries in
        #   `entries` that do not specify their own `log_name`. See also
        #   {Entry#log_name=}.
        # @param [Resource] resource A default monitored resource for those log
        #   entries in entries that do not specify their own resource. See also
        #   {Entry#resource}.
        # @param [Hash{Symbol,String => String}] labels User-defined `key:value`
        #   items that are added to the `labels` field of each log entry in
        #   `entries`, except when a log entry specifies its own `key:value`
        #   item with the same key. See also {Entry#labels=}.
        #
        # @return [Google::Cloud::Logging::AsyncWriter] Returns self.
        #
        # @example
        #   require "google/cloud/logging"
        #
        #   logging = Google::Cloud::Logging.new
        #   async = logging.async_writer
        #
        #   entry = logging.entry payload: "Job started.",
        #                         log_name: "my_app_log"
        #   entry.resource.type = "gae_app"
        #   entry.resource.labels[:module_id] = "1"
        #   entry.resource.labels[:version_id] = "20150925t173233"
        #
        #   async.write_entries entry
        #
        def write_entries entries, log_name: nil, resource: nil, labels: nil
          ensure_thread
          entries = Array(entries)
          @lock.synchronize do
            fail "AsyncWriter has been stopped" unless writable?
            queue_item = QueueItem.new entries, log_name, resource, labels
            if @queue.empty? || !@queue.last.try_combine(queue_item)
              @queue.push queue_item
            end
            @queue_size += entries.size
            @lock_cond.broadcast
            while @max_queue_size && @queue_size > @max_queue_size
              @lock_cond.wait
            end
          end
          self
        end

        ##
        # Creates a logger instance that is API-compatible with Ruby's standard
        # library [Logger](http://ruby-doc.org/stdlib/libdoc/logger/rdoc).
        #
        # The logger will use AsyncWriter to transmit log entries on a
        # background thread.
        #
        # @param [String] log_name A log resource name to be associated with the
        #   written log entries.
        # @param [Google::Cloud::Logging::Resource] resource The monitored
        #   resource to be associated with written log entries.
        # @param [Hash] labels A set of user-defined data to be associated with
        #   written log entries.
        #
        # @return [Google::Cloud::Logging::Logger] a Logger object that can be
        #   used in place of a ruby standard library logger object.
        #
        # @example
        #   require "google/cloud/logging"
        #
        #   logging = Google::Cloud::Logging.new
        #
        #   resource = logging.resource "gae_app",
        #                               module_id: "1",
        #                               version_id: "20150925t173233"
        #
        #   async = logging.async_writer
        #   logger = async.logger "my_app_log", resource, env: :production
        #   logger.info "Job started."
        #
        def logger log_name, resource, labels = {}
          Logger.new self, log_name, resource, labels
        end

        ##
        # Stops this asynchronous writer.
        #
        # After this call succeeds, the state will change to :stopping, and
        # you may not issue any additional write_entries calls. Any previously
        # issued writes will complete. Once any existing backlog has been
        # cleared, the state will change to :stopped.
        #
        # @return [Boolean] Returns true if the writer was running, or false
        #   if the writer had already been stopped.
        #
        def stop
          ensure_thread
          @lock.synchronize do
            if state != :stopped
              @state = :stopping
              @lock_cond.broadcast
              true
            else
              false
            end
          end
        end

        ##
        # Suspends this asynchronous writer.
        #
        # After this call succeeds, the state will change to :suspended, and
        # the writer will stop sending RPCs until resumed.
        #
        # @return [Boolean] Returns true if the writer had been running and was
        #   suspended, otherwise false.
        #
        def suspend
          ensure_thread
          @lock.synchronize do
            if state == :running
              @state = :suspended
              @lock_cond.broadcast
              true
            else
              false
            end
          end
        end

        ##
        # Resumes this suspended asynchronous writer.
        #
        # After this call succeeds, the state will change to :running, and
        # the writer will resume sending RPCs.
        #
        # @return [Boolean] Returns true if the writer had been suspended and
        #   is now running, otherwise false.
        #
        def resume
          ensure_thread
          @lock.synchronize do
            if state == :suspended
              @state = :running
              @lock_cond.broadcast
              true
            else
              false
            end
          end
        end

        ##
        # Returns true if this writer is running.
        #
        # @return [Boolean] Returns true if the writer is currently running.
        #
        def running?
          ensure_thread
          @lock.synchronize do
            state == :running
          end
        end

        ##
        # Returns true if this writer is suspended.
        #
        # @return [Boolean] Returns true if the writer is currently suspended.
        #
        def suspended?
          ensure_thread
          @lock.synchronize do
            state == :suspended
          end
        end

        ##
        # Returns true if this writer is still accepting writes. This means
        # it is either running or suspended.
        #
        # @return [Boolean] Returns true if the writer is accepting writes.
        #
        def writable?
          ensure_thread
          @lock.synchronize do
            state == :suspended || state == :running
          end
        end

        ##
        # Returns true if this writer is fully stopped.
        #
        # @return [Boolean] Returns true if the writer is fully stopped.
        #
        def stopped?
          ensure_thread
          @lock.synchronize do
            state == :stopped
          end
        end

        ##
        # Blocks until this asynchronous writer has been stopped, or the given
        # timeout (if present) has elapsed.
        #
        # @param [Number] timeout Timeout in seconds, or nil for no timeout.
        #
        # @return [Boolean] Returns true if the writer is stopped, or false
        #   if the timeout expired.
        #
        def wait_until_stopped timeout = nil
          ensure_thread
          deadline = timeout ? ::Time.new.to_f + timeout : nil
          @lock.synchronize do
            until state == :stopped
              cur_time = ::Time.new.to_f
              return false if deadline && cur_time >= deadline
              @lock_cond.wait(deadline ? deadline - cur_time : nil)
            end
          end
          true
        end

        protected

        ##
        # @private Ensures the background thread is running. This is called
        # at the start of all public methods, and kicks off the thread lazily.
        # It also ensures the thread gets restarted (with an empty queue) in
        # case this object is forked into a child process.
        #
        def ensure_thread
          @startup_lock.synchronize do
            if (@thread.nil? || !@thread.alive?) && @state != :stopped
              @queue_size = 0
              @queue = []
              @lock = Monitor.new
              @lock_cond = @lock.new_cond
              @thread = Thread.new { run_backgrounder }
            end
          end
        end

        ##
        # @private The background thread implementation, which continuously
        # waits for performs work, and returns only when fully stopped.
        #
        def run_backgrounder
          loop do
            queue_item = wait_next_item
            return unless queue_item
            begin
              logging.write_entries(
                queue_item.entries,
                log_name: queue_item.log_name,
                resource: queue_item.resource,
                labels: queue_item.labels
              )
            rescue => e
              # Ignore any exceptions thrown from the background thread, but
              # keep running to ensure its state behavior remains consistent.
              @last_exception = e
            end
          end
        end

        ##
        # @private Wait for and dequeue the next set of log entries to transmit.
        #
        # @return [QueueItem,NilClass] Returns the next set of entries. If
        #   the writer has been stopped and no more entries are left in the
        #   queue, returns nil.
        #
        def wait_next_item
          @lock.synchronize do
            while state == :suspended ||
                  (state == :running && @queue.empty?)
              @lock_cond.wait
            end
            if @queue.empty?
              @state = :stopped
              nil
            else
              queue_item = @queue.shift
              @queue_size -= queue_item.entries.size
              @lock_cond.broadcast
              queue_item
            end
          end
        end
      end
    end
  end
end


text:
package org.broadinstitute.dsde.firecloud.mock

import org.broadinstitute.dsde.firecloud.mock.MockUtils._
import org.broadinstitute.dsde.firecloud.model.EntityId
import org.broadinstitute.dsde.firecloud.model.ModelJsonProtocol._
import spray.json.DefaultJsonProtocol._
import org.mockserver.mock.action.ExpectationCallback
import org.mockserver.model.HttpResponse._
import org.mockserver.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.model.StatusCodes._
import spray.json._

class ValidEntityDeleteCallback extends ExpectationCallback {

  val validEntities = Set(EntityId("sample", "id"), EntityId("sample", "bar"))

  override def handle(httpRequest: HttpRequest): HttpResponse = {
    val deleteRequest = httpRequest.getBodyAsString.parseJson.convertTo[Set[EntityId]]

    if (deleteRequest.subsetOf(validEntities)) {
      response()
        .withHeaders(header)
        .withStatusCode(NoContent.intValue)
    }
    else {
      response()
        .withHeaders(header)
        .withStatusCode(BadRequest.intValue)
        .withBody(MockUtils.rawlsErrorReport(BadRequest).toJson.compactPrint)
    }
  }
}


text:
Imports System.Diagnostics

Public Class frmAddCounters
    Inherits System.Windows.Forms.Form
    Public ofrmNewAnalysis As frmNewAnalysis
    Public ofrmAddDataSourceCounter As frmAddDataSourceCounter
    Friend LastUsedComputerName As String
    Friend ofrmMain As frmPALEditor
    Dim arrPerfObjects() As PerfCounter
    Public aCounters() As String
    Public strDestination As String
    Dim arrCounterExplains(0, 1) As String

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    Friend WithEvents ListBoxPerfCounters As System.Windows.Forms.ListBox
    Friend WithEvents ListBoxPerfInstances As System.Windows.Forms.ListBox
    Friend WithEvents cbPerfObjects As System.Windows.Forms.ComboBox
    Friend WithEvents txtComputerName As System.Windows.Forms.TextBox
    Friend WithEvents btnAdd As System.Windows.Forms.Button
    Friend WithEvents btnClose As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents radAllPerfCounters As System.Windows.Forms.RadioButton
    Friend WithEvents radPerfCountersSelect As System.Windows.Forms.RadioButton
    Friend WithEvents radInstancesAll As System.Windows.Forms.RadioButton
    Friend WithEvents radInstancesSelect As System.Windows.Forms.RadioButton
    Friend WithEvents gbInstances As System.Windows.Forms.GroupBox
    Friend WithEvents gbCounters As System.Windows.Forms.GroupBox
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents txtExplain As System.Windows.Forms.TextBox
    Friend WithEvents btnConnect As System.Windows.Forms.Button
    Friend WithEvents StatusBar1 As System.Windows.Forms.StatusBar
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmAddCounters))
        Me.ListBoxPerfCounters = New System.Windows.Forms.ListBox
        Me.ListBoxPerfInstances = New System.Windows.Forms.ListBox
        Me.cbPerfObjects = New System.Windows.Forms.ComboBox
        Me.txtComputerName = New System.Windows.Forms.TextBox
        Me.btnAdd = New System.Windows.Forms.Button
        Me.btnClose = New System.Windows.Forms.Button
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.radAllPerfCounters = New System.Windows.Forms.RadioButton
        Me.radPerfCountersSelect = New System.Windows.Forms.RadioButton
        Me.radInstancesAll = New System.Windows.Forms.RadioButton
        Me.radInstancesSelect = New System.Windows.Forms.RadioButton
        Me.gbInstances = New System.Windows.Forms.GroupBox
        Me.gbCounters = New System.Windows.Forms.GroupBox
        Me.Label3 = New System.Windows.Forms.Label
        Me.txtExplain = New System.Windows.Forms.TextBox
        Me.btnConnect = New System.Windows.Forms.Button
        Me.StatusBar1 = New System.Windows.Forms.StatusBar
        Me.gbInstances.SuspendLayout()
        Me.gbCounters.SuspendLayout()
        Me.SuspendLayout()
        '
        'ListBoxPerfCounters
        '
        Me.ListBoxPerfCounters.Location = New System.Drawing.Point(8, 64)
        Me.ListBoxPerfCounters.Name = "ListBoxPerfCounters"
        Me.ListBoxPerfCounters.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended
        Me.ListBoxPerfCounters.Size = New System.Drawing.Size(168, 95)
        Me.ListBoxPerfCounters.TabIndex = 1
        '
        'ListBoxPerfInstances
        '
        Me.ListBoxPerfInstances.Location = New System.Drawing.Point(8, 64)
        Me.ListBoxPerfInstances.Name = "ListBoxPerfInstances"
        Me.ListBoxPerfInstances.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended
        Me.ListBoxPerfInstances.Size = New System.Drawing.Size(168, 95)
        Me.ListBoxPerfInstances.TabIndex = 2
        '
        'cbPerfObjects
        '
        Me.cbPerfObjects.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.cbPerfObjects.DropDownWidth = 184
        Me.cbPerfObjects.ImeMode = System.Windows.Forms.ImeMode.NoControl
        Me.cbPerfObjects.IntegralHeight = False
        Me.cbPerfObjects.ItemHeight = 13
        Me.cbPerfObjects.Location = New System.Drawing.Point(8, 64)
        Me.cbPerfObjects.MaxDropDownItems = 30
        Me.cbPerfObjects.Name = "cbPerfObjects"
        Me.cbPerfObjects.Size = New System.Drawing.Size(184, 21)
        Me.cbPerfObjects.Sorted = True
        Me.cbPerfObjects.TabIndex = 3
        '
        'txtComputerName
        '
        Me.txtComputerName.AcceptsReturn = True
        Me.txtComputerName.Location = New System.Drawing.Point(8, 24)
        Me.txtComputerName.Name = "txtComputerName"
        Me.txtComputerName.Size = New System.Drawing.Size(128, 20)
        Me.txtComputerName.TabIndex = 4
        Me.txtComputerName.Text = "txtComputerName"
        '
        'btnAdd
        '
        Me.btnAdd.Location = New System.Drawing.Point(16, 272)
        Me.btnAdd.Name = "btnAdd"
        Me.btnAdd.TabIndex = 5
        Me.btnAdd.Text = "Add"
        '
        'btnClose
        '
        Me.btnClose.Location = New System.Drawing.Point(296, 280)
        Me.btnClose.Name = "btnClose"
        Me.btnClose.TabIndex = 7
        Me.btnClose.Text = "Close"
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(8, 8)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(176, 16)
        Me.Label1.TabIndex = 8
        Me.Label1.Text = "Select counters from computer:"
        '
        'Label2
        '
        Me.Label2.Location = New System.Drawing.Point(8, 48)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(112, 16)
        Me.Label2.TabIndex = 9
        Me.Label2.Text = "Performance object:"
        '
        'radAllPerfCounters
        '
        Me.radAllPerfCounters.Location = New System.Drawing.Point(8, 16)
        Me.radAllPerfCounters.Name = "radAllPerfCounters"
        Me.radAllPerfCounters.TabIndex = 10
        Me.radAllPerfCounters.Text = "All counters"
        '
        'radPerfCountersSelect
        '
        Me.radPerfCountersSelect.Location = New System.Drawing.Point(8, 40)
        Me.radPerfCountersSelect.Name = "radPerfCountersSelect"
        Me.radPerfCountersSelect.Size = New System.Drawing.Size(152, 24)
        Me.radPerfCountersSelect.TabIndex = 11
        Me.radPerfCountersSelect.Text = "Select counters from list"
        '
        'radInstancesAll
        '
        Me.radInstancesAll.Location = New System.Drawing.Point(8, 16)
        Me.radInstancesAll.Name = "radInstancesAll"
        Me.radInstancesAll.TabIndex = 12
        Me.radInstancesAll.Text = "All instances"
        '
        'radInstancesSelect
        '
        Me.radInstancesSelect.Location = New System.Drawing.Point(8, 40)
        Me.radInstancesSelect.Name = "radInstancesSelect"
        Me.radInstancesSelect.Size = New System.Drawing.Size(152, 24)
        Me.radInstancesSelect.TabIndex = 13
        Me.radInstancesSelect.Text = "Select instances from list"
        '
        'gbInstances
        '
        Me.gbInstances.Controls.Add(Me.radInstancesSelect)
        Me.gbInstances.Controls.Add(Me.radInstancesAll)
        Me.gbInstances.Controls.Add(Me.ListBoxPerfInstances)
        Me.gbInstances.Location = New System.Drawing.Point(192, 96)
        Me.gbInstances.Name = "gbInstances"
        Me.gbInstances.Size = New System.Drawing.Size(184, 168)
        Me.gbInstances.TabIndex = 14
        Me.gbInstances.TabStop = False
        Me.gbInstances.Text = "Instances"
        '
        'gbCounters
        '
        Me.gbCounters.Controls.Add(Me.radPerfCountersSelect)
        Me.gbCounters.Controls.Add(Me.radAllPerfCounters)
        Me.gbCounters.Controls.Add(Me.ListBoxPerfCounters)
        Me.gbCounters.Location = New System.Drawing.Point(8, 96)
        Me.gbCounters.Name = "gbCounters"
        Me.gbCounters.Size = New System.Drawing.Size(184, 168)
        Me.gbCounters.TabIndex = 14
        Me.gbCounters.TabStop = False
        Me.gbCounters.Text = "Counters"
        '
        'Label3
        '
        Me.Label3.Location = New System.Drawing.Point(200, 0)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(112, 16)
        Me.Label3.TabIndex = 15
        Me.Label3.Text = "Counter description:"
        '
        'txtExplain
        '
        Me.txtExplain.Location = New System.Drawing.Point(200, 16)
        Me.txtExplain.Multiline = True
        Me.txtExplain.Name = "txtExplain"
        Me.txtExplain.ReadOnly = True
        Me.txtExplain.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
        Me.txtExplain.Size = New System.Drawing.Size(176, 72)
        Me.txtExplain.TabIndex = 16
        Me.txtExplain.Text = ""
        '
        'btnConnect
        '
        Me.btnConnect.Location = New System.Drawing.Point(136, 24)
        Me.btnConnect.Name = "btnConnect"
        Me.btnConnect.Size = New System.Drawing.Size(56, 20)
        Me.btnConnect.TabIndex = 1
        Me.btnConnect.Text = "Connect"
        '
        'StatusBar1
        '
        Me.StatusBar1.Location = New System.Drawing.Point(0, 307)
        Me.StatusBar1.Name = "StatusBar1"
        Me.StatusBar1.Size = New System.Drawing.Size(384, 16)
        Me.StatusBar1.TabIndex = 18
        '
        'frmAddCounters
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(384, 323)
        Me.Controls.Add(Me.StatusBar1)
        Me.Controls.Add(Me.btnConnect)
        Me.Controls.Add(Me.txtExplain)
        Me.Controls.Add(Me.txtComputerName)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.btnClose)
        Me.Controls.Add(Me.btnAdd)
        Me.Controls.Add(Me.cbPerfObjects)
        Me.Controls.Add(Me.gbInstances)
        Me.Controls.Add(Me.gbCounters)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.Name = "frmAddCounters"
        Me.Text = "Add Counters"
        Me.gbInstances.ResumeLayout(False)
        Me.gbCounters.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub frmAddCounters_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '<Populate txtComputerName with the local machine name>
        If LastUsedComputerName = "" Then
            txtComputerName.Text = System.Environment.MachineName
        Else
            txtComputerName.Text = LastUsedComputerName
        End If

        '</Populate txtComputerName with the local machine name>
        EnumeratePerfObjects(txtComputerName.Text)
    End Sub

    Private Sub EnumeratePerfObjects(ByVal strComputerName As String)
        StatusBar1.Text = "Connecting to " & strComputerName & "..."

        Dim arrPerfObjectNames() As String
        Dim o, i, c As Integer
        Dim objCategories() As PerformanceCounterCategory

        On Error Resume Next
        objCategories = PerformanceCounterCategory.GetCategories(strComputerName)
        If Err.Number <> 0 Then
            MsgBox("Unable to connect to " & strComputerName)
            Exit Sub
        End If

        radPerfCountersSelect.Checked = True
        radInstancesSelect.Checked = True
        ListBoxPerfCounters.Items.Clear()
        ListBoxPerfInstances.Items.Clear()
        cbPerfObjects.Items.Clear()

        ReDim arrPerfObjectNames(UBound(objCategories))
        For o = 0 To UBound(objCategories)
            arrPerfObjectNames(o) = objCategories(o).CategoryName.ToString
        Next

        Array.Sort(arrPerfObjectNames)

        For o = 0 To UBound(arrPerfObjectNames)
            cbPerfObjects.Items.Add(arrPerfObjectNames(o))
        Next
        cbPerfObjects.SelectedItem = "Processor"
    End Sub

    Private Sub ListBoxPerfObjects_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        EnumPerfCountersAndInstances(txtComputerName.Text)
    End Sub

    Private Structure PerfCounter
        Public Name As String
        Public Instances() As String
    End Structure

    Private Structure PerfObject
        Public Name As String
        Public Counters() As PerfCounter
    End Structure

    Private Sub EnumPerfCountersAndInstances(ByVal strMachineName As String)
        Dim i As Integer
        ListBoxPerfCounters.Items.Clear()
        ListBoxPerfInstances.Items.Clear()
        'gbInstances.Enabled = True
        gbCounters.Enabled = True
        radInstancesAll.Checked = False
        radInstancesSelect.Checked = True

        btnAdd.Enabled = True

        Dim arrPerfObjectNames() As String
        Dim o, c As Integer
        Dim arrTemp() As String

        Dim objPerfCategory As New PerformanceCounterCategory(cbPerfObjects.SelectedItem, strMachineName)
        Dim objPerfCounters() As PerformanceCounter
        Dim strPerfInstanceNames() As String

        On Error Resume Next
        strPerfInstanceNames = objPerfCategory.GetInstanceNames()

        If IsNothing(strPerfInstanceNames) = False Then
            If strPerfInstanceNames.Length > 0 Then
                objPerfCounters = objPerfCategory.GetCounters(strPerfInstanceNames(0).ToString)
            Else
                objPerfCounters = objPerfCategory.GetCounters()
                'gbInstances.Enabled = False
            End If
        Else
            objPerfCounters = objPerfCategory.GetCounters()
            'gbInstances.Enabled = False
        End If

        If objPerfCounters.Length = 0 Then
            gbCounters.Enabled = False
        End If

        If IsNothing(objPerfCounters) = True And IsNothing(strPerfInstanceNames) = True Then
            btnAdd.Enabled = False
            Exit Sub
        End If

        If objPerfCounters.Length > 0 Or strPerfInstanceNames.Length > 0 Then
            ReDim arrTemp(objPerfCounters.GetUpperBound(0))
            ReDim arrCounterExplains(objPerfCounters.GetUpperBound(0), 1)
            For c = 0 To objPerfCounters.GetUpperBound(0)
                arrTemp(c) = objPerfCounters(c).CounterName
                arrCounterExplains(c, 0) = objPerfCounters(c).CounterName
                arrCounterExplains(c, 1) = objPerfCounters(c).CounterHelp
            Next
            Array.Sort(arrTemp)
            For c = 0 To UBound(arrTemp)
                ListBoxPerfCounters.Items.Add(arrTemp(c))
            Next

            For i = 0 To strPerfInstanceNames.GetUpperBound(0)
                Array.Sort(strPerfInstanceNames)
                ListBoxPerfInstances.Items.Add(strPerfInstanceNames(i).ToString)
            Next
            On Error GoTo 0
            If ListBoxPerfInstances.Items.Count > 0 Then
                ListBoxPerfInstances.SetSelected(0, True)
            End If
            If ListBoxPerfCounters.Items.Count > 0 Then
                ListBoxPerfCounters.SetSelected(0, True)
            End If
        Else
            btnAdd.Enabled = False
            Exit Sub
        End If
        StatusBar1.Text = "Connected to " & txtComputerName.Text
        LastUsedComputerName = txtComputerName.Text
    End Sub

    Private Sub cbPerfObjects_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbPerfObjects.SelectedIndexChanged
        txtExplain.Text = ""
        EnumPerfCountersAndInstances(txtComputerName.Text)
    End Sub

    Private Sub radAllPerfCounters_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radAllPerfCounters.CheckedChanged
        If radAllPerfCounters.Checked = True Then
            Dim i As Integer
            For i = 0 To ListBoxPerfCounters.Items.Count - 1
                ListBoxPerfCounters.SetSelected(i, True)
                ListBoxPerfCounters.Enabled = False
            Next
        End If
    End Sub

    Private Sub radPerfCountersSelect_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radPerfCountersSelect.CheckedChanged
        ListBoxPerfCounters.Enabled = True
    End Sub

    Private Sub radInstancesAll_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radInstancesAll.CheckedChanged
        If radInstancesAll.Checked = True Then
            Dim i As Integer
            For i = 0 To ListBoxPerfInstances.Items.Count - 1
                ListBoxPerfInstances.SetSelected(i, True)
                ListBoxPerfInstances.Enabled = False
            Next
        End If
    End Sub

    Private Sub radInstancesSelect_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radInstancesSelect.CheckedChanged
        ListBoxPerfInstances.Enabled = True
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim sCounterPath, sPerfObject, sCounter, sInstance, sVarName As String

        Select Case Me.Owner.Name
            Case "frmNewAnalysis"
                sPerfObject = cbPerfObjects.SelectedItem.ToString
                sCounter = ListBoxPerfCounters.SelectedItem.ToString
                If radInstancesAll.Checked = True Then
                    If ListBoxPerfInstances.Items.Count > 0 Then
                        sInstance = "*"
                    Else
                        sInstance = ""
                    End If
                Else
                    If ListBoxPerfInstances.SelectedItems.Count > 0 Then
                        sInstance = ListBoxPerfInstances.SelectedItem.ToString
                    Else
                        If ListBoxPerfInstances.Items.Count > 0 Then
                            sInstance = "*"
                        Else
                            sInstance = ""
                        End If
                    End If
                End If
                If sInstance = "" Then
                    sCounterPath = "\" & sPerfObject & "\" & sCounter
                Else
                    sCounterPath = "\" & sPerfObject & "(" & sInstance & ")\" & sCounter
                End If

                ofrmNewAnalysis.txtNewAnalysisName.Text = GetCounterObject(sCounterPath) & " " & GetCounterName(sCounterPath)
                ofrmNewAnalysis.txtNewAnalysisCounter.Text = sCounterPath
                ofrmNewAnalysis.ComboBoxCategory.Text = cbPerfObjects.Text
                ofrmNewAnalysis.txtNewAnalysisDescription.Text = txtExplain.Text
                ofrmNewAnalysis.LastUsedComputerName = LastUsedComputerName
            Case "frmAddDataSourceCounter"
                sPerfObject = cbPerfObjects.SelectedItem.ToString
                sCounter = ListBoxPerfCounters.SelectedItem.ToString
                If radInstancesAll.Checked = True Then
                    If ListBoxPerfInstances.Items.Count > 0 Then
                        sInstance = "*"
                    Else
                        sInstance = ""
                    End If
                Else
                    If ListBoxPerfInstances.SelectedItems.Count > 0 Then
                        sInstance = ListBoxPerfInstances.SelectedItem.ToString
                    Else
                        If ListBoxPerfInstances.Items.Count > 0 Then
                            sInstance = "*"
                        Else
                            sInstance = ""
                        End If
                    End If
                End If
                If sInstance = "" Then
                    sCounterPath = "\" & sPerfObject & "\" & sCounter
                Else
                    sCounterPath = "\" & sPerfObject & "(" & sInstance & ")\" & sCounter
                End If
                sVarName = "CollectionOf" & ConvertCounterToVarName(sCounterPath)
                ofrmAddDataSourceCounter.txtCounterName.Text = sCounterPath
                ofrmAddDataSourceCounter.ComboBoxDataSourceCounterDataType.Text = "integer"
                ofrmAddDataSourceCounter.txtCollectionVarName.Text = sVarName
                ofrmAddDataSourceCounter.LastUsedComputerName = LastUsedComputerName
        End Select
    End Sub

    Function ConvertCounterToVarName(ByVal sCounter As String)
        Dim sCounterObject, sCounterName, sCounterInstance As String
        ' \\IDCWEB1\Processor(_Total)\% Processor Time
        sCounterObject = GetCounterObject(sCounter)
        sCounterName = GetCounterName(sCounter)
        sCounterInstance = GetCounterInstance(sCounter)
        If sCounterInstance <> "*" Then
            ConvertCounterToVarName = sCounterObject & sCounterName & sCounterInstance
        Else
            ConvertCounterToVarName = sCounterObject & sCounterName & "All"
        End If

        ConvertCounterToVarName = Replace(ConvertCounterToVarName, "/", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, "\", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, "%", "Percent")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, " ", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, ".", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, ":", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, "(", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, ")", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, "-", "")
        ConvertCounterToVarName = Replace(ConvertCounterToVarName, "_", "")
    End Function

    'Public Function OneCounterWithInstanceWildCards()
    '    Dim sCounter As String

    '    Return sCounter

    '    'Dim strBaseCounterPath, strCounterPath, strModifiedCounterPath As String
    '    ''Dim arrTemp()
    '    ''Dim arrTemp2() As sAlert
    '    'Dim i, c, d, a, b As Integer
    '    'Dim bDuplicateFound As Boolean
    '    'Dim arrCounterPath(), arrTempCounterPath() As String

    '    'strBaseCounterPath = cbPerfObjects.Text 'Processor
    '    'strCounterPath = strBaseCounterPath

    '    'If radInstancesAll.Checked = True Then
    '    '    ReDim arrTempCounterPath(0)
    '    '    arrTempCounterPath(0) = strCounterPath & "(*)" 'Processor(*)
    '    'Else
    '    '    'Enum through all of the instances
    '    '    If ListBoxPerfInstances.SelectedItems.Count > 0 Then
    '    '        ReDim arrTempCounterPath(ListBoxPerfInstances.SelectedItems.Count - 1)
    '    '        For i = 0 To ListBoxPerfInstances.SelectedItems.Count - 1
    '    '            arrTempCounterPath(i) = strCounterPath & "(" & ListBoxPerfInstances.SelectedItems(i) & ")" 'Processor(_Total)
    '    '        Next
    '    '    Else
    '    '        ReDim arrTempCounterPath(0)
    '    '        arrTempCounterPath(0) = strCounterPath 'Processor
    '    '    End If
    '    'End If

    '    'If radAllPerfCounters.Checked = True Then
    '    '    a = 0
    '    '    For i = 0 To UBound(arrTempCounterPath)
    '    '        ReDim Preserve arrCounterPath(a)
    '    '        arrCounterPath(a) = arrTempCounterPath(i) & "\" & "*" 'Processor(*)\*
    '    '        a = a + 1
    '    '    Next
    '    'Else
    '    '    If ListBoxPerfCounters.SelectedItems.Count > 0 Then
    '    '        a = 0
    '    '        For i = 0 To UBound(arrTempCounterPath)
    '    '            For c = 0 To ListBoxPerfCounters.SelectedItems.Count - 1
    '    '                ReDim Preserve arrCounterPath(a)
    '    '                arrCounterPath(a) = arrTempCounterPath(i) & "\" & ListBoxPerfCounters.SelectedItems(c) 'Processor(*)\% Processor Time
    '    '                a = a + 1
    '    '            Next
    '    '        Next
    '    '    Else
    '    '        For i = 0 To UBound(arrTempCounterPath)
    '    '            ReDim Preserve arrCounterPath(a)
    '    '            arrCounterPath(a) = arrTempCounterPath(i)
    '    '            a = a + 1
    '    '        Next
    '    '    End If
    '    'End If

    '    'Select Case UCase(strDestination)
    '    '    Case UCase("frmEditThresholds")

    '    '        For c = 0 To ListBoxPerfCounters.SelectedItems.Count - 1
    '    '            strCounterPath = strBaseCounterPath & "\" & ListBoxPerfCounters.SelectedItems(c) 'Processor\% Processor Time

    '    '            'strModifiedCounterPath = Mid(strCounterPath, InStr(3, strCounterPath, "\") + 1)
    '    '            bDuplicateFound = False
    '    '            If IsNothing(AlertProfiles) = True Then
    '    '                Exit Sub
    '    '            End If

    '    '            '<find the selected profile>
    '    '            Dim p As Integer
    '    '            p = FindSelectedAlertProfile(frmEditThresholds.cbAlertProfiles.Text)
    '    '            If p = -1 Then
    '    '                Exit Sub
    '    '            End If
    '    '            '</find the selected profile>

    '    '            If IsNothing(AlertProfiles(p)) = True Then
    '    '                Exit Sub
    '    '            End If

    '    '            If IsNothing(AlertProfiles(p).arrAlertsInProfile) = False Then
    '    '                For d = 0 To UBound(AlertProfiles(p).arrAlertsInProfile)
    '    '                    If IsNothing(AlertProfiles(p).arrAlertsInProfile(d)) = False Then
    '    '                        If AlertProfiles(p).arrAlertsInProfile(d).Name = strCounterPath Then
    '    '                            bDuplicateFound = True
    '    '                            Exit For
    '    '                        End If
    '    '                    End If
    '    '                Next
    '    '                If bDuplicateFound = False Then
    '    '                    '<add to memory>
    '    '                    If IsNothing(AlertProfiles(p).arrAlertsInProfile) = True Then
    '    '                        ReDim AlertProfiles(p).arrAlertsInProfile(0)
    '    '                    Else
    '    '                        ReDim Preserve AlertProfiles(p).arrAlertsInProfile(UBound(AlertProfiles(p).arrAlertsInProfile) + 1)
    '    '                    End If
    '    '                    AlertProfiles(p).arrAlertsInProfile(UBound(AlertProfiles(p).arrAlertsInProfile)).Name = strCounterPath

    '    '                    Dim e As Integer
    '    '                    Dim strExplain As String
    '    '                    For e = 0 To UBound(arrCounterExplains)
    '    '                        If IsNothing(arrCounterExplains(e, 0)) = False Or IsNothing(arrCounterExplains(e, 1)) = False Then
    '    '                            If arrCounterExplains(e, 0) = ListBoxPerfCounters.SelectedItems(c) Then
    '    '                                strExplain = arrCounterExplains(e, 1)
    '    '                                Exit For
    '    '                            End If
    '    '                        End If
    '    '                    Next

    '    '                    AlertProfiles(p).arrAlertsInProfile(UBound(AlertProfiles(p).arrAlertsInProfile)).Comment = strExplain
    '    '                    '</add to memory>
    '    '                    frmEditThresholds.listCounters.Items.Add(strCounterPath)
    '    '                End If
    '    '            Else
    '    '                ReDim AlertProfiles(p).arrAlertsInProfile(0)
    '    '                AlertProfiles(p).arrAlertsInProfile(UBound(AlertProfiles(p).arrAlertsInProfile)).Name = strCounterPath
    '    '                '</add to memory>
    '    '                frmEditThresholds.listCounters.Items.Add(strCounterPath)
    '    '            End If
    '    '        Next

    '    '    Case UCase("CounterGroup")

    '    '        'frmParent.AxAddCountersSystemMonitor.Counters.Add(strCounterPath)
    '    '        frmParent.StatusBar1.Text = "Adding counters to counter group in treeview..."
    '    '        Dim iCG As Integer

    '    '        '<Find the CounterGroup we are modifiying>
    '    '        For a = 0 To UBound(CounterGroups)
    '    '            If frmParent.TreeView1.SelectedNode.Text = CounterGroups(a).Name Then
    '    '                iCG = a
    '    '                Exit For
    '    '            End If
    '    '        Next
    '    '        '<Find the CounterGroup we are modifiying>

    '    '        Dim bFound As Boolean
    '    '        Dim intTreeNode As Integer
    '    '        For a = 0 To UBound(arrCounterPath)

    '    '            '<Does this path already exist? If yes, then don't add it.>
    '    '            If IsNothing(CounterGroups(iCG).Counters) = False Then
    '    '                bFound = False
    '    '                For b = 0 To UBound(CounterGroups(iCG).Counters)
    '    '                    If arrCounterPath(a) = CounterGroups(iCG).Counters(b).Name Then
    '    '                        bFound = True
    '    '                    End If
    '    '                Next
    '    '            Else
    '    '                bFound = False
    '    '            End If

    '    '            '</Does this path already exist? If yes, then don't add it.>

    '    '            If bFound = False Then
    '    '                frmParent.CreateCounter(arrCounterPath(a), iCG)
    '    '            End If
    '    '        Next
    '    '        CounterGroups(iCG).TreeNode.ExpandAll()
    '    'End Select

    'End Function

    Private Sub ListBoxPerfCounters_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBoxPerfCounters.SelectedIndexChanged
        Dim i As Integer

        If IsNothing(arrCounterExplains) = True Then
            txtExplain.Text = ""
            Exit Sub
        End If

        For i = 0 To UBound(arrCounterExplains)
            If IsNothing(arrCounterExplains(i, 0)) = False Or IsNothing(arrCounterExplains(i, 1)) = False Then
                If arrCounterExplains(i, 0) = ListBoxPerfCounters.Items.Item(ListBoxPerfCounters.SelectedIndex) Then
                    txtExplain.Text = arrCounterExplains(i, 1)
                    Exit Sub
                End If
            Else
                txtExplain.Text = ""
            End If
        Next
        'Find counter in arrCounterExplains, then get help.

    End Sub

    'Sub AddCounterToCounterGroup(ByVal strCounterPath As String, ByVal iCounterGroup As Integer)
    '    Dim strModifiedCounterPath As String
    '    Dim i, intTreeNode As Integer

    '    frmParent.StatusBar1.Text = "Adding counters to counter group in treeview..."
    '    'strModifiedCounterPath = Mid(strCounterPath, InStr(3, strCounterPath, "\") + 1)
    '    'MsgBox(AxAddCountersSystemMonitor.Counters.Count)

    '    '<Does this path already exist? If yes, then don't add it.>
    '    For i = 0 To frmParent.TreeView1.SelectedNode.GetNodeCount(False) - 1
    '        If frmParent.TreeView1.SelectedNode.Nodes(i).Text = strModifiedCounterPath Then
    '            'AxAddCountersSystemMonitor.Reset()
    '            frmParent.StatusBar1.Text = "Done"
    '            Exit Sub
    '        End If
    '    Next
    '    '</Does this path already exist? If yes, then don't add it.>

    '    '<Add to TreeView>
    '    Dim objNewTreeNodeCounter As New TreeNode
    '    objNewTreeNodeCounter.Text = strModifiedCounterPath
    '    objNewTreeNodeCounter.ImageIndex = frmParent.enumImage.Counter
    '    objNewTreeNodeCounter.SelectedImageIndex = frmParent.enumImage.Counter
    '    intTreeNode = frmParent.TreeView1.SelectedNode.Nodes.Add(objNewTreeNodeCounter)
    '    '</Add to TreeView>

    '    Dim a, b As Integer
    '    If IsNothing(CounterGroups) = False Then
    '        For a = 0 To UBound(CounterGroups)
    '            If IsNothing(CounterGroups(a)) = False Then
    '                If frmParent.TreeView1.SelectedNode.Text = CounterGroups(a).Name Then
    '                    If IsNothing(CounterGroups(a).Counters) = True Then
    '                        ReDim CounterGroups(a).Counters(0)
    '                    Else
    '                        ReDim Preserve CounterGroups(a).Counters(UBound(CounterGroups(a).Counters) + 1)
    '                    End If
    '                    b = UBound(CounterGroups(a).Counters)
    '                    CounterGroups(a).Counters(b).Name = strModifiedCounterPath
    '                    CounterGroups(a).Counters(b).TreeNode = frmParent.TreeView1.Nodes(0).Nodes(1).Nodes(intTreeNode)
    '                    Exit For
    '                End If
    '            End If
    '        Next
    '    End If

    '    frmParent.TreeView1.SelectedNode.Expand()
    '    'frmParent.AxAddCountersSystemMonitor.Reset()
    '    frmParent.StatusBar1.Text = "Done"
    'End Sub

    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        StatusBar1.Text = "Connecting to " & txtComputerName.Text & "..."
        EnumeratePerfObjects(txtComputerName.Text)
    End Sub

    Function GetCounterObject(ByVal sCounter As String)
        '\\IDCWEB1\Processor(_Total)\% Processor Time"
        '\Processor(_Total)\% Processor Time"
        '\\IDCWEB1\Processor\% Processor Time"
        '\Processor\% Processor Time"
        Dim sCounterObject As String
        Dim iLocParen, iLocThirdBackSlash, iLocBackSlash As Integer
        sCounterObject = sCounter
        ' Returns the counter object
        iLocParen = InStr(3, sCounterObject, "(")

        If sCounterObject.Substring(0, 2) = "\\" Then
            '\\IDCWEB1\Processor(_Total)\% Processor Time
            '\\IDCWEB1\Processor\% Processor Time
            iLocThirdBackSlash = InStr(3, sCounterObject, "\")
            sCounterObject = Mid(sCounterObject, iLocThirdBackSlash + 1)
            'Processor(_Total)\% Processor Time
            'Processor\% Processor Time
        ElseIf sCounterObject.Substring(0, 1) = "\" Then
            '\Processor\% Processor Time
            sCounterObject = Mid(sCounterObject, 2)
            'Processor\% Processor Time
        End If
        If iLocParen = 0 Then
            'Processor\% Processor Time
            iLocBackSlash = InStr(sCounterObject, "\")
            GetCounterObject = Mid(sCounterObject, 1, iLocBackSlash - 1)
        Else
            'Processor(_Total)\% Processor Time
            iLocParen = InStr(sCounterObject, "(")
            GetCounterObject = Mid(sCounterObject, 1, iLocParen - 1)
        End If
    End Function

    Function GetCounterName(ByVal sCounter)
        '\\IDCWEB1\Processor(_Total)\% Processor Time"
        '\Processor(_Total)\% Processor Time"
        ' Returns the counter name
        Dim sCounterName As String
        Dim iLocSecondBackSlash, iLocThirdBackSlash, iLocForthBackSlash As Integer
        sCounterName = sCounter
        If sCounterName.Substring(0, 2) = "\\" Then
            iLocThirdBackSlash = InStr(3, sCounterName, "\")
            iLocForthBackSlash = InStr(iLocThirdBackSlash + 1, sCounterName, "\")
            GetCounterName = Mid(sCounterName, iLocForthBackSlash + 1)
        Else
            iLocSecondBackSlash = InStr(3, sCounter, "\")
            GetCounterName = Mid(sCounterName, iLocSecondBackSlash + 1)
        End If
    End Function

    Function GetCounterInstance(ByVal sCounter)
        '\\IDCWEB1\Processor(_Total)\% Processor Time"
        ' Returns the counter instance name
        Dim sCounterInstance As String
        Dim iLocFirstParen, iLocSecondParen, iLen As Integer
        sCounterInstance = sCounter
        iLocFirstParen = Instr(sCounterInstance, "(")
        If iLocFirstParen = 0 Then
            GetCounterInstance = ""
            Exit Function
        End If
        iLocSecondParen = Instr(sCounterInstance, ")")
        iLen = iLocSecondParen - iLocFirstParen - 1
        GetCounterInstance = Mid(sCounterInstance, iLocFirstParen + 1, iLen)
    End Function
End Class


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.shippingruntime;

import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import java.io.IOException;
import java.lang.ClassNotFoundException;

/**
 *	Properties of a shipping rate calculated for a line item in a shipment.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ShippingItemRate implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	protected  Double amount;

	public Double getAmount() {
		return this.amount;
	}

	public void setAmount(Double amount) {
		this.amount = amount;
	}

	protected  String itemId;

	public String getItemId() {
		return this.itemId;
	}

	public void setItemId(String itemId) {
		this.itemId = itemId;
	}

	protected  Integer quantity;

	public Integer getQuantity() {
		return this.quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

}


text:
[Atom package](https://atom.io/packages/editorconfig)

> [EditorConfig](http://editorconfig.org) helps developers maintain consistent coding styles between different editors

![](https://f.cloud.github.com/assets/170270/2327994/dfe40cb4-a3f6-11e3-862f-894999973373.png)

## Install

```sh
$ apm install editorconfig
```

Or Settings → Packages → Search for `editorconfig`

## Getting started

See the EditorConfig [documentation](http://editorconfig.org).

## Supported properties

- root
- indent_style
- indent_size
- charset *(supported values: `latin1`, `utf-8`, `utf-16be`, `utf-16le`)*

## Features

- Applies the above settings from your `.editorconfig` file
- Syntax highlights `.editorconfig` files

## Example file

```ini
# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
```

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)


text:
/** @module vertx-web-js/route */
var utils = require('vertx-js/util/utils');
var RoutingContext = require('vertx-web-js/routing_context');

var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JRoute = io.vertx.ext.web.Route;

/**
 A route is a holder for a set of criteria which determine whether an HTTP request or failure should be routed
 to a handler.

 @class
*/
var Route = function(j_val) {

  var j_route = j_val;
  var that = this;

  /**
   Add an HTTP method for this route. By default a route will match all HTTP methods. If any are specified then the route
   will only match any of the specified methods

   @public
   @param method {Object} the HTTP method to add
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.method = function(method) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      j_route["method(io.vertx.core.http.HttpMethod)"](io.vertx.core.http.HttpMethod.valueOf(__args[0]));
      return that;
    } else utils.invalidArgs();
  };

  /**
   Set the path prefix for this route. If set then this route will only match request URI paths which start with this
   path prefix. Only a single path or path regex can be set for a route.

   @public
   @param path {string} the path prefix
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.path = function(path) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      j_route["path(java.lang.String)"](path);
      return that;
    } else utils.invalidArgs();
  };

  /**
   Set the path prefix as a regular expression. If set then this route will only match request URI paths, the beginning
   of which match the regex. Only a single path or path regex can be set for a route.

   @public
   @param path {string} the path regex
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.pathRegex = function(path) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      j_route["pathRegex(java.lang.String)"](path);
      return that;
    } else utils.invalidArgs();
  };

  /**
   Add a content type produced by this route. Used for content based routing.

   @public
   @param contentType {string} the content type
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.produces = function(contentType) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      return utils.convReturnVertxGen(j_route["produces(java.lang.String)"](contentType), Route);
    } else utils.invalidArgs();
  };

  /**
   Add a content type consumed by this route. Used for content based routing.

   @public
   @param contentType {string} the content type
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.consumes = function(contentType) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'string') {
      j_route["consumes(java.lang.String)"](contentType);
      return that;
    } else utils.invalidArgs();
  };

  /**
   Specify the order for this route. The router tests routes in that order.

   @public
   @param order {number} the order
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.order = function(order) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='number') {
      j_route["order(int)"](order);
      return that;
    } else utils.invalidArgs();
  };

  /**
   Specify this is the last route for the router.

   @public

   @return {Route} a reference to this, so the API can be used fluently
   */
  this.last = function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_route["last()"]();
      return that;
    } else utils.invalidArgs();
  };

  /**
   Specify a request handler for the route. The router routes requests to handlers depending on whether the various
   criteria such as method, path, etc match. There can be only one request handler for a route. If you set this more
   than once it will overwrite the previous handler.

   @public
   @param requestHandler {function} the request handler
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.handler = function(requestHandler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_route["handler(io.vertx.core.Handler)"](function(jVal) {
      requestHandler(utils.convReturnVertxGen(jVal, RoutingContext));
    });
      return that;
    } else utils.invalidArgs();
  };

  /**
   Specify a blocking request handler for the route.
   This method works just like {@link Route#handler} excepted that it will run the blocking handler on a worker thread
   so that it won't block the event loop. Note that it's safe to call context.next() from the
   blocking handler as it will be executed on the event loop context (and not on the worker thread.

   If the blocking handler is ordered it means that any blocking handlers for the same context are never executed
   concurrently but always in the order they were called. The default value of ordered is true. If you do not want this
   behaviour and don't mind if your blocking handlers are executed in parallel you can set ordered to false.

   @public
   @param requestHandler {function} the blocking request handler
   @param ordered {boolean} if true handlers are executed in sequence, otherwise are run in parallel
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.blockingHandler = function() {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_route["blockingHandler(io.vertx.core.Handler)"](function(jVal) {
      __args[0](utils.convReturnVertxGen(jVal, RoutingContext));
    });
      return that;
    }  else if (__args.length === 2 && typeof __args[0] === 'function' && typeof __args[1] ==='boolean') {
      j_route["blockingHandler(io.vertx.core.Handler,boolean)"](function(jVal) {
      __args[0](utils.convReturnVertxGen(jVal, RoutingContext));
    }, __args[1]);
      return that;
    } else utils.invalidArgs();
  };

  /**
   Specify a failure handler for the route. The router routes failures to failurehandlers depending on whether the various
   criteria such as method, path, etc match. There can be only one failure handler for a route. If you set this more
   than once it will overwrite the previous handler.

   @public
   @param failureHandler {function} the request handler
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.failureHandler = function(failureHandler) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] === 'function') {
      j_route["failureHandler(io.vertx.core.Handler)"](function(jVal) {
      failureHandler(utils.convReturnVertxGen(jVal, RoutingContext));
    });
      return that;
    } else utils.invalidArgs();
  };

  /**
   Remove this route from the router

   @public

   @return {Route} a reference to this, so the API can be used fluently
   */
  this.remove = function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_route["remove()"]();
      return that;
    } else utils.invalidArgs();
  };

  /**
   Disable this route. While disabled the router will not route any requests or failures to it.

   @public

   @return {Route} a reference to this, so the API can be used fluently
   */
  this.disable = function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_route["disable()"]();
      return that;
    } else utils.invalidArgs();
  };

  /**
   Enable this route.

   @public

   @return {Route} a reference to this, so the API can be used fluently
   */
  this.enable = function() {
    var __args = arguments;
    if (__args.length === 0) {
      j_route["enable()"]();
      return that;
    } else utils.invalidArgs();
  };

  /**
   If true then the normalised request path will be used when routing (e.g. removing duplicate /)
   Default is true

   @public
   @param useNormalisedPath {boolean} use normalised path for routing?
   @return {Route} a reference to this, so the API can be used fluently
   */
  this.useNormalisedPath = function(useNormalisedPath) {
    var __args = arguments;
    if (__args.length === 1 && typeof __args[0] ==='boolean') {
      j_route["useNormalisedPath(boolean)"](useNormalisedPath);
      return that;
    } else utils.invalidArgs();
  };

  /**
   @return the path prefix (if any) for this route

   @public

   @return {string}
   */
  this.getPath = function() {
    var __args = arguments;
    if (__args.length === 0) {
      return j_route["getPath()"]();
    } else utils.invalidArgs();
  };

  // A reference to the underlying Java delegate
  // NOTE! This is an internal API and must not be used in user code.
  // If you rely on this property your code is likely to break if we change it / remove it without warning.
  this._jdel = j_route;
};

// We export the Constructor function
module.exports = Route;