text:
/*     */ package com.hundsun.network.gates.genshan.biz.service.pojo.common;
/*     */
/*     */ import com.hundsun.network.gates.genshan.biz.service.BaseService;
/*     */ import com.hundsun.network.gates.genshan.biz.service.common.UploadService;
/*     */ import com.hundsun.network.gates.luosi.common.utils.CommonUtils;
/*     */ import com.hundsun.network.melody.common.util.ShortUUIDGenerator;
/*     */ import java.io.ByteArrayOutputStream;
/*     */ import java.io.File;
/*     */ import java.io.FileOutputStream;
/*     */ import java.io.IOException;
/*     */ import java.io.InputStream;
/*     */ import java.util.Date;
/*     */ import org.apache.commons.httpclient.util.DateUtil;
/*     */ import org.apache.commons.logging.Log;
/*     */ import org.apache.velocity.texen.util.FileUtil;
/*     */ import org.springframework.beans.factory.annotation.Value;
/*     */ import org.springframework.stereotype.Service;
/*     */ import org.springframework.web.multipart.MultipartFile;
/*     */
/*     */ @Service("uploadService")
/*     */ public class UploadServiceImpl extends BaseService
/*     */   implements UploadService
/*     */ {
/*     */
/*     */   @Value("${upload.root}")
/*     */   private String uploadRoot;
/*     */
/*     */   @Value("${upload.root.licence.url.path}")
/*     */   private String uploadUrl;
/*     */
/*     */   public String uploadFile(InputStream input, String imgExt)
/*     */   {
/*  44 */     StringBuffer imgPath = new StringBuffer();
/*  45 */     StringBuffer contextPath = new StringBuffer();
/*     */
/*  47 */     String pathPart = DateUtil.formatDate(new Date(), "/yyyy/MM/dd/");
/*  48 */     String fileName = ShortUUIDGenerator.randomUUID() + "." + imgExt;
/*  49 */     imgPath.append(this.uploadRoot);
/*  50 */     contextPath.append(this.uploadUrl);
/*  51 */     imgPath.append(pathPart);
/*  52 */     contextPath.append(pathPart);
/*  53 */     FileUtil.mkdir(imgPath.toString());
/*  54 */     imgPath.append(fileName);
/*  55 */     contextPath.append(fileName);
/*  56 */     if (writeFile(input, imgPath.toString())) {
/*  57 */       return contextPath.toString();
/*     */     }
/*  59 */     return null;
/*     */   }
/*     */
/*     */   public String uploadFile(MultipartFile file)
/*     */   {
/*  71 */     if (null == file) {
/*  72 */       this.log.error("uploadFile fail, file is null");
/*  73 */       return null;
/*     */     }
/*     */     try {
/*  76 */       return uploadFile(file.getInputStream(), CommonUtils.getFileSuffix(file.getOriginalFilename()));
/*     */     }
/*     */     catch (IOException e) {
/*  79 */       this.log.error("uploadFile fail", e);
/*  80 */     }return null;
/*     */   }
/*     */
/*     */   private boolean writeFile(InputStream input, String filePath)
/*     */   {
/*     */     try
/*     */     {
/*  92 */       if (null == input) {
/*  93 */         this.log.error("Parameter (InputStream in) is null!");
/*  94 */         return false;
/*     */       }
/*  96 */       FileOutputStream output = new FileOutputStream(filePath);
/*  97 */       ByteArrayOutputStream data = new ByteArrayOutputStream();
/*  98 */       int num = 0;
/*  99 */       byte[] buffer = new byte[1024];
/* 100 */       while ((num = input.read(buffer)) > 0) {
/* 101 */         data.write(buffer, 0, num);
/* 102 */         output.write(buffer);
/*     */       }
/* 104 */       output.close();
/* 105 */       return true;
/*     */     } catch (Exception e) {
/* 107 */       this.log.error("upload file error", e);
/* 108 */     }return false;
/*     */   }
/*     */
/*     */   public boolean deleteOriginalFile(String filePath)
/*     */   {
/* 113 */     StringBuffer sb = new StringBuffer();
/*     */
/* 115 */     sb.append(this.uploadRoot.substring(0, this.uploadRoot.length() - this.uploadUrl.length()));
/* 116 */     sb.append(filePath);
/* 117 */     File file = new File(sb.toString());
/* 118 */     if (file.exists()) {
/*     */       try {
/* 120 */         file.delete();
/* 121 */         return true;
/*     */       } catch (Exception e) {
/* 123 */         this.log.error("delete originalFile error, cause by:" + e);
/* 124 */         return false;
/*     */       }
/*     */     }
/* 127 */     this.log.debug("warning:the original file is not deleted, file name is:" + filePath);
/* 128 */     return true;
/*     */   }
/*     */ }

/* Location:           E:\__安装归档\linquan-20161112\deploy15\genshan\webroot\WEB-INF\classes\
 * Qualified Name:     com.hundsun.network.gates.genshan.biz.service.pojo.common.UploadServiceImpl
 * JD-Core Version:    0.6.0
 */


text:
package org.quartzpowered.protocol.codec.v1_8_R1.play.client;

import org.quartzpowered.network.buffer.Buffer;
import org.quartzpowered.network.protocol.codec.Codec;
import org.quartzpowered.protocol.packet.play.client.UpdateHealthPacket;

public class UpdateHealthCodec implements Codec<UpdateHealthPacket> {

    @Override
    public void encode(Buffer buffer, UpdateHealthPacket packet) {
        buffer.writeFloat(packet.getHealth());
        buffer.writeVarInt(packet.getFoodLevel());
        buffer.writeFloat(packet.getSaturation());
    }

    @Override
    public void decode(Buffer buffer, UpdateHealthPacket packet) {
        packet.setHealth(buffer.readFloat());
        packet.setFoodLevel(buffer.readVarInt());
        packet.setSaturation(buffer.readFloat());
    }
}

redpajama_set_name: RedPajamaGithub


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

<title>DefaultNameFactory (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.metrics

Class DefaultNameFactory

java.lang.Object

org.apache.cassandra.metrics.DefaultNameFactory

All Implemented Interfaces:

MetricNameFactory

public class DefaultNameFactory
extends java.lang.Object
implements MetricNameFactory

MetricNameFactory that generates default MetricName of metrics.

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
GROUP_NAME

Constructor Summary

Constructors

Constructor and Description

DefaultNameFactory(java.lang.String type)

DefaultNameFactory(java.lang.String type,
                  java.lang.String scope)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

protected static java.lang.String
createDefaultMBeanName(java.lang.String type,
                      java.lang.String name,
                      java.lang.String scope)

CassandraMetricsRegistry.MetricName
createMetricName(java.lang.String metricName)

Create a qualified name from given metric name.

static CassandraMetricsRegistry.MetricName
createMetricName(java.lang.String type,
                java.lang.String metricName,
                java.lang.String scope)

Methods inherited from class java.lang.Object

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

Field Detail

GROUP_NAME

public static final java.lang.String GROUP_NAME

See Also:

Constant Field Values

Constructor Detail

DefaultNameFactory

public DefaultNameFactory(java.lang.String type)

DefaultNameFactory

public DefaultNameFactory(java.lang.String type,
                          java.lang.String scope)

Method Detail

createMetricName

public CassandraMetricsRegistry.MetricName createMetricName(java.lang.String metricName)

Description copied from interface: MetricNameFactory

Create a qualified name from given metric name.

Specified by:

createMetricName in interface MetricNameFactory

Parameters:

metricName - part of qualified name.

Returns:

new String with given metric name.

createMetricName

public static CassandraMetricsRegistry.MetricName createMetricName(java.lang.String type,
                                                                   java.lang.String metricName,
                                                                   java.lang.String scope)

createDefaultMBeanName

protected static java.lang.String createDefaultMBeanName(java.lang.String type,
                                                         java.lang.String name,
                                                         java.lang.String scope)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
module Mongoid
  module Attributes

    # This module contains the behavior for processing attributes.
    module Processing

      # Process the provided attributes casting them to their proper values if a
      # field exists for them on the document. This will be limited to only the
      # attributes provided in the suppied +Hash+ so that no extra nil values get
      # put into the document's attributes.
      #
      # @example Process the attributes.
      #   person.process_attributes(:title => "sir", :age => 40)
      #
      # @param [ Hash ] attrs The attributes to set.
      # @param [ Symbol ] role A role for scoped mass assignment.
      # @param [ Boolean ] guard_protected_attributes False to skip mass assignment protection.
      #
      # @since 2.0.0.rc.7
      def process_attributes(attrs = nil, role = :default, guard_protected_attributes = true)
        with_mass_assignment(role, guard_protected_attributes) do
          attrs ||= {}
          if !attrs.empty?
            attrs = sanitize_for_mass_assignment(attrs, role) if guard_protected_attributes
            attrs.each_pair do |key, value|
              next if pending_attribute?(key, value)
              process_attribute(key, value)
            end
          end
          yield self if block_given?
          process_pending
        end
      end

      private

      # Get the current mass assignment options for this model.
      #
      # @api private
      #
      # @return [ Hash ] The mass assignment options.
      #
      # @since 3.0.7
      def mass_assignment_options
        @mass_assignment_options ||= {}
      end

      # Set the mass assignment options for the current model.
      #
      # @api private
      #
      # @return [ Hash ] The mass assignment options.
      #
      # @since 3.0.7
      attr_writer :mass_assignment_options

      # If the key provided is the name of a relation or a nested attribute, we
      # need to wait until all other attributes are set before processing
      # these.
      #
      # @example Is the attribute pending?
      #   document.pending_attribute?(:name, "Durran")
      #
      # @param [ Symbol ] key The name of the attribute.
      # @param [ Object ] value The value of the attribute.
      #
      # @return [ true, false ] True if pending, false if not.
      #
      # @since 2.0.0.rc.7
      def pending_attribute?(key, value)
        name = key.to_s
        if relations.has_key?(name)
          pending_relations[name] = value
          return true
        end
        if nested_attributes.has_key?(name)
          pending_nested[name] = value
          return true
        end
        return false
      end

      # Get all the pending relations that need to be set.
      #
      # @example Get the pending relations.
      #   document.pending_relations
      #
      # @return [ Hash ] The pending relations in key/value pairs.
      #
      # @since 2.0.0.rc.7
      def pending_relations
        @pending_relations ||= {}
      end

      # Get all the pending nested attributes that need to be set.
      #
      # @example Get the pending nested attributes.
      #   document.pending_nested
      #
      # @return [ Hash ] The pending nested attributes in key/value pairs.
      #
      # @since 2.0.0.rc.7
      def pending_nested
        @pending_nested ||= {}
      end

      # If the attribute is dynamic, add a field for it with a type of object
      # and then either way set the value.
      #
      # @example Process the attribute.
      #   document.process_attribute(name, value)
      #
      # @param [ Symbol ] name The name of the field.
      # @param [ Object ] value The value of the field.
      #
      # @since 2.0.0.rc.7
      def process_attribute(name, value)
        responds = respond_to?("#{name}=")
        if Mongoid.allow_dynamic_fields && !responds
          write_attribute(name, value)
        else
          raise Errors::UnknownAttribute.new(self.class, name) unless responds
          send("#{name}=", value)
        end
      end

      # Process all the pending nested attributes that needed to wait until
      # ids were set to fire off.
      #
      # @example Process the nested attributes.
      #   document.process_nested
      #
      # @since 2.0.0.rc.7
      def process_nested
        pending_nested.each_pair do |name, value|
          send("#{name}=", value)
        end
      end

      # Process all the pending items, then clear them out.
      #
      # @example Process the pending items.
      #   document.process_pending
      #
      # @param [ Hash ] options The mass assignment options.
      #
      # @since 2.0.0.rc.7
      def process_pending
        process_nested and process_relations
        pending_nested.clear and pending_relations.clear
      end

      # Process all the pending relations that needed to wait until ids were set
      # to fire off.
      #
      # @example Process the relations.
      #   document.process_relations
      #
      # @param [ Hash ] options The mass assignment options.
      #
      # @since 2.0.0.rc.7
      def process_relations
        pending_relations.each_pair do |name, value|
          metadata = relations[name]
          if value.is_a?(Hash)
            metadata.nested_builder(value, {}).build(self, mass_assignment_options)
          else
            send("#{name}=", value)
          end
        end
      end

      # Execute the block with the provided mass assignment options set.
      #
      # @api private
      #
      # @example Execute with mass assignment.
      #   model.with_mass_assignment(:default, true)
      #
      # @param [ Symbol ] role The role.
      # @param [ true, false ] guard_protected_attributes To enable mass
      #   assignment.
      #
      # @since 3.0.7
      def with_mass_assignment(role, guard_protected_attributes)
        begin
          self.mass_assignment_options =
            { as: role, without_protection: !guard_protected_attributes }
          yield
        ensure
          self.mass_assignment_options = nil
        end
      end
    end
  end
end


text:
OC_BEGIN_NAMESPACE

// Code to implement binary search.

// Requirements for class CT (container class) are that it has operator[].
// Requirements for class T is that it has operator== and operator<.

// Returns 'true' if the given value was found; 'false' if it was not.
// If 'true', 'location' will contain its index; if 'false'; 'location'
// will point to the next largest element -- the element that 'val' belongs
// just before.

template <class CT, class T>
bool OCBSearch (const CT& array, int length,
		T val,
		int initial_guess,
		int& location)
{
  // In case there ARE no elements
  int point_of_insertion = 0;

  int m = initial_guess;

  // Figure out where we are with binary search
  if (length!=0) {

    // Maybe we're lucky guessers!
    if (array[m] == val) {
      // Make sure we walk back to the leftmost instance of our match
      while (m > 0  &&  array[m-1] == val)
        m--;
      location = m;
      return true;
    }

    int l=0;
    int r=length;

    // Continue until boundaries cross
    while (l <= r  &&  l < length) {

      // Compute midpoint
      m = (l+r)/2;

      // Less than the val we are trying to insert, move left boundary
      if (array[m] < val)
        l = m + 1;

      // Right here!  Found out exactly where we are
      else if (array[m] == val) {
        // Make sure we walk back to the leftmost instance of our match
        while (m > 0  &&  array[m-1] == val)
          m--;
        location = m;
        return true;
      }

      // Else move right boundary
      else
        r = m - 1;
    }

    // At this point, we either found it exactly, or l and r
    // crossed over.  The crossing point is where we want to insert
    point_of_insertion = l;
  }

  location = point_of_insertion;
  return false;
}                                       // BSearchT

OC_END_NAMESPACE

#endif // OCBSEARCH_H_


text:
from oslo_config import cfg
from webob import exc as web_exc

from neutron.api.v2 import attributes as attr
from neutron.db import allowedaddresspairs_db as addr_pair_db
from neutron.db import db_base_plugin_v2
from neutron.db import portsecurity_db
from neutron.extensions import allowedaddresspairs as addr_pair
from neutron.extensions import portsecurity as psec
from neutron.extensions import securitygroup as secgroup
from neutron import manager
from neutron.tests.unit.db import test_db_base_plugin_v2

DB_PLUGIN_KLASS = ('neutron.tests.unit.db.test_allowedaddresspairs_db.'
                   'AllowedAddressPairTestPlugin')

class AllowedAddressPairTestCase(
        test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
    def setUp(self, plugin=None, ext_mgr=None):
        super(AllowedAddressPairTestCase, self).setUp(plugin)

        # Check if a plugin supports security groups
        plugin_obj = manager.NeutronManager.get_plugin()
        self._skip_port_security = ('port-security' not in
                                    plugin_obj.supported_extension_aliases)

class AllowedAddressPairTestPlugin(portsecurity_db.PortSecurityDbMixin,
                                   db_base_plugin_v2.NeutronDbPluginV2,
                                   addr_pair_db.AllowedAddressPairsMixin):

    """Test plugin that implements necessary calls on create/delete port for
    associating ports with port security and allowed address pairs.
    """

    supported_extension_aliases = ["allowed-address-pairs"]

    def create_port(self, context, port):
        p = port['port']
        with context.session.begin(subtransactions=True):
            neutron_db = super(AllowedAddressPairTestPlugin, self).create_port(
                context, port)
            p.update(neutron_db)
            if attr.is_attr_set(p.get(addr_pair.ADDRESS_PAIRS)):
                self._process_create_allowed_address_pairs(
                    context, p,
                    p[addr_pair.ADDRESS_PAIRS])
            else:
                p[addr_pair.ADDRESS_PAIRS] = None

        return port['port']

    def update_port(self, context, id, port):
        delete_addr_pairs = self._check_update_deletes_allowed_address_pairs(
            port)
        has_addr_pairs = self._check_update_has_allowed_address_pairs(port)

        with context.session.begin(subtransactions=True):
            ret_port = super(AllowedAddressPairTestPlugin, self).update_port(
                context, id, port)
            # copy values over - but not fixed_ips
            port['port'].pop('fixed_ips', None)
            ret_port.update(port['port'])

            if (delete_addr_pairs or has_addr_pairs):
                # delete address pairs and readd them
                self._delete_allowed_address_pairs(context, id)
                self._process_create_allowed_address_pairs(
                    context, ret_port,
                    ret_port[addr_pair.ADDRESS_PAIRS])

        return ret_port

class AllowedAddressPairDBTestCase(AllowedAddressPairTestCase):
    def setUp(self, plugin=None, ext_mgr=None):
        plugin = plugin or DB_PLUGIN_KLASS
        super(AllowedAddressPairDBTestCase,
              self).setUp(plugin=plugin, ext_mgr=ext_mgr)

class TestAllowedAddressPairs(AllowedAddressPairDBTestCase):

    def test_create_port_allowed_address_pairs_bad_format(self):
        with self.network() as net:
            bad_values = [False, True, 1.1, 1]
            for value in bad_values:
                self._create_port(
                    self.fmt, net['network']['id'],
                    expected_res_status=web_exc.HTTPBadRequest.code,
                    arg_list=(addr_pair.ADDRESS_PAIRS,),
                    allowed_address_pairs=value)

    def test_create_port_allowed_address_pairs(self):
        with self.network() as net:
            address_pairs = [{'mac_address': '00:00:00:00:00:01',
                              'ip_address': '10.0.0.1'}]
            res = self._create_port(self.fmt, net['network']['id'],
                                    arg_list=(addr_pair.ADDRESS_PAIRS,),
                                    allowed_address_pairs=address_pairs)
            port = self.deserialize(self.fmt, res)
            self.assertEqual(port['port'][addr_pair.ADDRESS_PAIRS],
                             address_pairs)
            self._delete('ports', port['port']['id'])

    def test_create_port_security_true_allowed_address_pairs(self):
        if self._skip_port_security:
            self.skipTest("Plugin does not implement port-security extension")

        with self.network() as net:
            address_pairs = [{'mac_address': '00:00:00:00:00:01',
                              'ip_address': '10.0.0.1'}]
            res = self._create_port(self.fmt, net['network']['id'],
                                    arg_list=('port_security_enabled',
                                              addr_pair.ADDRESS_PAIRS,),
                                    port_security_enabled=True,
                                    allowed_address_pairs=address_pairs)
            port = self.deserialize(self.fmt, res)
            self.assertTrue(port['port'][psec.PORTSECURITY])
            self.assertEqual(port['port'][addr_pair.ADDRESS_PAIRS],
                             address_pairs)
            self._delete('ports', port['port']['id'])

    def test_create_port_security_false_allowed_address_pairs(self):
        if self._skip_port_security:
            self.skipTest("Plugin does not implement port-security extension")

        with self.network() as net:
            address_pairs = [{'mac_address': '00:00:00:00:00:01',
                              'ip_address': '10.0.0.1'}]
            res = self._create_port(self.fmt, net['network']['id'],
                                    arg_list=('port_security_enabled',
                                              addr_pair.ADDRESS_PAIRS,),
                                    port_security_enabled=False,
                                    allowed_address_pairs=address_pairs)
            self.deserialize(self.fmt, res)
            self.assertEqual(409, res.status_int)

            address_pairs = []
            res = self._create_port(self.fmt, net['network']['id'],
                                    arg_list=('port_security_enabled',
                                              addr_pair.ADDRESS_PAIRS,),
                                    port_security_enabled=False,
                                    allowed_address_pairs=address_pairs)
            port = self.deserialize(self.fmt, res)
            self.assertFalse(port['port'][psec.PORTSECURITY])
            self.assertEqual(port['port'][addr_pair.ADDRESS_PAIRS],
                             address_pairs)
            self._delete('ports', port['port']['id'])

    def test_create_port_bad_mac(self):
        address_pairs = [{'mac_address': 'invalid_mac',
                          'ip_address': '10.0.0.1'}]
        self._create_port_with_address_pairs(address_pairs, 400)

    def test_create_port_bad_ip(self):
        address_pairs = [{'mac_address': '00:00:00:00:00:01',
                          'ip_address': '10.0.0.1222'}]
        self._create_port_with_address_pairs(address_pairs, 400)

    def test_create_missing_ip_field(self):
        address_pairs = [{'mac_address': '00:00:00:00:00:01'}]
        self._create_port_with_address_pairs(address_pairs, 400)

    def test_create_duplicate_mac_ip(self):
        address_pairs = [{'mac_address': '00:00:00:00:00:01',
                          'ip_address': '10.0.0.1'},
                         {'mac_address': '00:00:00:00:00:01',
                          'ip_address': '10.0.0.1'}]
        self._create_port_with_address_pairs(address_pairs, 400)

    def test_more_than_max_allowed_address_pair(self):
        cfg.CONF.set_default('max_allowed_address_pair', 3)
        address_pairs = [{'mac_address': '00:00:00:00:00:01',
                          'ip_address': '10.0.0.1'},
                         {'mac_address': '00:00:00:00:00:02',
                          'ip_address': '10.0.0.2'},
                         {'mac_address': '00:00:00:00:00:03',
                          'ip_address': '10.0.0.3'},
                         {'mac_address': '00:00:00:00:00:04',
                          'ip_address': '10.0.0.4'}]
        self._create_port_with_address_pairs(address_pairs, 400)

    def test_equal_to_max_allowed_address_pair(self):
        cfg.CONF.set_default('max_allowed_address_pair', 3)
        address_pairs = [{'mac_address': '00:00:00:00:00:01',
                          'ip_address': '10.0.0.1'},
                         {'mac_address': '00:00:00:00:00:02',
                          'ip_address': '10.0.0.2'},
                         {'mac_address': '00:00:00:00:00:03',
                          'ip_address': '10.0.0.3'}]
        self._create_port_with_address_pairs(address_pairs, 201)

    def test_create_overlap_with_fixed_ip(self):
        address_pairs = [{'mac_address': '00:00:00:00:00:01',
                          'ip_address': '10.0.0.2'}]
        with self.network() as network:
            with self.subnet(network=network, cidr='10.0.0.0/24') as subnet:
                fixed_ips = [{'subnet_id': subnet['subnet']['id'],
                              'ip_address': '10.0.0.2'}]
                res = self._create_port(self.fmt, network['network']['id'],
                                        arg_list=(addr_pair.ADDRESS_PAIRS,
                                        'fixed_ips'),
                                        allowed_address_pairs=address_pairs,
                                        fixed_ips=fixed_ips)
                self.assertEqual(res.status_int, 201)
                port = self.deserialize(self.fmt, res)
                self._delete('ports', port['port']['id'])

    def test_create_port_extra_args(self):
        address_pairs = [{'mac_address': '00:00:00:00:00:01',
                          'ip_address': '10.0.0.1',
                          'icbb': 'agreed'}]
        self._create_port_with_address_pairs(address_pairs, 400)

    def _create_port_with_address_pairs(self, address_pairs, ret_code):
        with self.network() as net:
            res = self._create_port(self.fmt, net['network']['id'],
                                    arg_list=(addr_pair.ADDRESS_PAIRS,),
                                    allowed_address_pairs=address_pairs)
            port = self.deserialize(self.fmt, res)
            self.assertEqual(res.status_int, ret_code)
            if ret_code == 201:
                self._delete('ports', port['port']['id'])

    def test_update_add_address_pairs(self):
        with self.network() as net:
            res = self._create_port(self.fmt, net['network']['id'])
            port = self.deserialize(self.fmt, res)
            address_pairs = [{'mac_address': '00:00:00:00:00:01',
                              'ip_address': '10.0.0.1'}]
            update_port = {'port': {addr_pair.ADDRESS_PAIRS:
                                    address_pairs}}
            req = self.new_update_request('ports', update_port,
                                          port['port']['id'])
            port = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(port['port'][addr_pair.ADDRESS_PAIRS],
                             address_pairs)
            self._delete('ports', port['port']['id'])

    def test_create_address_gets_port_mac(self):
        with self.network() as net:
            address_pairs = [{'ip_address': '23.23.23.23'}]
            res = self._create_port(self.fmt, net['network']['id'],
                                    arg_list=('port_security_enabled',
                                              addr_pair.ADDRESS_PAIRS,),
                                    allowed_address_pairs=address_pairs)
            port = self.deserialize(self.fmt, res)['port']
            port_addr_mac = port[addr_pair.ADDRESS_PAIRS][0]['mac_address']
            self.assertEqual(port_addr_mac,
                             port['mac_address'])
            self._delete('ports', port['id'])

    def test_update_port_security_off_address_pairs(self):
        if self._skip_port_security:
            self.skipTest("Plugin does not implement port-security extension")
        with self.network() as net:
            with self.subnet(network=net) as subnet:
                address_pairs = [{'mac_address': '00:00:00:00:00:01',
                                  'ip_address': '10.0.0.1'}]
                # The port should not have any security-groups associated to it
                with self.port(subnet=subnet,
                               arg_list=(psec.PORTSECURITY,
                                         addr_pair.ADDRESS_PAIRS,
                                         secgroup.SECURITYGROUPS),
                               port_security_enabled=True,
                               allowed_address_pairs=address_pairs,
                               security_groups=[]) as port:

                    update_port = {'port': {psec.PORTSECURITY: False}}
                    req = self.new_update_request('ports', update_port,
                                                  port['port']['id'])
                    res = req.get_response(self.api)
                    self.assertEqual(409, res.status_int)

    def test_update_with_none_and_own_mac_for_duplicate_ip(self):
        with self.network() as net:
            res = self._create_port(self.fmt, net['network']['id'])
            port = self.deserialize(self.fmt, res)
            mac_address = port['port']['mac_address']
            address_pairs = [{'ip_address': '10.0.0.1'},
                             {'mac_address': mac_address,
                              'ip_address': '10.0.0.1'}]
            update_port = {'port': {addr_pair.ADDRESS_PAIRS:
                                    address_pairs}}
            req = self.new_update_request('ports', update_port,
                                          port['port']['id'])
            res = req.get_response(self.api)
            self.assertEqual(400, res.status_int)

    def test_create_port_remove_allowed_address_pairs_with_list(self):
        self._test_create_port_remove_allowed_address_pairs([])

    def test_create_port_remove_allowed_address_pairs_with_none(self):
        self._test_create_port_remove_allowed_address_pairs(None)

    def _test_create_port_remove_allowed_address_pairs(self, update_value):
        with self.network() as net:
            address_pairs = [{'mac_address': '00:00:00:00:00:01',
                              'ip_address': '10.0.0.1'}]
            res = self._create_port(self.fmt, net['network']['id'],
                                    arg_list=(addr_pair.ADDRESS_PAIRS,),
                                    allowed_address_pairs=address_pairs)
            port = self.deserialize(self.fmt, res)
            update_port = {'port': {addr_pair.ADDRESS_PAIRS: update_value}}
            req = self.new_update_request('ports', update_port,
                                          port['port']['id'])
            port = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual([], port['port'][addr_pair.ADDRESS_PAIRS])
            self._delete('ports', port['port']['id'])


text:
@-webkit-keyframes rotating {
    from{
        -webkit-transform: rotateY(0deg);
    }
    to{
        -webkit-transform: rotateY(360deg);
    }
}

body{
    width: 200px;
    height: 36px;
    background-color: #d5d5d5;
    padding: 0;
    margin: 0;
}
div.operator{
    font-size: 14px;
    font-family: arial;
    font-weight: bold;
    background: #DDE4E3 no-repeat ;
    border-radius: 3px;
    margin: 4px 3px;
    padding: 5px;
    -webkit-transition: all 0.3s ease-in-out;
}
div.operator:hover{
    cursor: pointer;
    background-color: #F9FEFF;
    /*box-shadow: #999 1px 2px 3px;*/
}
.operator .operator-target{
    background: no-repeat ;
    padding-left: 33px;
    line-height: 28px;
    height: 28px;
    display: inline-block;
    margin: 0 auto;
    position: relative;
    overflow: hidden;
    opacity: 0.8;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 120px;
}
.operator .operator-target:before
{
    content: "";
    position: absolute;
    width: 28px;
    height: 28px;
    left: 0;
    background-size: 22px 22px;
    background-repeat: no-repeat;
    background-position: center center;
    -webkit-transition: all 0.3s ease-in-out;
    opacity: 1;
}
.operator:hover > span
{
    opacity: 1;
}
.operator:hover .operator-target:before
{
    /*-webkit-animation: rotating 3s linear infinite;*/
    background-size: 28px 28px;
    opacity: 1;
}
.sub-operator{
    display: none;
    list-style:none;
    font-weight:bold;
    color:#303133;
    padding:0;
    margin:0;
}
.sub-operator li{
    padding:0;
    margin:0;
}
#expand{
}
.download .operator-target:before{
    background-image: url("images/Download.svg");
}
#inspect .operator-target:before{
    background-image: url("images/Magnifying.svg");
}
#import_config .operator-target:before{
    background-image: url("images/YouVersion.svg");
}
#export_config .operator-target:before{
    background-image: url("images/Pinboard.svg");
}
#import_template .operator-target:before{
    background-image: url("images/WordPress.svg");
}

.operator:hover .operator-operation{
    background: #666666;
}
.operator-operation{
    width: 18px;
    height: 18px;
    display: inline-block;
    position: fixed;
    border-radius: 15px;
    background-color: #DDE4E3;
    opacity: 0.3;
    text-align: center;
    margin-left: 10px;
    margin-top: 6px;
    -webkit-transition: all 0.4s ease-in-out;
}
.operator-operation:hover{
    width: 60px;
    height: 28px;
    opacity: 1;
    margin-left: -32px;
    margin-top: 1px;
    -webkit-transition: all 0.4s ease-in-out;
}

.mini-icos{
    margin: 0;
    padding: 0;
}
.operator-operation:hover .mini-ico{
    width: 16px;
    -webkit-transform: scale(1,1);
    -webkit-transition: all 0.4s ease-in-out;
}
.mini-ico{
    margin-top: 6px;
    margin-right: 5px;
    position: relative;
    background: no-repeat center center;
    display: inline-block;
    width: 0;
    height: 16px;
    border-bottom: 3px solid transparent;
    border-left: 1px solid transparent;
    -webkit-transform: scale(0,1);
    -webkit-transition: all 0.4s ease-in-out;
}
.mini-ico:last-child{
    margin-right: 0;
}
.mini-ico:hover{
    border-bottom: 3px solid #ffffff;
    border-left: 1px solid #ffffff;
}
.mini-ico.modify{
    background-image: url("images/pen_16x16.png");
}
.mini-ico.delete{
    background-image: url("images/x_14x14.png");
}
.mini-ico.bind{
    background-image: url("images/pin_16x16.png");
}

.footer{
    padding-top: 8px;
}
.footer div{
    margin: 0 auto;
    /*text-align: center;*/
    text-align: right;
    padding-right: 10px;
}
.links{
    background: no-repeat ;
    background-size: 26px 26px;
    display: inline-block;
    height: 26px;
    width: 26px;
    border: 2px solid transparent;
    border-radius: 20px;
    opacity: 0.5;
    margin-bottom: 5px;
    -webkit-transition: all 0.3s ease-in-out;
}
.links:hover{
    border: 2px solid #ffffff;
    background-color: #ffffff;
    opacity: 1;
}
.feedback{
    background-image: url("images/Email.svg");
}
.github{
    background-image: url("images/GitHub.svg");
}
.help{
    background-image: url("images/Help.svg");
}


text:
<?php
use \Mollwitz\UnitFactory;

define("AUSTRIAN_FORCE", 1);
define("PRUSSIAN_FORCE", 2);

global $force_name;
$force_name[PRUSSIAN_FORCE] = "Prussian";
$force_name[AUSTRIAN_FORCE] = "Austrian";

class Burkersdorf extends \Mollwitz\JagCore
{
    public $specialHexesMap = ['SpecialHexA'=>1, 'SpecialHexB'=>1, 'SpecialHexC'=>2];

    /* @var Mapdata */
    public $mapData;
    public $mapViewer;
    public $force;
    /* @var Terrain */
    public $terrain;
    public $moveRules;
    public $combatRules;
    public $gameRules;
    public $victory;
    public $cities;
    public $loc;

    public $players;

    static function playMulti($name, $wargame, $arg = false)
    {
        $deployOne = $playerOne = "Austrian";
        $deployTwo = $playerTwo = "Prussian";

        @include_once "playMulti.php";
    }

    static function getHeader($name, $playerData, $arg = false)
    {
        @include_once "globalHeader.php";
        @include_once "header.php";
        @include_once "BurkersdorfHeader.php";

    }

    static function enterMulti()
    {
        @include_once "enterMulti.php";
    }

    static function getView($name, $mapUrl, $player = 0, $arg = false, $scenario = false, $game = false)
    {
        global $force_name;
        $youAre = $force_name[$player];
        $deployOne = $playerOne = "Austrian";
        $deployTwo = $playerTwo = "Prussian";
        @include_once "view.php";
    }

    public function terrainInit($terrainDoc){
        parent::terrainInit($terrainDoc);
        $this->cities = $this->specialHexA;
        $this->loc = $this->specialHexB;
    }

    function save()
    {
        $data = new stdClass();
        $data->mapData = $this->mapData;
        $data->mapViewer = $this->mapViewer;
        $data->moveRules = $this->moveRules->save();
        $data->force = $this->force;
        $data->gameRules = $this->gameRules->save();
        $data->combatRules = $this->combatRules->save();
        $data->players = $this->players;
        $data->victory = $this->victory->save();
        $data->terrainName = $this->terrainName;
        $data->arg = $this->arg;
        $data->scenario = $this->scenario;
        $data->game = $this->game;
        $data->cities = $this->cities;
        $data->loc = $this->loc;
        return $data;
    }

    public function init()
    {

        $artRange = 3;

        UnitFactory::$injector = $this->force;
        if($this->scenario->bigAustrian){
            for ($i = 0; $i < 6; $i++) {
                UnitFactory::create("infantry-1", AUSTRIAN_FORCE, "deployBox", "AusInfBadge.png", 4, 4, 3, true, STATUS_CAN_DEPLOY, "B", 1, 1, "Austrian", false, 'infantry');
            }
            for ($i = 0; $i < 25; $i++) {
                UnitFactory::create("infantry-1", AUSTRIAN_FORCE, "deployBox", "AusInfBadge.png", 3, 3, 3, true, STATUS_CAN_DEPLOY, "B", 1, 1, "Austrian", false, 'infantry');
            }
        }else{
            for ($i = 0; $i < 31; $i++) {
                UnitFactory::create("infantry-1", AUSTRIAN_FORCE, "deployBox", "AusInfBadge.png", 3, 3, 3, true, STATUS_CAN_DEPLOY, "B", 1, 1, "Austrian", false, 'infantry');
            }
        }

        for ($i = 0; $i < 5; $i++) {
            UnitFactory::create("infantry-1", AUSTRIAN_FORCE, "deployBox", "AusCavBadge.png", 4, 4, 5, true, STATUS_CAN_DEPLOY, "B", 1, 1, "Austrian", false, 'cavalry');
        }
        for ($i = 0; $i < 2; $i++) {
            UnitFactory::create("infantry-1", AUSTRIAN_FORCE, "deployBox", "AusCavBadge.png", 5, 5, 5, true, STATUS_CAN_DEPLOY, "B", 1, 1, "Austrian", false, 'cavalry');
        }
        for ($i = 0; $i < 1; $i++) {
            UnitFactory::create("infantry-1", AUSTRIAN_FORCE, "deployBox", "AusCavBadge.png", 5, 5, 6, true, STATUS_CAN_DEPLOY, "B", 1, 1, "Austrian", false, 'cavalry');
        }
        for ($i = 0; $i < 8; $i++) {
            UnitFactory::create("infantry-1", AUSTRIAN_FORCE, "deployBox", "AusArtBadge.png", 2, 2, 2, true, STATUS_CAN_DEPLOY, "B", 1, $artRange, "Austrian", false, 'artillery');
        }

        for ($i = 0; $i < 14; $i++) {
            UnitFactory::create("infantry-1", PRUSSIAN_FORCE, "deployBox", "PruInfBadge.png", 4, 4, 3, true, STATUS_CAN_DEPLOY, "A", 1, 1, "Prussian", false, 'infantry');
        }
        for ($i = 0; $i < 10; $i++) {
            UnitFactory::create("infantry-1", PRUSSIAN_FORCE, "deployBox", "PruInfBadge.png", 6, 6, 3, true, STATUS_CAN_DEPLOY, "A", 1, 1, "Prussian", false, 'infantry');
        }
        for ($i = 0; $i < 7; $i++) {
            UnitFactory::create("infantry-1", PRUSSIAN_FORCE, "deployBox", "PruCavBadge.png", 4, 4, 5, true, STATUS_CAN_DEPLOY, "A", 1, 1, "Prussian", false, 'cavalry');
        }
        for ($i = 0; $i < 3; $i++) {
            UnitFactory::create("infantry-1", PRUSSIAN_FORCE, "deployBox", "PruCavBadge.png", 5, 5, 5, true, STATUS_CAN_DEPLOY, "A", 1, 1, "Prussian", false, 'cavalry');
        }
        for ($i = 0; $i < 3; $i++) {
            UnitFactory::create("infantry-1", PRUSSIAN_FORCE, "deployBox", "PruCavBadge.png", 5, 5, 6, true, STATUS_CAN_DEPLOY, "A", 1, 1, "Prussian", false, 'cavalry');
        }
        for ($i = 0; $i < 5; $i++) {
            UnitFactory::create("infantry-1", PRUSSIAN_FORCE, "deployBox", "PruArtBadge.png", 2, 2, 2, true, STATUS_CAN_DEPLOY, "A", 1, $artRange, "Prussian", false, 'artillery');
        }
         for ($i = 0; $i < 1; $i++) {
            UnitFactory::create("infantry-1", PRUSSIAN_FORCE, "deployBox", "PruArtBadge.png", 4, 4, 2, true, STATUS_CAN_DEPLOY, "A", 1, $artRange, "Prussian", false, 'artillery');
        }
    }

    function __construct($data = null, $arg = false, $scenario = false, $game = false)
    {
        parent::__construct($data, $arg, $scenario, $game);
        if ($data) {
            $this->cities = $data->cities;
            $this->loc = $data->loc;
        } else {
            $this->victory = new Victory("Mollwitz/Burkersdorf/burkersdorfVictoryCore.php");

            $this->mapData->blocksZoc->blocked = true;
            $this->mapData->blocksZoc->blocksnonroad = true;

            $this->moveRules->enterZoc = "stop";
            $this->moveRules->exitZoc = "stop";
            $this->moveRules->noZocZoc = true;

            // game data
            $this->gameRules->setMaxTurn(12);
            $this->gameRules->setInitialPhaseMode(BLUE_DEPLOY_PHASE, DEPLOY_MODE);
            $this->gameRules->attackingForceId = BLUE_FORCE; /* object oriented! */
            $this->gameRules->defendingForceId = RED_FORCE; /* object oriented! */
            $this->force->setAttackingForceId($this->gameRules->attackingForceId); /* so object oriented */

            $this->gameRules->addPhaseChange(BLUE_DEPLOY_PHASE, RED_DEPLOY_PHASE, DEPLOY_MODE, RED_FORCE, BLUE_FORCE, false);
            $this->gameRules->addPhaseChange(RED_DEPLOY_PHASE, BLUE_MOVE_PHASE, MOVING_MODE, BLUE_FORCE, RED_FORCE, false);

            $this->gameRules->addPhaseChange(BLUE_MOVE_PHASE, BLUE_COMBAT_PHASE, COMBAT_SETUP_MODE, BLUE_FORCE, RED_FORCE, false);
            $this->gameRules->addPhaseChange(BLUE_COMBAT_PHASE, RED_MOVE_PHASE, MOVING_MODE, RED_FORCE, BLUE_FORCE, false);

            $this->gameRules->addPhaseChange(RED_MOVE_PHASE, RED_COMBAT_PHASE, COMBAT_SETUP_MODE, RED_FORCE, BLUE_FORCE, false);
            $this->gameRules->addPhaseChange(RED_COMBAT_PHASE, BLUE_MOVE_PHASE, MOVING_MODE, BLUE_FORCE, RED_FORCE, true);

        }
    }
}


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class hanode_routemonitor_binding(base_resource) :
	""" Binding class showing the routemonitor that can be bound to hanode.
	"""
	def __init__(self) :
		self._routemonitor = ""
		self._netmask = ""
		self._flags = 0
		self._routemonitorstate = ""
		self._id = 0
		self.___count = 0

	@property
	def routemonitor(self) :
		ur"""The IP address (IPv4 or IPv6).
		"""
		try :
			return self._routemonitor
		except Exception as e:
			raise e

	@routemonitor.setter
	def routemonitor(self, routemonitor) :
		ur"""The IP address (IPv4 or IPv6).
		"""
		try :
			self._routemonitor = routemonitor
		except Exception as e:
			raise e

	@property
	def id(self) :
		ur"""Number that uniquely identifies the local node. The ID of the local node is always 0.
Minimum value =  0
Maximum value =  64.
		"""
		try :
			return self._id
		except Exception as e:
			raise e

	@id.setter
	def id(self, id) :
		ur"""Number that uniquely identifies the local node. The ID of the local node is always 0.
Minimum value =  0
Maximum value =  64
		"""
		try :
			self._id = id
		except Exception as e:
			raise e

	@property
	def netmask(self) :
		ur"""The netmask.
		"""
		try :
			return self._netmask
		except Exception as e:
			raise e

	@netmask.setter
	def netmask(self, netmask) :
		ur"""The netmask.
		"""
		try :
			self._netmask = netmask
		except Exception as e:
			raise e

	@property
	def routemonitorstate(self) :
		ur"""State for route monitor.
Possible values = UP, DOWN.
		"""
		try :
			return self._routemonitorstate
		except Exception as e:
			raise e

	@property
	def flags(self) :
		ur"""The flags for this entry.
		"""
		try :
			return self._flags
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		ur""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(hanode_routemonitor_binding_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.hanode_routemonitor_binding
		except Exception as e :
			raise e

	def _get_object_name(self) :
		ur""" Returns the value of object identifier argument
		"""
		try :
			if self.id is not None :
				return str(self.id)
			return None
		except Exception as e :
			raise e

	@classmethod
	def add(cls, client, resource) :
		try :
			if resource and type(resource) is not list :
				updateresource = hanode_routemonitor_binding()
				updateresource.id = resource.id
				updateresource.routemonitor = resource.routemonitor
				updateresource.netmask = resource.netmask
				return updateresource.update_resource(client)
			else :
				if resource and len(resource) > 0 :
					updateresources = [hanode_routemonitor_binding() for _ in range(len(resource))]
					for i in range(len(resource)) :
						updateresources[i].id = resource[i].id
						updateresources[i].routemonitor = resource[i].routemonitor
						updateresources[i].netmask = resource[i].netmask
				return cls.update_bulk_request(client, updateresources)
		except Exception as e :
			raise e

	@classmethod
	def delete(cls, client, resource) :
		try :
			if resource and type(resource) is not list :
				deleteresource = hanode_routemonitor_binding()
				deleteresource.id = resource.id
				deleteresource.routemonitor = resource.routemonitor
				deleteresource.netmask = resource.netmask
				return deleteresource.delete_resource(client)
			else :
				if resource and len(resource) > 0 :
					deleteresources = [hanode_routemonitor_binding() for _ in range(len(resource))]
					for i in range(len(resource)) :
						deleteresources[i].id = resource[i].id
						deleteresources[i].routemonitor = resource[i].routemonitor
						deleteresources[i].netmask = resource[i].netmask
				return cls.delete_bulk_request(client, deleteresources)
		except Exception as e :
			raise e

	@classmethod
	def get(cls, service, id) :
		ur""" Use this API to fetch hanode_routemonitor_binding resources.
		"""
		try :
			obj = hanode_routemonitor_binding()
			obj.id = id
			response = obj.get_resources(service)
			return response
		except Exception as e:
			raise e

	@classmethod
	def get_filtered(cls, service, id, filter_) :
		ur""" Use this API to fetch filtered set of hanode_routemonitor_binding resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = hanode_routemonitor_binding()
			obj.id = id
			option_ = options()
			option_.filter = filter_
			response = obj.getfiltered(service, option_)
			return response
		except Exception as e:
			raise e

	@classmethod
	def count(cls, service, id) :
		ur""" Use this API to count hanode_routemonitor_binding resources configued on NetScaler.
		"""
		try :
			obj = hanode_routemonitor_binding()
			obj.id = id
			option_ = options()
			option_.count = True
			response = obj.get_resources(service, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e:
			raise e

	@classmethod
	def count_filtered(cls, service, id, filter_) :
		ur""" Use this API to count the filtered set of hanode_routemonitor_binding resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = hanode_routemonitor_binding()
			obj.id = id
			option_ = options()
			option_.count = True
			option_.filter = filter_
			response = obj.getfiltered(service, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e:
			raise e

	class Routemonitorstate:
		UP = "UP"
		DOWN = "DOWN"

class hanode_routemonitor_binding_response(base_response) :
	def __init__(self, length=1) :
		self.hanode_routemonitor_binding = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.hanode_routemonitor_binding = [hanode_routemonitor_binding() for _ in range(length)]


text:
#include <aws/ds/model/EnableRadiusRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::DirectoryService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

EnableRadiusRequest::EnableRadiusRequest() :
    m_directoryIdHasBeenSet(false),
    m_radiusSettingsHasBeenSet(false)
{
}

Aws::String EnableRadiusRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_directoryIdHasBeenSet)
  {
   payload.WithString("DirectoryId", m_directoryId);

  }

  if(m_radiusSettingsHasBeenSet)
  {
   payload.WithObject("RadiusSettings", m_radiusSettings.Jsonize());

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection EnableRadiusRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DirectoryService_20150416.EnableRadius"));
  return headers;

}


text:
/**
 * @author Kyle Brown <blackbarn@gmail.com>
 * @since 3/4/14 3:18 PM
 */
var jsonMask = require('json-mask');
var compile = jsonMask.compile;
var filter = jsonMask.filter;

module.exports = function (options) {
    options = options || {};

    /**
     * Take an object and filter it creating a partial.
     * @param {Object} obj - object to filter
     * @param {String} fields - json-mask compliant filter string.
     * @returns {Object}
     */
    function partialResponse(obj, fields) {
        // if no fields, don't filter. Otherwise filter the object with the fields.
        if (!fields) {
            return obj;
        } else if (options.exclude) {
            if (filter(obj, compile(options.exclude)) === null) {
                return filter(obj, compile(fields));
            } else {
                return obj;
            }
        } else {
            return filter(obj, compile(fields));
        }
    }

    /**
     * Wrap the original function with additional logic.
     * @param {Function} original - Original function, e.g., res.json
     * @returns {Function}
     */
    function wrap(original) {
        // returning a wrapped function.
        return function () {
            // get the query param that contains the filter list.
            var param = this.req.query[options.query || 'fields'];

            //if only one argument, user is not specifying status code along with data.
            if (arguments.length === 1) {
                //call the original function with the filtered data (first arg)
                original(partialResponse(arguments[0], param));
            } else if (arguments.length === 2) {
                //we have two arguments, user is sending status code along with data, handle accordingly.
                if (typeof arguments[1] === 'number') {
                    original(arguments[1], partialResponse(arguments[0], param));
                } else {
                    original(arguments[0], partialResponse(arguments[1], param));
                }
            }
        };
    }

    /**
     * Middleware function which masks the json/jsonp
     */
    return function (req, res, next) {
        if (!res.__isJSONMaskWrapped) {
            res.json = wrap(res.json.bind(res));
            res.jsonp = wrap(res.jsonp.bind(res));
            res.__isJSONMaskWrapped = true;
        }
        next();
    };
};


text:
require "rails_helper"

RSpec.describe Role, type: :model do
  include RolesHelper

  context "validations" do
    it { is_expected.to validate_presence_of(:user) }

    it { is_expected.to validate_presence_of(:plan) }

    it { is_expected.to allow_values(true, false).for(:active) }

    it { is_expected.not_to allow_value(nil).for(:active) }

    it {
      is_expected.to validate_numericality_of(:access)
        .only_integer
        .is_greater_than(0)
        .with_message("can't be less than zero")
    }

  end

  context "associations" do

    it { is_expected.to belong_to :user }

    it { is_expected.to belong_to :plan }

  end

  describe ".deactivate!" do
    before do
      @plan = build_plan(true, true, true)
    end

    subject { @plan }

    context "different access levels" do

      it "creator is no longer active" do
        role = subject.roles.creator.first
        role.deactivate!
        expect(role.active).to eql(false)
      end

      it "administrator is no longer active" do
        @role = subject.roles.administrator.first
        @role.deactivate!
        expect(@role.active).to eql(false)
      end

      it "editor is no longer active" do
        @role = subject.roles.editor.first
        @role.deactivate!
        expect(@role.active).to eql(false)
      end

      it "commenter is no longer active" do
        @role = subject.roles.commenter.first
        @role.deactivate!
        expect(@role.active).to eql(false)
      end

    end

    context "Deactivation calls Plan.deactivate! if Plan.authors is empty" do

      it "plan has no other authors" do
        plan = build_plan(false, false, false)
        role = plan.roles.creator.first
        role.plan.expects(:deactivate!).times(1)
        role.deactivate!
      end

      it "plan has another author" do
        plan = build_plan(true, false, false)
        role = plan.roles.creator.first
        role.plan.expects(:deactivate!).times(0)
        role.deactivate!
      end

    end

  end

end


text:
#ifndef HEADER_AEPHK_ERR_H
# define HEADER_AEPHK_ERR_H

#ifdef  __cplusplus
extern "C" {
#endif

/* BEGIN ERROR CODES */
/*
 * The following lines are auto generated by the script mkerr.pl. Any changes
 * made after this point may be overwritten when the script is next run.
 */
static void ERR_load_AEPHK_strings(void);
static void ERR_unload_AEPHK_strings(void);
static void ERR_AEPHK_error(int function, int reason, char *file, int line);
# define AEPHKerr(f,r) ERR_AEPHK_error((f),(r),__FILE__,__LINE__)

/* Error codes for the AEPHK functions. */

/* Function codes. */
# define AEPHK_F_AEP_CTRL                                 100
# define AEPHK_F_AEP_FINISH                               101
# define AEPHK_F_AEP_GET_CONNECTION                       102
# define AEPHK_F_AEP_INIT                                 103
# define AEPHK_F_AEP_MOD_EXP                              104
# define AEPHK_F_AEP_MOD_EXP_CRT                          105
# define AEPHK_F_AEP_RAND                                 106
# define AEPHK_F_AEP_RSA_MOD_EXP                          107

/* Reason codes. */
# define AEPHK_R_ALREADY_LOADED                           100
# define AEPHK_R_CLOSE_HANDLES_FAILED                     101
# define AEPHK_R_CONNECTIONS_IN_USE                       102
# define AEPHK_R_CTRL_COMMAND_NOT_IMPLEMENTED             103
# define AEPHK_R_FINALIZE_FAILED                          104
# define AEPHK_R_GET_HANDLE_FAILED                        105
# define AEPHK_R_GET_RANDOM_FAILED                        106
# define AEPHK_R_INIT_FAILURE                             107
# define AEPHK_R_MISSING_KEY_COMPONENTS                   108
# define AEPHK_R_MOD_EXP_CRT_FAILED                       109
# define AEPHK_R_MOD_EXP_FAILED                           110
# define AEPHK_R_NOT_LOADED                               111
# define AEPHK_R_OK                                       112
# define AEPHK_R_RETURN_CONNECTION_FAILED                 113
# define AEPHK_R_SETBNCALLBACK_FAILURE                    114
# define AEPHK_R_SIZE_TOO_LARGE_OR_TOO_SMALL              116
# define AEPHK_R_UNIT_FAILURE                             115

#ifdef  __cplusplus
}
#endif
#endif


text:
#ifndef VISIONCORE_MATH_STATISTICS_HPP
#define VISIONCORE_MATH_STATISTICS_HPP

#include <VisionCore/Platform.hpp>

#include <Eigen/Core>
#include <Eigen/Dense>

#include <VisionCore/Buffers/Buffer1D.hpp>
#include <VisionCore/Buffers/Buffer2D.hpp>
#include <VisionCore/Types/Polynomial.hpp>
#include <VisionCore/Types/Gaussian.hpp>
#include <VisionCore/Math/PolarSpherical.hpp>

/**
 * @note:
 * http://rebcabin.github.io/blog/2013/01/22/covariance-matrices/
 */

namespace vc
{

namespace math
{

/**
 * Running mean, variation, std. deviation, count and min,max.
 */
template<typename T>
class RunningStats
{
public:
    typedef T Scalar;
    static constexpr int Rows = 1;
    static constexpr int Cols = 1;
    static constexpr int Dimension = Rows * Cols;

    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    EIGEN_DEVICE_FUNC inline RunningStats()
    {
        reset();
    }

    EIGEN_DEVICE_FUNC inline void reset()
    {
        cnt = 0;
        minV = std::numeric_limits<T>::max();
        maxV = -std::numeric_limits<T>::max();
        sumX = sumXX = T(0.0);
    }

    EIGEN_DEVICE_FUNC inline void operator()(const T& x)
    {
        using Eigen::numext::mini;
        using Eigen::numext::maxi;

        // process
        cnt++;

        sumX += x;
        sumXX += (x * x);

        maxV = max(maxV, x); // NOTE what about weight?
        minV = min(minV, x);
    }

    EIGEN_DEVICE_FUNC inline std::size_t count() const
    {
        return cnt;
    }

    EIGEN_DEVICE_FUNC inline T mean() const
    {
        if(cnt > 0)
        {
            return sumX / T(cnt);
        }
        else
        {
            return T(0.0);
        }
    }

    EIGEN_DEVICE_FUNC inline T variance() const
    {
        if(cnt > 0)
        {
            const T bessel_correction = T(cnt) / T(cnt - 1);
            const T cm = mean();
            const T term1 = sumXX / T(cnt);

            return bessel_correction * (term1 - (cm*cm));
        }
        else
        {
            return T(0.0);
        }
    }

    EIGEN_DEVICE_FUNC inline T stddev() const
    {
        using Eigen::numext::sqrt;
        return sqrt(variance());
    }

    EIGEN_DEVICE_FUNC inline T running_sum() const { return sumX; }

    EIGEN_DEVICE_FUNC inline T min_value() const { return minV; }
    EIGEN_DEVICE_FUNC inline T max_value() const { return maxV; }

    EIGEN_DEVICE_FUNC inline types::Gaussian<T> gaussian() const
    {
        return types::Gaussian<T>(mean(), variance());
    }
private:
    std::size_t cnt;
    T sumX, sumXX;
    T minV, maxV;
};

/**
 * Specialization for Eigen.
 */
template<typename _Scalar, int _Rows, int _Cols, int _Options>
class RunningStats<Eigen::Matrix<_Scalar, _Rows, _Cols, _Options>>
{
public:
    typedef Eigen::Matrix<_Scalar, _Rows, _Cols, _Options> VectorType;
    typedef _Scalar Scalar;
    static constexpr int Rows = _Rows;
    static constexpr int Cols = _Cols;
    static constexpr int Dimension = Rows * Cols;

    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    EIGEN_DEVICE_FUNC inline RunningStats()
    {
        reset();
    }

    EIGEN_DEVICE_FUNC inline void reset()
    {
        cnt = 0;
        minV = VectorType::Constant(std::numeric_limits<Scalar>::max());
        maxV = VectorType::Constant(-std::numeric_limits<Scalar>::max());
        sumX = VectorType::Zero();
        sumXX = VectorType::Zero();
    }

    EIGEN_DEVICE_FUNC inline void operator()(const VectorType& x)
    {
        // process
        cnt++;

        sumX += x;
        sumXX += VectorType(x.array() * x.array());

        maxV = maxV.array().cwiseMax(x.array());
        minV = minV.array().cwiseMin(x.array());
    }

    EIGEN_DEVICE_FUNC inline std::size_t count() const
    {
        return cnt;
    }

    EIGEN_DEVICE_FUNC inline VectorType mean() const
    {
        if(cnt > 0)
        {
            return sumX / Scalar(cnt);
        }
        else
        {
            return VectorType::Zero();
        }
    }

    EIGEN_DEVICE_FUNC inline VectorType variance() const
    {
        if(cnt > 0)
        {
            const Scalar bessel_correction = Scalar(cnt) / Scalar(cnt - 1);
            const VectorType cm = mean();
            const VectorType term1 = sumXX / Scalar(cnt);

            return bessel_correction * (term1 - VectorType(cm.array() * cm.array()));
        }
        else
        {
            return VectorType::Zero();
        }
    }

    EIGEN_DEVICE_FUNC inline VectorType stddev() const
    {
        return sqrt(variance().array());
    }

    EIGEN_DEVICE_FUNC inline VectorType running_sum() const { return sumX; }

    EIGEN_DEVICE_FUNC inline VectorType min_value() const { return minV; }
    EIGEN_DEVICE_FUNC inline VectorType max_value() const { return maxV; }

    EIGEN_DEVICE_FUNC inline types::Gaussian<VectorType> gaussian() const
    {
        return types::Gaussian<VectorType>(mean(), variance());
    }
private:
    std::size_t cnt;
    VectorType sumX, sumXX, minV, maxV;
};

// ******************** RUNNING MULTIVARIATE *******************************

/**
 * Multivariate analysis.
 */
template<typename T>
class MultivariateStats;

template<typename _Scalar, int Rows, int Options>
class MultivariateStats<Eigen::Matrix<_Scalar, Rows, 1, Options>>
{
public:
    typedef Eigen::Matrix<_Scalar, Rows, 1, Options> VectorType;
    typedef Eigen::Matrix<_Scalar, Rows, Rows, Options> CovarianceType;
    typedef _Scalar Scalar;
    static constexpr std::size_t Dimensions = Rows;

    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    EIGEN_DEVICE_FUNC inline MultivariateStats()
    {
        reset();
    }

    EIGEN_DEVICE_FUNC inline void reset()
    {
        cnt = 0;
        minV = VectorType::Constant(std::numeric_limits<Scalar>::max());
        maxV = VectorType::Constant(-std::numeric_limits<Scalar>::max());
        sumX = VectorType::Zero();
        sumXX = CovarianceType::Zero();
    }

    EIGEN_DEVICE_FUNC inline void operator()(const VectorType& x)
    {
        // process
        cnt++;

        sumX += x;

        sumXX += (x * x.transpose());

        maxV = maxV.array().cwiseMax(x.array());
        minV = minV.array().cwiseMin(x.array());
    }

    EIGEN_DEVICE_FUNC inline std::size_t count() const
    {
        return cnt;
    }

    EIGEN_DEVICE_FUNC inline VectorType mean() const
    {
        if(cnt > 0)
        {
            return sumX / Scalar(cnt);
        }
        else
        {
            return VectorType::Zero();
        }
    }

    EIGEN_DEVICE_FUNC inline CovarianceType covariance() const
    {
        if(cnt > 0)
        {
            const Scalar bessel_correction = Scalar(cnt) / Scalar(cnt - 1);
            const VectorType m = mean();
            return bessel_correction * ( (sumXX / Scalar(cnt)) - (m * m.transpose()) );
        }
        else
        {
            return CovarianceType::Zero();
        }
    }

    EIGEN_DEVICE_FUNC inline VectorType running_sum() const { return sumX; }

    EIGEN_DEVICE_FUNC inline VectorType min_value() const { return minV; }
    EIGEN_DEVICE_FUNC inline VectorType max_value() const { return maxV; }

    EIGEN_DEVICE_FUNC inline types::MultivariateGaussian<Scalar,Rows> gaussian() const
    {
        return types::MultivariateGaussian<Scalar,Rows>(mean(), covariance());
    }
private:
    std::size_t cnt;
    VectorType sumX, minV, maxV;
    CovarianceType sumXX;
};

// ******************** ALLAN VARIANCE *******************************
// From: http://www.leapsecond.com/tools/adev_lib.c

template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type allanDeviation(std::size_t tau,
                                                                        InputIterator itbegin,
                                                                        InputIterator itend,
                                                                        bool isoverlapping = false,
                                                                        std::size_t* terms = nullptr)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    using namespace std;

    std::size_t n = 0;
    T sum = T(0.0);
    const std::size_t stride = isoverlapping ? 1 : tau;

    for ( ; (itbegin + 2 * tau) < itend ; itbegin += stride)
    {
        const T v = *(itbegin + 2 * tau) - T(2.0) * *(itbegin + tau) + *itbegin;
        sum += v * v;
        n += 1;
    }

    sum /= T(2.0);

    if(terms != nullptr) { *terms = n; }

    if (n < 3) { return T(0.0); }

    return sqrt(sum / n) / tau;
}

template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type hadamardDeviation(std::size_t tau,
                                                                           InputIterator itbegin,
                                                                           InputIterator itend,
                                                                           bool isoverlapping = false,
                                                                           std::size_t* terms = nullptr)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    using namespace std;

    std::size_t n = 0;
    T sum = T(0.0);
    const std::size_t stride = isoverlapping ? 1 : tau;

    for ( ; (itbegin + 3 * tau) < itend; itbegin += stride)
    {
        const T v = *(itbegin + 3 * tau) - T(3.0) * *(itbegin + 2 * tau) + T(3.0) * *(itbegin + tau) - *itbegin;
        sum += v * v;
        n += 1;
    }

    sum /= T(6.0);

    if(terms != nullptr) { *terms = n; }

    if (n < 3) { return T(0.0); }

    return sqrt(sum / n) / tau;
}

template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type modifiedAllanDeviation(std::size_t tau,
                                                                                InputIterator itbegin,
                                                                                InputIterator itend,
                                                                                std::size_t* terms = nullptr)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    using namespace std;

    std::size_t n = 0;
    T sum = T(0.0), v = T(0.0);

    InputIterator orgbegin = itbegin;

    for ( ; (itbegin + 2 * tau) < itend && (std::size_t)std::distance(orgbegin, itbegin) < tau; ++itbegin)
    {
        v += *(itbegin + 2 * tau) - T(2.0) * *(itbegin + tau) + *itbegin;
    }

    sum += v * v;
    n += 1;

    itbegin = orgbegin;

    for ( ; (itbegin + 3 * tau) < itend; ++itbegin)
    {
        v += *(itbegin + 3 * tau) - T(3.0) * *(itbegin + 2 * tau) + T(3.0) * *(itbegin + tau) - *itbegin;
        sum += v * v;
        n += 1;
    }

    sum /= T(2.0) * T(tau) * T(tau);

    if(terms != nullptr) { *terms = n; }
    if(n < 3) { return T(0.0); }

    return sqrt(sum / n) / tau;
}

template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type timeDeviation(std::size_t tau,
                                                                       InputIterator itbegin,
                                                                       InputIterator itend,
                                                                       std::size_t* terms = nullptr)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    using namespace std;
    return T(tau) * modifiedAllanDeviation(tau, itbegin, itend, terms) / sqrt(3.0);
}

// ******************** PEARSON PRODUCT MOMENT *******************************

/**
 * Calculate r_xy from data.
 */
template<typename T>
class PearsonProductMoment;

template<typename Derived, typename BaseType>
class PearsonProductMomentBase
{
public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    EIGEN_DEVICE_FUNC void reset()
    {
        stats_x.reset();
        stats_x2.reset();
        stats_y.reset();
        stats_y2.reset();
        stats_xy.reset();
    }

    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsX() const { return stats_x; }
    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsY() const { return stats_y; }
    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsX2() const { return stats_x2; }
    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsY2() const { return stats_y2; }
    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsXY() const { return stats_xy; }
protected:
    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsX() { return stats_x; }
    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsY() { return stats_y; }
    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsX2() { return stats_x2; }
    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsY2() { return stats_y2; }
    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsXY() { return stats_xy; }

private:
    RunningStats<BaseType> stats_x;
    RunningStats<BaseType> stats_y;
    RunningStats<BaseType> stats_xy;
    RunningStats<BaseType> stats_x2;
    RunningStats<BaseType> stats_y2;
};

template<typename T>
class PearsonProductMoment : public PearsonProductMomentBase<PearsonProductMoment<T>, T>
{
    typedef PearsonProductMomentBase<PearsonProductMoment<T>, T> Base;
public:
    typedef T BaseType;
    typedef types::Polynomial<BaseType,1> PolynomialT;

    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    EIGEN_DEVICE_FUNC inline PearsonProductMoment()
    {
        Base::reset();
    }

    EIGEN_DEVICE_FUNC void operator()(const T& x, const T& y)
    {
        Base::statsX()(x);
        Base::statsX2()(x*x);
        Base::statsY()(y);
        Base::statsY2()(y*y);
        Base::statsXY()(x*y);
    }

    EIGEN_DEVICE_FUNC BaseType result() const
    {
        using Eigen::numext::sqrt;
        return (Base::statsXY().mean() - (Base::statsX().mean() * Base::statsY().mean())) /
                sqrt( ( Base::statsX2().mean() - ( Base::statsX().mean() * Base::statsX().mean() ) ) *
                      ( Base::statsY2().mean() - ( Base::statsY().mean() * Base::statsY().mean() ) ) );
    }

    EIGEN_DEVICE_FUNC inline BaseType coefficientOfDetermination() const
    {
        BaseType r = result();
        return r*r;
    }

    EIGEN_DEVICE_FUNC inline PolynomialT lineEquation() const
    {
        PolynomialT ret;
        BaseType b = result() * ( Base::statsY().stddev() / Base::statsX().stddev() );
        BaseType a = Base::statsY().mean() - b * Base::statsX().mean();
        ret.coeff() << a , b;
        return ret;
    }
};

template<typename _Scalar, int _Rows, int _Cols>
class PearsonProductMoment<Eigen::Matrix<_Scalar, _Rows, _Cols> > :
  public PearsonProductMomentBase<PearsonProductMoment<Eigen::Matrix<_Scalar, _Rows, _Cols> > , Eigen::Matrix<_Scalar, _Rows, _Cols>>
{
    typedef PearsonProductMomentBase<PearsonProductMoment<Eigen::Matrix<_Scalar, _Rows, _Cols> > , Eigen::Matrix<_Scalar, _Rows, _Cols>> Base;
public:
    typedef Eigen::Matrix<_Scalar, _Rows, _Cols> BaseType;
    typedef types::Polynomial<BaseType,1> PolynomialT;

    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    EIGEN_DEVICE_FUNC inline PearsonProductMoment()
    {
        Base::reset();
    }

    EIGEN_DEVICE_FUNC void operator()(const BaseType& x, const BaseType& y)
    {
        Base::statsX()(x);
        Base::statsX2()(x.array() * x.array());
        Base::statsY()(y);
        Base::statsY2()(y.array() * y.array());
        Base::statsXY()(x.array() * y.array());
    }

    EIGEN_DEVICE_FUNC BaseType result() const
    {
        using Eigen::numext::sqrt;

        return (Base::statsXY().mean().array() - (Base::statsX().mean().array() * Base::statsY().mean().array())) /
                sqrt( ( Base::statsX2().mean().array() - ( Base::statsX().mean().array() * Base::statsX().mean().array() ) ) *
                      ( Base::statsY2().mean().array() - ( Base::statsY().mean().array() * Base::statsY().mean().array() ) ) );
    }

    EIGEN_DEVICE_FUNC inline BaseType coefficientOfDetermination() const
    {
        BaseType r = result();
        return r.array() * r.array();
    }

    EIGEN_DEVICE_FUNC inline PolynomialT lineEquation()
    {
        PolynomialT ret;
        BaseType b = result().array() * ( Base::statsY().stddev().array() / Base::statsX().stddev().array() );
        BaseType a = Base::statsY().mean().array() - b.array() * Base::statsX().mean().array();
        ret.coeff() << a , b;
        return ret;
    }
};

}

}

#endif // VISIONCORE_MATH_STATISTICS_HPP


text:
package httpstat

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"testing"
	"time"
)

const (
	TestDomainHTTP  = "http://example.com"
	TestDomainHTTPS = "https://example.com"
)

func DefaultTransport() *http.Transport {
	// It comes from std transport.go
	return &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext,
		MaxIdleConns:          100,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	}
}

// To avoid shared transport
func DefaultClient() *http.Client {
	return &http.Client{
		Transport: DefaultTransport(),
	}
}

func NewRequest(t *testing.T, urlStr string, result *Result) *http.Request {
	req, err := http.NewRequest("GET", urlStr, nil)
	if err != nil {
		t.Fatal("NewRequest failed:", err)
	}

	ctx := WithHTTPStat(req.Context(), result)
	return req.WithContext(ctx)
}

func TestHTTPStat_HTTPS(t *testing.T) {
	var result Result
	req := NewRequest(t, TestDomainHTTPS, &result)

	client := DefaultClient()
	res, err := client.Do(req)
	if err != nil {
		t.Fatal("client.Do failed:", err)
	}

	if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
		t.Fatal("io.Copy failed:", err)
	}
	res.Body.Close()
	result.End(time.Now())

	if !result.isTLS {
		t.Fatal("isTLS should be true")
	}

	for k, d := range result.durations() {
		if d <= 0*time.Millisecond {
			t.Fatalf("expect %s to be non-zero", k)
		}
	}
}

func TestHTTPStat_HTTP(t *testing.T) {
	var result Result
	req := NewRequest(t, TestDomainHTTP, &result)

	client := DefaultClient()
	res, err := client.Do(req)
	if err != nil {
		t.Fatal("client.Do failed:", err)
	}

	if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
		t.Fatal("io.Copy failed:", err)
	}
	res.Body.Close()
	result.End(time.Now())

	if result.isTLS {
		t.Fatal("isTLS should be false")
	}

	if got, want := result.TLSHandshake, 0*time.Millisecond; got != want {
		t.Fatalf("TLSHandshake time of HTTP = %d, want %d", got, want)
	}

	// Except TLS should be non zero
	durations := result.durations()
	delete(durations, "TLSHandshake")

	for k, d := range durations {
		if d <= 0*time.Millisecond {
			t.Fatalf("expect %s to be non-zero", k)
		}
	}
}

func TestHTTPStat_KeepAlive(t *testing.T) {
	req1, err := http.NewRequest("GET", TestDomainHTTPS, nil)
	if err != nil {
		t.Fatal("NewRequest failed:", err)
	}

	client := DefaultClient()
	res1, err := client.Do(req1)
	if err != nil {
		t.Fatal("Request failed:", err)
	}

	if _, err := io.Copy(ioutil.Discard, res1.Body); err != nil {
		t.Fatal("Copy body failed:", err)
	}
	res1.Body.Close()

	var result Result
	req2 := NewRequest(t, TestDomainHTTPS, &result)

	// When second request, connection should be re-used.
	res2, err := client.Do(req2)
	if err != nil {
		t.Fatal("Request failed:", err)
	}

	if _, err := io.Copy(ioutil.Discard, res2.Body); err != nil {
		t.Fatal("Copy body failed:", err)
	}
	res2.Body.Close()
	result.End(time.Now())

	// The following values should be zero.
	// Because connection is reused.
	durations := []time.Duration{
		result.DNSLookup,
		result.TCPConnection,
		result.TLSHandshake,
	}

	for i, d := range durations {
		if got, want := d, 0*time.Millisecond; got != want {
			t.Fatalf("#%d expect %d to be eq %d", i, got, want)
		}
	}
}

func TestHTTPStat_beforeGO17(t *testing.T) {
	var result Result
	req := NewRequest(t, TestDomainHTTPS, &result)

	// Before go1.7, it uses non context based Dial function.
	// It doesn't support httptrace.
	oldTransport := &http.Transport{
		Dial: (&net.Dialer{
			Timeout: 5 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 5 * time.Second,
	}

	client := &http.Client{
		Timeout:   time.Second * 10,
		Transport: oldTransport,
	}

	res, err := client.Do(req)
	if err != nil {
		t.Fatal("client.Do failed:", err)
	}

	if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
		t.Fatal("io.Copy failed:", err)
	}
	res.Body.Close()
	result.End(time.Now())

	// The following values are not mesured.
	durations := []time.Duration{
		result.DNSLookup,
		result.TCPConnection,
		// result.TLSHandshake,
	}

	for i, d := range durations {
		if got, want := d, 0*time.Millisecond; got != want {
			t.Fatalf("#%d expect %d to be eq %d", i, got, want)
		}
	}
}

func TestTotal_Zero(t *testing.T) {
	result := &Result{}
	result.End(time.Now())

	zero := 0 * time.Millisecond
	if result.total != zero {
		t.Fatalf("Total time is %d, want %d", result.total, zero)
	}

	if result.contentTransfer != zero {
		t.Fatalf("Total time is %d, want %d", result.contentTransfer, zero)
	}
}

func TestHTTPStat_Formatter(t *testing.T) {
	result := Result{
		DNSLookup:        100 * time.Millisecond,
		TCPConnection:    100 * time.Millisecond,
		TLSHandshake:     100 * time.Millisecond,
		ServerProcessing: 100 * time.Millisecond,
		contentTransfer:  100 * time.Millisecond,

		NameLookup:    100 * time.Millisecond,
		Connect:       100 * time.Millisecond,
		Pretransfer:   100 * time.Millisecond,
		StartTransfer: 100 * time.Millisecond,
		total:         100 * time.Millisecond,

		t5: time.Now(),
	}

	want := `DNS lookup:         100 ms
TCP connection:     100 ms
TLS handshake:      100 ms
Server processing:  100 ms
Content transfer:   100 ms

Name Lookup:     100 ms
Connect:         100 ms
Pre Transfer:    100 ms
Start Transfer:  100 ms
Total:           100 ms
`
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "%+v", result)
	if got := buf.String(); want != got {
		t.Fatalf("expect to be eq:\n\nwant:\n\n%s\ngot:\n\n%s\n", want, got)
	}
}


text:
var request = require('request');
var transliterate = require('transliteration');
var mongo = require('mongodb'),
  MongoClient = mongo.MongoClient,
  assert = require('assert');

var config = require('./../../config/config.json');

var dataStructure = require('./../dataStructure');
var _ = require('underscore');

// Connection URL
var dburl = config.dbInfo.url;

var util = require('./../util');
OTHER = {
  //保存订单数据入数据库
  saveOrderOTHER: function(req, res) {
    var item = req.body.data;
    var saveDatas = []; //保存入数据库数组

    if(item) {
      if(item.platform) {
        item.platform_en = transliterate.slugify(item.platform).replace(/\-/ig, '');
      }
      item.hotel_short_name = util.getHotelShortName(item.hotel);
      item.advance_days = util.getDiffDate(item.check_in_date, item.order_date, 'days');
      item.notice_hour = util.getRightDateHour(item.order_date);
      item.nights = item.stay_days;
      item.room_nights = item.room_number * item.stay_days;
      item.created = util.getRightDate(new Date().getTime());
      item.check_in_date = util.getRightDate(item.check_in_date);
      item.check_out_date = util.getRightDate(item.check_out_date);
      item.order_date = util.getRightDate(item.order_date);

      //在redis里面去查找订单号
      redisHander.getValue('order_numbers', function(res) {
        var order_numbers = [];
        if(!res) {
          order_numbers = [];
        }else{
          order_numbers = JSON.parse(res.value)
        }
        if(order_numbers.indexOf(item.order_number) == -1) {
          saveDatas.push(item);
          order_numbers.push(item.order_number);
        }
        redisHander.setValue('order_numbers', {value: JSON.stringify(order_numbers)});
      })
    }
    MongoClient.connect(dburl, function(err, db) {
      assert.equal(null, err);
      // console.log("Connected correctly to server");
      var collection = db.collection('ordersystermOther');
      // Insert some documents
      if(item) {
        if(saveDatas && saveDatas.length) {
          collection.insertMany([item], function(err, result) {
            assert.equal(err, null);
            db.close();
            res.send({
              result: 'TRUE',
              data: item
            });
          });
        }else{
          res.send({
            result: 'TRUE',
            data: []
          });
        }
      }else{
        res.send({
          result: 'FALSE',
          data: []
        });
      }

    });
  },

  getOrderListOTHERFromDB: function(cb, queryStr, page, limit) {
    queryStr = queryStr || {};
    page = page || 1;
    limit = limit || 10000;

    MongoClient.connect(dburl, function(err, db) {
      assert.equal(null, err);
      var collection = db.collection('ordersystermOther');
      var cursor = collection.find(queryStr);
      cursor.count(function(err, count) {
        cursor.skip((page - 1) * limit).limit(limit).toArray(function(err, docs) {
          assert.equal(null, err);
          db.close();
          if (cb && typeof cb === 'function') {
            cb(docs, count);
          }
        });
      })
    });
  },
  //获取美团订单数据列表
  getOrderListOTHER: function(req, res) {
    var listFilterKey = req.query.listFilterKey || 'order_date';
    var listFilterStartTime = (req.query.listFilterStartTime || new Date().toLocaleDateString().replace(/\//ig, '-')) + ' 00:00:00';
    listFilterStartTime = util.getRightDate(listFilterStartTime);
    var listFilterEndTime = (req.query.listFilterEndTime || new Date().toLocaleDateString().replace(/\//ig, '-')) + ' 23:59:59';
    listFilterEndTime = util.getRightDate(listFilterEndTime);

    var listFilterName = req.query.listFilterName;
    var listFilterHotelName = req.query.listFilterHotelName;
    var listFilterOrderNumber = req.query.listFilterOrderNumber;
    var listFilterBillingNumber = req.query.listFilterBillingNumber;

    var limit = Number(req.query.limit) || 20;
    var page = Number(req.query.page) || 1;
    var queryAnd = [{
      custom_name: new RegExp(listFilterName)
    }, {
      hotel: new RegExp(listFilterHotelName)
    }, {
      order_number: new RegExp(listFilterOrderNumber)
    }, {
      billing_number: new RegExp(listFilterBillingNumber)
    }];
    if(listFilterKey && listFilterKey != 'no') {
      queryAnd.push({
        [listFilterKey]: {
          $gte: listFilterStartTime,
          $lte: listFilterEndTime
        }
      })
    }
    var queryStr = {
      $and: queryAnd
    };
    // queryStr[listFilterKey] = {$gte: listFilterStartTime,$lte: listFilterEndTime} //{"order_date":{$lt:50}}
    this.getOrderListOTHERFromDB(function(docs, count) {
      res.send({
        result: 'TRUE',
        data: docs,
        count: count
      });
    }, queryStr, page, limit)
  },
  //获取数据
 getOrderDetailOTHER: function(req, res) {
   var item_id = req.body._id;
   MongoClient.connect(dburl, function(err, db) {
     assert.equal(null, err);
     var collection = db.collection('ordersystermOther');
     var o_id = new mongo.ObjectID(item_id);
     collection.findOne({
       "_id": o_id
     }, function(err, result) {
       db.close();
       res.send({
         result: 'TRUE',
         data: result
       });
     });
   });
 },

 //修改
 updateOrderOTHERItem: function(req, res) {
   var item_id = req.body._id;
   MongoClient.connect(dburl, function(err, db) {
     assert.equal(null, err);
     var collection = db.collection('ordersystermOther');
     var o_id = new mongo.ObjectID(item_id);
     // Update document where a is 2, set b equal to 1
     var _set = {};
     for(var key in req.body) {
       if(key != '_id') {
         _set[key] = req.body[key];
       }
     }
     if(_set.hotel) {
       _set.hotel_short_name = util.getHotelShortName(_set.hotel);
     }

     collection.updateOne({
       "_id": o_id
     }, {
         $set: _set
       }, function(err, result) {
         db.close();
         res.send({
           result: 'TRUE',
           data: result
         });
       });
   })
 },

 //删除
 deleteOrderOTHERitem: function(req, res) {
   var item_id = req.body._id;
   MongoClient.connect(dburl, function(err, db) {
     assert.equal(null, err);
     var collection = db.collection('ordersystermOther');
     var o_id = new mongo.ObjectID(item_id);
     // Update document where a is 2, set b equal to 1
     collection.deleteOne({
       "_id": o_id
     }, {}, function(err, result) {
         db.close();
         res.send({
           result: 'TRUE',
           data: result
         });
       });
   })
 },
 updateData: function(req, res) {
   this.getOrderListOTHERFromDB(function(docs, count) {
     MongoClient.connect(dburl, function(err, db) {
       assert.equal(null, err);
       var collection = db.collection('ordersystermOther');
       var number = 0;
       docs.forEach(function(doc, _index) {
         var o_id = new mongo.ObjectID(doc._id);
         collection.updateOne({
           "_id": o_id
         }, {
           $set: {
             check_in_date: util.getRightDate(doc.check_in_date),
             check_out_date: util.getRightDate(doc.check_out_date),
             order_date: util.getRightDate(doc.order_date)
           }
         }, function(err, result) {
           number ++;
           if(number >= count) {
             db.close();
             res.send({
               result: 'TRUE',
             });
           }
         });
       })

     })
   })
 }
}

module.exports = OTHER;


text:
package com.by_syk.nanoiconpack.tool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RelateReSort {
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("=== RelateReSort(v1.0.0) for NanoIconPack(v1.3.0) ===");

        List<Map<String, String>> itemList = getRelateItems();
        if (itemList == null) {
            System.out.println("error");
            return;
        }
        boolean withLetterIndex = withLetterIndex();
        sort(itemList);
        print(itemList, withLetterIndex);
    }

    private static List<Map<String, String>> getRelateItems() {
        List<Map<String, String>> dataList = new ArrayList<>();
        System.out.println("Array \"icons\"(\".\" to finish):");
        while (scanner.hasNext()) {
            String tmp = scanner.nextLine().trim();
            if (tmp.equals(".")) {
                break;
            }

            if (tmp.matches("<\\!--.+?-->")) {
                continue;
            }
            Map<String, String> map = new HashMap<>();
            map.put("icon", tmp);
            dataList.add(map);
        }

        System.out.println("Array \"icon_labels\"(\".\" to finish):");
        int index = 0;
        while (scanner.hasNext()) {
            String tmp = scanner.nextLine().trim();
            if (tmp.equals(".")) {
                break;
            }
            if (tmp.matches("<\\!--.+?-->")) {
                continue;
            }
            dataList.get(index++).put("label", tmp);
        }
        if (index < dataList.size()) {
            return null;
        }

        System.out.println("Array \"icon_labels\" in zh(\".\" to finish):");
        index = 0;
        while (scanner.hasNext()) {
            String tmp = scanner.nextLine().trim();
            if (tmp.equals(".")) {
                break;
            }
            if (tmp.matches("<\\!--.+?-->")) {
                continue;
            }
            dataList.get(index++).put("labelZh", tmp);
        }
        if (index < dataList.size()) {
            return null;
        }

        return dataList;
    }

    private static boolean withLetterIndex() {
        System.out.println("With letter index comment like \"<!-- A -->\", (Y/N)?");
        return scanner.next().toLowerCase().equals("y");
    }

    private static void sort(List<Map<String, String>> itemList) {
        Collections.sort(itemList, new Comparator<Map<String, String>>() {
            private Pattern pattern = Pattern.compile("<item>(.*?\\D)(\\d)</item>");

            @Override
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                String str1 = o1.get("icon");
                String str2 = o2.get("icon");
                Matcher matcher = pattern.matcher(str1);
                if (matcher.find()) {
                    str1 = matcher.replaceAll("<item>" + matcher.group(1) + "0"
                            + matcher.group(2) + "</item>");
                }
                matcher = pattern.matcher(str2);
                if (matcher.find()) {
                    str2 = matcher.replaceAll("<item>" + matcher.group(1) + "0"
                            + matcher.group(2) + "</item>");
                }
                return str1.compareTo(str2);
            }
        });
    }

    private static void print(List<Map<String, String>> itemList, boolean withLetterIndex) {
        List<String> iconList = new ArrayList<>();
        List<String> labelList = new ArrayList<>();
        List<String> labelZhList = new ArrayList<>();
        if (withLetterIndex) {
            for (int i = 'A'; i <= 'Z'; ++i) {
                String indexComment = "<!-- " + (char) i + " -->";
                iconList.add(indexComment);
                labelList.add(indexComment);
                labelZhList.add(indexComment);
                for (Map<String, String> map : itemList) {
                    String tmp = map.get("icon");
                    if (tmp.split("<item>")[1].toUpperCase().charAt(0) != i) {
                        continue;
                    }
                    iconList.add(tmp);
                    labelList.add(map.get("label"));
                    labelZhList.add(map.get("labelZh"));
                }
            }
        } else {
            for (Map<String, String> map : itemList) {
                iconList.add(map.get("icon"));
                labelList.add(map.get("label"));
                labelZhList.add(map.get("labelZh"));
            }
        }

        System.out.println();
        System.out.println("New array \"icons\":");
        for (String item : iconList) {
            System.out.println(item);
        }

        System.out.println();
        System.out.println("New array \"icon_labels\":");
        for (String item : labelList) {
            System.out.println(item);
        }

        System.out.println();
        System.out.println("New array \"icon_labels\" in zh:");
        for (String item : labelZhList) {
            System.out.println(item);
        }
    }
}