text:
title: Desktop Virtuale in Windows 10
date: 2017-05-31 16:00:00 +0200
author: Stefano Marzorati
layout: post
permalink: /desktop-virtuali-windows-10/
categories:
  - Windows
tags:
  - desktop
  - virtuale
  - virtual
  - windows
  - 10
---
Creare un nuovo desktop: **Tasto Windows + CTRL + D**
Passare al desktop precedente o successivo: **Tasto Windows + CTRL + Freccia sinistra/destra**
Chiudere il desktop attivo: **Tasto Windows + CTRL + F4**
Avviare la visione dei desktop (Task View): **Tasto Windows + TAB**


text:
EXPMatcherImplementationBegin(finish, (void))

__block LLSignalTestRecorder *actualRecorder = nil;

void (^subscribe)() = ^{
    if(!actualRecorder) {
        actualRecorder = LLRMRecorderForObject(actual);
    }
};

prerequisite(^BOOL{
    return LLRMCorrectClassesForActual(actual);
});

match(^BOOL{
    subscribe();

    return actualRecorder.hasCompleted || actualRecorder.hasErrored;
});

failureMessageForTo(^NSString *{
    if(!LLRMCorrectClassesForActual(actual)) {
        return [LLReactiveMatchersMessageBuilder actualNotCorrectClass:actual];
    }

    return [LLReactiveMatchersMessageBuilder actualNotFinished:actualRecorder];
});

failureMessageForNotTo(^NSString *{
    if(!LLRMCorrectClassesForActual(actual)) {
        return [LLReactiveMatchersMessageBuilder actualNotCorrectClass:actual];
    }
    if(actualRecorder.hasErrored) {
        return [[[[[LLReactiveMatchersMessageBuilder message] actual:actualRecorder] expectedBehaviour:@"not finish"] actualBehaviour:@"finished with error"] build];
    }

    return [[[[[LLReactiveMatchersMessageBuilder message] actual:actualRecorder] expectedBehaviour:@"not finish"] actualBehaviour:@"finished with completion"] build];
});

EXPMatcherImplementationEnd

redpajama_set_name: RedPajamaGithub


text:
opt01: spacemacs ile menüler açılsın

opt02: :Commands ile komutlara erişim

## opt02: :Commands ile komutlara erişim

Error: :Commands yanıt dönmüyor

opt01: yanlışlıkla silmiş olabilirim, git loglarından bakalım

forgit ile önceki commitleri nasıl görüyorduk?

nerede silinmiş bu komut?

``` bash
git grep '\bCommands\b' $(git rev-list --all)
  ##> c2265fdea729a0375af18f6064572af4f84bd284:plugin/my-vim-custom.vim:nnoremap cm :Commands<cr>
git grep '\bcommand! Files\b' $(git rev-list --all)
git grep '\bcommand! Commands\b' $(git rev-list --all)
  ##> empty
```

Bu komut o zaman fzf eklentisi içinde mi tanımlanmıştı acaba?

Fix: fzf ve fzf.vim diye iki tane eklenti var. İkincisini komentlemişim.

``` bash
Plug 'junegunn/fzf', { 'dir': '~/.fzf'}
Plug 'junegunn/fzf.vim'
```

# forgit

https://github.com/wfxr/forgit

Ref: forgit aliases with fzf <url:/Users/mertnuhoglu/.zshrc#tn=forgit aliases with fzf>

``` bash
alias forgit_add=ga						# `git add` selector
alias forgit_log=glo					# `git log` viewer
alias forgit_diff=gd					# `git diff` viewer
alias forgit_ignore=gi				# `.gitignore` generator
...
```


text:
"""
Description     : Simple Python implementation of the Apriori Algorithm
Usage:
    $python apriori.py -f DATASET.csv -s minSupport  -c minConfidence
    $python apriori.py -f DATASET.csv -s 0.15 -c 0.6
"""

import sys

from itertools import chain, combinations
from collections import defaultdict
from optparse import OptionParser

def subsets(arr):
    """ Returns non empty subsets of arr"""
    return chain(*[combinations(arr, i + 1) for i, a in enumerate(arr)])

def returnItemsWithMinSupport(itemSet, transactionList, minSupport, freqSet):
        """calculates the support for items in the itemSet and returns a subset
       of the itemSet each of whose elements satisfies the minimum support"""
        _itemSet = set()
        localSet = defaultdict(int)

        for item in itemSet:
                for transaction in transactionList:
                        if item.issubset(transaction):
                                freqSet[item] += 1
                                localSet[item] += 1

        for item, count in localSet.items():
                support = float(count)/len(transactionList)

                if support >= minSupport:
                        _itemSet.add(item)

        return _itemSet

def joinSet(itemSet, length):
        """Join a set with itself and returns the n-element itemsets"""
        return set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length])

def getItemSetTransactionList(data_iterator):
    transactionList = list()
    itemSet = set()
    for record in data_iterator:
        transaction = frozenset(record)
        transactionList.append(transaction)
        for item in transaction:
            itemSet.add(frozenset([item]))              # Generate 1-itemSets
    return itemSet, transactionList

def runApriori(data_iter, minSupport, minConfidence):
    """
    run the apriori algorithm. data_iter is a record iterator
    Return both:
     - items (tuple, support)
     - rules ((pretuple, posttuple), confidence)
    """
    itemSet, transactionList = getItemSetTransactionList(data_iter)

    freqSet = defaultdict(int)
    largeSet = dict()
    # Global dictionary which stores (key=n-itemSets,value=support)
    # which satisfy minSupport

    assocRules = dict()
    # Dictionary which stores Association Rules

    oneCSet = returnItemsWithMinSupport(itemSet,
                                        transactionList,
                                        minSupport,
                                        freqSet)

    currentLSet = oneCSet
    k = 2
    while(currentLSet != set([])):
        largeSet[k-1] = currentLSet
        currentLSet = joinSet(currentLSet, k)
        currentCSet = returnItemsWithMinSupport(currentLSet,
                                                transactionList,
                                                minSupport,
                                                freqSet)
        currentLSet = currentCSet
        k = k + 1

    def getSupport(item):
            """local function which Returns the support of an item"""
            return float(freqSet[item])/len(transactionList)

    toRetItems = []
    for key, value in largeSet.items():
        toRetItems.extend([(tuple(item), getSupport(item))
                           for item in value])

    toRetRules = []
    for key, value in largeSet.items()[1:]:
        for item in value:
            _subsets = map(frozenset, [x for x in subsets(item)])
            for element in _subsets:
                remain = item.difference(element)
                if len(remain) > 0:
                    confidence = getSupport(item)/getSupport(element)
                    if confidence >= minConfidence:
                        toRetRules.append(((tuple(element), tuple(remain)),
                                           confidence))
    return toRetItems, toRetRules

def printResults(items, rules):
    """prints the generated itemsets sorted by support and the confidence rules sorted by confidence"""
    for item, support in sorted(items, key=lambda (item, support): support):
        print "item: %s , %.3f" % (str(item), support)
    print "\n------------------------ RULES:"
    for rule, confidence in sorted(rules, key=lambda (rule, confidence): confidence):
        pre, post = rule
        print "Rule: %s ==> %s , %.3f" % (str(pre), str(post), confidence)

def dataFromFile(fname):
        """Function which reads from the file and yields a generator"""
        file_iter = open(fname, 'rU')
        for line in file_iter:
                line = line.strip().rstrip(',')                         # Remove trailing comma
                record = frozenset(line.split(','))
                yield record

if __name__ == "__main__":

    optparser = OptionParser()
    optparser.add_option('-f', '--inputFile',
                         dest='input',
                         help='filename containing csv',
                         default=None)
    optparser.add_option('-s', '--minSupport',
                         dest='minS',
                         help='minimum support value',
                         default=0.15,
                         type='float')
    optparser.add_option('-c', '--minConfidence',
                         dest='minC',
                         help='minimum confidence value',
                         default=0.6,
                         type='float')

    (options, args) = optparser.parse_args()

    inFile = None
    if options.input is None:
            inFile = sys.stdin
    elif options.input is not None:
            inFile = dataFromFile(options.input)
    else:
            print 'No dataset filename specified, system with exit\n'
            sys.exit('System will exit')

    minSupport = options.minS
    minConfidence = options.minC

    items, rules = runApriori(inFile, minSupport, minConfidence)

    printResults(items, rules)


text:
// For discussion and comments, see: http://remysharp.com/2009/01/07/html5-enabling-script/
(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while (i--){document.createElement(e[i])}})();

var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {

      if (el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      } else {
        el.addEventListener(type, fn, false);
      }
    };
  } else {
    return function (el, type, fn) {
      if (el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      } else {
        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
      }
    };
  }
})();


text:
namespace content {

MediaStreamTrackExtraData::MediaStreamTrackExtraData(
    webrtc::MediaStreamTrackInterface* track)
    : track_(track) {
}

MediaStreamTrackExtraData::~MediaStreamTrackExtraData() {
}

}  // namespace content


text:
package org.surfnet.oaaas.example.api.resource;

import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import java.security.Principal;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.surfnet.oaaas.example.api.domain.Course;
import org.surfnet.oaaas.example.api.domain.Student;
import org.surfnet.oaaas.example.api.domain.University;

/**
 * Main resource
 *
 */

@Path("/v1/api")
@Produces(MediaType.APPLICATION_JSON)
public class UniversityResource {

  private static final String UNIVERSITY_FOO_JSON = "university-foo-data.json";

  private final ObjectMapper objectMapper = new ObjectMapper().enable(
      DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY).setSerializationInclusion(
      JsonSerialize.Inclusion.NON_NULL);

  private University university;

  public UniversityResource() {
    super();
    init();
  }

  private void init() {
    try {
      university = getObjectMapper().readValue(
          Thread.currentThread().getContextClassLoader().getResourceAsStream(UNIVERSITY_FOO_JSON), University.class);
    } catch (Exception e) {
      throw new RuntimeException(String.format("Unable to parse %s", UNIVERSITY_FOO_JSON), e);
    }
  }

  protected ObjectMapper getObjectMapper() {
    return objectMapper;
  }

  @GET
  @Timed
  @Path("/student")
  public Response getAllStudents(@Auth
  Principal principal) {
    return Response.ok(university.getStudents()).build();
  }

  @GET
  @Timed
  @Path("/student/{studentId}")
  public Response getStudentById(@Auth
  Principal principal, @PathParam("studentId")
  String id) {
    List<Student> students = university.getStudents();
    for (Student student : students) {
      if (student.getId().equals(id)) {
        return Response.ok(student).build();
      }
    }
    return Response.status(Response.Status.NOT_FOUND).build();
  }

  @GET
  @Timed
  @Path("/course")
  public Response getAllCourses(@Auth
  Principal principal) {
    return Response.ok(university.getCourses()).build();
  }

  @GET
  @Timed
  @Path("/course/{courseId}")
  public Response getCourseById(@Auth
  Principal principal, @PathParam("courseId")
  String id) {
    List<Course> courses = university.getCourses();
    for (Course course : courses) {
      if (course.getId().equals(id)) {
        return Response.ok(course).build();
      }
    }
    return Response.status(Response.Status.NOT_FOUND).build();
  }

}


text:
//
//  FDCategory+Implementation.h
//  Feeds
//
//  Created by Ben Vanik on 10/7/08.
//  Copyright 2008 Ben Vanik ( http://www.noxa.org ). All rights reserved.
//

#import <Foundation/Foundation.h>
#import "FDCategory.h"

@interface FDCategory (Implementation)

/**
 * Initializes an instance with the given label.
 * @param label A human-readable label for the category.
 */
- (id) initWithLabel:(NSString*)label;

/**
 * Creates and returns a category with the contents of the given property list.
 * @param plist A serialized category in property list representation.
 */
+ (FDCategory*) categoryWithContentsOfPropertyList:(NSDictionary*)plist;

/**
 * Serialize the object to a property list.
 * @return The object in property list format.
 */
- (NSDictionary*) propertyList;

@end


text:
/* jshint sub: true */
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / @brief node-request-style HTTP requests
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2015 triAGENS GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Alan Plum
// / @author Copyright 2015, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

const internal = require('internal');
const Buffer = require('buffer').Buffer;
const httperr = require('http-errors');
const is = require('@arangodb/is');
const querystring = require('querystring');
const qs = require('qs');
const url = require('url');

class IncomingResponse {
  throw (msg) {
    if (this.status >= 400) {
      throw Object.assign(
        httperr(this.status, msg || this.message),
        {details: this}
      );
    }
  }
  constructor (res, encoding, json) {
    this.status = this.statusCode = res.code;
    this.message = res.message;
    this.headers = res.headers ? res.headers : {};
    this.body = this.rawBody = res.body;
    if (this.body && encoding !== null) {
      this.body = this.body.toString(encoding || 'utf-8');
      if (json !== false) {
        try {
          this.json = JSON.parse(this.body);
        } catch (e) {
          this.json = undefined;
        }
      }
    }
  }
  toString () {
    return this._PRINT({output: ''}).output;
  }
  _PRINT (ctx) {
    const MAX_BYTES = 100;
    ctx.output += `[${this.constructor.name} ${this.status} ${this.message} `;
    if (!this.body || !this.body.length) {
      ctx.output += 'empty';
    } else {
      ctx.output += `${this.body.length} bytes `;
      if (typeof this.body !== 'string') {
        ctx.output += '<binary>';
      } else if (this.body.length <= MAX_BYTES) {
        ctx.output += `"${this.body}"`;
      } else {
        const offset = (this.body.length - MAX_BYTES) / 2;
        ctx.output += `"…${
          this.body.slice(offset, offset + MAX_BYTES)
          .replace('\n', '\\n')
          .replace('\r', '\\r')
          .replace('\t', '\\t')
        }…"`;
      }
    }
    ctx.output += ']';
  }
}

function querystringify (query, useQuerystring) {
  if (!query) {
    return '';
  }
  if (typeof query === 'string') {
    return query.charAt(0) === '?' ? query.slice(1) : query;
  }
  return (useQuerystring ? querystring : qs).stringify(query)
    .replace(/[!'()*]/g, function (c) {
      // Stricter RFC 3986 compliance
      return '%' + c.charCodeAt(0).toString(16);
    });
}

function request (req) {
  if (typeof req === 'string') {
    req = {url: req, method: 'GET'};
  }

  let path = req.url || req.uri;
  if (!path) {
    throw new Error('Request URL must not be empty.');
  }

  let pathObj = typeof path === 'string' ? url.parse(path) : path;
  if (pathObj.auth) {
    let auth = pathObj.auth.split(':');
    req = Object.assign({
      auth: {
        username: decodeURIComponent(auth[0]),
        password: decodeURIComponent(auth[1])
      }
    }, req);
    delete pathObj.auth;
  }
  let query = typeof req.qs === 'string' ? req.qs : querystringify(req.qs, req.useQuerystring);
  if (query) {
    pathObj.search = query;
  }
  path = url.format(pathObj);

  if (path.indexOf("http:///") === 0) {
    path = path.replace("http:///", "/");
  }

  let contentType;
  let body = req.body;
  if (req.json) {
    body = JSON.stringify(body);
    contentType = 'application/json';
  } else if (typeof body === 'string') {
    contentType = 'text/plain; charset=utf-8';
  } else if (typeof body === 'object' && body instanceof Buffer) {
    contentType = 'application/octet-stream';
  } else if (!body) {
    if (req.form) {
      contentType = 'application/x-www-form-urlencoded';
      body = typeof req.form === 'string' ? req.form : querystringify(req.form, req.useQuerystring);
    } else if (req.formData) {
      // contentType = 'multipart/form-data'
      // body = formData(req.formData)
      throw new Error('Multipart form encoding is currently not supported.');
    } else if (req.multipart) {
      // contentType = 'multipart/related'
      // body = multipart(req.multipart)
      throw new Error('Multipart encoding is currently not supported.');
    }
  }

  const headers = {};

  if (contentType && !headers['content-type']) {
    headers['content-type'] = contentType;
  }

  if (req.headers) {
    Object.keys(req.headers).forEach(function (name) {
      headers[name.toLowerCase()] = req.headers[name];
    });
  }

  let options = {
    method: (req.method || 'get').toUpperCase(),
    headers: headers,
    returnBodyAsBuffer: true,
    returnBodyOnError: req.returnBodyOnError !== false
  };
  if (is.existy(req.timeout)) {
    options.timeout = req.timeout;
  }
  if (is.existy(req.followRedirect)) {
    options.followRedirects = req.followRedirect; // [sic] node-request compatibility
  }
  if (is.existy(req.maxRedirects)) {
    options.maxRedirects = req.maxRedirects;
  } else {
    options.maxRedirects = 10;
  }
  if (req.sslProtocol) {
    options.sslProtocol = req.sslProtocol;
  }
  if (is.existy(req.auth)) {
    if (is.existy(req.auth.jwt)) {
      options.jwt = req.auth.jwt;
    } else if (is.existy(req.auth.bearer)) {
      options.jwt = req.auth.bearer;
    } else if (is.existy(req.auth.username)) {
      options.username = req.auth.username;
      options.password = req.auth.password || "";
    }
  }
  let result = internal.download(path, body, options);

  return new IncomingResponse(result, req.encoding, req.json);
}

module.exports = request;
request.request = request;
request.Response = IncomingResponse;

for (const method of ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT']) {
  request[method.toLowerCase()] = function (url, options) {
    if (typeof url === 'object') {
      options = url;
    } else if (typeof url === 'string') {
      options = Object.assign({}, options, {url});
    }
    return request(Object.assign({method}, options));
  };
}


text:
Webos.Manager = function WManager() {
	Webos.Observable.call(this);
	this._name = 'Manager';
	Webos.Manager._list[this._name] = this;
};
Webos.Manager.prototype = {};
Webos.Manager._list = {};
Webos.Manager.get = function(name) {
	return Webos.Manager._list[name];
};
Webos.inherit(Webos.Manager, Webos.Observable);


text:
;(function($){
  var anim_dur = 300;
  var lazy_class = 'lazy';
  var lazy_bg_class = 'lazy-bg';
  var eager_class = 'eager';
  var working_class = 'working';
  var done_class = 'done';
  var image_attr = 'data-image';
  var non_empty_image_attr = '[' + image_attr + '!=""]';
  var is_webkit = /webkit/.test(navigator.userAgent.toLowerCase());
  var $body = null;

  var throttle_check_images = $.throttle(function(){
    check_images();
  }, 200);

  $(function(){
    $body = $(is_webkit ? 'body' : 'html');
    $(window)
      .on('load', window_load)
      .on('scroll.' + lazy_class, throttle_check_images)
      .on('resize.' + lazy_class, throttle_check_images);

    // Check slide images immediately
    check_images('ul.slides');
  });

  function window_load() {
    setTimeout(function(){
      check_images();
    }, anim_dur);
  }
  function check_images(container_selector) {
    if(container_selector === undefined || container_selector === null) {
      container_selector = '';
    } else {
      container_selector += ' ';
      if(!$($.trim(container_selector)).length) return false;
    }
    var unloaded_image_selector = container_selector
      + 'img.' + lazy_class
      + ':not(.' + working_class + ')'
      + ':not(.' + done_class + ')'
      + non_empty_image_attr;
    var unloaded_bg_selector = container_selector
      + '.' + lazy_bg_class
      + ':not(.' + working_class + ')'
      + ':not(.' + done_class + ')'
      + non_empty_image_attr;
    var ignore_range = !!container_selector.length;

    var $eager = $('.' + eager_class + non_empty_image_attr);
    if($eager.length) {
      $eager.filter(unloaded_image_selector).lazyLoad(ignore_range);
      $eager.filter(unloaded_bg_selector).lazyLoadBg(ignore_range);
      return false;
    }
    var $lazy_imgs = $(unloaded_image_selector);
    var $lazy_bgs = $(unloaded_bg_selector);
    if(!$lazy_imgs.length && !$lazy_bgs.length) {
      $(window)
        .off('scroll.' + lazy_class)
        .off('resize.' + lazy_class);
    }
    $lazy_imgs.each(function(){
      $(this).lazyLoad(ignore_range);
    });
    $lazy_bgs.each(function(){
      $(this).lazyLoadBg(ignore_range);
    });
  }
  function is_in_range($obj, lookaround) {
    if(!$obj.is(':visible')) return false;

    // Lookaround scales the region to be scanned for unloaded images
    // 0 = Only load images that are visible in the viewport (even a single pixel row)
    // 0.5 = Look outside of the viewport by an additional 50% of its height
    var obj_top = $obj.offset().top;
    var obj_height = $obj.innerHeight();
    var window_top = $body.scrollTop();
    var window_height = $(window).height();

    var top_in_range = (obj_top < window_top + (window_height * (1 + lookaround)));
    var bottom_in_range = (obj_top + obj_height > window_top - (window_height * lookaround));
    return (top_in_range && bottom_in_range);
  }

  $.fn.lazyLoad = function(ignore_range){
    var $img = this;
    if($img.hasClass(done_class)) return false;
    if(!ignore_range && !is_in_range($img, 0.25)) return false;

    var image_url = $img.attr(image_attr);
    var new_image = new Image();
    $(new_image).load(function(){
      $img
        .attr('src', image_url)
        .removeAttr('style ' + image_attr)
        .removeClass(working_class)
        .addClass(done_class);
    }).attr('src', image_url);
    $img.addClass(working_class).removeClass(lazy_class);
  };
  $.fn.lazyLoadBg = function(ignore_range, remove_when_loaded){
    var $bg = this;
    if($bg.hasClass(done_class)) return false;
    if(!ignore_range && !is_in_range($bg, 0.25)) return false;

    $bg.addClass(working_class);
    var image_url = $bg.attr(image_attr);

    var new_image = new Image();
    $(new_image).on('load', function(){
      $bg
        .css('background-image', 'url(\'' + image_url + '\')')
        .removeAttr(image_attr)
        .removeClass(working_class)
        .addClass(done_class);
      if($bg.hasClass(eager_class)) {
        $bg.removeClass(eager_class);
        check_images();
      }

      // Optionally remove .lazy-bg elements if .loaded container has
      // a background image that should be displayed once all other
      // backgrounds have loaded
      if(remove_when_loaded) {
        setTimeout(function(){
          var $container = $bg.parent();
          if(!$container.children(
            '.' + lazy_bg_class
            + ':not(' + working_class + ')'
            + ':not(' + done_class + ')'
          ).length) {
            $container.addClass('loaded').children('.' + lazy_bg_class).remove();
          }
        }, anim_dur);
      }
    }).attr('src', image_url);
  };
})(jQuery);


text:
LINTIGNOREDOT='internal/features.+should not use dot imports'
LINTIGNOREDOC='service/[^/]+/(api|service)\.go:.+(comment on exported|should have comment or be unexported)'

help:
	@echo "Please use \`make <target>' where <target> is one of"
	@echo "  api_info                to print a list of services and versions"
	@echo "  build                   to go build the SDK"
	@echo "  deps                    to go get the SDK dependencies"
	@echo "  docs                    to build SDK documentation"
	@echo "  generate                to go generate and make services"
	@echo "  generate-protocol-test  to generate protocol tests"
	@echo "  integration             to run integration tests"
	@echo "  lint                    to lint the SDK"
	@echo "  services                to generate services"
	@echo "  unit                    to run unit tests"

default: generate

generate-protocol-test:
	go generate ./internal/protocol/...

generate-test: generate-protocol-test

generate:
	go generate ./internal/endpoints
	@make services

services:
	go generate ./service

integration: deps
	go test ./internal/test/integration/... -tags=integration
	gucumber

lint: deps
	@echo "golint ./..."
	@lint=`golint ./...`; \
	lint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOT} -e ${LINTIGNOREDOC}`; \
	echo "$$lint"; \
	if [ "$$lint" != "" ]; then exit 1; fi

unit: deps build lint
	go test ./...

build:
	go build ./...

docs:
	rm -rf doc && bundle install && bundle exec yard

deps:
	@go get ./...
	@go get github.com/lsegal/gucumber/cmd/gucumber
	@go get github.com/golang/lint/golint

api_info:
	@go run internal/model/cli/api-info/api-info.go


text:
module ZenfolioAPI
	class Authentication

		attr_accessor :token

		# Connect to the Zenfolio API
		#
		# @author David Slone
		def initialize username,password
			@api_url = "http://api.zenfolio.com/api/1.7/zfapi.asmx"
			@username = username
			@password = password

			connection = ZenfolioAPI::HTTP.new()
			@response = connection.POST('AuthenticatePlain', [username, password])

			# Unable to authenticate the user. Return error code from server
			raise ZenfolioAPI::ZenfolioAPIAuthenticationError, @response['error'] if !@response['error'].nil?

			@token = @response['result']
		end
	end
end


text:
/* Charon
   Index libprep documents by [projectid, sampleid].
   Value: 1.
*/
function(doc) {
    if (doc.charon_doctype !== 'libprep') return;
    emit([doc.projectid, doc.sampleid], 1);
}


text:
paasta\_tools.api.views.flink module
====================================

.. automodule:: paasta_tools.api.views.flink
   :members:
   :undoc-members:
   :show-inheritance:


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.muatik</groupId>
    <artifactId>spring-boot-template</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
        </dependency>

    </dependencies>

</project>


text:
Puppet::Type.newtype(:cisco_interface) do
  @doc = "Manages a Cisco Network Interface.

  Any resource dependency should be run before the interface resource.

  cisco_interface {\"<interface>\":
    ..attributes..
  }

  <interface> is the complete name of the interface.

  Example:
    cisco_interface {\"Ethernet1/15\":
     shutdown                     => false,
     description                  => \"switched port\",
     switchport_mode              => access,
     access_vlan                  => 2,
     switchport_autostate_exclude => true,
     switchport_vtp               => true,
    }
    cisco_interface { \"Ethernet1/16\" :
     shutdown                     => true,
     description                  => \"routed port\",
     ipv4_address                 => \"192.168.1.1\",
     ipv4_netmask_length          => 24,
     ipv4_redirects               => true,
     ipv4_proxy_arp               => true,
     negotiate_auto               => true,
    }
    cisco_interface { \"loopback42\" :
     description                  => \"logical interface\",
     shutdown                     => true,
    }
    cisco_interface { \"loopback43\" :
     ensure                       => absent,
     # ensure will create or destroy a logical interface. If not specified
     # then the default behavior is to attempt to create the interface.
    }
    cisco_interface {\"Vlan98\":
     shutdown                     => true,
     description                  => \"svi interface\",
     svi_autostate                => true,
     svi_management               => true,
    }"

  ###################
  # Resource Naming #
  ###################

  # Parse out the title to fill in the attributes in these
  # patterns. These attributes can be overwritten later.
  def self.title_patterns
    identity = lambda { |x| x }
    patterns = []

    # Below pattern matches both parts of the full composite name.
    patterns << [
      /^(\S+)/,
      [
        [:interface, identity]
      ]
    ]
    return patterns
  end

  newparam(:interface, :namevar => :true) do
    desc "Name of the interface on the network element. Valid values are string."

    validate { |name|
      if name == "mgmt0"
        fail("Stay away from the management port.")
      end # if
    }

    munge { |value|
      value.downcase
    }
  end # param name

  #######################################
  # Basic / L2 Configuration Attributes #
  #######################################

  ensurable

  newproperty(:description) do
    desc "Description of the interface. Valid values are string, keyword
         'default'."

    munge { |value|
      value = :default if value == 'default'
      value
    }

  end # property description

  newproperty(:shutdown) do
    desc "Shutdown state of the interface."

    newvalues(:true, :false, :default)
  end # property shutdown

  newproperty(:switchport_mode) do
    desc "Switchport mode of the interface. To make an interface L3, set
          switchport_mode to 'disabled'. "

    newvalues(
      :disabled,
      :access,
      :tunnel,
      :fex_fabric,
      :trunk,
      :default)

  end # property switchport_mode

  newproperty(:access_vlan) do
    desc "The VLAN ID assigned to the interface. Valid values are
          integer, keyword 'default'."

    munge { |value|
      value = :default if value == 'default'
      begin
        value = Integer(value) unless value == :default
      rescue
        fail "access_vlan must be a valid integer, or default."
      end
      value
    }

  end # property access_vlan

  newproperty(:switchport_autostate_exclude) do
    desc "Exclude this port for the SVI link calculation."

    newvalues(:true, :false, :default)
  end # property switchport_autostate_exclude

  newproperty(:switchport_vtp) do
    desc "Enable or disable VTP on the interface."

    newvalues(:true, :false, :default)
  end # property switchport vtp

  newproperty(:negotiate_auto) do
    desc "Enable/Disable negotiate auto on the interface."

    newvalues(:true, :false, :default)
  end # property negotiate_auto

  ########################################
  # Begin L3 interface config attributes #
  ########################################

  newproperty(:ipv4_proxy_arp) do
    desc "<L3 attribute> Enables or disables proxy arp on the
          interface."

    newvalues(:true, :false, :default)
  end # property ipv4_proxy_arp

  newproperty(:ipv4_redirects) do
    desc "<L3 attribute> Enables or disables sending of IP redirect
          messages."

    newvalues(:true, :false, :default)
  end # property ipv4_redirects

  newproperty(:ipv4_address) do
    desc "<L3 attribute> IP address of the interface. Valid values are
          string, keyword 'default'."

    munge { | value |
      value = :default if value == 'default'
      valid_ipaddr = true
      begin
        if value != :default
          tmp_value = IPAddr.new(value)
          # check whether it is ipv4 address
          valid_ipaddr = tmp_value.ipv4?
        end
      rescue
        valid_ipaddr = false
      end
      # fail if it is not valid ipv4 address
      fail("ipv4_address - #{@resource[:ipv4_address]} must be " +
           "either a valid IPv4 address string or 'default'.") if
           value != :default and valid_ipaddr == false
      value
    }
  end # property ipv4_address

  newproperty(:ipv4_netmask_length) do
    desc "<L3 attribute> Network mask length of the IP address on the
          interface. Valid values are integer, keyword 'default'."

    munge { |value|
      begin
        value = Integer(value) unless value == :default
      rescue
        fail "Network mask length must be a valid integer."
      end
      fail("ipv4_netmask_length must be an integer between 0 and 32") if
           (value != :default) and (value < 0 or value > 32)
      value
    }
  end # property ipv4_netmask_length

  newproperty(:vrf) do
    desc "<L3 attribute> VRF member of the interface. Valid values
          are string, keyword 'default'."

    munge { |value|
      value = :default if value == 'default'
      value
    }
  end # property vrf

  # validate ipv4 address and mask combination
  validate do
    if self[:ipv4_address] != :default and
        self[:ipv4_netmask_length] == :default
      fail("The ipv4_netmask_length should have a valid value, " +
           "when ipv4_address has a valid IPv4 address in the manifest")
    end

    if self[:ipv4_address] == :default and
      (!self[:ipv4_netmask_length].nil? and
       self[:ipv4_netmask_length] != :default)
      fail("The ipv4_address should have a valid value, " +
           "when ipv4_netmask_length has a valid value in the manifest")
    end
  end

  #########################################
  # Begin SVI interface config attributes #
  #########################################

  newproperty(:svi_autostate) do
    desc "Enable/Disable autostate on the SVI interface."

    newvalues(:true, :false, :default)
  end # property svi_autostate

  newproperty(:svi_management) do
    desc "Enable/Disable management on the SVI interface."

    newvalues(:true, :false, :default)
  end # property svi_management

  ################
  # Autorequires #
  ################

  autorequire(:cisco_vlan) do |rel_catalog|
    reqs = []
    unless self[:access_vlan].nil? or self[:access_vlan] == :default
      reqs << rel_catalog.catalog.resource('Cisco_vlan', "#{self[:access_vlan]}")
    end # if
    reqs
  end # autorequire vlan

  autorequire(:cisco_vtp) do |rel_catalog|
    reqs = []
    reqs << rel_catalog.catalog.resource('Cisco_vtp')
    reqs # return
  end # autorequire vtp

end # Puppet::Type.newtype


text:
void statement(Token *t) {
  Kind tk = t->kind;
  if (tk == While || tk == Do || tk == Switch) {
    begin_continue_break(tk);
  }
  switch (t->kind) {
  case Break:
    st_break(t);
    break;
  case Continue:
    st_continue(t);
    break;
  case Switch:
    st_switch(t);
    break;
  case Case:
    st_case(t);
    break;
  case Default:
    st_default(t);
    break;
  case For:
    st_for(t);
    break;
  case Do:
    st_do(t);
    break;
  case While:
    st_while(t);
    break;
  case If:
    st_if(t);
    break;

  case Printf: case Exit:
    // TODO : Built-in fucntion, no returns
    st_build_in_void(t);
    break;
  case Input:
    // TODO : Build-in function, non-void returns
    st_build_in(t);
    break;
  case Lbrace:
    block(t, NULL);
    break;
  case Semicolon:
    nextToken(t, 0);
    break;
  case Ident: case IntNum: case Mul: case Incre: case Decre: case Return:
  case Int: case Float: case Char: case Double: case Short:
  case Struct: case Typedef: case Static: case Const:
  case IntP: case FloatP: case CharP: case DoubleP: case ShortP:// TODO : enhance here
    expr_with_check(t, 0, ';');
    break;
  case EOF_token:
    error("unknown error : EOF");
    return;
  default:
    error("unknown statement or expression");
    return;
  }
  if (tk == While || tk == Do || tk == Switch || tk == For) {
    end_continue_break();
  }
}

void st_break(Token *t) {
  if (loopNest_ct == 0) {
    error("no corresponding statement for 'break'");
  }
  // set jump to loop end
  genCode2(JMP, NO_FIX_BREAK_ADDR);
  loopNest[loopNest_ct-1].has_break = 1;
  checkNxtTokenKind(';');
  nextToken(t, 0);
  return;
}

void st_continue(Token *t) {
  if (loopNest_ct == 0) {
    error("no corresponding statement for 'continue'");
  }
  // set jump to loop top
  GEN_JMP_TOP(get_loop_top());
  checkNxtTokenKind(';');
  nextToken(t, 0);
  return;
}

void st_switch(Token *t) {
  int table_addr, end;
  nextToken(t, 0);
  expr_with_check(t, '(', ')');
  // jump to condition table check (1)
  GEN_JMP_BUTTOM(table_addr); // TODO : need to change name
  begin_switch(); // initialize
  statement(t);
  // jump to end of switch (2)
  GEN_JMP_BUTTOM(end);
  // set label (1) for condition table
  backpatch(table_addr, code_ct);
  end_switch(); // apply gathered case list as table
  // set label (2)
  backpatch(end, code_ct);
  return;
}

void st_case(Token *t) {
  nextToken(t, 0);
  // pick up const value for condition check
  // TODO : suspicious
  if (!is_const_expr()) {
    error("switch condition must be const value");
  } else if (switchNest_ct == 0) {
    error("no corresponding switch for 'case'");
  }

  expr_with_check(t, 0 , ':');
  int val;
  if (codes[code_ct-1].opcode == LDI) {
    val = codes[code_ct-1].opdatai; // TODO : suspicious
  }
  code_ct--; // remove LDI and its const
  int i;
  for (i = switchNest[switchNest_ct-1].case_list_st_addr; i < caseList_ct; i++) {
    if (caseList[i].value == val) {
      error("case condition is duplicating");
    }
  }
  if (caseList_ct >= MAX_CASE_SIZ) {
    error("too many cases");
  }
  caseList[caseList_ct].value = val;
  // caseList[i].address =
  caseList[caseList_ct++].address = code_ct;
  statement(t);
  return;
}

void st_default(Token *t) {
  if (switchNest_ct == 0) {
    error("no corresponding switch for 'default'");
  }
  // TODO : 0 is danger. -1 should be applied as initialization
  if (switchNest[switchNest_ct-1].default_addr != -1) {
    error("multiple 'default'");
  }
  // set address of switchNest[switchNest_ct].default_addr = ;
  switchNest[switchNest_ct-1].default_addr = code_ct;
  if (!checkNxtTokenKind(':')) {
    error("end ':' is missing");
  }
  nextToken(t, 0); nextToken(t, 0);
  statement(t);
}

void st_while(Token *t) {
  int loop_top, loop_buttom;
  nextToken(t, 0); // point at -> '('
  // set label to condition check. (1)
  LABEL_TOP(loop_top);
  expr_with_check(t, '(', ')');
  // jump to label (2) when condition is false.
  GEN_JPF_BUTTOM(loop_buttom);
  statement(t);
  // jump to label (1) to loop again
  GEN_JMP_TOP(loop_top);
  // set end label. (2)
  backpatch(loop_buttom, code_ct);
  return;
}

void st_if(Token *t) {
  int top, else_buttom, end_buttom;
  nextToken(t, 0);
  expr_with_check(t, '(', ')');
  // jump to label (1) when condition is false.
  GEN_JPF_BUTTOM(end_buttom);
  statement(t);
  if (t->kind != Else) {
    // set end label. (1)
    backpatch(end_buttom, code_ct);
    return;
  }
  // force jump to label (2) ???? suspicious
  GEN_JMP_BUTTOM(else_buttom);
  // set end label. (1)
  backpatch(end_buttom, code_ct);
  nextToken(t, 0); // point at -> 'if'?
  statement(t);
  // set end label. (2)
  backpatch(else_buttom, code_ct);
  return;
}

void st_do(Token *t) {
  int loop_top, loop_buttom;
  nextToken(t, 0); // point at -> '{'
  // set label to loop. (1)
  LABEL_TOP(loop_top);
  statement(t);
  if (t->kind == While) {
    nextToken(t, 0); //-> condition
    expr_with_check(t, '(', ')');
    checkNxtTokenKind(Semicolon);
    nextToken(t, 0);
    // jump to label (1) when condition is True.
    GEN_JPT_BUTTOM(loop_top);
  } else {
    error("'do' statement needs 'while'");
  }
}

void st_for(Token *t) {
  int loop_top, loop_buttom, inst_top, exp_label;
  nextToken(t, 0); nextToken(t, 0);
  if (t->kind == ';') {
    // no expr 1
    nextToken(t, 0);
  } else {
    expr_with_check(t, 0, ';');
  }

  // set label to loop. (1)
  LABEL_TOP(loop_top);
  if (t->kind == ';') {
    // no expr 2
    genCode2(LDI, 1); // true
    nextToken(t, 0);
  } else {
    expr_with_check(t, 0, ';');
  }
  // jump to end if false (3)
  GEN_JPF_BUTTOM(loop_buttom);
  // jump to statement (2)
  GEN_JMP_BUTTOM(inst_top);

  // set label to increment (4)
  begin_continue_break();
  LABEL_TOP(exp_label);
  if (t->kind == ')') {
    // no expr 3
    nextToken(t, 0);
  } else {
    expr_with_check(t, 0, ')');
  }
  // jump to label (1)
  GEN_JMP_TOP(loop_top);

  // set label (2)
  backpatch(inst_top, code_ct);
  statement(t);
  // jump to label (4)
  GEN_JMP_TOP(exp_label);
  // set label end (3)
  backpatch(loop_buttom, code_ct);
  return;
}

void st_build_in_void(Token *t) {
  return;
}

void st_build_in(Token *t) {
  return;
}

void begin_switch() {
  if (switchNest_ct >= MAX_SWITCH_NEST_SIZ) {
    error("switch is nesting over limitation");
  }
  switchNest[switchNest_ct].default_addr = -1;
  switchNest[switchNest_ct++].case_list_st_addr = caseList_ct;
}

void end_switch() {
  int i, st = switchNest[switchNest_ct-1].case_list_st_addr;
  for (i = st; i < caseList_ct; i++) {
    // compare caseList[i].value and stack top?
    genCode2(EQCMP, caseList[i].value);
    // jump to caseList[i].addr if true
    genCode2(JPT, caseList[i].address);
  }
  // TODO : remove top comparison result?
  genCode1(DEL);
  if (switchNest[switchNest_ct-1].default_addr != -1) {
    // when this nest has default
    // jump to switch_nest[switchNest_ct].default_addr
    genCode2(JMP, switchNest[switchNest_ct-1].default_addr);
  }
  caseList_ct = st;
  switchNest_ct--;
}

void begin_continue_break(Kind k) {
  if (loopNest_ct >= MAX_LOOP_NEST_SIZ) {
    error("loop nest exceeds limits");
  }
  loopNest[loopNest_ct].st_kind = k;
  loopNest[loopNest_ct].loop_top = code_ct;
  loopNest[loopNest_ct++].has_break = 0;
}

void end_continue_break() {
  if (loopNest[loopNest_ct-1].has_break)
    // set loop top label
    backpatch_break(loopNest[loopNest_ct-1].loop_top);
  loopNest_ct--;
}

int get_loop_top() {
  int i;
  // TODO : check textbook is using i > 0
  for (i = loopNest_ct-1; i >=0 ; i--) {
    if (loopNest[i].st_kind != Switch)
      return loopNest[i].loop_top;
  }
  error("no associating loop");
}


text:
myControllers.controller('firstAidsCtrl', function($scope, $ionicLoading) {
    startDB();
    $scope.playlists = [];
    ///////////  Retrieve All Task ////////////////
    retrieveAllTask();

    function retrieveAllTask() {
        $ionicLoading.show({
            template: 'Loading...'
        });
        console.log('Start retrive all task transaction.');
        db.transaction(retrieveAllTaskTransaction, transaction_error);

    }

    function retrieveAllTaskTransaction(tx) {
        tx.executeSql('SELECT * FROM Emergency', [], retrieveAllTaskSuccess, retrieveAllTaskError);
    }

    function retrieveAllTaskSuccess(tx, results) {

        var len = results.rows.length;

        console.log("Tasks amount: " + len);

        if (len == 0) {
            //$('#listContainer').html('loading...');
        } else {
            for (var i = 0; i < len; i++) {
                var item = {
                    title: results.rows.item(i).EmerName,
                    id: results.rows.item(i).EmerCode
                }
                $scope.playlists.push(item);
            }
        }
        $ionicLoading.hide();
        console.log($scope.playlists);
    }

    function retrieveAllTaskError(err) {
        navigator.notification.alert("Error processing SQL: " + err.code);
    }

    /////////// End Retrieve All Task ////////////////
});


text:
set -u # This prevents running the script if any of the variables have not been set
set -e # Exit if error is detected during pipeline execution

source ../../setenv-global.sh
print_header "Sensor simulator"

TEMP_DATA=$(pwd)/tmp
INSTALL_FLAG=$TEMP_DATA/install.marker  # Location where the install flag is set to avoid repeated installs
mkdir -p $TEMP_DATA

if [[ ! -f "$INSTALL_FLAG" ]]; then
    install_node
    touch ${INSTALL_FLAG}
fi

create_gcs_camera_bucket

if [ $# -eq 1 ]; then
    export TEST_IMAGE_FILE=$1
else
    export TEST_IMAGE_FILE=""
fi

export GOOGLE_APPLICATION_CREDENTIALS=${SERVICE_ACCOUNT_SECRET}

# Local directory with test images
export TEST_IMAGE_FOLDER=simulation-images
# Delay in seconds to send test messages
export DELAY=1
# How many test messages to send - do not forget to have proper number of test images, otherwise it will circle around and repeat many times
export NUM_ITERATIONS=1

echo "TEST_IMAGE_FILE='$TEST_IMAGE_FILE'"
cd js
npm start

print_footer "Sensor simulator has completed sending test messages."


text:
<html>
<head>
    <title>Simple shop</title>
    <meta charset='utf-8'/>
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport"
            content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0"/>
    <meta name="format-detection" content="telephone=no"/>
</head>
<body>
</body>
<script src="/src/bundle.js"></script>
</html>


text:
// zap.c :
//
// This program is designed to be a robust network performance test tool.
//
// It works on a controller/server model. The controller sends commands to the servers instructing them
// to send data to each other. The results of these tests are sent back to the controller to be used there.
//
// The basic test setup is as follows:
//
// 1.  Server X is started, listens on a well known TCP port.
// 2.  Server Y is started.
// 3.  Controller A is started, and configured by user to run a test. Controller chooses a global test ID ( TID ) for this test.
// 4.  Controller A opens a control TCP connection to Server X for test TID.
// 5.  Controller A opens a control TCP connection to Server Y for test TID.
// 6.  Controller A configures Server X to open a TCP connection to Server Y for test TID.
// 7.  Controller A configures Server X to send a UDP datagram to Server Y for test TID.
//     ( establishes NAT, in case data must flow the other way )
// *   Controller A configures Server <RX> to be ready for data reception.
// 8.  Controller A configures Server <TX> to send data to server <RX>
//     This data may be TCP/UDP/Batched in a variety of forms.
// 9.  Server Y periodically ( configurable ) sends performance updates to Controller A.
//    ... test runs ...
// 10. Controller A may, at any time, abort the test.
//    ... test runs ...
// 11. The controller finishes the test when it feels like it.
//     The Servers transmit/receive as much data as they were told to.
//
// Random notes:
//
// * IP addresses in unsigned __int32 form are ALWAYS network byte order.
//

#include "../zaplib/zaplib.h"
#include "../zaplib/error.h"

zap_config_t *pcfg;

#define		INFO	0
#define		ERROR	1

// Prototypes
unsigned __int32 get_stats( zap_history_t *history, double percentile );
void gather_stats( zap_history_t *history, unsigned __int32 value );

// Generate an approximately unique test id.
unsigned __int32 zap_generate_tid( void )
{
	time_t	tv;

	time( &tv );
	return ( unsigned __int32 )tv;
}

int compare( const void *d1, const void *d2 )
{
	unsigned __int32 *data1 = ( unsigned __int32 * )d1;
	unsigned __int32 *data2 = ( unsigned __int32 * )d2;

	if ( *data1 < *data2 ){
		return -1;
	}
	if ( *data1 > *data2 ){
		return 1;
	}

	return 0;
}
int zap_log_error(zap_config_t *config, char *msg, int type)
{
	FILE            *fileio;

	if(config->debugfile) {
		fileio = fopen( config->debugfile, "a+" );
		if ( !fileio ) {
			fprintf( stderr, "Error, file probably open by another application.\n" );
			return 1;
		}
		if(type == ERROR) {
			fprintf( fileio, "[ERROR]: %s", msg);
		}
		else {
			fprintf( fileio, "[INFO]: %s", msg);
		}

		fprintf( fileio, "\n");
		fclose( fileio );
	}
	return 0;

}
/*This function uses to dump the report to file from start_point to end_point
It just uses for -D option
*/
int zap_debug_dump_file( zap_config_t *config,
						  zap_performance_frame_t *perf,
						  zap_performance_frame_t p,
						  const double throughput,
						  const double total,
						  zap_history_t *history)
{
#ifdef WIN32
	__time64_t      timer;
#else
	time_t          timer;
#endif
	double          walk;
	char            time_str[30];
	FILE            *fileio;
	int				i;
	double race[] =	{ 0.0, 0.5, 0.90, 0.95, 0.990, 0.999 };

#ifdef WIN32
	_time64( &timer );
	sprintf( time_str, "%s", _ctime64( &timer ) );
#else
	time( &timer );
	ctime_r(&timer, time_str);
#endif
	// Take off the newline.
	time_str[24] = 0;

	fileio = fopen( config->debugfile, "a+" );

	if ( !fileio ) {
		fprintf( stderr, "Error, file probably open by another application.\n" );
		return 1;
	}

	fprintf( fileio, "%5d: %s->%s %6d=rx %3d=dr %3d=oo %3d=rp %5d=rx in %7.1fms  %6.1fmbps  %6.1f | ",
		p.batch,
		inet_ntoa2( config->txs_ip_address ),
		inet_ntoa2( config->rxs_ip_address[0] ),
		perf->payloads_received,
		perf->payloads_dropped,
		perf->payloads_outoforder,
		perf->payloads_repeated,
		p.payloads_received,
		( double )( ( double )( p.last_payload_timestamp - p.first_payload_timestamp ) ) / 1000.0,
		throughput,
		( p.batch > 0 )? ( total/( p.batch+1 ) ) : ( total ) );

	for ( i = 0; i < ( ( sizeof race ) / sizeof( double ) ); i++ ) {
		fprintf( fileio, "%4.1f ", get_stats( history, race[i] ) / 1000000.0 );
	}
	fprintf( fileio, "\n");
	fclose( fileio );

	return 0;
}

/*This function uses to log the package drop, it just uses for -L option*/
int zap_pkg_drop_dump_file( zap_config_t *config,
						  zap_performance_frame_t *perf)
{
#ifdef WIN32
	__time64_t      timer;
#else
	time_t          timer;
#endif
	double          walk;
	char            time_str[30];
	FILE            *fileio;
	char            delimit=',';
	int				new_file;
	int				i;

#ifdef WIN32
	_time64( &timer );
	sprintf( time_str, "%s", _ctime64( &timer ) );
#else
	time( &timer );
	ctime_r(&timer, time_str);
#endif
	// Take off the newline.
	time_str[24] = 0;

	fileio = fopen( config->logfile, "r" );
	if ( !fileio ) {
		new_file = 1;
	} else {
		new_file = 0;
		fclose( fileio );
	}

	fileio = fopen( config->logfile, "a+" );

	if ( !fileio ) {
		fprintf( stderr, "Error, file probably open by another application.\n" );
		return 1;
	}

	// Dump package drop information.
	if ( new_file ) {
		// If a new file, make the first row have text tags for all the columns

		fprintf( fileio, "Zap Version%c", delimit );
		fprintf( fileio, "Filename%c", delimit );
		fprintf( fileio, "Protocol%c", delimit );

		fprintf( fileio, "Invert Open%c", delimit );
		fprintf( fileio, "Tx IP%c", delimit );
		fprintf( fileio, "Rx IP%c", delimit );
		fprintf( fileio, "Multicast%c", delimit );
		fprintf( fileio, "ToS%c", delimit );

		fprintf( fileio, "Samples%c", delimit );
		fprintf( fileio, "Sample Size%c", delimit );
		fprintf( fileio, "Payload Length%c", delimit );
		fprintf( fileio, "Payload Transmit Delay%c", delimit );

		fprintf( fileio, "Payloads Received%c", delimit );
		fprintf( fileio, "Payloads Dropped%c", delimit );
		fprintf( fileio, "Payloads Repeated%c", delimit );
		fprintf( fileio, "Payloads Outoforder%c", delimit );

		fprintf( fileio, "Date%c", delimit );
		fprintf( fileio, "Notes%c", delimit );
		fprintf( fileio, "Tag%c", delimit );
		fprintf( fileio, "Sub Tag%c", delimit );

		fprintf( fileio, "\n" );
	}

	// Add this test's results to the last row of the file

	fprintf( fileio, "%d.%d%c", ZAP_MAJOR_VERSION, ZAP_MINOR_VERSION, delimit );
	fprintf( fileio, "%s%c", config->logfile, delimit );
	if ( config->station_config.tcp ){
		fprintf( fileio, "tcp%c", delimit );
	} else {
		fprintf( fileio, "udp%c", delimit );
	}

	fprintf( fileio, "%s%c", config->open_reverse ? "On" : "Off", delimit );
	fprintf( fileio, "%s:%s%c", inet_ntoa2( config->txs_ip_address ), inet_ntoa2( config->txs_ip_address_ctl ), delimit );
	for ( i = 0; i < ( int ) config->rxs_count; i++ ){
		fprintf( fileio, "%s:%s", inet_ntoa2( config->rxs_ip_address[i] ), inet_ntoa2( config->rxs_ip_address_ctl[i] ) );
	}
	fprintf( fileio, "%c", delimit );

	fprintf( fileio, "%s%c",	   config->multi_ip_address ? inet_ntoa2( config->multi_ip_address ) : "Off", delimit );
	fprintf( fileio, "%.2hhXh%c", ( char ) config->ip_tos, delimit );

	fprintf( fileio, "%d%c", config->station_config.batches, delimit );
	fprintf( fileio, "%d%c", config->station_config.batch_size, delimit );
	fprintf( fileio, "%d%c", config->station_config.payload_length, delimit );
	fprintf( fileio, "%d%c", config->station_config.payload_transmit_delay, delimit );

	fprintf( fileio, "%d%c", perf->payloads_received, delimit );
	fprintf( fileio, "%d%c", perf->payloads_dropped, delimit );
	fprintf( fileio, "%d%c", perf->payloads_repeated, delimit );
	fprintf( fileio, "%d%c", perf->payloads_outoforder, delimit );

	fprintf( fileio, "%s%c", time_str, delimit );
	fprintf( fileio, "%s%c", config->note,delimit );
	fprintf( fileio, "%s%c", config->tag, delimit );
	fprintf( fileio, "%s%c", config->sub, delimit );
	fprintf( fileio, "\n" );
	fclose( fileio );

	return 0;
}

int zap_control_dump_file( zap_config_t *config,
						  zap_performance_frame_t *perf,
						  zap_history_t *rates,
						  double total )
{
#ifdef WIN32
	__time64_t      timer;
#else
	time_t          timer;
#endif
	double          walk;
	char            time_str[30];
	FILE            *fileio;
	char            delimit=',';
	int				new_file;
	int				i;

#ifdef WIN32
	_time64( &timer );
	sprintf( time_str, "%s", _ctime64( &timer ) );
#else
	time( &timer );
	//sprintf( time_str, "%s", ctime( &timer ) );
	ctime_r(&timer, time_str);
#endif
	// Take off the newline.
	time_str[24] = 0;

	fileio = fopen( config->filename, "r" );
	if ( !fileio ) {
		new_file = 1;
	} else {
		new_file = 0;
		fclose( fileio );
	}

	fileio = fopen( config->filename, "a+" );

	if ( !fileio ) {
		fprintf( stderr, "Error, file probably open by another application.\n" );
		return 1;
	}

	// Dump percentiles.
	if ( new_file ) {
		// If a new file, make the first row have text tags for all the columns

		// WARNING -- other software ( VPT ) may now rely on these text tags for testing automation.
		// Removal of elements or editing of this tag text is discouraged.   Please change VPT if necessary.
		fprintf( fileio, "Zap Version%c", delimit );
		fprintf( fileio, "Filename%c", delimit );
		fprintf( fileio, "Protocol%c", delimit );

		fprintf( fileio, "Invert Open%c", delimit );
		fprintf( fileio, "Tx IP%c", delimit );
		fprintf( fileio, "Rx IP%c", delimit );
		fprintf( fileio, "Multicast%c", delimit );
		fprintf( fileio, "ToS%c", delimit );

		fprintf( fileio, "Samples%c", delimit );
		fprintf( fileio, "Sample Size%c", delimit );
		fprintf( fileio, "Payload Length%c", delimit );
		fprintf( fileio, "Payload Transmit Delay%c", delimit );

		fprintf( fileio, "Payloads Received%c", delimit );
		fprintf( fileio, "Payloads Dropped%c", delimit );
		fprintf( fileio, "Payloads Repeated%c", delimit );
		fprintf( fileio, "Payloads Outoforder%c", delimit );
		//fprintf( fileio, "Avg Throughput%c", delimit );

		fprintf( fileio, "Date%c", delimit );
		fprintf( fileio, "Notes%c", delimit );
		fprintf( fileio, "Tag%c", delimit );
		fprintf( fileio, "Sub Tag%c", delimit );

		// XXX percentiles must match below
		for ( walk = 0.0; walk < 0.991; walk += 0.01 ) {    // 1.0% increments from 0% to 99%
			fprintf( fileio, "%4.1f%%%c", walk*100.0, delimit );
		}
		for ( walk = 0.991; walk < 1.001; walk += 0.001 ) { // 0.1% increments from 99% to 100%
			fprintf( fileio, "%4.1f%%%c", walk*100.0, delimit );
		}
		fprintf( fileio, "\n" );
	}

	// Add this test's results to the last row of the file

	fprintf( fileio, "%d.%d%c", ZAP_MAJOR_VERSION, ZAP_MINOR_VERSION, delimit );
	fprintf( fileio, "%s%c", config->filename, delimit );
	if ( config->station_config.tcp ){
		fprintf( fileio, "tcp%c", delimit );
	} else {
		fprintf( fileio, "udp%c", delimit );
	}

	fprintf( fileio, "%s%c", config->open_reverse ? "On" : "Off", delimit );
	fprintf( fileio, "%s:%s%c", inet_ntoa2( config->txs_ip_address ), inet_ntoa2( config->txs_ip_address_ctl ), delimit );
	for ( i = 0; i < ( int ) config->rxs_count; i++ ){
		fprintf( fileio, "%s:%s", inet_ntoa2( config->rxs_ip_address[i] ), inet_ntoa2( config->rxs_ip_address_ctl[i] ) );
	}
	fprintf( fileio, "%c", delimit );

	fprintf( fileio, "%s%c",	   config->multi_ip_address ? inet_ntoa2( config->multi_ip_address ) : "Off", delimit );
	fprintf( fileio, "%.2hhXh%c", ( char ) config->ip_tos, delimit );

	fprintf( fileio, "%d%c", config->station_config.batches, delimit );
	fprintf( fileio, "%d%c", config->station_config.batch_size, delimit );
	fprintf( fileio, "%d%c", config->station_config.payload_length, delimit );
	fprintf( fileio, "%d%c", config->station_config.payload_transmit_delay, delimit );

	fprintf( fileio, "%d%c", perf->payloads_received, delimit );
	fprintf( fileio, "%d%c", perf->payloads_dropped, delimit );
	fprintf( fileio, "%d%c", perf->payloads_repeated, delimit );
	fprintf( fileio, "%d%c", perf->payloads_outoforder, delimit );
	//fprintf( fileio, "%.1f%c", ( config->station_config.batches>0 )?( total/config->station_config.batches ):0, delimit );

	fprintf( fileio, "%s%c", time_str, delimit );
	fprintf( fileio, "%s%c", config->note,delimit );
	fprintf( fileio, "%s%c", config->tag, delimit );
	fprintf( fileio, "%s%c", config->sub, delimit );
	// XXX percentiles must match above!
	for ( walk = 0.0; walk < .991; walk += 0.01 ) {		// 1.0% increments from 0% to 99%
		fprintf( fileio, "%4.1f%c", get_stats( rates, walk )/1000000.0, delimit );
	}
	for ( walk = 0.991; walk < 1.001; walk += 0.001 ) {	// 0.1% increments from 99% to 100%
		fprintf( fileio, "%4.1f%c", get_stats( rates, walk )/1000000.0, delimit );
	}
	fprintf( fileio, "\n" );
	fclose( fileio );

	return 0;
}

/* -------------------------------------------------------------------
* zap_exit
*
* Quietly exits. This protects some against being called multiple
* times. ( TODO: should use a mutex to ensure ( num++ == 0 ) is atomic. )
* ------------------------------------------------------------------- */

void zap_exit( int inSigno )
{
	static int		num = 0;
	unsigned int	i;

	if ( pcfg != NULL ) {
		for ( i = 0; i < pcfg->rxs_count; i++ ) {
			if ( pcfg->rxs_socket_ctl[i] != INVALID_SOCKET ) {
				shutdown( pcfg->rxs_socket_ctl[i], SHUT_WR );
				closesocket( pcfg->rxs_socket_ctl[i] );
			}
		}

		// Close control connections. ( Implicitly closes data connections. )
		if ( pcfg->txs_socket_ctl != INVALID_SOCKET ) {
			shutdown( pcfg->txs_socket_ctl, SHUT_WR );
			closesocket( pcfg->txs_socket_ctl );
		}
	}

	if ( num++ == 0 ) {
		fflush( 0 );
		exit( 0 );
	}
} /* end sig_exit */

//
// Returns:
//   0 = Normal response processed.
//   1 = Test complete message received.
//  <0 = Error.
int zap_control_process_rx( zap_config_t *config, SOCKET s, zap_history_t *history, zap_performance_frame_t *perf, double* total, double* throughput_array )
{
	static double r[] =		{ 0.0, 0.5, 0.90, 0.95, 0.990, 0.999 };
	const char				*histarr[] = {"0%",
									      "50%",
						                  "90%",
							              "95%",
							              "99%",
							              "99.9%"};
	zap_performance_frame_t p;
	int						i, j, k;
	unsigned __int32		*src, *dst;
	zap_frame_t				*frame;
	double					throughput;
	int                     len, lendst, lensrc;
	char                    buf[15];
	unsigned __int32		temp;

	if ( zap_read_frame( s, 1, &frame, NULL, NULL ) ){
		return -1;
	}

	src = ( unsigned __int32 * ) &( frame->payload.performance );
	dst = ( unsigned __int32 * ) &p;
	for ( i = 0; i < ( sizeof( p ) / 4 ); i++ ) {
		*dst = ntohl( *src );
		dst++;
		src++;
	}

	if ( ntohl( frame->header.zap_frame_type ) == zap_type_performance_result ) {
		perf->payloads_dropped += p.payloads_dropped;
		perf->payloads_outoforder += p.payloads_outoforder;
		perf->payloads_received += p.payloads_received;
		perf->payloads_repeated += p.payloads_repeated;

		gather_stats( history, p.bits_per_second );

		throughput = ( double )( ( double )p.bits_per_second ) / 1000000.0;

		if((config->average != 0) && (config->average >= p.batch + 1) ) {
			throughput_array[p.batch] =  throughput;
			*total = *total + throughput;
		}
		else if ((config->average != 0) && (config->average < p.batch + 1)) {
			*total = *total + throughput - throughput_array[0];
			for(k = 0; k < config->average - 1; k++){
				//Delete the first element and shitf left one element
				throughput_array[k] = throughput_array[k+1];
			}
			throughput_array[k] = throughput;
		}
		else{ // config->average == 0
			*total = *total + throughput;
		}

		if((config->average == 0) || config->average >= p.batch +1 ){
			temp = p.batch + 1;
		}
		else {
			temp = config->average;
		}

		printf( "%5d: %s->%s %6d=rx %3d=dr %3d=oo %3d=rp %5d=rx in %7.1fms  %6.1fmbps  %6.1f | ",
			p.batch,
			inet_ntoa2( config->txs_ip_address ),
			inet_ntoa2( config->rxs_ip_address[0] ),
			perf->payloads_received,
			perf->payloads_dropped,
			perf->payloads_outoforder,
			perf->payloads_repeated,
			p.payloads_received,
			( double )( ( double )( p.last_payload_timestamp - p.first_payload_timestamp ) ) / 1000.0,
			throughput,
			( p.batch > 0 )? ( *total/( temp ) ) : ( *total ) );

		for ( i = 0; i < ( ( sizeof r ) / sizeof( double ) ); i++ ) {
			printf( "%4.1f ", get_stats( history, r[i] ) / 1000000.0 );
		}
		printf( "\n" );
		//Check to make sure packages drop and user wants to log the file
		if (perf->payloads_dropped && config->logfile) {
			//Show message to user
			printf("%d packets drop. Take a look at %s file for mode detail\n", perf->payloads_dropped, config->logfile);
			//Dump to file
			zap_pkg_drop_dump_file(config, perf);
			//Exit
			zap_exit( 1 );
			cleanup_exit( 1 );
		}
		if(config->debugfile && p.batch >= config->start_point && p.batch <= config->end_point){
			zap_debug_dump_file( config, perf, p, throughput, *total , history);
		}
		if ( ( p.batch + 1 ) == config->station_config.batches ) {
			// print for
			lensrc = ( int )strlen( inet_ntoa2( config->txs_ip_address ) );
			lendst = ( int )strlen( inet_ntoa2( config->rxs_ip_address[0] ) );
			printf( "%5s: ", "#" );
			for ( i=0; i < lensrc - 3; i++ ) {
				printf( " " );
			}
			printf( "src  " );
			for ( i=0; i < lendst - 3; i++ ) {
				printf( " " );
			}
			printf( "dst        rx     dr     oo     rp       rx       b_time    b_thrput     avg | " );
			for ( i = 0; i < ( ( sizeof r ) / sizeof( double ) ); i++ ) {
				sprintf( buf, "%4.1f ", get_stats( history, r[i] ) / 1000000.0 );
				len = ( int )strlen( buf );
				for ( j= 0; j < ( len - ( int )strlen( histarr[i] ) - 1 ); j++ ) {
					printf( " " );
				}
				printf( "%s ", histarr[i] );
			}
			printf( "\n" );

			fprintf( stdout, " Test apparently complete\n" );
			return 1;
		}

		fflush( stdout );

		return 0;
	}

	if ( ntohl( frame->header.zap_frame_type ) == zap_type_test_complete ) {
	    return 1;
	}

	return -1;
}

void dump_stats( zap_history_t *history, FILE *fileio, char delimit )
{
    int					i;
    unsigned __int32	mb;
    int					total;

	if ( !history || !history->data ){
		return;
	}
	i = 0;
	for ( mb = 0; mb < ( history->data[history->gather_count - 1] + 1 ); mb += 1000 ) {
        total = 0;
        while ( history->data[i] < mb ) {
            i++;
            total++;
        }
        fprintf( fileio, "%d%c", total, delimit );
    }
}

unsigned __int32 get_stats( zap_history_t *history, double percentile )
{
    int			 offset;

    if ( !history->gather_max ) {
        return 0;
    }

    offset = ( int )( ( double ) history->gather_count * percentile );

	if ( offset >= ( history->gather_count - 1 ) ){
		offset = history->gather_count - 1;
	}

	if ( history->order ) {
		return history->data[offset];
	} else {
		return history->data[history->gather_count - offset - 1];
	}

}

void gather_stats( zap_history_t *history, unsigned __int32 value )
{
    if ( history->gather_count == history->gather_max ) {
        if ( !history->gather_max ) {
            history->gather_max = 512;
        } else {
            history->gather_max *= 2;
        }
        history->data = ( unsigned int * )realloc( history->data, history->gather_max * sizeof( history->data[0] ) );
    }
	history->data[history->gather_count] = value;
	history->gather_count++;
    qsort( history->data, history->gather_count, sizeof( history->data[0] ), compare );
}

int zap_compile_results( zap_config_t *config, zap_history_t *rate_history, zap_performance_frame_t *perf )
{
	fd_set					fd;
	int						n_fd = 0;
	unsigned __int32		i;
	struct timeval			tv;
	SOCKET					s[ZAP_MAX_RECEIVERS + 1];
	unsigned __int32		s_count;
	int						retval = 0;
	unsigned __int32		complete = 0;
	int						result;
    __int64					endtime;
	int						ttsk = 0;
	double					total= 0;
	unsigned __int32		count = 0;
	double					*throughput_array = NULL;	//Store value of each throughput when Zap receives package.

    endtime = get_current_usecs( ) + 1000000*config->test_seconds;
	memset( perf, 0, sizeof( perf ) );

	s_count = config->rxs_count + 1;

	// Get a nice array of sockets we're concerned with.
	for ( i = 0; i < config->rxs_count; i++ ) {
		s[i] = config->rxs_socket_ctl[i];
	}
	s[i] = config->txs_socket_ctl;

	//Allocate memory for throughput array
	if(config->average != 0) {
		throughput_array = (double *)malloc(config->average * sizeof(double));
		if(throughput_array == NULL) {
			exit_error("Can not allocate memory for throughput array\n");
		}
	}

	while ( !complete && ( get_current_usecs() - endtime < 0 ) ) {
		// Setup select.
		FD_ZERO( &fd );
		n_fd = 0;
		for ( i = 0; i < s_count; i++ )  {
			FD_SET( s[i], &fd );
			N_UPDATE( n_fd, s[i] );
		}
		tv.tv_sec = ( long )( config->results_timeout / 1000000 );
		tv.tv_usec = ( long )( config->results_timeout % 1000000 );

		// Wait for data.
		ttsk = select( n_fd+1, &fd, NULL, NULL, &tv );
		if ( ttsk == 0 ) {
		// Timeout
#ifdef WIN32 // Operation now in progress, so waiting for receiving data.
			if(	WSAGetLastError() != 0 || count >= 2) {
#else
			if(errno != EINPROGRESS || count >= 2)  {
#endif
				WARN_errno( 1, "zap_compile_results: Time out");
				zap_log_error(config, "zap_compile_results: Time out", ERROR);
				complete = 1;
				retval = 1;
			}
			else {
				count++;
				printf("\nConnection is slow,waiting for receiving data\n");
				zap_log_error(config, "Connection is slow,waiting for receiving data", ERROR);
			}
		} else {
			for ( i = 0; i < s_count; i++ ) {
				if ( FD_ISSET( s[i], &fd ) ) {
					result = zap_control_process_rx( config, s[i], rate_history, perf, &total, throughput_array );
					if ( result < 0 ) {
						zap_exit( 1 );
						cleanup_exit( 1 );
					}
					if ( result > 0 ) {
						// Got a complete message- ignore this
						unsigned int j;
						for ( j = i; j < ( s_count - 1 ); j++ ) {
							s[j] = s[j + 1];
						}
						s_count--;
						printf( "scount--\n" );
						if ( s_count == 1 ) { // Only the tx channel left...
						    printf( "complete\n" );
							complete = 1;
							retval = 0;
							break;
						} else {
							i--;
						}
					}
				}
			}
		}
	}

	// Dump results to file.
	if ( config->filename ) {
		if ( zap_control_dump_file( config, perf, rate_history, total ) ) {
			exit_error( "Could not output results\n" );
		}
	}
	// Deallocate memory of throughput_array
	if(throughput_array != NULL) {
		free(throughput_array);
	}
	if(config->debugfile != NULL){
		free(config->debugfile);
	}

	return retval;
}

//
// zap_controller - Controls zap servers to send data 'round.
//
// returns : 0 on success, non-zero on error.
//
int
zap_controller( zap_config_t *config )
{
	unsigned __int32		i;
	zap_history_t			rate_history = {NULL, 0, 0, 0};
	zap_performance_frame_t perf;

	memset( &perf, 0, sizeof( perf ) );

	// Select test ID
	config->tid = zap_generate_tid(  );

	// Open control connection to transmitter.
	if ( zap_socket( config->station_config.buf_required, 1, &config->txs_socket_ctl ) ) {
		errOut( "Could not allocate tx station socket.\n" );
		zap_log_error(config, "Could not allocate tx station socket.", ERROR);
		cleanup_exit( 1 );
	}

	if ( zap_connect( config->txs_ip_address_ctl, 1, config->txs_socket_ctl, 5000000 ) ) {
		zap_log_error(config, "Could not connect to tx station.", ERROR);
		errOut( "Could not connect to tx station %s.\n", inet_ntoa2( config->txs_ip_address_ctl ) );
		cleanup_exit( 1 );
	}

	// Open control connection to receivers.
	for ( i = 0; i < config->rxs_count; i++ ) {
		if ( zap_socket( config->station_config.buf_required, 1, &config->rxs_socket_ctl[i] ) ) {
			zap_log_error(config, "Could not allocate rx station socket.", ERROR);
			exit_error( "Could not allocate rx station socket.\n" );
		}
		if ( zap_connect( config->rxs_ip_address_ctl[i], 1, config->rxs_socket_ctl[i], 5000000 ) ) {
			zap_log_error(config, "Could not connect to rx station.", ERROR);
			exit_error( "Could not connect to rx station.\n" );
		}
	}

	// Configure Receivers.
	config->station_config.tx = 0;
	config->station_config.ip_tos = config->ip_tos;
	for ( i = 0; i < config->rxs_count; i++ ) {
		if ( zap_config( config->tid, config->rxs_socket_ctl[i], &config->station_config ) ) {
			zap_log_error(config, "Could not configure rx station. Possible version incompatibility.", ERROR);
			exit_error( "Could not configure rx station. Possible version incompatibility.\n" );
		}
	}

	// configure Transmitter.
	config->station_config.tx = 1;
	if ( zap_config( config->tid, config->txs_socket_ctl, &config->station_config ) ) {
		zap_log_error(config, "Could not configure tx station. Possible version incompatibility.", ERROR);
		exit_error( "Could not configure tx station. Possible version incompatibility.\n" );
	}

	// Open data connections in the appropriate directions.
	for ( i = 0; i < config->rxs_count; i++ ) {
		if ( config->open_reverse ) {
		    printf( "reverse\n" );
			if ( zap_data_connect( config->tid, config->rxs_socket_ctl[i], config->txs_ip_address ) ) {
				zap_log_error(config, "Could not connect rx to tx station via TCP.", ERROR);
				exit_error( "Could not connect rx to tx station via TCP\n" );
			}
		} else {
			if ( zap_data_connect( config->tid, config->txs_socket_ctl, config->rxs_ip_address[i] ) ) {
				zap_log_error(config, "Could not connect rx to tx station via TCP.", ERROR);
				exit_error( "Could not connect tx to rx station via TCP\n" );
			}
		}
	}

	// Indicate the test should start.
	if ( zap_test_start( config->tid, config->txs_socket_ctl ) ) {
		zap_log_error(config, "Could not start test.", ERROR);
		exit_error( "Could not start test\n" );
	}

	// Listen/wait for responses. ( Any TCP connection closing aborts test!!! )
	if ( zap_compile_results( config, &rate_history, &perf ) ) {
		zap_log_error(config, "Could not get responses.", ERROR);
		exit_error( "Could not get responses \n" );
	}

	for ( i = 0; i < config->rxs_count; i++ ) {
		zap_test_complete( config->tid, config->rxs_socket_ctl[i] );
		shutdown( config->rxs_socket_ctl[i], SHUT_WR );

#ifdef WIN32
		Sleep( SLEEP_TIME );
#else
		usleep( SLEEP_TIME );
#endif

		closesocket( config->rxs_socket_ctl[i] );
	}

	// Close control connections. ( Implicitly closes data connections. )
	zap_test_complete( config->tid, config->txs_socket_ctl );
	shutdown( config->txs_socket_ctl, SHUT_WR );

#ifdef WIN32
	Sleep( SLEEP_TIME );
#else
	usleep( SLEEP_TIME );
#endif

	closesocket( config->txs_socket_ctl );

	return 0;
}

//
// Parse the command-line arguments for zap.
//
int zap_parse_args( int argc, char *argv[], zap_config_t *config )
{
	int							i, j, k;
    int                         len;
    char						*found;
	unsigned __int32			number=0;
	unsigned __int32			ip_d;
	unsigned __int32			ip_c;
	unsigned __int32			value;
	unsigned __int32			stop_value;
	unsigned __int32			bit_rate = 0;
	unsigned __int32			frames = 0;
	float						fl;
	int							reverse = 0;
	FILE			            *fileio;
	int							payload_length_flag = 0;
	int							batch_time_flag = 0;

	memset( config, 0, sizeof ( *config ) );
	config->tag = "";
	config->sub = "";
	config->note= "";

//	// DEFAULTS!
	//
	// The default is designed to do the equivalent of the old "zap x.x.x.x --client"
	//
	// In this case, there is only one IP address, and that is the IP address of the transmitter. The
	// receiver IP address will be 127.0.0.1 in this case. If the receiver IP address is 127.0.0.1, we
	// really want to open the connection in reverse, since the transmitter won't really be able to open
	// a connection to 127.0.0.1 and expect it to get where we really want it to go. It's like testing
	// NAT by default, which is kinda cute.
	//
	config->station_config.asynchronous			= 1;		// At most one batch outstanding at a time.
	config->station_config.batch_completion		= 1;		// Yes, send frames to acknowledge completion.
	config->station_config.batch_inband_response= 0;		// No inband response required. ( i.e. not echo service )
	config->station_config.batch_report_rate = 1;			// 1 report per batch.
	config->station_config.batch_size = 50;					// 50 payloads per batch. This option is mutually exclusive from batch_time value
	config->station_config.batch_time = 50000;				// Run batch with 50000 milisecond, don't care how many payloads on a batch
															// This option is mutually exclusive from batch_size value
	config->station_config.batch_timeout = 1000000;			// 1 second timeout per batch.
	config->station_config.batch_transmit_delay = 1;		// No delay between batches. Well, 1 usec, but effectively zero.
	config->station_config.batches = 1000;					// 1000 batches.
	config->station_config.payload_length = 1472;			// Max size UDP frame.
	config->station_config.payload_timeout = 100000;		// 1/10 sec
	config->station_config.payload_transmit_delay = 1;		// No delay between payloads. Well, 1 usec, but effectively zero.
	config->station_config.tcp = 0;							// Use UDP by default (TCP support is deprecated).
	config->station_config.tx_ip = 0;						// Learn the IP address to which to transmit UDP frames.

	config->open_reverse = 0;
	config->results_timeout = 60 * 1000000;					// 60 second timeout waiting for results.

	config->txs_ip_address = 0;
	config->txs_ip_address_ctl = 0;

	config->rxs_count = 0;
	config->server = 0;
    config->test_seconds = 30000; // big enough to not matter
	config->debugfile = NULL;

	for ( i = 1; i < argc; i++ ) {
		if ( argv[i][0] == '-' ) {
			switch ( argv[i][1] ) {
				case 's':
				case 'd':
				case 'm':
					for ( j = 2; j < ( int )strlen( argv[i] ); j++ ) {
						if ( argv[i][j] == ',' ) {
							argv[i][j] = ' ';
						}
					}
					// Parse 1 or 2 IP addys.
					ip_d = 0;
					ip_c = 0;
					ip_d = inet_addr( &argv[i][2] );
					if ( ip_d ) {
						for ( j = 2; j < ( int )strlen( argv[i] ); j++ ) {
							if ( argv[i][j] == ' ' ) {
								ip_c = inet_addr( &argv[i][j+1] );
								break;
							}
						}
					}
					break;
				case 'l':
				case 'a':
				case 'o':
				case 'f':
				case 'X':
				case 'n':
				case 'p':
				case 'w':
					if ( sscanf( &argv[i][2], "%d", &value ) != 1 ) {
						// Bad scan..
						return 1;
					}
					break;
				case 'D':
					for ( j = 2; j < ( int )strlen( argv[i] ); j++ ) {
						if ( argv[i][j] == ',' ) {
							argv[i][j] = ' ';
						}
					}
					/*Get debug file name*/
					for ( j = 0; j < ( int )strlen( argv[i] ); j++ ) {
						if ( argv[i][j] == ' ' ) {
							config->debugfile = (char*)malloc(j * sizeof(char));
							strncpy(config->debugfile, argv[i] + 2, j-2);
							config->debugfile[j-2] = '\0';
							break;
						}
					}
					/*Get the start point*/
					for ( k = j+1; k < ( int )strlen( argv[i] ); k++ ) {
						if ( argv[i][k] == ' ' ) {
							char temp[10];
							strncpy(temp, argv[i]+j, k-j);
							value = atoi(temp);
						}
					}
					/*Get end point*/
					for ( k = j+1; k < ( int )strlen( argv[i] ); k++ ) {
						if ( argv[i][k] == ' ' ) {
							if ( sscanf( &argv[i][k+1], "%d", &stop_value ) != 1 ) {
								// Bad scan..
								return 1;
							}
						}
					}
					break;
			case 'q':

			    // For those options with numeric args, grab the numeric arg.
			    found = 0;
			    number = strtoul( &( argv[i][2] ), &found, 0 );
				if ( !found ) {
                    return 1;
				}
			    break;

				case 'r':
					if ( sscanf( &argv[i][2], "%f", &fl ) != 1 ) {
						// Bad scan..
						return 1;
					}
					if ( fl <= 0 ) {
						return 1;
					}
					fl *= 1000000.0;
					value = ( unsigned __int32 ) fl;
					break;
				default:
					break;
			}
			switch ( argv[i][1] ) {
				case 's':			// Source IP address
					if ( config->txs_ip_address ) {
						// return 1;		// Allow re-specifying IP addy on command line.
					}
					if ( ip_d ) {
						config->txs_ip_address = ip_d;
						if ( ip_c ) {
							config->txs_ip_address_ctl = ip_c;
						} else {
							config->txs_ip_address_ctl = ip_d;
						}
					} else {
						return 1;
					}
					break;
				case 'd':			// Destionation IP address
					if ( config->rxs_count >= ZAP_MAX_RECEIVERS ) {
						return 1;
					}
					if ( ip_d ) {
						config->rxs_ip_address[config->rxs_count] = ip_d;
						if ( ip_c ) {
							config->rxs_ip_address_ctl[config->rxs_count] = ip_c;
						} else {
							config->rxs_ip_address_ctl[config->rxs_count] = ip_d;
						}
						config->rxs_count++;
					} else {
						return 1;
					}
					break;
				case 'i':			// Invert connection opening.
					config->open_reverse = 1;
					break;
				case 'l':			// Payload length
					if ( value > 65527 ) {
						return 1;
					}
					if ( value < ( sizeof( zap_header_t ) + sizeof( zap_data_frame_t ) ) ) {
						value = sizeof( zap_header_t ) + sizeof( zap_data_frame_t );
					}
					config->station_config.payload_length = value;
					payload_length_flag = 1;
					break;
				case 'f':
					frames = value;
					break;
#ifndef NO_MTUDISC
				case 'M':			// Path MTU Discovery
					pmtudisc = !strcmp(&argv[i][2], "dont") ? IP_PMTUDISC_DONT :
					           !strcmp(&argv[i][2], "want") ? IP_PMTUDISC_WANT :
					           !strcmp(&argv[i][2], "do") ? IP_PMTUDISC_DO : -1;
					break;
#endif // NO_MTUDISC
				case 'a':			// Batch size- Average size- Sample size
					if ( value == 0 ) {
						value = 1;
					}
					config->station_config.batch_size = value;
					if (batch_time_flag == 0){
						// Disable -p option
						config->station_config.batch_time = 0;
					}
					break;
				case 'p':
					config->station_config.batch_time = value;
					batch_time_flag = 1;
					break;
				case 'q':
					  config->ip_tos = number;
					 break;
				case 'o':			// Max batches outstanding.
					if ( value == 0 ) {
						value = 1;
					}
					config->station_config.asynchronous = value;
					break;
				case 'm':			// Multicast IP
					break;
				case 'r':			// Data rate.
					bit_rate = value;
					break;
				case 'F':
					config->filename = &argv[i][2];
					break;
				case 'L':
					config->logfile = &argv[i][2];
					break;
				case 'D':
					if (stop_value < value) {
						printf("Invalid value. Stop point always more than start point!\n");
						return 1;
					}
					if ((value == 0) && (stop_value == 0) ) {
						//Log all results.
						value = 0;
						stop_value = 0xFFFFFFFF;
					}
					config->start_point = value;
					config->end_point = stop_value;
					break;
				case 'w':
					config->average = value;
					break;
				case 'T':
					config->tag = &argv[i][2];
					break;
				case 'S':
					config->sub = &argv[i][2];
					break;
				case 'N':
					config->note = &argv[i][2];
					break;
				case 'X':
					config->test_seconds = value;
                    printf( "Test will terminate in approximately %d seconds.\n", value );
                    config->station_config.batches = 1000000; // override batches
					break;
				case 'n':
					config->station_config.batches = value;
					break;
				case 'R':
					reverse = 1;
					break;
                case '-':
                    if ( argv[i][2] == 0 ) {
                        fprintf( stderr, "Error: Expecting more than just --\n" );
                        return 1;
                    }
                    len = ( int ) strlen( &argv[i][2] );
                    if ( strncmp( &argv[i][2], "server", len ) == 0 ) {
						config->server = 1;
                    } else {
                        fprintf( stderr, "Error: unexpected -- option received\n" );
                        return 1;
                    }
                    break;
				default:
					// Error.
					return 1;
			}
		}
	}

	// Check args.
	if ( !config->txs_ip_address_ctl ) {
		fprintf( stderr, "Error- Expecting at least one IP address with which to play\n" );
		return 1;
	}
	if ( !config->txs_ip_address ) {
		config->txs_ip_address = config->txs_ip_address_ctl;
	}

	if ( !config->rxs_count ) {
		config->rxs_count = 1;
		config->rxs_ip_address_ctl[0] = inet_addr( "127.0.0.1" );
		config->open_reverse = 1;
	}

	for ( i = 0; i < ( int ) config->rxs_count; i++ ) {
		if ( !config->rxs_ip_address_ctl[i] ) {
			fprintf( stderr, "Error- no rx_ctl IP address. Weird\n" );
			return 1;
		}
		if ( !config->rxs_ip_address[i] ) {
			config->rxs_ip_address[i] = config->rxs_ip_address_ctl[i];
		}
	}
	if ( config->station_config.tcp ) {
		if ( frames ) {
			config->station_config.payload_length *=frames;
		}
		if ( config->station_config.payload_length > 65535 ) {
			fprintf( stderr, "Error- cannot send length %d\n", config->station_config.payload_length );
			return 1;
		}
	} else {
		if(frames) {
			frames--;
			config->station_config.payload_length += /*1480*/config->station_config.payload_length*frames;
		}
		if ( config->station_config.payload_length > 65527 ) {
			fprintf( stderr, "Error- cannot send length %d\n", config->station_config.payload_length );
			return 1;
		}
	}

	// Check if the bit rate must be set.
	if ( bit_rate ) {
		double bps, bpp, usecs_p;

		bps = ( double )bit_rate;
		bpp = ( double )config->station_config.payload_length * 8;

		usecs_p = ( 1000000.0 / bit_rate ) * bpp;
		config->station_config.payload_transmit_delay = ( unsigned __int32 ) usecs_p;
		if ( config->station_config.payload_transmit_delay == 0 ) {
			config->station_config.payload_transmit_delay = 1;
		}

		//bit_rate
	}

	if ( reverse ) {
		if ( config->rxs_count != 1 ) {
			fprintf( stderr, "Error- can only reverse source/destination for unicast\n" );
			return 1;
		}
		ip_d = config->rxs_ip_address[0];
		ip_c = config->rxs_ip_address_ctl[0];
		config->rxs_ip_address[0] = config->txs_ip_address;
		config->rxs_ip_address_ctl[0] = config->txs_ip_address_ctl;
		config->txs_ip_address = ip_d;
		config->txs_ip_address_ctl = ip_c;
	}

	config->station_config.buf_required = config->station_config.batch_size * config->station_config.payload_length * config->station_config.asynchronous;
	//Print the current engaging information, it includes -p, -n, -l, -q option
	fprintf(stdout, "Engaging default options -p%d -n%d -l%d -q0x%x\n", config->station_config.batch_time,
		config->station_config.batches, config->station_config.payload_length, config->ip_tos);
#ifndef NO_MTUDISC
	if (pmtudisc != -1) {
		fprintf(stdout, "Engaging explicit option %s\n", ip_pmtudisc_str(pmtudisc));
	}
#endif // NO_MTUDISC
	fprintf(stdout, "\n");

	//Dump this information to log file in the case we set -D option
	if(config->debugfile){
		fileio = fopen( config->debugfile, "a+" );
		fprintf(fileio, "Engaging default options -p%d -n%d -l%d -q0x%x\n", config->station_config.batch_time,
			config->station_config.batches, config->station_config.payload_length, config->ip_tos);
#ifndef NO_MTUDISC
		if (pmtudisc != -1) {
			fprintf(fileio, "Engaging explicit option %s\n", ip_pmtudisc_str(pmtudisc));
		}
#endif // NO_MTUDISC
		fprintf(fileio, "\n");
		fclose(fileio);
	}
	return 0;
}

int zap( int argc, char *argv[] )
{
	zap_config_t			config;

    fprintf( stdout, "%s version %d.%d, Copyright ( C ) 2004-2009 Ruckus Wireless, Inc. All Rights Reserved.\n",
		argv[0],
        ZAP_MAJOR_VERSION,
        ZAP_MINOR_VERSION );
	fprintf( stdout, "Built %s at %s\n", __DATE__, __TIME__ );

	memset( ( char * )&config, 0, sizeof( config ) );

	if ( zap_parse_args( argc, argv, &config ) ) {
		fprintf( stderr, "%s [options] -s<IP_D>[,<IP_C>] [options]\n", argv[0] );
		fprintf( stderr, "   Zap has the following options: NOTE: options are CaSe sensitive!\n" );
		fprintf( stderr, "     -s<IP_D>[,<IP_C>]  - Specify the IP address of the source station. Traffic will be sent FROM this station.\n" );
		fprintf( stderr, "                          <IP_D> The IP address the station will use for data communication.\n" );
		fprintf( stderr, "                          <IP_C> The ( optional ) IP address the controller will use to communicate with the station.\n" );
		fprintf( stderr, "                          This option is required.\n" );
		fprintf( stderr, "     -d<IP_D>[,<IP_C>]  - Specify the IP address of the destination station. Traffic will be sent TO this station.\n" );
		fprintf( stderr, "                          <IP_D> The IP address the station will use for data communication.\n" );
		fprintf( stderr, "                          <IP_C> The ( optional ) IP address the controller will use to communicate with the station.\n" );
		fprintf( stderr, "                          This value defaults to the local station. Multiple may be specified for multicast.\n" );
		fprintf( stderr, "     -i                 - Invert Connection Opening - Opens initial connection from destination to source.\n" );
		fprintf( stderr, "                          Used to alieviate testing issues with NAT devices. Defaults off.\n" );
		fprintf( stderr, "     -l<length>         - Specifies a payload length of <length>. The largest payload in a single packet is:\n" );
		fprintf( stderr, "                          UDP: 1472 bytes.\n" );
		fprintf( stderr, "     -f<frames>         - Specifies how many full-length frames you want to use for framelength. Takes\n" );
		fprintf( stderr, "                          fragmentation into account. Completely overrides -l\n" );
#ifndef NO_MTUDISC
		fprintf( stderr, "     -M<pmtudisc hint>  - Specifies Path MTU Discovery (PMTUDISC) strategy. Options are: \n");
		fprintf( stderr, "                          do (always DF); want (do and fragment locally); dont (never DF).\n");
#endif // NO_MTUDISC
		fprintf( stderr, "     -a<sample size>    - <sample size> is the number of payloads sampled for performance measurement.\n" );
		fprintf( stderr, "                          This is the near-equivalent of zing's -E option. Defaults to 50.\n" );
		fprintf( stderr, "                          This option is mutually exclusive from -p option.\n" );
		fprintf( stderr, "     -p<period>         - Each sample lasts the specified ( in microseconds ) period.\n" );
		fprintf( stderr, "                          Successfully crosses sample boundaries.\n" );
		fprintf( stderr, "                          This option is mutually exclusive from -a option.\n" );
		fprintf( stderr, "     -q#                - Send frames with the specified 8 bit DSCP ( TOS bits ).\n" );
		fprintf( stderr, "                          NOTE: The frames coming back will NOT have these bits set, necessarily.\n" );
		fprintf( stderr, "                          On WinXP, the following registry key must be REG_DWORD,\n" );
		fprintf( stderr, "                          and ZERO to enable TOS bit setting: Local Machine\\System\\CurrentControlSet\\\n" );
		fprintf( stderr, "                          Services\\Tcpip\\Parameters\\DisableUserTOSSetting\n" );
		fprintf( stderr, "                          Common fields for Lowest  #: 0x08, 0x20: Background\n" );
		fprintf( stderr, "                          Common fields for Low     #: 0x00, 0x18: Best Effort\n" );
		fprintf( stderr, "                          Common fields for High    #: 0x28, 0xa0: Video\n" );
		fprintf( stderr, "                          Common fields for Highest #: 0x30, 0xe0: Voice\n" );
		fprintf( stderr, "                          Common fields for Unknown #: 0x88:       Video 2?\n" );
		fprintf( stderr, "     -n<number samples> - Specifies the number of samples in the test. Defaults to 1000.\n" );
		fprintf( stderr, "     -o<outstanding>    - Specifies the number of samples that may be outstanding ( in the air )\n" );
		fprintf( stderr, "                          at any given time. Defaults to 1.\n" );
		fprintf( stderr, "     -m<IP_M>           - Specify the destination multicast address to use for data communication.\n" );
		fprintf( stderr, "                          Defaults to none. Setting this enables multicast transmission via UDP.\n" );
		fprintf( stderr, "     -r<mbps>           - Controls the rate in mbits/s for transmitting data. Decimal values accepted\n" );
		fprintf( stderr, "                          Defaults to a very high data rate.\n" );
		fprintf( stderr, "     -R                 - Reverses the direction ( swaps source and destination ). Only works with unicast\n" );
		fprintf( stderr, "     -F<filename>       - Dump results ( appended ) to a comma seperated value file <filename>\n" );
		fprintf( stderr, "     -L<logfilename>    - Dump the log file and stop zap tool when some packet drop\n" );
		fprintf( stderr, "     -D<file><,start,stop>\n" );
		fprintf( stderr, "                        - Dump result to file for debugging\n" );
		fprintf( stderr, "                          Instruction: -Dfilename,start_point,stop_point.\n" );
		fprintf( stderr, "                          In order to dump all log file, using -Dfilname,0,0\n" );
		fprintf( stderr, "     -w<value>          - Get the average value of throughput\n");
		fprintf( stderr, "     -T<tag>            - Tag used to describe this test case within the dumped file, required with -F\n" );
		fprintf( stderr, "     -S<sub>            - Sub tag used to describe this test case within the dumped file.\n" );
		fprintf( stderr, "     -N<note>           - Note used to describe this test case within the dumped file.\n" );
		fprintf( stderr, "     -X<sec>            - Test for specified number of seconds.\n" );
		fprintf( stderr, "     --server           - Runs zap in server mode. No other arguments required.\n" );

		return 1;
	}

	pcfg = &config;
	return zap_controller( &config );
}

int main( int argc, char* argv[] )
{
	int			err;

	pcfg = NULL;
	signal( SIGTERM, zap_exit );
	signal( SIGINT, zap_exit );
#ifndef WIN32
    // Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#endif

	net_init(  );

	err = zap( argc, argv );
	cleanup_exit( err );
}


text:
package org.mule.mvel2.ast;

import org.mule.mvel2.ParserContext;
import org.mule.mvel2.compiler.ExecutableStatement;
import org.mule.mvel2.integration.VariableResolverFactory;

import static org.mule.mvel2.util.ParseTools.checkNameSafety;

/**
 * @author Christopher Brock
 */
public class DeclProtoVarNode extends ASTNode implements Assignment {
  private String name;

  public DeclProtoVarNode(String name, Proto type, int fields, ParserContext pCtx) {
    super(pCtx);
    this.egressType = Proto.ProtoInstance.class;
    checkNameSafety(this.name = name);

    if ((fields & COMPILE_IMMEDIATE) != 0) {
      pCtx.addVariable(name, egressType, true);
    }
  }

  public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
    if (!factory.isResolveable(name)) factory.createVariable(name, null, egressType);
    else throw new RuntimeException("variable defined within scope: " + name);
    return null;
  }

  public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
    if (!factory.isResolveable(name)) factory.createVariable(name, null, egressType);
    else throw new RuntimeException("variable defined within scope: " + name);

    return null;
  }

  public String getName() {
    return name;
  }

  public String getAssignmentVar() {
    return name;
  }

  public char[] getExpression() {
    return new char[0];
  }

  public boolean isAssignment() {
    return true;
  }

  public boolean isNewDeclaration() {
    return true;
  }

  public void setValueStatement(ExecutableStatement stmt) {
    throw new RuntimeException("illegal operation");
  }

  public String toString() {
    return "var:" + name;
  }
}


text:
<resources>
  <string name="app_name">spring-revealmanager</string>
</resources>


text:
extern mod extra(name = "extra", name = "nonstd");

fn main() { }


text:
using Newtonsoft.Json;
using DDPAIDash.Core.Json.Converters;

namespace DDPAIDash.Core.Types
{
    internal class MailBoxMessage
    {
        [JsonProperty("msgid")]
        [JsonConverter(typeof(MailBoxMessageKeysConverter))]
        public MailBoxMessageKeys Key { get; set; }

        [JsonProperty("data")]
        public string Data { get; set; }
    }
}


text:
Virtualenv
==========

Windows
-------

- pip install --user virtualenv
- C:\Users\XXX\AppData\Roaming\Python\Scripts\virtualenv.exe -p C:\\Python35\\python.exe Path\To\virtualEnv
- Path\To\virtualEnv\Scripts\activate.bat or source Path\To\virtualEnv\Scripts\activate

Linux
-----

- pip install --user virtualenv
- virtualenv -p /usr/bin/python3.5 Path\To\virtualEnv
- source Path\To\virtualEnv\Scripts\activate

Install requirements
--------------------

- for the service
  - pip install -r requirements/base.txt
- for the development
  - pip install -r requirements/dev.txt


text:
var EventBus = require('vertx-js/vertx-eventbus');
var TestService = require('test-js/test_service-proxy');

var eb = new EventBus();

eb.onopen = function () {
  var testService = new TestService(eb, 'someaddress');

  testService.failingMethod(function (err, res) {
    if (!err) {
      vertx.eventBus().send("testaddress", "unexpected failure " + err);
    } else if (res != null) {
      vertx.eventBus().send("testaddress", "unexpected result " + res);
    } else if (err.failureType != 'RECIPIENT_FAILURE') {
      vertx.eventBus().send("testaddress", "unexpected err type  " + err.failureType);
    } else if (err.message != 'wibble') {
      vertx.eventBus().send("testaddress", "unexpected err type  " + err.message);
    } else {
      vertx.eventBus().send("testaddress", "ok");
    }
  });
};


text:
using System.ComponentModel.DataAnnotations;

namespace DisasterRecoveryAPI.Models.BindingModels
{
    public class RiskBindingModel
    {
        [Required]
        public string Name;

        [Required]
        public int Probability;

        public string Description;
    }
}